This repository was archived by the owner on Feb 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathopts.c
2292 lines (1988 loc) · 63.1 KB
/
opts.c
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file
*
* @brief Support library used by plugin gopts.
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include <kdbopts.h>
#include <stdlib.h>
#include <string.h>
#include <kdbease.h>
#include <kdbhelper.h>
#include <kdbmeta.h>
#include <kdbassert.h>
#include <kdberrors.h>
#ifdef _WIN32
static const char SEP_ENV_VALUE = ';';
#else
static const char SEP_ENV_VALUE = ':';
#endif
// Meta key storing which command an option/argument belongs to.
static char * const META_COMMAND_KEY = "command/key";
struct OptionData
{
Key * specKey;
const char * metaKey;
const char * hasArg;
const char * kind;
const char * flagValue;
const char * argName;
bool hidden;
};
struct Specification
{
KeySet * options;
KeySet * keys;
KeySet * argIndices;
KeySet * commands;
bool useSubcommands;
};
/**
* Get value of meta key with name @p meta of Key @p key as string.
* @param key Key to retrieve meta value from.
* @param meta Name of meta key.
* @return NULL if the meta value is NULL or an empty string. Otherwise the meta value.
*/
static inline const char * keyGetMetaString (const Key * key, const char * meta)
{
const Key * mk = keyGetMeta (key, meta);
const char * value = mk == NULL ? NULL : keyString (mk);
return value != NULL && value[0] == '\0' ? NULL : value;
}
/**
* Get value of meta key identified by @p lookup of the Key @p key as string.
* @param key Key to retrieve meta value from.
* @param lookup A key pointer identifying the meta key to retrieve
* @return NULL if the meta value is NULL or an empty string. Otherwise the meta value.
*/
static inline const char * keyGetMetaStringByKey (Key * key, Key * lookup)
{
const Key * mk = ksLookup (keyMeta (key), lookup, KDB_O_DEL);
const char * value = mk == NULL ? NULL : keyString (mk);
return value != NULL && value[0] == '\0' ? NULL : value;
}
static int addProcKey (KeySet * ks, const Key * key, Key * valueKey);
static KeySet * parseEnvp (const char ** envp);
static KeySet * parseArgs (Key * command, KeySet * optionsSpec, bool useSubcommands, int argc, const char ** argv, int * endArg,
Key * errorKey);
static void setOption (Key * option, const char * value, bool repeated);
static Key * splitEnvValue (const Key * envKey);
static KeySet * ksMetaGetSingleOrArray (Key * key, const char * metaName);
char * generateUsageLine (const char * progname, Key * command, const Key * commandArgs);
static char * generateOptionsList (KeySet * keysWithOpts, Key * command);
static char * generateCommandsList (KeySet * keysWithOpts, Key * commandKey);
static char * generateArgsList (KeySet * keysWithOpts, Key * command);
static char * generateEnvsList (KeySet * keysWithOpts);
static bool optionOrArgBelongsToCommand (const Key * command, const Key * optionOrArg);
static bool processSpec (struct Specification * spec, KeySet * ks, Key * specParent, Key * errorKey);
static bool processOptions (struct Specification * spec, Key * command, Key * specKey, Key ** keyWithOpt, Key * errorKey);
static bool readOptionData (struct OptionData * optionData, Key * key, const char * metaKey, Key * errorKey);
static bool processShortOptSpec (struct Specification * spec, struct OptionData * optionData, Key * command, Key ** keyWithOpt,
char ** shortOptLine, Key * errorKey);
static bool processLongOptSpec (struct Specification * spec, struct OptionData * optionData, Key * command, Key ** keyWithOpt,
char ** longOptLine, Key * errorKey);
static bool processEnvVars (KeySet * usedEnvVars, Key * specKey, Key ** keyWithOpt, Key * errorKey);
static bool processArgs (Key * command, Key * specKey, KeySet * argIndices, Key ** keyWithOpt, Key * errorKey);
static int writeOptionValues (KeySet * ks, Key * keyWithOpt, KeySet * options, Key * errorKey);
static int writeEnvVarValues (KeySet * ks, Key * keyWithOpt, KeySet * envValues, Key * errorKey);
static int writeArgsValues (KeySet * ks, Key * keyWithOpt, Key * command, KeySet * argIndices, KeySet * args, Key * errorKey);
static bool parseLongOption (Key * command, KeySet * optionsSpec, KeySet * options, int argc, const char ** argv, int * index,
Key * errorKey);
static bool parseShortOptions (Key * command, KeySet * optionsSpec, KeySet * options, int argc, const char ** argv, int * index,
Key * errorKey);
static int writeOptions (Key * command, Key * commandKey, Key * commandArgs, bool writeArgs, bool * argsWritten, KeySet * options,
struct Specification * spec, KeySet * ks, const char * progname, const char ** envp, Key * parentKey);
/**
* This functions parses a specification of program options, together with a list of arguments
* and environment variables to extract the option values.
*
* The options have to be defined in the metadata of keys in the spec namespace. If an option value
* is found for any of the given keys, a new key with the same path but inside the proc namespace
* will be inserted into @p ks. This enables a cascading lookup to find these values.
*
* Take look at https://www.libelektra.org/tutorials/command-line-options for information on how exactly
* the specification works.
*
* NOTE: Per default option processing DOES NOT stop, when a non-option string is encountered in @p argv.
* If you want processing to stop, set the metadata `posixly = 1` on @p parentKey.
*
*
* @param ks The KeySet containing the specification for the options.
* @param argc The number of strings in argv.
* @param argv The arguments to be processed.
* @param envp A list of environment variables. This needs to be a null-terminated list of
* strings of the format 'KEY=VALUE'.
* @param parentKey The parent key below which the function will search for option specifications.
* Also used for error reporting. The key will be translated into the spec namespace
* automatically, e.g. 'user:/test/parent' will be translated into 'spec:/test/parent',
* before checking against spec keys.
*
* @retval 0 on success, this is the only case in which @p ks will be modified
* @retval -1 on error, the error will be set as metadata in @p errorKey
* @retval 1 if the help option `--help` was found, use elektraGetOptsHelpMessage() access the
* generated help message
*/
int elektraGetOpts (KeySet * ks, int argc, const char ** argv, const char ** envp, Key * parentKey)
{
elektraCursor initial = ksGetCursor (ks);
Key * specParent = keyDup (parentKey, KEY_CP_ALL);
// Translate key to spec namespace
keySetNamespace (specParent, KEY_NS_SPEC);
struct Specification spec;
if (!processSpec (&spec, ks, specParent, parentKey))
{
keyDel (specParent);
ksSetCursor (ks, initial);
return -1;
}
Key * command = keyNew ("/", KEY_END);
Key * commandKey = keyNew (keyName (specParent), KEY_END);
Key * commandArgs = keyNew ("/", KEY_END);
keyDel (specParent);
if (spec.useSubcommands)
{
int lastEndArg = 0;
while (lastEndArg < argc)
{
int endArg = -1;
KeySet * options =
parseArgs (command, spec.options, true, argc - lastEndArg, argv + lastEndArg, &endArg, parentKey);
if (options == NULL)
{
keyDel (command);
keyDel (commandKey);
keyDel (commandArgs);
ksDel (spec.options);
ksDel (spec.keys);
ksDel (spec.argIndices);
ksDel (spec.commands);
ksSetCursor (ks, initial);
return -1;
}
const Key * subCommand = NULL;
if (endArg >= 0)
{
endArg += lastEndArg;
Key * commandSpec = ksLookup (spec.keys, commandKey, 0);
Key * commandLookup = keyNew ("meta:/command", KEY_END);
keyAddBaseName (commandLookup, argv[endArg]);
subCommand = ksLookup (keyMeta (commandSpec), commandLookup, KDB_O_DEL);
}
bool argsWritten = false;
int result = writeOptions (command, commandKey, commandArgs, subCommand == NULL, &argsWritten, options, &spec, ks,
argv[0], envp, parentKey);
ksDel (options);
if (result != 0)
{
keyDel (command);
keyDel (commandKey);
keyDel (commandArgs);
ksDel (spec.options);
ksDel (spec.keys);
ksDel (spec.argIndices);
ksDel (spec.commands);
ksSetCursor (ks, initial);
return result;
}
if (subCommand == NULL && !argsWritten && endArg >= 0)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (parentKey, "Unknown sub-command: %s", argv[endArg]);
keyDel (command);
keyDel (commandKey);
keyDel (commandArgs);
ksDel (spec.options);
ksDel (spec.keys);
ksDel (spec.argIndices);
ksDel (spec.commands);
ksSetCursor (ks, initial);
return -1;
}
Key * procKey = keyNew ("proc:/", KEY_VALUE, "", KEY_END);
keyAddName (procKey, strchr (keyName (commandKey), '/'));
ksAppendKey (ks, procKey);
if (subCommand == NULL)
{
keyDel (command);
keyDel (commandKey);
keyDel (commandArgs);
ksDel (spec.options);
ksDel (spec.keys);
ksDel (spec.argIndices);
ksDel (spec.commands);
ksSetCursor (ks, initial);
return 0;
}
keySetString (procKey, keyString (subCommand));
keyAddBaseName (command, keyString (subCommand));
keyAddBaseName (commandKey, keyString (subCommand));
keyAddBaseName (commandArgs, argv[endArg]);
lastEndArg = endArg;
}
ELEKTRA_ASSERT (0, "should be unreachable");
return -2;
}
else
{
int endArg = 0;
KeySet * options = parseArgs (command, spec.options, false, argc, argv, &endArg, parentKey);
if (options == NULL)
{
keyDel (command);
keyDel (commandKey);
keyDel (commandArgs);
ksDel (spec.options);
ksDel (spec.keys);
ksDel (spec.argIndices);
ksDel (spec.commands);
ksSetCursor (ks, initial);
return -1;
}
int result = writeOptions (command, commandKey, commandArgs, true, NULL, options, &spec, ks, argv[0], envp, parentKey);
keyDel (command);
keyDel (commandKey);
keyDel (commandArgs);
ksDel (options);
ksDel (spec.options);
ksDel (spec.keys);
ksDel (spec.argIndices);
ksDel (spec.commands);
ksSetCursor (ks, initial);
return result;
}
}
/**
* Extracts the command whose help message was requested from the @p errorKey used in elektraGetOpts().
* NOTE: this only works, if elektraGetOpts() returned 1.
*
* @param errorKey The same Key as passed to elektraGetOpts() as errorKey.
* @param usage If this is not NULL, it will be used instead of the default usage line.
* @param prefix If this is not NULL, it will be inserted between the usage line and the options list.
*
* @return The command extracted from @p errorKey, or NULL if no command was found.
* The returned string MUST NOT be freed with elektraFree(). It will be valid as long as @p errorKey is not keyDel()'ed.
*/
const char * elektraGetOptsHelpCommand (Key * errorKey)
{
return keyGetMetaString (errorKey, "internal/libopts/help/command");
}
/**
* Extracts the help message from the @p helpKey used in elektraGetOpts().
*
* @param helpKey The same Key as passed to elektraGetOpts() as parentKey.
* @param usage If this is not NULL, it will be used instead of the default usage line.
* Use elektraGetOptsHelpCommand() to check which command was invoked to get the right usage line.
* @param prefix If this is not NULL, it will be inserted between the usage line and the options list.
*
* @return The full help message extracted from @p helpKey, or NULL if no help message was found.
* The returned string has to be freed with elektraFree().
*/
char * elektraGetOptsHelpMessage (Key * helpKey, const char * usage, const char * prefix)
{
const char * command = elektraGetOptsHelpCommand (helpKey);
Key * lookup;
if (usage == NULL)
{
lookup = keyNew ("meta:/internal/libopts/help/usage", KEY_END);
keyAddBaseName (lookup, command);
usage = keyGetMetaStringByKey (helpKey, lookup);
}
if (usage == NULL)
{
return NULL;
}
lookup = keyNew ("meta:/internal/libopts/help/options", KEY_END);
keyAddBaseName (lookup, command);
const char * options = keyGetMetaStringByKey (helpKey, lookup);
if (options == NULL)
{
options = "";
}
lookup = keyNew ("meta:/internal/libopts/help/commands", KEY_END);
keyAddBaseName (lookup, command);
const char * commands = keyGetMetaStringByKey (helpKey, lookup);
if (commands == NULL)
{
commands = "";
}
lookup = keyNew ("meta:/internal/libopts/help/args", KEY_END);
keyAddBaseName (lookup, command);
const char * args = keyGetMetaStringByKey (helpKey, lookup);
if (args == NULL)
{
args = "";
}
lookup = keyNew ("meta:/internal/libopts/help/envs", KEY_END);
keyAddBaseName (lookup, command);
const char * envs = keyGetMetaStringByKey (helpKey, lookup);
if (envs == NULL)
{
envs = "";
}
return elektraFormat ("%s%s%s%s%s%s", usage, prefix == NULL ? "" : prefix, options, commands, args, envs);
}
// -------------
// static functions
// -------------
/**
* Validate and process the specification set in the keys of @p ks, into @p spec.
*
* @param spec The target Specification struct.
* @param ks The KeySet containing the specification.
* @param specParent The parent key. All keys of the specification are below this keys.
* @param errorKey Used to report errors.
* @retval true on success.
* @retval false on failure.
*/
bool processSpec (struct Specification * spec, KeySet * ks, Key * specParent, Key * errorKey)
{
size_t specParentLen = strlen (keyName (specParent));
// This block determines whether the spec uses sub-commands.
bool useSubcommands = false;
{
Key * parent = ksLookupByName (ks, keyName (specParent), 0);
if (parent != NULL)
{
const Key * commandMeta = keyGetMeta (parent, "command");
const char * commandMetaString = keyString (commandMeta);
if (commandMetaString != NULL && strlen (commandMetaString) == 0)
{
useSubcommands = true;
}
else if (commandMeta != NULL)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (
errorKey, "On the parent key 'command' can only be set to an empty string. Offending key: %s",
keyName (parent));
return false;
}
keyDel (parent);
}
}
KeySet * usedEnvVars = ksNew (0, KS_END);
spec->options = ksNew (
1, keyNew ("/long/help", KEY_META, "hasarg", "none", KEY_META, "kind", "single", KEY_META, "flagvalue", "1", KEY_END),
KS_END);
spec->keys = ksNew (0, KS_END);
spec->argIndices = ksNew (0, KS_END);
spec->commands = ksNew (0, KS_END);
/**
* 1. Process all keys in the @p ks and
* a. Validate sub-commands (e.g., whether meta values are set correctly and the hierarchy of (sub-)commands is legal)
* b. Generate help text for each sub-command.
* c. Validate all options (long and short), arguments and environment variables, generate help texts for each and add them
* into the @spec.
*/
for (elektraCursor i = 0; i < ksGetSize (ks); ++i)
{
Key * cur = ksAtCursor (ks, i);
// Keys that aren't in the spec namespace or below the parent key are ignored.
if (keyGetNamespace (cur) != KEY_NS_SPEC || !keyIsBelowOrSame (specParent, cur))
{
continue;
}
bool isParentKey = strcmp (keyName (cur), keyName (specParent)) == 0;
Key * keyWithOpt = NULL;
// step 1a.) Validate sub-commands
// If meta key "command" is set, the current key is a sub-command.
const Key * commandMeta = keyGetMeta (cur, "command");
if (commandMeta != NULL)
{
if (!useSubcommands)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (
errorKey, "'command' can only be used, if it is set on the parent key as well. Offending key: %s",
keyName (cur));
ksDel (spec->options);
ksDel (spec->argIndices);
ksDel (spec->commands);
ksDel (spec->keys);
ksDel (usedEnvVars);
return false;
}
const char * commandMetaString = keyString (commandMeta);
if (commandMetaString == NULL || (strlen (commandMetaString) == 0 && !isParentKey))
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (
errorKey,
"'command' must be set to a non-empty string (except on the parent key). Offending key: %s",
keyName (cur));
ksDel (spec->options);
ksDel (spec->argIndices);
ksDel (spec->commands);
ksDel (spec->keys);
ksDel (usedEnvVars);
return false;
}
if (keyWithOpt == NULL)
{
keyWithOpt = keyNew (keyName (cur), KEY_META, "command", "1", KEY_END);
}
// step 1b.)
const char * optHelp = keyGetMetaString (cur, "opt/help");
const char * description = keyGetMetaString (cur, "description");
const char * help = optHelp != NULL ? optHelp : (description != NULL ? description : "");
char * commandHelp = elektraFormat (" %-28s%s", commandMetaString, help);
keySetMeta (keyWithOpt, "command/help", commandHelp);
elektraFree (commandHelp);
if (!isParentKey)
{
Key * helpKey = keyNew (keyName (cur) + specParentLen, KEY_META, "hasarg", "none", KEY_META, "kind",
"single", KEY_META, "flagvalue", "1", KEY_END);
keyAddName (helpKey, "/long/help");
ksAppendKey (spec->options, helpKey);
}
}
Key * command = keyNew ("/", KEY_VALUE, keyName (specParent), KEY_END);
if (useSubcommands && !isParentKey)
{
// Determine name of the parent of cur
Key * curParent = keyNew (keyName (cur), KEY_END);
if (strcmp (keyBaseName (curParent), "#") == 0)
{
keySetBaseName (curParent, NULL); // remove #
}
keySetBaseName (curParent, NULL);
// Check if parent of current key exists in the KeySet
Key * maybeCommand = ksLookup (ks, curParent, KDB_O_DEL);
if (maybeCommand == NULL)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (errorKey,
"The parent of this key (%s) must have the 'command' metakey set. "
"Offending key: parent doesn't exist",
keyName (cur));
keyDel (keyWithOpt);
keyDel (command);
ksDel (spec->options);
ksDel (spec->argIndices);
ksDel (spec->commands);
ksDel (spec->keys);
ksDel (usedEnvVars);
return false;
}
// Check if parent of current key has metakey "command" set
const char * commandMetaString = keyGetMetaString (maybeCommand, "command");
if (commandMetaString == NULL && strcmp (keyName (maybeCommand), keyName (specParent)) != 0)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (
errorKey, "The parent of this key (%s) must have the 'command' metakey set. Offending key: %s",
keyName (cur), keyName (maybeCommand));
keyDel (keyWithOpt);
keyDel (command);
ksDel (spec->options);
ksDel (spec->argIndices);
ksDel (spec->commands);
ksDel (spec->keys);
ksDel (usedEnvVars);
return false;
}
if (commandMeta != NULL)
{
// add sub-command to parent command
Key * parentCommand = ksLookup (spec->keys, maybeCommand, 0);
Key * subCommand = keyNew ("meta:/command", KEY_VALUE, keyBaseName (cur), KEY_END);
keyAddBaseName (subCommand, keyString (commandMeta));
if (ksLookup (keyMeta (parentCommand), subCommand, 0) != NULL)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (errorKey, "Duplicate sub-command '%s'. Offending key: %s",
keyString (commandMeta), keyName (cur));
keyDel (subCommand);
keyDel (keyWithOpt);
keyDel (command);
ksDel (spec->options);
ksDel (spec->argIndices);
ksDel (spec->keys);
ksDel (spec->commands);
ksDel (usedEnvVars);
return false;
}
ksAppendKey (keyMeta (parentCommand), subCommand);
}
keyAddName (command, keyName (maybeCommand) + specParentLen);
keySetString (command, keyString (maybeCommand));
if (commandMeta != NULL)
{
keySetMeta (command, "hassubcommands", "1");
}
}
keyCopyAllMeta (command, ksLookup (spec->commands, command, KDB_O_CREATE));
// step 1c.)
if (!processOptions (spec, command, cur, &keyWithOpt, errorKey))
{
keyDel (command);
keyDel (keyWithOpt);
ksDel (spec->argIndices);
ksDel (spec->options);
ksDel (spec->keys);
ksDel (spec->commands);
ksDel (usedEnvVars);
return false;
}
if (!processEnvVars (usedEnvVars, cur, &keyWithOpt, errorKey))
{
keyDel (command);
keyDel (keyWithOpt);
ksDel (spec->argIndices);
ksDel (spec->options);
ksDel (spec->keys);
ksDel (spec->commands);
ksDel (usedEnvVars);
return false;
}
if (!processArgs (command, cur, spec->argIndices, &keyWithOpt, errorKey))
{
keyDel (command);
keyDel (keyWithOpt);
ksDel (spec->argIndices);
ksDel (spec->options);
ksDel (spec->keys);
ksDel (spec->commands);
ksDel (usedEnvVars);
return false;
}
keyCopyAllMeta (ksLookup (spec->commands, command, KDB_O_CREATE), command);
keyDel (command);
if (keyWithOpt != NULL)
{
// Add the processed key to the KeySet
ksAppendKey (spec->keys, keyWithOpt);
}
}
ksDel (usedEnvVars);
for (kdb_long_long_t i = 0; i < ksGetSize (spec->argIndices); i++)
{
Key * cur = ksAtCursor (spec->argIndices, i);
const char * maxIndex = keyGetMetaString (cur, "index");
char indexMetaName[ELEKTRA_MAX_ARRAY_SIZE + sizeof ("index/")] = "index/#0";
kdb_long_long_t indexValue = 0;
while (maxIndex != NULL && strcmp (indexMetaName + sizeof ("index"), maxIndex) < 0)
{
const char * meta = keyGetMetaString (cur, indexMetaName);
if (meta == NULL)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (
errorKey,
"The values of 'args/index' must be continuous, but index " ELEKTRA_LONG_LONG_F
" is missing in keys below: %s",
indexValue, keyGetMetaString (cur, "key"));
ksDel (spec->argIndices);
ksDel (spec->options);
ksDel (spec->keys);
ksDel (spec->commands);
return false;
}
++indexValue;
elektraWriteArrayNumber (indexMetaName + sizeof ("index"), indexValue);
}
}
spec->useSubcommands = useSubcommands;
return true;
}
/**
* Process the option specification for @p specKey.
*
* @retval true on success
* @retval false on error
*/
bool processOptions (struct Specification * spec, Key * command, Key * specKey, Key ** keyWithOpt, Key * errorKey)
{
const char * optHelp = keyGetMetaString (specKey, "opt/help");
const char * description = keyGetMetaString (specKey, "description");
const char * help = optHelp != NULL ? optHelp : (description != NULL ? description : "");
KeySet * opts = ksMetaGetSingleOrArray (specKey, "opt");
if (opts == NULL)
{
const char * longOpt = keyGetMetaString (specKey, "opt/long");
if (longOpt == NULL)
{
return true;
}
// no other way to create Key with name "opt"
Key * k = keyNew ("/", KEY_META, "opt", "", KEY_END);
opts = ksNew (2, keyNew ("meta:/#", KEY_END), keyGetMeta (k, "opt"), KS_END);
keyDel (k);
}
ksRewind (opts);
ksNext (opts); // skip count
Key * metaKey;
char * shortOptLine = elektraStrDup ("");
char * longOptLine = elektraStrDup ("");
while ((metaKey = ksNext (opts)) != NULL)
{
struct OptionData optionData;
if (!readOptionData (&optionData, specKey, keyName (metaKey), errorKey))
{
ksDel (opts);
elektraFree (shortOptLine);
elektraFree (longOptLine);
return false;
}
if (!processShortOptSpec (spec, &optionData, command, keyWithOpt, &shortOptLine, errorKey))
{
ksDel (opts);
elektraFree (shortOptLine);
elektraFree (longOptLine);
return false;
}
if (!processLongOptSpec (spec, &optionData, command, keyWithOpt, &longOptLine, errorKey))
{
ksDel (opts);
elektraFree (shortOptLine);
elektraFree (longOptLine);
return false;
}
}
if (*keyWithOpt != NULL)
{
if (strlen (shortOptLine) > 2)
{
shortOptLine[strlen (shortOptLine) - 2] = '\0'; // trim ", " of end
}
if (strlen (longOptLine) > 2)
{
longOptLine[strlen (longOptLine) - 2] = '\0'; // trim ", " of end
}
char * optsLinePart = elektraFormat ("%s%s%s", shortOptLine, strlen (longOptLine) > 0 ? ", " : "", longOptLine);
elektraFree (shortOptLine);
elektraFree (longOptLine);
size_t length = strlen (optsLinePart);
if (length > 0)
{
char * optsLine;
if (length < 30)
{
optsLine = elektraFormat (" %-28s%s", optsLinePart, help);
}
else
{
optsLine = elektraFormat (" %s\n %30s%s", optsLinePart, "", help);
}
keySetMeta (*keyWithOpt, "opt/help", optsLine);
elektraFree (optsLine);
}
elektraFree (optsLinePart);
}
else
{
elektraFree (shortOptLine);
elektraFree (longOptLine);
}
ksDel (opts);
return true;
}
/**
* Read the option data (i.e. hasarg, flagvalue, etc.) for the option
* given by @p metaKey 's name from @p key.
* @retval true on success
* @retval false on error
*/
bool readOptionData (struct OptionData * optionData, Key * key, const char * metaKey, Key * errorKey)
{
// two slashes in string because array index is inserted in-between
char metaBuffer[ELEKTRA_MAX_ARRAY_SIZE + sizeof ("meta:/opt//flagvalue") + 1];
strncpy (metaBuffer, metaKey, ELEKTRA_MAX_ARRAY_SIZE + 3); // 3 = opt/ - null byte from ELEKTRA_MAX_SIZE
strncat (metaBuffer, "/arg", 11); // 11 = remaining space in metaBuffer
const char * hasArg = keyGetMetaString (key, metaBuffer);
if (hasArg == NULL)
{
hasArg = "required";
}
strncpy (metaBuffer, metaKey, ELEKTRA_MAX_ARRAY_SIZE + 3); // 3 = opt/ - null byte from ELEKTRA_MAX_SIZE
strncat (metaBuffer, "/arg/help", 11); // 11 = remaining space in metaBuffer
const char * argNameMeta = keyGetMetaString (key, metaBuffer);
strncpy (metaBuffer, metaKey, ELEKTRA_MAX_ARRAY_SIZE + 3); // 3 = opt/ - null byte from ELEKTRA_MAX_SIZE
strncat (metaBuffer, "/flagvalue", 11); // 11 = remaining space in metaBuffer
const char * flagValue = keyGetMetaString (key, metaBuffer);
if (flagValue == NULL)
{
flagValue = "1";
}
else if (elektraStrCmp (hasArg, "none") != 0 && elektraStrCmp (hasArg, "optional") != 0)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (
errorKey,
"The flagvalue metadata can only be used, if the opt/arg metadata is set to 'none' or "
"'optional'. (key: %s)",
keyName (key));
return false;
}
strncpy (metaBuffer, metaKey, ELEKTRA_MAX_ARRAY_SIZE + 3); // 3 = opt/ - null byte from ELEKTRA_MAX_SIZE
strncat (metaBuffer, "/hidden", 11); // 11 = remaining space in metaBuffer
bool hidden = false;
const char * hiddenStr = keyGetMetaString (key, metaBuffer);
if (hiddenStr != NULL && elektraStrCmp (hiddenStr, "1") == 0)
{
hidden = true;
}
const char * kind = "single";
if (elektraStrCmp (keyBaseName (key), "#") == 0)
{
kind = "array";
}
optionData->specKey = key;
optionData->metaKey = metaKey;
optionData->hasArg = hasArg;
optionData->flagValue = flagValue;
optionData->argName = argNameMeta;
optionData->hidden = hidden;
optionData->kind = kind;
return true;
}
/**
* Process a possible short option specification on @p keyWithOpt.
* The specification will be added to @p optionsSpec. The option
* string will be added to @p shortOptLine.
*
* @retval true on success
* @retval false on error
*/
bool processShortOptSpec (struct Specification * spec, struct OptionData * optionData, Key * command, Key ** keyWithOpt,
char ** shortOptLine, Key * errorKey)
{
Key * key = optionData->specKey;
const char * hasArg = optionData->hasArg;
const char * kind = optionData->kind;
const char * flagValue = optionData->flagValue;
const char * argName = optionData->argName;
bool hidden = optionData->hidden;
const char * shortOptStr = keyGetMetaString (optionData->specKey, optionData->metaKey);
if (shortOptStr == NULL || shortOptStr[0] == '\0')
{
return true;
}
const char shortOpt = shortOptStr[0];
if (shortOpt == '-')
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (errorKey,
"Character '-' cannot be used as a short option. It would collide with the "
"special string '--'. Offending key: %s",
keyName (key));
return false;
}
const char * commandName = command != NULL ? keyName (command) : "/";
Key * shortOptSpec = keyNew (commandName, KEY_META, "key", keyName (key), KEY_META, "hasarg", hasArg, KEY_META, "kind", kind,
KEY_META, "flagvalue", flagValue, KEY_END);
keyAddBaseName (shortOptSpec, "short");
keyAddBaseName (shortOptSpec, (char[]){ shortOpt, '\0' });
Key * existing = ksLookupByName (spec->options, keyName (shortOptSpec), 0);
if (existing != NULL)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (errorKey,
"The option '-%c' has already been specified for the key '%s'. Additional key: %s",
shortOpt, keyGetMetaString (existing, "key"), keyName (key));
keyDel (shortOptSpec);
keyDel (existing);
return false;
}
ksAppendKey (spec->options, shortOptSpec);
if (*keyWithOpt == NULL)
{
// Mark this option as belonging to command "command".
*keyWithOpt = keyNew (keyName (key), KEY_META, META_COMMAND_KEY, keyName (command), KEY_END);
}
elektraMetaArrayAdd (*keyWithOpt, "opt", keyName (shortOptSpec));
if (!hidden)
{
char * argString = "";
if (elektraStrCmp (hasArg, "required") == 0)
{
argString = argName == NULL ? " ARG" : elektraFormat (" %s", argName);
}
char * newShortOptLine = elektraFormat ("%s-%c%s, ", *shortOptLine, shortOpt, argString);
elektraFree (*shortOptLine);
if (argName != NULL)
{
elektraFree (argString);
}
*shortOptLine = newShortOptLine;
}
return true;
}
/**
* Process a possible long option specification on @p keyWithOpt.
* The specification will be added to @p optionsSpec. The option
* string will be added to @p longOptLine.
*
* @retval true on success
* @retval false on error
*/
bool processLongOptSpec (struct Specification * spec, struct OptionData * optionData, Key * command, Key ** keyWithOpt, char ** longOptLine,
Key * errorKey)
{
Key * key = optionData->specKey;
const char * hasArg = optionData->hasArg;
const char * kind = optionData->kind;
const char * flagValue = optionData->flagValue;
const char * argName = optionData->argName;
bool hidden = optionData->hidden;
char * longMeta = elektraFormat ("%s/long", optionData->metaKey);
const char * longOpt = keyGetMetaString (key, longMeta);
elektraFree (longMeta);
if (longOpt == NULL)
{
return true;
}
if (elektraStrCmp (longOpt, "help") == 0)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (errorKey,
"Option 'help' cannot be used as a long option. It would collide with the "
"help option '--help'. Offending key: %s",
keyName (key));
return false;
}
const char * commandName = command != NULL ? keyName (command) : "/";
Key * longOptSpec = keyNew (commandName, KEY_META, "key", keyName (key), KEY_META, "hasarg", hasArg, KEY_META, "kind", kind,
KEY_META, "flagvalue", flagValue, KEY_END);
keyAddBaseName (longOptSpec, "long");
keyAddBaseName (longOptSpec, longOpt);
Key * existing = ksLookupByName (spec->options, keyName (longOptSpec), 0);
if (existing != NULL)
{
ELEKTRA_SET_VALIDATION_SEMANTIC_ERRORF (errorKey,
"The option '--%s' has already been specified for the key '%s'. Additional key: %s",
longOpt, keyGetMetaString (existing, "key"), keyName (key));
keyDel (longOptSpec);
return false;
}
ksAppendKey (spec->options, longOptSpec);
if (*keyWithOpt == NULL)
{
// Mark this option as belonging to command "command".
*keyWithOpt = keyNew (keyName (key), KEY_META, META_COMMAND_KEY, keyName (command), KEY_END);
}
elektraMetaArrayAdd (*keyWithOpt, "opt", keyName (longOptSpec));
if (!hidden)
{
char * argString = "";
if (elektraStrCmp (hasArg, "required") == 0)
{
argString = argName == NULL ? "=ARG" : elektraFormat ("=%s", argName);
}
else if (elektraStrCmp (hasArg, "optional") == 0)
{
argString = argName == NULL ? "=[ARG]" : elektraFormat ("=[%s]", argName);
}
char * newLongOptLine = elektraFormat ("%s--%s%s, ", *longOptLine, longOpt, argString);
elektraFree (*longOptLine);
if (argName != NULL)
{