Files
cli/readme.hints.md
T

10 KiB

Gitzone CLI - Development Hints

  • the cli of the git.zone project.

Project Overview

Gitzone CLI (@git.zone/cli) is a comprehensive toolbelt for streamlining local development cycles. It provides utilities for:

  • Project initialization and templating (via smartscaf)
  • Code formatting and standardization
  • Version control and commit management
  • Docker and CI/CD integration
  • Meta project management

Architecture

Core Structure

  • Main CLI entry: cli.ts / cli.child.ts
  • Modular architecture with separate modules in ts/mod_* directories
  • Each module handles specific functionality (format, commit, docker, etc.)
  • Extensive use of plugins pattern via plugins.ts files

Configuration Management

  • Uses .smartconfig.json for tool configuration
  • CLI settings live under the @git.zone/cli namespace
  • Agent and non-interactive defaults now belong under @git.zone/cli.cli
  • Project type, module metadata, release settings, commit defaults, and format settings live in the same file

Format Module (mod_format) - SIGNIFICANTLY ENHANCED

The format module is responsible for project standardization:

Current Modules:

  1. cleanup - Removes obsolete files (yarn.lock, tslint.json, etc.)
  2. copy - File copying with glob patterns (fully implemented)
  3. gitignore - Creates/updates .gitignore from templates
  4. license - Checks dependency licenses for compatibility
  5. npmextra - Manages project metadata and configuration
  6. packagejson - Formats and updates package.json
  7. prettier - Applies code formatting with batching
  8. readme - Ensures readme files exist
  9. templates - Updates project templates based on type
  10. tsconfig - Formats TypeScript configuration

Execution Order (Dependency-Based):

  • Modules are now executed in parallel groups based on dependencies
  • Independent modules run concurrently for better performance
  • Dependency analyzer ensures correct execution order

New Architecture Features

  1. BaseFormatter Pattern: All formatters extend abstract BaseFormatter class
  2. FormatContext: Central state management across all modules
  3. FormatPlanner: Implements plan → action workflow
  4. RollbackManager: Full backup/restore capabilities
  5. ChangeCache: Tracks file changes to optimize performance
  6. DependencyAnalyzer: Manages module execution order
  7. DiffReporter: Generates diff views for changes
  8. FormatStats: Comprehensive execution statistics

Key Patterns

  1. Plugin Architecture: All dependencies imported through plugins.ts files
  2. Streaming: Uses smartstream for file processing
  3. Interactive Prompts: smartinteract for user input
  4. Enhanced Error Handling: Comprehensive try-catch with automatic rollback
  5. Template System: Templates handled by smartscaf, not directly by gitzone
  6. Type Safety: Full TypeScript with interfaces and type definitions

Important Notes

  • .nogit/ directory used for temporary/untracked files, backups, and cache
  • .nogit/gitzone-backups/ stores format operation backups
  • .nogit/gitzone-cache/ stores file change cache
  • Templates are managed by smartscaf - improvements should be made there
  • License checking configurable with exceptions support
  • All features implemented: ensureDependency, copy module, etc.

Recent Improvements (Completed)

  1. Plan → Action Workflow: Shows changes before applying them
  2. Rollback Mechanism: Full backup and restore on failures
  3. Enhanced Configuration: Granular control via .smartconfig.json
  4. Better Error Handling: Detailed errors with recovery options
  5. Performance Optimizations: Parallel execution and caching
  6. Reporting: Diff views, statistics, verbose logging
  7. Architecture: Clean separation of concerns with new classes
  8. Unified Version Bumping: Self-managed version updates eliminating npm warning pollution in deno.json

Version Bumping Refactor (Latest)

The commit module's version bumping has been refactored to eliminate npm command dependencies:

Changes:

  • Removed bumpNpmVersion() - was causing npm warnings to pollute deno.json
  • Removed syncVersionToDenoJson() - no longer needed with unified approach
  • Removed separate bumpDenoVersion() - replaced by unified implementation
  • Added readCurrentVersion() helper - reads from either package.json or deno.json
  • Added updateVersionFile() helper - updates JSON files directly
  • Unified bumpProjectVersion() - handles npm/deno/both with single clean code path

Benefits:

  • No npm warning pollution in version fields
  • Full control over version bumping process
  • Simpler git history (no amending, no force-tagging)
  • Same code path for all project types
  • Reuses existing calculateNewVersion() function

Auto-Accept Flag for Commits

The commit module now supports -y/--yes flag for non-interactive commits:

Usage:

  • gitzone commit -y - Auto-accepts AI recommendations without prompts
  • gitzone commit -yp - Auto-accepts and pushes to origin
  • Separate -p/--push flag controls push behavior

Implementation:

  • Creates AnswerBucket programmatically when -y flag detected
  • Preserves all UI output for transparency
  • Fully backward compatible with interactive mode
  • CI/CD friendly for automated workflows

