VOOZH about

URL: https://deepwiki.com/guanguans/ai-commit/9-api-reference

⇱ API Reference | guanguans/ai-commit | DeepWiki


Loading...
Menu

API Reference

This section documents the public interfaces, methods, and contracts of the core classes that make up the ai-commit codebase. It is intended for developers who need to extend, integrate with, or understand the internals of ai-commit.

The API is organized into three subsections:

For end-user usage documentation, see User Guide (3). For architectural patterns, see Architecture Deep Dive (4). For implementing custom generators, see Adding New Generators (5.4).


API Component Overview

ai-commit's programmatic API is organized into three layers:

Command Layer

Implements the CLI interface via Laravel Zero's console framework. Both commands extend LaravelZero\Framework\Commands\Command.

ClassFileRole
CommitCommandapp/Commands/CommitCommand.php32diff → type selection → AI generation → git commit
ConfigCommandapp/Commands/ConfigCommand.php30CRUD over ~/.ai-commit/.ai-commit.json and .ai-commit.json
ThanksCommandapp/Commands/ThanksCommand.phpShows sponsorship/acknowledgment output

Generator Layer

Implements the driver pattern for AI service abstraction. All generators implement GeneratorContract.

ClassFileRole
GeneratorManagerapp/GeneratorManager.php32Driver factory; resolves class names from config keys
GeneratorContractapp/Contracts/GeneratorContract.phpInterface: generate(string): string
AbstractGeneratorapp/Generators/AbstractGenerator.php28Base class: process execution, output, option hydration

Configuration Layer

Manages hierarchical settings with JSON file persistence.

ClassFileRole
ConfigManagerapp/ConfigManager.php39Extends Illuminate\Config\Repository; merges defaults → global → local

Class Hierarchy Diagram

The diagram below maps the full class hierarchy across all three layers, including concrete generator implementations.


Sources: app/Commands/CommitCommand.php32-298 app/Commands/ConfigCommand.php30-221 app/GeneratorManager.php32-78 app/ConfigManager.php39-270 app/Generators/AbstractGenerator.php28-106 app/Generators/OpenAIChatGenerator.php16-52 app/Generators/OpenAIGenerator.php app/Generators/ErnieBotGenerator.php app/Generators/BitoCliGenerator.php


Full Class Reference

ClassLocationKindPurpose
CommitCommandapp/Commands/CommitCommand.php32CommandOrchestrates commit workflow
ConfigCommandapp/Commands/ConfigCommand.php30CommandConfig CRUD (set/get/unset/reset/list/edit)
ThanksCommandapp/Commands/ThanksCommand.phpCommandSponsorship output
GeneratorManagerapp/GeneratorManager.php32ManagerDriver factory for generators
GeneratorContractapp/Contracts/GeneratorContract.phpInterfacegenerate(string): string contract
AbstractGeneratorapp/Generators/AbstractGenerator.php28AbstractProcess execution and option hydration
OpenAIGeneratorapp/Generators/OpenAIGenerator.phpGeneratorOpenAI Completions API
OpenAIChatGeneratorapp/Generators/OpenAIChatGenerator.php16GeneratorOpenAI Chat Completions API
MoonshotGeneratorapp/Generators/MoonshotGenerator.phpGeneratorMoonshot (Kimi) AI API
ErnieBotGeneratorapp/Generators/ErnieBotGenerator.phpGeneratorBaidu ERNIE Bot API
ErnieBotTurboGeneratorapp/Generators/ErnieBotTurboGenerator.phpGeneratorERNIE Bot Turbo variant
BitoCliGeneratorapp/Generators/BitoCliGenerator.phpGeneratorBito CLI binary
GithubCopilotCliGeneratorapp/Generators/GithubCopilotCliGenerator.phpGeneratorGitHub Copilot CLI binary
GithubModelsCliGeneratorapp/Generators/GithubModelsCliGenerator.phpGeneratorGitHub Models CLI binary
ConfigManagerapp/ConfigManager.php39RepositoryMulti-layer config with JSON persistence

Sources: app/Commands/CommitCommand.php32 app/Commands/ConfigCommand.php30 app/GeneratorManager.php32 app/Contracts/GeneratorContract.php app/Generators/AbstractGenerator.php28 app/ConfigManager.php39


API Interaction Flow

The following sequence diagram shows how the three API layers interact during a typical commit command execution.


