Merge pull request #64 from parkervcp/fix_file_parser

fix file parsing
This commit is contained in:
Dane Everitt 2020-10-11 15:27:53 -07:00 committed by GitHub
commit 3a496af9f1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -390,39 +390,26 @@ func (f *ConfigurationFile) parseYamlFile(path string) error {
// scanning a file and performing a replacement. You should attempt to use anything other // scanning a file and performing a replacement. You should attempt to use anything other
// than this function where possible. // than this function where possible.
func (f *ConfigurationFile) parseTextFile(path string) error { func (f *ConfigurationFile) parseTextFile(path string) error {
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644) input, err := ioutil.ReadFile(path)
if err != nil { if err != nil {
return err return errors.WithStack(err)
} }
defer file.Close()
scanner := bufio.NewScanner(file) lines := strings.Split(string(input), "\n")
for scanner.Scan() { for i, line := range lines {
hasReplaced := false
t := scanner.Text()
// Iterate over the potential replacements for the line and check if there are
// any matches.
for _, replace := range f.Replace { for _, replace := range f.Replace {
if !strings.HasPrefix(t, replace.Match) { // If this line doesn't match what we expect for the replacement, move on to the next
// line. Otherwise, update the line to have the replacement value.
if !strings.HasPrefix(line, replace.Match) {
continue continue
} }
hasReplaced = true lines[i] = replace.ReplaceWith.String()
t = strings.Replace(t, replace.Match, replace.ReplaceWith.String(), 1)
}
// If there was a replacement that occurred on this specific line, do a write to the file
// immediately to write that modified content to the disk.
if hasReplaced {
if _, err := file.WriteAt([]byte(t+"\n"), int64(len(scanner.Bytes()))); err != nil {
return err
}
} }
} }
if err := scanner.Err(); err != nil { if err := ioutil.WriteFile(path, []byte(strings.Join(lines, "\n")), 0644); err != nil {
return err return errors.WithStack(err)
} }
return nil return nil