К основному содержанию
скилл CX Codex

go-build-release — скилл для Claude Code: что делает и как установить

Настраивает воспроизводимую сборку и публикацию бинарников на Go. Помогает прописать GoReleaser, генерацию SBOM, подпись через cosign и сборку образов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add eduardo-sl/go-agent-skills --skill go-build-release -a claude-code
Открыть на GitHub

Что делает go-build-release

Скилл даёт правила для сборки проверяемых артефактов на Go. Он помогает внедрить флаг -trimpath, отключить cgo через CGO_ENABLED=0 и получить идентичные контрольные суммы SHA-256 между чистыми сборками. Сюда же входит внедрение версий через debug.ReadBuildInfo() или -ldflags без фиксации времени сборки по часам.

Внутри описаны шаблоны конфигурации GoReleaser версии 2, генерация манифестов SBOM с помощью syft, выпуск файла checksums.txt и бесключевая подпись артефактов утилитой cosign. Для контейнеров предлагается сборка через ko без Dockerfile либо многоэтапный Dockerfile на базе distroless с запуском от непривилегированного пользователя.

Для работы обязательны Go и git. Без установленных GoReleaser, cosign или ko автоматизация этих шагов не запустится. Скилл не предназначен для линтинга или тестов: эти задачи вынесены в go-ci.

Какие задачи решает

  • настроить воспроизводимую кросс-компиляцию под разные ОС и архитектуры
  • составить конфигурацию GoReleaser для публикации релизов в CI
  • сгенерировать SBOM и подписать контрольные суммы через cosign
  • собрать минимальный контейнерный образ сервиса с помощью ko
  • исправить вывод devel в команде версии скомпилированного бинарника

Примеры запросов агенту

  • Помоги настроить .goreleaser.yaml для кросс-компиляции под linux и darwin
  • Сделай воспроизводимую сборку cmd/api с флагом -trimpath и CGO_ENABLED=0
  • Добавь в пайплайн генерацию SBOM и подпись контрольных сумм через cosign

Как установить go-build-release

1Через Skills CLI (Vercel)

npx skills add eduardo-sl/go-agent-skills --skill go-build-release -a claude-code

2Вручную: положить файлы

~/.claude/skills/go-build-release/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/go-build-release/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о go-build-release

Как установить go-build-release в Claude Code?

Выполните в терминале команду npx skills add eduardo-sl/go-agent-skills --skill go-build-release -a claude-code. Скилл сохранится по пути ~/.claude/skills/go-build-release/SKILL.md.

Что делает скилл go-build-release?

Он инструктирует агента, как собирать байт-в-байт идентичные бинарники на Go, настраивать GoReleaser, выпускать SBOM и подписывать артефакты через cosign.

Какие инструменты нужны для работы скилла?

Обязательно требуются установленный Go и git. GoReleaser, cosign, syft и ko понадобятся только тогда, когда проект использует соответствующие шаги пайплайна.

Исходный текст

SKILL.md · MIT
---
name: go-build-release
description: >
  Build and release Go binaries that are reproducible and verifiable:
  version stamping, -trimpath builds, cross-compilation, GoReleaser,
  checksums, SBOMs, cosign signing, build provenance attestations, and
  container images with ko or a multi-stage Dockerfile. Use when: "release
  a Go binary", "set up GoReleaser", "cross-compile", "reproducible build",
  "sign the release", "generate an SBOM", "build provenance", "publish a
  container image", "version command shows (devel)".
  Not for: test and lint pipelines (go-ci), shrinking the binary or image
  (go-binary-size), auditing dependencies (go-dependency-audit).
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain and git. GoReleaser, cosign, syft and ko are optional, used when the project adopts them.
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(git:*) Bash(goreleaser:*)
metadata:
  author: eduardo-sl
  version: "1.0.0"
---

# Go Build and Release

A release is a promise that the binary users run is the one your source
and pipeline produced. Make it reproducible so anyone can rebuild it, and
verifiable so anyone can check it — before automating the publishing.

Detailed reference material, loaded on demand:

- `references/goreleaser.md` — a complete `.goreleaser.yaml` and the
  tag-triggered release workflow.
- `references/supply-chain.md` — SBOMs, cosign signing and verification,
  provenance attestations, signing container images.

Read a reference file only when the summary below is not enough.

## 1. Version Stamping

```go
// Go 1.24+: built from a git checkout, Main.Version is the tag (v1.4.0)
// or a pseudo-version; vcs.* settings carry the commit and dirty flag.
info, _ := debug.ReadBuildInfo()
fmt.Println(info.Main.Version, info.GoVersion)
```

```bash
go version -m ./bin/api          # inspect what a binary was built from
```

- Prefer build info: it needs no flags and cannot drift from the source.
- When a release tool builds from an archive without `.git`, inject the
  values: `-ldflags "-X main.version=v1.4.0 -X main.commit=$SHA"`.
- Never stamp the wall-clock build time — it makes every build unique.
  Use the commit time if you need a date.

## 2. Reproducible Builds

The same source, toolchain and flags must give byte-identical binaries:

```bash
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o bin/api ./cmd/api
sha256sum bin/api   # rebuild in a clean checkout and compare
```

- `-trimpath` removes your machine's paths from the binary.
- Pin the toolchain: the `go` and `toolchain` lines in `go.mod`, the same
  image or `setup-go` version in CI. Go's own toolchain is reproducible
  since 1.21.
- `CGO_ENABLED=0` unless you need cgo — a C toolchain is one more input
  that varies between machines.
- `go mod download` and `go mod verify` before building, so a tampered
  module cache fails the build.

## 3. Cross-Compilation

```bash
go tool dist list                                  # every GOOS/GOARCH pair
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -trimpath -o bin/api-linux-arm64 ./cmd/api
GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -o bin/api.exe ./cmd/api
```

Pure Go cross-compiles from any host. With cgo you need a C cross-compiler
per target; prefer pure-Go dependencies (e.g. a pure-Go SQLite driver)
when you ship to several platforms. Raise `GOAMD64` (v2/v3) only when every
target CPU supports it — the binary will not start on older ones.

## 4. Release Automation with GoReleaser

One config builds every target, archives, checksums, SBOMs and signs:

```yaml
# .goreleaser.yaml (excerpt — full file in references/goreleaser.md)
version: 2
builds:
  - main: ./cmd/api
    env: [CGO_ENABLED=0]
    flags: [-trimpath]
    ldflags: ["-s -w -X main.version={{.Version}} -X main.commit={{.Commit}}"]
    mod_timestamp: "{{ .CommitTimestamp }}" # reproducible file times
    goos: [linux, darwin, windows]
    goarch: [amd64, arm64]
checksum:
  name_template: checksums.txt
```

```bash
goreleaser check                         # validate the config
goreleaser release --snapshot --clean    # full dry run, nothing published
```

Release on tag push (`v1.4.0`) from CI, never from a laptop: the pipeline
is the only place whose inputs are recorded.

## 5. Supply-Chain Artifacts

| Artifact | Answers | Produced by |
|---|---|---|
| `checksums.txt` | Did my download arrive intact? | GoReleaser `checksum` |
| SBOM (SPDX or CycloneDX) | What is inside this binary? | `syft`, GoReleaser `sboms` |
| Signature bundle (`.sigstore.json`) | Did this project's pipeline publish it? | `cosign sign-blob --bundle`, keyless in CI |
| Provenance attestation | Which workflow, commit and runner built it? | `actions/attest` (SLSA provenance) |

Sign the checksums file rather than every archive — one signature then
covers them all. Keyless signing uses the CI job's OIDC identity, so there
is no private key to leak or rotate. Publish the exact verification
commands in the release notes; a signature nobody verifies protects
nobody. Commands: `references/supply-chain.md`.

## 6. Container Images

- **Pure-Go services: `ko`.** Builds from the Go source without a
  Dockerfile, on a distroless base, multi-arch, with an SBOM, reproducibly:
  `KO_DOCKER_REPO=ghcr.io/acme ko build --bare --platform=linux/amd64,linux/arm64 ./cmd/api`.
- **Otherwise a multi-stage Dockerfile:** build in `golang:<version>`,
  copy the binary into `gcr.io/distroless/static:nonroot`, run as non-root.
- Reference images by digest in deployments, and sign them with cosign.
- Image size is owned by the go-binary-size skill.

## 7. Versioning

- Tags are semver with a `v` prefix: `v1.4.0`. Never move or delete a
  published tag — the module proxy has cached it, and users' `go.sum`
  pins its hash.
