Skip to content
Snippets Groups Projects
Commit b64716fd authored by Anton Sattarov's avatar Anton Sattarov
Browse files

Merge branch 'feature/2941-GoWrapGrpc' into feature/2941-GoWrapTemplateForGrpcTransport

# Conflicts:
#	perxis-proto
parents b2c487d0 93fdc42e
No related branches found
No related tags found
No related merge requests found
Showing
with 2492 additions and 121 deletions
.idea .idea
.task
*.bak
dist/ dist/
release/ release/
\ No newline at end of file
...@@ -18,12 +18,12 @@ run_tests: ...@@ -18,12 +18,12 @@ run_tests:
junit: report.xml junit: report.xml
lint: lint:
image: golangci/golangci-lint:v1.61-alpine image: golangci/golangci-lint:v1.62.2-alpine
rules: rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH)' - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH)'
stage: test stage: test
script: script:
- golangci-lint run --issues-exit-code 1 --print-issued-lines=false --new-from-rev $CI_MERGE_REQUEST_DIFF_BASE_SHA --out-format code-climate:gl-code-quality-report.json,line-number - golangci-lint run --config .golangci.yml --issues-exit-code 1 --print-issued-lines=false --new-from-rev $CI_MERGE_REQUEST_DIFF_BASE_SHA --out-format code-climate:gl-code-quality-report.json,line-number
artifacts: artifacts:
reports: reports:
codequality: gl-code-quality-report.json codequality: gl-code-quality-report.json
......
run:
# Timeout for analysis, e.g. 30s, 5m.
# Default: 1m
timeout: 15m
# This file contains only configs which differ from defaults.
# All possible options can be found here https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml
linters-settings:
cyclop:
# The maximal code complexity to report.
# Default: 10
max-complexity: 30
# The maximal average package complexity.
# If it's higher than 0.0 (float) the check is enabled
# Default: 0.0
package-average: 10.0
errcheck:
# Report about not checking of errors in type assertions: `a := b.(MyStruct)`.
# Such cases aren't reported by default.
# Default: false
check-type-assertions: true
exhaustive:
# Program elements to check for exhaustiveness.
# Default: [ switch ]
check:
- switch
- map
exhaustruct:
# List of regular expressions to exclude struct packages and their names from checks.
# Regular expressions must match complete canonical struct package/name/structname.
# Default: []
exclude:
# std libs
- "^net/http.Client$"
- "^net/http.Cookie$"
- "^net/http.Request$"
- "^net/http.Response$"
- "^net/http.Server$"
- "^net/http.Transport$"
- "^net/url.URL$"
- "^os/exec.Cmd$"
- "^reflect.StructField$"
# public libs
- "^github.com/Shopify/sarama.Config$"
- "^github.com/Shopify/sarama.ProducerMessage$"
- "^github.com/mitchellh/mapstructure.DecoderConfig$"
- "^github.com/prometheus/client_golang/.+Opts$"
- "^github.com/spf13/cobra.Command$"
- "^github.com/spf13/cobra.CompletionOptions$"
- "^github.com/stretchr/testify/mock.Mock$"
- "^github.com/testcontainers/testcontainers-go.+Request$"
- "^github.com/testcontainers/testcontainers-go.FromDockerfile$"
- "^golang.org/x/tools/go/analysis.Analyzer$"
- "^google.golang.org/protobuf/.+Options$"
- "^gopkg.in/yaml.v3.Node$"
funlen:
# Checks the number of lines in a function.
# If lower than 0, disable the check.
# Default: 60
lines: 100
# Checks the number of statements in a function.
# If lower than 0, disable the check.
# Default: 40
statements: 50
# Ignore comments when counting lines.
# Default false
ignore-comments: true
gochecksumtype:
# Presence of `default` case in switch statements satisfies exhaustiveness, if all members are not listed.
# Default: true
default-signifies-exhaustive: false
gocognit:
# Minimal code complexity to report.
# Default: 30 (but we recommend 10-20)
min-complexity: 20
gocritic:
# Settings passed to gocritic.
# The settings key is the name of a supported gocritic checker.
# The list of supported checkers can be find in https://go-critic.github.io/overview.
settings:
captLocal:
# Whether to restrict checker to params only.
# Default: true
paramsOnly: false
underef:
# Whether to skip (*x).method() calls where x is a pointer receiver.
# Default: true
skipRecvDeref: false
gomodguard:
blocked:
# List of blocked modules.
# Default: []
modules:
- github.com/golang/protobuf:
recommendations:
- google.golang.org/protobuf
reason: "see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules"
- github.com/satori/go.uuid:
recommendations:
- github.com/google/uuid
reason: "satori's package is not maintained"
- github.com/gofrs/uuid:
recommendations:
- github.com/gofrs/uuid/v5
reason: "gofrs' package was not go module before v5"
govet:
# Enable all analyzers.
# Default: false
enable-all: true
# Disable analyzers by name.
# Run `go tool vet help` to see all analyzers.
# Default: []
disable:
- fieldalignment # too strict
# Settings per analyzer.
settings:
shadow:
# Whether to be strict about shadowing; can be noisy.
# Default: false
strict: true
inamedparam:
# Skips check for interface methods with only a single parameter.
# Default: false
skip-single-param: true
mnd:
# List of function patterns to exclude from analysis.
# Values always ignored: `time.Date`,
# `strconv.FormatInt`, `strconv.FormatUint`, `strconv.FormatFloat`,
# `strconv.ParseInt`, `strconv.ParseUint`, `strconv.ParseFloat`.
# Default: []
ignored-functions:
- args.Error
- flag.Arg
- flag.Duration.*
- flag.Float.*
- flag.Int.*
- flag.Uint.*
- os.Chmod
- os.Mkdir.*
- os.OpenFile
- os.WriteFile
- prometheus.ExponentialBuckets.*
- prometheus.LinearBuckets
nakedret:
# Make an issue if func has more lines of code than this setting, and it has naked returns.
# Default: 30
max-func-lines: 0
nolintlint:
# Exclude following linters from requiring an explanation.
# Default: []
allow-no-explanation: [ funlen, gocognit, lll ]
# Enable to require an explanation of nonzero length after each nolint directive.
# Default: false
require-explanation: true
# Enable to require nolint directives to mention the specific linter being suppressed.
# Default: false
require-specific: true
perfsprint:
# Optimizes into strings concatenation.
# Default: true
strconcat: false
reassign:
# Patterns for global variable names that are checked for reassignment.
# See https://github.com/curioswitch/go-reassign#usage
# Default: ["EOF", "Err.*"]
patterns:
- ".*"
rowserrcheck:
# database/sql is always checked
# Default: []
packages:
- github.com/jmoiron/sqlx
sloglint:
# Enforce not using global loggers.
# Values:
# - "": disabled
# - "all": report all global loggers
# - "default": report only the default slog logger
# https://github.com/go-simpler/sloglint?tab=readme-ov-file#no-global
# Default: ""
no-global: "all"
# Enforce using methods that accept a context.
# Values:
# - "": disabled
# - "all": report all contextless calls
# - "scope": report only if a context exists in the scope of the outermost function
# https://github.com/go-simpler/sloglint?tab=readme-ov-file#context-only
# Default: ""
context: "scope"
tenv:
# The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures.
# Otherwise, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked.
# Default: false
all: true
linters:
disable-all: true
enable:
## enabled by default
- errcheck # checking for unchecked errors, these unchecked errors can be critical bugs in some cases
- gosimple # specializes in simplifying a code
- govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- ineffassign # detects when assignments to existing variables are not used
- staticcheck # is a go vet on steroids, applying a ton of static analysis checks
- typecheck # like the front-end of a Go compiler, parses and type-checks Go code
- unused # checks for unused constants, variables, functions and types
## disabled by default
- asasalint # checks for pass []any as any in variadic func(...any)
- asciicheck # checks that your code does not contain non-ASCII identifiers
- bidichk # checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- canonicalheader # checks whether net/http.Header uses canonical header
- copyloopvar # detects places where loop variables are copied (Go 1.22+)
- cyclop # checks function and package cyclomatic complexity
- dupl # tool for code clone detection
- durationcheck # checks for two durations multiplied together
- errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error
- errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13
- exhaustive # checks exhaustiveness of enum switch statements
- fatcontext # detects nested contexts in loops
- forbidigo # forbids identifiers
- funlen # tool for detection of long functions
- gocheckcompilerdirectives # validates go compiler directive comments (//go:)
- gochecknoglobals # checks that no global variables exist
- gochecknoinits # checks that no init functions are present in Go code
- gochecksumtype # checks exhaustiveness on Go "sum types"
- gocognit # computes and checks the cognitive complexity of functions
- goconst # finds repeated strings that could be replaced by a constant
- gocritic # provides diagnostics that check for bugs, performance and style issues
- gocyclo # computes and checks the cyclomatic complexity of functions
- godot # checks if comments end in a period
- goimports # in addition to fixing imports, goimports also formats your code in the same style as gofmt
- gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod
- gomodguard # allow and block lists linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations
- goprintffuncname # checks that printf-like functions are named with f at the end
- gosec # inspects source code for security problems
- iface # checks the incorrect use of interfaces, helping developers avoid interface pollution
- intrange # finds places where for loops could make use of an integer range
- lll # reports long lines
- loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap)
- makezero # finds slice declarations with non-zero initial length
- mirror # reports wrong mirror patterns of bytes/strings usage
- mnd # detects magic numbers
- musttag # enforces field tags in (un)marshaled structs
- nakedret # finds naked returns in functions greater than a specified function length
- nestif # reports deeply nested if statements
- nilerr # finds the code that returns nil even if it checks that the error is not nil
- nilnil # checks that there is no simultaneous return of nil error and an invalid value
- noctx # finds sending http request without context.Context
- nolintlint # reports ill-formed or insufficient nolint directives
- nonamedreturns # reports all named returns
- nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL
- perfsprint # checks that fmt.Sprintf can be replaced with a faster alternative
- predeclared # finds code that shadows one of Go's predeclared identifiers
- protogetter # reports direct reads from proto message fields when getters should be used
- reassign # checks that package variables are not reassigned
- recvcheck # checks for receiver type consistency
- revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint
- rowserrcheck # checks whether Err of rows is checked successfully
- sloglint # ensure consistent code style when using log/slog
- spancheck # checks for mistakes with OpenTelemetry/Census spans
- sqlclosecheck # checks that sql.Rows and sql.Stmt are closed
- stylecheck # is a replacement for golint
- tenv # detects using os.Setenv instead of t.Setenv since Go1.17
- testableexamples # checks if examples are testable (have an expected output)
- testifylint # checks usage of github.com/stretchr/testify
#- testpackage # makes you use a separate _test package
- unconvert # removes unnecessary type conversions
- unparam # reports unused function parameters
- usestdlibvars # detects the possibility to use variables/constants from the Go standard library
- wastedassign # finds wasted assignment statements
- whitespace # detects leading and trailing whitespace
## you may want to enable
#- decorder # checks declaration order and count of types, constants, variables and functions
#- exhaustruct # [highly recommend to enable] checks if all structure fields are initialized
#- gci # controls golang package import order and makes it always deterministic
#- ginkgolinter # [if you use ginkgo/gomega] enforces standards of using ginkgo and gomega
#- godox # detects FIXME, TODO and other comment keywords
#- goheader # checks is file header matches to pattern
#- inamedparam # [great idea, but too strict, need to ignore a lot of cases by default] reports interfaces with unnamed method parameters
#- interfacebloat # checks the number of methods inside an interface
#- ireturn # accept interfaces, return concrete types
#- prealloc # [premature optimization, but can be used in some cases] finds slice declarations that could potentially be preallocated
#- tagalign # checks that struct tags are well aligned
#- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope
#- wrapcheck # checks that errors returned from external packages are wrapped
#- zerologlint # detects the wrong usage of zerolog that a user forgets to dispatch zerolog.Event
## disabled
#- containedctx # detects struct contained context.Context field
#- contextcheck # [too many false positives] checks the function whether use a non-inherited context
#- depguard # [replaced by gomodguard] checks if package imports are in a list of acceptable packages
#- dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
#- dupword # [useless without config] checks for duplicate words in the source code
#- err113 # [too strict] checks the errors handling expressions
#- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted
#- exportloopref # [not necessary from Go 1.22] checks for pointers to enclosing loop variables
#- forcetypeassert # [replaced by errcheck] finds forced type assertions
#- gofmt # [replaced by goimports] checks whether code was gofmt-ed
#- gofumpt # [replaced by goimports, gofumports is not available yet] checks whether code was gofumpt-ed
#- gosmopolitan # reports certain i18n/l10n anti-patterns in your Go codebase
#- grouper # analyzes expression groups
#- importas # enforces consistent import aliases
#- maintidx # measures the maintainability index of each function
#- misspell # [useless] finds commonly misspelled English words in comments
#- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity
#- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test
#- tagliatelle # checks the struct tags
#- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers
#- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines
issues:
# Maximum count of issues with the same text.
# Set to 0 to disable.
# Default: 3
max-same-issues: 50
exclude-rules:
- source: "(noinspection|TODO)"
linters: [ godot ]
- source: "//noinspection"
linters: [ gocritic ]
- path: "_test\\.go"
linters:
- bodyclose
- dupl
- errcheck
- funlen
- goconst
- gosec
- noctx
- wrapcheck
- mnd
- path: "_middleware\\.go"
linters:
- nonamedreturns
- revive
- stylecheck
- path: "test/.*\\.go"
linters:
- mnd
- text: "shadow: declaration of \"(err|ctx)\" shadows declaration at"
linters:
- govet
\ No newline at end of file
# Changelog # Changelog
All notable changes to this project will be documented in this file. ## [0.32.0] - 2025-02-28
### 🚀 Новые возможности
- **invitations**: Обновлен API Invitations с поддержкой многоразовых приглашений [#2929](https://git.perx.ru/perxis/perxis/-/issues/2929) ([b80739c](https://git.perx.ru/perxis/perxis-go/-/commit/b80739ccdb1c4d0402a6b47e41e84fc20fac04d2))
- **core**: Добавлен метод для получения объекта из архива GetArchived [#2922](https://git.perx.ru/perxis/perxis/-/issues/2922) ([ed1f360](https://git.perx.ru/perxis/perxis-go/-/commit/ed1f360fff5453263d42d36427e77f8b115aee76))
- **schema**: Добавлена возможность использования в схеме типов соответствующих данным массива, строки и числа [#2890](https://git.perx.ru/perxis/perxis/-/issues/2890) ([c55180e](https://git.perx.ru/perxis/perxis-go/-/commit/c55180ef69df6577e96b6322963d48618c869592))
### ⚙️ Прочие задачи
- Добавлена спецификация JSON Schema для схемы коллекций ([7cf1e93](https://git.perx.ru/perxis/perxis-go/-/commit/7cf1e93096763f6e204492171fa26ab15c3616a2))
<!-- generated by git-cliff -->
## [0.31.1] - 2024-12-28
### 🐛 Исправлены ошибки
- **files**: Исправлена ошибка при которой временные файлы не перемещались в постоянное хранилище ([87b6304](https://git.perx.ru/perxis/perxis-go/-/commit/87b6304193c2cfb6c53189aaf497bef0215254ca))
<!-- generated by git-cliff -->
## [0.31.0] - 2024-12-19
### 🚀 Новые возможности
- Обновлен сервис Logs после изменений в прото-спецификации сервиса ([a86999a](https://git.perx.ru/perxis/perxis-go/-/commit/a86999a62c4963837032c6cbf86fb6ef7b486b8b))
- Добавлен возврат общего количества ревизий для метода ListRevisions [#2885](https://git.perx.ru/perxis/perxis/-/issues/2885) ([5671511](https://git.perx.ru/perxis/perxis-go/-/commit/56715111dda38d3d5e62beeebe649d64cf602a4c))
- **items**: Добавлен метод Items.CheckoutRevision [#2846](https://git.perx.ru/perxis/perxis/-/issues/2846) ([36ffcd0](https://git.perx.ru/perxis/perxis-go/-/commit/36ffcd03014b8b7da3abdc42a4450e2093d5102d))
- **extensions**: Добавлены поля для передачи клиентских данных при запросах ActionRequest ([e09530b](https://git.perx.ru/perxis/perxis-go/-/commit/e09530b49f4a52155b966c68adbf76d62799f6bd))
### ⚙️ Прочие задачи
- Добавлен фильтр по тегам (tag) в Collections.List ([8d47f17](https://git.perx.ru/perxis/perxis-go/-/commit/8d47f1781c029151163e868e9d9abca531ebce49))
- Пакет template вынесен в корень проекта ([9093516](https://git.perx.ru/perxis/perxis-go/-/commit/90935168e52dc76a61c78dc40a2c17a953f3d554))
- Перегенерированы клиенты, моки, middleware [#2862](https://git.perx.ru/perxis/perxis/-/issues/2862) ([0e67767](https://git.perx.ru/perxis/perxis-go/-/commit/0e67767d112c1f34990c02c64b51c74fbfbbc59c))
- Добавлена конфигурация для golangci-lint с добавлением дополнительных линтеров [#2953](https://git.perx.ru/perxis/perxis/-/issues/2953) ([c0721ec](https://git.perx.ru/perxis/perxis-go/-/commit/c0721ec476fa0043191bb29f827a8e5ac13c5b13))
- Обновление Taskfile [#2849](https://git.perx.ru/perxis/perxis/-/issues/2849) ([7ecb191](https://git.perx.ru/perxis/perxis-go/-/commit/7ecb191b8f8716c82ffce6be60b81b688b6d7291))
<!-- generated by git-cliff -->
## [0.30.0] - 2024-10-22 ## [0.30.0] - 2024-10-22
......
...@@ -2,67 +2,212 @@ version: '3' ...@@ -2,67 +2,212 @@ version: '3'
vars: vars:
PROTODIR: perxis-proto/proto PROTODIR: perxis-proto/proto
PBDIR: pb PBDIR: proto
DATE:
sh: date -Idate
tasks:
tools:brew:
desc: Установка инструментов через brew
cmds:
- brew tap caarlos0/tap
- brew install caarlos0/tap/svu
- brew install git-cliff
- brew install goreleaser
- brew install mockery
- brew install protoc-gen-go
- brew install protoc-gen-go-grpc
# Тесты
test:unit:
aliases: [tu]
desc: Запускает только юнит-тесты
cmds:
- go test ./...
test:unit:short:
aliases: [tus]
desc: Запускает только быстрые юнит-тесты
cmds:
- go test -short ./...
test:integration:
desc: Запускает только интеграционные тесты
cmds:
- go test -tags integration ./...
test:integration:short:
desc: Запускает только быстрые интеграционные тесты
cmds:
- go test -tags integration -short ./...
test:all:
desc: Запускает все тесты (юнит и интеграционные)
cmds:
- go test -tags all ./...
test:all:short:
desc: Запускает все быстрые тесты (юнит и интеграционные)
cmds:
- go test -tags all -short ./...
# Release
release:changelog:
aliases: [cl]
desc: "Подготовка CHANGELOG.md"
vars:
CURRENT_VERSION: CURRENT_VERSION:
sh: svu current sh: svu current
RELEASE_VERSION: RELEASE_VERSION:
sh: svu next sh: svu next
cmds:
- mkdir -p release
- git cliff {{ .CURRENT_VERSION }}.. --tag {{ .RELEASE_VERSION }} > release/CHANGELOG.md
tasks: release:prepare:
changelog: desc: "Подготовка к релизу"
cmds: cmds:
- git-cliff > CHANGELOG.md --tag {{ .RELEASE_VERSION }} - task: release:changelog
- go mod tidy
# - sed -i '' 's/ServerVersion.*=.*/ServerVersion = "{{ .RELEASE_VERSION }}"/' internal/version/version.go
# - sed -i '' 's/APIVersion.*=.*/APIVersion = "{{ .PERXIS_GO_VERSION }}"/' internal/version/version.go
# release release:finalize:
# - Сделать changelog desc: "Формирует все необходимые файлы к релизу"
# - Закоммитить все изменения vars:
# - Пометить тэгом версию CURRENT_VERSION:
# пререлиз - `git tag "$(svu pr --pre-release alpha.1 --build 9)"` sh: svu current
# пререлиз - `git tag "$(svu next)"` RELEASE_VERSION:
# - Запушить код и тэги на сервер (иначе будет непонятная ошибка goreleaser Not found) sh: svu next
release: MAJOR_VERSION:
sh: VERSION="{{ .RELEASE_VERSION }}"; echo "${VERSION%.*}"
cmds:
- cp CHANGELOG.md CHANGELOG.md.bak
- sed -i '' '/^# Changelog/d' CHANGELOG.md
- cat release/CHANGELOG.md CHANGELOG.md > CHANGELOG.md.tmp
- mv CHANGELOG.md.tmp CHANGELOG.md
release:version:
aliases: [v, ver]
desc: Текущие версии релизов
silent: true
vars:
CURRENT_VERSION:
sh: svu current
RELEASE_VERSION:
sh: svu next
cmds:
- echo 'Current version {{.CURRENT_VERSION}}'
- echo 'Release version {{.RELEASE_VERSION}}'
release:build:
desc: Сборка Release
summary: |
1. Сделать подготовку:
- task release:prepare
2. Закоммитить все изменения
3. Пометить тэгом версию
- пререлиз - `git tag "$(svu pr --pre-release alpha.1 --build 9)"`
- релиз - `git tag "$(svu next)"`
4. Запушить код и тэги на сервер (иначе будет непонятная ошибка goreleaser Not found)
vars:
CURRENT_VERSION:
sh: svu current
RELEASE_VERSION:
sh: svu next
cmds: cmds:
- mkdir -p release
- git-cliff {{ .CURRENT_VERSION }}.. --tag {{ .RELEASE_VERSION }} > release/CHANGELOG.md
- goreleaser release --clean --release-notes=release/CHANGELOG.md - goreleaser release --clean --release-notes=release/CHANGELOG.md
mocks: gen:proto:
deps: desc: "Компилиция .proto файлов в каталоге {{ .PROTODIR }} в код Go"
- mocks.proto
mocks.proto:
sources: sources:
- proto/**/*.proto - "{{ .PROTODIR }}/**/*.proto"
generates: - exclude: "{{ .PROTODIR }}/status/status.proto"
- proto/mocks/*.go
cmds: cmds:
- mockery --all --dir proto --output proto/mocks - for: sources
task: gen:proto:file
vars:
FILE: "{{ .ITEM }}"
silent: true
gen:proto:file:
desc: "Преобразует переданный .proto файл в код на языке Go для работы с сообщениями protobuf и сервисами gRPC."
cmds:
- protoc -I={{ .PROTODIR }} --experimental_allow_proto3_optional --go_out={{ .PBDIR }} --go-grpc_out={{ .PBDIR }} --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative {{ .FILE }}
gen:middleware:
desc: "Генерирует middleware для всех пакетов"
summary: |
Команда перегенерирует middleware для всех пакетов.
Для конфигурации доступны следующие переменные:
* DIR - путь до пакета, содержащего уже сгенерированные middleware
* MIDDLEWARE_NAME - имя middleware, которое нужно перегенерировать, без указания расширения
Примеры использования:
Перегенерация всех middleware только для пакета items:
task regen:middleware DIR=pkg/items
proto: Перегенерация всех recovery middleware для всех пакетов:
task regen:middleware MIDDLEWARE_NAME=recovering_middleware
Перегенерация middleware телеметрии для пакета collections:
task gen:middleware DIR=pkg/collections MIDDLEWARE_NAME=recovering_middleware
vars:
DIR: '{{ default "**" .DIR }}'
MIDDLEWARE_NAME: '{{ default "*" .MIDDLEWARE_NAME }}'
sources: sources:
- '{{ .PROTODIR }}/**/*.proto' - "{{ .DIR }}/middleware/{{ .MIDDLEWARE_NAME }}.go"
# generates:
# - '{{ .PBDIR }}/*.go'
ignore_error: true # Игнорировать ошибки, из-за status/status.proto
# silent: true
cmds: cmds:
- for: sources - for: sources
cmd: echo {{ .ITEM }} cmd: go generate {{ .ITEM }}
# cmd: '[ "{{.FILE}}" != "perxis-proto/proto/status/status.proto" ]'
# - protoc --proto_path={{ .PROTODIR }} --experimental_allow_proto3_optional --go_out={{ .PBDIR }} --go-grpc_out={{ .PBDIR }} --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative {{ .FILE }}
gen:mocks:
desc: "Генерирует моки"
cmds:
- task: gen:mocks:proto
- task: gen:mocks:services
# cmd: protoc --proto_path={{ .PROTODIR }} --experimental_allow_proto3_optional --go_out={{ .PBDIR }} --go-grpc_out={{ .PBDIR }} --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative {{ .ITEM }} gen:mocks:proto:
# task: proto_file desc: "Команда генерирует моки для всех proto-файлов"
# vars: sources:
# FILE: '{{ .ITEM }}' - "{{.PBDIR}}/**/*.pb.go"
# ignore_error: true cmds:
- mockery --all --dir {{.PBDIR}} --output {{.PBDIR}}/mocks
proto_file: gen:mocks:services:
desc: "Генерирует моки для всех интерфейсов в директориях, где находится файл service.go."
sources: sources:
- '{{ .FILE }}' - "**/service.go"
- exclude: "**/mocks/**"
cmds: cmds:
- '[ "{{.FILE}}" != "perxis-proto/proto/status/status.proto" ]' # Игнорировать ошибки, из-за status/status.proto - for: sources
- protoc --proto_path={{ .PROTODIR }} --experimental_allow_proto3_optional --go_out={{ .PBDIR }} --go-grpc_out={{ .PBDIR }} --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative {{ .FILE }} task: gen:mock:dir
silent: true vars:
\ No newline at end of file DIR: "{{ dir .ITEM }}"
gen:mock:dir:
internal: true
desc: "Вспомогательная команда для генерации моков"
cmds:
- mockery --log-level="error" --all --exported --dir "{{ .DIR }}" --output="{{ .DIR }}/mocks"
gen:microgen:all:
desc: "Генерирует go-kit для всех файлов service.go. Поддерживается для версии microgen < 1.0.0"
sources:
- "**/service.go"
deps:
- for: sources
task: gen:microgen:file
vars:
FILE: "{{ .ITEM }}"
gen:microgen:file:
desc: "Вспомогательная команда для генерации go-kit для переданного файла. Выходные файлы сохраняются в директории с входным файлом."
cmds:
- microgen -file {{ .FILE }} -out {{ dir .FILE }}
This diff is collapsed.
...@@ -14,7 +14,7 @@ func WithLog(s {{.Interface.Type}}, logger *zap.Logger, log_access bool) {{.Inte ...@@ -14,7 +14,7 @@ func WithLog(s {{.Interface.Type}}, logger *zap.Logger, log_access bool) {{.Inte
if log_access { if log_access {
s = AccessLoggingMiddleware(logger)(s) s = AccessLoggingMiddleware(logger)(s)
} }
{{- if (has $serviceName (list "Items" "Collections") ) }} {{- if (has $serviceName (list "Items" "Collections" "Spaces" "Roles") ) }}
s = LoggingMiddleware(logger)(s) s = LoggingMiddleware(logger)(s)
{{ else }} {{ else }}
s = ErrorLoggingMiddleware(logger)(s) s = ErrorLoggingMiddleware(logger)(s)
......
...@@ -12,7 +12,6 @@ breaking_always_bump_major = true ...@@ -12,7 +12,6 @@ breaking_always_bump_major = true
# changelog header # changelog header
header = """ header = """
# Changelog\n # Changelog\n
All notable changes to this project will be documented in this file.\n
""" """
# template for the changelog body # template for the changelog body
# https://keats.github.io/tera/docs/#introduction # https://keats.github.io/tera/docs/#introduction
...@@ -25,16 +24,16 @@ body = """ ...@@ -25,16 +24,16 @@ body = """
{% for group, commits in commits | group_by(attribute="group") %} {% for group, commits in commits | group_by(attribute="group") %}
### {{ group | striptags | trim | upper_first }} ### {{ group | striptags | trim | upper_first }}
{% for commit in commits %} {% for commit in commits %}
- {% if commit.scope %}*({{ commit.scope }})* {% endif %}\ - {% if commit.scope %}**{{ commit.scope }}**: {% endif %}\
{% if commit.breaking %}[**breaking**] {% endif %}\ {% if commit.breaking %}[**breaking**] {% endif %}\
{{ commit.message | upper_first }} \ {{ commit.message | upper_first }} \
{% if commit.links %}\ {% if commit.links %}\
({% for link in commit.links %}\ {% for link in commit.links %}\
[{{ link.text }}]({{ link.href }}) \ [{{ link.text }}]({{ link.href }}) \
{% if not loop.last %}, {% endif %}\ {% if not loop.last %}, {% endif %}\
{% endfor %})\ {% endfor %}\
{% endif %}\ {% endif %}\
-([{{ commit.id | truncate(length=7, end="") }}]($REPO/-/commit/{{ commit.id }}))\ ([{{ commit.id | truncate(length=7, end="") }}]($REPO/-/commit/{{ commit.id }}))\
{% endfor %} {% endfor %}
{% endfor %}\n {% endfor %}\n
""" """
...@@ -69,20 +68,20 @@ commit_preprocessors = [ ...@@ -69,20 +68,20 @@ commit_preprocessors = [
] ]
# regex for parsing and grouping commits # regex for parsing and grouping commits
commit_parsers = [ commit_parsers = [
{ message = "^feat", group = "<!-- 0 -->🚀 Features" }, { message = "^feat", group = "<!-- 0 -->🚀 Новые возможности" },
{ message = "^fix", group = "<!-- 1 -->🐛 Bug Fixes" }, { message = "^fix", group = "<!-- 1 -->🐛 Исправлены ошибки" },
{ message = "^doc", group = "<!-- 3 -->📚 Documentation" }, { message = "^doc", group = "<!-- 3 -->📚 Документация" },
{ message = "^perf", group = "<!-- 4 -->⚡ Performance" }, { message = "^perf", group = "<!-- 4 -->⚡ Производительность" },
{ message = "^refactor", group = "<!-- 2 -->🚜 Refactor", skip = true }, { message = "^refactor", group = "<!-- 2 -->🚜 Рефакторинг", skip = true },
{ message = "^style", group = "<!-- 5 -->🎨 Styling" }, { message = "^style", group = "<!-- 5 -->🎨 Styling" },
{ message = "^test", group = "<!-- 6 -->🧪 Testing" }, { message = "^test", group = "<!-- 6 -->🧪 Тесты" },
{ message = "^chore\\(release\\): prepare for", skip = true }, { message = "^chore\\(release\\): prepare for", skip = true },
{ message = "^chore\\(deps.*\\)", skip = true }, { message = "^chore\\(deps.*\\)", skip = true },
{ message = "^chore\\(pr\\)", skip = true }, { message = "^chore\\(pr\\)", skip = true },
{ message = "^chore\\(pull\\)", skip = true }, { message = "^chore\\(pull\\)", skip = true },
{ message = "^chore|^ci", group = "<!-- 7 -->⚙️ Miscellaneous Tasks" }, { message = "^chore|^ci", group = "<!-- 7 -->⚙️ Прочие задачи" },
{ body = ".*security", group = "<!-- 8 -->🛡️ Security" }, { body = ".*security", group = "<!-- 8 -->🛡️ Безопастность" },
{ message = "^revert", group = "<!-- 9 -->◀️ Revert" }, { message = "^revert", group = "<!-- 9 -->◀️ Отменены изменения" },
{ message = "^irefac", skip = true }, { message = "^irefac", skip = true },
] ]
# protect breaking changes from being skipped due to matching a skipping commit_parser # protect breaking changes from being skipped due to matching a skipping commit_parser
...@@ -102,6 +101,12 @@ sort_commits = "oldest" ...@@ -102,6 +101,12 @@ sort_commits = "oldest"
# limit the number of commits included in the changelog. # limit the number of commits included in the changelog.
# limit_commits = 42 # limit_commits = 42
link_parsers = [ link_parsers = [
{ pattern = "#(\\d+)", href = "https://git.perx.ru/perxis/perxis/-/issues/$1"},
{ pattern = "#(PRXS-(\\d+))", href = "https://tracker.yandex.ru/$1"}, { pattern = "#(PRXS-(\\d+))", href = "https://tracker.yandex.ru/$1"},
{ pattern = "RFC(\\d+)", text = "ietf-rfc$1", href = "https://datatracker.ietf.org/doc/html/rfc$1"}, { pattern = "RFC(\\d+)", text = "ietf-rfc$1", href = "https://datatracker.ietf.org/doc/html/rfc$1"},
] ]
[remote.gitlab]
owner = "perxis"
repo = "perxis-go"
api_url = "https://git.perx.ru/api/v4/"
\ No newline at end of file
// Code generated by mockery v2.50.0. DO NOT EDIT.
package mocks
import (
id "git.perx.ru/perxis/perxis-go/id"
mock "github.com/stretchr/testify/mock"
)
// Descriptor is an autogenerated mock type for the Descriptor type
type Descriptor struct {
mock.Mock
}
// FromMap provides a mock function with given fields: _a0
func (_m *Descriptor) FromMap(_a0 map[string]interface{}) error {
ret := _m.Called(_a0)
if len(ret) == 0 {
panic("no return value specified for FromMap")
}
var r0 error
if rf, ok := ret.Get(0).(func(map[string]interface{}) error); ok {
r0 = rf(_a0)
} else {
r0 = ret.Error(0)
}
return r0
}
// FromParts provides a mock function with given fields: _a0
func (_m *Descriptor) FromParts(_a0 []string) error {
ret := _m.Called(_a0)
if len(ret) == 0 {
panic("no return value specified for FromParts")
}
var r0 error
if rf, ok := ret.Get(0).(func([]string) error); ok {
r0 = rf(_a0)
} else {
r0 = ret.Error(0)
}
return r0
}
// Map provides a mock function with no fields
func (_m *Descriptor) Map() map[string]interface{} {
ret := _m.Called()
if len(ret) == 0 {
panic("no return value specified for Map")
}
var r0 map[string]interface{}
if rf, ok := ret.Get(0).(func() map[string]interface{}); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(map[string]interface{})
}
}
return r0
}
// New provides a mock function with no fields
func (_m *Descriptor) New() id.Descriptor {
ret := _m.Called()
if len(ret) == 0 {
panic("no return value specified for New")
}
var r0 id.Descriptor
if rf, ok := ret.Get(0).(func() id.Descriptor); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(id.Descriptor)
}
}
return r0
}
// String provides a mock function with no fields
func (_m *Descriptor) String() string {
ret := _m.Called()
if len(ret) == 0 {
panic("no return value specified for String")
}
var r0 string
if rf, ok := ret.Get(0).(func() string); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(string)
}
return r0
}
// Type provides a mock function with no fields
func (_m *Descriptor) Type() string {
ret := _m.Called()
if len(ret) == 0 {
panic("no return value specified for Type")
}
var r0 string
if rf, ok := ret.Get(0).(func() string); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(string)
}
return r0
}
// Validate provides a mock function with no fields
func (_m *Descriptor) Validate() error {
ret := _m.Called()
if len(ret) == 0 {
panic("no return value specified for Validate")
}
var r0 error
if rf, ok := ret.Get(0).(func() error); ok {
r0 = rf()
} else {
r0 = ret.Error(0)
}
return r0
}
// NewDescriptor creates a new instance of Descriptor. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewDescriptor(t interface {
mock.TestingT
Cleanup(func())
}) *Descriptor {
mock := &Descriptor{}
mock.Mock.Test(t)
t.Cleanup(func() { mock.AssertExpectations(t) })
return mock
}
// Code generated by mockery v2.50.0. DO NOT EDIT.
package mocks
import (
id "git.perx.ru/perxis/perxis-go/id"
mock "github.com/stretchr/testify/mock"
)
// ObjectHandler is an autogenerated mock type for the ObjectHandler type
type ObjectHandler struct {
mock.Mock
}
// Execute provides a mock function with given fields: _a0
func (_m *ObjectHandler) Execute(_a0 interface{}) *id.ObjectId {
ret := _m.Called(_a0)
if len(ret) == 0 {
panic("no return value specified for Execute")
}
var r0 *id.ObjectId
if rf, ok := ret.Get(0).(func(interface{}) *id.ObjectId); ok {
r0 = rf(_a0)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*id.ObjectId)
}
}
return r0
}
// NewObjectHandler creates a new instance of ObjectHandler. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewObjectHandler(t interface {
mock.TestingT
Cleanup(func())
}) *ObjectHandler {
mock := &ObjectHandler{}
mock.Mock.Test(t)
t.Cleanup(func() { mock.AssertExpectations(t) })
return mock
}
// Code generated by mockery v2.50.0. DO NOT EDIT.
package mocks
import (
id "git.perx.ru/perxis/perxis-go/id"
mock "github.com/stretchr/testify/mock"
)
// ObjectIdentifier is an autogenerated mock type for the ObjectIdentifier type
type ObjectIdentifier struct {
mock.Mock
}
// ObjectId provides a mock function with no fields
func (_m *ObjectIdentifier) ObjectId() *id.ObjectId {
ret := _m.Called()
if len(ret) == 0 {
panic("no return value specified for ObjectId")
}
var r0 *id.ObjectId
if rf, ok := ret.Get(0).(func() *id.ObjectId); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*id.ObjectId)
}
}
return r0
}
// NewObjectIdentifier creates a new instance of ObjectIdentifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewObjectIdentifier(t interface {
mock.TestingT
Cleanup(func())
}) *ObjectIdentifier {
mock := &ObjectIdentifier{}
mock.Mock.Test(t)
t.Cleanup(func() { mock.AssertExpectations(t) })
return mock
}
// Code generated by mockery v2.50.0. DO NOT EDIT.
package mocks
import (
image "image"
io "io"
mock "github.com/stretchr/testify/mock"
)
// EncodeFunc is an autogenerated mock type for the EncodeFunc type
type EncodeFunc struct {
mock.Mock
}
// Execute provides a mock function with given fields: w, img
func (_m *EncodeFunc) Execute(w io.Writer, img image.Image) error {
ret := _m.Called(w, img)
if len(ret) == 0 {
panic("no return value specified for Execute")
}
var r0 error
if rf, ok := ret.Get(0).(func(io.Writer, image.Image) error); ok {
r0 = rf(w, img)
} else {
r0 = ret.Error(0)
}
return r0
}
// NewEncodeFunc creates a new instance of EncodeFunc. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewEncodeFunc(t interface {
mock.TestingT
Cleanup(func())
}) *EncodeFunc {
mock := &EncodeFunc{}
mock.Mock.Test(t)
t.Cleanup(func() { mock.AssertExpectations(t) })
return mock
}
// Code generated by mockery v2.46.3. DO NOT EDIT. // Code generated by mockery v2.50.0. DO NOT EDIT.
package mocks package mocks
import mock "github.com/stretchr/testify/mock" import mock "github.com/stretchr/testify/mock"
// spaceGetter is an autogenerated mock type for the spaceGetter type // SpaceGetter is an autogenerated mock type for the spaceGetter type
type spaceGetter struct { type SpaceGetter struct {
mock.Mock mock.Mock
} }
// GetSpaceID provides a mock function with given fields: // GetSpaceID provides a mock function with no fields
func (_m *spaceGetter) GetSpaceID() string { func (_m *SpaceGetter) GetSpaceID() string {
ret := _m.Called() ret := _m.Called()
if len(ret) == 0 { if len(ret) == 0 {
...@@ -27,13 +27,13 @@ func (_m *spaceGetter) GetSpaceID() string { ...@@ -27,13 +27,13 @@ func (_m *spaceGetter) GetSpaceID() string {
return r0 return r0
} }
// newSpaceGetter creates a new instance of spaceGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // NewSpaceGetter creates a new instance of SpaceGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value. // The first argument is typically a *testing.T value.
func newSpaceGetter(t interface { func NewSpaceGetter(t interface {
mock.TestingT mock.TestingT
Cleanup(func()) Cleanup(func())
}) *spaceGetter { }) *SpaceGetter {
mock := &spaceGetter{} mock := &SpaceGetter{}
mock.Mock.Test(t) mock.Mock.Test(t)
t.Cleanup(func() { mock.AssertExpectations(t) }) t.Cleanup(func() { mock.AssertExpectations(t) })
......
...@@ -38,7 +38,6 @@ type Entry struct { ...@@ -38,7 +38,6 @@ type Entry struct {
CallerID *id.ObjectId `json:"caller_id,omitempty" bson:"caller_id,omitempty" mapstructure:"caller_id,omitempty"` CallerID *id.ObjectId `json:"caller_id,omitempty" bson:"caller_id,omitempty" mapstructure:"caller_id,omitempty"`
Attr interface{} `json:"attr,omitempty" bson:"attr,omitempty" mapstructure:"attr,omitempty"` Attr interface{} `json:"attr,omitempty" bson:"attr,omitempty" mapstructure:"attr,omitempty"`
Tags []string `json:"tags,omitempty" bson:"tags,omitempty" mapstructure:"tags,omitempty"` Tags []string `json:"tags,omitempty" bson:"tags,omitempty" mapstructure:"tags,omitempty"`
SearchScore float64 `json:"searchScore,omitempty" bson:"search_score,omitempty"`
} }
//func convertInterfaceToAny(v interface{}) (*any.Any, error) { //func convertInterfaceToAny(v interface{}) (*any.Any, error) {
...@@ -55,14 +54,13 @@ func EntryToPB(entry *Entry) *pb.LogEntry { ...@@ -55,14 +54,13 @@ func EntryToPB(entry *Entry) *pb.LogEntry {
logEntry := &pb.LogEntry{ logEntry := &pb.LogEntry{
Id: entry.ID, Id: entry.ID,
Timestamp: timestamppb.New(entry.Timestamp), Timestamp: timestamppb.New(entry.Timestamp),
Level: pb.LogLevel(entry.Level), Level: pb.LogLevel(entry.Level), //nolint:gosec //overflow doesn't expected
Message: entry.Message, Message: entry.Message,
Category: entry.Category, Category: entry.Category,
Component: entry.Component, Component: entry.Component,
Event: entry.Event, Event: entry.Event,
Attr: nil, // implement Attr: nil, // implement
Tags: entry.Tags, Tags: entry.Tags,
SearchScore: entry.SearchScore,
} }
if entry.ObjectID != nil { if entry.ObjectID != nil {
logEntry.ObjectId = entry.ObjectID.String() logEntry.ObjectId = entry.ObjectID.String()
...@@ -76,14 +74,13 @@ func EntryToPB(entry *Entry) *pb.LogEntry { ...@@ -76,14 +74,13 @@ func EntryToPB(entry *Entry) *pb.LogEntry {
func EntryFromPB(request *pb.LogEntry) *Entry { func EntryFromPB(request *pb.LogEntry) *Entry {
logEntry := &Entry{ logEntry := &Entry{
ID: request.Id, ID: request.GetId(),
Timestamp: request.Timestamp.AsTime(), Timestamp: request.GetTimestamp().AsTime(),
Level: Level(request.Level), Level: Level(request.GetLevel()),
Message: request.Message, Message: request.GetMessage(),
Category: request.Category, Category: request.GetCategory(),
Component: request.Component, Component: request.GetComponent(),
Event: request.Event, Event: request.GetEvent(),
SearchScore: request.SearchScore,
} }
if request.ObjectId != "" { if request.ObjectId != "" {
......
...@@ -88,23 +88,21 @@ func TestFindRequest(t *testing.T) { ...@@ -88,23 +88,21 @@ func TestFindRequest(t *testing.T) {
func TestFindResult(t *testing.T) { func TestFindResult(t *testing.T) {
t.Run("From PB", func(t *testing.T) { t.Run("From PB", func(t *testing.T) {
res := FindResultFromPB(&pb.FindResult{ res := FindResultFromPB(&pb.FindResult{
Options: &pb.FindOptions{Limit: 2, Sort: []string{"timestamp"}, Fields: []string{"level"}}, Options: &pb.FindOptions{Limit: 2, Sort: []string{"timestamp"}},
}) })
assert.True(t, res.Options.After.IsZero()) assert.True(t, res.Options.After.IsZero())
assert.True(t, res.Options.Before.IsZero()) assert.True(t, res.Options.Before.IsZero())
assert.Equal(t, 2, res.Options.Limit) assert.Equal(t, 2, res.Options.Limit)
assert.Equal(t, []string{"timestamp"}, res.Options.Sort) assert.Equal(t, []string{"timestamp"}, res.Options.Sort)
assert.Equal(t, []string{"level"}, res.Options.Fields)
}) })
t.Run("To PB", func(t *testing.T) { t.Run("To PB", func(t *testing.T) {
res := FindResultToPB(&FindResult{ res := FindResultToPB(&FindResult{
Options: &FindOptions{Limit: 2, Sort: []string{"timestamp"}, Fields: []string{"level"}}, Options: &FindOptions{Limit: 2, Sort: []string{"timestamp"}},
}) })
assert.False(t, res.Options.After.IsValid()) assert.False(t, res.Options.After.IsValid())
assert.False(t, res.Options.Before.IsValid()) assert.False(t, res.Options.Before.IsValid())
assert.Equal(t, int32(2), res.Options.Limit) assert.Equal(t, int32(2), res.Options.Limit)
assert.Equal(t, []string{"timestamp"}, res.Options.Sort) assert.Equal(t, []string{"timestamp"}, res.Options.Sort)
assert.Equal(t, []string{"level"}, res.Options.Fields)
}) })
t.Run("From PB: with nil filter and options", func(t *testing.T) { t.Run("From PB: with nil filter and options", func(t *testing.T) {
res := FindResultFromPB(&pb.FindResult{Filter: nil, Options: nil}) res := FindResultFromPB(&pb.FindResult{Filter: nil, Options: nil})
......
// Code generated by mockery v2.46.3. DO NOT EDIT. // Code generated by mockery v2.50.0. DO NOT EDIT.
package mocks package mocks
import ( import (
items "git.perx.ru/perxis/perxis-go/pkg/items" logs "git.perx.ru/perxis/perxis-go/logs"
mock "github.com/stretchr/testify/mock" mock "github.com/stretchr/testify/mock"
) )
...@@ -14,19 +14,19 @@ type Middleware struct { ...@@ -14,19 +14,19 @@ type Middleware struct {
} }
// Execute provides a mock function with given fields: _a0 // Execute provides a mock function with given fields: _a0
func (_m *Middleware) Execute(_a0 items.Items) items.Items { func (_m *Middleware) Execute(_a0 logs.Service) logs.Service {
ret := _m.Called(_a0) ret := _m.Called(_a0)
if len(ret) == 0 { if len(ret) == 0 {
panic("no return value specified for Execute") panic("no return value specified for Execute")
} }
var r0 items.Items var r0 logs.Service
if rf, ok := ret.Get(0).(func(items.Items) items.Items); ok { if rf, ok := ret.Get(0).(func(logs.Service) logs.Service); ok {
r0 = rf(_a0) r0 = rf(_a0)
} else { } else {
if ret.Get(0) != nil { if ret.Get(0) != nil {
r0 = ret.Get(0).(items.Items) r0 = ret.Get(0).(logs.Service)
} }
} }
......
// Code generated by mockery v2.50.0. DO NOT EDIT.
package mocks
import (
logs "git.perx.ru/perxis/perxis-go/logs"
mock "github.com/stretchr/testify/mock"
)
// WriteSyncer is an autogenerated mock type for the WriteSyncer type
type WriteSyncer struct {
mock.Mock
}
// Sync provides a mock function with no fields
func (_m *WriteSyncer) Sync() error {
ret := _m.Called()
if len(ret) == 0 {
panic("no return value specified for Sync")
}
var r0 error
if rf, ok := ret.Get(0).(func() error); ok {
r0 = rf()
} else {
r0 = ret.Error(0)
}
return r0
}
// Write provides a mock function with given fields: entry
func (_m *WriteSyncer) Write(entry *logs.Entry) error {
ret := _m.Called(entry)
if len(ret) == 0 {
panic("no return value specified for Write")
}
var r0 error
if rf, ok := ret.Get(0).(func(*logs.Entry) error); ok {
r0 = rf(entry)
} else {
r0 = ret.Error(0)
}
return r0
}
// NewWriteSyncer creates a new instance of WriteSyncer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewWriteSyncer(t interface {
mock.TestingT
Cleanup(func())
}) *WriteSyncer {
mock := &WriteSyncer{}
mock.Mock.Test(t)
t.Cleanup(func() { mock.AssertExpectations(t) })
return mock
}
// Code generated by mockery v2.50.0. DO NOT EDIT.
package mocks
import mock "github.com/stretchr/testify/mock"
// SpaceGetter is an autogenerated mock type for the spaceGetter type
type SpaceGetter struct {
mock.Mock
}
// GetSpaceID provides a mock function with no fields
func (_m *SpaceGetter) GetSpaceID() string {
ret := _m.Called()
if len(ret) == 0 {
panic("no return value specified for GetSpaceID")
}
var r0 string
if rf, ok := ret.Get(0).(func() string); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(string)
}
return r0
}
// NewSpaceGetter creates a new instance of SpaceGetter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewSpaceGetter(t interface {
mock.TestingT
Cleanup(func())
}) *SpaceGetter {
mock := &SpaceGetter{}
mock.Mock.Test(t)
t.Cleanup(func() { mock.AssertExpectations(t) })
return mock
}
...@@ -168,9 +168,7 @@ func FindOptionsToPB(opts *FindOptions) *pb.FindOptions { ...@@ -168,9 +168,7 @@ func FindOptionsToPB(opts *FindOptions) *pb.FindOptions {
res := &pb.FindOptions{ res := &pb.FindOptions{
Sort: opts.Sort, Sort: opts.Sort,
Fields: opts.Fields, Limit: int32(opts.Limit), //nolint:gosec //overflow doesn't expected
ExcludeFields: opts.ExcludeFields,
Limit: int32(opts.Limit),
} }
if !opts.After.IsZero() { if !opts.After.IsZero() {
...@@ -190,10 +188,8 @@ func FindOptionsFromPB(opts *pb.FindOptions) *FindOptions { ...@@ -190,10 +188,8 @@ func FindOptionsFromPB(opts *pb.FindOptions) *FindOptions {
return nil return nil
} }
res := &FindOptions{ res := &FindOptions{
Sort: opts.Sort, Sort: opts.GetSort(),
Fields: opts.Fields, Limit: int(opts.GetLimit()),
ExcludeFields: opts.ExcludeFields,
Limit: int(opts.Limit),
} }
if opts.After.IsValid() { if opts.After.IsValid() {
......
Subproject commit 28531974cc43f8ce31e7456241f3cb2535f8c179 Subproject commit 0627c9f829178bc6de2623a0b6d42964c44de496
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment