/
usage.go
812 lines (628 loc) · 18.3 KB
/
usage.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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
// Package usage provides methods and structs for generating usage info for
// command-line tools
package usage
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2024 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/essentialkaos/ek/v12/fmtc"
"github.com/essentialkaos/ek/v12/mathutil"
"github.com/essentialkaos/ek/v12/strutil"
"github.com/essentialkaos/ek/v12/version"
)
// ////////////////////////////////////////////////////////////////////////////////// //
const (
_SPACES = " "
_DOTS = "................................................................"
)
const _BREADCRUMBS_MIN_SIZE = 8
// ////////////////////////////////////////////////////////////////////////////////// //
const (
DEFAULT_COMMANDS_COLOR_TAG = "{y}"
DEFAULT_OPTIONS_COLOR_TAG = "{g}"
DEFAULT_EXAMPLE_DESC_COLOR_TAG = "{&}{s-}"
DEFAULT_APP_NAME_COLOR_TAG = "{c*}"
DEFAULT_APP_VER_COLOR_TAG = "{c}"
DEFAULT_APP_REL_COLOR_TAG = "{s}"
DEFAULT_APP_BUILD_COLOR_TAG = "{s-}"
)
const (
VERSION_FULL = "full"
VERSION_SIMPLE = "simple"
VERSION_MAJOR = "major"
VERSION_MINOR = "minor"
VERSION_PATCH = "patch"
VERSION_RELEASE = "release"
VERSION_BUILD = "build"
)
// ////////////////////////////////////////////////////////////////////////////////// //
type Environment []EnvironmentInfo
type EnvironmentInfo struct {
Name string
Version string
}
// About contains info about app
type About struct {
App string // App is app name
Version string // Version is current app version in semver notation
Release string // Release is current app release
Build string // Build is current app build
Desc string // Desc is short info about app
Year int // Year is year when owner company was founded
License string // License is name of license
Owner string // Owner is name of owner (company/developer)
BugTracker string // BugTracker is URL of bug tracker
AppNameColorTag string // AppNameColorTag contains default app name color tag
VersionColorTag string // VersionColorTag contains default app version color tag
ReleaseColorTag string // ReleaseColorTag contains default app release color tag
BuildColorTag string // BuildColorTag contains default app build color tag
ReleaseSeparator string // ReleaseSeparator contains symbol for version and release separation (default: -)
DescSeparator string // DescSeparator contains symbol for version and description separation (default: -)
Environment Environment // Environment contains info about environment
// Function for checking app updates
UpdateChecker UpdateChecker
}
// Info contains info about commands, options, and examples
type Info struct {
AppNameColorTag string // AppNameColorTag contains default app name color tag
CommandsColorTag string // CommandsColorTag contains default commands color tag
OptionsColorTag string // OptionsColorTag contains default options color tag
ExampleDescColorTag string // ExampleDescColorTag contains default example description color tag
Breadcrumbs bool // Breadcrumbs is flag for using bread crumbs for commands and options output
Name string // Name is app name
Args []string // Args is slice with app arguments
Spoiler string // Spoiler contains additional info
Commands []*Command // Commands is list of supported commands
Options []*Option // Options is list of supported options
Examples []*Example // Examples is list of usage examples
curGroup string
}
// UpdateChecker is a base for all update checkers
type UpdateChecker struct {
Payload string
CheckFunc func(app, version, data string) (string, time.Time, bool)
}
// ////////////////////////////////////////////////////////////////////////////////// //
// Command contains info about supported command
type Command struct {
Name string // Name is command name
Desc string // Desc is command description
Group string // Group is command group name
Args []string // Args is slice with arguments
BoundOptions []string // BoundOptions is slice with long names of related options
ColorTag string // ColorTag contains default color tag
info *Info
}
// Option contains info about supported option
type Option struct {
Short string // Short is short option name (with one minus prefix)
Long string // Long is long option name (with two minuses prefix)
Desc string // Desc is option description
Arg string // Arg is option argument
ColorTag string // ColorTag contains default color tag
info *Info
}
// Example contains usage example
type Example struct {
Cmd string // Cmd is command usage example
Desc string // Desc is usage description
Raw bool // Raw is raw example flag (without automatic binary name appending)
info *Info
}
// ////////////////////////////////////////////////////////////////////////////////// //
// NewInfo creates new info struct
func NewInfo(args ...string) *Info {
var name string
if len(args) != 0 {
name = args[0]
args = args[1:]
}
name = strutil.Q(name, filepath.Base(os.Args[0]))
info := &Info{
Name: name,
Args: args,
Breadcrumbs: true,
}
return info
}
// AddGroup adds new command group
func (i *Info) AddGroup(group string) {
if i == nil {
return
}
i.curGroup = group
}
// AddCommand adds command (name, description, args)
func (i *Info) AddCommand(a ...string) *Command {
if i == nil || len(a) < 2 {
return nil
}
group := "Commands"
if i.curGroup != "" {
group = i.curGroup
}
cmd := &Command{
Name: a[0],
Desc: a[1],
Args: a[2:],
Group: group,
info: i,
}
i.Commands = append(i.Commands, cmd)
return cmd
}
// AddOption adds option (name, description, args)
func (i *Info) AddOption(a ...string) *Option {
if i == nil || len(a) < 2 {
return nil
}
long, short := parseOptionName(a[0])
opt := &Option{
Long: long,
Short: short,
Desc: a[1],
Arg: strings.Join(a[2:], " "),
info: i,
}
i.Options = append(i.Options, opt)
return opt
}
// AddExample adds example of application usage
func (i *Info) AddExample(a ...string) {
if i == nil || len(a) == 0 {
return
}
a = append(a, "")
i.Examples = append(i.Examples, &Example{a[0], a[1], false, i})
}
// AddRawExample adds example of application usage without command prefix
func (i *Info) AddRawExample(a ...string) {
if i == nil || len(a) == 0 {
return
}
a = append(a, "")
i.Examples = append(i.Examples, &Example{a[0], a[1], true, i})
}
// AddSpoiler adds spoiler
func (i *Info) AddSpoiler(spoiler string) {
if i == nil {
return
}
i.Spoiler = spoiler
}
// BoundOptions bounds command with options
func (i *Info) BoundOptions(cmd string, options ...string) {
if i == nil || cmd == "" {
return
}
for _, command := range i.Commands {
if command.Name == cmd {
for _, opt := range options {
longOption, _ := parseOptionName(opt)
command.BoundOptions = append(command.BoundOptions, longOption)
}
return
}
}
}
// GetCommand tries to find command with given name
func (i *Info) GetCommand(name string) *Command {
if i == nil {
return nil
}
for _, command := range i.Commands {
if command.Name == name {
return command
}
}
return nil
}
// GetOption tries to find option with given name
func (i *Info) GetOption(name string) *Option {
if i == nil {
return nil
}
name, _ = parseOptionName(name)
for _, option := range i.Options {
if option.Long == name {
return option
}
}
return nil
}
// Print prints usage info
func (i *Info) Print() {
if i == nil {
return
}
appNameColorTag := strutil.B(
i.AppNameColorTag != "" && fmtc.IsTag(i.AppNameColorTag),
i.AppNameColorTag, DEFAULT_APP_NAME_COLOR_TAG,
)
optionsColorTag := strutil.B(
i.OptionsColorTag != "" && fmtc.IsTag(i.OptionsColorTag),
i.OptionsColorTag, DEFAULT_OPTIONS_COLOR_TAG,
)
commandsColorTag := strutil.B(
i.CommandsColorTag != "" && fmtc.IsTag(i.CommandsColorTag),
i.CommandsColorTag, DEFAULT_COMMANDS_COLOR_TAG,
)
usageMessage := "\n{*}Usage:{!} " + appNameColorTag + i.Name + "{!}"
if len(i.Options) != 0 {
usageMessage += " " + optionsColorTag + "{options}{!}"
}
if len(i.Commands) != 0 {
usageMessage += " " + commandsColorTag + "{command}{!}"
}
if len(i.Args) != 0 {
usageMessage += " " + strings.Join(i.Args, " ")
}
fmtc.Println(usageMessage)
if i.Spoiler != "" {
fmtc.NewLine()
fmtc.Println(i.Spoiler)
}
if len(i.Commands) != 0 {
printCommands(i)
}
if len(i.Options) != 0 {
printOptions(i)
}
if len(i.Examples) != 0 {
printExamples(i)
}
fmtc.NewLine()
}
// ////////////////////////////////////////////////////////////////////////////////// //
// String returns a string representation of the command
func (c *Command) String() string {
if c == nil {
return ""
}
return c.Name
}
// String returns a string representation of the option
func (o *Option) String() string {
if o == nil {
return ""
}
return "--" + o.Long
}
// ////////////////////////////////////////////////////////////////////////////////// //
// Print prints info about command
func (c *Command) Print() {
if c == nil {
return
}
size := getCommandSize(c)
useBreadcrumbs := true
maxSize := size
colorTag := strutil.Q(
strutil.B(c.ColorTag != "" && fmtc.IsTag(c.ColorTag), c.ColorTag, ""),
DEFAULT_COMMANDS_COLOR_TAG,
)
if c.info != nil {
colorTag = strutil.Q(c.info.CommandsColorTag, colorTag)
maxSize = getMaxCommandSize(c.info.Commands, c.Group)
useBreadcrumbs = c.info.Breadcrumbs
}
fmtc.Printf(" "+colorTag+"%s{!}", c.Name)
if len(c.Args) != 0 {
fmtc.Print(" " + printArgs(c.Args...))
}
fmtc.Print(getSeparator(size, maxSize, useBreadcrumbs))
fmtc.Print(c.Desc)
fmtc.NewLine()
}
// Print prints info about option
func (o *Option) Print() {
if o == nil {
return
}
size := getOptionSize(o)
useBreadcrumbs := true
maxSize := size
colorTag := strutil.Q(
strutil.B(o.ColorTag != "" && fmtc.IsTag(o.ColorTag), o.ColorTag, ""),
DEFAULT_OPTIONS_COLOR_TAG,
)
if o.info != nil {
colorTag = strutil.Q(o.info.OptionsColorTag, colorTag)
maxSize = getMaxOptionSize(o.info.Options)
useBreadcrumbs = o.info.Breadcrumbs
}
fmtc.Printf(" " + formatOptionName(o, colorTag))
if o.Arg != "" {
fmtc.Print(" " + printArgs(o.Arg))
}
fmtc.Print(getSeparator(size, maxSize, useBreadcrumbs))
fmtc.Print(o.Desc)
fmtc.NewLine()
}
// Print prints usage example
func (e *Example) Print() {
if e == nil {
return
}
appName := os.Args[0]
if e.info != nil {
appName = e.info.Name
}
if e.Raw {
fmtc.Printf(" %s\n", e.Cmd)
} else {
fmtc.Printf(" %s %s\n", appName, e.Cmd)
}
if e.Desc != "" {
descColor := strutil.Q(
strutil.B(
e.info.ExampleDescColorTag != "" && fmtc.IsTag(e.info.ExampleDescColorTag),
e.info.ExampleDescColorTag, "",
), DEFAULT_EXAMPLE_DESC_COLOR_TAG,
)
fmtc.Printf(" "+descColor+"%s{!}\n", e.Desc)
}
}
// ////////////////////////////////////////////////////////////////////////////////// //
// Print prints version info
func (a *About) Print(infoType ...string) {
if a == nil {
return
}
if len(infoType) != 0 {
ver := getRawVersion(a, infoType[0])
if ver != "" {
fmtc.Println(ver)
return
}
}
nameColor := strutil.Q(
strutil.B(a.AppNameColorTag != "" && fmtc.IsTag(a.AppNameColorTag), a.AppNameColorTag, ""),
DEFAULT_APP_NAME_COLOR_TAG,
)
versionColor := strutil.Q(
strutil.B(a.VersionColorTag != "" && fmtc.IsTag(a.VersionColorTag), a.VersionColorTag, ""),
DEFAULT_APP_VER_COLOR_TAG,
)
releaseColor := strutil.Q(
strutil.B(a.ReleaseColorTag != "" && fmtc.IsTag(a.ReleaseColorTag), a.ReleaseColorTag, ""),
DEFAULT_APP_REL_COLOR_TAG,
)
buildColor := strutil.Q(
strutil.B(a.BuildColorTag != "" && fmtc.IsTag(a.BuildColorTag), a.BuildColorTag, ""),
DEFAULT_APP_BUILD_COLOR_TAG,
)
relSeparator := strutil.Q(a.ReleaseSeparator, "-")
descSeparator := strutil.Q(a.DescSeparator, "-")
fmtc.Printf("\n"+nameColor+"%s{!} "+versionColor+"%s{!}", a.App, a.Version)
fmtc.If(a.Release != "").Printf(releaseColor+relSeparator+"%s{!}", a.Release)
fmtc.If(a.Build != "").Printf(buildColor+" (%s){!}", a.Build)
fmtc.Printf(" "+descSeparator+" %s\n", a.Desc)
if len(a.Environment) > 0 {
fmtc.Printf("{s-}│{!}\n")
for i, env := range a.Environment {
if len(a.Environment) != i+1 {
fmtc.Printf("{s-}├ %s: %s{!}\n", env.Name, strutil.Q(env.Version, "—"))
} else {
fmtc.Printf("{s-}└ %s: %s{!}\n", env.Name, strutil.Q(env.Version, "—"))
}
}
}
fmtc.NewLine()
if a.Owner != "" {
fmtc.If(a.Year == 0).Printf(
"{s-}Copyright (C) %d %s{!}\n",
time.Now().Year(), a.Owner,
)
fmtc.If(a.Year != 0).Printf(
"{s-}Copyright (C) %d-%d %s{!}\n",
a.Year, time.Now().Year(), a.Owner,
)
}
fmtc.If(a.License != "").Printf("{s-}%s{!}\n", a.License)
if a.UpdateChecker.CheckFunc != nil && a.UpdateChecker.Payload != "" {
newVersion, releaseDate, hasUpdate := a.UpdateChecker.CheckFunc(
a.App, a.Version, a.UpdateChecker.Payload,
)
if hasUpdate && isNewerVersion(a.Version, newVersion) {
printNewVersionInfo(a.Version, newVersion, releaseDate)
}
}
fmtc.If(a.Owner != "" || a.License != "").NewLine()
}
// ////////////////////////////////////////////////////////////////////////////////// //
// printCommands prints all supported commands
func printCommands(info *Info) {
var curGroup string
for _, command := range info.Commands {
if curGroup != command.Group {
printGroupHeader(command.Group)
curGroup = command.Group
}
command.Print()
}
}
// printOptions prints all supported options
func printOptions(info *Info) {
printGroupHeader("Options")
for _, option := range info.Options {
option.Print()
}
}
// printExamples prints all usage examples
func printExamples(info *Info) {
printGroupHeader("Examples")
total := len(info.Examples)
for index, example := range info.Examples {
example.Print()
if index < total-1 {
fmtc.NewLine()
}
}
}
// printArgs prints arguments with colors
func printArgs(args ...string) string {
var result string
for _, a := range args {
if strings.HasPrefix(a, "?") {
result += "{s-}" + a[1:] + "{!} "
} else {
result += "{s}" + a + "{!} "
}
}
return fmtc.Sprint(strings.TrimRight(result, " "))
}
// getRawVersion prints raw (just numbers) version info
func getRawVersion(about *About, infoType string) string {
switch infoType {
case VERSION_FULL:
return about.Version +
fmtc.If(about.Release != "").Sprint("-"+about.Release) +
fmtc.If(about.Build != "").Sprint("+"+about.Build)
case VERSION_SIMPLE:
return about.Version
case VERSION_RELEASE:
return about.Release
case VERSION_BUILD:
return about.Build
}
ver, _ := version.Parse(about.Version)
if ver.IsZero() {
return ""
}
switch infoType {
case VERSION_MAJOR:
return fmtc.Sprintf("%d", ver.Major())
case VERSION_MINOR:
return fmtc.Sprintf("%d", ver.Minor())
case VERSION_PATCH:
return fmtc.Sprintf("%d", ver.Patch())
}
return ""
}
// formatOptionName formats option name
func formatOptionName(opt *Option, colorTag string) string {
if opt.Short != "" {
return fmt.Sprintf(
"%s--%s{s}, %s-%s{!}",
colorTag, opt.Long, colorTag, opt.Short,
)
}
return colorTag + "--" + opt.Long + "{!}"
}
// parseOptionName parses option name
func parseOptionName(name string) (string, string) {
if strings.Contains(name, ":") {
return strutil.ReadField(name, 1, false, ':'),
strutil.ReadField(name, 0, false, ':')
}
return name, ""
}
// getSeparator return bread crumbs (or spaces if colors are disabled) for
// item name aligning
func getSeparator(size, maxSize int, breadcrumbs bool) string {
if breadcrumbs && !fmtc.DisableColors && maxSize > _BREADCRUMBS_MIN_SIZE {
return " {s-}" + _DOTS[:maxSize-size] + "{!} "
}
return " " + _SPACES[:maxSize-size] + " "
}
// getMaxCommandSize returns the biggest command size
func getMaxCommandSize(commands []*Command, group string) int {
var size int
for _, command := range commands {
if group != "" && command.Group != group {
continue
}
size = mathutil.Max(size, getCommandSize(command)+2)
}
return size
}
// getMaxOptionSize returns the biggest option size
func getMaxOptionSize(options []*Option) int {
var size int
for _, option := range options {
size = mathutil.Max(size, getOptionSize(option)+2)
}
return size
}
// getOptionSize calculates final command size
func getCommandSize(cmd *Command) int {
size := strutil.Len(cmd.Name) + 2
for _, arg := range cmd.Args {
if strings.HasPrefix(arg, "?") {
size += strutil.Len(arg)
} else {
size += strutil.Len(arg) + 1
}
}
return size
}
// getOptionSize calculates final option size
func getOptionSize(opt *Option) int {
var size int
if opt.Short != "" {
size += strutil.Len(opt.Long) + strutil.Len(opt.Short) + 4
} else {
size += strutil.Len(opt.Long) + 1
}
if opt.Arg != "" {
size += strutil.Len(opt.Arg)
if !strings.HasPrefix(opt.Arg, "?") {
size++
}
}
return size
}
// printGroupHeader print category header
func printGroupHeader(name string) {
fmtc.Printf("\n{*}%s{!}\n\n", name)
}
// isNewerVersion return true if latest version is greater than current
func isNewerVersion(current, latest string) bool {
v1, err := version.Parse(current)
if err != nil {
return false
}
v2, err := version.Parse(latest)
if err != nil {
return false
}
return v2.Greater(v1)
}
// printNewVersionInfo print info about latest release
func printNewVersionInfo(curVersion, newVersion string, releaseDate time.Time) {
cv, err := version.Parse(curVersion)
if err != nil {
return
}
nv, err := version.Parse(newVersion)
if err != nil {
return
}
days := int(time.Since(releaseDate) / (time.Hour * 24))
colorTag := "{s}"
switch {
case cv.Major() != nv.Major():
colorTag = "{r}"
case cv.Minor() != nv.Minor():
colorTag = "{y}"
}
fmtc.NewLine()
fmtc.Printf(colorTag+"Latest version is %s{!} ", newVersion)
switch days {
case 0:
fmtc.Println("{s-}(released today){!}")
case 1:
fmtc.Println("{s-}(released 1 day ago){!}")
default:
fmtc.Printf("{s-}(released %d days ago){!}\n", days)
}
}