Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

gist-cache-rs Documentation

Welcome to the official documentation for gist-cache-rs, a high-performance CLI tool written in Rust for efficiently caching, searching, and executing GitHub Gists.

What is gist-cache-rs?

gist-cache-rs provides a streamlined workflow for managing and executing your GitHub Gists locally. It features a sophisticated 2-layer caching system that dramatically reduces execution time and network overhead, making it perfect for developers who frequently use Gists as script repositories.

Key Features

  • High Performance - Lightning-fast caching and search operations implemented in Rust
  • 🔄 Smart Updates - Incremental cache updates that only fetch what’s changed
  • 💾 2-Layer Caching - Intelligent caching of both metadata and content for 20x faster execution
  • 🔍 Flexible Search - Multiple search modes: by ID, filename, or description
  • ▶️ Multi-Language Support - Execute scripts in bash, python, ruby, node, php, perl, pwsh, TypeScript and more
  • 🎛️ Smart Interpreter Detection - Automatic interpreter selection from shebangs, file extensions, and content analysis (v0.8.6+)
  • 💬 Interactive Mode - Full support for interactive scripts
  • 📦 Modern Python - uv support with PEP 723 metadata compatibility
  • 📥 Easy Downloads - Save Gist files directly to your download folder
  • 🗂️ Cache Management - Powerful commands for cache inspection and maintenance
  • 📊 Progress Display - Visual feedback with progress bars and spinners
  • 🎯 Interactive Selection - Intuitive arrow-key navigation for selecting Gists
  • 📋 Output Format Options - JSON output for scripting and automation

Platform Support

gist-cache-rs works seamlessly across Linux, macOS, and Windows 10 or later.

Quick Navigation

For Users

Get started quickly with these essential guides:

For Developers

Contributing to the project or want to understand the internals?

Test Specifications

Detailed functional verification documentation:

Getting Help

License

This project is licensed under the MIT License.

Installation Guide

Prerequisites

Required

  • Rust toolchain (1.85 or later)

    Linux / macOS:

    rustc --version  # Verify
    

    Installation method:

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    

    Windows:

    rustc --version  # Verify
    

    Installation method: Download from rustup.rs

  • GitHub CLI (gh) - Authenticated

    Linux / macOS:

    gh --version     # Verify
    gh auth status   # Check authentication status
    

    Windows:

    gh --version     # Verify
    gh auth status   # Check authentication status
    

    Authentication method:

    gh auth login
    

    Installation: GitHub CLI

  • Git (for repository cloning)

Installation Methods

Interactively performs all steps.

Linux / macOS

# Clone the repository
git clone https://github.com/7rikazhexde/gist-cache-rs.git
cd gist-cache-rs

# Run the setup script
./script/setup.sh install

Actions performed:

  1. ✅ Prerequisite check
  2. 📁 Project directory detection
  3. 🔨 Release build
  4. 📦 Select installation method
  5. ⚙️ Perform installation
  6. ⚙️ Configuration file setup (optional - v0.8.7+)
    • Interactive interpreter selection for each file extension
    • Python (.py): uv or python3
    • Ruby (.rb): ruby
    • JavaScript (.js): node
    • TypeScript (.ts): ts-node, deno, or bun
    • Shell (.sh): bash, sh, or zsh
    • PHP (.php): php
    • Perl (.pl): perl
    • PowerShell (.ps1): pwsh
    • Fallback (*): bash, python3, or sh
  7. 🔄 Initial cache creation
  8. ⌨️ Alias setup (optional)

Windows

# Clone the repository
git clone https://github.com/7rikazhexde/gist-cache-rs.git
cd gist-cache-rs

# Run the setup script
.\script\setup.ps1 install

Actions performed:

  1. ✅ Prerequisite check (Rust, GitHub CLI)
  2. 🔨 Release build
  3. 📦 Perform cargo install
  4. ⚙️ Configuration file setup (optional - v0.8.7+)
    • Interactive interpreter selection for each file extension
    • Python (.py): uv or python3
    • Ruby (.rb): ruby
    • JavaScript (.js): node
    • TypeScript (.ts): ts-node, deno, or bun
    • Shell (.sh): bash, sh, or zsh
    • PHP (.php): php
    • Perl (.pl): perl
    • PowerShell (.ps1): pwsh
    • Fallback (*): bash, python3, or sh
  5. 🔄 Initial cache creation (optional)

Installation location:

  • Binary: %USERPROFILE%\.cargo\bin\gist-cache-rs.exe
  • Cache: %LOCALAPPDATA%\gist-cache\

Method 2: cargo install (All platforms)

cargo build --release
cargo install --path .

Installation location:

  • Linux/macOS: ~/.cargo/bin/gist-cache-rs
  • Windows: %USERPROFILE%\.cargo\bin\gist-cache-rs.exe

PATH setting:

Linux / macOS: Usually set automatically. If not set:

# Add to ~/.bashrc or ~/.zshrc
export PATH="$HOME/.cargo/bin:$PATH"
source ~/.bashrc

Windows: Cargo’s bin directory is automatically added to PATH. If not set:

  1. Open “Edit the system environment variables”
  2. Click “Environment Variables…” button
  3. Edit “Path” under User variables
  4. Add %USERPROFILE%\.cargo\bin

Method 3: System directory

cargo build --release
sudo cp target/release/gist-cache-rs /usr/local/bin/

Installation location: /usr/local/bin/gist-cache-rs Feature: Shared by all users, requires sudo privileges

Method 4: User directory

cargo build --release
mkdir -p ~/bin
cp target/release/gist-cache-rs ~/bin/

Installation location: ~/bin/gist-cache-rs

PATH setting:

# Add to ~/.bashrc or ~/.zshrc
export PATH="$HOME/bin:$PATH"
source ~/.bashrc
cargo build --release

# Link to /usr/local/bin (requires sudo)
sudo ln -sf "$(pwd)/target/release/gist-cache-rs" /usr/local/bin/gist-cache-rs

# Or link to ~/bin
mkdir -p ~/bin
ln -sf "$(pwd)/target/release/gist-cache-rs" ~/bin/gist-cache-rs

Feature: Automatically reflected after build, convenient for development

Post-Installation Setup

If you didn’t set up configuration during installation, you can configure it anytime:

Interactive Setup (Recommended):

# Use interactive configuration with cursor-based UI
gist-cache-rs config setting

This will guide you through:

  • Selecting interpreters for each file extension (.py, .rb, .js, .ts, .sh, .php, .pl, .ps1)
  • Setting fallback interpreter for unknown extensions (*)
  • Configuring execution settings (confirm_before_run)
  • Setting cache retention period

Manual Configuration:

# Set interpreter for Python files
gist-cache-rs config set defaults.interpreter.py python3

# Set fallback interpreter
gist-cache-rs config set defaults.interpreter."*" bash

# View configuration
gist-cache-rs config show

For more details, see the Configuration Guide.

2. Initial Cache Creation

gist-cache-rs update

Detailed display:

gist-cache-rs update --verbose

3. Alias Setting (Optional)

Automatic setting (when using setup.sh)

Set interactively during installation:

Use recommended alias names (gcrsu, gcrsr)? [Y/n]: y

Or

Use recommended alias names (gcrsu, gcrsr)? [Y/n]: n
Alias name for gist-cache-rs update: gcu
Alias name for gist-cache-rs run: gcr

Manual setting

# Add to ~/.bashrc or ~/.zshrc
alias gcrsu='gist-cache-rs update'
alias gcrsr='gist-cache-rs run'

# Apply settings
source ~/.bashrc

Installation Verification

# Check version
gist-cache-rs --version

# Display help
gist-cache-rs --help

# Check cache status
gist-cache-rs update --verbose

Troubleshooting

command not found: gist-cache-rs

Cause: PATH is not set

Solution (Linux/macOS):

# Check installation location
which gist-cache-rs

# Check PATH
echo $PATH

# If in ~/.cargo/bin
export PATH="$HOME/.cargo/bin:$PATH"

# If in ~/bin
export PATH="$HOME/bin:$PATH"

# Apply settings
source ~/.bashrc

Solution (Windows):

# Check installation location
where.exe gist-cache-rs

# Check PATH
$env:PATH

# Set environment variable (PowerShell)
$env:PATH += ";$env:USERPROFILE\.cargo\bin"

# For persistent setting
[System.Environment]::SetEnvironmentVariable("Path", $env:PATH, [System.EnvironmentVariableTarget]::User)

Permission error

Cause: No execution permission

Solution:

# Grant execution permission
chmod +x ~/.cargo/bin/gist-cache-rs
# Or
chmod +x /usr/local/bin/gist-cache-rs
# Or
chmod +x ~/bin/gist-cache-rs

Build error

Cause: Outdated Rust version, dependency issues

Solution:

# Update Rust
rustup update

# Update dependencies
cargo update

# Clean build
cargo clean
cargo build --release

GitHub CLI authentication error

Error: GitHub CLI (gh) is not authenticated

Solution:

gh auth login

PowerShell execution policy error (Windows)

Error: This system\'s script execution is disabled...

Solution:

# Allow script execution for current user
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

# Or bypass for specific script only
powershell -ExecutionPolicy Bypass -File .\script\setup.ps1 install

Cache not created

Error: Cache file not found

Solution:

# Initial cache creation
gist-cache-rs update

# Display detailed information
gist-cache-rs update --verbose

Rate limit error

Warning: Rate limit remaining is low

Solution:

  • Wait for a while and retry
  • Avoid --force option
  • Use differential update

Uninstallation

Automatic Uninstallation

Linux / macOS

./script/setup.sh uninstall

Interactively select:

  • Binary deletion
  • Cache directory deletion
  • Alias deletion

Windows

.\script\setup.ps1 uninstall

Interactively select:

  • Binary deletion
  • Cache directory deletion

Manual Uninstallation

Linux / macOS

# If installed with cargo
cargo uninstall gist-cache-rs

# If installed in system directory
sudo rm /usr/local/bin/gist-cache-rs

# If installed in user directory
rm ~/bin/gist-cache-rs

# Delete cache directory
rm -rf ~/.cache/gist-cache/

# Delete config directory
rm -rf ~/.config/gist-cache/

# Remove aliases (delete relevant lines from ~/.bashrc or ~/.zshrc)
# Example:
# alias gcrsu='gist-cache-rs update'
# alias gcrsr='gist-cache-rs run'

Windows

# If installed with cargo
cargo uninstall gist-cache-rs

# Delete cache directory
Remove-Item -Recurse -Force "$env:LOCALAPPDATA\gist-cache"

# Delete config directory
Remove-Item -Recurse -Force "$env:APPDATA\gist-cache"

Next Steps

Quick Start Guide

A minimal guide to get started with gist-cache-rs in 5 minutes.

Step 1: Verify Prerequisites

# Check if Rust is installed
rustc --version

# Check if GitHub CLI is installed
gh --version

# Check if authenticated with GitHub CLI
gh auth status

If not installed, please refer to the Installation Guide.

Step 2: Installation

# Clone the repository
git clone https://github.com/7rikazhexde/gist-cache-rs.git
cd gist-cache-rs

# Build and install
cargo build --release
cargo install --path .

# Verify installation
gist-cache-rs --version

For other installation methods, please refer to the Installation Guide.

Step 3: Initial Cache Creation

# Create cache (with progress display)
gist-cache-rs update

# With detailed output (recommended)
gist-cache-rs update --verbose

Example Output (Normal Mode with Progress Display):

Updating Gist cache...
⠙ Fetching Gist information from GitHub API...
Fetched 42 Gists
[████████████████████████████████] 42/42 (100%)
Cache update completed
Total Gists: 42

Example Output (Verbose Mode):

Updating Gist cache...
Mode: Force full update
Rate limit remaining: 4999
Fetching Gist information from GitHub API...
Gists fetched: 42
New/Updated: 42 items
Cache update completed
Total Gists: 42

Note: The normal mode displays a spinner while fetching Gists and a progress bar when processing multiple Gists (10+). Use --verbose for detailed logs instead of progress indicators.

Step 4: Search and Execute Gist

Preview (Check content without executing)

# Search by keyword and preview
gist-cache-rs run --preview backup

Actually Execute

# Execute a Bash script
gist-cache-rs run backup bash

# Execute a Python script
gist-cache-rs run data_analysis.py python3

# Execute a Python script with uv
gist-cache-rs run ml-script uv

Execute with Arguments

# Pass arguments to a script
gist-cache-rs run backup bash /src /dst

# Pass arguments to a Python script
gist-cache-rs run data_analysis.py python3 input.csv --output result.json

Step 5: Configuration (Optional)

Set up your preferences with the config command:

# Interactive configuration with cursor-based UI
gist-cache-rs config setting

# Follow the prompts to:
# - Select interpreters for each file extension
# - Configure execution settings
# - Set cache retention period

Method 2: Manual Commands

# Set default interpreter (saves time)
gist-cache-rs config set defaults.interpreter python3

# Enable execution confirmation for safety
gist-cache-rs config set execution.confirm_before_run true

# View your configuration
gist-cache-rs config show

For more configuration options, see the Configuration Guide.

Step 6: Alias Setting (Optional)

To use it more conveniently, set up aliases:

# Add to ~/.bashrc
echo 'alias gcrsu="gist-cache-rs update"' >> ~/.bashrc
echo 'alias gcrsr="gist-cache-rs run"' >> ~/.bashrc
source ~/.bashrc

# Now you can use the shortened forms
gcrsu                # Update cache
gcrsr backup bash    # Execute Gist

Frequently Used Commands

Configuration Management

# Interactive configuration setup (recommended)
gist-cache-rs config setting

# Set configuration values
gist-cache-rs config set defaults.interpreter python3
gist-cache-rs config set execution.confirm_before_run true
gist-cache-rs config set cache.retention_days 30

# Get configuration values
gist-cache-rs config get defaults.interpreter

# Show all configuration
gist-cache-rs config show

# Edit config file
gist-cache-rs config edit

# Reset to defaults
gist-cache-rs config reset

Cache Management

# Differential update (normal)
gist-cache-rs update

# Force full update
gist-cache-rs update --force

# Detailed display
gist-cache-rs update --verbose

Content Cache Management

# Display cache list
gist-cache-rs cache list

# Check cache size
gist-cache-rs cache size

# Clean old cache entries
gist-cache-rs cache clean --older-than 30        # Remove entries older than 30 days
gist-cache-rs cache clean --orphaned             # Remove orphaned cache files
gist-cache-rs cache clean --dry-run --orphaned   # Preview what would be deleted

# Clear all caches
gist-cache-rs cache clear

Gist Search and Execution

# Basic search and execution
gist-cache-rs run keyword

# Preview (check content without executing)
gist-cache-rs run -p keyword

# Interactive mode (when using read command, etc.)
gist-cache-rs run -i interactive-script

# Save to download folder
gist-cache-rs run --download backup bash

# Download after preview
gist-cache-rs run -p --download script

# Search by filename
gist-cache-rs run --filename setup.sh

# Search by description
gist-cache-rs run --description deployment

# Get latest information before execution (force update)
gist-cache-rs run --force backup bash

Specify Interpreter

Argument specifications depend on the script.

# Bash (default)
gist-cache-rs run script bash arg1 arg2 ...

# Python3
gist-cache-rs run script python3 arg1 arg2 ...

# Ruby
gist-cache-rs run script ruby arg1 arg2 ...

# Node.js
gist-cache-rs run script node arg1 arg2 ...

# uv (PEP 723 compatible)
gist-cache-rs run script uv arg1 arg2 ...

Practical Examples

Please check the Usage Examples.

Troubleshooting

Cache not found

# Error: Cache file not found
→ Run gist-cache-rs update

GitHub authentication error

# Error: GitHub CLI is not authenticated
→ Run gh auth login

Command not found

# If command not found
→ Check path with which gist-cache-rs
→ Check if ~/.cargo/bin or /usr/local/bin is in PATH

Search results not found

# Cache might be old
→ Update with gist-cache-rs update

Help

# Overall help
gist-cache-rs --help

# Subcommand help
gist-cache-rs update --help
gist-cache-rs run --help

# Running without arguments also displays help
gist-cache-rs run

Configuration Guide

gist-cache-rs supports user configuration through both CLI commands and a configuration file. This allows you to customize default behavior and set preferences for script execution and cache management.

Configuration File Location

The configuration file is stored at:

  • Linux/macOS: ~/.config/gist-cache/config.toml
  • Windows: %APPDATA%\gist-cache\config.toml

The configuration file uses TOML format and is created automatically when you first use gist-cache-rs config commands.

Available Configuration Options

defaults.interpreter

Set the default interpreter for script execution. You can configure interpreters in two ways:

Simple Configuration (Legacy)

Set a single default interpreter for all scripts:

# Set default interpreter
gist-cache-rs config set defaults.interpreter python3

# Now you can omit the interpreter argument
gist-cache-rs run my-script  # Uses python3 by default

Advanced Configuration (Per-Extension)

New in v0.8.6: Configure different interpreters for different file types:

# Set interpreter for Python files
gist-cache-rs config set defaults.interpreter.py python3

# Set interpreter for Ruby files
gist-cache-rs config set defaults.interpreter.rb ruby

# Set interpreter for TypeScript files
gist-cache-rs config set defaults.interpreter.ts deno

# Set interpreter for JavaScript files
gist-cache-rs config set defaults.interpreter.js node

# Set wildcard fallback for all other file types
gist-cache-rs config set defaults.interpreter."*" bash

Supported interpreters: bash, sh, zsh, python3, ruby, node, perl, php, pwsh, ts-node, deno, bun, uv, etc.

Interpreter Resolution Priority

When executing a script, the interpreter is determined using the following priority order (highest to lowest):

  1. Command-line argument - Explicitly specified interpreter
  2. Shebang detection - From #!/usr/bin/env python3 or #!/usr/bin/python3
  3. User configuration - Extension-based settings (defaults.interpreter.<ext>)
  4. Heuristics - Filename patterns (e.g., Makefilemake)
  5. Content analysis - Language detection from file content (using tokei)
  6. Global defaults - Wildcard (defaults.interpreter."*") or bash fallback

Example Configuration File:

[defaults.interpreter]
py = "python3"
rb = "ruby"
ts = "deno"
js = "node"
sh = "bash"
Makefile = "make"
"*" = "bash"  # Wildcard fallback

Example Usage:

# Python script with .py extension - automatically uses python3
gist-cache-rs run data-analysis  # Detects .py, uses python3

# Override with command-line argument
gist-cache-rs run data-analysis bash  # Forces bash

# Script with shebang - uses detected interpreter
gist-cache-rs run setup-script  # Reads #!/usr/bin/env python3

# Unknown file type - uses wildcard fallback
gist-cache-rs run unknown-script  # Uses bash (from "*")

execution.confirm_before_run

Enable or disable confirmation prompt before executing scripts (for safety).

Values: true or false

# Enable confirmation prompt
gist-cache-rs config set execution.confirm_before_run true

# Disable confirmation prompt
gist-cache-rs config set execution.confirm_before_run false

cache.retention_days

Set the number of days to retain cached content before automatic cleanup.

Values: Any positive integer (days)

# Set retention period to 30 days
gist-cache-rs config set cache.retention_days 30

Configuration Commands

Interactive Configuration Setting

New in v0.8.7: Configure all settings interactively using a cursor-based menu:

gist-cache-rs config setting

This command provides an interactive interface to configure all settings with visual selection:

  • Interpreter selection: Choose interpreters for each file extension using cursor keys
  • Execution settings: Toggle confirm_before_run with Yes/No prompt
  • Cache settings: Set retention days with validation (1-365)
  • Current values: Shows current configuration values as defaults
  • Validation: Prevents invalid values before saving

Example flow:

Interactive Configuration Setting

Configure interpreters for each file extension and other settings.

Select interpreter for .py
  Interpreter for .py
  > uv
    python3

✓ Set .py: uv

Select interpreter for .rb
  Interpreter for .rb
  > ruby

✓ Set .rb: ruby

...

Execution Settings
  Confirm before running scripts? (Y/n): n
✓ Set confirm_before_run: false

Cache Settings
  Cache retention days (1-365) [30]: 60
✓ Set retention_days: 60

✓ Configuration saved successfully!

Config file: /home/user/.config/gist-cache/config.toml

This is the recommended way to configure gist-cache-rs, especially for first-time setup or when you want to review all available options.

Set a Configuration Value

gist-cache-rs config set <key> <value>

Examples:

# Set default interpreter to python3
gist-cache-rs config set defaults.interpreter python3

# Enable execution confirmation
gist-cache-rs config set execution.confirm_before_run true

# Set cache retention to 60 days
gist-cache-rs config set cache.retention_days 60

Get a Configuration Value

gist-cache-rs config get <key>

Examples:

# Get current default interpreter
gist-cache-rs config get defaults.interpreter
# Output: python3

# Get confirmation setting
gist-cache-rs config get execution.confirm_before_run
# Output: true

# Get a value that's not set
gist-cache-rs config get cache.retention_days
# Output: Config key 'cache.retention_days' not set

Show All Configuration

Display all current configuration settings:

gist-cache-rs config show

Example output:

Configuration:

[defaults]
  [interpreter]
    py = python3
    * = bash
[execution]
  confirm_before_run = true
[cache]
  retention_days = 30

Config file: /home/user/.config/gist-cache/config.toml

Edit Configuration File

Open the configuration file in your default text editor:

gist-cache-rs config edit

This command uses the $EDITOR environment variable (Linux/macOS) or notepad (Windows) to open the config file. If $EDITOR is not set, it falls back to vi on Unix-like systems.

Reset Configuration

Reset all configuration to default values:

gist-cache-rs config reset

This removes the configuration file and resets all settings to defaults.

Configuration File Format

The configuration file uses TOML format. Here are examples:

Simple Configuration

[defaults]
interpreter = "python3"

[execution]
confirm_before_run = true

[cache]
retention_days = 30

Advanced Configuration (v0.8.6+)

[defaults.interpreter]
py = "python3"
rb = "ruby"
ts = "deno"
js = "node"
sh = "bash"
Makefile = "make"
"*" = "bash"  # Wildcard fallback for unknown file types

[execution]
confirm_before_run = false

[cache]
retention_days = 30

You can edit this file directly using gist-cache-rs config edit or any text editor.

Practical Examples

Example 1: Set Default Python Interpreter

If you primarily run Python scripts, set the default interpreter:

# Set default to python3
gist-cache-rs config set defaults.interpreter python3

# Now you can run Python scripts without specifying the interpreter
gist-cache-rs run data-analysis
# Instead of: gist-cache-rs run data-analysis python3

Example 1b: Configure Per-Extension Interpreters (v0.8.6+)

For mixed-language projects, configure different interpreters for different file types:

# Use interactive configuration (v0.8.7+)
gist-cache-rs config setting

# Follow the prompts to select interpreters for each extension
# - Use arrow keys to navigate
# - Press Enter to confirm selection
# - All settings are validated before saving

Method 2: Manual CLI commands

# Configure interpreters for different languages
gist-cache-rs config set defaults.interpreter.py python3
gist-cache-rs config set defaults.interpreter.rb ruby
gist-cache-rs config set defaults.interpreter.ts deno
gist-cache-rs config set defaults.interpreter.js node
gist-cache-rs config set defaults.interpreter."*" bash

# View your configuration
gist-cache-rs config show

Result:

# Now scripts automatically use the right interpreter
gist-cache-rs run data-script      # .py file → uses python3
gist-cache-rs run deploy-script    # .rb file → uses ruby
gist-cache-rs run build-script     # .ts file → uses deno
gist-cache-rs run test-runner      # .js file → uses node
gist-cache-rs run backup-script    # .sh file → uses bash (wildcard)

Example 2: Enable Safety Confirmation

For added security when running scripts:

# Enable confirmation before execution
gist-cache-rs config set execution.confirm_before_run true

# Now you'll be prompted before executing any script
gist-cache-rs run backup
# Prompt: Execute backup.sh with bash? [y/N]:

Example 3: Manage Cache Retention

Set how long to keep cached content:

# Keep cache for 60 days
gist-cache-rs config set cache.retention_days 60

# Clean old cache entries older than retention period
gist-cache-rs cache clean --older-than 60

Example 4: View Current Configuration

Check your current settings:

# Show all configuration
gist-cache-rs config show

# Or check specific settings
gist-cache-rs config get defaults.interpreter
gist-cache-rs config get execution.confirm_before_run

Environment Variable Override

For testing or temporary configurations, you can override the config directory using the GIST_CACHE_DIR environment variable:

# Use a custom directory for both config and cache
GIST_CACHE_DIR=/tmp/test-cache gist-cache-rs config show

This is particularly useful for:

  • Testing different configurations
  • Isolating test environments
  • Running multiple configurations simultaneously

Tips

  1. Use interactive setup first: Run config setting for first-time configuration (v0.8.7+)
  2. Start with safe defaults: Enable confirm_before_run when you’re new to the tool
  3. Use per-extension configuration: Set up interpreters for each file type you commonly use
  4. Set a wildcard fallback: Configure defaults.interpreter."*" to handle unknown file types
  5. Leverage shebang detection: Scripts with shebangs automatically use the correct interpreter
  6. Regular cleanup: Set an appropriate retention_days value to keep your cache clean
  7. Check before reset: Use config show before config reset to review your settings
  8. Interactive vs. Manual: Use config setting for guided setup, config set for quick changes
  9. Edit directly for complex changes: Use config edit to modify multiple settings at once
  10. Override when needed: Command-line arguments always take precedence over configuration
  • gist-cache-rs config setting - Interactive configuration (v0.8.7+)
  • gist-cache-rs config --help - Show config command help
  • gist-cache-rs cache clean --help - Cache cleanup options
  • gist-cache-rs run --help - Script execution options

Examples Collection

This document presents practical examples of gist-cache-rs usage.

Basic Usage

Cache Update

# First time or full update
$ gist-cache-rs update --verbose
Updating Gist cache...
Mode: Differential update
Rate limit remaining: 4966
Existing cache detected
GitHub user (cache reuse): your-username
Last updated: 2025-10-26T02:22:04Z
Fetching Gist information from GitHub API...
Gists fetched: 1
Differential merge complete: Existing 124 + Diff 1 → Total 124
Updated: 1 item
Cache update completed
Total Gists: 124

# If no updates
$ gist-cache-rs update --verbose
Updating Gist cache...
Mode: Differential update
Rate limit remaining: 4964
Existing cache detected
GitHub user (cache reuse): your-username
Last updated: 2025-10-26T02:35:44Z
Fetching Gist information from GitHub API...
Gists fetched: 0
No updates
Cache update completed
Total Gists: 124

Bash Script Examples

Example 1: Sequential Folder Creation Script

Gist Description: A script to create 100 folders with sequential numbers (start number to end number) in a specified path.

Preview content in preview mode

$ gist-cache-rs run -p create_folder
Description: A script to create 100 folders with sequential numbers (start number to end number) in a specified path. #bash
Files: create_folders.sh

=== Gist Content ===
--- create_folders.sh ---
#!/bin/bash
# A script to create 100 folders with sequential numbers (start number to end number) in a specified path.

show_usage() {
  echo "Usage: $0 [prefix] [destination] [start_number] [end_number]"
  echo ""
  echo "If arguments are omitted, you can enter them interactively"
  # ... (omitted)
}
# ... (script body)
$ gist-cache-rs run -p create
Multiple Gists found:

? Select a Gist
  > A script to create 100 folders with sequential numbers (start number to end number) in a specified path. #bash | create_folders.sh
    Create GitHub Gist with CLI | create_gist.sh
    Create multiple directories | create_dirs.sh
    Create backup archive | create_backup.sh
    Create project template | create_template.sh
    Create Docker container | create_container.sh
    Create test data | create_testdata.py
  [↑↓ to move, enter to select, type to filter]

Description: A script to create 100 folders with sequential numbers (start number to end number) in a specified path. #bash
Files: create_folders.sh
# ... (content displayed)

Key Points:

  • 🖱️ Use arrow keys (↑↓) to navigate between options
  • ⌨️ Press Enter to select the highlighted item
  • 🔍 Type to filter the list in real-time
  • ❌ Press Esc or Ctrl+C to cancel

Execute in interactive mode

$ gist-cache-rs run -i create_folder
Description: A script to create 100 folders with sequential numbers (start number to end number) in a specified path. #bash
Files: create_folders.sh
Executing: create_folders.sh (bash)

Usage: /tmp/create_folders.sh [prefix] [destination] [start_number] [end_number]

If arguments are omitted, you can enter them interactively

Example: /tmp/create_folders.sh aaa /path/to/directory 1000 1500

------------------------------------------------------
 ~$ /tmp/create_folders.sh aaa bbb 0 200
 Creating folder: ./bbb/aaa_No.0-99 (range: 0-99)
 Creating folder: ./bbb/aaa_No.100-200 (range: 100-200)
------------------------------------------------------

Run in interactive mode? (y/N): y

=== Interactive Mode ===
Enter prefix: test1
Enter destination directory: ./test
Enter start number: 0
Enter end number: 1000

 Creating folder: ./test/test1_No.0-99 (range: 0-99)
 Creating folder: ./test/test1_No.100-199 (range: 100-199)
 Creating folder: ./test/test1_No.200-299 (range: 200-299)
 Creating folder: ./test/test1_No.300-399 (range: 300-399)
 Creating folder: ./test/test1_No.400-499 (range: 400-499)
 Creating folder: ./test/test1_No.500-599 (range: 500-599)
 Creating folder: ./test/test1_No.600-699 (range: 600-699)
 Creating folder: ./test/test1_No.700-799 (range: 700-799)
 Creating folder: ./test/test1_No.800-899 (range: 800-899)
 Creating folder: ./test/test1_No.900-999 (range: 900-999)
 Creating folder: ./test/test1_No.1000-1000 (range: 1000-1000)
Processing completed.

Key Points:

  • 📝 Enable interactive mode with the -i option.
  • 💬 The read command within the script works correctly.
  • ✅ The script executes while accepting user input.

Python Script Examples

Example 2: Pandas/NumPy Data Analysis (PEP 723 Compatible)

Gist Description: data_analysis.py - Pandas/NumPy usage example #python #pandas #numpy #uv #pep723 #csv

Search by tag (Preview)

$ gist-cache-rs run -p '#pep723'
Multiple Gists found:

? Select a Gist
  > data_analysis.py - Pandas/NumPy usage example #python #pandas #numpy #uv #pep723 #csv | data_analysis.py
    uv_test.py - UV temporary installation test #python #pandas #numpy #uv #pep723 | uv_test.py
  [↑↓ to move, enter to select]

Description: data_analysis.py - Pandas/NumPy usage example #python #pandas #numpy #uv #pep723 #csv
Files: data_analysis.py

=== Gist Content ===
--- data_analysis.py ---
#!/usr/bin/env python3
# /// script
# dependencies = ["pandas", "numpy"]
# ///

import pandas as pd
import numpy as np
import sys
import os