Development Tips

  • Always check readme.plan.md for ongoing improvement plans
  • Use .smartconfig.json for any new configuration options
  • Keep modules focused and single-purpose
  • Maintain the existing plugin pattern for dependencies
  • Test format operations on sample projects before deploying
  • Consider backward compatibility when changing configuration structure
  • Use BaseFormatter pattern for new format modules
  • Leverage FormatContext for cross-module state sharing

Configuration Examples

{
  "@git.zone/cli": {
    "cli": {
      "interactive": true,
      "output": "human",
      "checkUpdates": true
    },
    "format": {
      "interactive": true,
      "showStats": true,
      "modules": {
        "skip": ["prettier"],
        "only": []
      }
    }
  }
}

CLI Usage

Commit Commands

# Interactive commit (default)
gitzone commit

# Read-only recommendation
gitzone commit recommend --json

# Auto-accept AI recommendations (no prompts)
gitzone commit -y
gitzone commit --yes

# Auto-accept and push to origin
gitzone commit -yp
gitzone commit -y -p
gitzone commit --yes --push

# Run format before commit
gitzone commit --format

Format Commands

# Basic format
gitzone format

# Read-only JSON plan
gitzone format plan --json

# Dry run to preview changes
gitzone format --dry-run

# Non-interactive apply
gitzone format --write --yes

# Plan only (no execution)
gitzone format --plan-only

# Save plan for later
gitzone format --save-plan format.json

# Execute saved plan
gitzone format --from-plan format.json

# Verbose mode
gitzone format --verbose

# Detailed diff views
gitzone format --detailed

# Inspect config for agents and scripts
gitzone config show --json
gitzone config set cli.output json
gitzone config get release.accessLevel

Common Issues (Now Resolved)

  1. Format operations are now reversible with rollback
  2. Enhanced error messages with recovery suggestions
  3. All modules fully implemented (including copy)
  4. Dry-run capability available
  5. Extensive configuration options available

Future Considerations

  • Plugin system for custom formatters
  • Git hooks integration for pre-commit formatting
  • Advanced UI with interactive configuration
  • Format presets for common scenarios
  • Performance benchmarking tools

API Changes

Smartfile v13 Migration (Latest - Completed)

The project has been fully migrated from @push.rocks/smartfile v11 to v13, which introduced a major breaking change where filesystem operations were split into two separate packages:

Packages:

  • @push.rocks/smartfile v13.0.1 - File representation classes (SmartFile, StreamFile, VirtualDirectory)
  • @push.rocks/smartfs v1.1.0 - Filesystem operations (read, write, exists, stat, etc.)

Key API Changes:

  1. File Reading:

    • Old: plugins.smartfile.fs.toStringSync(path) or plugins.smartfile.fs.toObjectSync(path)
    • New: await plugins.smartfs.file(path).encoding('utf8').read() + JSON.parse if needed
    • Important: read() returns string | Buffer - use as string type assertion when encoding is set
  2. File Writing:

    • Old: plugins.smartfile.memory.toFs(content, path) or plugins.smartfile.memory.toFsSync(content, path)
    • New: await plugins.smartfs.file(path).encoding('utf8').write(content)
  3. File Existence:

    • Old: plugins.smartfile.fs.fileExists(path) or plugins.smartfile.fs.fileExistsSync(path)
    • New: await plugins.smartfs.file(path).exists()
  4. Directory Operations:

    • Old: plugins.smartfile.fs.ensureDir(path)
    • New: await plugins.smartfs.directory(path).recursive().create()
    • Old: plugins.smartfile.fs.remove(path)
    • New: await plugins.smartfs.directory(path).recursive().delete() or await plugins.smartfs.file(path).delete()
  5. Directory Listing:

    • Old: plugins.smartfile.fs.listFolders(path) or plugins.smartfile.fs.listFoldersSync(path)
    • New: await plugins.smartfs.directory(path).list() then filter by stats.isDirectory
    • Note: list() returns IDirectoryEntry[] with path and name properties - use stat() to check if directory
  6. File Stats:

    • Old: stats.isDirectory() (method)
    • New: stats.isDirectory (boolean property)
    • Old: stats.mtimeMs
    • New: stats.mtime.getTime()
  7. SmartFile Factory:

    • Old: Direct SmartFile instantiation
    • New: plugins.smartfile.SmartFileFactory.nodeFs() then factory methods

Migration Pattern: All sync methods must become async. Functions that were previously synchronous (like getProjectName()) now return Promise<T> and must be awaited.

Affected Modules:

  • ts/mod_format/* (largest area - 15+ files)
  • ts/mod_commit/* (version bumping)
  • ts/mod_services/* (configuration management)
  • ts/mod_meta/* (meta repository management)
  • ts/mod_standard/* (template listing)
  • ts/mod_template/* (template operations)

Previous API Changes:

  • smartnpm requires instance creation: new NpmRegistry()
  • Type imports use import type for proper verbatim module syntax