Sources: app/Commands/CommitCommand.php52-105 app/GeneratorManager.php63-77 app/Generators/OpenAIChatGenerator.php28-41 app/ConfigManager.php62-80


Extension Points Summary

Custom Generator Registration

Use GeneratorManager::extend() (inherited from Illuminate\Support\Manager) to register a custom driver without modifying config/ai-commit.php:

app(GeneratorManager::class)->extend('custom_ai', function ($app, $config) {
 return new CustomAIGenerator(new Repository($config));
});

The closure receives the application container and the generator config array. It must return an instance implementing GeneratorContract.

Sources: app/GeneratorManager.php32-78

Configuration Programmatic Access

ConfigManager::makeFrom() loads and merges one or more files (.php or .json) in order:

$config = ConfigManager::makeFrom('/path/to/base.php', '/path/to/override.json');

Sources: app/ConfigManager.php85-88

Process Output Customization

Override runningCallback() in a subclass of AbstractGenerator to intercept process stdout/stderr:

protected function runningCallback(): callable
{
 return function (string $type, string $data): void {
 // $type is either Process::OUT or Process::ERR
 $this->customLogger->log($type, $data);
 };
}

Sources: app/Generators/AbstractGenerator.php82-87 </old_str>

<old_str>

CommitCommand API

The CommitCommand class orchestrates the AI-powered commit message generation workflow.

Constructor


Accepts a GeneratorManager instance via dependency injection. The ConfigManager is initialized from the ai-commit configuration.

Location: app/Commands/CommitCommand.php41-45

Public Methods

handle(): void

Executes the commit command workflow with the following pipeline:

  1. Validates Git repository context
  2. Retrieves staged changes via git diff --cached
  3. Prompts user for commit type selection
  4. Generates commit message using configured AI generator
  5. Displays message and requests user confirmation
  6. Executes git commit or regenerates on rejection

Throws: RuntimeException when no cached files exist for commit

Location: app/Commands/CommitCommand.php52-105

complete(CompletionInput, CompletionSuggestions): void

Provides shell completion suggestions for command options:

  • --generator option: suggests available generator names from configuration
  • --prompt option: suggests available prompt template names

Location: app/Commands/CommitCommand.php113-124

Command Configuration

The command defines these input options via configure():

OptionShortcutTypeDefaultDescription
path-ArgumentConfigManager::localPath('')Working directory path
--commit-options-Arrayconfig('commit_options')Options passed to git commit
--diff-options-Arrayconfig('diff_options')Options passed to git diff
--generator-gStringconfig('generator')Generator name to use
--prompt-pStringconfig('prompt')Prompt template name
--no-edit-FlagfalseDisable commit message editing
--no-verify-FlagfalseSkip Git hooks
--config-cStringnullCustom config file path
--dry-run-FlagfalseGenerate message without committing
--diff-StringnullUse provided diff instead of git diff

Location: app/Commands/CommitCommand.php132-190

Private Helper Methods

diffCommand(): array

Constructs the Git diff command array: ['git', 'diff', '--cached', ...diffOptions]

commitCommandFor(string $message): array

Builds the Git commit command with conditional --no-edit and --no-verify flags based on configuration and TTY support.

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

Assembles the AI prompt by replacing placeholders in the template:

  • <diff> → staged changes content
  • <type> → selected commit type
  • <type-prompt> → formatted type instruction

Returns empty type prompt when 'auto' is selected (first option).

Location: app/Commands/CommitCommand.php236-254

createProcess(array $command, ...): Process

Factory method for creating Symfony\Component\Process\Process instances with debug output support.

Location: app/Commands/CommitCommand.php268-282

Sources: app/Commands/CommitCommand.php1-299

ConfigCommand API

The ConfigCommand class provides programmatic access to configuration management operations.

Actions Support


Sources: app/Commands/ConfigCommand.php30-221

Constructor


Initializes ConfigManager from the ai-commit configuration. No dependencies injected.

Location: app/Commands/ConfigCommand.php43-47

Public Methods

handle(): int

Executes the requested configuration action. Returns Command::SUCCESS (0) or Command::FAILURE (1).

Workflow:

  1. Determines target file via configFile() (respects --global, --file options)
  2. Ensures file exists, creates if necessary
  3. Loads configuration from file
  4. Executes action (set/get/unset/reset/list/edit)
  5. Persists changes for write operations

