VOOZH about

URL: https://deepwiki.com/guanguans/ai-commit/9.1-core-commands-api

⇱ Core Commands API | guanguans/ai-commit | DeepWiki


Loading...
Menu

Core Commands API

This document provides a technical API reference for the core command classes in ai-commit. These classes extend Laravel Zero's Command base class and implement the primary user-facing functionality. This documentation is intended for developers who want to extend ai-commit, integrate it into other tools, or understand the command implementation details.

For information about using these commands as an end user, see User Guide. For architectural details about the command pattern implementation, see Command Architecture. For generator-specific APIs, see Generator Interface API.

Scope: This page documents the public API surface of CommitCommand, ConfigCommand, and ThanksCommand classes, including their methods, options, arguments, and integration points.

Command Class Hierarchy

All commands in ai-commit extend Laravel Zero's Command class, which itself extends Symfony Console's Command. The following diagram maps the command structure to actual code entities:


Sources: app/Commands/CommitCommand.php32-298 app/Commands/ConfigCommand.php30-221 app/Commands/ThanksCommand.php18-44

CommitCommand API

The CommitCommand class is the primary entry point for AI-powered commit message generation. It orchestrates the entire workflow from Git diff retrieval through AI generation to final commit execution.

Class Definition

Namespace: App\Commands
Extends: LaravelZero\Framework\Commands\Command
File: app/Commands/CommitCommand.php32

Constructor

public function __construct(GeneratorManager $generatorManager)

Parameters:

  • $generatorManager (GeneratorManager): Injected dependency for accessing AI generators via driver pattern

Behavior:

  • Resolves ConfigManager from the service container via config('ai-commit')
  • Calls parent constructor to complete Laravel Zero command initialization

Sources: app/Commands/CommitCommand.php41-45

Public Methods

handle()

public function handle(): void

Purpose: Main command execution method implementing the commit message generation pipeline.

Workflow:

  1. Validates Git repository context (git rev-parse --is-inside-work-tree)
  2. Retrieves staged diff content (git diff --cached)
  3. Prompts user for commit type selection
  4. Generates commit message via selected AI generator
  5. Displays message and requests user confirmation
  6. Executes Git commit (unless --dry-run specified)

Throws:

  • RuntimeException: When no cached files are available to commit
  • \Throwable: From underlying Git or AI generator operations

Implementation Pattern: Uses Laravel collection pipeline with tap() for sequential execution phases.

Sources: app/Commands/CommitCommand.php52-105

complete()

public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void

Purpose: Provides shell completion suggestions for command options.

Parameters:

  • $input (CompletionInput): Current completion context
  • $suggestions (CompletionSuggestions): Output suggestions container

Completion Support:

  • --generator: Suggests available generator names from configuration
  • --prompt: Suggests available prompt template names from configuration

Sources: app/Commands/CommitCommand.php113-124

Protected Methods

configure()

protected function configure(): void

Purpose: Defines command signature, arguments, and options programmatically.

Registered Arguments:

ArgumentModeDescriptionDefault
pathOptionalWorking directory for Git operationsConfigManager::localPath('')

Registered Options:

OptionShortcutModeDescriptionDefault Source
--commit-options-ArrayAdditional options for git commitcommit_options config
--diff-options-ArrayAdditional options for git diffdiff_options config
--generator-gRequiredAI generator namegenerator config
--prompt-pRequiredPrompt template nameprompt config
--no-edit-FlagDisable commit message editing-
--no-verify-FlagSkip Git commit hooks-
--config-cOptionalCustom config file path-
--dry-run-FlagGenerate message without committing-
--diff-OptionalProvide diff content directly-

Sources: app/Commands/CommitCommand.php132-190

initialize()

protected function initialize(InputInterface $input, OutputInterface $output): void

Purpose: Pre-execution initialization hook called before handle().

Behavior:

  • If --config option provided, loads specified config file and overrides input options with values from config
  • Maps config keys (commit_options, diff_options, generator, prompt) to their corresponding command options

Sources: app/Commands/CommitCommand.php198-216

Private Methods

The following private methods support internal command operation:

diffCommand()

private function diffCommand(): array

Returns: array - Command array for git diff execution including --cached flag and configured diff options.

Sources: app/Commands/CommitCommand.php218-221

commitCommandFor()

private function commitCommandFor(string $message): array

Parameters:

  • $message (string): Commit message to use

Returns: array - Command array for git commit execution with message and additional options.

Logic:

  • Appends --no-edit if editing disabled or TTY unavailable
  • Appends --no-verify if hook verification disabled
  • Merges with configured commit options

Sources: app/Commands/CommitCommand.php226-234

promptFor()

