```zsh
#!/usr/bin/env zsh
#######################################################################
## SCRIPT INFO
##
## audit_inception_commit.sh
## - Open Integrity Audit of a Git Repository Inception Commit
##
## VERSION: 0.1.0
## (Last Updated: 2024-01-29)
##
## 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: Structural integrity and format
## - Proofs: Cryptographic SSH signature verification
## - References: Committer identity verification
## - Requirements: Open Integrity and GitHub community standards compliance
##
## The script is a part of a Proof-of-Concept (POC) for using
## Git repositories as a cryptographic roots of trust, leveraging empty,
## SSH-signed inception commits for a secure indentifier that can
## be independently verified across distributed platforms.
##
## FEATURES:
## - Local audit of Inception Commit (Progressive Trust phases 2-5)
## - Empty inception commit validation for SHA-1 trust mitigation
## - SSH-based commit signing for cryptographic integrity
## - Independent verification of platform-agnostic signatures
## - Authentication against key fingerprint of signature
## - GitHub standards compliance checking
##
## For more on the progressive trust life cycle, see:
## https://developer.blockchaincommons.com/progressive-trust/
##
## LIMITATIONS:
## - Currently only supports testing the Inception Commit (commit 0) of a
## local git repository
## - Script must be executed from within the repository being audited
## (a CLI parameter option for repository path is a work-in-progress)
## - GitHub standards compliance checks are very basic
##
## USAGE: audit_inception_commit.sh [options]
##
## OPTIONS:
## --help Show this help message
## --verbose Enable detailed output
## --quiet Suppress non-critical output
## --debug Show debugging information
## --no-prompt Run non-interactively
## --no-color Disable colored output
## --color Force colored output
##
## REQUIREMENTS:
## - Zsh 5.8 or later
## - Git 2.34 or later
## - GitHub CLI (gh) 2.65.0 or later, authenticated with GitHub
## - OpenSSH 8.2+ for signature verification
##
## 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>
## (c) 2025 Christopher Allen
## Licensed under BSD-2-Clause Plus Patent License
##
## CONTRIBUTING:
## This script is a work-in-progress and welcomes community contributions.
## - GitHub: https://github.com/BlockchainCommons/Open-Integrity
##
## SUPPORT:
## If you like these tools, my writing, our digital rights advocacy, our
## point-of-view, we invite you to sponsor us.
##
## It's a way to plug into an network that's not focused on the "big guys".
## We design decentralized solutions where everyone wins. We represent
## smaller developers in a vendor-neutral, platform-neutral way, helping
## us all to work together.
##
## You can become a monthly patron on our GitHub Sponsor Page
## https://github.com/sponsors/BlockchainCommons for as little as $20 a
## month, or you can make a one-time donation.
##
## But please don't think of this as a transaction. It's an opportunity to
## advance the open web, digital civil liberties, and human rights together.
## You get to plug into our various projects, and hopefully will find a way
## to actively contribute to the digital commons yourself. Let's collaborate!
##
## -- Christopher Allen <ChristopherA@LifeWithAlacrity.com>
## Github: [@ChristopherA](https://github.com/ChristopherA)
## Twitter: [@ChristopherA](https://twitter.com/ChristopherA)
## Bluesky: [@ChristopherA](https://bsky.app/profile/christophera.bsky.social)
#######################################################################
#######################################################################
##CHANGE LOG
#######################################################################
## 0.1.0 - Initial Release (2024-01-29)
## - 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 verification)
## * 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: ZSH Configuration and Environment Initialization
##--------------------------------------------------------------------##
## Description:
## - Configures the Zsh environment to ensure robust error handling and
## predictable execution behavior.
## - Implements safe Zsh options to prevent silent script failures,
## unintentional global variables, or accidental file overwrites.
## - Declares script-scoped variables, constants, and execution flags
## - Early functions for setting up the script environment and verifying
## requirements.
##
## Declarations:
## - Safe ZSH Environment Options: Strict error-handling and behavior flags.
## - Script-Scoped Variables:
## - Boolean Constants: TRUE and FALSE for boolean logic.
## - Execution Flags: Control script behavior and modes.
## - Script Constants: Immutable variables for script metadata and
## runtime context.
## - Command-Line Arguments and Runtime Context: Processes arguments and
## runtime details for improved usability and debugging.
##
## Functions:
## - setup_Environment: Initializes script settings and variables.
## - check_Requirements: Verifies all prerequisites are met.
#######################################################################
#----------------------------------------------------------------------#
# Safe ZSH Environment Options
#----------------------------------------------------------------------#
# Description:
# - Configures Zsh options to ensure safe and predictable script execution.
# - Prevents common pitfalls such as unintentional global variable creation,
# silent command failures, and accidental file overwrites.
#----------------------------------------------------------------------#
# 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 ERR exit status of the last command in the pipe that failed
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-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 - Execution Flags
#----------------------------------------------------------------------#
# - Script-scoped flags controlling various modes and behaviors
# - Declared as integers using `typeset -i` to ensure type safety
#----------------------------------------------------------------------#
typeset -i ScriptRunning=$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 Constants
#----------------------------------------------------------------------#
typeset -r ScriptFileName="${0##*/}" # Script base name
typeset -r ScriptBaseName=${${0:A:t}%.*} # Name without extension
typeset -r ScriptFileExt=${0##*.} # File extension
typeset -r ScriptRealFilePath=$(realpath "${0:A}") # Absolute path
typeset -r ScriptRealDirName=$(basename "$(realpath "${0:A:h}")") # Directory name
typeset -r ScriptRealDirPath=$(realpath "${0:A:h}") # Directory path
typeset -r ScriptRealParentDir=$(realpath "${0:A:h:h}") # Parent directory
#----------------------------------------------------------------------#
# Script-Scoped Variables - Command-Line Arguments and Runtime Context
#----------------------------------------------------------------------#
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
#----------------------------------------------------------------------#
# Script-Scoped Variables - Environment Detection Variables
#----------------------------------------------------------------------#
# - 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 Constants
#----------------------------------------------------------------------#
# 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 TputColors=0
# Safely retrieve the number of terminal colors
if command -v tput >/dev/null 2>&1; then
TputColors=$(tput colors 2>/dev/null || echo 0) # Default to 0 if tput fails
if (( TputColors >= 8 )); then
Output_Has_Color=$TRUE
elif ! (( Output_Quiet_Mode )); then
print "WARNING: Insufficient color support (${TputColors} 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
#----------------------------------------------------------------------#
typeset Inception_Commit_Repo_Id # Stores inception commit SHA
#----------------------------------------------------------------------#
# Function: cleanup
#----------------------------------------------------------------------#
# Description:
# Performs cleanup operations when the script exits.
#
# Parameters:
# $1 - Success flag (boolean)
# $2 - Verbose flag (boolean)
#
# Returns:
# None
#----------------------------------------------------------------------#
function cleanup {
typeset Success=$1
typeset Verbose=$2
# Reset the script running flag
ScriptRunning=$FALSE
if (( Success == $TRUE )); then
# On success, report cleanup completion in debug mode
z_Output debug "Cleanup completed successfully."
else
# On failure, use warning type which respects quiet mode
z_Output warn "Script terminated with errors. Cleanup completed."
fi
}
#----------------------------------------------------------------------#
# Function: check_Requirements
#----------------------------------------------------------------------#
# Description:
# Verifies that all required external tools and capabilities are
# available. Called as part of environment initialization.
#
# Parameters:
# None
#
# Returns:
# 0 if all requirements are met
# 1 if any requirement is missing
#----------------------------------------------------------------------#
function check_Requirements {
typeset -i ErrorCount=0
# Local function to check Zsh version
function check_Zsh_Version {
typeset ZshOutput MinVer
typeset -i Major=0 Minor=0
ZshOutput="$(zsh --version)"
if [[ -z "${ZshOutput}" ]]; then
z_Error "Failed to get Zsh version"
return 1
fi
# Extract version numbers using parameter expansion
MinVer="${ZshOutput#*zsh }"
MinVer="${MinVer%% *}"
Major="${MinVer%%.*}"
Minor="${MinVer#*.}"
if (( Major < 5 || (Major == 5 && Minor < 8) )); then
z_Error "Zsh version 5.8 or later required (found ${Major}.${Minor})"
return 1
fi
return 0
}
# local function to check required commands
function check_Required_Commands {
typeset -a RequiredCommands=(
"printf" # For formatted output
"zsh" # To check version
)
typeset Command
typeset -i CmdIdx
typeset ErrorCount=0
for (( CmdIdx=1; CmdIdx <= ${#RequiredCommands[@]}; CmdIdx++ )); do
Command="${RequiredCommands[CmdIdx]}"
if ! command -v "${Command}" >/dev/null 2>&1; then
z_Error "Required command not found: ${Command}"
(( ErrorCount++ ))
fi
done
return $ErrorCount
}
# Execute each test
check_Zsh_Version || (( ErrorCount++ ))
check_Required_Commands || (( ErrorCount++ ))
return (( ErrorCount ? 1 : 0 ))
}
#----------------------------------------------------------------------#
# Function: setup_Environment
#----------------------------------------------------------------------#
# Description:
# Initializes the script environment and checks requirements.
# Part of the core environment initialization process.
#
# Parameters:
# None
#
# Returns:
# 0 on successful setup
# 1 on setup failure
#----------------------------------------------------------------------#
function setup_Environment {
# Check requirements
check_Requirements || return 1
# Additional setup steps can be added here
return 0
}
########################################################################
## Section: z_Tools
##--------------------------------------------------------------------##
## Description:
## - This section contains reusable tools for managing script output
## and interactions in a consistent and modular manner.
##
## Usage:
## - Designed to be imported or reused in other scripts for consistent
## output handling and interaction.
##
## Functions:
## - z_Output: Modular output function for managing script messages and prompts.
########################################################################
#----------------------------------------------------------------------#
# Function: z_Output
#----------------------------------------------------------------------#
# Description:
# A flexible and modular function for displaying formatted output
# in Zsh scripts. Provides consistent output formatting with support
# for multiple message types, emoji prefixes, text wrapping,
# indentation, verbosity levels, and interactive prompts.
#
# Version: 1.0.00 (2024-01-17)
#
# Change Log: - 1.0.0 Initial stable release (2024-01-17)
# - Feature complete with
# - Nine message types
# - Five modes
# - Text wrapping, indentation, and color support
# - Emoji and Unicode handling
# - Flexible message type and mode controls
# - Robust interactive and non-interactive prompting
#
# Features:
# - Message Types: print, info, verbose, success, warn, error,
# debug, vdebug, prompt
# - Verbosity Modes:
# - Verbose for detailed information
# - Quiet to suppress non-critical messages
# - Debug for troubleshooting output
# - Other Modes:
# - No-Prompt to disable interactive prompts
# - Color to set color output
# - Text Formatting: wrapping, indentation, ANSI colors
# - Emoji Support: Customizable emoji prefixes per message type
# - Interactive Prompts: With default values and automation support
#
# Default Behaviors:
# print type:
# - By default, behaves exactly like zsh's native print command
# - No formatting (wrapping, indentation, emoji) by default
# - Can optionally use formatting features if explicitly requested
# - Suppressed in quiet mode like other non-critical messages
# - Emoji support must be explicitly enabled via Emoji option
#
# Other message types:
# - Without indent:
# * If Wrap=0 or Wrap not specified: No wrapping
# * If Wrap>0: Wrap at specified width
# - With indent:
# * Always wraps (at terminal width if Wrap not specified)
# * Wraps at Wrap width if specified and < terminal width
# * Continuation lines indented +2 spaces from base indent
# - Line Continuation:
# * Wrapped lines align with text after emoji/prefix
# * Preserves spacing and formatting
# - Mode Controls:
# * debug/vdebug respect both Force and mode flags
# * verbose respects both quiet mode and Force
# * error shows even in quiet mode
#
# Parameters:
# 1. Type (string):
# Message type controlling appearance and behavior
# Supported types:
# print: Standard output, like zsh print (no formatting by default)
# info: Informational messages (cyan, đĄ)
# verbose: Detailed output shown in verbose mode, hidden in quiet (blue, đ)
# success: Success messages (green, â
)
# warn: Warning messages (yellow, â ī¸)
# error: Critical errors, shown even in quiet mode (red, â)
# debug: Debug messages shown only in debug mode (magenta, đ ī¸)
# vdebug: Verbose debug messages, requires both debug AND verbose (magenta, đ)
# prompt: Interactive prompts (standout color, â, supports non-interactive)
#
# 2. Message (string):
# The text content to display. Supports:
# - Multi-line text
# - Spaces and tabs (preserved)
# - Empty messages
# - Special characters
# - Very long words/URLs
# - Unicode including emoji
#
# 3. Options (Key=Value pairs, optional):
# Additional formatting options:
#
# Color (string):
# - ANSI color code to override default for message type
# - Empty string disables coloring
# Example: Color="$(tput setaf 1)" # Force red text
# Color="" # Disable color
#
# Emoji (string):
# - Custom emoji prefix overriding default for message type
# - Empty string disables emoji
# - Required for print type to show emoji
# Example: Emoji="đ" # Custom star emoji
#
# Wrap (integer):
# - Maximum line width for text wrapping
# - When not specified or 0:
# * No wrapping if no indent specified
# * Terminal width wrapping if indent specified
# - When >0: Wrap at specified width
# - When >terminal width: Wrap at terminal width
# - Minimum 20 characters, maximum current terminal width
# - Adjusts automatically if terminal is resized
# - Takes precedence over indent-triggered wrapping
# Example: Wrap=60 # Wrap at 60 characters
#
# Indent (integer):
# - Number of spaces for left indentation
# - Defaults to 0 (no indent)
# - When specified: Enables wrapping even if Wrap=0
# - Applies to all lines including wrapped text
# - Wrapped lines get +2 spaces additional indent
# - Wrap width defaults to terminal width if not specified
# Example: Indent=4 # Four space indent
#
# Default (string):
# - Default value for prompts when non-interactive
# - Used when Output_Prompt_Enabled is FALSE
# - Preserves exact spacing when used
# Example: Default="yes" # Default prompt response
#
# Force (boolean):
# - Forces output even in quiet mode
# - Overrides quiet mode for all message types
# - Does not bypass debug/verbose mode requirements
# - vdebug still requires both debug AND verbose even with Force
# Example: Force=$TRUE # Force display in quiet mode
#
# Returns:
# - For prompts: Prints and returns user input or default value
# - For messages: Prints formatted text, returns 0
# - For errors: Prints error message and returns 1
# - Returns 2 for invalid message types
#
# Dependencies:
# Required commands:
# - tput: For color and terminal capabilities
# - printf: For formatted output
#
# Required zsh options:
# - localoptions: For local option scope
# - warncreateglobal: For variable scope warnings
#
# Script-scoped variables (must be declared):
# - Output_Verbose_Mode (integer): Controls verbose message display
# - Output_Quiet_Mode (integer): Controls message suppression
# - Output_Debug_Mode (integer): Controls debug message display
# - Output_Prompt_Enabled (integer): Controls interactive prompting
# - TRUE/FALSE (integer): Boolean constants as integers (i.e. 1/0)
# - Term_* variables: Color and formatting codes
#
# Required terminal color variables (script-local read-only):
# - Basic colors: Term_Black, Term_Red, Term_Green, Term_Yellow,
# Term_Blue, Term_Magenta, Term_Cyan, Term_White:
# - Bright colors: Term_BrightBlack, Term_BrightRed,
# Term_BrightGreen, Term_BrightYellow, Term_BrightBlue,
# Term_BrightMagenta, Term_BrightCyan, Term_BrightWhite
# - Text attributes: Term_Bold, Term_Underline,
# Term_NoUnderline, Term_Standout, Term_NoStandout,
# Term_Blink, Term_Dim, Term_Reverse, Term_Invisible
# - Reset all: Term_Reset
#
# Examples:
# ### Basic Message Types ###
# - Print (standard output):
# z_Output print "Standard message with no formatting"
# z_Output print "Print with wrap" Wrap=60
# z_Output print "Print with emoji" Emoji="đ"
#
# - Info messages:
# z_Output info "Basic informational message"
# z_Output info "Custom info message" Emoji="âšī¸" Color="$Term_Cyan"
# z_Output info "Info with wrap and indent" Wrap=60 Indent=4
#
# - Success messages:
# z_Output success "Operation completed successfully"
# z_Output success "Detailed success" Wrap=60 Indent=2
#
# - Warning messages:
# z_Output warn "Configuration issue detected"
# z_Output warn "Multi-line warning\nSecond line" Indent=4
#
# - Error messages:
# z_Output error "Operation failed"
# z_Output error "Critical error" Color="$Term_BrightRed"
#
# ### Debug and Verbose Messages ###
# - Debug messages (requires debug mode):
# z_Output debug "Debug information follows..."
# z_Output debug "Force debug message" Force=$TRUE
#
# - Verbose messages (requires verbose mode):
# z_Output verbose "Detailed processing information"
# z_Output verbose "Force verbose message" Force=$TRUE
#
# - Verbose debug (requires both modes):
# z_Output vdebug "Detailed debug trace"
# z_Output vdebug "Forced vdebug" Force=$TRUE
#
# ### Interactive Prompts ###
# - Basic prompts:
# UserInput=$(z_Output prompt "Enter your name:")
# Choice=$(z_Output prompt "Continue? (Y/n):" Default="Y")
#
# - Non-interactive mode:
# Output_Prompt_Enabled=$FALSE
# Default=$(z_Output prompt "Skip prompt" Default="yes")
#
# ### Advanced Formatting ###
# - Wrapping and indentation:
# z_Output info "Long wrapped message at 60 chars" Wrap=60
# z_Output warn "Indented warning message" Indent=4
# z_Output info "Combined format" Wrap=50 Indent=2
#
# - Custom formatting:
# z_Output info "Custom color" Color="$Term_BrightCyan"
# z_Output warn "Custom emoji" Emoji="âĄ"
# z_Output info "No emoji message" Emoji=""
#
# - Complex combinations:
# z_Output info "Complex formatted message with custom\n" \
# "appearance and wrapped text that spans\n" \
# "multiple lines" \
# Wrap=40 Indent=4 Emoji="đĸ" Color="$Term_BrightBlue"
#
# ### Mode Control ###
# - Quiet mode override:
# z_Output info "Always show this" Force=$TRUE
# z_Output verbose "Force verbose in quiet" Force=$TRUE
#
# - Debug control:
# z_Output debug "Debug if enabled" Force=$TRUE
# z_Output vdebug "Vdebug needs both modes" Force=$TRUE
#
# Notes:
# - Terminal Support:
# - Requires terminal with ANSI color support
# - Automatically wraps to terminal width
# - Adapts to terminal resizing during execution
# - Degrades gracefully in basic terminals
# - Minimum width of 20 characters enforced
# - Uses current terminal width at time of each call
#
# - Text Processing:
# - Preserves tabs (converts to spaces)
# - Maintains spacing and line breaks
# - Handles special characters and Unicode
# - Word-wraps long text
# - Preserves empty lines
# - Handles multi-byte characters and emoji correctly
#
# - Message Control:
# - Quiet mode suppresses all except error and forced messages
# - Verbose mode shows verbose messages (unless quiet)
# - Debug mode enables debug messages
# - Debug AND verbose modes required for vdebug
# - Force flag overrides quiet mode only
# - Error messages always show regardless of modes
#
# - Zsh Specific:
# - Uses Zsh parameter expansion flags
# - Requires Zsh arrays and associative arrays
# - Takes advantage of Zsh string manipulation
# - Uses Zsh read builtin for prompts
# - Handles zsh-specific terminal behavior
#
# Known Issues:
# - Space Preservation in Interactive Prompts:
# When entering text at interactive prompts (not accepting defaults),
# spaces may be affected:
# - Leading spaces are stripped
# - Trailing spaces may be inconsistent
# - Internal spaces are preserved
# This is a limitation of zsh's read builtin and affects only
# manually entered text; default values preserve spaces correctly.
#----------------------------------------------------------------------#
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 regex pattern matching using =~ behaves differently than bash
# Captures stored in $match array rather than bash's ${BASH_REMATCH}
while (( $# > 0 )); do
if [[ "$1" =~ ^([^=]+)=(.*)$ ]]; then
KeyName="${match[1]}"
Value="${match[2]}"
OptionsMap[$KeyName]="$Value"
else
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 Default="${OptionsMap[Default]:-}"
typeset EmptyDefault="$([[ -z "$Default" ]] && echo "(empty)" || echo "$Default")"
typeset Prompt="${MessageText:-Enter value}"
typeset PromptEmoji="${OptionsMap[Emoji]:-${EmojiMap[$MessageType]:-}}"
typeset PromptText
if [[ -n "$Default" ]]; then
# :+ is parameter expansion shared with bash but more commonly used in zsh
PromptText="${PromptEmoji:+$PromptEmoji }${Prompt} [${EmptyDefault}]"
else
PromptText="${PromptEmoji:+$PromptEmoji }${Prompt}"
fi
if (( Output_Prompt_Enabled == 0 )); then
print -- "${Default}"
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:-$Default}"
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=(${(ps:\n:)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
if (( WordWidth > EffectiveWidth )); then
while (( ${#WordText} > EffectiveWidth )); do
# Zsh array slicing uses [start,end] unlike bash's offset/length
CurrentLine+="${WordText[1,EffectiveWidth]}"
OutputText+="${CurrentLine}"$'\n'
WordText="${WordText[EffectiveWidth+1,-1]}"
CurrentLine="${WrapIndentText}"
IsFirstLine=0
done
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: audit_local_inception_commit
#----------------------------------------------------------------------#
# Description:
# Performs a multi-phase audit of a Git repository's inception commit,
# following the Progressive Trust lifecycle phases 2-4:
# - Phase 2 (Wholeness): Assesses structural integrity & format
# - Phase 3 (Proofs): Verifies cryptographic elements
# - Phase 4 (References): Checks trust references & identity
# = Phase 5 (Requirements): Audits compliance with requirements
#
# Parameters:
# None
#
# Returns:
# 0 if all audit phases pass
# 1 on any audit phase failure
#----------------------------------------------------------------------#
audit_local_inception_commit() {
#------------------------------------------------------------------#
# Local Function: locate_inception_commit
# Phase 2 (Wholeness) prerequisite: Find and assess inception commit
#------------------------------------------------------------------#
function locate_inception_commit {
Inception_Commit_Repo_Id=$(git rev-list --max-parents=0 HEAD 2>/dev/null)
if [[ $? -eq 0 && -n "$Inception_Commit_Repo_Id" ]]; then
z_Output verbose Indent=4 "Found inception commit ${Inception_Commit_Repo_Id}"
z_Output success Indent=2 "Repository Structure: Inception commit found"
return 0
else
z_Output verbose Indent=4 "No inception commit found"
z_Output error "Repository Structure: No inception commit found"
Inception_Commit_Repo_Id=""
return 1
fi
}
#------------------------------------------------------------------#
# Local Function: validate_empty_commit
# Phase 2 (Wholeness): Validate commit is empty (contains no files)
#------------------------------------------------------------------#
function validate_empty_commit {
typeset tree_hash empty_tree_hash
tree_hash=$(git cat-file -p "${Inception_Commit_Repo_Id}" | awk '/^tree / {print $2}')
empty_tree_hash=$(git hash-object -t tree /dev/null)
if [[ "${tree_hash}" == "${empty_tree_hash}" ]]; then
z_Output verbose Indent=4 "Tree hash matches empty commit requirements"
z_Output success Indent=2 "Content Validation: Commit is empty as required"
return 0
else
z_Output verbose Indent=4 "Tree hash does not match empty commit requirements"
z_Output error "Content Validation: Commit is not empty"
return 1
fi
}
#------------------------------------------------------------------#
# Local Function: validate_commit_message_format
# Phase 2 (Wholeness): Validate commit message meets requirements
#------------------------------------------------------------------#
function validate_commit_message_format {
typeset commit_message
commit_message=$(git log "${Inception_Commit_Repo_Id}" -1 --pretty=%B)
if echo "${commit_message}" | grep -q "Initialize repository and establish a SHA-1 root of trust" && \
echo "${commit_message}" | grep -q "Signed-off-by:"; then
z_Output verbose Indent=4 "Found required initialization message and sign-off"
z_Output success Indent=2 "Format Validation: Commit message meets requirements"
return 0
else
z_Output verbose Indent=4 "Missing required message elements"
z_Output error "Format Validation: Commit message incomplete"
return 1
fi
}
#------------------------------------------------------------------#
# Local Function: authenticate_ssh_signature
# Phase 3 (Proofs): Verify authentication of cryptographic signature
#------------------------------------------------------------------#
function authenticate_ssh_signature {
if git verify-commit "${Inception_Commit_Repo_Id}" >/dev/null 2>&1; then
z_Output verbose Indent=4 "Signature authenticated against public key"
z_Output success Indent=2 "SSH Signature: Verified"
return 0
else
z_Output verbose Indent=4 "Signature validation failed"
z_Output error "SSH Signature: Verification failed"
return 1
fi
}
#------------------------------------------------------------------#
# Local Function: affirm_committer_signature
# Phase 4 (References): Affirm keyholder via signature fingerprint
#------------------------------------------------------------------#
function affirm_committer_signature {
typeset signing_key_fingerprint committer_name
z_Output verbose Indent=4 "Extracting key fingerprint..."
signing_key_fingerprint=$(git log "${Inception_Commit_Repo_Id}" -1 --show-signature --pretty=format:'' | \
grep -o "SHA256:[^ ]*")
committer_name=$(git log "${Inception_Commit_Repo_Id}" -1 --pretty=format:'%cn')
if [[ "${committer_name}" == "${signing_key_fingerprint}" ]]; then
z_Output verbose Indent=4 "Matched committer name to fingerprint"
z_Output success Indent=2 "Identity Check: Committer matches key fingerprint"
return 0
else
z_Output verbose Indent=4 "Committer name does not match fingerprint"
z_Output error "Identity Check: Committer does not match key fingerprint"
return 1
fi
}
# Initialize audit state
typeset -i audit_success=$TRUE
# Main audit header
z_Output info "\nInception Commit Audit Report" Emoji=""
z_Output verbose Emoji="" "Evaluating overall inception commit compliance with standards..."
z_Output verbose Emoji="" ""
# Wholeness Assessment (Phase 2) header and checks
z_Output info "Wholeness Assessment:"
z_Output verbose Emoji="" "(Progressive Trust Phase 2)"
z_Output verbose Indent=2 Emoji="đ" "Assessing repository structure..."
if ! locate_inception_commit; then
return 1
fi
z_Output verbose Emoji="" ""
z_Output verbose Indent=2 Emoji="đ" "Validating commit content..."
if ! validate_empty_commit; then
audit_success=$FALSE
fi
z_Output verbose Emoji="" ""
z_Output verbose Indent=2 Emoji="đ" "Validating message format..."
if ! validate_commit_message_format; then
audit_success=$FALSE
fi
# Cryptographic Proofs (Phase 3) header and checks
z_Output verbose Emoji="" ""
z_Output info "Cryptographic Proofs:"
z_Output verbose Emoji="" "(Progressive Trust Phase 3)"
z_Output verbose Indent=2 Emoji="đ" "Authenticating SSH signature..."
if ! authenticate_ssh_signature; then
audit_success=$FALSE
fi
# Trust References (Phase 4) header and checks
z_Output verbose Emoji="" ""
z_Output info "Trust References:"
z_Output verbose Emoji="" "(Progressive Trust Phase 4)"
z_Output verbose Indent=2 Emoji="đ" "Affirming identity references..."
if ! affirm_committer_signature; then
audit_success=$FALSE
fi
return $(( audit_success ? 0 : 1 ))
}
#----------------------------------------------------------------------#
# Function: complies_with_Github_Standards
#----------------------------------------------------------------------#
# Description:
# Implements Phase 5 (Requirements/Community Standards) of Progressive
# Trust by checking compliance with GitHub's standards for signed
# commits and repository initialization.
#
# Parameters:
# commit_sha - The SHA-1 hash of the inception commit to check
#
# Returns:
# 0 if compliance check succeeds
# 1 if compliance check fails or GitHub access fails
#----------------------------------------------------------------------#
complies_with_Github_Standards() {
typeset commit_sha="$1"
typeset github_repo github_org_id response
# Parameter validation
[[ -z "$commit_sha" ]] && {
z_Output error "Missing commit SHA for GitHub standards compliance"
return 1
}
# Check GitHub repository accessibility
gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name' 2>/dev/null >/dev/null || {
z_Output warn "Repository not on GitHub or 'gh' CLI not authenticated."
return 1
}
# Extract GitHub repository information
github_repo=$(basename "$(git config --get remote.origin.url)" .git)
github_org_id=$(basename "$(dirname "$(git config --get remote.origin.url)")")
typeset github_url="https://github.com/${github_org_id}/${github_repo}/commit/${commit_sha}"
# Phase 5 header and information
z_Output info "Community Standards:"
z_Output verbose Emoji="" "(Progressive Trust Phase 5)"
z_Output info Indent=2 Emoji="đ" "GitHub-specific compliance check available"
# Handle interactive vs non-interactive mode
if (( Output_Prompt_Enabled != TRUE )); then
response="Y"
else
response=$(z_Output prompt "Check compliance with GitHub standards (opens GitHub page)? [y/N]:" Default="N" Indent=4 )
fi
# Process response and provide compliance info
case "${response:-Y}" in
[Yy]*)
z_Output verbose "Opening GitHub standards compliance page..."
open "$github_url"
;;
*)
z_Output verbose Indent=4 "GitHub standards compliance URL available for review:"
z_Output verbose "${github_url}" Emoji=""
;;
esac
return 0
}
#----------------------------------------------------------------------#
# Function: core_functionality
#----------------------------------------------------------------------#
# Description:
# Coordinates the Progressive Trust audit workflow, managing the
# execution of phases and presentation of results. Executes phases in
# sequence:
# - Phases 2-4: Audit local inception commit structure and credentials
# - Phase 5: Check compliance with GitHub community standards
#
# Parameters:
# None
#
# Returns:
# 0 on successful completion
# 1 on audit or execution failure
#----------------------------------------------------------------------#
core_functionality() {
# Execute local audit of Phases 2-4
audit_local_inception_commit
typeset -i Validation_Status=$?
# Handle audit failure
if (( Validation_Status != 0 )); then
z_Output error "Audit Complete: FAILED"
return 1
fi
# Reference to other useful local git commands with shortened SHA
z_Output verbose Emoji="" ""
z_Output verbose Indent=2 Emoji="" "Other useful local git commands (for reference):"
z_Output verbose Indent=4 Emoji="" "View inception commit details: git log ${Inception_Commit_Repo_Id:0:7} -1"
z_Output verbose Indent=4 Emoji="" "View inception commit structure: git cat-file -p ${Inception_Commit_Repo_Id:0:7}"
z_Output verbose Indent=4 Emoji="" "Verify inception commit signature: git verify-commit ${Inception_Commit_Repo_Id:0:7}"
z_Output verbose Emoji="" ""
# Execute Phase 5 community standards compliance
complies_with_Github_Standards "${Inception_Commit_Repo_Id}"
# Final audit status
z_Output verbose Emoji="" ""
z_Output success Emoji="đ¯" "Audit Complete: Local git repo at \`$ScriptRealDirName\` in compliance\n with Open Integrity specification for Inception Commits." Force=1
z_Output verbose Emoji="" "(Progressive Trust phases 1-5 passed.)"
return 0
}
#----------------------------------------------------------------------#
# Function: show_Help
#----------------------------------------------------------------------#
# Description:
# Displays help information following zsh conventions and utilizing
# z_Output's formatting capabilities. Shows usage, options, and examples
# in a structured format.
#
# Parameters:
# None
#
# Returns:
# 0 always
#
# Output:
# Formatted help text using z_Output's indentation capabilities
#----------------------------------------------------------------------#
function show_Help {
z_Output Emoji="" Wrap=80 info \
"Progressive Trust Audit for Git Repository Inception Commits\n"
z_Output Emoji="" Indent=2 Wrap=78 info "CURRENT LIMITATIONS:"
z_Output Emoji="" Indent=4 Wrap=76 print \
"This script must currently be copied into the Git repository being tested."
z_Output Emoji="" Indent=4 Wrap=76 print \
"Support for specifying a repository path is work-in-progress.\n"
z_Output Emoji="" Indent=2 Wrap=78 info "USAGE:"
z_Output Emoji="" Indent=4 Wrap=76 print "${ScriptFileName} [options]\n"
z_Output Emoji="" Indent=2 Wrap=78 info "OPTIONS:"
z_Output Emoji="" Indent=4 Wrap=76 print "-v, --verbose Enable detailed progress messages"
z_Output Emoji="" Indent=4 Wrap=76 print "-q, --quiet Suppress non-essential output"
z_Output Emoji="" Indent=4 Wrap=76 print "-d, --debug Show debug information for troubleshooting"
z_Output Emoji="" Indent=4 Wrap=76 print "-h, --help Show this help message"
z_Output Emoji="" Indent=4 Wrap=76 print "-n, --no-color Disable colored output"
z_Output Emoji="" Indent=4 Wrap=76 print "-c, --color Force colored output"
z_Output Emoji="" Indent=4 Wrap=76 print "-p, --no-prompt Run non-interactively"
z_Output Emoji="" Indent=4 Wrap=76 print "-i, --interactive Force interactive prompts\n"
z_Output Emoji="" Indent=2 Wrap=78 info "AUDIT PHASES:"
z_Output Emoji="" Indent=4 Wrap=76 print "Phase 2 (Wholeness) Verifies structural integrity and message format"
z_Output Emoji="" Indent=4 Wrap=76 print "Phase 3 (Proofs) Validates cryptographic SSH signatures"
z_Output Emoji="" Indent=4 Wrap=76 print "Phase 4 (References) Checks committer identity against authorized keys"
z_Output Emoji="" Indent=4 Wrap=76 print "Phase 5 (Requirements) Audits GitHub community standards compliance\n"
z_Output Emoji="" Indent=2 Wrap=78 info "EXAMPLES:"
z_Output Emoji="" Indent=4 Wrap=76 print "Standard audit:"
z_Output Emoji="" Indent=6 Wrap=74 print "${ScriptFileName}"
z_Output Emoji="" Indent=4 Wrap=76 print "Detailed output:"
z_Output Emoji="" Indent=6 Wrap=74 print "${ScriptFileName} --verbose"
z_Output Emoji="" Indent=4 Wrap=76 print "Non-interactive mode:"
z_Output Emoji="" Indent=6 Wrap=74 print "${ScriptFileName} --quiet --no-prompt\n"
exit 0
}
#----------------------------------------------------------------------#
# Function: parse_Arguments
#----------------------------------------------------------------------#
#
# Description:
# Parses command line arguments and sets script behavior flags.
# Also detects the execution environment through various environment
# variables and terminal capabilities to determine appropriate modes
# for color output and interactive prompting.
#
# Parameters:
# $@ - Command line arguments
#
# Returns:
# - 0 on successful argument parsing
# - 1 on error or when help is requested
#
# Options:
# -v, --verbose Enable verbose output
# -q, --quiet Enable quiet mode (suppress non-critical output)
# -d, --debug Enable debug mode
# -h, --help Show help message and exit
# -n, --no-color Disable colored output
# -c, --color Force colored output (overrides auto-detection)
# -p, --no-prompt Disable interactive prompts (non-interactive mode)
# -i, --interactive Force interactive mode (overrides non-interactive detection)
#
# Environment Variables Used:
# - NO_COLOR: Industry standard for disabling color output
# - FORCE_COLOR: Build system standard for forcing color output
# - CI: Indicates running in a Continuous Integration environment
# - PS1: Shell prompt variable, unset indicates non-interactive shell
# - TERM: Terminal type, "dumb" indicates limited terminal capabilities
#
# Globals Modified:
# - Output_Verbose_Mode: Controls verbose message display
# - Output_Quiet_Mode: Controls suppression of non-critical output
# - Output_Debug_Mode: Controls debug information display
# - Output_Color_Enabled: Controls use of ANSI color in output
# - Output_Prompt_Enabled: Controls interactive prompt behavior
#
# Detection Precedence:
# Color Mode:
# 1. Command line flags (--no-color, --color)
# 2. NO_COLOR environment variable
# 3. FORCE_COLOR environment variable
# 4. TERM=dumb check
# 5. Terminal capability auto-detection
#
# Interactive Mode:
# 1. Command line flags (--no-prompt, --interactive)
# 2. CI environment detection
# 3. PS1 environment variable check
# 4. TERM=dumb check
# 5. Terminal capability auto-detection
#
# Side Effects:
# - May write to stderr for help display
# - Outputs debug information if debug mode is enabled
#
# Notes:
# - All environment variable checks are logged when debug mode is enabled
# - Terminal capability checks use both stdin and stdout for interactive mode
# - Color support is determined using `tput colors` when auto-detecting
#
# Example Usage:
# parse_Arguments --verbose --no-color "$@"
# parse_Arguments --debug --interactive "$@"
#
# See Also:
# - show_Help: Displays detailed usage information
# - z_Output: Uses the parsed settings for output control
#----------------------------------------------------------------------#
function parse_Arguments {
# Store initial state
typeset -i Initial_Verbose=$Output_Verbose_Mode
typeset -i Initial_Quiet=$Output_Quiet_Mode
typeset -i Initial_Debug=$Output_Debug_Mode
typeset -i Initial_Color=$Output_Color_Enabled
typeset -i Initial_Prompt=$Output_Prompt_Enabled
# Temporary arrays for zparseopts
typeset -a verbose quiet debug help no_color force_color no_prompt force_interactive
# Temporary arrays for zparseopts
typeset -a verbose quiet debug help no_color force_color no_prompt force_interactive
# Parse options using zparseopts
if ! zparseopts -D -E -F - \
v=verbose -verbose=verbose \
q=quiet -quiet=quiet \
d=debug -debug=debug \
h=help -help=help \
n=no_color -no-color=no_color \
c=force_color -color=force_color \
p=no_prompt -no-prompt=no_prompt \
i=force_interactive -interactive=force_interactive; then
# Restore initial state on parse error
Output_Verbose_Mode=$Initial_Verbose
Output_Quiet_Mode=$Initial_Quiet
Output_Debug_Mode=$Initial_Debug
Output_Color_Enabled=$Initial_Color
Output_Prompt_Enabled=$Initial_Prompt
return 1
fi
# Process debug first since we'll use it for logging other flags
(( ${#debug} > 0 )) && Output_Debug_Mode=$TRUE
# Process help next
if (( ${#help} > 0 )); then
show_Help
exit 0 # Exit immediately after showing help
fi
# Process standard flags atomically
(( ${#verbose} > 0 )) && Output_Verbose_Mode=$TRUE
(( ${#quiet} > 0 )) && Output_Quiet_Mode=$TRUE
(( ${#debug} > 0 )) && Output_Debug_Mode=$TRUE
#----------------------------------------------------------------------
# Color Detection
#----------------------------------------------------------------------
# Store previous color state for potential rollback
typeset -i Previous_Color=$Output_Color_Enabled
# First check explicit flags (highest priority)
if (( ${#no_color} > 0 )); then
Output_Color_Enabled=$FALSE
elif (( ${#force_color} > 0 )); then
Output_Color_Enabled=$TRUE
# Then check standard environment variables
elif [[ -n "${Script_No_Color}" ]]; then
Output_Color_Enabled=$FALSE
elif [[ -n "${Script_Force_Color}" ]]; then
Output_Color_Enabled=$TRUE
elif [[ "${Script_Term}" == "dumb" ]]; then
Output_Color_Enabled=$FALSE
else
# Default: enable colors if we have a color-capable terminal
if [[ -t 1 ]] && tput colors >/dev/null 2>&1; then
Output_Color_Enabled=$TRUE
else
Output_Color_Enabled=$FALSE
fi
fi
#----------------------------------------------------------------------
# Interactive Mode Detection
#----------------------------------------------------------------------
# Store previous prompt state for potential rollback
typeset -i Previous_Prompt=$Output_Prompt_Enabled
# First check explicit flags (highest priority)
if (( ${#no_prompt} > 0 )); then
Output_Prompt_Enabled=$FALSE
z_Output debug "parse_Arguments: Output_Prompt_Enabled set to $FALSE due to --no-prompt"
elif (( ${#force_interactive} > 0 )); then
Output_Prompt_Enabled=$TRUE
z_Output debug "parse_Arguments: Output_Prompt_Enabled set to $TRUE due to --interactive"
else
# Default to terminal checks, PS1 is just a hint
if [[ -t 0 && -t 1 ]]; then
Output_Prompt_Enabled=$TRUE
z_Output debug "parse_Arguments: Output_Prompt_Enabled set to $TRUE due to -t checks"
elif [[ -n "${Script_PS1}" ]]; then
Output_Prompt_Enabled=$TRUE
z_Output debug "parse_Arguments: Output_Prompt_Enabled set to $TRUE due to PS1"
else
Output_Prompt_Enabled=$FALSE
z_Output debug "parse_Arguments: Output_Prompt_Enabled set to $FALSE (no terminal or PS1 unset)"
fi
fi
return 0
}
#----------------------------------------------------------------------#
# Function: main
#----------------------------------------------------------------------#
# Description:
# Entry point for the script. Handles environment setup, argument
# parsing, and orchestrates the demonstration of output functions.
# Includes proper error handling and cleanup.
#
# Parameters:
# $@ - Command line arguments passed to the script
#
# Returns:
# - 0 on successful execution
# - 1 on error during setup or execution
# - 2 on invalid arguments
#
# Exit Codes:
# - 0: Success
# - 1: General error
# - 2: Invalid arguments
# - 130: Script interrupted (SIGINT)
# - 143: Script terminated (SIGTERM)
#----------------------------------------------------------------------#
function main {
typeset ExitCode=0
typeset ErrorMsg=""
# Prevent recursive execution
if (( ScriptRunning )); then
z_Output error "Error: Recursive script execution detected"
return 1
fi
ScriptRunning=$TRUE
# Setup error handling and cleanup
trap 'cleanup $TRUE $Output_Verbose_Mode' EXIT
trap 'cleanup $FALSE $Output_Verbose_Mode; exit 130' INT
trap 'cleanup $FALSE $Output_Verbose_Mode; exit 143' TERM
# Initialize environment
if ! setup_Environment; then
ErrorMsg="Failed to initialize environment"
ExitCode=1
z_Output error "${ErrorMsg}"
return $ExitCode
fi
# Parse command line arguments
if ! parse_Arguments "$@"; then
if (( $? == 1 )) && (( ${#help} > 0 )); then
# Help was displayed, exit normally
return 0
fi
ErrorMsg="Failed to parse command line arguments"
ExitCode=2
z_Output error "${ErrorMsg}"
return $ExitCode
fi
# Debug output if enabled
if (( Output_Debug_Mode )); then
z_Output verbose "Starting script execution:" Force=$TRUE
z_Output verbose "- Script path: $ScriptRealFilePath" Force=$TRUE
z_Output verbose "- Arguments: $Cmd_Args_String" Force=$TRUE
z_Output verbose "- Working directory: $PWD" Force=$TRUE
fi
# Run the core functionality
if ! core_functionality; then
ErrorMsg="Output demonstration failed"
ExitCode=1
z_Output error "${ErrorMsg}"
return $ExitCode
fi
# Success
if (( Output_Debug_Mode )); then
z_Output verbose "Script completed successfully" Force=$TRUE
fi
return $ExitCode
}
# Execute main with all arguments
main "$@"
```