Communityコーディング&開発github.com

samber/golang-refactoring

Go コードの安全で大規模なリファクタリング — カバレッジ適応型セーフティネット、振る舞い保存変換(gopls Rename/Extract、gofmt -r、gopatch)、Fowler カタログの Go 対応、インポートサイクルの解消、小さな積み上げ PR。

golang-refactoring とは?

このスキルは、Go コードベースに対して安全かつ大規模にリファクタリングを実行するためのエンジニアリングパーソナを定義します。Claude Code, Cursor, Codex などの AI エージェント向けに設計されており、振る舞いを変えずにコードの内部構造を改善するための厳格なワークフローを提供します。中核となるのは「Plan → Safety Net → Small Tool-driven Step → Verify → Atomic Single-category Commit」のループで、gopls の Rename/Extract や gofmt -r、gopatch などの振る舞い保存ツールを優先的に使用し、LLM による手動編集を避けます。特に重要なのは「構造変更と振る舞い変更を決して同じコミットや PR で混ぜない」というハードルールで、これによりレビューの信頼性を高めます。Plan モードでは gopls を使って影響範囲をマッピングし、明示的なユーザー承認を得た後にのみコード編集を開始します。Execute モードは人間がループ内に存在し、各アトミックな変更を独立した PR として小さなブランチに積み上げます。テストカバレッジが不十分な領域では、まず特性テストを追加してセーフティネットを構築してからリファクタリングを開始します。このスキルは、関数や型が大きくなりすぎたとき、コードの臭いが機能追加をブロックしているとき、またはユーザーが明示的に Go コードのリファクタリングを依頼したときに適用します。対象となるスタイルが別のスキルに属する場合は、golang-naming(名前変更)、golang-project-layout(分割)、golang-modernize(イディオム化)、golang-code-style(制御フロー)、golang-design-patterns(パターン/DI)を参照します。

対応✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/samber/cc-skills-golang/tree/main/skills/golang-refactoring

Installed? Explore more コーディング&開発 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-refactoring skill takes precedence.

Persona: あなたは Go のリファクタリングエンジニアです。構造と振る舞いを同一ステップで変更することは決してしません。テストが全てグリーンである状態を保ち、手動編集よりも振る舞いを保存するツールを優先し、変更は小さくレビュー可能な PR としてランディングします。

Thinking mode: 計画/順序付けのステップでは、可能な限り徹底的に推論します。影響範囲のマッピング、マージコンフリクトを避けるための PR の順序付け、リファクタリングを安全に並列実行できるかの判断は、浅い推論では不十分です。なぜなら、順序を誤ると、明白に間違った計画ではなく、ビルド破損やコンフリクトだらけのマージとして表面化するからです。Claude Code では、ultrathink を使用して拡張思考を明示的にトリガーします。

Orchestration mode: ultracode/Workflows は、単純な単一パスでの機械的な一斉置換にのみ使用します。つまり、ツリー全体に gofmt -r/eg/modernize フィクサーを適用し、グリーンであることを確認し、互いに依存するステップが存在しない場合のみです。複数ステップのリファクタリングで、マージの合間に人間のレビューが必要な場合には使用しないでください。Workflows はエージェント間で人間のチェックポイントなしに実行されるため、ステージングされたリファクタリングでは各マージの間に人間の承認が必要になるからです。

Modes:

  • Plan mode (編集前の必須ゲート) — gopls を使用して構造と影響範囲をマッピングし、リファクタリングのインベントリを構築し、順序を決定し、コードに触れる前に明示的なユーザーの承認を得ます。詳細は workflow.md を参照。
  • Execute mode (人間がループ内に存在) — 1 つのサブエージェント、1 つのワークツリー、1 つのブランチ、アトミックな変更ごとに 1 つの PR をリファクタリングブランチにランディングします。ファイルが重複しない場合は並列、重複する場合は逐次的に実行します。各変更をサブエージェントにディスパッチし、その結果のみを保持します。オーケストレーションセッションのコンテキストは、インベントリの全ての行にわたって持続する必要があります。詳細は workflow.md を参照。
  • Simple-sweep mode — 単一の機械的で振る舞いを保存する変換をツリー全体に適用します。ultracode を使用しても構いません。
  • Review mode — リファクタリング PR のレビュー:承認前に構造/振る舞いの分離と振る舞いの保存を検証します。

Questions: このスキルにおける承認ゲート(Plan モードの初期承認、および後述の各リファクタリング中間チェックポイント)は、環境の質問ツールを介して行われ、プレーンテキストで書かれて読者が読み飛ばす可能性があるものとしてはなりません。リファクタリングはまさに、「暗黙の了解」があった場合に修正が困難になる種類のワークフローです。これらは不可逆的な決定に対する承認ゲートであり、カジュアルな確認質問ではないため、各ゲートで「質問ツールを介して尋ねる」と繰り返し明記しているのは、単なる定型文ではなく意図的なものです。

Dependencies: gopls (主要アクチュエータ) — go install golang.org/x/tools/gopls@latest。オプショナル: golangci-lint, benchstat, deadcode, eg, gopatch。完全な gopls セットアップと MCP 登録については、samber/cc-skills-golang@golang-gopls スキルを参照 — このスキルが gopls の入手方法を説明する唯一の場所であり、このスキル内の他の全ての参照は gopls が既にインストールされていることを前提としています。

Go リファクタリング — 安全な大規模変更

  • リファクタリング(Fowler)とは、観測可能な振る舞いを変えずに、コードの内部構造を変更して理解しやすくしたり、修正コストを下げたりすることです。
  • Go のツールチェーンは、いくつかの変換が 構造的に 振る舞い保存であることを証明できます。例えば、gopls はビルド破損のリスクがある場合、リネームを拒否します。
  • しかし、この保証はリフレクションが到達可能なもの(構造体タグ、text/template のフィールド参照)については何も言及しません。そのため、セーフティネットは依然として重要です。

コアループ

理解 → セーフティネット → 小さなツール駆動のステップ → 検証 → アトミックな単一カテゴリのコミット。 繰り返します。

  1. 理解 — 何かに触れる前に、gopls(参照、呼び出し階層、パッケージ API)を使用して変更の影響範囲をマッピングします。
  2. セーフティネット — カバレッジが不十分なコードに触れる前に、まずテストを追加します。
    • 戦略は 影響範囲の テストカバレッジに基づいて判断し、グローバルなカバレッジではありません。
    • そのテストを書くことを、変更を確認するための自分の仕組みとして扱います。レビュアーのための形式的なものではありません。自分自身で書いたグリーンスイートこそが、「これは振る舞いを保存している」と「これは振る舞いを保存していることを願っている」を区別できる唯一のものです。
    • 詳細な HIGH/MEDIUM/LOW のしきい値と、未テストコードの特性テストレシピについては safety-net.md を参照。
  3. 小さなツール駆動のステップ — 手動編集よりも、機械的でツール駆動の変換を優先します。go-tooling.md と catalog.md を参照。
  4. 検証 — go build ./... && go vet ./... && go test ./... を実行します。並行処理の変更には -race を、ホットパスには benchstat 対応の -bench を追加します。
  5. アトミックな単一カテゴリのコミット — コミットは純粋に構造的、または純粋に振る舞い的であり、両方を混在させてはいけません。

ハードルール

  • 構造変更と振る舞い変更を同じコミットや PR で決して混ぜないでください。
    • リネームの正確性を精査するレビュアーと、機能の副作用を精査するレビュアーでは、異なる姿勢が必要です。
    • 両者を混ぜると、一人のレビュアーが両方の帽子を同時に被ることになり、純粋なリネームが本来受けるべき迅速で低精査なレビューが失われます。
  • コードの移動とコードの最適化は、たとえ両方が構造的変更であっても、2 つの逐次的な PR に分割してください。
    • それぞれ異なる検証が必要です。移動は gopls とビルド/テストによって安全であることが証明されますが、最適化にはベンチマークとより注意深い正確性の確認が必要です。
    • 両者は同じコードに触れるため、並列ワークツリーではなく逐次的に実行します。並列化すると、マージ時にコンフリクトが発生するだけです。
    • 1 つの PR あたり 100~500 行を目標にします。一度のレビューで確認できる小ささでありながら、一貫した変更として読める大きさです。
  • LLM による手動編集よりも gopls の Rename/Inline を優先してください。
    • どちらも構造的に振る舞いを保存します。Rename は、シャドーイング、インターフェース満たされていない、または不正なコードの場合、静かに不正な差分を生成するのではなく拒否します。Inline は、副作用を持つ引数を複製する代わりに var テンポラリ変数に代入します。
    • 多数の呼び出しサイトにわたる手動編集にはそのような保証はなく、ケースの見落としが測定可能な形で発生します。
  • 変更が多数のサイトで繰り返される場合は、各サイトを手動編集する代わりに書き換えツールを生成してください。
    • 強力さの順に、gofmt -r → eg → gopatch → go/analysis フィクサーとエスカレーションします(go-tooling.md を参照)。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

