-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathhandler.go
More file actions
307 lines (284 loc) · 9.14 KB
/
handler.go
File metadata and controls
307 lines (284 loc) · 9.14 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// SPDX-License-Identifier: MIT
package args
import (
"errors"
"flag"
"fmt"
"io"
"os"
"runtime/debug"
"strings"
"sync"
"time"
"github.com/kr/pretty"
"github.com/rokath/trice/internal/com"
"github.com/rokath/trice/internal/decoder"
"github.com/rokath/trice/internal/do"
"github.com/rokath/trice/internal/emitter"
"github.com/rokath/trice/internal/id"
"github.com/rokath/trice/internal/receiver"
"github.com/rokath/trice/internal/translator"
"github.com/rokath/trice/pkg/cipher"
"github.com/rokath/trice/pkg/msg"
"github.com/spf13/afero"
)
// Handler parses args and executes the selected sub-command.
//
// args is expected in os.Args form where args[0] is the executable name and
// args[1] is the sub-command.
func Handler(w io.Writer, fSys *afero.Afero, args []string) error {
// Trim leading and trailing whitespace
//for i := range args {
// args[i] = strings.TrimSpace(args[i])
//}
if Date == "" { // goreleaser will set Date, otherwise use file info.
path, err := os.Executable()
if err != nil {
Date = fmt.Sprint(err) // just in case, simply show the error
} else {
fi, err := fSys.Stat(path)
if err == nil { // On running main tests file-info is invalid, so do not use it in that case.
Date = fi.ModTime().String()
} else {
Date = fmt.Sprint(err) // just in case, simply show the error
}
}
}
// Verify that a sub-command has been provided: os.Arg[0] is the main command (trice), os.Arg[1] will be the sub-command.
if len(args) < 2 {
m := "no args, try: '" + args[0] + " help'"
return errors.New(m)
}
// Switch on the sub-command. Parse the flags for appropriate FlagSet.
// FlagSet.Parse() requires a set of arguments to parse as input.
// os.Args[2:] will be all arguments starting after the sub-command at os.Args[1]
subCmd := args[1]
subArgs := args[2:]
switch subCmd { // Check which sub-command is invoked.
default:
return fmt.Errorf("unknown sub-command '%s'. try: '%s help|h'", subCmd, args[0])
case "h", "help":
msg.OnErr(fsScHelp.Parse(subArgs))
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
return scHelp(w)
case "s", "scan":
msg.OnErr(fsScScan.Parse(subArgs))
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
_, err := com.GetSerialPorts(w)
return err
case "ver", "version":
msg.OnErr(fsScVersion.Parse(subArgs))
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
if Verbose {
bi, ok := debug.ReadBuildInfo()
if !ok {
fmt.Println("buildInfo not ok")
} else {
pretty.Println(bi)
}
}
return scVersion(w)
case "a", "add":
msg.OnErr(fsScAdd.Parse(subArgs))
id.CompactSrcs()
id.ProcessAliases()
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
return id.SubCmdIdAdd(w, fSys)
case "generate":
msg.OnErr(fsScGenerate.Parse(subArgs))
id.CompactSrcs()
id.ProcessAliases()
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
return id.SubCmdGenerate(w, fSys)
case "i", "insert":
msg.OnErr(fsScInsert.Parse(subArgs))
id.CompactSrcs()
id.ProcessAliases()
emitter.AddUserLabels()
err := id.EvaluateIDRangeStrings()
if err != nil {
return err
}
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
//fmt.Println(id.StructuredLoggingFormatString)
//fmt.Println(id.StructuredLoggingValuesString)
//return err
return id.SubCmdIdInsert(w, fSys)
case "c", "clean":
msg.OnErr(fsScClean.Parse(subArgs))
id.CompactSrcs()
id.ProcessAliases()
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
return id.SubCmdIdClean(w, fSys)
case "sd", "shutdown":
msg.OnErr(fsScSdSv.Parse(subArgs))
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
return emitter.ScShutdownRemoteDisplayServer(w, 0) // 0|1: 0=no 1=with shutdown timestamp in display server
case "ds", "displayServer":
msg.OnErr(fsScSv.Parse(subArgs))
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
return emitter.ScDisplayServer(w) // endless loop
case "l", "log":
id.Logging = true
msg.OnErr(fsScLog.Parse(subArgs))
id.ProcessAliases()
emitter.AddUserLabels()
decoder.TargetTimeStampUnitPassed = isLogFlagPassed("ts")
decoder.ShowTargetStamp32Passed = isLogFlagPassed("ts32")
decoder.ShowTargetStamp16Passed = isLogFlagPassed("ts16")
decoder.ShowTargetStamp0Passed = isLogFlagPassed("ts0")
decoder.ShowTargetStamp32DeltaPassed = isLogFlagPassed("ts32delta")
decoder.ShowTargetStamp16DeltaPassed = isLogFlagPassed("ts16delta")
decoder.ShowTargetStamp0DeltaPassed = isLogFlagPassed("ts0delta")
w = do.DistributeArgs(w, fSys, LogfileName, Verbose)
logLoop(w, fSys) // endless loop
return nil
}
}
// https://stackoverflow.com/questions/35809252/check-if-flag-was-provided-in-go
func isLogFlagPassed(name string) bool {
found := false
fsScLog.Visit(func(f *flag.Flag) {
if f.Name == name {
found = true
}
})
return found
}
type selector struct {
flag bool
info func(io.Writer) error
}
// logLoop prepares writing and lut and provides a retry mechanism for unplugged UART.
func logLoop(w io.Writer, fSys *afero.Afero) {
msg.FatalOnErr(cipher.SetUp(w)) // does nothing when -password is ""
if decoder.TestTableMode {
// set switches if they not set already
// trice l -ts off -prefix " }, ``" -suffix "\n``}," -color off
if emitter.HostStamp == "LOCmicro" {
emitter.HostStamp = "off"
}
if defaultPrefix == emitter.Prefix {
emitter.Prefix = " }, `"
}
if emitter.Suffix == "" {
emitter.Suffix = "`},"
}
if emitter.ColorPalette == "default" {
emitter.ColorPalette = "off"
}
decoder.TargetStamp32 = "" // todo: justify this line
}
var ilu id.TriceIDLookUp
if id.FnJSON == "emptyFile" { // reserved name for tests only
ilu = make(id.TriceIDLookUp)
} else {
ilu = id.NewLut(w, fSys, id.FnJSON) // lut is a map, that means a pointer
decoder.IDLUT = ilu
}
m := new(sync.RWMutex) // m is a pointer to a read write mutex for lu
m.Lock()
ilu.AddFmtCount(w)
m.Unlock()
// Just in case the id list file FnJSON gets updated, the file watcher updates lut.
// This way trice needs NOT to be restarted during development process.
//go ilu.FileWatcher(w, fSys, m)
var li id.TriceIDLookUpLI // nil
if id.LIFnJSON == "emptyFile" { // reserved name for tests only
li = make(id.TriceIDLookUpLI) // li is not nil, but empty
} else {
if _, err := fSys.Stat(id.LIFnJSON); errors.Is(err, os.ErrNotExist) {
if id.LIFnJSON != "off" && id.LIFnJSON != "none" && id.LIFnJSON != "no" {
if Verbose {
fmt.Fprintf(w, "path/to/ %s does not exist: li is nil\n", id.LIFnJSON)
}
}
} else {
li = id.NewLutLI(w, fSys, id.LIFnJSON) // lut is a map, that means a pointer
decoder.LILUT = li
// Just in case the id location information file LIFnJSON gets updated, the file watcher updates li.
// This way trice needs NOT to be restarted during development process.
//go li.FileWatcher(w, fSys)
}
}
sw := emitter.New(w)
var interrupted bool
var counter int
for {
rwc, e := receiver.NewReadWriteCloser(w, fSys, Verbose, receiver.Port, receiver.PortArguments)
if e != nil {
fmt.Fprintln(w, e)
if !interrupted {
return // hopeless
}
time.Sleep(1000 * time.Millisecond) // retry interval
fmt.Fprintf(w, "\rsig:(re-)setup input port...%d", counter)
counter++
continue
}
defer func() { msg.OnErr(rwc.Close()) }()
interrupted = true
if receiver.ShowInputBytes {
rwc = receiver.NewBytesViewer(w, rwc)
}
if receiver.BinaryLogfileName != "off" && receiver.BinaryLogfileName != "none" {
rwc = receiver.NewBinaryLogger(w, fSys, rwc)
}
e = translator.Translate(w, sw, ilu, m, li, rwc)
if io.EOF == e {
return // end of predefined buffer
}
}
}
// scVersion is sub-command 'version'. It prints version information.
func scVersion(w io.Writer) error {
if Verbose {
fmt.Fprintln(w, "https://github.com/rokath/trice")
}
// Fallback if nothing has been set (e.g., go install without ldflags)
if Version == "" && Commit == "" && Date == "" && Branch == "" {
fmt.Fprintln(w, "version=dev (no build info)")
return nil
}
dirtyText := ""
if GitState == "dirty" {
dirtyText = " (local modifications at build time)"
}
// If version is set (GoReleaser or local build)
if Version != "" {
// GoReleaser builds usually don't set Branch/GitState/GitStatus.
// For those, we omit the branch to avoid "branch=" being empty.
if Branch != "" {
fmt.Fprintf(w, "no version, branch=%s%s, commit=%s, built at %s", Branch, dirtyText, Commit, Date)
} else {
fmt.Fprintf(w, "version=%s, commit=%s, built at %s",
Version, Commit, Date)
}
// Optional: append builtBy if present.
if BuiltBy != "" {
fmt.Fprintf(w, " (built by %s)", BuiltBy)
}
fmt.Fprintln(w)
} else {
// Fallback to Branch/Commit for local dev builds with missing version
if Branch != "" {
fmt.Fprintf(w, "branch=%s%s, ", Branch, dirtyText)
}
if Commit != "" {
fmt.Fprintf(w, "commit=%s, ", Commit)
}
fmt.Fprintf(w, "built at %s\n", Date)
}
// Only with verbose + dirty: display list of files that were modified at build time.
if Verbose && GitState == "dirty" && GitStatus != "" {
fmt.Fprintln(w, "modified files at build time:")
for _, line := range strings.Split(GitStatus, "|") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
fmt.Fprintf(w, " %s\n", line)
}
}
return nil
}