Throws: UnsupportedConfigActionException for invalid actions

Location: app/Commands/ConfigCommand.php55-114

complete(CompletionInput, CompletionSuggestions): void

Provides shell completion:

  • action argument: suggests ['set', 'get', 'unset', 'reset', 'list', 'edit']
  • key argument: suggests all configuration keys in dot notation
  • --editor option: suggests Unix/Windows editor names

Location: app/Commands/ConfigCommand.php122-139

hydratedActions(): string (static)

Returns comma-separated list of supported actions for display: "set, get, unset, reset, list, edit"

Location: app/Commands/ConfigCommand.php141-144

Command Arguments and Options

ParameterTypeRequiredDescription
actionArgumentYesOperation name (set/get/unset/reset/list/edit)
keyArgumentNoConfiguration key in dot notation
valueArgumentNoValue to set (for set action)
--global / -gFlagNoApply to global config file
--file / -fStringNoApply to specified config file
--editor / -eStringNoSpecify text editor for edit action

Location: app/Commands/ConfigCommand.php152-162

Private Helper Methods

configFile(): string

Returns target configuration file path based on options precedence:

  1. --file option value
  2. Global path if --global flag set
  3. Local path (default)

editor(): string

Resolves text editor binary for edit action:

  1. Returns --editor option if provided
  2. Searches for Unix editors: ['editor', 'vim', 'vi', 'nano', 'pico', 'ed']
  3. Searches for Windows editors: ['notepad']

Throws: RuntimeException if no editor found

Location: app/Commands/ConfigCommand.php190-205

argToValue(string $arg): mixed

Converts string argument to typed value. Decodes JSON strings, returns plain strings otherwise.

valueToArg(mixed $value): string

Converts typed value to string representation. Encodes non-strings as JSON with ConfigManager::JSON_OPTIONS.

Location: app/Commands/ConfigCommand.php210-220

Sources: app/Commands/ConfigCommand.php1-222

GeneratorManager API

The GeneratorManager implements the driver pattern for instantiating AI generators.

Class Hierarchy


Sources: app/GeneratorManager.php32-78

Public Methods

getDefaultDriver(): string

Returns the default generator name from configuration: config('ai-commit.generator')

Location: app/GeneratorManager.php41-44

generator(?string $generator = null): GeneratorContract

Alias for driver(). Returns generator instance for the specified name, or default if null.

Location: app/GeneratorManager.php46-49

generate(string $prompt): string

Convenience method that generates a commit message using the default generator. Equivalent to:


Location: app/GeneratorManager.php51-54

Protected Methods

createDriver(mixed $driver): GeneratorContract

Factory method that instantiates generator instances. Resolution algorithm:

  1. Check for custom creators via extend()
  2. Load generator configuration from config("ai-commit.generators.$driver")
  3. Extract driver key from config (defaults to $driver parameter)
  4. Convert driver name to studly case class name (special case: openaiOpenAI)
  5. Attempt to instantiate App\Generators\{StudlyName}Generator
  6. Pass Repository wrapper of generator config to constructor

Example Resolution:

  • Driver: openai_chat
  • Config: config('ai-commit.generators.openai_chat.driver')'openai_chat'
  • Class: App\Generators\OpenAIChatGenerator

Throws: InvalidArgumentException if class doesn't exist

Location: app/GeneratorManager.php63-77

Sources: app/GeneratorManager.php1-79

AbstractGenerator API

Base class providing common functionality for all generator implementations.

Constructor


Accepts generator-specific configuration as Illuminate\Config\Repository. Initializes:

  • $this->output: Cloned OutputStyle with debug verbosity for logging
  • $this->helperSet: Helper set from Laravel Artisan for process execution

Location: app/Generators/AbstractGenerator.php36-40

Protected Properties

PropertyTypeDescription
$configRepositoryGenerator-specific configuration from generators.{name}
$outputOutputStyleConsole output interface with debug verbosity
$helperSetHelperSetSymfony console helpers for process execution

Location: app/Generators/AbstractGenerator.php30-31

Protected Helper Methods

mustRunProcess(): Process

Executes a process and throws ProcessFailedException on non-zero exit code.


Parameters:

  • $cmd: Command as array, Process instance, or shell command string
  • $error: Error message to display on failure
  • $callback: Callback invoked with process output (type, data)
  • $verbosity: Minimum verbosity level for output
  • $output: Output interface (defaults to $this->output)

