コード解析・生成・リファクタリングのタスクに、スクリプトや自動化ワークフローで Cursor CLI を使おう。

仕組み

非対話型のスクリプト実行や自動化には print mode-p, --print)を使おう。

スクリプトでのファイル変更

スクリプト内でファイルを変更する場合は、--print--force を組み合わせよう:
# print モードでファイル変更を有効化
cursor-agent -p --force "このコードをモダンな ES6+ 構文にリファクタして"

# --force がない場合、変更は提案のみで適用されない
cursor-agent -p "このファイルに JSDoc コメントを追加して"  # ファイルは変更されない

# 実際にファイルを変更するバッチ処理
find src/ -name "*.js" | while read file; do
  cursor-agent -p --force "この $file に網羅的な JSDoc コメントを追加して"
done
--force フラグを使うと、確認なしでエージェントが直接ファイルを変更する

セットアップ

詳しい手順は InstallationAuthentication をチェックしてね。
# Cursor CLI をインストール
curl https://cursor.com/install -fsS | bash

# スクリプト用の API キーを設定
export CURSOR_API_KEY=your_api_key_here
cursor-agent -p "Analyze this code"

スクリプト例

スクリプトの用途に応じて出力形式を使い分けよう。詳しくはOutput formatを見てね。

コードベースを検索する

読みやすい出力には --output-format text を使う:
#!/bin/bash
# シンプルなコードベースへの質問

cursor-agent -p --output-format text "What does this codebase do?"

自動コードレビュー

構造化された分析には --output-format json を使う:
#!/bin/bash
# simple-code-review.sh - 基本的なコードレビュー用スクリプト

echo "Starting code review..."

# 直近の変更をレビュー
cursor-agent -p --force --output-format text \
  "Review the recent code changes and provide feedback on:
  - Code quality and readability  
  - Potential bugs or issues
  - Security considerations
  - Best practices compliance

  Provide specific suggestions for improvement and write to review.txt"

if [ $? -eq 0 ]; then
  echo "✅ コードレビューが正常に完了したよ"
else
  echo "❌ コードレビューに失敗したよ"
  exit 1
fi

リアルタイム進行状況のトラッキング

リアルタイムの進行状況をトラッキングするには --output-format stream-json を使う:
#!/bin/bash
# stream-progress.sh - リアルタイムで進行状況をトラッキング

echo "🚀 ストリーム処理を開始..."

# リアルタイムに進行をトラッキング
accumulated_text=""
tool_count=0
start_time=$(date +%s)

cursor-agent -p --force --output-format stream-json \
  "Analyze this project structure and create a summary report in analysis.txt" | \
  while IFS= read -r line; do
    
    type=$(echo "$line" | jq -r '.type // empty')
    subtype=$(echo "$line" | jq -r '.subtype // empty')
    
    case "$type" in
      "system")
        if [ "$subtype" = "init" ]; then
          model=$(echo "$line" | jq -r '.model // "unknown"')
          echo "🤖 使用モデル: $model"
        fi
        ;;
        
      "assistant")
        # ストリーミングされたテキストの差分を蓄積
        content=$(echo "$line" | jq -r '.message.content[0].text // empty')
        accumulated_text="$accumulated_text$content"
        
        # ライブ進捗表示
        printf "\r📝 生成中: %d 文字" ${#accumulated_text}
        ;;
        
      "tool_call")
        if [ "$subtype" = "started" ]; then
          tool_count=$((tool_count + 1))
          
          # ツール情報を抽出
          if echo "$line" | jq -e '.tool_call.writeToolCall' > /dev/null 2>&1; then
            path=$(echo "$line" | jq -r '.tool_call.writeToolCall.args.path // "unknown"')
            echo -e "\n🔧 ツール #$tool_count: $path を作成中"
          elif echo "$line" | jq -e '.tool_call.readToolCall' > /dev/null 2>&1; then
            path=$(echo "$line" | jq -r '.tool_call.readToolCall.args.path // "unknown"')
            echo -e "\n📖 ツール #$tool_count: $path を読み取り中"
          fi
          
        elif [ "$subtype" = "completed" ]; then
          # ツール結果を抽出して表示
          if echo "$line" | jq -e '.tool_call.writeToolCall.result.success' > /dev/null 2>&1; then
            lines=$(echo "$line" | jq -r '.tool_call.writeToolCall.result.success.linesCreated // 0')
            size=$(echo "$line" | jq -r '.tool_call.writeToolCall.result.success.fileSize // 0')
            echo "   ✅ $lines 行を作成 ($size bytes)"
          elif echo "$line" | jq -e '.tool_call.readToolCall.result.success' > /dev/null 2>&1; then
            lines=$(echo "$line" | jq -r '.tool_call.readToolCall.result.success.totalLines // 0')
            echo "   ✅ $lines 行を読み取り"
          fi
        fi
        ;;
        
      "result")
        duration=$(echo "$line" | jq -r '.duration_ms // 0')
        end_time=$(date +%s)
        total_time=$((end_time - start_time))
        
        echo -e "\n\n🎯 ${duration}ms で完了(合計 ${total_time}s)"
        echo "📊 最終統計: ツール $tool_count 件、生成 ${#accumulated_text} 文字"
        ;;
    esac
  done