summaryrefslogtreecommitdiff
path: root/install/utils.go
blob: 6748613bfed99a7cb7099cebd172baaeeac49d12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package install

import (
	"fmt"
	"os"
	"regexp"

	"github.com/posener/script"
)

func lineInFile(path string, line string) bool {
	return script.Cat(path).Grep(regexp.MustCompile("^"+line+"$")).Wc().Lines > 0
}

func createFile(path string, content string) error {
	return script.Echo(content).ToFile(path)
}

func appendFile(path string, content string) error {
	return script.Echo(content).AppendFile(path)
}

func removeFromFile(path string, line string) error {
	backupPath := path + ".bck"
	err := script.Cat(path).ToFile(backupPath)
	if err != nil {
		return fmt.Errorf("creating backup file: %s", err)
	}

	tmp, err := script.Cat(path).Modify(script.Grep{Re: regexp.MustCompile("^" + line + "$"), Invert: true}).ToTempFile()
	if err != nil {
		return fmt.Errorf("failed remove: %s", err)
	}
	defer os.Remove(tmp)

	err = script.Cat(tmp).ToFile(path)
	if err != nil {
		restoreErr := script.Cat(backupPath).ToFile(path)
		if restoreErr != nil {
			return fmt.Errorf("failed write: %s, and failed restore: %s", err, restoreErr)
		}
	}
	return nil
}