Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 37db8e97ca | |||
| 2a6a65ce80 | |||
| 3fd8dc2a49 | |||
| d790a9edfe | |||
| 51343768d9 | |||
| a14c3f1181 | |||
| 7483fd4194 | |||
| c1ecd947ac | |||
| 712abe3c9d | |||
| d053faeb23 | |||
| 8a5aae3de9 | |||
| 4f0592e342 | |||
| 232a0eb903 |
+4
-1
@@ -1,6 +1,6 @@
|
||||
# build output
|
||||
/bin/
|
||||
releaser-*
|
||||
/releaser-*
|
||||
|
||||
# test coverage
|
||||
coverage.out
|
||||
@@ -10,3 +10,6 @@ coverage.html
|
||||
/docs/themes/
|
||||
/docs/public/
|
||||
|
||||
# Task runner cache
|
||||
/.task/
|
||||
|
||||
|
||||
+15
-3
@@ -20,6 +20,19 @@
|
||||
# api + write_repository
|
||||
# (do NOT use CI_JOB_TOKEN — it cannot push tags back)
|
||||
|
||||
# Optional preflight job for merge-request pipelines: validates the release
|
||||
# environment (branch pattern, remote URL, auth, version files, release
|
||||
# target) without releasing anything.
|
||||
.releaser:check:
|
||||
stage: test
|
||||
image: ${RELEASER_IMAGE:-registry.example.com/releaser:latest}
|
||||
variables:
|
||||
GIT_DEPTH: 0
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
script:
|
||||
- releaser --check --branch "release/0.0"
|
||||
|
||||
.releaser:release:
|
||||
stage: release
|
||||
image: ${RELEASER_IMAGE:-registry.example.com/releaser:latest}
|
||||
@@ -41,9 +54,8 @@
|
||||
- git config user.name "${GITLAB_USER_NAME:-Releaser CI}"
|
||||
|
||||
script:
|
||||
- releaser
|
||||
--branch "$CI_COMMIT_BRANCH"
|
||||
$RELEASER_EXTRA_ARGS
|
||||
# No --branch needed: releaser falls back to CI_COMMIT_BRANCH on detached HEAD.
|
||||
- releaser $RELEASER_EXTRA_ARGS
|
||||
|
||||
artifacts:
|
||||
reports:
|
||||
|
||||
@@ -50,6 +50,16 @@ git:
|
||||
# - "packages/frontend/package.json"
|
||||
# - "packages/backend/package.json"
|
||||
|
||||
# python:
|
||||
# Single pyproject.toml path (opt-in — no default).
|
||||
# Reads [project].version (PEP 621) first, then [tool.poetry].version.
|
||||
# pyproject_toml: "pyproject.toml"
|
||||
|
||||
# Multiple pyproject.toml paths for monorepos (overrides pyproject_toml).
|
||||
# pyproject_tomls:
|
||||
# - "pyproject.toml"
|
||||
# - "packages/cli/pyproject.toml"
|
||||
|
||||
# gradle:
|
||||
# Single build.gradle or build.gradle.kts path (opt-in — no default).
|
||||
# Both Groovy DSL (single-quoted) and Kotlin DSL (double-quoted) are supported.
|
||||
|
||||
@@ -3,6 +3,78 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
## [1.10.0] - 2026-07-16
|
||||
|
||||
### Added
|
||||
|
||||
- **`--check` preflight** — validates the release environment without releasing: branch resolution + pattern match, working tree state, tag discovery, shallow clone, remote origin URL parseability (the same parse the push performs), push auth method, configured version files, and release target; reports all problems at once and exits non-zero when any check fails
|
||||
- **Shallow clone detection** — when the clone is shallow and no previous release tag is found, releaser refuses to release instead of silently restarting versioning at `X.Y.0` (previous tags may sit beyond the fetch depth); a shallow clone whose history includes the latest tag proceeds normally
|
||||
- **`--allow-shallow` flag** — bypasses the shallow-clone guard for a genuine first release
|
||||
- **`.releaser:check` CI job template** — optional merge-request-pipeline preflight job in `.releaser.gitlab-ci.yml`
|
||||
|
||||
### Changed
|
||||
|
||||
- **CI examples** — the GitLab CI examples in README and docs now set `GIT_DEPTH: 0`, which the shallow-clone guard would otherwise surface as an error on first release
|
||||
|
||||
## [1.9.0] - 2026-07-16
|
||||
|
||||
### Added
|
||||
|
||||
- **CI branch detection fallback** — on detached HEAD (the normal state in CI checkouts), the branch name now falls back to `CI_COMMIT_BRANCH`, then `CI_COMMIT_REF_NAME` (GitLab CI), then `GITHUB_REF_NAME` (GitHub Actions) before erroring; `--branch` is no longer required in CI
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Detached HEAD push** — the go-git push paths (token and SSH agent) used the refspec `refs/heads/<branch>`, a ref that never exists in a detached CI checkout; go-git silently skipped the branch update and pushed only the tag, so the release commit never reached the remote branch. Both paths now push HEAD's commit hash to the branch instead
|
||||
|
||||
### Changed
|
||||
|
||||
- **`.releaser.gitlab-ci.yml` template** — dropped the now-redundant `--branch "$CI_COMMIT_BRANCH"` from the job script
|
||||
|
||||
## [1.8.0] - 2026-07-12
|
||||
|
||||
### Added
|
||||
|
||||
- **Release notifications** — new `internal/notify` package; best-effort notification on release to Slack, Microsoft Teams, Google Chat, Telegram, and/or a generic JSON webhook; every target is independently opt-in and a failed notification never fails the release
|
||||
- **`notify` config section** — `slack_webhook_url`, `teams_webhook_url`, `google_chat_webhook_url`, `telegram_bot_token` + `telegram_chat_id`, `webhook_url`; each also configurable via env var (`SLACK_WEBHOOK_URL`, `TEAMS_WEBHOOK_URL`, `GOOGLE_CHAT_WEBHOOK_URL`, `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`, `RELEASER_WEBHOOK_URL`)
|
||||
- **`FuzzMessagePayloads`** in `internal/notify` — 100% per-package statement coverage maintained across all 15 packages
|
||||
|
||||
## [1.7.1] - 2026-07-12
|
||||
|
||||
### Added
|
||||
|
||||
- **Apache License 2.0** — `LICENSE` file added, Copyright 2026 K3nnyfr (alex@k3nny.fr); linked from a new `## License` section in README.md
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`task docs:build` stale output** — Hugo build now passes `--cleanDestinationDir` so removed/renamed files don't linger in `docs/public`
|
||||
|
||||
### Changed
|
||||
|
||||
- **`.gitignore`** — `/.task/` (Task runner's local checksum cache) is now ignored
|
||||
|
||||
## [1.7.0] - 2026-07-12
|
||||
|
||||
### Added
|
||||
|
||||
- **Python `pyproject.toml` support** — new `internal/pyproject` package; reads `[project].version` (PEP 621) first, then `[tool.poetry].version` (Poetry); original formatting preserved on write; `regexp.QuoteMeta` ensures safety with dot-containing version strings
|
||||
- **`python.pyproject_toml` / `python.pyproject_tomls` config** — opt-in, no default; `pyproject_tomls` list overrides `pyproject_toml` for monorepos; follows the established multi-value pattern (Maven, Node, Gradle)
|
||||
- **`--pyproject <path>` flag** — overrides `python.pyproject_toml` and clears `pyproject_tomls`; shown in verbose config table as `python.paths`
|
||||
- **`FuzzReadVersion` / `FuzzWriteVersion`** in `internal/pyproject` — 100% per-package statement coverage maintained across all 14 packages
|
||||
|
||||
## [1.6.3] - 2026-07-11
|
||||
|
||||
### Added
|
||||
|
||||
- **Logo** — `docs/static/images/releaser-logo-1024.png` (1024×1024) set as Geekdoc site header logo via `geekdocLogo`; 128×128 version added to README above the release badge
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`.gitignore` over-matching** — `releaser-*` was catching files inside `docs/static/images/`; anchored to `/releaser-*` so only root-level release binaries are excluded
|
||||
|
||||
### Changed
|
||||
|
||||
- **`docs/hugo.toml` `baseURL`** — set to `https://releaser.k3nny.fr/` (was `"/"`)
|
||||
|
||||
## [1.6.2] - 2026-07-11
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -15,9 +15,12 @@ internal/config/ — .releaser.yml loader + env var overlay + source trackin
|
||||
internal/ghclient/ — minimal GitHub Releases API client
|
||||
internal/gitutil/ — go-git helpers: tag discovery, commit walker, push
|
||||
internal/glclient/ — minimal GitLab Releases API client
|
||||
internal/gradle/ — build.gradle / build.gradle.kts version reader/writer
|
||||
internal/maven/ — pom.xml version reader/writer
|
||||
internal/node/ — package.json version reader/writer
|
||||
internal/notes/ — release notes body generator
|
||||
internal/notify/ — Slack / Teams / Google Chat / Telegram / webhook release notifications
|
||||
internal/pyproject/ — pyproject.toml version reader/writer
|
||||
internal/version/ — semver next-version calculator
|
||||
```
|
||||
|
||||
@@ -62,10 +65,12 @@ All seed cases must pass. The table below is authoritative — keep it in sync w
|
||||
| `internal/changelog` | `FuzzUpdate` | rewrites arbitrary existing file content |
|
||||
| `internal/commits` | `FuzzParse` | parses arbitrary commit message strings |
|
||||
| `internal/gradle` | `FuzzReadVersion`, `FuzzWriteVersion` | reads/rewrites arbitrary Gradle build file content |
|
||||
| `internal/pyproject` | `FuzzReadVersion`, `FuzzWriteVersion` | reads/rewrites arbitrary pyproject.toml content |
|
||||
| `internal/glclient` | `FuzzEncodeProjectPath` | encodes arbitrary project path strings |
|
||||
| `internal/maven` | `FuzzReadVersion`, `FuzzReplaceProjectVersion` | reads/rewrites arbitrary XML file content |
|
||||
| `internal/node` | `FuzzReadVersion`, `FuzzWriteVersion` | reads/rewrites arbitrary JSON file content |
|
||||
| `internal/notes` | `FuzzGenerate` | generates notes from arbitrary commit messages |
|
||||
| `internal/notify` | `FuzzMessagePayloads` | builds notification JSON payloads from arbitrary release notes |
|
||||
|
||||
Packages **not** requiring fuzz tests (no free-form text parsing): `internal/config` (yaml.v3 handles parsing), `internal/ghclient` (HTTP client, no text parsing), `internal/gitutil` (git operations), `internal/version` (typed inputs only), `cmd` (CLI orchestration). When adding a new package, check whether it parses text or rewrites files — if yes, add a row above.
|
||||
|
||||
@@ -74,6 +79,17 @@ Fuzz seed corpus guidelines:
|
||||
- Include empty string, binary/non-UTF-8 bytes (`"\x00\xff"`), and inputs that stress known branches (e.g. existing `## [version]` heading for changelog).
|
||||
- The fuzz body must never assert on return values — only verify no panic.
|
||||
|
||||
## Documentation sync
|
||||
|
||||
**Every change that adds, changes, or removes a feature, flag, or config key must update all of the following in the same commit:**
|
||||
|
||||
- `README.md` — features list, usage examples, option tables, version badge
|
||||
- `CHANGELOG.md` — new dated `## [X.Y.Z]` entry (see `/release` skill for format)
|
||||
- `ROADMAP.md` — mark shipped items `✓`, add a "Shipped in vX.Y.Z" note, drop outdated caveats
|
||||
- Hugo docs under `docs/content/` (`installation.md`, `usage.md`, `configuration.md`, `ci-integration.md`, `changelog.md`) — whichever pages describe the changed behavior
|
||||
|
||||
Treat these as one unit: a PR that changes CLI behavior or config but leaves any of the above stale is incomplete. `docs/content/changelog.md` only needs an entry for tagged (minor/major) releases, matching the pattern already in that file — patch-only releases are covered by the root `CHANGELOG.md` but not duplicated there.
|
||||
|
||||
## Dependency rules
|
||||
|
||||
- **No new external dependencies** unless absolutely necessary. The project deliberately avoids pulling in large ecosystems.
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 K3nnyfr (alex@k3nny.fr)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,9 +1,13 @@
|
||||
# releaser
|
||||
|
||||

|
||||
<img src="docs/static/images/releaser-logo-128.png" alt="releaser logo" width="128">
|
||||
|
||||

|
||||
|
||||
A CI-friendly release automation tool for GitFlow workflows using Conventional Commits.
|
||||
|
||||
**[Documentation](https://releaser.k3nny.fr)** · **[Repository](https://git.k3nny.fr/k3nny/releaser)**
|
||||
|
||||
## Problem
|
||||
|
||||
Standard tools like `semantic-release` are designed for trunk-based development. In a GitFlow setup with versioned release branches (`release/1.1`, `release/1.2`), they either fail to respect the branch's version range or require brittle configuration.
|
||||
@@ -24,6 +28,7 @@ release/1.2 branch
|
||||
3. **Commit analysis** — parses Conventional Commits between last tag and HEAD
|
||||
4. **Version bump** — increments patch (the minor is owned by the branch)
|
||||
5. **Release** — updates `pom.xml` / `package.json` / `build.gradle`, commits, tags, creates GitLab or GitHub release
|
||||
6. **Notify** — best-effort notification to Slack, Microsoft Teams, Google Chat, Telegram, and/or a generic webhook
|
||||
|
||||
## Version bump rules
|
||||
|
||||
@@ -60,15 +65,23 @@ releaser --no-commit
|
||||
# … then commit manually and re-run:
|
||||
releaser --tag-only
|
||||
|
||||
# Explicitly target a branch (useful in detached HEAD CI)
|
||||
# Explicitly target a branch (detached HEAD falls back to
|
||||
# CI_COMMIT_BRANCH / CI_COMMIT_REF_NAME / GITHUB_REF_NAME automatically)
|
||||
releaser --branch release/1.2
|
||||
|
||||
# First release from a shallow clone (no previous tag exists yet)
|
||||
releaser --allow-shallow
|
||||
|
||||
# Write changelog to a custom file
|
||||
releaser --changelog-file CHANGES.md
|
||||
|
||||
# Show configuration sources, commit list, and version decision
|
||||
releaser --verbose --dry-run
|
||||
|
||||
# Preflight: validate branch, working tree, remote URL, push auth,
|
||||
# version files, and release target — reports all problems at once
|
||||
releaser --check
|
||||
|
||||
# Target a specific pom.xml
|
||||
releaser --pom path/to/pom.xml
|
||||
|
||||
@@ -121,6 +134,12 @@ gradle: # opt-in — no default; om
|
||||
# - "build.gradle"
|
||||
# - "module-a/build.gradle"
|
||||
|
||||
python: # opt-in — no default; omit to skip
|
||||
# pyproject_toml: "pyproject.toml" # PEP 621 [project] or [tool.poetry]
|
||||
# pyproject_tomls: # monorepo: list overrides pyproject_toml
|
||||
# - "pyproject.toml"
|
||||
# - "packages/cli/pyproject.toml"
|
||||
|
||||
gitlab:
|
||||
url: "https://gitlab.example.com" # or env CI_SERVER_URL
|
||||
token: "" # env GITLAB_TOKEN (never commit this)
|
||||
@@ -129,6 +148,14 @@ gitlab:
|
||||
github:
|
||||
token: "" # env GITHUB_TOKEN (never commit this)
|
||||
repo: "" # "owner/repo" format
|
||||
|
||||
notify: # opt-in — every field independent; failures are warnings, not errors
|
||||
# slack_webhook_url: "" # or env SLACK_WEBHOOK_URL
|
||||
# teams_webhook_url: "" # or env TEAMS_WEBHOOK_URL
|
||||
# google_chat_webhook_url: "" # or env GOOGLE_CHAT_WEBHOOK_URL
|
||||
# telegram_bot_token: "" # or env TELEGRAM_BOT_TOKEN (both required)
|
||||
# telegram_chat_id: "" # or env TELEGRAM_CHAT_ID
|
||||
# webhook_url: "" # generic {"version","notes"} JSON POST; or env RELEASER_WEBHOOK_URL
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
@@ -140,8 +167,13 @@ github:
|
||||
| `CI_PROJECT_ID` | GitLab project identifier (numeric) |
|
||||
| `CI_PROJECT_PATH` | GitLab project identifier (fallback) |
|
||||
| `GITHUB_TOKEN` | GitHub API auth |
|
||||
| `SLACK_WEBHOOK_URL` | Slack release notification |
|
||||
| `TEAMS_WEBHOOK_URL` | Microsoft Teams release notification |
|
||||
| `GOOGLE_CHAT_WEBHOOK_URL` | Google Chat release notification |
|
||||
| `TELEGRAM_BOT_TOKEN` / `TELEGRAM_CHAT_ID` | Telegram release notification (both required) |
|
||||
| `RELEASER_WEBHOOK_URL` | Generic webhook release notification |
|
||||
|
||||
When both `github.*` and `gitlab.*` are configured, GitHub takes precedence.
|
||||
When both `github.*` and `gitlab.*` are configured, GitHub takes precedence. All `notify.*` targets are independent — any combination may be configured at once, and a failed notification never fails the release.
|
||||
|
||||
## CI integration (GitLab CI example)
|
||||
|
||||
@@ -153,9 +185,14 @@ release:
|
||||
- if: $CI_COMMIT_BRANCH =~ /^release\/.+$/
|
||||
variables:
|
||||
GITLAB_TOKEN: $RELEASE_TOKEN # project/group CI variable with api + write_repository scope
|
||||
GIT_DEPTH: 0 # full history — shallow clones hide previous release tags
|
||||
script:
|
||||
- releaser
|
||||
artifacts:
|
||||
reports:
|
||||
dotenv: release.env # exposes NEXT_VERSION to downstream jobs
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Apache License 2.0 — see [LICENSE](LICENSE).
|
||||
|
||||
+5
-2
@@ -8,7 +8,7 @@
|
||||
- [x] Commit range walker (last tag → HEAD, or full history on first release)
|
||||
- [x] Version bump calculator — returns plain `X.Y.Z` (prefix kept separate)
|
||||
- [x] `--dry-run` flag: print next version and exit
|
||||
- [x] `--branch` flag: override branch detection (detached HEAD in CI)
|
||||
- [x] `--branch` flag: override branch detection (detached HEAD in CI); detached HEAD auto-falls back to `CI_COMMIT_BRANCH` / `CI_COMMIT_REF_NAME` / `GITHUB_REF_NAME` — ✓ shipped v1.9.0, along with detached-HEAD push fix
|
||||
- [x] Exit code 2 when no releasable commits
|
||||
|
||||
## v0.2 — Config + Maven + local git ops ✅
|
||||
@@ -86,4 +86,7 @@
|
||||
## Future / backlog
|
||||
|
||||
- ~~Gradle support (`build.gradle` / `build.gradle.kts`)~~ — ✓ shipped v1.6.0 (`internal/gradle`; Groovy + Kotlin DSL; multi-module via `gradle.build_files`; `--gradle` flag)
|
||||
- Slack / Teams notification on release
|
||||
- ~~Python `pyproject.toml` version bump (`[project].version` and `[tool.poetry].version`; single and multi-path like Maven's `pom_paths`)~~ — ✓ shipped v1.7.0 (`internal/pyproject`; PEP 621 + Poetry; `python.pyproject_tomls`; `--pyproject` flag)
|
||||
- ~~Slack / Teams notification on release~~ — ✓ shipped v1.8.0 (`internal/notify`; Slack, Microsoft Teams, Google Chat, Telegram, and generic webhook; each opt-in via `notify.*` config or env var; best-effort — never fails the release)
|
||||
- ~~Shallow clone detection~~ — ✓ shipped v1.10.0 (refuses to release when the clone is shallow and no previous tag is found — would silently restart at X.Y.0; `--allow-shallow` escape hatch for a true first release)
|
||||
- ~~CI preflight~~ — ✓ shipped v1.10.0 as `--check` (branch resolution, working tree, shallow clone, remote URL parse, push auth method, version files, release target; reports all problems at once). Possible later upgrades: online token-scope validation against the GitLab/GitHub API, promotion to a `doctor` subcommand
|
||||
|
||||
+7
-1
@@ -24,6 +24,12 @@ tasks:
|
||||
generates:
|
||||
- "{{.BIN}}"
|
||||
|
||||
install:
|
||||
desc: installs the binary in /usr/local/bin/
|
||||
cmds:
|
||||
- task: build
|
||||
- sudo cp ./bin/releaser /usr/local/bin/releaser
|
||||
|
||||
run:
|
||||
desc: Build and run releaser (pass args with -- e.g. task run -- --dry-run)
|
||||
deps: [build]
|
||||
@@ -126,4 +132,4 @@ tasks:
|
||||
desc: Build docs to docs/public/ (requires hugo)
|
||||
deps: [docs:setup]
|
||||
cmds:
|
||||
- hugo --source docs --destination public --minify
|
||||
- hugo --source docs --destination public --cleanDestinationDir --minify
|
||||
+294
-27
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
|
||||
gogit "github.com/go-git/go-git/v5"
|
||||
"github.com/go-git/go-git/v5/plumbing/transport"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.k3nny.fr/releaser/internal/branch"
|
||||
@@ -20,8 +21,10 @@ import (
|
||||
"git.k3nny.fr/releaser/internal/glclient"
|
||||
"git.k3nny.fr/releaser/internal/gradle"
|
||||
"git.k3nny.fr/releaser/internal/maven"
|
||||
"git.k3nny.fr/releaser/internal/pyproject"
|
||||
"git.k3nny.fr/releaser/internal/node"
|
||||
"git.k3nny.fr/releaser/internal/notes"
|
||||
"git.k3nny.fr/releaser/internal/notify"
|
||||
semver "git.k3nny.fr/releaser/internal/version"
|
||||
)
|
||||
|
||||
@@ -90,6 +93,17 @@ gradle:
|
||||
# - "module-a/build.gradle"
|
||||
# - "module-b/build.gradle"
|
||||
|
||||
python:
|
||||
# Single pyproject.toml path (opt-in — no default).
|
||||
# Reads [project].version (PEP 621) first, then [tool.poetry].version.
|
||||
# pyproject_toml: "pyproject.toml"
|
||||
|
||||
# Multiple pyproject.toml paths for monorepos (overrides pyproject_toml).
|
||||
# pyproject_tomls:
|
||||
# - "pyproject.toml"
|
||||
# - "packages/cli/pyproject.toml"
|
||||
# - "packages/lib/pyproject.toml"
|
||||
|
||||
gitlab:
|
||||
# GitLab instance URL. Falls back to the CI_SERVER_URL environment variable.
|
||||
# url: "https://gitlab.example.com"
|
||||
@@ -110,6 +124,29 @@ github:
|
||||
|
||||
# Repository in "owner/repo" format.
|
||||
# repo: ""
|
||||
|
||||
notify:
|
||||
# Every field below is opt-in. A target is only used when its required
|
||||
# fields are set (via this file, or the matching environment variable).
|
||||
# Notification failures never fail the release — they're logged as warnings.
|
||||
|
||||
# Slack incoming webhook URL. Falls back to SLACK_WEBHOOK_URL.
|
||||
# slack_webhook_url: ""
|
||||
|
||||
# Microsoft Teams incoming webhook URL. Falls back to TEAMS_WEBHOOK_URL.
|
||||
# teams_webhook_url: ""
|
||||
|
||||
# Google Chat incoming webhook URL. Falls back to GOOGLE_CHAT_WEBHOOK_URL.
|
||||
# google_chat_webhook_url: ""
|
||||
|
||||
# Telegram bot token and chat ID — both required. Fall back to
|
||||
# TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID.
|
||||
# telegram_bot_token: ""
|
||||
# telegram_chat_id: ""
|
||||
|
||||
# Generic webhook URL — POSTed a {"version": ..., "notes": ...} JSON body.
|
||||
# Falls back to RELEASER_WEBHOOK_URL.
|
||||
# webhook_url: ""
|
||||
`
|
||||
|
||||
var (
|
||||
@@ -158,11 +195,14 @@ func newRootCmd() *cobra.Command {
|
||||
noRelease bool
|
||||
noCommit bool
|
||||
tagOnly bool
|
||||
allowShallow bool
|
||||
check bool
|
||||
branchOverride string
|
||||
repoPath string
|
||||
pomOverride string
|
||||
gradleOverride string
|
||||
changelogFile string
|
||||
gradleOverride string
|
||||
pyprojectOverride string
|
||||
changelogFile string
|
||||
tagPrefixFlag string
|
||||
tagPrefixSet bool
|
||||
patternFlag string
|
||||
@@ -184,8 +224,9 @@ func newRootCmd() *cobra.Command {
|
||||
repoPath: repoPath,
|
||||
branchOverride: branchOverride,
|
||||
pomOverride: pomOverride,
|
||||
gradleOverride: gradleOverride,
|
||||
changelogFile: changelogFile,
|
||||
gradleOverride: gradleOverride,
|
||||
pyprojectOverride: pyprojectOverride,
|
||||
changelogFile: changelogFile,
|
||||
tagPrefixFlag: tagPrefixFlag,
|
||||
tagPrefixSet: tagPrefixSet,
|
||||
patternFlag: patternFlag,
|
||||
@@ -195,6 +236,8 @@ func newRootCmd() *cobra.Command {
|
||||
noRelease: noRelease,
|
||||
noCommit: noCommit,
|
||||
tagOnly: tagOnly,
|
||||
allowShallow: allowShallow,
|
||||
check: check,
|
||||
releaseEnvFile: releaseEnvFile,
|
||||
})
|
||||
},
|
||||
@@ -207,10 +250,13 @@ func newRootCmd() *cobra.Command {
|
||||
root.Flags().BoolVar(&noRelease, "no-release", false, "push commit and tag but skip creating the release")
|
||||
root.Flags().BoolVar(&noCommit, "no-commit", false, "update files but do not commit, tag, or push")
|
||||
root.Flags().BoolVar(&tagOnly, "tag-only", false, "tag HEAD without updating files (assumes version was already committed)")
|
||||
root.Flags().StringVar(&branchOverride, "branch", "", "override branch name detection (required in detached HEAD)")
|
||||
root.Flags().BoolVar(&allowShallow, "allow-shallow", false, "proceed in a shallow clone even when no previous release tag is found")
|
||||
root.Flags().BoolVar(&check, "check", false, "preflight: validate branch, working tree, remote, auth, version files, and release target without releasing")
|
||||
root.Flags().StringVar(&branchOverride, "branch", "", "override branch name detection (detached HEAD falls back to CI_COMMIT_BRANCH, CI_COMMIT_REF_NAME, GITHUB_REF_NAME)")
|
||||
root.Flags().StringVar(&repoPath, "repo", ".", "path to git repository")
|
||||
root.Flags().StringVar(&pomOverride, "pom", "", "override maven.pom_path from config")
|
||||
root.Flags().StringVar(&gradleOverride, "gradle", "", "override gradle.build_file from config")
|
||||
root.Flags().StringVar(&pyprojectOverride, "pyproject", "", "override python.pyproject_toml from config")
|
||||
root.Flags().StringVar(&changelogFile, "changelog-file", "CHANGELOG.md", "path to changelog file relative to repo root")
|
||||
root.Flags().StringVar(&tagPrefixFlag, "tag-prefix", "", "override git.tag_prefix from config")
|
||||
root.Flags().StringVar(&patternFlag, "branch-pattern", "", "override git.branch_pattern from config")
|
||||
@@ -235,9 +281,10 @@ type options struct {
|
||||
repoPath string
|
||||
branchOverride string
|
||||
pomOverride string
|
||||
gradleOverride string
|
||||
changelogFile string
|
||||
tagPrefixFlag string
|
||||
gradleOverride string
|
||||
pyprojectOverride string
|
||||
changelogFile string
|
||||
tagPrefixFlag string
|
||||
tagPrefixSet bool
|
||||
patternFlag string
|
||||
patternSet bool
|
||||
@@ -246,9 +293,20 @@ type options struct {
|
||||
noRelease bool
|
||||
noCommit bool
|
||||
tagOnly bool
|
||||
allowShallow bool
|
||||
check bool
|
||||
releaseEnvFile string
|
||||
}
|
||||
|
||||
// maskedIfSet reports whether a secret-like config value is set, without
|
||||
// printing the value itself.
|
||||
func maskedIfSet(v string) string {
|
||||
if v != "" {
|
||||
return "(set)"
|
||||
}
|
||||
return "(not set)"
|
||||
}
|
||||
|
||||
func printVerboseConfig(cfg config.Config, src config.Sources) {
|
||||
logSection("configuration")
|
||||
rows := []struct{ key, val string }{
|
||||
@@ -296,21 +354,24 @@ func printVerboseConfig(cfg config.Config, src config.Sources) {
|
||||
}
|
||||
return strings.Join(paths, ", ")
|
||||
}()},
|
||||
{"python.paths", func() string {
|
||||
paths := cfg.Python.EffectivePaths()
|
||||
if len(paths) == 0 {
|
||||
return "(not configured)"
|
||||
}
|
||||
return strings.Join(paths, ", ")
|
||||
}()},
|
||||
{"gitlab.url", cfg.GitLab.URL},
|
||||
{"gitlab.token", func() string {
|
||||
if cfg.GitLab.Token != "" {
|
||||
return "(set)"
|
||||
}
|
||||
return "(not set)"
|
||||
}()},
|
||||
{"gitlab.token", maskedIfSet(cfg.GitLab.Token)},
|
||||
{"gitlab.project", cfg.GitLab.Project},
|
||||
{"github.token", func() string {
|
||||
if cfg.GitHub.Token != "" {
|
||||
return "(set)"
|
||||
}
|
||||
return "(not set)"
|
||||
}()},
|
||||
{"github.token", maskedIfSet(cfg.GitHub.Token)},
|
||||
{"github.repo", cfg.GitHub.Repo},
|
||||
{"notify.slack_webhook_url", maskedIfSet(cfg.Notify.SlackWebhookURL)},
|
||||
{"notify.teams_webhook_url", maskedIfSet(cfg.Notify.TeamsWebhookURL)},
|
||||
{"notify.google_chat_webhook_url", maskedIfSet(cfg.Notify.GoogleChatWebhookURL)},
|
||||
{"notify.telegram_bot_token", maskedIfSet(cfg.Notify.TelegramBotToken)},
|
||||
{"notify.telegram_chat_id", maskedIfSet(cfg.Notify.TelegramChatID)},
|
||||
{"notify.webhook_url", maskedIfSet(cfg.Notify.WebhookURL)},
|
||||
}
|
||||
for _, r := range rows {
|
||||
source := src[r.key]
|
||||
@@ -388,6 +449,11 @@ func run(o options) error {
|
||||
cfg.Gradle.BuildFiles = nil
|
||||
src["gradle.build_files"] = "flag: --gradle"
|
||||
}
|
||||
if o.pyprojectOverride != "" {
|
||||
cfg.Python.PyprojectTOML = o.pyprojectOverride
|
||||
cfg.Python.PyprojectTOMLs = nil
|
||||
src["python.pyproject_tomls"] = "flag: --pyproject"
|
||||
}
|
||||
if o.patternSet {
|
||||
cfg.Git.BranchPattern = o.patternFlag
|
||||
src["git.branch_pattern"] = "flag: --branch-pattern"
|
||||
@@ -397,6 +463,10 @@ func run(o options) error {
|
||||
printVerboseConfig(cfg, src)
|
||||
}
|
||||
|
||||
if o.check {
|
||||
return runCheck(o, cfg, absRepo)
|
||||
}
|
||||
|
||||
// --- Git ---
|
||||
repo, err := gogit.PlainOpenWithOptions(absRepo, &gogit.PlainOpenOptions{DetectDotGit: true})
|
||||
if err != nil {
|
||||
@@ -442,6 +512,20 @@ func run(o options) error {
|
||||
return fmt.Errorf("find latest tag: %w", err)
|
||||
}
|
||||
|
||||
// A shallow clone with no tag found is ambiguous: either a genuine first
|
||||
// release, or the previous tags sit beyond the fetch depth — in which case
|
||||
// releasing would silently restart at X.Y.0. When a tag was found the
|
||||
// version math is correct regardless of shallowness.
|
||||
if lastTag == "" && !o.allowShallow {
|
||||
shallow, err := gitutil.IsShallow(repo)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check shallow clone: %w", err)
|
||||
}
|
||||
if shallow {
|
||||
return fmt.Errorf("no release tag found in a shallow clone — previous tags may be beyond the fetch depth; fetch full history (GIT_DEPTH: 0 in GitLab CI, fetch-depth: 0 in GitHub Actions, or git fetch --unshallow), or pass --allow-shallow if this is truly the first release")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Commit range ---
|
||||
var messages []string
|
||||
if lastTag == "" {
|
||||
@@ -594,6 +678,20 @@ func run(o options) error {
|
||||
filesToCommit = append(filesToCommit, relGradlePath)
|
||||
}
|
||||
|
||||
// pyproject.toml (opt-in via python.pyproject_toml / python.pyproject_tomls)
|
||||
for _, relPyprojectPath := range cfg.Python.EffectivePaths() {
|
||||
pyprojectPath := filepath.Join(absRepo, relPyprojectPath)
|
||||
currentPyVersion, err := pyproject.ReadVersion(pyprojectPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read pyproject version: %w", err)
|
||||
}
|
||||
if err := pyproject.WriteVersion(pyprojectPath, currentPyVersion, nextVersion); err != nil {
|
||||
return fmt.Errorf("update pyproject version: %w", err)
|
||||
}
|
||||
logDone("%s: %s → %s", relPyprojectPath, currentPyVersion, nextVersion)
|
||||
filesToCommit = append(filesToCommit, relPyprojectPath)
|
||||
}
|
||||
|
||||
// CHANGELOG.md
|
||||
changelogAbsPath := filepath.Join(absRepo, o.changelogFile)
|
||||
if err := changelog.Update(changelogAbsPath, nextTag, nextVersion, messages); err != nil {
|
||||
@@ -640,7 +738,10 @@ func run(o options) error {
|
||||
}
|
||||
logDone("pushed")
|
||||
|
||||
releaseNotes := notes.Generate(nextTag, messages)
|
||||
|
||||
if o.noRelease {
|
||||
notifyRelease(cfg, nextTag, releaseNotes)
|
||||
fmt.Printf("released %s\n", nextTag)
|
||||
return nil
|
||||
}
|
||||
@@ -652,15 +753,181 @@ func run(o options) error {
|
||||
}
|
||||
if publisher == nil {
|
||||
logWarn("no release provider configured — skipping release creation")
|
||||
fmt.Printf("released %s\n", nextTag)
|
||||
return nil
|
||||
} else {
|
||||
if err := publisher.CreateRelease(context.Background(), nextTag, releaseNotes); err != nil {
|
||||
return fmt.Errorf("create release: %w", err)
|
||||
}
|
||||
logDone("release created: %s", nextTag)
|
||||
}
|
||||
|
||||
releaseNotes := notes.Generate(nextTag, messages)
|
||||
if err := publisher.CreateRelease(context.Background(), nextTag, releaseNotes); err != nil {
|
||||
return fmt.Errorf("create release: %w", err)
|
||||
}
|
||||
logDone("release created: %s", nextTag)
|
||||
notifyRelease(cfg, nextTag, releaseNotes)
|
||||
fmt.Printf("released %s\n", nextTag)
|
||||
return nil
|
||||
}
|
||||
|
||||
// runCheck is the --check preflight: it validates everything a release needs
|
||||
// without writing or pushing anything, and reports every problem at once
|
||||
// instead of stopping at the first. Purely informational lines use logStep;
|
||||
// validated checks use logDone; failures use logWarn and fail the run.
|
||||
func runCheck(o options, cfg config.Config, absRepo string) error {
|
||||
logSection("check")
|
||||
|
||||
failed := 0
|
||||
fail := func(format string, args ...any) {
|
||||
logWarn(format, args...)
|
||||
failed++
|
||||
}
|
||||
|
||||
repo, err := gogit.PlainOpenWithOptions(absRepo, &gogit.PlainOpenOptions{DetectDotGit: true})
|
||||
if err != nil {
|
||||
return fmt.Errorf("open repository: %w", err)
|
||||
}
|
||||
|
||||
// --- branch resolution + pattern match ---
|
||||
var info branch.Info
|
||||
branchOK := false
|
||||
branchName := o.branchOverride
|
||||
var branchErr error
|
||||
if branchName == "" {
|
||||
branchName, branchErr = gitutil.CurrentBranch(repo)
|
||||
}
|
||||
if branchErr == nil {
|
||||
info, branchErr = branch.Parse(branchName, cfg.Git.BranchPattern)
|
||||
}
|
||||
if branchErr != nil {
|
||||
fail("branch: %v", branchErr)
|
||||
} else {
|
||||
info.TagPrefix = cfg.Git.TagPrefix
|
||||
branchOK = true
|
||||
logDone("branch: %s → major=%d, minor=%d", branchName, info.Major, info.Minor)
|
||||
}
|
||||
|
||||
// --- working tree ---
|
||||
if clean, err := gitutil.IsWorkingTreeClean(repo); err != nil {
|
||||
fail("working tree: %v", err)
|
||||
} else if !clean {
|
||||
fail("working tree has uncommitted changes")
|
||||
} else {
|
||||
logDone("working tree clean")
|
||||
}
|
||||
|
||||
// --- tag discovery + shallow clone ---
|
||||
if !branchOK {
|
||||
logStep("tag discovery skipped (branch unresolved)")
|
||||
} else if lastTag, _, err := gitutil.LatestTag(repo, info); err != nil {
|
||||
fail("tag discovery: %v", err)
|
||||
} else if lastTag != "" {
|
||||
logDone("latest tag: %s", lastTag)
|
||||
} else if shallow, err := gitutil.IsShallow(repo); err != nil {
|
||||
fail("shallow check: %v", err)
|
||||
} else if shallow && !o.allowShallow {
|
||||
fail("no release tag found in a shallow clone — previous tags may be beyond the fetch depth; fetch full history or pass --allow-shallow")
|
||||
} else if shallow {
|
||||
logStep("no previous tag in a shallow clone (--allow-shallow)")
|
||||
} else {
|
||||
logDone("no previous tag (first release)")
|
||||
}
|
||||
|
||||
// --- remote + push auth ---
|
||||
if remote, err := repo.Remote("origin"); err != nil {
|
||||
fail("remote origin: %v", err)
|
||||
} else {
|
||||
url := remote.Config().URLs[0]
|
||||
// The same parse the push transport performs — catches malformed
|
||||
// remote URLs (e.g. shell quoting accidents in CI set-url lines).
|
||||
if _, err := transport.NewEndpoint(url); err != nil {
|
||||
fail("remote origin URL: %v", err)
|
||||
} else {
|
||||
logDone("remote origin: %s", url)
|
||||
}
|
||||
switch {
|
||||
case cfg.GitLab.Token != "":
|
||||
logStep("push auth: HTTPS token (oauth2)")
|
||||
case strings.HasPrefix(url, "git@") || strings.HasPrefix(url, "ssh://"):
|
||||
logStep("push auth: SSH agent, git CLI fallback")
|
||||
default:
|
||||
logStep("push auth: git CLI (credential helpers, netrc)")
|
||||
}
|
||||
}
|
||||
|
||||
// --- version files ---
|
||||
anyPom := false
|
||||
for _, relPomPath := range cfg.Maven.EffectivePomPaths() {
|
||||
pomPath := filepath.Join(absRepo, relPomPath)
|
||||
_, statErr := os.Stat(pomPath)
|
||||
if errors.Is(statErr, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if statErr != nil {
|
||||
fail("%s: %v", relPomPath, statErr)
|
||||
continue
|
||||
}
|
||||
anyPom = true
|
||||
if v, err := maven.ReadVersion(pomPath); err != nil {
|
||||
fail("%s: %v", relPomPath, err)
|
||||
} else {
|
||||
logDone("%s: version %s", relPomPath, v)
|
||||
}
|
||||
}
|
||||
if !anyPom {
|
||||
logStep("no pom.xml — Maven version bump will be skipped")
|
||||
}
|
||||
for _, relPkgPath := range cfg.Node.EffectivePaths() {
|
||||
if v, err := node.ReadVersion(filepath.Join(absRepo, relPkgPath)); err != nil {
|
||||
fail("%s: %v", relPkgPath, err)
|
||||
} else {
|
||||
logDone("%s: version %s", relPkgPath, v)
|
||||
}
|
||||
}
|
||||
for _, relGradlePath := range cfg.Gradle.EffectiveBuildFiles() {
|
||||
if v, err := gradle.ReadVersion(filepath.Join(absRepo, relGradlePath)); err != nil {
|
||||
fail("%s: %v", relGradlePath, err)
|
||||
} else {
|
||||
logDone("%s: version %s", relGradlePath, v)
|
||||
}
|
||||
}
|
||||
for _, relPyprojectPath := range cfg.Python.EffectivePaths() {
|
||||
if v, err := pyproject.ReadVersion(filepath.Join(absRepo, relPyprojectPath)); err != nil {
|
||||
fail("%s: %v", relPyprojectPath, err)
|
||||
} else {
|
||||
logDone("%s: version %s", relPyprojectPath, v)
|
||||
}
|
||||
}
|
||||
|
||||
// --- release target (mirrors buildPublisher precedence) ---
|
||||
switch {
|
||||
case cfg.GitHub.Token != "" && cfg.GitHub.Repo != "":
|
||||
logDone("release target: GitHub (%s)", cfg.GitHub.Repo)
|
||||
case cfg.GitLab.URL != "" && cfg.GitLab.Project != "":
|
||||
if cfg.GitLab.Token == "" {
|
||||
fail("release target: GitLab configured but GITLAB_TOKEN not set")
|
||||
} else {
|
||||
logDone("release target: GitLab (%s, project %s)", cfg.GitLab.URL, cfg.GitLab.Project)
|
||||
}
|
||||
default:
|
||||
logStep("no release provider configured — release creation will be skipped")
|
||||
}
|
||||
|
||||
if failed > 0 {
|
||||
return fmt.Errorf("%d check(s) failed", failed)
|
||||
}
|
||||
fmt.Println("all checks passed")
|
||||
return nil
|
||||
}
|
||||
|
||||
// notifyRelease sends best-effort release notifications to every configured
|
||||
// target. Failures are logged as warnings, not errors — the release itself
|
||||
// already succeeded by the time this runs.
|
||||
func notifyRelease(cfg config.Config, tagName, releaseNotes string) {
|
||||
notifyCfg := notify.Config{
|
||||
SlackWebhookURL: cfg.Notify.SlackWebhookURL,
|
||||
TeamsWebhookURL: cfg.Notify.TeamsWebhookURL,
|
||||
GoogleChatWebhookURL: cfg.Notify.GoogleChatWebhookURL,
|
||||
TelegramBotToken: cfg.Notify.TelegramBotToken,
|
||||
TelegramChatID: cfg.Notify.TelegramChatID,
|
||||
WebhookURL: cfg.Notify.WebhookURL,
|
||||
}
|
||||
for _, err := range notify.SendAll(context.Background(), notifyCfg, notify.Message{Version: tagName, Notes: releaseNotes}) {
|
||||
logWarn("notification failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,6 +150,9 @@ func TestRunDetachedHead(t *testing.T) {
|
||||
// Detach HEAD
|
||||
head, _ := repo.Head()
|
||||
repo.Storer.SetReference(plumbing.NewHashReference(plumbing.HEAD, head.Hash()))
|
||||
for _, name := range []string{"CI_COMMIT_BRANCH", "CI_COMMIT_REF_NAME", "GITHUB_REF_NAME"} {
|
||||
t.Setenv(name, "")
|
||||
}
|
||||
|
||||
err := execCmd(t, "--dry-run", "--repo", dir) // no --branch
|
||||
if err == nil {
|
||||
@@ -157,6 +160,24 @@ func TestRunDetachedHead(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDetachedHeadCIBranchEnv(t *testing.T) {
|
||||
repo, dir := setupRepo(t)
|
||||
addFile(t, dir, "src.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("src.go")
|
||||
w.Commit("fix: patch something", &gogit.CommitOptions{Author: testSig()})
|
||||
head, _ := repo.Head()
|
||||
repo.Storer.SetReference(plumbing.NewHashReference(plumbing.HEAD, head.Hash()))
|
||||
for _, name := range []string{"CI_COMMIT_REF_NAME", "GITHUB_REF_NAME"} {
|
||||
t.Setenv(name, "")
|
||||
}
|
||||
t.Setenv("CI_COMMIT_BRANCH", "release/1.2")
|
||||
|
||||
if err := execCmd(t, "--dry-run", "--repo", dir); err != nil {
|
||||
t.Fatalf("detached HEAD with CI_COMMIT_BRANCH should succeed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBadConfig(t *testing.T) {
|
||||
_, dir := setupRepo(t)
|
||||
if err := os.WriteFile(filepath.Join(dir, ".releaser.yml"), []byte("{[invalid"), 0644); err != nil {
|
||||
@@ -484,6 +505,277 @@ func TestRunNoRelease(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── --check preflight ─────────────────────────────────────────────────────────
|
||||
|
||||
func TestRunCheckAllPass(t *testing.T) {
|
||||
repo, dir := setupRepoWithRemote(t)
|
||||
addFile(t, dir, "package.json", `{"name":"x","version":"1.2.0"}`)
|
||||
addFile(t, dir, "build.gradle", "version = '1.2.0'\n")
|
||||
addFile(t, dir, "pyproject.toml", "[project]\nname = \"x\"\nversion = \"1.2.0\"\n")
|
||||
addFile(t, dir, ".releaser.yml", `node:
|
||||
package_json: package.json
|
||||
gradle:
|
||||
build_file: build.gradle
|
||||
python:
|
||||
pyproject_toml: pyproject.toml
|
||||
`)
|
||||
commitAll(t, repo, dir, "chore: add version files")
|
||||
head, _ := repo.Head()
|
||||
repo.CreateTag("1.2.0", head.Hash(), nil)
|
||||
|
||||
t.Setenv("CI_SERVER_URL", "https://gitlab.example.com")
|
||||
t.Setenv("CI_PROJECT_ID", "42")
|
||||
t.Setenv("GITLAB_TOKEN", "test-token")
|
||||
|
||||
if err := execCmd(t, "--check", "--branch", "release/1.2", "--repo", dir); err != nil {
|
||||
t.Fatalf("--check should pass on a healthy repo: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckFailures(t *testing.T) {
|
||||
// One run accumulating several failures: unresolvable branch (detached,
|
||||
// no CI env), dirty tree + unreadable pom, missing configured version
|
||||
// files, no remote, GitLab target without token.
|
||||
repo, dir := setupRepo(t)
|
||||
addFile(t, dir, ".releaser.yml", `node:
|
||||
package_json: missing/package.json
|
||||
gradle:
|
||||
build_file: missing/build.gradle
|
||||
python:
|
||||
pyproject_toml: missing/pyproject.toml
|
||||
`)
|
||||
commitAll(t, repo, dir, "chore: config")
|
||||
head, _ := repo.Head()
|
||||
repo.Storer.SetReference(plumbing.NewHashReference(plumbing.HEAD, head.Hash()))
|
||||
for _, name := range []string{"CI_COMMIT_BRANCH", "CI_COMMIT_REF_NAME", "GITHUB_REF_NAME"} {
|
||||
t.Setenv(name, "")
|
||||
}
|
||||
// Invalid pom left uncommitted: dirties the tree and fails ReadVersion.
|
||||
addFile(t, dir, "pom.xml", "<not-a-pom/>")
|
||||
|
||||
t.Setenv("CI_SERVER_URL", "https://gitlab.example.com")
|
||||
t.Setenv("CI_PROJECT_ID", "42")
|
||||
t.Setenv("GITLAB_TOKEN", "")
|
||||
|
||||
err := execCmd(t, "--check", "--repo", dir)
|
||||
if err == nil {
|
||||
t.Fatal("expected --check to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckMalformedRemoteURL(t *testing.T) {
|
||||
// The shell-quoting accident from real life: quotes stored inside the URL.
|
||||
repo, dir := setupRepo(t)
|
||||
if _, err := repo.CreateRemote(&gitcfg.RemoteConfig{
|
||||
Name: "origin",
|
||||
URLs: []string{`"https://oauth2:${TOKEN}@example.com/group/proj.git"`},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := execCmd(t, "--check", "--branch", "release/1.2", "--repo", dir)
|
||||
if err == nil {
|
||||
t.Fatal("expected --check to flag the malformed remote URL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckSSHRemoteFirstRelease(t *testing.T) {
|
||||
repo, dir := setupRepo(t)
|
||||
if _, err := repo.CreateRemote(&gitcfg.RemoteConfig{
|
||||
Name: "origin",
|
||||
URLs: []string{"git@example.com:group/proj.git"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// SSH auth line + "no previous tag (first release)" + no release provider
|
||||
// + absent pom ("no pom.xml" note) — all informational, none failing.
|
||||
if err := execCmd(t, "--check", "--pom", "missing.xml", "--branch", "release/1.2", "--repo", dir); err != nil {
|
||||
t.Fatalf("--check on clean SSH-remote repo: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckShallowNoTag(t *testing.T) {
|
||||
repo, dir := setupRepoWithRemote(t)
|
||||
head, _ := repo.Head()
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "shallow"), []byte(head.Hash().String()+"\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := execCmd(t, "--check", "--branch", "release/1.2", "--repo", dir)
|
||||
if err == nil {
|
||||
t.Fatal("expected --check to fail for shallow clone with no tag")
|
||||
}
|
||||
|
||||
if err := execCmd(t, "--check", "--allow-shallow", "--branch", "release/1.2", "--repo", dir); err != nil {
|
||||
t.Fatalf("--check with --allow-shallow: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckShallowReadError(t *testing.T) {
|
||||
_, dir := setupRepoWithRemote(t)
|
||||
if err := os.Mkdir(filepath.Join(dir, ".git", "shallow"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := execCmd(t, "--check", "--branch", "release/1.2", "--repo", dir)
|
||||
if err == nil {
|
||||
t.Fatal("expected --check to fail when the shallow file is unreadable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckLatestTagFails(t *testing.T) {
|
||||
if os.Getuid() == 0 {
|
||||
t.Skip("skipping: chmod restrictions do not apply when running as root")
|
||||
}
|
||||
_, dir := setupRepoWithRemote(t)
|
||||
tagsDir := filepath.Join(dir, ".git", "refs", "tags")
|
||||
os.Chmod(tagsDir, 0000)
|
||||
defer os.Chmod(tagsDir, 0755)
|
||||
|
||||
err := execCmd(t, "--check", "--branch", "release/1.2", "--repo", dir)
|
||||
if err == nil {
|
||||
t.Fatal("expected --check to fail when tag discovery fails")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckWorktreeStatusFails(t *testing.T) {
|
||||
_, dir := setupRepoWithRemote(t)
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "index"), []byte("not a valid git index"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := execCmd(t, "--check", "--branch", "release/1.2", "--repo", dir)
|
||||
if err == nil {
|
||||
t.Fatal("expected --check to fail when the worktree status is unreadable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckNotARepo(t *testing.T) {
|
||||
err := execCmd(t, "--check", "--branch", "release/1.2", "--repo", t.TempDir())
|
||||
if err == nil {
|
||||
t.Fatal("expected --check to fail outside a git repository")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckPomStatError(t *testing.T) {
|
||||
_, dir := setupRepoWithRemote(t)
|
||||
|
||||
// Null byte in the path: os.Stat fails with EINVAL, not ErrNotExist.
|
||||
err := execCmd(t, "--check", "--pom", "p\x00om.xml", "--branch", "release/1.2", "--repo", dir)
|
||||
if err == nil {
|
||||
t.Fatal("expected --check to fail on a pom path stat error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckGitHubTarget(t *testing.T) {
|
||||
repo, dir := setupRepoWithRemote(t)
|
||||
addFile(t, dir, ".releaser.yml", `github:
|
||||
repo: owner/proj
|
||||
`)
|
||||
commitAll(t, repo, dir, "chore: config")
|
||||
t.Setenv("GITHUB_TOKEN", "gh-token")
|
||||
|
||||
if err := execCmd(t, "--check", "--branch", "release/1.2", "--repo", dir); err != nil {
|
||||
t.Fatalf("--check with GitHub target: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunShallowCloneNoTag(t *testing.T) {
|
||||
repo, dir := setupRepo(t)
|
||||
addFile(t, dir, "src.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("src.go")
|
||||
hash, _ := w.Commit("fix: patch something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
// Mark the clone shallow: no tag + shallow must refuse to release.
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "shallow"), []byte(hash.String()+"\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := execCmd(t, "--dry-run", "--branch", "release/1.2", "--repo", dir)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for shallow clone with no release tag")
|
||||
}
|
||||
|
||||
if err := execCmd(t, "--dry-run", "--allow-shallow", "--branch", "release/1.2", "--repo", dir); err != nil {
|
||||
t.Fatalf("--allow-shallow should bypass the shallow guard: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunShallowCheckFails(t *testing.T) {
|
||||
repo, dir := setupRepo(t)
|
||||
addFile(t, dir, "src.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("src.go")
|
||||
w.Commit("fix: patch something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
// Directory where the shallow file is expected → IsShallow read error.
|
||||
if err := os.Mkdir(filepath.Join(dir, ".git", "shallow"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := execCmd(t, "--dry-run", "--branch", "release/1.2", "--repo", dir)
|
||||
if err == nil {
|
||||
t.Fatal("expected error when the shallow check fails")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunShallowCloneWithTag(t *testing.T) {
|
||||
// A tag within the shallow history pins the version — shallowness is fine.
|
||||
repo, dir := setupRepo(t)
|
||||
initialHead, _ := repo.Head()
|
||||
repo.CreateTag("1.2.0", initialHead.Hash(), nil)
|
||||
addFile(t, dir, "src.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("src.go")
|
||||
hash, _ := w.Commit("fix: patch something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "shallow"), []byte(hash.String()+"\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := execCmd(t, "--dry-run", "--branch", "release/1.2", "--repo", dir); err != nil {
|
||||
t.Fatalf("shallow clone with a reachable tag should release: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCIDetachedHeadPush(t *testing.T) {
|
||||
repo, dir := setupRepoWithRemote(t)
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: patch something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
// Simulate a GitLab CI checkout: detached HEAD, no local branch ref,
|
||||
// branch name only available through the environment.
|
||||
head, _ := repo.Head()
|
||||
repo.Storer.SetReference(plumbing.NewHashReference(plumbing.HEAD, head.Hash()))
|
||||
if err := repo.Storer.RemoveReference(plumbing.NewBranchReferenceName("master")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("CI_COMMIT_BRANCH", "release/1.2")
|
||||
t.Setenv("CI_COMMIT_REF_NAME", "")
|
||||
t.Setenv("GITHUB_REF_NAME", "")
|
||||
t.Setenv("GITLAB_TOKEN", "test-token")
|
||||
|
||||
if err := execCmd(t, "--no-release", "--repo", dir); err != nil {
|
||||
t.Fatalf("CI-style detached run: %v", err)
|
||||
}
|
||||
|
||||
remote, err := repo.Remote("origin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bare, err := gogit.PlainOpen(remote.Config().URLs[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := bare.Reference(plumbing.NewBranchReferenceName("release/1.2"), false); err != nil {
|
||||
t.Errorf("release commit was not pushed to the remote branch: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunMissingToken(t *testing.T) {
|
||||
_, dir := setupRepoWithRemote(t)
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
@@ -526,6 +818,118 @@ func TestRunWithGitLab(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunWithNotify(t *testing.T) {
|
||||
var notified bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
notified = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, dir := setupRepoWithRemote(t)
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
repo, _ := gogit.PlainOpen(dir)
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: patch something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
t.Setenv("SLACK_WEBHOOK_URL", srv.URL)
|
||||
|
||||
err := execCmd(t, "--branch", "release/1.2", "--repo", dir)
|
||||
if err != nil {
|
||||
t.Fatalf("release with notify: unexpected error: %v", err)
|
||||
}
|
||||
if !notified {
|
||||
t.Error("expected Slack webhook to be called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunNotifyFailureDoesNotFailRelease(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, dir := setupRepoWithRemote(t)
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
repo, _ := gogit.PlainOpen(dir)
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: patch something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
t.Setenv("SLACK_WEBHOOK_URL", srv.URL)
|
||||
|
||||
old := os.Stderr
|
||||
r, wPipe, _ := os.Pipe()
|
||||
os.Stderr = wPipe
|
||||
|
||||
err := execCmd(t, "--branch", "release/1.2", "--repo", dir)
|
||||
|
||||
wPipe.Close()
|
||||
os.Stderr = old
|
||||
rawBytes, _ := io.ReadAll(r)
|
||||
output := string(rawBytes)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("a failed notification must not fail the release: %v", err)
|
||||
}
|
||||
if !strings.Contains(output, "notification failed") {
|
||||
t.Errorf("expected a notification-failed warning, got:\n%s", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunNoReleaseStillNotifies(t *testing.T) {
|
||||
var notified bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
notified = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, dir := setupRepoWithRemote(t)
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
repo, _ := gogit.PlainOpen(dir)
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: patch something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
t.Setenv("SLACK_WEBHOOK_URL", srv.URL)
|
||||
|
||||
err := execCmd(t, "--no-release", "--branch", "release/1.2", "--repo", dir)
|
||||
if err != nil {
|
||||
t.Fatalf("--no-release: unexpected error: %v", err)
|
||||
}
|
||||
if !notified {
|
||||
t.Error("expected Slack webhook to be called even with --no-release")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunNoPushSkipsNotify(t *testing.T) {
|
||||
var notified bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
notified = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, dir := setupRepo(t)
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
repo, _ := gogit.PlainOpen(dir)
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: patch something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
t.Setenv("SLACK_WEBHOOK_URL", srv.URL)
|
||||
|
||||
err := execCmd(t, "--no-push", "--branch", "release/1.2", "--repo", dir)
|
||||
if err != nil {
|
||||
t.Fatalf("--no-push: unexpected error: %v", err)
|
||||
}
|
||||
if notified {
|
||||
t.Error("--no-push must not send notifications — nothing was published")
|
||||
}
|
||||
}
|
||||
|
||||
// ── main() tests via exitFn ───────────────────────────────────────────────────
|
||||
|
||||
func TestMainSuccess(t *testing.T) {
|
||||
@@ -1101,6 +1505,7 @@ func TestPrintVerboseConfigBumpRulesAndNode(t *testing.T) {
|
||||
},
|
||||
Node: config.NodeConfig{PackageJSON: "package.json"},
|
||||
Gradle: config.GradleConfig{BuildFile: "build.gradle"},
|
||||
Python: config.PythonConfig{PyprojectTOML: "pyproject.toml"},
|
||||
}
|
||||
src := config.Sources{}
|
||||
|
||||
@@ -1122,6 +1527,9 @@ func TestPrintVerboseConfigBumpRulesAndNode(t *testing.T) {
|
||||
if !strings.Contains(output, "build.gradle") {
|
||||
t.Error("expected 'build.gradle' in output for gradle.paths")
|
||||
}
|
||||
if !strings.Contains(output, "pyproject.toml") {
|
||||
t.Error("expected 'pyproject.toml' in output for python.paths")
|
||||
}
|
||||
}
|
||||
|
||||
// ── node package.json handling ────────────────────────────────────────────────
|
||||
@@ -1321,3 +1729,143 @@ func TestRunGradleWriteVersionFails(t *testing.T) {
|
||||
t.Fatal("expected error when build.gradle is read-only")
|
||||
}
|
||||
}
|
||||
|
||||
// ── pyproject.toml handling ───────────────────────────────────────────────────
|
||||
|
||||
func writePyprojectFile(t *testing.T, dir, ver string) {
|
||||
t.Helper()
|
||||
content := fmt.Sprintf("[project]\nname = \"my-app\"\nversion = \"%s\"\n", ver)
|
||||
if err := os.WriteFile(filepath.Join(dir, "pyproject.toml"), []byte(content), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPyprojectVersionBump(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
repo, err := gogit.PlainInit(dir, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writePyprojectFile(t, dir, "0.0.0")
|
||||
commitAll(t, repo, dir, "chore: init")
|
||||
|
||||
os.WriteFile(filepath.Join(dir, ".releaser.yml"), []byte("python:\n pyproject_toml: \"pyproject.toml\"\n"), 0644)
|
||||
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
if err := execCmd(t, "--no-push", "--branch", "release/1.2", "--repo", dir); err != nil {
|
||||
t.Fatalf("pyproject version bump: unexpected error: %v", err)
|
||||
}
|
||||
|
||||
data, _ := os.ReadFile(filepath.Join(dir, "pyproject.toml"))
|
||||
if !strings.Contains(string(data), `version = "1.2.0"`) {
|
||||
t.Errorf("expected version 1.2.0 in pyproject.toml, got: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPyprojectPoetryVersionBump(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
repo, err := gogit.PlainInit(dir, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
content := "[tool.poetry]\nname = \"my-app\"\nversion = \"0.0.0\"\n"
|
||||
os.WriteFile(filepath.Join(dir, "pyproject.toml"), []byte(content), 0644)
|
||||
commitAll(t, repo, dir, "chore: init")
|
||||
|
||||
os.WriteFile(filepath.Join(dir, ".releaser.yml"), []byte("python:\n pyproject_toml: \"pyproject.toml\"\n"), 0644)
|
||||
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
if err := execCmd(t, "--no-push", "--branch", "release/1.2", "--repo", dir); err != nil {
|
||||
t.Fatalf("poetry version bump: unexpected error: %v", err)
|
||||
}
|
||||
|
||||
data, _ := os.ReadFile(filepath.Join(dir, "pyproject.toml"))
|
||||
if !strings.Contains(string(data), `version = "1.2.0"`) {
|
||||
t.Errorf("expected version 1.2.0 in pyproject.toml, got: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPyprojectOverrideFlag(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
repo, err := gogit.PlainInit(dir, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(dir, "sub"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
content := "[project]\nversion = \"0.0.0\"\n"
|
||||
os.WriteFile(filepath.Join(dir, "sub", "pyproject.toml"), []byte(content), 0644)
|
||||
commitAll(t, repo, dir, "chore: init")
|
||||
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
if err := execCmd(t, "--no-push", "--branch", "release/1.2", "--repo", dir, "--pyproject", "sub/pyproject.toml"); err != nil {
|
||||
t.Fatalf("--pyproject flag: unexpected error: %v", err)
|
||||
}
|
||||
|
||||
data, _ := os.ReadFile(filepath.Join(dir, "sub", "pyproject.toml"))
|
||||
if !strings.Contains(string(data), `version = "1.2.0"`) {
|
||||
t.Errorf("expected version 1.2.0, got: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPyprojectReadVersionFails(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
repo, err := gogit.PlainInit(dir, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// pyproject.toml with no version field
|
||||
os.WriteFile(filepath.Join(dir, "pyproject.toml"), []byte("[build-system]\nrequires=[]\n"), 0644)
|
||||
commitAll(t, repo, dir, "chore: init")
|
||||
|
||||
os.WriteFile(filepath.Join(dir, ".releaser.yml"), []byte("python:\n pyproject_toml: \"pyproject.toml\"\n"), 0644)
|
||||
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
if err := execCmd(t, "--branch", "release/1.2", "--repo", dir); err == nil {
|
||||
t.Fatal("expected error when pyproject.toml has no version")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPyprojectWriteVersionFails(t *testing.T) {
|
||||
if os.Getuid() == 0 {
|
||||
t.Skip("skipping: chmod restrictions do not apply when running as root")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
repo, err := gogit.PlainInit(dir, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writePyprojectFile(t, dir, "0.0.0")
|
||||
commitAll(t, repo, dir, "chore: init")
|
||||
|
||||
os.WriteFile(filepath.Join(dir, ".releaser.yml"), []byte("python:\n pyproject_toml: \"pyproject.toml\"\n"), 0644)
|
||||
|
||||
addFile(t, dir, "x.go", "// fix")
|
||||
w, _ := repo.Worktree()
|
||||
w.Add("x.go")
|
||||
w.Commit("fix: something", &gogit.CommitOptions{Author: testSig()})
|
||||
|
||||
os.Chmod(filepath.Join(dir, "pyproject.toml"), 0444)
|
||||
defer os.Chmod(filepath.Join(dir, "pyproject.toml"), 0644)
|
||||
|
||||
if err := execCmd(t, "--branch", "release/1.2", "--repo", dir); err == nil {
|
||||
t.Fatal("expected error when pyproject.toml is read-only")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ title: releaser
|
||||
|
||||
**CI-friendly release automation for GitFlow workflows using Conventional Commits.**
|
||||
|
||||
[Source code](https://git.k3nny.fr/k3nny/releaser) · [Releases](https://git.k3nny.fr/k3nny/releaser/releases)
|
||||
|
||||
Standard tools like `semantic-release` are designed for trunk-based development. In a GitFlow setup with versioned release branches (`release/1.1`, `release/1.2`), they either fail to respect the branch's version range or require brittle configuration.
|
||||
|
||||
`releaser` is built for this exact workflow: it reads the branch name to pin the `major.minor`, parses Conventional Commits to determine the patch increment, and handles everything from `pom.xml` / `package.json` update to GitLab/GitHub tag and release creation.
|
||||
|
||||
@@ -3,6 +3,35 @@ title: Changelog
|
||||
weight: 50
|
||||
---
|
||||
|
||||
## v1.10.0 — 2026-07-16
|
||||
|
||||
### Added
|
||||
|
||||
- **`--check` preflight** — validates branch, working tree, shallow clone, remote URL, push auth, version files, and release target without releasing; reports all problems at once, non-zero exit on failure
|
||||
- **Shallow clone detection** — refuses to release when the clone is shallow and no previous tag is found (tags may be beyond the fetch depth); `--allow-shallow` bypasses the guard for a genuine first release
|
||||
|
||||
## v1.9.0 — 2026-07-16
|
||||
|
||||
### Added
|
||||
|
||||
- **CI branch detection fallback** — on detached HEAD, the branch name falls back to `CI_COMMIT_BRANCH`, then `CI_COMMIT_REF_NAME` (GitLab CI), then `GITHUB_REF_NAME` (GitHub Actions); `--branch` is no longer required in CI
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Detached HEAD push** — go-git pushes silently skipped the branch update in detached CI checkouts (only the tag was pushed); the branch is now pushed from HEAD's commit hash
|
||||
|
||||
## v1.8.0 — 2026-07-12
|
||||
|
||||
### Added
|
||||
|
||||
- **Release notifications** — best-effort notification on release to Slack, Microsoft Teams, Google Chat, Telegram, and/or a generic JSON webhook via the new `notify` config section; every target is independently opt-in (config file or env var), and a failed notification never fails the release
|
||||
|
||||
## v1.7.0 — 2026-07-12
|
||||
|
||||
### Added
|
||||
|
||||
- **Python `pyproject.toml` support** — opt-in via `python.pyproject_toml` (single) or `python.pyproject_tomls` (list); reads `[project].version` (PEP 621) first, then `[tool.poetry].version`; original formatting preserved; `--pyproject <path>` CLI flag for one-off overrides
|
||||
|
||||
## v1.6.0 — 2026-07-11
|
||||
|
||||
### Added
|
||||
@@ -73,4 +102,4 @@ weight: 50
|
||||
|
||||
## v1.0 and earlier
|
||||
|
||||
See the [full CHANGELOG](https://git.k3nny.fr/releaser/src/branch/main/CHANGELOG.md) in the repository.
|
||||
See the [full CHANGELOG](https://git.k3nny.fr/k3nny/releaser/src/branch/main/CHANGELOG.md) in the repository.
|
||||
|
||||
@@ -29,6 +29,7 @@ release:
|
||||
- if: $CI_COMMIT_BRANCH =~ /^release\/.+$/
|
||||
variables:
|
||||
GITLAB_TOKEN: $RELEASE_TOKEN
|
||||
GIT_DEPTH: 0 # full history — shallow clones hide previous release tags
|
||||
script:
|
||||
- releaser
|
||||
artifacts:
|
||||
@@ -83,7 +84,7 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
curl -sSL https://git.k3nny.fr/releaser/releases/latest/download/releaser-linux-amd64 \
|
||||
curl -sSL https://git.k3nny.fr/k3nny/releaser/releases/latest/download/releaser-linux-amd64 \
|
||||
-o /usr/local/bin/releaser
|
||||
chmod +x /usr/local/bin/releaser
|
||||
releaser
|
||||
@@ -93,9 +94,41 @@ jobs:
|
||||
`fetch-depth: 0` is required. A shallow clone (`--depth 1`) hides the previous tag, causing `releaser` to treat every commit as the first release.
|
||||
{{< /hint >}}
|
||||
|
||||
## Preflight checks
|
||||
|
||||
`releaser --check` validates the release environment without releasing anything: branch resolution and pattern match, working tree state, shallow clone, remote URL parseability (the same parse the push performs — it catches shell-quoting accidents in `set-url` lines), which push auth would be used, configured version files, and the release target. All problems are reported at once, and the exit code is non-zero if any check fails.
|
||||
|
||||
Note the split with `--dry-run`: dry-run answers *"what version would be released?"* (it analyzes commits and computes the bump); `--check` answers *"will the release plumbing work?"* (everything dry-run never touches). Run `--check` in merge-request pipelines to catch broken CI configuration before it blocks a real release:
|
||||
|
||||
```yaml
|
||||
release:check:
|
||||
stage: test
|
||||
image: registry.example.com/releaser:latest
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
variables:
|
||||
GIT_DEPTH: 0
|
||||
script:
|
||||
- releaser --check --branch "release/0.0" # any pattern-matching name works for validation
|
||||
```
|
||||
|
||||
## Shallow clones
|
||||
|
||||
GitLab CI checks out a shallow clone by default (`GIT_DEPTH: 20`), and shallow clones hide any release tag beyond the fetch depth — tag discovery would silently restart versioning at `X.Y.0`. `releaser` detects this: when the clone is shallow **and** no previous release tag is found, it refuses to release and asks for full history.
|
||||
|
||||
Fix it by fetching full history (`GIT_DEPTH: 0` in GitLab CI, `fetch-depth: 0` in GitHub Actions, or `git fetch --unshallow`). If the project genuinely has no release tag yet, pass `--allow-shallow` to release anyway.
|
||||
|
||||
A shallow clone whose history does include the latest release tag is fine — the version calculation is unaffected, and `releaser` proceeds normally.
|
||||
|
||||
## Detached HEAD
|
||||
|
||||
In CI environments where `git checkout` leaves the repository in detached HEAD state, pass the branch name explicitly:
|
||||
CI runners check out a commit SHA, leaving the repository in detached HEAD state. `releaser` detects this and falls back to the branch name from the CI environment, in order:
|
||||
|
||||
1. `CI_COMMIT_BRANCH` (GitLab CI, branch pipelines)
|
||||
2. `CI_COMMIT_REF_NAME` (GitLab CI)
|
||||
3. `GITHUB_REF_NAME` (GitHub Actions)
|
||||
|
||||
So on branch pipelines no extra configuration is needed. To override the detected name (or on runners that set none of these variables), pass it explicitly:
|
||||
|
||||
```yaml
|
||||
script:
|
||||
|
||||
@@ -53,6 +53,14 @@ gradle: # opt-in — omit section t
|
||||
# - "build.gradle"
|
||||
# - "module-a/build.gradle"
|
||||
|
||||
python: # opt-in — omit section to skip
|
||||
# pyproject_toml: "pyproject.toml" # PEP 621 [project].version or [tool.poetry].version
|
||||
|
||||
# Monorepo: list overrides pyproject_toml.
|
||||
# pyproject_tomls:
|
||||
# - "pyproject.toml"
|
||||
# - "packages/cli/pyproject.toml"
|
||||
|
||||
gitlab:
|
||||
url: "https://gitlab.example.com" # or env CI_SERVER_URL
|
||||
token: "" # prefer env GITLAB_TOKEN
|
||||
@@ -61,6 +69,14 @@ gitlab:
|
||||
github:
|
||||
token: "" # prefer env GITHUB_TOKEN
|
||||
repo: "" # "owner/repo" format
|
||||
|
||||
notify: # opt-in — every field independent; failures are warnings, not errors
|
||||
# slack_webhook_url: "" # or env SLACK_WEBHOOK_URL
|
||||
# teams_webhook_url: "" # or env TEAMS_WEBHOOK_URL
|
||||
# google_chat_webhook_url: "" # or env GOOGLE_CHAT_WEBHOOK_URL
|
||||
# telegram_bot_token: "" # or env TELEGRAM_BOT_TOKEN (both required)
|
||||
# telegram_chat_id: "" # or env TELEGRAM_CHAT_ID
|
||||
# webhook_url: "" # generic {"version","notes"} JSON POST; or env RELEASER_WEBHOOK_URL
|
||||
```
|
||||
|
||||
{{< hint info >}}
|
||||
@@ -76,6 +92,11 @@ When both `github.*` and `gitlab.*` are configured, GitHub takes precedence.
|
||||
| `CI_PROJECT_ID` | GitLab project identifier (numeric) |
|
||||
| `CI_PROJECT_PATH` | GitLab project identifier (fallback) |
|
||||
| `GITHUB_TOKEN` | GitHub API auth |
|
||||
| `SLACK_WEBHOOK_URL` | Slack release notification |
|
||||
| `TEAMS_WEBHOOK_URL` | Microsoft Teams release notification |
|
||||
| `GOOGLE_CHAT_WEBHOOK_URL` | Google Chat release notification |
|
||||
| `TELEGRAM_BOT_TOKEN` / `TELEGRAM_CHAT_ID` | Telegram release notification (both required) |
|
||||
| `RELEASER_WEBHOOK_URL` | Generic webhook release notification |
|
||||
|
||||
## Config sources
|
||||
|
||||
@@ -128,6 +149,27 @@ node:
|
||||
- "packages/backend/package.json"
|
||||
```
|
||||
|
||||
## Python support
|
||||
|
||||
The `python` section is opt-in — if omitted, no `pyproject.toml` is touched. `releaser` reads `[project].version` (PEP 621) first; if not found it falls back to `[tool.poetry].version`. The original file formatting is preserved on write.
|
||||
|
||||
```yaml
|
||||
python:
|
||||
pyproject_toml: "pyproject.toml"
|
||||
```
|
||||
|
||||
Use `pyproject_tomls` for monorepos:
|
||||
|
||||
```yaml
|
||||
python:
|
||||
pyproject_tomls:
|
||||
- "pyproject.toml"
|
||||
- "packages/cli/pyproject.toml"
|
||||
- "packages/lib/pyproject.toml"
|
||||
```
|
||||
|
||||
The `--pyproject <path>` CLI flag sets a single path and clears `pyproject_tomls`.
|
||||
|
||||
## Gradle support
|
||||
|
||||
The `gradle` section is opt-in — if omitted, no build file is touched. Both Groovy DSL (`version = '1.2.3'`) and Kotlin DSL (`version = "1.2.3"`) are supported; the original quote style is preserved on write.
|
||||
@@ -148,3 +190,24 @@ gradle:
|
||||
```
|
||||
|
||||
The `--gradle <path>` CLI flag sets a single build file path and clears `build_files`.
|
||||
|
||||
## Notifications
|
||||
|
||||
The `notify` section is opt-in — every target is independent, and any combination may be configured at once. A notification failure is logged as a warning and never fails the release; notifications fire once the tag has been pushed, whether or not a GitLab/GitHub release is also created (`--no-release` still notifies; `--no-push` and `--no-commit` do not, since nothing was published).
|
||||
|
||||
```yaml
|
||||
notify:
|
||||
slack_webhook_url: "https://hooks.slack.com/services/..."
|
||||
teams_webhook_url: "https://outlook.office.com/webhook/..."
|
||||
google_chat_webhook_url: "https://chat.googleapis.com/v1/spaces/.../messages?key=..."
|
||||
telegram_bot_token: "123456:ABC-..."
|
||||
telegram_chat_id: "-1001234567890"
|
||||
webhook_url: "https://example.com/hooks/releaser"
|
||||
```
|
||||
|
||||
- **Slack** / **Google Chat** — a single `{"text": "..."}` incoming-webhook payload.
|
||||
- **Microsoft Teams** — a legacy O365 connector `MessageCard` payload (the format Teams incoming webhook URLs accept).
|
||||
- **Telegram** — `telegram_bot_token` and `telegram_chat_id` are both required; posts to the Bot API `sendMessage` endpoint as plain text (no `parse_mode`, since release notes come from free-form commit messages and aren't guaranteed to be valid Telegram Markdown).
|
||||
- **Generic webhook** — POSTs `{"version": "<tag>", "notes": "<release notes>"}` for any downstream consumer (n8n, Zapier, a custom receiver).
|
||||
|
||||
Each field also has an environment variable fallback — see [Environment variables](#environment-variables) above.
|
||||
|
||||
@@ -5,11 +5,11 @@ weight: 10
|
||||
|
||||
## Pre-built binaries
|
||||
|
||||
Download the latest release for your platform from the [Releases page](https://git.k3nny.fr/releaser/releases).
|
||||
Download the latest release for your platform from the [Releases page](https://git.k3nny.fr/k3nny/releaser/releases).
|
||||
|
||||
```bash
|
||||
# Linux (amd64)
|
||||
curl -sSL https://git.k3nny.fr/releaser/releases/download/v1.5.0/releaser-v1.5.0-linux-amd64 \
|
||||
curl -sSL https://git.k3nny.fr/k3nny/releaser/releases/download/v1.5.0/releaser-v1.5.0-linux-amd64 \
|
||||
-o /usr/local/bin/releaser
|
||||
chmod +x /usr/local/bin/releaser
|
||||
```
|
||||
@@ -19,13 +19,13 @@ Available platforms: `linux-amd64`, `linux-arm64`, `darwin-amd64`, `darwin-arm64
|
||||
## Docker
|
||||
|
||||
```bash
|
||||
docker pull git.k3nny.fr/releaser/releaser:latest
|
||||
docker pull git.k3nny.fr/k3nny/releaser/releaser:latest
|
||||
|
||||
# Run in the current repository
|
||||
docker run --rm \
|
||||
-v "$PWD:/repo" \
|
||||
-e GITLAB_TOKEN="$GITLAB_TOKEN" \
|
||||
git.k3nny.fr/releaser/releaser:latest
|
||||
git.k3nny.fr/k3nny/releaser/releaser:latest
|
||||
```
|
||||
|
||||
## Build from source
|
||||
@@ -33,7 +33,7 @@ docker run --rm \
|
||||
Requires Go 1.21+.
|
||||
|
||||
```bash
|
||||
git clone https://git.k3nny.fr/releaser/releaser.git
|
||||
git clone https://git.k3nny.fr/k3nny/releaser/releaser.git
|
||||
cd releaser
|
||||
go build -o /usr/local/bin/releaser ./cmd
|
||||
```
|
||||
|
||||
@@ -35,13 +35,16 @@ releaser --verbose --dry-run
|
||||
| Flag | Default | Description |
|
||||
|------|---------|-------------|
|
||||
| `--dry-run` | false | Print next version and exit without making any changes |
|
||||
| `--branch <name>` | auto-detected | Override branch name (useful in detached HEAD / CI) |
|
||||
| `--check` | false | Preflight: validate branch, working tree, remote URL, push auth, version files, and release target without releasing |
|
||||
| `--branch <name>` | auto-detected | Override branch name (detached HEAD falls back to `CI_COMMIT_BRANCH`, `CI_COMMIT_REF_NAME`, `GITHUB_REF_NAME`) |
|
||||
| `--branch-pattern <regex>` | `^(?:.*/)?release/(\d+)\.(\d+)$` | Override branch pattern (two capture groups: major, minor) |
|
||||
| `--tag-prefix <prefix>` | `""` | Prefix for version tags (e.g. `v` → `v1.2.3`) |
|
||||
| `--pom <path>` | `pom.xml` | Path to pom.xml relative to repo root |
|
||||
| `--gradle <path>` | — | Override `gradle.build_file` from config |
|
||||
| `--pyproject <path>` | — | Override `python.pyproject_toml` from config |
|
||||
| `--changelog-file <path>` | `CHANGELOG.md` | Path to changelog file |
|
||||
| `--release-env-file <path>` | `release.env` | Path for dotenv artifact; pass `""` to disable |
|
||||
| `--allow-shallow` | false | Proceed in a shallow clone even when no previous release tag is found |
|
||||
| `--no-commit` | false | Update version files but stop before committing |
|
||||
| `--no-push` | false | Commit and tag locally, skip push and release |
|
||||
| `--no-release` | false | Push branch and tag but skip release creation |
|
||||
|
||||
+8
-3
@@ -1,4 +1,4 @@
|
||||
baseURL = "/"
|
||||
baseURL = "https://releaser.k3nny.fr/"
|
||||
title = "releaser"
|
||||
theme = "geekdoc"
|
||||
|
||||
@@ -13,9 +13,14 @@ pygmentsCodeFences = true
|
||||
endLevel = 9
|
||||
|
||||
[params]
|
||||
geekdocRepo = "https://git.k3nny.fr/releaser"
|
||||
geekdocEditPath = "edit/main/docs/content"
|
||||
geekdocLogo = "images/releaser-logo-1024.png"
|
||||
geekdocRepo = "https://git.k3nny.fr/k3nny/releaser"
|
||||
geekdocEditPath = "_edit/main/docs"
|
||||
geekdocSearch = true
|
||||
geekdocMenuBundle = true
|
||||
geekdocBreadcrumb = false
|
||||
geekdocToC = true
|
||||
|
||||
[params.geekdocContentLicense]
|
||||
name = "Apache License 2.0"
|
||||
link = "https://git.k3nny.fr/k3nny/releaser/src/branch/main/LICENSE"
|
||||
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 7.0 KiB |
+115
-5
@@ -17,9 +17,11 @@ type Config struct {
|
||||
Git GitConfig `yaml:"git"`
|
||||
Maven MavenConfig `yaml:"maven"`
|
||||
Node NodeConfig `yaml:"node"`
|
||||
Gradle GradleConfig `yaml:"gradle"`
|
||||
GitLab GitLabConfig `yaml:"gitlab"`
|
||||
Gradle GradleConfig `yaml:"gradle"`
|
||||
Python PythonConfig `yaml:"python"`
|
||||
GitLab GitLabConfig `yaml:"gitlab"`
|
||||
GitHub GitHubConfig `yaml:"github"`
|
||||
Notify NotifyConfig `yaml:"notify"`
|
||||
}
|
||||
|
||||
type GitConfig struct {
|
||||
@@ -91,6 +93,23 @@ func (g GradleConfig) EffectiveBuildFiles() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
type PythonConfig struct {
|
||||
PyprojectTOML string `yaml:"pyproject_toml"` // single path (opt-in, no default)
|
||||
PyprojectTOMLs []string `yaml:"pyproject_tomls"` // multiple paths; overrides PyprojectTOML
|
||||
}
|
||||
|
||||
// EffectivePaths returns the list of pyproject.toml paths to process.
|
||||
// Returns nil when no python paths are configured (python processing is opt-in).
|
||||
func (p PythonConfig) EffectivePaths() []string {
|
||||
if len(p.PyprojectTOMLs) > 0 {
|
||||
return p.PyprojectTOMLs
|
||||
}
|
||||
if p.PyprojectTOML != "" {
|
||||
return []string{p.PyprojectTOML}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type GitLabConfig struct {
|
||||
URL string `yaml:"url"`
|
||||
Token string `yaml:"token"`
|
||||
@@ -102,6 +121,17 @@ type GitHubConfig struct {
|
||||
Repo string `yaml:"repo"` // "owner/repo"
|
||||
}
|
||||
|
||||
// NotifyConfig configures best-effort release notifications. Every field is
|
||||
// opt-in — a target is only used when its required fields are non-empty.
|
||||
type NotifyConfig struct {
|
||||
SlackWebhookURL string `yaml:"slack_webhook_url"`
|
||||
TeamsWebhookURL string `yaml:"teams_webhook_url"`
|
||||
GoogleChatWebhookURL string `yaml:"google_chat_webhook_url"`
|
||||
TelegramBotToken string `yaml:"telegram_bot_token"`
|
||||
TelegramChatID string `yaml:"telegram_chat_id"`
|
||||
WebhookURL string `yaml:"webhook_url"`
|
||||
}
|
||||
|
||||
func defaults() Config {
|
||||
return Config{
|
||||
Git: GitConfig{
|
||||
@@ -135,13 +165,21 @@ func defaultSources() Sources {
|
||||
"maven.pom_paths": "default",
|
||||
"node.package_json": "default",
|
||||
"node.package_jsons": "default",
|
||||
"gradle.build_file": "default",
|
||||
"gradle.build_files": "default",
|
||||
"gitlab.url": "default",
|
||||
"gradle.build_file": "default",
|
||||
"gradle.build_files": "default",
|
||||
"python.pyproject_toml": "default",
|
||||
"python.pyproject_tomls": "default",
|
||||
"gitlab.url": "default",
|
||||
"gitlab.token": "default",
|
||||
"gitlab.project": "default",
|
||||
"github.token": "default",
|
||||
"github.repo": "default",
|
||||
"notify.slack_webhook_url": "default",
|
||||
"notify.teams_webhook_url": "default",
|
||||
"notify.google_chat_webhook_url": "default",
|
||||
"notify.telegram_bot_token": "default",
|
||||
"notify.telegram_chat_id": "default",
|
||||
"notify.webhook_url": "default",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,6 +257,12 @@ func LoadWithSources(dir string) (Config, Sources, error) {
|
||||
if len(overlay.Gradle.BuildFiles) > 0 {
|
||||
src["gradle.build_files"] = "config file"
|
||||
}
|
||||
if overlay.Python.PyprojectTOML != "" {
|
||||
src["python.pyproject_toml"] = "config file"
|
||||
}
|
||||
if len(overlay.Python.PyprojectTOMLs) > 0 {
|
||||
src["python.pyproject_tomls"] = "config file"
|
||||
}
|
||||
if overlay.GitLab.URL != "" {
|
||||
src["gitlab.url"] = "config file"
|
||||
}
|
||||
@@ -234,6 +278,24 @@ func LoadWithSources(dir string) (Config, Sources, error) {
|
||||
if overlay.GitHub.Repo != "" {
|
||||
src["github.repo"] = "config file"
|
||||
}
|
||||
if overlay.Notify.SlackWebhookURL != "" {
|
||||
src["notify.slack_webhook_url"] = "config file"
|
||||
}
|
||||
if overlay.Notify.TeamsWebhookURL != "" {
|
||||
src["notify.teams_webhook_url"] = "config file"
|
||||
}
|
||||
if overlay.Notify.GoogleChatWebhookURL != "" {
|
||||
src["notify.google_chat_webhook_url"] = "config file"
|
||||
}
|
||||
if overlay.Notify.TelegramBotToken != "" {
|
||||
src["notify.telegram_bot_token"] = "config file"
|
||||
}
|
||||
if overlay.Notify.TelegramChatID != "" {
|
||||
src["notify.telegram_chat_id"] = "config file"
|
||||
}
|
||||
if overlay.Notify.WebhookURL != "" {
|
||||
src["notify.webhook_url"] = "config file"
|
||||
}
|
||||
|
||||
return cfg, src, nil
|
||||
}
|
||||
@@ -284,4 +346,52 @@ func (c *Config) ApplyEnvWithSources(src Sources) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.Notify.SlackWebhookURL == "" {
|
||||
if v := os.Getenv("SLACK_WEBHOOK_URL"); v != "" {
|
||||
c.Notify.SlackWebhookURL = v
|
||||
if src != nil {
|
||||
src["notify.slack_webhook_url"] = "env: SLACK_WEBHOOK_URL"
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.Notify.TeamsWebhookURL == "" {
|
||||
if v := os.Getenv("TEAMS_WEBHOOK_URL"); v != "" {
|
||||
c.Notify.TeamsWebhookURL = v
|
||||
if src != nil {
|
||||
src["notify.teams_webhook_url"] = "env: TEAMS_WEBHOOK_URL"
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.Notify.GoogleChatWebhookURL == "" {
|
||||
if v := os.Getenv("GOOGLE_CHAT_WEBHOOK_URL"); v != "" {
|
||||
c.Notify.GoogleChatWebhookURL = v
|
||||
if src != nil {
|
||||
src["notify.google_chat_webhook_url"] = "env: GOOGLE_CHAT_WEBHOOK_URL"
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.Notify.TelegramBotToken == "" {
|
||||
if v := os.Getenv("TELEGRAM_BOT_TOKEN"); v != "" {
|
||||
c.Notify.TelegramBotToken = v
|
||||
if src != nil {
|
||||
src["notify.telegram_bot_token"] = "env: TELEGRAM_BOT_TOKEN"
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.Notify.TelegramChatID == "" {
|
||||
if v := os.Getenv("TELEGRAM_CHAT_ID"); v != "" {
|
||||
c.Notify.TelegramChatID = v
|
||||
if src != nil {
|
||||
src["notify.telegram_chat_id"] = "env: TELEGRAM_CHAT_ID"
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.Notify.WebhookURL == "" {
|
||||
if v := os.Getenv("RELEASER_WEBHOOK_URL"); v != "" {
|
||||
c.Notify.WebhookURL = v
|
||||
if src != nil {
|
||||
src["notify.webhook_url"] = "env: RELEASER_WEBHOOK_URL"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,6 +338,141 @@ func TestLoadGradleBuildFilesSources(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPythonEffectivePaths(t *testing.T) {
|
||||
if got := (PythonConfig{}).EffectivePaths(); got != nil {
|
||||
t.Errorf("empty config: got %v, want nil", got)
|
||||
}
|
||||
if got := (PythonConfig{PyprojectTOML: "pyproject.toml"}).EffectivePaths(); len(got) != 1 || got[0] != "pyproject.toml" {
|
||||
t.Errorf("single path: got %v", got)
|
||||
}
|
||||
p := PythonConfig{PyprojectTOML: "pyproject.toml", PyprojectTOMLs: []string{"a/pyproject.toml", "b/pyproject.toml"}}
|
||||
if got := p.EffectivePaths(); len(got) != 2 || got[0] != "a/pyproject.toml" {
|
||||
t.Errorf("multi-path priority: got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadPythonSources(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
content := "python:\n pyproject_toml: \"pyproject.toml\"\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, filename), []byte(content), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, src, err := LoadWithSources(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if src["python.pyproject_toml"] != "config file" {
|
||||
t.Errorf("src[python.pyproject_toml] = %q, want %q", src["python.pyproject_toml"], "config file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadPythonPathsSources(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
content := "python:\n pyproject_tomls:\n - \"a/pyproject.toml\"\n - \"b/pyproject.toml\"\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, filename), []byte(content), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, src, err := LoadWithSources(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if src["python.pyproject_tomls"] != "config file" {
|
||||
t.Errorf("src[python.pyproject_tomls] = %q, want %q", src["python.pyproject_tomls"], "config file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadNotifySources(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
content := `
|
||||
notify:
|
||||
slack_webhook_url: "https://hooks.slack.example/x"
|
||||
teams_webhook_url: "https://outlook.office.example/y"
|
||||
google_chat_webhook_url: "https://chat.googleapis.example/z"
|
||||
telegram_bot_token: "bot-token"
|
||||
telegram_chat_id: "chat-1"
|
||||
webhook_url: "https://example.com/webhook"
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(dir, filename), []byte(content), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, src, err := LoadWithSources(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Notify.SlackWebhookURL != "https://hooks.slack.example/x" {
|
||||
t.Errorf("SlackWebhookURL = %q", cfg.Notify.SlackWebhookURL)
|
||||
}
|
||||
if cfg.Notify.TeamsWebhookURL != "https://outlook.office.example/y" {
|
||||
t.Errorf("TeamsWebhookURL = %q", cfg.Notify.TeamsWebhookURL)
|
||||
}
|
||||
if cfg.Notify.GoogleChatWebhookURL != "https://chat.googleapis.example/z" {
|
||||
t.Errorf("GoogleChatWebhookURL = %q", cfg.Notify.GoogleChatWebhookURL)
|
||||
}
|
||||
if cfg.Notify.TelegramBotToken != "bot-token" {
|
||||
t.Errorf("TelegramBotToken = %q", cfg.Notify.TelegramBotToken)
|
||||
}
|
||||
if cfg.Notify.TelegramChatID != "chat-1" {
|
||||
t.Errorf("TelegramChatID = %q", cfg.Notify.TelegramChatID)
|
||||
}
|
||||
if cfg.Notify.WebhookURL != "https://example.com/webhook" {
|
||||
t.Errorf("WebhookURL = %q", cfg.Notify.WebhookURL)
|
||||
}
|
||||
|
||||
wantConfigFile := []string{
|
||||
"notify.slack_webhook_url", "notify.teams_webhook_url", "notify.google_chat_webhook_url",
|
||||
"notify.telegram_bot_token", "notify.telegram_chat_id", "notify.webhook_url",
|
||||
}
|
||||
for _, key := range wantConfigFile {
|
||||
if got := src[key]; got != "config file" {
|
||||
t.Errorf("src[%q] = %q, want %q", key, got, "config file")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyEnvWithSourcesNotify(t *testing.T) {
|
||||
t.Setenv("SLACK_WEBHOOK_URL", "https://hooks.slack.example/env")
|
||||
t.Setenv("TEAMS_WEBHOOK_URL", "https://outlook.office.example/env")
|
||||
t.Setenv("GOOGLE_CHAT_WEBHOOK_URL", "https://chat.googleapis.example/env")
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "env-bot-token")
|
||||
t.Setenv("TELEGRAM_CHAT_ID", "env-chat-id")
|
||||
t.Setenv("RELEASER_WEBHOOK_URL", "https://example.com/env-webhook")
|
||||
|
||||
cfg := defaults()
|
||||
src := defaultSources()
|
||||
cfg.ApplyEnvWithSources(src)
|
||||
|
||||
cases := []struct {
|
||||
got, want, srcKey, wantSrc string
|
||||
}{
|
||||
{cfg.Notify.SlackWebhookURL, "https://hooks.slack.example/env", "notify.slack_webhook_url", "env: SLACK_WEBHOOK_URL"},
|
||||
{cfg.Notify.TeamsWebhookURL, "https://outlook.office.example/env", "notify.teams_webhook_url", "env: TEAMS_WEBHOOK_URL"},
|
||||
{cfg.Notify.GoogleChatWebhookURL, "https://chat.googleapis.example/env", "notify.google_chat_webhook_url", "env: GOOGLE_CHAT_WEBHOOK_URL"},
|
||||
{cfg.Notify.TelegramBotToken, "env-bot-token", "notify.telegram_bot_token", "env: TELEGRAM_BOT_TOKEN"},
|
||||
{cfg.Notify.TelegramChatID, "env-chat-id", "notify.telegram_chat_id", "env: TELEGRAM_CHAT_ID"},
|
||||
{cfg.Notify.WebhookURL, "https://example.com/env-webhook", "notify.webhook_url", "env: RELEASER_WEBHOOK_URL"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if c.got != c.want {
|
||||
t.Errorf("got %q, want %q", c.got, c.want)
|
||||
}
|
||||
if src[c.srcKey] != c.wantSrc {
|
||||
t.Errorf("src[%q] = %q, want %q", c.srcKey, src[c.srcKey], c.wantSrc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyEnvNotifyDoesNotOverwrite(t *testing.T) {
|
||||
t.Setenv("SLACK_WEBHOOK_URL", "https://hooks.slack.example/env")
|
||||
|
||||
cfg := defaults()
|
||||
cfg.Notify.SlackWebhookURL = "https://hooks.slack.example/config"
|
||||
cfg.ApplyEnv()
|
||||
|
||||
if cfg.Notify.SlackWebhookURL != "https://hooks.slack.example/config" {
|
||||
t.Errorf("SlackWebhookURL overwritten: got %q", cfg.Notify.SlackWebhookURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadPartialOverride(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
// Only override tag_prefix — commit_message should keep its default
|
||||
|
||||
+58
-13
@@ -42,17 +42,43 @@ func IsWorkingTreeClean(repo *gogit.Repository) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// ciBranchEnvVars are checked in order when HEAD is detached: CI runners
|
||||
// (GitLab, GitHub Actions) check out a commit SHA, so the branch name is only
|
||||
// available through the environment. CI_COMMIT_BRANCH is unset on tag and
|
||||
// merge-request pipelines, where CI_COMMIT_REF_NAME would hold a non-branch
|
||||
// ref — a name that fails branch pattern parsing with a clear error.
|
||||
var ciBranchEnvVars = []string{"CI_COMMIT_BRANCH", "CI_COMMIT_REF_NAME", "GITHUB_REF_NAME"}
|
||||
|
||||
// CurrentBranch returns the short branch name from HEAD.
|
||||
// Returns an error when HEAD is detached (common in CI pipelines).
|
||||
// When HEAD is detached (common in CI pipelines), it falls back to the CI
|
||||
// environment variables that carry the branch name, and errors only when
|
||||
// none of them is set.
|
||||
func CurrentBranch(repo *gogit.Repository) (string, error) {
|
||||
head, err := repo.Head()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read HEAD: %w", err)
|
||||
}
|
||||
if !head.Name().IsBranch() {
|
||||
return "", fmt.Errorf("HEAD is detached — use --branch to specify the release branch")
|
||||
if head.Name().IsBranch() {
|
||||
return head.Name().Short(), nil
|
||||
}
|
||||
return head.Name().Short(), nil
|
||||
for _, name := range ciBranchEnvVars {
|
||||
if v := os.Getenv(name); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("HEAD is detached and no CI branch variable is set (%s) — use --branch to specify the release branch", strings.Join(ciBranchEnvVars, ", "))
|
||||
}
|
||||
|
||||
// IsShallow reports whether the repository is a shallow clone. In shallow CI
|
||||
// checkouts (GitLab CI defaults to GIT_DEPTH: 20) release tags beyond the
|
||||
// fetch depth are invisible to LatestTag, which would silently restart
|
||||
// versioning at X.Y.0.
|
||||
func IsShallow(repo *gogit.Repository) (bool, error) {
|
||||
roots, err := repo.Storer.Shallow()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return len(roots) > 0, nil
|
||||
}
|
||||
|
||||
type tagCandidate struct {
|
||||
@@ -269,6 +295,21 @@ func isSSHURL(u string) bool {
|
||||
return strings.HasPrefix(u, "git@") || strings.HasPrefix(u, "ssh://")
|
||||
}
|
||||
|
||||
// pushRefSpecs builds the refspecs for the release push. The branch source is
|
||||
// HEAD's commit hash rather than refs/heads/<branch>: in CI checkouts HEAD is
|
||||
// detached and the local branch ref does not exist, in which case go-git
|
||||
// silently skips the branch update and pushes only the tag.
|
||||
func pushRefSpecs(repo *gogit.Repository, branchName, tagName string) ([]gitconfig.RefSpec, error) {
|
||||
head, err := repo.Head()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read HEAD: %w", err)
|
||||
}
|
||||
return []gitconfig.RefSpec{
|
||||
gitconfig.RefSpec(fmt.Sprintf("%s:refs/heads/%s", head.Hash(), branchName)),
|
||||
gitconfig.RefSpec(fmt.Sprintf("refs/tags/%s:refs/tags/%s", tagName, tagName)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func pushWithSSHAgent(repo *gogit.Repository, branchName, tagName string) error {
|
||||
auth, err := newSSHAgentAuth("git")
|
||||
if err != nil {
|
||||
@@ -280,12 +321,14 @@ func pushWithSSHAgent(repo *gogit.Repository, branchName, tagName string) error
|
||||
return fmt.Errorf("remote origin not found: %w", err)
|
||||
}
|
||||
|
||||
refSpecs, err := pushRefSpecs(repo, branchName, tagName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
opts := &gogit.PushOptions{
|
||||
RefSpecs: []gitconfig.RefSpec{
|
||||
gitconfig.RefSpec(fmt.Sprintf("refs/heads/%s:refs/heads/%s", branchName, branchName)),
|
||||
gitconfig.RefSpec(fmt.Sprintf("refs/tags/%s:refs/tags/%s", tagName, tagName)),
|
||||
},
|
||||
Auth: auth,
|
||||
RefSpecs: refSpecs,
|
||||
Auth: auth,
|
||||
}
|
||||
|
||||
if err := remote.Push(opts); err != nil && !errors.Is(err, gogit.NoErrAlreadyUpToDate) {
|
||||
@@ -300,11 +343,13 @@ func pushWithGoGit(repo *gogit.Repository, branchName, tagName, token string) er
|
||||
return fmt.Errorf("remote origin not found: %w", err)
|
||||
}
|
||||
|
||||
refSpecs, err := pushRefSpecs(repo, branchName, tagName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
opts := &gogit.PushOptions{
|
||||
RefSpecs: []gitconfig.RefSpec{
|
||||
gitconfig.RefSpec(fmt.Sprintf("refs/heads/%s:refs/heads/%s", branchName, branchName)),
|
||||
gitconfig.RefSpec(fmt.Sprintf("refs/tags/%s:refs/tags/%s", tagName, tagName)),
|
||||
},
|
||||
RefSpecs: refSpecs,
|
||||
Auth: &githttp.BasicAuth{
|
||||
Username: "oauth2",
|
||||
Password: token,
|
||||
|
||||
@@ -157,16 +157,29 @@ func TestCurrentBranch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentBranchDetached(t *testing.T) {
|
||||
repo, dir := newTestRepo(t)
|
||||
addCommit(t, repo, dir, "chore: init", "initial")
|
||||
// clearCIBranchEnv unsets the CI branch variables so detached-HEAD tests
|
||||
// behave the same on a developer machine and inside an actual CI job.
|
||||
func clearCIBranchEnv(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, name := range ciBranchEnvVars {
|
||||
t.Setenv(name, "")
|
||||
}
|
||||
}
|
||||
|
||||
// Detach HEAD by replacing the symbolic ref with a hash ref
|
||||
func detachHead(t *testing.T, repo *gogit.Repository) {
|
||||
t.Helper()
|
||||
head, _ := repo.Head()
|
||||
detached := plumbing.NewHashReference(plumbing.HEAD, head.Hash())
|
||||
if err := repo.Storer.SetReference(detached); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentBranchDetached(t *testing.T) {
|
||||
repo, dir := newTestRepo(t)
|
||||
addCommit(t, repo, dir, "chore: init", "initial")
|
||||
detachHead(t, repo)
|
||||
clearCIBranchEnv(t)
|
||||
|
||||
_, err := CurrentBranch(repo)
|
||||
if err == nil {
|
||||
@@ -174,6 +187,109 @@ func TestCurrentBranchDetached(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentBranchDetachedCIFallback(t *testing.T) {
|
||||
repo, dir := newTestRepo(t)
|
||||
addCommit(t, repo, dir, "chore: init", "initial")
|
||||
detachHead(t, repo)
|
||||
|
||||
t.Run("CI_COMMIT_BRANCH wins over CI_COMMIT_REF_NAME", func(t *testing.T) {
|
||||
clearCIBranchEnv(t)
|
||||
t.Setenv("CI_COMMIT_BRANCH", "release/1.2")
|
||||
t.Setenv("CI_COMMIT_REF_NAME", "release/9.9")
|
||||
|
||||
name, err := CurrentBranch(repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if name != "release/1.2" {
|
||||
t.Errorf("got %q, want release/1.2", name)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("CI_COMMIT_REF_NAME when CI_COMMIT_BRANCH unset", func(t *testing.T) {
|
||||
clearCIBranchEnv(t)
|
||||
t.Setenv("CI_COMMIT_REF_NAME", "release/3.4")
|
||||
|
||||
name, err := CurrentBranch(repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if name != "release/3.4" {
|
||||
t.Errorf("got %q, want release/3.4", name)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GITHUB_REF_NAME as last resort", func(t *testing.T) {
|
||||
clearCIBranchEnv(t)
|
||||
t.Setenv("GITHUB_REF_NAME", "release/5.6")
|
||||
|
||||
name, err := CurrentBranch(repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if name != "release/5.6" {
|
||||
t.Errorf("got %q, want release/5.6", name)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("env ignored when HEAD is on a branch", func(t *testing.T) {
|
||||
attached, attachedDir := newTestRepo(t)
|
||||
addCommit(t, attached, attachedDir, "chore: init", "initial")
|
||||
clearCIBranchEnv(t)
|
||||
t.Setenv("CI_COMMIT_BRANCH", "release/9.9")
|
||||
|
||||
name, err := CurrentBranch(attached)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if name == "release/9.9" {
|
||||
t.Error("CI env var must not override an attached HEAD")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── IsShallow ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func TestIsShallow(t *testing.T) {
|
||||
repo, dir := newTestRepo(t)
|
||||
hash := addCommit(t, repo, dir, "chore: init", "initial")
|
||||
|
||||
shallow, err := IsShallow(repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if shallow {
|
||||
t.Error("full clone reported as shallow")
|
||||
}
|
||||
|
||||
// A shallow clone is marked by .git/shallow listing the boundary commits.
|
||||
shallowPath := filepath.Join(dir, ".git", "shallow")
|
||||
if err := os.WriteFile(shallowPath, []byte(hash.String()+"\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shallow, err = IsShallow(repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !shallow {
|
||||
t.Error("clone with .git/shallow not reported as shallow")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsShallowReadError(t *testing.T) {
|
||||
repo, dir := newTestRepo(t)
|
||||
addCommit(t, repo, dir, "chore: init", "initial")
|
||||
|
||||
// A directory where the shallow file is expected: Open succeeds but
|
||||
// reading fails, exercising the Storer.Shallow error path.
|
||||
if err := os.Mkdir(filepath.Join(dir, ".git", "shallow"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := IsShallow(repo); err == nil {
|
||||
t.Error("expected error when shallow file is unreadable")
|
||||
}
|
||||
}
|
||||
|
||||
// ── LatestTag ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func TestLatestTagNoTags(t *testing.T) {
|
||||
@@ -702,6 +818,64 @@ func TestPushWithBareRemote(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushDetachedHeadUpdatesRemoteBranch(t *testing.T) {
|
||||
// Regression: in a CI checkout HEAD is detached and refs/heads/<branch>
|
||||
// does not exist locally — go-git silently skipped the branch refspec and
|
||||
// pushed only the tag. The push must carry HEAD's commit to the branch.
|
||||
remoteDir := t.TempDir()
|
||||
if _, err := gogit.PlainInit(remoteDir, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
repo, dir := newTestRepo(t)
|
||||
hash := addCommit(t, repo, dir, "fix: something", "v1")
|
||||
addTag(t, repo, "v1.2.1")
|
||||
detachHead(t, repo)
|
||||
if err := repo.Storer.RemoveReference(plumbing.NewBranchReferenceName("master")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := repo.CreateRemote(&gitconfig.RemoteConfig{
|
||||
Name: "origin",
|
||||
URLs: []string{remoteDir},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := Push(repo, "release/1.2", "v1.2.1", "dummy-token"); err != nil {
|
||||
t.Fatalf("Push from detached HEAD failed: %v", err)
|
||||
}
|
||||
|
||||
bare, err := gogit.PlainOpen(remoteDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref, err := bare.Reference(plumbing.NewBranchReferenceName("release/1.2"), false)
|
||||
if err != nil {
|
||||
t.Fatalf("remote branch ref missing after push: %v", err)
|
||||
}
|
||||
if ref.Hash() != hash {
|
||||
t.Errorf("remote branch at %s, want HEAD commit %s", ref.Hash(), hash)
|
||||
}
|
||||
if _, err := bare.Reference(plumbing.NewTagReferenceName("v1.2.1"), false); err != nil {
|
||||
t.Errorf("remote tag ref missing after push: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushWithGoGitUnbornHead(t *testing.T) {
|
||||
// Repo with a remote but no commits: pushRefSpecs fails reading HEAD.
|
||||
repo, _ := newTestRepo(t)
|
||||
if _, err := repo.CreateRemote(&gitconfig.RemoteConfig{
|
||||
Name: "origin",
|
||||
URLs: []string{t.TempDir()},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pushWithGoGit(repo, "master", "v1.0.0", "some-token"); err == nil {
|
||||
t.Error("expected error for unborn HEAD")
|
||||
}
|
||||
}
|
||||
|
||||
// ── IsWorkingTreeClean: w.Status() error path ────────────────────────────────
|
||||
|
||||
func TestIsWorkingTreeCleanCorruptIndex(t *testing.T) {
|
||||
@@ -1040,6 +1214,26 @@ func TestPushWithGoGitNoRemote(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushWithSSHAgentUnbornHead(t *testing.T) {
|
||||
orig := newSSHAgentAuth
|
||||
newSSHAgentAuth = func(user string) (*gitssh.PublicKeysCallback, error) {
|
||||
return &gitssh.PublicKeysCallback{User: user}, nil
|
||||
}
|
||||
defer func() { newSSHAgentAuth = orig }()
|
||||
|
||||
// Repo with a remote but no commits: pushRefSpecs fails reading HEAD.
|
||||
repo, _ := newTestRepo(t)
|
||||
if _, err := repo.CreateRemote(&gitconfig.RemoteConfig{
|
||||
Name: "origin",
|
||||
URLs: []string{t.TempDir()},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pushWithSSHAgent(repo, "master", "v1.0.0"); err == nil {
|
||||
t.Error("expected error for unborn HEAD")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushWithGoGitPushFails(t *testing.T) {
|
||||
repo, dir := newTestRepo(t)
|
||||
addCommit(t, repo, dir, "fix: c1", "v1")
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// googleChatPayload matches the Google Chat Incoming Webhook contract: a
|
||||
// single "text" field.
|
||||
type googleChatPayload struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func newGoogleChatPayload(msg Message) googleChatPayload {
|
||||
return googleChatPayload{Text: fmt.Sprintf("*Released %s*\n\n%s", msg.Version, msg.Notes)}
|
||||
}
|
||||
|
||||
func sendGoogleChat(ctx context.Context, webhookURL string, msg Message) error {
|
||||
return postJSON(ctx, webhookURL, newGoogleChatPayload(msg))
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSendGoogleChat(t *testing.T) {
|
||||
var got googleChatPayload
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewDecoder(r.Body).Decode(&got) //nolint:errcheck
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := sendGoogleChat(context.Background(), srv.URL, Message{Version: "v1.2.3", Notes: "- feat: y"}); err != nil {
|
||||
t.Fatalf("sendGoogleChat: %v", err)
|
||||
}
|
||||
if !strings.Contains(got.Text, "v1.2.3") || !strings.Contains(got.Text, "feat: y") {
|
||||
t.Errorf("payload text = %q", got.Text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendGoogleChatError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := sendGoogleChat(context.Background(), srv.URL, Message{Version: "v1.0.0"}); err == nil {
|
||||
t.Fatal("expected error for 400 response")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// Package notify sends best-effort release notifications to chat and webhook targets.
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Message is the content of a release notification, shared across all targets.
|
||||
type Message struct {
|
||||
Version string // tag name, e.g. "v1.2.3"
|
||||
Notes string // release notes body
|
||||
}
|
||||
|
||||
// Config holds the destination for every supported notification target.
|
||||
// Every field is opt-in — a target is skipped when its required fields are empty.
|
||||
type Config struct {
|
||||
SlackWebhookURL string
|
||||
TeamsWebhookURL string
|
||||
GoogleChatWebhookURL string
|
||||
TelegramBotToken string
|
||||
TelegramChatID string
|
||||
WebhookURL string
|
||||
}
|
||||
|
||||
var httpClient = &http.Client{Timeout: 15 * time.Second}
|
||||
|
||||
// SendAll sends msg to every target configured in cfg. Each target is attempted
|
||||
// independently — a failure on one does not prevent the others from being tried.
|
||||
// Returns one error per failed target, or nil if every configured target
|
||||
// succeeded (or none were configured).
|
||||
func SendAll(ctx context.Context, cfg Config, msg Message) []error {
|
||||
var errs []error
|
||||
|
||||
if cfg.SlackWebhookURL != "" {
|
||||
if err := sendSlack(ctx, cfg.SlackWebhookURL, msg); err != nil {
|
||||
errs = append(errs, fmt.Errorf("slack: %w", err))
|
||||
}
|
||||
}
|
||||
if cfg.TeamsWebhookURL != "" {
|
||||
if err := sendTeams(ctx, cfg.TeamsWebhookURL, msg); err != nil {
|
||||
errs = append(errs, fmt.Errorf("teams: %w", err))
|
||||
}
|
||||
}
|
||||
if cfg.GoogleChatWebhookURL != "" {
|
||||
if err := sendGoogleChat(ctx, cfg.GoogleChatWebhookURL, msg); err != nil {
|
||||
errs = append(errs, fmt.Errorf("google chat: %w", err))
|
||||
}
|
||||
}
|
||||
if cfg.TelegramBotToken != "" && cfg.TelegramChatID != "" {
|
||||
if err := sendTelegram(ctx, cfg.TelegramBotToken, cfg.TelegramChatID, msg); err != nil {
|
||||
errs = append(errs, fmt.Errorf("telegram: %w", err))
|
||||
}
|
||||
}
|
||||
if cfg.WebhookURL != "" {
|
||||
if err := sendWebhook(ctx, cfg.WebhookURL, msg); err != nil {
|
||||
errs = append(errs, fmt.Errorf("webhook: %w", err))
|
||||
}
|
||||
}
|
||||
|
||||
return errs
|
||||
}
|
||||
|
||||
// postJSON POSTs payload as JSON to url and treats any non-2xx response as an error.
|
||||
func postJSON(ctx context.Context, url string, payload any) error {
|
||||
body, _ := json.Marshal(payload) // payload fields are always plain strings — Marshal cannot fail here
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("returned status %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// FuzzMessagePayloads verifies that building a notification payload never
|
||||
// panics on arbitrary version/notes strings, no matter the target — release
|
||||
// notes are generated from free-form commit messages and end up embedded in
|
||||
// every payload below.
|
||||
func FuzzMessagePayloads(f *testing.F) {
|
||||
f.Add("v1.2.3", "release notes")
|
||||
f.Add("", "")
|
||||
f.Add("v1.0.0", "* markdown _weird_ [chars] `code` <html> & \"quotes\"")
|
||||
f.Add("tag\nwith\nnewline", "notes\x00with\xffbinary")
|
||||
f.Add("v1.0.0", strings.Repeat("x", 10000))
|
||||
|
||||
f.Fuzz(func(t *testing.T, version, notes string) {
|
||||
msg := Message{Version: version, Notes: notes}
|
||||
_, _ = json.Marshal(newSlackPayload(msg))
|
||||
_, _ = json.Marshal(newGoogleChatPayload(msg))
|
||||
_, _ = json.Marshal(newTeamsPayload(msg))
|
||||
_, _ = json.Marshal(newTelegramPayload("chat-id", msg))
|
||||
_, _ = json.Marshal(newWebhookPayload(msg))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// alwaysFailTransport returns an error for every request.
|
||||
type alwaysFailTransport struct{}
|
||||
|
||||
func (alwaysFailTransport) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
return nil, &testTransportError{"connection refused"}
|
||||
}
|
||||
|
||||
type testTransportError struct{ msg string }
|
||||
|
||||
func (e *testTransportError) Error() string { return e.msg }
|
||||
|
||||
func TestPostJSONSuccess(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := postJSON(context.Background(), srv.URL, map[string]string{"a": "b"}); err != nil {
|
||||
t.Fatalf("postJSON: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostJSONBadURL(t *testing.T) {
|
||||
err := postJSON(context.Background(), "http://\x00bad", map[string]string{"a": "b"})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid URL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostJSONRequestFails(t *testing.T) {
|
||||
orig := httpClient
|
||||
httpClient = &http.Client{Transport: alwaysFailTransport{}}
|
||||
defer func() { httpClient = orig }()
|
||||
|
||||
err := postJSON(context.Background(), "http://127.0.0.1:1", map[string]string{"a": "b"})
|
||||
if err == nil {
|
||||
t.Fatal("expected error when HTTP request fails")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostJSONNon2xx(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
err := postJSON(context.Background(), srv.URL, map[string]string{"a": "b"})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for 500 response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendAllNoneConfigured(t *testing.T) {
|
||||
errs := SendAll(context.Background(), Config{}, Message{Version: "v1.0.0"})
|
||||
if errs != nil {
|
||||
t.Fatalf("expected no errors, got %v", errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendAllAllSucceed(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
origBase := telegramAPIBase
|
||||
telegramAPIBase = srv.URL
|
||||
defer func() { telegramAPIBase = origBase }()
|
||||
|
||||
cfg := Config{
|
||||
SlackWebhookURL: srv.URL,
|
||||
TeamsWebhookURL: srv.URL,
|
||||
GoogleChatWebhookURL: srv.URL,
|
||||
TelegramBotToken: "tok",
|
||||
TelegramChatID: "123",
|
||||
WebhookURL: srv.URL,
|
||||
}
|
||||
errs := SendAll(context.Background(), cfg, Message{Version: "v1.0.0", Notes: "notes"})
|
||||
if errs != nil {
|
||||
t.Fatalf("expected no errors, got %v", errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendAllAllFail(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
origBase := telegramAPIBase
|
||||
telegramAPIBase = srv.URL
|
||||
defer func() { telegramAPIBase = origBase }()
|
||||
|
||||
cfg := Config{
|
||||
SlackWebhookURL: srv.URL,
|
||||
TeamsWebhookURL: srv.URL,
|
||||
GoogleChatWebhookURL: srv.URL,
|
||||
TelegramBotToken: "tok",
|
||||
TelegramChatID: "123",
|
||||
WebhookURL: srv.URL,
|
||||
}
|
||||
errs := SendAll(context.Background(), cfg, Message{Version: "v1.0.0"})
|
||||
if len(errs) != 5 {
|
||||
t.Fatalf("expected 5 errors, got %d: %v", len(errs), errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendAllTelegramRequiresBothFields(t *testing.T) {
|
||||
calls := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
origBase := telegramAPIBase
|
||||
telegramAPIBase = srv.URL
|
||||
defer func() { telegramAPIBase = origBase }()
|
||||
|
||||
// Only bot token set — chat ID missing — Telegram target must be skipped.
|
||||
errs := SendAll(context.Background(), Config{TelegramBotToken: "tok"}, Message{Version: "v1.0.0"})
|
||||
if errs != nil {
|
||||
t.Fatalf("expected no errors, got %v", errs)
|
||||
}
|
||||
if calls != 0 {
|
||||
t.Fatalf("expected telegram to be skipped, got %d calls", calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// slackPayload matches the Slack Incoming Webhook contract: a single "text"
|
||||
// field, interpreted as Slack mrkdwn.
|
||||
type slackPayload struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func newSlackPayload(msg Message) slackPayload {
|
||||
return slackPayload{Text: fmt.Sprintf("*Released %s*\n\n%s", msg.Version, msg.Notes)}
|
||||
}
|
||||
|
||||
func sendSlack(ctx context.Context, webhookURL string, msg Message) error {
|
||||
return postJSON(ctx, webhookURL, newSlackPayload(msg))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSendSlack(t *testing.T) {
|
||||
var got slackPayload
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||
t.Errorf("Content-Type = %q", ct)
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&got) //nolint:errcheck
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := sendSlack(context.Background(), srv.URL, Message{Version: "v1.2.3", Notes: "- fix: x"}); err != nil {
|
||||
t.Fatalf("sendSlack: %v", err)
|
||||
}
|
||||
if !strings.Contains(got.Text, "v1.2.3") || !strings.Contains(got.Text, "fix: x") {
|
||||
t.Errorf("payload text = %q", got.Text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendSlackError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := sendSlack(context.Background(), srv.URL, Message{Version: "v1.0.0"}); err == nil {
|
||||
t.Fatal("expected error for 403 response")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// teamsPayload is a Microsoft Teams "Incoming Webhook" O365 connector card
|
||||
// (MessageCard schema) — the format Teams webhook URLs still accept.
|
||||
type teamsPayload struct {
|
||||
Type string `json:"@type"`
|
||||
Context string `json:"@context"`
|
||||
Summary string `json:"summary"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func newTeamsPayload(msg Message) teamsPayload {
|
||||
title := fmt.Sprintf("Released %s", msg.Version)
|
||||
return teamsPayload{
|
||||
Type: "MessageCard",
|
||||
Context: "http://schema.org/extensions",
|
||||
Summary: title,
|
||||
Title: title,
|
||||
Text: msg.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func sendTeams(ctx context.Context, webhookURL string, msg Message) error {
|
||||
return postJSON(ctx, webhookURL, newTeamsPayload(msg))
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSendTeams(t *testing.T) {
|
||||
var got teamsPayload
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewDecoder(r.Body).Decode(&got) //nolint:errcheck
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := sendTeams(context.Background(), srv.URL, Message{Version: "v1.2.3", Notes: "- fix: z"}); err != nil {
|
||||
t.Fatalf("sendTeams: %v", err)
|
||||
}
|
||||
if got.Type != "MessageCard" {
|
||||
t.Errorf("Type = %q, want MessageCard", got.Type)
|
||||
}
|
||||
if !strings.Contains(got.Title, "v1.2.3") || !strings.Contains(got.Summary, "v1.2.3") {
|
||||
t.Errorf("Title/Summary = %q/%q, want to contain v1.2.3", got.Title, got.Summary)
|
||||
}
|
||||
if !strings.Contains(got.Text, "fix: z") {
|
||||
t.Errorf("Text = %q", got.Text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendTeamsError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := sendTeams(context.Background(), srv.URL, Message{Version: "v1.0.0"}); err == nil {
|
||||
t.Fatal("expected error for 503 response")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// telegramAPIBase is the Telegram Bot API host. Overridden in tests.
|
||||
var telegramAPIBase = "https://api.telegram.org"
|
||||
|
||||
// telegramPayload matches the Telegram Bot API sendMessage contract. Notes
|
||||
// are sent as plain text (no parse_mode) — release notes come from arbitrary
|
||||
// commit messages and are not guaranteed to be valid Telegram Markdown/HTML,
|
||||
// and a malformed entity makes the whole request fail with a 400.
|
||||
type telegramPayload struct {
|
||||
ChatID string `json:"chat_id"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func newTelegramPayload(chatID string, msg Message) telegramPayload {
|
||||
return telegramPayload{
|
||||
ChatID: chatID,
|
||||
Text: fmt.Sprintf("Released %s\n\n%s", msg.Version, msg.Notes),
|
||||
}
|
||||
}
|
||||
|
||||
func sendTelegram(ctx context.Context, botToken, chatID string, msg Message) error {
|
||||
url := fmt.Sprintf("%s/bot%s/sendMessage", telegramAPIBase, botToken)
|
||||
return postJSON(ctx, url, newTelegramPayload(chatID, msg))
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSendTelegram(t *testing.T) {
|
||||
var got telegramPayload
|
||||
var path string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
json.NewDecoder(r.Body).Decode(&got) //nolint:errcheck
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
orig := telegramAPIBase
|
||||
telegramAPIBase = srv.URL
|
||||
defer func() { telegramAPIBase = orig }()
|
||||
|
||||
if err := sendTelegram(context.Background(), "bot-token", "chat-1", Message{Version: "v1.2.3", Notes: "notes body"}); err != nil {
|
||||
t.Fatalf("sendTelegram: %v", err)
|
||||
}
|
||||
if !strings.Contains(path, "bot-token") {
|
||||
t.Errorf("path = %q, want to contain bot token", path)
|
||||
}
|
||||
if got.ChatID != "chat-1" {
|
||||
t.Errorf("ChatID = %q, want chat-1", got.ChatID)
|
||||
}
|
||||
if !strings.Contains(got.Text, "v1.2.3") || !strings.Contains(got.Text, "notes body") {
|
||||
t.Errorf("Text = %q", got.Text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendTelegramError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
orig := telegramAPIBase
|
||||
telegramAPIBase = srv.URL
|
||||
defer func() { telegramAPIBase = orig }()
|
||||
|
||||
if err := sendTelegram(context.Background(), "bot-token", "chat-1", Message{Version: "v1.0.0"}); err == nil {
|
||||
t.Fatal("expected error for 400 response")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package notify
|
||||
|
||||
import "context"
|
||||
|
||||
// webhookPayload is a generic JSON envelope for arbitrary API webhooks
|
||||
// (e.g. n8n, Zapier, a custom receiver) that don't follow a chat-app schema.
|
||||
type webhookPayload struct {
|
||||
Version string `json:"version"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
func newWebhookPayload(msg Message) webhookPayload {
|
||||
return webhookPayload(msg)
|
||||
}
|
||||
|
||||
func sendWebhook(ctx context.Context, url string, msg Message) error {
|
||||
return postJSON(ctx, url, newWebhookPayload(msg))
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSendWebhook(t *testing.T) {
|
||||
var got webhookPayload
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewDecoder(r.Body).Decode(&got) //nolint:errcheck
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := sendWebhook(context.Background(), srv.URL, Message{Version: "v1.2.3", Notes: "notes body"}); err != nil {
|
||||
t.Fatalf("sendWebhook: %v", err)
|
||||
}
|
||||
if got.Version != "v1.2.3" {
|
||||
t.Errorf("Version = %q, want v1.2.3", got.Version)
|
||||
}
|
||||
if got.Notes != "notes body" {
|
||||
t.Errorf("Notes = %q, want %q", got.Notes, "notes body")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendWebhookError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if err := sendWebhook(context.Background(), srv.URL, Message{Version: "v1.0.0"}); err == nil {
|
||||
t.Fatal("expected error for 500 response")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package pyproject
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// sectionRe matches a TOML section from its header to the next header (or end of file).
|
||||
// TOML section headers always appear at the start of a line, so \n[ is a reliable boundary.
|
||||
var (
|
||||
projectSectionRe = regexp.MustCompile(`(?s)\[project\].*?(?:\n\[|\z)`)
|
||||
poetrySectionRe = regexp.MustCompile(`(?s)\[tool\.poetry\].*?(?:\n\[|\z)`)
|
||||
)
|
||||
|
||||
// versionLineRe matches version = "x.y.z" on its own line inside a section.
|
||||
var versionLineRe = regexp.MustCompile(`(?m)^version\s*=\s*"([^"]+)"`)
|
||||
|
||||
// ReadVersion returns the project version from a pyproject.toml file.
|
||||
// It checks [project] (PEP 621) first, then [tool.poetry] (Poetry).
|
||||
func ReadVersion(path string) (string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
content := string(data)
|
||||
for _, sectionRe := range []*regexp.Regexp{projectSectionRe, poetrySectionRe} {
|
||||
section := sectionRe.FindString(content)
|
||||
if section == "" {
|
||||
continue
|
||||
}
|
||||
m := versionLineRe.FindStringSubmatch(section)
|
||||
if m != nil {
|
||||
return m[1], nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no version found in %s", path)
|
||||
}
|
||||
|
||||
// WriteVersion replaces the project version in a pyproject.toml file in-place.
|
||||
// oldVersion must match what ReadVersion returned.
|
||||
func WriteVersion(path, oldVersion, newVersion string) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
updated, ok := replaceVersion(string(data), oldVersion, newVersion)
|
||||
if !ok {
|
||||
return fmt.Errorf("version %q not found in %s", oldVersion, path)
|
||||
}
|
||||
return os.WriteFile(path, []byte(updated), 0644)
|
||||
}
|
||||
|
||||
// replaceVersion finds and replaces the version in the first [project] or [tool.poetry]
|
||||
// section that contains it. Returns the updated content and true on success.
|
||||
// regexp.QuoteMeta is used so version strings with dots or specials are safe.
|
||||
func replaceVersion(content, oldVersion, newVersion string) (string, bool) {
|
||||
re := regexp.MustCompile(`(?m)^(version\s*=\s*)"` + regexp.QuoteMeta(oldVersion) + `"`)
|
||||
for _, sectionRe := range []*regexp.Regexp{projectSectionRe, poetrySectionRe} {
|
||||
loc := sectionRe.FindStringIndex(content)
|
||||
if loc == nil {
|
||||
continue
|
||||
}
|
||||
section := content[loc[0]:loc[1]]
|
||||
m := re.FindStringSubmatchIndex(section)
|
||||
if m == nil {
|
||||
continue
|
||||
}
|
||||
// m[0]:m[1] = full match; m[2]:m[3] = group 1 (prefix "version = ")
|
||||
newSection := section[:m[0]] + section[m[2]:m[3]] + `"` + newVersion + `"` + section[m[1]:]
|
||||
return content[:loc[0]] + newSection + content[loc[1]:], true
|
||||
}
|
||||
return content, false
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package pyproject
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const pyprojectPEP621 = `[project]
|
||||
name = "my-package"
|
||||
version = "1.2.3"
|
||||
description = "A test package"
|
||||
dependencies = ["requests>=2.0", "click>=8.0"]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
`
|
||||
|
||||
const pyprojectPoetry = `[tool.poetry]
|
||||
name = "my-package"
|
||||
version = "1.2.3"
|
||||
description = "A test package"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.9"
|
||||
requests = "^2.0"
|
||||
`
|
||||
|
||||
const pyprojectBoth = `[project]
|
||||
name = "my-package"
|
||||
version = "1.2.3"
|
||||
|
||||
[tool.poetry]
|
||||
name = "my-package"
|
||||
version = "1.2.3"
|
||||
`
|
||||
|
||||
const pyprojectBuildSystemFirst = `[build-system]
|
||||
requires = ["hatchling"]
|
||||
|
||||
[project]
|
||||
name = "my-package"
|
||||
version = "1.2.3"
|
||||
`
|
||||
|
||||
func writePyproject(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "pyproject.toml")
|
||||
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// ── ReadVersion ───────────────────────────────────────────────────────────────
|
||||
|
||||
func TestReadVersionPEP621(t *testing.T) {
|
||||
got, err := ReadVersion(writePyproject(t, pyprojectPEP621))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != "1.2.3" {
|
||||
t.Errorf("got %q, want 1.2.3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadVersionPoetry(t *testing.T) {
|
||||
got, err := ReadVersion(writePyproject(t, pyprojectPoetry))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != "1.2.3" {
|
||||
t.Errorf("got %q, want 1.2.3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadVersionPEP621TakesPrecedence(t *testing.T) {
|
||||
// When both [project] and [tool.poetry] are present, [project] wins.
|
||||
got, err := ReadVersion(writePyproject(t, pyprojectBoth))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != "1.2.3" {
|
||||
t.Errorf("got %q, want 1.2.3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadVersionBuildSystemIgnored(t *testing.T) {
|
||||
// version under [build-system] must not be returned.
|
||||
got, err := ReadVersion(writePyproject(t, pyprojectBuildSystemFirst))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != "1.2.3" {
|
||||
t.Errorf("got %q, want 1.2.3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadVersionMissingFile(t *testing.T) {
|
||||
_, err := ReadVersion(filepath.Join(t.TempDir(), "pyproject.toml"))
|
||||
if err == nil {
|
||||
t.Error("expected error for missing file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadVersionNoVersion(t *testing.T) {
|
||||
_, err := ReadVersion(writePyproject(t, `[build-system]
|
||||
requires = ["hatchling"]
|
||||
`))
|
||||
if err == nil {
|
||||
t.Error("expected error when no version is found")
|
||||
}
|
||||
}
|
||||
|
||||
// ── WriteVersion ──────────────────────────────────────────────────────────────
|
||||
|
||||
func TestWriteVersionPEP621(t *testing.T) {
|
||||
path := writePyproject(t, pyprojectPEP621)
|
||||
if err := WriteVersion(path, "1.2.3", "1.2.4"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
data, _ := os.ReadFile(path)
|
||||
s := string(data)
|
||||
if !strings.Contains(s, `version = "1.2.4"`) {
|
||||
t.Errorf("expected updated version; got:\n%s", s)
|
||||
}
|
||||
// build-system section must not be touched
|
||||
if strings.Contains(s, `"hatchling>=1.2.4"`) {
|
||||
t.Error("build-system section was incorrectly modified")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteVersionPoetry(t *testing.T) {
|
||||
path := writePyproject(t, pyprojectPoetry)
|
||||
if err := WriteVersion(path, "1.2.3", "1.2.4"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
data, _ := os.ReadFile(path)
|
||||
if !strings.Contains(string(data), `version = "1.2.4"`) {
|
||||
t.Errorf("expected updated version; got:\n%s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteVersionBothSectionsUpdatesProject(t *testing.T) {
|
||||
path := writePyproject(t, pyprojectBoth)
|
||||
if err := WriteVersion(path, "1.2.3", "1.2.4"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
data, _ := os.ReadFile(path)
|
||||
s := string(data)
|
||||
// [project] version updated
|
||||
if !strings.Contains(s, `[project]`) || strings.Index(s, `version = "1.2.4"`) > strings.Index(s, `[tool.poetry]`) {
|
||||
t.Error("expected [project] version to be updated first")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteVersionMissingFile(t *testing.T) {
|
||||
err := WriteVersion(filepath.Join(t.TempDir(), "pyproject.toml"), "1.0.0", "1.0.1")
|
||||
if err == nil {
|
||||
t.Error("expected error for missing file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteVersionNotFound(t *testing.T) {
|
||||
path := writePyproject(t, pyprojectPEP621)
|
||||
err := WriteVersion(path, "9.9.9", "9.9.10")
|
||||
if err == nil {
|
||||
t.Error("expected error when old version not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteVersionReadOnly(t *testing.T) {
|
||||
if os.Getuid() == 0 {
|
||||
t.Skip("skipping: chmod restrictions do not apply when running as root")
|
||||
}
|
||||
path := writePyproject(t, pyprojectPEP621)
|
||||
os.Chmod(path, 0444)
|
||||
defer os.Chmod(path, 0644)
|
||||
if err := WriteVersion(path, "1.2.3", "1.2.4"); err == nil {
|
||||
t.Error("expected error writing to read-only file")
|
||||
}
|
||||
}
|
||||
|
||||
// ── replaceVersion ────────────────────────────────────────────────────────────
|
||||
|
||||
func TestReplaceVersionNotFound(t *testing.T) {
|
||||
content := `[build-system]
|
||||
requires = ["hatchling"]
|
||||
`
|
||||
got, ok := replaceVersion(content, "1.0.0", "1.0.1")
|
||||
if ok {
|
||||
t.Error("expected ok=false when no matching section")
|
||||
}
|
||||
if got != content {
|
||||
t.Error("content should be unchanged when not found")
|
||||
}
|
||||
}
|
||||
|
||||
// ── fuzz ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
// FuzzReadVersion verifies ReadVersion never panics on arbitrary file content.
|
||||
func FuzzReadVersion(f *testing.F) {
|
||||
f.Add(pyprojectPEP621)
|
||||
f.Add(pyprojectPoetry)
|
||||
f.Add(pyprojectBoth)
|
||||
f.Add(`[project]` + "\n")
|
||||
f.Add("")
|
||||
f.Add("\x00\xff")
|
||||
|
||||
f.Fuzz(func(t *testing.T, content string) {
|
||||
path := filepath.Join(t.TempDir(), "pyproject.toml")
|
||||
os.WriteFile(path, []byte(content), 0644) //nolint:errcheck
|
||||
ReadVersion(path) //nolint:errcheck
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzWriteVersion verifies WriteVersion never panics on arbitrary content or version strings.
|
||||
func FuzzWriteVersion(f *testing.F) {
|
||||
f.Add(pyprojectPEP621, "1.2.3", "1.2.4")
|
||||
f.Add(pyprojectPoetry, "1.2.3", "1.2.4")
|
||||
f.Add(pyprojectBoth, "1.2.3", "1.2.4")
|
||||
f.Add("", "1.0.0", "1.0.1")
|
||||
f.Add(`[project]`+"\n"+"version = \"1.0.0\"\n", "1.0.0", "1.0.1")
|
||||
|
||||
f.Fuzz(func(t *testing.T, content, oldVersion, newVersion string) {
|
||||
path := filepath.Join(t.TempDir(), "pyproject.toml")
|
||||
os.WriteFile(path, []byte(content), 0644) //nolint:errcheck
|
||||
WriteVersion(path, oldVersion, newVersion) //nolint:errcheck
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user