Repository navigation
Expand file tree
/
Copy pathclimate.go
More file actions
652 lines (460 loc) · 15.6 KB
/
Copy pathclimate.go
File metadata and controls
652 lines (460 loc) · 15.6 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
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
// Copyright 2019-2025, Matthew Wilson and Synesis Information Systems. All
// rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
* Created: 22nd March 2019
* Updated: 20th August 2026
*/
package libclimate
import (
"github.com/synesissoftware/libCLImate.Go/internal"
clasp "github.com/synesissoftware/CLASP.Go"
"fmt"
"io"
"os"
"path"
"unicode"
)
// Type of flags passed to the [Init] method.
type InitFlag int64
// Type of flags passed to the [Climate.Parse] and [Climate.ParseAndVerify] methods.
type ParseFlag int64
// Type of flags passed to the [Climate.AddFlag] and [Climate.AddOption] methods.
type AliasFlag int64
// Structure representing a CLI parsing context, obtained from [Init].
type Climate struct {
Specifications []*clasp.Specification // The specifications created by [Init].
ParseFlags clasp.ParseFlag // Parsing flags.
Version any // Version field that can be specified by application code in the function called by [Init].
VersionPrefix string // Version-prefix field that can be specified by application code in the function called by [Init].
InfoLines []string // Information lines field that can be specified by application code in the function called by [Init].
ValuesString string // Values-string field that can be specified by application code in the function called by [Init].
ProgramName string // Program-name field that can be specified by application code in the function called by [Init]. Defaults to `os.Args[0]`.
ValueNames []string // Specifies a list of value names that may be used in a contingent report when insufficient values are specified on the command-line (as determined by [Climate.ValuesConstraint]).
ValuesConstraint []int // An array of 1 or 2 numbers that specify the number of values, or the minimum and maximum number of values, required. A value of -1 means "no constraint", so, for example, the constraint `{2, -1}` means 2+ values are required.
UsageHelpSuffix string // An optional string to be applied to the end of the contingent report produced by [Climate.Abort]. Defaults to nothing. Specify ":" for default suffix string of "; use --help for usage". Insert leading "; " unless first character is punctuation.
initFlags InitFlag
stream io.Writer
exiter internal.Exiter
}
// Structure representing CLI results, obtained from [Climate.Parse].
type Result struct {
Flags []*clasp.Argument // Array of all flags.
Options []*clasp.Argument // Array of all options.
Values []*clasp.Argument // Array of all values.
ProgramName string // The program name inferred by [Init], which may be overridden in the function called by [Init].
Argv []string // The original argument string array passed to [Parse].
arguments *clasp.Arguments
parseFlags ParseFlag
stream io.Writer
exiter internal.Exiter
valueNames []string
valuesConstraint []int
usageHelpSuffix string
}
// Callback function for specification of Climate via DSL.
type InitFunc func(cl *Climate) error
// Type of callback function that may be specified to [Climate.AddFlagFunc].
type FlagFunc func()
// Type of callback function that may be specified to
// [Climate.AddOptionFunc], which receives the argument and its
// specification.
type OptionFunc func(option *clasp.Argument, specification *clasp.Specification)
const (
InitFlag_None InitFlag = 0 // No initialisation flags specified.
)
const (
InitFlag_PanicOnFailure InitFlag = 1 << iota // Causes [Init] to panic if an error encountered during processing.
InitFlag_NoHelpFlag // Suppresses the provision and processing of a help flag (aka "--help").
InitFlag_NoVersionFlag // Suppresses the provision and processing of a version flag (aka "--version").
)
const (
ParseFlag_None ParseFlag = 0 // No parse flags specified.
)
const (
ParseFlag_PanicOnFailure ParseFlag = 1 << iota // Causes [Climate.Parse] to panic if an error encountered during processing.
ParseFlag_DontCheckUnused // Causes [Climate.Verify] to ignore unrecognised arguments.
)
const (
_libCLImate_FlagFunc = "_libCLImate_FlagFunc_F73BB1C0_92D7_4cd5_9C36_DB672290CBE7"
_libCLImate_OptionFunc = "_libCLImate_OptionFunc_F73BB1C0_92D7_4cd5_9C36_DB672290CBE7"
)
const (
UsageHelpSuffix_Default = "; use --help for usage"
)
/* /////////////////////////////////////////////////////////////////////////
* helper functions
*/
func parse_Exiter_from_options_(options ...any) (result internal.Exiter, err error) {
for _, option := range options {
switch v := option.(type) {
case internal.Exiter:
return v, nil
}
}
return
}
func parse_Stream_from_options_(options ...any) (result io.Writer, err error) {
for _, option := range options {
switch v := option.(type) {
case io.Writer:
return v, nil
}
}
return
}
func parse_InitFlags_from_options_(options ...any) (result InitFlag, err error) {
for _, option := range options {
switch v := option.(type) {
case InitFlag:
result |= v
}
}
return
}
func parse_ParseFlags_from_options_(options ...any) (result ParseFlag, err error) {
for _, option := range options {
switch v := option.(type) {
case ParseFlag:
result |= v
}
}
return
}
func pointer_specifications_to_value_specifications(input []*clasp.Specification) (result []clasp.Specification) {
result = make([]clasp.Specification, len(input))
for i, a := range input {
result[i] = *a
}
return
}
func uhs_(uhs string) string {
switch uhs {
default:
var first rune
for _, c := range uhs {
first = c
break
}
if unicode.IsPunct(first) {
return uhs
} else {
return "; " + uhs
}
case ":":
return UsageHelpSuffix_Default
case "":
// do nothing
return ""
}
}
/* /////////////////////////////////////////////////////////////////////////
* API functions
*/
// Initialises a Climate instance, according to the given function (which
// may not be nil) and arguments.
func Init(initFn InitFunc, options ...any) (climate *Climate, err error) {
var initFlags InitFlag
var stream io.Writer
var exiter internal.Exiter
if err == nil {
initFlags, err = parse_InitFlags_from_options_(options...)
}
if err == nil {
stream, err = parse_Stream_from_options_(options...)
}
if err == nil {
exiter, err = parse_Exiter_from_options_(options...)
}
if err == nil && exiter == nil {
exiter = new(internal.DefaultExiter)
}
if err == nil {
var program_name string
if 0 != len(os.Args[0]) {
program_name = path.Base(os.Args[0])
}
climate = &Climate{
Specifications: []*clasp.Specification{},
//ParseFlags:
//Version:
//VersionPrefix:
//InfoLines:
// ValuesString:
ProgramName: program_name,
// ValueNames:
// ValuesConstraint:
UsageHelpSuffix: UsageHelpSuffix_Default,
initFlags: initFlags,
stream: stream,
exiter: exiter,
}
if 0 == (initFlags & InitFlag_NoHelpFlag) {
climate.AddFlag(clasp.HelpFlag())
}
if 0 == (initFlags & InitFlag_NoVersionFlag) {
climate.AddFlag(clasp.VersionFlag())
}
err = initFn(climate)
}
if err != nil {
if 0 != (InitFlag_PanicOnFailure & initFlags) {
panic(err)
}
}
return
}
// Adds an alias to the Climate instance
//
// The resolved_name param can be the name of a flag or option, or an
// option-with-value. The alias param is the alias (which must not
// contain an equals sign.
func (cl *Climate) AddAlias(resolved_name, alias string) {
f := clasp.Flag(resolved_name).SetAlias(alias)
cl.Specifications = append(cl.Specifications, &f)
}
// Adds a (copy of the) flag to the Climate instance.
func (cl *Climate) AddFlag(flag clasp.Specification, flags ...AliasFlag) {
cl.Specifications = append(cl.Specifications, &flag)
}
// Adds a (copy of the) flag to the Climate instance.
func (cl *Climate) AddFlagFunc(flag clasp.Specification, flagFn FlagFunc, flags ...AliasFlag) {
newFlag := flag.SetExtra(_libCLImate_FlagFunc, flagFn)
cl.Specifications = append(cl.Specifications, &newFlag)
}
// Adds a (copy of the) option to the Climate instance.
func (cl *Climate) AddOption(option clasp.Specification, flags ...AliasFlag) {
cl.Specifications = append(cl.Specifications, &option)
}
// Adds a (copy of the) option to the Climate instance.
func (cl *Climate) AddOptionFunc(option clasp.Specification, optionFn OptionFunc, flags ...AliasFlag) {
newOption := option.SetExtra(_libCLImate_OptionFunc, optionFn)
cl.Specifications = append(cl.Specifications, &newOption)
}
// Parses a command line, obtaining a Result instance representing the
// arguments received by the process.
func (cl Climate) Parse(argv []string, options ...any) (result Result, err error) {
var parseFlags ParseFlag
var stream io.Writer
var exiter internal.Exiter
var arguments *clasp.Arguments
if err == nil {
parseFlags, err = parse_ParseFlags_from_options_(options...)
}
if err == nil {
stream, err = parse_Stream_from_options_(options...)
}
if err == nil && stream == nil {
if cl.stream != nil {
stream = cl.stream
} else {
stream = os.Stderr
}
}
if err == nil {
exiter, err = parse_Exiter_from_options_(options...)
}
if err == nil && exiter == nil {
exiter = cl.exiter
}
if err == nil {
parse_params := clasp.ParseParams{
Specifications: pointer_specifications_to_value_specifications(cl.Specifications),
}
arguments = clasp.Parse(argv, parse_params)
if 0 == (cl.initFlags & InitFlag_NoHelpFlag) {
if arguments.FlagIsSpecified(clasp.HelpFlag()) {
clasp.ShowUsage(parse_params.Specifications, clasp.UsageParams{
Version: cl.Version,
VersionPrefix: cl.VersionPrefix,
InfoLines: cl.InfoLines,
ValuesString: cl.ValuesString,
Stream: stream,
Exiter: exiter,
ProgramName: arguments.ProgramName,
})
}
}
if 0 == (cl.initFlags & InitFlag_NoVersionFlag) {
if arguments.FlagIsSpecified(clasp.VersionFlag()) {
clasp.ShowVersion(parse_params.Specifications, clasp.UsageParams{
Version: cl.Version,
VersionPrefix: cl.VersionPrefix,
Stream: stream,
Exiter: exiter,
ProgramName: arguments.ProgramName,
})
}
}
for i := 0; i != len(arguments.Arguments); i++ {
var argument *clasp.Argument = arguments.Arguments[i]
var alias *clasp.Specification = argument.ArgumentSpecification
if alias != nil {
if 0 != len(alias.Extras) {
if ff, ff_ok := alias.Extras[_libCLImate_FlagFunc]; ff_ok {
switch fn := ff.(type) {
case FlagFunc:
fn()
argument.Use()
default:
// Issue warning
}
}
if of, of_ok := alias.Extras[_libCLImate_OptionFunc]; of_ok {
switch fn := of.(type) {
case OptionFunc:
fn(argument, alias)
argument.Use()
default:
// Issue warning
}
}
}
}
}
}
if err != nil {
if 0 != (ParseFlag_PanicOnFailure & parseFlags) {
panic(err)
}
} else {
result = Result{
Flags: arguments.Flags,
Options: arguments.Options,
Values: arguments.Values,
ProgramName: arguments.ProgramName,
Argv: argv,
arguments: arguments,
parseFlags: parseFlags,
stream: stream,
exiter: exiter,
valueNames: cl.ValueNames,
valuesConstraint: cl.ValuesConstraint,
usageHelpSuffix: cl.UsageHelpSuffix,
}
}
return
}
func (result Result) validateValues1(stream io.Writer, constraint int) {
n := len(result.Values)
if constraint < 0 {
// do not validate
} else {
if constraint < n {
fmt.Fprintf(result.stream, "%s: too many values%s\n", result.ProgramName, uhs_(result.usageHelpSuffix))
result.exiter.Exit(1)
}
if constraint > n {
var value_name string
if n < len(result.valueNames) {
value_name = result.valueNames[n]
} else {
value_name = fmt.Sprintf("value-%d", n)
}
fmt.Fprintf(result.stream, "%s: %s not specified%s\n", result.ProgramName, value_name, uhs_(result.usageHelpSuffix))
result.exiter.Exit(1)
}
}
}
func (result Result) validateValues2(stream io.Writer, min, max int) {
if min == max {
result.validateValues1(stream, min)
} else {
n := len(result.Values)
if max > 0 && max < n {
fmt.Fprintf(result.stream, "%s: too many values%s\n", result.ProgramName, uhs_(result.usageHelpSuffix))
result.exiter.Exit(1)
}
if min > 0 && min > n {
var value_name string
if n < len(result.valueNames) {
value_name = result.valueNames[n]
} else {
value_name = fmt.Sprintf("value-%d", n)
}
fmt.Fprintf(result.stream, "%s: %s not specified%s\n", result.ProgramName, value_name, uhs_(result.usageHelpSuffix))
result.exiter.Exit(1)
}
}
}
// Verifies that all given arguments received are recognised according to
// the specified flags and options
func (result Result) Verify(options ...any) {
var parseFlags ParseFlag
stream, _ := parse_Stream_from_options_(options...)
if stream == nil {
stream = result.stream
}
if stream == nil {
stream = os.Stderr
}
parseFlags, _ = parse_ParseFlags_from_options_(options...)
parseFlags |= result.parseFlags
if 0 == (ParseFlag_DontCheckUnused & parseFlags) {
// Check for any unrecognised flags or options
if unused := result.arguments.GetUnusedFlagsAndOptions(); 0 != len(unused) {
fmt.Fprintf(stream, "%s: unrecognised flag/option: %s%s\n", result.arguments.ProgramName, unused[0].Str(), uhs_(result.usageHelpSuffix))
result.exiter.Exit(1)
}
}
switch len(result.valuesConstraint) {
case 0:
// do not validate
case 1:
result.validateValues1(stream, result.valuesConstraint[0])
default:
result.validateValues2(stream, result.valuesConstraint[0], result.valuesConstraint[1])
}
}
// Parses via [Climate.Parse] and verifies via [Result.Verify].
//
// Panics, rather than returns, if the ParseFlag_PanicOnFailure flag is
// specified
func (cl Climate) ParseAndVerify(argv []string, options ...any) (result Result, err error) {
result, err = cl.Parse(argv, options...)
if err != nil {
return
} else {
result.Verify(options...)
return
}
}
// Emits the given message and, optionally, err to the standard error
// stream, prefixed with the program name, and then terminates the process
// with a non-0 exit code.
func (cl Climate) Abort(message string, err error, options ...any) {
var exiter internal.Exiter
stream, _ := parse_Stream_from_options_(options...)
if stream == nil {
stream = cl.stream
}
if stream == nil {
stream = os.Stderr
}
exiter, _ = parse_Exiter_from_options_(options...)
if exiter == nil {
exiter = cl.exiter
}
uhs := uhs_(cl.UsageHelpSuffix)
if err != nil {
fmt.Fprintf(stream, "%s: %s: %v%s\n", cl.ProgramName, message, err, uhs)
} else {
fmt.Fprintf(stream, "%s: %s%s\n", cl.ProgramName, message, uhs)
}
exiter.Exit(1)
}
// Determines if the given flag is specified
func (result Result) FlagIsSpecified(id any) bool {
return result.arguments.FlagIsSpecified(id)
}
// Looks for a flag with the given id - name, or the specification instance - and
// returns it and the value true if found; if not, returns nil and false.
func (result Result) LookupFlag(id any) (*clasp.Argument, bool) {
return result.arguments.LookupFlag(id)
}
// Looks for an option with the given id - name, or the specification instance - and
// returns it and the value true if found; if not, returns nil and false.
func (result Result) LookupOption(id any) (*clasp.Argument, bool) {
return result.arguments.LookupOption(id)
}
/* ///////////////////////////// end of file //////////////////////////// */