mcpField
R
rg-code-search

rg-code-search

github.com/laurigates開発5943 回インストール1 日前に更新
リポジトリ

rg-code-search について

rg-code-searchは、ripgrepでソースコードやテキストを検索する開発者向けの手順ガイドです。パターン検索、絞り込み、出力制御、コード監査で使う検索方法を扱います。

主な機能

  1. 01正規表現と複数行検索
  2. 02ファイル種別、glob、パスでの絞り込み
  3. 03コンテキストと出力の制御
  4. 04定義、テスト、コードマーカーの検索

活用シーン

  1. 01関数やクラスの定義を探す
  2. 02TODOやデバッグ文をコード監査で確認
  3. 03対象ファイル種別を限定して検索
  4. 04一致箇所を見つけてファイルを別ツールに渡す

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/laurigates/claude-plugins --skill rg-code-search

インストール後、Claude Code で/rg-code-searchを入力して読み込まれたか確認します。

詳細

rg コード検索

強力なフィルタリングとパターンマッチングを備えた、超高速コード検索ツール rg(ripgrep)のエキスパート向けガイドです。

このスキルを使う場面

このスキルを使う場面...代わりに fd-file-finding を使う場面...
ファイルの内容からテキストや正規表現のパターンを検索する名前、拡張子、パスでファイルを検索する
ファイルの種類(-t py、-t js)で一致結果を絞り込むmtime、サイズ、-type でファイルを絞り込む
ソースファイルをまたいで複数行パターンを検索する別のツールに渡すファイルを探す
このスキルを使う場面...代わりに binary-analysis を使う場面...
ソースコードまたはテキストエンコードされたファイルを検索するコンパイル済みバイナリやファームウェアから文字列を抽出する
リポジトリ内の追跡対象ファイルにあるハードコードされたパターンを監査するELF、Mach-O、または .bin ファイル内の認証情報を探す

主な機能

ripgrep の利点

  • 非常に高速です(Rust で記述されています)
  • .gitignore を自動的に尊重します
  • 大文字と小文字を自動判別して検索します
  • デフォルトで再帰検索します
  • 色付きの出力です
  • 複数行検索に対応しています
  • 置換機能があります

基本的な使い方

簡単な検索
# Basic search
rg pattern                  # Search in current directory
rg "import numpy"           # Search for exact phrase
rg function_name            # Search for function name

# Case-sensitive search
rg -s Pattern               # Force case-sensitive
rg -i PATTERN               # Force case-insensitive
ファイルの種類による絞り込み
# Search specific file types
rg pattern -t py            # Python files only
rg pattern -t rs            # Rust files only
rg pattern -t js            # JavaScript files
rg pattern -t md            # Markdown files

# Multiple types
rg pattern -t py -t rs      # Python and Rust

# List available types
rg --type-list              # Show all known types
拡張子による絞り込み
# Filter by extension
rg pattern -g '*.rs'        # Rust files
rg pattern -g '*.{js,ts}'   # JavaScript and TypeScript
rg pattern -g '!*.min.js'   # Exclude minified files

高度なパターン

正規表現
# Word boundaries
rg '\bfunction\b'           # Match whole word "function"
rg '\btest_\w+'             # Words starting with test_

# Line anchors
rg '^import'                # Lines starting with import
rg 'return$'                # Lines ending with return
rg '^class \w+:'            # Python class definitions

# Character classes
rg 'TODO|FIXME|XXX'         # Find markers
rg '[Ee]rror'               # Error or error
rg '\d{3}-\d{4}'            # Phone numbers
複数行検索
# Multi-line patterns
rg -U 'fn.*\{.*\}'          # Function definitions (Rust)
rg -U 'struct.*{[^}]*}'     # Struct definitions

# Context lines
rg -A 5 pattern             # Show 5 lines after
rg -B 3 pattern             # Show 3 lines before
rg -C 2 pattern             # Show 2 lines before and after
出力形式
# Control output
rg -l pattern               # List files with matches only
rg -c pattern               # Count matches per file
rg --count-matches pattern  # Total match count

# Show context
rg -n pattern               # Show line numbers (default)
rg -N pattern               # Don't show line numbers
rg --heading pattern        # Group by file (default)
rg --no-heading pattern     # Don't group by file

# Customize output
rg --vimgrep pattern        # Vim-compatible format
rg --json pattern           # JSON output

高度な絞り込み

パスによる絞り込み
# Search in specific directories
rg pattern src/             # Only src/ directory
rg pattern src/ tests/      # Multiple directories

# Exclude paths
rg pattern -g '!target/'    # Exclude target/
rg pattern -g '!{dist,build,node_modules}/'  # Exclude multiple

# Full path matching
rg pattern -g '**/test/**'  # Only test directories
内容による絞り込み
# Search only in files containing pattern
rg --files-with-matches "import.*React" | xargs rg "useState"

# Exclude files by content
rg pattern --type-not markdown

# Search only uncommitted files
rg pattern $(git diff --name-only)
サイズと隠しファイル
# Include hidden files
rg pattern -u               # Include hidden
rg pattern -uu              # Include hidden + .gitignore'd
rg pattern -uuu             # Unrestricted: everything

# Exclude by size
rg pattern --max-filesize 1M  # Skip files over 1MB

コード検索パターン

定義の検索
# Function definitions
rg '^def \w+\('             # Python functions
rg 'fn \w+\('               # Rust functions
rg '^function \w+\('        # JavaScript functions
rg '^\s*class \w+'          # Class definitions

# Interface/type definitions
rg '^interface \w+'         # TypeScript interfaces
rg '^type \w+ ='            # Type aliases
rg '^struct \w+'            # Struct definitions (Rust/Go)
使用箇所の検索
# Find function calls
rg 'functionName\('         # Direct calls
rg '\.methodName\('         # Method calls

# Find imports
rg '^import.*module_name'   # Python imports
rg '^use.*crate_name'       # Rust uses
rg "^import.*'package'"     # JavaScript imports
コード品質チェック
# Find TODOs and FIXMEs
rg 'TODO|FIXME|XXX|HACK'    # Find all markers
rg -t py '#\s*TODO'         # Python TODOs
rg -t rs '//\s*TODO'        # Rust TODOs

# Find debug statements
rg 'console\.log'           # JavaScript
rg 'println!'               # Rust
rg 'print\('                # Python

# Find security issues
rg 'password.*=|api_key.*=' # Potential secrets
rg 'eval\('                 # Eval usage
rg 'exec\('                 # Exec usage
テストパターン
# Find tests
rg '^def test_' -t py       # Python tests
rg '#\[test\]' -t rs        # Rust tests
rg "describe\(|it\(" -t js  # JavaScript tests

# Find skipped tests
rg '@skip|@pytest.mark.skip' -t py
rg '#\[ignore\]' -t rs
rg 'test\.skip|it\.skip' -t js

ファイル操作

検索と置換
# Preview replacements
rg pattern --replace replacement

# Perform replacement (requires external tool)
rg pattern -l | xargs sed -i 's/pattern/replacement/g'

# With confirmation (using fd and interactive)
fd -e rs | xargs rg pattern --files-with-matches | xargs -I {} sh -c 'vim -c "%s/pattern/replacement/gc" -c "wq" {}'
他のツールとの連携
# Pipe to other commands
rg -l "TODO" | xargs wc -l          # Count lines with TODOs
rg "function" --files-with-matches | xargs nvim  # Open files in editor

# Combine with fd (prefer fd's native -x execution)
fd -e py -x rg "class.*Test" {}     # Find test classes
fd -e rs -x rg "unsafe" {}          # Find unsafe blocks

# Count occurrences
rg -c pattern | awk -F: '{sum+=$2} END {print sum}'
統計と分析
# Count total matches
rg pattern --count-matches --no-filename | awk '{sum+=$1} END {print sum}'

# Find most common matches
rg pattern -o | sort | uniq -c | sort -rn

# Files with most matches
rg pattern -c | sort -t: -k2 -rn | head -10

パフォーマンスの最適化

高速化のヒント
# Limit search
rg pattern --max-depth 3    # Limit directory depth
rg pattern -g '*.rs' -t rust  # Use type filters

# Parallel processing (default)
rg pattern -j 4             # Use 4 threads

# Memory management
rg pattern --mmap           # Use memory maps (faster)
rg pattern --no-mmap        # Don't use memory maps
大規模なコードベースへの取り組み方
# Narrow scope first
rg pattern src/             # Specific directory
rg pattern -t py -g '!test*'  # Specific type, exclude tests

# Use file list caching
rg --files > /tmp/files.txt
rg pattern $(cat /tmp/files.txt)

# Exclude large directories
rg pattern -g '!{target,node_modules,dist,build}/'

ベストプラクティス

rg を使う場面

  • コード内のパターンを検索する
  • 関数やクラスの定義を見つける
  • コードを分析、監査する
  • リファクタリングを支援する
  • セキュリティスキャンを行う

代わりに grep を使う場面

  • POSIX 互換性が必要な場合
  • 単発の簡単な検索を行う場合
  • パイプで渡された入力(stdin)を検索する場合
  • システム管理のタスクを行う場合

効果的な検索のヒント

  • パターン内の正規表現の特殊文字をエスケープします
  • 無視対象や隠しファイルを検索するときは -u フラグを使います
  • --glob '!vendor' を使って、大きなバイナリファイルや生成ファイルを除外します
  • 高速性と便利なデフォルト設定を活かすため、grep より rg を優先します

クイックリファレンス

主要なオプション
オプション用途例
-t TYPEファイルの種類で絞り込みrg -t py pattern
-g GLOBGlob パターンrg -g '*.rs' pattern
-i大文字と小文字を区別しないrg -i pattern
-s大文字と小文字を区別するrg -s Pattern
-w単語全体に一致rg -w word
-l一致箇所のあるファイルrg -l pattern
-cファイルごとの一致数rg -c pattern
-A N一致箇所の後の行rg -A 5 pattern
-B N一致箇所の前の行rg -B 3 pattern
-C N前後の行rg -C 2 pattern
-U複数行rg -U 'pattern.*'
-u隠しファイルを含めるrg -u pattern
--replaceテキストを置換rg pattern --replace new
ファイルの種類(一般的なもの)
種類拡張子
-t pyPython(.py、.pyi)
-t rsRust(.rs)
-t jsJavaScript(.js、.jsx)
-t tsTypeScript(.ts、.tsx)
-t goGo(.go)
-t mdMarkdown(.md、.markdown)
-t yamlYAML(.yaml、.yml)
-t jsonJSON(.json)
よく使うコマンドパターン
# Find function definitions across codebase
rg '^\s*(def|fn|function)\s+\w+' -t py -t rs -t js

# Find all imports
rg '^(import|use|require)' -t py -t rs -t js

# Find potential bugs
rg 'TODO|FIXME|XXX|HACK|BUG'

# Find test files and count tests
rg -t py '^def test_' -c

# Find large functions (50+ lines)
rg -U 'def \w+.*\n(.*\n){50,}' -t py

# Security audit
rg 'password|api_key|secret|token' -i -g '!*.{lock,log}'

このため、開発ワークフローで高速かつ強力なコード検索を行うには、rg が最適なツールです。

コメント