fix file parsing
resolves #2393 loads, edits, and re-writes the file instead of inline edits that seem to break. This inefficient but it works in my testing.
This commit is contained in:
parent
37e59e6928
commit
4c9aaeb769
|
@ -390,38 +390,31 @@ 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)
|
// read file
|
||||||
|
input, err := ioutil.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
scanner := bufio.NewScanner(file)
|
// split file into lines to parse one by one.
|
||||||
for scanner.Scan() {
|
lines := strings.Split(string(input), "\n")
|
||||||
hasReplaced := false
|
|
||||||
t := scanner.Text()
|
|
||||||
|
|
||||||
// Iterate over the potential replacements for the line and check if there are
|
for i, line := range lines {
|
||||||
// any matches.
|
|
||||||
for _, replace := range f.Replace {
|
for _, replace := range f.Replace {
|
||||||
if !strings.HasPrefix(t, replace.Match) {
|
// skip if line doesn't have the prefix
|
||||||
|
if !strings.HasPrefix(line, replace.Match) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
hasReplaced = true
|
// replace line if it has the prefix
|
||||||
t = strings.Replace(t, replace.Match, replace.ReplaceWith.String(), 1)
|
lines[i] = replace.ReplaceWith.String()
|
||||||
}
|
|
||||||
|
|
||||||
// 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 {
|
// join all the file lines with new lines between
|
||||||
|
output := strings.Join(lines, "\n")
|
||||||
|
err = ioutil.WriteFile(path, []byte(output), 0644)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user