-
Notifications
You must be signed in to change notification settings - Fork 0
/
aliases.go
95 lines (83 loc) · 1.88 KB
/
aliases.go
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"bufio"
"bytes"
"io/ioutil"
"os"
"strings"
)
type aliases map[string]string
func readAll() (aliases, error) {
file, err := os.Open(aliasFile)
if err != nil {
return nil, err
}
defer file.Close()
aliases := make(aliases)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.Replace(scanner.Text(), "alias", "", 1)
line = strings.TrimSpace(line)
parts := strings.Split(line, "=")
aliases[parts[0]] = strings.Trim(parts[1], "\"")
}
return aliases, nil
}
func readOne(name string) (alias, error) {
aliases, err := readAll()
if err != nil {
return alias{}, err
}
if !aliases.exists(name) {
return alias{}, errNoSuchAlias
}
alias := alias{name: name, value: aliases[name]}
return alias, nil
}
func (aliases aliases) exists(name string) bool {
if _, exists := aliases[name]; exists {
return true
}
return false
}
func (aliases aliases) append(alias alias) error {
file, err := os.OpenFile(aliasFile, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer file.Close()
if _, err = file.WriteString(alias.string() + "\n"); err != nil {
return err
}
return nil
}
func (aliases aliases) modify(alias alias) error {
if !aliases.exists(alias.name) {
return errNoSuchAlias
}
aliases[alias.name] = alias.value
return aliases.persist()
}
func (aliases aliases) remove(name string) error {
if !aliases.exists(name) {
return errNoSuchAlias
}
delete(aliases, name)
return aliases.persist()
}
func (aliases aliases) persist() error {
var out bytes.Buffer
for name := range aliases {
alias := alias{name: name, value: aliases[name]}
out.WriteString(alias.string() + "\n")
}
return ioutil.WriteFile(aliasFile, out.Bytes(), 0600)
}
func (aliases aliases) strings() []string {
var s []string
for name := range aliases {
alias := alias{name: name, value: aliases[name]}
s = append(s, alias.string())
}
return s
}