-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathaudit_inception_commit-POC.sh
More file actions
executable file
·2899 lines (2597 loc) · 115 KB
/
audit_inception_commit-POC.sh
File metadata and controls
executable file
·2899 lines (2597 loc) · 115 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
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
#!/usr/bin/env zsh
########################################################################
## SCRIPT INFO
########################################################################
## audit_inception_commit-POC.sh
## - Open Integrity Audit of a Git Repository Inception Commit
##
## VERSION: 0.1.05 (2025-03-04)
##
## DESCRIPTION:
## This script performs a multi-part review of a Git repository's inception
## commit, auditing compliance with Open Integrity specifications across
## multiple Progressive Trust phases:
## - Wholeness: Assessing structural integrity and format
## - Proofs: Cryptographic SSH signature authentication
## - References: Affirming committer identity via references
## - Requirements: Auditing Open Integrity and GitHub community standards
##
## The script is a part of a Proof-of-Concept (POC) for using
## Git repositories as cryptographic roots of trust, leveraging empty,
## SSH-signed inception commits for a secure identifier that can
## be independently authenticated across distributed platforms.
##
## DESIGN PHILOSOPHY:
## - Progressive Trust Implementation - Follows a phased approach to building
## trust in cryptographic identities.
## - Separation of Concerns - Clear distinction between framework utilities,
## domain-specific functions, and controller logic.
## - Non-Destructive Operation - All operations are read-only; the script never
## modifies repositories or Git configuration.
## - Two-Phase Argument Processing - Framework arguments are processed before
## domain-specific ones for consistent behavior.
## - Layered Architecture - Organized in foundation, utility, domain,
## orchestration, and controller layers.
##
## FEATURES:
## - Local Inception Commit Auditing:
## * Empty commit validation for SHA-1 collision resistance
## * Commit message format verification
## * Repository structure assessment
## - Cryptographic Verification:
## * SSH signature validation with proper Git configuration
## * Support for both global and local allowed signers files
## * Key fingerprint and committer identity correlation
## - Progressive Trust Implementation:
## * Phase 2 (Wholeness): Structural integrity assessment
## * Phase 3 (Proofs): Cryptographic signature verification
## * Phase 4 (References): Identity authentication and linking
## * Phase 5 (Requirements): GitHub standards compliance
## - Flexible Execution Modes:
## * Interactive and non-interactive operation
## * Configurable verbosity (standard, verbose, debug)
## * Color support with terminal capability detection
## * Compatible with CI/CD environments
##
## For more on the progressive trust life cycle, see:
## https://developer.blockchaincommons.com/progressive-trust/
##
## LIMITATIONS:
## - Currently only supports testing the inception commit of a local Git repository
## - Script must be executed within or near the repository being audited
## - GitHub standards compliance checks are very basic
##
## SECURITY CONSIDERATIONS:
## - SHA-1 used in Git commit identifiers has known cryptographic weaknesses
## - SSH keys should be protected with appropriate permissions (600)
## - Verification only confirms the inception commit is properly signed
## - Trust models assume proper management of allowed_signers files
## - This script performs read-only operations and never modifies repositories
## - The script does not store or transmit any cryptographic keys
##
## USAGE: audit_inception_commit-POC.sh [options]
##
## OPTIONS:
## -C, --chdir <path> Change to specified directory before execution
## -v, --verbose Enable detailed output
## -q, --quiet Suppress non-critical output
## -d, --debug Show debugging information
## -p, --no-prompt Run non-interactively
## -i, --interactive Force interactive prompts
## -n, --no-color Disable colored output
## -c, --color Force colored output
## -h, --help Show this help message
##
## EXAMPLES:
## # Basic audit of current directory repository:
## audit_inception_commit-POC.sh
##
## # Audit a specific repository with detailed output:
## audit_inception_commit-POC.sh -C /path/to/repo --verbose
##
## # Non-interactive audit for CI/CD pipelines:
## audit_inception_commit-POC.sh --no-prompt --quiet -C /path/to/repo
##
## # Debugging output with all details:
## audit_inception_commit-POC.sh -C /path/to/repo --verbose --debug
##
## REQUIREMENTS:
## - Zsh 5.8 or later
## - Git 2.34 or later (required for SSH signing support)
## - GitHub CLI (gh) 2.65.0 or later, authenticated with GitHub (optional)
## - OpenSSH 8.2+ for signature verification
##
## INTEGRATION:
## This script can be integrated into CI/CD pipelines, pre-commit hooks,
## or used as a standalone verification tool. It returns standard exit
## codes that can be used for automated decision making:
## 0 - Local verification phases (1-3) passed successfully, even if
## remote phases (4-5) have warnings
## 1 - General failure or local verification failure
## 2 - Invalid usage or arguments
## 5 - Git repository error (not a repo, commit issues)
## 6 - Configuration error
## 127 - Missing dependency
##
## Note that only failures in local verification phases (1-3) will produce
## non-zero exit codes. Issues with remote verification phases (4-5) are
## reported as warnings but don't affect the exit code.
##
## LICENSE:
## (c) 2025 By Blockchain Commons LLC
## https://www.BlockchainCommons.com
## Licensed under BSD-2-Clause Plus Patent License
## https://spdx.org/licenses/BSD-2-Clause-Patent.html
##
## PORTIONS:
## z_Output function:
## Z_Utils - ZSH Utility Scripts
## - <https://github.com/ChristopherA/Z_Utils>
## - <did:repo:e649e2061b945848e53ff369485b8dd182747991>
## (c) 2025 Christopher Allen
## Licensed under BSD-2-Clause Plus Patent License
##
## PART OF:
## Open Integrity Project of Blockchain Commons LLC.
## - Open Integrity Core
## - <https://github.com/OpenIntegrityProject/core>
## - <did:repo:69c8659959f1a6aa281bdc1b8653b381e741b3f6>
########################################################################
########################################################################
## CHANGE LOG
########################################################################
## 0.1.05 - Fixed Exit Code Behavior (2025-03-04)
## - Implemented the architectural decision for exit codes:
## * Non-zero exit codes now only returned for issues in phases 1-3
## * Issues in phases 4-5 reported as warnings without affecting exit code
## * Success (exit code 0) now returned for repositories that pass
## local verification even if GitHub integration is unavailable
## - Updated comments and documentation to reflect new behavior:
## * Added tracking of phase numbers in Trust_Assessment_Status
## * Improved error reporting with phase information
## - Fixed exit code inconsistency by using explicit exit statements
## - Improved output with clear warnings for non-critical issues
## - Updated regression tests to match new exit code behavior
##
## 0.1.04 - GitHub Integration Test Fix (2025-03-04)
## - Fixed GitHub integration testing issues:
## * Updated test script to expect exit code 1 for GitHub repositories
## * Ensured oi_Comply_With_GitHub_Standards returns Exit_Status_Success
## for non-critical failures
## * Added comprehensive documentation about exit code behavior
## - Updated issue documentation:
## * Added new issue for GitHub Integration Test Failures (resolved)
## * Updated Inconsistent Exit Code Behavior issue (partially resolved)
## * Documented architectural decision still needed for exit codes
##
## 0.1.03 - Major Architecture Update (2025-03-01)
## - Implemented two-phase argument processing
## * Added z_Parse_Initial_Arguments for framework arguments
## * Added parse_Remaining_Arguments for domain arguments
## * Added dedicated handler functions for complex parameters
## - Reorganized functions into architectural layers:
## * Foundation Layer: Error handling, environment setup
## * Utility Layer: z_Utils functions
## * Domain Layer: oi_Utils functions
## * Orchestration Layer: Audit execution functions
## * Controller Layer: main and core_Logic functions
## - Clarified controller function responsibilities
## * Refined main() to focus on initialization and orchestration
## * Refactored core_Logic() for workflow sequencing
## * Created execute_Audit_Phases() for phase management
## - Enhanced documentation
## * Standardized all function documentation blocks
## * Improved section headers with architectural context
## * Added security considerations section
## * Extended script header with design philosophy
## - Reordered functions by strict dependency relationships
## - Refactored longer functions for better maintainability
##
## 0.1.02 - Updated version (2025-02-28)
## - Enhanced function naming consistency
## - Improved script structure and organization
## - Added repository DID output in default mode
## - Improved error handling with centralized reporting
## - Enhanced function documentation
## - Added detailed comments for complex logic
## - Added condensed trust assessment results for default mode
##
## 0.1.01 - Updated version (2025-02-28)
## - Enhanced security documentation and considerations
## - Improved function documentation for clarity and completeness
## - Enhanced error messaging with actionable guidance
## - Improved Zsh feature utilization
## - Added more detailed verification status tracking
## - Improved compliance with Zsh scripting best practices:
## * Standardized function documentation blocks
## * Enhanced error handling and exit code usage
## * Improved variable naming and scoping
##
## 0.1.00 - Initial Release (2025-02-27)
## - Core audit functionality for inception commits
## - Support for Progressive Trust phases 2-5:
## * Phase 2: Wholeness (structural integrity, format)
## * Phase 3: Proofs (cryptographic signatures)
## * Phase 4: References (identity authentication)
## * Phase 5: GitHub community standards
## - Interactive and non-interactive operation modes
## - Colored output with configurable options
## - Comprehensive help and usage information
## - Verbose and debug output modes
## - Initial support for GitHub standards compliance
## - Basic error handling and reporting
## - Script must currently be run from within repository
########################################################################
########################################################################
## SECTION: Foundation Layer - Environment Configuration
##--------------------------------------------------------------------##
## Description:
## This foundational layer configures the Zsh environment to ensure
## robust error handling and predictable execution behavior. It
## establishes the script's operational context through initialization
## of essential constants, variables, and execution flags.
##
## Architectural Role:
## As the first layer in the script's architecture, the Foundation Layer
## creates the secure, consistent base upon which all other layers depend.
## It ensures predictable behavior across different systems and shell
## configurations by explicitly setting shell options and initializing
## the script's state.
##
## Design Philosophy:
## - Explicit Environment Control: Reset and configure the shell environment
## to ensure consistent behavior regardless of user shell settings.
## - Safe Defaults: Enable strict error handling to prevent silent failures.
## - Clear State Management: Initialize all script-scoped variables with
## explicit typing and readability.
## - Terminal Adaptation: Detect and configure color capabilities based on
## the execution environment.
##
## Content:
## - Shell Environment Reset: Standardize Zsh environment
## - Safe Shell Options: Enforce strict error handling
## - Boolean Constants: Define TRUE/FALSE values
## - Exit Status Constants: Define standardized return codes
## - Execution Flags: Control script behavior modes
## - Script Information: Track execution context
## - Audit-Specific Variables: Track verification state
## - Terminal Configuration: Adapt to display capabilities
##
## Dependencies:
## - Requires Zsh 5.8+ with support for advanced parameter handling
## - May use tput for terminal capability detection (if available)
##
## Notes:
## - This section contains initialization code only, no functions
## - Variables are declared with appropriate typing (integer, array, etc.)
## - Constants are properly declared as readonly (-r) to prevent modification
########################################################################
# Reset the shell environment to a default Zsh state for predictability
emulate -LR zsh
# Setting safe options for robust error handling:
setopt errexit # Exit the script when a command fails
setopt nounset # Treat unset variables as an error
setopt pipefail # Return the exit status of the last command that failed in a pipeline
setopt noclobber # Prevents accidental overwriting of files
setopt localoptions # Ensures script options remain local
setopt warncreateglobal # Warns if a global variable is created by mistake
setopt no_nomatch # Prevents errors when a glob pattern does not match
setopt no_list_ambiguous # Disables ambiguous globbing behavior
# Script constants
typeset -r Script_Name=$(basename "$0")
typeset -r Script_Version="0.1.05"
#----------------------------------------------------------------------#
# Script-Scoped Variables - Boolean Constants
#----------------------------------------------------------------------#
# - `TRUE` and `FALSE` are integer constants representing boolean values.
# - Declared as readonly to ensure immutability
#----------------------------------------------------------------------#
typeset -r -i TRUE=1 # Represents the "true" state or enabled mode
typeset -r -i FALSE=0 # Represents the "false" state or disabled mode
#----------------------------------------------------------------------#
# Script-Scoped Variables - Exit Status Codes
#----------------------------------------------------------------------#
# - Standard exit codes for script return values
# - All status codes are read-only integers
#----------------------------------------------------------------------#
typeset -r -i Exit_Status_Success=0 # Successful execution
typeset -r -i Exit_Status_General=1 # General error (unspecified)
typeset -r -i Exit_Status_Usage=2 # Invalid usage or arguments
typeset -r -i Exit_Status_IO=3 # Input/output error
typeset -r -i Exit_Status_Git_Failure=5 # Git operation failed
typeset -r -i Exit_Status_Config=6 # Configuration error
typeset -r -i Exit_Status_Dependency=127 # Missing dependency
#----------------------------------------------------------------------#
# Script-Scoped Variables - Execution Flags
#----------------------------------------------------------------------#
# - Script-scoped flags controlling various modes and behaviors
# - Declared as integers using `typeset -i` to ensure type safety
#----------------------------------------------------------------------#
typeset -i Script_Running=$FALSE # Prevents recursive execution
typeset -i Output_Verbose_Mode=$FALSE # Verbose mode
typeset -i Output_Quiet_Mode=$FALSE # Quiet mode
typeset -i Output_Debug_Mode=$FALSE # Debug mode
typeset -i Output_Color_Enabled=$TRUE # Color output
typeset -i Output_Prompt_Enabled=$TRUE # Interactive prompting
#----------------------------------------------------------------------#
# Script-Scoped Variables - Script Information
#----------------------------------------------------------------------#
# - Script name, path, and other context information
# - All path-related constants are readonly
#----------------------------------------------------------------------#
typeset -r Script_FileName="${0##*/}" # Script base name
typeset -r Script_BaseName=${${0:A:t}%.*} # Name without extension
typeset -r Script_FileExt=${0##*.} # File extension
typeset -r Script_RealFilePath=$(realpath "${0:A}") # Absolute path
typeset -r Script_RealDirName=$(basename "$(realpath "${0:A:h}")") # Directory name
typeset -r Script_RealDirPath=$(realpath "${0:A:h}") # Directory path
typeset -r Script_RealParentDir=$(realpath "${0:A:h:h}") # Parent directory
#----------------------------------------------------------------------#
# Script-Scoped Variables - Command-Line Arguments
#----------------------------------------------------------------------#
# - Storage for original command-line arguments
# - Allows reference to original input throughout execution
#----------------------------------------------------------------------#
typeset -a Cmd_Args=("$@") # All arguments
typeset -r Cmd_Args_Count="${#Cmd_Args[@]}" # Argument count
typeset -a Cmd_Positional_Args=("${(@)Cmd_Args:#--*}") # Non-flag arguments
typeset -A Cmd_Parsed_Flags # Parsed flag storage
typeset Cmd_Args_String="${*}" # Original args string
typeset -r Cmd_Invocation_Path=$(realpath "$0") # Invocation path
typeset Working_Directory # Working directory from -C/--chdir
#----------------------------------------------------------------------#
# Script-Scoped Variables - Environment Detection
#----------------------------------------------------------------------#
# - Environment variables used for detecting terminal capabilities
# and script execution context
# - These can be overridden by command line flags
#----------------------------------------------------------------------#
typeset Script_No_Color="${NO_COLOR:-}" # Industry standard for disabling color
typeset Script_Force_Color="${FORCE_COLOR:-}" # Build system standard for forcing color
typeset Script_CI="${CI:-}" # Continuous Integration environment flag
typeset Script_PS1="${PS1:-}" # Shell prompt - indicates interactive shell
typeset Script_Term="${TERM:-}" # Terminal type and capabilities
#----------------------------------------------------------------------#
# Terminal Color Configuration
#----------------------------------------------------------------------#
# Description:
# - Defines terminal colors and attributes for script output styling.
# - Includes basic colors, bright variations, and emphasis attributes.
# - Dynamically initialized based on terminal capabilities.
# - Read-only to ensure consistent and predictable usage.
#----------------------------------------------------------------------#
typeset -i Output_Has_Color=$FALSE
typeset -i Tput_Colors=0
# Safely retrieve the number of terminal colors
if command -v tput >/dev/null 2>&1; then
Tput_Colors=$(tput colors 2>/dev/null || echo 0) # Default to 0 if tput fails
if (( Tput_Colors >= 8 )); then
Output_Has_Color=$TRUE
elif ! (( Output_Quiet_Mode )); then
print "WARNING: Insufficient color support (${Tput_Colors} colors) - disabling color output."
fi
else
if ! (( Output_Quiet_Mode )); then
print "WARNING: 'tput' command not found - disabling color output."
fi
fi
# Initialize terminal color variables if supported and enabled
if (( Output_Has_Color && Output_Color_Enabled )); then
# Basic Colors
Term_Black=$(tput setaf 0)
Term_Red=$(tput setaf 1)
Term_Green=$(tput setaf 2)
Term_Yellow=$(tput setaf 3)
Term_Blue=$(tput setaf 4)
Term_Magenta=$(tput setaf 5)
Term_Cyan=$(tput setaf 6)
Term_White=$(tput setaf 7)
# Bright Colors
Term_BrightBlack=$(tput bold; tput setaf 0)
Term_BrightRed=$(tput bold; tput setaf 1)
Term_BrightGreen=$(tput bold; tput setaf 2)
Term_BrightYellow=$(tput bold; tput setaf 3)
Term_BrightBlue=$(tput bold; tput setaf 4)
Term_BrightMagenta=$(tput bold; tput setaf 5)
Term_BrightCyan=$(tput bold; tput setaf 6)
Term_BrightWhite=$(tput bold; tput setaf 7)
# Emphasis Attributes
Term_Bold=$(tput bold)
Term_Underline=$(tput smul)
Term_NoUnderline=$(tput rmul)
Term_Standout=$(tput smso)
Term_NoStandout=$(tput rmso)
Term_Blink=$(tput blink)
Term_Dim=$(tput dim)
Term_Reverse=$(tput rev)
Term_Invisible=$(tput invis)
# Reset Attributes
Term_Reset=$(tput sgr0)
else
# Fallback to empty strings if color is unsupported or disabled
Term_Black="" Term_Red="" Term_Green=""
Term_Yellow="" Term_Blue="" Term_Magenta=""
Term_Cyan="" Term_White=""
Term_BrightBlack="" Term_BrightRed="" Term_BrightGreen=""
Term_BrightYellow="" Term_BrightBlue="" Term_BrightMagenta=""
Term_BrightCyan="" Term_BrightWhite=""
Term_Bold="" Term_Underline="" Term_NoUnderline=""
Term_Standout="" Term_NoStandout="" Term_Blink=""
Term_Dim="" Term_Reverse="" Term_Invisible=""
Term_Reset=""
fi
# Make all terminal color and attribute variables readonly
typeset -r Term_Black Term_Red Term_Green \
Term_Yellow Term_Blue Term_Magenta \
Term_Cyan Term_White Term_BrightBlack \
Term_BrightRed Term_BrightGreen Term_BrightYellow \
Term_BrightBlue Term_BrightMagenta Term_BrightCyan \
Term_BrightWhite Term_Bold Term_Underline \
Term_NoUnderline Term_Standout Term_NoStandout \
Term_Blink Term_Dim Term_Reverse \
Term_Invisible Term_Reset
#----------------------------------------------------------------------#
# Script-Scoped Variables - Audit Specific Variables
#----------------------------------------------------------------------#
# - Variables specifically for tracking audit state and results
# - Used throughout the script for storing commit information
#----------------------------------------------------------------------#
typeset Inception_Commit_Repo_Id # Stores inception commit SHA-1
typeset Repo_DID # Stores the repository DID
# Associative array for tracking assessment status
typeset -A Trust_Assessment_Status
# Initialize with all assessments set to FALSE and their phase numbers
Trust_Assessment_Status=(
# Assessment results
"structure" $FALSE
"content" $FALSE
"format" $FALSE
"signature" $FALSE
"identity" $FALSE
"standards" $FALSE
# Phase numbers for each assessment (for exit code determination)
"structure_phase" 2 # Wholeness - local
"content_phase" 2 # Wholeness - local
"format_phase" 2 # Wholeness - local
"signature_phase" 3 # Cryptographic Proofs - local
"identity_phase" 4 # Trust References - remote
"standards_phase" 5 # Community Standards - remote
)
########################################################################
## SECTION: Utility Layer - z_Utils Functions
##--------------------------------------------------------------------##
## Description:
## This layer contains reusable Zsh utility functions (z_Utils) that
## provide general-purpose functionality for script infrastructure,
## environment management, error handling, and output formatting.
## These functions establish core capabilities needed by higher layers
## but are not specific to Open Integrity auditing processes.
##
## Architectural Role:
## The Utility Layer sits between the Foundation Layer and domain-specific
## layers, providing standardized services and abstractions that
## higher-level functions can rely on. These utilities encapsulate
## common tasks to reduce code duplication and maintain consistency
## throughout the script.
##
## Design Philosophy:
## - Reusability: Functions designed to be used across multiple scripts
## - Abstraction: Hide implementation details behind clean interfaces
## - Consistency: Provide uniform behavior for common operations
## - Robustness: Include comprehensive error handling
##
## Functions (in dependency order):
## - z_Output: Advanced formatted output with multiple message types
## - z_Report_Error: Centralized error reporting
## - z_Convert_Path_To_Relative: Converts absolute paths to relative
## - z_Check_Requirements: Verifies required tools and capabilities
## - z_Setup_Environment: Initializes script environment
## - z_Cleanup: Performs cleanup when script exits
##
## Naming Convention:
## - All functions are prefixed with "z_" indicating general Zsh utilities
## - Function names follow verb_Object pattern
## - First word lowercase, subsequent words capitalized
##
## Dependencies:
## - Foundation Layer environment variables and constants
## - Some functions may require external commands (tput, command)
##
## Note:
## This section implements general-purpose utilities that can be
## reused across multiple scripts in the z_Utils library. The code is
## maintained separately and imported into this script.
##
## Source:
## Z_Utils - ZSH Utility Scripts
## - <https://github.com/ChristopherA/Z_Utils>
## - <did:repo:e649e2061b945848e53ff369485b8dd182747991>
## (c) 2025 Christopher Allen
## Licensed under BSD-2-Clause Plus Patent License
########################################################################
#----------------------------------------------------------------------#
# Function: z_Output
#----------------------------------------------------------------------#
# Description:
# A utility function for formatted output in Zsh scripts. Supports
# multiple message types, text formatting, emoji, indentation,
# verbosity levels, and interactive prompts.
#
# Version: 1.0.00 (2025-02-27)
#
# Parameters:
# $1 - Message type (string): Determines message behavior and visibility
# Values: print, info, verbose, success, warn, error, debug,
# vdebug, prompt
# Remaining parameters - Either message text or Key=Value options
#
# Options (Key=Value):
# - Color="<ANSI Code>" - Override default message color
# - Emoji="🔹" - Set a custom emoji (default varies by type)
# - Wrap=<int> - Maximum line width (default: terminal width)
# - Indent=<int> - Left indentation (enables wrapping)
# - Force=1 - Overrides quiet mode for all message types
# - Default="value" - Pre-set response for non-interactive prompts
#
# Returns:
# 0 for standard messages
# 1 for errors
# 2 for invalid message types
#
# Required Script Variables:
# - TRUE/FALSE - Boolean constants (1/0)
# - Output_Verbose_Mode - Enables `verbose` messages
# - Output_Quiet_Mode - Suppresses non-critical messages
# - Output_Debug_Mode - Enables `debug` messages
# - Output_Prompt_Enabled - Controls interactive prompting
# - Various Term_* color variables
#
# Side Effects:
# - Outputs formatted text to stdout
# - May prompt for user input when type is "prompt"
#
# Dependencies:
# - tput for color support and terminal detection
#
# Usage Examples:
# z_Output print "Standard output message"
# z_Output verbose "Details shown only in verbose mode"
# z_Output error "Error message always shown"
# z_Output debug "Debugging information"
# z_Output prompt "Enter value:" Default="default"
# z_Output info Indent=2 "Indented informational message"
# z_Output warn Force=1 "Warning that shows even in quiet mode"
#----------------------------------------------------------------------#
function z_Output {
# Required first parameter is message type with error on missing
# ${1:?msg} is shared between zsh/bash but behavior differs on missing parameter
typeset MessageType="${1:?Missing message type}"
shift
# Zsh arrays are 1-based and require explicit declaration of pattern matching arrays
# match/mbegin/mend are special zsh arrays used for regex capture groups
typeset -a match mbegin mend
typeset -a MessageParts
# -A creates associative array (like bash -A but with different scoping rules)
typeset -A OptionsMap
# In zsh, typeset creates local variables with explicit typing
# Unlike bash where local/declare are interchangeable
typeset MessageText IndentText WrapIndentText PrefixText
typeset LineText WordText CurrentLine OutputText
typeset KeyName Value
# Zsh associative arrays persist declaration order unlike bash
typeset -A ColorMap EmojiMap SuppressionMap
ColorMap=(
"print" "$Term_Reset"
"info" "$Term_Cyan"
"verbose" "$Term_Yellow"
"success" "$Term_Green"
"warn" "$Term_Magenta"
"error" "$Term_Red"
"debug" "$Term_Blue"
"vdebug" "$Term_Blue"
"prompt" "$Term_Standout"
"reset" "$Term_Reset"
)
EmojiMap=(
"print" ""
"info" "💡"
"verbose" "📘"
"success" "✅"
"warn" "⚠️"
"error" "❌"
"debug" "🛠️"
"vdebug" "🔍"
"prompt" "❓"
)
SuppressionMap=(
"print" 1
"info" 1
"verbose" 1
"success" 1
"warn" 1
"error" 0
"debug" 1
"vdebug" 1
"prompt" 0
)
# Zsh parameter expansion flags and word splitting differ from bash:
# 1. =~ regex captures go to $match array (unlike bash's ${BASH_REMATCH})
# 2. Options must be in the form 'Option=value' (no spaces)
while (( $# > 0 )); do
if [[ "$1" =~ '^([[:alnum:]_]+)=(.*)$' ]]; then
KeyName="${match[1]}"
Value="${match[2]}"
OptionsMap[$KeyName]="$Value"
else
# Store as message content
MessageParts+=( "$1" )
fi
shift
done
# ${(j: :)array} is zsh array joining with space separator
# Equivalent to "${array[*]}" in bash but preserves multiple spaces
MessageText="${(j: :)MessageParts}"
# Explicit integer declaration required in zsh for arithmetic context
typeset -i AllowMessage=$FALSE
case "$MessageType" in
"vdebug")
# Zsh arithmetic expressions use (( )) like bash but with stricter typing
(( AllowMessage = (Output_Debug_Mode == 1 && Output_Verbose_Mode == 1) ? TRUE : FALSE ))
;;
"debug")
(( AllowMessage = (Output_Debug_Mode == 1) ? TRUE : FALSE ))
;;
"verbose")
(( AllowMessage = (Output_Verbose_Mode == 1) ? TRUE : FALSE ))
;;
*)
(( AllowMessage = TRUE ))
;;
esac
if (( Output_Quiet_Mode == 1 && ${SuppressionMap[$MessageType]:-0} == 1 && ${OptionsMap[Force]:-0} != 1 )); then
return 0
fi
if (( AllowMessage == 0 && ${OptionsMap[Force]:-0} != 1 )); then
return 0
fi
if [[ "$MessageType" == "prompt" ]]; then
typeset DefaultValue="${OptionsMap[Default]:-}"
typeset EmptyDefault="$([[ -z "$DefaultValue" ]] && echo "(empty)" || echo "$DefaultValue")"
typeset Prompt="${MessageText:-Enter value}"
typeset PromptEmoji="${OptionsMap[Emoji]:-${EmojiMap[$MessageType]:-}}"
typeset IndentText=""
typeset PromptText
# Handle indentation for prompts
typeset -i IndentSize=${OptionsMap[Indent]:-0}
(( IndentSize > 0 )) && IndentText="$(printf '%*s' $IndentSize '')"
if [[ -n "$DefaultValue" ]]; then
# :+ is parameter expansion shared with bash but more commonly used in zsh
PromptText="${IndentText}${PromptEmoji:+$PromptEmoji }${Prompt} [${EmptyDefault}]"
else
PromptText="${IndentText}${PromptEmoji:+$PromptEmoji }${Prompt}"
fi
if (( Output_Prompt_Enabled == 0 )); then
print -- "${DefaultValue}"
return 0
fi
# Zsh read has -r flag like bash but variable=value? syntax for prompt
# This syntax preserves exact spacing unlike bash's -p flag
typeset UserInput
read -r "UserInput?${PromptText}: "
print -- "${UserInput:-$DefaultValue}"
return 0
fi
typeset CurrentColor="${OptionsMap[Color]:-${ColorMap[$MessageType]:-}}"
typeset ResetColor="${ColorMap[reset]}"
typeset CurrentEmoji=""
if [[ -n "$MessageText" && ("$MessageType" != "print" || ( -v "OptionsMap[Emoji]" )) ]]; then
# Use :+ to check if Emoji is set (even if empty) before falling back to default
if [[ -v "OptionsMap[Emoji]" ]]; then
CurrentEmoji="${OptionsMap[Emoji]}"
else
CurrentEmoji="${EmojiMap[$MessageType]:-}"
fi
[[ -n "$CurrentEmoji" ]] && CurrentEmoji+=" "
fi
# Integer math in zsh requires explicit typing for reliable results
typeset -i IndentSize=${OptionsMap[Indent]:-0}
typeset -i BaseIndent=$IndentSize
(( BaseIndent < 0 )) && BaseIndent=0
IndentText=""
[[ $BaseIndent -gt 0 ]] && IndentText="$(printf '%*s' $BaseIndent '')"
WrapIndentText="$IndentText"
[[ $BaseIndent -gt 0 ]] && WrapIndentText+=" "
typeset -i TerminalWidth=$(tput cols)
typeset -i RequestedWrap=${OptionsMap[Wrap]:-0}
typeset -i WrapWidth
if (( RequestedWrap == 0 && IndentSize == 0 )); then
# print -- behaves differently than echo in zsh, more predictable for output
print -- "${CurrentColor}${CurrentEmoji}${MessageText}${ResetColor}"
return 0
elif (( RequestedWrap > 0 )); then
WrapWidth=$(( RequestedWrap <= TerminalWidth ? RequestedWrap : TerminalWidth ))
elif (( IndentSize > 0 )); then
WrapWidth=$TerminalWidth
else
print -- "${CurrentColor}${CurrentEmoji}${MessageText}${ResetColor}"
return 0
fi
typeset -i WrapMargin=2
typeset -i MinContentWidth=40
typeset -i EffectiveWidth=$(( WrapWidth - BaseIndent - WrapMargin ))
(( EffectiveWidth < MinContentWidth )) && EffectiveWidth=MinContentWidth
OutputText=""
CurrentLine="${IndentText}${CurrentEmoji}"
typeset -i IsFirstLine=1
# ${(ps:\n:)text} is zsh-specific splitting that preserves empty lines
# Unlike bash IFS splitting which would collapse empty lines
typeset -a Lines
typeset Line
Lines=("${(@f)MessageText}")
typeset -i LineNum=1
for Line in $Lines; do
if (( LineNum > 1 )); then
OutputText+="${CurrentLine}"$'\n'
CurrentLine="${IndentText}"
IsFirstLine=0
fi
# Split preserving exact whitespace patterns
typeset -a Words
Words=(${(ps: :)Line})
for WordText in $Words; do
# Tab expansion consistent between zsh/bash
WordText=${WordText//$'\t'/ }
# ${(%)string} is zsh-specific expansion that handles prompt escapes
# Used for accurate Unicode width calculation, no bash equivalent
typeset -i WordWidth=${#${(%)WordText}}
typeset -i CurrentWidth=${#${(%)CurrentLine}}
if (( CurrentWidth + WordWidth + 1 > WrapWidth - WrapMargin )); then
if (( CurrentWidth > ${#IndentText} + (IsFirstLine ? ${#CurrentEmoji} : 0) )); then
OutputText+="${CurrentLine}"$'\n'
CurrentLine="${WrapIndentText}"
IsFirstLine=0
fi
# Handle words longer than the wrap width
if (( WordWidth > EffectiveWidth )); then
# Process long words by breaking them into chunks
typeset ChunkSize=$EffectiveWidth
typeset RemainingWord="$WordText"
while (( ${#RemainingWord} > ChunkSize )); do
typeset CurrentChunk="${RemainingWord:0:$ChunkSize}"
CurrentLine+="$CurrentChunk"
OutputText+="${CurrentLine}"$'\n'
RemainingWord="${RemainingWord:$ChunkSize}"
CurrentLine="${WrapIndentText}"
IsFirstLine=0
done
# Add any remaining part of the word
WordText="$RemainingWord"
fi
CurrentLine+="$WordText"
else
if (( CurrentWidth == ${#IndentText} + (IsFirstLine ? ${#CurrentEmoji} : 0) )); then
CurrentLine+="$WordText"
else
CurrentLine+=" $WordText"
fi
fi
done
(( LineNum++ ))
done
[[ -n "$CurrentLine" ]] && OutputText+="${CurrentLine}"
print -- "${CurrentColor}${OutputText}${ResetColor}"
return 0
}
#----------------------------------------------------------------------#
# Function: z_Report_Error
#----------------------------------------------------------------------#
# Description:
# Centralized error reporting function for consistent error handling.
# Formats error messages with appropriate styling and outputs them
# to stderr. Uses z_Output if available, otherwise falls back to
# direct stderr printing.
#
# Parameters:
# $1 - Error message to display (string) - The text to show to the user
# $2 - Optional exit code (integer) - Defaults to Exit_Status_General
#
# Returns:
# Returns the specified error code or Exit_Status_General (1)
#
# Required Script Variables:
# Exit_Status_General - Default error code to use if none specified
#
# Side Effects:
# - Outputs error message to stderr
# - May use terminal styling if color output is enabled
#
# Dependencies:
# - May use z_Output if available, otherwise uses print -u2
#
# Usage Example:
# z_Report_Error "Failed to access repository" $Exit_Status_IO
#----------------------------------------------------------------------#
function z_Report_Error() {
typeset ErrorMessage="$1"
typeset -i ErrorCode="${2:-$Exit_Status_General}"
# Check if z_Output is available
if typeset -f z_Output >/dev/null 2>&1; then
z_Output error "$ErrorMessage"
else
print -u2 "❌ ERROR: $ErrorMessage"
fi
return $ErrorCode
}
#----------------------------------------------------------------------#
# Function: z_Convert_Path_To_Relative
#----------------------------------------------------------------------#
# Description:
# Converts an absolute path into a relative one, based on the current
# working directory (PWD). If the path is exactly the current directory,
# it returns the directory name rather than "." for better readability.
# This function improves user-facing path displays throughout the script.
#
# Parameters:
# $1 - The absolute or partial path to convert (string) - Must be a valid path
#
# Returns:
# Prints the relative path to stdout
# Exit_Status_Success (0) on successful conversion
#
# Required Script Variables:
# PWD - Current working directory (automatically provided by Zsh)
# Exit_Status_Success - Standard success exit code
#
# Side Effects:
# None - Pure calculation function with no state changes
#
# Dependencies:
# None - Uses only Zsh built-in parameter expansion
#
# Usage Examples:
# rel_path=$(z_Convert_Path_To_Relative "/etc/myconfig.conf")
# # Returns "../../etc/myconfig.conf" if PWD is "/home/user"
#
# rel_path=$(z_Convert_Path_To_Relative "$PWD")
# # Returns directory name (e.g., "scripts") instead of "."
#----------------------------------------------------------------------#
function z_Convert_Path_To_Relative() {
typeset pathAbsolute="${1:A}" # Canonical absolute path
typeset pwdAbsolute="${PWD:A}" # Canonical current directory
# If it's exactly the current dir, return the basename instead of "."
if [[ "$pathAbsolute" == "$pwdAbsolute" ]]; then
print "$(basename "$pathAbsolute")"
return $Exit_Status_Success
fi
# If it's a sub-path of the current dir, prefix with "./"
if [[ "$pathAbsolute" == "$pwdAbsolute/"* ]]; then
print "./${pathAbsolute#$pwdAbsolute/}"
return $Exit_Status_Success
fi
# Otherwise, attempt to find a common ancestor
typeset pathCommon="$pwdAbsolute"
typeset pathResult=""
# Step upwards until we find shared directory
while ! [[ "$pathAbsolute" = ${pathCommon}* ]]; do
pathResult="../$pathResult"
pathCommon="${pathCommon:h}"
done
# If pathCommon is non-empty, remove that portion
if [[ -n "$pathCommon" ]]; then
typeset pathRelative="${pathAbsolute#$pathCommon/}"
if [[ -n "$pathRelative" ]]; then
print "${pathResult}${pathRelative}"
else
# If removing pathCommon leaves nothing, remove trailing slash
print "${pathResult%/}"
fi
else
# Fallback: no common ancestor => remain absolute
print "$pathAbsolute"
fi
return $Exit_Status_Success
}
#----------------------------------------------------------------------#
# Function: z_Check_Requirements
#----------------------------------------------------------------------#
# Description:
# Verifies that all required external tools and capabilities are
# available for script execution. Checks minimum version requirements
# and validates the presence of essential command-line utilities.
#
# Parameters:
# None
#
# Returns:
# Exit_Status_Success (0) if all requirements are met
# Exit_Status_Dependency (127) if any requirement is missing
#
# Required Script Variables:
# Exit_Status_Success - Success exit code
# Exit_Status_Dependency - Exit code for missing dependencies
#
# Side Effects:
# - May output error messages on validation failure
#
# Dependencies:
# - z_Report_Error for error reporting
# - External commands being tested (zsh, git, etc.)
#
# Usage Example:
# z_Check_Requirements || exit $?
#----------------------------------------------------------------------#
function z_Check_Requirements {
typeset -i ErrorCount=0
# Check Zsh version
function check_Zsh_Version {
typeset ZshOutput MinVer
typeset -i Major=0 Minor=0