Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@

name: CI

on:
push:
branches: [ master ]
branches: [master]
pull_request:
branches: [ master ]
branches: [master]

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
go: [ '1.25' ]
go: ["1.26"]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v7

- name: Setup Go
uses: actions/setup-go@v3
uses: actions/setup-go@v7
with:
go-version: ${{ matrix.go }}

Expand Down
201 changes: 194 additions & 7 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
version: "2"

run:
go: "1.25"
go: "1.26"
timeout: 5m
tests: false
tests: true
issues-exit-code: 1
modules-download-mode: readonly
allow-parallel-runners: true
Expand All @@ -12,7 +12,7 @@ issues:
max-issues-per-linter: 0
max-same-issues: 0
new: false
fix: false
fix: true

output:
formats:
Expand All @@ -27,6 +27,7 @@ formatters:
enable:
- gofmt
- goimports
- gofumpt

linters:
settings:
Expand All @@ -36,7 +37,6 @@ linters:
- -S1023
- -ST1000
- -ST1003
- -SA1019
- -ST1020
gosec:
excludes:
Expand All @@ -47,9 +47,160 @@ linters:
- G306
- G501
- G505
- G506
- G507
tagliatelle:
case:
rules:
json: snake # JSON: snake_case (user_id)
yaml: snake # YAML: snake_case
xml: camel # XML: camelCase
mapstructure: snake # mapstructure: snake_case
env: upperSnake # ENV: UPPER_SNAKE_CASE
varnamelen:
min-name-length: 2 # Минимальная длина имени
max-distance: 5 # i, j, k допустимы в scope <= 5 строк
ignore-names:
- err # err — идиоматично
- ok # ok — идиоматично
- id # id — часто используется
- db # db — часто используется
- tx # tx — транзакция
- wg # wg — WaitGroup
- mu # mu — mutex
- rw # rw — RWMutex
- ch # ch — channel
- fn # fn — function
- sb # sb — strings.Builder
- ctx # ctx — context
- q # q — querier
- r # r — repo / reader
- s # s — strategy / service
- f # f — filter
- a # a — left operand (сравнение)
- b # b — right operand (сравнение)
ignore-type-assert-ok: true # Игнорировать v, ok := x.(T)
ignore-map-index-ok: true # Игнорировать v, ok := m[k]
ignore-chan-recv-ok: true # Игнорировать v, ok := <-ch
ignore-decls:
- i int # for i := ...
- j int # вложенные циклы
- n int # количество
- t testing.T # тесты
- b testing.B # бенчмарки
- r *http.Request # HTTP handler
- w http.ResponseWriter # HTTP handler
- c *gin.Context # Gin context
- c echo.Context # Echo context
- s *Server # конструктор Server
- m *metrics # конструктор metrics
revive:
severity: warning
rules:
# -------------------------------------------------------------------------
# Предотвращение багов
# -------------------------------------------------------------------------
- name: atomic # Проверяет правильное использование sync/atomic
- name: range-val-in-closure # Захват переменной цикла в замыкании
- name: range-val-address # Взятие адреса переменной цикла
- name: unreachable-code # Недостижимый код после return/panic
- name: unchecked-type-assertion # Type assertion без проверки ok
- name: datarace # Потенциальные data races
- name: identical-branches # Одинаковые ветки if/else
- name: defer # Проблемы с defer (в циклах, результат)
- name: call-to-gc # Явные вызовы runtime.GC()
- name: waitgroup-by-value # WaitGroup передан по значению

# -------------------------------------------------------------------------
# Обработка ошибок — Go proverb: "Don't just check errors, handle them gracefully"
# -------------------------------------------------------------------------
- name: error-strings # Ошибки не должны начинаться с большой буквы
- name: error-return # error должен быть последним возвращаемым значением
- name: errorf # Использовать fmt.Errorf вместо errors.New + fmt.Sprintf
- name: unhandled-error # Необработанные ошибки
arguments:
- "fmt.Print"
- "fmt.Printf"
- "fmt.Println"

# -------------------------------------------------------------------------
# Сложность — Go proverb: "Clear is better than clever"
# -------------------------------------------------------------------------
- name: cognitive-complexity
arguments: [15] # Cognitive complexity <= 15
- name: cyclomatic
arguments: [10] # Cyclomatic complexity <= 10
- name: function-result-limit
arguments: [3] # Максимум 3 возвращаемых значения
- name: argument-limit
arguments: [5] # Максимум 5 аргументов функции

