-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
162 lines (137 loc) · 3.47 KB
/
main.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/*
Command xo is a command line utility that takes an input string from stdin and
formats the regexp matches.
*/
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"regexp"
"unicode/utf8"
)
func main() {
if len(os.Args) == 1 {
help()
}
arg := os.Args[1]
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) != 0 {
throw("Nothing passed to stdin")
}
parts, err := split(arg)
if err != nil {
throw("Invalid argument string")
}
if len(parts) <= 1 {
throw("No pattern or formatter specified")
}
if len(parts) > 3 {
throw("Extra delimiter detected (maybe try one other than `/`)")
}
var (
flags string
pattern string
format string
)
pattern = parts[0]
format = parts[1]
if len(parts) > 2 {
flags = parts[2]
pattern = fmt.Sprintf(`(?%s)%s`, flags, pattern)
}
rx, err := regexp.Compile(pattern)
if err != nil {
throw("Invalid regular expression")
}
in, _ := ioutil.ReadAll(os.Stdin)
matches := rx.FindAllSubmatch(in, -1)
if matches == nil {
throw("No matches found")
}
fallbacks := make(map[int]string)
for _, group := range matches {
result := format
for i, match := range group {
value := string(match)
rxFallback, err := regexp.Compile(fmt.Sprintf(`(\$%d)\?:(([-_A-za-z0-9]((\\.)+)?)+)`, i))
if err != nil {
throw("Failed to parse default arguments", err.Error())
}
// Remove extraneous escapes. This is done because Go doesn't support
// lookbehinds, i.e. `(\$%d)\?:(([-_A-za-z0-9]|(?<=\\).)+)`, so we have
// to match escaped fallback characters using the regexp above, which
// matches backslashes as well as the escaped character.
rxEsc, _ := regexp.Compile(`\\(.)`)
fallback := rxFallback.FindStringSubmatch(result)
if len(fallback) > 1 {
// Store fallback values if key does not already exist
if _, ok := fallbacks[i]; !ok {
fallbacks[i] = rxEsc.ReplaceAllString(string(fallback[2]), "$1")
}
result = rxFallback.ReplaceAllString(result, "$1")
}
// Set default for empty values
if value == "" {
value = fallbacks[i]
}
// Replace values
rxRepl, _ := regexp.Compile(fmt.Sprintf(`\$%d`, i))
result = rxRepl.ReplaceAllString(result, value)
}
fmt.Printf("%s\n", result)
}
}
// split slices str into all substrings separated by non-escaped values of the
// first rune and returns a slice of those substrings.
// It removes one backslash escape from any escaped delimiters.
func split(str string) ([]string, error) {
if !utf8.ValidString(str) {
return nil, errors.New("Invalid string")
}
// Grab the first rune.
delim, size := utf8.DecodeRuneInString(str)
str = str[size:]
var (
subs []string
buffer bytes.Buffer
)
for len(str) > 0 {
r, size := utf8.DecodeRuneInString(str)
str = str[size:]
if r == '\\' {
peek, peekSize := utf8.DecodeRuneInString(str)
if peek == delim {
buffer.WriteRune(peek)
str = str[peekSize:]
continue
}
}
if r == delim {
if buffer.Len() > 0 {
subs = append(subs, buffer.String())
buffer = *new(bytes.Buffer)
}
continue
}
buffer.WriteRune(r)
}
if buffer.Len() > 0 {
subs = append(subs, buffer.String())
}
return subs, nil
}
// help prints how to use this whole `xo` thing then gracefully exits.
func help() {
fmt.Printf("%s\n", "Usage: xo '/<pattern>/<formatter>/[flags]'")
os.Exit(0)
}
// throw prints a bunch of strings and then exits with a non-zero exit code.
func throw(errs ...string) {
for _, err := range errs {
fmt.Printf("%s\n", err)
}
os.Exit(1)
}