- A breaking change to a library is a new major version with a `/v2`
  module path, not just a `v2.0.0` tag.
- A bad release is withdrawn with `retract` in `go.mod` (the
  go-dependency-audit skill), then fixed in a new patch release.
- Generate release notes from Conventional Commits (git-commit skill);
  GoReleaser's `changelog.groups` sorts them into features and fixes.

## Verification Checklist

1. `go version -m` on the release binary shows the tag and commit
2. Two clean builds of the same tag produce identical SHA-256 sums
3. `-trimpath`, `CGO_ENABLED=0` (or a justified cgo build), pinned toolchain
4. No build timestamps; file times derived from the commit
5. Releases come from a tag-triggered CI job, never a laptop
6. `checksums.txt` is signed; SBOMs are published; provenance is attested
7. Release notes include the `cosign verify-blob` / `gh attestation verify` commands
8. Images built with ko or multi-stage on distroless, non-root, referenced by digest
9. Published tags are never moved; bad releases are retracted

© eduardo-sl · MIT · eduardo-sl/go-agent-skills

Похожие скиллы

Все скиллы по теме «DevOps и инфраструктура» →
wizard Matt Pocock Скилл создаёт интерактивный bash-скрипт для ручных шагов: настройки сервисов, секретов CI и разовых миграций. 553 369установок hyperframes-cli heygen-com Управляет проектами HyperFrames через терминал: собирает таймлайн, проверяет контраст кадров, запускает предпросмотр и рендерит видео локально или в облаке. CX Codex +1 1 300 000установок setup-pre-commit Matt Pocock Скилл настраивает pre-commit для JavaScript-репозитория: Husky запускает форматирование, проверку типов и тесты перед коммитом. 489 289установок using-git-worktrees Jesse Vincent Готовит изолированное рабочее дерево перед доработкой или выполнением плана. Проверяет текущий репозиторий, выбирает нативные средства платформы либо Git. CX Codex 217 153установок finishing-a-development-branch Jesse Vincent Скилл проверяет тесты и помогает выбрать, как завершить работу в ветке: слить её, открыть Pull Request или оставить как есть. CX Codex 214 439установок orca-cli stablyai Скилл даёт агенту доступ к worktree, терминалам, артефактам и встроенному браузеру Orca через CLI. Пригодится, когда работа идёт в окружении Orca. CX Codex +1 354 000установок

Из того же набора34

go-semantic-tools Ищет вызовы, реализации и зависимости в Go-проектах через gopls и go list, а не текстовый поиск. Понимает интерфейсы, embedding и cross-package использование — то, что grep не видит. CX Codex +1 ★ 83звёзд репо go-refactoring Пошаговый регламент безопасного рефакторинга кода на Go без изменения поведения программы под контролем компилятора и тестов. CX Codex +1 ★ 83звёзд репо go-dependency-audit Скилл проверяет зависимости Go-модуля на уязвимости, устаревшие версии и проблемы в go.mod. Пригодится перед обновлением или ревью зависимостей. CX Codex +1 ★ 83звёзд репо go-ci Скилл помогает агенту писать и настраивать GitHub Actions для Go-проектов. Нужен, когда нужна пайплайн с линтингом, тестами, проверками безопасности и кешированием. CX Codex +1 ★ 83звёзд репо go-binary-size Скилл помогает найти, что увеличивает Go-бинарник или контейнерный образ, и проверить размер после изменений. Пригодится для уменьшения CLI перед распространением или аудита зависимостей. CX Codex +1 ★ 83звёзд репо git-commit Скилл учит агента писать коммиты по Conventional Commits: тип, область, императив в заголовке. Пригодится, когда история коммитов в проекте превратилась в кашу. CX Codex +1 ★ 83звёзд репо go-test-table-driven Скилл помогает писать и рефакторить табличные тесты в Go. Он следит за структурой тест-кейсов, именами подтестов и убирает лишние ветвления из цикла. CX Codex +1 ★ 83звёзд репо go-test-quality Скилл помогает писать и проверять тесты Go: от выбора подхода до изоляции сценариев и поиска пробелов в покрытии. Пригодится при доработке тестов и разборе нестабильных проверок. CX Codex +1 ★ 83звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой