Skip to content

Commit

Permalink
feat: replacements can be regexes
Browse files Browse the repository at this point in the history
  • Loading branch information
femnad committed Feb 5, 2024
1 parent 318fa79 commit 307bf60
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 26 deletions.
1 change: 1 addition & 0 deletions entity/ensurelines.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ type Replacement struct {
Absent bool `yaml:"absent"`
Old string `yaml:"old"`
New string `yaml:"new"`
Regex bool `yaml:"regex"`
}

type LineInFile struct {
Expand Down
5 changes: 0 additions & 5 deletions internal/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package internal

import (
"fmt"
"os"
"strings"

marecmd "github.com/femnad/mare/cmd"
Expand Down Expand Up @@ -65,10 +64,6 @@ func MaybeRunWithSudoForPath(cmdStr, path string) error {
}

func Move(src, dst string, setOwner bool) error {
if IsHomePath(dst) {
return os.Rename(src, dst)
}

mv := fmt.Sprintf("mv %s %s", src, dst)
err := MaybeRunWithSudoForPath(mv, dst)
if err != nil {
Expand Down
47 changes: 26 additions & 21 deletions provision/ensurelines.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path"
"regexp"

mapset "github.com/deckarep/golang-set/v2"

Expand Down Expand Up @@ -76,34 +77,38 @@ func replace(file string, tmpFile *os.File, line entity.LineInFile) (result ensu
scanner := bufio.NewScanner(srcFile)
scanner.Split(bufio.ScanLines)

replacements := make(map[string]string)
removals := make(map[string]bool)
for _, replacement := range line.Replace {
if replacement.Absent {
removals[replacement.Old] = true
continue
}

replacements[replacement.Old] = replacement.New
}

var changed bool
for scanner.Scan() {
var lineToWrite string
l := scanner.Text()

_, remove := removals[l]
if remove {
changed = true
continue
var absent bool
for _, needle := range line.Replace {
absent = needle.Absent
var regex *regexp.Regexp
if needle.Regex {
regex, err = regexp.Compile(needle.Old)
if err != nil {
return result, err
}

if regex.MatchString(l) {
changed = true
if absent {
break
}
lineToWrite = needle.New
}
} else if l == needle.Old {
changed = true
lineToWrite = needle.New
} else {
lineToWrite = l
}
}

newLine, ok := replacements[l]
if ok {
lineToWrite = newLine
changed = true
} else {
lineToWrite = l
if absent && changed {
continue
}

_, err = tmpFile.WriteString(lineToWrite + "\n")
Expand Down

0 comments on commit 307bf60

Please sign in to comment.