# -------------------------------------------------------------------------
# Чистота кода — Go proverb: "A little copying is better than a little dependency"
# -------------------------------------------------------------------------
- name: indent-error-flow # if err != nil { return } вместо else
- name: early-return # Ранний возврат вместо вложенности
- name: superfluous-else # Лишний else после return
- name: if-return # Упрощение if/return
- name: empty-block # Пустые блоки кода
- name: unnecessary-stmt # Ненужные операторы
- name: redundant-import-alias # import pkg "pkg" — лишний алиас
- name: confusing-results # Запутанные возвращаемые значения
- name: bool-literal-in-expr # if x == true → if x
- name: constant-logical-expr # Константные логические выражения
- name: modifies-parameter # Модификация параметров функции
- name: modifies-value-receiver # Модификация value receiver (бесполезно)
- name: redefines-builtin-id # Переопределение встроенных идентификаторов
- name: string-of-int # string(int) — частая ошибка
- name: time-equal # time.Time сравнение через ==
- name: unconditional-recursion # Безусловная рекурсия (бесконечный цикл)
- name: useless-break # break в конце case (Go делает это автоматически)

# -------------------------------------------------------------------------
# Хорошие практики — Go proverbs
# -------------------------------------------------------------------------
- name: context-as-argument # context.Context первым аргументом
- name: context-keys-type # Ключи контекста должны быть типизированы
- name: var-declaration # var x = 1 → x := 1
- name: blank-imports # Запрет blank imports кроме main/test
- name: dot-imports # Запрет dot imports
- name: unexported-return # Публичная функция возвращает приватный тип
- name: exported # Экспортируемые идентификаторы должны быть задокументированы
arguments:
- "checkPrivateReceivers"
- "disableStutteringCheck"

# -------------------------------------------------------------------------
# Именование — Go proverb: "Good naming is like good coding: concise"
# -------------------------------------------------------------------------
- name: var-naming
arguments:
- [
"ID",
"URL",
"API",
"HTTP",
"JSON",
"XML",
"DB",
"SQL",
"UUID",
"UID",
"GUID",
"TTL",
"TCP",
"UDP",
"IP",
"RPC",
"QPS",
"EOF",
]
- name: package-comments # Пакеты должны иметь комментарии
- name: receiver-naming # Имена receiver (r, s, c, не this/self)
exclusions:
rules:
- path: pki/internal/xocsp/ocsp.go
linters:
- revive
- nestif
paths:
- vendors/
default: none
Expand All @@ -60,7 +211,7 @@ linters:
- gocyclo
- ineffassign
- unparam
# - unused
- unused
- prealloc
- durationcheck
- staticcheck
Expand All @@ -69,3 +220,39 @@ linters:
- errorlint
- bodyclose
- gosec
- nilerr
- nilnesserr
- nilnil
- bidichk
- contextcheck
- fatcontext
- makezero
- forcetypeassert
- unconvert
- copyloopvar
- prealloc
- perfsprint
- gocritic
- goconst
- mnd
- revive
- predeclared
- reassign
- recvcheck
- asciicheck
- importas
- durationcheck
- tparallel
- thelper
- usetesting
- musttag
- errchkjson
- tagalign
- usestdlibvars
- nestif
- mirror
- whitespace
- decorder
- nonamedreturns
- inamedparam
- testpackage
26 changes: 26 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Agent instructions

## Project

- This repository is the Go module `go.osspkg.com/encrypt`; `go.mod` requires Go 1.26.
- Public packages are `aesgcm` (AES-GCM), `hash` (hash adapter), `pgp` (OpenPGP), and `pki` (X.509/OCSP).
- `pki/internal/xocsp` contains the internal OCSP ASN.1 implementation used by `pki`.
- Keep changes scoped to the package being changed. Public behavior and security-relevant limits should stay documented in Godoc and README where relevant.

## Commands

Run commands from the repository root.

- `go test ./...` runs all Go package tests.
- `make tests` runs the repository's `goppy test` target.
- `make lint` runs `goppy lint`. It can update files through configured formatting and fixes; inspect `git diff` afterward.
- `make build` runs `goppy build --arch=amd64`.
- `make ci` is the CI command from `.github/workflows/ci.yml`. It runs the `pre-commit` chain: install/setup, license, lint, tests, and build. The install step installs `goppy@latest`; the chain is not a read-only validation command.

## Changes and validation

- Keep `go.mod` and `go.sum` in sync when changing dependencies.
- Add or update tests for behavior changes and security fixes. Use `go test ./...` for full-suite validation; use package-scoped `go test` for focused changes.
- The linter configuration is in `.golangci.yml`; prefer fixing findings over adding suppressions. Explain any necessary suppression inline.
- Review the final worktree diff, especially after `make lint` or `make ci`, because these targets may modify files.
- Do not run publishing, deployment, or other external release operations as part of local validation.
Loading
Loading