Location: app/Generators/AbstractGenerator.php42-56

runProcess(): Process

Executes a process without throwing on failure. Same signature as mustRunProcess().

Converts string commands to Process instances via Process::fromShellCommandline(). Delegates execution to ProcessHelper::run().

Location: app/Generators/AbstractGenerator.php58-70

getHelper(string $name): HelperInterface

Returns Symfony console helper by name. Typically used to retrieve ProcessHelper.

Throws: InvalidArgumentException if helper not registered

Location: app/Generators/AbstractGenerator.php77-80

runningCallback(): callable

Returns default callback for process output:

  • Process::OUT: Writes to output normally
  • Process::ERR: Writes with red color (<fg=red>)

Location: app/Generators/AbstractGenerator.php82-87

ensureWithOptions(array $command): array

Appends hydrated options to command array: [...$command, ...$this->hydratedOptions()]

Useful for CLI-based generators to merge configured options.

Location: app/Generators/AbstractGenerator.php89-92

hydratedOptions(): array

Converts config('options') associative array into flat command-line arguments list.

Example:


Filters out null values and empty strings.

Location: app/Generators/AbstractGenerator.php97-105

Sources: app/Generators/AbstractGenerator.php1-107

GeneratorContract Interface

The core contract all generators must implement.


Method Contract


Accepts a prompt string (containing diff, commit type, and instructions) and returns a generated commit message string.

Contract Requirements:

  • Must accept any non-empty prompt string
  • Should return sanitized, plain text commit message
  • May throw RequestException, ConnectionException, or ProcessFailedException
  • Should handle streaming responses if supported by AI service
  • Must strip API response wrappers (JSON, markdown code blocks, etc.)

Example Implementation Pattern:


Sources: app/Generators/OpenAIChatGenerator.php28-41 app/Generators/AbstractGenerator.php28

ConfigManager API

The ConfigManager extends Laravel's Repository to provide multi-layer configuration management with persistence.

Static Factory Methods

load(): ConfigManager

Creates a ConfigManager instance and registers it as config('ai-commit').

Returns: New ConfigManager instance loaded from all available sources

Location: app/ConfigManager.php62-65

make(?array $items = null): ConfigManager

Creates a ConfigManager instance from provided items or default configuration cascade.

Cascade Order (if $items is null):

  1. config/ai-commit.php (default)
  2. ~/.ai-commit/.ai-commit.json (global, if exists)
  3. ./.ai-commit.json (local, if exists)

Location: app/ConfigManager.php70-80

makeFrom(string ...$files): ConfigManager

Creates instance by loading and merging specified configuration files.

Parameters: Variable number of file paths (PHP or JSON)

Location: app/ConfigManager.php85-88

globalPath(): string

Returns global configuration file path:

  • Windows: C:\Users\{username}\.ai-commit\.ai-commit.json
  • Unix: ~/.ai-commit/.ai-commit.json

Location: app/ConfigManager.php90-95

localPath(string $path = '.ai-commit.json'): string

Returns local configuration file path relative to current working directory.

Default: ./.ai-commit.json

Location: app/ConfigManager.php97-106

Instance Methods

putGlobal(int $options = JSON_OPTIONS): bool|int

Persists current configuration to global file with JSON encoding.

Returns: Number of bytes written or false on failure

Location: app/ConfigManager.php111-114

putLocal(int $options = JSON_OPTIONS): bool|int

Persists current configuration to local file.

Location: app/ConfigManager.php119-122

putFile(string $file, int $options = JSON_OPTIONS): bool|int

Persists configuration to specified file. Filters out non-serializable objects before writing:

Excluded Keys:

  • generators.*.parameters.messages
  • generators.*.parameters.prompt
  • generators.*.parameters.user
  • Any object values not implementing JsonSerializable, Arrayable, or Jsonable

Creates parent directory if not exists.

Location: app/ConfigManager.php127-163

replaceFrom(string $file): ConfigManager

Loads configuration from file and merges it recursively into current instance using array_replace_recursive.

Location: app/ConfigManager.php168-171

replace(array $items): ConfigManager

Merges provided array recursively into current configuration.

Location: app/ConfigManager.php176-181

forget(mixed $keys): ConfigManager

Removes specified keys from configuration. Accepts single key or array of keys in dot notation.