private function promptFor(string $cachedDiff, string $type): string

Parameters:

  • $cachedDiff (string): Git diff content
  • $type (string): Selected commit type

Returns: string - Fully constructed prompt with placeholders replaced.

Placeholder Replacements:

  • <type> → Selected commit type (or cleared if auto)
  • <type-prompt> → Type-specific instruction (or cleared if auto)
  • <diff> → Staged changes content

Sources: app/Commands/CommitCommand.php236-254

createProcess()

private function createProcess(
 array $command,
 ?string $cwd = null,
 ?array $env = null,
 mixed $input = null,
 ?float $timeout = 60
): Process

Purpose: Factory method for creating Symfony Process instances with debugging support.

Parameters:

  • $command (array): Command and arguments
  • $cwd (?string): Working directory (defaults to path argument)
  • $env (?array): Environment variables
  • $input (mixed): Process input
  • $timeout (?float): Execution timeout in seconds

Returns: Symfony\Component\Process\Process

Sources: app/Commands/CommitCommand.php268-282

shouldntEdit() / shouldEdit()

private function shouldntEdit(): bool
private function shouldEdit(): bool

Logic: Returns true if commit message editing should be disabled based on:

  • TTY support availability
  • --no-edit option
  • no_edit configuration value

Sources: app/Commands/CommitCommand.php284-292

shouldntVerify()

private function shouldntVerify(): bool

Logic: Returns true if Git commit hooks should be bypassed based on:

  • --no-verify option
  • no_verify configuration value

Sources: app/Commands/CommitCommand.php294-297

Command Execution Flow

CommitCommand::handle() lifecycle — from invocation to git commit


Sources: app/Commands/CommitCommand.php52-105

ConfigCommand API

The ConfigCommand class provides a comprehensive CLI interface for managing ai-commit configuration files. It supports six operations (set, get, unset, reset, list, edit) across multiple configuration scopes (global, local, custom).

Class Definition

Namespace: App\Commands
Extends: LaravelZero\Framework\Commands\Command
File: app/Commands/ConfigCommand.php30

Constants

private const ACTIONS = ['set', 'get', 'unset', 'reset', 'list', 'edit'];
private const UNIX_EDITORS = ['editor', 'vim', 'vi', 'nano', 'pico', 'ed'];
private const WINDOWS_EDITORS = ['notepad'];

Sources: app/Commands/ConfigCommand.php32-34

Constructor

public function __construct()

Behavior:

  • Resolves ConfigManager from service container via config('ai-commit')
  • Calls parent constructor

Sources: app/Commands/ConfigCommand.php43-47

Public Methods

handle()

public function handle(): int

Purpose: Executes the requested configuration operation.

Returns: int - Exit code (self::SUCCESS or self::FAILURE)

Throws:

  • \Illuminate\Contracts\Filesystem\FileNotFoundException
  • \JsonException
  • UnsupportedConfigActionException: When action is not in ACTIONS list

Operation Dispatch Table:

ActionArguments RequiredBehavior
setkey, valueSets configuration key to value, persists to file
getkey (optional)Outputs value for key, or entire config as JSON if no key
unsetkeyRemoves configuration key, persists to file
resetkey (optional)Restores key (or all config) from default PHP config
list-Displays all configuration as dot-notation key-value pairs
edit-Opens configuration file in text editor

Sources: app/Commands/ConfigCommand.php55-114

complete()

public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void

Purpose: Provides shell completion suggestions.

Completion Support:

  • action argument: Suggests action names from ACTIONS
  • key argument: Suggests configuration keys from current config
  • --editor option: Suggests editor names from UNIX_EDITORS

Sources: app/Commands/ConfigCommand.php122-139

hydratedActions()

public static function hydratedActions(): string

Purpose: Returns comma-separated string of available actions for help text.

Returns: string - Example: "set, get, unset, reset, list, edit"

Sources: app/Commands/ConfigCommand.php141-144

Protected Methods

configure()

protected function configure(): void

Registered Arguments:

ArgumentModeDescription
actionRequiredAction name (set, get, unset, reset, list, edit)
keyOptionalConfiguration key in dot notation
valueOptionalConfiguration value for set operation

Registered Options:

OptionShortcutModeDescription
--global-gFlagOperate on global config file
--file-fOptionalSpecify custom config file path
--editor-eOptionalSpecify text editor for edit action

Sources: app/Commands/ConfigCommand.php152-162

initialize()

protected function initialize(InputInterface $input, OutputInterface $output): void

Purpose: Ensures global configuration file exists before command execution.

Behavior: Creates global config directory and file if not present via ConfigManager::putGlobal().

Sources: app/Commands/ConfigCommand.php170-175

Private Methods

configFile()

private function configFile(): string

Purpose: Determines which configuration file to operate on based on options.

Returns: string - Absolute file path

Resolution Order:

  1. --file option value (if provided)
  2. ConfigManager::globalPath() (if --global flag set)
  3. ConfigManager::localPath() (default)

Sources: app/Commands/ConfigCommand.php177-188

editor()

private function editor(): string

Purpose: Determines which text editor to use for edit action.

Returns: string - Editor command name

Throws: RuntimeException - If no editor found

Resolution Logic:

  1. Returns --editor option value if provided
  2. Searches for first available editor in platform-specific list:
    • Unix: UNIX_EDITORS array
    • Windows: WINDOWS_EDITORS array
  3. Uses ExecutableFinder to verify editor availability in $PATH

Sources: app/Commands/ConfigCommand.php190-205

argToValue()

private function argToValue(string $arg): mixed

Purpose: Converts CLI argument string to appropriate PHP type.

Parameters:

  • $arg (string): Input argument

Returns: mixed - Decoded value (if valid JSON) or original string

Throws: \JsonException

Sources: app/Commands/ConfigCommand.php210-213

valueToArg()

private function valueToArg(mixed $value): string

Purpose: Converts PHP value to CLI output string.

Parameters:

  • $value (mixed): Configuration value

Returns: string - JSON-encoded string (for non-string types) or original string

Sources: app/Commands/ConfigCommand.php215-220

Configuration Scope Resolution


Sources: app/Commands/ConfigCommand.php55-114

ThanksCommand API

A simple utility command that prompts users to star the GitHub repository.

Class Definition

Namespace: App\Commands
Extends: LaravelZero\Framework\Commands\Command
File: app/Commands/ThanksCommand.php18

Public Methods

handle()

public function handle(): void

Purpose: Interactive prompt encouraging GitHub repository engagement.

Behavior:

  1. Asks user if they want to star the repository
  2. If user responds "yes" or "y", opens browser to GitHub repository URL using platform-specific command:
    • macOS: open
    • Windows: start
    • Linux/other: xdg-open
  3. Displays repository URL in console output

Sources: app/Commands/ThanksCommand.php26-43

Command Registration and Discovery

Commands are automatically discovered by Laravel Zero through the app/Commands namespace. The application bootstrap process scans this directory and registers all classes extending Command.


Sources: app/Commands/CommitCommand.php32 app/Commands/ConfigCommand.php30 app/Commands/ThanksCommand.php18

Integration Points for Extension

Developers extending ai-commit can hook into the command layer through several mechanisms:

Custom Command Creation

New commands are created by extending LaravelZero\Framework\Commands\Command, placing the class in app/Commands/, and defining $signature and $description properties along with a handle() method. See app/Commands/ThanksCommand.php18-44 for a minimal example, and app/Commands/CommitCommand.php32-45 for an example with constructor injection.

Commands automatically gain access to:

  • Laravel's service container via $this->laravel
  • Configuration via config() helper
  • All Laravel Zero console helpers (ask(), confirm(), choice(), etc.)

Dependency Injection

Commands support constructor injection for type-hinted dependencies:

  • GeneratorManager: Access to AI generator drivers
  • ConfigManager: Configuration management
  • Any custom service registered in service providers

Example: app/Commands/CommitCommand.php41 demonstrates GeneratorManager injection.

Command Options and Configuration

New options can be added to existing commands through:

  1. Option Registration: Add to configure() method
  2. Configuration Keys: Define defaults in config/ai-commit.php
  3. Option Resolution: Access via $this->option('name')

Process Execution Helpers

The createProcess() pattern in CommitCommand provides a reusable template for executing shell commands with debugging support:

Pattern: app/Commands/CommitCommand.php268-282

Key features:

  • Automatic working directory resolution
  • Debug output when --verbose flag active
  • Timeout configuration
  • TTY support detection

Command Lifecycle Hooks

All commands follow the Symfony Console component lifecycle:


Implementation Examples:

Sources: app/Commands/CommitCommand.php app/Commands/ConfigCommand.php

Error Handling and Exit Codes

Commands return integer exit codes following Unix conventions:

ConstantValueMeaning
self::SUCCESS0Successful execution
self::FAILURE1Generic failure
self::INVALID2Invalid input/usage

Exception Handling:

  • CommitCommand::handle() throws exceptions up to Laravel Zero's exception handler
  • ConfigCommand::handle() catches and returns FAILURE exit code for validation errors
  • Uncaught exceptions are logged and displayed with stack traces in verbose mode

Sources: app/Commands/ConfigCommand.php55-114

Refresh this wiki

On this page