74 lines
1.6 KiB
Go
74 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"os"
|
|
)
|
|
|
|
func fileExists(path string) (bool, error) {
|
|
_, err := os.Stat(path)
|
|
if err == nil {
|
|
return true, nil
|
|
}
|
|
if os.IsNotExist(err) {
|
|
return false, nil
|
|
}
|
|
return false, err
|
|
}
|
|
|
|
func getFileContentLines(path string) ([]string, error) {
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
var lines []string
|
|
scanner := bufio.NewScanner(file)
|
|
for scanner.Scan() {
|
|
lines = append(lines, scanner.Text())
|
|
}
|
|
if err := scanner.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return lines, nil
|
|
}
|
|
|
|
func writeOverContentInFile(path string, lines []string) error {
|
|
file, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
writer := bufio.NewWriter(file)
|
|
for _, line := range lines {
|
|
_, err := writer.WriteString(line + "\n")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
err = writer.Flush()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func writeHostsFile(data *workingData) error {
|
|
var newFileContent []string
|
|
newFileContent = append(newFileContent, data.PrefixContent...)
|
|
if len(data.NewContent) > 0 {
|
|
data.NewContent = dedupeSlice(data.NewContent)
|
|
newFileContent = append(newFileContent, "# "+startPattern)
|
|
newFileContent = append(newFileContent, data.NewContent...)
|
|
newFileContent = append(newFileContent, "# "+endPattern)
|
|
}
|
|
newFileContent = append(newFileContent, data.PostfixContent...)
|
|
if slicesEqual(newFileContent, data.DefaultContent) == false {
|
|
err := writeOverContentInFile(data.HostsFileLocation, newFileContent)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|