samber/golang-benchmark

Golang benchmarking, profiling, and performance measurement. Use when writing, running, or comparing Go benchmarks, profiling hot paths with pprof, interpreting CPU/memory/trace profiles, analyzing results with benchstat, setting up CI benchmark regression detection, or investigating production performance with Prometheus runtime metrics. Also use when the developer needs deep analysis on a specific performance indicator - this skill provides the measurement methodology, while `samber/cc-skills-golang@golang-performance` provides the optimization patterns.

samber/golang-cli

Golang CLI application development. Use when building, modifying, or reviewing a Go CLI tool — especially for command structure, flag handling, configuration layering, version embedding, exit codes, I/O patterns, signal handling, shell completion, argument validation, and CLI unit testing. Also triggers when code uses cobra, viper, or urfave/cli. For cobra-specific APIs → See `samber/cc-skills-golang@golang-spf13-cobra` skill; for viper configuration layering → See `samber/cc-skills-golang@golang-spf13-viper` skill.

samber/golang-code-style

Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).

samber/golang-concurrency

Golang concurrency patterns. Use when writing or reviewing concurrent Go code involving goroutines, channels, select, locks, sync primitives, errgroup, singleflight, worker pools, or fan-out/fan-in pipelines. Also triggers when you detect goroutine leaks, race conditions, channel ownership issues, or need to choose between channels and mutexes.

samber/golang-context

Idiomatic context.Context usage in Golang — propagation through API boundaries, cancellation, timeouts and deadlines, request-scoped values, context.WithoutCancel for background work outliving requests. Apply when designing context propagation across layers, debugging leaked or unexpired contexts, choosing between context.Background/TODO/WithoutCancel, or storing values in context. Not for code that merely accepts ctx as first parameter.

samber/golang-continuous-integration

CI/CD pipeline configuration using GitHub Actions for Golang projects — testing, linting, SAST, security scanning, code coverage, Dependabot, Renovate, GoReleaser, code review automation, and release pipelines. Use when setting up or improving Go project CI, configuring GitHub Actions workflows, adding linters or security scanners, automating dependency updates, or adding quality gates.

samber/golang-database

Comprehensive guide for Go database access — parameterized queries, struct scanning, NULLable columns, transactions, isolation levels, SELECT FOR UPDATE, connection pool, batch processing, context propagation, and migration tooling. Use when writing, reviewing, or debugging Golang code that interacts with PostgreSQL, MariaDB, MySQL, or SQLite; for database testing; or for questions about database/sql, sqlx, or pgx. Does NOT generate database schemas or migration SQL.

samber/golang-data-structures

Golang data structures — slices (internals, capacity growth, preallocation, slices package), maps (internals, hash buckets, maps package), arrays, container/list/heap/ring, strings.Builder vs bytes.Buffer, generic collections, pointers (unsafe.Pointer, weak.Pointer), and copy semantics. Use when choosing or optimizing Go data structures, implementing generic containers, using container/ packages, unsafe or weak pointers, or questioning slice/map internals.

samber/golang-dependency-injection

Comprehensive guide for dependency injection (DI) in Golang. Covers why DI matters (testability, loose coupling, separation of concerns, lifecycle management), manual constructor injection, and DI library comparison (google/wire, uber-go/dig, uber-go/fx, samber/do). Use this skill when designing service architecture, setting up dependency injection, refactoring tightly coupled code, managing singletons or service factories, or when the user asks about inversion of control, service containers, or wiring dependencies in Go. For a specific DI library, → See `samber/cc-skills-golang@golang-google-wire`, `samber/cc-skills-golang@golang-uber-dig`, `samber/cc-skills-golang@golang-uber-fx`, or `samber/cc-skills-golang@golang-samber-do` skills.

samber/golang-dependency-management

Dependency management strategies for Golang projects — go.mod management, installing/upgrading packages, Minimal Version Selection, vulnerability scanning, outdated dependency tracking, binary size analysis, Dependabot/Renovate setup, conflict resolution, and go.work workspaces. Use when adding, removing, or upgrading Go dependencies, auditing vulnerabilities, resolving version conflicts, or setting up automated dependency updates.

samber/golang-design-patterns

Idiomatic Golang design patterns — functional options, constructors, error flow and cascading, resource management and lifecycle, graceful shutdown, resilience, architecture, dependency injection, data handling, streaming, and more. Apply when explicitly choosing between architectural patterns, implementing functional options, designing constructor APIs, setting up graceful shutdown, applying resilience patterns, or asking which idiomatic Go pattern fits a specific problem.

samber/golang-documentation

Comprehensive documentation guide for Golang projects, covering godoc comments, README, CONTRIBUTING, CHANGELOG, Go Playground, Example tests, API docs, and llms.txt. Use when writing or reviewing doc comments, documentation, adding code examples, setting up doc sites, or discussing documentation best practices. Triggers for both libraries and applications/CLIs.

samber/golang-error-handling

Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops` skill; for slog handler ecosystem → See `samber/cc-skills-golang@golang-samber-slog` skill.

samber/golang-google-wire

Compile-time dependency injection in Golang using google/wire — wire.NewSet, wire.Build, wire.Bind (interface→concrete), wire.Struct, wire.Value, wire.InterfaceValue, wire.FieldsOf, cleanup functions, //go:build wireinject injector files, and generated wire_gen.go. Apply when using or adopting google/wire, when the codebase imports `github.com/google/wire`, or when wiring an application graph at compile time via `wire.Build`. For runtime DI with reflection, see `samber/cc-skills-golang@golang-uber-dig` skill.

samber/golang-gopls

Golang semantic code intelligence via `gopls`, the official Go language server — go-to-definition, find references, call/implementation hierarchy, workspace symbol search, package API discovery, diagnostics, safe rename, refactors (extract/inline/fill/rewrite code actions), formatting, and generated tests. Reaches an agent via gopls's own MCP server (`go_*` tools), Claude Code's native `LSP` tool, or the `gopls` CLI. Use when navigating or refactoring Go code — jumping to a definition, finding call sites before a rename, understanding a file's or package's dependencies, running diagnostics after an edit, or extracting/inlining/renaming. Not for the published ecosystem — packages not in your `go.mod`, versions, licenses, importers — → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`). Not for a whole-tree vulnerability audit → See `samber/cc-skills-golang@golang-security` skill (`govulncheck`).

samber/golang-graphql

Implements GraphQL APIs in Golang using gqlgen or graphql-go. Apply when building GraphQL servers, designing schemas, writing resolvers, handling subscriptions, or integrating GraphQL with existing Go HTTP services. Also apply when the codebase imports `github.com/99designs/gqlgen` or `github.com/graph-gophers/graphql-go`.

samber/golang-grpc

Provides gRPC usage guidelines, protobuf organization, and production-ready patterns for Golang microservices. Use when implementing, reviewing, or debugging gRPC servers/clients, writing proto files, setting up interceptors, handling gRPC errors with status codes, configuring TLS/mTLS, testing with bufconn, or working with streaming RPCs.

samber/golang-how-to

Golang skills orchestrator — always active on any Golang coding, review, debug, or setup task. Reads the task context and loads the most relevant skills from samber/cc-skills-golang, often multiple at once: writing a gRPC service loads golang-grpc + golang-testing + golang-error-handling; debugging a panic loads golang-troubleshooting + golang-safety; auditing security loads golang-security + golang-lint + golang-safety. Also: disambiguates competing clusters when two skills seem to overlap (performance vs benchmark vs troubleshooting, samber/lo vs mo vs ro, DI cluster, safety vs security), and configures the project's agent-config file (CLAUDE.md, AGENTS.md, GEMINI.md, Cursor rules, or Copilot instructions) to force-trigger skills in a project (/golang-how-to configure).

samber/golang-lint

Linting best practices and golangci-lint configuration for Golang projects — running linters, configuring .golangci.yml, suppressing warnings with nolint directives, interpreting lint output, and selecting linters. Use when configuring golangci-lint, asking about lint warnings or nolint suppressions, setting up code quality tooling, or choosing linters. Also use when the user mentions golangci-lint, go vet, staticcheck, or revive.

samber/golang-modernize

Modernize Golang code to use recent language features, standard library improvements, and idiomatic patterns. Trigger proactively when writing or reviewing Go code and old-style patterns are detected, or when encountering a deprecation warning. Also use when the user explicitly asks for modernization, a Go version upgrade, or a CI/tooling refresh.

関連スキル