Example: $config->forget(['generators.openai.api_key', 'prompt'])

Location: app/ConfigManager.php188-193

toDotArray(): array

Converts configuration to flat array with dot-notation keys.

Example Output:


Location: app/ConfigManager.php224-227

toArray(): array

Converts configuration to nested array, recursively converting Arrayable instances.

Location: app/ConfigManager.php232-235

toJson(mixed $options = JSON_OPTIONS): string

Serializes configuration to JSON string.

Default Options: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR

Location: app/ConfigManager.php244-247

Configuration File Format

The ConfigManager supports two file formats:

ExtensionHandlerUse Case
.phprequireShipped defaults (config/ai-commit.php)
.jsonFile::json()User configuration (global/local)

Sources: app/ConfigManager.php252-269

Constants

ConstantValuePurpose
BASE_NAME.ai-commit.jsonDefault config filename
BASE_DIRNAME.ai-commitGlobal config directory name
JSON_OPTIONSSee aboveDefault JSON encoding flags

Location: app/ConfigManager.php47-49

Sources: app/ConfigManager.php1-271

Configuration Structure Reference

The following diagram shows the complete configuration structure with array keys that can be accessed via ConfigManager:


Access Examples:


Sources: config/ai-commit.php14-260

Method Call Flow Example

The following sequence diagram illustrates how the APIs interact during commit message generation:


Sources: app/Commands/CommitCommand.php52-105 app/GeneratorManager.php63-77 app/Generators/OpenAIChatGenerator.php28-41

Return Type Reference

Key return types for API methods:

MethodReturn TypeNullableDescription
ConfigManager::load()ConfigManagerNoNew instance
ConfigManager::make()ConfigManagerNoNew or configured instance
ConfigManager::globalPath()stringNoAbsolute path
ConfigManager::putGlobal()bool|intNoBytes written or false
ConfigManager::toJson()stringNoJSON string
GeneratorManager::generator()GeneratorContractNoGenerator instance
GeneratorManager::generate()stringNoGenerated message
AbstractGenerator::mustRunProcess()ProcessNoSuccessful process
GeneratorContract::generate()stringNoCommit message
CommitCommand::handle()void-No return
ConfigCommand::handle()intNoExit code (0 or 1)

Sources: app/ConfigManager.php62-247 app/GeneratorManager.php41-54 app/Generators/AbstractGenerator.php42-70

Extension Points

Developers can extend ai-commit functionality through these interfaces:

Custom Generator Registration


The custom generator must implement GeneratorContract::generate(string): string.

Sources: app/GeneratorManager.php32-78

Configuration Override


Sources: app/ConfigManager.php62-88

Process Execution Hooks

Extend AbstractGenerator and override runningCallback() to customize process output handling:


Sources: app/Generators/AbstractGenerator.php82-87

CommitCommand API

The CommitCommand class orchestrates the AI-powered commit message generation workflow.

Constructor


Accepts a GeneratorManager instance via dependency injection. The ConfigManager is initialized from the ai-commit configuration.

Location: app/Commands/CommitCommand.php41-45

Public Methods

handle(): void

Executes the commit command workflow with the following pipeline:

  1. Validates Git repository context
  2. Retrieves staged changes via git diff --cached
  3. Prompts user for commit type selection
  4. Generates commit message using configured AI generator
  5. Displays message and requests user confirmation
  6. Executes git commit or regenerates on rejection

Throws: RuntimeException when no cached files exist for commit

Location: app/Commands/CommitCommand.php52-105

complete(CompletionInput, CompletionSuggestions): void

Provides shell completion suggestions for command options:

  • --generator option: suggests available generator names from configuration
  • --prompt option: suggests available prompt template names

Location: app/Commands/CommitCommand.php113-124

Command Configuration

The command defines these input options via configure():

OptionShortcutTypeDefaultDescription
path-ArgumentConfigManager::localPath('')Working directory path
--commit-options-Arrayconfig('commit_options')Options passed to git commit
--diff-options-Arrayconfig('diff_options')Options passed to git diff
--generator-gStringconfig('generator')Generator name to use
--prompt-pStringconfig('prompt')Prompt template name
--no-edit-FlagfalseDisable commit message editing
--no-verify-FlagfalseSkip Git hooks
--config-cStringnullCustom config file path
--dry-run-FlagfalseGenerate message without committing
--diff-StringnullUse provided diff instead of git diff

Location: app/Commands/CommitCommand.php132-190

Private Helper Methods

diffCommand(): array

Constructs the Git diff command array: ['git', 'diff', '--cached', ...diffOptions]

commitCommandFor(string $message): array

Builds the Git commit command with conditional --no-edit and --no-verify flags based on configuration and TTY support.

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

Assembles the AI prompt by replacing placeholders in the template:

  • <diff> → staged changes content
  • <type> → selected commit type
  • <type-prompt> → formatted type instruction

Returns empty type prompt when 'auto' is selected (first option).

Location: app/Commands/CommitCommand.php236-254

createProcess(array $command, ...): Process

Factory method for creating Symfony\Component\Process\Process instances with debug output support.

Location: app/Commands/CommitCommand.php268-282

Sources: app/Commands/CommitCommand.php1-299

ConfigCommand API

The ConfigCommand class provides programmatic access to configuration management operations.

Actions Support


Sources: app/Commands/ConfigCommand.php30-221

Constructor


Initializes ConfigManager from the ai-commit configuration. No dependencies injected.

Location: app/Commands/ConfigCommand.php43-47

Public Methods

handle(): int

Executes the requested configuration action. Returns Command::SUCCESS (0) or Command::FAILURE (1).

Workflow:

  1. Determines target file via configFile() (respects --global, --file options)
  2. Ensures file exists, creates if necessary
  3. Loads configuration from file
  4. Executes action (set/get/unset/reset/list/edit)
  5. Persists changes for write operations

Throws: UnsupportedConfigActionException for invalid actions

Location: app/Commands/ConfigCommand.php55-114

complete(CompletionInput, CompletionSuggestions): void

Provides shell completion:

  • action argument: suggests ['set', 'get', 'unset', 'reset', 'list', 'edit']
  • key argument: suggests all configuration keys in dot notation
  • --editor option: suggests Unix/Windows editor names

Location: app/Commands/ConfigCommand.php122-139

hydratedActions(): string (static)

Returns comma-separated list of supported actions for display: "set, get, unset, reset, list, edit"

Location: app/Commands/ConfigCommand.php141-144

Command Arguments and Options

ParameterTypeRequiredDescription
actionArgumentYesOperation name (set/get/unset/reset/list/edit)
keyArgumentNoConfiguration key in dot notation
valueArgumentNoValue to set (for set action)
--global / -gFlagNoApply to global config file
--file / -fStringNoApply to specified config file
--editor / -eStringNoSpecify text editor for edit action

Location: app/Commands/ConfigCommand.php152-162

Private Helper Methods

configFile(): string

Returns target configuration file path based on options precedence:

  1. --file option value
  2. Global path if --global flag set
  3. Local path (default)

editor(): string

Resolves text editor binary for edit action:

  1. Returns --editor option if provided
  2. Searches for Unix editors: ['editor', 'vim', 'vi', 'nano', 'pico', 'ed']
  3. Searches for Windows editors: ['notepad']

Throws: RuntimeException if no editor found

Location: app/Commands/ConfigCommand.php190-205

argToValue(string $arg): mixed

Converts string argument to typed value. Decodes JSON strings, returns plain strings otherwise.

valueToArg(mixed $value): string

Converts typed value to string representation. Encodes non-strings as JSON with ConfigManager::JSON_OPTIONS.

Location: app/Commands/ConfigCommand.php210-220

Sources: app/Commands/ConfigCommand.php1-222

GeneratorManager API

The GeneratorManager implements the driver pattern for instantiating AI generators.

Class Hierarchy


Sources: app/GeneratorManager.php32-78

Public Methods

getDefaultDriver(): string

Returns the default generator name from configuration: config('ai-commit.generator')

Location: app/GeneratorManager.php41-44

generator(?string $generator = null): GeneratorContract

Alias for driver(). Returns generator instance for the specified name, or default if null.

Location: app/GeneratorManager.php46-49

generate(string $prompt): string

Convenience method that generates a commit message using the default generator. Equivalent to:


Location: app/GeneratorManager.php51-54

Protected Methods

createDriver(mixed $driver): GeneratorContract

