newtypedecl 0.0.1

declarative newtype macro
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
# -*- mode: sh; sh-shell: bash -*-
# vim: set ft=bash:
# shellcheck shell=bash

### Provides help, extracts documentation from modules
###
### Inline documentation uses two or three hash characters. Three '###' is used for file level
### documentation to describe a file entirely. Two '##' are used in different contexts:
###
### Variable definitions that use the 'declare' keyword can use '##' at the end of the same
### line to document the variable.
###
### Functions use formal parameter syntax: 'function name ## [--opt] <required> [optional] - description'
### Parameters use: <mandatory>, [optional], param.., [param..], --flags, foo|bar alternatives.
### Multi-line documentation continues on following lines starting with optional whitespace
### followed by '##' and parameter explanations.
###
### Rules are documented by '##' lines before the rule definition, using the same formal
### parameter syntax when the rule accepts parameters.
###
### Only variables, functions and rules that have doc comments are included in the output.

# prototype: "topic" = "help"
# prototype: "rule" = "help"
# prototype: "function" = "help"
# prototype: "variable" = "help"
# prototype: "-s" = "literal -s"
# prototype: "--short" = "literal --short"

function help
{
  local -a args=("$@")
  local section_only=0

  if (( ${#args[@]} > 0 )); then
    case "${args[0]}" in
      -s|--short)
        section_only=1
        args=("${args[@]:1}")
        ;;
    esac
  fi

  local query="${args[*]}"
  if [[ -z "$query" ]]; then
    section_only=0
  fi

  local force_pager="${BAR_FORCE_PAGER:-}"
  local pager=""
  local -a pager_cmd=()
  local pager_available=1
  local use_pager=1
  local stdout_is_tty=1
  [[ -t 1 ]] || stdout_is_tty=0

  if [[ -n "$force_pager" ]]; then
    case "$force_pager" in
      less)
        if is_command_installed less; then
          pager="less"
        else
          pager_available=0
        fi
        ;;
      more)
        if is_command_installed more; then
          pager="more"
        else
          pager_available=0
        fi
        ;;
      *)
        pager_available=0
        ;;
    esac
  else
    if is_command_installed less; then
      pager="less"
    elif is_command_installed more; then
      pager="more"
    else
      pager_available=0
    fi
  fi

  if [[ "$pager" == "less" ]]; then
    pager_cmd=(less -R -F)
  elif [[ "$pager" == "more" ]]; then
    pager_cmd=(more)
  fi

  if [[ $stdout_is_tty -eq 0 || $pager_available -eq 0 ]]; then
    use_pager=0
  fi

  local target_line=""
  local search_term=""
  local case_sensitive=0
  local found_line=""
  local found_span=""
  local found_proto=""
  local best_rank=9999
  local best_line=""
  local best_span=""
  local best_proto=""

  if [[ -n "$query" ]]; then
    # Smart case: if query contains any uppercase letter -> case-sensitive search
    case_sensitive=0
    if [[ "$query" =~ [A-Z] ]]; then
      case_sensitive=1
    fi

    local entry span remainder value proto start_line lineno
    local lower_query="${query,,}"

    # Iterate index (which preserves case) and perform a prefix match.
    while IFS= read -r entry; do
      [[ -z "$entry" ]] && continue
      span="${entry%%:*}"
      remainder="${entry#*:}"
      proto="${remainder%%:*}"
      value="${remainder#*:}"
      [[ -z "$value" ]] && continue

      start_line="${span%%-*}"
      if [[ "$start_line" =~ ^[0-9]+$ ]]; then
        lineno="$start_line"
      else
        continue
      fi

      # Escape regex metacharacters in query for safe use in =~
      local q_escaped
      q_escaped=$(printf '%s' "$query" | sed -e 's/[]\\.^$*+?()[\]{}|]/\\&/g')

      local matched=0
      local match_exact=0
      local begins_value=0

      if (( case_sensitive == 1 )); then
        if [[ "$value" =~ (^|[^[:alnum:]])$q_escaped ]]; then
          matched=1
          if [[ "$value" == "$query" ]]; then
            match_exact=1
          fi
          if (( ${#value} >= ${#query} )) && [[ "${value:0:${#query}}" == "$query" ]]; then
            begins_value=1
          fi
        fi
      else
        local lower_value lower_q_escaped
        lower_value="${value,,}"
        lower_q_escaped=$(printf '%s' "${q_escaped,,}")
        if [[ "$lower_value" =~ (^|[^[:alnum:]])$lower_q_escaped ]]; then
          matched=1
          if [[ "$lower_value" == "$lower_query" ]]; then
            match_exact=1
          fi
          if (( ${#lower_value} >= ${#lower_query} )) && [[ "${lower_value:0:${#lower_query}}" == "$lower_query" ]]; then
            begins_value=1
          fi
        fi
      fi

      if (( matched == 0 )); then
        continue
      fi

      local rank
      case "$proto" in
        topic) rank=100 ;;
        function) rank=200 ;;
        rule) rank=300 ;;
        variable) rank=400 ;;
        *) rank=500 ;;
      esac

      if (( begins_value == 1 )); then
        (( rank -= 20 ))
      fi

      if (( match_exact == 1 )); then
        (( rank -= 10 ))
      fi

      if (( rank < best_rank || (rank == best_rank && lineno < best_line) )); then
        best_rank=$rank
        best_line="$lineno"
        best_span="$span"
        best_proto="$proto"
      fi

      if (( rank <= 90 )); then
        # Exact topic match (or better) cannot be improved further
        break
      fi
    done < <(help_indexer)

    if [[ -n "$best_line" ]]; then
      found_line="$best_line"
      found_span="$best_span"
      found_proto="$best_proto"
    fi

    if [[ -n "$found_line" ]]; then
      target_line="$found_line"
    else
      # Not found in index -> forward as text search to pager
      # Escape forward slashes for pager search patterns
      search_term="${query//\//\\/}"
    fi
  fi

  local render_span=""
  if (( section_only == 1 )); then
    if [[ -n "$found_line" && "$found_proto" != "text" ]]; then
      render_span="$found_span"
      target_line=""
      search_term=""
    else
      section_only=0
    fi
  fi

  if [[ $use_pager -eq 0 ]]; then
    if [[ -n "$render_span" ]]; then
      help_render "$render_span"
      return
    fi
    if (( stdout_is_tty == 0 )); then
      local -a help_lines=()
      mapfile -t help_lines < <(help_render)

      local total=${#help_lines[@]}
      if (( total == 0 )); then
        return
      fi

      local start_idx=0
      if [[ -n "$target_line" && "$target_line" =~ ^[0-9]+$ ]]; then
        local idx=$(( target_line - 1 ))
        if (( idx >= 0 && idx < total )); then
          start_idx=$idx
        fi
      fi

      if (( start_idx < 0 || start_idx >= total )); then
        start_idx=0
      fi

      local i
      for ((i=start_idx; i<total; i++)); do
        printf '%s\n' "${help_lines[i]}" || return 0
      done
      return
    fi

    if [[ -n "$render_span" ]]; then
      help_render "$render_span"
    else
      help_render
    fi
    return
  fi

  if [[ -n "$target_line" ]]; then
    pager_cmd+=("+$target_line")
  elif [[ -n "$search_term" ]]; then
    # Only include case-insensitive flag for less when we used smart-case (case-insensitive)
    if [[ "$pager" == "less" ]]; then
      if [[ "$case_sensitive" -eq 0 ]]; then
        pager_cmd+=(-I "+/${search_term}")
      else
        pager_cmd+=("+/${search_term}")
      fi
    else
      pager_cmd+=("+/${search_term}")
    fi
  fi

  if (( ${#pager_cmd[@]} == 0 )); then
    if [[ -n "$render_span" ]]; then
      help_render "$render_span"
    else
      help_render
    fi
    return
  fi

  # shellcheck disable=2034
  BAR_VERBOSITY_LEVEL=0
  if [[ -n "$render_span" ]]; then
    "${pager_cmd[@]}" < <(help_render "$render_span")
  else
    "${pager_cmd[@]}" < <(help_render)
  fi
}

# Help text formatting rules:
# - Basic identation step is 2 spaces
# - Normal text indentation is a even number of spaces
# - Code segments are indented by a odd number of spaces.
# - Major headers have 2 empty lines above and one empty line behind.
# - Topevel headers (at column 0) are ALL UPPERCASE. With the following section idented.
# - Quote blocks like the 'LICENSE' at the end use one extra indentation level.
# - Lists start at the same indentation level as the text.
function help_render
{
  local span="${1:-}"
  if ! declare -p help_render_cache >/dev/null 2>&1; then
    declare -ga help_render_cache=()
  mapfile -t help_render_cache <<EOF

  bar -- BAshRulez the bash rule evaluator

ABOUT

  Bar is a command runner that determines the order of commands and which ones to run, based
  on rules. It lets the user define rules that dependently and conditionally evaluate shell
  statements.  This is similar to other tools such as 'make' or 'just' but adds some
  opinionated differences. There is support for using bar as driver for githooks for
  automating workflows.

  The notable differences to other similar tools are:

  * Rules in bar can have multiple clauses.
  * Normally rules are conjunctive, when a clause of a rule fails then the rule fails and not
    further evaluated.
  * Rules can be made disjunctive, then a rule succeeds on the first succeeding clause.
  * Clauses can be conditionally skipped.
  * The results of rules are cached. Normally rules are evaluated only once, although there is
    a form to define rules that always evaluate.
  * We have a module that can memorize commands persistently and schedule evaluation to the
    background. A later instance can pick up the results from this background evaluation.

  When you read this because you have seen 'bar' or '.bar' used in a repository then you may
  look at INITIAL INSTALLATION below.


QUICKSTART

  When you cloned a project that uses bar then you can:

   ./bar                # just runs whatever the maintainer decided as default
   ./bar watch          # watches the project for changes and runs the default
   ./bar watch fastchk  # watches the project for changes and runs fast checks
   ./bar activate       # installs githooks and other local prep work

  When you want to install and use it in your own projects:

   git clone https://seed.pipapo.org/z3WhBdHt1VVNyeQ61zpY66pNzuSrP.git bar
   cd bar
   ./bar init_install ~/.local/
   git pull   # to get updates

  Then you can initialize it in your projects with:

   bar init
   git add Barf Bar.d .gitignore
   git commit -m 'start using bar'

   bar init_update  # for updating the version stored in the project

  The second personality of bar is 'please' eg.:

   please wake <hostname>     # sends a wake-on-lan packet to a host
   please suspend <hostname>  # remotely sends a host to suspend-to-ram

  Buildin help system:

   bar help [topic]
   ./bar help [topic]


INVOCATION AND SEMANTICS

   bar [rulefile] [--bare] [rule [arguments..]]
   please [rulefile] [--bare] [rule [arguments..]]
   ./bar [rulefile] [--bare] [rule [arguments..]]
   <symlink> [arguments..]

  Starts by loading all initial modules (those which have underscores in their name) and the
  rulefile, which is either "Barf", "barf", ".Barf", ".barf" when called as 'bar' or "Pleasef"
  "pleasef" ".Pleasef" ".pleasef" "\$HOME/.Pleasef" when called as 'please' and when the first
  argument is not a file.

  The duality of having 'bar' installed as 'please' is not only for making it more
  polite. This allows for a user to have private '.Pleasef' defining rules that are for common
  administration tasks distinct from versioned per-project 'Barf' and 'Bar.d' rules.

  Note that the rules for looking up the Barf/Pleasef and the modules are somewhat distinct.
  Nevertheless modules are in either way only loaded from a single directory and are not
  located in different paths. This is a opinionated choice to make the module system
  self-contained and not depend on secondary locations.

  Then the given rule (or MAIN) with the supplied arguments becomes evaluated. Finally, if
  a 'CLEANUP' rule exists, it is evaluated.

  The exit code of the invocation is the exit code of the main rule.

  Just calling 'bar' without any arguments will evaluate the 'MAIN' rule which should be what
  people expect by default. Other useful rules like 'help' for this documentation are defined
  by modules.

  When called by a symlink, the standard rulefile is loaded and instead of ‘MAIN’, a rule with
  the same name as the symlink is called with all arguments passed.


MODULE API/RULES

$(help_describe_files "$BAR_DIR"/* )


INITIAL INSTALLATION

  Bar can be invoked in different ways:

  1.  Installed in \$PATH:
      To make this work it is best to clone bar locally and symlink the checked out files
      to your '.local/' tree. This allows easy upgrades via git:

      When you have radicle (https://radicle.xyz/) installed you can clone it with:

       rad clone rad:z3WhBdHt1VVNyeQ61zpY66pNzuSrP

      Otherwise it can be cloned by git with:

       git clone https://seed.pipapo.org/z3WhBdHt1VVNyeQ61zpY66pNzuSrP.git bar

      Then you can install it in your ~/.local tree with:

       cd bar
       ./bar init_install ~/.local/

      This creates symlinks to 'bar', 'please', 'Bar.d', 'Barf.default', 'Please.default' in ~/.local
      and symlinks 'Bar.d/*' to '~/.config/please/'.

      Now 'bar' is installed, check it with 'bar help'

  2.  The local './bar' initialized from above:
      Since bar is a bash script, it’s easy to version and ship it with other software.
      To initialize it in a current directory use either of:

       bar init          # creates bar, Barf, Bar.d/
       bar init --hidden # creates .bar, .Barf, .Bar.d/

      After that Barf can be customized, unnecessary modules in Bar.d/ may be deleted.
      Once that is done these files should be put under version control.

      When the installed bar from 1. becomes updated then a local version can be updated by:

       bar init --update

      This only updates 'bar' and any existing modules in 'Bar.d/' but will not touch the
      'Barf' file since that is meant for local customization.

       bar init_update_merge_barf

      Will do a merge of the installed 'Barf' file with the local one. This *will* leave 3-way
      conflict markers behind when there are changes. These must be manually resolved!

      The updated files should then be committed to version control.

  3.  githooks symlinked from './.git/hooks/*' -> '../../bar'
      'bar' has support to be used as githooks. This needs manual enabling. Individual hooks can be
      enabled or disabled with 'bar githook_enable <hook>' and 'bar githook_disable <hook>'.
      For existing projects using 'bar' a maintainer can setup rules to activate all necessary hooks.
      This then can be activated by './bar activate'.


GIT HOOK ACTIVATION

  Bar will be inert in a project that ships with bar initialized. One can call it manually by
  './bar'.  A maintainer of the project may define 'activate' rules that activate
  githooks. These are then activated by './bar activate'. This will create symlinks in the
  '.git/hooks/' directory to the 'bar' script. These hooks will then be executed when the
  respective git hook is triggered. The rules for these hooks are defined in the 'Barf' file
  in the project directory.


RULE SEMANTICS

  Rules are a named, ordered collection of clauses. They are considered pure with inputs being
  the current directory name and the rule's arguments. Note that the content of files is *not*
  considered and the outcome of the rule should not depend on external variables. Rules are
  evaluated lazily, only once; the result of a rule is cached. This means that rules, esp. the
  actions within the body must have deterministic sematics. For performance reasons this is
  not enforced but one may observe surprising behavior when this requirement is violated.

  Rules will be autoloaded on demand from modules in 'Bar.d/' (see below AUTOMATIC MODULE
  LOADING). For rules where this fails a fallback exits that creates an implicit rule for any
  command and shell function defined with a body calling the respective command.

  Each clause in a rule has its own set of dependencies. Dependencies are other rules which
  are evaluated in order. When a (normal) dependency fails then rule it is considered to be
  failed as well and no further attempts to evaluate following dependencies and clauses are
  made.

  Dependencies can be used as 'checking' dependency which either expects the dependency to
  succeed (suffixed with a '?') or fail (prefixed with a '!'). When such a checking dependency
  fails then the rest of the current clause is skipped. This allows conditional evaluation.
  Further dependencies may be tagged as unconditional by suffix them when a tilde '~', these
  are just evaluated but rules evaluation will proceed unconditionally even if such a
  dependency fails.

  Finally every clause can have an optional body. This are shell commands executed when all
  dependencies succeeded. Because of quotiung in shell becomes a but unwieldly there are
  shortcuts to make the body refer to shell functions, this should be preferred.


RULE DEFINITION SYNTAX

   rule [[--rule-flag].. <name>:] [--clause-flag].. [[!]deps[?|~][??] args..]..
   rule [[--rule-flag].. <name>:] [--clause-flag].. [[!]deps[?|~][??] args..].. -
   rule [[--rule-flag].. <name>:] [--clause-flag].. [[!]deps[?|~][??] args..].. -- [body..]

  * [--rule-flag]

    Sets flags for a rule. Flags are additive and affect the rule, not single clauses.

    --always
      The result is not cached and the rule will be always evaluated again.

    --bare
      When this rule is called as initial rule (bar <rule>) then do not eval SETUP,
      PREPROCESS, POSTPROCESS and CLEANUP.

    --reverse
      The clauses of this rule will be evaluated in reverse order

    --disjunct
      Makes the clauses of this rule disjunctive. The rule will succeed with the first
      successful clause. Normally clauses are conjunctive and fail with the first failing
      clause.

    --meta
      Metarules do not have their own clause local variable. This allow them to modify
      the clause locals of the calling rule. 'clause_local' for example is a metarule.
      User defined rules that want to modify clause locals will need to be meta too.
      See 'try_cargo_toolchain' for an example.

  * [<name>:]

    A rule can have a optional name (suffixed with a colon).  When the name is not given it
    defaults to 'MAIN'.  Rules that have only a name but no dependencies and no body create a
    body that calls a bash command or function with the same name as the rule passing rule
    arguments to it.

  * [--clause-flag]..

    Sets flags affecting this clause only.

    --conclusive
      Makes a clause result conclusive, if not skipped no more clauses will be tried.

    --default
      Default clauses will be kept at the end of the list of clauses. Using '--default'
      together with 'disjunct' rules allows one to hook up action while maintaining a fallback
      or warning/error when no hooked up rule succeeded.

  * [[!]deps[?|~][??] args..]..

    Dependencies, are a list of other rules that this rule depends on. These will be executed
    in order. If any of the dependencies fails then this rule is considered failed as well, no
    further dependencies, bodies or clauses are executed unless this dependency is a checking
    or unconditional one.

    A dependency can be either prefixed with an exclamation mark or suffixed with question
    marks or a tilde. The exclamation mark prefix expects the dependency to fail and will
    continue then, if the dependency succeeds then the remaining dependencies and the rule
    body are skipped. With a question mark as suffix the dependency is expected to succeed,
    when it fails then the rest of the dependencies and the rule body is skipped. With a tilde
    as suffix outcome of the dependencny is ignored and the rest of the dependencies and the
    rule body is executed.  The difference here is that these checking dependencies decide if
    a clause should be skipped or succeed while a failure on a normal dependency will fail a
    rule instantly. When a rule is suffixed with two question marks then this behaves like
    "'rule_exists? dep' dep". Making this dependency optional. This can be combined with the
    another question mark, a tilde, or explamation mark prefix. This is commonly used to
    define optional rule hooks.

    Dependencies can have arguments. When provided then the dependency and its arguments must
    be quoted. These arguments are passed in the 'RULE_ARGS' array to the body of the rule.

  * -

    When there is a single hypen '-' at the end of a rule definition then the rule body is a
    call to a command or function of the same name as the rule with all arguments passed. This
    is used when one wants to add dependencies to a existing command or function.

  * -- [body..]

    After a double hyphen a optional rule body follows. This are the commands to
    execute for this clause. If these fail then the rule is considered failed. When a name but
    no body and no dependencies are given then the body defaults to the rule name. This makes
    it easy to translate simple parameterless commands and functions to rules. Usually the
    body has to be quoted to prevent shell expansions at definition time. Later when a rule
    becomes evaluated the body is passed to 'eval'.

    When the body is omitted, then the rule body is read from stdin. This allows to use
    heredocs or herestrings or read the body from a file.

    When a rule overrides an existing command a 'NOTE' will be printed on higher verbosity
    levels. The user is responsible for sensible overiding of commands.

  Rules must not have mutually recursive dependencies. When such is detected the
  evaluation aborts.

  Examples:

   # Add a clause to 'MAIN'
   rule -- echo hello

   # Different ways to define rule bodies
   rule foo_ok: -- echo inline
   rule foo_ok: -- '
       echo inline quoted
   '
   rule foo_ok: -- <<<"echo herestring"
   rule foo_ok: -- <<EOR
      echo heredoc
   EOR

   # Make a rule that fails
   rule foo_fail: -- false

   # functions and commands can be used as rules, this should be preferred
   function example
   {
       echo "i am example called with \$*"
   }

   # add a tests rule with 3 clauses
   rule tests: foo_ok? 'example "argument"' -- echo "foo_ok success"
   rule tests: !foo_ok -- echo "This is never called, but MAIN still passes"
   rule tests: foo_fail? -- echo "This is also never called"

   # add tests to MAIN
   rule tests

  For some more examples see the 'example' file that ships with bar.


  Special Rules and Names

    Rules that do not have a name fall back to 'MAIN', when no rule name is given at execution
    time then 'MAIN' will be evaluated.

    If exist 'SETUP', 'PREPROCESS', 'POSTPROCESS' and 'CLEANUP' will be called.
    * SETUP
      Should set up the environment for all subsequent evaluation. Rules in 'SETUP'
      should be self-sufficient and not expect a working environment yet.
      A failure here will abort bar.
    * PREPROCESS
      Doing any preparatory tasks within the set up environment.
      A failure here will abort bar.
    * MAIN
      When the bar is not called via a symlink or the user did not provide a rule to
      evaluate, then MAIN is the default rule. Otherwise the user supplied or symlink-deduced
      rulename will be evaluated. The result of this rule determines the exitcode of bar.
    * POSTPROCESS
      Is for evaluating things after the main rule finished. The environment and
      state is still the same as in the main rule. A failure here will be reported but not
      reflected in the exitode.
    * CLEANUP
      Is for removing temporary resources and doing any other kind of cleanup work. This
      means the state and environment at cleanup time may be differen/partially destructed and
      should not be relied upon. Clauses in the CLEANUP rule are evaluated in reverse order of
      their definition. A failure here will be reported but not reflected in the exitcode.

    After a rule that is not flagged with '--always' got evaluated it is not allowed to add
    more clauses to it anymore, as the outcome would be unexpected and impure.


  Keep-Going Mode

    Bar supports a keep-going facility via the BAR_KEEP_GOING environment variable. When
    enabled, clauses that fail do not immediately halt rule evaluation—subsequent clauses
    continue to execute, though the overall failure is still propagated.

    BAR_KEEP_GOING can be set to a number which is decremented on each failure, when this
    reachs zero no more failures are accepted and the evaluation will terminate.

    When BAR_KEEP_GOING set to anything else than a number then evaluation will accept
    infinite failures.

    When not set then it defaults to one then evaluation will terminate on the
    first failure.

    Clauses marked '--conclusive' immediately halt keep-going.


  Purity Requirements

    All rules and functions must be sequentiually pure in their success branch. This means
    side effects must not alter the behavior of subsequent rules when they fail. For rules
    where this may be the case, like rules changing directories they must rather die than
    proceed with a undefined state in case of a failure.


RULE ENVIRONMENT

  Rules implicitly depend on the arguments passed and the current directory they run in. Any
  other state or environment variable is not considered. When the result of a rule would
  depend on such external state then the rule is impure and may lead to wrong
  results.


MODULES

  Modules are shell snippets normally located in '\$BAR_DIR' ('Bar.d/', 'bar.d/', '.Bar.d/' or
  '.bar.d/') when called as 'bar' or symlink or '~/.config/please' when called as 'please'.
  The 'std_lib' and 'rules_lib' are always loaded at startup. Modules matching '*_rules' are
  also autoloaded at startup. Any other '*_lib' must be manuallly loaded with 'require'.
  Modules with simple alphabetic names without underscores are lazy loaded on demand.

  Modules are loaded with the 'require' function. This ensures that they are loaded only once.
  Require will load modules outside of '\$BAR_DIR' when a path containing at least one slash
  is given.

  The first variant for modules that are initially loaded is used for modules that define
  helper functions that don't have associated rules or rules that are primarly used for
  checking conditions before delegating to the actual rules which do the work.

  The second variant is for mudules that define rules which are self-contained and can't
  extend existing rules with new clauses. Here are the rules and functions which do the actual
  work.

  The reason for this is that some will add clauses to existing rule which must be done before
  the rules are evaluated while we can improve performance by lazy loading modules that are
  not always needed.

  The module loader derives the module name from the rule name by removing any prefixes and
  suffixes. Thus the rules which shall trigger loading must follow the naming schema with the
  module name after the prefixes in the rule name.

  Per convention '<name>_rules' is a module that contains the rules (and few functions) that
  that add clauses to other rules to make 'name' accessible. These '*_rules' files are
  autoloaded at startup.

  '<name>_lib' are libraries for support functions other modules may use (with 'require
  name_lib').


AUTOMATIC MODULE LOADING

  Rule names may include underscores, then the word before the first underscore is used to
  determine a module name used for auto-loading rules. They can have special prefixes which
  are removed when auto-loading:

  - 'is_', 'has_' and 'try_' are reserved for check rules they don't have any special
    semantic except for being stripped at auto loading.

  When a rule is not found then a module name is derived from the rule name by removing the
  'try_', 'is_', 'has_' prefixes and cutting off anything behind the first
  underscore. Eg. 'try_module_check' results in 'module'. This is then searched as
  'Bar.d/module', 'bar.d/module', '.Bar.d/module' or '.bar.d/module' (or respective please
  variants) and loaded if present. Thus modules that are automatically loaded must be named by
  single word without underscores.


STANDARD RULES

  Bar ships with a module that defines a set of standard rules where other modules can add
  clauses to. Check 'Bar.d/std_rules' for details.

  'SETUP', 'PREPROCESS', 'MAIN', 'POSTPROCESS' and 'CLEANUP' are special rule names called
  approbiately.

  The 'clause_local [var[=value]]' is for defining variables that are local to a clause.  Only
  scalars can be clause local. Ideally this should be used as dependency and setting a a
  variable to a value. It can be used in a function as well esp when creating other metarules.


MAIN API

$(help_describe_files "$BAR_SELF")


DOCUMENTATION WRITING GUIDELINES

  Bar uses a structured documentation format that serves both human readers and automated
  tools like help generation and bash completion. Documentation uses '##' comment markers.

  File-Level Documentation:

    Use '###' at the start of a file to describe the module/file:

     ### This module provides cargo/rust support.

  Variable Documentation:

    Variables declared with 'declare' can be documented on the same line:

     declare -g MYVAR="value" ## Description of the variable

  Function Documentation:

    Functions should have documentation in the form:

     function name ## [--opt] <required> [optional..] - Short description

    The parameter list uses a formal syntax:
    - <param>    - Mandatory parameter (prototype)
    - [param]    - Optional parameter (prototype)
    - <param..>  - One or more occurrences (suffix .. after closing >)
    - <param>..  - One or more occurrences (suffix .. after closing >)
    - [param..]  - Zero or more occurrences (suffix .. after closing ])
    - [param]..  - Zero or more occurrences (suffix .. after closing ])
    - <> and []  - Can be nested
    - word       - Anything not in <> or [] is a literal (like 'as', 'into', ':')
    - --flag     - Literal flag (can be in <--flag> for prototype completion)
    - -f         - Literal short flag
    - a|b        - Alternatives where a and b can be any of the above
                   (a|b|c|d etc. any number allowed)
                   Note: <a..|b> is at least one 'a' or a single 'b'
                         <a|b>.. is at least one of 'a' or 'b'
    - param      - Parameter names serve as prototypes for completion

    Examples:

    - function rename ## <this> as|into <that> - rename this as/into that
      Requires literal 'as' or 'into' at the 2nd position.
    - function process ## <input:> <output> - process input to output
      The colon ':' after <input> is a literal character.

    Parameter identifiers start with an alphabetic character followed by [[:alnum:]-_].
    These serve as prototypes for completion and are refined in following documentation.

    Multi-line documentation continues on following lines starting with '##':

     function foo ## [--verbose|-v] <input> [output] - Process files
     {
         ## [--verbose|-v] - Enable verbose output
         ## <input>         - Input file to process
         ## [output]        - Optional output file (defaults to stdout)
         ...
     }

  Rule Documentation:

    Rules are documented with '##' lines before the rule definition:

     ## <target> - Build the specified target
     rule build:

    For rules with parameters, use the same formal syntax as functions:

     ## [--toolchain] <target> [options..] - Build target
     rule build:

  Documentation Prototypes for Completion:

    Parameter identifiers map to completion functions. Common prototypes include:

    - <file>      - Any file on filesystem
    - <directory> - Any directory
    - <path>      - Any valid path
    - <text>      - Any text input
    - <number>    - Numeric input
    - <rule>      - Existing rule name
    - <command>   - Command or function name

    Module-specific prototypes can be defined (e.g., <toolchain> in cargo module).
    See contrib/bar_complete for completion implementation details.
    
  Defining Custom Completion Prototypes:

    Modules can define custom prototypes for parameter completion using single-hash comments
    that must start at column 0 (no leading whitespace):
    
      # prototype: "mytype" = "file"
      # prototype: "myfile" = "file existing local"
      # prototype: "mycommand" = "command"
      # prototype: "toolchain" = "extcomp cargo"
      # prototype: "gitargs" = "extcomp git"
    
    These definitions register a prototype with a completer. The format is:

      # prototype: "prototype_name" = "completer_spec"
    
    Where completer_spec is either:
    - A built-in completer name (file, directory, path, rule, command, etc.)
    - A completer with predicates (e.g., "file existing local")
    - "ext function_name" for external/custom completers (calls bar --bare function_name)
    - "extcomp command" for black-box external command completion (invokes command's native bash completion)
    
    The "extcomp" type enables leveraging any command's existing bash completion by invoking
    it as a black box. For example, "extcomp git" will use git's native completion for all
    git subcommands and flags. This works with git, cargo, ssh, and any other command that
    has bash completion support.
    
    Note: The '# prototype:' comment must start at the beginning of the line (column 0).
    
    These are registered as "module@prototype" in the completion registry, allowing
    module-specific completion behavior while maintaining fallback to global prototypes.


BASH COMPLETION

  Bar supports bash completion for rulefiles, rules, functions, and their arguments. Completion
  is automatically installed when you run 'bar init_install'.

  The completion script is installed to '~/.bash_completion/bar_complete'. To enable it,
  either source it in your .bashrc:

   source ~/.bash_completion/bar_complete

  Or if you have bash-completion package installed, it should be automatically loaded.

  Completion works for:

  - bar <TAB>       - completes rulefiles, rules, and functions in current directory
  - please <TAB>    - completes rulefiles, rules, and functions
  - ./bar <TAB>     - completes rulefiles, rules, and functions from local bar

  The completion logic will:

  1.  Find any user rule files in current directory (files containing 'function' or 'rule',
      or with shebang pointing to bar/please)
  2.  Complete available bash functions and rules from default rule file and Bar.d/ modules
  3.  Provide context-aware argument completion based on parameter types


LICENSE

    bar -- BAsh Rulez
    Copyright (C) 2025  Christian Thäter <ct.bar@pipapo.org>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
EOF
  fi

  if [[ -z "$span" ]]; then
    printf '%s\n' "${help_render_cache[@]}"
    return
  fi

  if [[ "$span" =~ ^([0-9]+)-([0-9]+)$ ]]; then
    local start="${BASH_REMATCH[1]}"
    local end="${BASH_REMATCH[2]}"
    local i
    for ((i=start; i<=end; i++)); do
      printf '%s\n' "${help_render_cache[i-1]}"
    done
    return
  fi

  printf '%s\n' "${help_render_cache[@]}"
}


function help_indexer
{
  help_render | awk '
    function trim(str) {
      gsub(/^[ \t]+|[ \t]+$/, "", str)
      return str
    }

    function record_result(start, end, proto, value,    idx) {
      if (end < start) {
        end = start
      }
      idx = ++result_count
      result_start[idx] = start
      result_end[idx] = end
      result_proto[idx] = proto
      result_value[idx] = value
    }

    function close_sections(new_indent,    end_line) {
      while (stack_size > 0 && stack_indent[stack_size] >= new_indent) {
        end_line = stack_last_content[stack_size]
        if (end_line == 0) {
          end_line = stack_start[stack_size]
        }
        record_result(stack_start[stack_size], end_line, stack_proto[stack_size], stack_value[stack_size])
        stack_size--
      }
    }

    function push_section(proto, value, indent) {
      stack_size++
      stack_indent[stack_size] = indent
      stack_proto[stack_size] = proto
      stack_value[stack_size] = value
      stack_start[stack_size] = NR
      stack_last_content[stack_size] = NR
    }

    function touch_sections() {
      for (i = 1; i <= stack_size; i++) {
        stack_last_content[i] = NR
      }
    }

    function find_span_end(start, start_indent,    j, end_line) {
      end_line = start
      for (j = start + 1; j <= NR; j++) {
        if (line_has_text[j] == 0) {
          continue
        }
        if (indentation[j] <= start_indent) {
          break
        }
        end_line = j
      }
      return end_line
    }

    BEGIN {
      code_indent = 0
      stack_size = 0
      result_count = 0
    }

    {
      line = $0
      indent = 0
      if (match(line, /^ +/)) {
        indent = RLENGTH
      }

      trimmed = trim(line)
      has_text = (trimmed != "") ? 1 : 0

      if (code_indent > 0) {
        if (trimmed != "" && indent < code_indent) {
          code_indent = 0
        } else {
          trimmed_lines[NR] = ""
          blank[NR] = 1
          indentation[NR] = indent
          line_has_text[NR] = has_text
          if (has_text) {
            close_sections(indent)
            touch_sections()
          }
          next
        }
      }

      if (trimmed != "" && (indent % 2) == 1) {
        code_indent = indent
        trimmed_lines[NR] = ""
        blank[NR] = 1
        indentation[NR] = indent
        line_has_text[NR] = has_text
        if (has_text) {
          close_sections(indent)
          touch_sections()
        }
        next
      }

      trimmed_lines[NR] = trimmed
      blank[NR] = (trimmed == "") ? 1 : 0
      indentation[NR] = indent
      line_has_text[NR] = has_text

      if (has_text) {
        close_sections(indent)
      }

      if (line ~ /^    Functions:/) {
        section = "function"
        if (has_text) {
          touch_sections()
        }
        next
      }
      if (line ~ /^    Rules:/) {
        section = "rule"
        if (has_text) {
          touch_sections()
        }
        next
      }
      if (line ~ /^    Variables:/) {
        section = "variable"
        if (has_text) {
          touch_sections()
        }
        next
      }

      if (section != "" && line ~ /^      [^[:space:]]/) {
        name = trimmed
        split(name, parts, /[[:space:]]+/)
        name = parts[1]
        sub(/:$/, "", name)
        push_section(section, name, indent)
      }

      if (has_text && line !~ /^      / && line !~ /^        / && line !~ /^    (Functions|Rules|Variables):/) {
        section = ""
      }

      if (has_text) {
        touch_sections()
      }
    }

    END {
      close_sections(-1)
      for (i = 1; i <= NR; i++) {
        candidate = trimmed_lines[i]
        if (candidate == "") {
          continue
        }
        if (candidate ~ /^[[:punct:]]/ || candidate ~ /[[:punct:]]$/) {
          continue
        }
        if (candidate ~ / - /) {
          continue
        }
        prev_blank = (i == 1) ? 1 : blank[i - 1]
        next_blank = (i == NR) ? 0 : blank[i + 1]
        if (prev_blank && next_blank) {
          span_end = find_span_end(i, indentation[i])
          record_result(i, span_end, "topic", candidate)
        }
      }

      for (i = 1; i <= result_count; i++) {
        printf "%d-%d:%s:%s\n", result_start[i], result_end[i], result_proto[i], result_value[i]
      }
    }
  '
}


function help_describe_files
{
    local file
    for file in "$@"; do
        if help_describe_file "$file"; then
            help_describe_variables "$file"
            help_describe_functions "$file"
            help_describe_rules "$file"
        else
            warn "$file has no top level doc"
        fi
    done
}


function help_describe_file
{
    awk '
        function printout(text) {
            out = out text "\n"
        }

        /^###/ {
            line = $0
            sub(/^###[ ]?/, "", line)
            printout(indent line)
            indent = "    "
            next
        }

        END {
            name = FILENAME
            gsub(/^.*\//, "", name)
            if (out != "") {
                print "  " name " - " out
            } else {
                exit 1
            }
        }
    ' "$1"
}

function help_describe_functions
{
    awk '
        function printout(text) {
            out = out text "\n"
        }

    /^function[ \t]+[A-Za-z_][A-Za-z0-9_]*[ \t]*##/ {
            split($0, parts, "##")
            if (length(parts) < 2) {
                next
            }

            namepart = parts[1]
      sub(/^function[ \t]+/, "", namepart)
            sub(/[ \t].*$/, "", namepart)

            infopart = parts[2]
            sub(/^[ \t]+/, "", infopart)

            proto = infopart
            desc = ""
            split(infopart, proto_desc, " - ")
            if (length(proto_desc) >= 2) {
                proto = proto_desc[1]
                desc = substr(infopart, length(proto) + 4)
            }

            if (proto == infopart) {
                desc = ""
            }

            printout()
            if (proto != "") {
                printout("      " namepart " " proto)
            } else {
                printout("      " namepart)
            }
      if (desc != "") {
                printout("        " desc)
            }
            next
        }

        /^([ \t][ \t])+##[^#].*/ {
            line = $0
            sub(/^.*##[ ]?/, "", line)
            printout("        " line)
            next
        }

        END {
            if (out != "") {
                print "    Functions:"
                print out
            }
        }
    ' "$1"
}

function help_describe_rules
{
    awk '
        function printout(text) {
            out = out text "\n"
        }

    function trim(text) {
      sub(/^[ \t]+/, "", text)
      sub(/[ \t]+$/, "", text)
      return text
    }

    function reset_docs(    idx) {
      doc_count = 0
      for (idx in doc_lines) {
        delete doc_lines[idx]
      }
    }

    BEGIN {
      doc_count = 0
    }

    /^rule([ \t].*)?/ {
      if (doc_count > 0) {
        line = $0
        sub(/^.*rule[ \t]+/, "", line)
        while (line ~ /^--[A-Za-z_-]+[ \t]+/) {
          sub(/^--[A-Za-z_-]+[ \t]+/, "", line)
        }
        rule_name = line
        sub(/[ \t].*$/, "", rule_name)
        sub(/:$/, "", rule_name)

        first = trim(doc_lines[1])
        proto_line = ""
        summary = ""
        split_pos = index(first, " - ")
        if (split_pos > 0) {
          proto_line = trim(substr(first, 1, split_pos - 1))
          summary = trim(substr(first, split_pos + 3))
        } else {
          summary = first
        }

        printout("")
        if (proto_line != "") {
          printout("      " rule_name " " proto_line)
        } else {
          printout("      " rule_name)
        }
        if (summary != "") {
          printout("        " summary)
        }

        if (doc_count > 1) {
          for (i = 2; i <= doc_count; i++) {
            extra = trim(doc_lines[i])
            if (extra != "") {
              printout("        " extra)
            }
          }
        }
      }

      reset_docs()
      next
    }

    /^##[^.]/ {
      line = $0
      sub(/^##[ \t]*/, "", line)
      doc_count++
      doc_lines[doc_count] = line
      next
    }

    {
      reset_docs()
      next
    }

    END {
      if (out != "") {
        print "    Rules:"
        print out
      }
    }
  ' "$1"
}



function help_describe_variables
{
    awk '
        function printout(text) {
            out = out text "\n"
        }

    /declare[ \t]+.*##/ {
      before = $0
      sub(/[ \t]*##.*/, "", before)
      desc = $0
      sub(/^.*##[ ]?/, "", desc)

      rest = before
      sub(/^declare[ \t]+/, "", rest)

      flags = ""
      if (rest ~ /^-[A-Za-zA-Z]+/) {
        flags = rest
        sub(/[ \t].*$/, "", flags)
        sub(/^-/, "", flags)
        sub(/^[^ \t]+[ \t]*/, "", rest)
      }

      varname = rest
      sub(/[ \t=].*$/, "", varname)

      if (varname == "") {
        next
      }

      value = rest
      if (value ~ /=/) {
        equals = index(value, "=")
        value = substr(value, equals + 1)
        sub(/^[ \t]*"?/, "", value)
        sub(/"?[ \t]*$/, "", value)
      } else {
        value = ""
      }

      line = "      " varname
      if (flags != "") {
        line = line " (" flags ")"
      }

      printout("")
      printout(line)
      printout("        " desc)
      if (value != "") {
        printout("        Default: " value)
      }
      next
    }

        END {
            if (out != "") {
                print "    Variables:"
                print out
            }
        }
    ' "$1"
}

# Define --bare rule for help (reads existing module files)
## [[-s|--short] topic|rule|function|variable|text] - Show help topics
##   - [-s|--short]:                 Show only the queried sections
##   - topic|rule|function|variable: Navigate to or show only specified topics
##   - text:                         Search the specified text in the documentation
rule --bare help:

# Provide indexer via bare rule for external consumers like completion
rule --bare help_indexer: