mcpField
U
unix-goto-development

unix-goto-development

github.com/manutej开发62427 次安装39 周前更新
代码仓库

关于 unix-goto-development

面向 unix-goto 贡献者的开发技能,指导如何扩展和维护 Shell 导航系统,涵盖模块架构、缓存、功能流程、测试、文档和性能验证。

主要功能

  1. 01模块架构与加载顺序
  2. 02九步功能开发流程
  3. 03缓存与导航模式
  4. 04单元、集成和性能测试
  5. 05API 与用户文档指南

适用场景

  1. 01添加书签或历史命令
  2. 02优化缓存目录导航
  3. 03测试导航模块变更
  4. 04编写新 Shell 命令文档

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/manutej/luxor-claude-marketplace --skill unix-goto-development

安装后在 Claude Code 中输入/unix-goto-development确认已加载。

附带文件README.md

详细介绍

unix-goto 开发专家

全面掌握 unix-goto Shell 导航系统的开发知识——这是一款高性能 Unix 导航工具,支持自然语言、缓存导航耗时低于 100 毫秒,测试覆盖率达 100%。

何时使用此技能

在以下情况下使用此技能:

  • 为 unix-goto Shell 导航系统开发新功能
  • 实现基于缓存的导航优化
  • 添加书签、历史记录或导航命令
  • 遵循标准的 9 步功能添加工作流
  • 与 Linear 项目管理集成
  • 编写全面的测试套件(必须达到 100% 覆盖率)
  • 优化性能,以满足低于 100 毫秒的目标
  • 为 Shell 模块编写 API 文档
  • 调试导航或缓存问题

请勿在以下情况下使用此技能:

  • 一般 Bash 脚本编写(请使用通用 Bash 技能)
  • 非导航类 Shell 工具
  • 没有性能要求的项目
  • 简单的一次性 Shell 脚本

项目概览

unix-goto 系统架构

unix-goto 是一款高性能 Unix 导航系统,遵循五项核心原则:

  1. 简单——一行即可加载(source goto.sh),配置最少
  2. 快速——导航耗时低于 100 毫秒
  3. 精简——不臃肿,不依赖不必要的组件
  4. 经过测试——核心功能的测试覆盖率达 100%
  5. 文档完善——文档清晰、全面
关键性能指标
指标目标实际达成状态
缓存导航<100ms26ms✅ 超出目标
缓存命中率>90%92-95%✅ 超出目标
加速比20-50x8x⏳ 按计划推进
测试覆盖率100%100%✅ 达标
缓存构建时间<5s3-5s✅ 达标
系统架构
┌─────────────────────────────────────────────────────────────┐
│                      User Interface                         │
│  goto, bookmark, recent, back, goto list, goto benchmark   │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                    Core Navigation                          │
│  goto-function.sh - Main routing and path resolution        │
└─────────────────────────────────────────────────────────────┘
                            │
          ┌─────────────────┼─────────────────┐
          ▼                 ▼                 ▼
┌──────────────────┐ ┌──────────────┐ ┌──────────────────┐
│  Cache System    │ │  Bookmarks   │ │  History         │
│  cache-index.sh  │ │  bookmark-   │ │  history-        │
│                  │ │  command.sh  │ │  tracking.sh     │
│  O(1) lookup     │ │              │ │                  │
│  Auto-refresh    │ │  Add/Remove  │ │  Track visits    │
└──────────────────┘ └──────────────┘ └──────────────────┘
模块依赖关系

关键加载顺序(必须先加载依赖项,再加载依赖模块):

goto.sh (loader)
  ├── history-tracking.sh (no dependencies)
  ├── back-command.sh (depends on: history-tracking.sh)
  ├── recent-command.sh (depends on: history-tracking.sh)
  ├── bookmark-command.sh (no dependencies)
  ├── cache-index.sh (no dependencies)
  ├── list-command.sh (depends on: bookmark-command.sh)
  ├── benchmark-command.sh (depends on: cache-index.sh)
  ├── benchmark-workspace.sh (no dependencies)
  └── goto-function.sh (depends on: all above)

核心知识

9 步功能添加工作流

这是为 unix-goto 添加任何功能的标准流程。请完成全部九个步骤。

步骤 1:规划功能

编写任何代码之前,请先回答以下问题:

规划问题:

  • 要解决什么问题?
  • 用户界面是什么样的(命令/标志)?
  • 预期性能如何?
  • 有哪些依赖项?
  • 需要哪些测试?
  • 需要哪些文档?

规划模板:

Feature: [Name]
Problem: [User pain point]
Interface: [Commands/flags]
Performance: [Target metrics]
Dependencies: [Module dependencies]
Tests: [Test scenarios]
Docs: [API.md, README.md sections]

示例——最近目录功能(CET-77):

Feature: Recent Directories Command
Problem: Users can't quickly revisit recently navigated directories
Interface: goto recent [n]
Performance: <10ms for history retrieval
Dependencies: history-tracking.sh
Tests:
  - List recent directories
  - Handle empty history
  - Limit to N entries
  - Navigate to recent directory by number
Docs: Add to API.md and README.md
步骤 2:创建模块(如有需要)

模块模板:

#!/bin/bash
# unix-goto - [Module purpose]
# https://github.com/manutej/unix-goto

# Storage location
GOTO_MODULE_FILE="${GOTO_MODULE_FILE:-$HOME/.goto_module}"

# Main function
goto_module() {
    local subcommand="$1"
    shift

    case "$subcommand" in
        list)
            # Implementation
            ;;
        add)
            # Implementation
            ;;
        --help|-h|help|"")
            echo "goto module - [Description]"
            echo ""
            echo "Usage:"
            echo "  goto module list     [Description]"
            echo "  goto module add      [Description]"
            ;;
        *)
            echo "Unknown command: $subcommand"
            return 1
            ;;
    esac
}

关键模块模式:

  1. 函数命名:

    • 公共函数:不带前缀(goto、bookmark、recent)
    • 内部函数:使用双下划线(__goto_navigate_to、__goto_cache_lookup)
    • 变量:全局变量使用大写,本地变量使用小写
  2. 环境变量:

    # Always provide defaults
    GOTO_INDEX_FILE="${GOTO_INDEX_FILE:-$HOME/.goto_index}"
    GOTO_CACHE_TTL="${GOTO_CACHE_TTL:-86400}"
    GOTO_SEARCH_DEPTH="${GOTO_SEARCH_DEPTH:-3}"
    
  3. 返回码:

    • 0 - 成功
    • 1 - 一般错误(未找到、输入无效)
    • 2 - 找到多个匹配项(仅限缓存查找)
步骤 3:添加到加载器

编辑 goto.sh,按照正确的依赖顺序加载模块:

# Add to load sequence (respect dependencies)
source "$GOTO_LIB_DIR/history-tracking.sh"
source "$GOTO_LIB_DIR/module.sh"  # NEW - add after dependencies
source "$GOTO_LIB_DIR/back-command.sh"

依赖规则:

  • 无依赖项的模块最先加载
  • 依赖其他模块的模块必须在依赖项之后加载
  • Main goto-function.sh 最后加载(依赖所有模块)
步骤 4:集成到主函数

编辑 lib/goto-function.sh,将命令路由到相应模块:

goto() {
    case "$1" in
        module)  # NEW
            if command -v goto_module &> /dev/null; then
                shift
                goto_module "$@"
            else
                echo "⚠️  Module command not loaded"
            fi
            return
            ;;
    esac
}
步骤 5:添加测试(必须达到 100% 覆盖率)

测试文件模板:

#!/bin/bash
# Test suite for [feature] functionality

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/lib/module.sh"

# Test counters
TESTS_PASSED=0
TESTS_FAILED=0

# Test helper
pass() {
    echo "✓ PASS: $1"
    ((TESTS_PASSED++))
}

fail() {
    echo "✗ FAIL: $1"
    ((TESTS_FAILED++))
}

# Test 1: [Description]
test_feature() {
    # Arrange
    local input="test"

    # Act
    local result=$(function_under_test "$input")

    # Assert
    if [[ "$result" == "expected" ]]; then
        pass "Feature works"
    else
        fail "Feature failed: got '$result'"
    fi
}

# Run tests
test_feature

# Summary
echo ""
echo "Tests passed: $TESTS_PASSED"
echo "Tests failed: $TESTS_FAILED"

[ $TESTS_FAILED -eq 0 ] && exit 0 || exit 1

测试类别(全部必需):

  1. 单元测试——测试单个函数
  2. 集成测试——测试模块交互
  3. 边界情况——测试边界条件
  4. 性能测试——验证速度要求

CET-77(最近目录)的示例:

# Unit test
test_get_recent_dirs() {
    result=$(__goto_recent_dirs 5)
    [ $? -eq 0 ] && pass "Get recent dirs" || fail "Get recent dirs failed"
}

# Integration test
test_goto_recent_navigation() {
    goto recent 1
    [ $? -eq 0 ] && pass "Navigate to recent dir" || fail "Navigation failed"
}

# Edge case
test_empty_history() {
    rm -f ~/.goto_history
    result=$(goto recent)
    [[ "$result" == *"No history"* ]] && pass "Empty history" || fail "Empty history check"
}

# Performance test
test_recent_speed() {
    start=$(date +%s%N)
    __goto_recent_dirs 10
    end=$(date +%s%N)
    duration=$(((end - start) / 1000000))
    [ $duration -lt 10 ] && pass "Recent dirs <10ms" || fail "Too slow: ${duration}ms"
}
步骤 6:编写 API 文档

在 docs/API.md 中添加:

## Module API

### `goto module`

[Description of what the module does]

**Signature:**
```bash
goto module <subcommand>

子命令:

  • list - [说明]
  • add - [说明]

性能: [目标指标]

示例:

goto module list
goto module add value

返回代码:

  • 0 - 成功
  • 1 - 错误

实现: lib/module.sh


**Example from CET-77:**
```markdown
## Recent Directories

### `goto recent [n]`

Display recently navigated directories in reverse chronological order.

**Signature:**
```bash
goto recent [n]

参数:

  • n - 可选,显示最近目录的数量(默认:全部)

性能: 检索历史记录耗时 <10ms

示例:

goto recent        # Show all recent directories
goto recent 5      # Show 5 most recent

实现: lib/recent-command.sh


#### Step 7: Update User Documentation

Add to `README.md`:

```markdown
### Module

[User-facing description]

```bash
goto module list    # [Description]
goto module add     # [Description]

#### Step 8: Performance Validation

Validate performance meets targets:

```bash
# Add benchmark if performance-critical
goto benchmark module 10

# Measure overhead
time goto_module list

# Expected: <100ms for navigation, <10ms for lookups

性能目标:

  • 缓存导航:<100ms
  • 书签查找:<10ms
  • 缓存提速:>20x
  • 缓存命中率:>90%
  • 构建缓存:<5s
步骤 9:更新 Linear issue 并提交

更新 Linear issue:

  • 添加实现说明
  • 包含测试结果
  • 包含性能指标
  • 链接到提交
  • 移至“Complete”

提交格式:

git commit -m "feat: implement module feature (CET-XX)

[Detailed explanation]

Features:
- Feature 1
- Feature 2

Performance:
- Metric: value

Tests:
- X/X tests passing
- 100% coverage

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>"

提交类型:

  • feat: - 新功能
  • fix: - 修复错误
  • perf: - 性能改进
  • refactor: - 代码重构
  • test: - 添加或更新测试
  • docs: - 仅文档变更
  • chore: - 构建、依赖项或工具

来自 CET-85 的提交示例:

feat: implement comprehensive benchmark suite (CET-85)

Implement complete benchmark framework with 5 benchmark tests, helpers,
workspace generation, and CSV results storage.

Features:
- 5 benchmark tests: cached vs uncached, multi-level paths, max depth,
  cache build performance, parallel navigation
- Benchmark helpers library with timing, stats, workspace management
- CSV results storage in ~/.goto_benchmarks/
- Performance target assertions (<100ms navigation)
- Comprehensive statistical analysis (min/max/mean/median/stddev)

Performance:
- Cached navigation: 26ms (target: <100ms) ✓
- Cache build: 3-5s (target: <5s) ✓
- Speedup ratio: 8x (target: >20x, in progress)

Tests:
- 5/5 benchmark tests passing
- All performance targets met for Phase 1

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
功能检查清单

提交任何功能前:

  • 实现已完成
  • 已在 goto.sh 中加载
  • 已集成到主 goto 函数
  • 已编写测试并通过(100% 覆盖率)
  • 已在 docs/API.md 中编写 API 文档
  • 已更新 README.md 中的用户文档
  • 已验证性能(如适用)
  • 已在 Linear issue 中更新结果
  • 已按正确的格式提交
缓存系统架构

用途: 通过自动刷新实现 O(1) 文件夹查找

实现: lib/cache-index.sh

关键组件:

  • __goto_cache_build - O(n) 索引构建
  • __goto_cache_lookup - O(1) 哈希表查找
  • __goto_cache_is_valid - 基于 TTL 的验证
  • 缓存过期时自动刷新(TTL 为 24 小时)

缓存文件格式:

# unix-goto folder index cache
# Version: 1.0
# Built: 1697558122
# Depth: 3
# Format: folder_name|full_path|depth|last_modified
#---
unix-goto|/Users/manu/Documents/LUXOR/Git_Repos/unix-goto|8|1697558100
GAI-3101|/Users/manu/Documents/LUXOR/PROJECTS/GAI-3101|6|1697558050

性能:

  • 构建时间:O(n) - 1200+ 个文件夹耗时 3-5s
  • 查找时间:O(1) - 目标 <100ms,实际 26ms
  • 存储:487 个文件夹约 42KB

缓存查找返回代码:

__goto_cache_lookup "folder"
# Returns:
#   0 - Single match found (path to stdout)
#   1 - Not found in cache
#   2 - Multiple matches found (all paths to stdout)
导航数据流
User Input → goto "project"
    │
    ├─► Check special cases (list, index, benchmark, @bookmark)
    ├─► Check multi-level paths (contains /)
    ├─► Try cache lookup (O(1)) → Cache hit → Navigate
    ├─► Try direct folder match in search paths
    ├─► Recursive search (max depth 3)
    │   ├─► Single match → Navigate
    │   └─► Multiple matches → Show disambiguation
    └─► Natural language AI resolution (if spaces)
书签系统架构

存储位置: ~/.goto_bookmarks

格式:

work|/Users/manu/work|1697558122
api|/Users/manu/code/api-server|1697558130

关键函数:

  • __goto_bookmark_add - 验证后添加
  • __goto_bookmark_remove - 按名称移除
  • __goto_bookmark_get - 获取路径(O(1) grep)
  • __goto_bookmark_goto - 导航到书签

性能目标: 查找耗时 <10ms

用法:

bookmark add work /path/to/work
bookmark remove work
goto @work
历史记录跟踪架构

存储位置: ~/.goto_history

格式:

1697558122|/Users/manu/work
1697558130|/Users/manu/Documents/LUXOR

关键函数:

  • __goto_track - 追加并自动修剪(最多 100 条)
  • __goto_get_history - 获取完整历史记录
  • __goto_recent_dirs - 按时间倒序获取不重复的目录
  • __goto_stack_push/pop - 基于堆栈的后退导航

用法示例:

goto recent        # Show all recent directories
goto recent 5      # Show 5 most recent
back              # Go back to previous directory

示例

示例 1:添加最近目录功能(CET-77)

步骤 1:规划

Feature: Recent Directories Command
Problem: Users can't quickly revisit recently navigated directories
Interface: goto recent [n]
Performance: <10ms for history retrieval
Dependencies: history-tracking.sh
Tests: List recent, empty history, limit entries, navigate by number
Docs: API.md, README.md

步骤 2:创建模块(lib/recent-command.sh)

#!/bin/bash
# unix-goto - Recent directories command
# https://github.com/manutej/unix-goto

# Get recent directories
__goto_recent_dirs() {
    local limit="${1:-}"

    if [ ! -f "$GOTO_HISTORY_FILE" ]; then
        return 1
    fi

    # Extract paths, reverse order, unique, limit
    local dirs=$(awk -F'|' '{print $2}' "$GOTO_HISTORY_FILE" | \
                 tac | \
                 awk '!seen[$0]++' | \
                 ${limit:+head -n "$limit"})

    echo "$dirs"
    return 0
}

# Recent command implementation
goto_recent() {
    local limit="${1:-}"

    local dirs=$(__goto_recent_dirs "$limit")

    if [ -z "$dirs" ]; then
        echo "No recent directories"
        return 1
    fi

    echo "$dirs"
    return 0
}

步骤 3:添加到加载器(goto.sh)

source "$GOTO_LIB_DIR/history-tracking.sh"
source "$GOTO_LIB_DIR/recent-command.sh"  # NEW

步骤 4:集成(lib/goto-function.sh)

goto() {
    case "$1" in
        recent)
            shift
            goto_recent "$@"
            return
            ;;
    esac
}

步骤 5:添加测试(test-recent.sh)

#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/lib/recent-command.sh"

TESTS_PASSED=0
TESTS_FAILED=0

pass() { echo "✓ PASS: $1"; ((TESTS_PASSED++)); }
fail() { echo "✗ FAIL: $1"; ((TESTS_FAILED++)); }

# Test 1: Get recent directories
test_get_recent() {
    result=$(__goto_recent_dirs)
    [ $? -eq 0 ] && pass "Get recent dirs" || fail "Failed"
}

# Test 2: Empty history
test_empty_history() {
    rm -f ~/.goto_history
    result=$(goto_recent)
    [[ "$result" == *"No recent"* ]] && pass "Empty history" || fail "Empty check"
}

# Test 3: Limit results
test_limit_results() {
    result=$(__goto_recent_dirs 5)
    count=$(echo "$result" | wc -l)
    [ $count -le 5 ] && pass "Limit to 5" || fail "Limit failed"
}

# Run tests
test_get_recent
test_empty_history
test_limit_results

echo ""
echo "Passed: $TESTS_PASSED, Failed: $TESTS_FAILED"
[ $TESTS_FAILED -eq 0 ] && exit 0 || exit 1

步骤 6:编写 API 文档(docs/API.md)

## Recent Directories

### `goto recent [n]`

Display recently navigated directories in reverse chronological order.

**Performance:** <10ms for history retrieval

**Examples:**
```bash
goto recent        # Show all recent directories
goto recent 5      # Show 5 most recent

**Step 7: Update README** (`README.md`)
```markdown
### Recent Directories

Quickly revisit recently navigated directories:

```bash
goto recent        # Show all recent directories
goto recent 5      # Show 5 most recent

**Step 8: Validate Performance**
```bash
time goto recent
# Expected: <10ms

步骤 9:提交

git commit -m "feat: implement recent directories command (CET-77)

Add goto recent command to display recently navigated directories.

Features:
- List all recent directories
- Limit to N most recent
- Unique directories only
- Reverse chronological order

Performance:
- History retrieval: <10ms ✓

Tests:
- 3/3 tests passing
- 100% coverage

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>"
示例 2:添加基准测试套件(CET-85)

完整的基准测试实现,包含辅助函数、工作区和 CSV 存储。

基准测试结构(benchmarks/bench-cached-vs-uncached.sh)

#!/bin/bash
# Benchmark: Cached vs Uncached Navigation Performance

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$SCRIPT_DIR/.."

source "$SCRIPT_DIR/bench-helpers.sh"
source "$REPO_DIR/lib/cache-index.sh"

main() {
    bench_header "Cached vs Uncached Navigation Performance"

    echo "Configuration:"
    echo "  Iterations: 10"
    echo "  Warmup: 3 runs"
    echo ""

    benchmark_cached_vs_uncached

    generate_summary
}

benchmark_cached_vs_uncached() {
    bench_section "Benchmark: Cached vs Uncached Lookup"

    # Setup workspace
    local workspace=$(bench_create_workspace "medium")

    # Phase 1: Uncached lookup
    echo "Phase 1: Uncached lookup (no cache)"
    echo "─────────────────────────────────"

    # Warmup
    bench_warmup "__goto_cache_lookup unix-goto" 3

    # Run benchmark
    local uncached_stats=$(bench_run "uncached" \
        "__goto_cache_lookup unix-goto" 10)

    IFS=',' read -r uc_min uc_max uc_mean uc_median uc_stddev <<< "$uncached_stats"

    bench_print_stats "$uncached_stats" "Uncached Results"

    # Phase 2: Cached lookup
    echo ""
    echo "Phase 2: Cached lookup (with cache)"
    echo "─────────────────────────────────"

    # Build cache
    __goto_cache_build

    # Warmup
    bench_warmup "__goto_cache_lookup unix-goto" 3

    # Run benchmark
    local cached_stats=$(bench_run "cached" \
        "__goto_cache_lookup unix-goto" 10)

    IFS=',' read -r c_min c_max c_mean c_median c_stddev <<< "$cached_stats"

    bench_print_stats "$cached_stats" "Cached Results"

    # Calculate speedup
    local speedup=$(bench_compare "$uc_mean" "$c_mean")

    echo ""
    echo "Speedup Analysis:"
    echo "  Speedup ratio:                               ${speedup}x"

    # Assert targets
    bench_assert_target "$c_mean" 100 "Cached navigation time"

    # Save results
    bench_save_result "cached_vs_uncached" "$uncached_stats" "uncached"
    bench_save_result "cached_vs_uncached" "$cached_stats" "cached"

    # Cleanup
    bench_cleanup_workspace "$workspace"
}

main
exit 0

基准测试辅助函数(benchmarks/bench-helpers.sh)

#!/bin/bash
# Benchmark helper functions

BENCH_RESULTS_DIR="${BENCH_RESULTS_DIR:-$HOME/.goto_benchmarks}"

# High-precision timing
bench_time_ms() {
    local cmd="$*"
    local start=$(date +%s%N)
    eval "$cmd" > /dev/null 2>&1
    local end=$(date +%s%N)
    echo $(((end - start) / 1000000))
}

# Calculate statistics
bench_calculate_stats() {
    local values=("$@")
    local count=${#values[@]}

    # Sort values
    IFS=$'\n' sorted=($(sort -n <<<"${values[*]}"))

    # Min/Max
    local min=${sorted[0]}
    local max=${sorted[$((count-1))]}

    # Mean
    local sum=0
    for val in "${values[@]}"; do
        sum=$((sum + val))
    done
    local mean=$((sum / count))

    # Median
    local mid=$((count / 2))
    local median=${sorted[$mid]}

    # Standard deviation
    local variance=0
    for val in "${values[@]}"; do
        local diff=$((val - mean))
        variance=$((variance + diff * diff))
    done
    variance=$((variance / count))
    local stddev=$(echo "sqrt($variance)" | bc)

    echo "$min,$max,$mean,$median,$stddev"
}

# Print header
bench_header() {
    local title="$1"
    echo "╔══════════════════════════════════════════════════════════════════╗"
    printf "║  %-62s  ║\n" "$title"
    echo "╚══════════════════════════════════════════════════════════════════╝"
    echo ""
}

# Print section
bench_section() {
    local title="$1"
    echo "$title"
    echo "─────────────────────────────────────────────────────────────────"
}

# Print statistics block
bench_print_stats() {
    local stats="$1"
    local label="$2"

    IFS=',' read -r min max mean median stddev <<< "$stats"

    echo ""
    echo "$label:"
    printf "  Min:                                             %dms\n" "$min"
    printf "  Max:                                             %dms\n" "$max"
    printf "  Mean:                                            %dms\n" "$mean"
    printf "  Median:                                          %dms\n" "$median"
    printf "  Std Dev:                                       %.2fms\n" "$stddev"
}

# Assert performance target
bench_assert_target() {
    local actual="$1"
    local target="$2"
    local label="$3"

    if [ "$actual" -lt "$target" ]; then
        echo "✓ $label meets target: ${actual}ms (target: <${target}ms)"
    else
        echo "✗ $label exceeds target: ${actual}ms (target: <${target}ms)"
    fi
}

# Initialize results directory
bench_init() {
    mkdir -p "$BENCH_RESULTS_DIR"
}

# Save benchmark result
bench_save_result() {
    bench_init

    local name="$1"
    local stats="$2"
    local metadata="${3:-}"

    local timestamp=$(date +%s)
    local results_file="$BENCH_RESULTS_DIR/results.csv"

    # Create header if file doesn't exist
    if [ ! -f "$results_file" ]; then
        echo "timestamp,benchmark_name,operation,min_ms,max_ms,mean_ms,median_ms,stddev,metadata" > "$results_file"
    fi

    # Append result
    echo "$timestamp,$name,$metadata,$stats" >> "$results_file"
}

# Create test workspace
bench_create_workspace() {
    local size="${1:-medium}"
    local workspace=$(mktemp -d)

    case "$size" in
        small)
            # 10 folders
            for i in {1..10}; do
                mkdir -p "$workspace/folder-$i"
            done
            ;;
        medium)
            # 50 folders
            for i in {1..50}; do
                mkdir -p "$workspace/folder-$i"
            done
            ;;
        large)
            # 500 folders
            for i in {1..500}; do
                mkdir -p "$workspace/folder-$i"
            done
            ;;
    esac

    echo "$workspace"
}

# Cleanup workspace
bench_cleanup_workspace() {
    local workspace="$1"
    rm -rf "$workspace"
}

# Run benchmark iterations
bench_run() {
    local name="$1"
    local cmd="$2"
    local iterations="${3:-10}"

    local times=()

    for i in $(seq 1 $iterations); do
        local time=$(bench_time_ms "$cmd")
        times+=("$time")
        printf "  Run %2d: %dms\n" "$i" "$time"
    done

    bench_calculate_stats "${times[@]}"
}

# Warmup iterations
bench_warmup() {
    local cmd="$1"
    local iterations="${2:-3}"

    for i in $(seq 1 $iterations); do
        eval "$cmd" > /dev/null 2>&1
    done
}

# Compare performance
bench_compare() {
    local baseline="$1"
    local optimized="$2"

    local speedup=$(echo "scale=2; $baseline / $optimized" | bc)
    echo "$speedup"
}

最佳实践

代码风格规范

函数结构:

function_name() {
    local param1="$1"
    local param2="${2:-default}"

    # Validate inputs
    if [ -z "$param1" ]; then
        echo "Error: param1 required"
        return 1
    fi

    # Main logic
    local result=$(process "$param1")

    # Return value
    echo "$result"
    return 0
}

错误处理:

# Always check command success
if ! goto index rebuild; then
    echo "Failed to rebuild cache"
    return 1
fi

# Use meaningful error messages
if [ ! -d "$target_dir" ]; then
    echo "❌ Directory not found: $target_dir"
    return 1
fi

注释:

# Good: Explain why, not what
# Cache lookup is O(1) because we use grep on indexed file

# Bad: Explain what (obvious from code)
# Set folder_name to first parameter
folder_name="$1"
数据文件格式模式

标准格式: 使用竖线分隔,并包含元数据标头

# Module data file
# Version: 1.0
# Built: [timestamp]
# Format: field1|field2|field3
#---
value1|value2|value3
value1|value2|value3
性能优化提示

缓存系统:

  • 对所有查找使用缓存
  • 限制递归搜索深度
  • 避免冗余的文件系统操作
  • 使用 grep 快速匹配文本

内存:

  • 缓存文件:500 个文件夹时小于 100KB
  • 内存使用:极少(仅 shell 函数)
  • 无常驻进程
调试提示

启用 Bash 跟踪:

set -x
source goto.sh
goto test
set +x

检查函数是否存在:

if declare -f __goto_cache_lookup > /dev/null; then
    echo "Function loaded"
fi

调试缓存问题:

# View cache file
cat ~/.goto_index

# Check cache age
stat -f %m ~/.goto_index

# Rebuild and observe
goto index rebuild
Linear 工作流集成

Linear 项目详情:

  • 团队:Ceti-luxor
  • 项目:unix-goto - Shell Navigation Tool
  • 项目 ID:7232cafe-cb71-4310-856a-0d584e6f3df0

问题生命周期:

Backlog → In Progress → Complete

标准工作流:

  1. 从第 3 阶段待办事项中选择一个问题
  2. 在 Linear 中将其移至“In Progress”
  3. 创建功能分支:feature/CET-XX-feature-name
  4. 按照 9 步工作流实施
  5. 彻底测试(100% 覆盖率)
  6. 按正确格式提交
  7. 使用结果更新 Linear 问题
  8. 将其移至“Complete”

Linear 问题模板:

## Problem
What problem does this solve?

## Solution
How will we solve it?

## Acceptance Criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Tests pass
- [ ] Performance targets met

## Performance Targets
- Metric 1: <target>
- Metric 2: <target>

## Dependencies
- Issue CET-XX (if applicable)

快速参考

基本命令
# Development
source goto.sh                 # Load all modules
goto index rebuild             # Rebuild cache
bash test-cache.sh             # Run cache tests
bash test-benchmark.sh         # Run benchmark tests
goto benchmark all             # Run all benchmarks

# Debugging
set -x; goto project; set +x   # Trace execution
declare -F | grep goto         # List functions
cat ~/.goto_index              # View cache

# Git workflow
git checkout -b feature/CET-XX # Create branch
git commit -m "feat: ..."      # Commit with proper format
git push origin feature/CET-XX # Push to remote

# Performance
time goto project              # Measure navigation
goto benchmark navigation      # Benchmark navigation
goto index status              # Check cache health
文件位置
~/.goto_index         - Cache file
~/.goto_bookmarks     - Bookmarks file
~/.goto_history       - History file
~/.goto_stack         - Navigation stack
~/.goto_benchmarks/   - Benchmark results directory
性能目标汇总
指标目标当前
缓存导航<100ms26ms ✓
缓存构建<5s3-5s ✓
缓存命中率>90%92-95% ✓
加速比20-50x8x ⚠
测试覆盖率100%100% ✓

技能版本: 1.0 最后更新: 2025 年 10 月 维护者: Manu Tej + Claude Code 源代码仓库: https://github.com/manutej/unix-goto

评论

支持 Markdown