Factory method that instantiates generator instances. Resolution algorithm:

  1. Check for custom creators via extend()
  2. Load generator configuration from config("ai-commit.generators.$driver")
  3. Extract driver key from config (defaults to $driver parameter)
  4. Convert driver name to studly case class name (special case: openaiOpenAI)
  5. Attempt to instantiate App\Generators\{StudlyName}Generator
  6. Pass Repository wrapper of generator config to constructor

Example Resolution:

  • Driver: openai_chat
  • Config: config('ai-commit.generators.openai_chat.driver')'openai_chat'
  • Class: App\Generators\OpenAIChatGenerator

Throws: InvalidArgumentException if class doesn't exist

Location: app/GeneratorManager.php63-77

Sources: app/GeneratorManager.php1-79

AbstractGenerator API

Base class providing common functionality for all generator implementations.

Constructor


Accepts generator-specific configuration as Illuminate\Config\Repository. Initializes:

  • $this->output: Cloned OutputStyle with debug verbosity for logging
  • $this->helperSet: Helper set from Laravel Artisan for process execution

Location: app/Generators/AbstractGenerator.php36-40

Protected Properties

PropertyTypeDescription
$configRepositoryGenerator-specific configuration from generators.{name}
$outputOutputStyleConsole output interface with debug verbosity
$helperSetHelperSetSymfony console helpers for process execution

Location: app/Generators/AbstractGenerator.php30-31

Protected Helper Methods

mustRunProcess(): Process

Executes a process and throws ProcessFailedException on non-zero exit code.


Parameters:

  • $cmd: Command as array, Process instance, or shell command string
  • $error: Error message to display on failure
  • $callback: Callback invoked with process output (type, data)
  • $verbosity: Minimum verbosity level for output
  • $output: Output interface (defaults to $this->output)

Location: app/Generators/AbstractGenerator.php42-56

runProcess(): Process

Executes a process without throwing on failure. Same signature as mustRunProcess().

Converts string commands to Process instances via Process::fromShellCommandline(). Delegates execution to ProcessHelper::run().

Location: app/Generators/AbstractGenerator.php58-70

getHelper(string $name): HelperInterface

Returns Symfony console helper by name. Typically used to retrieve ProcessHelper.

Throws: InvalidArgumentException if helper not registered

Location: app/Generators/AbstractGenerator.php77-80

runningCallback(): callable

Returns default callback for process output:

  • Process::OUT: Writes to output normally
  • Process::ERR: Writes with red color (<fg=red>)

Location: app/Generators/AbstractGenerator.php82-87

ensureWithOptions(array $command): array

Appends hydrated options to command array: [...$command, ...$this->hydratedOptions()]

Useful for CLI-based generators to merge configured options.

Location: app/Generators/AbstractGenerator.php89-92

hydratedOptions(): array

Converts config('options') associative array into flat command-line arguments list.

Example:


Filters out null values and empty strings.

Location: app/Generators/AbstractGenerator.php97-105

Sources: app/Generators/AbstractGenerator.php1-107

GeneratorContract Interface

The core contract all generators must implement.


Method Contract


Accepts a prompt string (containing diff, commit type, and instructions) and returns a generated commit message string.

Contract Requirements:

  • Must accept any non-empty prompt string
  • Should return sanitized, plain text commit message
  • May throw RequestException, ConnectionException, or ProcessFailedException
  • Should handle streaming responses if supported by AI service
  • Must strip API response wrappers (JSON, markdown code blocks, etc.)

Example Implementation Pattern:


Sources: app/Generators/OpenAIChatGenerator.php28-41 app/Generators/AbstractGenerator.php28

ConfigManager API

The ConfigManager extends Laravel's Repository to provide multi-layer configuration management with persistence.

Static Factory Methods

load(): ConfigManager

Creates a ConfigManager instance and registers it as config('ai-commit').

Returns: New ConfigManager instance loaded from all available sources

Location: app/ConfigManager.php62-65

make(?array $items = null): ConfigManager

Creates a ConfigManager instance from provided items or default configuration cascade.

Cascade Order (if $items is null):

  1. config/ai-commit.php (default)
  2. ~/.ai-commit/.ai-commit.json (global, if exists)
  3. ./.ai-commit.json (local, if exists)

Location: app/ConfigManager.php70-80

makeFrom(string ...$files): ConfigManager

Creates instance by loading and merging specified configuration files.

Parameters: Variable number of file paths (PHP or JSON)

Location: app/ConfigManager.php85-88

globalPath(): string