def main() -> None:
    print(f"Pandas version: {pd.__version__}")
    print(f"NumPy version: {np.__version__}")

    if len(sys.argv) < 2:
        print("Error: Please specify the path to the CSV file (e.g., input.csv)")
        sys.exit(1)

    csv_file = sys.argv[1]

    if not os.path.exists(csv_file):
        print(f"Error: File '{csv_file}' not found.")
        sys.exit(1)

    # Read CSV file
    try:
        df = pd.read_csv(csv_file)
        print(f"\nCSV file '{csv_file}' read (rows: {len(df)})")
        print("\nDataFrame (first 5 rows):")
        print(df.head())

        # Simple data analysis
        print(f"\nNumber of columns: {len(df.columns)}")
        print(f"\nMean:\n{df.mean(numeric_only=True)}")

        # Generate random data as an example (optional)
        if len(df) > 0:
            print(f"\nAdded random column 'Random':")
            df["Random"] = np.random.randint(1, 100, len(df))
            print(df[["Random"]].head())

    except Exception as e:
        print(f"Error: An exception occurred during CSV processing: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()

Execute with uv (automatic dependency management)

$ gist-cache-rs run 723 uv sample/input.csv
Multiple Gists found:

? Select a Gist
  > data_analysis.py - Pandas/NumPy usage example #python #pandas #numpy #uv #pep723 #csv | data_analysis.py
    uv_test.py - UV temporary installation test #python #pandas #numpy #uv #pep723 | uv_test.py
  [↑↓ to move, enter to select]

Description: data_analysis.py - Pandas/NumPy usage example #python #pandas #numpy #uv #pep723 #csv
Files: data_analysis.py
Executing: data_analysis.py (python3)

Pandas version: 2.3.3
NumPy version: 2.3.4

CSV file 'sample/input.csv' read (rows: 5)

DataFrame (first 5 rows):
    A   B
0  77  28
1   5  65
2  47  34
3  84  82
4  65  46

Number of columns: 2

Mean:
A    55.6
B    51.0
dtype: float64

Added random column 'Random':
   Random
0      67
1      70
2       7
3      74
4      60

Key Points:

  • 📦 Dependencies defined by PEP 723 metadata (# /// script).
  • uv automatically installs pandas and numpy.
  • 🔧 The argument sample/input.csv is passed to the script.
  • 🎯 Executes temporarily without polluting the global environment.

Search Techniques

# Search for all Gists containing "create"
$ gist-cache-rs run create

# Search for all Gists containing "data"
$ gist-cache-rs run data
# Filter by hashtag
$ gist-cache-rs run '#bash'
$ gist-cache-rs run '#python'
$ gist-cache-rs run '#pep723'
# Search directly by filename
$ gist-cache-rs run --filename data_analysis.py
$ gist-cache-rs run --filename create_folders.sh
# Search only by description
$ gist-cache-rs run --description "Data Analysis"
$ gist-cache-rs run --description "Numpy"

5. Direct ID Specification

# Execute directly using Gist ID
$ gist-cache-rs run --id [your_gist_id] uv input.csv

Cache Management Examples

Check Cache List

$ gist-cache-rs cache list
List of cached Gists:

ID: 7bcb324e9291fa350334df8efb7f0deb
  Description: hello_args.sh - Argument display script #bash #test
  Files: hello_args.sh
  Updated: 2025-10-26 12:30:45

ID: e3a6336c9f3476342626551372f14d6e
  Description: data_analysis.py - Pandas/NumPy usage example #python #pep723
  Files: data_analysis.py
  Updated: 2025-10-25 18:22:10

Total: 2 Gists cached

List Cache in JSON Format

# Output in JSON format for scripting
$ gist-cache-rs cache list --format json
[
  {
    "id": "7bcb324e9291fa350334df8efb7f0deb",
    "description": "hello_args.sh - Argument display script #bash #test",
    "files": [
      "hello_args.sh"
    ],
    "updated_at": "2025-10-26T12:30:45+09:00"
  },
  {
    "id": "e3a6336c9f3476342626551372f14d6e",
    "description": "data_analysis.py - Pandas/NumPy usage example #python #pep723",
    "files": [
      "data_analysis.py"
    ],
    "updated_at": "2025-10-25T18:22:10+09:00"
  }
]

# Filter with jq (requires jq installed)
$ gist-cache-rs cache list --format json | jq '.[] | select(.description | contains("python"))'
{
  "id": "e3a6336c9f3476342626551372f14d6e",
  "description": "data_analysis.py - Pandas/NumPy usage example #python #pep723",
  "files": [
    "data_analysis.py"
  ],
  "updated_at": "2025-10-25T18:22:10+09:00"
}

# Extract only IDs
$ gist-cache-rs cache list --format json | jq -r '.[].id'
7bcb324e9291fa350334df8efb7f0deb
e3a6336c9f3476342626551372f14d6e

# Count Gists by tag
$ gist-cache-rs cache list --format json | jq '[.[] | select(.description | contains("#bash"))] | length'
1

Key Points:

  • 📋 Use --format json to output machine-readable JSON
  • 🔧 Perfect for scripting and automation tasks
  • 🎯 Combine with jq for powerful filtering and data extraction
  • 📊 JSON output includes: id, description, files array, and updated_at timestamp

Check Cache Size

$ gist-cache-rs cache size
Cache Size Information:

Number of cached Gists: 15
Total size: 89.45 KB
Cache directory: /home/user/.cache/gist-cache/contents

Clean Old Cache Entries

# Preview what would be deleted (dry-run mode)
$ gist-cache-rs cache clean --dry-run --older-than 30
Clean cache entries

DRY RUN MODE - No files will be deleted

  Removing entries older than 30 days

Would delete 3 entries:

  ID: 7bcb324e9291fa350334df8efb7f0deb
    Description: old script #bash
    Updated: 2025-09-15 10:20:30

  ID: a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
    Description: deprecated utility
    Updated: 2025-09-01 08:15:22

  ID: 9f8e7d6c5b4a3210fedcba9876543210
    Description: test script
    Updated: 2025-08-28 14:45:10

Would free up: 145.23 KB

# Actually delete old entries
$ gist-cache-rs cache clean --older-than 30
Clean cache entries

  Removing entries older than 30 days

Deleted 3 entries:

  ID: 7bcb324e9291fa350334df8efb7f0deb
    Description: old script #bash
    Updated: 2025-09-15 10:20:30

  ID: a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
    Description: deprecated utility
    Updated: 2025-09-01 08:15:22

  ID: 9f8e7d6c5b4a3210fedcba9876543210
    Description: test script
    Updated: 2025-08-28 14:45:10

Freed up: 145.23 KB

# Remove orphaned cache files (content without metadata)
$ gist-cache-rs cache clean --orphaned
Clean cache entries

  Removing orphaned content cache files

Deleted 2 entries:

  ID: orphaned123456 (orphaned)
  ID: deleted789abc (orphaned)

Freed up: 23.45 KB

Clear All Caches

$ gist-cache-rs cache clear
Clear All Caches

Are you sure you want to delete 15 Gist caches?
  This operation is irreversible.

Proceed? (y/N): y

All caches deleted

--force Option Usage Examples

Always execute development Gists with the latest version

# Use in the cycle of editing and executing development scripts
$ gist-cache-rs run --force test-script bash arg1 arg2

# Internally performs the following actions:
# 1. Incrementally updates the metadata cache.
# 2. If the Gist has been updated, deletes the content cache.
# 3. Fetches and executes the latest version.
# 4. Creates a new cache.

Combine with search options

# Search by description and always execute the latest version
$ gist-cache-rs run --force --description "backup script" bash /src /dst

# Search by filename and execute the latest version
$ gist-cache-rs run --force --filename deploy.sh bash

Key Points:

  • 📡 Automatically runs update (incremental update) before execution.
  • ⚡ If the Gist is not updated, it executes quickly using the existing cache.
  • 🔄 Only fetches a new version if it has been updated.

File Download

Basic Download

# Save to download folder after execution
$ gist-cache-rs run --download data_analysis uv input.csv

Description: data_analysis.py - Pandas/NumPy usage example #python #pandas #numpy #uv #pep723 #csv
Files: data_analysis.py
Executing: data_analysis.py (python3)

Pandas version: 2.3.3
NumPy version: 2.3.4
# ... (execution results)

=== Downloading File ===
  ✓ Download complete: /home/user/Downloads/data_analysis.py

1 file saved to /home/user/Downloads

Download After Preview

# Download after confirming content
$ gist-cache-rs run -p --download backup

Description: Backup script #bash #backup
Files: backup.sh

=== Gist Content ===
--- backup.sh ---
#!/bin/bash
# Backup script
# ... (content displayed)

=== Downloading File ===
  ✓ Download complete: /home/user/Downloads/backup.sh

1 file saved to /home/user/Downloads

Force Update and Download

# Get the latest version, then execute and download
$ gist-cache-rs run -f --download setup bash

Updating Gist cache...
No updates
Cache update completed

Description: Setup script #bash #setup
Files: setup.sh
Executing: setup.sh (bash)
# ... (execution results)

=== Downloading File ===
  ✓ Download complete: /home/user/Downloads/setup.sh

1 file saved to /home/user/Downloads

Download by ID

# Directly specify Gist ID to download
$ gist-cache-rs run --download --id abc123def456

ID specified mode: abc123def456

Description: Useful script #bash
Files: utility.sh
Executing: utility.sh (bash)
# ... (execution results)

=== Downloading File ===
  ✓ Download complete: /home/user/Downloads/utility.sh

1 file saved to /home/user/Downloads

Key Points:

  • 📥 Saves to the download folder (~/Downloads).
  • 🔄 Cache is automatically created during download, speeding up subsequent executions.
  • 🎯 Can be used with other options (--preview, --force, --interactive, etc.).
  • 💾 Useful for saving files separately from executable script caches.

Operation Order:

  1. --preview --download: Preview display → Download
  2. --force --download: Cache update → Execute → Download
  3. --download only: Execute → Download

Configuration Examples

New in v0.8.7: Use the interactive configuration command to set up all settings at once:

$ gist-cache-rs config setting
Interactive Configuration Setting

Configure interpreters for each file extension and other settings.

Select interpreter for .py
? Interpreter for .py
  > uv
    python3
  [↑↓ to move, enter to select]

✓ Set .py: uv

Select interpreter for .rb
? Interpreter for .rb
  > ruby
  [↑↓ to move, enter to select]

✓ Set .rb: ruby

# ... (continues for all extensions)

Execution Settings
? Confirm before running scripts? (Y/n): n
✓ Set confirm_before_run: false

Cache Settings
? Cache retention days (1-365) [30]: 60
✓ Set retention_days: 60

✓ Configuration saved successfully!

Config file: /home/user/.config/gist-cache/config.toml

Key Points:

  • 🎯 Interactive UI: Configure all settings with cursor navigation
  • 🔍 Current values shown: Existing settings appear as defaults
  • Validation: Invalid values are rejected before saving
  • 💾 Auto-save: All settings saved automatically when complete

Example: Set Default Interpreter

Save time by setting a default interpreter for your most-used language:

# Set python3 as default
$ gist-cache-rs config set defaults.interpreter python3
✓ Set defaults.interpreter = python3

# Now you can omit the interpreter argument
$ gist-cache-rs run data-analysis
# Executes with python3 automatically

# View your configuration
$ gist-cache-rs config show
Configuration:

[defaults]
  [interpreter]
    py = python3
[execution]

[cache]

Config file: /home/user/.config/gist-cache/config.toml

Example: Enable Safety Confirmation

Add a confirmation prompt before executing scripts:

# Enable confirmation
$ gist-cache-rs config set execution.confirm_before_run true
✓ Set execution.confirm_before_run = true

# Now you'll be prompted before execution
$ gist-cache-rs run backup bash
Execute backup.sh with bash? [y/N]: y
Executing: backup.sh (bash)
# ... script output

Example: Manage Configuration

# Set cache retention period
$ gist-cache-rs config set cache.retention_days 30
✓ Set cache.retention_days = 30

# Get specific value
$ gist-cache-rs config get cache.retention_days
30

# Edit config file directly
$ gist-cache-rs config edit
# Opens config file in your default editor

# Reset all configuration
$ gist-cache-rs config reset
✓ Configuration reset to defaults

For more details, see the Configuration Guide.


Tips & Tricks

1. Quickly Execute Recently Updated Gists

# Since the cache is sorted by update time in descending order,
# the first one found by partial match is the latest.
$ gist-cache-rs run keyword

2. Gists with Multiple Files

# If there are multiple files, the first file will be executed.
$ gist-cache-rs run multi-file-gist

3. Debug Mode

# Display debug information in verbose mode
$ gist-cache-rs update --verbose

# Preview content before execution
$ gist-cache-rs run -p script-name

4. Combine with Aliases

# Alias frequently used scripts
alias analyze='gcrsr data_analysis uv'

# Usage example
analyze mydata.csv

Troubleshooting

Q: Script not found

# Update the cache
$ gist-cache-rs update

# Check details in verbose mode
$ gist-cache-rs update --verbose

Q: Interactive mode does not work

# Use the -i option
$ gist-cache-rs run -i script-name

# For bash, it may work without -i
$ gist-cache-rs run script-name bash

Q: Error with uv

# Check if uv is installed
$ which uv

# Try executing with python3
$ gist-cache-rs run script-name python3

Shell Completions

gist-cache-rs supports shell completions for Bash, Zsh, Fish, and PowerShell. This enables auto-completion of commands, subcommands, and options by pressing the Tab key, significantly improving the command-line experience.

Supported Shells

  • Bash - Linux, macOS, Windows (Git Bash, WSL)
  • Zsh - macOS (default), Linux
  • Fish - Linux, macOS
  • PowerShell - Windows, Linux, macOS (PowerShell Core)

Generating Completion Scripts

Use the completions subcommand to generate shell-specific completion scripts:

gist-cache-rs completions <SHELL>

Where <SHELL> is one of: bash, zsh, fish, or powershell.

Before Installation

Backup Your Configuration

Before modifying shell configuration files, it’s recommended to create backups:

Bash:

# Backup .bashrc
cp ~/.bashrc ~/.bashrc.backup

Zsh:

# Backup .zshrc
cp ~/.zshrc ~/.zshrc.backup

Fish:

# Backup Fish config
cp -r ~/.config/fish ~/.config/fish.backup

PowerShell:

# Backup PowerShell profile (if exists)
if (Test-Path $PROFILE) {
    Copy-Item $PROFILE "$PROFILE.backup"
}

Restore from Backup

If something goes wrong, you can restore your configuration:

Bash/Zsh:

# Restore .bashrc or .zshrc
cp ~/.bashrc.backup ~/.bashrc
# or
cp ~/.zshrc.backup ~/.zshrc

# Reload configuration
source ~/.bashrc  # or source ~/.zshrc

Fish:

# Restore Fish config
rm -rf ~/.config/fish
cp -r ~/.config/fish.backup ~/.config/fish

PowerShell:

# Restore PowerShell profile
Copy-Item "$PROFILE.backup" $PROFILE

# Reload profile
. $PROFILE

Installation Instructions

Bash

Linux / macOS:

  1. Generate Completion Script: Create the directory for completions and generate the script.

    # Create the directory if it doesn't exist
    mkdir -p ~/.local/share/bash-completion/completions
    
    # Generate and install the completion script
    gist-cache-rs completions bash > ~/.local/share/bash-completion/completions/gist-cache-rs
    
  2. Activate Completions: The bash-completion package should automatically load the script. If completions do not work after starting a new shell session, you may need to source it manually in your ~/.bashrc.

    # Add this line to ~/.bashrc if completions are not loading
    echo 'source ~/.local/share/bash-completion/completions/gist-cache-rs' >> ~/.bashrc
    

    To apply the change immediately, run source ~/.bashrc.

Windows (Git Bash):

# Create completions directory
mkdir -p ~/bash-completion/completions

# Generate completion script
gist-cache-rs completions bash > ~/bash-completion/completions/gist-cache-rs

# Add to ~/.bashrc
echo 'source ~/bash-completion/completions/gist-cache-rs' >> ~/.bashrc

Zsh

macOS / Linux:

# Create completion directory if it doesn't exist
mkdir -p ~/.zfunc

# Generate completion script
gist-cache-rs completions zsh > ~/.zfunc/_gist-cache-rs

Add to your ~/.zshrc (if not already present):

# Add custom completion directory to fpath
fpath=(~/.zfunc $fpath)

# Initialize completion system
autoload -Uz compinit && compinit

Reload your shell or run:

source ~/.zshrc

Fish

Linux / macOS:

Fish automatically loads completion scripts from its completions directory.

# Generate and place the completion script
gist-cache-rs completions fish > ~/.config/fish/completions/gist-cache-rs.fish

The changes will take effect when you start a new Fish session. No additional configuration is needed.

PowerShell

Windows:

  1. Generate Completion Script: First, ensure the target directory exists and then generate the script.

    # Create a directory for PowerShell scripts if it doesn't exist
    $scriptDir = ~\Documents\PowerShell\Scripts
    if (-not (Test-Path $scriptDir)) {
        New-Item -ItemType Directory -Force -Path $scriptDir
    }
    
    # Generate the completion script
    gist-cache-rs completions powershell > $scriptDir\gist-cache-rs.ps1
    
  2. Update PowerShell Profile: Next, add the script to your PowerShell profile to have it load automatically.

    # Create the profile if it doesn't exist
    if (-not (Test-Path $PROFILE)) {
        New-Item -Path $PROFILE -ItemType File -Force
    }
    
    # Add the script loading command to your profile
    Add-Content $PROFILE "`n. $scriptDir\gist-cache-rs.ps1"
    
  3. Activate Completions: The changes will take effect when you start a new PowerShell session. To apply them immediately in your current session, run:

    . $PROFILE
    

    Note on Execution Policy: If you encounter an error, your script execution policy might be too restrictive. You can check it with Get-ExecutionPolicy. If it’s Restricted, you may need to change it. For example:

    # This allows locally created scripts to run
    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
    

Linux / macOS (PowerShell Core):

# Create scripts directory
mkdir -p ~/.config/powershell/scripts

# Generate completion script
gist-cache-rs completions powershell > ~/.config/powershell/scripts/gist-cache-rs.ps1

# Add to profile
Add-Content $PROFILE "`n. ~/.config/powershell/scripts/gist-cache-rs.ps1"

Configuration Files

After installation, the following files will be created:

Bash

Completion script location:

~/.local/share/bash-completion/completions/gist-cache-rs

Profile configuration (~/.bashrc):

# gist-cache-rs shell completion (if manually added)
source ~/.local/share/bash-completion/completions/gist-cache-rs

Zsh

Completion script location:

~/.zfunc/_gist-cache-rs

Profile configuration (~/.zshrc):

# Add custom completion directory to fpath
fpath=(~/.zfunc $fpath)

# Initialize completion system
autoload -Uz compinit && compinit

Fish

Completion script location:

~/.config/fish/completions/gist-cache-rs.fish

No profile configuration needed - Fish automatically loads completions from this directory.

PowerShell

Completion script location (Windows):

~\Documents\PowerShell\Scripts\gist-cache-rs.ps1

Profile configuration ($PROFILE):

# gist-cache-rs shell completion
. ~\Documents\PowerShell\Scripts\gist-cache-rs.ps1

PowerShell profile location:

  • Windows: ~\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
  • Linux/macOS: ~/.config/powershell/Microsoft.PowerShell_profile.ps1

Verifying Installation

After installation, restart your shell or reload the configuration file to test the completion.

Bash/Zsh (WSL2/Linux/macOS)

Complete subcommands:

$ gist-cache-rs [Tab]
-h           -V           --help       --version
update       run          cache        config       completions  help

Complete options:

$ gist-cache-rs run --[Tab]
--interactive  --preview      --force        --download
--id           --filename     --description  --help

Auto-complete partial input:

gist-cache-rs ru[Tab]
gist-cache-rs run    # ← Auto-completed

View help after completion:

$ gist-cache-rs run --help
Search from cache and execute

Usage: gist-cache-rs run [OPTIONS] [QUERY] [INTERPRETER] [SCRIPT_ARGS]...

Arguments:
  [QUERY]           Search keyword (ID, filename, or description)
  [INTERPRETER]     Interpreter or execution command (bash, python3, uv, etc.)
  [SCRIPT_ARGS]...  Additional arguments to pass to the script

Options:
  -i, --interactive  Interactive script execution mode
  -p, --preview      Preview mode (display content only)
  -f, --force        Update Gist cache before execution
      --download     Save file to download folder
      --id           Direct ID specification mode
      --filename     Search by filename
      --description  Search by description
  -h, --help         Print help

PowerShell (Windows)

Complete subcommands (press Tab after typing):

PS> gist-cache-rs [Tab]
# Cycles through: update, run, cache, config, completions, help, -h, --help, -V, --version

Complete options:

PS> gist-cache-rs run --[Tab]
# Cycles through: --interactive, --preview, --force, --download, --id, --filename, --description, --help

Auto-complete partial input:

PS> gist-cache-rs ru[Tab]
PS> gist-cache-rs run    # ← Auto-completed

Complete cache subcommands:

PS> gist-cache-rs cache [Tab]
# Cycles through: list, size, clean, clear, help

Troubleshooting

Completions Not Working (Bash)

  1. Verify the completion script exists:

    ls -l ~/.local/share/bash-completion/completions/gist-cache-rs
    
  2. Check if bash-completion is installed:

    # Ubuntu/Debian
    sudo apt install bash-completion
    
    # macOS (via Homebrew)
    brew install bash-completion@2
    
  3. Reload your shell:

    source ~/.bashrc
    

Completions Not Working (Zsh)

  1. Verify compinit is called in ~/.zshrc:

    grep compinit ~/.zshrc
    
  2. Check the fpath includes your completion directory:

    echo $fpath
    
  3. Rebuild completion cache:

    rm ~/.zcompdump
    compinit
    

Completions Not Working (Fish)

  1. Verify the completion script exists:

    ls -l ~/.config/fish/completions/gist-cache-rs.fish
    
  2. Reload Fish completions:

    fish_update_completions
    

Completions Not Working (PowerShell)

  1. Check execution policy:

    Get-ExecutionPolicy
    

    If it’s Restricted, change it:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
    
  2. Verify profile exists and is loaded:

    Test-Path $PROFILE
    cat $PROFILE
    
  3. Reload profile:

    . $PROFILE
    

Updating Completions

When you update gist-cache-rs to a new version with new commands or options, regenerate the completion scripts using the same installation commands shown above. The new script will overwrite the old one.

Editing Shell Configuration

If you need to modify or review your shell configuration:

Edit Configuration Files

Bash:

# Edit .bashrc with your preferred editor
nano ~/.bashrc
# or
vim ~/.bashrc
# or
code ~/.bashrc  # VS Code

Zsh:

# Edit .zshrc
nano ~/.zshrc
# or
vim ~/.zshrc

Fish:

# Edit Fish config
nano ~/.config/fish/config.fish
# or use Fish's web-based configuration
fish_config

PowerShell:

# Edit PowerShell profile
notepad $PROFILE
# or
code $PROFILE  # VS Code

Verify Configuration Content

Check what was added to your configuration files:

Bash:

# View .bashrc content related to gist-cache-rs
grep -A 2 "gist-cache-rs" ~/.bashrc

Zsh:

# View .zshrc content related to completion setup
grep -A 3 "gist-cache-rs\|compinit" ~/.zshrc

PowerShell:

# View profile content related to gist-cache-rs
Get-Content $PROFILE | Select-String -Pattern "gist-cache-rs" -Context 0,2

Apply Changes

After editing, reload the configuration:

Bash:

source ~/.bashrc

Zsh:

source ~/.zshrc

Fish:

source ~/.config/fish/config.fish

PowerShell:

. $PROFILE

Uninstalling Completions

To remove shell completions:

Bash:

rm ~/.local/share/bash-completion/completions/gist-cache-rs

Zsh:

rm ~/.zfunc/_gist-cache-rs

Fish:

rm ~/.config/fish/completions/gist-cache-rs.fish

PowerShell:

# Windows
Remove-Item ~\Documents\PowerShell\Scripts\gist-cache-rs.ps1

# Linux/macOS
rm ~/.config/powershell/scripts/gist-cache-rs.ps1

Don’t forget to remove the corresponding lines from your shell’s configuration file (.bashrc, .zshrc, or PowerShell profile).

Architecture and Design

This guide provides a comprehensive overview of gist-cache-rs’s architecture, design patterns, and implementation details.

Project Overview

gist-cache-rs is a Rust CLI tool for efficiently caching, searching, and executing GitHub Gists. It offers fast incremental updates, multi-language script execution support, and content caching capabilities.

Supported Platforms: Linux, macOS, Windows 10 or later

Supported Interpreters: bash, sh, zsh, python3, ruby, node, php, perl, pwsh (PowerShell Core), TypeScript (ts-node, deno, bun), uv

Architecture Overview

Module Structure

The codebase follows a modular architecture with clear separation of concerns:

src/
├── cache/              # Cache management layer
│   ├── content.rs      # Content cache (1001 lines)
│   ├── types.rs        # Data type definitions (246 lines)
│   ├── update.rs       # Incremental update logic (849 lines)
│   └── mod.rs
├── github/             # GitHub API integration
│   ├── api.rs          # GitHub CLI wrapper (212 lines)
│   ├── client.rs       # Trait definitions (104 lines)
│   └── mod.rs
├── execution/          # Script execution
│   ├── runner.rs       # Multi-interpreter execution (758 lines)
│   └── mod.rs
├── search/             # Search functionality
│   ├── query.rs        # Search query processing (420 lines)
│   └── mod.rs
├── cli.rs              # CLI argument processing (967 lines)
├── config.rs           # Configuration management (163 lines)
├── error.rs            # Error type definitions (160 lines)
├── lib.rs              # Library root
└── main.rs             # Entry point

Total: 16 files, approx. 4,660 lines

Cache Module (cache/)

The cache layer implements a sophisticated 2-layer caching structure:

types.rs: Core data structures

  • GistCache: Main cache container
  • GistInfo: Individual gist metadata
  • GistFile: File information
  • CacheMetadata: Cache metadata and timestamps

update.rs: CacheUpdater implementation

  • Handles incremental metadata cache updates using GitHub API’s since parameter
  • Automatically deletes corresponding content cache when Gist updates are detected
  • Implements rate limit checking and warning system

content.rs: ContentCache implementation

  • Manages individual Gist content files in ~/.cache/gist-cache/contents/{gist_id}/{filename}
  • Created on-demand during first execution
  • Provides approximately 20x performance improvement for subsequent executions
  • Implements cache cleaning functionality:
    • clean(): Remove old or orphaned cache entries
    • --older-than: Delete entries based on Gist’s updated_at timestamp
    • --orphaned: Remove content cache files without corresponding metadata
    • --dry-run: Preview deletion without actually removing files

GitHub Module (github/)

Handles all GitHub API interactions:

api.rs: GitHubApi wrapper

  • Wraps GitHub CLI (gh) for authentication
  • Implements rate limit checks
  • Handles gist retrieval operations
  • All GitHub operations use gh CLI instead of direct REST API calls

client.rs: Trait definitions

  • Defines the GitHubClient trait for dependency injection
  • Enables testing with mock implementations

Implements flexible search functionality:

query.rs: SearchQuery implementation

  • Multiple search modes:
    • Auto: Detects if query is a Gist ID (32-character hexadecimal), or searches filename/description
    • ID: Direct ID search
    • Filename: Searches filenames only
    • Description: Searches descriptions only
  • Interactive selection UI using numbered prompts

Execution Module (execution/)

Handles multi-interpreter script execution:

runner.rs: ScriptRunner implementation

  • Supports multiple interpreters (bash, python, ruby, node, php, perl, pwsh, TypeScript, uv)
  • Two execution modes:
    • Stdin-based: Default for most interpreters
    • File-based: Required for uv, php, pwsh, TypeScript interpreters

Special Interpreter Handling:

  • uv: File-based execution for PEP 723 metadata support
  • php: Forced file-based execution for reliable argument handling
  • pwsh/powershell: File-based execution for script execution policy compatibility
  • TypeScript interpreters (ts-node, deno, bun): File-based execution for module resolution
    • ts-node: Executes TypeScript on Node.js
    • deno: Uses deno run command in Deno runtime
    • bun: Executes in Bun runtime
  • Interactive mode: Uses inherit() for stdio to support commands like read

Configuration (config.rs)

Manages application configuration:

Cache paths (platform-specific):

  • Overridable by environment variable GIST_CACHE_DIR (for testing)
  • Unix: ~/.cache/gist-cache/cache.json and ~/.cache/gist-cache/contents/
  • Windows: %LOCALAPPDATA%\gist-cache\cache.json and %LOCALAPPDATA%\gist-cache\contents\

Download path: Uses dirs::download_dir() to conform to OS standards

Test isolation: Can be tested without affecting actual user cache by setting GIST_CACHE_DIR

Error Handling (error.rs)

Centralized error handling using thiserror crate for type-safe error management.

Key Design Patterns

1. Incremental Updates

Metadata cache updates use GitHub API’s since parameter to fetch only changed gists. Timestamp stored in last_updated field of cache.json.

2. 2-Layer Caching (On-demand)

Metadata Cache:

  • Stores gist metadata (id, description, files, updated_at) in cache.json
  • Updated with the update command

Content Cache:

  • Stores actual script body in contents/{gist_id}/{filename}
  • Created on-demand during execution
  • Automatically deleted when Gist updates

Cache Freshness Management: The update command compares updated_at of new and old metadata, and deletes the content cache directory (contents/{gist_id}/) for updated Gists.

3. GitHub CLI Integration

Uses gh command for authentication and API access instead of direct REST API calls. This provides:

  • Automatic authentication handling
  • Consistent credential management
  • Better error messages

4. Multi-Interpreter Support

The execution layer abstracts different interpreters and implements special handling:

  • Shell scripts (bash/sh/zsh): Direct execution
  • uv: File-based using uv run command for PEP 723 support
  • php: Forced file-based execution for reliable argument handling
  • pwsh/powershell: Forced file-based execution for script execution policy compatibility
  • TypeScript (ts-node, deno, bun): Forced file-based execution for module resolution
  • Others: Standard stdin-based execution

5. Search Modes

Supports flexible searching:

  • Auto: Intelligent detection of query type
  • ID: Direct ID search for exact matches
  • Filename: Searches filenames only
  • Description: Searches descriptions only

6. --force Option

When --force is specified with the run command:

  1. Automatically executes the update command (incremental update, not update --force)
  2. If the Gist was updated, the content cache is deleted
  3. Fetches and executes the latest version
  4. Creates a new cache

This ensures that the latest version is always executed during active development.

7. --download Option

When --download is specified with the run command:

  • Saves the Gist file to the download folder (~/Downloads)
  • Convenient for saving files separately from executable script caches
  • Content cache is also automatically created during download
  • Can be used with other options (--preview, --force, --interactive, etc.)

Important Implementation Details

Date and Time Handling

All timestamps use ISO 8601 format (%Y-%m-%dT%H:%M:%SZ) without sub-seconds to maintain compatibility with the original bash implementation. Custom serializer/deserializer is available in cache/types.rs.

Cache File Format

Structure of cache.json:

{
  "metadata": {
    "last_updated": "2024-01-01T12:00:00Z",
    "total_count": 42,
    "github_user": "username"
  },
  "gists": [...]
}

Execution Modes

  • Stdin Mode (default): Pipes script content directly to the interpreter
  • File Mode (uv, php, interactive): Creates a temporary file for execution
  • Interactive Mode (-i): Uses inherit() for stdio to support read command in scripts
  • Preview Mode (-p/--preview): Displays Description, Files, and Gist content without execution

Platform-Specific Implementations

Windows Support:

  • Permission Settings: Uses conditional compilation (#[cfg(unix)]) to run chmod only on Unix
  • Path Settings: Uses platform-specific cache directories
    • Unix: ~/.cache/gist-cache
    • Windows: %LOCALAPPDATA%\gist-cache
  • Installation Script: Provides PowerShell version (script/setup.ps1)

Cross-Platform Design:

  • Explicit branching with conditional compilation (cfg attributes)
  • Prioritizes platform-independent code
  • Prevents degradation in existing Linux/macOS environments

Rate Limiting

The Updater checks the rate limit and warns if remaining requests are less than 50. Forced full updates via update --force can consume significant rate limits as it fetches all gists.

Content Cache Behavior Flow

  1. First Execution: Fetches content from GitHub API and creates a cache after execution
  2. Subsequent Executions: Reads from cache for faster execution (no network access, ~20x faster)
  3. Gist Update: The update command detects changes and automatically deletes the content cache
  4. First Execution After Update: Fetches the latest version from API and creates a new cache

--force Option Behavior

When run --force is specified:

  1. Automatically executes the update command (incremental update)
  2. If the Gist was updated, the content cache is deleted
  3. Fetches and executes the latest version
  4. Creates a new cache

This ensures that even when Gists are frequently updated during development, the latest version is always executed.

Cache Management

Content cache management functions implemented with cache subcommand:

  • cache list: Displays a list of cached Gists (ID, description, filename, update time)
  • cache size: Displays the total size of the cache directory
  • cache clean: Deletes orphaned caches (not yet implemented, planned for future)
  • cache clear: Deletes all content caches (with confirmation prompt)

Methods provided by ContentCache struct:

  • list_cached_gists(): Get a list of cached Gist IDs
  • total_size(): Calculate the total size of the cache directory
  • clear_all(): Delete all caches
  • read(), write(), exists(): Read/write individual caches

Development Commands

Build and Test

# Development build
cargo build

# Release build (optimized)
cargo build --release

# Local installation
cargo install --path .

# Run tests
cargo test

# Run tests with verbose output
cargo test -- --nocapture

Code Quality Checks (via justfile)

# Run all checks (format, lint, test)
just check

# Format check only
just fmt-check

# Lint with clippy
just lint

# Run tests silently
just test

# Auto-format code
just fmt

# CI checks (treat warnings as errors)
just ci-check

Application Execution

# Cache update
cargo run -- update
cargo run -- update --force
cargo run -- update --verbose

# Gist execution
cargo run -- run <query> [interpreter] [args...]
cargo run -- run --preview <query>
cargo run -- run --interactive <query>
cargo run -- run --force <query>  # Update cache before execution
cargo run -- run --download <query>  # Save to download folder

# Cache management
cargo run -- cache list
cargo run -- cache size
cargo run -- cache clear

Dependencies

Primary Runtime Dependencies

  • tokio: Asynchronous runtime
  • reqwest: HTTP client (unused, remnant from direct API implementation era)
  • serde/serde_json: Serialization
  • clap: CLI argument parsing
  • chrono: Date and time handling
  • anyhow/thiserror: Error handling
  • dirs: Platform-specific directory detection
  • colored: Terminal output coloring

Development Dependencies

  • mockall: Mocking library (for external dependency testing)
  • tempfile: Temporary files/directories (for testing)
  • assert_cmd: For CLI testing (for future integration tests)

Release Process

Automated Release Builds

When a tag is pushed, GitHub Actions automatically builds and releases platform-specific binaries.

# Update version
vim Cargo.toml CHANGELOG.md
git add Cargo.toml CHANGELOG.md
git commit -m "🔖 Bump version to 0.5.0"

# Create and push tag
git tag v0.5.0
git push origin main
git push origin v0.5.0

Build Target Platforms

  • Linux (x86_64): gist-cache-rs-linux-x86_64.tar.gz
  • macOS (x86_64): gist-cache-rs-macos-x86_64.tar.gz
  • macOS (Apple Silicon): gist-cache-rs-macos-aarch64.tar.gz
  • Windows (x86_64): gist-cache-rs-windows-x86_64.zip

Workflow

Defined in .github/workflows/release.yml:

  1. create-release: Creates release page, generates release notes
  2. build-release: Parallel builds (4 platforms), uploads assets

Test Strategy and Execution Guide

Overview

gist-cache-rs’s test strategy is structured in a three-layer architecture: unit tests, integration tests, and E2E tests.

Current Coverage: 68.95% (533/773 lines) Number of Automated Tests: 153 (Unit 120 + Integration 33) Manual E2E Tests: 26 cases


Test Pyramid Structure

Test TypeCountLocationExecution Method
Unit Tests120src/ within #[cfg(test)]cargo test (auto)
Integration Tests33tests/ directorycargo test (auto)
E2E Tests26 casesdocs/tests/Manual execution
Total153--

Principles of the Test Pyramid:

  • Most unit tests (78%) - Fast, no external dependencies
  • Integration tests in the middle (22%) - Verifies actual process execution
  • Minimal E2E tests (manual) - Comprehensive user-centric verification

Test Execution

Basic Test Execution

# Run all tests
cargo test

# With verbose output
cargo test -- --nocapture

# Run specific tests only
cargo test test_cache_content

Running Tests with ignore Attribute

# Run tests including those with the ignore attribute
cargo test -- --include-ignored

# Run only tests with the ignore attribute
cargo test -- --ignored

Coverage Measurement

# Display coverage to standard output
cargo tarpaulin --out Stdout

# Generate HTML report
cargo tarpaulin --out Html --output-dir coverage

# See docs/testing/COVERAGE.md for details

Test Configuration

1. Unit Tests (120)

Location: src/ within #[cfg(test)] module

Coverage Target:

  • Data structures and serialization (cache/types.rs)
  • Cache management logic (cache/content.rs, cache/update.rs)
  • Search logic (search/query.rs)
  • CLI argument processing (cli.rs)
  • Configuration management (config.rs)
  • Error handling (error.rs)
  • Basic functionality of the execution runner (execution/runner.rs)
  • GitHub API mock (github/client.rs)

Features:

  • Fast execution (no external dependencies)
  • Excludes GitHub API dependencies with MockGitHubClient
  • Automatable in CI/CD

2. Integration Tests (33)

Location: tests/ directory

2.1 CLI Tests (tests/cli_tests.rs) - 15

  • Verification of command-line argument processing
  • Subcommand operation verification (update, run, cache)
  • Error case verification (authentication errors, no cache, etc.)
  • Flag combination verification (--preview, --force, --filename, etc.)

2.2 Interpreter Integration Tests (tests/integration_test.rs) - 12

  • Bash, Python, Node.js execution tests
  • TypeScript (ts-node, deno, bun) execution tests
  • Ruby, Perl, PHP execution tests
  • Argument passing, error handling
  • Preview mode operation verification

2.3 Runner Tests (tests/runner_test.rs) - 6

  • Detailed verification of script execution logic
  • Cache creation operation verification
  • Download mode operation verification
  • Force file-based execution verification
  • Multi-file Gist selection logic

Features:

  • Verifies actual process execution
  • Unix environment only (#[cfg_attr] controlled)
  • Automatically skipped if interpreter is not installed

3. E2E Tests (26 cases, manual)

Location: docs/tests/

Test Sets:

  1. Caching functionality (test_set_01_caching.md) - 8 cases
  2. Search functionality (test_set_02_search.md) - 6 cases
  3. Interpreter (test_set_03_interpreter.md) - 7 cases
  4. Preview functionality (test_set_04_preview.md) - 5 cases

Features:

  • Comprehensive verification using actual Gists
  • User-centric workflow verification
  • Detailed reproducible steps included

Testing Policy

What to Cover with Unit Tests

Targets:

  • Business logic
  • Data transformation/serialization
  • Error handling
  • Mockable external dependencies

Not Targets:

  • External process execution (bash, python, etc.) → Verified by integration tests
  • GitHub CLI (gh command) → Replaced by MockGitHubClient, or #[ignore] tests
  • User input processing → Verified by E2E tests

Test Quality Metrics

Target Coverage: 60-70% (Standard for CLI tools) Current Coverage: 68.95% ✅ Target achieved

Reasons for Achievement:

  • Core logic has high coverage (types 100%, config 96%, content 83%, cli 78%)
  • External process dependent code (runner.rs 20%, api.rs 8%) verified by integration tests
  • Low coverage for thin wrappers is acceptable

Troubleshooting

Tests are filtered out

Cause: Execution in non-Unix environment, or interpreter not installed

Solution:

  • Unix environment recommended for integration tests
  • Install interpreters (bash, python, node, etc.)
  • Or, automatic skipping is normal behavior

Coverage cannot be measured

Cause: tarpaulin is not installed

Solution:

cargo install cargo-tarpaulin

Integration tests fail

Cause: Interpreter (bash, python, node, etc.) not installed

Solution:

  • Install necessary interpreters
  • Or, skipping is normal behavior

Detailed Documentation


References


Last Updated: 2025-11-06 Current Coverage: 68.95% Number of Automated Tests: 153 Covered Lines: 533/773 lines

Code Coverage Measurement Guide

Current Coverage Status

Overall Coverage: 68.95% (533/773 lines) Number of Automated Tests: 153 (Unit 120 + Integration 33) Target: 60-70% ✅ Achieved

Module-wise Coverage

ModuleCoverageCovered/TotalStatus
cache/types.rs100.00%15/15✅ Perfect
config.rs96.15%25/26✅ Excellent
cache/content.rs83.54%66/79✅ Good
cli.rs78.16%161/206✅ Good
search/query.rs70.59%48/68🟡 Good
cache/update.rs62.24%89/143🟡 Improvement needed
execution/runner.rs19.88%34/171🔴 Many external dependencies
github/api.rs8.33%5/60🔴 Many external dependencies
error.rs0.00%0/1🟡 No test required
main.rs0.00%0/4🟡 Verified by E2E

Coverage Measurement Commands

Basic Measurement

# Display coverage to standard output
cargo tarpaulin --out Stdout

# Generate HTML report
cargo tarpaulin --out Html --output-dir coverage

# Generate both
cargo tarpaulin --out Html --out Stdout --output-dir coverage

Detailed Measurement

# With detailed output (coverage information per line)
cargo tarpaulin --out Stdout --verbose

# Timeout setting (for large projects)
cargo tarpaulin --out Stdout --timeout 120

# Display only the last 100 lines (abbreviates long output)
cargo tarpaulin --out Stdout 2>&1 | tail -100

Module-wise Measurement

# Test only specific modules
cargo tarpaulin --out Stdout --lib

# Exclude specific files
cargo tarpaulin --out Stdout --exclude-files 'tests/*'

# Run only specific tests
cargo tarpaulin --out Stdout --test integration_test

Measurement via justfile

# If coverage task is already added to justfile
just coverage

# Or directly
just check  # lint + test (no coverage)

Coverage Design Philosophy

High Coverage Modules (70% or more)

Core business logic maintains high coverage:

  • cache/types.rs (100%): Data structures, serialization
  • config.rs (96%): Configuration management, platform-specific paths
  • cache/content.rs (84%): Content cache management
  • cli.rs (78%): CLI argument processing
  • search/query.rs (71%): Search logic

Medium Coverage Modules (50-70%)

Affected by external dependencies, but business logic covered by mocks:

  • cache/update.rs (62%): Tested with mocked GitHubClient

Low Coverage Modules (less than 50%)

Highly dependent on external processes/commands, quality ensured by integration tests:

  • execution/runner.rs (20%): Actual execution of bash, python, etc. → 12 languages verified by integration tests
  • github/api.rs (8%): gh command execution → Replaced by MockGitHubClient
  • main.rs (0%): Entry point → Verified by E2E tests
  • error.rs (0%): Simple type definition → Tested at runtime

How to Read Coverage Reports

Interpretation of Standard Output

|| Uncovered Lines:
|| src/cache/content.rs: 88, 90, 116, 118, ...

This indicates which lines in each file are not covered.

HTML Report

In the HTML report (coverage/index.html):

  • Green: Covered lines
  • Red: Uncovered lines
  • Gray: Unexecutable lines (comments, blank lines, etc.)

To open in a browser:

# For Linux
xdg-open coverage/index.html

# For macOS
open coverage/index.html

# For Windows
start coverage/index.html

Usage in CI/CD

GitHub Actions

- name: Run tests with coverage
  run: cargo tarpaulin --out Xml --output-dir coverage

- name: Upload coverage to Codecov
  uses: codecov/codecov-action@v3
  with:
    files: ./coverage/cobertura.xml

Troubleshooting

cargo-tarpaulin is not installed

cargo install cargo-tarpaulin

Timeout error

# Extend timeout
cargo tarpaulin --out Stdout --timeout 300

Out of memory

# Limit parallel execution
cargo tarpaulin --out Stdout --jobs 1

References


Last Updated: 2025-11-06 Current Coverage: 68.95% Number of Automated Tests: 153 Covered Lines: 533/773 lines

Test Inventory - Classification and Overview of All Tests

Created Date: 2025-11-06 Total Number of Tests: 153 Coverage: 68.95% (533/773 lines)


Test Classification

Test Pyramid Structure

Test TypeCountLocation
Unit Tests120src/ within #[cfg(test)]
Integration Tests33tests/ directory
E2E Tests26 casesdocs/tests/ (Manual)
Total153-

1. Unit Tests (120)

1.1 cache/types.rs (11)

Location: src/cache/types.rs within #[cfg(test)] module

Purpose: Data structure serialization/deserialization, type conversion

Test NamePurposeImportance
test_gist_cache_serializationGistCache JSON conversion⭐⭐⭐
test_datetime_serializationDatetime serialization (without sub-seconds)⭐⭐⭐
test_datetime_deserializationDatetime deserialization⭐⭐⭐
test_gist_info_without_descriptionHandling Gist without description⭐⭐
test_github_gist_to_gist_infoGitHub API → Internal type conversion⭐⭐⭐
test_gist_file_cloneGistFile clone
test_cache_metadataMetadata structure⭐⭐
OthersBasic type operations

Coverage: 100% (15/15 lines)

Windows Support: ✅ Fully supported (no file I/O dependencies)


1.2 config.rs (5)

Location: src/config.rs within #[cfg(test)] module

Purpose: Configuration management, platform-specific path generation

Test NamePurposeImportance
test_config_newConfig initialization⭐⭐⭐
test_config_defaultDefault settings⭐⭐⭐
test_ensure_cache_dirCache directory creation⭐⭐⭐
test_ensure_download_dirDownload directory creation⭐⭐
test_cache_existsCache file existence check⭐⭐

Coverage: 96.15% (25/26 lines)

Windows Support: ✅ Fully supported (tests platform-specific path generation)


1.3 cache/content.rs (18)

Location: src/cache/content.rs within #[cfg(test)] module

Purpose: Content cache read/write, directory management

Test NamePurposeImportance
test_write_and_readBasic read/write⭐⭐⭐
test_read_nonexistent_fileError handling for non-existent files⭐⭐⭐
test_write_creates_gist_directoryAutomatic directory creation⭐⭐⭐
test_overwrite_existing_fileOverwriting existing file⭐⭐
test_multiple_files_in_same_gistMultiple file management⭐⭐⭐
test_delete_gistDeleting Gist cache⭐⭐
test_delete_gist_already_deletedHandling already deleted Gist
test_list_cached_gistsListing cached Gists⭐⭐
test_list_cached_gists_when_no_cache_dirHandling no cache directory⭐⭐
test_list_cached_gists_with_file_in_contents_dirHandling unexpected files⭐⭐
test_total_sizeCalculating cache size⭐⭐
test_total_size_when_no_cache_dirSize when no directory
test_clear_allClearing all caches⭐⭐
test_clear_all_when_emptyClearing empty directory
test_cache_path_generationPath generation accuracy⭐⭐
test_self_healing_unexpected_filesSelf-healing of anomalous files⭐⭐
2 OthersEdge cases

Coverage: 83.54% (66/79 lines)

Windows Support: ✅ Fully supported (cross-platform with tempfile)


1.4 cli.rs (21)

Location: src/cli.rs within #[cfg(test)] module

Purpose: CLI argument parsing, interpreter analysis, cache commands

Test NamePurposeImportance
test_parse_interpreter_bashBash interpreter parsing⭐⭐⭐
test_parse_interpreter_pythonPython interpreter parsing⭐⭐⭐
test_parse_interpreter_nodeNode interpreter parsing⭐⭐
test_parse_interpreter_rubyRuby interpreter parsing⭐⭐
test_parse_interpreter_phpPHP interpreter parsing⭐⭐
test_parse_interpreter_perlPerl interpreter parsing⭐⭐
test_parse_interpreter_pwshPowerShell Core interpreter parsing⭐⭐
test_parse_interpreter_powershellWindows PowerShell interpreter parsing⭐⭐
test_parse_interpreter_ts_nodets-node interpreter parsing⭐⭐
test_parse_interpreter_denoDeno interpreter parsing⭐⭐
test_parse_interpreter_bunBun interpreter parsing⭐⭐
test_parse_interpreter_uvuv interpreter parsing⭐⭐
test_parse_interpreter_poetryPoetry interpreter parsing⭐⭐
test_parse_interpreter_shsh interpreter parsing⭐⭐
test_parse_interpreter_zshzsh interpreter parsing⭐⭐
test_parse_interpreter_python_aliaspython3 alias⭐⭐
test_parse_interpreter_noneNo interpreter⭐⭐
test_parse_interpreter_custom_invalidInvalid custom interpreter⭐⭐⭐
test_format_bytesByte formatting⭐⭐
test_format_bytes_edge_casesByte boundary values⭐⭐
test_format_bytes_multiple_gbGB unit display
test_handle_cache_command_list_emptyEmpty cache list⭐⭐
test_handle_cache_command_list_with_cacheCache list display⭐⭐⭐
test_handle_cache_command_list_no_metadataList without metadata⭐⭐
test_handle_cache_command_sizeCache size display⭐⭐
test_handle_cache_command_cleanCache clean (unimplemented)
test_run_gist_cache_not_foundCache not found error⭐⭐⭐
test_run_gist_no_resultsNo search results error⭐⭐⭐
test_run_gist_with_filename_searchFilename search mode⭐⭐⭐
test_run_gist_with_description_searchDescription search mode⭐⭐⭐
test_print_run_helpHelp display

Coverage: 78.16% (161/206 lines)

Windows Support: ✅ Fully supported


1.5 search/query.rs (26)

Location: src/search/query.rs within #[cfg(test)] module

Purpose: Search functionality, ID/filename/description search

Test NamePurposeImportance
test_search_by_idID search⭐⭐⭐
test_search_id_no_matchID search no match⭐⭐
test_search_by_filenameFilename search⭐⭐⭐
test_search_by_filename_case_insensitiveCase-insensitive filename search⭐⭐⭐
test_search_filename_multiple_filesMultiple file Gist search⭐⭐⭐
test_search_by_descriptionDescription search⭐⭐⭐
test_search_by_description_case_insensitiveCase-insensitive description search⭐⭐⭐
test_search_by_description_no_descriptionGist without description⭐⭐
test_search_bothFilename + description search⭐⭐⭐
test_search_both_filename_only_matchFilename only match⭐⭐
test_search_both_description_only_matchDescription only match⭐⭐
test_search_both_multiple_matchesMultiple matches⭐⭐
test_search_both_no_descriptionBoth search when no description⭐⭐
test_search_mode_auto_detects_idAuto: ID detection⭐⭐⭐
test_search_mode_auto_detects_bothAuto: Keyword detection⭐⭐⭐
test_search_mode_auto_with_short_hexAuto: 31-char hex⭐⭐⭐
test_search_mode_auto_with_non_hexAuto: Non-hexadecimal⭐⭐⭐
test_search_with_auto_mode_idAuto mode: ID⭐⭐
test_search_with_auto_mode_keywordAuto mode: Keyword⭐⭐
test_search_no_resultsNo search results⭐⭐⭐
test_search_empty_gist_listEmpty Gist list⭐⭐
test_select_from_single_resultSelection of single result⭐⭐
test_select_from_empty_resultsSelection from empty results⭐⭐
3 OthersEdge cases

Coverage: 70.59% (48/68 lines)

Windows Support: ✅ Fully supported


1.6 cache/update.rs (16)

Location: src/cache/update.rs within #[cfg(test)] module

Purpose: Cache update logic, differential update, MockGitHubClient

Test NamePurposeImportance
test_updater_newCacheUpdater initialization⭐⭐
test_save_and_load_cacheCache save/load⭐⭐⭐
test_load_cache_missing_fileHandling missing file⭐⭐⭐
test_save_cache_invalid_jsonDetecting invalid JSON⭐⭐
test_update_force_with_mockForce update (Mock)⭐⭐⭐
test_update_differential_with_mockDifferential update (Mock)⭐⭐⭐
test_update_with_no_changesHandling no updates⭐⭐
test_update_with_rate_limit_warningRate limit warning⭐⭐⭐
test_update_auth_failureAuthentication failure error⭐⭐⭐
test_update_with_gist_modification_deletes_cacheCache deletion upon Gist modification⭐⭐⭐
test_cache_updater_with_verboseVerbose mode⭐⭐
test_update_verbose_modeVerbose detailed logs⭐⭐
test_update_differential_with_existing_cache_verboseVerbose differential update⭐⭐
test_update_with_low_rate_limit_verboseVerbose low rate limit⭐⭐
test_update_gist_modification_verboseVerbose Gist update⭐⭐
test_update_force_verbose_without_existing_cacheVerbose new cache⭐⭐

Coverage: 62.24% (89/143 lines)

Windows Support: ✅ Fully supported


1.7 execution/runner.rs (10)

Location: src/execution/runner.rs within #[cfg(test)] module

Purpose: Basic functionality of ScriptRunner (file selection, option settings)

Test NamePurposeImportance
test_runner_newScriptRunner initialization⭐⭐
test_run_optionsRunOptions settings⭐⭐
test_run_options_combinationsOption combinations⭐⭐
test_run_options_preview_modePreview mode⭐⭐
test_run_options_download_modeDownload mode⭐⭐
test_select_main_file_single_fileSingle file selection⭐⭐⭐
test_select_main_file_multiple_filesMultiple file selection⭐⭐⭐
test_select_main_file_by_interpreterInterpreter-specific selection⭐⭐⭐
test_select_main_file_with_explicit_filenameExplicit filename specification⭐⭐⭐
test_runner_with_different_interpretersBehavior of each interpreter⭐⭐
test_display_infoInformation display

Coverage: 19.88% → 69.01% (improved by integration tests)

Windows Support: ✅ Fully supported (excluding execution part)


1.8 github/api.rs (1)

Location: src/github/api.rs within #[cfg(test)] module

Purpose: Initialization of GitHubApi struct (execution tests are #[ignore])

Test NamePurposeImportance
test_api_structureBasic structure functionality
test_check_auth_when_authenticated (#[ignore])gh authentication check⭐⭐⭐
test_get_user (#[ignore])Get username⭐⭐
test_check_rate_limit (#[ignore])Rate limit check⭐⭐
test_fetch_gists_without_since (#[ignore])Get all Gists⭐⭐⭐
test_fetch_gists_with_since (#[ignore])Get differential Gists⭐⭐⭐

Coverage: 8.33% (5/60 lines)

Windows Support: ⚠️ Partial support (requires gh CLI)


1.9 github/client.rs (5)

Location: src/github/client.rs within #[cfg(test)] module

Purpose: MockGitHubClient operation verification

Test NamePurposeImportance
test_mock_check_auth_successMock authentication success⭐⭐
test_mock_get_userMock user retrieval⭐⭐
test_mock_check_rate_limitMock rate limit⭐⭐
test_mock_fetch_gistsMock Gist retrieval⭐⭐
test_mock_fetch_gist_contentMock content retrieval⭐⭐

Coverage: 100% (MockGitHubClient implementation)

Windows Support: ✅ Fully supported


1.10 error.rs (4)

Location: src/error.rs within #[cfg(test)] module

Purpose: Error type conversion, display

Test NamePurposeImportance
test_error_displayError display⭐⭐
test_error_from_ioIO error conversion⭐⭐
test_error_from_jsonJSON error conversion⭐⭐
test_error_from_reqwestHTTP error conversion
test_result_type_aliasResult type alias

Coverage: 0% (Error types tested at runtime)

Windows Support: ✅ Fully supported


2. Integration Tests (12)

2.1 tests/integration_test.rs (6)

Location: tests/integration_test.rs

Purpose: Verification of actual interpreter execution

Dependencies: bash, python3, node (Unix environment recommended)

Test NamePurposefixtureImportance
test_execute_bash_scriptBash executionhello.sh⭐⭐⭐
test_execute_python_scriptPython executionhello.py⭐⭐⭐
test_execute_node_scriptNode.js executionhello.js⭐⭐
test_execute_with_argumentsArgument passingargs_echo.sh⭐⭐⭐
test_execute_failing_scriptError detectionerror_exit.sh⭐⭐⭐
test_preview_mode_does_not_executePreview modehello.sh⭐⭐⭐

Contribution to Coverage: execution/runner.rs +30-40%

Windows Support: ⚠️ Conditional

  • bash: Requires Git Bash or WSL
  • python3: Requires Windows Python
  • node: Requires Windows Node.js

2.2 tests/runner_test.rs (6)

Location: tests/runner_test.rs

Purpose: Detailed verification of ScriptRunner operations

Dependencies: bash (Unix environment recommended)

Test NamePurposefixtureImportance
test_download_mode_creates_fileDownload featurehello.sh⭐⭐⭐
test_preview_with_download_modePreview + Downloadhello.sh⭐⭐
test_cache_creation_after_executionCache creationhello.sh⭐⭐⭐
test_multiple_files_gistMultiple file selectionhello.sh⭐⭐⭐
test_force_file_based_executionFile-based executionhello.sh⭐⭐
test_script_with_empty_argumentsEmpty argument handlinghello.sh⭐⭐

Contribution to Coverage: execution/runner.rs +10-15%

Windows Support: ⚠️ Conditional (requires bash)

| args_echo.sh | Argument passing test | echo "Arguments: $@" | | error_exit.sh | Error test | exit 1 |

Windows Support: ⚠️ Newline code attention (LF recommended)


3. E2E Tests (26 Cases, Manual)

3.1 E2E Test Overview

What is E2E Testing?: Verification of complete user workflow by actually executing the binary from the command line

Reason for Not Implemented Yet: Lower priority than integration tests

Planned Implementation:

tests/e2e/
├── test_full_workflow.sh        # Complete flow of update → run
├── test_cache_management.sh     # cache list/size/clear
└── test_option_combinations.sh  # --force, --preview, --download

Expected Benefits:

  • Full assurance of user experience
  • Integration verification between modules
  • Automation of manual tests

Test Classification Summary

ClassificationNumber of TestsCoverage ContributionWindows SupportStatus
Unit Tests12057-60%✅ Full✅ Completed
Integration Tests12+10-11%⚠️ Conditional✅ Completed
E2E Tests26 cases+2-3%⚠️ Conditional📝 Completed
Total13268.18%--

Test Importance Criteria

MarkMeaningDescription
⭐⭐⭐EssentialDirectly leads to data loss or critical bugs
⭐⭐RecommendedAffects user experience or major features
OptionalEdge cases or rare situations

Coverage Contribution

High Contribution (10% or more)

  • Integration Tests (tests/integration_test.rs + runner_test.rs): +10.87%
    • Covers execution part of execution/runner.rs

Medium Contribution (5-10%)

  • cli.rs Unit Tests: Contributes approx. 5-6% to overall
  • search/query.rs Unit Tests: Contributes approx. 4-5% to overall

Low Contribution (1-5%)

  • Individual unit tests for each module

Test Implementation History

Phase 1-5 (Unit Tests): 120

  • cache/types.rs: 11
  • config.rs: 5
  • cache/content.rs: 18
  • cli.rs: 21
  • search/query.rs: 26
  • cache/update.rs: 16
  • execution/runner.rs: 10
  • github/client.rs: 5
  • error.rs: 4
  • Others: 4

Achieved Coverage: 57.31%

Phase 6 (Integration Tests): 12

  • tests/integration_test.rs: 6
  • tests/runner_test.rs: 6
  • tests/fixtures/: 5 files

Achieved Coverage: 68.18% (+10.87%)

Phase 7 (E2E): 26 Cases (Manual Execution)

Expected Coverage: 70-71% (+2-3%)


Last Updated: 2025-11-06 Coverage: 68.95% (533/773 lines)

Evaluation of the Necessity of GitHub CLI Related Tests

Date of Execution

2025-11-05

Evaluation Purpose

To evaluate the necessity of automated and reproducible tests for GitHub CLI (gh) related functionalities.

Current Testing Status

1. Automated Unit Tests (using MockGitHubClient)

Location: src/github/client.rs Coverage Target: All methods of the GitHubClient trait Execution Environment: CI/CD, Local (gh authentication not required)

TestContentStatus
test_mock_check_auth_successMock for authentication status check✅ Automated Execution
test_mock_get_userMock for getting username✅ Automated Execution
test_mock_check_rate_limitMock for rate limit check✅ Automated Execution
test_mock_fetch_gistsMock for fetching Gist list✅ Automated Execution
test_mock_fetch_gist_contentMock for fetching Gist content✅ Automated Execution

Features:

  • No external dependencies (no GitHub access required)
  • Fast (no network required)
  • 100% reproducibility (controlled by mocks)
  • Fully covers business logic

2. Manual Tests (with #[ignore] attribute)

Location: src/github/api.rs Execution Method: cargo test -- --ignored Execution Environment: Requires a gh authenticated environment

TestContentStatus
test_check_auth_when_authenticatedActual gh authentication status check🟡 Manually executable
test_get_userActual GitHub username retrieval🟡 Manually executable
test_check_rate_limitActual rate limit check🟡 Manually executable
test_fetch_gists_without_sinceActual full Gist retrieval🟡 Manually executable
test_fetch_gists_with_sinceActual differential Gist retrieval🟡 Manually executable

Features:

  • Requires GitHub authentication
  • Network dependent
  • Consumes API rate limit
  • Verifies actual gh CLI commands

3. Functional Verification Tests (Manual E2E)

Location: docs/tests/*.md Execution Method: Manual execution (following procedures described in documentation) Coverage: End-to-end functionality

Test SetNumber of Test CasesStatusVerification Content
test_set_01_caching.mdTC1-8✅ ImplementedCache update, differential retrieval, –force
test_set_02_search.mdTC1-6✅ ImplementedAll search modes
test_set_03_interpreter.mdTC1-7✅ ImplementedMulti-language interpreter
test_set_04_preview.mdTC1-5✅ ImplementedPreview function

Features:

  • Comprehensive verification using actual Gists
  • Includes Gist editing on GitHub (TC4, TC5)
  • User-centric operation verification
  • Detailed reproducible steps

Characteristics of GitHubApi Implementation

src/github/api.rs (212 lines) is designed as a thin wrapper:

#![allow(unused)]
fn main() {
// Example: check_auth() - 18 lines
pub fn check_auth(&self) -> Result<()> {
    let output = Command::new("gh")
        .args(["auth", "status"])
        .output()
        .map_err(|_| GistCacheError::NotAuthenticated)?;

    if !output.status.success() {
        return Err(GistCacheError::NotAuthenticated);
    }
    Ok(())
}
}

Implementation Characteristics:

  1. Simple Command Execution: Just calls the gh CLI command
  2. Minimal Logic: No logic other than error handling and JSON parsing
  3. Clear Responsibilities: Only responsible for GitHub access
  4. Trait Separation: Coupled with business logic only via traits

Test Coverage Analysis

ModuleCoverageReason for Not Covered
github/api.rs8.33%gh CLI dependency, external command execution
github/client.rs100.00%Fully covered by MockGitHubClient
cache/update.rs62.24%Main logic covered by MockGitHubClient

Important Insights:

  • Low coverage of github/api.rs is not an issue: It is a thin wrapper and contains no business logic.
  • Business logic has high coverage: Code dependent on the GitHubClient trait is sufficiently tested by MockGitHubClient.

Evaluation of the Necessity of Additional Automated Tests

Advantages

  1. Automated Verification in CI/CD: Automatically detects gh-related regressions
  2. Improved Developer Experience: Can verify gh operations locally
  3. Synchronization of Documentation and Code: Automates manual tests

Disadvantages

  1. Addition of External Dependencies:

    • Requires GitHub authentication settings in CI environment
    • Token management becomes complex even with GitHub Actions secrets
    • Tests become unstable due to network failures
  2. API Rate Limit:

    • Each test consumes GitHub API
    • Rate limit decreases with each CI execution
    • fetch_gists tests consume particularly large amounts
  3. Brittleness:

    • Affected by GitHub API changes
    • Tests break if they rely on actual Gist data which changes
    • Requires creation and management of Gists for testing
  4. Duplication of Tests:

    • Business logic is already covered by MockGitHubClient
    • Verification of gh CLI command behavior is outside the scope of this project
    • Limited added value
  5. Maintenance Cost:

    • Complex test environment setup
    • Additional CI configuration maintenance
    • Requires 대응 to GitHub API changes

Recommendations

Conclusion: Additional automated tests are not necessary

Reasons:

  1. Appropriate separation of concerns is achieved

    • Business logic: Automated tests with MockGitHubClient (high coverage)
    • gh CLI wrapper: Thin wrapper with no complex logic
    • E2E verification: Comprehensively verified by manual tests
  2. Inappropriate risk/cost ratio

    • Bugs detectable by additional tests: gh CLI command syntax errors, output format changes
    • These are sufficiently covered by existing #[ignore] tests and functional verification tests
    • Low value compared to increased CI environment complexity and maintenance costs
  3. Current testing strategy is appropriate

    • Automated tests: Full coverage of business logic (using MockGitHubClient)
    • Manual tests: Verify gh CLI behavior as needed (#[ignore] tests)
    • E2E verification: Comprehensive user-centric verification (docs/tests)
  4. Minimization of external dependencies

    • gh CLI is assumed to work in the user’s environment
    • Value of configuring gh authentication in CI environment is limited
    • Developers can manually verify with cargo test -- --ignored as needed

Alternatives (if automation is needed in the future)

Options if additional verification is needed in the future:

Option 1: GitHub Actions dedicated integration test workflow

name: GitHub CLI Integration Tests
on:
  workflow_dispatch:  # Manual execution only

jobs:
  gh-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup gh CLI
        run: gh auth login --with-token <<< "${{ secrets.GH_TOKEN }}"
      - name: Run ignored tests
        run: cargo test -- --ignored

Features:

  • Manual trigger only (does not run with every CI execution)
  • Used as final verification before release
  • Minimizes impact on rate limit

Option 2: Provide test scripts

#!/bin/bash
# scripts/test_gh_integration.sh
# Script for developers to run manually as needed

echo "Running GitHub CLI integration tests..."
echo "Note: GitHub authentication is required (gh auth status)"

# Check authentication
if ! gh auth status > /dev/null 2>&1; then
    echo "Error: GitHub authentication is required. Please run 'gh auth login'."
    exit 1
fi

# Run ignored tests
echo "Running: cargo test -- --ignored"
cargo test -- --ignored

echo "Completed!"

Features:

  • Developers run manually as needed
  • No impact on CI environment
  • Simple re-execution steps

Summary

ItemEvaluation
Current test quality✅ Sufficient (68.95% coverage, appropriate separation of concerns)
Necessity of additional automated tests❌ Not necessary (cost > benefit)
Effectiveness of MockGitHubClient✅ Sufficient (fully covers business logic)
Effectiveness of functional verification tests✅ Sufficient (E2E verified, reproducible)
Effectiveness of #[ignore] tests✅ Sufficient (manually executable as needed)

Final Recommendation:

  • Maintain current testing strategy
  • Do not implement additional automated tests
  • Manually verify with cargo test -- --ignored as needed
  • In CI/CD, run only existing automated tests (using MockGitHubClient)

This strategy optimizes the balance between test coverage and maintenance costs.

mdbook Documentation Setup

This guide describes how to set up, build, and deploy the mdbook documentation for gist-cache-rs.

Local Development

Prerequisites

Install mdbook:

cargo install mdbook

Build and Serve Locally

# Build the documentation
mdbook build

# Serve with live reload (recommended for development)
mdbook serve

# The documentation will be available at http://localhost:3000

Directory Structure

gist-cache-rs/
├── book.toml                     # mdbook configuration
├── book/
│   ├── src/                      # Source markdown files
│   │   ├── README.md
│   │   ├── SUMMARY.md            # Table of contents
│   │   ├── user-guide/
│   │   ├── developer-guide/
│   │   └── test-specs/
│   └── book/                     # Generated HTML (gitignored)
└── .github/workflows/
    └── deploy-mdbook.yml         # GitHub Pages deployment

GitHub Pages Deployment

Initial Setup

  1. Enable GitHub Pages in Repository Settings

    • Go to your repository on GitHub
    • Navigate to SettingsPages
    • Under “Source”, select GitHub Actions
  2. Push Changes to Main Branch

    • The workflow automatically triggers when changes to documentation files are pushed
    • Monitored paths:
      • book/**
      • book.toml
      • README.md
      • .github/workflows/deploy-mdbook.yml
  3. Manual Deployment (Optional)

    • Go to Actions tab in your repository
    • Select Deploy mdbook to GitHub Pages workflow
    • Click Run workflowRun workflow

Deployment Workflow

The deployment workflow (.github/workflows/deploy-mdbook.yml) performs the following:

  1. Build

    • Checks out the repository
    • Sets up mdbook (latest version)
    • Builds the documentation with mdbook build
    • Uploads the generated HTML as a Pages artifact
  2. Deploy

    • Deploys the artifact to GitHub Pages
    • The documentation will be available at: https://<username>.github.io/<repository-name>/

Verification

After deployment:

  1. Check the Actions tab for workflow status
  2. Once completed, visit your GitHub Pages URL:
    • For this repository: https://7rikazhexde.github.io/gist-cache-rs/

Troubleshooting

Workflow fails with “Pages deployment is not enabled”

Solution: Ensure GitHub Pages is enabled in repository settings with source set to “GitHub Actions”

Changes not reflected after deployment

Solution:

  • Check that your changes were committed to the main branch
  • Wait a few minutes for GitHub Pages cache to update
  • Try a hard refresh in your browser (Ctrl+Shift+R)

Build fails with “mdbook not found”

Solution: This should not happen in CI as the workflow installs mdbook automatically. For local development, run cargo install mdbook

Updating Documentation

Editing Content

  1. Edit markdown files in book/src/
  2. Test locally with mdbook serve
  3. Commit and push changes
  4. The workflow will automatically rebuild and deploy

Adding New Pages

  1. Create a new markdown file in the appropriate directory:

    • User documentation: book/src/user-guide/
    • Developer documentation: book/src/developer-guide/
    • Test specifications: book/src/test-specs/
  2. Add the new page to book/src/SUMMARY.md:

    - [New Page Title](path/to/new-page.md)
    
  3. Test locally and push changes

Modifying Structure

Edit book/src/SUMMARY.md to reorganize the table of contents. The structure in SUMMARY.md determines the navigation menu.

Configuration

book.toml

Key configurations:

  • title: Documentation title
  • src: Source directory (book/src)
  • build-dir: Output directory (book/book)
  • Theme: Rust theme with Navy dark theme
  • Features: Search, code folding, edit links

Customization

To customize the appearance:

  1. Add custom CSS in book/theme/custom.css
  2. Modify book.toml settings
  3. See mdbook documentation for all options

CI/CD Integration

The deployment workflow integrates with:

  • Trigger: Push to main branch or manual workflow dispatch
  • Permissions: Read contents, write to Pages, id-token for deployment
  • Concurrency: Only one deployment runs at a time

Additional Resources

Test Results Summary

Functional Verification Tests

Functional Verification Test Results (2025-11-01)

Target Gist:

  • ID: 7bcb324e9291fa350334df8efb7f0deb
  • Filename: hello_args.sh
  • URL: https://gist.github.com/7rikazhexde/7bcb324e9291fa350334df8efb7f0deb

Test Result Summary

TCTest ContentResultNotes
TC1First execution (no cache)✅ SuccessConfirmed retrieval from API, cache creation
TC2Second execution (with cache)✅ SuccessConfirmed fast loading from cache
TC3update command (no change)✅ SuccessConfirmed cache retention
TC4Behavior after Gist update✅ SuccessConfirmed automatic cache deletion, latest version retrieval
TC5–force option✅ SuccessConfirmed automatic update execution, latest version retrieval
TC6cache list command✅ SuccessConfirmed cache list display
TC7cache size command✅ SuccessConfirmed cache size display
TC8cache clear command✅ SuccessConfirmed all cache deletion

All 8 test cases passed.

Key Verification Points

Basic Content Cache Operation

  • On first execution, retrieves from GitHub API and caches to ~/.cache/gist-cache/contents/{gist_id}/{filename}
  • Message “Info: Cache not found, fetching from GitHub API…” displayed correctly
  • Subsequent executions load instantly from cache (no network access, approx. 20x faster)

Metadata Update and Cache Freshness Management

  • update command detects Gist update: “Gist update detected: 7bcb324e9291fa350334df8efb7f0deb”
  • Content cache directory for updated Gist is automatically deleted
  • Unchanged Gists retain their cache

Behavior after Gist update (TC4)

  • Edited Gist on GitHub (added comment: # TEST MODIFICATION 1)
  • Confirmed “Updated: 1 item” with update --verbose
  • Confirmed content cache directory is deleted
  • Latest version retrieved and reflected in new cache on next execution

–force Option Behavior (TC5)

  • Executed with run --force without manually running update command
  • update is automatically executed before run (output: “Updating Gist cache…”)
  • Gist update detected, cache automatically deleted (output: “Updated: 1 item”, “Cache deleted: 1 item”)
  • Latest version (# TEST MODIFICATION 2) retrieved and executed
  • Confirmed ability to always run the latest version of Gists under development

cache Command Behavior (TC6-8)

  • cache list: Displays list of cached Gists (ID, description, filename, updated_at, total count)
  • cache size: Displays cache size information (number of Gists, total size, directory path)
  • cache clear: Clears all caches with a confirmation prompt

Technical Notes

  • Gist updates automated using GitHub CLI (gh api)
  • Two edits performed to test TC4 and TC5
  • All tests confirmed expected behavior
  • Rate limit remaining: 4971 (at end of tests)

Functional Verification Test Results (Test Set 2: Search Functionality) (2025-11-01)

Test Design Document: request/functional_verification_test_design_search.md

Target Gists:

  • Multiple hello_args related Gists (total 7)
  • Test ID: 7bcb324e9291fa350334df8efb7f0deb (hello_args.sh)

Test Result Summary

TCTest ContentResultNotes
TC1Auto search (default)✅ SuccessKeyword “hello” hit 7 items, confirmed selection UI
TC2Direct ID specification (–id)✅ SuccessConfirmed ID specification mode message display
TC3Filename search (–filename)✅ SuccessSingle result, confirmed direct execution
TC4Description search (–description)✅ SuccessTag search “#bash” hit 2 items, confirmed
TC5Selection from multiple candidates✅ SuccessSelected number 7, confirmed Python script execution
TC60 search results error✅ SuccessConfirmed error message, exit code 1

All 6 test cases passed.

Key Verification Points

Auto Search (TC1)

  • Keyword “hello” hit 7 Gists
  • Multiple candidate selection UI (numbered list) displayed correctly
  • Description and filename of each Gist displayed
  • After selecting a number, the corresponding Gist is executed

Direct ID Specification (TC2)

  • Specified Gist directly with --id 7bcb324e9291fa350334df8efb7f0deb
  • Skipped search process and executed directly
  • “ID specification mode” message displayed

Filename Search (TC3)

  • Exact match search with --filename hello_args.sh
  • Skipped selection UI for single result and executed directly
  • Only filename is searched, description is excluded

Description Search (TC4)

  • Tag search with --description "#bash"
  • Only Gists containing “#bash” in description hit (2 items)
  • Filename is not searched
  • Confirmed effective tag filtering

Selection UI from Multiple Candidates (TC5)

  • Keyword “hello” displayed 7 candidates
  • Selected number 7, confirmed Python script (hello_args.py) execution
  • Confirmed “Info: Cache not found, fetching from GitHub API…” message when cache is absent
  • Arguments passed correctly

Error Handling for 0 Search Results (TC6)

  • Searched with non-existent keyword “nonexistent_gist_xyz”
  • Clear error message “No search results for query: nonexistent_gist_xyz” displayed
  • Exited with code 1 (non-zero)
  • Confirmed proper error handling without program crash

Verified Search Modes

  • Auto Search: Partial match search targeting both filename and description
  • Direct ID Specification: Direct access by Gist ID
  • Filename Search: Search targeting only filename
  • Description Search: Search targeting only description (including tag search)
  • Multiple Candidate Selection UI: Interactive selection by number input
  • Error Handling: Proper error handling when 0 search results

Functional Verification Test Results (Test Set 3: Interpreter Operation Verification) (2025-11-01)

Test Design Document: request/functional_verification_test_design_interpreter.md

Target Gists:

  • hello_args related scripts for various languages (Bash, Python, Ruby, Node.js, PHP, Perl)
  • Test Bash ID: 7bcb324e9291fa350334df8efb7f0deb (hello_args.sh)

Test Result Summary

TCTest ContentResultNotes
TC1Bash execution✅ SuccessBash 5.1.16, confirmed argument passing
TC2Python execution✅ SuccessPython 3.12.4, confirmed argument passing
TC3Ruby execution✅ SuccessRuby 3.3.5, confirmed argument passing
TC4Node.js execution✅ SuccessNode.js v22.13.0, confirmed argument passing
TC5PHP execution✅ SuccessPHP 8.1.2, confirmed argument passing and numerical calculation
TC6Perl execution✅ SuccessPerl v5.34.0, confirmed argument passing
TC7UV execution (PEP 723)✅ SuccessPython 3.12.5, confirmed argument passing

All 7 test cases passed.

Key Verification Points

Bash Execution (TC1)

  • Executed with direct ID specification (--id 7bcb324e9291fa350334df8efb7f0deb)
  • Bash version displayed: 5.1.16(1)-release
  • 3 arguments (arg1, arg2, arg3) passed correctly
  • “Could not calculate as a number” displayed as arguments are not numerical

Python Execution (TC2)

  • Executed with filename specification (--filename hello_args.py)
  • Python version displayed: 3.12.4
  • 3 arguments (10, 20, 30) passed correctly

Ruby Execution (TC3)

  • Executed with filename specification (--filename hello_args.rb)
  • Retrieved from GitHub API due to cache absence
  • Ruby version displayed: 3.3.5
  • 2 arguments (test1, test2) passed correctly

Node.js Execution (TC4)

  • Executed with filename specification (--filename hello_args.js)
  • Retrieved from GitHub API due to cache absence
  • Node.js version displayed: v22.13.0
  • 2 arguments (hello, world) passed correctly

PHP Execution (TC5)

  • Executed with filename specification (--filename hello_args.php)
  • Retrieved from GitHub API due to cache absence
  • PHP version displayed: 8.1.2-1ubuntu2.22
  • 2 arguments (100, 200) passed correctly
  • Numerical calculation confirmed: 100 + 200 = 300

Perl Execution (TC6)

  • Executed with filename specification (--filename hello_args.pl)
  • Retrieved from GitHub API due to cache absence
  • Perl version displayed: v5.34.0
  • 3 arguments (foo, bar, baz) passed correctly

UV Execution - PEP 723 Compatible (TC7)

  • Executed with filename specification (--filename hello_args.py)
  • Interpreter specified: uv
  • Python version displayed: 3.12.5 (environment managed by uv)
  • 3 arguments (5, 10, 15) passed correctly
  • PEP 723 metadata processed correctly

Verified Functions

  • Multi-language Support: Bash, Python, Ruby, Node.js, PHP, Perl (6 languages) operate normally
  • UV Integration: Automatic management of Python execution environment by uv, compliant with PEP 723
  • Correct Argument Passing: Arguments passed correctly for each interpreter
  • Version Display: Version information for each language correctly retrieved and displayed
  • Content Cache: After initial API retrieval, subsequent loads are fast from cache

Functional Verification Test Results (Test Set 4: Preview Function Verification) (2025-11-01)

Test Design Document: request/functional_verification_test_design_preview.md

Target Gists:

  • create_folders.sh (ID: 587558d7c6a9d11b6ec648db364844da)
  • hello_args related scripts for various languages (Python, Bash, Ruby)

Test Result Summary

TCTest ContentResultNotes
TC1Preview with Auto Search✅ SuccessInteractive test, selection from multiple candidates
TC2Preview with Direct ID Specification✅ SuccessConfirmed full display of create_folders.sh
TC3Preview with Filename Specification✅ SuccessConfirmed full display of hello_args.py
TC4Preview with Cache✅ SuccessConfirmed fast loading from cache
TC5–preview long option✅ SuccessConfirmed same behavior as -p

All 5 test cases passed.

Key Verification Points

Preview with Auto Search (TC1)

  • Multiple candidates displayed in keyword search
  • Gist content preview displayed after selecting a number
  • Script is not executed (preview only)

Preview with Direct ID Specification (TC2)

  • Directly specified with --id 587558d7c6a9d11b6ec648db364844da
  • “ID specification mode” message displayed
  • Description: A script to create 100 folders with sequential numbers (start number to end number) in a specified path.
  • Files: create_folders.sh
  • === Gist Content === section displayed
  • --- create_folders.sh --- header displayed
  • Full script (approx. 100 lines) displayed correctly
  • Script is not executed

Preview with Filename Specification (TC3)

  • Searched with --filename hello_args.py
  • Direct preview display for single result
  • Description: hello_args.py - Python argument test script #python #test
  • Full Python script displayed correctly
  • Script is not executed

Preview with Cache (TC4)

  • hello_args.sh cache already exists
  • Executed with --id 7bcb324e9291fa350334df8efb7f0deb
  • “Info: Cache not found…” message is not displayed
  • Fast loading from cache
  • Full Bash script displayed correctly (including TEST MODIFICATION 1, 2 comments)
  • Script is not executed

–preview Long Option (TC5)

  • Executed with --preview --filename hello_args.rb
  • Same preview mode behavior as -p
  • Description: hello_args.rb - Ruby argument test script #ruby #test #gist-cache-rs
  • Full Ruby script displayed correctly
  • Script is not executed

Verified Functions

  • Basic Preview Mode Operation: Displays content only without executing script with -p/--preview option
  • Combination with Search Modes: Preview works with Auto Search, Direct ID specification, and Filename Search
  • Display of Gist Content: Description, Files, and full script content displayed correctly
  • Cache Integration: Fast loading from cache if available, API retrieval otherwise
  • Option Format: Both short option (-p) and long option (–preview) work

gist-cache-rs Functional Verification Test Design Document

Test Objective

To confirm that the gist-cache-rs 2-layer caching mechanism operates correctly as designed.

Target Gist

  • Gist ID: 7bcb324e9291fa350334df8efb7f0deb
  • Filename: hello_args.sh
  • Description: Bash argument test script
  • URL: https://gist.github.com/7rikazhexde/7bcb324e9291fa350334df8efb7f0deb

Prerequisites

  • gist-cache-rs is installed
  • GitHub CLI is authenticated
  • Metadata cache is up-to-date (gist-cache-rs update has been executed)

Test Case List

TC1: First Execution (no content cache)

Objective: Confirm that on first execution, content is fetched from GitHub API and content cache is created.

Prerequisites:

  • Metadata cache exists
  • Content cache for hello_args.sh does not exist

Steps:

  1. Delete content cache: rm -rf ~/.cache/gist-cache/contents/7bcb324e9291fa350334df8efb7f0deb/
  2. Execute: gist-cache-rs run hello_args.sh bash arg1 arg2 arg3
  3. Verify existence of cache file: ls ~/.cache/gist-cache/contents/7bcb324e9291fa350334df8efb7f0deb/

Expected Result:

  • Message “Info: Cache not found, fetching from GitHub API…” is displayed.
  • Script executes successfully.
  • Arguments are displayed correctly (arg1, arg2, arg3).
  • Content cache file is created (~/.cache/gist-cache/contents/7bcb324e9291fa350334df8efb7f0deb/hello_args.sh).

TC2: Second Execution (with content cache)

Objective: Confirm that on second and subsequent executions, content is loaded quickly from cache.

Prerequisites:

  • TC1 completed (content cache exists)

Steps:

  1. Execute: gist-cache-rs run hello_args.sh bash test1 test2
  2. Subjectively check execution time.

Expected Result:

  • Message “Info: Cache not found…” is not displayed.
  • Script executes instantly (no network wait).
  • Arguments are displayed correctly (test1, test2).
  • Execution is faster than TC1 due to loading from cache.

TC3: Metadata Update via update Command (no change)

Objective: Confirm that content cache is retained if there are no changes to the Gist.

Prerequisites:

  • TC2 completed (content cache exists)

Steps:

  1. Execute update command: gist-cache-rs update --verbose
  2. Verify existence of cache file: ls -la ~/.cache/gist-cache/contents/7bcb324e9291fa350334df8efb7f0deb/
  3. Execute: gist-cache-rs run hello_args.sh bash check

Expected Result:

  • “No updates” or “Updated: 0 items” is displayed by the update command.
  • Content cache file is not deleted.
  • Execution loads from cache (no API message).

TC4: Behavior after Gist Update

Objective: Confirm that if a Gist is updated, content cache is deleted after update, and the latest version is fetched on next execution.

Prerequisites:

  • TC3 completed (content cache exists)

Steps:

  1. Edit hello_args.sh on GitHub (e.g., add a comment line).
  2. Record timestamp of cache file: stat ~/.cache/gist-cache/contents/7bcb324e9291fa350334df8efb7f0deb/hello_args.sh
  3. Execute update command: gist-cache-rs update --verbose
  4. Verify existence of cache file: ls ~/.cache/gist-cache/contents/7bcb324e9291fa350334df8efb7f0deb/
  5. Execute: gist-cache-rs run hello_args.sh bash updated

Expected Result:

  • “Updated: 1 item” is displayed by the update command.
  • Content cache directory is deleted (contents/7bcb324e9291fa350334df8efb7f0deb/ does not exist).
  • “Info: Cache not found, fetching from GitHub API…” is displayed on execution.
  • Latest version of the script is executed (edits are reflected).
  • New content cache is created.

TC5: --force Option Behavior

Objective: Confirm that run --force automatically executes update before running.

Prerequisites:

  • TC4 completed (content cache exists)

Steps:

  1. Edit hello_args.sh on GitHub again (e.g., add another comment).
  2. Without executing update command, execute with --force option: gist-cache-rs run --force hello_args.sh bash force_test

Expected Result:

  • Metadata cache is automatically updated before execution (internal process).
  • Content cache is deleted because the Gist was updated.
  • Latest version of the script is executed (second edit is reflected).
  • New content cache is created.

TC6: cache list Command

Objective: Confirm that the cache list is displayed correctly.

Prerequisites:

  • TC5 completed (content cache exists)

Steps:

  1. Execute: gist-cache-rs cache list

Expected Result:

  • hello_args.sh (ID: 7bcb324e9291fa350334df8efb7f0deb) is displayed in the list.
  • Description, filename, and updated_at are displayed.
  • Total number of cached Gists is displayed.

TC7: cache size Command

Objective: Confirm that the cache size is displayed correctly.

Prerequisites:

  • TC6 completed

Steps:

  1. Execute: gist-cache-rs cache size

Expected Result:

  • Number of cached Gists is displayed.
  • Total size is displayed (e.g., in KB).
  • Path to the cache directory is displayed.

TC8: cache clear Command

Objective: Confirm that all caches are deleted.

Prerequisites:

  • TC7 completed (content cache exists)

Steps:

  1. Execute: gist-cache-rs cache clear
  2. Enter y at the confirmation prompt.
  3. Verify cache directory: ls ~/.cache/gist-cache/contents/

Expected Result:

  • Confirmation prompt is displayed.
  • Message “All caches deleted” is displayed.
  • contents directory becomes empty.
  • Next execution behaves as a first execution.

Test Execution Order

  1. TC1: First execution (no cache)
  2. TC2: Second execution (with cache)
  3. TC3: update (no change)
  4. TC4: Behavior after Gist update ← Requires editing on GitHub
  5. TC5: –force option ← Requires re-editing on GitHub
  6. TC6: cache list
  7. TC7: cache size
  8. TC8: cache clear

Notes

  • TC4 and TC5 require Gist editing on GitHub.
  • Minor edits (e.g., adding a comment) are sufficient.
  • Metadata cache should be up-to-date before running tests (gist-cache-rs update).
  • State is carried over between test cases, so they must be executed in order.

gist-cache-rs Functional Verification Test Design Document (Test Set 2: Search Functionality)

Test Objective

To confirm that the gist-cache-rs search functionality operates correctly as designed.

Target Functionality

  • Auto Search (default)
  • Direct ID Specification Search (–id)
  • Filename Search (–filename)
  • Description Search (–description)
  • Selection UI from multiple candidates
  • Error handling for 0 search results

Prerequisites

  • gist-cache-rs is installed
  • GitHub CLI is authenticated
  • Metadata cache is up-to-date (gist-cache-rs update has been executed)
  • Multiple test Gists exist

Test Case List

TC1: Auto Search (default)

Objective: Confirm that automatic search by keyword works correctly.

Prerequisites:

  • Multiple Gists including hello_args.sh exist

Steps:

  1. Search by keyword “hello”: gist-cache-rs run hello bash
  2. Check search results.
  3. If multiple candidates are displayed, select a number and execute.

Expected Result:

  • Gists containing “hello” in filename or description are displayed.
  • If 1 item, executed directly; if multiple, selection UI is displayed.
  • Selected Gist is executed correctly.

Verification Items:

  • Partial match search by filename works.
  • Partial match search by description works.
  • Case-insensitive search works.

TC2: Direct ID Specification (–id)

Objective: Confirm that search by directly specifying Gist ID works correctly.

Prerequisites:

  • Gist ID for hello_args.sh (7bcb324e9291fa350334df8efb7f0deb) is known.

Steps:

  1. Directly specify Gist ID: gist-cache-rs run --id 7bcb324e9291fa350334df8efb7f0deb bash test
  2. Check execution result.

Expected Result:

  • Specified Gist is executed directly, skipping the search process.
  • “ID specification mode” message is displayed.
  • Multiple candidate selection UI is not displayed.

Verification Items:

  • Direct access with accurate Gist ID is possible.
  • “ID specification mode” message is displayed.
  • Cannot be used in conjunction with other search options (error or ignored).

TC3: Filename Search (–filename)

Objective: Confirm that search limited to filename works correctly.

Prerequisites:

  • Multiple Gists including hello_args.sh exist.

Steps:

  1. Search by filename: gist-cache-rs run --filename hello_args.sh bash
  2. Check search results.
  3. Check execution result.

Expected Result:

  • Only Gists with filename matching “hello_args.sh” are searched.
  • Gists with “hello_args.sh” in description but different filename are excluded.
  • Partial match search (e.g., “hello” finds “hello_args.sh”) works.

Verification Items:

  • Filename search works correctly.
  • Description is not searched.
  • If multiple matches, selection UI is displayed.

TC4: Description Search (–description)

Objective: Confirm that search limited to description works correctly.

Prerequisites:

  • Gists containing specific keywords in description (e.g., “#bash”, “#test”) exist.

Steps:

  1. Search by description: gist-cache-rs run --description "#bash" bash
  2. Check search results.
  3. Select one from multiple candidates and execute.

Expected Result:

  • Only Gists containing “#bash” in description are searched.
  • If “#bash” is in filename but not description, Gist is excluded.
  • Partial match search works.

Verification Items:

  • Description search works correctly.
  • Filename is not searched.
  • Tag search (e.g., “#bash”) works effectively.

TC5: Selection from Multiple Candidates

Objective: Confirm that the UI for selecting by number from multiple search results works correctly.

Prerequisites:

  • Searching for “hello” hits multiple Gists.

Steps:

  1. Search with a keyword that hits multiple results: gist-cache-rs run hello bash
  2. Check the displayed candidate list.
  3. Select a number (e.g., enter 4 and press Enter).
  4. Confirm that the selected Gist is executed.

Expected Result:

  • Multiple Gists are displayed in a numbered list.
  • Description and filename of each Gist are displayed.
  • “Select a number (1-N):” prompt is displayed.
  • Gist corresponding to the entered number is executed.

Verification Items:

  • Numbered list is displayed correctly.
  • Entering a valid number executes the corresponding Gist.
  • Error handling for invalid numbers (0, out of range, string, etc.).

TC6: Error Handling for 0 Search Results

Objective: Confirm that error handling when no search results are found works correctly.

Prerequisites:

  • Use a non-existent keyword (e.g., “nonexistent_gist_xyz”).

Steps:

  1. Search with a non-existent keyword: gist-cache-rs run nonexistent_gist_xyz bash
  2. Check error message.
  3. Check exit code.

Expected Result:

  • Error message like “No search results for query: nonexistent_gist_xyz” is displayed.
  • Program exits with an appropriate error code (non-zero).
  • Program does not crash.

Verification Items:

  • Clear error message is displayed.
  • Exit code is non-zero.
  • No memory leaks or crashes occur.

Additional Test Cases

TC7: Search with Special Characters

Objective: Confirm that search with keywords containing special characters works correctly.

Steps:

  1. Search with a keyword containing special characters: gist-cache-rs run "data_analysis.py" bash

Expected Result:

  • Filenames containing underscores or periods are searched correctly.
  • Special characters are searched without escaping.

TC8: Search with Spaces

Objective: Confirm that search for descriptions containing spaces works correctly.

Steps:

  1. Search with a keyword containing spaces: gist-cache-rs run --description "Test Script" bash

Expected Result:

  • Descriptions containing spaces are searched correctly.
  • Keywords enclosed in quotes are processed correctly.

Test Execution Order

  1. TC1: Auto Search (default)
  2. TC2: Direct ID Specification (–id)
  3. TC3: Filename Search (–filename)
  4. TC4: Description Search (–description)
  5. TC5: Selection from Multiple Candidates
  6. TC6: Error Handling for 0 Search Results
  7. TC7: Search with Special Characters (optional)
  8. TC8: Search with Spaces (optional)

Notes

  • TC5 requires interactive input, making automation difficult.
  • TC6 is an error case, so it should be executed after normal tests.
  • Search results vary depending on the environment (owned Gists).
  • Metadata cache should be up-to-date before running tests.

gist-cache-rs Functional Verification Test Design Document (Test Set 3: Interpreter Operation Verification)

Test Objective

To confirm that gist-cache-rs correctly launches each interpreter, passes arguments, and executes scripts.

Target Functionality

  • Bash execution (bash)
  • Python execution (python3)
  • Ruby execution (ruby)
  • Node.js execution (node)
  • PHP execution (php)
  • Perl execution (perl)
  • PowerShell execution (pwsh)
  • TypeScript execution (ts-node, deno, bun)
  • UV execution (uv run) - PEP 723 compatible

Prerequisites

  • gist-cache-rs is installed
  • GitHub CLI is authenticated
  • Metadata cache is up-to-date (gist-cache-rs update has been executed)
  • Each interpreter is installed on the system
  • Test Gists for hello_args series exist

Test Case List

TC1: Bash Execution

Objective: Confirm that Bash scripts are executed correctly.

Prerequisites:

  • hello_args.sh (ID: 7bcb324e9291fa350334df8efb7f0deb) exists.

Steps:

  1. Execute with Bash: gist-cache-rs run --id 7bcb324e9291fa350334df8efb7f0deb bash arg1 arg2 arg3
  2. Check execution result.

Expected Result:

  • Bash version is displayed.
  • Number of arguments “3” is displayed.
  • Arguments are displayed correctly (arg1, arg2, arg3).
  • “Could not calculate as a number” is displayed as arguments are not numerical.

Verification Items:

  • Bash interpreter launches correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

TC2: Python Execution

Objective: Confirm that Python scripts are executed correctly.

Prerequisites:

  • hello_args.py exists.

Steps:

  1. Execute with Python: gist-cache-rs run --filename hello_args.py python3 10 20 30
  2. Check execution result.

Expected Result:

  • Python version is displayed.
  • Number of arguments “3” is displayed.
  • Arguments are displayed correctly (10, 20, 30).
  • If the Python script has a sum calculation function, the sum “60” is displayed.

Verification Items:

  • Python interpreter launches correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

TC3: Ruby Execution

Objective: Confirm that Ruby scripts are executed correctly.

Prerequisites:

  • hello_args.rb exists.

Steps:

  1. Execute with Ruby: gist-cache-rs run --filename hello_args.rb ruby test1 test2
  2. Check execution result.

Expected Result:

  • Ruby version is displayed.
  • Number of arguments “2” is displayed.
  • Arguments are displayed correctly (test1, test2).

Verification Items:

  • Ruby interpreter launches correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

TC4: Node.js Execution

Objective: Confirm that Node.js scripts are executed correctly.

Prerequisites:

  • hello_args.js or hello_args_2.js exists.

Steps:

  1. Execute with Node.js: gist-cache-rs run --filename hello_args.js node hello world
  2. Check execution result.

Expected Result:

  • Node.js version is displayed.
  • Number of arguments “2” is displayed.
  • Arguments are displayed correctly (hello, world).

Verification Items:

  • Node.js interpreter launches correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

TC5: PHP Execution

Objective: Confirm that PHP scripts are executed correctly.

Prerequisites:

  • hello_args.php exists.

Steps:

  1. Execute with PHP: gist-cache-rs run --filename hello_args.php php 100 200
  2. Check execution result.

Expected Result:

  • PHP version is displayed.
  • Number of arguments “2” is displayed.
  • Arguments are displayed correctly (100, 200).
  • Confirmed numerical calculation function: 100 + 200 = 300.

Verification Items:

  • PHP interpreter launches correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

TC6: Perl Execution

Objective: Confirm that Perl scripts are executed correctly.

Prerequisites:

  • hello_args.pl exists.

Steps:

  1. Execute with Perl: gist-cache-rs run --filename hello_args.pl perl foo bar baz
  2. Check execution result.

Expected Result:

  • Perl version is displayed.
  • Number of arguments “3” is displayed.
  • Arguments are displayed correctly (foo, bar, baz).

Verification Items:

  • Perl interpreter launches correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

TC7: PowerShell Execution

Objective: Confirm that PowerShell scripts are executed correctly.

Prerequisites:

  • hello_args.ps1 (ID: 2cb45541fee10264b615fd641c577a20) exists.
  • pwsh command is installed (PowerShell Core).

Steps:

  1. Execute with PowerShell: gist-cache-rs run --id 2cb45541fee10264b615fd641c577a20 pwsh test1 test2 test3
  2. Check execution result.

Expected Result:

  • PowerShell version is displayed.
  • Number of arguments “3” is displayed.
  • Arguments are displayed correctly (test1, test2, test3).
  • “Calculation impossible because it contains non-numerical values” is displayed as arguments are not numerical.

Verification Items:

  • PowerShell interpreter (pwsh) launches correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

Numerical Argument Test:

  1. Execute with PowerShell: gist-cache-rs run --filename hello_args.ps1 pwsh 10 20 30
  2. Expected Result: Sum “60” is displayed.

TC8: TypeScript Execution (Deno)

Objective: Confirm that TypeScript scripts are executed correctly with Deno.

Prerequisites:

  • hello_args_deno.ts (ID: 9b0e7e1bdf7d24c3f28a80d18f6aaafe) exists.
  • deno command is installed.

Steps:

  1. Execute with Deno (no arguments): gist-cache-rs run --filename hello_args_deno.ts deno
  2. Execute with Deno (string arguments): gist-cache-rs run --filename hello_args_deno.ts deno test1 test2 test3
  3. Execute with Deno (numerical arguments): gist-cache-rs run --filename hello_args_deno.ts deno 10 20 30
  4. Check each execution result.

Expected Result:

  • Deno version is displayed.
  • TypeScript version is displayed.
  • V8 version is displayed.
  • No arguments: Usage example is displayed.
  • String arguments: Number of arguments “3”, arguments displayed correctly (test1, test2, test3), “Calculation impossible because it contains non-numerical values”.
  • Numerical arguments: Number of arguments “3”, arguments displayed correctly (10, 20, 30), sum “60” is displayed.

Verification Items:

  • Deno interpreter launches correctly.
  • TypeScript file (.ts) is recognized correctly.
  • deno run command is used correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

TC9: TypeScript Execution (ts-node)

Objective: Confirm that TypeScript scripts are executed correctly with ts-node.

Prerequisites:

  • hello_args.ts (ID: c3c925384cc8241d8cd30f269af84332) exists.
  • ts-node command is installed (npm install -g ts-node typescript).

Steps:

  1. Execute with ts-node: gist-cache-rs run --filename hello_args.ts ts-node hello world
  2. Check execution result.

Expected Result:

  • TypeScript version is displayed.
  • Node.js version is displayed.
  • Number of arguments “2” is displayed.
  • Arguments are displayed correctly (hello, world).
  • “Calculation impossible because it contains non-numerical values” is displayed as arguments are not numerical.

Verification Items:

  • ts-node interpreter launches correctly.
  • TypeScript file (.ts) is recognized correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

Notes:

  • ts-node executes TypeScript on Node.js, so npm install -g ts-node typescript is required.
  • If not installed, this test case can be skipped.

TC10: TypeScript Execution (Bun)

Objective: Confirm that TypeScript scripts are executed correctly with Bun.

Prerequisites:

  • hello_args_bun.ts (ID: a3d74a884ff923fc83c047c2cf3d6f08) exists.
  • bun command is installed.

Steps:

  1. Execute with Bun: gist-cache-rs run --filename hello_args_bun.ts bun 100 200
  2. Check execution result.

Expected Result:

  • Bun version is displayed.
  • Number of arguments “2” is displayed.
  • Arguments are displayed correctly (100, 200).
  • Sum “300” is displayed.

Verification Items:

  • Bun interpreter launches correctly.
  • TypeScript file (.ts) is recognized correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

Notes:

  • Bun is a fast JavaScript/TypeScript runtime.
  • If not installed, this test case can be skipped.

TC11: UV Execution (PEP 723 Compatible)

Objective: Confirm that Python scripts are executed correctly with UV (PEP 723 compatible).

Prerequisites:

  • hello_args.py exists.
  • uv command is installed.

Steps:

  1. Execute with UV: gist-cache-rs run --filename hello_args.py uv 5 10 15
  2. Check execution result.

Expected Result:

  • Python version is displayed (Python environment managed by uv).
  • Number of arguments “3” is displayed.
  • Arguments are displayed correctly (5, 10, 15).
  • If the script has a sum calculation function, the sum “30” is displayed.

Verification Items:

  • UV interpreter (uv run) launches correctly.
  • PEP 723 metadata is processed correctly.
  • Arguments are passed correctly.
  • Script executes successfully.

Test Execution Order

  1. TC1: Bash Execution
  2. TC2: Python Execution
  3. TC3: Ruby Execution
  4. TC4: Node.js Execution
  5. TC5: PHP Execution
  6. TC6: Perl Execution
  7. TC7: PowerShell Execution
  8. TC8: TypeScript Execution (Deno)
  9. TC9: TypeScript Execution (ts-node)
  10. TC10: TypeScript Execution (Bun)
  11. TC11: UV Execution (PEP 723)

Notes

  • Ensure each interpreter is installed on the system.
  • Tests for uninstalled interpreters can be skipped.
  • TC7 (PowerShell) primarily targets PowerShell Core (pwsh) on Linux/macOS.
  • TC8-10 (TypeScript) verify operation with respective runtimes.
    • TC8 (Deno): Native TypeScript support, most recommended (operation confirmed).
    • TC9 (ts-node): Executes TypeScript on Node.js, requires installation (npm install -g ts-node typescript).
    • TC10 (Bun): Native TypeScript support, fast execution (requires installation).
  • TC11 (UV) specifically aims to verify PEP 723 compatibility.
  • Output format may vary depending on the specific script implementation.
  • Argument handling depends on the specifications of each language.

gist-cache-rs Functional Verification Test Design Document (Test Set 4: Preview Function Verification)

Test Objective

To confirm that the gist-cache-rs preview function (-p/--preview) works correctly.

Target Functionality

  • Preview display with Auto Search
  • Preview display with Direct ID Specification
  • Preview display with Filename Search
  • Preview display with existing cache
  • --preview option (long option) behavior

Prerequisites

  • gist-cache-rs is installed
  • GitHub CLI is authenticated
  • Metadata cache is up-to-date (gist-cache-rs update has been executed)
  • Test Gists for hello_args series exist

Test Case List

TC1: Preview with Auto Search (-p option)

Objective: Confirm that preview is displayed correctly with keyword search.

Prerequisites:

  • Searching for “hello” hits multiple Gists.

Steps:

  1. Search with -p option: gist-cache-rs run -p hello bash
  2. Select one from multiple candidates (e.g., number 7).
  3. Check displayed content.

Expected Result:

  • Multiple Gists are displayed in a numbered list.
  • After selecting a number, the following are displayed:
    • Description
    • Files
    • === Gist Content === section
    • --- Filename --- header
    • File content (source code)
  • Script is not executed (no version information or argument display).

Verification Items:

  • Preview mode launches correctly.
  • Gist content is displayed correctly.
  • Exits without executing.

TC2: Preview with Direct ID Specification

Objective: Confirm that preview is displayed correctly when specifying ID.

Prerequisites:

  • hello_args.sh (ID: 7bcb324e9291fa350334df8efb7f0deb) is known.

Steps:

  1. Preview with ID: gist-cache-rs run -p --id 7bcb324e9291fa350334df8efb7f0deb bash
  2. Check displayed content.

Expected Result:

  • “ID specification mode” message is displayed.
  • Search process is skipped.
  • Description, Files, Gist content are displayed.
  • Script is not executed.

Verification Items:

  • Combination of direct ID specification and preview mode works.
  • Selection UI is skipped.
  • Content is displayed correctly.

TC3: Preview with Filename Specification

Objective: Confirm that preview is displayed correctly with filename search.

Prerequisites:

  • hello_args.py exists.

Steps:

  1. Preview with filename: gist-cache-rs run -p --filename hello_args.py python3
  2. Check displayed content.

Expected Result:

  • Gist containing hello_args.py is searched.
  • If single result, direct preview display.
  • If multiple results, selection UI is displayed.
  • Gist content is displayed correctly.
  • Script is not executed.

Verification Items:

  • Combination of filename search and preview mode works.
  • Content is displayed correctly.

TC4: Preview with Cache

Objective: Confirm preview behavior when content cache exists.

Prerequisites:

  • hello_args.sh is already cached (executed previously).

Steps:

  1. Verify cache: ls ~/.cache/gist-cache/contents/7bcb324e9291fa350334df8efb7f0deb/
  2. Execute preview: gist-cache-rs run -p --id 7bcb324e9291fa350334df8efb7f0deb bash
  3. Check displayed content.

Expected Result:

  • “Info: Cache not found…” message is not displayed.
  • Content is loaded quickly from cache.
  • Gist content is displayed correctly.
  • Script is not executed.

Verification Items:

  • Preview display from cache works.
  • No network access occurs (if cache already exists).

TC5: --preview Option (Long Option)

Objective: Confirm that the long option --preview works correctly.

Prerequisites:

  • hello_args.rb exists.

Steps:

  1. Search with --preview option: gist-cache-rs run --preview --filename hello_args.rb ruby
  2. Check displayed content.

Expected Result:

  • Behaves the same as -p.
  • Gist content is displayed correctly.
  • Script is not executed.

Verification Items:

  • Long option --preview works.
  • Consistent behavior with -p.

Test Execution Order

  1. TC1: Preview with Auto Search (Interactive Test)
  2. TC2: Preview with Direct ID Specification
  3. TC3: Preview with Filename Specification
  4. TC4: Preview with Cache
  5. TC5: –preview Option (Long Option)

Notes

  • TC1 requires interactive input.
  • Scripts are not executed in preview mode.
  • Messages vary depending on cache presence.
  • TC4 creates cache after TC2 execution.
  • Arguments (bash, python3, etc.) are not used in preview display (display only).