-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
211 lines (174 loc) · 6.31 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"path/filepath"
)
var usage = `
Usage: %s OPTION... [FILE]...
Print selected parts of lines from each FILE to standard output.
With no FILE, or when FILE is -, read standard input.
-f --fields FIELDS select only these fields; also print any line
that contains no delimiter character.
Fields can be used more than once
-cw --cut-on-whitespace cut on any whitespace but also trim following
whitespace aswell until first non-whitepsace
-cmw --cut-on-multi-whitespace cut on consecutive whitespace but also trim following
whitespace aswell until first non-whitepsace
-cs --cut-on-seperator STR cut whenever STR is encountered in a line
-cf --cut-on-format DELIMS cut line applying one delimiter in STR after
another
-fsep --format-seperator STR use STR as seperator in the DELIMS specification
Default: ','
-osep --ouput-seperator STR use the STR as the output field seperator
Default: ' '
Only one of the following can be used at a time:
-cw
-cmw
-cs
-cf
FIELDS is made up of one range, or many ranges separated by commas.
Selected input is written in the same order that it is read.
Each range is one of:
N N'th field, counted from 1
-N (num items on line) - N
N: from N'th field, to end of line
-N: (num items on line) - N, to the end of line
N:M from N'th to M'th (included) field
:M from first to M'th (included) field
:-M from first to ((num items on line) - M)'th (included) field
: from beginning to end of line
DELIMS is made up on one seperator, or many seperators seperated by commas.
The seperator of DELIMS can be changed using --format-seperator.
Each delimiter can be one of:
s cut on next whitespace
t cut on next tab
w cut on next whitespace but consume all consecutive aswell
m cut on next multi whitespace and consume all consecutive aswell
<str> cut on next encounter of str, where str can by any string
Note: whitespace always means tab and space.
Examples:
$ echo "A B C" | gut -cw -f 2:
B C
$ echo "A B C" | gut -f -2:
B C
$ echo "A;;B C" | gut -cf "<;;>,m"
A B C
$ echo "A B,C" | gut -cf "s|<,>" -fsep "|"
A B C
`
// selection options
var fieldsArg = arg[string]{aliases: []string{"f", "fields"}}
// cutting options
var cutOnWhitespaceArg = arg[bool]{aliases: []string{"cw", "cut-on-whitespace"}}
var cutOnMultiWhitespaceArg = arg[bool]{aliases: []string{"cmw", "cut-on-multi-whitespace"}}
var cutOnSeperatorArg = arg[string]{aliases: []string{"cs", "cut-on-seperator"}}
var cutOnFormatArg = arg[string]{aliases: []string{"cf", "cut-on-format"}}
// seperators
var formatSeperatorArg = arg[string]{aliases: []string{"fsep", "format-seperator"}, defaultValue: ","}
var outputSeperatorArg = arg[string]{aliases: []string{"osep", "output-seperator"}, defaultValue: " "}
func setupFlags() {
sArgs := []*arg[string]{&fieldsArg, &cutOnSeperatorArg, &cutOnFormatArg, &formatSeperatorArg, &outputSeperatorArg}
bArgs := []*arg[bool]{&cutOnWhitespaceArg, &cutOnMultiWhitespaceArg}
for _, sArg := range sArgs {
for _, alias := range sArg.aliases {
flag.StringVar(&sArg.value, alias, sArg.defaultValue, "")
}
}
for _, bArg := range bArgs {
for _, alias := range bArg.aliases {
flag.BoolVar(&bArg.value, alias, bArg.defaultValue, "")
}
}
flag.Usage = func() {
fmt.Fprintf(os.Stderr, usage, os.Args[0])
}
flag.Parse()
}
func getGutter() StringSplitter {
// ensure that only one action is performed
actionCount := countValue(
true,
cutOnWhitespaceArg.value,
cutOnMultiWhitespaceArg.value,
len(cutOnSeperatorArg.value) != 0,
len(cutOnFormatArg.value) != 0)
if actionCount > 1 {
die("You can only use one of the cutting actions but you specified more than one")
}
switch {
case cutOnWhitespaceArg.value:
return cutterToSplitter(singleWsCutter)
case cutOnMultiWhitespaceArg.value:
return cutterToSplitter(multiWsCutter)
case len(cutOnSeperatorArg.value) != 0:
return cutterToSplitter(cutterFromSeperator(cutOnSeperatorArg.value))
case len(cutOnFormatArg.value) != 0:
cutters, err := flagToCutters(cutOnFormatArg.value, formatSeperatorArg.value)
if err != nil {
die("Error: %v", err)
}
return func(s string) []string {
return cutWithCutters(s, cutters)
}
}
return cutterToSplitter(multiWsCutter)
}
func getSpans() []span {
// get the spans either by default or user provided value
if len(fieldsArg.value) == 0 {
return []span{{}}
}
spans, err := flagToSpans(fieldsArg.value, ",")
if err != nil {
die("Error: %v\n", err)
}
return spans
}
func getReaders() []io.Reader {
files := flag.Args()
if len(files) == 0 || (len(files) == 1 && files[0] == "-") {
return []io.Reader{os.Stdin}
}
var readers []io.Reader
for _, fileName := range files {
if file, err := os.Open(filepath.Clean(fileName)); err != nil {
die("The file '%s' could not be opened for reading!", fileName)
} else {
readers = append(readers, AutoCloseReader{file})
}
}
return readers
}
func do(writer io.Writer, readers []io.Reader, oSep string, spans []span, chunker StringSplitter) {
for _, reader := range readers {
lineScanner := bufio.NewScanner(reader)
for lineScanner.Scan() {
isFirstPart := true // one can not know in advance what the last one will be
parts := chunker(lineScanner.Text())
for _, span := range spans {
for _, selected := range access(span, parts) {
if !isFirstPart {
io.WriteString(writer, oSep)
}
io.WriteString(writer, selected)
isFirstPart = false
}
}
io.WriteString(writer, "\n")
}
if lineScanner.Err() != nil {
die("An error occured during reading: %v", lineScanner.Err())
}
}
}
func main() {
setupFlags()
gutter := getGutter()
spans := getSpans()
readers := getReaders()
do(os.Stdout, readers, outputSeperatorArg.value, spans, gutter)
}