Returns global configuration file path:

  • Windows: C:\Users\{username}\.ai-commit\.ai-commit.json
  • Unix: ~/.ai-commit/.ai-commit.json

Location: app/ConfigManager.php90-95

localPath(string $path = '.ai-commit.json'): string

Returns local configuration file path relative to current working directory.

Default: ./.ai-commit.json

Location: app/ConfigManager.php97-106

Instance Methods

putGlobal(int $options = JSON_OPTIONS): bool|int

Persists current configuration to global file with JSON encoding.

Returns: Number of bytes written or false on failure

Location: app/ConfigManager.php111-114

putLocal(int $options = JSON_OPTIONS): bool|int

Persists current configuration to local file.

Location: app/ConfigManager.php119-122

putFile(string $file, int $options = JSON_OPTIONS): bool|int

Persists configuration to specified file. Filters out non-serializable objects before writing:

Excluded Keys:

  • generators.*.parameters.messages
  • generators.*.parameters.prompt
  • generators.*.parameters.user
  • Any object values not implementing JsonSerializable, Arrayable, or Jsonable

Creates parent directory if not exists.

Location: app/ConfigManager.php127-163

replaceFrom(string $file): ConfigManager

Loads configuration from file and merges it recursively into current instance using array_replace_recursive.

Location: app/ConfigManager.php168-171

replace(array $items): ConfigManager

Merges provided array recursively into current configuration.

Location: app/ConfigManager.php176-181

forget(mixed $keys): ConfigManager

Removes specified keys from configuration. Accepts single key or array of keys in dot notation.

Example: $config->forget(['generators.openai.api_key', 'prompt'])

Location: app/ConfigManager.php188-193

toDotArray(): array

Converts configuration to flat array with dot-notation keys.

Example Output:


Location: app/ConfigManager.php224-227

toArray(): array

Converts configuration to nested array, recursively converting Arrayable instances.

Location: app/ConfigManager.php232-235

toJson(mixed $options = JSON_OPTIONS): string

Serializes configuration to JSON string.

Default Options: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR

Location: app/ConfigManager.php244-247

Configuration File Format

The ConfigManager supports two file formats:

ExtensionHandlerUse Case
.phprequireShipped defaults (config/ai-commit.php)
.jsonFile::json()User configuration (global/local)

Sources: app/ConfigManager.php252-269

Constants

ConstantValuePurpose
BASE_NAME.ai-commit.jsonDefault config filename
BASE_DIRNAME.ai-commitGlobal config directory name
JSON_OPTIONSSee aboveDefault JSON encoding flags

Location: app/ConfigManager.php47-49

Sources: app/ConfigManager.php1-271

Configuration Structure Reference

The following diagram shows the complete configuration structure with array keys that can be accessed via ConfigManager:


Access Examples:


Sources: config/ai-commit.php14-260

Method Call Flow Example

The following sequence diagram illustrates how the APIs interact during commit message generation:


Sources: app/Commands/CommitCommand.php52-105 app/GeneratorManager.php63-77 app/Generators/OpenAIChatGenerator.php28-41

Return Type Reference

Key return types for API methods:

MethodReturn TypeNullableDescription
ConfigManager::load()ConfigManagerNoNew instance
ConfigManager::make()ConfigManagerNoNew or configured instance
ConfigManager::globalPath()stringNoAbsolute path
ConfigManager::putGlobal()bool|intNoBytes written or false
ConfigManager::toJson()stringNoJSON string
GeneratorManager::generator()GeneratorContractNoGenerator instance
GeneratorManager::generate()stringNoGenerated message
AbstractGenerator::mustRunProcess()ProcessNoSuccessful process
GeneratorContract::generate()stringNoCommit message
CommitCommand::handle()void-No return
ConfigCommand::handle()intNoExit code (0 or 1)

Sources: app/ConfigManager.php62-247 app/GeneratorManager.php41-54 app/Generators/AbstractGenerator.php42-70

Extension Points

Developers can extend ai-commit functionality through these interfaces:

Custom Generator Registration


The custom generator must implement GeneratorContract::generate(string): string.

Sources: app/GeneratorManager.php32-78

Configuration Override


Sources: app/ConfigManager.php62-88

Process Execution Hooks

Extend AbstractGenerator and override runningCallback() to customize process output handling:


Sources: app/Generators/AbstractGenerator.php82-87

Refresh this wiki

On this page