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
23 changes: 23 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Feature request
description: Предложить улучшение
labels: ["enhancement", "needs-spec"]
body:
- type: textarea
id: problem
attributes:
label: Проблема/боль
description: Что хотите решить?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Предложение
description: Как это должно работать? (API-скиз)
render: go
- type: checkboxes
id: compatibility
attributes:
label: Совместимость
options:
- label: Изменение не ломает существующий API
5 changes: 5 additions & 0 deletions .github/ISSUE_TEMPLATE/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Вопросы по использованию / Q&A
url: https://github.com/{{MODULE_PATH}}/discussions
about: Задавайте вопросы здесь, если это не баг и не фича.
23 changes: 23 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Feature request
description: Предложить улучшение
labels: ["enhancement", "needs-spec"]
body:
- type: textarea
id: problem
attributes:
label: Проблема/боль
description: Что хотите решить?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Предложение
description: Как это должно работать? (API-скиз)
render: go
- type: checkboxes
id: compatibility
attributes:
label: Совместимость
options:
- label: Изменение не ломает существующий API
15 changes: 15 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
### Что сделано
-

### Зачем
-

### Как тестировать
-

### Чеклист
- [ ] Тесты добавлены/обновлены
- [ ] Документация обновлена при необходимости
- [ ] Нет ломающих изменений без обсуждения

Fixes #
34 changes: 34 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
build-test-lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.23'
cache: true
- name: Go mod tidy (no diff)
run: go mod tidy && git diff --exit-code
- name: Lint
uses: golangci/golangci-lint-action@v7
with:
version: latest
args: --timeout=5m
- name: Test (race + cover)
run: go test ./... -race -coverprofile=coverage.out -covermode=atomic
- name: Govulncheck
uses: golang/govulncheck-action@v1
with:
go-version-input: '1.23'
- name: Upload coverage artifact
uses: actions/upload-artifact@v4
with:
name: coverage
path: coverage.out
20 changes: 20 additions & 0 deletions .github/workflows/release-notes.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Release Drafter
on:
push:
branches: [ main ]
pull_request:
types: [opened, reopened, synchronize, closed]
permissions:
contents: read
jobs:
update_release_draft:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- uses: release-drafter/release-drafter@v6
with:
disable-autolabeler: false
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
18 changes: 18 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Binaries and build
/bin/
/dist/
/out/
/coverage.out
*.test
*.exe
*.dll
*.so
*.dylib

# IDE
.vscode/
.idea/
*.iml

# Go
vendor/
41 changes: 41 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
version: "2"
run:
tests: true
linters:
enable:
- gocritic
- revive
settings:
revive:
severity: warning
rules:
- name: var-naming
- name: exported
- name: package-comments
- name: unused-parameter
- name: indent-error-flow
exclusions:
generated: lax
rules:
- linters:
- errcheck
path: _test\.go
paths:
- third_party$
- builtin$
- examples$
issues:
max-issues-per-linter: 0
max-same-issues: 3
formatters:
enable:
- gofumpt
settings:
gofumpt:
extra-rules: true
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$
30 changes: 30 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Contributing to barugoo/distribution

Спасибо, что хотите помочь 💚

## Требования
- Go ≥ 1.22
- `make`, `golangci-lint`, `govulncheck`

## Как начать
1. Форк → ветка `feat/<slug>` или `fix/<slug>`
2. `make lint && make test`
3. Откройте PR с понятным описанием и ссылкой на Issue (если есть)

## Коммиты
Используем Conventional Commits:
`feat: ...`, `fix: ...`, `docs: ...`, `refactor: ...`, `test: ...`, `chore: ...`

## Проверки перед PR
- `go mod tidy` не создаёт диффов
- Линтеры зелёные
- Тесты зелёные, покрытие не просело для критических путей
- Обновлены README/доки при необходимости

## Кодстайл
- `gofmt`, `go vet`, `golangci-lint`
- Экспортируемые типы и функции документируются Godoc-комментами
- Ошибки оборачиваем контекстом `fmt.Errorf("...: %w", err)`

## Релизы
- SemVer. Ломающие изменения — только в major или через `v0.*` с чётким описанием.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Dmitrii Shelamov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
25 changes: 25 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
PKG := ./...
GO ?= go

.PHONY: all fmt vet lint test vuln tidy ci
all: fmt vet lint test vuln

fmt:
$(GO) fmt $(PKG)

vet:
$(GO) vet $(PKG)

lint:
golangci-lint run

test:
$(GO) test $(PKG) -race -coverprofile=coverage.out -covermode=atomic

vuln:
govulncheck $(PKG)

tidy:
$(GO) mod tidy

ci: tidy lint test vuln
81 changes: 58 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,65 @@
# Distribution package
# your-lib

## About
This package is used to split arbitrary decimal.Decimal values (usually money amounts) based on `distribution.Layout` that describes weights of each bucket, i.e.:
```
{
bucket1: 1/3,
bucket2: 1/6,
bucket3: 1/2
}
Библиотека на Go для предсказуемого дробления произвольных чисел на заранее заданные доли.

sum of all fractions is always 1
```
[![Go Reference](https://pkg.go.dev/badge/github.com/barugoo/distribution.svg)](https://pkg.go.dev/github.com/barugoo/distribution)
[![CI](https://github.com/barugoo/distribution/actions/workflows/ci.yml/badge.svg)](https://github.com/barugoo/distribution/actions/workflows/ci.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/barugoo/distribution)](https://goreportcard.com/report/github.com/barugoo/distribution)

The result of "splitting" operation is a `distribution.Value` that contains the buckets with calculated shares of initial value (with specific precision) and the remainder.
For example distribution of `100` using the above `distribution.Layout` will produce this result:
---

## Установка

```bash
go get github.com/barugoo/distribution@latest
```
{
precision: 2,
bucket1: 33.33,
bucket2: 16.66,
bucket3: 50,
remainder: 0.01
}

sum is always 100
---

## Быстрый старт

```go
package main

import (
"fmt"
"github.com/barugoo/distribution"
)

func main() {
c := yourlib.New(yourlib.WithPrefix("demo: "))
out := c.Do("hello")
fmt.Println(out)
}
```
The `remainder` will be added automatically based on which `distribution.Bucket` in variadic slice of `MakeLayout` was marked as `remaindable`

External code doesn't have access to internals of `Value` or `Layout` and there are no mutating methods in the public API - which means there's no way for an importing code to break the internal rules of this package.
---

## Почему your-lib?

* Простое, предсказуемое API
* Минимум зависимостей
* Семантическое версионирование и стабильность API после v1

---

## Документация

* [API на pkg.go.dev](https://pkg.go.dev/github.com/barugoo/distribution)
* Примеры использования: папка [`/examples`](./examples)
* Вопросы и обсуждения: [Discussions](https://github.com/barugoo/distribution/discussions)

---

## Безопасность

См. [SECURITY.md](./SECURITY.md).

---

## Вклад

См. [CONTRIBUTING.md](./CONTRIBUTING.md).
Будем рады любому участию! 🙌

```
4 changes: 4 additions & 0 deletions core/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import (
"github.com/shopspring/decimal"
)

// Bucket represents a single bucket in a distribution; immutable
type Bucket[T comparable] struct {
Key T
Value decimal.Decimal
ShouldAddRemainder bool
}

// BucketSlice is a slice of Buckets; immutable
type BucketSlice[T comparable] []Bucket[T]

func (s BucketSlice[T]) copy() BucketSlice[T] {
Expand All @@ -21,13 +23,15 @@ func (s BucketSlice[T]) copy() BucketSlice[T] {
return cloned
}

// Total returns the total value of all buckets in the slice
func (s BucketSlice[T]) Total() (sum decimal.Decimal) {
for _, v := range s {
sum = sum.Add(v.Value)
}
return sum
}

// String returns a string representation of the BucketSlice
func (s BucketSlice[T]) String() string {
var str strings.Builder
str.WriteString("[")
Expand Down
8 changes: 8 additions & 0 deletions core/core.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package core

import "github.com/shopspring/decimal"

// toDecimal is a shorthand for decimal.NewFromFloat(f)
func toDecimal(f float64) decimal.Decimal {
return decimal.NewFromFloat(f)
}
Loading
Loading