Compare commits
185 Commits
3cbb3f3406
...
v0.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
| b96262eb0c | |||
| 5a0bc6f78b | |||
| f27abcb53e | |||
| 6c7b77970b | |||
| 80d88a0352 | |||
| c0a3f55f12 | |||
| 7216fb5f98 | |||
| 6b0b8ce6de | |||
| 8112a001d2 | |||
| 8552f92ddb | |||
| c09c7a2ac7 | |||
| 54cc6baf95 | |||
| 7eebbbbfc3 | |||
| c8eb64adec | |||
| 9333573cd8 | |||
| d44ff1260d | |||
| f059fef320 | |||
| 7555d3e6c9 | |||
| 750632f80e | |||
| 90559fe01b | |||
| b49c1f379e | |||
| cd828dc06d | |||
| c9879cffa2 | |||
| c0cc50b127 | |||
| f837871b77 | |||
| d06b62efe2 | |||
| 926b74bc0b | |||
| fdce017aff | |||
| 8350cbf9c9 | |||
| 02896b6e12 | |||
| 3a99536f9c | |||
| fa34cbaff3 | |||
| 3e516d0ac1 | |||
| f99fb59cd4 | |||
| dbfae9ea81 | |||
| f33023f8e0 | |||
| 5847f40ab5 | |||
| f656a2d2e9 | |||
| 578503c1ca | |||
| 39dca97f9b | |||
| 283f62813f | |||
| f89bdf7edf | |||
| 86c1da2cf5 | |||
| e43df4416e | |||
| 9b51447acd | |||
| 80ec9e3fb4 | |||
| 86b73db71f | |||
| 52e3a389bb | |||
| cf9e451ecd | |||
| 6376ef23f1 | |||
| 7d92c477c2 | |||
| 6eec022bb0 | |||
| 15dd58f5ac | |||
| df064bd1d3 | |||
| 42569b4af2 | |||
| 50d3573257 | |||
| 39196a525c | |||
| cfd8ba7cb2 | |||
| 182da397e3 | |||
| a3e993d95a | |||
| 33e10635b6 | |||
| 618a7c9dd3 | |||
| 41e58ef894 | |||
| 29e1bab228 | |||
| ca571aca4f | |||
| ff90510c38 | |||
| db9e24f7dc | |||
| 4bb480f990 | |||
| d51a0ada5e | |||
| f2124b3b7b | |||
| ae0e4a0263 | |||
| c7942210d5 | |||
| c339872bfe | |||
| e030794969 | |||
| 10964bebd4 | |||
| e84d28d249 | |||
| 8314e0e4d8 | |||
| b6a490cefc | |||
| 2e0d302178 | |||
| 95599e96f6 | |||
| 1eb1cc6491 | |||
| edd670e62f | |||
| c8fa8ef85f | |||
| eee979db7b | |||
| b80d4ee071 | |||
| 40068af1bf | |||
| 6397d41517 | |||
| b3b959ce77 | |||
| f80970a9d4 | |||
| eed95896f4 | |||
| 45dd827dda | |||
| c5f925c949 | |||
| 368043984e | |||
| cabc56b134 | |||
| 1c41f7a0d1 | |||
| 30fe4fe206 | |||
| 89981abbe5 | |||
| 9086306498 | |||
| 3974a4686a | |||
| 1dfa774164 | |||
| 9d2ca66a79 | |||
| 02050016c1 | |||
| ff83af1e34 | |||
| 56e652aae3 | |||
| 1498ec7498 | |||
| f53354be5f | |||
| 89c5b2c1fd | |||
| 1ebd45c975 | |||
| 8bac90a9a8 | |||
| 5848307948 | |||
| 1cad13649e | |||
| 136a97fb6c | |||
| 1de7555b3e | |||
| 0c7129ab75 | |||
| 8c742cd11d | |||
| 7afc0de092 | |||
| 2a246990fe | |||
| f9f0349eca | |||
| f4a32dae73 | |||
| a4b1b6d5d2 | |||
| f55f6331cb | |||
| 8ff8efa4a2 | |||
| 6de0428675 | |||
| 9e480f0b4f | |||
| 60175d6690 | |||
| 5e60fe3113 | |||
| dab4fdf2b3 | |||
| e6def4ed7b | |||
| ceb7e2847a | |||
| 55333b08ae | |||
| 21294404d7 | |||
| c6a5db8aeb | |||
| d970aac709 | |||
| 579daa9485 | |||
| a67a00a733 | |||
| c9afc8dd12 | |||
| 0eec4a30ed | |||
| 3e9b5c1b99 | |||
| 08093124af | |||
| 12e866a94a | |||
| b240e3cfa9 | |||
| a0cb466395 | |||
| e4be7fa699 | |||
| 85b2b39fb6 | |||
| e146a5c61e | |||
| 536a57916f | |||
| af1a76a2f7 | |||
| 1af589dbe8 | |||
| f07545810b | |||
| bb5a8288e6 | |||
| f4d9cf20ec | |||
| ce3a85e3e6 | |||
| 791152370c | |||
| 1d06ba019c | |||
| 685cd8a64d | |||
| 6b777dd861 | |||
| 8b417760c6 | |||
| 4dee2841e0 | |||
| b4d348dd1f | |||
| b744346210 | |||
| 91712fd900 | |||
| a1ee067b53 | |||
| 1d6611601c | |||
| 539877ecc7 | |||
| d0247d1ccb | |||
| 9e619c98a4 | |||
| bdf6a155b5 | |||
| eb2cab78bb | |||
| 692a503c26 | |||
| 717d6d0d04 | |||
| e98ee0f7b9 | |||
| 5d6a6d10bd | |||
| c83313b3b9 | |||
| 7481dd0fd2 | |||
| 3757d40ac4 | |||
| 7d2c0c10d4 | |||
| 617c243923 | |||
| be225cf634 | |||
| 22a3dfe9bc | |||
| d692607e2b | |||
| 9e855c81a6 | |||
| cc7ca47469 | |||
| 6c2695f870 | |||
| 43c20b0f61 | |||
| 4f914f10cf |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -105,6 +105,9 @@ $RECYCLE.BIN/
|
|||||||
|
|
||||||
# Local History for Visual Studio Code
|
# Local History for Visual Studio Code
|
||||||
.history/
|
.history/
|
||||||
|
|
||||||
|
# ReleaseKit build output
|
||||||
|
/dist/
|
||||||
|
/.releasekit/
|
||||||
|
|
||||||
# Built Visual Studio Code Extensions
|
# Built Visual Studio Code Extensions
|
||||||
*.vsix
|
|
||||||
|
|||||||
30
AGENTS.md
Normal file
30
AGENTS.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<!-- codebase-memory-mcp:start -->
|
||||||
|
# Codebase Knowledge Graph (codebase-memory-mcp)
|
||||||
|
|
||||||
|
This project uses codebase-memory-mcp to maintain a knowledge graph of the codebase.
|
||||||
|
ALWAYS prefer MCP graph tools over grep/glob/file-search for code discovery.
|
||||||
|
|
||||||
|
## Priority Order
|
||||||
|
1. `search_graph` — find functions, classes, routes, variables by pattern
|
||||||
|
2. `trace_path` — trace who calls a function or what it calls
|
||||||
|
3. `get_code_snippet` — read specific function/class source code
|
||||||
|
4. `query_graph` — run Cypher queries for complex patterns
|
||||||
|
5. `get_architecture` — high-level project summary
|
||||||
|
|
||||||
|
## When to fall back to grep/glob
|
||||||
|
- Searching for string literals, error messages, config values
|
||||||
|
- Searching non-code files (Dockerfiles, shell scripts, configs)
|
||||||
|
- When MCP tools return insufficient results
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
- Find a handler: `search_graph(name_pattern=".*OrderHandler.*")`
|
||||||
|
- Who calls it: `trace_path(function_name="OrderHandler", direction="inbound")`
|
||||||
|
- Read source: `get_code_snippet(qualified_name="pkg/orders.OrderHandler")`
|
||||||
|
<!-- codebase-memory-mcp:end -->
|
||||||
|
|
||||||
|
Start with `docs/development.md` for orientation and use its policy reading guide
|
||||||
|
to select the policies applicable to the task. Do not read the entire suite by
|
||||||
|
default.
|
||||||
|
|
||||||
|
Read and follow `docs/policy/agents.md` before recommending, planning, or
|
||||||
|
implementing repository changes.
|
||||||
20
COPYRIGHT
Normal file
20
COPYRIGHT
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
ReleaseKit
|
||||||
|
|
||||||
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
|
SPDX-License-Identifier: LGPL-3.0-or-later
|
||||||
|
|
||||||
|
This library is free software: you can redistribute it and/or modify it
|
||||||
|
under the terms of the GNU Lesser General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
The GNU Lesser General Public License version 3 and its incorporated
|
||||||
|
GNU General Public License version 3 text are provided in LICENSE.
|
||||||
|
|
||||||
|
This library is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Lesser General Public License for more details.
|
||||||
|
|
||||||
|
Third-party code and assets are subject to their respective license terms.
|
||||||
800
LICENSE
800
LICENSE
@@ -1,304 +1,840 @@
|
|||||||
GNU LESSER GENERAL PUBLIC LICENSE
|
GNU LESSER GENERAL PUBLIC LICENSE
|
||||||
Version 3, 29 June 2007
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
|
||||||
|
|
||||||
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
|
This version of the GNU Lesser General Public License incorporates
|
||||||
|
the terms and conditions of version 3 of the GNU General Public
|
||||||
|
License, supplemented by the additional permissions listed below.
|
||||||
|
|
||||||
0. Additional Definitions.
|
0. Additional Definitions.
|
||||||
|
|
||||||
As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License.
|
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||||
|
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||||
|
General Public License.
|
||||||
|
|
||||||
"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
|
"The Library" refers to a covered work governed by this License,
|
||||||
|
other than an Application or a Combined Work as defined below.
|
||||||
|
|
||||||
An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
|
An "Application" is any work that makes use of an interface provided
|
||||||
|
by the Library, but which is not otherwise based on the Library.
|
||||||
|
Defining a subclass of a class defined by the Library is deemed a mode
|
||||||
|
of using an interface provided by the Library.
|
||||||
|
|
||||||
A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version".
|
A "Combined Work" is a work produced by combining or linking an
|
||||||
|
Application with the Library. The particular version of the Library
|
||||||
|
with which the Combined Work was made is also called the "Linked
|
||||||
|
Version".
|
||||||
|
|
||||||
The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
|
The "Minimal Corresponding Source" for a Combined Work means the
|
||||||
|
Corresponding Source for the Combined Work, excluding any source code
|
||||||
|
for portions of the Combined Work that, considered in isolation, are
|
||||||
|
based on the Application, and not on the Linked Version.
|
||||||
|
|
||||||
The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
|
The "Corresponding Application Code" for a Combined Work means the
|
||||||
|
object code and/or source code for the Application, including any data
|
||||||
|
and utility programs needed for reproducing the Combined Work from the
|
||||||
|
Application, but excluding the System Libraries of the Combined Work.
|
||||||
|
|
||||||
1. Exception to Section 3 of the GNU GPL.
|
1. Exception to Section 3 of the GNU GPL.
|
||||||
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
|
|
||||||
|
You may convey a covered work under sections 3 and 4 of this License
|
||||||
|
without being bound by section 3 of the GNU GPL.
|
||||||
|
|
||||||
2. Conveying Modified Versions.
|
2. Conveying Modified Versions.
|
||||||
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
|
|
||||||
|
|
||||||
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
|
If you modify a copy of the Library, and, in your modifications, a
|
||||||
|
facility refers to a function or data to be supplied by an Application
|
||||||
|
that uses the facility (other than as an argument passed when the
|
||||||
|
facility is invoked), then you may convey a copy of the modified
|
||||||
|
version:
|
||||||
|
|
||||||
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
|
a) under this License, provided that you make a good faith effort to
|
||||||
|
ensure that, in the event an Application does not supply the
|
||||||
|
function or data, the facility still operates, and performs
|
||||||
|
whatever part of its purpose remains meaningful, or
|
||||||
|
|
||||||
|
b) under the GNU GPL, with none of the additional permissions of
|
||||||
|
this License applicable to that copy.
|
||||||
|
|
||||||
3. Object Code Incorporating Material from Library Header Files.
|
3. Object Code Incorporating Material from Library Header Files.
|
||||||
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
|
|
||||||
|
|
||||||
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
|
The object code form of an Application may incorporate material from
|
||||||
|
a header file that is part of the Library. You may convey such object
|
||||||
|
code under terms of your choice, provided that, if the incorporated
|
||||||
|
material is not limited to numerical parameters, data structure
|
||||||
|
layouts and accessors, or small macros, inline functions and templates
|
||||||
|
(ten or fewer lines in length), you do both of the following:
|
||||||
|
|
||||||
b) Accompany the object code with a copy of the GNU GPL and this license document.
|
a) Give prominent notice with each copy of the object code that the
|
||||||
|
Library is used in it and that the Library and its use are
|
||||||
|
covered by this License.
|
||||||
|
|
||||||
|
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||||
|
document.
|
||||||
|
|
||||||
4. Combined Works.
|
4. Combined Works.
|
||||||
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
|
|
||||||
|
|
||||||
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
|
You may convey a Combined Work under terms of your choice that,
|
||||||
|
taken together, effectively do not restrict modification of the
|
||||||
|
portions of the Library contained in the Combined Work and reverse
|
||||||
|
engineering for debugging such modifications, if you also do each of
|
||||||
|
the following:
|
||||||
|
|
||||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
|
a) Give prominent notice with each copy of the Combined Work that
|
||||||
|
the Library is used in it and that the Library and its use are
|
||||||
|
covered by this License.
|
||||||
|
|
||||||
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
|
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||||
|
document.
|
||||||
|
|
||||||
|
c) For a Combined Work that displays copyright notices during
|
||||||
|
execution, include the copyright notice for the Library among
|
||||||
|
these notices, as well as a reference directing the user to the
|
||||||
|
copies of the GNU GPL and this license document.
|
||||||
|
|
||||||
d) Do one of the following:
|
d) Do one of the following:
|
||||||
|
|
||||||
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
|
0) Convey the Minimal Corresponding Source under the terms of this
|
||||||
|
License, and the Corresponding Application Code in a form
|
||||||
|
suitable for, and under terms that permit, the user to
|
||||||
|
recombine or relink the Application with a modified version of
|
||||||
|
the Linked Version to produce a modified Combined Work, in the
|
||||||
|
manner specified by section 6 of the GNU GPL for conveying
|
||||||
|
Corresponding Source.
|
||||||
|
|
||||||
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
|
1) Use a suitable shared library mechanism for linking with the
|
||||||
|
Library. A suitable mechanism is one that (a) uses at run time
|
||||||
|
a copy of the Library already present on the user's computer
|
||||||
|
system, and (b) will operate properly with a modified version
|
||||||
|
of the Library that is interface-compatible with the Linked
|
||||||
|
Version.
|
||||||
|
|
||||||
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
|
e) Provide Installation Information, but only if you would otherwise
|
||||||
|
be required to provide such information under section 6 of the
|
||||||
|
GNU GPL, and only to the extent that such information is
|
||||||
|
necessary to install and execute a modified version of the
|
||||||
|
Combined Work produced by recombining or relinking the
|
||||||
|
Application with a modified version of the Linked Version. (If
|
||||||
|
you use option 4d0, the Installation Information must accompany
|
||||||
|
the Minimal Corresponding Source and Corresponding Application
|
||||||
|
Code. If you use option 4d1, you must provide the Installation
|
||||||
|
Information in the manner specified by section 6 of the GNU GPL
|
||||||
|
for conveying Corresponding Source.)
|
||||||
|
|
||||||
5. Combined Libraries.
|
5. Combined Libraries.
|
||||||
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
|
|
||||||
|
|
||||||
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
|
You may place library facilities that are a work based on the
|
||||||
|
Library side by side in a single library together with other library
|
||||||
|
facilities that are not Applications and are not covered by this
|
||||||
|
License, and convey such a combined library under terms of your
|
||||||
|
choice, if you do both of the following:
|
||||||
|
|
||||||
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
|
a) Accompany the combined library with a copy of the same work based
|
||||||
|
on the Library, uncombined with any other library facilities,
|
||||||
|
conveyed under the terms of this License.
|
||||||
|
|
||||||
|
b) Give prominent notice with the combined library that part of it
|
||||||
|
is a work based on the Library, and explaining where to find the
|
||||||
|
accompanying uncombined form of the same work.
|
||||||
|
|
||||||
6. Revised Versions of the GNU Lesser General Public License.
|
6. Revised Versions of the GNU Lesser General Public License.
|
||||||
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
|
The Free Software Foundation may publish revised and/or new versions
|
||||||
|
of the GNU Lesser General Public License from time to time. Such new
|
||||||
|
versions will be similar in spirit to the present version, but may
|
||||||
|
differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall
|
Each version is given a distinguishing version number. If the
|
||||||
apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
|
Library as you received it specifies that a certain numbered version
|
||||||
|
of the GNU Lesser General Public License "or any later version"
|
||||||
|
applies to it, you have the option of following the terms and
|
||||||
|
conditions either of that published version or of any later version
|
||||||
|
published by the Free Software Foundation. If the Library as you
|
||||||
|
received it does not specify a version number of the GNU Lesser
|
||||||
|
General Public License, you may choose any version of the GNU Lesser
|
||||||
|
General Public License ever published by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Library as you received it specifies that a proxy can decide
|
||||||
|
whether future versions of the GNU Lesser General Public License shall
|
||||||
|
apply, that proxy's public statement of acceptance of any version is
|
||||||
|
permanent authorization for you to choose that version for the
|
||||||
|
Library.
|
||||||
|
|
||||||
GNU GENERAL PUBLIC LICENSE
|
GNU GENERAL PUBLIC LICENSE
|
||||||
Version 3, 29 June 2007
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
Preamble
|
Preamble
|
||||||
|
|
||||||
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and modification follow.
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
TERMS AND CONDITIONS
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
0. Definitions.
|
0. Definitions.
|
||||||
|
|
||||||
“This License” refers to version 3 of the GNU General Public License.
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
A “covered work” means either the unmodified Program or a work based on the Program.
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
1. Source Code.
|
1. Source Code.
|
||||||
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
|
||||||
|
|
||||||
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
The Corresponding Source for a work in source code form is that same work.
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
2. Basic Permissions.
|
2. Basic Permissions.
|
||||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
|
||||||
|
|
||||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
|
||||||
|
|
||||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
4. Conveying Verbatim Copies.
|
4. Conveying Verbatim Copies.
|
||||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
|
||||||
|
|
||||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
5. Conveying Modified Source Versions.
|
5. Conveying Modified Source Versions.
|
||||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
|
||||||
|
|
||||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
6. Conveying Non-Source Forms.
|
6. Conveying Non-Source Forms.
|
||||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
|
||||||
|
|
||||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
7. Additional Terms.
|
7. Additional Terms.
|
||||||
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
|
||||||
|
|
||||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
8. Termination.
|
8. Termination.
|
||||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
|
||||||
|
|
||||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
9. Acceptance Not Required for Having Copies.
|
9. Acceptance Not Required for Having Copies.
|
||||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
10. Automatic Licensing of Downstream Recipients.
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
|
||||||
|
|
||||||
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
11. Patents.
|
11. Patents.
|
||||||
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
|
||||||
|
|
||||||
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
12. No Surrender of Others' Freedom.
|
12. No Surrender of Others' Freedom.
|
||||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
13. Use with the GNU Affero General Public License.
|
13. Use with the GNU Affero General Public License.
|
||||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
14. Revised Versions of this License.
|
14. Revised Versions of this License.
|
||||||
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
15. Disclaimer of Warranty.
|
15. Disclaimer of Warranty.
|
||||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
16. Limitation of Liability.
|
16. Limitation of Liability.
|
||||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
17. Interpretation of Sections 15 and 16.
|
17. Interpretation of Sections 15 and 16.
|
||||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
How to Apply These Terms to Your New Programs
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
ReleaseKit
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
Copyright (C) 2026 eric
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
ReleaseKit Copyright (C) 2026 eric
|
<program> Copyright (C) <year> <name of author>
|
||||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
|
|||||||
83
README.md
83
README.md
@@ -1,3 +1,84 @@
|
|||||||
# ReleaseKit
|
# ReleaseKit
|
||||||
|
|
||||||
ReleaseKit is an opinionated Go library that bundles common scripts and functions for releasing applications.
|
ReleaseKit is an opinionated Go library and executable for a shared release
|
||||||
|
process. The Go module, root `releasekit` facade, `buildinfo` runtime package,
|
||||||
|
local candidate check, source-tag publication API, selected-target build API,
|
||||||
|
tagged-source delivery API, and the `version`, `check`, `publish`, `build`,
|
||||||
|
`deliver`, and `ci-deliver` commands are implemented. ReleaseKit's source-only
|
||||||
|
maintainer procedure and prepared Woodpecker workflow for hosted note-page
|
||||||
|
delivery are documented. ReleaseKit does not declare binary deliverables.
|
||||||
|
|
||||||
|
Release operations can select one Go module within a repository. The repository
|
||||||
|
root remains the default; a selected module's declared import path and physical
|
||||||
|
directory determine its complete Git tag and module-local release note. See the
|
||||||
|
[candidate check](docs/consumers/check.md),
|
||||||
|
[publication](docs/consumers/publish.md), and
|
||||||
|
[multi-module example](examples/multi-module/).
|
||||||
|
|
||||||
|
See the [consumer adoption guide](docs/consumers/adoption.md) to add ReleaseKit
|
||||||
|
as a versioned Go tool or package dependency, and the
|
||||||
|
[v0.1.0 release note](docs/releases/v0.1.0.md) for the initial baseline.
|
||||||
|
|
||||||
|
Run the offline Go test suite from the repository root with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go test ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
The version command prints ReleaseKit's version:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit version
|
||||||
|
```
|
||||||
|
|
||||||
|
The local candidate check validates a committed release note, runs the standard
|
||||||
|
offline Go suite with any selected shared validation checks, and then runs
|
||||||
|
configured product checks:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit check v1.2.3
|
||||||
|
```
|
||||||
|
|
||||||
|
Publish the source tag from a committed candidate with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./scripts/release v1.2.3
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [ReleaseKit maintainer procedure](docs/release.md) for preparation and
|
||||||
|
failure recovery.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- [Consumer adoption](docs/consumers/adoption.md): versioned CLI tool and Go API
|
||||||
|
dependencies, upgrades, and CI adoption.
|
||||||
|
- [Contributor guide](docs/development.md): orientation, validation, and selective
|
||||||
|
policy reading.
|
||||||
|
- [CLI contract](docs/cli.md): the `version`, `check`, `publish`, `build`,
|
||||||
|
`deliver`, and `ci-deliver` commands.
|
||||||
|
- [Configuration](docs/config.md): profile fields and child-command settings.
|
||||||
|
- [Runtime version guidance](docs/consumers/runtime-version.md): how applications
|
||||||
|
read their embedded version through `buildinfo`.
|
||||||
|
- [Build guidance](docs/consumers/build.md): compile selected Go targets with an
|
||||||
|
injected application version.
|
||||||
|
- [Delivery guidance](docs/consumers/delivery.md): deliver tagged source and
|
||||||
|
report hosted page and asset status.
|
||||||
|
- [Gitea integration](docs/integrations/gitea.md): hosted release-page
|
||||||
|
operations and their failure behavior.
|
||||||
|
- [Candidate check guidance](docs/consumers/check.md): local candidate validation
|
||||||
|
through the Go API and CLI.
|
||||||
|
- [Source publication guidance](docs/consumers/publish.md): validate and publish
|
||||||
|
the exact annotated source tag through the Go API.
|
||||||
|
- [Maintainer release procedure](docs/release.md): ReleaseKit's source-only
|
||||||
|
publication workflow and recovery.
|
||||||
|
- [Internal package inventory](docs/internal/overview.md): implemented internal
|
||||||
|
components and their responsibilities.
|
||||||
|
- [Architecture policy](docs/policy/architecture.md): responsibility and dependency
|
||||||
|
boundaries for development.
|
||||||
|
- [ADR 0001](docs/adr/0001-public-facade.md): the accepted public facade decision.
|
||||||
|
- [Policy provenance](docs/policy/meta.md): adopted policy sources and update
|
||||||
|
guidance.
|
||||||
|
|
||||||
|
ReleaseKit is licensed under the [LGPL v3.0 or later](COPYRIGHT).
|
||||||
|
|
||||||
|
[Open Source attribution notices](docs/oss/attribution.md) are available.
|
||||||
|
|||||||
156
build.go
Normal file
156
build.go
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Target identifies one explicit Go operating-system and architecture pair.
|
||||||
|
type Target struct {
|
||||||
|
OS string // Go operating system name, such as "linux".
|
||||||
|
Arch string // Go architecture name, such as "amd64".
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildSpec selects the application package, output name, and target pairs.
|
||||||
|
type BuildSpec struct {
|
||||||
|
MainPackage string // Go package path to build, such as "./cmd/app".
|
||||||
|
BinaryName string // filename component used in output artifacts.
|
||||||
|
Targets []Target // selected target pairs; duplicates are removed in order.
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildRequest contains the source and output settings for Build.
|
||||||
|
type BuildRequest struct {
|
||||||
|
RepositoryDir string // directory within the source Git checkout whose HEAD is recorded.
|
||||||
|
// ModuleDir selects a repository-relative module directory; empty selects
|
||||||
|
// the repository root.
|
||||||
|
ModuleDir string
|
||||||
|
Version string // stable vMAJOR.MINOR.PATCH value injected at link time.
|
||||||
|
Spec BuildSpec // application package, artifact name, and targets.
|
||||||
|
OutputDir string // output location; relative paths use ModuleDir and empty selects <module>/dist.
|
||||||
|
Output io.Writer // optional build progress destination.
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildArtifact identifies one generated binary and its SHA-256 digest.
|
||||||
|
type BuildArtifact struct {
|
||||||
|
Path string // absolute path to the generated binary.
|
||||||
|
Filename string // generated filename.
|
||||||
|
Target Target // Go target used for this artifact.
|
||||||
|
SHA256 string // lowercase hexadecimal digest of the complete file.
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildResult describes the source and artifacts reached by Build.
|
||||||
|
type BuildResult struct {
|
||||||
|
RepositoryDir string // absolute source repository path.
|
||||||
|
ModuleDir string // absolute selected module directory.
|
||||||
|
ModulePath string // selected module's declared Go path.
|
||||||
|
Tag string // complete tag derived for this version.
|
||||||
|
CandidateCommit string // Git HEAD observed when the build started.
|
||||||
|
// SourceVerified reports clean source and the same HEAD observed before and
|
||||||
|
// after a completed build. It is required for binary delivery, not an attestation.
|
||||||
|
SourceVerified bool
|
||||||
|
Version string // requested injected version.
|
||||||
|
MainPackage string // Go package path built.
|
||||||
|
BinaryName string // artifact name prefix.
|
||||||
|
OutputDir string // resolved output directory.
|
||||||
|
Targets []Target // normalized target pairs.
|
||||||
|
Artifacts []BuildArtifact // completed output files, including partial success.
|
||||||
|
Compiler string // output of the selected local Go toolchain's version command.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build resolves the selected module's working-tree identity, then compiles the
|
||||||
|
// selected targets with Version injected through buildinfo. It uses the
|
||||||
|
// available compatible local Go toolchain, applies ReleaseKit's readonly
|
||||||
|
// offline build settings, preserves effective cache and tool settings, and
|
||||||
|
// verifies the version command on the Go host before succeeding. Relative
|
||||||
|
// output paths use ModuleDir; an empty path selects its dist directory. An
|
||||||
|
// empty target set records source identity without running the Go toolchain.
|
||||||
|
// Errors return partial build facts in the result.
|
||||||
|
func Build(ctx context.Context, request BuildRequest) (BuildResult, error) {
|
||||||
|
spec := *internalBuildSpec(&request.Spec)
|
||||||
|
result := internalbuild.Result{Version: request.Version}
|
||||||
|
failure := func(err error) (BuildResult, error) {
|
||||||
|
result.Settings = artifact.NormalizeSettings(spec.MainPackage, spec.BinaryName, spec.Targets)
|
||||||
|
return publicBuildResult(result), err
|
||||||
|
}
|
||||||
|
if !versioncontract.ValidStableVersion(request.Version) {
|
||||||
|
return failure(fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version))
|
||||||
|
}
|
||||||
|
repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return failure(err)
|
||||||
|
}
|
||||||
|
result.RepositoryDir = repositoryDir
|
||||||
|
identity, err := releaseidentity.FromWorkingTree(ctx, repositoryDir, request.ModuleDir, request.Version)
|
||||||
|
result.ModuleDir, result.ModulePath, result.Tag = identity.ModuleDir, identity.ModulePath, identity.Tag
|
||||||
|
if err != nil {
|
||||||
|
return failure(err)
|
||||||
|
}
|
||||||
|
result, err = internalbuild.BuildResolved(ctx, internalbuild.Request{
|
||||||
|
Identity: identity,
|
||||||
|
Spec: spec,
|
||||||
|
OutputDir: request.OutputDir,
|
||||||
|
Output: request.Output,
|
||||||
|
})
|
||||||
|
return publicBuildResult(result), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func publicBuildResult(result internalbuild.Result) BuildResult {
|
||||||
|
public := BuildResult{
|
||||||
|
RepositoryDir: result.RepositoryDir,
|
||||||
|
ModuleDir: result.ModuleDir,
|
||||||
|
ModulePath: result.ModulePath,
|
||||||
|
Tag: result.Tag,
|
||||||
|
CandidateCommit: result.CandidateCommit,
|
||||||
|
SourceVerified: result.SourceVerified,
|
||||||
|
Version: result.Version,
|
||||||
|
MainPackage: result.Settings.MainPackage,
|
||||||
|
BinaryName: result.Settings.BinaryName,
|
||||||
|
OutputDir: result.OutputDir,
|
||||||
|
Compiler: result.Compiler,
|
||||||
|
Targets: make([]Target, 0, len(result.Settings.Targets)),
|
||||||
|
Artifacts: make([]BuildArtifact, 0, len(result.Artifacts)),
|
||||||
|
}
|
||||||
|
for _, target := range result.Settings.Targets {
|
||||||
|
public.Targets = append(public.Targets, Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
public.Artifacts = append(public.Artifacts, BuildArtifact{
|
||||||
|
Path: artifact.Path,
|
||||||
|
Filename: artifact.Filename,
|
||||||
|
Target: Target{OS: artifact.Target.OS, Arch: artifact.Target.Arch},
|
||||||
|
SHA256: artifact.SHA256,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return public
|
||||||
|
}
|
||||||
|
|
||||||
|
func internalBuildSpec(spec *BuildSpec) *internalbuild.Spec {
|
||||||
|
if spec == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
result := &internalbuild.Spec{MainPackage: spec.MainPackage, BinaryName: spec.BinaryName}
|
||||||
|
for _, target := range spec.Targets {
|
||||||
|
result.Targets = append(result.Targets, internalbuild.Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func internalBuildResult(result BuildResult) *internalbuild.Result {
|
||||||
|
input := internalBuildSpec(&BuildSpec{MainPackage: result.MainPackage, BinaryName: result.BinaryName, Targets: result.Targets})
|
||||||
|
settings := artifact.NormalizeSettings(input.MainPackage, input.BinaryName, input.Targets)
|
||||||
|
converted := &internalbuild.Result{RepositoryDir: result.RepositoryDir, ModuleDir: result.ModuleDir, ModulePath: result.ModulePath, Tag: result.Tag, CandidateCommit: result.CandidateCommit, SourceVerified: result.SourceVerified, Settings: settings, Version: result.Version, MainPackage: settings.MainPackage, BinaryName: settings.BinaryName, OutputDir: result.OutputDir, Compiler: result.Compiler}
|
||||||
|
for _, target := range settings.Targets {
|
||||||
|
converted.Targets = append(converted.Targets, internalbuild.Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
converted.Artifacts = append(converted.Artifacts, internalbuild.Artifact{Path: artifact.Path, Filename: artifact.Filename, Target: internalbuild.Target{OS: artifact.Target.OS, Arch: artifact.Target.Arch}, SHA256: artifact.SHA256})
|
||||||
|
}
|
||||||
|
return converted
|
||||||
|
}
|
||||||
863
build_test.go
Normal file
863
build_test.go
Normal file
@@ -0,0 +1,863 @@
|
|||||||
|
package releasekit_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildPreservesInvalidVersionAndDeclarationFailureEvidence(t *testing.T) {
|
||||||
|
spec := releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "widget", Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}, {OS: "linux", Arch: "amd64"}}}
|
||||||
|
invalid, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: filepath.Join(t.TempDir(), "absent"), Version: "bad-version", Spec: spec,
|
||||||
|
})
|
||||||
|
if !errors.Is(err, releasekit.ErrInvalidVersion) || invalid.Version != "bad-version" || invalid.MainPackage != spec.MainPackage || invalid.BinaryName != spec.BinaryName || len(invalid.Targets) != 1 {
|
||||||
|
t.Fatalf("invalid version result = %#v, error = %v", invalid, err)
|
||||||
|
}
|
||||||
|
repo := newPublishFixture(t)
|
||||||
|
writeFile(t, repo.work, "nested/go.mod", "go 1.26.0\n")
|
||||||
|
failed, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repo.work, ModuleDir: "nested", Version: "v1.2.3", Spec: spec,
|
||||||
|
})
|
||||||
|
if err == nil || failed.RepositoryDir != repo.work || failed.ModuleDir != filepath.Join(repo.work, "nested") || failed.Version != "v1.2.3" || failed.MainPackage != spec.MainPackage || failed.BinaryName != spec.BinaryName || len(failed.Targets) != 1 || failed.SourceVerified {
|
||||||
|
t.Fatalf("declaration failure = %#v, error = %v", failed, err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if _, err := releasekit.Build(ctx, releasekit.BuildRequest{RepositoryDir: repo.work, Version: "v1.2.3", Spec: spec}); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("canceled build error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCreatesSelectedTargetsAndInjectsVersion(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) == 2 && os.Args[1] == "version" {
|
||||||
|
fmt.Printf("fixture %s\n", buildinfo.Version())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
outputDir := filepath.Join(t.TempDir(), "artifacts")
|
||||||
|
t.Setenv("GOOS", "windows")
|
||||||
|
t.Setenv("GOARCH", "arm64")
|
||||||
|
t.Setenv("GOFLAGS", "-race")
|
||||||
|
var progress bytes.Buffer
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "linux", Arch: "arm64"},
|
||||||
|
{OS: "darwin", Arch: "arm64"},
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
OutputDir: outputDir,
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v; partial result = %#v", err, result)
|
||||||
|
}
|
||||||
|
if result.CandidateCommit == "" || result.CandidateCommit != buildGit(t, repository, "rev-parse", "HEAD") {
|
||||||
|
t.Fatalf("candidate commit = %q", result.CandidateCommit)
|
||||||
|
}
|
||||||
|
if result.Compiler == "" || len(result.Targets) != 3 || len(result.Artifacts) != 3 {
|
||||||
|
t.Fatalf("build result = %#v", result)
|
||||||
|
}
|
||||||
|
wantNames := []string{
|
||||||
|
"fixture-v1.2.3-linux-amd64",
|
||||||
|
"fixture-v1.2.3-linux-arm64",
|
||||||
|
"fixture-v1.2.3-darwin-arm64",
|
||||||
|
}
|
||||||
|
for index, artifact := range result.Artifacts {
|
||||||
|
if artifact.Filename != wantNames[index] || artifact.Target != result.Targets[index] {
|
||||||
|
t.Fatalf("artifact %d = %#v", index, artifact)
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(artifact.Path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256(contents)
|
||||||
|
if artifact.SHA256 != hex.EncodeToString(digest[:]) {
|
||||||
|
t.Fatalf("artifact digest = %q, want %x", artifact.SHA256, digest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(progress.String(), "checking fixture version output") {
|
||||||
|
t.Fatalf("build progress = %q", progress.String())
|
||||||
|
}
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
if artifact.Target != (releasekit.Target{OS: runtime.GOOS, Arch: runtime.GOARCH}) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
command := exec.Command(artifact.Path, "version")
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil || string(output) != "fixture v1.2.3\n" {
|
||||||
|
t.Fatalf("native version command output = %q, error = %v", output, err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildUsesGoHostDespiteAmbientTargetEnvironment(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) }
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
t.Setenv("GOOS", "windows")
|
||||||
|
t.Setenv("GOARCH", "arm64")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: "windows", Arch: "arm64"}},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v; partial result = %#v", err, result)
|
||||||
|
}
|
||||||
|
if len(result.Artifacts) != 1 || result.Artifacts[0].Filename != "fixture-v1.2.3-windows-arm64.exe" {
|
||||||
|
t.Fatalf("build artifacts = %#v", result.Artifacts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildIgnoresAmbientAndPersistentArchitectureTuning(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } }
|
||||||
|
`)
|
||||||
|
|
||||||
|
for _, source := range []string{"process environment", "Go environment file"} {
|
||||||
|
t.Run(source, func(t *testing.T) {
|
||||||
|
unsetBuildEnv(t, "GOCACHE")
|
||||||
|
unsetBuildEnv(t, "GOAMD64")
|
||||||
|
unsetBuildEnv(t, "GOEXPERIMENT")
|
||||||
|
unsetBuildEnv(t, "GOFLAGS")
|
||||||
|
cache := filepath.Join(t.TempDir(), "configured-cache")
|
||||||
|
goEnv := filepath.Join(t.TempDir(), "go-env")
|
||||||
|
if source == "Go environment file" {
|
||||||
|
contents := fmt.Sprintf("GOAMD64=v2\nGOEXPERIMENT=loopvar\nGOFLAGS=-run=^$\nGOCACHE=%s\n", cache)
|
||||||
|
if err := os.WriteFile(goEnv, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := os.WriteFile(goEnv, nil, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("GOAMD64", "v2")
|
||||||
|
t.Setenv("GOEXPERIMENT", "loopvar")
|
||||||
|
t.Setenv("GOFLAGS", "-run=^$")
|
||||||
|
}
|
||||||
|
t.Setenv("GOENV", goEnv)
|
||||||
|
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v; partial result = %#v", err, result)
|
||||||
|
}
|
||||||
|
metadata := goBuildMetadata(t, result.Artifacts[0].Path)
|
||||||
|
if !strings.Contains(metadata, "GOAMD64=v1") || strings.Contains(metadata, "GOAMD64=v2") || strings.Contains(metadata, "GOEXPERIMENT=loopvar") {
|
||||||
|
t.Fatalf("build metadata includes ambient tuning:\n%s", metadata)
|
||||||
|
}
|
||||||
|
if source == "Go environment file" {
|
||||||
|
entries, err := os.ReadDir(cache)
|
||||||
|
if err != nil || len(entries) == 0 {
|
||||||
|
t.Fatalf("configured persistent cache was not used: entries=%d error=%v", len(entries), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func goBuildMetadata(t *testing.T, binary string) string {
|
||||||
|
t.Helper()
|
||||||
|
t.Setenv("GOENV", "off")
|
||||||
|
t.Setenv("GOFLAGS", "")
|
||||||
|
t.Setenv("GOEXPERIMENT", "")
|
||||||
|
t.Setenv("GOAMD64", "")
|
||||||
|
t.Setenv("GOOS", "")
|
||||||
|
t.Setenv("GOARCH", "")
|
||||||
|
output, err := exec.Command("go", "version", "-m", binary).CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("go version -m: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
return string(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func unsetBuildEnv(t *testing.T, key string) {
|
||||||
|
t.Helper()
|
||||||
|
value, exists := os.LookupEnv(key)
|
||||||
|
if err := os.Unsetenv(key); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if exists {
|
||||||
|
_ = os.Setenv(key, value)
|
||||||
|
} else {
|
||||||
|
_ = os.Unsetenv(key)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildWithNoTargetsDoesNotInvokeCompiler(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
func main() {}
|
||||||
|
`)
|
||||||
|
outputDir := filepath.Join(t.TempDir(), "must-not-be-created")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
OutputDir: outputDir,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v", err)
|
||||||
|
}
|
||||||
|
if result.CandidateCommit == "" || result.Compiler != "" || len(result.Targets) != 0 || len(result.Artifacts) != 0 {
|
||||||
|
t.Fatalf("empty build result = %#v", result)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(outputDir); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("empty build created output directory: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildUsesNestedWorkingTreeModuleAndModuleRelativeOutput(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||||
|
moduleDir := filepath.Join(repository, "integrations", "nested")
|
||||||
|
writeNestedBuildConsumer(t, repository, "integrations/nested", "example.com/nestedbuild", `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) == 2 && os.Args[1] == "version" {
|
||||||
|
if logPath := os.Getenv("RELEASEKIT_SMOKE_LOG"); logPath != "" {
|
||||||
|
if executable, err := os.Executable(); err == nil {
|
||||||
|
_ = os.WriteFile(logPath, []byte(executable), 0o600)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Printf("nested-app %s\n", buildinfo.Version())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
outputDirectory := "artifacts"
|
||||||
|
crossTarget := releasekit.Target{OS: "darwin", Arch: "arm64"}
|
||||||
|
if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
|
||||||
|
crossTarget = releasekit.Target{OS: "linux", Arch: "amd64"}
|
||||||
|
}
|
||||||
|
nativeTarget := releasekit.Target{OS: runtime.GOOS, Arch: runtime.GOARCH}
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
ModuleDir: "integrations/nested",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "nested-app",
|
||||||
|
Targets: []releasekit.Target{nativeTarget, crossTarget},
|
||||||
|
},
|
||||||
|
OutputDir: outputDirectory,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v; result = %#v", err, result)
|
||||||
|
}
|
||||||
|
if result.ModuleDir != moduleDir || result.ModulePath != "example.com/nestedbuild" || result.Tag != "integrations/nested/v1.2.3" {
|
||||||
|
t.Fatalf("nested build identity = %#v", result)
|
||||||
|
}
|
||||||
|
wantOutput := filepath.Join(moduleDir, outputDirectory)
|
||||||
|
if result.OutputDir != wantOutput || len(result.Artifacts) != 2 {
|
||||||
|
t.Fatalf("nested build output = %#v, want directory %q and two artifacts", result, wantOutput)
|
||||||
|
}
|
||||||
|
var native string
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
if filepath.Dir(artifact.Path) != wantOutput || !strings.Contains(artifact.Filename, "nested-app-v1.2.3-") {
|
||||||
|
t.Fatalf("nested artifact = %#v", artifact)
|
||||||
|
}
|
||||||
|
if artifact.Target == nativeTarget {
|
||||||
|
native = artifact.Path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if native == "" {
|
||||||
|
t.Fatalf("native artifact missing from %#v", result.Artifacts)
|
||||||
|
}
|
||||||
|
if output, err := exec.Command(native, "version").CombinedOutput(); err != nil || string(output) != "nested-app v1.2.3\n" {
|
||||||
|
t.Fatalf("nested native version = %q, error = %v", output, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
localTemporary := filepath.Join(repository, "source-temporary")
|
||||||
|
if err := os.Mkdir(localTemporary, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
crossOutput := filepath.Join(t.TempDir(), "cross-artifacts")
|
||||||
|
smokeLog := filepath.Join(t.TempDir(), "smoke-executable")
|
||||||
|
t.Setenv("RELEASEKIT_SMOKE_LOG", smokeLog)
|
||||||
|
t.Setenv("TMPDIR", localTemporary)
|
||||||
|
smokeResult, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
ModuleDir: "integrations/nested",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "nested-app",
|
||||||
|
Targets: []releasekit.Target{crossTarget},
|
||||||
|
},
|
||||||
|
OutputDir: crossOutput,
|
||||||
|
})
|
||||||
|
if err != nil || len(smokeResult.Artifacts) != 1 {
|
||||||
|
t.Fatalf("nested cross build with source-local TMPDIR = %#v, %v", smokeResult, err)
|
||||||
|
}
|
||||||
|
smokePathBytes, err := os.ReadFile(smokeLog)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read native smoke executable path: %v", err)
|
||||||
|
}
|
||||||
|
smokePath := string(smokePathBytes)
|
||||||
|
relativeSmokePath, err := filepath.Rel(repository, smokePath)
|
||||||
|
if err != nil || relativeSmokePath == "." || (!filepath.IsAbs(relativeSmokePath) && relativeSmokePath != ".." && !strings.HasPrefix(relativeSmokePath, ".."+string(filepath.Separator))) {
|
||||||
|
t.Fatalf("native smoke output path %q is inside repository %q (relative %q, error %v)", smokePath, repository, relativeSmokePath, err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(smokePath); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("native smoke output %q was not removed: %v", smokePath, err)
|
||||||
|
}
|
||||||
|
remaining, err := os.ReadDir(localTemporary)
|
||||||
|
if err != nil || len(remaining) != 0 {
|
||||||
|
t.Fatalf("native smoke output remained in source-local TMPDIR: %v %v", remaining, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
emptyResult, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
ModuleDir: "integrations/nested",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
})
|
||||||
|
if err != nil || emptyResult.Compiler != "" || emptyResult.OutputDir != filepath.Join(moduleDir, "dist") {
|
||||||
|
t.Fatalf("nested empty build = %#v, %v", emptyResult, err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(emptyResult.OutputDir); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("empty nested build created dist: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildResolvesDirtyWorkingTreeDeclaration(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||||
|
declarationPath := filepath.Join(repository, "go.mod")
|
||||||
|
contents, err := os.ReadFile(declarationPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
updated := strings.Replace(string(contents), "module example.com/buildfixture", "module example.com/changedbuild", 1)
|
||||||
|
if updated == string(contents) {
|
||||||
|
t.Fatal("fixture module declaration was not replaced")
|
||||||
|
}
|
||||||
|
writeBuildFixture(t, repository, "go.mod", updated)
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.ModulePath != "example.com/changedbuild" || result.Tag != "v1.2.3" {
|
||||||
|
t.Fatalf("dirty declaration identity = %#v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildRegeneratesOwnedOutputsAndPreservesUnrelatedFiles(t *testing.T) {
|
||||||
|
const source = `package main
|
||||||
|
import("fmt";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo")
|
||||||
|
func main(){fmt.Println("fixture",buildinfo.Version())}
|
||||||
|
`
|
||||||
|
repository := newBuildConsumer(t, source)
|
||||||
|
outputDir := t.TempDir()
|
||||||
|
unrelated := filepath.Join(outputDir, "keep.txt")
|
||||||
|
if err := os.WriteFile(unrelated, []byte("keep this file"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
request := releasekit.BuildRequest{RepositoryDir: repository, Version: "v1.2.3", Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}, OutputDir: outputDir}
|
||||||
|
unsafe := request
|
||||||
|
unsafe.Spec.BinaryName = "../unsafe"
|
||||||
|
if _, err := releasekit.Build(context.Background(), unsafe); err == nil {
|
||||||
|
t.Fatal("unsafe binary name accepted")
|
||||||
|
}
|
||||||
|
first, err := releasekit.Build(context.Background(), request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
repeated, err := releasekit.Build(context.Background(), request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if repeated.Artifacts[0].SHA256 != first.Artifacts[0].SHA256 {
|
||||||
|
t.Fatal("identical build changed output")
|
||||||
|
}
|
||||||
|
writeBuildFixture(t, repository, "cmd/app/main.go", source+"\nfunc init(){if len([]byte(buildinfo.Version()))==0 {panic(\"changed build\")}}\n")
|
||||||
|
changed, err := releasekit.Build(context.Background(), request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if changed.Artifacts[0].SHA256 == first.Artifacts[0].SHA256 {
|
||||||
|
t.Fatal("changed source did not regenerate binary")
|
||||||
|
}
|
||||||
|
content, err := os.ReadFile(unrelated)
|
||||||
|
if err != nil || string(content) != "keep this file" {
|
||||||
|
t.Fatalf("unrelated file=%q %v", content, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildReturnsPartialArtifactsAfterTargetFailure(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{
|
||||||
|
{OS: runtime.GOOS, Arch: runtime.GOARCH},
|
||||||
|
{OS: "invalid-os", Arch: "invalid-arch"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
if err == nil || len(result.Artifacts) != 1 {
|
||||||
|
t.Fatalf("Build() result = %#v, error = %v; want one retained artifact", result, err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(result.Artifacts[0].Path); err != nil {
|
||||||
|
t.Fatalf("partial artifact was not retained: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildReportsMissingMainPackage(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/missing",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "cmd/missing") || len(result.Artifacts) != 0 {
|
||||||
|
t.Fatalf("Build() result = %#v, error = %v; want missing-package failure", result, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildReportsIncorrectVersionOutputAndRetainsBinary(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("wrong") } }
|
||||||
|
`)
|
||||||
|
outputDir := filepath.Join(t.TempDir(), "artifacts")
|
||||||
|
result, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
OutputDir: outputDir,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "native version output") || len(result.Artifacts) != 1 {
|
||||||
|
t.Fatalf("Build() result = %#v, error = %v; want retained-binary smoke failure", result, err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(result.Artifacts[0].Path); err != nil {
|
||||||
|
t.Fatalf("built artifact was not retained after smoke failure: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCancellationReturnsCompletedArtifacts(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, "package main\nfunc main() {}\n")
|
||||||
|
realGo, err := exec.LookPath("go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
wrapperDir := t.TempDir()
|
||||||
|
wrapper := filepath.Join(wrapperDir, "go")
|
||||||
|
callCount := filepath.Join(wrapperDir, "build-count")
|
||||||
|
blocked := filepath.Join(wrapperDir, "second-build-started")
|
||||||
|
contents := "#!/bin/sh\n" +
|
||||||
|
"for argument do\n" +
|
||||||
|
" if [ \"$argument\" = build ]; then\n" +
|
||||||
|
" count=0\n" +
|
||||||
|
" if [ -f \"$RELEASEKIT_BUILD_COUNT\" ]; then count=$(cat \"$RELEASEKIT_BUILD_COUNT\"); fi\n" +
|
||||||
|
" count=$((count + 1))\n" +
|
||||||
|
" printf '%s\\n' \"$count\" > \"$RELEASEKIT_BUILD_COUNT\"\n" +
|
||||||
|
" if [ \"$count\" -eq 2 ]; then : > \"$RELEASEKIT_BUILD_BLOCKED\"; exec sleep 30; fi\n" +
|
||||||
|
" fi\n" +
|
||||||
|
"done\n" +
|
||||||
|
"exec \"$RELEASEKIT_BUILD_REAL_GO\" \"$@\"\n"
|
||||||
|
if err := os.WriteFile(wrapper, []byte(contents), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", wrapperDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
t.Setenv("RELEASEKIT_BUILD_COUNT", callCount)
|
||||||
|
t.Setenv("RELEASEKIT_BUILD_BLOCKED", blocked)
|
||||||
|
t.Setenv("RELEASEKIT_BUILD_REAL_GO", realGo)
|
||||||
|
secondTarget := releasekit.Target{OS: "darwin", Arch: "arm64"}
|
||||||
|
if secondTarget == (releasekit.Target{OS: runtime.GOOS, Arch: runtime.GOARCH}) {
|
||||||
|
secondTarget = releasekit.Target{OS: "linux", Arch: "amd64"}
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan struct {
|
||||||
|
result releasekit.BuildResult
|
||||||
|
err error
|
||||||
|
}, 1)
|
||||||
|
go func() {
|
||||||
|
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}, secondTarget},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "artifacts"),
|
||||||
|
})
|
||||||
|
done <- struct {
|
||||||
|
result releasekit.BuildResult
|
||||||
|
err error
|
||||||
|
}{result: result, err: err}
|
||||||
|
}()
|
||||||
|
ticker := time.NewTicker(10 * time.Millisecond)
|
||||||
|
defer ticker.Stop()
|
||||||
|
deadline := time.NewTimer(30 * time.Second)
|
||||||
|
defer deadline.Stop()
|
||||||
|
for {
|
||||||
|
if _, err := os.Stat(blocked); err == nil {
|
||||||
|
cancel()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case outcome := <-done:
|
||||||
|
cancel()
|
||||||
|
t.Fatalf("Build() ended before cancellation: result=%#v error=%v", outcome.result, outcome.err)
|
||||||
|
case <-deadline.C:
|
||||||
|
cancel()
|
||||||
|
outcome := <-done
|
||||||
|
t.Fatalf("second build did not start: result=%#v error=%v", outcome.result, outcome.err)
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outcome := <-done
|
||||||
|
if !errors.Is(outcome.err, context.Canceled) || len(outcome.result.Artifacts) != 1 {
|
||||||
|
t.Fatalf("canceled build result=%#v error=%v; want one retained artifact", outcome.result, outcome.err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree(t *testing.T) {
|
||||||
|
repository := newPublishFixture(t)
|
||||||
|
realGo, err := exec.LookPath("go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
goShimDir := t.TempDir()
|
||||||
|
goLog := filepath.Join(goShimDir, "go-commands")
|
||||||
|
goShim := filepath.Join(goShimDir, "go")
|
||||||
|
shimSource := "#!/bin/sh\nset -eu\nprintf '%s\\n' \"$*\" >> \"$RELEASEKIT_REAL_GO_LOG\"\nexec \"$RELEASEKIT_REAL_GO\" \"$@\"\n"
|
||||||
|
if err := os.WriteFile(goShim, []byte(shimSource), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("RELEASEKIT_REAL_GO", realGo)
|
||||||
|
t.Setenv("RELEASEKIT_REAL_GO_LOG", goLog)
|
||||||
|
t.Setenv("GOENV", "off")
|
||||||
|
t.Setenv("PATH", goShimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
writeFile(t, repository.work, "guide.md", "# Guide\n[section](#guide)\n")
|
||||||
|
gitRun(t, repository.work, "add", "guide.md")
|
||||||
|
gitRun(t, repository.work, "commit", "-m", "add Markdown guide")
|
||||||
|
prepareCandidateBuild(t, repository.work, `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Printf("fixture %s\n", buildinfo.Version()) } }
|
||||||
|
`)
|
||||||
|
var validations int
|
||||||
|
candidate, err := releasekit.Check(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repository.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Validation: releasekit.ValidationSpec{Markdown: &releasekit.MarkdownValidationSpec{}},
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error {
|
||||||
|
validations++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Check() error = %v", err)
|
||||||
|
}
|
||||||
|
if validations != 1 || candidate.Commit != gitText(t, repository.work, "rev-parse", "HEAD") {
|
||||||
|
t.Fatalf("candidate = %#v, validation calls = %d", candidate, validations)
|
||||||
|
}
|
||||||
|
goCommands, err := os.ReadFile(goLog)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var discoveries, suites, builds, versions int
|
||||||
|
for _, command := range strings.Split(strings.TrimSpace(string(goCommands)), "\n") {
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(command, "env "):
|
||||||
|
discoveries++
|
||||||
|
case strings.HasPrefix(command, "test "):
|
||||||
|
suites++
|
||||||
|
case strings.HasPrefix(command, "build "):
|
||||||
|
builds++
|
||||||
|
case command == "version":
|
||||||
|
versions++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if discoveries != 2 || suites != 1 || builds != 1 || versions != 1 {
|
||||||
|
t.Fatalf("Go commands = %q; discovery=%d suite=%d build=%d version=%d, want 2, 1, 1, 1", goCommands, discoveries, suites, builds, versions)
|
||||||
|
}
|
||||||
|
if got := gitText(t, repository.work, "status", "--porcelain"); got != "" {
|
||||||
|
t.Fatalf("candidate build dirtied worktree: %s", got)
|
||||||
|
}
|
||||||
|
if paths, err := filepath.Glob(filepath.Join(filepath.Dir(repository.work), ".releasekit-candidate-build-*")); err != nil || len(paths) != 0 {
|
||||||
|
t.Fatalf("temporary candidate output remains: %v, error=%v", paths, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublishBuildFailurePreventsTagCreation(t *testing.T) {
|
||||||
|
repository := newPublishFixture(t)
|
||||||
|
prepareCandidateBuild(t, repository.work, "package main\nfunc main() {}\n")
|
||||||
|
var validations int
|
||||||
|
result, err := releasekit.Publish(context.Background(), releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: repository.work,
|
||||||
|
Product: "Sample App",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
AdditionalChecks: func(context.Context, releasekit.Candidate) error {
|
||||||
|
validations++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/missing",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "build candidate") || result.TagObject != "" {
|
||||||
|
t.Fatalf("Publish() result=%#v error=%v; want build failure before tag creation", result, err)
|
||||||
|
}
|
||||||
|
if validations != 1 {
|
||||||
|
t.Fatalf("validation calls = %d, want 1", validations)
|
||||||
|
}
|
||||||
|
if _, err := exec.Command("git", "--git-dir", repository.bare, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3").CombinedOutput(); err == nil {
|
||||||
|
t.Fatal("build failure published the release tag")
|
||||||
|
}
|
||||||
|
if _, err := exec.Command("git", "-C", repository.work, "show-ref", "--verify", "--quiet", "refs/tags/v1.2.3").CombinedOutput(); err == nil {
|
||||||
|
t.Fatal("build failure created a local release tag")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newBuildConsumer(t *testing.T, mainSource string) string {
|
||||||
|
t.Helper()
|
||||||
|
repository, err := os.MkdirTemp("", "releasekit-build-consumer-")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = os.RemoveAll(repository) })
|
||||||
|
root, err := filepath.Abs(".")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
module := fmt.Sprintf("module example.com/buildfixture\n\ngo 1.26.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", filepath.ToSlash(root))
|
||||||
|
writeBuildFixture(t, repository, "go.mod", module)
|
||||||
|
writeBuildFixture(t, repository, "cmd/app/main.go", mainSource)
|
||||||
|
writeBuildFixture(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n")
|
||||||
|
buildGit(t, repository, "init", "--initial-branch=main")
|
||||||
|
buildGit(t, repository, "config", "user.name", "ReleaseKit Build Test")
|
||||||
|
buildGit(t, repository, "config", "user.email", "releasekit-build@example.test")
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "build fixture")
|
||||||
|
return repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeNestedBuildConsumer(t *testing.T, repository, moduleDir, modulePath, mainSource string) string {
|
||||||
|
t.Helper()
|
||||||
|
root, err := filepath.Abs(".")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
module := fmt.Sprintf("module %s\n\ngo 1.26.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", modulePath, filepath.ToSlash(root))
|
||||||
|
writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "go.mod")), module)
|
||||||
|
writeBuildFixture(t, repository, filepath.ToSlash(filepath.Join(moduleDir, "cmd/app/main.go")), mainSource)
|
||||||
|
return filepath.Join(repository, filepath.FromSlash(moduleDir))
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareCandidateBuild(t *testing.T, repository, mainSource string) {
|
||||||
|
t.Helper()
|
||||||
|
root, err := filepath.Abs(".")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
module := fmt.Sprintf("module example.com/candidatebuild\n\ngo 1.26.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.0.0\n\nreplace gitea.maximumdirect.net/eric/ReleaseKit => %s\n", filepath.ToSlash(root))
|
||||||
|
writeFile(t, repository, "go.mod", module)
|
||||||
|
writeFile(t, repository, ".gitignore", "dist/\n")
|
||||||
|
writeFile(t, repository, "cmd/app/main.go", mainSource)
|
||||||
|
writeFile(t, repository, "cmd/app/main_test.go", "package main\nimport \"testing\"\nfunc TestCandidateFixture(t *testing.T) {}\n")
|
||||||
|
gitRun(t, repository, "add", "--all")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add buildable candidate")
|
||||||
|
gitRun(t, repository, "config", "remote.origin.mirror", "false")
|
||||||
|
gitRun(t, repository, "push", "origin", "HEAD:refs/heads/main")
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeBuildFixture(t *testing.T, directory, name, contents string) {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(directory, filepath.FromSlash(name))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildGit(t *testing.T, directory string, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
command := exec.Command("git", append([]string{"-C", directory}, args...)...)
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("git %v: %v\n%s", args, err, output)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(output))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildSourceEligibilitySurvivesLaterCheckoutCleanup(t *testing.T) {
|
||||||
|
const source = `package main
|
||||||
|
import("fmt";"os";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo")
|
||||||
|
func main(){ if len(os.Args)>1 && os.Args[1]=="version" {fmt.Println("fixture",buildinfo.Version())} }
|
||||||
|
`
|
||||||
|
for _, mode := range []string{"clean", "dirty before build", "changed during build", "commit during build"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
repository := newBuildConsumer(t, source)
|
||||||
|
writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", "# Fixture v1.2.3\n")
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "release note")
|
||||||
|
buildGit(t, repository, "tag", "v1.2.3")
|
||||||
|
mutate := func() { writeBuildFixture(t, repository, "cmd/app/main.go", source+"\n// local change\n") }
|
||||||
|
if mode == "dirty before build" {
|
||||||
|
mutate()
|
||||||
|
}
|
||||||
|
var writer *sourceChangeWriter
|
||||||
|
request := releasekit.BuildRequest{RepositoryDir: repository, Version: "v1.2.3", Spec: releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}, OutputDir: t.TempDir()}
|
||||||
|
if mode == "changed during build" || mode == "commit during build" {
|
||||||
|
writer = &sourceChangeWriter{change: func() {
|
||||||
|
mutate()
|
||||||
|
if mode == "commit during build" {
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "source advanced during compilation")
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
request.Output = writer
|
||||||
|
}
|
||||||
|
result, err := releasekit.Build(context.Background(), request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.SourceVerified != (mode == "clean") {
|
||||||
|
t.Fatalf("source eligibility=%t for %s", result.SourceVerified, mode)
|
||||||
|
}
|
||||||
|
if mode == "clean" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
buildGit(t, repository, "restore", "cmd/app/main.go")
|
||||||
|
buildGit(t, repository, "checkout", "--detach", "v1.2.3")
|
||||||
|
delivered, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{RepositoryDir: repository, Product: "Fixture", Version: "v1.2.3", Prebuilt: &result})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "build source") || delivered.State != releasekit.DeliveryNotAttempted {
|
||||||
|
t.Fatalf("dirty source delivered: %#v %v", delivered, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type sourceChangeWriter struct{ change func() }
|
||||||
|
|
||||||
|
func (w *sourceChangeWriter) Write(p []byte) (int, error) {
|
||||||
|
if w.change != nil {
|
||||||
|
w.change()
|
||||||
|
w.change = nil
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCandidateBuildDoesNotRequireWritableRepositoryParent(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" || os.Getuid() == 0 {
|
||||||
|
t.Skip("requires ordinary Unix permission checks")
|
||||||
|
}
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
import("fmt";"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo")
|
||||||
|
func main(){fmt.Println("fixture",buildinfo.Version())}
|
||||||
|
`)
|
||||||
|
writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", "# Fixture v1.2.3\n")
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "note")
|
||||||
|
parent := t.TempDir()
|
||||||
|
moved := filepath.Join(parent, "repo")
|
||||||
|
if err := os.Rename(repository, moved); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Chmod(parent, 0555); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { os.Chmod(parent, 0700) })
|
||||||
|
_, err := releasekit.Check(context.Background(), releasekit.ReleaseRequest{RepositoryDir: moved, Product: "Fixture", Version: "v1.2.3", AdditionalChecks: func(context.Context, releasekit.Candidate) error { return nil }, Build: &releasekit.BuildSpec{MainPackage: "./cmd/app", BinaryName: "fixture", Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}}}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if status := buildGit(t, moved, "status", "--porcelain"); status != "" {
|
||||||
|
t.Fatalf("candidate dirtied: %s", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
12
buildinfo/version.go
Normal file
12
buildinfo/version.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
// Package buildinfo provides runtime version information for applications
|
||||||
|
// built with ReleaseKit.
|
||||||
|
package buildinfo
|
||||||
|
|
||||||
|
import "gitea.maximumdirect.net/eric/ReleaseKit/internal/runtimeinfo"
|
||||||
|
|
||||||
|
// Version returns the injected release identifier when available. Otherwise,
|
||||||
|
// it returns the executable's main module version, or "dev" when that metadata
|
||||||
|
// is unavailable or identifies a development build.
|
||||||
|
func Version() string {
|
||||||
|
return runtimeinfo.Version()
|
||||||
|
}
|
||||||
81
buildinfo/version_integration_test.go
Normal file
81
buildinfo/version_integration_test.go
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package buildinfo_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestVersionInConsumerExecutable(t *testing.T) {
|
||||||
|
repo, err := filepath.Abs("..")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dir := t.TempDir()
|
||||||
|
module := fmt.Sprintf(`module example.com/versionfixture
|
||||||
|
|
||||||
|
go 1.26.0
|
||||||
|
|
||||||
|
require gitea.maximumdirect.net/eric/ReleaseKit v0.0.0
|
||||||
|
|
||||||
|
replace gitea.maximumdirect.net/eric/ReleaseKit => %s
|
||||||
|
`, filepath.ToSlash(repo))
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(module), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
program := `package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() { fmt.Print(buildinfo.Version()) }
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(program), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
linkerArgs []string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "development build", want: "dev"},
|
||||||
|
{
|
||||||
|
name: "injected release version",
|
||||||
|
linkerArgs: []string{"-X", versioncontract.InjectedVersionLinkerSymbol + "=v1.2.3"},
|
||||||
|
want: "v1.2.3",
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
binary := filepath.Join(t.TempDir(), "versionfixture")
|
||||||
|
args := []string{"build", "-o", binary}
|
||||||
|
if len(test.linkerArgs) > 0 {
|
||||||
|
args = append(args, "-ldflags", fmt.Sprint(test.linkerArgs[0], " ", test.linkerArgs[1]))
|
||||||
|
}
|
||||||
|
args = append(args, ".")
|
||||||
|
|
||||||
|
build := exec.Command("go", args...)
|
||||||
|
build.Dir = dir
|
||||||
|
build.Env = append(os.Environ(), "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off")
|
||||||
|
if output, err := build.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("build consumer fixture: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
|
||||||
|
command := exec.Command(binary)
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("run consumer fixture: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
if string(output) != test.want {
|
||||||
|
t.Fatalf("version output = %q, want %q", output, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
246
check.go
Normal file
246
check.go
Normal file
@@ -0,0 +1,246 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/publish"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrInvalidVersion reports a version that is not stable vMAJOR.MINOR.PATCH.
|
||||||
|
var ErrInvalidVersion = candidate.ErrInvalidVersion
|
||||||
|
|
||||||
|
// ErrUnexpectedPushURL reports that the effective publication push URL does
|
||||||
|
// not exactly match ReleaseRequest.ExpectedPushURL.
|
||||||
|
var ErrUnexpectedPushURL = publish.ErrUnexpectedPushURL
|
||||||
|
|
||||||
|
// Candidate identifies one committed local source revision selected for
|
||||||
|
// validation. ModuleDir is the absolute selected module directory, ModulePath
|
||||||
|
// is its declared Go import path, and Tag is the complete derived Git tag.
|
||||||
|
type Candidate struct {
|
||||||
|
RepositoryDir string
|
||||||
|
ModuleDir string
|
||||||
|
ModulePath string
|
||||||
|
Tag string
|
||||||
|
Commit string
|
||||||
|
Version string // selected stable semantic version.
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReleaseRequest contains the inputs used to validate and optionally build one
|
||||||
|
// local candidate. Remote is retained for publication operations; Check makes
|
||||||
|
// no remote availability claim.
|
||||||
|
type ReleaseRequest struct {
|
||||||
|
// RepositoryDir names a directory within the source Git checkout. Operations
|
||||||
|
// resolve its root before applying repository-relative selections.
|
||||||
|
RepositoryDir string
|
||||||
|
// ModuleDir selects a repository-relative module directory; empty selects
|
||||||
|
// the repository root.
|
||||||
|
ModuleDir string
|
||||||
|
Product string
|
||||||
|
Version string // stable semantic version, independent of the derived Git tag.
|
||||||
|
Remote string
|
||||||
|
// ExpectedPushURL optionally requires Publish's resolved push URL to match
|
||||||
|
// this string exactly before validation or tag creation. Check ignores this
|
||||||
|
// publication-only expectation. A mismatch returns ErrUnexpectedPushURL.
|
||||||
|
ExpectedPushURL string
|
||||||
|
// Validation selects optional checks run against the captured candidate.
|
||||||
|
Validation ValidationSpec
|
||||||
|
// AdditionalChecks optionally runs product checks after shared validation.
|
||||||
|
AdditionalChecks func(context.Context, Candidate) error
|
||||||
|
Build *BuildSpec // optional selected-target build after validation.
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidationSpec selects optional shared validation checks. Its zero value
|
||||||
|
// preserves the current validation behavior. File checks inspect the selected
|
||||||
|
// module and shared-file inputs. Independent nested modules form automatic
|
||||||
|
// input boundaries; vendored files remain included. Referenced destinations
|
||||||
|
// remain available for targeted inspection without expanding the input set.
|
||||||
|
type ValidationSpec struct {
|
||||||
|
// SharedFiles adds repository-relative committed files to optional file
|
||||||
|
// checks. Nil selects the optional root COPYRIGHT, LICENSE, and
|
||||||
|
// docs/oss/attribution.md defaults; an empty non-nil slice selects none.
|
||||||
|
// Explicit files replace the defaults and must exist even when file checks
|
||||||
|
// are off.
|
||||||
|
SharedFiles []string
|
||||||
|
Go GoValidationSpec
|
||||||
|
// GoFormat checks the formatting of committed regular Go source files. It
|
||||||
|
// does not modify repository contents and is disabled when false.
|
||||||
|
GoFormat bool
|
||||||
|
// Markdown selects committed Markdown destination and fragment checking.
|
||||||
|
// Nil disables the check; an empty object enables it with the default
|
||||||
|
// behavior, reporting outside-checkout destinations as out of scope.
|
||||||
|
Markdown *MarkdownValidationSpec
|
||||||
|
// ModuleDistribution selects checks for files that affect module-source
|
||||||
|
// distribution. Its zero value disables those checks.
|
||||||
|
ModuleDistribution ModuleDistributionValidationSpec
|
||||||
|
// FileSize selects a committed-file size check. Nil disables it; an empty
|
||||||
|
// object selects the 1,000,000-byte default.
|
||||||
|
FileSize *FileSizeValidationSpec
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkdownValidationSpec selects behavior for committed Markdown links.
|
||||||
|
type MarkdownValidationSpec struct {
|
||||||
|
// EnforceCheckoutBoundary fails when a local destination resolves outside
|
||||||
|
// the candidate checkout. Submodule contents remain out of scope.
|
||||||
|
EnforceCheckoutBoundary bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileSizeValidationSpec selects a maximum size for each committed blob.
|
||||||
|
type FileSizeValidationSpec struct {
|
||||||
|
// LimitBytes is the maximum decimal byte count. Nil selects 1,000,000;
|
||||||
|
// zero is a zero-byte limit, and negative values are invalid.
|
||||||
|
LimitBytes *int64
|
||||||
|
// Exclusions are literal module-relative file or directory paths.
|
||||||
|
// A directory exclusion includes committed descendants.
|
||||||
|
Exclusions []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ModuleDistributionValidationSpec selects independent module-source
|
||||||
|
// distribution checks.
|
||||||
|
type ModuleDistributionValidationSpec struct {
|
||||||
|
// WorkspaceFiles rejects committed go.work and go.work.sum blobs, including
|
||||||
|
// nested paths and symlink entries. It does not select Go's test workspace.
|
||||||
|
WorkspaceFiles bool
|
||||||
|
// LocalReplacements rejects filesystem replacements in committed go.mod
|
||||||
|
// declarations in the selected inputs, including vendor and explicit shared
|
||||||
|
// files. It does not select Go's workspace.
|
||||||
|
LocalReplacements bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// GoValidationSpec selects checks performed by the Go toolchain.
|
||||||
|
type GoValidationSpec struct {
|
||||||
|
// Race runs the one standard Go test suite with the race detector enabled.
|
||||||
|
Race bool
|
||||||
|
// FullVet runs go vet after the suite instead of the test-time vet pass.
|
||||||
|
// Failures use the go-vet validation check identity.
|
||||||
|
FullVet bool
|
||||||
|
// CompileTargets checks that every package builds for each complete target
|
||||||
|
// pair after testing and vet. Compilation uses CGO_ENABLED=0 and does not
|
||||||
|
// produce artifacts or execute target binaries. Failures use the
|
||||||
|
// package-compile validation check identity.
|
||||||
|
CompileTargets []Target
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check validates one local, committed release candidate. It requires a clean
|
||||||
|
// worktree and index on main, a selected module declaration and module-local
|
||||||
|
// committed note matching Product and Version, and an unused local tag. An
|
||||||
|
// empty ModuleDir selects the repository root. The module declaration
|
||||||
|
// determines the full Git tag for the semantic Version. It always runs the
|
||||||
|
// offline Go test suite with the available compatible local Go toolchain and
|
||||||
|
// Go host target, then calls
|
||||||
|
// AdditionalChecks when supplied. Validation.Go.Race runs that one suite with
|
||||||
|
// the race detector, Validation.Go.FullVet runs go vet after the suite instead
|
||||||
|
// of test-time vet, and Validation.Go.CompileTargets compiles all packages for
|
||||||
|
// each selected GOOS/GOARCH pair after tests and vet with cgo disabled. Package
|
||||||
|
// compilation produces no artifacts and does not execute target binaries.
|
||||||
|
// Validation.GoFormat checks regular committed Go source after those selected
|
||||||
|
// Go checks and before AdditionalChecks. Its zero value disables formatting.
|
||||||
|
// Validation.ModuleDistribution.WorkspaceFiles rejects committed workspace
|
||||||
|
// files after formatting. Its zero value disables that distribution check and
|
||||||
|
// does not change Go's workspace environment.
|
||||||
|
// Validation.ModuleDistribution.LocalReplacements parses committed go.mod
|
||||||
|
// declarations in the selected inputs and rejects filesystem replacements
|
||||||
|
// after workspace-file inspection. Its zero value disables that check.
|
||||||
|
// Validation.FileSize checks each selected committed blob after module
|
||||||
|
// distribution checks. Its nil value disables size checks; an empty object
|
||||||
|
// enables the default limit.
|
||||||
|
// Validation.Markdown checks committed local Markdown destinations and
|
||||||
|
// supported fragments after file-size inspection and before AdditionalChecks.
|
||||||
|
// Nil disables the check; an empty object enables it. Outside-checkout
|
||||||
|
// destinations are reported as out of scope unless the selected specification
|
||||||
|
// enforces the checkout boundary. Submodule contents remain out of scope.
|
||||||
|
// The zero values of all selections preserve the ordinary suite. If
|
||||||
|
// Build selects targets, Check builds them after validation in temporary
|
||||||
|
// storage outside the worktree, then rechecks
|
||||||
|
// branch, HEAD, worktree, index, and local tag state. Success establishes local
|
||||||
|
// candidate evidence only; it does not establish remote availability.
|
||||||
|
func Check(ctx context.Context, request ReleaseRequest) (Candidate, error) {
|
||||||
|
checked, err := candidate.Check(ctx, candidateRequest(request))
|
||||||
|
if err != nil {
|
||||||
|
return publicCandidate(checked), convertValidationError(err)
|
||||||
|
}
|
||||||
|
return publicCandidate(checked), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func publicCandidate(checked candidate.Candidate) Candidate {
|
||||||
|
return Candidate{
|
||||||
|
RepositoryDir: checked.RepositoryDir,
|
||||||
|
ModuleDir: checked.ModuleDir,
|
||||||
|
ModulePath: checked.ModulePath,
|
||||||
|
Tag: checked.Tag,
|
||||||
|
Commit: checked.Commit,
|
||||||
|
Version: checked.Version,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func candidateRequest(request ReleaseRequest) candidate.Request {
|
||||||
|
fileSize := internalFileSizeSettings(request.Validation.FileSize)
|
||||||
|
result := candidate.Request{
|
||||||
|
RepositoryDir: request.RepositoryDir,
|
||||||
|
ModuleDir: request.ModuleDir,
|
||||||
|
Product: request.Product,
|
||||||
|
Version: request.Version,
|
||||||
|
Validation: validation.Settings{
|
||||||
|
Race: request.Validation.Go.Race,
|
||||||
|
FullVet: request.Validation.Go.FullVet,
|
||||||
|
CompileTargets: make([]validation.Target, len(request.Validation.Go.CompileTargets)),
|
||||||
|
SharedFiles: copyStringSlice(request.Validation.SharedFiles),
|
||||||
|
GoFormat: request.Validation.GoFormat,
|
||||||
|
Markdown: internalMarkdownSettings(request.Validation.Markdown),
|
||||||
|
ModuleDistribution: validation.ModuleDistributionSettings{
|
||||||
|
WorkspaceFiles: request.Validation.ModuleDistribution.WorkspaceFiles,
|
||||||
|
LocalReplacements: request.Validation.ModuleDistribution.LocalReplacements,
|
||||||
|
},
|
||||||
|
FileSize: fileSize,
|
||||||
|
},
|
||||||
|
AdditionalChecks: candidateChecks(request.AdditionalChecks),
|
||||||
|
AfterValidate: internalbuild.CandidateCallback(internalBuildSpec(request.Build), request.Output),
|
||||||
|
Output: request.Output,
|
||||||
|
}
|
||||||
|
for index, target := range request.Validation.Go.CompileTargets {
|
||||||
|
result.Validation.CompileTargets[index] = validation.Target{OS: target.OS, Arch: target.Arch}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyStringSlice(values []string) []string {
|
||||||
|
if values == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return append(make([]string, 0, len(values)), values...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func internalMarkdownSettings(spec *MarkdownValidationSpec) *validation.MarkdownSettings {
|
||||||
|
if spec == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &validation.MarkdownSettings{EnforceCheckoutBoundary: spec.EnforceCheckoutBoundary}
|
||||||
|
}
|
||||||
|
|
||||||
|
func internalFileSizeSettings(spec *FileSizeValidationSpec) *validation.FileSizeSettings {
|
||||||
|
if spec == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var limitBytes *int64
|
||||||
|
if spec.LimitBytes != nil {
|
||||||
|
limit := *spec.LimitBytes
|
||||||
|
limitBytes = &limit
|
||||||
|
}
|
||||||
|
return &validation.FileSizeSettings{
|
||||||
|
LimitBytes: limitBytes,
|
||||||
|
Exclusions: append([]string(nil), spec.Exclusions...),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func candidateChecks(checks func(context.Context, Candidate) error) func(context.Context, candidate.Candidate) error {
|
||||||
|
if checks == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return func(ctx context.Context, captured candidate.Candidate) error {
|
||||||
|
return checks(ctx, publicCandidate(captured))
|
||||||
|
}
|
||||||
|
}
|
||||||
38
check_request_test.go
Normal file
38
check_request_test.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestCandidateRequestPreservesSharedFileSelection(t *testing.T) {
|
||||||
|
for _, tt := range []struct {
|
||||||
|
name string
|
||||||
|
input []string
|
||||||
|
wantNil bool
|
||||||
|
wantValues []string
|
||||||
|
}{
|
||||||
|
{name: "omitted defaults", input: nil, wantNil: true},
|
||||||
|
{name: "explicit empty", input: []string{}, wantValues: []string{}},
|
||||||
|
{name: "explicit paths", input: []string{"LICENSE", "docs/shared.md"}, wantValues: []string{"LICENSE", "docs/shared.md"}},
|
||||||
|
} {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
request := ReleaseRequest{Validation: ValidationSpec{SharedFiles: tt.input}}
|
||||||
|
mapped := candidateRequest(request).Validation.SharedFiles
|
||||||
|
if (mapped == nil) != tt.wantNil {
|
||||||
|
t.Fatalf("mapped shared files nil=%t, want %t", mapped == nil, tt.wantNil)
|
||||||
|
}
|
||||||
|
if len(mapped) != len(tt.wantValues) {
|
||||||
|
t.Fatalf("mapped shared files = %#v, want %#v", mapped, tt.wantValues)
|
||||||
|
}
|
||||||
|
for index, value := range tt.wantValues {
|
||||||
|
if mapped[index] != value {
|
||||||
|
t.Fatalf("mapped shared files = %#v, want %#v", mapped, tt.wantValues)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(tt.input) != 0 {
|
||||||
|
request.Validation.SharedFiles[0] = "changed"
|
||||||
|
if mapped[0] != tt.wantValues[0] {
|
||||||
|
t.Fatal("mapped shared-file selection aliases the caller's slice")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
103
cmd/releasekit/assets_test.go
Normal file
103
cmd/releasekit/assets_test.go
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildAndPrebuiltDeliveryUseSameDirectoryBase(t *testing.T) {
|
||||||
|
for _, tt := range []struct {
|
||||||
|
name, module string
|
||||||
|
absolute bool
|
||||||
|
alias bool
|
||||||
|
}{
|
||||||
|
{name: "root relative"},
|
||||||
|
{name: "nested relative", module: "apps/widget"},
|
||||||
|
{name: "nested absolute", module: "apps/widget", absolute: true},
|
||||||
|
{name: "nested checkout alias", module: "apps/widget", absolute: true, alias: true},
|
||||||
|
} {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
repository := newDeliveryBuildRepository(t)
|
||||||
|
moduleDirectory := repository
|
||||||
|
tag := "v1.2.3"
|
||||||
|
if tt.module != "" {
|
||||||
|
moduleDirectory = filepath.Join(repository, filepath.FromSlash(tt.module))
|
||||||
|
tag = tt.module + "/v1.2.3"
|
||||||
|
for _, name := range []string{"go.mod", "main.go", "docs/releases/v1.2.3.md"} {
|
||||||
|
contents, err := os.ReadFile(filepath.Join(repository, filepath.FromSlash(name)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writeRepositoryFile(t, repository, tt.module+"/"+name, string(contents))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeRepositoryFile(t, repository, ".gitignore", "dist/\n")
|
||||||
|
state := &deliveryServerState{tag: tag}
|
||||||
|
server := newDeliveryServer(t, state)
|
||||||
|
defer server.Close()
|
||||||
|
settings := cli.Settings{Product: "Example Product", ModuleDir: tt.module,
|
||||||
|
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
|
||||||
|
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||||
|
}
|
||||||
|
writeDeliveryProfile(t, repository, settings)
|
||||||
|
cliGitRun(t, repository, "add", ".")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "Prepare module source and output exclusion")
|
||||||
|
state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||||
|
cliGitRun(t, repository, "tag", tag)
|
||||||
|
output, resolved := "dist", filepath.Join(moduleDirectory, "dist")
|
||||||
|
if tt.absolute {
|
||||||
|
output = filepath.Join(t.TempDir(), "assets")
|
||||||
|
resolved = output
|
||||||
|
}
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
invocationRepository := repository
|
||||||
|
if tt.alias {
|
||||||
|
invocationRepository = filepath.Join(t.TempDir(), "checkout-alias")
|
||||||
|
if err := os.Symlink(repository, invocationRepository); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if status := run(context.Background(), []string{"build", "--repo", invocationRepository, "--output", output, "v1.2.3"}, &stdout, &stderr); status != 0 {
|
||||||
|
t.Fatalf("build status=%d, stderr=%s", status, stderr.String())
|
||||||
|
}
|
||||||
|
receipt, err := cli.LoadBuildReceipt(filepath.Join(resolved, cli.BuildReceiptName))
|
||||||
|
if err != nil || receipt.ModuleDir != moduleDirectory || receipt.Tag != tag {
|
||||||
|
t.Fatalf("build receipt=%#v, error=%v", receipt, err)
|
||||||
|
}
|
||||||
|
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
|
||||||
|
args := []string{"deliver", "--repo", invocationRepository, "--assets", output, "v1.2.3"}
|
||||||
|
stdout.Reset()
|
||||||
|
stderr.Reset()
|
||||||
|
if status := run(context.Background(), args, &stdout, &stderr); status != 0 || state.releaseCreates != 1 || state.assetUploads != 2 {
|
||||||
|
t.Fatalf("delivery status=%d, creates=%d, uploads=%d, stderr=%s", status, state.releaseCreates, state.assetUploads, stderr.String())
|
||||||
|
}
|
||||||
|
if tt.alias {
|
||||||
|
if status := run(context.Background(), []string{"deliver", "--repo", repository, "--assets", output, "v1.2.3"}, &stdout, &stderr); status != 0 || state.assetUploads != 2 {
|
||||||
|
t.Fatalf("physical-path retry status=%d, uploads=%d, stderr=%s", status, state.assetUploads, stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tt.module != "" {
|
||||||
|
cliGitRun(t, repository, "tag", "v1.2.3")
|
||||||
|
wrongModule := settings
|
||||||
|
wrongModule.ModuleDir = ""
|
||||||
|
invocation := cli.Invocation{Repository: repository, AssetsDir: resolved, Version: "v1.2.3"}
|
||||||
|
requestsBefore := state.apiRequests
|
||||||
|
if status := deliverWithSettings(context.Background(), invocation, wrongModule, &stdout, &stderr); status != 1 || state.apiRequests != requestsBefore {
|
||||||
|
t.Fatalf("wrong module status=%d, requests=%d->%d, stderr=%s", status, requestsBefore, state.apiRequests, stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(receipt.Artifacts[0].Path, []byte("changed"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
requestsBefore := state.apiRequests
|
||||||
|
if status := run(context.Background(), args, &stdout, &stderr); status != 1 || state.apiRequests != requestsBefore {
|
||||||
|
t.Fatalf("changed content status=%d, requests=%d->%d, stderr=%s", status, requestsBefore, state.apiRequests, stderr.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
71
cmd/releasekit/committed_identity_test.go
Normal file
71
cmd/releasekit/committed_identity_test.go
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCandidateCheckUsesCommittedDeclarationSymlink(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
if err := os.Rename(filepath.Join(repository, "go.mod"), filepath.Join(repository, "module.txt")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink("module.txt", filepath.Join(repository, "go.mod")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product"})
|
||||||
|
cliGitRun(t, repository, "add", ".")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "Use committed declaration symlink")
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
if status := run(context.Background(), []string{"check", "--repo", repository, "v1.2.3"}, &stdout, &stderr); status != 0 {
|
||||||
|
t.Fatalf("linked declaration check status=%d stderr=%s", status, stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPageOnlyDeliveryUsesCommittedModuleInSparseCheckout(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
const module = "apps/widget"
|
||||||
|
writeRepositoryFile(t, repository, module+"/go.mod", "module example.com/widget\n\ngo 1.26.0\n")
|
||||||
|
writeRepositoryFile(t, repository, module+"/docs/releases/v1.2.3.md", "# Example Product v1.2.3\n\nNested release note.\n")
|
||||||
|
cliGitRun(t, repository, "add", ".")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "Add sparse release module")
|
||||||
|
state := &deliveryServerState{tag: module + "/v1.2.3"}
|
||||||
|
server := newDeliveryServer(t, state)
|
||||||
|
defer server.Close()
|
||||||
|
writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", ModuleDir: module,
|
||||||
|
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||||
|
})
|
||||||
|
state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||||
|
cliGitRun(t, repository, "tag", state.tag)
|
||||||
|
cliGitRun(t, repository, "checkout", "--detach", state.tag)
|
||||||
|
cliGitRun(t, repository, "sparse-checkout", "set", "--cone", "docs")
|
||||||
|
if _, err := os.Stat(filepath.Join(repository, filepath.FromSlash(module))); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("module fixture is materialized: %v", err)
|
||||||
|
}
|
||||||
|
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
|
||||||
|
gitOnly := t.TempDir()
|
||||||
|
gitPath, err := exec.LookPath("git")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink(gitPath, filepath.Join(gitOnly, "git")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", gitOnly)
|
||||||
|
for _, args := range [][]string{
|
||||||
|
{"deliver", "--repo", repository, "v1.2.3"},
|
||||||
|
{"ci-deliver", "--repo", repository, "--prepared", "--expected-module", module, "--commit", state.commit, state.tag},
|
||||||
|
} {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
if status := run(context.Background(), args, &stdout, &stderr); status != 0 || state.releaseCreates != 1 || state.assetUploads != 0 {
|
||||||
|
t.Fatalf("%s sparse delivery status=%d creates=%d uploads=%d stderr=%s", args[0], status, state.releaseCreates, state.assetUploads, stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
54
cmd/releasekit/example_source_test.go
Normal file
54
cmd/releasekit/example_source_test.go
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMultiModuleExampleSetupUsesCurrentSourceTool(t *testing.T) {
|
||||||
|
root := cliRepositoryRoot(t)
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
copyExampleTree(t, filepath.Join(root, "examples", "multi-module"), repository)
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
environment := append(os.Environ(), "GOTOOLCHAIN=local", "GOWORK=off", "GOPROXY=off", "GOSUMDB=off", "GOFLAGS=")
|
||||||
|
goCommand := func(directory string, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
command := exec.Command("go", args...)
|
||||||
|
command.Dir, command.Env = directory, environment
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("go %q: %v\n%s", args, err, output)
|
||||||
|
}
|
||||||
|
return string(output)
|
||||||
|
}
|
||||||
|
selections := []struct {
|
||||||
|
directory, profile, product, version string
|
||||||
|
}{
|
||||||
|
{".", "releasekit-root.json", "Example Consumer", "v1.2.3"},
|
||||||
|
{"integrations/ckconfig", "releasekit-ckconfig.json", "Example Consumer Integration", "v1.2.3"},
|
||||||
|
{"integrations/core/v2", "releasekit-core-v2.json", "Example Consumer Core v2", "v2.1.0"},
|
||||||
|
}
|
||||||
|
for _, selected := range selections {
|
||||||
|
directory := filepath.Join(repository, filepath.FromSlash(selected.directory))
|
||||||
|
if selected.directory != "integrations/core/v2" {
|
||||||
|
writeRepositoryFile(t, repository, selected.directory+"/source.go", "package candidate\n")
|
||||||
|
}
|
||||||
|
goCommand(directory, "mod", "edit", "-require="+module+"@v0.0.0", "-replace="+module+"="+root, "-tool="+module+"/cmd/releasekit")
|
||||||
|
goCommand(directory, "mod", "tidy")
|
||||||
|
writeRepositoryFile(t, repository, selected.directory+"/docs/releases/"+selected.version+".md", "# "+selected.product+" "+selected.version+"\n\nSource verification fixture.\n")
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "add", ".")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "Select current source in disposable example")
|
||||||
|
for _, selected := range selections {
|
||||||
|
output := goCommand(filepath.Join(repository, filepath.FromSlash(selected.directory)), "tool", "releasekit", "check", "--config", selected.profile, selected.version)
|
||||||
|
if !strings.Contains(output, "is valid") {
|
||||||
|
t.Fatalf("source-selected check output=%s", output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if status := cliGitOutput(t, repository, "status", "--porcelain"); status != "" {
|
||||||
|
t.Fatalf("source verification changed committed fixture: %s", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
322
cmd/releasekit/internal/cli/config.go
Normal file
322
cmd/releasekit/internal/cli/config.go
Normal file
@@ -0,0 +1,322 @@
|
|||||||
|
// Package cli owns command parsing, profile settings, and child-command
|
||||||
|
// adaptation for the ReleaseKit executable.
|
||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
const Usage = "usage: releasekit version\n releasekit check [--repo DIR] [--config FILE] VERSION\n releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] VERSION\n releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION\n releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION\n releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] --commit OID TAG"
|
||||||
|
|
||||||
|
type Command string
|
||||||
|
|
||||||
|
const (
|
||||||
|
VersionCommand Command = "version"
|
||||||
|
CheckAction Command = "check"
|
||||||
|
PublishAction Command = "publish"
|
||||||
|
BuildAction Command = "build"
|
||||||
|
DeliveryAction Command = "deliver"
|
||||||
|
CIDeliveryAction Command = "ci-deliver"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Invocation contains parsed command settings owned by the CLI adapter.
|
||||||
|
type Invocation struct {
|
||||||
|
Command Command
|
||||||
|
Repository string
|
||||||
|
ConfigPath string
|
||||||
|
OutputDir string
|
||||||
|
AssetsDir string
|
||||||
|
Remote string
|
||||||
|
Commit string
|
||||||
|
Version string
|
||||||
|
ExpectedModule string
|
||||||
|
ExpectedTag string
|
||||||
|
Prepared bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse accepts only commands that have been implemented by the executable.
|
||||||
|
func Parse(args []string) (Invocation, error) {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return Invocation{}, errors.New("a command is required")
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case string(VersionCommand):
|
||||||
|
if len(args) != 1 {
|
||||||
|
return Invocation{}, errors.New("version takes no arguments")
|
||||||
|
}
|
||||||
|
return Invocation{Command: VersionCommand}, nil
|
||||||
|
case string(CheckAction), string(PublishAction), string(BuildAction), string(DeliveryAction), string(CIDeliveryAction):
|
||||||
|
action := Command(args[0])
|
||||||
|
flags := flag.NewFlagSet(string(action), flag.ContinueOnError)
|
||||||
|
flags.SetOutput(io.Discard)
|
||||||
|
repository := flags.String("repo", ".", "repository directory")
|
||||||
|
configPath := flags.String("config", "", "profile path")
|
||||||
|
var outputDir string
|
||||||
|
if action == BuildAction {
|
||||||
|
flags.StringVar(&outputDir, "output", "", "build output directory")
|
||||||
|
}
|
||||||
|
var assetsDir string
|
||||||
|
if action == DeliveryAction {
|
||||||
|
flags.StringVar(&assetsDir, "assets", "", "verified build assets directory")
|
||||||
|
}
|
||||||
|
var remote *string
|
||||||
|
expectedModule := ""
|
||||||
|
if action == PublishAction || action == CIDeliveryAction {
|
||||||
|
flags.StringVar(&expectedModule, "expected-module", "", "expected module directory from a launcher mapping")
|
||||||
|
}
|
||||||
|
expectedCommit := ""
|
||||||
|
prepared := false
|
||||||
|
if action == CIDeliveryAction {
|
||||||
|
remote = flags.String("remote", "origin", "Git remote")
|
||||||
|
flags.StringVar(&expectedCommit, "commit", "", "expected tagged commit")
|
||||||
|
flags.BoolVar(&prepared, "prepared", false, "verify an already prepared tagged checkout without fetching or checkout")
|
||||||
|
}
|
||||||
|
if err := flags.Parse(args[1:]); err != nil {
|
||||||
|
return Invocation{}, err
|
||||||
|
}
|
||||||
|
if flags.NArg() != 1 {
|
||||||
|
return Invocation{}, fmt.Errorf("%s requires one version argument", action)
|
||||||
|
}
|
||||||
|
if action == CIDeliveryAction && expectedCommit == "" {
|
||||||
|
return Invocation{}, errors.New("ci-deliver requires --commit OID")
|
||||||
|
}
|
||||||
|
if action == CIDeliveryAction && !validGitObjectID(expectedCommit) {
|
||||||
|
return Invocation{}, errors.New("ci-deliver --commit must be a full Git object ID")
|
||||||
|
}
|
||||||
|
version := flags.Arg(0)
|
||||||
|
expectedTag := ""
|
||||||
|
if action == CIDeliveryAction {
|
||||||
|
expectedTag = version
|
||||||
|
if slash := strings.LastIndex(version, "/"); slash >= 0 {
|
||||||
|
version = version[slash+1:]
|
||||||
|
}
|
||||||
|
if !versioncontract.ValidStableVersion(version) {
|
||||||
|
return Invocation{}, errors.New("ci-deliver TAG must end in a stable vMAJOR.MINOR.PATCH version")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !versioncontract.ValidStableVersion(version) {
|
||||||
|
return Invocation{}, errors.New("VERSION must be a stable vMAJOR.MINOR.PATCH version")
|
||||||
|
}
|
||||||
|
parsedRemote := ""
|
||||||
|
if remote != nil {
|
||||||
|
parsedRemote = *remote
|
||||||
|
}
|
||||||
|
return Invocation{Command: action, Repository: *repository, ConfigPath: *configPath, OutputDir: outputDir, AssetsDir: assetsDir, Remote: parsedRemote, Commit: expectedCommit, Version: version, ExpectedModule: expectedModule, ExpectedTag: expectedTag, Prepared: prepared}, nil
|
||||||
|
default:
|
||||||
|
return Invocation{}, fmt.Errorf("unknown command %q", args[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validGitObjectID(value string) bool {
|
||||||
|
if len(value) != 40 && len(value) != 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, char := range value {
|
||||||
|
if (char < '0' || char > '9') && (char < 'a' || char > 'f') && (char < 'A' || char > 'F') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckCommand contains one direct child-process invocation from a profile.
|
||||||
|
type CheckCommand struct {
|
||||||
|
Args []string `json:"args"`
|
||||||
|
Env map[string]string `json:"env,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Settings contains the product, remote, publication expectation, shared
|
||||||
|
// validation selections, and check commands read from a releasekit.json profile.
|
||||||
|
type Settings struct {
|
||||||
|
Product string `json:"product"`
|
||||||
|
ModuleDir string `json:"module_dir,omitempty"`
|
||||||
|
Remote string `json:"remote,omitempty"`
|
||||||
|
ExpectedPushURL string `json:"expected_push_url,omitempty"`
|
||||||
|
Checks []CheckCommand `json:"checks,omitempty"`
|
||||||
|
Validation *ValidationSettings `json:"validation,omitempty"`
|
||||||
|
Build *BuildSettings `json:"build,omitempty"`
|
||||||
|
Delivery *DeliverySettings `json:"delivery,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidationSettings selects shared candidate checks in a release profile.
|
||||||
|
type ValidationSettings struct {
|
||||||
|
// SharedFiles selects committed files relative to the repository root.
|
||||||
|
// Nil uses optional defaults; a non-nil empty slice selects no shared files.
|
||||||
|
SharedFiles []string `json:"shared_files"`
|
||||||
|
Go GoValidationSettings `json:"go,omitempty"`
|
||||||
|
// GoFormat checks the formatting of committed regular Go source files.
|
||||||
|
// Omitted or false disables the check.
|
||||||
|
GoFormat bool `json:"go_format,omitempty"`
|
||||||
|
Markdown *MarkdownSettings `json:"markdown,omitempty"`
|
||||||
|
ModuleDistribution ModuleDistributionSettings `json:"module_distribution,omitempty"`
|
||||||
|
// FileSize checks the size of each committed blob. Null or omission disables
|
||||||
|
// the check; an empty object enables the default limit.
|
||||||
|
FileSize *FileSizeSettings `json:"file_size,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkdownSettings selects committed Markdown destination and fragment checks.
|
||||||
|
type MarkdownSettings struct {
|
||||||
|
// EnforceCheckoutBoundary fails local destinations that resolve outside
|
||||||
|
// the candidate checkout. Submodule contents remain out of scope.
|
||||||
|
EnforceCheckoutBoundary bool `json:"enforce_checkout_boundary,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileSizeSettings selects the maximum committed-file size and literal exclusions.
|
||||||
|
type FileSizeSettings struct {
|
||||||
|
LimitBytes *int64 `json:"limit_bytes,omitempty"`
|
||||||
|
Exclusions []string `json:"exclusions,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ModuleDistributionSettings selects committed module-source distribution checks.
|
||||||
|
type ModuleDistributionSettings struct {
|
||||||
|
// WorkspaceFiles rejects committed go.work and go.work.sum blobs.
|
||||||
|
// Omitted or false disables the check.
|
||||||
|
WorkspaceFiles bool `json:"workspace_files,omitempty"`
|
||||||
|
// LocalReplacements rejects filesystem replacements in committed go.mod files.
|
||||||
|
// Omitted or false disables the check.
|
||||||
|
LocalReplacements bool `json:"local_replacements,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GoValidationSettings selects checks performed by the Go toolchain.
|
||||||
|
type GoValidationSettings struct {
|
||||||
|
Race bool `json:"race,omitempty"`
|
||||||
|
FullVet bool `json:"full_vet,omitempty"`
|
||||||
|
CompileTargets []string `json:"compile_targets,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeliverySettings selects the hosted Gitea release destination.
|
||||||
|
type DeliverySettings struct {
|
||||||
|
BaseURL string `json:"base_url"`
|
||||||
|
Owner string `json:"owner"`
|
||||||
|
Repository string `json:"repository"`
|
||||||
|
TokenEnv string `json:"token_env,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildSettings selects the Go application package, artifact name, and targets.
|
||||||
|
type BuildSettings struct {
|
||||||
|
MainPackage string `json:"main_package,omitempty"`
|
||||||
|
BinaryName string `json:"binary_name,omitempty"`
|
||||||
|
Targets []string `json:"targets,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadSettings reads a profile path relative to repoDir unless it is absolute.
|
||||||
|
// An empty configPath selects <repoDir>/releasekit.json.
|
||||||
|
func LoadSettings(repoDir, configPath string) (Settings, error) {
|
||||||
|
resolvedRepo, err := filepath.Abs(repoDir)
|
||||||
|
if err != nil {
|
||||||
|
return Settings{}, fmt.Errorf("resolve repository directory %q: %w", repoDir, err)
|
||||||
|
}
|
||||||
|
if configPath == "" {
|
||||||
|
configPath = "releasekit.json"
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(configPath) {
|
||||||
|
configPath = filepath.Join(resolvedRepo, configPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.Open(configPath)
|
||||||
|
if err != nil {
|
||||||
|
return Settings{}, fmt.Errorf("open profile %q: %w", configPath, err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
var settings Settings
|
||||||
|
decoder := json.NewDecoder(file)
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if err := decoder.Decode(&settings); err != nil {
|
||||||
|
return Settings{}, fmt.Errorf("decode profile %q: %w", configPath, err)
|
||||||
|
}
|
||||||
|
var extra any
|
||||||
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||||
|
if err == nil {
|
||||||
|
return Settings{}, fmt.Errorf("decode profile %q: multiple JSON values", configPath)
|
||||||
|
}
|
||||||
|
return Settings{}, fmt.Errorf("decode profile %q: %w", configPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(settings.Product) == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: product is required", configPath)
|
||||||
|
}
|
||||||
|
if settings.Remote == "" {
|
||||||
|
settings.Remote = "origin"
|
||||||
|
}
|
||||||
|
for i, check := range settings.Checks {
|
||||||
|
if len(check.Args) == 0 || check.Args[0] == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: checks[%d].args must include a command", configPath, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if settings.Build != nil {
|
||||||
|
if len(settings.Build.Targets) != 0 {
|
||||||
|
if strings.TrimSpace(settings.Build.MainPackage) == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.main_package is required when targets are selected", configPath)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(settings.Build.BinaryName) == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.binary_name is required when targets are selected", configPath)
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(settings.Build.BinaryName, "/\\\r\n") {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.binary_name must be a filename component", configPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i, target := range settings.Build.Targets {
|
||||||
|
if strings.Count(target, "/") != 1 {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.targets[%d] must be GOOS/GOARCH", configPath, i)
|
||||||
|
}
|
||||||
|
goos, goarch, _ := strings.Cut(target, "/")
|
||||||
|
if strings.TrimSpace(goos) == "" || strings.TrimSpace(goarch) == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.targets[%d] must be GOOS/GOARCH", configPath, i)
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(goos+goarch, "\\\r\n") {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: build.targets[%d] contains an unsafe filename component", configPath, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if settings.Validation != nil {
|
||||||
|
if fileSize := settings.Validation.FileSize; fileSize != nil && fileSize.LimitBytes != nil && *fileSize.LimitBytes < 0 {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: validation.file_size.limit_bytes must not be negative", configPath)
|
||||||
|
}
|
||||||
|
for i, target := range settings.Validation.Go.CompileTargets {
|
||||||
|
if strings.Count(target, "/") != 1 {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: validation.go.compile_targets[%d] must be GOOS/GOARCH", configPath, i)
|
||||||
|
}
|
||||||
|
goos, goarch, _ := strings.Cut(target, "/")
|
||||||
|
if strings.TrimSpace(goos) == "" || strings.TrimSpace(goarch) == "" {
|
||||||
|
return Settings{}, fmt.Errorf("profile %q: validation.go.compile_targets[%d] must be GOOS/GOARCH", configPath, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return settings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunChecks runs configured argument vectors in dir. Each command receives
|
||||||
|
// its own environment overlay and inherits the remaining process environment.
|
||||||
|
func RunChecks(ctx context.Context, dir string, checks []CheckCommand, ownedEnv map[string]string, stdout, stderr io.Writer) error {
|
||||||
|
for i, check := range checks {
|
||||||
|
environment := make(map[string]string, len(check.Env)+len(ownedEnv))
|
||||||
|
for key, value := range check.Env {
|
||||||
|
environment[key] = value
|
||||||
|
}
|
||||||
|
for key, value := range ownedEnv {
|
||||||
|
environment[key] = value
|
||||||
|
}
|
||||||
|
if err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: check.Args,
|
||||||
|
Dir: dir,
|
||||||
|
Env: environment,
|
||||||
|
Stdout: stdout,
|
||||||
|
Stderr: stderr,
|
||||||
|
}); err != nil {
|
||||||
|
return fmt.Errorf("run check %d: %w", i+1, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
411
cmd/releasekit/internal/cli/config_test.go
Normal file
411
cmd/releasekit/internal/cli/config_test.go
Normal file
@@ -0,0 +1,411 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParse(t *testing.T) {
|
||||||
|
invocation, err := Parse([]string{"version"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if invocation.Command != VersionCommand {
|
||||||
|
t.Fatalf("Parse() command = %q, want %q", invocation.Command, VersionCommand)
|
||||||
|
}
|
||||||
|
check, err := Parse([]string{"check", "--repo", "repository with spaces", "--config", "profiles/release config.json", "v1.2.3"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if check.Command != CheckAction || check.Repository != "repository with spaces" || check.ConfigPath != "profiles/release config.json" || check.Version != "v1.2.3" {
|
||||||
|
t.Fatalf("Parse(check) = %#v", check)
|
||||||
|
}
|
||||||
|
publish, err := Parse([]string{"publish", "--repo", "candidate", "--config", "releasekit.json", "v1.2.4"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if publish.Command != PublishAction || publish.Repository != "candidate" || publish.ConfigPath != "releasekit.json" || publish.Version != "v1.2.4" {
|
||||||
|
t.Fatalf("Parse(publish) = %#v", publish)
|
||||||
|
}
|
||||||
|
publishMapped, err := Parse([]string{"publish", "--repo", "candidate", "--expected-module", "integrations/ckconfig", "v1.2.4"})
|
||||||
|
if err != nil || publishMapped.ExpectedModule != "integrations/ckconfig" {
|
||||||
|
t.Fatalf("Parse(publish --expected-module) = %#v, error = %v", publishMapped, err)
|
||||||
|
}
|
||||||
|
build, err := Parse([]string{"build", "--repo", "candidate", "--config", "releasekit.json", "--output", "output with spaces", "v1.2.5"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if build.Command != BuildAction || build.Repository != "candidate" || build.ConfigPath != "releasekit.json" || build.OutputDir != "output with spaces" || build.Version != "v1.2.5" {
|
||||||
|
t.Fatalf("Parse(build) = %#v", build)
|
||||||
|
}
|
||||||
|
deliver, err := Parse([]string{"deliver", "--repo", "candidate", "--config", "releasekit.json", "--assets", "assets with spaces", "v1.2.6"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if deliver.Command != DeliveryAction || deliver.Repository != "candidate" || deliver.ConfigPath != "releasekit.json" || deliver.AssetsDir != "assets with spaces" || deliver.Version != "v1.2.6" {
|
||||||
|
t.Fatalf("Parse(deliver) = %#v", deliver)
|
||||||
|
}
|
||||||
|
ciDelivery, err := Parse([]string{"ci-deliver", "--repo", "candidate", "--config", "profiles/release config.json", "--remote", "upstream", "--prepared", "--expected-module", "integrations/ckconfig", "--commit", "0123456789abcdef0123456789abcdef01234567", "integrations/ckconfig/v1.2.7"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ciDelivery.Command != CIDeliveryAction || ciDelivery.Repository != "candidate" || ciDelivery.ConfigPath != "profiles/release config.json" || ciDelivery.Remote != "upstream" || ciDelivery.Commit != "0123456789abcdef0123456789abcdef01234567" || ciDelivery.Version != "v1.2.7" || ciDelivery.ExpectedTag != "integrations/ckconfig/v1.2.7" || ciDelivery.ExpectedModule != "integrations/ckconfig" || !ciDelivery.Prepared {
|
||||||
|
t.Fatalf("Parse(ci-deliver) = %#v", ciDelivery)
|
||||||
|
}
|
||||||
|
ciDefault, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.8"})
|
||||||
|
if err != nil || ciDefault.Remote != "origin" {
|
||||||
|
t.Fatalf("Parse(ci-deliver defaults) = %#v, error = %v", ciDefault, err)
|
||||||
|
}
|
||||||
|
if _, err := Parse([]string{"ci-deliver", "v1.2.3"}); err == nil || !strings.Contains(err.Error(), "--commit") {
|
||||||
|
t.Fatalf("Parse(ci-deliver without commit) error = %v, want required commit", err)
|
||||||
|
}
|
||||||
|
if _, err := Parse([]string{"ci-deliver", "--commit", "abc123", "v1.2.3"}); err == nil || !strings.Contains(err.Error(), "full Git object ID") {
|
||||||
|
t.Fatalf("Parse(ci-deliver with abbreviated commit) error = %v, want full object ID error", err)
|
||||||
|
}
|
||||||
|
if _, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "integrations/ckconfig/latest"}); err == nil || !strings.Contains(err.Error(), "stable vMAJOR.MINOR.PATCH") {
|
||||||
|
t.Fatalf("Parse(ci-deliver unstable terminal tag) error = %v", err)
|
||||||
|
}
|
||||||
|
if _, err := Parse([]string{"check", "v1.2.3", "--repo", "repository"}); err == nil {
|
||||||
|
t.Fatal("Parse accepted a flag after the version")
|
||||||
|
}
|
||||||
|
if _, err := Parse([]string{"ci-deliver", "--commit", "0123456789abcdef0123456789abcdef01234567", "v1.2.3", "--repo", "repository"}); err == nil {
|
||||||
|
t.Fatal("Parse accepted a ci-deliver flag after the version")
|
||||||
|
}
|
||||||
|
if _, err := Parse(nil); err == nil || !strings.Contains(err.Error(), "command is required") {
|
||||||
|
t.Fatalf("Parse(nil) error = %v, want missing-command error", err)
|
||||||
|
}
|
||||||
|
if _, err := Parse([]string{"unknown"}); err == nil || !strings.Contains(err.Error(), "unknown command") {
|
||||||
|
t.Fatalf("Parse(unknown) error = %v, want unknown-command error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsResolvesPathsAndPreservesArguments(t *testing.T) {
|
||||||
|
repoDir := filepath.Join(t.TempDir(), "repository with spaces")
|
||||||
|
profileDir := filepath.Join(repoDir, "profiles with spaces")
|
||||||
|
if err := os.MkdirAll(profileDir, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := Settings{
|
||||||
|
Product: "Example Product",
|
||||||
|
Remote: "upstream",
|
||||||
|
Checks: []CheckCommand{{
|
||||||
|
Args: []string{"sh", "scripts/check release.sh", "two words"},
|
||||||
|
Env: map[string]string{"RELEASE_MODE": "candidate check"},
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
contents, err := json.Marshal(want)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(profileDir, "release profile.json"), contents, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := LoadSettings(repoDir, filepath.Join("profiles with spaces", "release profile.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got.Product != want.Product || got.Remote != want.Remote || len(got.Checks) != 1 {
|
||||||
|
t.Fatalf("LoadSettings() = %#v, want product, remote, and one check", got)
|
||||||
|
}
|
||||||
|
if got.Checks[0].Args[1] != "scripts/check release.sh" || got.Checks[0].Args[2] != "two words" {
|
||||||
|
t.Fatalf("check arguments were changed: %#v", got.Checks[0].Args)
|
||||||
|
}
|
||||||
|
if got.Checks[0].Env["RELEASE_MODE"] != "candidate check" {
|
||||||
|
t.Fatalf("check environment = %#v", got.Checks[0].Env)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsDefaultsRemoteAndConfigPath(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
contents := `{"product":"Example"}`
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
if err := os.WriteFile(profilePath, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
}{
|
||||||
|
{name: "default path"},
|
||||||
|
{name: "absolute path", path: profilePath},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
settings, err := LoadSettings(repoDir, test.path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.Remote != "origin" {
|
||||||
|
t.Fatalf("default remote = %q, want origin", settings.Remote)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsReadsGoValidation(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
if err := os.WriteFile(profilePath, []byte(`{"product":"Example","expected_push_url":"ssh://git.example/owner/repo.git","validation":{"go_format":true,"markdown":{"enforce_checkout_boundary":true},"module_distribution":{"workspace_files":true,"local_replacements":true},"file_size":{"limit_bytes":0,"exclusions":["assets"]},"go":{"race":true,"full_vet":true,"compile_targets":["linux/amd64","linux/arm64","darwin/arm64"]}}}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
settings, err := LoadSettings(repoDir, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.Validation == nil || !settings.Validation.GoFormat || settings.Validation.Markdown == nil || !settings.Validation.Markdown.EnforceCheckoutBoundary || !settings.Validation.ModuleDistribution.WorkspaceFiles || !settings.Validation.ModuleDistribution.LocalReplacements || !settings.Validation.Go.Race || !settings.Validation.Go.FullVet {
|
||||||
|
t.Fatalf("validation settings = %#v, want Go formatting, workspace inspection, race, and full vet enabled", settings.Validation)
|
||||||
|
}
|
||||||
|
if settings.Validation.FileSize == nil || settings.Validation.FileSize.LimitBytes == nil || *settings.Validation.FileSize.LimitBytes != 0 || len(settings.Validation.FileSize.Exclusions) != 1 || settings.Validation.FileSize.Exclusions[0] != "assets" {
|
||||||
|
t.Fatalf("file size settings = %#v, want explicit zero limit and exclusions", settings.Validation.FileSize)
|
||||||
|
}
|
||||||
|
if got, want := strings.Join(settings.Validation.Go.CompileTargets, ","), "linux/amd64,linux/arm64,darwin/arm64"; got != want {
|
||||||
|
t.Fatalf("compile targets = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if settings.ExpectedPushURL != "ssh://git.example/owner/repo.git" {
|
||||||
|
t.Fatalf("expected push URL = %q", settings.ExpectedPushURL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsPreservesSharedFilesSelection(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
profileDir := filepath.Join(repoDir, "profiles")
|
||||||
|
if err := os.MkdirAll(profileDir, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
profile string
|
||||||
|
wantNil bool
|
||||||
|
wantFile string
|
||||||
|
}{
|
||||||
|
{name: "omitted", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{}}`, wantNil: true},
|
||||||
|
{name: "null", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{"shared_files":null}}`, wantNil: true},
|
||||||
|
{name: "empty", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{"shared_files":[]}}`},
|
||||||
|
{name: "selected", profile: `{"product":"Example","module_dir":"integrations/ckconfig","validation":{"shared_files":["../README.md"]}}`, wantFile: "../README.md"},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
path := filepath.Join(profileDir, "release.json")
|
||||||
|
if err := os.WriteFile(path, []byte(test.profile), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(repoDir, filepath.Join("profiles", "release.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.ModuleDir != "integrations/ckconfig" {
|
||||||
|
t.Fatalf("module_dir = %q", settings.ModuleDir)
|
||||||
|
}
|
||||||
|
if settings.Validation == nil || (settings.Validation.SharedFiles == nil) != test.wantNil {
|
||||||
|
t.Fatalf("shared_files = %#v, want nil=%t", settings.Validation, test.wantNil)
|
||||||
|
}
|
||||||
|
if test.wantFile != "" && (len(settings.Validation.SharedFiles) != 1 || settings.Validation.SharedFiles[0] != test.wantFile) {
|
||||||
|
t.Fatalf("shared_files = %#v, want %q", settings.Validation.SharedFiles, test.wantFile)
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(settings)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var roundTrip Settings
|
||||||
|
if err := json.Unmarshal(encoded, &roundTrip); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if (roundTrip.Validation.SharedFiles == nil) != test.wantNil {
|
||||||
|
t.Fatalf("serialized shared_files = %#v, want nil=%t; JSON=%s", roundTrip.Validation.SharedFiles, test.wantNil, encoded)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsPreservesMarkdownObjectSelection(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
profile string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "omitted", profile: `{"product":"Example","validation":{}}`},
|
||||||
|
{name: "null", profile: `{"product":"Example","validation":{"markdown":null}}`},
|
||||||
|
{name: "empty object", profile: `{"product":"Example","validation":{"markdown":{}}}`, want: true},
|
||||||
|
{name: "boundary enabled", profile: `{"product":"Example","validation":{"markdown":{"enforce_checkout_boundary":true}}}`, want: true},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
if err := os.WriteFile(profilePath, []byte(test.profile), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(repoDir, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := settings.Validation != nil && settings.Validation.Markdown != nil
|
||||||
|
if got != test.want {
|
||||||
|
t.Fatalf("Markdown selected = %t, want %t", got, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsPreservesEmptyAndNullFileSize(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
profile string
|
||||||
|
enabled bool
|
||||||
|
}{
|
||||||
|
{name: "empty object", profile: `{"product":"Example","validation":{"file_size":{}}}`, enabled: true},
|
||||||
|
{name: "default limit", profile: `{"product":"Example","validation":{"file_size":{"limit_bytes":null}}}`, enabled: true},
|
||||||
|
{name: "null object", profile: `{"product":"Example","validation":{"file_size":null}}`},
|
||||||
|
{name: "omitted object", profile: `{"product":"Example","validation":{}}`},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
if err := os.WriteFile(profilePath, []byte(test.profile), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(repoDir, profilePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := settings.Validation != nil && settings.Validation.FileSize != nil
|
||||||
|
if got != test.enabled {
|
||||||
|
t.Fatalf("FileSize enabled = %t, want %t", got, test.enabled)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsRejectsNegativeFileSizeLimit(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
profilePath := filepath.Join(repoDir, "releasekit.json")
|
||||||
|
profile := `{"product":"Example","validation":{"file_size":{"limit_bytes":-1}}}`
|
||||||
|
if err := os.WriteFile(profilePath, []byte(profile), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadSettings(repoDir, profilePath); err == nil || !strings.Contains(err.Error(), "validation.file_size.limit_bytes") {
|
||||||
|
t.Fatalf("LoadSettings() error = %v, want invalid negative file-size limit", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExampleProfileLoads(t *testing.T) {
|
||||||
|
repoDir, err := filepath.Abs(filepath.Join("..", "..", "..", ".."))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(repoDir, filepath.Join("examples", "releasekit.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.Product != "Example" || settings.Remote != "origin" || len(settings.Checks) != 0 {
|
||||||
|
t.Fatalf("example settings = %#v", settings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildProfileLoads(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
path := filepath.Join(repoDir, "profile.json")
|
||||||
|
if err := os.WriteFile(path, []byte(`{"product":"Example","build":{"main_package":"./cmd/app","binary_name":"example","targets":["linux/amd64","darwin/arm64"]}}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(repoDir, path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.Build == nil || settings.Build.MainPackage != "./cmd/app" || settings.Build.BinaryName != "example" || len(settings.Build.Targets) != 2 {
|
||||||
|
t.Fatalf("build settings = %#v", settings.Build)
|
||||||
|
}
|
||||||
|
repoDir, err = filepath.Abs(filepath.Join("..", "..", "..", ".."))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
example, err := LoadSettings(repoDir, filepath.Join("examples", "releasekit-binary.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if example.Build == nil || len(example.Build.Targets) != 3 {
|
||||||
|
t.Fatalf("binary example settings = %#v", example.Build)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadSettingsRejectsInvalidProfiles(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
content string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "missing product", content: `{}`, want: "product is required"},
|
||||||
|
{name: "unknown top-level field", content: `{"product":"Example","future":{}}`, want: "unknown field"},
|
||||||
|
{name: "build package required", content: `{"product":"Example","build":{"binary_name":"example","targets":["linux/amd64"]}}`, want: "build.main_package is required"},
|
||||||
|
{name: "build target format", content: `{"product":"Example","build":{"main_package":".","binary_name":"example","targets":["linux"]}}`, want: "must be GOOS/GOARCH"},
|
||||||
|
{name: "compile target format", content: `{"product":"Example","validation":{"go":{"compile_targets":["linux"]}}}`, want: "validation.go.compile_targets[0] must be GOOS/GOARCH"},
|
||||||
|
{name: "compile target missing architecture", content: `{"product":"Example","validation":{"go":{"compile_targets":["linux/"]}}}`, want: "validation.go.compile_targets[0] must be GOOS/GOARCH"},
|
||||||
|
{name: "compile target missing operating system", content: `{"product":"Example","validation":{"go":{"compile_targets":["/amd64"]}}}`, want: "validation.go.compile_targets[0] must be GOOS/GOARCH"},
|
||||||
|
{name: "compile target repeated separator", content: `{"product":"Example","validation":{"go":{"compile_targets":["linux/amd64/arm64"]}}}`, want: "validation.go.compile_targets[0] must be GOOS/GOARCH"},
|
||||||
|
{name: "unsafe binary name", content: `{"product":"Example","build":{"main_package":".","binary_name":"../example","targets":["linux/amd64"]}}`, want: "filename component"},
|
||||||
|
{name: "unknown command field", content: `{"product":"Example","checks":[{"args":["true"],"shell":true}]}`, want: "unknown field"},
|
||||||
|
{name: "command is required", content: `{"product":"Example","checks":[{"args":[]}]}`, want: "must include a command"},
|
||||||
|
{name: "multiple JSON values", content: `{"product":"Example"}{"product":"Other"}`, want: "multiple JSON values"},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repoDir := t.TempDir()
|
||||||
|
path := filepath.Join(repoDir, "profile.json")
|
||||||
|
if err := os.WriteFile(path, []byte(test.content), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadSettings(repoDir, path); err == nil || !strings.Contains(err.Error(), test.want) {
|
||||||
|
t.Fatalf("LoadSettings() error = %v, want text %q", err, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunChecksUsesConfiguredArgumentsEnvironmentAndDirectory(t *testing.T) {
|
||||||
|
workdir := filepath.Join(t.TempDir(), "repo with spaces")
|
||||||
|
if err := os.Mkdir(workdir, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
err := RunChecks(context.Background(), workdir, []CheckCommand{{
|
||||||
|
Args: []string{helperExecutable(t), "-test.run=TestConfiguredCommandHelper", "--", "argument with spaces"},
|
||||||
|
Env: map[string]string{
|
||||||
|
"RELEASEKIT_CONFIGURED_HELPER": "1",
|
||||||
|
"RELEASEKIT_CONFIGURED_VALUE": "selected value",
|
||||||
|
"RELEASEKIT_VERSION": "profile value",
|
||||||
|
},
|
||||||
|
}}, map[string]string{"RELEASEKIT_VERSION": "captured version", "RELEASEKIT_CANDIDATE": "captured commit"}, &stdout, &stderr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := fmt.Sprintf("%s|argument with spaces|selected value|captured version|captured commit", workdir)
|
||||||
|
if stdout.String() != want {
|
||||||
|
t.Fatalf("stdout = %q, want %q", stdout.String(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfiguredCommandHelper(t *testing.T) {
|
||||||
|
if os.Getenv("RELEASEKIT_CONFIGURED_HELPER") != "1" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
workdir, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
os.Exit(9)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stdout, "%s|%s|%s|%s|%s", workdir, os.Args[len(os.Args)-1], os.Getenv("RELEASEKIT_CONFIGURED_VALUE"), os.Getenv("RELEASEKIT_VERSION"), os.Getenv("RELEASEKIT_CANDIDATE"))
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func helperExecutable(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
executable, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return executable
|
||||||
|
}
|
||||||
305
cmd/releasekit/internal/cli/receipt.go
Normal file
305
cmd/releasekit/internal/cli/receipt.go
Normal file
@@ -0,0 +1,305 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
const BuildReceiptName = ".releasekit-build.json"
|
||||||
|
const BuildReceiptSchemaVersion = 1
|
||||||
|
|
||||||
|
type ReceiptTarget struct {
|
||||||
|
OS string `json:"os"`
|
||||||
|
Arch string `json:"arch"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReceiptArtifact struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
Target ReceiptTarget `json:"target"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildReceipt is private local coordination data for generated binaries.
|
||||||
|
type BuildReceipt struct {
|
||||||
|
SchemaVersion int `json:"schema_version"`
|
||||||
|
RepositoryDir string `json:"repository_dir"`
|
||||||
|
ModuleDir string `json:"module_dir"`
|
||||||
|
ModulePath string `json:"module_path"`
|
||||||
|
Tag string `json:"tag"`
|
||||||
|
CandidateCommit string `json:"candidate_commit"`
|
||||||
|
SourceVerified bool `json:"source_verified"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
MainPackage string `json:"main_package"`
|
||||||
|
BinaryName string `json:"binary_name"`
|
||||||
|
OutputDir string `json:"output_dir"`
|
||||||
|
Targets []ReceiptTarget `json:"targets"`
|
||||||
|
Compiler string `json:"compiler"`
|
||||||
|
Artifacts []ReceiptArtifact `json:"artifacts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteBuildReceipt(outputDir string, receipt BuildReceipt) (string, error) {
|
||||||
|
resolvedDir, err := filepath.Abs(outputDir)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("resolve build receipt directory: %w", err)
|
||||||
|
}
|
||||||
|
receipt.OutputDir = resolvedDir
|
||||||
|
if err := validateBuildReceipt(receipt); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
contents, err := json.MarshalIndent(receipt, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("encode build receipt: %w", err)
|
||||||
|
}
|
||||||
|
contents = append(contents, '\n')
|
||||||
|
temporary, err := os.CreateTemp(resolvedDir, ".releasekit-build-receipt-*")
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("create temporary build receipt: %w", err)
|
||||||
|
}
|
||||||
|
temporaryPath := temporary.Name()
|
||||||
|
defer os.Remove(temporaryPath)
|
||||||
|
if _, err := temporary.Write(contents); err != nil {
|
||||||
|
_ = temporary.Close()
|
||||||
|
return "", fmt.Errorf("write build receipt: %w", err)
|
||||||
|
}
|
||||||
|
if err := temporary.Close(); err != nil {
|
||||||
|
return "", fmt.Errorf("close build receipt: %w", err)
|
||||||
|
}
|
||||||
|
path := filepath.Join(resolvedDir, BuildReceiptName)
|
||||||
|
if err := os.Rename(temporaryPath, path); err != nil {
|
||||||
|
if _, statErr := os.Lstat(path); statErr != nil {
|
||||||
|
return "", fmt.Errorf("install build receipt: %w", err)
|
||||||
|
}
|
||||||
|
if removeErr := os.Remove(path); removeErr != nil {
|
||||||
|
return "", fmt.Errorf("replace prior build receipt: %w", removeErr)
|
||||||
|
}
|
||||||
|
if err := os.Rename(temporaryPath, path); err != nil {
|
||||||
|
return "", fmt.Errorf("install build receipt: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadBuildReceipt(path string) (BuildReceipt, error) {
|
||||||
|
resolvedPath, err := filepath.Abs(path)
|
||||||
|
if err != nil {
|
||||||
|
return BuildReceipt{}, fmt.Errorf("resolve build receipt path: %w", err)
|
||||||
|
}
|
||||||
|
if filepath.Base(resolvedPath) != BuildReceiptName {
|
||||||
|
return BuildReceipt{}, fmt.Errorf("build receipt filename must be %s", BuildReceiptName)
|
||||||
|
}
|
||||||
|
file, err := os.Open(resolvedPath)
|
||||||
|
if err != nil {
|
||||||
|
return BuildReceipt{}, fmt.Errorf("open build receipt: %w", err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
var receipt BuildReceipt
|
||||||
|
decoder := json.NewDecoder(file)
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if err := decoder.Decode(&receipt); err != nil {
|
||||||
|
return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err)
|
||||||
|
}
|
||||||
|
var extra any
|
||||||
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||||
|
if err == nil {
|
||||||
|
return BuildReceipt{}, errors.New("decode build receipt: multiple JSON values")
|
||||||
|
}
|
||||||
|
return BuildReceipt{}, fmt.Errorf("decode build receipt: %w", err)
|
||||||
|
}
|
||||||
|
if err := validateBuildReceipt(receipt); err != nil {
|
||||||
|
if receipt.SchemaVersion != BuildReceiptSchemaVersion {
|
||||||
|
return BuildReceipt{}, fmt.Errorf("%w; regenerate it with the updated build command", err)
|
||||||
|
}
|
||||||
|
return BuildReceipt{}, err
|
||||||
|
}
|
||||||
|
if !sameDirectory(receipt.OutputDir, filepath.Dir(resolvedPath)) {
|
||||||
|
return BuildReceipt{}, errors.New("build receipt output directory does not match its location")
|
||||||
|
}
|
||||||
|
return receipt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (receipt BuildReceipt) MatchesBuild(repositoryDir, commit, version string, settings BuildSettings) bool {
|
||||||
|
if !sameDirectory(receipt.RepositoryDir, repositoryDir) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if receipt.CandidateCommit != commit || receipt.Version != version {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
want := artifact.NormalizeSettings(settings.MainPackage, settings.BinaryName, parseReceiptTargets(settings.Targets))
|
||||||
|
got := artifact.NormalizeSettings(receipt.MainPackage, receipt.BinaryName, parseStoredTargets(receipt.Targets))
|
||||||
|
if want.MainPackage != got.MainPackage || want.BinaryName != got.BinaryName || len(want.Targets) != len(got.Targets) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i, target := range want.Targets {
|
||||||
|
if target != got.Targets[i] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameDirectory(first, second string) bool {
|
||||||
|
firstInfo, err := os.Stat(first)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
secondInfo, err := os.Stat(second)
|
||||||
|
return err == nil && os.SameFile(firstInfo, secondInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateBuildReceipt(receipt BuildReceipt) error {
|
||||||
|
if receipt.SchemaVersion != BuildReceiptSchemaVersion {
|
||||||
|
return fmt.Errorf("unsupported or missing build receipt schema version %d", receipt.SchemaVersion)
|
||||||
|
}
|
||||||
|
if !versioncontract.ValidStableVersion(receipt.Version) {
|
||||||
|
return fmt.Errorf("build receipt has invalid version %q", receipt.Version)
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(receipt.RepositoryDir) || !filepath.IsAbs(receipt.ModuleDir) || !filepath.IsAbs(receipt.OutputDir) {
|
||||||
|
return errors.New("build receipt repository, module, and output directories must be absolute")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(receipt.ModulePath) == "" || strings.TrimSpace(receipt.Tag) == "" {
|
||||||
|
return errors.New("build receipt is missing module path or full tag")
|
||||||
|
}
|
||||||
|
if err := validateRecordedIdentity(receipt); err != nil {
|
||||||
|
return fmt.Errorf("build receipt has inconsistent module identity: %w", err)
|
||||||
|
}
|
||||||
|
if !validCommitID(receipt.CandidateCommit) {
|
||||||
|
return errors.New("build receipt has invalid candidate commit")
|
||||||
|
}
|
||||||
|
if receipt.MainPackage == "" || !artifact.ValidComponent(receipt.BinaryName) || receipt.Compiler == "" {
|
||||||
|
return errors.New("build receipt is missing build identity")
|
||||||
|
}
|
||||||
|
if len(receipt.Targets) == 0 || len(receipt.Artifacts) != len(receipt.Targets) {
|
||||||
|
return errors.New("build receipt target and artifact counts do not match")
|
||||||
|
}
|
||||||
|
seenTargets := make(map[ReceiptTarget]bool, len(receipt.Targets))
|
||||||
|
seenArtifacts := make(map[ReceiptTarget]bool, len(receipt.Artifacts))
|
||||||
|
targets := make([]artifact.Target, 0, len(receipt.Targets))
|
||||||
|
for _, target := range receipt.Targets {
|
||||||
|
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
|
||||||
|
return fmt.Errorf("build receipt has unsafe target %q/%q", target.OS, target.Arch)
|
||||||
|
}
|
||||||
|
if seenTargets[target] {
|
||||||
|
return fmt.Errorf("build receipt repeats target %s/%s", target.OS, target.Arch)
|
||||||
|
}
|
||||||
|
seenTargets[target] = true
|
||||||
|
targets = append(targets, artifact.Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
declarations := artifact.ExpectedBuild(receipt.BinaryName, receipt.Version, targets)
|
||||||
|
wantByTarget := make(map[ReceiptTarget]string, len(declarations))
|
||||||
|
for _, declaration := range declarations {
|
||||||
|
target := ReceiptTarget{OS: declaration.Target.OS, Arch: declaration.Target.Arch}
|
||||||
|
wantByTarget[target] = declaration.Filename
|
||||||
|
}
|
||||||
|
for _, artifact := range receipt.Artifacts {
|
||||||
|
if !seenTargets[artifact.Target] || seenArtifacts[artifact.Target] {
|
||||||
|
return fmt.Errorf("build receipt has an unexpected artifact target %s/%s", artifact.Target.OS, artifact.Target.Arch)
|
||||||
|
}
|
||||||
|
seenArtifacts[artifact.Target] = true
|
||||||
|
wantName := wantByTarget[artifact.Target]
|
||||||
|
if artifact.Filename != wantName || filepath.Base(artifact.Filename) != artifact.Filename {
|
||||||
|
return fmt.Errorf("build receipt has invalid artifact filename %q", artifact.Filename)
|
||||||
|
}
|
||||||
|
wantPath := filepath.Join(receipt.OutputDir, artifact.Filename)
|
||||||
|
if !filepath.IsAbs(artifact.Path) || filepath.Clean(artifact.Path) != filepath.Clean(wantPath) {
|
||||||
|
return fmt.Errorf("build receipt artifact path does not match filename %q", artifact.Filename)
|
||||||
|
}
|
||||||
|
if !validSHA256(artifact.SHA256) {
|
||||||
|
return fmt.Errorf("build receipt has invalid SHA-256 for %q", artifact.Filename)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateRecordedIdentity(receipt BuildReceipt) error {
|
||||||
|
repositoryDir := filepath.Clean(receipt.RepositoryDir)
|
||||||
|
moduleDir := filepath.Clean(receipt.ModuleDir)
|
||||||
|
relative, err := filepath.Rel(repositoryDir, moduleDir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("relate module directory to repository: %w", err)
|
||||||
|
}
|
||||||
|
if relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) {
|
||||||
|
return errors.New("module directory is outside repository")
|
||||||
|
}
|
||||||
|
if relative == "" {
|
||||||
|
relative = "."
|
||||||
|
}
|
||||||
|
identity, err := releaseidentity.Derive(releaseidentity.Selection{
|
||||||
|
RepositoryDir: repositoryDir,
|
||||||
|
ModuleDir: moduleDir,
|
||||||
|
ModuleSubdir: filepath.ToSlash(relative),
|
||||||
|
}, []byte("module "+receipt.ModulePath+"\n"), receipt.Version)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if identity.Tag != receipt.Tag {
|
||||||
|
return fmt.Errorf("full tag %q does not match module selection and version; want %q", receipt.Tag, identity.Tag)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseReceiptTargets(targets []string) []artifact.Target {
|
||||||
|
parsed := make([]artifact.Target, 0, len(targets))
|
||||||
|
for _, value := range targets {
|
||||||
|
goos, goarch, ok := strings.Cut(value, "/")
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parsed = append(parsed, artifact.Target{OS: goos, Arch: goarch})
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseStoredTargets(targets []ReceiptTarget) []artifact.Target {
|
||||||
|
parsed := make([]artifact.Target, 0, len(targets))
|
||||||
|
for _, target := range targets {
|
||||||
|
parsed = append(parsed, artifact.Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func validCommitID(value string) bool {
|
||||||
|
if len(value) != 40 && len(value) != 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, char := range value {
|
||||||
|
if !(char >= '0' && char <= '9' || char >= 'a' && char <= 'f') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validSHA256(value string) bool {
|
||||||
|
if len(value) != sha256.Size*2 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, char := range value {
|
||||||
|
if !(char >= '0' && char <= '9' || char >= 'a' && char <= 'f') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveBuildReceipt invalidates prior CLI coordination data after a rebuild.
|
||||||
|
func RemoveBuildReceipt(outputDir string) error {
|
||||||
|
err := os.Remove(filepath.Join(outputDir, BuildReceiptName))
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalidate prior build receipt: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
190
cmd/releasekit/internal/cli/receipt_test.go
Normal file
190
cmd/releasekit/internal/cli/receipt_test.go
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildReceiptRoundTripBindsRootAndNestedModuleIdentity(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
moduleDir string
|
||||||
|
modulePath string
|
||||||
|
tag string
|
||||||
|
}{
|
||||||
|
{name: "root", moduleDir: ".", modulePath: "example.com/receipt", tag: "v1.2.3"},
|
||||||
|
{name: "nested", moduleDir: "integrations/ckconfig", modulePath: "example.com/ckconfig", tag: "integrations/ckconfig/v1.2.3"},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
outputDir := t.TempDir()
|
||||||
|
repositoryDir := t.TempDir()
|
||||||
|
moduleDir := repositoryDir
|
||||||
|
if test.moduleDir != "." {
|
||||||
|
moduleDir = filepath.Join(repositoryDir, filepath.FromSlash(test.moduleDir))
|
||||||
|
if err := os.MkdirAll(moduleDir, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
filename := "example-v1.2.3-linux-amd64"
|
||||||
|
artifactPath := filepath.Join(outputDir, filename)
|
||||||
|
contents := []byte("built application")
|
||||||
|
if err := os.WriteFile(artifactPath, contents, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256(contents)
|
||||||
|
receipt := BuildReceipt{
|
||||||
|
SchemaVersion: BuildReceiptSchemaVersion,
|
||||||
|
RepositoryDir: repositoryDir,
|
||||||
|
ModuleDir: moduleDir,
|
||||||
|
ModulePath: test.modulePath,
|
||||||
|
Tag: test.tag,
|
||||||
|
CandidateCommit: strings.Repeat("a", 40),
|
||||||
|
Version: "v1.2.3",
|
||||||
|
MainPackage: "./cmd/example",
|
||||||
|
BinaryName: "example",
|
||||||
|
Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}},
|
||||||
|
Compiler: "go version go1.25.0 linux/amd64",
|
||||||
|
Artifacts: []ReceiptArtifact{{
|
||||||
|
Path: artifactPath, Filename: filename,
|
||||||
|
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: hex.EncodeToString(digest[:]),
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
path, err := WriteBuildReceipt(outputDir, receipt)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
loaded, err := LoadBuildReceipt(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings := BuildSettings{MainPackage: "./cmd/example", BinaryName: "example", Targets: []string{"linux/amd64", "linux/amd64"}}
|
||||||
|
if !loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
|
||||||
|
t.Fatalf("receipt does not match normalized build settings: %#v", loaded)
|
||||||
|
}
|
||||||
|
aliases := t.TempDir()
|
||||||
|
repositoryAlias, outputAlias := filepath.Join(aliases, "repository"), filepath.Join(aliases, "output")
|
||||||
|
if err := os.Symlink(repositoryDir, repositoryAlias); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink(outputDir, outputAlias); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !loaded.MatchesBuild(repositoryAlias, receipt.CandidateCommit, receipt.Version, settings) {
|
||||||
|
t.Fatal("receipt rejected an alias of its source repository")
|
||||||
|
}
|
||||||
|
if _, err := LoadBuildReceipt(filepath.Join(outputAlias, BuildReceiptName)); err != nil {
|
||||||
|
t.Fatalf("load receipt through output alias: %v", err)
|
||||||
|
}
|
||||||
|
if loaded.MatchesBuild(t.TempDir(), receipt.CandidateCommit, receipt.Version, settings) {
|
||||||
|
t.Fatal("receipt matched a different repository")
|
||||||
|
}
|
||||||
|
settings.BinaryName = "other"
|
||||||
|
if loaded.MatchesBuild(repositoryDir, strings.Repeat("a", 40), "v1.2.3", settings) {
|
||||||
|
t.Fatal("receipt matched changed build settings")
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(artifactPath, []byte("changed artifact"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadBuildReceipt(path); err != nil {
|
||||||
|
t.Fatalf("receipt loading verified changed artifact bytes: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.Remove(artifactPath); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadBuildReceipt(path); err != nil {
|
||||||
|
t.Fatalf("receipt loading required artifact bytes: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadBuildReceiptRejectsUnknownFieldsAndMultipleValues(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "unknown field", body: `{"schema_version":1,"unexpected":true}`, want: "unknown field"},
|
||||||
|
{name: "unversioned receipt", body: `{}`, want: "regenerate it with the updated build command"},
|
||||||
|
{name: "unknown schema", body: `{"schema_version":2}`, want: "regenerate it with the updated build command"},
|
||||||
|
{name: "multiple values", body: `{} {}`, want: "multiple JSON values"},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), BuildReceiptName)
|
||||||
|
if err := os.WriteFile(path, []byte(test.body), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadBuildReceipt(path); err == nil || !strings.Contains(err.Error(), test.want) {
|
||||||
|
t.Fatalf("LoadBuildReceipt() error = %v, want %q", err, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteBuildReceiptRejectsInconsistentRecordedIdentity(t *testing.T) {
|
||||||
|
repositoryDir := t.TempDir()
|
||||||
|
moduleDir := filepath.Join(repositoryDir, "integrations", "ckconfig")
|
||||||
|
if err := os.MkdirAll(moduleDir, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
outputDir := t.TempDir()
|
||||||
|
receipt := BuildReceipt{
|
||||||
|
SchemaVersion: BuildReceiptSchemaVersion,
|
||||||
|
RepositoryDir: repositoryDir, ModuleDir: moduleDir, ModulePath: "example.com/ckconfig", Tag: "v1.2.3",
|
||||||
|
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
|
||||||
|
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
|
||||||
|
Artifacts: []ReceiptArtifact{{
|
||||||
|
Path: filepath.Join(outputDir, "helper-v1.2.3-linux-amd64"), Filename: "helper-v1.2.3-linux-amd64",
|
||||||
|
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: strings.Repeat("a", 64),
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
if _, err := WriteBuildReceipt(outputDir, receipt); err == nil || !strings.Contains(err.Error(), "full tag") {
|
||||||
|
t.Fatalf("WriteBuildReceipt() error = %v, want inconsistent full tag", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadBuildReceiptRejectsMismatchedModuleIdentity(t *testing.T) {
|
||||||
|
repositoryDir := t.TempDir()
|
||||||
|
outputDir := t.TempDir()
|
||||||
|
artifactPath := filepath.Join(outputDir, "helper-v1.2.3-linux-amd64")
|
||||||
|
contents := []byte("fixture")
|
||||||
|
if err := os.WriteFile(artifactPath, contents, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256(contents)
|
||||||
|
receipt := BuildReceipt{
|
||||||
|
SchemaVersion: BuildReceiptSchemaVersion,
|
||||||
|
RepositoryDir: repositoryDir, ModuleDir: repositoryDir, ModulePath: "example.com/receipt", Tag: "v1.2.3",
|
||||||
|
CandidateCommit: strings.Repeat("a", 40), Version: "v1.2.3", MainPackage: ".", BinaryName: "helper",
|
||||||
|
OutputDir: outputDir, Targets: []ReceiptTarget{{OS: "linux", Arch: "amd64"}}, Compiler: "go version fixture",
|
||||||
|
Artifacts: []ReceiptArtifact{{
|
||||||
|
Path: artifactPath, Filename: filepath.Base(artifactPath),
|
||||||
|
Target: ReceiptTarget{OS: "linux", Arch: "amd64"}, SHA256: hex.EncodeToString(digest[:]),
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
contents, err := json.Marshal(receipt)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var fields map[string]any
|
||||||
|
if err := json.Unmarshal(contents, &fields); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fields["module_dir"] = filepath.Join(repositoryDir, "integrations", "ckconfig")
|
||||||
|
contents, err = json.Marshal(fields)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
path := filepath.Join(outputDir, BuildReceiptName)
|
||||||
|
if err := os.WriteFile(path, contents, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadBuildReceipt(path); err == nil || !strings.Contains(err.Error(), "inconsistent module identity") {
|
||||||
|
t.Fatalf("LoadBuildReceipt() error = %v, want inconsistent module identity", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
44
cmd/releasekit/local_module_test.go
Normal file
44
cmd/releasekit/local_module_test.go
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMainModuleWithoutDomainSupportsCheckBuildAndPageDelivery(t *testing.T) {
|
||||||
|
repository := newDeliveryBuildRepository(t)
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example\n\ngo 1.26.0\n")
|
||||||
|
cliGitRun(t, repository, "add", ".")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "Use local main module path")
|
||||||
|
state := &deliveryServerState{}
|
||||||
|
server := newDeliveryServer(t, state)
|
||||||
|
defer server.Close()
|
||||||
|
settings := cli.Settings{Product: "Example Product",
|
||||||
|
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}},
|
||||||
|
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||||
|
}
|
||||||
|
writeDeliveryProfile(t, repository, settings)
|
||||||
|
for _, args := range [][]string{
|
||||||
|
{"check", "--repo", repository, "v1.2.3"},
|
||||||
|
{"build", "--repo", repository, "--output", filepath.Join(t.TempDir(), "assets"), "v1.2.3"},
|
||||||
|
} {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
if status := run(context.Background(), args, &stdout, &stderr); status != 0 || !strings.Contains(stdout.String(), "module example version v1.2.3 tag v1.2.3") {
|
||||||
|
t.Fatalf("%s status=%d stdout=%s stderr=%s", args[0], status, stdout.String(), stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
settings.Build = nil
|
||||||
|
writeDeliveryProfile(t, repository, settings)
|
||||||
|
state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||||
|
cliGitRun(t, repository, "tag", "v1.2.3")
|
||||||
|
t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token")
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
if status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr); status != 0 || state.releaseCreates != 1 || state.assetUploads != 0 {
|
||||||
|
t.Fatalf("page delivery status=%d creates=%d uploads=%d stderr=%s", status, state.releaseCreates, state.assetUploads, stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
498
cmd/releasekit/main.go
Normal file
498
cmd/releasekit/main.go
Normal file
@@ -0,0 +1,498 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
code := run(ctx, os.Args[1:], os.Stdout, os.Stderr)
|
||||||
|
stop()
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||||
|
invocation, err := cli.Parse(args)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%v\n%s\n", err, cli.Usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if invocation.Command != cli.VersionCommand {
|
||||||
|
invocation.Repository, err = git.RepositoryRoot(ctx, invocation.Repository)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch invocation.Command {
|
||||||
|
case cli.VersionCommand:
|
||||||
|
fmt.Fprintf(stdout, "releasekit %s\n", buildinfo.Version())
|
||||||
|
return 0
|
||||||
|
case cli.CheckAction, cli.PublishAction:
|
||||||
|
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
request := candidateRequest(invocation, settings, stderr)
|
||||||
|
if invocation.Command == cli.PublishAction {
|
||||||
|
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "profile module selection: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
request.ExpectedPushURL = settings.ExpectedPushURL
|
||||||
|
fmt.Fprintf(stderr, "validating and publishing module %s version %s\n", selectedModuleLabel(settings.ModuleDir), invocation.Version)
|
||||||
|
result, err := releasekit.Publish(ctx, request)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "publication state=%s phase=%s module=%s module-dir=%s version=%s tag=%s commit=%s tag-object=%s endpoint=%q: %s\n", result.State, result.Phase, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.TagObject, result.Endpoint, candidateFailureText(err))
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if result.State == releasekit.PublicationUnknown {
|
||||||
|
return 3
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "published %s as %s at %s (tag object %s)\n", result.Version, result.Tag, result.CandidateCommit, result.TagObject)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
candidate, err := releasekit.Check(ctx, request)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "check failed module=%s module-dir=%s version=%s tag=%s commit=%s: %s\n", candidate.ModulePath, candidate.ModuleDir, candidate.Version, candidate.Tag, candidate.Commit, candidateFailureText(err))
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "local candidate module %s version %s tag %s at %s is valid\n", candidate.ModulePath, candidate.Version, candidate.Tag, candidate.Commit)
|
||||||
|
return 0
|
||||||
|
case cli.BuildAction:
|
||||||
|
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if settings.Build == nil {
|
||||||
|
fmt.Fprintln(stderr, "build requires build settings in the profile")
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
ModuleDir: settings.ModuleDir,
|
||||||
|
Version: invocation.Version,
|
||||||
|
Spec: *configuredBuildSpec(settings.Build),
|
||||||
|
OutputDir: invocation.OutputDir,
|
||||||
|
Output: stderr,
|
||||||
|
})
|
||||||
|
if result.OutputDir != "" && len(result.Targets) != 0 {
|
||||||
|
if receiptErr := cli.RemoveBuildReceipt(result.OutputDir); receiptErr != nil {
|
||||||
|
fmt.Fprintf(stderr, "%v\n", receiptErr)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "build failed module=%s module-dir=%s version=%s tag=%s commit=%s: %v\n", result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, err)
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
fmt.Fprintf(stderr, "built %s %s\n", artifact.Filename, artifact.SHA256)
|
||||||
|
}
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if len(result.Targets) == 0 {
|
||||||
|
fmt.Fprintf(stdout, "no build targets selected for module %s version %s tag %s at %s\n", result.ModulePath, result.Version, result.Tag, result.CandidateCommit)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
receipt := receiptFromBuild(result)
|
||||||
|
receiptPath, err := cli.WriteBuildReceipt(result.OutputDir, receipt)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "write build receipt: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
stored, err := cli.LoadBuildReceipt(receiptPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "verify build receipt: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if !stored.MatchesBuild(result.RepositoryDir, result.CandidateCommit, result.Version, *settings.Build) {
|
||||||
|
fmt.Fprintln(stderr, "build receipt does not match the selected source and build settings")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "built %d artifacts for module %s version %s tag %s at %s with %s\n", len(result.Artifacts), result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.Compiler)
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
fmt.Fprintf(stdout, "%s %s\n", artifact.Filename, artifact.SHA256)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "build receipt: %s\n", receiptPath)
|
||||||
|
return 0
|
||||||
|
case cli.DeliveryAction:
|
||||||
|
return runDelivery(ctx, invocation, stdout, stderr)
|
||||||
|
case cli.CIDeliveryAction:
|
||||||
|
return runCIDelivery(ctx, invocation, stdout, stderr)
|
||||||
|
}
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func candidateRequest(invocation cli.Invocation, settings cli.Settings, output io.Writer) releasekit.ReleaseRequest {
|
||||||
|
request := releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
ModuleDir: settings.ModuleDir,
|
||||||
|
Product: settings.Product,
|
||||||
|
Version: invocation.Version,
|
||||||
|
Remote: settings.Remote,
|
||||||
|
Validation: validationSpec(settings.Validation),
|
||||||
|
Build: configuredBuildSpec(settings.Build),
|
||||||
|
Output: output,
|
||||||
|
}
|
||||||
|
if len(settings.Checks) != 0 {
|
||||||
|
checks := settings.Checks
|
||||||
|
request.AdditionalChecks = func(ctx context.Context, candidate releasekit.Candidate) error {
|
||||||
|
return cli.RunChecks(ctx, candidate.ModuleDir, checks, map[string]string{
|
||||||
|
"RELEASEKIT_VERSION": candidate.Version,
|
||||||
|
"RELEASEKIT_CANDIDATE": candidate.Commit,
|
||||||
|
"RELEASEKIT_REPOSITORY_DIR": candidate.RepositoryDir,
|
||||||
|
"RELEASEKIT_MODULE_DIR": candidate.ModuleDir,
|
||||||
|
"RELEASEKIT_MODULE_PATH": candidate.ModulePath,
|
||||||
|
"RELEASEKIT_TAG": candidate.Tag,
|
||||||
|
}, output, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
|
||||||
|
func validationSpec(settings *cli.ValidationSettings) releasekit.ValidationSpec {
|
||||||
|
if settings == nil {
|
||||||
|
return releasekit.ValidationSpec{}
|
||||||
|
}
|
||||||
|
result := releasekit.ValidationSpec{
|
||||||
|
SharedFiles: copyStringsPreservingEmpty(settings.SharedFiles),
|
||||||
|
GoFormat: settings.GoFormat,
|
||||||
|
ModuleDistribution: releasekit.ModuleDistributionValidationSpec{
|
||||||
|
WorkspaceFiles: settings.ModuleDistribution.WorkspaceFiles,
|
||||||
|
LocalReplacements: settings.ModuleDistribution.LocalReplacements,
|
||||||
|
},
|
||||||
|
Go: releasekit.GoValidationSpec{
|
||||||
|
Race: settings.Go.Race,
|
||||||
|
FullVet: settings.Go.FullVet,
|
||||||
|
CompileTargets: make([]releasekit.Target, len(settings.Go.CompileTargets)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if settings.Markdown != nil {
|
||||||
|
result.Markdown = &releasekit.MarkdownValidationSpec{
|
||||||
|
EnforceCheckoutBoundary: settings.Markdown.EnforceCheckoutBoundary,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if settings.FileSize != nil {
|
||||||
|
var limitBytes *int64
|
||||||
|
if settings.FileSize.LimitBytes != nil {
|
||||||
|
limit := *settings.FileSize.LimitBytes
|
||||||
|
limitBytes = &limit
|
||||||
|
}
|
||||||
|
result.FileSize = &releasekit.FileSizeValidationSpec{
|
||||||
|
LimitBytes: limitBytes,
|
||||||
|
Exclusions: append([]string(nil), settings.FileSize.Exclusions...),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for index, target := range settings.Go.CompileTargets {
|
||||||
|
goos, goarch, _ := strings.Cut(target, "/")
|
||||||
|
result.Go.CompileTargets[index] = releasekit.Target{OS: goos, Arch: goarch}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func candidateFailureText(err error) string {
|
||||||
|
return err.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkExpectedModule(ctx context.Context, repositoryDir, expectedModule, profileModule string) error {
|
||||||
|
if expectedModule == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
commit, err := git.CaptureHead(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
expected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, expectedModule, commit)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("normalize expected module %q: %w", expectedModule, err)
|
||||||
|
}
|
||||||
|
selected, err := releaseidentity.ResolveCommittedSelection(ctx, repositoryDir, profileModule, commit)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("normalize profile module %q: %w", profileModule, err)
|
||||||
|
}
|
||||||
|
if expected.ModuleSubdir != selected.ModuleSubdir {
|
||||||
|
return fmt.Errorf("expected module %q resolves to %q, but the profile selects %q", expectedModule, expected.ModuleSubdir, selected.ModuleSubdir)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectedModuleLabel(moduleDir string) string {
|
||||||
|
if moduleDir == "" {
|
||||||
|
return "."
|
||||||
|
}
|
||||||
|
return moduleDir
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyStringsPreservingEmpty(values []string) []string {
|
||||||
|
if values == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return append([]string{}, values...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||||
|
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return deliverWithSettings(ctx, invocation, settings, stdout, stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stderr io.Writer) int {
|
||||||
|
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
Tag: invocation.ExpectedTag,
|
||||||
|
Remote: invocation.Remote,
|
||||||
|
ExpectedCommit: invocation.Commit,
|
||||||
|
VerifyOnly: invocation.Prepared,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "prepare tagged checkout: %v\n", err)
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
settings, err := cli.LoadSettings(invocation.Repository, invocation.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load profile: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if err := checkExpectedModule(ctx, invocation.Repository, invocation.ExpectedModule, settings.ModuleDir); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "profile module selection: %v\n", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
destination, status := deliveryDestination(settings, stderr)
|
||||||
|
if status != 0 {
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
if settings.Build != nil && len(settings.Build.Targets) != 0 {
|
||||||
|
if err := releasekit.PrepareBuildDependencies(ctx, releasekit.DependencyPreparationRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
ModuleDir: settings.ModuleDir,
|
||||||
|
}); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "prepare build dependencies: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// deliverWithSettings adapts prepared CLI state to the public delivery facade.
|
||||||
|
// CI entry points can reuse it after preparing the checkout and loading its profile.
|
||||||
|
func deliverWithSettings(ctx context.Context, invocation cli.Invocation, settings cli.Settings, stdout, stderr io.Writer) int {
|
||||||
|
destination, status := deliveryDestination(settings, stderr)
|
||||||
|
if status != 0 {
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func deliveryDestination(settings cli.Settings, stderr io.Writer) (releasekit.GiteaDestination, int) {
|
||||||
|
delivery := settings.Delivery
|
||||||
|
if delivery == nil || strings.TrimSpace(delivery.BaseURL) == "" || strings.TrimSpace(delivery.Owner) == "" || strings.TrimSpace(delivery.Repository) == "" {
|
||||||
|
fmt.Fprintln(stderr, "deliver requires base_url, owner, and repository in the profile delivery settings")
|
||||||
|
return releasekit.GiteaDestination{}, 2
|
||||||
|
}
|
||||||
|
tokenEnv := delivery.TokenEnv
|
||||||
|
if strings.TrimSpace(tokenEnv) == "" {
|
||||||
|
tokenEnv = "RELEASEKIT_GITEA_TOKEN"
|
||||||
|
}
|
||||||
|
token, ok := os.LookupEnv(tokenEnv)
|
||||||
|
if !ok || strings.TrimSpace(token) == "" {
|
||||||
|
fmt.Fprintf(stderr, "deliver requires a non-empty token in environment variable %s\n", tokenEnv)
|
||||||
|
return releasekit.GiteaDestination{}, 2
|
||||||
|
}
|
||||||
|
return releasekit.GiteaDestination{BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository, Token: token}, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func deliverWithDestination(ctx context.Context, invocation cli.Invocation, settings cli.Settings, destination releasekit.GiteaDestination, stdout, stderr io.Writer) int {
|
||||||
|
hasTargets := settings.Build != nil && len(settings.Build.Targets) != 0
|
||||||
|
if invocation.AssetsDir != "" && !hasTargets {
|
||||||
|
fmt.Fprintln(stderr, "--assets requires build targets in the profile")
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
var buildSpec *releasekit.BuildSpec
|
||||||
|
var prebuilt *releasekit.BuildResult
|
||||||
|
if invocation.AssetsDir == "" && settings.Build != nil {
|
||||||
|
buildSpec = configuredBuildSpec(settings.Build)
|
||||||
|
}
|
||||||
|
if hasTargets {
|
||||||
|
if invocation.AssetsDir != "" {
|
||||||
|
commit, err := git.CaptureHead(ctx, invocation.Repository)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "capture asset source commit: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
selection, err := releaseidentity.ResolveCommittedSelection(ctx, invocation.Repository, settings.ModuleDir, commit)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "resolve asset module directory: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
assetsDir := artifact.OutputDirectory(selection.ModuleDir, invocation.AssetsDir)
|
||||||
|
receipt, err := cli.LoadBuildReceipt(filepath.Join(assetsDir, cli.BuildReceiptName))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "load verified build receipt: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if !receipt.MatchesBuild(invocation.Repository, receipt.CandidateCommit, invocation.Version, *settings.Build) {
|
||||||
|
fmt.Fprintln(stderr, "build receipt does not match the selected repository, version, or build settings")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
prebuilt = buildResultFromReceipt(receipt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: invocation.Repository,
|
||||||
|
ModuleDir: settings.ModuleDir,
|
||||||
|
Product: settings.Product,
|
||||||
|
Version: invocation.Version,
|
||||||
|
ExpectedTag: invocation.ExpectedTag,
|
||||||
|
Destination: destination,
|
||||||
|
Build: buildSpec,
|
||||||
|
Prebuilt: prebuilt,
|
||||||
|
Output: stderr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "delivery state=%s module=%s module-dir=%s version=%s tag=%s commit=%s url=%s: %v\n", result.State, result.ModulePath, result.ModuleDir, result.Version, result.Tag, result.CandidateCommit, result.ReleaseURL, err)
|
||||||
|
writeDeliveryAssets(stderr, result)
|
||||||
|
writeDeliveryRecovery(stderr, result)
|
||||||
|
if errors.Is(err, releasekit.ErrInvalidVersion) {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if result.State == releasekit.DeliveryUnknown {
|
||||||
|
return 3
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "delivered module %s version %s tag %s at %s (state %s)\n", result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.State)
|
||||||
|
if result.ReleaseURL != "" {
|
||||||
|
fmt.Fprintf(stdout, "release: %s\n", result.ReleaseURL)
|
||||||
|
}
|
||||||
|
writeDeliveryAssets(stdout, result)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeDeliveryAssets(output io.Writer, result releasekit.DeliveryResult) {
|
||||||
|
for _, group := range []struct {
|
||||||
|
label string
|
||||||
|
assets []releasekit.DeliveryAsset
|
||||||
|
}{{"matching", result.Matching}, {"uploaded", result.Uploaded}, {"pending", result.Pending}, {"conflicting", result.Conflicting}, {"uncertain", result.Uncertain}} {
|
||||||
|
for _, asset := range group.assets {
|
||||||
|
fmt.Fprintf(output, "%s %s %s\n", group.label, asset.Filename, asset.SHA256)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeDeliveryRecovery(output io.Writer, result releasekit.DeliveryResult) {
|
||||||
|
switch result.State {
|
||||||
|
case releasekit.DeliveryNotAttempted:
|
||||||
|
fmt.Fprintf(output, "recovery: fix the local or preflight failure for module %s version %s tag %s before retrying; no remote write was attempted\n", result.ModulePath, result.Version, result.Tag)
|
||||||
|
case releasekit.DeliveryPartial:
|
||||||
|
fmt.Fprintf(output, "recovery: fix the reported cause, then retry module %s version %s tag %s\n", result.ModulePath, result.Version, result.Tag)
|
||||||
|
case releasekit.DeliveryConflict:
|
||||||
|
fmt.Fprintf(output, "recovery: investigate conflicting hosted content for module %s version %s tag %s; use a new version if the source or published contents need correction\n", result.ModulePath, result.Version, result.Tag)
|
||||||
|
case releasekit.DeliveryUnknown:
|
||||||
|
fmt.Fprintf(output, "recovery: resolve the remote state for module %s version %s tag %s before retrying\n", result.ModulePath, result.Version, result.Tag)
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(result.Matching)+len(result.Uploaded)+len(result.Conflicting)+len(result.Uncertain) != 0 {
|
||||||
|
fmt.Fprintln(output, "if rebuilding could change asset bytes already on the server, retain the original build artifacts and retry with deliver --assets DIR")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildResultFromReceipt(receipt cli.BuildReceipt) *releasekit.BuildResult {
|
||||||
|
result := &releasekit.BuildResult{
|
||||||
|
RepositoryDir: receipt.RepositoryDir, ModuleDir: receipt.ModuleDir, ModulePath: receipt.ModulePath, Tag: receipt.Tag,
|
||||||
|
CandidateCommit: receipt.CandidateCommit, SourceVerified: receipt.SourceVerified,
|
||||||
|
Version: receipt.Version, MainPackage: receipt.MainPackage, BinaryName: receipt.BinaryName,
|
||||||
|
OutputDir: receipt.OutputDir, Compiler: receipt.Compiler,
|
||||||
|
}
|
||||||
|
for _, target := range receipt.Targets {
|
||||||
|
result.Targets = append(result.Targets, releasekit.Target{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
for _, artifact := range receipt.Artifacts {
|
||||||
|
result.Artifacts = append(result.Artifacts, releasekit.BuildArtifact{
|
||||||
|
Path: artifact.Path, Filename: artifact.Filename,
|
||||||
|
Target: releasekit.Target{OS: artifact.Target.OS, Arch: artifact.Target.Arch}, SHA256: artifact.SHA256,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func configuredBuildSpec(settings *cli.BuildSettings) *releasekit.BuildSpec {
|
||||||
|
if settings == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
spec := &releasekit.BuildSpec{
|
||||||
|
MainPackage: settings.MainPackage,
|
||||||
|
BinaryName: settings.BinaryName,
|
||||||
|
Targets: make([]releasekit.Target, 0, len(settings.Targets)),
|
||||||
|
}
|
||||||
|
for _, value := range settings.Targets {
|
||||||
|
goos, goarch, _ := strings.Cut(value, "/")
|
||||||
|
spec.Targets = append(spec.Targets, releasekit.Target{OS: goos, Arch: goarch})
|
||||||
|
}
|
||||||
|
return spec
|
||||||
|
}
|
||||||
|
|
||||||
|
func receiptFromBuild(result releasekit.BuildResult) cli.BuildReceipt {
|
||||||
|
receipt := cli.BuildReceipt{
|
||||||
|
SchemaVersion: cli.BuildReceiptSchemaVersion,
|
||||||
|
RepositoryDir: result.RepositoryDir,
|
||||||
|
ModuleDir: result.ModuleDir,
|
||||||
|
ModulePath: result.ModulePath,
|
||||||
|
Tag: result.Tag,
|
||||||
|
CandidateCommit: result.CandidateCommit,
|
||||||
|
SourceVerified: result.SourceVerified,
|
||||||
|
Version: result.Version,
|
||||||
|
MainPackage: result.MainPackage,
|
||||||
|
BinaryName: result.BinaryName,
|
||||||
|
OutputDir: result.OutputDir,
|
||||||
|
Compiler: result.Compiler,
|
||||||
|
Targets: make([]cli.ReceiptTarget, 0, len(result.Targets)),
|
||||||
|
Artifacts: make([]cli.ReceiptArtifact, 0, len(result.Artifacts)),
|
||||||
|
}
|
||||||
|
for _, target := range result.Targets {
|
||||||
|
receipt.Targets = append(receipt.Targets, cli.ReceiptTarget{OS: target.OS, Arch: target.Arch})
|
||||||
|
}
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
receipt.Artifacts = append(receipt.Artifacts, cli.ReceiptArtifact{
|
||||||
|
Path: artifact.Path,
|
||||||
|
Filename: artifact.Filename,
|
||||||
|
Target: cli.ReceiptTarget{OS: artifact.Target.OS, Arch: artifact.Target.Arch},
|
||||||
|
SHA256: artifact.SHA256,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return receipt
|
||||||
|
}
|
||||||
1554
cmd/releasekit/main_test.go
Normal file
1554
cmd/releasekit/main_test.go
Normal file
File diff suppressed because it is too large
Load Diff
247
cmd/releasekit/multi_module_example_test.go
Normal file
247
cmd/releasekit/multi_module_example_test.go
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMultiModuleSelectorMapsSelectorsAndTags(t *testing.T) {
|
||||||
|
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
|
||||||
|
helper := filepath.Join(example, "select-module.sh")
|
||||||
|
for _, test := range []struct {
|
||||||
|
mode string
|
||||||
|
value string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{mode: "selector", value: "root", want: "root\tv[01].*\t.\treleasekit-root.json"},
|
||||||
|
{mode: "selector", value: "ckconfig", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
|
||||||
|
{mode: "tag", value: "integrations/ckconfig/v1.2.3", want: "ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json"},
|
||||||
|
{mode: "tag", value: "integrations/core/v2.3.4", want: "core-v2\tintegrations/core/v2.*\tintegrations/core/v2\treleasekit-core-v2.json"},
|
||||||
|
{mode: "tag", value: "v1.2.3", want: "root\tv[01].*\t.\treleasekit-root.json"},
|
||||||
|
} {
|
||||||
|
t.Run(test.mode+" "+test.value, func(t *testing.T) {
|
||||||
|
got := runModuleSelector(t, helper, test.mode, test.value, "")
|
||||||
|
if strings.TrimSpace(got) != test.want {
|
||||||
|
t.Fatalf("selector output = %q, want %q", got, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
mapPath := filepath.Join(t.TempDir(), "release modules.tsv")
|
||||||
|
if err := os.WriteFile(mapPath, []byte("one\tfeature/*\tmodules/one\tprofiles/one.json\ntwo\tfeature/v1.*\tmodules/two\tprofiles/two.json\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if output := runModuleSelectorError(t, helper, "selector", "absent", mapPath); !strings.Contains(output, "no module map row") {
|
||||||
|
t.Fatalf("unknown selector error = %q", output)
|
||||||
|
}
|
||||||
|
if output := runModuleSelectorError(t, helper, "tag", "feature/v1.2.3", mapPath); !strings.Contains(output, "ambiguous") {
|
||||||
|
t.Fatalf("ambiguous event error = %q", output)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.WriteFile(mapPath, []byte("space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := runModuleSelector(t, helper, "tag", "feature/v1.2.3", mapPath)
|
||||||
|
want := "space\tfeature/*\tintegrations/ck config\tprofiles/core release.json"
|
||||||
|
if strings.TrimSpace(got) != want {
|
||||||
|
t.Fatalf("paths with spaces = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMultiModuleLauncherUsesSelectedModuleAndProfile(t *testing.T) {
|
||||||
|
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
copyExampleTree(t, example, repository)
|
||||||
|
|
||||||
|
rootModule := "module example.com/multi-module-consumer\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.197\n"
|
||||||
|
selectedModule := "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.198\n"
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", rootModule)
|
||||||
|
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", selectedModule)
|
||||||
|
spaceModule := "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.299\n"
|
||||||
|
writeRepositoryFile(t, repository, "integrations/ck config/go.mod", spaceModule)
|
||||||
|
writeRepositoryFile(t, repository, "profiles/core release.json", `{"product":"Example Consumer Integration","module_dir":"integrations/ck config"}`)
|
||||||
|
cliGitRun(t, repository, "add", ".")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "prepare multi-module launcher fixture")
|
||||||
|
|
||||||
|
mapPath := filepath.Join(t.TempDir(), "release modules.tsv")
|
||||||
|
if err := os.WriteFile(mapPath, []byte("with space\tfeature/*\tintegrations/ck config\tprofiles/core release.json\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
shimDir := t.TempDir()
|
||||||
|
goLog := filepath.Join(t.TempDir(), "go commands")
|
||||||
|
argsLog := filepath.Join(t.TempDir(), "tool arguments")
|
||||||
|
shim := `#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
printf 'cwd=%s args=%s\n' "$PWD" "$*" >> "$RELEASEKIT_TEST_GO_LOG"
|
||||||
|
modfile=
|
||||||
|
output=
|
||||||
|
previous=
|
||||||
|
for argument in "$@"; do
|
||||||
|
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
|
||||||
|
if [ "$previous" = -o ]; then output=$argument; fi
|
||||||
|
previous=$argument
|
||||||
|
done
|
||||||
|
if [ -n "$modfile" ]; then cat "$modfile" >> "$RELEASEKIT_TEST_GO_LOG"; fi
|
||||||
|
if [ "$1" = build ]; then
|
||||||
|
cat > "$output" <<'TOOL'
|
||||||
|
#!/bin/sh
|
||||||
|
printf '<%s>\n' "$@" > "$RELEASEKIT_TEST_TOOL_ARGS"
|
||||||
|
TOOL
|
||||||
|
chmod +x "$output"
|
||||||
|
fi
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
t.Setenv("RELEASEKIT_MODULE_MAP", mapPath)
|
||||||
|
t.Setenv("RELEASEKIT_TEST_GO_LOG", goLog)
|
||||||
|
t.Setenv("RELEASEKIT_TEST_TOOL_ARGS", argsLog)
|
||||||
|
launcher := filepath.Join(repository, "release.sh")
|
||||||
|
command := exec.Command(launcher, "with space", "v1.2.4")
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
command.Stdout = &stdout
|
||||||
|
command.Stderr = &stderr
|
||||||
|
if err := command.Run(); err != nil {
|
||||||
|
t.Fatalf("launcher error: %v stdout=%q stderr=%q", err, stdout.String(), stderr.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
goCommands, err := os.ReadFile(goLog)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
wantModule := filepath.Join(repository, "integrations", "ck config")
|
||||||
|
if !strings.Contains(string(goCommands), "cwd="+wantModule) || !strings.Contains(string(goCommands), "v0.2.299") || strings.Contains(string(goCommands), "v0.2.197") {
|
||||||
|
t.Fatalf("tool bootstrap did not use selected module metadata: %s", goCommands)
|
||||||
|
}
|
||||||
|
toolArgs, err := os.ReadFile(argsLog)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, expected := range []string{"<publish>", "<--repo>", "<" + repository + ">", "<--config>", "<profiles/core release.json>", "<--expected-module>", "<integrations/ck config>", "<v1.2.4>"} {
|
||||||
|
if !strings.Contains(string(toolArgs), expected) {
|
||||||
|
t.Errorf("publication arguments %q omit %q", toolArgs, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(string(goCommands), repository+"/.releasekit-bootstrap.") {
|
||||||
|
t.Fatalf("temporary tool metadata was placed inside the repository: %s", goCommands)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMultiModuleLauncherBuildsToolFromSelectedDependency(t *testing.T) {
|
||||||
|
example := filepath.Join(cliRepositoryRoot(t), "examples", "multi-module")
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
copyExampleTree(t, example, repository)
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/multi-module-consumer\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.197\n")
|
||||||
|
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", "module example.com/multi-module-consumer/integrations/ckconfig\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit v0.2.198\n")
|
||||||
|
cliGitRun(t, repository, "add", ".")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "prepare selected tool module")
|
||||||
|
|
||||||
|
proxy := writeReleaseKitModuleProxy(t)
|
||||||
|
moduleCache := t.TempDir()
|
||||||
|
t.Setenv("GOMODCACHE", moduleCache)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = filepath.WalkDir(moduleCache, func(path string, entry fs.DirEntry, err error) error {
|
||||||
|
if err == nil && entry.IsDir() {
|
||||||
|
_ = os.Chmod(path, 0o700)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
})
|
||||||
|
t.Setenv("GOPROXY", "file://"+filepath.ToSlash(proxy))
|
||||||
|
t.Setenv("GOSUMDB", "off")
|
||||||
|
t.Setenv("GOTOOLCHAIN", "local")
|
||||||
|
moduleBefore, err := os.ReadFile(filepath.Join(repository, "integrations", "ckconfig", "go.mod"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
command := exec.Command(filepath.Join(repository, "release.sh"), "ckconfig", "v1.2.3")
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("launcher error: %v output=%q", err, output)
|
||||||
|
}
|
||||||
|
for _, expected := range []string{
|
||||||
|
"tool-version=v0.2.198 helper=tool-only dependency",
|
||||||
|
`"publish"`, `"--repo"`, `"` + repository + `"`,
|
||||||
|
`"--config"`, `"releasekit-ckconfig.json"`,
|
||||||
|
`"--expected-module"`, `"integrations/ckconfig"`, `"v1.2.3"`,
|
||||||
|
} {
|
||||||
|
if !strings.Contains(string(output), expected) {
|
||||||
|
t.Errorf("launcher output %q omits %q", output, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(string(output), "tool-version=v0.2.197") {
|
||||||
|
t.Fatalf("launcher built the root-selected ReleaseKit version: %s", output)
|
||||||
|
}
|
||||||
|
moduleAfter, err := os.ReadFile(filepath.Join(repository, "integrations", "ckconfig", "go.mod"))
|
||||||
|
if err != nil || !bytes.Equal(moduleAfter, moduleBefore) {
|
||||||
|
t.Fatalf("selected module go.mod changed: got %q want %q error=%v", moduleAfter, moduleBefore, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runModuleSelector(t *testing.T, helper, mode, value, mapPath string) string {
|
||||||
|
t.Helper()
|
||||||
|
command := exec.Command("sh", helper, mode, value)
|
||||||
|
command.Env = os.Environ()
|
||||||
|
if mapPath != "" {
|
||||||
|
command.Env = append(command.Env, "RELEASEKIT_MODULE_MAP="+mapPath)
|
||||||
|
}
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("selector %s %q: %v: %s", mode, value, err, output)
|
||||||
|
}
|
||||||
|
return string(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runModuleSelectorError(t *testing.T, helper, mode, value, mapPath string) string {
|
||||||
|
t.Helper()
|
||||||
|
command := exec.Command("sh", helper, mode, value)
|
||||||
|
command.Env = append(os.Environ(), "RELEASEKIT_MODULE_MAP="+mapPath)
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("selector %s %q unexpectedly succeeded: %s", mode, value, output)
|
||||||
|
}
|
||||||
|
return string(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyExampleTree(t *testing.T, source, destination string) {
|
||||||
|
t.Helper()
|
||||||
|
err := filepath.WalkDir(source, func(path string, entry fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
relative, err := filepath.Rel(source, path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if relative == "." {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
target := filepath.Join(destination, relative)
|
||||||
|
if entry.IsDir() {
|
||||||
|
return os.MkdirAll(target, 0o700)
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
info, err := entry.Info()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
mode := info.Mode().Perm()
|
||||||
|
if err := os.WriteFile(target, contents, mode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Chmod(target, mode)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(fmt.Errorf("copy multi-module example: %w", err))
|
||||||
|
}
|
||||||
|
}
|
||||||
408
cmd/releasekit/multi_module_woodpecker_test.go
Normal file
408
cmd/releasekit/multi_module_woodpecker_test.go
Normal file
@@ -0,0 +1,408 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMultiModuleWoodpeckerDelivery(t *testing.T) {
|
||||||
|
root := cliRepositoryRoot(t)
|
||||||
|
example := filepath.Join(root, "examples", "multi-module")
|
||||||
|
contents, err := os.ReadFile(filepath.Join(example, "woodpecker.yml"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(contents), "deliver")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "$${", "${")
|
||||||
|
for _, eventTag := range []string{"refs/tags/v[01].*", "refs/tags/integrations/ckconfig/v*", "refs/tags/integrations/core/v2.*"} {
|
||||||
|
if !strings.Contains(string(contents), eventTag) {
|
||||||
|
t.Errorf("workflow tag filters omit %q", eventTag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toolBinary := buildWorkflowCLI(t, root)
|
||||||
|
proxy := writeWorkflowToolProxy(t)
|
||||||
|
|
||||||
|
t.Run("nested page delivery retries from tagged mapping", func(t *testing.T) {
|
||||||
|
const tag = "integrations/ckconfig/v1.2.3"
|
||||||
|
delivery := newMappedDeliveryFixture(t, tag)
|
||||||
|
repository := newWorkflowRepository(t, example)
|
||||||
|
writeMappedProfile(t, repository, "releasekit-ckconfig.json", cli.Settings{
|
||||||
|
Product: "Example Consumer Integration", ModuleDir: "integrations/ckconfig",
|
||||||
|
Delivery: workflowDeliverySettings(delivery.URL),
|
||||||
|
})
|
||||||
|
writeRepositoryFile(t, repository, "integrations/ckconfig/docs/releases/v1.2.3.md", "# Example Consumer Integration v1.2.3\n\nTagged integration note.\n")
|
||||||
|
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", workflowModuleFile("example.com/multi-module-consumer/integrations/ckconfig", "v0.2.197"))
|
||||||
|
commit := tagAndPushWorkflowRepository(t, repository, tag)
|
||||||
|
delivery.commit = commit
|
||||||
|
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
|
||||||
|
if output := runWoodpeckerBlock(t, command, repository, env); !strings.Contains(output, "state complete") || !strings.Contains(output, "tool-version=v0.2.197") {
|
||||||
|
t.Fatalf("tagged page delivery output = %q", output)
|
||||||
|
}
|
||||||
|
if delivery.creates != 1 || delivery.requests == 0 || delivery.tag != tag {
|
||||||
|
t.Fatalf("page delivery fixture = %#v", delivery)
|
||||||
|
}
|
||||||
|
|
||||||
|
cliGitRun(t, repository, "checkout", "main")
|
||||||
|
writeRepositoryFile(t, repository, "release-modules.tsv", "# changed after release\nroot\tv[01].*\t.\treleasekit-root.json\n")
|
||||||
|
writeRepositoryFile(t, repository, "integrations/ckconfig/go.mod", workflowModuleFile("example.com/multi-module-consumer/integrations/ckconfig", "v0.2.198"))
|
||||||
|
cliGitRun(t, repository, "add", ".")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "change default branch release selection")
|
||||||
|
cliGitRun(t, repository, "push", "origin", "main")
|
||||||
|
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "tool-version=v0.2.197") || strings.Contains(output, "tool-version=v0.2.198") {
|
||||||
|
t.Fatalf("tag retry did not use its committed tool version: %q", output)
|
||||||
|
}
|
||||||
|
if delivery.creates != 1 || delivery.tag != tag {
|
||||||
|
t.Fatalf("tag retry did not reuse the tagged mapping: %#v", delivery)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("binary delivery from physical major module", func(t *testing.T) {
|
||||||
|
const tag = "integrations/core/v2.1.0"
|
||||||
|
delivery := newMappedDeliveryFixture(t, tag)
|
||||||
|
repository := newWorkflowRepository(t, example)
|
||||||
|
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
|
||||||
|
Product: "Example Consumer Core v2", ModuleDir: "integrations/core/v2",
|
||||||
|
Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "core", Targets: []string{"linux/amd64"}},
|
||||||
|
Delivery: workflowDeliverySettings(delivery.URL),
|
||||||
|
})
|
||||||
|
writeRepositoryFile(t, repository, "integrations/core/v2/docs/releases/v2.1.0.md", "# Example Consumer Core v2 v2.1.0\n\nTagged core note.\n")
|
||||||
|
prepareWorkflowModuleSum(t, repository, "integrations/core/v2", proxy)
|
||||||
|
commit := tagAndPushWorkflowRepository(t, repository, tag)
|
||||||
|
delivery.commit = commit
|
||||||
|
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "tool-version=v0.2.197") || !strings.Contains(output, "state complete") {
|
||||||
|
t.Fatalf("binary delivery output = %q", output)
|
||||||
|
}
|
||||||
|
if delivery.creates != 1 || delivery.uploads != 2 || delivery.tag != tag {
|
||||||
|
t.Fatalf("binary delivery fixture = %#v", delivery)
|
||||||
|
}
|
||||||
|
if _, ok := delivery.assets["core-v2.1.0-linux-amd64"]; !ok {
|
||||||
|
t.Fatalf("binary asset missing: %#v", delivery.assets)
|
||||||
|
}
|
||||||
|
if _, ok := delivery.assets["SHA256SUMS"]; !ok {
|
||||||
|
t.Fatalf("checksum asset missing: %#v", delivery.assets)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("binary delivery from virtual major module", func(t *testing.T) {
|
||||||
|
const tag = "integrations/core/v2.1.0"
|
||||||
|
delivery := newMappedDeliveryFixture(t, tag)
|
||||||
|
repository := newWorkflowRepository(t, example)
|
||||||
|
writeRepositoryFile(t, repository, "release-modules.tsv", strings.ReplaceAll(readWorkflowFile(t, repository, "release-modules.tsv"), "integrations/core/v2\treleasekit-core-v2.json", "integrations/core\treleasekit-core-v2.json"))
|
||||||
|
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
|
||||||
|
Product: "Example Consumer Core v2", ModuleDir: "integrations/core",
|
||||||
|
Delivery: workflowDeliverySettings(delivery.URL),
|
||||||
|
})
|
||||||
|
writeRepositoryFile(t, repository, "integrations/core/go.mod", workflowModuleFile("example.com/multi-module-consumer/integrations/core/v2", "v0.2.197"))
|
||||||
|
writeRepositoryFile(t, repository, "integrations/core/main.go", readWorkflowFile(t, example, "integrations/core/v2/main.go"))
|
||||||
|
writeRepositoryFile(t, repository, "integrations/core/docs/releases/v2.1.0.md", "# Example Consumer Core v2 v2.1.0\n\nTagged core note.\n")
|
||||||
|
prepareWorkflowModuleSum(t, repository, "integrations/core", proxy)
|
||||||
|
commit := tagAndPushWorkflowRepository(t, repository, tag)
|
||||||
|
delivery.commit = commit
|
||||||
|
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "tool-version=v0.2.197") || !strings.Contains(output, "state complete") {
|
||||||
|
t.Fatalf("virtual-major delivery output = %q", output)
|
||||||
|
}
|
||||||
|
if delivery.creates != 1 || delivery.tag != tag {
|
||||||
|
t.Fatalf("virtual-major delivery fixture = %#v", delivery)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("inconsistent mapping fails exact event tag check", func(t *testing.T) {
|
||||||
|
const tag = "integrations/ckconfig/v2.1.0"
|
||||||
|
delivery := newMappedDeliveryFixture(t, tag)
|
||||||
|
repository := newWorkflowRepository(t, example)
|
||||||
|
mapping := readWorkflowFile(t, repository, "release-modules.tsv")
|
||||||
|
mapping = strings.Replace(mapping,
|
||||||
|
"ckconfig\tintegrations/ckconfig/v*\tintegrations/ckconfig\treleasekit-ckconfig.json",
|
||||||
|
"ckconfig\tintegrations/ckconfig/v*\tintegrations/core/v2\treleasekit-core-v2.json", 1)
|
||||||
|
writeRepositoryFile(t, repository, "release-modules.tsv", mapping)
|
||||||
|
writeMappedProfile(t, repository, "releasekit-core-v2.json", cli.Settings{
|
||||||
|
Product: "Example Consumer Core v2", ModuleDir: "integrations/core/v2",
|
||||||
|
Delivery: workflowDeliverySettings(delivery.URL),
|
||||||
|
})
|
||||||
|
writeRepositoryFile(t, repository, "integrations/core/v2/docs/releases/v2.1.0.md", "# Example Consumer Core v2 v2.1.0\n\nMismatched mapped note.\n")
|
||||||
|
commit := tagAndPushWorkflowRepository(t, repository, tag)
|
||||||
|
delivery.commit = commit
|
||||||
|
env := multiModuleWorkflowEnvironment(t, repository, commit, tag, toolBinary, proxy)
|
||||||
|
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||||
|
t.Fatalf("inconsistent mapping succeeded: %s", output)
|
||||||
|
} else if !strings.Contains(output, tag) || !strings.Contains(output, "integrations/core/v2.1.0") {
|
||||||
|
t.Fatalf("inconsistent mapping did not fail the exact tag comparison: %s", output)
|
||||||
|
}
|
||||||
|
if delivery.requests != 0 {
|
||||||
|
t.Fatalf("exact event tag mismatch reached hosted delivery: %#v", delivery)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type mappedDeliveryFixture struct {
|
||||||
|
URL string
|
||||||
|
tag string
|
||||||
|
commit string
|
||||||
|
page bool
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
creates int
|
||||||
|
uploads int
|
||||||
|
requests int
|
||||||
|
assets map[string][]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func newMappedDeliveryFixture(t *testing.T, tag string) *mappedDeliveryFixture {
|
||||||
|
t.Helper()
|
||||||
|
state := &mappedDeliveryFixture{tag: tag, assets: make(map[string][]byte)}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
state.requests++
|
||||||
|
if r.Header.Get("Authorization") != "token fixture-token" {
|
||||||
|
t.Errorf("delivery authorization = %q", r.Header.Get("Authorization"))
|
||||||
|
}
|
||||||
|
apiRoot := "/api/v1/repos/owner/example/"
|
||||||
|
escapedTag := url.PathEscape(tag)
|
||||||
|
switch r.URL.EscapedPath() {
|
||||||
|
case apiRoot + "tags/" + escapedTag:
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"name": tag, "commit": map[string]string{"sha": state.commit}})
|
||||||
|
case apiRoot + "releases/tags/" + escapedTag:
|
||||||
|
if !state.page {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": serverURL(r) + "/releases/10", "tag_name": tag, "target_commitish": state.commit, "name": state.name, "body": state.body, "draft": false, "prerelease": false})
|
||||||
|
case apiRoot + "releases":
|
||||||
|
var payload struct {
|
||||||
|
Tag string `json:"tag_name"`
|
||||||
|
Commit string `json:"target_commitish"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
t.Errorf("decode release create: %v", err)
|
||||||
|
}
|
||||||
|
if payload.Tag != tag || payload.Commit != state.commit {
|
||||||
|
t.Errorf("release payload = %#v", payload)
|
||||||
|
}
|
||||||
|
state.page = true
|
||||||
|
state.name = payload.Name
|
||||||
|
state.body = payload.Body
|
||||||
|
state.creates++
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": serverURL(r) + "/releases/10", "tag_name": tag, "target_commitish": state.commit, "name": payload.Name, "body": payload.Body, "draft": false, "prerelease": false})
|
||||||
|
case apiRoot + "releases/10/assets":
|
||||||
|
if r.Method == http.MethodGet {
|
||||||
|
listing := make([]map[string]any, 0, len(state.assets))
|
||||||
|
for name, content := range state.assets {
|
||||||
|
listing = append(listing, map[string]any{"id": len(listing) + 1, "name": name, "size": len(content), "browser_download_url": serverURL(r) + "/files/" + name})
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(listing)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := r.ParseMultipartForm(1 << 20); err != nil {
|
||||||
|
t.Errorf("parse asset upload: %v", err)
|
||||||
|
http.Error(w, "multipart", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := r.URL.Query().Get("name")
|
||||||
|
file, _, err := r.FormFile("attachment")
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("read asset %q: %v", name, err)
|
||||||
|
http.Error(w, "attachment", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
content, err := io.ReadAll(file)
|
||||||
|
_ = file.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("read asset bytes: %v", err)
|
||||||
|
}
|
||||||
|
state.assets[name] = content
|
||||||
|
state.uploads++
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": state.uploads, "name": name, "size": len(content)})
|
||||||
|
default:
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/files/") {
|
||||||
|
name := strings.TrimPrefix(r.URL.Path, "/files/")
|
||||||
|
if content, ok := state.assets[name]; ok {
|
||||||
|
_, _ = w.Write(content)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.Errorf("unexpected delivery request %s %s", r.Method, r.URL.EscapedPath())
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
state.URL = server.URL
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
|
||||||
|
func serverURL(r *http.Request) string {
|
||||||
|
return "http://" + r.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildWorkflowCLI(t *testing.T, root string) string {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(t.TempDir(), "releasekit")
|
||||||
|
command := exec.Command("go", "build", "-o", path, "./cmd/releasekit")
|
||||||
|
command.Dir = root
|
||||||
|
command.Env = append(os.Environ(), "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off")
|
||||||
|
if output, err := command.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("build workflow CLI: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeWorkflowToolProxy(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
const helper = "example.com/releasekit-helper"
|
||||||
|
proxyDir := t.TempDir()
|
||||||
|
moduleFile := "module " + module + "\n\ngo 1.25.0\n\nrequire " + helper + " v1.0.0\n"
|
||||||
|
for _, version := range []string{"v0.2.197", "v0.2.198"} {
|
||||||
|
main := fmt.Sprintf(`package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
helper "%s"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Println("tool-version=%s helper=" + helper.Version)
|
||||||
|
command := exec.Command(os.Getenv("RELEASEKIT_TEST_BINARY"), os.Args[1:]...)
|
||||||
|
command.Env = os.Environ()
|
||||||
|
command.Stdout = os.Stdout
|
||||||
|
command.Stderr = os.Stderr
|
||||||
|
if err := command.Run(); err != nil {
|
||||||
|
if exit, ok := err.(*exec.ExitError); ok { os.Exit(exit.ExitCode()) }
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`, helper, version)
|
||||||
|
files := map[string]string{
|
||||||
|
"cmd/releasekit/main.go": main,
|
||||||
|
"buildinfo/version.go": "package buildinfo\nimport \"gitea.maximumdirect.net/eric/ReleaseKit/internal/runtimeinfo\"\nfunc Version() string { return runtimeinfo.Version() }\n",
|
||||||
|
"internal/runtimeinfo/version.go": "package runtimeinfo\nvar injectedVersion string\nfunc Version() string { if injectedVersion != \"\" { return injectedVersion }; return \"dev\" }\n",
|
||||||
|
}
|
||||||
|
writeModuleProxyVersion(t, proxyDir, module, version, moduleFile, files)
|
||||||
|
}
|
||||||
|
writeModuleProxyVersion(t, proxyDir, helper, "v1.0.0", "module "+helper+"\n\ngo 1.25.0\n", map[string]string{"helper.go": "package helper\nconst Version = \"tagged dependency\"\n"})
|
||||||
|
return proxyDir
|
||||||
|
}
|
||||||
|
|
||||||
|
func newWorkflowRepository(t *testing.T, example string) string {
|
||||||
|
t.Helper()
|
||||||
|
repository := filepath.Join(t.TempDir(), "multi module checkout")
|
||||||
|
if err := os.Mkdir(repository, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
copyExampleTree(t, example, repository)
|
||||||
|
for _, selection := range []struct{ directory, module string }{
|
||||||
|
{".", "example.com/multi-module-consumer"},
|
||||||
|
{"integrations/ckconfig", "example.com/multi-module-consumer/integrations/ckconfig"},
|
||||||
|
{"integrations/core/v2", "example.com/multi-module-consumer/integrations/core/v2"},
|
||||||
|
} {
|
||||||
|
writeRepositoryFile(t, repository, selection.directory+"/go.mod", workflowModuleFile(selection.module, "v0.2.197"))
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "init", "--initial-branch=main")
|
||||||
|
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
|
||||||
|
cliGitRun(t, repository, "config", "user.email", "releasekit@example.test")
|
||||||
|
cliGitRun(t, repository, "config", "commit.gpgsign", "false")
|
||||||
|
return repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func workflowModuleFile(module, version string) string {
|
||||||
|
return fmt.Sprintf("module %s\n\ngo 1.25.0\n\nrequire gitea.maximumdirect.net/eric/ReleaseKit %s\n", module, version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func workflowDeliverySettings(baseURL string) *cli.DeliverySettings {
|
||||||
|
return &cli.DeliverySettings{BaseURL: baseURL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_GITEA_TOKEN"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeMappedProfile(t *testing.T, repository, name string, settings cli.Settings) {
|
||||||
|
t.Helper()
|
||||||
|
contents, err := json.MarshalIndent(settings, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writeRepositoryFile(t, repository, name, string(contents)+"\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func tagAndPushWorkflowRepository(t *testing.T, repository, tag string) string {
|
||||||
|
t.Helper()
|
||||||
|
cliGitRun(t, repository, "add", "--all")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "prepare mapped delivery")
|
||||||
|
commit := cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||||
|
cliGitRun(t, repository, "tag", tag)
|
||||||
|
remote := filepath.Join(filepath.Dir(repository), "origin.git")
|
||||||
|
cliGitRun(t, repository, "init", "--bare", remote)
|
||||||
|
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||||
|
cliGitRun(t, repository, "push", "origin", "HEAD:refs/heads/main", "refs/tags/"+tag)
|
||||||
|
return commit
|
||||||
|
}
|
||||||
|
|
||||||
|
func multiModuleWorkflowEnvironment(t *testing.T, repository, commit, tag, binary, proxy string) map[string]string {
|
||||||
|
t.Helper()
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
environment := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
environment["CI_COMMIT_TAG"] = tag
|
||||||
|
environment["RELEASEKIT_TEST_BINARY"] = binary
|
||||||
|
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
|
||||||
|
cache := environment["GOMODCACHE"]
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = filepath.WalkDir(cache, func(path string, entry fs.DirEntry, err error) error {
|
||||||
|
if err == nil && entry.IsDir() {
|
||||||
|
_ = os.Chmod(path, 0o700)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return environment
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareWorkflowModuleSum(t *testing.T, repository, moduleDir, proxy string) {
|
||||||
|
t.Helper()
|
||||||
|
cache := t.TempDir()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = filepath.WalkDir(cache, func(path string, entry fs.DirEntry, err error) error {
|
||||||
|
if err == nil && entry.IsDir() {
|
||||||
|
_ = os.Chmod(path, 0o700)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
})
|
||||||
|
command := exec.Command("go", "mod", "download", "gitea.maximumdirect.net/eric/ReleaseKit@v0.2.197")
|
||||||
|
command.Dir = filepath.Join(repository, filepath.FromSlash(moduleDir))
|
||||||
|
command.Env = append(os.Environ(), "GOMODCACHE="+cache, "GOPROXY=file://"+filepath.ToSlash(proxy), "GOSUMDB=off", "GOWORK=off", "GOTOOLCHAIN=local", "GOFLAGS=-modcacherw")
|
||||||
|
if output, err := command.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("prepare tagged module sums: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readWorkflowFile(t *testing.T, repository, name string) string {
|
||||||
|
t.Helper()
|
||||||
|
contents, err := os.ReadFile(filepath.Join(repository, filepath.FromSlash(name)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(contents)
|
||||||
|
}
|
||||||
220
cmd/releasekit/release_wrapper_test.go
Normal file
220
cmd/releasekit/release_wrapper_test.go
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReleaseWrapperPreservesNativeExitStatuses(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
t.Skip("POSIX release entry point")
|
||||||
|
}
|
||||||
|
_, source, _, _ := runtime.Caller(0)
|
||||||
|
root := filepath.Clean(filepath.Join(filepath.Dir(source), "../.."))
|
||||||
|
originalPath := os.Getenv("PATH")
|
||||||
|
realGit, err := exec.LookPath("git")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sources := releaseWrapperSources(t, root)
|
||||||
|
for _, mode := range []struct {
|
||||||
|
name string
|
||||||
|
status int
|
||||||
|
version string
|
||||||
|
}{{"success", 0, "v1.2.3"}, {"invalid", 2, "invalid"}, {"rejected", 1, "v1.2.3"}, {"unknown", 3, "v1.2.3"}} {
|
||||||
|
t.Run(mode.name, func(t *testing.T) {
|
||||||
|
repository := filepath.Join(t.TempDir(), "source")
|
||||||
|
for path, contents := range sources {
|
||||||
|
name := filepath.Join(repository, path)
|
||||||
|
if err := os.MkdirAll(filepath.Dir(name), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(name, contents, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := os.Chmod(filepath.Join(repository, "scripts/release"), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "init", "--initial-branch=main")
|
||||||
|
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
|
||||||
|
cliGitRun(t, repository, "config", "user.email", "fixture@example.test")
|
||||||
|
cliGitRun(t, repository, "config", "commit.gpgsign", "false")
|
||||||
|
validationLog := filepath.Join(t.TempDir(), "validation.log")
|
||||||
|
t.Setenv("RELEASEKIT_TEST_CANDIDATE_LOG", validationLog)
|
||||||
|
candidateTest := `package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReleaseCandidate(t *testing.T) {
|
||||||
|
f, err := os.OpenFile(os.Getenv("RELEASEKIT_TEST_CANDIDATE_LOG"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
if _, err := f.WriteString("validated\n"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "candidate_test.go"), []byte(candidateTest), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Join(repository, "docs/releases"), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "docs/releases/v1.2.3.md"), []byte("# ReleaseKit v1.2.3\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
profile := map[string]any{
|
||||||
|
"product": "ReleaseKit",
|
||||||
|
"checks": []map[string]any{{"args": []string{"sh", "-c", "if [ -n \"$RELEASEKIT_TEST_ARM_GIT_SHIM\" ]; then : > \"$RELEASEKIT_TEST_ARM_GIT_SHIM\"; fi"}}},
|
||||||
|
"delivery": map[string]any{
|
||||||
|
"base_url": "https://gitea.maximumdirect.net",
|
||||||
|
"owner": "eric",
|
||||||
|
"repository": "ReleaseKit",
|
||||||
|
"token_env": "RELEASEKIT_GITEA_TOKEN",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
content, _ := json.Marshal(profile)
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "releasekit.json"), content, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "add", "--all")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "prepare wrapper fixture")
|
||||||
|
remote := filepath.Join(t.TempDir(), "origin.git")
|
||||||
|
cliGitRun(t, repository, "init", "--bare", remote)
|
||||||
|
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||||
|
cliGitRun(t, repository, "push", "origin", "HEAD:refs/heads/main")
|
||||||
|
fetch := filepath.Join(t.TempDir(), "fetch.git")
|
||||||
|
cliGitRun(t, repository, "init", "--bare", fetch)
|
||||||
|
cliGitRun(t, repository, "remote", "set-url", "origin", fetch)
|
||||||
|
cliGitRun(t, repository, "remote", "set-url", "--push", "origin", remote)
|
||||||
|
if mode.name == "rejected" {
|
||||||
|
if err := os.WriteFile(filepath.Join(remote, "hooks/pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if mode.name == "unknown" {
|
||||||
|
bin := t.TempDir()
|
||||||
|
marker := filepath.Join(bin, "push-started")
|
||||||
|
armMarker := filepath.Join(bin, "arm-git-shim")
|
||||||
|
shim := `#!/bin/sh
|
||||||
|
if [ -f "$RELEASEKIT_TEST_ARM_GIT_SHIM" ]; then
|
||||||
|
for arg do
|
||||||
|
if [ "$arg" = push ]; then
|
||||||
|
"$RELEASEKIT_TEST_REAL_GIT" "$@" || exit 1
|
||||||
|
"$RELEASEKIT_TEST_REAL_GIT" remote set-url --push origin "$RELEASEKIT_TEST_MOVED_ENDPOINT"
|
||||||
|
: > "$RELEASEKIT_TEST_PUSH_MARKER"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if [ -f "$RELEASEKIT_TEST_ARM_GIT_SHIM" ] && [ -f "$RELEASEKIT_TEST_PUSH_MARKER" ]; then
|
||||||
|
for arg do if [ "$arg" = ls-remote ]; then exit 128; fi; done
|
||||||
|
fi
|
||||||
|
exec "$RELEASEKIT_TEST_REAL_GIT" "$@"
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(bin, "git"), []byte(shim), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
t.Setenv("RELEASEKIT_TEST_REAL_GIT", realGit)
|
||||||
|
t.Setenv("RELEASEKIT_TEST_PUSH_MARKER", marker)
|
||||||
|
t.Setenv("RELEASEKIT_TEST_MOVED_ENDPOINT", fetch)
|
||||||
|
t.Setenv("RELEASEKIT_TEST_ARM_GIT_SHIM", armMarker)
|
||||||
|
}
|
||||||
|
command := exec.Command("./scripts/release", mode.version)
|
||||||
|
command.Dir = repository
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
status := 0
|
||||||
|
if err != nil {
|
||||||
|
exit, ok := err.(*exec.ExitError)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
status = exit.ExitCode()
|
||||||
|
}
|
||||||
|
if status != mode.status {
|
||||||
|
t.Fatalf("status=%d want=%d output=%s", status, mode.status, output)
|
||||||
|
}
|
||||||
|
validated, readErr := os.ReadFile(validationLog)
|
||||||
|
if mode.name == "invalid" {
|
||||||
|
if !os.IsNotExist(readErr) {
|
||||||
|
t.Fatalf("invalid input ran candidate validation: %q, %v", validated, readErr)
|
||||||
|
}
|
||||||
|
} else if readErr != nil || string(validated) != "validated\n" {
|
||||||
|
t.Fatalf("candidate suite must run once: %q, %v", validated, readErr)
|
||||||
|
}
|
||||||
|
if mode.name == "unknown" {
|
||||||
|
if !strings.Contains(string(output), fmt.Sprintf("endpoint=%q", remote)) {
|
||||||
|
t.Fatalf("captured endpoint missing: %s", output)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", originalPath)
|
||||||
|
// Execute the runbook's guarded recovery commands verbatim.
|
||||||
|
recovery := `test "$(git ls-remote --get-url -- "$releasekit_endpoint")" = "$releasekit_endpoint" &&
|
||||||
|
git ls-remote --refs -- "$releasekit_endpoint" "refs/tags/$releasekit_version"`
|
||||||
|
query := exec.Command("sh", "-c", recovery)
|
||||||
|
query.Dir = repository
|
||||||
|
query.Env = append(os.Environ(), "releasekit_endpoint="+remote, "releasekit_version=v1.2.3")
|
||||||
|
found, err := query.Output()
|
||||||
|
if err != nil || len(found) == 0 {
|
||||||
|
t.Fatalf("captured endpoint recovery failed: %q %v", found, err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(found), cliGitOutput(t, repository, "rev-parse", "refs/tags/v1.2.3")) {
|
||||||
|
t.Fatalf("wrong recovered tag: %s", found)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "config", "url."+fetch+".insteadOf", remote)
|
||||||
|
blocked := exec.Command("sh", "-c", recovery)
|
||||||
|
blocked.Dir = repository
|
||||||
|
blocked.Env = query.Env
|
||||||
|
if output, err := blocked.Output(); err == nil || len(output) != 0 {
|
||||||
|
t.Fatalf("rewritten endpoint should block query: %q %v", output, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchQuery := exec.Command(realGit, "ls-remote", "--refs", "origin", "refs/tags/v1.2.3")
|
||||||
|
fetchQuery.Dir = repository
|
||||||
|
stale, err := fetchQuery.Output()
|
||||||
|
if err != nil || len(stale) != 0 {
|
||||||
|
t.Fatalf("fetch fixture unexpectedly found tag: %q %v", stale, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture current, nonignored source once, including worktree changes. The
|
||||||
|
// candidate gets one small test instead of the project's full test suite.
|
||||||
|
func releaseWrapperSources(t *testing.T, root string) map[string][]byte {
|
||||||
|
t.Helper()
|
||||||
|
list := exec.Command("git", "ls-files", "-z", "--cached", "--others", "--exclude-standard")
|
||||||
|
list.Dir = root
|
||||||
|
paths, err := list.Output()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sources := make(map[string][]byte)
|
||||||
|
for _, path := range strings.Split(string(paths), "\x00") {
|
||||||
|
if path == "" || strings.HasSuffix(path, "_test.go") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(filepath.Join(root, path))
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
continue // Tracked files removed from the current worktree.
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sources[path] = contents
|
||||||
|
}
|
||||||
|
return sources
|
||||||
|
}
|
||||||
117
cmd/releasekit/releasekit_delivery_workflow_test.go
Normal file
117
cmd/releasekit/releasekit_delivery_workflow_test.go
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) {
|
||||||
|
_, sourceFile, _, ok := runtime.Caller(0)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("locate integration test source")
|
||||||
|
}
|
||||||
|
root := filepath.Clean(filepath.Join(filepath.Dir(sourceFile), "../.."))
|
||||||
|
profile, err := cli.LoadSettings(root, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("load ReleaseKit source-only profile: %v", err)
|
||||||
|
}
|
||||||
|
if profile.Build != nil && len(profile.Build.Targets) != 0 {
|
||||||
|
t.Fatalf("ReleaseKit profile declares binary targets: %#v", profile.Build.Targets)
|
||||||
|
}
|
||||||
|
if profile.Delivery == nil || profile.Delivery.BaseURL != "https://gitea.maximumdirect.net" || profile.Delivery.Owner != "eric" || profile.Delivery.Repository != "ReleaseKit" || profile.Delivery.TokenEnv != "RELEASEKIT_GITEA_TOKEN" {
|
||||||
|
t.Fatalf("ReleaseKit delivery profile = %#v", profile.Delivery)
|
||||||
|
}
|
||||||
|
repository := filepath.Join(t.TempDir(), "tagged ReleaseKit")
|
||||||
|
clone := exec.Command("git", "clone", "--local", "--no-hardlinks", root, repository)
|
||||||
|
if output, err := clone.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("clone ReleaseKit source: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test")
|
||||||
|
cliGitRun(t, repository, "config", "user.email", "releasekit@example.test")
|
||||||
|
|
||||||
|
const version = "v1.2.3"
|
||||||
|
note := "# ReleaseKit v1.2.3\n\nSource-only delivery fixture.\n\n" +
|
||||||
|
"[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/COPYRIGHT) |\n" +
|
||||||
|
"[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/LICENSE) |\n" +
|
||||||
|
"[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v1.2.3/docs/oss/attribution.md)\n"
|
||||||
|
notePath := filepath.Join(repository, "docs", "releases", version+".md")
|
||||||
|
if err := os.MkdirAll(filepath.Dir(notePath), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(notePath, []byte(note), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "add", "docs/releases/"+version+".md")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "prepare source-only delivery")
|
||||||
|
|
||||||
|
state := &deliveryServerState{product: "ReleaseKit"}
|
||||||
|
server := newDeliveryServer(t, state)
|
||||||
|
defer server.Close()
|
||||||
|
writeDeliveryProfile(t, repository, cli.Settings{
|
||||||
|
Product: "ReleaseKit",
|
||||||
|
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||||
|
})
|
||||||
|
state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||||
|
cliGitRun(t, repository, "tag", "-a", version, "-m", "ReleaseKit v1.2.3")
|
||||||
|
|
||||||
|
remote := filepath.Join(t.TempDir(), "origin.git")
|
||||||
|
initRemote := exec.Command("git", "init", "--bare", remote)
|
||||||
|
if output, err := initRemote.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("initialize local delivery remote: %v\n%s", err, output)
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "remote", "set-url", "origin", remote)
|
||||||
|
cliGitRun(t, repository, "push", "origin", "HEAD:refs/heads/main", "refs/tags/"+version)
|
||||||
|
|
||||||
|
template, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "releasekit-source-delivery.yml"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(template), "deliver")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
env := map[string]string{
|
||||||
|
"CI_WORKSPACE": repository,
|
||||||
|
"CI_COMMIT_SHA": state.commit,
|
||||||
|
"CI_COMMIT_TAG": version,
|
||||||
|
"RELEASEKIT_GITEA_TOKEN": "fixture-token",
|
||||||
|
"GOTOOLCHAIN": "local",
|
||||||
|
"GOPROXY": "off",
|
||||||
|
"GOSUMDB": "off",
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "$${", "${")
|
||||||
|
|
||||||
|
state.remoteCommit = strings.Repeat("f", 40)
|
||||||
|
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||||
|
t.Fatalf("delivery with a mismatched hosted tag succeeded: %s", output)
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 0 || cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}") != state.commit {
|
||||||
|
t.Fatal("delivery failure changed hosted release state or source tag")
|
||||||
|
}
|
||||||
|
state.remoteCommit = ""
|
||||||
|
|
||||||
|
for attempt := 0; attempt < 2; attempt++ {
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "state complete") {
|
||||||
|
t.Fatalf("delivery attempt %d output = %q", attempt+1, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 1 || state.assetUploads != 0 || state.assetListReads != 0 {
|
||||||
|
t.Fatalf("page-only workflow calls = creates:%d uploads:%d asset reads:%d", state.releaseCreates, state.assetUploads, state.assetListReads)
|
||||||
|
}
|
||||||
|
if state.noteBody != note {
|
||||||
|
t.Fatalf("hosted note body = %q, want complete note %q", state.noteBody, note)
|
||||||
|
}
|
||||||
|
if got := cliGitOutput(t, repository, "rev-parse", "refs/tags/"+version+"^{commit}"); got != state.commit {
|
||||||
|
t.Fatalf("source tag moved after delivery: %s, want %s", got, state.commit)
|
||||||
|
}
|
||||||
|
if status := cliGitOutput(t, repository, "status", "--porcelain"); status != "" {
|
||||||
|
t.Fatalf("tagged checkout became dirty after delivery: %s", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
34
cmd/releasekit/repository_test.go
Normal file
34
cmd/releasekit/repository_test.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNativeCheckFromChildUsesRootProfileAndSuite(t *testing.T) {
|
||||||
|
binary := buildWorkflowCLI(t, cliRepositoryRoot(t))
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
writeRepositoryFile(t, repository, "candidate_test.go", "package candidate\nimport \"testing\"\nfunc TestFixture(t *testing.T) { t.Fatal(\"root suite failure\") }\n")
|
||||||
|
writeRepositoryFile(t, repository, "releasekit.json", `{"product":"Example Product"}`)
|
||||||
|
writeRepositoryFile(t, repository, "apps/widget/go.mod", "module example.com/widget\n\ngo 1.26.0\n")
|
||||||
|
writeRepositoryFile(t, repository, "apps/widget/widget_test.go", "package widget\nimport \"testing\"\nfunc TestWidget(t *testing.T) {}\n")
|
||||||
|
cliGitRun(t, repository, "add", ".")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "Add failing root and passing child")
|
||||||
|
command := exec.Command(binary, "check", "v1.2.3")
|
||||||
|
command.Dir = filepath.Join(repository, "apps", "widget")
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 || !strings.Contains(string(output), "root suite failure") || !strings.Contains(string(output), "module=example.com/cli-candidate") {
|
||||||
|
t.Fatalf("child invocation error = %v, output = %s", err, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeBuildClassifiesInvalidVersionBeforeSourceAccess(t *testing.T) {
|
||||||
|
binary := buildWorkflowCLI(t, cliRepositoryRoot(t))
|
||||||
|
command := exec.Command(binary, "build", "--repo", filepath.Join(t.TempDir(), "absent"), "bad-version")
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 2 || !strings.Contains(string(output), "stable vMAJOR.MINOR.PATCH") {
|
||||||
|
t.Fatalf("invalid build error = %v, output = %s", err, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
672
cmd/releasekit/woodpecker_test.go
Normal file
672
cmd/releasekit/woodpecker_test.go
Normal file
@@ -0,0 +1,672 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWoodpeckerTagDeliveryTemplate(t *testing.T) {
|
||||||
|
root := cliRepositoryRoot(t)
|
||||||
|
templatePath := filepath.Join(root, "examples", "woodpecker", "tag-delivery.yml")
|
||||||
|
contents, err := os.ReadFile(templatePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(contents), "deliver")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "$${", "${")
|
||||||
|
|
||||||
|
t.Run("source-only", func(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, false)
|
||||||
|
state := &deliveryServerState{}
|
||||||
|
server := newDeliveryServer(t, state)
|
||||||
|
defer server.Close()
|
||||||
|
writeDeliveryProfile(t, repository, cli.Settings{
|
||||||
|
Product: "Example Product",
|
||||||
|
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||||
|
})
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
state.commit = commit
|
||||||
|
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "state complete") {
|
||||||
|
t.Fatalf("delivery output=%q", output)
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 1 || state.assetUploads != 0 {
|
||||||
|
t.Fatalf("source-only calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads)
|
||||||
|
}
|
||||||
|
assertModuleBootstrap(t, repository, goLog, moduleBefore)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("binary", func(t *testing.T) {
|
||||||
|
repository := newDeliveryBuildRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, true)
|
||||||
|
state := &deliveryServerState{}
|
||||||
|
server := newDeliveryServer(t, state)
|
||||||
|
defer server.Close()
|
||||||
|
writeDeliveryProfile(t, repository, cli.Settings{
|
||||||
|
Product: "Example Product",
|
||||||
|
Build: &cli.BuildSettings{
|
||||||
|
MainPackage: ".",
|
||||||
|
BinaryName: "helper",
|
||||||
|
Targets: []string{fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)},
|
||||||
|
},
|
||||||
|
Delivery: &cli.DeliverySettings{BaseURL: server.URL, Owner: "owner", Repository: "example"},
|
||||||
|
})
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
state.commit = commit
|
||||||
|
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||||
|
sumBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.sum"))
|
||||||
|
for attempt := 0; attempt < 2; attempt++ {
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "state complete") {
|
||||||
|
t.Fatalf("delivery attempt %d output=%q", attempt+1, output)
|
||||||
|
}
|
||||||
|
if attempt == 1 && !strings.Contains(output, "matching SHA256SUMS") {
|
||||||
|
t.Fatalf("second delivery did not reuse matching assets: %q", output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if state.releaseCreates != 1 || state.assetUploads != 2 {
|
||||||
|
t.Fatalf("binary calls = creates:%d uploads:%d", state.releaseCreates, state.assetUploads)
|
||||||
|
}
|
||||||
|
if _, ok := state.assets["helper-v1.2.3-"+runtime.GOOS+"-"+runtime.GOARCH]; !ok {
|
||||||
|
t.Fatalf("binary asset was not delivered: %#v", state.assets)
|
||||||
|
}
|
||||||
|
if _, ok := state.assets["SHA256SUMS"]; !ok {
|
||||||
|
t.Fatalf("checksum manifest was not delivered: %#v", state.assets)
|
||||||
|
}
|
||||||
|
assertModuleBootstrap(t, repository, goLog, moduleBefore, sumBefore)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("wrong tag stops before Go", func(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, false)
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, strings.Repeat("f", len(commit)), goDir, goLog)
|
||||||
|
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||||
|
t.Fatalf("wrong tag succeeded: %s", output)
|
||||||
|
}
|
||||||
|
assertNoCommands(t, goLog)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("dirty module stops before Go", func(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, false)
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/different-tool-selection\n\ngo 1.25.0\n")
|
||||||
|
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||||
|
t.Fatalf("dirty module succeeded: %s", output)
|
||||||
|
}
|
||||||
|
assertNoCommands(t, goLog)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("selected executable receives event arguments and its status", func(t *testing.T) {
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
selectReleaseKitModule(t, repository, root, false)
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
goDir, goLog := installControlledGoBootstrapShim(t)
|
||||||
|
toolArgs := filepath.Join(t.TempDir(), "tool-arguments")
|
||||||
|
env := templateEnvironment(repository, strings.ToUpper(commit), goDir, goLog)
|
||||||
|
env["RELEASEKIT_TOOL_ARGS_LOG"] = toolArgs
|
||||||
|
env["RELEASEKIT_TOOL_EXIT"] = "37"
|
||||||
|
output, err := executeWoodpeckerBlock(command, repository, env)
|
||||||
|
var exitError *exec.ExitError
|
||||||
|
if !errors.As(err, &exitError) || exitError.ExitCode() != 37 {
|
||||||
|
t.Fatalf("template error = %v, want propagated exit 37; output=%q", err, output)
|
||||||
|
}
|
||||||
|
args := readWoodpeckerFixtureFile(t, toolArgs)
|
||||||
|
for _, expected := range []string{"<ci-deliver>", "<--repo>", "<" + repository + ">", "<--prepared>", "<--commit>", "<" + strings.ToUpper(commit) + ">", "<v1.2.3>"} {
|
||||||
|
if !strings.Contains(args, expected) {
|
||||||
|
t.Errorf("selected executable arguments %q omit %q", args, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertGoSelection(t, repository, goLog)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWoodpeckerTagDeliveryUsesTaggedModuleVersion(t *testing.T) {
|
||||||
|
// Synthetic downloads must leave the caller's module cache untouched.
|
||||||
|
callerCache := t.TempDir()
|
||||||
|
t.Setenv("GOMODCACHE", callerCache)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
entries, err := os.ReadDir(callerCache)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(entries) != 0 {
|
||||||
|
t.Errorf("synthetic module downloads modified the caller's cache: %v", entries)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
root := cliRepositoryRoot(t)
|
||||||
|
contents, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "tag-delivery.yml"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(contents), "deliver")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "$${", "${")
|
||||||
|
proxy := writeReleaseKitModuleProxy(t)
|
||||||
|
|
||||||
|
t.Run("older tag retry uses its committed module selection", func(t *testing.T) {
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+module+" v0.2.197\n")
|
||||||
|
cliGitRun(t, repository, "add", "go.mod")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "select the earlier ReleaseKit version")
|
||||||
|
oldCommit := cliGitOutput(t, repository, "rev-parse", "HEAD")
|
||||||
|
cliGitRun(t, repository, "tag", "v1.2.3")
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+module+" v0.2.198\n")
|
||||||
|
cliGitRun(t, repository, "add", "go.mod")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "upgrade the default branch tool")
|
||||||
|
cliGitRun(t, repository, "init", "--bare", filepath.Join(filepath.Dir(repository), "origin.git"))
|
||||||
|
remote := filepath.Join(filepath.Dir(repository), "origin.git")
|
||||||
|
cliGitRun(t, repository, "remote", "add", "origin", remote)
|
||||||
|
cliGitRun(t, repository, "push", "origin", "refs/heads/main", "refs/tags/v1.2.3")
|
||||||
|
cliGitRun(t, repository, "checkout", "--detach", oldCommit)
|
||||||
|
if mainModule := cliGitOutput(t, repository, "show", "main:go.mod"); !strings.Contains(mainModule, module+" v0.2.198") {
|
||||||
|
t.Fatalf("default branch module = %q, want upgraded tool selection", mainModule)
|
||||||
|
}
|
||||||
|
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||||
|
commit := oldCommit
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
|
||||||
|
sumLog := filepath.Join(t.TempDir(), "tool-only-sums")
|
||||||
|
env["RELEASEKIT_SUM_LOG"] = sumLog
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "tool-version=v0.2.197") || !strings.Contains(output, "helper=tool-only dependency") || strings.Contains(output, "tool-version=v0.2.198") {
|
||||||
|
t.Fatalf("retry selected the wrong tool version: %q", output)
|
||||||
|
}
|
||||||
|
assertModuleBootstrap(t, repository, goLog, moduleBefore)
|
||||||
|
assertToolOnlyChecksums(t, sumLog)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("versioned replacement selects its declared source", func(t *testing.T) {
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
goMod := "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire " + module + " v0.2.197\n\nreplace " + module + " v0.2.197 => " + module + " v0.2.198\n"
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", goMod)
|
||||||
|
cliGitRun(t, repository, "add", "go.mod")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "select a versioned tool replacement")
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
moduleBefore := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod"))
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
|
||||||
|
sumLog := filepath.Join(t.TempDir(), "tool-only-sums")
|
||||||
|
env["RELEASEKIT_SUM_LOG"] = sumLog
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "tool-version=v0.2.198") || !strings.Contains(output, "helper=tool-only dependency") {
|
||||||
|
t.Fatalf("versioned replacement was not selected: %q", output)
|
||||||
|
}
|
||||||
|
assertModuleBootstrap(t, repository, goLog, moduleBefore)
|
||||||
|
assertToolOnlyChecksums(t, sumLog)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWoodpeckerSourceDeliveryTemplateSelfBootstraps(t *testing.T) {
|
||||||
|
root := cliRepositoryRoot(t)
|
||||||
|
contents, err := os.ReadFile(filepath.Join(root, "examples", "woodpecker", "releasekit-source-delivery.yml"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
block, err := extractWoodpeckerCommand(string(contents), "deliver")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
command := strings.ReplaceAll(block, "$${", "${")
|
||||||
|
repository := newCLIRepository(t)
|
||||||
|
const dependency = "example.com/releasekit-helper"
|
||||||
|
proxyDir := t.TempDir()
|
||||||
|
writeModuleProxyVersion(t, proxyDir, dependency, "v1.0.0", "module "+dependency+"\n\ngo 1.25.0\n", map[string]string{
|
||||||
|
"helper.go": "package helper\n\nconst Message = \"prepared tool dependency\"\n",
|
||||||
|
})
|
||||||
|
var proxyRequests atomic.Int64
|
||||||
|
files := http.FileServer(http.Dir(proxyDir))
|
||||||
|
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
proxyRequests.Add(1)
|
||||||
|
files.ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer proxy.Close()
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", "module example.com/cli-candidate\n\ngo 1.25.0\n\nrequire "+dependency+" v1.0.0\n")
|
||||||
|
writeRepositoryFile(t, repository, "cmd/releasekit/main.go", "package main\n\nimport (\"fmt\"; \"os\"; helper \""+dependency+"\")\n\nfunc main() {\n\tfmt.Println(\"self-bootstrap \" + helper.Message)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n}\n")
|
||||||
|
preparationEnv := map[string]string{}
|
||||||
|
useSyntheticModuleProxy(t, preparationEnv, proxy.URL)
|
||||||
|
runWoodpeckerBlock(t, "go mod download "+dependency, repository, preparationEnv)
|
||||||
|
cliGitRun(t, repository, "add", "cmd/releasekit/main.go", "go.mod", "go.sum")
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "add the self-bootstrapped command")
|
||||||
|
commit := pushTaggedCLIRepository(t, repository)
|
||||||
|
goDir, goLog := installGoBootstrapShim(t)
|
||||||
|
env := templateEnvironment(repository, commit, goDir, goLog)
|
||||||
|
useSyntheticModuleProxy(t, env, proxy.URL)
|
||||||
|
proxyRequests.Store(0)
|
||||||
|
env["CI_COMMIT_SHA"] = strings.Repeat("0", len(commit))
|
||||||
|
if output, err := executeWoodpeckerBlock(command, repository, env); err == nil {
|
||||||
|
t.Fatalf("wrong commit unexpectedly bootstrapped the tool: %s", output)
|
||||||
|
}
|
||||||
|
assertNoCommands(t, goLog)
|
||||||
|
if proxyRequests.Load() != 0 {
|
||||||
|
t.Fatal("wrong commit reached tool dependency preparation")
|
||||||
|
}
|
||||||
|
env["CI_COMMIT_SHA"] = commit
|
||||||
|
output := runWoodpeckerBlock(t, command, repository, env)
|
||||||
|
if !strings.Contains(output, "self-bootstrap prepared tool dependency") || !strings.Contains(output, `"`+commit+`"`) {
|
||||||
|
t.Fatalf("self-bootstrap output = %q", output)
|
||||||
|
}
|
||||||
|
if proxyRequests.Load() == 0 {
|
||||||
|
t.Fatal("self-bootstrap did not prepare its dependency from the local proxy")
|
||||||
|
}
|
||||||
|
if !strings.Contains(output, `"ci-deliver"`) || !strings.Contains(output, `"`+repository+`"`) || !strings.Contains(output, `"--prepared"`) || !strings.Contains(output, `"v1.2.3"`) {
|
||||||
|
t.Fatalf("self-bootstrapped command arguments = %q", output)
|
||||||
|
}
|
||||||
|
log := readWoodpeckerFixtureFile(t, goLog)
|
||||||
|
if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, "build -mod=readonly -o ") || !strings.Contains(log, "./cmd/releasekit") {
|
||||||
|
t.Fatalf("self-bootstrap Go command = %q", log)
|
||||||
|
}
|
||||||
|
var executable string
|
||||||
|
for index, field := range strings.Fields(log) {
|
||||||
|
if field == "-o" && index+1 < len(strings.Fields(log)) {
|
||||||
|
executable = strings.Fields(log)[index+1]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if executable == "" {
|
||||||
|
t.Fatalf("self-bootstrap output path missing from Go command: %q", log)
|
||||||
|
}
|
||||||
|
if relative, err := filepath.Rel(repository, executable); err != nil || relative == "." || (!strings.HasPrefix(relative, ".."+string(filepath.Separator)) && relative != "..") {
|
||||||
|
t.Fatalf("self-bootstrap executable %q is not outside source %q: relative=%q error=%v", executable, repository, relative, err)
|
||||||
|
}
|
||||||
|
if status := cliGitOutput(t, repository, "status", "--porcelain", "--untracked-files=all"); status != "" {
|
||||||
|
t.Fatalf("self-bootstrap changed the tagged source: %q", status)
|
||||||
|
}
|
||||||
|
if branch := cliGitOutput(t, repository, "rev-parse", "--abbrev-ref", "HEAD"); branch != "HEAD" {
|
||||||
|
t.Fatalf("self-bootstrap checkout branch = %q, want detached HEAD", branch)
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(filepath.Dir(repository))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, entry := range entries {
|
||||||
|
if strings.HasPrefix(entry.Name(), ".releasekit-source.") {
|
||||||
|
t.Fatalf("self-bootstrap temporary directory remains: %s", entry.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cliRepositoryRoot(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
_, sourceFile, _, ok := runtime.Caller(0)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("locate integration test source")
|
||||||
|
}
|
||||||
|
return filepath.Clean(filepath.Join(filepath.Dir(sourceFile), "../.."))
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractWoodpeckerCommand(contents, stepName string) (string, error) {
|
||||||
|
lines := strings.Split(contents, "\n")
|
||||||
|
stepHeader := " - name: " + stepName
|
||||||
|
for i, line := range lines {
|
||||||
|
if strings.TrimSpace(line) != strings.TrimSpace(stepHeader) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for j := i + 1; j < len(lines); j++ {
|
||||||
|
trimmed := strings.TrimSpace(lines[j])
|
||||||
|
if strings.HasPrefix(lines[j], " - name:") {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if trimmed != "- |" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var block []string
|
||||||
|
for k := j + 1; k < len(lines); k++ {
|
||||||
|
current := lines[k]
|
||||||
|
if strings.TrimSpace(current) == "" {
|
||||||
|
block = append(block, "")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
indent := len(current) - len(strings.TrimLeft(current, " "))
|
||||||
|
if indent < 8 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
block = append(block, current[8:])
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(strings.Join(block, "\n")), nil
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("step %q has no literal command block", stepName)
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("step %q was not found", stepName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func installGoBootstrapShim(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
shimDir := t.TempDir()
|
||||||
|
goLog := filepath.Join(shimDir, "go-commands")
|
||||||
|
shim := `#!/bin/sh
|
||||||
|
printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG"
|
||||||
|
"$RELEASEKIT_REAL_GO" "$@"
|
||||||
|
status=$?
|
||||||
|
if [ "$status" -eq 0 ] && [ "$1" = "build" ] && [ -n "${RELEASEKIT_SUM_LOG:-}" ]; then
|
||||||
|
modfile=
|
||||||
|
for argument in "$@"; do
|
||||||
|
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
|
||||||
|
done
|
||||||
|
cp "${modfile%.mod}.sum" "$RELEASEKIT_SUM_LOG"
|
||||||
|
fi
|
||||||
|
exit "$status"
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return shimDir, goLog
|
||||||
|
}
|
||||||
|
|
||||||
|
func installControlledGoBootstrapShim(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
shimDir := t.TempDir()
|
||||||
|
goLog := filepath.Join(shimDir, "go-commands")
|
||||||
|
shim := `#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
printf 'cwd=%s GOWORK=%s GOTOOLCHAIN=%s %s\n' "$PWD" "$GOWORK" "$GOTOOLCHAIN" "$*" >> "$RELEASEKIT_GO_LOG"
|
||||||
|
modfile=
|
||||||
|
for argument in "$@"; do
|
||||||
|
case "$argument" in -modfile=*) modfile=${argument#-modfile=} ;; esac
|
||||||
|
done
|
||||||
|
[ -n "$modfile" ] && [ -f "$modfile" ] || { echo 'alternate module file is missing' >&2; exit 89; }
|
||||||
|
[ -f "${modfile%.mod}.sum" ] || { echo 'alternate checksum file is missing' >&2; exit 88; }
|
||||||
|
grep -F "$RELEASEKIT_MODULE v0.2.0" "$modfile" >/dev/null || { echo 'module selection was not copied' >&2; exit 87; }
|
||||||
|
case "$1" in
|
||||||
|
list)
|
||||||
|
printf '%s v0.2.0\n' "$RELEASEKIT_MODULE"
|
||||||
|
;;
|
||||||
|
build)
|
||||||
|
output=
|
||||||
|
previous=
|
||||||
|
for argument in "$@"; do
|
||||||
|
if [ "$previous" = "-o" ]; then output=$argument; break; fi
|
||||||
|
previous=$argument
|
||||||
|
done
|
||||||
|
[ -n "$output" ] || { echo 'go build omitted output path' >&2; exit 90; }
|
||||||
|
cat > "$output" <<'TOOL'
|
||||||
|
#!/bin/sh
|
||||||
|
printf '<%s>\n' "$@" > "$RELEASEKIT_TOOL_ARGS_LOG"
|
||||||
|
exit "${RELEASEKIT_TOOL_EXIT:-0}"
|
||||||
|
TOOL
|
||||||
|
chmod +x "$output"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "unexpected Go command: $1" >&2
|
||||||
|
exit 91
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(filepath.Join(shimDir, "go"), []byte(shim), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return shimDir, goLog
|
||||||
|
}
|
||||||
|
|
||||||
|
func useSyntheticModuleProxy(t *testing.T, environment map[string]string, proxyURL string) {
|
||||||
|
t.Helper()
|
||||||
|
environment["GOMODCACHE"] = t.TempDir()
|
||||||
|
environment["GOPROXY"] = proxyURL
|
||||||
|
environment["GOSUMDB"] = "off"
|
||||||
|
environment["GONOPROXY"] = "none"
|
||||||
|
environment["GOPRIVATE"] = ""
|
||||||
|
environment["GOWORK"] = "off"
|
||||||
|
environment["GOTOOLCHAIN"] = "local"
|
||||||
|
environment["GOENV"] = "off"
|
||||||
|
environment["GOFLAGS"] = "-modcacherw"
|
||||||
|
}
|
||||||
|
|
||||||
|
func templateEnvironment(repository, commit, shimDir, goLog string) map[string]string {
|
||||||
|
realGo, _ := exec.LookPath("go")
|
||||||
|
return map[string]string{
|
||||||
|
"CI_WORKSPACE": repository,
|
||||||
|
"CI_COMMIT_SHA": commit,
|
||||||
|
"CI_COMMIT_TAG": "v1.2.3",
|
||||||
|
"RELEASEKIT_GITEA_TOKEN": "fixture-token",
|
||||||
|
"RELEASEKIT_MODULE": "gitea.maximumdirect.net/eric/ReleaseKit",
|
||||||
|
"RELEASEKIT_REAL_GO": realGo,
|
||||||
|
"RELEASEKIT_GO_LOG": goLog,
|
||||||
|
"GOTOOLCHAIN": "local",
|
||||||
|
"GOPROXY": "off",
|
||||||
|
"GOSUMDB": "off",
|
||||||
|
"GOFLAGS": "",
|
||||||
|
"PATH": shimDir + string(os.PathListSeparator) + os.Getenv("PATH"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runWoodpeckerBlock(t *testing.T, block, repository string, environment map[string]string) string {
|
||||||
|
t.Helper()
|
||||||
|
output, err := executeWoodpeckerBlock(block, repository, environment)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Woodpecker command failed: %v\ncommand: %s\noutput: %s", err, block, output)
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
}
|
||||||
|
|
||||||
|
func executeWoodpeckerBlock(block, repository string, environment map[string]string) (string, error) {
|
||||||
|
command := exec.Command("sh", "-e", "-c", block)
|
||||||
|
command.Dir = repository
|
||||||
|
command.Env = os.Environ()
|
||||||
|
for key, value := range environment {
|
||||||
|
command.Env = setEnvironment(command.Env, key, value)
|
||||||
|
}
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
return string(output), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectReleaseKitModule(t *testing.T, repository, releaseKitSource string, includeSum bool) {
|
||||||
|
t.Helper()
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
goMod := fmt.Sprintf("module example.com/tagged-app\n\ngo 1.26.0\n\nrequire %s v0.2.0\n\nreplace %s => %s\n", module, module, strconv.Quote(releaseKitSource))
|
||||||
|
writeRepositoryFile(t, repository, "go.mod", goMod)
|
||||||
|
cliGitRun(t, repository, "add", "go.mod")
|
||||||
|
if includeSum {
|
||||||
|
writeRepositoryFile(t, repository, "go.sum", "")
|
||||||
|
cliGitRun(t, repository, "add", "go.sum")
|
||||||
|
}
|
||||||
|
cliGitRun(t, repository, "commit", "-m", "select ReleaseKit from module configuration")
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeReleaseKitModuleProxy(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
const module = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
const toolDependency = "example.com/releasekit-helper"
|
||||||
|
proxyDir := t.TempDir()
|
||||||
|
toolModule := "module " + module + "\n\ngo 1.25.0\n\nrequire " + toolDependency + " v1.0.0\n"
|
||||||
|
for _, version := range []string{"v0.2.197", "v0.2.198"} {
|
||||||
|
files := map[string]string{
|
||||||
|
"cmd/releasekit/main.go": "package main\n\nimport (\"fmt\"; \"os\"; tooldep \"example.com/releasekit-helper\")\n\nfunc main() {\n\tfmt.Println(\"tool-version=" + version + " helper=\" + tooldep.Version)\n\tfmt.Printf(\"tool-args=%q\\n\", os.Args[1:])\n}\n",
|
||||||
|
}
|
||||||
|
writeModuleProxyVersion(t, proxyDir, module, version, toolModule, files)
|
||||||
|
}
|
||||||
|
writeModuleProxyVersion(t, proxyDir, toolDependency, "v1.0.0", "module "+toolDependency+"\n\ngo 1.25.0\n", map[string]string{"tooldep.go": "package tooldep\n\nconst Version = \"tool-only dependency\"\n"})
|
||||||
|
return proxyDir
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeModuleProxyVersion(t *testing.T, proxyDir, module, version, moduleFile string, files map[string]string) {
|
||||||
|
t.Helper()
|
||||||
|
var escaped strings.Builder
|
||||||
|
for _, character := range module {
|
||||||
|
if character >= 'A' && character <= 'Z' {
|
||||||
|
escaped.WriteByte('!')
|
||||||
|
character += 'a' - 'A'
|
||||||
|
}
|
||||||
|
escaped.WriteRune(character)
|
||||||
|
}
|
||||||
|
moduleVersions := filepath.Join(proxyDir, filepath.FromSlash(escaped.String()), "@v")
|
||||||
|
if err := os.MkdirAll(moduleVersions, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(moduleVersions, "list")); os.IsNotExist(err) {
|
||||||
|
if err := os.WriteFile(filepath.Join(moduleVersions, "list"), []byte(version+"\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
listPath := filepath.Join(moduleVersions, "list")
|
||||||
|
list := readWoodpeckerFixtureFile(t, listPath)
|
||||||
|
if !strings.Contains(list, version+"\n") {
|
||||||
|
if err := os.WriteFile(listPath, []byte(list+version+"\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(moduleVersions, version+".mod"), []byte(moduleFile), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
info := fmt.Sprintf("{\"Version\":%q,\"Time\":\"2026-10-01T00:00:00Z\"}\n", version)
|
||||||
|
if err := os.WriteFile(filepath.Join(moduleVersions, version+".info"), []byte(info), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
archive, err := os.Create(filepath.Join(moduleVersions, version+".zip"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writer := zip.NewWriter(archive)
|
||||||
|
prefix := module + "@" + version + "/"
|
||||||
|
files["go.mod"] = moduleFile
|
||||||
|
for name, contents := range files {
|
||||||
|
file, err := writer.Create(prefix + name)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := file.Write([]byte(contents)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := archive.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertModuleBootstrap(t *testing.T, repository, goLog, moduleBefore string, sumBefore ...string) {
|
||||||
|
t.Helper()
|
||||||
|
assertGoSelection(t, repository, goLog)
|
||||||
|
if got := readWoodpeckerFixtureFile(t, filepath.Join(repository, "go.mod")); got != moduleBefore {
|
||||||
|
t.Fatalf("source go.mod changed during bootstrap: got %q, want %q", got, moduleBefore)
|
||||||
|
}
|
||||||
|
sumPath := filepath.Join(repository, "go.sum")
|
||||||
|
if len(sumBefore) == 0 {
|
||||||
|
if _, err := os.Stat(sumPath); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("source go.sum state changed: stat error = %v", err)
|
||||||
|
}
|
||||||
|
} else if got := readWoodpeckerFixtureFile(t, sumPath); got != sumBefore[0] {
|
||||||
|
t.Fatalf("source go.sum changed during bootstrap: got %q, want %q", got, sumBefore[0])
|
||||||
|
}
|
||||||
|
if status := cliGitOutput(t, repository, "status", "--porcelain", "--untracked-files=all"); status != "" {
|
||||||
|
t.Fatalf("bootstrap changed tagged source: %q", status)
|
||||||
|
}
|
||||||
|
if branch := cliGitOutput(t, repository, "rev-parse", "--abbrev-ref", "HEAD"); branch != "HEAD" {
|
||||||
|
t.Fatalf("checkout branch = %q, want detached HEAD", branch)
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(filepath.Dir(repository))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, entry := range entries {
|
||||||
|
if strings.HasPrefix(entry.Name(), ".releasekit-bootstrap.") {
|
||||||
|
t.Fatalf("temporary bootstrap directory remains: %s", entry.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertGoSelection(t *testing.T, repository, goLog string) {
|
||||||
|
t.Helper()
|
||||||
|
log := readWoodpeckerFixtureFile(t, goLog)
|
||||||
|
list := "list -mod=mod -modfile="
|
||||||
|
build := "build -mod=mod -modfile="
|
||||||
|
module := "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
if !strings.Contains(log, "GOWORK=off GOTOOLCHAIN=local") || !strings.Contains(log, list) || !strings.Contains(log, "-m "+module) {
|
||||||
|
t.Fatalf("Go module selection command is missing required settings: %q", log)
|
||||||
|
}
|
||||||
|
if !strings.Contains(log, build) || !strings.Contains(log, module+"/cmd/releasekit") || strings.Contains(log, "@v0.2.0") {
|
||||||
|
t.Fatalf("Go build did not use the selected module without a version suffix: %q", log)
|
||||||
|
}
|
||||||
|
if strings.Index(log, list) > strings.Index(log, build) {
|
||||||
|
t.Fatalf("Go build ran before module selection: %q", log)
|
||||||
|
}
|
||||||
|
var modfile string
|
||||||
|
for _, field := range strings.Fields(log) {
|
||||||
|
if strings.HasPrefix(field, "-modfile=") {
|
||||||
|
modfile = strings.TrimPrefix(field, "-modfile=")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if modfile == "" {
|
||||||
|
t.Fatalf("Go commands did not receive an alternate module file: %q", log)
|
||||||
|
}
|
||||||
|
if relative, err := filepath.Rel(repository, modfile); err != nil || relative == "." || (!strings.HasPrefix(relative, ".."+string(filepath.Separator)) && relative != "..") {
|
||||||
|
t.Fatalf("alternate module file %q is not outside source %q: relative=%q error=%v", modfile, repository, relative, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertNoCommands(t *testing.T, goLog string) {
|
||||||
|
t.Helper()
|
||||||
|
contents, err := os.ReadFile(goLog)
|
||||||
|
if err != nil && !os.IsNotExist(err) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(contents) != 0 {
|
||||||
|
t.Fatalf("Go ran before tag/source verification: %q", contents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertToolOnlyChecksums(t *testing.T, path string) {
|
||||||
|
t.Helper()
|
||||||
|
sums := readWoodpeckerFixtureFile(t, path)
|
||||||
|
if !strings.Contains(sums, "example.com/releasekit-helper v1.0.0 h1:") {
|
||||||
|
t.Fatalf("temporary module sum file omitted the tool-only dependency checksum: %q", sums)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readWoodpeckerFixtureFile(t *testing.T, path string) string {
|
||||||
|
t.Helper()
|
||||||
|
contents, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
func setEnvironment(environment []string, key, value string) []string {
|
||||||
|
prefix := key + "="
|
||||||
|
for i, entry := range environment {
|
||||||
|
if strings.HasPrefix(entry, prefix) {
|
||||||
|
environment[i] = prefix + value
|
||||||
|
return environment
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return append(environment, prefix+value)
|
||||||
|
}
|
||||||
141
delivery.go
Normal file
141
delivery.go
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
package releasekit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
internaldelivery "gitea.maximumdirect.net/eric/ReleaseKit/internal/delivery"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DeliveryState describes the result of one delivery invocation.
|
||||||
|
type DeliveryState string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// DeliveryNotAttempted means this invocation made no remote write.
|
||||||
|
DeliveryNotAttempted DeliveryState = "not_attempted"
|
||||||
|
// DeliveryComplete means the release page and all declared assets match.
|
||||||
|
DeliveryComplete DeliveryState = "complete"
|
||||||
|
// DeliveryPartial means a page or some assets were delivered, with work pending.
|
||||||
|
DeliveryPartial DeliveryState = "partial"
|
||||||
|
// DeliveryConflict means existing hosted content differs from the declaration.
|
||||||
|
DeliveryConflict DeliveryState = "conflict"
|
||||||
|
// DeliveryUnknown means a remote write may have succeeded but could not be resolved.
|
||||||
|
DeliveryUnknown DeliveryState = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GiteaDestination supplies the hosted repository and explicit access token.
|
||||||
|
type GiteaDestination struct {
|
||||||
|
BaseURL string
|
||||||
|
Owner string
|
||||||
|
Repository string
|
||||||
|
Token string
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeliveryAsset identifies a hosted asset by filename and SHA-256 digest.
|
||||||
|
type DeliveryAsset struct {
|
||||||
|
Filename string
|
||||||
|
SHA256 string
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeliveryRequest identifies a local tagged checkout and its explicit Gitea
|
||||||
|
// destination. Build selects a managed build; Prebuilt supplies caller-owned
|
||||||
|
// build output instead. They cannot both be set. Either may be nil for
|
||||||
|
// page-only delivery when both are nil. Build with no targets, or an empty
|
||||||
|
// Prebuilt result, also performs page-only delivery.
|
||||||
|
type DeliveryRequest struct {
|
||||||
|
RepositoryDir string // directory within the tagged source Git checkout.
|
||||||
|
// ModuleDir selects a repository-relative module directory; empty selects
|
||||||
|
// the repository root.
|
||||||
|
ModuleDir string
|
||||||
|
Product string
|
||||||
|
Version string
|
||||||
|
// ExpectedTag optionally requires the full CI event tag to match the
|
||||||
|
// selected module's derived tag before building or making hosted requests.
|
||||||
|
ExpectedTag string
|
||||||
|
Destination GiteaDestination
|
||||||
|
// Build selects binaries to build in temporary storage outside the checkout.
|
||||||
|
Build *BuildSpec
|
||||||
|
// Prebuilt supplies an existing build whose files remain caller-owned.
|
||||||
|
Prebuilt *BuildResult
|
||||||
|
// Output receives progress from a managed build.
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeliveryResult reports hosted content and the state reached by this
|
||||||
|
// invocation. A partial result may accompany an error. The asset slices are
|
||||||
|
// current observations: an asset appears in at most one slice, and early
|
||||||
|
// failures may leave some declared assets unreported.
|
||||||
|
type DeliveryResult struct {
|
||||||
|
RepositoryDir string
|
||||||
|
ModuleDir string
|
||||||
|
ModulePath string
|
||||||
|
Tag string // complete derived Git tag.
|
||||||
|
Version string // selected stable semantic version.
|
||||||
|
CandidateCommit string
|
||||||
|
ReleaseURL string
|
||||||
|
State DeliveryState
|
||||||
|
// Matching lists existing attachments with the declared content.
|
||||||
|
Matching []DeliveryAsset
|
||||||
|
// Uploaded lists assets whose uploads were confirmed during this invocation.
|
||||||
|
Uploaded []DeliveryAsset
|
||||||
|
// Pending lists assets known to be missing.
|
||||||
|
Pending []DeliveryAsset
|
||||||
|
// Conflicting lists assets with detected content conflicts.
|
||||||
|
Conflicting []DeliveryAsset
|
||||||
|
// Uncertain lists assets whose remote state could not be resolved.
|
||||||
|
Uncertain []DeliveryAsset
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deliver verifies the selected local tag and hosted source, then creates or
|
||||||
|
// finds its release page and adds any missing declared build assets. Build
|
||||||
|
// requests are compiled into temporary storage that Deliver removes on return.
|
||||||
|
// Prebuilt artifacts remain caller-owned and are not removed. Both paths
|
||||||
|
// validate source identity and artifact contents before hosted writes.
|
||||||
|
// Module selection and declaration links resolve from the captured commit.
|
||||||
|
// Page-only delivery can use a sparse checkout with available committed objects;
|
||||||
|
// managed builds require their selected source files in the working tree.
|
||||||
|
func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, error) {
|
||||||
|
result := DeliveryResult{Version: request.Version, State: DeliveryNotAttempted}
|
||||||
|
destination := gitea.Destination{
|
||||||
|
BaseURL: request.Destination.BaseURL, Owner: request.Destination.Owner,
|
||||||
|
Repository: request.Destination.Repository, Token: request.Destination.Token,
|
||||||
|
}
|
||||||
|
var prebuilt *internalbuild.Result
|
||||||
|
if request.Prebuilt != nil {
|
||||||
|
prebuilt = internalBuildResult(*request.Prebuilt)
|
||||||
|
}
|
||||||
|
internalResult, err := internaldelivery.Deliver(ctx, internaldelivery.Request{
|
||||||
|
RepositoryDir: request.RepositoryDir,
|
||||||
|
ModuleDir: request.ModuleDir,
|
||||||
|
Product: request.Product,
|
||||||
|
Version: request.Version,
|
||||||
|
ExpectedTag: request.ExpectedTag,
|
||||||
|
Destination: destination,
|
||||||
|
Build: internalBuildSpec(request.Build),
|
||||||
|
Prebuilt: prebuilt,
|
||||||
|
Output: request.Output,
|
||||||
|
})
|
||||||
|
result.RepositoryDir = internalResult.RepositoryDir
|
||||||
|
result.ModuleDir = internalResult.ModuleDir
|
||||||
|
result.ModulePath = internalResult.ModulePath
|
||||||
|
result.Tag = internalResult.Tag
|
||||||
|
result.CandidateCommit = internalResult.CandidateCommit
|
||||||
|
result.ReleaseURL = internalResult.ReleaseURL
|
||||||
|
result.State = DeliveryState(internalResult.State)
|
||||||
|
result.Matching = deliveryAssets(internalResult.Matching)
|
||||||
|
result.Uploaded = deliveryAssets(internalResult.Uploaded)
|
||||||
|
result.Pending = deliveryAssets(internalResult.Pending)
|
||||||
|
result.Conflicting = deliveryAssets(internalResult.Conflicting)
|
||||||
|
result.Uncertain = deliveryAssets(internalResult.Uncertain)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func deliveryAssets(assets []gitea.AssetIdentity) []DeliveryAsset {
|
||||||
|
result := make([]DeliveryAsset, 0, len(assets))
|
||||||
|
for _, asset := range assets {
|
||||||
|
result = append(result, DeliveryAsset{Filename: asset.Filename, SHA256: asset.SHA256})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
66
delivery_reads_linux_test.go
Normal file
66
delivery_reads_linux_test.go
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
package releasekit_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeliverReadsLocalBinaryOnceForVerificationAndOnceForUpload(t *testing.T) {
|
||||||
|
repository, build, expected := newDeliveryBenchmarkFixture(t)
|
||||||
|
watcher, err := syscall.InotifyInit1(syscall.IN_NONBLOCK | syscall.IN_CLOEXEC)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer syscall.Close(watcher)
|
||||||
|
// Close events separate successive opens so inotify cannot coalesce them.
|
||||||
|
if _, err := syscall.InotifyAddWatch(watcher, build.Artifacts[0].Path, syscall.IN_OPEN|syscall.IN_CLOSE_NOWRITE); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
state := &deliveryBenchmarkServer{commit: build.CandidateCommit, assets: expected}
|
||||||
|
state.reset(false)
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(state.serveHTTP))
|
||||||
|
defer server.Close()
|
||||||
|
state.baseURL = server.URL
|
||||||
|
result, err := releasekit.Deliver(t.Context(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository, Product: "Sample App", Version: build.Version,
|
||||||
|
Destination: facadeDeliveryDestination(server.URL), Prebuilt: &build,
|
||||||
|
})
|
||||||
|
if err != nil || result.State != releasekit.DeliveryComplete || len(result.Uploaded) != len(expected) {
|
||||||
|
t.Fatalf("delivery = %#v, error = %v", result, err)
|
||||||
|
}
|
||||||
|
state.verifyUploads(t)
|
||||||
|
opens := 0
|
||||||
|
var events [256]byte
|
||||||
|
for {
|
||||||
|
n, err := syscall.Read(watcher, events[:])
|
||||||
|
if errors.Is(err, syscall.EAGAIN) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if errors.Is(err, syscall.EINTR) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for offset := 0; offset < n; {
|
||||||
|
mask := binary.NativeEndian.Uint32(events[offset+4:])
|
||||||
|
if mask&syscall.IN_Q_OVERFLOW != 0 {
|
||||||
|
t.Fatal("artifact event queue overflowed")
|
||||||
|
}
|
||||||
|
if mask&syscall.IN_OPEN != 0 {
|
||||||
|
opens++
|
||||||
|
}
|
||||||
|
nameLength := binary.NativeEndian.Uint32(events[offset+12:])
|
||||||
|
offset += syscall.SizeofInotifyEvent + int(nameLength)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if opens != 2 {
|
||||||
|
t.Fatalf("local binary opened %d times; want one verification read and one upload read", opens)
|
||||||
|
}
|
||||||
|
}
|
||||||
692
delivery_test.go
Normal file
692
delivery_test.go
Normal file
@@ -0,0 +1,692 @@
|
|||||||
|
package releasekit_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Deliver() error = %v; result = %#v", err, result)
|
||||||
|
}
|
||||||
|
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("delivery result = %#v", result)
|
||||||
|
}
|
||||||
|
if len(result.Uploaded) != 2 || len(remote.assets) != 2 {
|
||||||
|
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets))
|
||||||
|
}
|
||||||
|
if !strings.Contains(progress.String(), "checking fixture version output") {
|
||||||
|
t.Fatalf("build progress = %q", progress.String())
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("managed build output remains: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "linux", Arch: "arm64"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Deliver() error = %v; result = %#v", err, result)
|
||||||
|
}
|
||||||
|
if result.State != releasekit.DeliveryComplete || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("delivery result = %#v", result)
|
||||||
|
}
|
||||||
|
wantAssets := []string{
|
||||||
|
"fixture-v1.2.3-linux-amd64",
|
||||||
|
"fixture-v1.2.3-linux-arm64",
|
||||||
|
"SHA256SUMS",
|
||||||
|
}
|
||||||
|
if len(result.Uploaded) != len(wantAssets) || len(remote.assets) != len(wantAssets) {
|
||||||
|
t.Fatalf("uploaded = %#v; hosted assets = %v", result.Uploaded, mapKeys(remote.assets))
|
||||||
|
}
|
||||||
|
for _, name := range wantAssets {
|
||||||
|
if _, ok := remote.assets[name]; !ok {
|
||||||
|
t.Errorf("hosted assets omit %q: %v", name, mapKeys(remote.assets))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(progress.String(), "checking fixture version output") {
|
||||||
|
t.Fatalf("build progress = %q", progress.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverPrebuiltArtifactsRemainCallerOwned(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
outputDir := filepath.Join(t.TempDir(), "caller-owned-assets")
|
||||||
|
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
OutputDir: outputDir,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v", err)
|
||||||
|
}
|
||||||
|
server, _ := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Prebuilt: &prebuilt,
|
||||||
|
})
|
||||||
|
if err != nil || result.State != releasekit.DeliveryComplete {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v", result, err)
|
||||||
|
}
|
||||||
|
for _, artifact := range prebuilt.Artifacts {
|
||||||
|
if _, err := os.Stat(artifact.Path); err != nil {
|
||||||
|
t.Errorf("caller-owned artifact %q was removed: %v", artifact.Path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "caller-owned-assets"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() error = %v", err)
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(prebuilt.Artifacts[0].Path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(contents) == 0 {
|
||||||
|
t.Fatal("built artifact is empty")
|
||||||
|
}
|
||||||
|
contents[0] ^= 0xff
|
||||||
|
if err := os.WriteFile(prebuilt.Artifacts[0].Path, contents, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Prebuilt: &prebuilt,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "verify build assets") || result.State != releasekit.DeliveryNotAttempted {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want local asset verification failure", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none before local verification", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverPageOnlySkipsBuildAndHostedAssets(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
build *releasekit.BuildSpec
|
||||||
|
prebuilt *releasekit.BuildResult
|
||||||
|
}{
|
||||||
|
{name: "no build"},
|
||||||
|
{name: "empty target set", build: &releasekit.BuildSpec{}},
|
||||||
|
{name: "empty prebuilt result", prebuilt: &releasekit.BuildResult{}},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
prebuilt := test.prebuilt
|
||||||
|
if prebuilt != nil {
|
||||||
|
built, err := releasekit.Build(context.Background(), releasekit.BuildRequest{RepositoryDir: repository, Version: "v1.2.3"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Build() for page-only prebuilt identity = %#v, %v", built, err)
|
||||||
|
}
|
||||||
|
prebuilt = &built
|
||||||
|
}
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: test.build,
|
||||||
|
Prebuilt: prebuilt,
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err != nil || result.State != releasekit.DeliveryComplete {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v", result, err)
|
||||||
|
}
|
||||||
|
if len(remote.assets) != 0 || len(result.Uploaded) != 0 || len(result.Pending) != 0 {
|
||||||
|
t.Fatalf("page-only delivery included assets: result=%#v assets=%v", result, mapKeys(remote.assets))
|
||||||
|
}
|
||||||
|
if progress.Len() != 0 {
|
||||||
|
t.Fatalf("page-only delivery emitted build progress: %q", progress.String())
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("page-only delivery allocated temporary output: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverUsesCommittedModuleIdentityForSeparatePages(t *testing.T) {
|
||||||
|
repository := newTwoModuleDeliveryConsumer(t)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
wrongTag, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
ExpectedTag: "integrations/wrong/v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
})
|
||||||
|
if err == nil || wrongTag.Tag != "v1.2.3" || remote.requests != 0 {
|
||||||
|
t.Fatalf("delivery with inconsistent expected tag = %#v, %v; hosted requests %d", wrongTag, err, remote.requests)
|
||||||
|
}
|
||||||
|
|
||||||
|
rootResult, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
ExpectedTag: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
})
|
||||||
|
if err != nil || rootResult.State != releasekit.DeliveryComplete || rootResult.Tag != "v1.2.3" {
|
||||||
|
t.Fatalf("root delivery = %#v, %v", rootResult, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
nestedTag := "integrations/ckconfig/v1.2.3"
|
||||||
|
remote.tag = nestedTag
|
||||||
|
remote.noteBody = "# Fixture v1.2.3\n\nNested delivery fixture.\n"
|
||||||
|
nestedResult, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
ModuleDir: "integrations/ckconfig",
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
ExpectedTag: nestedTag,
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
})
|
||||||
|
if err != nil || nestedResult.State != releasekit.DeliveryComplete || nestedResult.Tag != nestedTag || nestedResult.ModulePath != "example.com/ckconfig" {
|
||||||
|
t.Fatalf("nested delivery = %#v, %v", nestedResult, err)
|
||||||
|
}
|
||||||
|
if len(remote.pages) != 2 || !remote.pages["v1.2.3"] || !remote.pages[nestedTag] {
|
||||||
|
t.Fatalf("created hosted pages = %#v", remote.pages)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsPrebuiltArtifactsForAnotherModuleBeforeHostedRequests(t *testing.T) {
|
||||||
|
repository := newTwoModuleDeliveryConsumer(t)
|
||||||
|
prebuilt, err := releasekit.Build(context.Background(), releasekit.BuildRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
OutputDir: filepath.Join(t.TempDir(), "root-artifacts"),
|
||||||
|
})
|
||||||
|
if err != nil || !prebuilt.SourceVerified {
|
||||||
|
t.Fatalf("root Build() = %#v, %v", prebuilt, err)
|
||||||
|
}
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
remote.tag = "integrations/ckconfig/v1.2.3"
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
ModuleDir: "integrations/ckconfig",
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
ExpectedTag: remote.tag,
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Prebuilt: &prebuilt,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "selected tagged module") || result.Tag != remote.tag {
|
||||||
|
t.Fatalf("nested delivery with root artifacts = %#v, %v", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests before prebuilt identity rejection = %d", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTwoModuleDeliveryConsumer(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
writeNestedBuildConsumer(t, repository, "integrations/ckconfig", "example.com/ckconfig", `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } }
|
||||||
|
`)
|
||||||
|
writeBuildFixture(t, repository, "integrations/ckconfig/docs/releases/v1.2.3.md", "# Fixture v1.2.3\n\nNested delivery fixture.\n")
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "add nested release module")
|
||||||
|
buildGit(t, repository, "tag", "-f", "v1.2.3")
|
||||||
|
buildGit(t, repository, "tag", "integrations/ckconfig/v1.2.3")
|
||||||
|
return repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsDirtyTaggedSourceBeforeBuildOrHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
writeBuildFixture(t, repository, "local-change.txt", "dirty source")
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want preflight failure for known commit", result, err)
|
||||||
|
}
|
||||||
|
if progress.Len() != 0 {
|
||||||
|
t.Fatalf("build started before source eligibility passed: %q", progress.String())
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsCheckoutAwayFromTagBeforeBuildOrHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
tagCommit := buildGit(t, repository, "rev-parse", "HEAD")
|
||||||
|
writeBuildFixture(t, repository, "later-change.txt", "new commit")
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "advance checkout after release tag")
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit == tagCommit {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want tag/HEAD mismatch", result, err)
|
||||||
|
}
|
||||||
|
if progress.Len() != 0 {
|
||||||
|
t.Fatalf("build started before tag/HEAD agreement: %q", progress.String())
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsInvalidCommittedNoteBeforeBuildOrHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumerWithNote(t, "# Different Product v1.2.3\n\nWrong product.\n")
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
var progress strings.Builder
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: &progress,
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want committed-note preflight failure", result, err)
|
||||||
|
}
|
||||||
|
if progress.Len() != 0 {
|
||||||
|
t.Fatalf("build started before committed-note validation: %q", progress.String())
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverManagedBuildRejectsCheckoutMutationBeforeHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
writer := &sourceChangeWriter{change: func() {
|
||||||
|
source, err := os.ReadFile(filepath.Join(repository, "cmd/app/main.go"))
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("read application source: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeBuildFixture(t, repository, "cmd/app/main.go", string(source)+"\n// changed during delivery build\n")
|
||||||
|
}}
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: writer,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "build source") || result.State != releasekit.DeliveryNotAttempted {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want build-source eligibility failure", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("ineligible managed build output remains: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/missing",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || result.CandidateCommit != remote.commit {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want managed build failure before hosted writes", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("failed managed build output remains: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverManagedBuildCancellationCleansTemporaryOutput(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
temporaryRoot := t.TempDir()
|
||||||
|
t.Setenv("TMPDIR", temporaryRoot)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
writer := deliveryCancelWriter{cancel: cancel}
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "fixture",
|
||||||
|
Targets: []releasekit.Target{{OS: runtime.GOOS, Arch: runtime.GOARCH}},
|
||||||
|
},
|
||||||
|
Output: writer,
|
||||||
|
})
|
||||||
|
if !errors.Is(err, context.Canceled) || result.State != releasekit.DeliveryNotAttempted {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want cancellation before hosted writes", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
if entries, err := os.ReadDir(temporaryRoot); err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("canceled managed build output remains: entries=%v error=%v", entries, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeliverRejectsBothBuildSourcesBeforeHostedWrites(t *testing.T) {
|
||||||
|
repository := newTaggedDeliveryConsumer(t)
|
||||||
|
server, remote := newFacadeDeliveryServer(t, repository)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
result, err := releasekit.Deliver(context.Background(), releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Fixture",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Destination: facadeDeliveryDestination(server.URL),
|
||||||
|
Build: &releasekit.BuildSpec{},
|
||||||
|
Prebuilt: &releasekit.BuildResult{},
|
||||||
|
})
|
||||||
|
if err == nil || result.State != releasekit.DeliveryNotAttempted || !strings.Contains(err.Error(), "both") {
|
||||||
|
t.Fatalf("Deliver() = %#v, %v; want invalid build-source combination", result, err)
|
||||||
|
}
|
||||||
|
if remote.requests != 0 {
|
||||||
|
t.Fatalf("hosted requests = %d, want none", remote.requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTaggedDeliveryConsumer(t *testing.T) string {
|
||||||
|
return newTaggedDeliveryConsumerWithNote(t, "# Fixture v1.2.3\n\nDelivery fixture.\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTaggedDeliveryConsumerWithNote(t *testing.T, note string) string {
|
||||||
|
t.Helper()
|
||||||
|
repository := newBuildConsumer(t, `package main
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
func main() { if len(os.Args) == 2 && os.Args[1] == "version" { fmt.Println("fixture", buildinfo.Version()) } }
|
||||||
|
`)
|
||||||
|
writeBuildFixture(t, repository, "docs/releases/v1.2.3.md", note)
|
||||||
|
buildGit(t, repository, "add", "--all")
|
||||||
|
buildGit(t, repository, "commit", "-m", "add release note")
|
||||||
|
buildGit(t, repository, "tag", "v1.2.3")
|
||||||
|
return repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func facadeDeliveryDestination(baseURL string) releasekit.GiteaDestination {
|
||||||
|
return releasekit.GiteaDestination{BaseURL: baseURL, Owner: "owner", Repository: "example", Token: "fixture-token"}
|
||||||
|
}
|
||||||
|
|
||||||
|
type deliveryCancelWriter struct{ cancel context.CancelFunc }
|
||||||
|
|
||||||
|
func (writer deliveryCancelWriter) Write(content []byte) (int, error) {
|
||||||
|
writer.cancel()
|
||||||
|
return len(content), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type facadeDeliveryServer struct {
|
||||||
|
t *testing.T
|
||||||
|
commit string
|
||||||
|
tag string
|
||||||
|
version string
|
||||||
|
noteBody string
|
||||||
|
pages map[string]bool
|
||||||
|
requests int
|
||||||
|
assets map[string][]byte
|
||||||
|
url string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFacadeDeliveryServer(t *testing.T, repository string) (*httptest.Server, *facadeDeliveryServer) {
|
||||||
|
t.Helper()
|
||||||
|
state := &facadeDeliveryServer{t: t, commit: buildGit(t, repository, "rev-parse", "HEAD"), tag: "v1.2.3", version: "v1.2.3", noteBody: "# Fixture v1.2.3\n\nDelivery fixture.\n", pages: make(map[string]bool), assets: make(map[string][]byte)}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(state.serveHTTP))
|
||||||
|
state.url = server.URL
|
||||||
|
return server, state
|
||||||
|
}
|
||||||
|
|
||||||
|
func (state *facadeDeliveryServer) serveHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||||
|
state.requests++
|
||||||
|
if r.Header.Get("Authorization") != "token fixture-token" {
|
||||||
|
state.t.Errorf("authorization = %q", r.Header.Get("Authorization"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch r.URL.EscapedPath() {
|
||||||
|
case "/api/v1/repos/owner/example/tags/" + url.PathEscape(state.tag):
|
||||||
|
_, _ = fmt.Fprintf(w, `{"name":%q,"commit":{"sha":%q}}`, state.tag, state.commit)
|
||||||
|
case "/api/v1/repos/owner/example/releases/tags/" + url.PathEscape(state.tag):
|
||||||
|
if !state.pages[state.tag] {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state.writeRelease(w)
|
||||||
|
case "/api/v1/repos/owner/example/releases":
|
||||||
|
var payload struct {
|
||||||
|
Tag string `json:"tag_name"`
|
||||||
|
Target string `json:"target_commitish"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
state.t.Errorf("decode release payload: %v", err)
|
||||||
|
http.Error(w, "invalid payload", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if payload.Tag != state.tag || payload.Target != state.commit || payload.Name != "Fixture "+state.version {
|
||||||
|
state.t.Errorf("release payload = %#v", payload)
|
||||||
|
}
|
||||||
|
state.pages[state.tag] = true
|
||||||
|
state.writeRelease(w)
|
||||||
|
case "/api/v1/repos/owner/example/releases/10/assets":
|
||||||
|
if r.Method == http.MethodGet {
|
||||||
|
list := make([]map[string]any, 0, len(state.assets))
|
||||||
|
for name, content := range state.assets {
|
||||||
|
list = append(list, map[string]any{"id": len(list) + 1, "name": name, "size": len(content), "browser_download_url": state.url + "/files/" + name})
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(list)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := r.URL.Query().Get("name")
|
||||||
|
file, _, err := r.FormFile("attachment")
|
||||||
|
if err != nil {
|
||||||
|
state.t.Errorf("read upload %q: %v", name, err)
|
||||||
|
http.Error(w, "invalid multipart upload", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
content, err := io.ReadAll(file)
|
||||||
|
_ = file.Close()
|
||||||
|
if err != nil {
|
||||||
|
state.t.Errorf("read upload %q: %v", name, err)
|
||||||
|
}
|
||||||
|
state.assets[name] = content
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": len(state.assets), "name": name, "size": len(content)})
|
||||||
|
default:
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/files/") {
|
||||||
|
name := strings.TrimPrefix(r.URL.Path, "/files/")
|
||||||
|
content, ok := state.assets[name]
|
||||||
|
if !ok {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write(content)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
state.t.Errorf("unexpected delivery request %s %s", r.Method, r.URL)
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (state *facadeDeliveryServer) writeRelease(w http.ResponseWriter) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||||
|
"id": 10, "html_url": state.url + "/releases/10", "tag_name": state.tag,
|
||||||
|
"target_commitish": state.commit, "name": "Fixture " + state.version,
|
||||||
|
"body": state.noteBody, "draft": false, "prerelease": false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func mapKeys(values map[string][]byte) []string {
|
||||||
|
keys := make([]string, 0, len(values))
|
||||||
|
for key := range values {
|
||||||
|
keys = append(keys, key)
|
||||||
|
}
|
||||||
|
return keys
|
||||||
|
}
|
||||||
3
doc.go
Normal file
3
doc.go
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
// Package releasekit is the public facade for ReleaseKit's release process.
|
||||||
|
// Public operations are added as their behavior is implemented.
|
||||||
|
package releasekit
|
||||||
84
docs/adr/0001-public-facade.md
Normal file
84
docs/adr/0001-public-facade.md
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
# ADR 0001: Own public contracts through facades
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted.
|
||||||
|
|
||||||
|
## Date
|
||||||
|
|
||||||
|
2026-10-05
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
ReleaseKit is being designed as an opinionated Go library with a release
|
||||||
|
executable. Its responsibilities include publication, cross-builds, version
|
||||||
|
injection, and artifact delivery. Consuming applications also need lightweight
|
||||||
|
access to the version embedded in their binaries.
|
||||||
|
|
||||||
|
ConfigKit and PromptKit demonstrate a facade approach in which public packages
|
||||||
|
own consumer contracts and delegate to internal implementation. This gives
|
||||||
|
maintainers room to change internal structure while preserving supported type
|
||||||
|
identity, method sets, and behavior. ReleaseKit needs that boundary from its
|
||||||
|
first implementation.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
The root `releasekit` package is the public facade for release orchestration. A
|
||||||
|
separate public `buildinfo` package is the facade for runtime version information.
|
||||||
|
Each package exposes a cohesive set of operations and values justified by
|
||||||
|
consumer needs.
|
||||||
|
|
||||||
|
Each facade defines its public named types and owns their documented behavior.
|
||||||
|
Exported signatures, fields, callbacks, and method sets use facade-owned types
|
||||||
|
and deliberately selected public dependencies. Handles retain implementation
|
||||||
|
state in private fields and expose explicitly selected methods. Forwarding and
|
||||||
|
conversion code translates between public contracts and internal representations.
|
||||||
|
|
||||||
|
Implementation packages live under Go's `internal/` boundary. Dependency
|
||||||
|
direction runs from public facades into internal implementation. Contracts shared
|
||||||
|
between implementation packages belong inside that boundary. Git operations, Go
|
||||||
|
toolchain execution, Gitea integration, and orchestration bookkeeping remain
|
||||||
|
implementation responsibilities, with package layout chosen for cohesion.
|
||||||
|
|
||||||
|
The `buildinfo` facade has a lightweight dependency graph suitable for application
|
||||||
|
runtime imports. Its version accessor is a supported public contract. ReleaseKit's
|
||||||
|
builder and runtime implementation own the linker symbol and injection mechanism
|
||||||
|
together, allowing applications to obtain their version through the accessor.
|
||||||
|
|
||||||
|
The release executable invokes the supported orchestration facade and owns
|
||||||
|
command parsing, output, and exit codes. The library returns consumer-facing
|
||||||
|
errors and outcomes that describe publication state, including partial progress
|
||||||
|
and uncertainty.
|
||||||
|
|
||||||
|
Go declarations and GoDoc own exact public API contracts. Additional public
|
||||||
|
packages and extension interfaces require a deliberate decision grounded in a
|
||||||
|
durable consumer need. Compiled-export and dependency checks protect facade
|
||||||
|
ownership; external-package behavioral tests protect consumer semantics.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- Keep implementation in public packages: reduces forwarding work and makes
|
||||||
|
implementation declarations part of the surface contributors must maintain.
|
||||||
|
- Use aliases or embedded implementation types: reduces conversion code while
|
||||||
|
coupling consumer type identity and method sets to implementation types.
|
||||||
|
- Provide one facade for orchestration and runtime version access: offers one
|
||||||
|
import path and a shared dependency graph for both responsibilities.
|
||||||
|
- Expose a public package for each implementation component: enables direct
|
||||||
|
component reuse and expands the compatibility surface across Git, build, and
|
||||||
|
delivery machinery.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Consumers depend on deliberate contracts in `releasekit` and `buildinfo`.
|
||||||
|
Internal algorithms, collaborators, and package boundaries can evolve while
|
||||||
|
those contracts remain stable. Both public packages participate in ReleaseKit's
|
||||||
|
versioning and compatibility obligations.
|
||||||
|
|
||||||
|
Explicit forwarding and conversions add maintenance work. They must preserve
|
||||||
|
error identity, value ownership, callback lifetime, and observable outcomes.
|
||||||
|
Boundary checks and representative consumer tests provide evidence for those
|
||||||
|
properties as implementation proceeds.
|
||||||
|
|
||||||
|
The separate `buildinfo` facade supports runtime use with a small dependency
|
||||||
|
surface. Its integration with the builder requires tests that verify the selected
|
||||||
|
release version is injected and reported correctly.
|
||||||
63
docs/adr/0002-routine-releases.md
Normal file
63
docs/adr/0002-routine-releases.md
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# ADR 0002: Make routine releases a shared responsibility
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted.
|
||||||
|
|
||||||
|
## Date
|
||||||
|
|
||||||
|
2026-10-06
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Applications in the suite repeat release code and require developers to manage
|
||||||
|
similar release decisions. ReleaseKit centralizes this work. Its value depends
|
||||||
|
on reducing application maintenance and the time developers spend on releases.
|
||||||
|
|
||||||
|
Build specialization, environment standardization, and detailed inspection can
|
||||||
|
serve particular consumers. Supporting them can also expand the API,
|
||||||
|
configuration, and release knowledge each application must maintain. ReleaseKit
|
||||||
|
needs a clear priority for evaluating these tradeoffs.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
ReleaseKit provides a standard, minimal API for routine releases. It minimizes
|
||||||
|
application-owned release code, duplication across applications, and the
|
||||||
|
decisions application developers must make.
|
||||||
|
|
||||||
|
ReleaseKit owns the common release procedure and sensible defaults. Applications
|
||||||
|
supply product facts, compatibility requirements, and product-specific checks.
|
||||||
|
|
||||||
|
Hardware-specific build options, strict build reproducibility, extensive build
|
||||||
|
inspection, and comparable specialization are non-goals to the extent that
|
||||||
|
supporting them conflicts with these primary goals.
|
||||||
|
|
||||||
|
Evaluate proposed capabilities by their effect on ordinary application
|
||||||
|
integration: the code applications maintain, the configuration they supply, and
|
||||||
|
the release decisions developers make. A demonstrated consumer need informs
|
||||||
|
that assessment; the selected approach must preserve the routine release model.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- A broadly configurable release toolkit gives applications control over build
|
||||||
|
and release mechanics. Applications then own more composition code and
|
||||||
|
configuration decisions.
|
||||||
|
- A tightly standardized build environment prioritizes reproducibility and
|
||||||
|
detailed build records. It adds environment maintenance and coordination
|
||||||
|
responsibilities across applications.
|
||||||
|
|
||||||
|
The selected approach evaluates those capabilities by the application work and
|
||||||
|
developer effort they save.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Common release operations belong behind reusable orchestration. Shared defaults
|
||||||
|
reduce configuration and routine decisions. ReleaseKit can absorb internal
|
||||||
|
complexity when doing so keeps application integration small and maintainable.
|
||||||
|
|
||||||
|
New options carry implementation, maintenance, and decision costs. Consumer
|
||||||
|
needs justify evaluating an option; its adoption must support the primary goals.
|
||||||
|
|
||||||
|
The [architecture policy](../policy/architecture.md) owns current architectural
|
||||||
|
constraints. [ADR 0001](0001-public-facade.md) records the facade boundaries.
|
||||||
|
GoDoc owns exact API contracts.
|
||||||
76
docs/adr/0003-declarative-validation.md
Normal file
76
docs/adr/0003-declarative-validation.md
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
# ADR 0003: Declare optional validation through a shared specification
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted.
|
||||||
|
|
||||||
|
## Date
|
||||||
|
|
||||||
|
2026-10-07
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Consumers have different release-validation needs. Their additional checks
|
||||||
|
include reusable mechanics such as formatting inspection and Go toolchain
|
||||||
|
invocations, alongside assertions about product behavior. Maintaining the
|
||||||
|
reusable mechanics in each application duplicates code and coordination work.
|
||||||
|
|
||||||
|
[ADR 0001](0001-public-facade.md) establishes facade ownership of public
|
||||||
|
contracts. [ADR 0002](0002-routine-releases.md) prioritizes routine releases
|
||||||
|
with little application-owned code or recurring developer effort. Optional
|
||||||
|
validation needs a common selection and execution model that supports these
|
||||||
|
decisions as shared capabilities grow.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Consumers select shared validation through a typed, facade-owned specification
|
||||||
|
and equivalent release-profile settings. Related settings belong together.
|
||||||
|
Omitted optional settings preserve existing default validation behavior.
|
||||||
|
|
||||||
|
`Check` and `Publish` use one internal validation path bound to the captured
|
||||||
|
candidate. ReleaseKit owns execution, ordering, coordination between selected
|
||||||
|
checks, and propagation of failures and cancellation. The CLI maps profile
|
||||||
|
settings to the facade and owns presentation.
|
||||||
|
|
||||||
|
Shared validation exposes consistent diagnostics through facade-owned errors.
|
||||||
|
Findings identify the check and provide actionable detail where applicable.
|
||||||
|
Error wrapping preserves underlying causes and cancellation semantics.
|
||||||
|
Validation failures and publication outcomes retain their distinct meanings.
|
||||||
|
|
||||||
|
The existing `AdditionalChecks` callback and profile `checks` support
|
||||||
|
product-specific assertions. Publication guards, artifact builds, and delivery
|
||||||
|
retain their separate configuration and responsibilities. Validation execution
|
||||||
|
and coordination remain internal implementation responsibilities.
|
||||||
|
|
||||||
|
Evaluate optional capabilities by the application maintenance they remove,
|
||||||
|
their clarity of scope, configuration burden, and maintenance cost. A
|
||||||
|
capability can serve a small subset of consumers when those benefits justify
|
||||||
|
shared support. Consumers select the checks appropriate to their products.
|
||||||
|
|
||||||
|
GoDoc owns exact public API contracts, and the configuration reference owns
|
||||||
|
profile settings. Roadmaps own feature scope and implementation sequencing.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- Consumer-owned commands preserve local control and leave applications
|
||||||
|
maintaining reusable inspection, invocation, and coordination code.
|
||||||
|
- Independently configured check and publication paths allow separate
|
||||||
|
validation choices and require consumers to keep those choices aligned.
|
||||||
|
- A public validator-registration framework supports custom composition and
|
||||||
|
expands the public lifecycle and ordering contracts. The existing
|
||||||
|
additional-check extension point supports current product-specific needs.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Applications can replace repeated release mechanics with small declarations.
|
||||||
|
Go callers and CLI users receive equivalent selected validation through the
|
||||||
|
same release operations. Existing consumers retain their default behavior and
|
||||||
|
additional-check integration as optional capabilities are introduced.
|
||||||
|
|
||||||
|
ReleaseKit assumes responsibility for maintaining shared checks, coordinating
|
||||||
|
their interactions, and presenting useful diagnostics. Public selections and
|
||||||
|
error contracts carry compatibility obligations. Verification must cover
|
||||||
|
default behavior, equivalent API and profile selections, and failure propagation.
|
||||||
|
|
||||||
|
Internal execution can evolve within the facade boundaries. Each new capability
|
||||||
|
requires a clear scope and evidence that shared ownership reduces consumer work.
|
||||||
68
docs/adr/0004-module-selected-tooling.md
Normal file
68
docs/adr/0004-module-selected-tooling.md
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# ADR 0004: Select release tooling from the released application's module configuration
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted.
|
||||||
|
|
||||||
|
## Date
|
||||||
|
|
||||||
|
2026-10-07
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Applications can declare ReleaseKit as a Go module dependency and use that
|
||||||
|
selection to build their local release tool. A separate CI version pin creates
|
||||||
|
a second declaration that maintainers must coordinate during upgrades. The two
|
||||||
|
paths can then use different ReleaseKit versions for the same release.
|
||||||
|
|
||||||
|
Hosted delivery runs after source publication and may be retried for an older
|
||||||
|
release. It needs a stable source for tool-version selection associated with
|
||||||
|
that release. [ADR 0002](0002-routine-releases.md) prioritizes reducing repeated
|
||||||
|
configuration and routine release decisions.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
For applications that declare ReleaseKit as a module dependency, the standard
|
||||||
|
integration selects the tool through the application's module configuration.
|
||||||
|
Local publication uses the candidate's module configuration. CI delivery uses
|
||||||
|
the released source's module configuration. Both paths follow the same
|
||||||
|
module-based selection approach.
|
||||||
|
|
||||||
|
CI verifies the triggering tag and commit and checks out that source before
|
||||||
|
resolving and building the release tool. Delivery retries use the same released
|
||||||
|
source for tool selection. The application maintains its ReleaseKit dependency
|
||||||
|
as the shared version declaration for these operations.
|
||||||
|
|
||||||
|
Tool bootstrap and dependency preparation remain separate from offline
|
||||||
|
validation and builds. The CI integration supplies the event, environment, and
|
||||||
|
credentials; the application profile supplies product and delivery settings.
|
||||||
|
Source publication and hosted delivery retain their separate outcomes.
|
||||||
|
|
||||||
|
Consumers using a separately installed tool and ReleaseKit's own source
|
||||||
|
bootstrap remain supported use cases. Adoption guidance describes the
|
||||||
|
appropriate bootstrap for each integration.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- An independent CI version pin makes tool selection explicit in the workflow
|
||||||
|
and requires maintainers to coordinate it with the application's dependency.
|
||||||
|
- Selecting from the current default branch follows ongoing dependency
|
||||||
|
updates and allows delivery retries for an older release to select a newer
|
||||||
|
tool.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Applications using the standard module-based integration update one dependency
|
||||||
|
declaration for local publication and CI delivery. Tool selection follows the
|
||||||
|
released source when delivery is retried, preserving the release's dependency
|
||||||
|
choice as the application evolves.
|
||||||
|
|
||||||
|
CI must establish the released checkout before tool bootstrap. Its environment
|
||||||
|
must provide a compatible Go toolchain and access to the dependencies needed
|
||||||
|
to build the selected tool. Retrying delivery for an older release retains
|
||||||
|
those preparation requirements.
|
||||||
|
|
||||||
|
Maintained templates and adoption guidance must preserve this selection order.
|
||||||
|
Verification should exercise a dependency-version change and selection from
|
||||||
|
the triggering release's source. Exact commands and bootstrap mechanics belong
|
||||||
|
in the maintained integration guidance and examples.
|
||||||
111
docs/adr/0005-module-release-scope.md
Normal file
111
docs/adr/0005-module-release-scope.md
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
# ADR 0005: Select a Go module as the unit of release
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Accepted.
|
||||||
|
|
||||||
|
## Date
|
||||||
|
|
||||||
|
2026-10-09
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
A Go repository can contain independently versioned modules. CommandKit plans
|
||||||
|
to release its core and optional integrations from one repository. Each module
|
||||||
|
needs its own validation, release note, semantic version, and Git tag.
|
||||||
|
|
||||||
|
ReleaseKit currently couples the semantic version to the Git tag and uses the
|
||||||
|
repository directory for Go validation and release-note discovery. Supporting
|
||||||
|
independent modules through consumer-owned publication code would duplicate
|
||||||
|
ReleaseKit's responsibilities.
|
||||||
|
|
||||||
|
[ADR 0002](0002-routine-releases.md) prioritizes routine releases with little
|
||||||
|
application-owned code or recurring decision-making.
|
||||||
|
[ADR 0003](0003-declarative-validation.md) establishes shared declarative
|
||||||
|
validation. Module selection should give those checks a coherent release scope.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Each check or publication invocation selects one Go module within a Git
|
||||||
|
repository. Omitted module selection means the repository-root module. The
|
||||||
|
public Go API and CLI/profile interface express the same selection. Consumers
|
||||||
|
can use small per-module profiles through a shared launcher.
|
||||||
|
|
||||||
|
ReleaseKit distinguishes the repository directory, selected module directory,
|
||||||
|
semantic version, and complete Git tag. It derives the tag using Go's module
|
||||||
|
tag conventions and the selected module's committed declaration. Derivation
|
||||||
|
accounts for major-version directories. For example, a module in
|
||||||
|
`integrations/ckconfig` at `v0.2.0` uses the tag
|
||||||
|
`integrations/ckconfig/v0.2.0`. A module declared with a `/v2` suffix and stored
|
||||||
|
in `integrations/ckconfig/v2` uses `integrations/ckconfig/v2.0.0` for `v2.0.0`.
|
||||||
|
|
||||||
|
The semantic version identifies the module release. The complete tag identifies
|
||||||
|
its source in the shared repository and governs uniqueness, tag creation,
|
||||||
|
publication, source links, and recovery. Candidate evidence, publication
|
||||||
|
results, and CLI output identify the selected module and both version and tag,
|
||||||
|
alongside the existing commit and publication evidence. Failure outcomes retain
|
||||||
|
the resolved identity for recovery.
|
||||||
|
|
||||||
|
Release notes belong at `<module-directory>/docs/releases/<version>.md` and
|
||||||
|
identify the product and semantic version in their title. ReleaseKit reads the
|
||||||
|
selected note from the captured candidate. Root-module releases retain the
|
||||||
|
existing note layout and unprefixed tags. Modules can publish equal semantic
|
||||||
|
versions through their distinct notes and tags.
|
||||||
|
|
||||||
|
Mandatory and optional release validation share the selected module's scope.
|
||||||
|
Go tests, selected vet, and package compilation execute in that module with
|
||||||
|
the existing offline environment. File checks inspect the module's committed
|
||||||
|
contents and relevant release materials. Independently released nested modules
|
||||||
|
are excluded from their parent's validation scope. Selecting the root module
|
||||||
|
follows the same rule.
|
||||||
|
|
||||||
|
A check may inspect referenced material outside the selected module when needed
|
||||||
|
to validate an in-scope item. Resolving a Markdown link to shared repository
|
||||||
|
documentation does not add that destination's documents to the validation input
|
||||||
|
set. The checkout remains the boundary for checks of outside-checkout links.
|
||||||
|
Shared release materials follow established conventions and documented
|
||||||
|
consumer requirements.
|
||||||
|
|
||||||
|
Product-specific checks receive the selected module context and repository
|
||||||
|
context for deliberate composition checks. ReleaseKit applies module selection
|
||||||
|
consistently across its shared checks, avoiding separate scope settings for
|
||||||
|
each check.
|
||||||
|
|
||||||
|
Publication guards cover the shared repository: cleanliness, branch, candidate
|
||||||
|
commit, authoritative endpoint, and the complete selected tag. The standard
|
||||||
|
suite runs once for the selected candidate and module. Successful source-tag
|
||||||
|
publication remains the completion point, with existing failure and uncertain
|
||||||
|
publication outcomes preserved. Consumers prepare released sibling dependencies
|
||||||
|
and choose their publication order.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- Consumer-owned module publication gives each application responsibility for
|
||||||
|
tag conventions, validation, and recovery, duplicating shared mechanics.
|
||||||
|
- Module-local Go execution with repository-wide optional validation lets
|
||||||
|
unrelated modules block a selected release and gives checks inconsistent
|
||||||
|
scopes.
|
||||||
|
- Independent scope settings for each check require consumers to coordinate
|
||||||
|
multiple declarations of the same release boundary.
|
||||||
|
- Coordinated multi-module publication adds release-set and dependency-ordering
|
||||||
|
responsibilities beyond the demonstrated need for individual releases.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Consumers describe the module and product being released while ReleaseKit owns
|
||||||
|
the common procedure. Existing single-module repositories retain their default
|
||||||
|
behavior. Root modules containing independently released nested modules gain
|
||||||
|
module-scoped validation; release notes and migration guidance must explain
|
||||||
|
that change.
|
||||||
|
|
||||||
|
The shared candidate and publication paths must carry module scope and separate
|
||||||
|
version and tag identity throughout validation, diagnostics, and recovery.
|
||||||
|
Verification must cover root defaults, nested-module failures, equal versions
|
||||||
|
across modules, major-version directories, validation boundaries, and exact-tag
|
||||||
|
publication outcomes.
|
||||||
|
|
||||||
|
GoDoc and consumer documentation will own exact API and scope contracts.
|
||||||
|
Configuration and CLI documentation will own profile fields, commands, and
|
||||||
|
output. Implementation planning will define interactions with artifact builds
|
||||||
|
and hosted delivery. ReleaseKit's maintainer release policy continues to govern
|
||||||
|
ReleaseKit's own releases; consumers document their adopted module conventions.
|
||||||
260
docs/cli.md
Normal file
260
docs/cli.md
Normal file
@@ -0,0 +1,260 @@
|
|||||||
|
# Command line
|
||||||
|
|
||||||
|
ReleaseKit currently provides six commands. The exit statuses below belong
|
||||||
|
to the native executable. `go run` examples are convenient for source execution,
|
||||||
|
but the Go driver maps a nonzero child exit status to 1. Use the built executable
|
||||||
|
or `./scripts/release` for publication when distinct statuses are needed.
|
||||||
|
|
||||||
|
Print the executable version:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit version
|
||||||
|
```
|
||||||
|
|
||||||
|
This prints `releasekit <version>` followed by a newline and exits with status 0.
|
||||||
|
The version comes from [`buildinfo.Version`](consumers/runtime-version.md).
|
||||||
|
|
||||||
|
Check a local candidate:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit check [--repo DIR] [--config FILE] VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
`VERSION` must use stable `vMAJOR.MINOR.PATCH` syntax. Options must precede the
|
||||||
|
version. The repository argument defaults to the current directory. ReleaseKit
|
||||||
|
resolves its containing Git checkout root before selecting the module or profile;
|
||||||
|
the profile defaults to `<repository-root>/releasekit.json`. A successful command prints the
|
||||||
|
captured module, version, full tag, and commit. It checks the committed release note and
|
||||||
|
local Git state, runs the standard offline Go test suite (with `-race` when
|
||||||
|
`validation.go.race` is true), and runs a separate `go vet -mod=readonly ./...`
|
||||||
|
pass after successful tests when `validation.go.full_vet` is true. It then runs
|
||||||
|
selected package compilation and committed Go formatting, followed by
|
||||||
|
configured additional checks in profile order. It does not inspect remote
|
||||||
|
availability or publish a tag.
|
||||||
|
|
||||||
|
The profile's optional `module_dir` selects a repository-relative physical
|
||||||
|
module directory; omission selects the root module. Validation and configured
|
||||||
|
product checks use that module selection. Additional check commands run with
|
||||||
|
the selected module as their working directory and receive
|
||||||
|
`RELEASEKIT_VERSION`, `RELEASEKIT_CANDIDATE`, `RELEASEKIT_REPOSITORY_DIR`,
|
||||||
|
`RELEASEKIT_MODULE_DIR`, `RELEASEKIT_MODULE_PATH`, and `RELEASEKIT_TAG` in their
|
||||||
|
environment. These values are added to each child environment without changing
|
||||||
|
the ReleaseKit process environment.
|
||||||
|
|
||||||
|
When `validation.go.compile_targets` is selected, `check` compiles all packages
|
||||||
|
for each configured `GOOS/GOARCH` pair after tests and full vet, using static
|
||||||
|
mode with cgo disabled. This check produces no artifacts and does not execute
|
||||||
|
target binaries. Compilation failures use the `package-compile` identity and
|
||||||
|
show the selected target. When `validation.go_format` is true, `check` examines
|
||||||
|
regular committed Go files with the Go formatter after tests, vet, and package
|
||||||
|
compilation. It uses the selected module and shared-file inputs, including
|
||||||
|
vendored source, and ignores the worktree
|
||||||
|
and symlink blobs, and reports unformatted paths as `go-format` without
|
||||||
|
modifying files. When `validation.module_distribution.workspace_files` is true,
|
||||||
|
`check` reports committed `go.work` and `go.work.sum` blobs in those inputs,
|
||||||
|
including symlink entries, as `workspace-files`. Automatic file inputs stop at
|
||||||
|
independent nested modules. This inspection is independent of
|
||||||
|
`GOWORK` and ignores uncommitted files. Any artifact build selected by the
|
||||||
|
separate `build` setting runs after shared validation and configured checks.
|
||||||
|
When `validation.markdown` is a non-null object, `check` checks committed local
|
||||||
|
Markdown destinations and supported heading fragments after file-size
|
||||||
|
inspection. An empty object enables the check; omission or `null` disables it.
|
||||||
|
Outside-checkout links are written as out-of-scope observations to standard
|
||||||
|
error by default. Setting `validation.markdown.enforce_checkout_boundary` to
|
||||||
|
true makes those links fail; submodule-content observations remain
|
||||||
|
nonfailures. Failures use the `markdown-links` identity with the source location
|
||||||
|
and target.
|
||||||
|
|
||||||
|
`check` writes errors and diagnostics to standard error. It returns status 0
|
||||||
|
after local validation, 1 after a candidate validation failure, and 2 for usage,
|
||||||
|
profile, or invalid-version errors. Shared validation failures identify the
|
||||||
|
failed check and retain useful findings and cause context in one diagnostic;
|
||||||
|
separate full-vet failures use the `go-vet` identity.
|
||||||
|
Unsupported argument sequences print usage to standard error.
|
||||||
|
|
||||||
|
Publish a source tag:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit publish [--repo DIR] [--config FILE] [--expected-module DIR] VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
`publish` reads the same product, remote, validation, and additional-check
|
||||||
|
settings as `check`. It checks the authoritative remote and validates the
|
||||||
|
candidate: the single standard offline Go test suite runs first, with `-race`
|
||||||
|
when `validation.go.race` is true. When `validation.go.full_vet` is true,
|
||||||
|
test-time vet is disabled and `go vet -mod=readonly ./...` runs after successful
|
||||||
|
tests. Selected package compilation and committed Go formatting follow. The
|
||||||
|
selected file checks then run in order: workspace files, local replacements,
|
||||||
|
file size, and Markdown. Configured checks run afterward in profile order. It
|
||||||
|
then creates an annotated local tag
|
||||||
|
and pushes only its exact full tag object. It prints the confirmed semantic
|
||||||
|
version, full tag, candidate commit, and tag object
|
||||||
|
on success. Validation
|
||||||
|
progress and failed publication state, including the captured publication
|
||||||
|
endpoint for recovery, are written to standard error. A signal
|
||||||
|
cancels the active operation; if it arrives during a push, the library's
|
||||||
|
bounded reconciliation determines whether the exact tag was accepted.
|
||||||
|
Shared validation failures use the same check and finding presentation as
|
||||||
|
`check`, alongside publication state and phase.
|
||||||
|
|
||||||
|
When `validation.go.compile_targets` is selected, package compilation runs
|
||||||
|
after tests and full vet and before configured checks. Each failure is reported
|
||||||
|
as `package-compile` with its selected target; this does not create build
|
||||||
|
artifacts or execute target binaries. When `validation.go_format` is true,
|
||||||
|
committed Go formatting runs after package compilation and before configured
|
||||||
|
checks. The selected workspace-file check then reports committed go.work and
|
||||||
|
go.work.sum paths as `workspace-files`. Formatting failures are reported as
|
||||||
|
`go-format` with affected paths and preserve parser or source-inspection causes.
|
||||||
|
|
||||||
|
When `validation.module_distribution.local_replacements` is true, the command
|
||||||
|
parses committed `go.mod` declarations in the selected module after
|
||||||
|
workspace-file inspection. Vendored contents remain in scope, while
|
||||||
|
automatic inputs stop at independently released nested modules. Explicit shared
|
||||||
|
files join the file-check inputs without expanding Go scope. Filesystem replacements use
|
||||||
|
the `local-replacements` identity and include the declaration path, source line,
|
||||||
|
and target; versioned replacements are permitted. Committed module symlinks are
|
||||||
|
resolved within the candidate, regardless of `GOWORK`.
|
||||||
|
When `validation.file_size` is a non-null object, the command checks each
|
||||||
|
committed blob after module-distribution checks. An omitted or null object
|
||||||
|
disables the check; an empty object enables the 1,000,000 decimal-byte default.
|
||||||
|
Oversized files use the `file-size` identity and report their path and measured
|
||||||
|
size against the limit. See the [configuration reference](config.md) for
|
||||||
|
literal exclusions and the current-candidate scope.
|
||||||
|
When `validation.markdown` is a non-null object, `publish` checks committed
|
||||||
|
Markdown destinations after file-size inspection and before configured checks.
|
||||||
|
It reports outside-checkout links to standard error unless boundary enforcement
|
||||||
|
is selected; submodule contents remain out of scope. Markdown failures stop
|
||||||
|
publication before product checks or tag creation.
|
||||||
|
|
||||||
|
`--expected-module DIR` optionally checks a launcher's selected physical module
|
||||||
|
against the profile's `module_dir` before candidate work. Both paths are
|
||||||
|
normalized relative to the repository; the profile remains the source of module
|
||||||
|
selection. The root selection is `.`.
|
||||||
|
|
||||||
|
The optional profile field `expected_push_url` applies only to `publish`. A
|
||||||
|
nonempty value must exactly match the effective push URL resolved by Git;
|
||||||
|
mismatches fail during preflight before Go validation or tag creation. Git URL
|
||||||
|
rewrites are resolved first, and the push URL is used when fetch and push URLs
|
||||||
|
differ. `check` ignores this field.
|
||||||
|
|
||||||
|
The command returns status 0 for confirmed publication, 1 for a known
|
||||||
|
publication failure or conflict, 2 for usage, profile, or invalid-version
|
||||||
|
errors, and 3 when the push outcome remains unknown. Unknown status must be
|
||||||
|
resolved against the authoritative remote before retrying. The
|
||||||
|
[maintainer procedure](release.md) selects the repository profile and gives
|
||||||
|
the source-release workflow.
|
||||||
|
|
||||||
|
Build selected application targets:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit build [--repo DIR] [--config FILE] [--output DIR] VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
`build` requires a `build` object in the profile. It compiles the selected
|
||||||
|
targets with the requested version injected, checks the native `version`
|
||||||
|
invocation, and writes binaries plus the private `.releasekit-build.json`
|
||||||
|
receipt into `dist` by default. `--output` selects a different directory;
|
||||||
|
relative paths are resolved from the selected module directory. Selected
|
||||||
|
artifact filenames are regenerated while unrelated files are preserved. A complete nonempty build
|
||||||
|
writes a receipt only after compilation and smoke checking succeed. On partial
|
||||||
|
failure, standard error lists completed outputs and prior receipts in that
|
||||||
|
output directory are invalidated; no new receipt is written. An
|
||||||
|
empty target list returns the source commit without building or writing a
|
||||||
|
receipt.
|
||||||
|
|
||||||
|
The command returns status 0 on completion, 1 for build or output failure, and
|
||||||
|
2 for usage, profile, or invalid-version errors. It builds the current source
|
||||||
|
tree and does not perform candidate validation or remote publication. `check`
|
||||||
|
and `publish` run the same configured build after their one candidate
|
||||||
|
validation, using temporary output outside the worktree.
|
||||||
|
|
||||||
|
Deliver a tagged source release to Gitea:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
`deliver` requires a `delivery` profile object and its configured token
|
||||||
|
environment variable, which defaults to `RELEASEKIT_GITEA_TOKEN`. It verifies
|
||||||
|
the local tag, clean tagged checkout, hosted tag, and committed release note,
|
||||||
|
then creates or finds the release page and reports delivery state separately
|
||||||
|
from source publication. Historical lightweight tags and detached checkouts
|
||||||
|
are supported when `HEAD` is the selected tag commit; delivery does not require
|
||||||
|
the former remote `main` to match.
|
||||||
|
|
||||||
|
When the profile has build targets and `--assets` is omitted, `deliver` passes
|
||||||
|
the configured build directly to the public delivery facade. The facade builds
|
||||||
|
the tagged source into temporary storage, removes it when the operation ends,
|
||||||
|
and uploads its binaries and complete `SHA256SUMS`. When `--assets DIR` is
|
||||||
|
supplied, that directory must contain the private `.releasekit-build.json`
|
||||||
|
receipt and matching unchanged artifacts; this keeps the caller's original
|
||||||
|
bytes available for retries. Relative `--assets` paths use the selected module
|
||||||
|
directory, matching `build --output`; absolute paths retain their supplied base.
|
||||||
|
Profiles without targets use page-only delivery
|
||||||
|
and need no receipt, binary build, or manifest. `deliver` never runs candidate
|
||||||
|
checks or publishes a tag.
|
||||||
|
|
||||||
|
Use one `deliver` invocation for the normal workflow. To build without delivery
|
||||||
|
credentials, or to retain build output across retries, run `build --output DIR`
|
||||||
|
first and then run `deliver --assets DIR` with the token available. The ordinary
|
||||||
|
`deliver` command does not download application dependencies or change the
|
||||||
|
checkout.
|
||||||
|
|
||||||
|
The command returns 0 for complete delivery, 1 for a known failure, conflict,
|
||||||
|
or partial delivery, 2 for usage, profile, or missing-credential errors, and 3
|
||||||
|
when a remote write remains uncertain. The result lists matching, uploaded,
|
||||||
|
pending, conflicting, and uncertain assets as disjoint current observations;
|
||||||
|
early failures may leave some declared assets unreported. On failure, the CLI
|
||||||
|
prints state-based recovery guidance. Fix local or preflight failures before
|
||||||
|
retrying; fix the reported cause before retrying partial delivery; resolve an
|
||||||
|
unknown remote state before retrying; and investigate conflicts, using a new
|
||||||
|
version if the source or published contents need correction. If rebuilding
|
||||||
|
could change asset bytes already on the server, retain the original build
|
||||||
|
artifacts and retry with `--assets DIR`. Matching content is kept and only
|
||||||
|
known missing assets are added. See the
|
||||||
|
[delivery consumer guide](consumers/delivery.md) and
|
||||||
|
[Gitea integration guide](integrations/gitea.md).
|
||||||
|
|
||||||
|
Prepare a tagged CI checkout and deliver it:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
releasekit ci-deliver [--repo DIR] [--config FILE] [--remote NAME] [--prepared] [--expected-module DIR] --commit OID TAG
|
||||||
|
```
|
||||||
|
|
||||||
|
`TAG` is the complete Git tag name, including any module path prefix. Its last
|
||||||
|
path component must be a stable semantic version; other commands continue to
|
||||||
|
take a semantic `VERSION`. By default, `ci-deliver` fetches the exact `TAG` from
|
||||||
|
the selected Git remote (default `origin`), requires its peeled commit to match
|
||||||
|
the required full `--commit` object ID, checks out that commit detached, then
|
||||||
|
verifies the tag, HEAD, and clean worktree. With `--prepared`, it performs those
|
||||||
|
checks read-only against the existing checkout and does not fetch or check out.
|
||||||
|
In either mode, it loads the profile from the verified source. `--expected-module`
|
||||||
|
optionally checks that the profile selects the module chosen by a launcher;
|
||||||
|
module selection itself remains profile-owned. The command validates delivery
|
||||||
|
settings and the configured token, then downloads application dependencies only
|
||||||
|
when the profile selects build targets. Binary profiles are built and delivered
|
||||||
|
through the same facade path as `deliver`; source-only profiles skip dependency
|
||||||
|
downloads and binary builds.
|
||||||
|
`--config` follows the existing profile path rules: relative paths are resolved
|
||||||
|
from `--repo`, and absolute paths are used as-is. The default mode prepares and
|
||||||
|
changes the selected checkout; `--prepared` reuses a verified checkout.
|
||||||
|
Ordinary `deliver` continues to operate on already prepared source without
|
||||||
|
fetching, checking out, or downloading dependencies.
|
||||||
|
|
||||||
|
In Woodpecker, pass `CI_WORKSPACE`, `CI_COMMIT_SHA`, and `CI_COMMIT_TAG` as the
|
||||||
|
repository, expected commit, and full tag arguments. The CLI does not read
|
||||||
|
provider-specific environment variable names. Checkout and dependency
|
||||||
|
preparation failures return status 1; usage, profile, credential, and invalid
|
||||||
|
version errors return status 2. Final delivery uses the same statuses as
|
||||||
|
`deliver`: 0 for complete, 1 for known failure, conflict, or partial delivery,
|
||||||
|
and 3 for uncertain remote state.
|
||||||
|
|
||||||
|
The maintained module-based tag workflow verifies and checks out the event tag
|
||||||
|
before resolving the consumer module. It builds the ReleaseKit version already
|
||||||
|
selected by that tagged `go.mod`, using temporary alternate module files outside
|
||||||
|
the source checkout. This tool bootstrap is separate from `ci-deliver`'s
|
||||||
|
application dependency preparation for binary profiles. ReleaseKit's own
|
||||||
|
source workflow self-bootstraps `./cmd/releasekit`; consumers without a declared
|
||||||
|
ReleaseKit module dependency can use the separately installed-tool command.
|
||||||
|
See the [delivery guide](consumers/delivery.md#woodpecker-tag-workflows) for
|
||||||
|
compatible Go environments, retries, and preparation details.
|
||||||
228
docs/config.md
Normal file
228
docs/config.md
Normal file
@@ -0,0 +1,228 @@
|
|||||||
|
# Configuration
|
||||||
|
|
||||||
|
ReleaseKit reads a JSON profile from `<repository-root>/releasekit.json` by default.
|
||||||
|
The repository argument defaults to the current directory; the CLI resolves its
|
||||||
|
containing Git checkout root. A relative profile path is resolved from that root;
|
||||||
|
an absolute path is used as-is.
|
||||||
|
|
||||||
|
The current profile fields are:
|
||||||
|
|
||||||
|
| Field | Required | Behavior |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `product` | Yes | Product name used by release operations. |
|
||||||
|
| `module_dir` | No | Repository-relative physical Go module directory with its own `go.mod`; omission selects `.` (the repository root). |
|
||||||
|
| `remote` | No | Selected Git remote; defaults to `origin`. |
|
||||||
|
| `expected_push_url` | No | Exact effective push URL required by `publish`; ignored by local `check`. |
|
||||||
|
| `checks` | No | Ordered additional child commands, each with an argument vector and optional environment map. |
|
||||||
|
| `validation` | No | Optional shared checks selected by ReleaseKit. |
|
||||||
|
| `build` | No | Optional main package, binary name, and selected `GOOS/GOARCH` target strings. |
|
||||||
|
| `delivery` | No | Optional Gitea `base_url`, `owner`, `repository`, and `token_env` settings for tagged-source delivery. |
|
||||||
|
|
||||||
|
`module_dir` names the selected module's physical location in the repository;
|
||||||
|
ReleaseKit reads its declared import path from that module's own `go.mod`. The
|
||||||
|
physical directory and declared path are distinct: a declared `/v2` module can
|
||||||
|
live either at `integrations/core` or `integrations/core/v2`, while both use the
|
||||||
|
same full release tag. Root-only profiles can omit `module_dir` and do not need
|
||||||
|
a module map.
|
||||||
|
|
||||||
|
Each check requires a nonempty `args` array whose first element names the
|
||||||
|
executable. Arguments are passed directly to the child process; ReleaseKit does
|
||||||
|
not parse a shell command string. Select a shell explicitly when a check needs
|
||||||
|
shell syntax. Each `env` map overlays the current environment for that child.
|
||||||
|
The overlay does not modify the ReleaseKit process environment.
|
||||||
|
|
||||||
|
Unknown fields are rejected so a setting cannot be silently ignored. The
|
||||||
|
`build` object contains `main_package`, `binary_name`, and `targets`. A selected
|
||||||
|
target requires the package and binary name; each target is written as one
|
||||||
|
`GOOS/GOARCH` pair. An omitted or empty target list means no binary work.
|
||||||
|
|
||||||
|
The optional `validation` object selects shared checks implemented by ReleaseKit.
|
||||||
|
`validation.shared_files` is a committed file list resolved from the repository
|
||||||
|
root. Omission or `null` uses `COPYRIGHT`, `LICENSE`, and
|
||||||
|
`docs/oss/attribution.md` when present for enabled file checks; `[]` selects no
|
||||||
|
shared files. An explicit list replaces those defaults. Each explicit file must
|
||||||
|
exist in the candidate, even when no file checks are enabled. Paths are literal,
|
||||||
|
repository-relative files with no glob semantics and may select a file outside
|
||||||
|
the chosen module. ReleaseKit deduplicates them with module inputs by path. This
|
||||||
|
field does not enable any checks or expand Go test, vet, or package-compilation
|
||||||
|
scope. Automatic file inputs stop at independent nested-module boundaries;
|
||||||
|
vendored files remain included. Reference inspection can read destinations
|
||||||
|
elsewhere in the captured repository without adding them to those inputs.
|
||||||
|
`validation.go.race` enables the race detector for the single standard Go test
|
||||||
|
suite. `validation.go.full_vet` runs a separate native `go vet` pass after that
|
||||||
|
suite succeeds; ReleaseKit disables test-time vet for that suite to avoid
|
||||||
|
running vet twice. `validation.go.compile_targets` is an ordered array of
|
||||||
|
`GOOS/GOARCH` pairs. After tests and selected full vet pass, ReleaseKit compiles
|
||||||
|
all packages for each target with cgo disabled. Each pair must include both
|
||||||
|
components; the selected Go toolchain reports unsupported complete targets.
|
||||||
|
This source compatibility check does not name or produce binaries, run a target
|
||||||
|
executable, or create an artifact manifest. Omitted or empty `compile_targets`
|
||||||
|
selects no package-compilation pass. When `full_vet` is omitted or false, the
|
||||||
|
test command keeps its existing vet behavior. These settings are independent.
|
||||||
|
`validation.go_format` checks regular committed Go blobs with the Go formatter
|
||||||
|
used to build ReleaseKit. It uses the selected file inputs, including vendor and
|
||||||
|
explicit shared files, and ignores
|
||||||
|
symlink blobs and the worktree, and reports every selected path whose bytes
|
||||||
|
change under formatting. It never writes formatted bytes back. Omitted or false
|
||||||
|
disables the check. It runs after tests, selected full vet, and selected package
|
||||||
|
compilation, before configured product checks.
|
||||||
|
|
||||||
|
When `validation.markdown` is an object, ReleaseKit checks local destinations
|
||||||
|
and supported heading fragments in committed regular Markdown files. Omission
|
||||||
|
or `null` disables the check; `{}` enables it. Schemed and protocol-relative
|
||||||
|
links are skipped, URI query components do not affect path checks, and other
|
||||||
|
existing files or directories receive existence checks only. Missing local
|
||||||
|
destinations, symlink cycles, and missing Markdown headings fail with the
|
||||||
|
`markdown-links` identity. Outside-checkout destinations are reported as out
|
||||||
|
of scope by default. Set
|
||||||
|
`validation.markdown.enforce_checkout_boundary` to `true` to fail those links;
|
||||||
|
submodule contents remain out of scope under either setting.
|
||||||
|
|
||||||
|
The parser recognizes inline links, images, reference links, and CommonMark
|
||||||
|
autolinks; link-like text in code is ignored, and raw HTML destinations are
|
||||||
|
outside this check. For linked images, the image source and enclosing link
|
||||||
|
target are checked. Image labels supply alternative text.
|
||||||
|
Relative paths resolve from the source document in the
|
||||||
|
captured commit. Query components are ignored for file existence, and percent
|
||||||
|
escapes in local paths and fragments are decoded once. Fragments are compared
|
||||||
|
in lowercase with anchors derived from visible ATX or Setext heading text.
|
||||||
|
Anchors keep Unicode letters and numbers, underscores, and hyphens; spaces
|
||||||
|
become hyphens, and repeated headings receive numeric suffixes.
|
||||||
|
|
||||||
|
When `validation.module_distribution.workspace_files` is true, it reports
|
||||||
|
committed `go.work` and `go.work.sum` files in the selected module inputs,
|
||||||
|
including nested paths and symlinks. It checks the captured candidate regardless
|
||||||
|
of `GOWORK`; it does not select or change the workspace used by Go commands,
|
||||||
|
and vendored contents remain in scope. Omitted or false disables it. When
|
||||||
|
`validation.module_distribution.local_replacements` is true, it parses the
|
||||||
|
selected module's committed `go.mod` declarations. Vendored contents remain in
|
||||||
|
scope; an explicit shared-file selection can include an individual declaration
|
||||||
|
from another module. It reports
|
||||||
|
`replace` directives whose replacement has no version. These filesystem
|
||||||
|
replacements include relative and absolute paths; versioned module replacements
|
||||||
|
are permitted. Committed `go.mod` symlinks are resolved within the candidate,
|
||||||
|
and unavailable selected contents or parse failures are reported as inspection
|
||||||
|
errors. This selection is independent of `workspace_files` and Go's `GOWORK`
|
||||||
|
setting. Omitted or false disables it.
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"product": "Example",
|
||||||
|
"validation": {
|
||||||
|
"go": {
|
||||||
|
"race": true,
|
||||||
|
"full_vet": true,
|
||||||
|
"compile_targets": ["linux/amd64", "linux/arm64"]
|
||||||
|
},
|
||||||
|
"go_format": true,
|
||||||
|
"markdown": {},
|
||||||
|
"module_distribution": {
|
||||||
|
"workspace_files": true,
|
||||||
|
"local_replacements": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When `validation.file_size` is an object, ReleaseKit compares each committed
|
||||||
|
blob's size with `limit_bytes`. The limit uses decimal bytes and rejects only
|
||||||
|
sizes strictly greater than the limit. An omitted or null object disables the
|
||||||
|
check; `{}` enables it with a default of 1,000,000 bytes. A missing or null
|
||||||
|
`limit_bytes` selects that default, zero is a valid limit, and negative limits
|
||||||
|
are invalid.
|
||||||
|
|
||||||
|
`validation.file_size.exclusions` contains literal paths relative to the
|
||||||
|
selected module. Directory exclusions include committed descendants, using path
|
||||||
|
boundaries (`assets` does not exclude `assets-old`). Ordinary relative path
|
||||||
|
normalization applies; metacharacters are literal and unmatched paths have no
|
||||||
|
effect. The check measures regular and symlink blobs, including small binaries;
|
||||||
|
symlink size is the committed link text. Gitlinks have no measured size. Only
|
||||||
|
the captured candidate is checked, one offending file is reported at a time,
|
||||||
|
and historical or aggregate repository size is not measured.
|
||||||
|
|
||||||
|
The `delivery` object contains `base_url`, `owner`, `repository`, and optional
|
||||||
|
`token_env`. Its values are required when running `deliver`, but credentials are
|
||||||
|
not required for `check`, `publish`, or `build`. `token_env` names the
|
||||||
|
environment variable containing the Gitea token; it defaults to
|
||||||
|
`RELEASEKIT_GITEA_TOKEN`. The CLI reads this variable only for `deliver` and
|
||||||
|
passes its value explicitly to the library operation.
|
||||||
|
|
||||||
|
`expected_push_url`, when nonempty, is compared exactly with Git's resolved
|
||||||
|
effective push URL during `publish`, before candidate validation. It applies
|
||||||
|
to the push destination when fetch and push URLs differ, and Git URL rewrites
|
||||||
|
such as `insteadOf` are resolved before comparison. A mismatch fails preflight;
|
||||||
|
omitting the field keeps the selected remote's existing behavior. `check` is
|
||||||
|
local-only and ignores this publication expectation.
|
||||||
|
|
||||||
|
The `check` and `publish` commands run one
|
||||||
|
`go test -mod=readonly -count=1 ./...` suite with Go module and toolchain network
|
||||||
|
access disabled, adding `-race` when `validation.go.race` is true. When
|
||||||
|
`validation.go.full_vet` is true, they add `-vet=off` to that test command and
|
||||||
|
run native `go vet -mod=readonly ./...` after successful tests. They then run
|
||||||
|
`go build -mod=readonly -o <os.DevNull> ./...` in static mode for each
|
||||||
|
`validation.go.compile_targets` entry, in profile order. Compile failures use
|
||||||
|
the `package-compile` identity and include the selected target. When selected,
|
||||||
|
`validation.go_format` checks regular committed Go source with go/format after
|
||||||
|
package compilation; unformatted paths use the `go-format` identity. When
|
||||||
|
`validation.module_distribution.workspace_files` is true, shared validation
|
||||||
|
also reports committed go.work and go.work.sum blobs after Go formatting, using
|
||||||
|
the workspace-files identity. Uncommitted workspace files are not inspected.
|
||||||
|
When `validation.module_distribution.local_replacements` is true, shared
|
||||||
|
validation parses committed `go.mod` files after workspace inspection and reports
|
||||||
|
filesystem replacements as `local-replacements`, with path, directive line, and
|
||||||
|
target. Versioned replacements are permitted; parse and inspection failures
|
||||||
|
preserve their causes.
|
||||||
|
When `validation.file_size` is selected, shared validation checks committed
|
||||||
|
blob sizes after module-distribution checks and reports the first oversized
|
||||||
|
path with the `file-size` identity and measured and limit byte counts.
|
||||||
|
When `validation.markdown` is selected, Markdown checking follows file-size
|
||||||
|
inspection and runs before configured product checks. Out-of-scope observations
|
||||||
|
are written to the command's standard error and do not fail validation unless
|
||||||
|
the checkout boundary is enforced. Submodule observations remain nonfailures.
|
||||||
|
Configured `checks` commands run afterward, once each in order, as additional
|
||||||
|
product checks. Artifact builds selected by the separate `build` setting run
|
||||||
|
after shared validation and product checks.
|
||||||
|
|
||||||
|
Do not repeat the standard suite or vet in `checks`; doing so repeats work. The
|
||||||
|
`build` command uses the selected build settings and writes binaries to `dist` unless
|
||||||
|
`--output` selects another path.
|
||||||
|
The `deliver` command uses the delivery destination and token. By default it
|
||||||
|
passes selected targets to the delivery facade, which builds tagged-source
|
||||||
|
artifacts into temporary storage and removes them when delivery returns. An
|
||||||
|
absent build object or an empty target set selects page-only delivery. Use
|
||||||
|
`build --output DIR` followed by `deliver --assets DIR` when artifacts must be
|
||||||
|
retained for retries or when build and delivery credentials need separate
|
||||||
|
invocations. Ordinary `deliver` does not download application dependencies or
|
||||||
|
change the checkout.
|
||||||
|
|
||||||
|
`ci-deliver` takes a full Git `TAG`; its final path component is the stable
|
||||||
|
semantic version and the complete value is checked against the profile's
|
||||||
|
derived tag. By default it fetches the selected tag, confirms its peeled commit
|
||||||
|
matches the provider-supplied commit ID, checks it out detached, and verifies
|
||||||
|
the tag, HEAD, and clean worktree. With `--prepared`, it performs the same
|
||||||
|
checks against an existing checkout without fetching or checking out. It then
|
||||||
|
loads the profile from that source and validates delivery settings and
|
||||||
|
credentials. An optional `--expected-module` checks a launcher's module
|
||||||
|
selection against the profile. It runs `go mod download` only when the profile
|
||||||
|
has selected build targets; source-only delivery does not need application
|
||||||
|
dependencies. Default preparation may access the network and may update
|
||||||
|
`go.sum`. For binary tagged delivery, prepare and commit that module's sums
|
||||||
|
before tagging so dependency preparation leaves the tagged checkout clean. The
|
||||||
|
command takes CI values as arguments, so profile settings remain independent of
|
||||||
|
Woodpecker environment variable names. See the
|
||||||
|
[CLI contract](cli.md) for the invocation and exit statuses.
|
||||||
|
|
||||||
|
This application dependency preparation is separate from bootstrapping the
|
||||||
|
ReleaseKit executable. The maintained module-based tag workflow verifies the
|
||||||
|
tag first, then uses temporary copies of that tag's module files to build the
|
||||||
|
ReleaseKit version selected by the consumer's `go.mod`. The
|
||||||
|
[delivery guide](consumers/delivery.md#woodpecker-tag-workflows) describes that
|
||||||
|
bootstrap, the self-bootstrapped source workflow, and the separately installed
|
||||||
|
tool option.
|
||||||
|
|
||||||
|
ReleaseKit's source-only profile is
|
||||||
|
[releasekit.json](../releasekit.json).
|
||||||
|
See the [source-only profile](../examples/releasekit.json) and
|
||||||
|
[binary profile](../examples/releasekit-binary.json). The
|
||||||
|
[CLI contract](cli.md) lists the currently available command.
|
||||||
66
docs/consumers/adoption.md
Normal file
66
docs/consumers/adoption.md
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
# Adopt ReleaseKit
|
||||||
|
|
||||||
|
Use a versioned Go tool dependency when ReleaseKit provides the repository's
|
||||||
|
release commands. This records the CLI in `go.mod` and keeps it available to
|
||||||
|
maintainers without adding imports to application or library code.
|
||||||
|
|
||||||
|
## CLI tool dependency
|
||||||
|
|
||||||
|
From the consumer module's root, select the ReleaseKit version to adopt:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
: "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}"
|
||||||
|
go get -tool "gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}"
|
||||||
|
go mod tidy
|
||||||
|
go tool releasekit version
|
||||||
|
```
|
||||||
|
|
||||||
|
Select a release that implements the API, profile, and workflow you are adopting.
|
||||||
|
The module-release interface requires a release containing that feature;
|
||||||
|
pre-feature versions through v0.3.0 use their corresponding historical interface.
|
||||||
|
Go records the executable package in
|
||||||
|
a `tool` directive and the module version in a `require` directive. The tool
|
||||||
|
declaration retains the dependency through `go mod tidy`. Commit the resulting
|
||||||
|
`go.mod` and `go.sum` changes. To upgrade, repeat the command with the chosen
|
||||||
|
version and review the module changes.
|
||||||
|
|
||||||
|
The Go tool dependency feature requires Go 1.24 or later. The current ReleaseKit
|
||||||
|
module declares a Go 1.26.0 minimum, so use Go 1.26.0 or later for the current
|
||||||
|
release. Tool dependencies share the consumer's module graph: their requirements
|
||||||
|
participate in dependency version selection and can raise the consumer module's
|
||||||
|
Go minimum. See the
|
||||||
|
[Go tool dependency reference](https://go.dev/ref/mod#go-mod-file-tool).
|
||||||
|
|
||||||
|
Run `go tool releasekit` from within the consumer module to use its selected
|
||||||
|
version. Follow the [CLI contract](../cli.md) for commands and exit statuses,
|
||||||
|
and the [configuration reference](../config.md) for the release profile.
|
||||||
|
|
||||||
|
## Go API consumers
|
||||||
|
|
||||||
|
Consumers importing the root `releasekit` API or
|
||||||
|
[`buildinfo`](runtime-version.md) use ordinary package dependencies. Add the
|
||||||
|
required imports and select the module version:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
: "${RELEASEKIT_TOOL_VERSION:?Set the released ReleaseKit version to adopt}"
|
||||||
|
go get "gitea.maximumdirect.net/eric/ReleaseKit@${RELEASEKIT_TOOL_VERSION}"
|
||||||
|
go mod tidy
|
||||||
|
```
|
||||||
|
|
||||||
|
API consumers can also register the CLI with `go get -tool` as above. Both uses
|
||||||
|
share the module-selected ReleaseKit version.
|
||||||
|
|
||||||
|
## CI adoption
|
||||||
|
|
||||||
|
The maintained [consumer tag-delivery workflow](delivery.md#woodpecker-tag-workflows)
|
||||||
|
supports both tool and ordinary package dependencies. It builds ReleaseKit from
|
||||||
|
the tagged consumer's module selection, so the committed module files also
|
||||||
|
govern CI delivery and retries. Registering the CLI as a tool is sufficient for
|
||||||
|
consumers that use ReleaseKit only for maintainer commands.
|
||||||
|
|
||||||
|
Upgrade the module-selected tool and workflow together. For a tag created before
|
||||||
|
that upgrade, retry with the workflow matching the tool recorded at that tag.
|
||||||
|
Keep its immutable module files and tag intact. See the
|
||||||
|
[delivery guide](delivery.md#woodpecker-tag-workflows) for tagged-source bootstrap
|
||||||
|
and the [example's source verification](../../examples/multi-module/README.md#local-source-verification)
|
||||||
|
for testing an unreleased checkout in a disposable consumer repository.
|
||||||
90
docs/consumers/build.md
Normal file
90
docs/consumers/build.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# Build versioned application binaries
|
||||||
|
|
||||||
|
Use `releasekit.Build` when an application needs binaries for explicit Go
|
||||||
|
operating-system and architecture pairs:
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
releasekit "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func build(ctx context.Context) error {
|
||||||
|
result, err := releasekit.Build(ctx, releasekit.BuildRequest{
|
||||||
|
RepositoryDir: "/work/project",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Spec: releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/project",
|
||||||
|
BinaryName: "project",
|
||||||
|
Targets: []releasekit.Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "linux", Arch: "arm64"},
|
||||||
|
{OS: "darwin", Arch: "arm64"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
OutputDir: "dist",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err // result retains completed artifacts when a later step fails.
|
||||||
|
}
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
fmt.Println(artifact.Filename, artifact.SHA256)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`Build` resolves `ModuleDir` and the selected module's working-tree declaration
|
||||||
|
once, records the repository's current `HEAD`, injects the selected stable
|
||||||
|
version into `buildinfo.Version`, and returns repository/module identity, the
|
||||||
|
derived tag, compiler identity, normalized targets, artifact paths, filenames,
|
||||||
|
and SHA-256 digests. It does not require a release note, unused tag, clean
|
||||||
|
`main`, or publication. Names follow
|
||||||
|
`<binary>-<version>-<goos>-<goarch>`; Windows targets add `.exe`. A repeated
|
||||||
|
target pair is built once, at its first position. Local builds may use modified
|
||||||
|
source. `SourceVerified` is true only after a complete build observes clean
|
||||||
|
source and the same HEAD before and after compilation; binary delivery requires
|
||||||
|
that fact. This observation is not a source snapshot or attestation guarantee.
|
||||||
|
|
||||||
|
Go commands run from `ModuleDir`, so `MainPackage` is interpreted within that
|
||||||
|
module. The default output directory is `<module>/dist`; a relative `OutputDir`
|
||||||
|
is resolved from the module, while an absolute path is used as supplied.
|
||||||
|
Selected artifact filenames are regenerated. Other files in the output
|
||||||
|
directory are left in place. A failed later build or native version check
|
||||||
|
returns the binaries already generated in `BuildResult.Artifacts`.
|
||||||
|
|
||||||
|
Builds use the available compatible Go toolchain selected locally; ReleaseKit
|
||||||
|
does not download a different toolchain automatically. It disables workspace
|
||||||
|
discovery and module network access, uses readonly module mode, sets
|
||||||
|
`CGO_ENABLED=0`, and passes `-trimpath` and `-buildvcs=false`. Effective cache,
|
||||||
|
module-cache, temporary-directory, and tool settings are retained, including
|
||||||
|
values from Go's persistent environment file. Ambient experiment and CPU
|
||||||
|
feature settings are cleared so the selected toolchain uses its baseline for
|
||||||
|
each target. Each selected target is compiled explicitly. ReleaseKit then runs
|
||||||
|
the `version` command on a native binary and requires `<binary> <version>`
|
||||||
|
followed by a newline. If no selected target matches the Go host, it builds a
|
||||||
|
temporary native binary for this check and removes it afterward.
|
||||||
|
Cross-compilation does not promise that a binary runs on another platform.
|
||||||
|
|
||||||
|
An empty target list records the source commit and returns without invoking Go,
|
||||||
|
creating the output directory, or running a version check. It does not require a
|
||||||
|
main package or binary name. This supports source-only operations without
|
||||||
|
silently adding a binary check.
|
||||||
|
|
||||||
|
The [`build` command](../cli.md) reads the same build specification from the
|
||||||
|
profile and writes a private receipt alongside its artifacts. `check` and
|
||||||
|
`publish` run selected builds after the standard suite and any additional
|
||||||
|
checks using temporary output outside the worktree. Candidate checks do not
|
||||||
|
write a receipt or leave build files in the repository. Disposable native
|
||||||
|
version-check output also remains outside the whole repository when `TMPDIR`
|
||||||
|
points inside the source tree.
|
||||||
|
|
||||||
|
For delivery from a tagged checkout, `deliver` builds selected tagged-source
|
||||||
|
targets into temporary storage by default. Use `--assets DIR` to deliver a
|
||||||
|
separate build output; ReleaseKit requires the current module-bound receipt and
|
||||||
|
checks its source identity and normalized build settings. It verifies artifact
|
||||||
|
bytes and sizes during delivery before the first Gitea write. Older receipts
|
||||||
|
must be regenerated with the updated `build` command. See the
|
||||||
|
[delivery consumer guide](delivery.md) for page-only delivery and retry states.
|
||||||
149
docs/consumers/check.md
Normal file
149
docs/consumers/check.md
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
# Local candidate check
|
||||||
|
|
||||||
|
Use `releasekit.Check` to verify a candidate against the current local
|
||||||
|
repository state:
|
||||||
|
|
||||||
|
```go
|
||||||
|
result, err := releasekit.Check(ctx, releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: "/work/project",
|
||||||
|
Product: "Example",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Validation: releasekit.ValidationSpec{
|
||||||
|
Go: releasekit.GoValidationSpec{Race: true, FullVet: true},
|
||||||
|
},
|
||||||
|
AdditionalChecks: func(ctx context.Context, candidate releasekit.Candidate) error {
|
||||||
|
return runProjectChecks(ctx, candidate.RepositoryDir)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Println(result.Version, result.Commit)
|
||||||
|
```
|
||||||
|
|
||||||
|
Set `ReleaseRequest.ModuleDir` to select a nested module using a
|
||||||
|
repository-relative physical directory; omission or `.` selects the root
|
||||||
|
module. ReleaseKit reads that module's committed `go.mod` and returns its
|
||||||
|
physical `ModuleDir`, declared `ModulePath`, semantic `Version`, and complete
|
||||||
|
`Tag` in the candidate and result. A physical `/v2` directory is removed from
|
||||||
|
the tag prefix only when the declared module path also ends in `/v2`. For
|
||||||
|
example, both `integrations/core/v2` and `integrations/core` can declare
|
||||||
|
`example.com/project/integrations/core/v2` and use the tag
|
||||||
|
`integrations/core/v2.1.0`. The release note lives under the physical module at
|
||||||
|
`<module>/docs/releases/<version>.md`.
|
||||||
|
|
||||||
|
The repository must have a clean index and worktree on `main`, and the selected
|
||||||
|
version must be stable `vMAJOR.MINOR.PATCH`. The module-local committed
|
||||||
|
`<module>/docs/releases/<version>.md` note must have a first Markdown H1 containing the
|
||||||
|
product name and exact version as complete title elements. No local tag with
|
||||||
|
the derived complete tag may already exist. Different modules may use the same
|
||||||
|
semantic version with distinct notes and tags.
|
||||||
|
|
||||||
|
ReleaseKit runs one `go test -mod=readonly -count=1 ./...` suite from the
|
||||||
|
selected module directory with the available compatible local Go toolchain.
|
||||||
|
Set `Validation.Go.Race` to run that
|
||||||
|
suite with `-race`; set `Validation.Go.FullVet` to run
|
||||||
|
`go vet -mod=readonly ./...` after successful tests, with test-time vet disabled
|
||||||
|
for the suite. Set `Validation.Go.CompileTargets` to compile packages for each
|
||||||
|
complete target pair after tests and vet. Package compilation uses
|
||||||
|
`CGO_ENABLED=0`, writes no artifact, and does not execute a target binary; its
|
||||||
|
failures use the `package-compile` identity and include the target. The zero
|
||||||
|
values retain the ordinary native test behavior and select no compilation.
|
||||||
|
Set `Validation.GoFormat` to check committed regular Go files using the Go
|
||||||
|
formatter built into ReleaseKit. It uses the selected file inputs, including
|
||||||
|
vendor and explicit shared files, and
|
||||||
|
ignores symlink blobs and worktree changes, and reports unformatted paths as
|
||||||
|
`go-format` without rewriting files. Its zero value disables the check; it runs
|
||||||
|
after tests, selected vet, and package compilation, before `AdditionalChecks`.
|
||||||
|
|
||||||
|
Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed
|
||||||
|
`go.work` and `go.work.sum` files in the selected module inputs, including
|
||||||
|
symlink entries. It examines the captured candidate even when
|
||||||
|
`GOWORK=off`, ignores uncommitted files, and does not change Go test workspace
|
||||||
|
selection; vendored contents remain in scope. The zero value disables the check;
|
||||||
|
failures use `workspace-files`.
|
||||||
|
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
|
||||||
|
the selected module's committed `go.mod` declarations. Vendored contents remain
|
||||||
|
in scope; automatic inputs stop at independently released nested modules. An
|
||||||
|
explicit shared-file selection can include another module's declaration. It reports
|
||||||
|
filesystem `replace` directives with their source path, line, and target as
|
||||||
|
`local-replacements`; versioned replacements are
|
||||||
|
permitted. Committed module symlinks are resolved within the candidate. Parse
|
||||||
|
and inspection errors retain their causes, and the rule applies even when
|
||||||
|
`GOWORK=off`. Its zero value disables the check.
|
||||||
|
Set `Validation.FileSize` to check each committed blob against a byte limit.
|
||||||
|
Nil disables the check; an empty object enables the default of 1,000,000
|
||||||
|
decimal bytes. `LimitBytes` is strict greater-than, accepts zero, and rejects
|
||||||
|
negative values. `Exclusions` contains literal files or directories relative to
|
||||||
|
the selected module; excluded directories include descendants. Symlink blobs are
|
||||||
|
measured by link-text bytes, and gitlinks are omitted. The check applies to the
|
||||||
|
captured candidate and reports one oversized file with its measurement as
|
||||||
|
`file-size`; it does not measure historical or aggregate size.
|
||||||
|
Set `Validation.Markdown` to check committed local Markdown destinations and
|
||||||
|
supported heading fragments. Nil disables the check; an empty object enables
|
||||||
|
it with outside-checkout destinations reported as out of scope. Set
|
||||||
|
`EnforceCheckoutBoundary` to fail outside-checkout links. Submodule contents
|
||||||
|
remain out of scope under either setting. The checker runs after file-size
|
||||||
|
inspection and before `AdditionalChecks`; its nonfailure observations use the
|
||||||
|
request's output writer. Markdown failures use the `markdown-links` identity
|
||||||
|
and include the source location and destination.
|
||||||
|
|
||||||
|
Use these selections for ReleaseKit-owned validation rather than repeating the
|
||||||
|
standard suite, selected vet/format/distribution checks, or Markdown navigation
|
||||||
|
checks in `AdditionalChecks` or profile `checks`. Keep release-note rules and
|
||||||
|
consumer-specific assertions—such as tests of maintained examples—in those
|
||||||
|
product-owned checks.
|
||||||
|
The `Candidate` supplies both `RepositoryDir` and `ModuleDir`, plus the declared
|
||||||
|
`ModulePath`, semantic `Version`, and full `Tag`; use its module directory for
|
||||||
|
module-local product checks. ReleaseKit calls `AdditionalChecks` once after
|
||||||
|
shared validation when supplied.
|
||||||
|
|
||||||
|
`ValidationSpec.SharedFiles` adds committed, repository-relative files to
|
||||||
|
ReleaseKit's optional file checks without enabling any checks. A nil slice
|
||||||
|
selects the optional defaults `COPYRIGHT`, `LICENSE`, and
|
||||||
|
`docs/oss/attribution.md`, when present; a non-nil empty slice selects none.
|
||||||
|
Explicit files replace those defaults, must exist even when file checks are
|
||||||
|
disabled, and may be in another module. Combined inputs are deduplicated by
|
||||||
|
repository-relative path.
|
||||||
|
|
||||||
|
Automatic file inputs stop at independent nested-module boundaries, including
|
||||||
|
fixture modules. Vendored files remain included. Shared selection affects file
|
||||||
|
inputs only; Go validation retains the selected module's scope. Reference reads
|
||||||
|
can inspect destinations elsewhere in the captured repository without adding
|
||||||
|
those destinations to the input set.
|
||||||
|
|
||||||
|
It does not download a different toolchain automatically. If race prerequisites
|
||||||
|
are unavailable, the `go-test` check fails rather than being skipped; a selected
|
||||||
|
full-vet failure is reported as `go-vet`. The suite uses the Go host target,
|
||||||
|
disables workspace and module network access, and ignores ambient `GOFLAGS`,
|
||||||
|
experiment, and CPU feature overrides. Effective cache and native cgo/C-tool
|
||||||
|
settings are preserved, including values from Go's persistent environment
|
||||||
|
file. The check revalidates the branch, commit, and cleanliness after
|
||||||
|
validation.
|
||||||
|
|
||||||
|
For checksum failures during dependency preparation, use the
|
||||||
|
[module checksum investigation guide](delivery.md#investigating-module-checksum-mismatches).
|
||||||
|
|
||||||
|
A successful check is evidence about the local candidate only. It does not
|
||||||
|
check whether a remote branch or tag is available and does not create a tag.
|
||||||
|
The [`check` command](../cli.md) reads the product and optional additional
|
||||||
|
commands from `releasekit.json`.
|
||||||
|
|
||||||
|
## Publishing the source tag
|
||||||
|
|
||||||
|
`releasekit.Publish` uses the same request and validation order: the standard
|
||||||
|
suite runs first, followed by `AdditionalChecks` when supplied. It surrounds
|
||||||
|
validation with authoritative remote guards before annotated-tag creation and
|
||||||
|
an exact tag push. The
|
||||||
|
selected remote must publish `main` at the captured commit and must not already
|
||||||
|
contain the selected complete tag. A successful result includes the endpoint and
|
||||||
|
tag object ID. Publication states distinguish an unattempted push, a tag that
|
||||||
|
was created locally but not pushed, a successful push, a guard conflict, and an
|
||||||
|
unresolved push error. See the [publication guide](publish.md) for the complete
|
||||||
|
workflow.
|
||||||
|
|
||||||
|
When a push reports an error, ReleaseKit makes one bounded query for the
|
||||||
|
authoritative tag. An exact tag object match confirms success. An absent tag is
|
||||||
|
reported as `not_published`, a different object as `conflict`, and an unreadable
|
||||||
|
query as `unknown`. The local annotated tag is retained in every case; an
|
||||||
|
`unknown` result is neither success nor proof that the remote lacks the tag.
|
||||||
311
docs/consumers/delivery.md
Normal file
311
docs/consumers/delivery.md
Normal file
@@ -0,0 +1,311 @@
|
|||||||
|
# Deliver a tagged source release
|
||||||
|
|
||||||
|
Use `releasekit.Deliver` or the `deliver` command after a source tag exists.
|
||||||
|
Delivery status is separate from source publication: a delivery problem does
|
||||||
|
not move or remove the tag, and a retry can use the same immutable version.
|
||||||
|
The operation accepts historical lightweight and annotated tags, including a
|
||||||
|
detached checkout, when the checked-out `HEAD` identifies the selected tag
|
||||||
|
commit. It does not require the old remote `main` to match.
|
||||||
|
|
||||||
|
Delivery resolves the selected module's declaration and release note from the
|
||||||
|
captured commit. `Version` remains the semantic version; the full tag includes
|
||||||
|
the selected module's repository-relative physical path when it is nested. The
|
||||||
|
profile or API request selects the physical module directory. The optional API
|
||||||
|
`ExpectedTag` checks that a CI event's literal tag agrees with the derived tag
|
||||||
|
before any build or hosted request.
|
||||||
|
|
||||||
|
## CI preparation
|
||||||
|
|
||||||
|
Use `PrepareTaggedCheckout` when a disposable CI checkout must be verified
|
||||||
|
against the commit that triggered the job. It fetches only the selected tag
|
||||||
|
from the chosen remote (default `origin`), compares the peeled tag commit with
|
||||||
|
the expected commit, and checks out that commit detached. Fetch or checkout
|
||||||
|
conflicts are returned so the caller can replace or repair the workspace.
|
||||||
|
Cancellation is returned to the caller; the operation does not publish a tag
|
||||||
|
or hosted content.
|
||||||
|
|
||||||
|
```go
|
||||||
|
err := releasekit.PrepareTaggedCheckout(ctx, releasekit.TaggedCheckoutRequest{
|
||||||
|
RepositoryDir: repositoryDir,
|
||||||
|
Tag: "integrations/example/v1.2.3",
|
||||||
|
ExpectedCommit: ciCommit,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For binary profiles, call `PrepareBuildDependencies` with a
|
||||||
|
`DependencyPreparationRequest` selecting the repository and module after
|
||||||
|
checkout preparation and before delivery. It runs `go mod download` in that
|
||||||
|
module with workspace discovery disabled and the available compatible local Go
|
||||||
|
toolchain.
|
||||||
|
The operation may use the network and updates the Go module cache while
|
||||||
|
preserving the caller's proxy, private-module, credential, and cache settings.
|
||||||
|
If checksums are missing, Go may update `go.sum`. For binary CI delivery, prepare
|
||||||
|
and commit the selected module's `go.sum` before tagging: delivery verifies the
|
||||||
|
tagged source remains clean after dependency preparation. See the
|
||||||
|
[Go Modules Reference](https://go.dev/ref/mod#go-mod-download). Cancellation
|
||||||
|
and command errors are returned. Page-only profiles do not need dependency
|
||||||
|
preparation.
|
||||||
|
|
||||||
|
Set `TaggedCheckoutRequest.VerifyOnly` when a bootstrap step already fetched and
|
||||||
|
detached the event tag. This mode checks the exact tag, expected commit, `HEAD`,
|
||||||
|
and clean worktree without fetching or changing the checkout. Both modes require
|
||||||
|
the full `Tag` and expected commit.
|
||||||
|
|
||||||
|
## Command line
|
||||||
|
|
||||||
|
Add a Gitea destination to the profile:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"product": "Example",
|
||||||
|
"delivery": {
|
||||||
|
"base_url": "https://gitea.example",
|
||||||
|
"owner": "example",
|
||||||
|
"repository": "example",
|
||||||
|
"token_env": "RELEASEKIT_GITEA_TOKEN"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Fetch and check out the immutable tag, then deliver it:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git checkout --detach v1.2.3
|
||||||
|
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver v1.2.3
|
||||||
|
```
|
||||||
|
|
||||||
|
The CLI reads the named token variable only for `deliver`; its default name is
|
||||||
|
`RELEASEKIT_GITEA_TOKEN`. It verifies the local checkout and hosted tag before
|
||||||
|
creating or accepting a hosted release page. The full checked-in note is the
|
||||||
|
hosted body. A retry accepts an identical page and matching attachments, adds
|
||||||
|
only missing assets, and reports conflicts without replacing content.
|
||||||
|
For nested modules, the note comes from that module's committed
|
||||||
|
`docs/releases/<version>.md`, and the hosted page is keyed by its complete tag.
|
||||||
|
|
||||||
|
With no build targets, delivery is page-only: no builder, version smoke check,
|
||||||
|
receipt, binary asset, or checksum manifest is involved. Committed module
|
||||||
|
directories and declaration links can be resolved from a sparse checkout;
|
||||||
|
page-only delivery needs the committed objects and note. Managed builds require
|
||||||
|
the selected source files to be materialized. With selected targets,
|
||||||
|
one `deliver` invocation builds the tagged source through the facade into
|
||||||
|
temporary storage and delivers the result. To retain artifacts for a retry or
|
||||||
|
separate credentials between build and delivery, use two invocations:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
releasekit build --output dist v1.2.3
|
||||||
|
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver --assets dist v1.2.3
|
||||||
|
```
|
||||||
|
|
||||||
|
The build command does not need delivery credentials. The `--assets DIR`
|
||||||
|
directory must contain the private `.releasekit-build.json` receipt created by
|
||||||
|
`build`. ReleaseKit checks its schema, repository, commit, version, resolved
|
||||||
|
module directory and path, full tag, normalized build settings, and artifact
|
||||||
|
declarations. Old receipts must be regenerated with the updated `build`
|
||||||
|
command. Delivery verifies the artifact bytes and sizes before making a hosted
|
||||||
|
request; caller-owned files remain available for retries.
|
||||||
|
Ordinary `deliver` does not download application dependencies or change the
|
||||||
|
checkout.
|
||||||
|
|
||||||
|
The result reports `complete`, `partial`, `conflict`, `unknown`, or
|
||||||
|
`not_attempted`, along with matching, uploaded, pending, conflicting, and
|
||||||
|
uncertain assets when known. These are disjoint current observations: an asset
|
||||||
|
appears in at most one category, and early failures may leave some declared
|
||||||
|
assets unreported. `Matching` means existing content matches; `Uploaded` means
|
||||||
|
an upload was confirmed during this invocation; `Pending` means known missing
|
||||||
|
work; `Conflicting` means different hosted content was found; `Uncertain` means
|
||||||
|
the remote state could not be resolved.
|
||||||
|
|
||||||
|
Fix local or preflight failures before retrying. For partial delivery, fix the
|
||||||
|
reported cause and retry the same version. Resolve an unknown remote outcome
|
||||||
|
before retrying. Investigate conflicts and use a new version if the source or
|
||||||
|
published content needs correction. If rebuilding could change bytes already
|
||||||
|
on the server, retain the original build output and retry with `--assets DIR`.
|
||||||
|
The command does not run candidate checks or publish tags.
|
||||||
|
|
||||||
|
## Go API
|
||||||
|
|
||||||
|
Pass the Gitea credential explicitly. Set `Build` to a `BuildSpec` to compile
|
||||||
|
selected targets as part of delivery. The facade verifies the local tag, clean
|
||||||
|
checkout, and committed release note before compiling. Managed output is stored
|
||||||
|
outside the checkout and removed when delivery returns. `Output` receives build
|
||||||
|
progress. With no build, or with an empty target set, delivery is page-only.
|
||||||
|
|
||||||
|
To deliver binaries built separately, set `Prebuilt` to the `BuildResult`.
|
||||||
|
ReleaseKit checks its repository, module directory, declared module path, full
|
||||||
|
tag, semantic version, tagged commit, normalized settings, and artifact evidence
|
||||||
|
against the selected committed module. Binary results must record verified
|
||||||
|
source. The current files are checked against their recorded digests before any
|
||||||
|
hosted request. The files remain caller-owned, so callers can retain the
|
||||||
|
original bytes for retries and are responsible for cleanup. With neither
|
||||||
|
artifact source, an empty managed target set, or a matching empty prebuilt
|
||||||
|
result, delivery is page-only. Do not set both `Build` and `Prebuilt` in one
|
||||||
|
request.
|
||||||
|
|
||||||
|
```go
|
||||||
|
result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{
|
||||||
|
RepositoryDir: "/work/example",
|
||||||
|
ModuleDir: "integrations/example",
|
||||||
|
Product: "Example",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
ExpectedTag: "integrations/example/v1.2.3", // optional CI event check
|
||||||
|
Destination: releasekit.GiteaDestination{
|
||||||
|
BaseURL: "https://gitea.example",
|
||||||
|
Owner: "example",
|
||||||
|
Repository: "example",
|
||||||
|
Token: token,
|
||||||
|
},
|
||||||
|
Build: &releasekit.BuildSpec{
|
||||||
|
MainPackage: "./cmd/example",
|
||||||
|
BinaryName: "example",
|
||||||
|
Targets: []releasekit.Target{{OS: "linux", Arch: "amd64"}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
// Keep the returned state and any completed asset identities for recovery.
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Println(result.State, result.ReleaseURL)
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [CLI contract](../cli.md), [configuration reference](../config.md),
|
||||||
|
and [Gitea integration guide](../integrations/gitea.md) for exact settings,
|
||||||
|
exit codes, and transport behavior.
|
||||||
|
|
||||||
|
## Woodpecker tag workflows
|
||||||
|
|
||||||
|
Use the maintained [tag-delivery workflow](../../examples/woodpecker/tag-delivery.yml)
|
||||||
|
in the consumer repository's `.woodpecker/` directory. Set `GO_IMAGE` to an
|
||||||
|
image with Git and a Go toolchain compatible with the consumer module and its
|
||||||
|
selected ReleaseKit version. Choose the patch used for the consumer's release
|
||||||
|
build and validation. The template uses `GOTOOLCHAIN=local`; Go does not download
|
||||||
|
a different toolchain. The tag's `go.mod` must select ReleaseKit as a module
|
||||||
|
dependency. For CLI-only consumers, use the versioned Go tool dependency
|
||||||
|
described in the [adoption guide](adoption.md). Ordinary package dependencies
|
||||||
|
also work with this template.
|
||||||
|
|
||||||
|
Select a tool release implementing this workflow's interface before adopting it;
|
||||||
|
the [adoption guide](adoption.md#ci-adoption) owns coordinated tool/workflow
|
||||||
|
upgrades. Retries of older tags use the workflow matching their recorded tool.
|
||||||
|
|
||||||
|
Configure the Woodpecker repository secret `releasekit_gitea_token`; the
|
||||||
|
template maps it to `RELEASEKIT_GITEA_TOKEN` for delivery. The repository needs
|
||||||
|
a `delivery` profile. Page-only and binary behavior both use this template; the
|
||||||
|
profile's build target list selects whether application binaries are built and
|
||||||
|
delivered.
|
||||||
|
|
||||||
|
Before running Go, the template fetches the explicit event tag, compares its
|
||||||
|
peeled commit with the provider's full commit ID without regard to hex case,
|
||||||
|
checks out that commit detached, and confirms the source tree is clean. It then
|
||||||
|
copies the tagged `go.mod` and any `go.sum` to a temporary directory outside
|
||||||
|
the checkout. `go list -m` confirms that the module selects ReleaseKit; Go uses
|
||||||
|
an alternate `-modfile` to prepare dependencies and build the selected
|
||||||
|
`cmd/releasekit` package without changing the tagged module files. The template
|
||||||
|
invokes that executable with `CI_WORKSPACE`, `CI_COMMIT_SHA`, and
|
||||||
|
`CI_COMMIT_TAG`. A cleanup trap removes the temporary metadata and executable.
|
||||||
|
|
||||||
|
Tool bootstrap and application artifact preparation are separate. The bootstrap
|
||||||
|
resolves and builds ReleaseKit from the tagged consumer's module configuration.
|
||||||
|
After the workflow verifies and checks out the event tag, the resulting CLI uses
|
||||||
|
`ci-deliver --prepared` to repeat the tag, commit, HEAD, and cleanliness checks
|
||||||
|
without another fetch or checkout. It loads the tagged profile and downloads
|
||||||
|
application dependencies only when build targets are selected; it builds and
|
||||||
|
delivers those targets with the note page. Source-only profiles skip application
|
||||||
|
dependency downloads and binary work. Dependency preparation for binaries may
|
||||||
|
use the network. Prepare and commit the selected module's `go.sum` before
|
||||||
|
tagging; an uncommitted change makes the later delivery source check fail. A
|
||||||
|
retry still uses the same immutable tag and that tag's module settings, even
|
||||||
|
after the default branch selects a newer ReleaseKit version.
|
||||||
|
|
||||||
|
The root-only [`tag-delivery.yml`](../../examples/woodpecker/tag-delivery.yml)
|
||||||
|
keeps the small default profile and root-module bootstrap. For consumers that
|
||||||
|
release several modules from one repository, copy the contents of the maintained
|
||||||
|
[multi-module example](../../examples/multi-module/) to the consumer repository
|
||||||
|
root and use its [`woodpecker.yml`](../../examples/multi-module/woodpecker.yml),
|
||||||
|
[`release-modules.tsv`](../../examples/multi-module/release-modules.tsv), and
|
||||||
|
shared selector. The event tag chooses one row from the tagged checkout; the
|
||||||
|
profile and physical module must agree, and ReleaseKit verifies the derived tag.
|
||||||
|
The example covers source-only integration pages and a binary core module.
|
||||||
|
|
||||||
|
If the application does not declare ReleaseKit as a module dependency, install
|
||||||
|
the executable separately and invoke the same `ci-deliver` command. For
|
||||||
|
ReleaseKit's own source workflow, the maintained
|
||||||
|
[source-delivery template](../../examples/woodpecker/releasekit-source-delivery.yml)
|
||||||
|
checks out the tag and self-bootstraps `./cmd/releasekit` into temporary storage.
|
||||||
|
Its readonly tool build uses committed module metadata and can fetch missing
|
||||||
|
dependencies through normal Go proxy, private-module, checksum, and cache
|
||||||
|
settings. Tool bootstrap follows tag verification; offline candidate validation
|
||||||
|
and application artifact compilation retain their separate environments.
|
||||||
|
|
||||||
|
The normal Go module and build caches are sufficient. Cache mounts may be added
|
||||||
|
as deployment configuration when they help the runner; they are not needed by
|
||||||
|
the template. A separately installed executable can be installed with
|
||||||
|
`go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@PIN`, then run
|
||||||
|
with the same arguments:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
releasekit ci-deliver --repo "$CI_WORKSPACE" --commit "$CI_COMMIT_SHA" "$CI_COMMIT_TAG"
|
||||||
|
```
|
||||||
|
|
||||||
|
The module-based workflow follows the ReleaseKit version selected by the tagged
|
||||||
|
consumer's `go.mod`, so retries use that source's original selection. Update the
|
||||||
|
consumer module configuration when adopting a newer ReleaseKit version and
|
||||||
|
verify it with a tag fixture. The command and profile behavior are documented
|
||||||
|
in the [CLI contract](../cli.md) and [configuration reference](../config.md).
|
||||||
|
|
||||||
|
Woodpecker runs delivery after the tag event, independently from the source
|
||||||
|
publication result. Read its workflow status as delivery status: a delivery
|
||||||
|
failure does not undo source publication. A failed, partial, or uncertain run
|
||||||
|
can be inspected and retried against the same immutable tag and commit; do not
|
||||||
|
move the tag to make a retry pass. See
|
||||||
|
[Woodpecker's environment reference](https://woodpecker-ci.org/docs/usage/environment)
|
||||||
|
for runner-provided tag and commit variables and
|
||||||
|
[workflow syntax](https://woodpecker-ci.org/docs/usage/workflow-syntax) for tag
|
||||||
|
events, sequential steps, and the shared workspace.
|
||||||
|
|
||||||
|
## Investigating module checksum mismatches
|
||||||
|
|
||||||
|
During tool installation or dependency preparation, a checksum mismatch means
|
||||||
|
the bytes Go read differ from a recorded checksum. The message alone does not
|
||||||
|
identify whether those bytes came from the local cache or a remote source.
|
||||||
|
Keep checksum verification enabled and retain the error, selected version,
|
||||||
|
and relevant `go.sum` entries. Go's [module authentication reference](https://go.dev/ref/mod#authenticating)
|
||||||
|
describes these checks.
|
||||||
|
|
||||||
|
To isolate a public ReleaseKit download from application settings and the
|
||||||
|
existing module cache, run the following with a compatible local Go toolchain.
|
||||||
|
Replace `v0.2.0` with the affected version. This diagnostic accesses the public
|
||||||
|
Go proxy and checksum database and retains its temporary directory for inspection.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
(
|
||||||
|
checksum_dir=$(mktemp -d) || exit 1
|
||||||
|
printf 'Checksum investigation directory: %s\n' "$checksum_dir"
|
||||||
|
cd "$checksum_dir" || exit 1
|
||||||
|
GOENV=off GOFLAGS= GOWORK=off GOTOOLCHAIN=local \
|
||||||
|
GOPRIVATE= GONOPROXY= GONOSUMDB= \
|
||||||
|
GOPROXY=https://proxy.golang.org GOSUMDB=sum.golang.org \
|
||||||
|
GOMODCACHE="$checksum_dir/modules" \
|
||||||
|
go mod download -json gitea.maximumdirect.net/eric/ReleaseKit@v0.2.0
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
A successful isolated download establishes that this version verifies through
|
||||||
|
the selected proxy. Compare its `GoMod`, `GoModSum`, and `Sum` with the affected
|
||||||
|
cache and the application's recorded checksums. Locate the original cache with
|
||||||
|
`go env GOMODCACHE`; Go stores downloaded module metadata separately from the
|
||||||
|
extracted source. See the [module cache reference](https://go.dev/ref/mod#module-cache).
|
||||||
|
|
||||||
|
Once a stale cache entry is confirmed, preserve a copy, quarantine that entry
|
||||||
|
while no Go process is using it, and retry normal dependency preparation. For
|
||||||
|
a confirmed stale `.mod`, quarantine that file alone. Preserve application
|
||||||
|
checksums and published tags. Routine downloads can continue to use the normal
|
||||||
|
module cache.
|
||||||
|
|
||||||
|
If the isolated download also fails, investigate the selected proxy, tagged
|
||||||
|
source, and recorded checksums with the maintainer before changing local state.
|
||||||
|
Record any difference between proxy and direct fetching. A confirmed cache
|
||||||
|
problem can be repaired locally; changes to published source follow the
|
||||||
|
maintainer's immutable-release procedure.
|
||||||
122
docs/consumers/publish.md
Normal file
122
docs/consumers/publish.md
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
# Source tag publication
|
||||||
|
|
||||||
|
Use `releasekit.Publish` to validate a committed candidate and push its exact
|
||||||
|
annotated source tag:
|
||||||
|
|
||||||
|
```go
|
||||||
|
result, err := releasekit.Publish(ctx, releasekit.ReleaseRequest{
|
||||||
|
RepositoryDir: "/work/project",
|
||||||
|
ModuleDir: "integrations/example",
|
||||||
|
Product: "Example",
|
||||||
|
Version: "v1.2.3",
|
||||||
|
ExpectedPushURL: "ssh://git.example/owner/example.git",
|
||||||
|
Validation: releasekit.ValidationSpec{
|
||||||
|
Go: releasekit.GoValidationSpec{Race: true, FullVet: true},
|
||||||
|
},
|
||||||
|
AdditionalChecks: func(ctx context.Context, candidate releasekit.Candidate) error {
|
||||||
|
return runProjectChecks(ctx, candidate.ModuleDir)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Println(result.ModulePath, result.Version, result.Tag, result.CandidateCommit, result.TagObject)
|
||||||
|
```
|
||||||
|
|
||||||
|
`ModuleDir` is a repository-relative physical module directory; omit it or use
|
||||||
|
`.` for a root-module release. ReleaseKit reads the selected module's committed
|
||||||
|
declaration and derives the complete Git tag from its declared module path and
|
||||||
|
physical location. `Version` remains the stable semantic version. The note is
|
||||||
|
`<module>/docs/releases/<version>.md`; an on-disk `/v2` directory is part of
|
||||||
|
the note path but is removed from the tag prefix only when the module path ends
|
||||||
|
in `/v2`. `PublicationResult` returns the absolute `ModuleDir`, declared
|
||||||
|
`ModulePath`, complete `Tag`, and existing commit and tag-object evidence.
|
||||||
|
|
||||||
|
The optional `ValidationSpec.SharedFiles` selects additional committed files
|
||||||
|
for enabled file checks. Its nil and empty-slice behavior is described in the
|
||||||
|
[candidate check guide](check.md#local-candidate-check).
|
||||||
|
|
||||||
|
Publication captures a clean candidate on `main`, validates its committed
|
||||||
|
release note, and checks the selected remote before running candidate checks.
|
||||||
|
Set `ExpectedPushURL` to require the effective push destination to match an
|
||||||
|
exact string. Git URL rewrites are resolved first, and the push URL is compared
|
||||||
|
when fetch and push URLs differ. A mismatch fails preflight before Go validation,
|
||||||
|
callbacks, or tag creation; detect it with
|
||||||
|
`errors.Is(err, releasekit.ErrUnexpectedPushURL)`. `Check` ignores this
|
||||||
|
publication-only field.
|
||||||
|
It runs one `go test -mod=readonly -count=1 ./...` suite with the available
|
||||||
|
compatible local Go toolchain. Set `Validation.Go.Race` to run that suite with
|
||||||
|
`-race`. Set `Validation.Go.FullVet` to run `go vet -mod=readonly ./...` after
|
||||||
|
successful tests, with test-time vet disabled for that suite. The zero values
|
||||||
|
keep ordinary test-time vet behavior. It then calls `AdditionalChecks` once
|
||||||
|
when supplied. The standard suite cannot be replaced;
|
||||||
|
move product-specific behavior into `AdditionalChecks` and remove repeated
|
||||||
|
standard-suite commands from custom checks. A failed suite or additional check
|
||||||
|
prevents tag creation, and wrapped errors preserve their causes.
|
||||||
|
If race prerequisites are unavailable, the selected suite fails as `go-test`
|
||||||
|
instead of silently running without the race detector. Full-vet failures are
|
||||||
|
reported as `go-vet` and stop publication before tag creation.
|
||||||
|
|
||||||
|
Set `Validation.Go.CompileTargets` to compile packages for each complete target
|
||||||
|
pair after tests and vet. This uses `CGO_ENABLED=0`, produces no artifact, and
|
||||||
|
does not execute target binaries. A failure is reported as `package-compile`
|
||||||
|
with the selected target and prevents tag creation.
|
||||||
|
|
||||||
|
Set `Validation.GoFormat` to check committed regular Go source using the Go
|
||||||
|
formatter built into ReleaseKit. It uses the selected file inputs, including
|
||||||
|
vendor and explicit shared files, and ignores
|
||||||
|
worktree changes and symlink blobs, and reports unformatted paths as
|
||||||
|
`go-format` without changing files. The default is disabled. The check follows
|
||||||
|
tests, selected vet, and package compilation, and a failure stops publication
|
||||||
|
before product checks or tag creation.
|
||||||
|
|
||||||
|
Set `Validation.ModuleDistribution.WorkspaceFiles` to reject committed
|
||||||
|
`go.work` and `go.work.sum` blobs in the selected inputs, including symlink entries.
|
||||||
|
The rule reads the captured candidate regardless of `GOWORK`; uncommitted files
|
||||||
|
are ignored, and Go workspace selection and vendor behavior are unchanged. Its
|
||||||
|
zero value disables the check. Findings use `workspace-files` and stop
|
||||||
|
publication before product checks or tag creation.
|
||||||
|
Set `Validation.ModuleDistribution.LocalReplacements` independently to parse
|
||||||
|
selected module's committed `go.mod` declarations. Vendored contents remain in
|
||||||
|
scope; automatic inputs stop at independently released nested modules. Explicit
|
||||||
|
shared files can include another module's declaration. Filesystem
|
||||||
|
`replace` directives are reported with their source path, line, and target as
|
||||||
|
`local-replacements`; versioned replacements are
|
||||||
|
permitted. Committed module symlinks are resolved within the candidate, and
|
||||||
|
parse or inspection errors retain their causes. This check is independent of
|
||||||
|
`GOWORK`; its zero value disables it, and a failure stops publication before
|
||||||
|
product checks or tag creation.
|
||||||
|
Set `Validation.FileSize` to check each committed blob against a byte limit.
|
||||||
|
Nil disables the check; an empty object enables the default of 1,000,000
|
||||||
|
decimal bytes. `LimitBytes` uses strict greater-than, accepts zero, and rejects
|
||||||
|
negative values. `Exclusions` contains literal files or directories relative to
|
||||||
|
the selected module, including committed descendants of excluded directories.
|
||||||
|
Symlink blob size is its link text; gitlinks are omitted. This check measures only the
|
||||||
|
captured candidate and reports one oversized file with its measurement as
|
||||||
|
`file-size`; it stops publication before product checks or tag creation.
|
||||||
|
|
||||||
|
Set `Validation.Markdown` to check committed local Markdown destinations and
|
||||||
|
supported heading fragments during publication. Nil disables the check; an
|
||||||
|
empty object enables it with outside-checkout links reported as out of scope.
|
||||||
|
Set `EnforceCheckoutBoundary` to fail those links. Submodule contents remain
|
||||||
|
out of scope under either setting. Observations use the request's output writer;
|
||||||
|
failures use `markdown-links` and stop publication before product checks or tag
|
||||||
|
creation.
|
||||||
|
|
||||||
|
ReleaseKit-owned selections replace duplicate generic suite, vet, formatting,
|
||||||
|
distribution, and Markdown checks in configured product checks. Keep
|
||||||
|
release-note rules and consumer-specific assertions, such as maintained-example
|
||||||
|
tests, in `AdditionalChecks` or profile `checks`.
|
||||||
|
|
||||||
|
If `Build` selects targets, ReleaseKit verifies them after the standard suite
|
||||||
|
and additional checks, before creating the tag. The operation then rechecks the
|
||||||
|
candidate and remote guards, creates an annotated tag for the captured commit,
|
||||||
|
and pushes only that tag object.
|
||||||
|
|
||||||
|
A successful result means Git confirmed the push or an exact authoritative tag
|
||||||
|
query confirmed it after a push error. The local tag is retained after a failed
|
||||||
|
push. `PublicationState` distinguishes a known failure, conflict, confirmed
|
||||||
|
publication, and unresolved outcome. Resolve an unknown result against the
|
||||||
|
captured endpoint before retrying; see the [maintainer procedure](../release.md)
|
||||||
|
for the recovery steps. The [CLI contract](../cli.md) documents command output
|
||||||
|
and exit statuses.
|
||||||
17
docs/consumers/runtime-version.md
Normal file
17
docs/consumers/runtime-version.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# Runtime version
|
||||||
|
|
||||||
|
Applications can read their embedded version through the public `buildinfo`
|
||||||
|
package:
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
|
||||||
|
version := buildinfo.Version()
|
||||||
|
```
|
||||||
|
|
||||||
|
`Version` returns the identifier injected into the executable when present.
|
||||||
|
Otherwise it returns the executable's main module version when that metadata is
|
||||||
|
available and is not `(devel)`. It returns `dev` when neither source provides a
|
||||||
|
release identifier. Applications should use this accessor for version output;
|
||||||
|
the runtime implementation and [ReleaseKit's build API](build.md) own the
|
||||||
|
injection detail.
|
||||||
91
docs/development.md
Normal file
91
docs/development.md
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
# Developing ReleaseKit
|
||||||
|
|
||||||
|
ReleaseKit contains a Go module with the documented root `releasekit` facade,
|
||||||
|
adopted policies, and design documents. See the [README](../README.md) for
|
||||||
|
orientation.
|
||||||
|
|
||||||
|
Read the [agent policy](policy/agents.md) and inspect the worktree before editing.
|
||||||
|
Preserve unrelated changes and follow explicit instructions about commits.
|
||||||
|
The [architecture policy](policy/architecture.md) governs development boundaries;
|
||||||
|
[ADR 0001](adr/0001-public-facade.md) records the facade decision. The
|
||||||
|
[documentation policy](policy/documentation.md#canonical-ownership) owns the
|
||||||
|
documentation topic map.
|
||||||
|
|
||||||
|
[ADR 0002](adr/0002-routine-releases.md) records the priorities and non-goals
|
||||||
|
behind ReleaseKit's standard, minimal API for routine releases.
|
||||||
|
|
||||||
|
## Policy Reading Guide
|
||||||
|
|
||||||
|
| Policy | Read before… |
|
||||||
|
| --- | --- |
|
||||||
|
| [Policy set provenance](policy/meta.md) | Adopting policies, checking upstream revisions, or updating the adopted policy set. |
|
||||||
|
| [Agents](policy/agents.md) | Recommending, planning, or implementing repository changes. |
|
||||||
|
| [Architecture](policy/architecture.md) | Planning or changing library or executable code or its structure. |
|
||||||
|
| [Testing](policy/testing.md) | Selecting validation for code changes, or adding, changing, removing, or evaluating tests. |
|
||||||
|
| [Documentation](policy/documentation.md) | Writing, revising, or reorganizing documentation. |
|
||||||
|
| [OSS](policy/oss.md) | Adding or updating dependencies or incorporated third-party material, or changing licensing or attribution. |
|
||||||
|
| [Release](policy/release.md) | Preparing or publishing a release, changing release procedures, or making versioning and compatibility decisions. |
|
||||||
|
|
||||||
|
- Read applicable policies before making decisions they govern; multiple policies
|
||||||
|
may apply.
|
||||||
|
- Select policies using the task triggers above. Follow cross-references to
|
||||||
|
relevant sections when needed to resolve a concrete question.
|
||||||
|
- Reuse policies already available in context; reread when changed or no longer
|
||||||
|
available.
|
||||||
|
- Expand reading when the task's scope expands.
|
||||||
|
- When revising a policy itself, read that policy and any provisions elsewhere
|
||||||
|
affected by the revision.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Run the offline Go test suite from the repository root with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go test ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the compiled public API and dependency-boundary checks from the repository
|
||||||
|
root with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./internal/apicheck
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [candidate check guide](consumers/check.md), [source publication guide](consumers/publish.md),
|
||||||
|
[build consumer guide](consumers/build.md),
|
||||||
|
and [internal package inventory](internal/overview.md) for implemented behavior
|
||||||
|
and capability ownership.
|
||||||
|
|
||||||
|
For prose changes, review the diff and check local links, fragment destinations,
|
||||||
|
provenance, template residue, and consistency with current repository contents.
|
||||||
|
Check prose whitespace with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git diff --check -- '*.md' COPYRIGHT
|
||||||
|
git diff --cached --check -- '*.md' COPYRIGHT
|
||||||
|
```
|
||||||
|
|
||||||
|
Verbatim license texts retain their supplied formatting. When changing those
|
||||||
|
texts, compare their bytes with the selected upstream source.
|
||||||
|
|
||||||
|
Run the source publication command from the candidate repository root with
|
||||||
|
`./scripts/release VERSION`. It uses the local Go toolchain and committed
|
||||||
|
`releasekit.json` profile; prepare module dependencies before offline candidate
|
||||||
|
validation. The [maintainer release procedure](release.md) owns preparation,
|
||||||
|
publication, and recovery. Hosted note-page delivery is a separate prepared
|
||||||
|
workflow and does not change the successful-tag-push completion point. ReleaseKit
|
||||||
|
does not declare binary deliverables.
|
||||||
|
|
||||||
|
## Testing synthetic modules
|
||||||
|
|
||||||
|
Tests that serve synthetic module versions through local proxies should pass a
|
||||||
|
test-owned temporary `GOMODCACHE` to every Go subprocess that consumes those
|
||||||
|
versions. Scope fixture-specific proxy and checksum settings to those processes.
|
||||||
|
This applies the [testing policy's isolation requirements](policy/testing.md#test-execution-requirements)
|
||||||
|
to module downloads and keeps fixture metadata out of developer and CI caches.
|
||||||
|
|
||||||
|
Distinct fixture version numbers still occupy the real module's cache namespace.
|
||||||
|
Use temporary caches even when the selected versions have never been published.
|
||||||
|
Verify isolation at the shared fixture boundary; ordinary builds can continue
|
||||||
|
to use their prepared dependency cache. Consumer recovery guidance lives in the
|
||||||
|
[module checksum investigation guide](consumers/delivery.md#investigating-module-checksum-mismatches).
|
||||||
86
docs/integrations/gitea.md
Normal file
86
docs/integrations/gitea.md
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
# Gitea release pages
|
||||||
|
|
||||||
|
ReleaseKit's public `Deliver` operation and `deliver` command verify tagged
|
||||||
|
source, find or create the selected module's release page, inspect existing assets, and
|
||||||
|
upload missing assets through the internal Gitea client. Page-only and
|
||||||
|
binary-producing profiles use the same delivery path. The
|
||||||
|
[consumer delivery guide](../consumers/delivery.md) covers caller workflows;
|
||||||
|
this guide describes the Gitea protocol and its failure behavior.
|
||||||
|
|
||||||
|
The caller supplies the Gitea base URL, owner, repository name, and token
|
||||||
|
explicitly. The client does not read ambient credentials. The token is sent in
|
||||||
|
the `Authorization: token …` request header and is not included in errors or
|
||||||
|
results. The base URL must use HTTP or HTTPS and cannot contain URL credentials,
|
||||||
|
a query, or a fragment.
|
||||||
|
|
||||||
|
The selected module derives a complete tag from its semantic version, declared
|
||||||
|
module path, and physical repository-relative directory. For example, version
|
||||||
|
`v1.2.3` in `integrations/ckconfig` uses
|
||||||
|
`integrations/ckconfig/v1.2.3`; a root module uses `v1.2.3`. A `/v2` module
|
||||||
|
stored at `integrations/core/v2` uses `integrations/core/v2.1.0`; the same
|
||||||
|
declared module stored at `integrations/core` derives the same tag. ReleaseKit
|
||||||
|
removes a final physical `/v2` directory from the tag prefix only when the
|
||||||
|
module declaration has that `/v2` suffix. A module-local note stays at
|
||||||
|
`<module>/docs/releases/<version>.md`, including a physical `/v2` directory.
|
||||||
|
The default shared validation convention uses repository-root `COPYRIGHT`,
|
||||||
|
`LICENSE`, and `docs/oss/attribution.md` when present. Consumers own their license
|
||||||
|
layout and release-note links. Use the complete derived tag as the immutable
|
||||||
|
source ref and the actual repository-relative file paths in those links.
|
||||||
|
Shared-file selection controls validation inputs; delivery preserves the
|
||||||
|
committed note and its footer links. The client first reads
|
||||||
|
`/api/v1/repos/{owner}/{repo}/tags/{tag}` and requires the hosted tag's commit
|
||||||
|
SHA to equal the captured source commit. It then reads
|
||||||
|
`/api/v1/repos/{owner}/{repo}/releases/tags/{tag}`. A matching existing page
|
||||||
|
must have that tag, the complete committed release note as its body, and stable
|
||||||
|
non-draft state. Its existing title is retained. ReleaseKit does not edit a
|
||||||
|
conflicting page. Slash-containing tags are escaped as one URL path segment.
|
||||||
|
|
||||||
|
If the page is absent, the client posts to `/api/v1/repos/{owner}/{repo}/releases`
|
||||||
|
with the selected full tag and commit, the release note's H1 as title, the complete
|
||||||
|
note as body, and draft and prerelease disabled. A create conflict, interrupted
|
||||||
|
response, or malformed create response (including inconsistent decoded fields)
|
||||||
|
triggers one lookup. An exact page found
|
||||||
|
there confirms the existing content; a differing page is a conflict. If that
|
||||||
|
lookup cannot determine the result after a possibly successful write, the
|
||||||
|
client returns an unknown outcome. Other HTTP failures retain their structured
|
||||||
|
failure kind and status code. A recovered create retains its write history;
|
||||||
|
a later asset-inspection failure reports partial page progress.
|
||||||
|
|
||||||
|
For a binary-producing release, the client can build a deterministic
|
||||||
|
`SHA256SUMS` file from the declared artifact names and SHA-256 digests. Entries
|
||||||
|
are sorted by filename and use the standard two-space separator. A source-only
|
||||||
|
release produces no manifest.
|
||||||
|
|
||||||
|
Asset inspection lists the release attachments, streams each declared existing
|
||||||
|
file, and compares its SHA-256 digest. It reports each asset as matching,
|
||||||
|
missing, conflicting, or unverifiable. Same-name attachments with different
|
||||||
|
bytes are conflicts even when their reported size matches. An existing
|
||||||
|
`SHA256SUMS` must exactly match the complete expected manifest; a subset or
|
||||||
|
different manifest is a conflict. An unreadable attachment is unverifiable,
|
||||||
|
not missing. A failed read-only inspection reports `not_attempted`; if this
|
||||||
|
invocation already delivered the page, its outcome retains `partial` progress.
|
||||||
|
Unknown-write outcomes are reserved for unresolved writes. Unrelated attachments are returned separately and are preserved.
|
||||||
|
|
||||||
|
Attachment downloads and redirects carry the Gitea authorization token only
|
||||||
|
when their scheme, host, and port match the configured service. Cross-origin
|
||||||
|
content is downloaded without that token and verified by its digest.
|
||||||
|
|
||||||
|
The upload operation accepts only an inspection result without conflicts or
|
||||||
|
unverifiable assets. It uploads missing binaries in filename order and then the
|
||||||
|
missing `SHA256SUMS`, using multipart field `attachment` and the filename query
|
||||||
|
parameter `name`. Matching attachments are retained; unrelated and existing
|
||||||
|
attachments are never overwritten or deleted. Results use disjoint current
|
||||||
|
observations: matching, uploaded, pending, conflicting, and uncertain. An asset
|
||||||
|
moved from known missing work to another category is removed from `pending`;
|
||||||
|
later known-missing assets can remain pending when an earlier upload stops the
|
||||||
|
operation. Early failures may leave declarations unreported. After an ambiguous
|
||||||
|
upload or an upload name conflict, the client performs one list and content
|
||||||
|
check. It does not repeat the POST when the result is missing or cannot be
|
||||||
|
verified, so a caller can resolve the remote state before retrying.
|
||||||
|
|
||||||
|
Uploads use the configured service origin and the same explicit token header.
|
||||||
|
Source-only page delivery supplies no binary assets and creates no manifest.
|
||||||
|
|
||||||
|
The integration tests use a local HTTP fixture and assert request paths,
|
||||||
|
payloads, authorization, streaming comparisons, manifest handling, and failure
|
||||||
|
handling. They do not contact a live Gitea service or use real credentials.
|
||||||
89
docs/internal/gotool.md
Normal file
89
docs/internal/gotool.md
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
# Go command environments
|
||||||
|
|
||||||
|
`internal/gotool` resolves effective Go settings when an operation first needs
|
||||||
|
a Go command and applies the shared environment to its commands. Candidate
|
||||||
|
validation and its build callback share an operation-local owner while the
|
||||||
|
inherited environment and persistent Go settings file remain unchanged.
|
||||||
|
Standalone and delivery builds create their own owners. The package uses
|
||||||
|
`internal/process` for cancellation, the working directory, output, and wrapped
|
||||||
|
errors.
|
||||||
|
|
||||||
|
## Command output ownership
|
||||||
|
|
||||||
|
`Tool.Run` executes a status-only command. It forwards combined stdout and
|
||||||
|
stderr to the optional writer while the child runs, then releases its capture
|
||||||
|
on success. Failures include the captured diagnostic text and preserve the
|
||||||
|
underlying process or forwarding error.
|
||||||
|
|
||||||
|
`Tool.Output` returns combined stdout and stderr for commands whose output is
|
||||||
|
needed by the caller, such as compiler identification. After the child stops,
|
||||||
|
the capture's backing bytes transfer to the caller without a second copy. A
|
||||||
|
failed output command returns both those bytes and an error containing the
|
||||||
|
diagnostic text. The capture remains in memory for the duration of the child;
|
||||||
|
the component benchmark compares one 8 MiB write with the same output in
|
||||||
|
32 KiB writes, forwarding to `io.Discard`. Smaller writes incur buffer-growth
|
||||||
|
allocations. The [output benchmark](../../internal/gotool/performance_test.go)
|
||||||
|
measures total allocated bytes per operation, excluding subprocess overhead and
|
||||||
|
diagnostic strings. These totals count all allocations, including superseded
|
||||||
|
buffers. The returned slice retains the final buffer holding the complete output.
|
||||||
|
Peak live memory depends on buffer growth, garbage collection, and other command
|
||||||
|
work and is not measured by allocation totals. Failed output also formats
|
||||||
|
diagnostics into the error, so the returned bytes and diagnostic string can
|
||||||
|
coexist. Disk-backed diagnostics could reduce large failure peaks, but add file
|
||||||
|
lifecycle and cleanup work and remain a follow-up option.
|
||||||
|
|
||||||
|
Dependency preparation uses a separate command environment so proxy, private
|
||||||
|
module, checksum, and cache settings remain available. Its completed capture
|
||||||
|
uses the same ownership transfer when formatting a failure.
|
||||||
|
|
||||||
|
## Configuration discovery
|
||||||
|
|
||||||
|
The owner asks the installed `go` command for `GOHOSTOS`, `GOHOSTARCH`, and the
|
||||||
|
`GOENV` settings-file path, then queries effective operational settings with
|
||||||
|
that host selected. Both queries use `GOTOOLCHAIN=local` and controlled
|
||||||
|
`GOFLAGS`. Discovery sets
|
||||||
|
`GOEXPERIMENT=none` and clears architecture feature variables so an invalid or
|
||||||
|
nonbaseline tuning value cannot prevent settings from being read. The
|
||||||
|
experiment override is discovery-only.
|
||||||
|
|
||||||
|
The persistent Go environment remains active during discovery. The owner copies
|
||||||
|
the effective cache and module-cache locations, Go root, temporary directory,
|
||||||
|
and native cgo/C-tool configuration into its settings. This captures values
|
||||||
|
supplied by either the process environment or the persistent Go environment
|
||||||
|
file.
|
||||||
|
|
||||||
|
The operation-local owner snapshots the inherited environment and selected
|
||||||
|
settings file. It reuses the resolved tool across validation and its following
|
||||||
|
build callback while those inputs match. Subsequent Go acquisition rediscovers
|
||||||
|
settings when a consumer callback changes either input. An unavailable snapshot
|
||||||
|
disables reuse while discovery follows the Go tool's accepted configuration.
|
||||||
|
Ownership is operation-local.
|
||||||
|
|
||||||
|
Configuration discovery parses JSON from stdout. Stderr is captured separately
|
||||||
|
and included in command-failure diagnostics, so a successful query can emit
|
||||||
|
warnings while supplying valid configuration.
|
||||||
|
|
||||||
|
## Command environments
|
||||||
|
|
||||||
|
Every Go command receives `GOENV=off`, so removed persistent values cannot
|
||||||
|
return. ReleaseKit owns `GOFLAGS=-mod=readonly`, `GOWORK=off`,
|
||||||
|
`GOTOOLCHAIN=local`, `GOPROXY=off`, `GONOPROXY=none`, and `GOSUMDB=off`.
|
||||||
|
Native commands use `GOHOSTOS` and `GOHOSTARCH` and retain the effective
|
||||||
|
`CGO_ENABLED`, `CC`, `CXX`, `PKG_CONFIG`, and `CGO_CFLAGS`, `CGO_CPPFLAGS`,
|
||||||
|
`CGO_CXXFLAGS`, and `CGO_LDFLAGS`. Static commands use the selected target and
|
||||||
|
`CGO_ENABLED=0`.
|
||||||
|
|
||||||
|
Both modes clear `GOEXPERIMENT` and the Go architecture feature variables
|
||||||
|
`GOAMD64`, `GOARM`, `GOARM64`, `GO386`, `GOMIPS`, `GOMIPS64`, `GOPPC64`,
|
||||||
|
`GORISCV64`, and `GOWASM`. The selected Go toolchain supplies its ordinary
|
||||||
|
baseline values. Effective `GOCACHE`, `GOCACHEPROG`, `GOMODCACHE`, `GOPATH`,
|
||||||
|
`GOROOT`, and `GOTMPDIR` values are retained. Other process variables remain
|
||||||
|
available to child commands.
|
||||||
|
|
||||||
|
Candidate validation runs the offline `go test` suite and selected full
|
||||||
|
`go vet` pass from the selected module directory using native mode.
|
||||||
|
Package-compilation checks use static mode for each selected target and direct
|
||||||
|
Go's output to the operating system null device, so they leave no binary
|
||||||
|
artifact. Artifact builds also compile selected targets in static mode, then
|
||||||
|
build the native version-check executable, which runs as a normal child
|
||||||
|
process.
|
||||||
115
docs/internal/overview.md
Normal file
115
docs/internal/overview.md
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
# Package and capability inventory
|
||||||
|
|
||||||
|
Public Go contracts are defined in declarations and GoDoc. ReleaseKit supports
|
||||||
|
two Go facades and a command-line interface:
|
||||||
|
|
||||||
|
- The root `releasekit` package is the orchestration facade. `Check` validates
|
||||||
|
one local candidate, `Publish` validates and publishes its exact annotated
|
||||||
|
source tag, `Build` compiles selected application targets, and `Deliver`
|
||||||
|
delivers a tagged note page and any declared assets. `PrepareTaggedCheckout`
|
||||||
|
and `PrepareBuildDependencies` provide explicit local CI preparation.
|
||||||
|
- `buildinfo` is the small runtime facade. `Version` reports the injected
|
||||||
|
application version, the main-module version when available, or `dev`.
|
||||||
|
- `cmd/releasekit` is the executable interface. Its `version`, `check`,
|
||||||
|
`publish`, `build`, `deliver`, and `ci-deliver` commands adapt profiles and
|
||||||
|
command output to the supported library operations.
|
||||||
|
|
||||||
|
See the [CLI contract](../cli.md), [configuration reference](../config.md),
|
||||||
|
[candidate check guide](../consumers/check.md),
|
||||||
|
[source publication guide](../consumers/publish.md),
|
||||||
|
[build guide](../consumers/build.md),
|
||||||
|
[delivery guide](../consumers/delivery.md), and
|
||||||
|
[runtime version guide](../consumers/runtime-version.md) for task-oriented use.
|
||||||
|
Go declarations and GoDoc remain the owners of exact exported contracts.
|
||||||
|
|
||||||
|
## Module and dependencies
|
||||||
|
|
||||||
|
The module is `gitea.maximumdirect.net/eric/ReleaseKit`, with Go language
|
||||||
|
version `1.26.0`. `go.mod` requires `golang.org/x/mod` and Goldmark for internal
|
||||||
|
validation; public facades do not expose either dependency. `go list ./...`
|
||||||
|
reports these implemented packages:
|
||||||
|
|
||||||
|
| Package | Responsibility |
|
||||||
|
| --- | --- |
|
||||||
|
| `releasekit` | Public orchestration facade and consumer-owned request/result types. |
|
||||||
|
| `buildinfo` | Public runtime version accessor. |
|
||||||
|
| `cmd/releasekit` | Executable entry point, command routing, output, and exit status. |
|
||||||
|
| `cmd/releasekit/internal/cli` | Command parsing, strict JSON profile loading, configured checks, and private build receipts. |
|
||||||
|
| `internal/apicheck` | Compiled-export and import-boundary checks run during development. |
|
||||||
|
| `internal/artifact` | Shared build-target normalization, artifact declarations, filename rules, and checksum-manifest naming. |
|
||||||
|
| `internal/build` | Resolved-identity builds, normalized settings, selected-module compilation, version injection, external native smoke output, and artifact digests. |
|
||||||
|
| `internal/candidate` | Stable-version, note, repository-state, candidate capture, and post-validation checks. |
|
||||||
|
| `internal/delivery` | Captured-commit module identity and note selection, literal-tag checkout checks, prebuilt identity binding, managed builds in disposable storage outside the checkout, structural artifact declaration, manifest assembly, one local digest-and-size preflight before hosted requests, and delivery coordination. |
|
||||||
|
| `internal/git` | Git command boundary, committed-tree reads and shared reference traversal, checkout-root and commit capture, lazy local-only batched blob reads, push-destination resolution, exact ref inspection, tagged checkout preparation, and tag operations, including captured-endpoint verification during recovery. |
|
||||||
|
| `internal/gitea` | Gitea API transport, full-tag hosted release pages, asset inspection, manifests, and uploads. |
|
||||||
|
| `internal/gotool` | Operation-local Go configuration discovery and reuse, shared native-validation and static-build environments, and network-capable dependency preparation; see [Go command environments](gotool.md). |
|
||||||
|
| `internal/tempdir` | Disposable system temporary storage outside source worktrees. |
|
||||||
|
| `internal/process` | Cancellable child-process execution, including owned stdin/stdout pipes for serialized exchanges, with per-command environment overlays and removals. |
|
||||||
|
| `internal/preparation` | Coordination for expected-commit tag checkout and Go module dependency preparation. |
|
||||||
|
| `internal/releaseidentity` | Committed-object and working-tree module selection, declaration reading, and semantic-version-to-tag derivation. |
|
||||||
|
| `internal/validation` | Shared Go validation with optional race, full-vet, and static package-compilation target selections, formatting, workspace-file and filesystem-replacement checks, per-blob size limits, and selected Markdown destination and fragment checking; `internal/candidate` retains capture, callback sequencing, and local-state rechecks. |
|
||||||
|
| `internal/publish` | Publication guards, one validation run, annotated tag creation, push, and recovery state. |
|
||||||
|
| `internal/runtimeinfo` | Injected version selection and cached fallback metadata lookup for the runtime facade. |
|
||||||
|
| `internal/versioncontract` | Shared stable-version rules and linker-symbol identity. |
|
||||||
|
|
||||||
|
The `buildinfo` facade depends only on its small runtime implementation. The
|
||||||
|
root facade forwards to internal implementation packages. The CLI adapter is
|
||||||
|
owned under `cmd/releasekit/internal`; implementation packages do not import
|
||||||
|
either public facade. `internal/apicheck` verifies exported type ownership and
|
||||||
|
dependency direction with `go run ./internal/apicheck`. These constraints are
|
||||||
|
also recorded in [ADR 0001](../adr/0001-public-facade.md) and the
|
||||||
|
[architecture policy](../policy/architecture.md).
|
||||||
|
|
||||||
|
Candidate checking captures and validates one clean committed source revision
|
||||||
|
in `internal/candidate`. Its validation bridge calls `internal/validation` for
|
||||||
|
the selected module's default offline Go suite, then runs product-specific
|
||||||
|
checks once. Validation and its post-validation build callback share one local
|
||||||
|
Go settings owner. Each Go acquisition checks inherited and persistent inputs;
|
||||||
|
settings are rediscovered when subsequent Go work needs them. An unavailable
|
||||||
|
persistent-settings snapshot disables reuse. The candidate package owns builds and local-state
|
||||||
|
rechecks; publication owns endpoint guards, tag creation, push, and recovery
|
||||||
|
around that same candidate validation path. `internal/validation.CandidateTree` reads
|
||||||
|
committed blobs lazily and resolves local destinations from committed entries;
|
||||||
|
it does not consult neighboring files or traverse submodule checkouts.
|
||||||
|
See the [shared validation guide](validation.md) for checker, Go command, and
|
||||||
|
candidate-file integration mechanics.
|
||||||
|
|
||||||
|
Delivery verifies all local binary sizes and digests before hosted requests.
|
||||||
|
Its Gitea upload path reuses that verification and streams missing files once
|
||||||
|
for transport. Independent calls to the internal client's `UploadMissing`
|
||||||
|
verify missing local files before writing. Both paths share remote inspection,
|
||||||
|
conflict handling, and reconciliation.
|
||||||
|
|
||||||
|
## Capability owners and behavioral evidence
|
||||||
|
|
||||||
|
The following tests are representative evidence from the current offline suite,
|
||||||
|
not a separate release matrix:
|
||||||
|
|
||||||
|
| Capability | Implementation owner | Existing evidence |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Runtime version lookup and injected application version | `buildinfo`, `internal/runtimeinfo`, `internal/versioncontract`, `internal/build` | `TestVersionInConsumerExecutable`, `TestVersion` |
|
||||||
|
| Candidate capture, shared validation, public diagnostics, additional checks, and rechecks | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestRunUsesOneSuiteWithSelectedRaceSetting`, `TestRunReportsRacePrerequisiteFailureWithoutFallback`, `TestRunExecutesRaceEnabledSuiteOnHost`, `TestRunCompilesTargetsAfterTestAndVetInSelectionOrder`, `TestRunAttributesTargetCompileFailureAndStops`, `TestRunCompilesSourceOnlyAndExecutablePackagesWithoutArtifacts`, `TestCandidateRequestMapsGoValidation`, `TestCandidateRequestPreservesMarkdownObjectSelection`, `TestLoadSettingsReadsGoValidation`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestCheckUsesSelectedRaceSuiteBeforeAdditionalChecks`, `TestCheckCapturesCandidateAndCallsAdditionalChecksOnce`, `TestCheckReturnsPublicValidationError`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails`, `TestCheckCommandBindsConfiguredChecksToCapturedCandidate`, `TestPublishCommandPublishesConfiguredCandidate`, `TestCandidateCommandsPresentValidationDiagnosticsOnce`, `TestDeliverPageOnlyCreatesAndReusesRelease` |
|
||||||
|
| Committed-file validation: formatting, workspace files, local replacements, and file size | `internal/validation`, `internal/candidate`, `releasekit.Check`, `releasekit.Publish`, CLI profile conversion | `TestCheckGoFormatUsesCapturedRegularGoBlobs`, `TestCheckWorkspaceFilesReportsCommittedBlobNames`, `TestCheckLocalReplacementsParsesCommittedModuleDeclarations`, `TestCheckLocalReplacementsFollowsCommittedModuleSymlinks`, `TestCheckFileSizeUsesStrictLimitsAndDefault`, `TestCheckFileSizeAppliesLiteralPathExclusions`, `TestCheckFileSizeUsesCommittedBlobSizes`, `TestCheckFileSizeUsesOnlyCandidateFilesIndividually` |
|
||||||
|
| Internal Markdown parsing, committed destinations, fragments, boundary observations, and public selection | `releasekit.Check`, `releasekit.Publish`, `internal/candidate`, `internal/validation`, `cmd/releasekit/internal/cli` | `TestParseMarkdownLinksAndSourceLocations`, `TestParseMarkdownDecodesEntitiesInDestinations`, `TestParseMarkdownHeadingAnchors`, `TestMarkdownCacheKeepsParsedDocumentsPerCandidatePath`, `TestCheckMarkdownLinksResolvesCommittedDestinationsAndFragments`, `TestCheckMarkdownLinksReportsMissingPathsAnchorsAndCycles`, `TestCheckMarkdownLinksUsesResolvedMarkdownIdentity`, `TestCheckMarkdownLinksReportsBoundaryAndSubmoduleObservations`, `TestCheckMarkdownLinksPreservesResolverCauseAndCancellation`, `TestCheckMarkdownLinksPreservesAnchorReadCause`, `TestRunSelectsMarkdownWithCombinedGoChecksAndReportsOutOfScopeLinks`, `TestMarkdownValidationRunsThroughCheckAndPublish`, `TestLoadSettingsPreservesMarkdownObjectSelection`, `TestValidationSpecPreservesMarkdownObjectSelection` |
|
||||||
|
| Shared Go settings for validation and builds | `internal/gotool`, `internal/process`, `internal/candidate`, `internal/build` | `TestDefaultValidationDoesNotInheritGOFLAGSRunFilter`, `TestNativeAndStaticCommandsUseOwnedBaseline`, `TestPersistentSettingsPreserveCachesAndNativeCTools`, `TestOwnerReusesSettingsUntilInheritedEnvironmentChanges`, `TestOwnerRefreshesWhenPersistentSettingsChange`, `TestCheckSharesGoDiscoveryWithAfterValidateCallback`, `TestCheckBuildsAfterValidationAndKeepsOutputOutsideWorktree`, `TestRunValidatesOnlyTheSelectedModule`, `TestBuildIgnoresAmbientAndPersistentArchitectureTuning` |
|
||||||
|
| Batched local Git blob reads | `internal/git`, `internal/process` | `TestBlobReaderReadsLooseAndPackedObjects`, `TestBlobReaderMissingObjectKeepsBatchSessionUsable`, `TestCandidateObjectReadsStayLocalInPartialClones` |
|
||||||
|
| Piped child-process exchanges and cancellation cleanup | `internal/process` | `TestStartPipedExchangesBeforeInputEOFAndPreservesSettings`, `TestStartPipedCancellationAfterReadinessReapsChild`, `TestStartPipedPreservesNonzeroExit` |
|
||||||
|
| Authoritative endpoint and exact annotated tag publication | `releasekit.Publish`, `internal/publish`, `internal/git` | `TestPublishPushesOnlyTheCapturedAnnotatedTag`, `TestPublishRejectsUnexpectedPushURLBeforeValidation`, `TestPublishComparesExpectedURLWithResolvedInsteadOfDestination`, `TestPublishExpectedPushURLUsesPushURLWhenFetchAndPushDiffer`, `TestCheckIgnoresExpectedPushURL`, `TestResolveUsesPushURLAndQueriesWithoutMutation` |
|
||||||
|
| Publication partial and uncertain recovery | `internal/publish`, `internal/git` | `TestPublishRejectedPushKeepsLocalTagAndReportsNotPublished`, `TestPublishLostAcknowledgmentConfirmsExactRemoteObject`, `TestPublishLostAcknowledgmentWithChangedEndpointRemainsUnknown`, `TestPublishUnavailableReconciliationRemainsUnknownAndPreservesPushError` |
|
||||||
|
| Cross-builds, version smoke checks, module paths, empty target sets, and partial outputs | `releasekit.Build`, `internal/build`, `internal/artifact`, `internal/tempdir`, `buildinfo` | `TestBuildCreatesSelectedTargetsAndInjectsVersion`, `TestBuildUsesNestedWorkingTreeModuleAndModuleRelativeOutput`, `TestBuildResolvesDirtyWorkingTreeDeclaration`, `TestBuildWithNoTargetsDoesNotInvokeCompiler`, `TestBuildReturnsPartialArtifactsAfterTargetFailure`, `TestNormalizeSettingsKeepsBuildInputsAndNormalizesTargets`, `TestOutsideFallsBackWhenTemporaryDirectoryIsInsideWorktree` |
|
||||||
|
| Page-only and managed or prebuilt binary delivery | `releasekit.Deliver`, `internal/delivery`, `internal/gitea`, CLI | `TestDeliverPageOnlySkipsBuildAndHostedAssets`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages`, `TestDeliverRejectsPrebuiltArtifactsForAnotherModuleBeforeHostedRequests`, `TestDeliverManagedBuildUploadsArtifactsAndCleansTemporaryOutput`, `TestDeliverBinaryConsumerWithBuildinfoAndSelectedTargets`, `TestDeliverPrebuiltArtifactsRemainCallerOwned`, `TestDeliverRejectsSameSizePrebuiltTamperingBeforeHostedWrites`, `TestDeliverManagedBuildFailureCleansTemporaryOutputBeforeHostedWrites`, `TestDeliverManagedBuildCancellationCleansTemporaryOutput`, `TestDeliverBuildsTaggedArtifactsAndReusesAssets`, `TestDeliverRejectsTamperedAssetsAndStaleReceiptBeforeRemoteWrites`, `TestEnsureReleaseEscapesSlashContainingTag` |
|
||||||
|
| Tagged checkout and build dependency preparation | `releasekit.PrepareTaggedCheckout`, `releasekit.PrepareBuildDependencies`, `internal/preparation`, `internal/git`, `internal/gotool` | `TestPrepareTaggedCheckoutFetchesExpectedCommitAndDetaches`, `TestPrepareTaggedCheckoutRejectsWrongCommitBeforeCheckout`, `TestPrepareTaggedCheckoutReportsLocalCheckoutConflict`, `TestPrepareTaggedCheckoutReportsConflictingLocalTag`, `TestPrepareBuildDependenciesUsesSelectedModuleDirectory`, `TestPrepareBuildDependenciesPreservesPreparationEnvironment`, `TestPrepareBuildDependenciesPropagatesCommandFailure`, `TestPrepareBuildDependenciesPropagatesCancellation` |
|
||||||
|
| Shared module identity and tag derivation | `internal/releaseidentity`, `internal/candidate`, `internal/build`, `internal/delivery` | `TestDeriveUsesModuleDeclarationAndPhysicalLayout`, `TestCommittedAndWorkingTreeDeclarationsUseTheirOwnSources`, `TestSelectedNestedModuleDoesNotRequireRootDeclaration`, `TestBuildResolvesDirtyWorkingTreeDeclaration`, `TestDeliverUsesCommittedModuleIdentityForSeparatePages` |
|
||||||
|
| Page, manifest, asset comparison, and additive retry outcomes | `internal/gitea` | `TestEnsureReleaseCreatesMissingPageFromCommittedNote`, `TestInspectAssetsDetectsSameNameAndSizeWithDifferentBytes`, `TestUploadMissingPartialFailureThenRerunOnlyMissingAssets` |
|
||||||
|
| CLI profiles and prepared Woodpecker sequences | `cmd/releasekit`, `cmd/releasekit/internal/cli`, `examples/woodpecker/`, `examples/multi-module/` | `TestLoadSettingsRejectsInvalidProfiles`, `TestWoodpeckerTagDeliveryTemplate`, `TestWoodpeckerTagDeliveryUsesTaggedModuleVersion`, `TestWoodpeckerSourceDeliveryTemplateSelfBootstraps`, `TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout`, `TestMultiModuleSelectorMapsSelectorsAndTags`, `TestMultiModuleLauncherUsesSelectedModuleAndProfile`, `TestMultiModuleWoodpeckerDelivery` |
|
||||||
|
|
||||||
|
Run the complete suite with `go test ./...`. The public API and import boundary
|
||||||
|
check is `go run ./internal/apicheck`. Local HTTP and Git fixtures exercise
|
||||||
|
publication and delivery without real credentials or a hosted service.
|
||||||
|
|
||||||
|
## Integration references
|
||||||
|
|
||||||
|
The [Gitea integration guide](../integrations/gitea.md) owns the HTTP contract
|
||||||
|
and hosted response handling. The [Woodpecker examples](../../examples/woodpecker/)
|
||||||
|
are prepared integrations; their YAML is not active in this repository, and no
|
||||||
|
live Woodpecker runner, configured secret, or hosted delivery has been used.
|
||||||
182
docs/internal/validation.md
Normal file
182
docs/internal/validation.md
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
# Shared validation mechanics
|
||||||
|
|
||||||
|
`internal/validation` owns reusable checks for one captured candidate.
|
||||||
|
`internal/candidate` captures the clean source revision and keeps the
|
||||||
|
validation sequence shared by local checking and publication. It calls the
|
||||||
|
shared executor, runs product-specific `AdditionalChecks` once, and owns the
|
||||||
|
post-validation build callback and local-state recheck. `internal/publish`
|
||||||
|
adds its endpoint guards, tag creation, push, and recovery around that same
|
||||||
|
candidate path.
|
||||||
|
|
||||||
|
The executor runs one offline Go suite from the captured module directory,
|
||||||
|
optionally with the race detector when selected. When full vet is selected, it
|
||||||
|
disables test-time vet for that suite and runs native
|
||||||
|
`go vet -mod=readonly ./...` from the same directory after the suite succeeds.
|
||||||
|
It then runs `go build -mod=readonly -o <os.DevNull> ./...` there in static mode
|
||||||
|
for each selected package-compilation target, preserving target order and
|
||||||
|
stopping on the first failure. This compiles source without producing an
|
||||||
|
artifact or executing a target binary. Test, vet, and package-compilation
|
||||||
|
failures retain their `go-test`, `go-vet`, and `package-compile` identities,
|
||||||
|
selected target where applicable, and underlying causes. Its
|
||||||
|
request carries the captured repository directory and commit, output writer,
|
||||||
|
and internal settings. When selected, the Go-format check loads the candidate
|
||||||
|
tree once, reads regular Go blobs from the captured commit, and compares them
|
||||||
|
with go/format output. It uses the selected inputs, including vendor and explicit
|
||||||
|
shared files, and skips
|
||||||
|
symlink blobs, reports all unformatted paths, and stops with a contextual cause
|
||||||
|
on parse or inspection errors. It runs before product checks and build callbacks.
|
||||||
|
`Request.ReadCandidateTree` lets selected file checks request candidate
|
||||||
|
contents; the Go-only path does not enumerate the tree.
|
||||||
|
|
||||||
|
## Selected validation inputs
|
||||||
|
|
||||||
|
`CandidateTree` keeps the full committed repository lookup separate from the
|
||||||
|
ordered file input set. The selected module's committed inputs
|
||||||
|
exclude independently released nested modules, while vendored contents stay
|
||||||
|
in scope. Selection indexes boundary directories once and checks each entry's
|
||||||
|
ancestors, so unrelated boundaries are not scanned for each file. The
|
||||||
|
[scope benchmark](../../internal/validation/scope_performance_test.go) varies
|
||||||
|
boundary count while retaining 20,000 input files.
|
||||||
|
Explicit shared-file selections are normalized from repository-root
|
||||||
|
paths, added as individual files, and deduplicated with module inputs by path.
|
||||||
|
File-size exclusions are normalized from the selected module directory. Link
|
||||||
|
resolution can still inspect a committed destination outside the selected input
|
||||||
|
set without adding that destination's content to the checks. The public
|
||||||
|
selection, nil/empty behavior, and profile path bases belong to the
|
||||||
|
[configuration reference](../config.md) and the root facade's GoDoc.
|
||||||
|
|
||||||
|
The workspace-file check uses that same candidate inventory and reports blob
|
||||||
|
entries named go.work or go.work.sum, including nested paths and symlink blobs.
|
||||||
|
It does not read workspace contents or depend on the workspace selected for Go
|
||||||
|
commands.
|
||||||
|
The local-replacement check parses selected go.mod blobs with
|
||||||
|
`golang.org/x/mod/modfile`, including vendor and explicitly shared declarations.
|
||||||
|
It follows committed symlink declarations through the captured tree and fails
|
||||||
|
with an inspection cause when their selected contents are unavailable. A
|
||||||
|
replacement with no parsed version is reported with its go.mod path, line,
|
||||||
|
directive, and target; versioned replacements are allowed. It runs after the
|
||||||
|
workspace-file check using the same candidate inventory. Resolved module bodies
|
||||||
|
are parsed once per blob object ID; only owned filesystem-replacement targets
|
||||||
|
and line numbers remain cached. Each declaration path receives findings from
|
||||||
|
that summary in its own path context.
|
||||||
|
The optional file-size check applies normalized literal file/directory
|
||||||
|
exclusions with path-boundary matching, then requests local Git sizes for the
|
||||||
|
remaining selected blobs. Sizes include symlink link-text bytes; gitlinks are
|
||||||
|
omitted. The check returns the first oversized path with `FileSizeMeasurement`.
|
||||||
|
The optional Markdown check follows file-size inspection and uses the same
|
||||||
|
candidate tree. It parses regular Markdown blobs, resolves local destinations,
|
||||||
|
and checks supported anchors; outside-checkout and submodule observations are
|
||||||
|
written to the shared output writer. A nil writer keeps library use quiet.
|
||||||
|
`CandidateTree` enumerates full repository path, type, mode, and object metadata
|
||||||
|
without requiring blob contents or sizes. Checks acquire sizes and bytes for
|
||||||
|
their selected inputs and required references. Unreferenced blobs in excluded
|
||||||
|
modules remain outside those reads. Destinations resolve without consulting
|
||||||
|
the worktree or neighboring files. Each tree owns one lazy Git blob reader;
|
||||||
|
direct tree users must close it when finished. The shared validation executor
|
||||||
|
closes its tree on every return before product checks or build callbacks run.
|
||||||
|
A metadata-only selection never starts the reader. Per-read contexts cancel
|
||||||
|
an in-flight blob exchange. The context supplied when creating the tree governs
|
||||||
|
the reader lifetime, including shutdown and child reaping.
|
||||||
|
Regular-file reads return independent caller-owned byte slices and are not
|
||||||
|
retained by the tree. Symlink targets are retained as immutable owned strings
|
||||||
|
by blob object ID; explicitly reading a symlink still returns independent
|
||||||
|
bytes. The Go-format check caches only whether each successfully inspected
|
||||||
|
object is formatted, then reports every unformatted path that refers to it.
|
||||||
|
|
||||||
|
The internal Markdown parser uses Goldmark to record inline, reference, and
|
||||||
|
autolinks, images, titles, and their source use sites, and to build heading
|
||||||
|
anchors from visible AST text. It supports ATX and Setext headings, decodes
|
||||||
|
Markdown text through the parser, and assigns collision-free numeric suffixes
|
||||||
|
to repeated anchors. Link locations use one-based line and byte-column values.
|
||||||
|
The Markdown cache shares parsed records and anchors by regular blob object ID,
|
||||||
|
with a path lookup for callers. Retained destinations and titles own their
|
||||||
|
string storage, and parsed records contain content-relative locations only.
|
||||||
|
|
||||||
|
`checkMarkdownLinks` examines regular `.md` blobs from the captured tree. It
|
||||||
|
skips schemed and protocol-relative URIs, strips query components, and decodes
|
||||||
|
percent escapes once in local paths and fragments. It resolves destinations
|
||||||
|
through `CandidateTree.ResolveDestination` relative to the current source path;
|
||||||
|
decoded fragments are compared in lowercase against anchors from the resolved
|
||||||
|
regular Markdown document. Missing
|
||||||
|
paths, symlink cycles, and missing anchors produce `markdown-links` findings at
|
||||||
|
the source use site. Outside-checkout links produce out-of-scope observations by
|
||||||
|
default and findings when boundary enforcement is selected. Submodule-content
|
||||||
|
observations remain out of scope under either setting. Observations go to the
|
||||||
|
provided writer; a nil writer keeps library use quiet. Public selection is
|
||||||
|
defined in the [configuration reference](../config.md) and GoDoc.
|
||||||
|
|
||||||
|
Committed-tree metadata and blob reads disable lazy fetching and Git transports
|
||||||
|
for those child commands. Missing local objects produce inspection errors;
|
||||||
|
source preparation retains its separate network-capable operations. See Git's
|
||||||
|
[lazy-fetch controls](https://git-scm.com/docs/git) for the command mechanism.
|
||||||
|
Candidate and delivery release-note reads use the same local object boundary.
|
||||||
|
|
||||||
|
Public validation errors convert their diagnostic fields to the internal
|
||||||
|
failure model for shared formatting. Converted failures retain their original
|
||||||
|
contextual cause and reuse its rendering when it already contains the same
|
||||||
|
diagnostics. The CLI presents the complete error chain, including candidate
|
||||||
|
context around callback-supplied diagnostics.
|
||||||
|
|
||||||
|
## Adding a shared check
|
||||||
|
|
||||||
|
When an optional check is accepted for implementation:
|
||||||
|
|
||||||
|
1. Define its typed Go setting in the root facade and its equivalent CLI-owned
|
||||||
|
JSON field. Specify zero-value and omitted-profile behavior in GoDoc and the
|
||||||
|
configuration reference. Keep future settings in the roadmap until their
|
||||||
|
check is implemented.
|
||||||
|
2. Add the corresponding internal setting and explicit conversions. Use the
|
||||||
|
same root request conversion for `Check` and `Publish`, and the shared CLI
|
||||||
|
request conversion for profile-based candidate commands.
|
||||||
|
3. Implement a plain check function owned by `internal/validation`. Keep its
|
||||||
|
rule semantics in the capability owner and pass only the captured candidate
|
||||||
|
inputs it needs. A file-oriented check can call `Request.ReadCandidateTree`
|
||||||
|
and read only the blobs it inspects.
|
||||||
|
4. Return an internal `*Failure` with the check identity, repository-relative
|
||||||
|
findings, useful locations where available, and the underlying cause. Let
|
||||||
|
the root facade convert those records to its own diagnostic types. Preserve
|
||||||
|
cancellation and process errors through `Unwrap`.
|
||||||
|
5. Add the check to the shared executor at the ordering point selected by its
|
||||||
|
capability. Stop on failure. Keep product assertions in `AdditionalChecks`
|
||||||
|
and profile `checks`; keep artifact building in `internal/build`.
|
||||||
|
6. Cover observable behavior through both the Go facade and profile path when
|
||||||
|
both are supported. Check default behavior, useful findings, cause
|
||||||
|
preservation, cancellation where relevant, and failure stopping. Reuse the
|
||||||
|
existing local Git and CLI fixtures.
|
||||||
|
7. Update only the canonical owners for behavior that has landed: GoDoc for the
|
||||||
|
API, configuration and CLI references for profile behavior, and this
|
||||||
|
inventory for internal ownership. Record proposed checks under
|
||||||
|
`docs/roadmap/`.
|
||||||
|
|
||||||
|
Do not add a public validator registration interface. The public specification
|
||||||
|
selects ReleaseKit-owned checks; `AdditionalChecks` remains the extension point
|
||||||
|
for product behavior.
|
||||||
|
|
||||||
|
## Go command environment reuse
|
||||||
|
|
||||||
|
The current executor uses the [shared Go command environment](gotool.md) for
|
||||||
|
its offline suite, vet pass, and selected-target package compilation.
|
||||||
|
|
||||||
|
Reuse `internal/gotool` for native and static environments and target handling.
|
||||||
|
Keep toolchain and module-cache discovery in `gotool`; do not reproduce its
|
||||||
|
environment logic in a checker. Artifact output names, version injection,
|
||||||
|
native smoke checks, and artifact digests remain owned by `internal/build`.
|
||||||
|
|
||||||
|
## File-check coordination
|
||||||
|
|
||||||
|
File checks consume the captured tree and return findings to the shared error
|
||||||
|
model. They do not read sibling worktrees or follow live symlink targets.
|
||||||
|
`CandidateTree.ResolveDestination` returns data describing entries,
|
||||||
|
directories, missing paths, checkout boundaries, submodule paths, and symlink
|
||||||
|
cycles; the caller selects which observations fail validation or are reported
|
||||||
|
as out of scope.
|
||||||
|
|
||||||
|
The shared Git path resolver walks committed components and symlink targets
|
||||||
|
in order using the tree's indexed metadata and lazy symlink reader. Active
|
||||||
|
symlink expansion detects cycles, and traversal honors cancellation. Absolute
|
||||||
|
destinations and symlink targets within the repository directory map back to
|
||||||
|
candidate-relative paths; existence still comes from committed entries.
|
||||||
|
|
||||||
|
The public selection is owned by the facade and profile;
|
||||||
|
the internal checker uses the committed-file and destination-resolution
|
||||||
|
primitives described here.
|
||||||
49
docs/oss/attribution.md
Normal file
49
docs/oss/attribution.md
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
# Open Source Attribution Notices
|
||||||
|
|
||||||
|
## Go Authors
|
||||||
|
|
||||||
|
Selected module: `golang.org/x/mod` at `v0.40.0`.
|
||||||
|
|
||||||
|
Copyright 2009 The Go Authors.
|
||||||
|
|
||||||
|
SPDX-License-Identifier: BSD-3-Clause
|
||||||
|
|
||||||
|
License and notices: [BSD 3-Clause](licenses/BSD-3-Clause.txt) | [LICENSE](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f/LICENSE).
|
||||||
|
|
||||||
|
[Source](https://go.googlesource.com/mod/+/d3398d06de5fa5c71083d3d1c26f2cda73508e0f).
|
||||||
|
|
||||||
|
## Goldmark
|
||||||
|
|
||||||
|
Selected module: `github.com/yuin/goldmark/v2` at `v2.1.6`.
|
||||||
|
|
||||||
|
Copyright (c) 2019 Yusuke Inuzuka.
|
||||||
|
|
||||||
|
SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
License and notices: [MIT](licenses/MIT.txt) |
|
||||||
|
[LICENSE](https://github.com/yuin/goldmark/blob/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c/LICENSE).
|
||||||
|
|
||||||
|
[Source](https://github.com/yuin/goldmark/tree/a8d4ee5a0bd7d5493fdd1e339b4e75df92f8684c).
|
||||||
|
|
||||||
|
## Standard Repository Policies
|
||||||
|
|
||||||
|
Material: policy documents under `docs/policy/`, the root `AGENTS.md` orientation,
|
||||||
|
and the Policy Reading Guide in `docs/development.md`, adapted for this repository.
|
||||||
|
The release policy incorporates revision `e833faddf120c789a9b45348edaf75720de16348`;
|
||||||
|
the remaining material incorporates revision
|
||||||
|
`d84a38ebab26f048cafbe59a2246700c35d29843`.
|
||||||
|
|
||||||
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
|
SPDX-License-Identifier: CC-BY-SA-4.0
|
||||||
|
|
||||||
|
License and notices: [CC BY-SA 4.0](licenses/CC-BY-SA-4.0.txt) |
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/LICENSE).
|
||||||
|
|
||||||
|
Release-policy notices:
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/LICENSE).
|
||||||
|
|
||||||
|
[Release-policy source](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/docs/policy/release.md) |
|
||||||
|
[Other policy material source](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843).
|
||||||
27
docs/oss/licenses/BSD-3-Clause.txt
Normal file
27
docs/oss/licenses/BSD-3-Clause.txt
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
Copyright 2009 The Go Authors.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are
|
||||||
|
met:
|
||||||
|
|
||||||
|
* Redistributions of source code must retain the above copyright
|
||||||
|
notice, this list of conditions and the following disclaimer.
|
||||||
|
* Redistributions in binary form must reproduce the above
|
||||||
|
copyright notice, this list of conditions and the following disclaimer
|
||||||
|
in the documentation and/or other materials provided with the
|
||||||
|
distribution.
|
||||||
|
* Neither the name of Google LLC nor the names of its
|
||||||
|
contributors may be used to endorse or promote products derived from
|
||||||
|
this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||||
|
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||||
|
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||||
|
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||||
|
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||||
|
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||||
|
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||||
|
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
170
docs/oss/licenses/CC-BY-SA-4.0.txt
Normal file
170
docs/oss/licenses/CC-BY-SA-4.0.txt
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
Creative Commons Attribution-ShareAlike 4.0 International
|
||||||
|
|
||||||
|
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
|
||||||
|
|
||||||
|
Using Creative Commons Public Licenses
|
||||||
|
|
||||||
|
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
||||||
|
|
||||||
|
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
|
||||||
|
|
||||||
|
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described.
|
||||||
|
|
||||||
|
Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
|
||||||
|
|
||||||
|
Creative Commons Attribution-ShareAlike 4.0 International Public License
|
||||||
|
|
||||||
|
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
||||||
|
|
||||||
|
Section 1 – Definitions.
|
||||||
|
|
||||||
|
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
||||||
|
|
||||||
|
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
||||||
|
|
||||||
|
c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
|
||||||
|
|
||||||
|
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
||||||
|
|
||||||
|
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
||||||
|
|
||||||
|
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
||||||
|
|
||||||
|
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
|
||||||
|
|
||||||
|
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
||||||
|
|
||||||
|
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
||||||
|
|
||||||
|
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
|
||||||
|
|
||||||
|
k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
||||||
|
|
||||||
|
l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
||||||
|
|
||||||
|
m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
||||||
|
|
||||||
|
Section 2 – Scope.
|
||||||
|
|
||||||
|
a. License grant.
|
||||||
|
|
||||||
|
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
||||||
|
|
||||||
|
A. reproduce and Share the Licensed Material, in whole or in part; and
|
||||||
|
|
||||||
|
B. produce, reproduce, and Share Adapted Material.
|
||||||
|
|
||||||
|
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
||||||
|
|
||||||
|
3. Term. The term of this Public License is specified in Section 6(a).
|
||||||
|
|
||||||
|
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
||||||
|
|
||||||
|
5. Downstream recipients.
|
||||||
|
|
||||||
|
A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
||||||
|
|
||||||
|
B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.
|
||||||
|
|
||||||
|
C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
||||||
|
|
||||||
|
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
||||||
|
|
||||||
|
b. Other rights.
|
||||||
|
|
||||||
|
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
||||||
|
|
||||||
|
2. Patent and trademark rights are not licensed under this Public License.
|
||||||
|
|
||||||
|
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
|
||||||
|
|
||||||
|
Section 3 – License Conditions.
|
||||||
|
|
||||||
|
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
||||||
|
|
||||||
|
a. Attribution.
|
||||||
|
|
||||||
|
1. If You Share the Licensed Material (including in modified form), You must:
|
||||||
|
|
||||||
|
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
||||||
|
|
||||||
|
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
||||||
|
|
||||||
|
ii. a copyright notice;
|
||||||
|
|
||||||
|
iii. a notice that refers to this Public License;
|
||||||
|
|
||||||
|
iv. a notice that refers to the disclaimer of warranties;
|
||||||
|
|
||||||
|
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
||||||
|
|
||||||
|
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
||||||
|
|
||||||
|
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
||||||
|
|
||||||
|
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
||||||
|
|
||||||
|
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
||||||
|
|
||||||
|
b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
|
||||||
|
|
||||||
|
1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
|
||||||
|
|
||||||
|
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
|
||||||
|
|
||||||
|
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
|
||||||
|
|
||||||
|
Section 4 – Sui Generis Database Rights.
|
||||||
|
|
||||||
|
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
||||||
|
|
||||||
|
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
|
||||||
|
|
||||||
|
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
|
||||||
|
|
||||||
|
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
||||||
|
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
||||||
|
|
||||||
|
Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
||||||
|
|
||||||
|
a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
|
||||||
|
|
||||||
|
b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
|
||||||
|
|
||||||
|
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
||||||
|
|
||||||
|
Section 6 – Term and Termination.
|
||||||
|
|
||||||
|
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
||||||
|
|
||||||
|
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
||||||
|
|
||||||
|
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
||||||
|
|
||||||
|
2. upon express reinstatement by the Licensor.
|
||||||
|
|
||||||
|
c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
||||||
|
|
||||||
|
d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
||||||
|
|
||||||
|
e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
||||||
|
|
||||||
|
Section 7 – Other Terms and Conditions.
|
||||||
|
|
||||||
|
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
||||||
|
|
||||||
|
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
||||||
|
|
||||||
|
Section 8 – Interpretation.
|
||||||
|
|
||||||
|
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
||||||
|
|
||||||
|
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
||||||
|
|
||||||
|
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
||||||
|
|
||||||
|
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
||||||
|
|
||||||
|
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
|
||||||
|
|
||||||
|
Creative Commons may be contacted at creativecommons.org.
|
||||||
21
docs/oss/licenses/MIT.txt
Normal file
21
docs/oss/licenses/MIT.txt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2019 Yusuke Inuzuka
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
90
docs/policy/agents.md
Normal file
90
docs/policy/agents.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# Agent Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.3
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-05
|
||||||
|
|
||||||
|
**Upstream Source:** [agents.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/agents.md)
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Agents must read and follow these rules.
|
||||||
|
|
||||||
|
## Implementation Discipline
|
||||||
|
|
||||||
|
**KEY PRINCIPLES:** Write the simplest idiomatic code that satisfies the user's
|
||||||
|
request. Do not implicitly strengthen requirements, restrictions, or guarantees
|
||||||
|
beyond what the user actually requested.
|
||||||
|
|
||||||
|
**Keep implementation machinery proportionate.** Use straightforward,
|
||||||
|
idiomatic code and introduce only the machinery needed to support the requested
|
||||||
|
behavior and flexibility. Optimize for conceptual simplicity and
|
||||||
|
maintainability, not for the fewest lines, fewest options, or narrowest product
|
||||||
|
surface.
|
||||||
|
|
||||||
|
**Do not invent restrictions.** Do not reject, prohibit, constrain, cap,
|
||||||
|
harden, or otherwise narrow behavior unless required by the user, an explicit
|
||||||
|
repository contract, or an unavoidable correctness constraint. Preserve
|
||||||
|
operator and caller choice where policy has not been established. If an
|
||||||
|
additional restriction appears advisable, present it as a decision rather than
|
||||||
|
silently implementing it.
|
||||||
|
|
||||||
|
A correctness constraint must follow from the requested behavior or an
|
||||||
|
established invariant, not from the convenience of the chosen implementation.
|
||||||
|
Explain the specific failure it prevents and why a less restrictive
|
||||||
|
implementation cannot satisfy the contract.
|
||||||
|
|
||||||
|
**Do not invent guarantees.** Do not strengthen public contracts, guarantees,
|
||||||
|
or invariants beyond those expressly requested by the user.
|
||||||
|
|
||||||
|
**Use the standard library.** For example: in almost every case, the best
|
||||||
|
approach to copying files is to use the standard library. Writing custom code to
|
||||||
|
implement power-loss protection at the application level, or to guard against
|
||||||
|
bad actors with privileged and concurrent access to the host's filesystem,
|
||||||
|
is wasteful, unnecessary, and not idiomatic. Stick to the simple, standard, and
|
||||||
|
idiomatic approach unless another path is expressly requested by the user.
|
||||||
|
|
||||||
|
**An implementation detail is not repository policy.** Tests and documentation
|
||||||
|
must not elevate incidental behavior into a durable guarantee or restriction
|
||||||
|
unless that behavior was expressly selected as part of the contract.
|
||||||
|
|
||||||
|
Existing explicit contracts remain authoritative. Changing one requires a
|
||||||
|
deliberate decision. Agent-authored plans, tests, documentation, and prior
|
||||||
|
implementations do not independently establish additional contracts. Identify
|
||||||
|
the authorizing requirement or decision; when that authority is unclear, surface
|
||||||
|
the ambiguity rather than treating repetition as approval.
|
||||||
|
|
||||||
|
## Git Commit Policy
|
||||||
|
|
||||||
|
By default, commit each completed, nonempty unit of work using a
|
||||||
|
concise, plain-English message describing what changed. This policy is standing
|
||||||
|
authorization to create those local commits; a separate user request is not
|
||||||
|
required. An explicit user instruction to leave work uncommitted takes precedence.
|
||||||
|
|
||||||
|
A unit of work is a focused, reviewable outcome, including its relevant tests and
|
||||||
|
documentation.
|
||||||
|
Complete the appropriate validation before committing. If work is incomplete or
|
||||||
|
validation is blocked, report that state accurately.
|
||||||
|
|
||||||
|
Before committing:
|
||||||
|
|
||||||
|
1. Run `git status --short` and review the relevant diff, including any staged
|
||||||
|
changes. Identify changes that predate the current unit of work.
|
||||||
|
2. Exclude secrets, local environment files, generated junk, and unrelated changes.
|
||||||
|
3. Stage only the files or hunks belonging to the completed unit. Use `git add .`
|
||||||
|
only when every included change belongs to that unit. Preserve unrelated
|
||||||
|
staged and unstaged work.
|
||||||
|
4. Review `git diff --staged` and run appropriate checks for the change. Reuse
|
||||||
|
successful checks for unchanged content.
|
||||||
|
5. Review `git log --oneline -n 10` and use
|
||||||
|
`git commit -m "<concise plain-English commit message>"`.
|
||||||
|
6. Report the commit identifier and any remaining uncommitted work.
|
||||||
|
|
||||||
|
If the unit cannot be safely separated from pre-existing work, leave it uncommitted
|
||||||
|
and explain the overlap rather than silently including that work. If a commit
|
||||||
|
fails, preserve the changes and report the failure; do not bypass hooks.
|
||||||
|
|
||||||
|
Default commit authorization does not authorize pushing, publishing, amending,
|
||||||
|
resetting, reverting, or rewriting history. Those actions require a separate user
|
||||||
|
instruction. Do not use `git commit -a` or `git commit --no-verify` to bypass the
|
||||||
|
staging and validation discipline above.
|
||||||
121
docs/policy/architecture.md
Normal file
121
docs/policy/architecture.md
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
# Architecture Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.3
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-06
|
||||||
|
|
||||||
|
**Upstream Source:** [architecture.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/architecture.md)
|
||||||
|
|
||||||
|
## Purpose And Ownership
|
||||||
|
|
||||||
|
ReleaseKit is an opinionated Go library and release executable for common
|
||||||
|
publication, builds, version injection, and delivery. This policy owns
|
||||||
|
responsibility boundaries, dependency direction, and adopted constraints for
|
||||||
|
development. Roadmaps own proposed capabilities, implementation status, and
|
||||||
|
sequencing.
|
||||||
|
|
||||||
|
The [internal documentation](../internal/overview.md) owns concrete package
|
||||||
|
inventory and implementation mechanics. Canonical public contracts own exact
|
||||||
|
behavior; ADRs record decision rationale.
|
||||||
|
|
||||||
|
## Adopted Constraints And Implemented Structure
|
||||||
|
|
||||||
|
Architectural constraints govern current and future development and reflect
|
||||||
|
deliberately selected requirements and decisions. Current architecture describes
|
||||||
|
implemented structure. Roadmaps record proposals, implementation status, and
|
||||||
|
sequencing; ADRs record significant decisions and rationale. Internal
|
||||||
|
implementation choices evolve within these constraints.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
Evaluate ReleaseKit development and adoption against both criteria:
|
||||||
|
|
||||||
|
1. Applications delete substantial release infrastructure while retaining clear
|
||||||
|
ownership of product-specific checks and compatibility decisions.
|
||||||
|
2. Consumers adopt one coherent set of deliberately selected release conventions.
|
||||||
|
|
||||||
|
Consumer implementations supply evidence of needs. ReleaseKit selects a common
|
||||||
|
model and enough flexibility to express genuine product requirements. API
|
||||||
|
designs should demonstrate reduced consumer infrastructure and consistent
|
||||||
|
conventions through representative consumers.
|
||||||
|
|
||||||
|
## Responsibility Boundaries
|
||||||
|
|
||||||
|
ReleaseKit owns the mechanics of selected publication, version injection,
|
||||||
|
cross-build, and delivery conventions. Applications supply product identity,
|
||||||
|
their main package, selected build targets, application-specific candidate
|
||||||
|
checks, and delivery declarations. Applications own their compatibility
|
||||||
|
decisions and adaptation of version output to the supported runtime accessor.
|
||||||
|
|
||||||
|
The release executable invokes the supported orchestration facade and owns
|
||||||
|
argument parsing, output, and exit codes. Library operations return meaningful
|
||||||
|
errors and outcomes, including partial progress and uncertain publication state.
|
||||||
|
Consumers map those values to their own user interfaces.
|
||||||
|
|
||||||
|
ReleaseKit builds and tests independently of consuming repositories. Production
|
||||||
|
dependencies use supported public contracts available independently of consumer
|
||||||
|
checkouts. Committed module and workspace configuration supports independent
|
||||||
|
builds; temporary local development configuration remains local.
|
||||||
|
|
||||||
|
## Public Facades And Dependency Direction
|
||||||
|
|
||||||
|
[ADR 0001](../adr/0001-public-facade.md) records the accepted decision for the root
|
||||||
|
`releasekit` orchestration facade and separate `buildinfo` runtime facade.
|
||||||
|
Both belong to one Go module and share its versioning and compatibility
|
||||||
|
obligations. Each facade exposes a cohesive consumer contract.
|
||||||
|
|
||||||
|
Public named types belong to their facade. Exported signatures, fields,
|
||||||
|
callbacks, and method sets use facade-owned types and deliberately selected
|
||||||
|
public dependencies. Handles retain private implementation state, with explicit
|
||||||
|
forwarding and conversions preserving supported identity, ownership, error
|
||||||
|
semantics, and callback lifetime.
|
||||||
|
|
||||||
|
Implementation packages live under Go's `internal/` boundary. Dependencies run
|
||||||
|
from facades into internal implementation; internal production packages depend
|
||||||
|
on internal contracts. Git operations, Go toolchain execution, Gitea integration,
|
||||||
|
and orchestration bookkeeping belong behind that boundary. Additional public
|
||||||
|
packages and extension interfaces require a deliberate decision grounded in a
|
||||||
|
durable consumer need.
|
||||||
|
|
||||||
|
Go declarations and GoDoc own exact API contracts. Compiled-export checks,
|
||||||
|
dependency checks, and external-package behavioral tests protect the selected
|
||||||
|
facade boundaries.
|
||||||
|
|
||||||
|
## Runtime Version Boundary
|
||||||
|
|
||||||
|
The `buildinfo` public API exposes runtime information justified by
|
||||||
|
consumer needs. Its implementation uses the standard library and a small
|
||||||
|
internal dependency graph independent of release orchestration. Applications
|
||||||
|
read their embedded version through its supported accessor.
|
||||||
|
|
||||||
|
The builder and runtime implementation own the linker symbol and injection
|
||||||
|
mechanism together. Dependency checks protect the runtime boundary;
|
||||||
|
build-and-run integration tests verify that the builder injects the selected
|
||||||
|
version and the public accessor reports it correctly.
|
||||||
|
|
||||||
|
## External Effects
|
||||||
|
|
||||||
|
Keep Git, filesystem, Go toolchain, and Gitea effects behind proportionate
|
||||||
|
internal boundaries and perform them through explicit operations. Select
|
||||||
|
interfaces and package layout for actual responsibilities and testability.
|
||||||
|
The library owns reusable outcomes and failure handling; the executable owns
|
||||||
|
presentation and process exits.
|
||||||
|
|
||||||
|
Source publication and asynchronous delivery have distinct outcomes. The
|
||||||
|
[release policy](release.md) governs releases of ReleaseKit itself. Go
|
||||||
|
declarations and GoDoc define supported consumer API contracts;
|
||||||
|
[consumer guides](../consumers/) explain their use, and
|
||||||
|
[integration guides](../integrations/) define external formats and protocols.
|
||||||
|
Roadmaps record planned capabilities and implementation status.
|
||||||
|
|
||||||
|
## Trust Boundaries And Threat Scope
|
||||||
|
|
||||||
|
Base defenses and guarantees on selected requirements. Candidate validation,
|
||||||
|
remote-state changes, transport failures, and partial delivery receive explicit
|
||||||
|
handling. Additional threat scenarios require a deliberate scope decision under
|
||||||
|
the [agent policy](agents.md).
|
||||||
|
|
||||||
|
Public API, [configuration](../config.md), and integration contracts own
|
||||||
|
credential supply and observable handling. Internal documents own the mechanisms.
|
||||||
|
Tests use local collaborators and controlled failures as specified by the
|
||||||
|
[testing policy](testing.md).
|
||||||
176
docs/policy/documentation.md
Normal file
176
docs/policy/documentation.md
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
# Documentation Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.11
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-05
|
||||||
|
|
||||||
|
**Upstream Source:** [documentation.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/documentation.md)
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
This policy assigns each documentation topic to one canonical owner. Its goal is
|
||||||
|
to keep ReleaseKit's documentation accurate, concise, discoverable, and resistant
|
||||||
|
to drift for consumers, maintainers, developers, and coding agents.
|
||||||
|
|
||||||
|
## Core Rules
|
||||||
|
|
||||||
|
### One Canonical Owner
|
||||||
|
|
||||||
|
Each authoritative fact belongs in one document. A non-owning document may give
|
||||||
|
a short, stable summary for orientation, but it must link to the canonical owner
|
||||||
|
for volatile details.
|
||||||
|
|
||||||
|
Volatile details include commands, flags, configuration fields and defaults,
|
||||||
|
module keys, schemas, file names, paths, status codes, retry behavior, and
|
||||||
|
runtime guarantees. If readers could reasonably treat a statement as a
|
||||||
|
contract, maintain it only in the owning document.
|
||||||
|
|
||||||
|
### Current And Future Behavior
|
||||||
|
|
||||||
|
Outside `docs/roadmap/`, documentation describes implemented behavior only.
|
||||||
|
Partial features may be described only to their implemented boundary.
|
||||||
|
|
||||||
|
Architectural constraints may govern future changes. Describe current structure
|
||||||
|
from implemented behavior.
|
||||||
|
|
||||||
|
ADRs may record an accepted architectural decision before implementation. The
|
||||||
|
roadmap owns implementation status and sequencing until the decision is
|
||||||
|
implemented. Current architecture, user, operator, integration, and internal
|
||||||
|
documentation are updated when the behavior lands.
|
||||||
|
|
||||||
|
### Audience And Detail
|
||||||
|
|
||||||
|
Write for the document's stated audience and include only the detail needed for
|
||||||
|
its owned topic. Keep user and operator docs focused on using and operating the
|
||||||
|
application. Developer docs should link to user-facing and external contracts
|
||||||
|
for their definitions.
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
Complete copyable files belong in `examples/`. Documentation may use the
|
||||||
|
smallest illustrative snippet needed to explain its owned topic, but should link
|
||||||
|
to maintained examples for complete copyable files.
|
||||||
|
|
||||||
|
Examples must be valid, secret-free, and tested where practical. Commands and
|
||||||
|
configuration used in documentation should match the application.
|
||||||
|
|
||||||
|
### Security And Privacy
|
||||||
|
|
||||||
|
Documentation and examples must not contain real credentials, private keys,
|
||||||
|
private environment dumps, sensitive source material, or private infrastructure
|
||||||
|
details unless intentionally public. Document secret-handling mechanisms, not
|
||||||
|
secret values.
|
||||||
|
|
||||||
|
## Canonical Ownership
|
||||||
|
|
||||||
|
| Topic | Canonical owner | Owned content | Content owned elsewhere |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Product orientation and minimal example | `README.md` | Purpose, current status, shortest useful example when implemented, and navigation, including licensing and attribution. | Complete command reference, configuration reference, operational procedures, implementation detail. |
|
||||||
|
| Contributor entry point | `docs/development.md` | Task-oriented reading guide, contributor orientation, baseline validation commands, and canonical links. | Package inventory, architecture rules, subsystem behavior, detailed change recipes. |
|
||||||
|
| ReleaseKit architecture policy | `docs/policy/architecture.md` | System shape, normative ownership, dependency direction, boundaries, invariants, safety properties, and non-goals. | Concrete package inventory, implementation mechanics, contributor procedures, decision history, future work. |
|
||||||
|
| Policy-set provenance and upstream navigation | `docs/policy/meta.md` | Policy-set origin, local authority, adoption baselines, and upstream adoption and update links. | Task-specific reading triggers, detailed adoption procedures, and formal attribution notices. |
|
||||||
|
| Agent policy | `docs/policy/agents.md` | Proportionate, idiomatic implementation; rules against inventing requirements, restrictions, guarantees, or policy. | Application contracts, architecture, testing policy, and contributor procedures. |
|
||||||
|
| Documentation policy | `docs/policy/documentation.md` | Documentation ownership, audience boundaries, maintenance rules, and ADR/document lifecycle. | Application architecture or product behavior. |
|
||||||
|
| Testing policy | `docs/policy/testing.md` | Test philosophy, risk sufficiency, boundaries, doubles, coverage, regressions, and test maintenance. | Subsystem behavior, application contracts, subsystem-specific test inventories, and implementation plans. |
|
||||||
|
| Release policy | `docs/policy/release.md` | Versioning, compatibility, release integrity and immutability, release documentation, proportionate gates, publication controls, completion, and required versus optional checks. | Repository-specific commands, product installation guidance, CLI version semantics, historical release summaries, and CI implementation detail. |
|
||||||
|
| Open source licensing and attribution policy | `docs/policy/oss.md` | License defaults and author choices, COPYRIGHT and attribution formats, license/notice links, discoverability, maintenance, and concrete exceptions. | Component entries, license texts, release commands, and dependency security review. |
|
||||||
|
| Project copyright and license grant | `COPYRIGHT` | Project identity, copyright holders and years, SPDX expression, grant, separately licensed document scope, warranty disclaimer, and third-party statement. | Complete license texts and upstream component attribution. |
|
||||||
|
| Project license texts | `LICENSE` | Complete project and incorporated companion license texts, with required project-specific fields. | General licensing policy and upstream component attribution. |
|
||||||
|
| Upstream component attribution | `docs/oss/attribution.md` | House Format component entries: identity, material scope and modifications where applicable, copyright, license, required notices, and license, notice, and source links. | General attribution policy, exception reasoning, research narratives, compliance commentary, and complete standard license texts. |
|
||||||
|
| Standard license texts | `docs/oss/licenses/` | Complete, verbatim standard license texts shared by applicable entries, including copied documentation. | Project-specific upstream notices, attribution prose, and policy interpretation. |
|
||||||
|
| Repository-specific release procedure | `docs/release.md` | Maintainer prerequisites, candidate preparation, validation and publication commands and automated guards, asynchronous deliverables, delivery status, optional consumer verification, and recovery. | General release requirements, product installation guidance, historical release summaries, and current compatibility contracts. |
|
||||||
|
| CLI contract (if applicable) | `docs/cli.md` | Commands, arguments, flags, invocation semantics, and exit codes. | End-to-end operating procedures, configuration field definitions, runtime filesystem layout, module implementation details. |
|
||||||
|
| Configuration contract (if applicable) | `docs/config.md` | Discovery, precedence, fields, defaults, environment inputs, and validation for implemented configuration. | Complete example files, CLI syntax, runtime state lifecycle, implementation details. |
|
||||||
|
| Exported Go API (when implemented) | Go declarations and GoDoc | Exact symbol contracts, errors, ownership, and lifecycle semantics for each facade. | Consumer walkthroughs, CLI contracts, integration protocols, and internal mechanics. |
|
||||||
|
| Consumer guidance for the public Go API (if applicable) | `docs/consumers/` | Task-oriented public Go API usage, minimal examples, and consumer responsibilities. | HTTP wire semantics, external protocol contracts, internal implementation detail. |
|
||||||
|
| Integration contracts for external components (if applicable) | `docs/integrations/` | External formats and protocols, upstream and downstream contracts, logical output paths and schemas, media types, and compatibility. | Physical runtime placement and lifecycle, internal transformations, CLI syntax, configuration defaults. |
|
||||||
|
| Inventory of implemented internal packages | `docs/internal/overview.md` | Implemented packages and components, responsibilities, and links to focused internal docs. | Normative architecture, contributor reading policy, external contracts. |
|
||||||
|
| Behavior and architecture of internal packages | Other files under `docs/internal/` | Implementation flow, collaborators, state transitions, package-local guarantees and failures, and relevant tests. | Global architecture invariants, configuration definitions and defaults, external schemas, operator procedures. |
|
||||||
|
| Architectural decision records | `docs/adr/` | Significant decisions, context, alternatives, rationale, consequences, and supersession history. | Current behavior reference, implementation status, task sequencing. |
|
||||||
|
| Future work and implementation status | `docs/roadmap/` | Proposed, accepted, deferred, or rejected work; implementation status, sequencing, and task breakdowns. | Implemented behavior reference and architectural decision rationale. |
|
||||||
|
| Release-note history | `docs/releases/` | One checked-in summary per source release under the procedure; the note at its immutable tag is the release record. | Current commands, behavior, contracts, and compatibility definitions. |
|
||||||
|
| Complete copyable artifacts | `examples/` | Maintained configuration, inputs, and other copyable or runnable files. | Field-by-field reference, command reference, prose explanation. |
|
||||||
|
|
||||||
|
Create supporting documents for existing interfaces and responsibilities when
|
||||||
|
substantive content is available. The CLI, configuration, consumer, integration,
|
||||||
|
internal, example, and release-procedure owners become documents as their
|
||||||
|
corresponding implementation lands. Keep implementation status in the roadmap
|
||||||
|
and avoid empty owners.
|
||||||
|
|
||||||
|
## Boundary Rules
|
||||||
|
|
||||||
|
### Orientation
|
||||||
|
|
||||||
|
Link among orientation, architecture, and internal documents; maintain each
|
||||||
|
package or behavior description in its canonical owner.
|
||||||
|
|
||||||
|
### Go API, CLI, And Configuration
|
||||||
|
|
||||||
|
Go declarations and GoDoc own exact exported contracts. Consumer guidance
|
||||||
|
explains tasks and links to those declarations. CLI documentation owns invocation
|
||||||
|
and exit semantics; configuration documentation owns settings. Release procedures
|
||||||
|
own maintainer publication and recovery workflows. Link across those owners
|
||||||
|
when a task spans their boundaries.
|
||||||
|
|
||||||
|
### Releases
|
||||||
|
|
||||||
|
The release policy defines requirements and invariants that every release must
|
||||||
|
satisfy. The repository-specific release procedure defines the commands and
|
||||||
|
workflow maintainers use to satisfy that policy. Release notes record history
|
||||||
|
at immutable tags. Maintain current behavior in its canonical documentation,
|
||||||
|
update it with the corresponding behavior changes, and keep release procedures
|
||||||
|
consistent with adopted policy.
|
||||||
|
|
||||||
|
### Project Licensing And Upstream Attribution
|
||||||
|
|
||||||
|
README and release documents link to the canonical licensing and attribution
|
||||||
|
materials under the [OSS policy](oss.md). The release procedure owns URL
|
||||||
|
construction and publication mechanics.
|
||||||
|
|
||||||
|
### Contracts And Implementation
|
||||||
|
|
||||||
|
GoDoc, CLI, configuration, and integration documents define externally observable
|
||||||
|
shapes and semantics. Internal documents explain how ReleaseKit implements or
|
||||||
|
consumes those contracts. Internal docs may name a field, file, or protocol to
|
||||||
|
identify a dependency, but must link to its canonical contract for the definition.
|
||||||
|
|
||||||
|
### Security Topics
|
||||||
|
|
||||||
|
This policy owns what documentation and examples may contain. Architecture owns
|
||||||
|
selected security invariants. Public API, configuration, and integration
|
||||||
|
contracts own credential supply and observable handling. Internal docs own
|
||||||
|
implementation mechanisms only.
|
||||||
|
|
||||||
|
## Architecture Decision Records
|
||||||
|
|
||||||
|
Use sequentially numbered ADR filenames such as
|
||||||
|
`0001-record-architecture-decisions.md`. Follow the lightweight Nygard format:
|
||||||
|
|
||||||
|
1. title;
|
||||||
|
2. status;
|
||||||
|
3. date;
|
||||||
|
4. context;
|
||||||
|
5. decision;
|
||||||
|
6. alternatives considered;
|
||||||
|
7. consequences.
|
||||||
|
|
||||||
|
Treat the decision content of an accepted ADR as immutable. When a decision
|
||||||
|
changes, create a new ADR and update the earlier ADR's status to superseded.
|
||||||
|
Rejected architectural alternatives belong in the ADR; rejected product ideas
|
||||||
|
belong in the roadmap. Routine choices need no ADR.
|
||||||
|
|
||||||
|
## Maintenance
|
||||||
|
|
||||||
|
When behavior changes, update its canonical owner in the same change. If
|
||||||
|
ownership moves, remove the old definition and replace it with a link where
|
||||||
|
navigation remains useful.
|
||||||
|
|
||||||
|
Before completing documentation work:
|
||||||
|
|
||||||
|
- verify affected behavior and examples;
|
||||||
|
- check commands, flags, fields, defaults, schemas, and paths against their
|
||||||
|
implementation;
|
||||||
|
- keep unimplemented behavior in the roadmap, subject to the ADR exception;
|
||||||
|
- remove stale references and validate links;
|
||||||
|
- confirm that non-owning documents summarize and link rather than redefine;
|
||||||
|
- confirm that no secrets or sensitive private data were added.
|
||||||
27
docs/policy/meta.md
Normal file
27
docs/policy/meta.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# Policy Set Provenance
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.0
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-05
|
||||||
|
|
||||||
|
**Upstream Source:** [meta.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/meta.md)
|
||||||
|
|
||||||
|
## Origin And Local Authority
|
||||||
|
|
||||||
|
This repository's policy set is adapted from
|
||||||
|
[Standard Repository Policies](https://gitea.maximumdirect.net/eric/policy).
|
||||||
|
The adopted local policies govern work in this repository. Upstream revisions
|
||||||
|
become local policy through deliberate adoption, preserving local decisions.
|
||||||
|
Each policy's `Upstream Source` identifies its adopted baseline.
|
||||||
|
|
||||||
|
## Adoption And Updates
|
||||||
|
|
||||||
|
For policy adoption, upstream revision reviews, and updates, consult the
|
||||||
|
[upstream adoption and update guide](https://gitea.maximumdirect.net/eric/policy/src/branch/main/docs/adoption.md).
|
||||||
|
That guide and the reference example collection are maintained upstream and
|
||||||
|
accessed through links. Keep discovery links pointed at the current upstream
|
||||||
|
project and guide; keep adopted-source and example links pinned to commits.
|
||||||
|
|
||||||
|
The local [developer guide](../development.md) routes tasks to applicable
|
||||||
|
policies. Formal credit and licensing notices for the copied policy material
|
||||||
|
belong in the local [attribution document](../oss/attribution.md).
|
||||||
221
docs/policy/oss.md
Normal file
221
docs/policy/oss.md
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
# Open Source Licensing And Attribution Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.8
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-08
|
||||||
|
|
||||||
|
**Upstream Source:** [oss.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/oss.md)
|
||||||
|
|
||||||
|
## Purpose And Scope
|
||||||
|
|
||||||
|
This policy defines project licensing conventions and a repeatable House Format
|
||||||
|
for upstream attribution and license notices. It covers the project's own code
|
||||||
|
and upstream components incorporated into or distributed with the application
|
||||||
|
or library, including relevant transitive dependencies and copied code,
|
||||||
|
documentation, or assets.
|
||||||
|
Determine treatment from the component's terms and actual use.
|
||||||
|
|
||||||
|
Consulting development guidance or using tooling alone does not require an
|
||||||
|
attribution entry. Copying or adapting documentation for inclusion in the
|
||||||
|
repository is different: preserve its applicable attribution and license terms.
|
||||||
|
A material's role as development guidance does not exempt copied documents.
|
||||||
|
Apply any express permissions for attribution-free reuse of example formatting.
|
||||||
|
|
||||||
|
The baseline is a publicly available source repository with releases published
|
||||||
|
alongside it. The format is independent of language, forge, and build system.
|
||||||
|
It does not require attribution for every development tool, establish license
|
||||||
|
compatibility, or resolve every obligation arising from use or distribution.
|
||||||
|
|
||||||
|
## Canonical Locations
|
||||||
|
|
||||||
|
The [documentation policy](documentation.md) assigns ownership:
|
||||||
|
|
||||||
|
- `COPYRIGHT`: project name, copyright statements, SPDX expression, grant,
|
||||||
|
warranty disclaimer, and third-party statement.
|
||||||
|
- `LICENSE` contains the complete, unmodified project license text, including
|
||||||
|
incorporated companion text. Dependency attribution does not relicense the project.
|
||||||
|
- `docs/oss/attribution.md`: canonical component entries.
|
||||||
|
- `docs/oss/licenses/`: complete, verbatim standard and applicable companion texts.
|
||||||
|
|
||||||
|
Use recognizable license filenames, such as `Apache-2.0.txt` or `LGPL-3.0.txt`.
|
||||||
|
A shared standard text may serve multiple entries. Keep explanations outside
|
||||||
|
license texts and preserve distinct versions and exceptions.
|
||||||
|
|
||||||
|
## Upstream Reference Examples
|
||||||
|
|
||||||
|
Use the commit-pinned upstream examples to create actual project notices.
|
||||||
|
Retain their links and keep the example collection upstream; keep applicable
|
||||||
|
license texts locally as specified above.
|
||||||
|
|
||||||
|
The pinned upstream [standard license reference collection](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/oss/licenses/README.md)
|
||||||
|
provides texts to copy for applicable licenses and their companions.
|
||||||
|
|
||||||
|
## Project Licensing
|
||||||
|
|
||||||
|
ReleaseKit's selected grant is LGPL version 3 or later, recorded in
|
||||||
|
[COPYRIGHT](../../COPYRIGHT). It applies to the library and release
|
||||||
|
executable. Adapted policy documents, agent orientation, and the policy reading
|
||||||
|
guide retain their CC-BY-SA-4.0 scope as identified in the
|
||||||
|
[attribution document](../oss/attribution.md).
|
||||||
|
|
||||||
|
Unless the author specifies otherwise, use **GPL version 3 or later**
|
||||||
|
(`GPL-3.0-or-later`) for applications and **LGPL version 3 or later**
|
||||||
|
(`LGPL-3.0-or-later`) for libraries. An author's explicit choice takes precedence:
|
||||||
|
for example, a one-off script may use MIT. Such a choice requires no exception
|
||||||
|
rationale, additional approval, or compensating controls under this policy.
|
||||||
|
|
||||||
|
These defaults guide new license selection. Adopting this policy does not
|
||||||
|
relicense existing code or override third-party terms. Preserve an existing
|
||||||
|
license unless the author deliberately changes it. For mixed-purpose projects,
|
||||||
|
follow the author's selected scope rather than inferring different licenses for
|
||||||
|
individual packages.
|
||||||
|
|
||||||
|
Use the upstream [application COPYRIGHT example](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/examples/licensing/application/COPYRIGHT)
|
||||||
|
or [library COPYRIGHT example](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/examples/licensing/library/COPYRIGHT)
|
||||||
|
to create the project’s root `COPYRIGHT` file.
|
||||||
|
Use verified project names, contribution years, and copyright holders.
|
||||||
|
For another selected license, adapt the grant, SPDX expression, disclaimer, and
|
||||||
|
text references together to reflect the author's selected grant.
|
||||||
|
|
||||||
|
For GPLv3 projects, copy the complete GPLv3 text into `LICENSE`. For LGPLv3
|
||||||
|
projects, place the complete LGPLv3 text followed by the complete GPLv3 text in
|
||||||
|
`LICENSE`; the LGPL incorporates the GPL terms. Keep the texts unmodified and
|
||||||
|
place project-specific statements in `COPYRIGHT`. For the default grants, the
|
||||||
|
grant and SPDX expression in `COPYRIGHT` must expressly identify `or-later`;
|
||||||
|
follow the author’s choice if a different grant is selected.
|
||||||
|
|
||||||
|
For other licenses, provide their complete text and any required project-specific
|
||||||
|
fields; the standard reference collection remains unchanged. Keep `COPYRIGHT`,
|
||||||
|
`LICENSE`, SPDX expressions, and README descriptions consistent with the actual
|
||||||
|
grant. This convention introduces no blanket requirement for per-file headers;
|
||||||
|
preserve notices or add them where the applicable terms require them.
|
||||||
|
|
||||||
|
Identify separately licensed documentation or assets in the attribution
|
||||||
|
document, with links to their license information. The project grant uses the
|
||||||
|
upstream template's third-party statement.
|
||||||
|
|
||||||
|
## Upstream Attribution House Format
|
||||||
|
|
||||||
|
Begin `docs/oss/attribution.md` with `# Open Source Attribution Notices`,
|
||||||
|
followed directly by component entries. These comprise the complete document.
|
||||||
|
|
||||||
|
Each entry presents these five fields in order, with blank lines between them:
|
||||||
|
|
||||||
|
1. **Project name** as a level-two heading. An optional identification paragraph
|
||||||
|
may follow, such as `Selected module: MODULE at VERSION.` with the module and
|
||||||
|
version in backticks. For copied documentation, a concise `Material:` sentence
|
||||||
|
may identify the affected files and whether they were adapted or copied
|
||||||
|
without modification. A factual qualifier such as `(transitive dependency)`
|
||||||
|
is permitted. Limit optional identification prose to factual component and
|
||||||
|
material scope.
|
||||||
|
2. **Upstream copyright statement or statements**, preserving their wording.
|
||||||
|
Put multiple statements in separate paragraphs. Include this field when the
|
||||||
|
selected upstream source supplies an applicable statement; otherwise, omit it.
|
||||||
|
3. **SPDX license identifier or expression**, when applicable, using
|
||||||
|
`SPDX-License-Identifier: EXPRESSION`.
|
||||||
|
4. **License and notice links**, beginning `License and notices:`, separated
|
||||||
|
by ` | `, and ending with a period. Label local standard texts by license
|
||||||
|
name, such as `MIT` or `Apache 2.0`. Label upstream files by their actual
|
||||||
|
filenames, such as `COPYRIGHT`, `LICENSE`, `NOTICE`, or `PATENTS`.
|
||||||
|
5. **Source repository link**, rendered exactly as `[Source](COMMIT_URL).`.
|
||||||
|
|
||||||
|
Use the upstream [attribution example](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/examples/licensing/attribution.md)
|
||||||
|
to create the project’s `docs/oss/attribution.md`.
|
||||||
|
The example illustrates omitted fields and multiple copyrights and licenses.
|
||||||
|
Replace the uppercase placeholders and illustrative URLs with actual component
|
||||||
|
information. Local license links are relative to the destination
|
||||||
|
`docs/oss/attribution.md`; copy the applicable texts into its `licenses/`
|
||||||
|
directory. Do not copy example entries for components the project does not use.
|
||||||
|
|
||||||
|
These are five fields, not a line limit. Omit the SPDX field when no applicable
|
||||||
|
identifier exists; identify nonstandard terms through the linked text. Preserve
|
||||||
|
licensing alternatives and exceptions, and record a selected option when
|
||||||
|
relevant through the factual license identification. Do not invent an identifier
|
||||||
|
or silently resolve an unsettled licensing choice.
|
||||||
|
|
||||||
|
Keep entries factual. Do not add agent-authored explanations of license
|
||||||
|
expressions, file-level license scope, research performed, retained source
|
||||||
|
notices, or compliance conclusions. Avoid filler such as "none is invented
|
||||||
|
here" and embellished link labels such as "upstream LICENSE", "additional
|
||||||
|
patent grant", or "at the imported commit". Preserve actual required upstream
|
||||||
|
content; this rule excludes editorial additions, not required notices. Policy
|
||||||
|
interpretation and exception reasoning belong in the adopted OSS policy or an
|
||||||
|
appropriate decision record, not the attribution document.
|
||||||
|
|
||||||
|
## License Texts And Upstream Links
|
||||||
|
|
||||||
|
Link standard license texts to their local copies. Link project-specific
|
||||||
|
notices to their upstream copies. Every upstream repository or notice link must
|
||||||
|
identify the exact commit corresponding to the
|
||||||
|
imported version, including the selected source revision for copied material.
|
||||||
|
|
||||||
|
Classify material according to its contents. An upstream `LICENSE`,
|
||||||
|
`COPYING`, or similar file may contain project-specific notices or exceptions
|
||||||
|
in addition to standard wording. Link both the local standard text and the
|
||||||
|
commit-specific upstream file when needed. Make companion license texts directly
|
||||||
|
reachable from the entry.
|
||||||
|
|
||||||
|
For project-specific license and attribution material, this policy accepts
|
||||||
|
direct links to the applicable upstream texts as satisfying reproduction,
|
||||||
|
inclusion, or copy requirements. This is the adopted house interpretation.
|
||||||
|
Agents must apply it without adding local-copy requirements or seeking repeated
|
||||||
|
approval solely because a license uses those terms.
|
||||||
|
|
||||||
|
This interpretation concerns notice reproduction. Concrete obligations such as
|
||||||
|
marking modified files or supplying corresponding source receive their own
|
||||||
|
applicable treatment. Preserve required notices already present in incorporated
|
||||||
|
source files; the central attribution entry does not authorize stripping them.
|
||||||
|
|
||||||
|
## Discoverability
|
||||||
|
|
||||||
|
End the project's README with two friendly statements linking to its actual
|
||||||
|
grant in `COPYRIGHT` and the attribution document. For example, for a project
|
||||||
|
with the stated license:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
ReleaseKit is licensed under the [LGPL v3.0 or later](COPYRIGHT).
|
||||||
|
|
||||||
|
[Open Source attribution notices](docs/oss/attribution.md) are available.
|
||||||
|
```
|
||||||
|
|
||||||
|
Each new checked-in release document and its hosted download page must end
|
||||||
|
with links whose visible text is `COPYRIGHT | LICENSE | ATTRIBUTION`. Use absolute
|
||||||
|
URLs to those files at the release's immutable tag or corresponding immutable source
|
||||||
|
revision so the links work in both locations. This release navigation is distinct
|
||||||
|
from upstream component links, which must use the imported commit.
|
||||||
|
|
||||||
|
Reuse the checked-in release document as the hosted release body where supported.
|
||||||
|
The release procedure owns concrete URLs and publication mechanics for delivering
|
||||||
|
the links through the selected channel. Do not maintain duplicate notice lists.
|
||||||
|
These conventions do not by themselves require separate downloadable license
|
||||||
|
assets, source bundles, or a different binary package format.
|
||||||
|
|
||||||
|
## Maintenance And Exceptions
|
||||||
|
|
||||||
|
Update project licensing statements together when the author changes the grant
|
||||||
|
or its scope. Update upstream notices in the change that adds, removes, upgrades,
|
||||||
|
copies, or changes the distribution of a relevant component. Check the selected source's license
|
||||||
|
and notices rather than assuming they are unchanged. Update affected entries,
|
||||||
|
commit links, and texts; retain historical versions through Git.
|
||||||
|
|
||||||
|
Check affected statements, faithful standard-text copies, and link destinations
|
||||||
|
as part of ordinary change review. For a future release tag, check intended file
|
||||||
|
paths against the candidate source; the tag need not resolve remotely before
|
||||||
|
publication. Do not add publication-time network checks, CI polling, recurring
|
||||||
|
legal sign-offs, mandatory scanners, or a full software bill of materials merely
|
||||||
|
to implement this policy.
|
||||||
|
|
||||||
|
Use the House Format routinely. Raise an exception only for a concrete obligation
|
||||||
|
or unresolved rights question it does not address, including any arising from a
|
||||||
|
particular distribution channel. Record the issue and selected treatment in the
|
||||||
|
adopted OSS policy or an appropriate decision record. Attribution entries
|
||||||
|
contain the resulting factual identification and required material, without
|
||||||
|
repeating that reasoning. Resolve the issue before the affected use or
|
||||||
|
distribution without reopening settled choices.
|
||||||
|
Common ownership of projects is neither required nor a blanket exception.
|
||||||
|
|
||||||
|
Apply the formatting convention prospectively. Do not rewrite published tags,
|
||||||
|
notes, binaries, or checksums to retrofit it. Address actual omissions deliberately
|
||||||
|
under the applicable terms and the [release correction policy](release.md#immutability-and-failure-recovery).
|
||||||
|
Ordinary attribution maintenance and release links are preparation work, not new
|
||||||
|
release approval gates.
|
||||||
256
docs/policy/release.md
Normal file
256
docs/policy/release.md
Normal file
@@ -0,0 +1,256 @@
|
|||||||
|
# Release Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.6
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-08
|
||||||
|
|
||||||
|
**Upstream Source:** [release.md](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/docs/policy/release.md)
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
This policy defines a proportionate workflow for validating and publishing an
|
||||||
|
intended source revision under a fresh version. Releases should require little
|
||||||
|
routine intervention, avoid repeated work, and preserve published contents.
|
||||||
|
|
||||||
|
Adopt stronger verification or reproducibility requirements through an explicit
|
||||||
|
project-specific decision justified by the intended audience and support needs.
|
||||||
|
|
||||||
|
The repository-specific commands belong in `docs/release.md`. Historical release
|
||||||
|
summaries belong in `docs/releases/`. The procedure must agree with the adopted
|
||||||
|
policy and link to it rather than introduce additional release requirements.
|
||||||
|
|
||||||
|
This policy governs releases of ReleaseKit itself. Go declarations and GoDoc
|
||||||
|
own supported consumer API contracts. The maintainer runbook describes
|
||||||
|
ReleaseKit's implemented source publication and hosted-page delivery procedure.
|
||||||
|
|
||||||
|
## Release Model And Completion
|
||||||
|
|
||||||
|
A source release identifies one exact committed source revision through an
|
||||||
|
immutable version tag and a version-matched, checked-in release note. The
|
||||||
|
primary release branch is `main`.
|
||||||
|
The procedure must name the authoritative publication remote.
|
||||||
|
|
||||||
|
A successful push of the intended annotated tag, with its source commit already
|
||||||
|
published on authoritative `main`, completes the release. The remote branch must
|
||||||
|
identify the validated candidate before the command publishes only the exact
|
||||||
|
intended tag object. The [maintainer runbook](../release.md) identifies the
|
||||||
|
authoritative endpoint and command.
|
||||||
|
|
||||||
|
Release commands must finish at successful publication. They must not wait for
|
||||||
|
or poll CI, require successful CI status, inspect downloadable artifacts, or
|
||||||
|
check consumer installation or Go module availability as completion gates.
|
||||||
|
A failed or ambiguous push requires resolving the authoritative remote state
|
||||||
|
before declaring success or retrying; successful pushes do not require a
|
||||||
|
separate remote read-back gate.
|
||||||
|
|
||||||
|
ReleaseKit's deliverables are its immutable source tag and a hosted Gitea
|
||||||
|
release page whose body is the complete checked-in release note. A prepared
|
||||||
|
Woodpecker workflow builds the local release tool from that tagged source and
|
||||||
|
delivers the note page. This adds no executable download or binary manifest.
|
||||||
|
Any later distribution of executable builds requires a deliberate update
|
||||||
|
identifying the deliverables, selected targets, and automation responsibilities.
|
||||||
|
Supporting cross-builds for consumers does not declare ReleaseKit binaries.
|
||||||
|
Additional declared deliverables may be published asynchronously from the
|
||||||
|
tagged source, must be traceable to that source, and must identify the same
|
||||||
|
version.
|
||||||
|
|
||||||
|
Track source-release completion and artifact delivery separately. Report delivery
|
||||||
|
failures and optional investigations under artifact-delivery status.
|
||||||
|
|
||||||
|
## Versioning And Compatibility
|
||||||
|
|
||||||
|
Stable releases use Semantic Versioning in the form `vMAJOR.MINOR.PATCH`, with
|
||||||
|
no leading zeroes. Prereleases require an explicit adopted policy defining
|
||||||
|
their format and use.
|
||||||
|
|
||||||
|
The selected version must be unused locally and on the authoritative remote.
|
||||||
|
Do not require queries to every configured remote or publication service.
|
||||||
|
A version known to have already been published must not be reused, even if the
|
||||||
|
normal guards do not inspect that channel. Adding a distribution channel
|
||||||
|
requires a deliberate update to the policy and procedure where needed.
|
||||||
|
|
||||||
|
For releases at or after `v1.0.0`:
|
||||||
|
|
||||||
|
- a major release may make intentional incompatible changes;
|
||||||
|
- a minor release may add backward-compatible behavior or raise the Go consumer
|
||||||
|
minimum as described below; and
|
||||||
|
- a patch release may make backward-compatible fixes.
|
||||||
|
|
||||||
|
Before `v1.0.0`, a minor release may change a documented public, operational,
|
||||||
|
configuration, data, integration, or compatibility contract when the release
|
||||||
|
note explains the impact and required consumer action. A patch release must
|
||||||
|
not intentionally break those contracts within its minor line.
|
||||||
|
|
||||||
|
Additional compatibility promises and deliberate exceptions belong in the
|
||||||
|
adopted policy or canonical contract documentation. Release notes explain
|
||||||
|
changes; they do not redefine current compatibility contracts.
|
||||||
|
|
||||||
|
## Consumer Minimum And Release Toolchain
|
||||||
|
|
||||||
|
ReleaseKit provides reasonable support for routine build and release needs,
|
||||||
|
following [ADR 0002](../adr/0002-routine-releases.md). Distinguish the minimum Go
|
||||||
|
toolchain supported for consumers from the toolchain maintainers use to build
|
||||||
|
and validate a release. The consumer minimum belongs in [go.mod](../../go.mod);
|
||||||
|
the [maintainer runbook](../release.md) defines the selected release toolchain
|
||||||
|
and its setup commands.
|
||||||
|
|
||||||
|
Select the Go series during release preparation. When advancing the consumer
|
||||||
|
minimum, use the latest locally available stable series and record its initial
|
||||||
|
stable version in `go.mod`, such as `go 1.26.0`. Use a higher patch minimum when
|
||||||
|
a dependency requirement or identified correctness fix requires it, and document
|
||||||
|
the reason.
|
||||||
|
|
||||||
|
Build the maintainer release executable and validate the candidate with the
|
||||||
|
same latest locally available patch of the selected series. Keep that toolchain
|
||||||
|
active throughout preparation, tool bootstrap, and validation, using local
|
||||||
|
toolchain selection. CI jobs performing release builds and validation use the
|
||||||
|
selected toolchain; maintained CI images follow that choice. A newer validation
|
||||||
|
patch version alone leaves the consumer minimum unchanged.
|
||||||
|
|
||||||
|
For release-policy purposes, successful build and release validation on that
|
||||||
|
patch are sufficient to presume support across the selected Go series, subject
|
||||||
|
to the declared consumer minimum and concrete evidence of incompatibility.
|
||||||
|
This relies on Go's [release policy](https://go.dev/doc/devel/release#policy) and
|
||||||
|
[compatibility commitments](https://go.dev/doc/go1compat). Investigate specific
|
||||||
|
compatibility concerns as they arise. Routine releases require no patch-version
|
||||||
|
matrix. Record the actual validation toolchain in the release evidence.
|
||||||
|
|
||||||
|
A minor release may raise the Go consumer minimum, including from one Go series
|
||||||
|
to the next, both before and after `v1.0.0`. This is an explicit exception to the
|
||||||
|
backward-compatibility requirement for minor releases. Patch releases preserve
|
||||||
|
the consumer minimum. Explain an increase's impact and required consumer action
|
||||||
|
in the release note. Other incompatible changes remain subject to the versioning
|
||||||
|
rules above.
|
||||||
|
|
||||||
|
## Release Documentation And Preparation
|
||||||
|
|
||||||
|
Every new release must include `docs/releases/<version>.md` in the tagged
|
||||||
|
source tree. Use the complete version tag as the filename and begin with a
|
||||||
|
title containing the product name and that exact version.
|
||||||
|
|
||||||
|
Include a short summary and any relevant compatibility impact or upgrade
|
||||||
|
instructions. Choose sections suited to the release and keep the note
|
||||||
|
proportionate to the change.
|
||||||
|
|
||||||
|
Keep exact current contracts in their canonical documents and update affected
|
||||||
|
documentation with the behavior change. Link to those documents from the note
|
||||||
|
where useful. Derive the annotated tag's message from the checked-in note.
|
||||||
|
|
||||||
|
Include the release footer defined by the [OSS policy](oss.md#discoverability)
|
||||||
|
in each new release document and preserve it on the hosted download page. The
|
||||||
|
release procedure defines the concrete URLs and publication mechanics. Prepare
|
||||||
|
these links with the release note; they do not add a network check or approval
|
||||||
|
gate.
|
||||||
|
|
||||||
|
Handle version selection, release-note content, and retirement of completed
|
||||||
|
roadmaps during preparation. Preserve planned and deferred work and repair
|
||||||
|
affected links when retiring roadmaps. Reuse ordinary change review for
|
||||||
|
unintended files, credentials, and private data. Scope release-content review
|
||||||
|
to the tagged source.
|
||||||
|
|
||||||
|
## Candidate Validation
|
||||||
|
|
||||||
|
Provide one publication command that validates the final committed candidate,
|
||||||
|
checks publication state, and publishes the intended refs. A validation-only
|
||||||
|
mode or command may be provided for diagnosis, but must not be a required step
|
||||||
|
before publication repeats the same checks.
|
||||||
|
|
||||||
|
Run the complete deterministic, offline default test suite once for the final
|
||||||
|
candidate, following the [testing policy](testing.md). For repositories that
|
||||||
|
publish builds, verify the required build targets. Select those targets for
|
||||||
|
the project's actual support commitments; native testing on each platform
|
||||||
|
and access to particular hardware are not default release prerequisites.
|
||||||
|
|
||||||
|
The publication command runs the standard offline Go test suite, followed by
|
||||||
|
any additional product checks. The [maintainer runbook](../release.md) owns its
|
||||||
|
invocation. ReleaseKit's source-only deliverable adds no binary target matrix.
|
||||||
|
|
||||||
|
Additional gates must address a concrete risk that the existing checks do not
|
||||||
|
adequately cover. Do not automatically require linting, race testing, module
|
||||||
|
hygiene audits, documentation audits, credential scans, example validation, or
|
||||||
|
expanded platform matrices solely because they are possible. Retain such
|
||||||
|
checks when their distinct protection justifies their cost. A one-time migration
|
||||||
|
check must not silently become a permanent release requirement.
|
||||||
|
|
||||||
|
Release tests must not require real credentials, mutable application services,
|
||||||
|
paid APIs, live service probes, or inference calls. The procedure may describe
|
||||||
|
dependency preparation separately from offline validation.
|
||||||
|
|
||||||
|
Avoid duplicate validation across release phases. Successful checks for the
|
||||||
|
same final candidate need not be repeated solely to satisfy another phase;
|
||||||
|
any reuse must clearly apply to that exact candidate. Persistent validation
|
||||||
|
caches are not required. If the candidate changes, validate the new candidate.
|
||||||
|
Cheap publication-state checks may be repeated immediately before pushing
|
||||||
|
because local or remote state may have changed during validation.
|
||||||
|
|
||||||
|
Automate mechanical guards. Human review gates are strongly disfavored: add one
|
||||||
|
only through an explicit project-specific policy decision explaining the
|
||||||
|
concrete risk and why ordinary change review or automation is insufficient.
|
||||||
|
Do not add routine confirmations for checks the command can perform itself.
|
||||||
|
|
||||||
|
## Publication Guards
|
||||||
|
|
||||||
|
Automate the checks needed to publish the intended source under a fresh version:
|
||||||
|
|
||||||
|
- the version has the adopted format and is unused locally and on the
|
||||||
|
authoritative remote;
|
||||||
|
- the worktree and index are clean on the primary release branch;
|
||||||
|
- the source being published is the exact candidate that passed validation,
|
||||||
|
including its matching release note;
|
||||||
|
- authoritative `main` already identifies that candidate; and
|
||||||
|
- the annotated tag identifies the validated candidate and only its exact object
|
||||||
|
is published through an explicit tag ref.
|
||||||
|
|
||||||
|
Fetch the authoritative branch and tag state as needed for these checks.
|
||||||
|
Do not force branch or tag updates to bypass a failed guard. Publish explicit
|
||||||
|
refs rather than all local tags. Do not require CI success, publication-service
|
||||||
|
availability checks, or a separate manual confirmation for each guard.
|
||||||
|
|
||||||
|
## Immutability And Failure Recovery
|
||||||
|
|
||||||
|
Published version tags and published contents are immutable. Do not move,
|
||||||
|
overwrite, recreate, or delete a published tag, or replace a published artifact,
|
||||||
|
checksum, signature, provenance statement, or release note under that version.
|
||||||
|
The checked-in note at the immutable tag is that release's historical record.
|
||||||
|
|
||||||
|
If validation fails before publication, correct and commit the candidate and
|
||||||
|
rerun the publication command. If a push fails or its outcome is ambiguous,
|
||||||
|
query the authoritative tag ref once. Confirm success only when it identifies
|
||||||
|
the exact intended tag object on the validated commit; otherwise report failed
|
||||||
|
or unknown status and retain the local tag. Resolve that authoritative state
|
||||||
|
before retrying. Remove an unpublished local tag only after confirming it was
|
||||||
|
never published or used by a release channel.
|
||||||
|
An unavailable remote leaves publication status unknown; do not overwrite a tag
|
||||||
|
to resolve uncertainty.
|
||||||
|
|
||||||
|
Transient network, authentication, CI, or consumer-availability failures do not
|
||||||
|
by themselves require a new version. Asynchronous delivery may be retried from
|
||||||
|
the same immutable tag. Missing artifacts may be published later, provided
|
||||||
|
existing published contents are not replaced and the additions remain consistent
|
||||||
|
with the tagged source and any already-published checksum manifest. If that
|
||||||
|
cannot be achieved, publish a new version.
|
||||||
|
|
||||||
|
A defect requiring changes to published source or contents requires a corrected
|
||||||
|
commit, a new semantically appropriate version, a matching release note, and
|
||||||
|
the release procedure again. Leave the original release intact. A channel's
|
||||||
|
yank, deprecation, or advisory mechanism may warn consumers away from a defective
|
||||||
|
release without replacing its contents or reusing its version.
|
||||||
|
|
||||||
|
## Repository Release Procedure
|
||||||
|
|
||||||
|
Create and maintain `docs/release.md` with the first working publication command
|
||||||
|
as a short, executable maintainer runbook. It must identify:
|
||||||
|
|
||||||
|
1. prerequisites, selected release toolchain, primary branch, and authoritative
|
||||||
|
remote;
|
||||||
|
2. version and release-note preparation;
|
||||||
|
3. one publication command with its selected local checks and automated guards;
|
||||||
|
4. declared deliverables, required build targets, and automation responsibilities;
|
||||||
|
5. the successful-push completion point and separately reported delivery status;
|
||||||
|
and
|
||||||
|
6. failure handling, ambiguous-push recovery, and asynchronous delivery retries.
|
||||||
|
|
||||||
|
Use copyable commands where practical. Keep optional diagnostics and consumer
|
||||||
|
verification clearly optional. The procedure must not turn preparation work,
|
||||||
|
ordinary change review, or post-publication investigation into additional
|
||||||
|
release gates.
|
||||||
285
docs/policy/testing.md
Normal file
285
docs/policy/testing.md
Normal file
@@ -0,0 +1,285 @@
|
|||||||
|
# Testing Policy
|
||||||
|
|
||||||
|
**Base Policy Version:** 1.3
|
||||||
|
|
||||||
|
**Last Updated**: 2026-10-05
|
||||||
|
|
||||||
|
**Upstream Source:** [testing.md](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/testing.md)
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Our tests exist to make **incorrect changes expensive and correct changes cheap**.
|
||||||
|
|
||||||
|
We optimize for sufficient confidence in important behavior while minimizing friction on future development.
|
||||||
|
|
||||||
|
## Every test has a cost
|
||||||
|
|
||||||
|
Every test has an immediate and continuing cost: writing, review, execution,
|
||||||
|
diagnosis, fixture maintenance, and updates when legitimate behavior changes.
|
||||||
|
Tests can also constrain refactoring, duplicate policy, and add failure noise.
|
||||||
|
|
||||||
|
A test is warranted only when the confidence it provides justifies these costs.
|
||||||
|
Evaluate that tradeoff at two levels:
|
||||||
|
|
||||||
|
1. **Per test:** What realistic defect does this test detect, how consequential would that defect be, and is that protection worth the test's lifetime cost?
|
||||||
|
2. **Across the suite:** Does this collection provide materially more confidence than a smaller, simpler suite would?
|
||||||
|
|
||||||
|
Some friction is intentional. Tests should make dangerous changes—such as breaking compatibility, corrupting data, violating security boundaries, or reintroducing subtle bugs—require deliberate review. Keep ordinary internal changes inexpensive.
|
||||||
|
|
||||||
|
Evaluate maintenance cost against the specific failure being protected. When omitting a plausible test, be able to state why the protected failure is low-risk, already covered, obvious, reversible, or cheaper to detect elsewhere. For consequential, subtle, or difficult-to-observe behavior, the presumption should favor testing.
|
||||||
|
|
||||||
|
## Default testing style
|
||||||
|
|
||||||
|
Use a **classical/Detroit-style** approach:
|
||||||
|
|
||||||
|
- Test observable behavior, resulting state, contracts, and invariants.
|
||||||
|
- Use real internal collaborators when they are fast and deterministic.
|
||||||
|
- Use fakes, stubs, or mocks primarily at expensive, nondeterministic, destructive, or external boundaries.
|
||||||
|
- Prefer package-level behavioral tests over tests coupled to private helpers or internal call sequences.
|
||||||
|
- Treat exact collaborator interactions as testable behavior only when the interaction itself is a requirement.
|
||||||
|
|
||||||
|
Examples of appropriate seams include clocks, randomness, subprocesses, remote APIs, object storage, email, and paid LLM calls.
|
||||||
|
|
||||||
|
## Test execution requirements
|
||||||
|
|
||||||
|
Tests in the default suite must be deterministic, offline, and independent of real credentials. They must not invoke paid APIs or depend on mutable external services. Tests that require live infrastructure must be explicitly opt-in and clearly separated from the default suite.
|
||||||
|
|
||||||
|
Control clocks, randomness, environment variables, and other process-global or machine-specific state when they affect behavior. Tests should be safe to run repeatedly and alongside other tests without depending on execution order or state left by an earlier test.
|
||||||
|
|
||||||
|
## ReleaseKit Priorities
|
||||||
|
|
||||||
|
As the corresponding features are implemented, prioritize:
|
||||||
|
|
||||||
|
- publication of the exact validated candidate and tag object, using temporary
|
||||||
|
local Git repositories and remotes;
|
||||||
|
- remote advancement, rejected pushes, lost acknowledgments, and unavailable
|
||||||
|
remotes, with accurate failed, successful, and unknown outcomes;
|
||||||
|
- preservation of published content and consistent retries after partial asset
|
||||||
|
delivery, using a local HTTP server for Gitea interactions;
|
||||||
|
- cross-build target selection and version injection, including a host-runnable
|
||||||
|
application whose public `buildinfo` accessor reports the selected version;
|
||||||
|
- public type ownership, exported signatures and method sets, error identity,
|
||||||
|
and dependency direction across both facades; and
|
||||||
|
- a `buildinfo` dependency graph restricted to the standard library and small
|
||||||
|
internal runtime implementation, independent of orchestration.
|
||||||
|
|
||||||
|
These priorities guide risk-based tests as features land. Compilation of a
|
||||||
|
cross-built binary establishes build compatibility; execution requires a
|
||||||
|
compatible host. The developer guide owns actual test commands.
|
||||||
|
|
||||||
|
## What deserves tests
|
||||||
|
|
||||||
|
To the extent the following features are present in the application, prioritize tests for:
|
||||||
|
|
||||||
|
1. Public and package-level contracts.
|
||||||
|
2. Domain rules and important invariants.
|
||||||
|
3. Boundary conditions and malformed input.
|
||||||
|
4. Failure handling, cancellation, retries, recovery, and partial success.
|
||||||
|
5. Serialization, schemas, compatibility, and round trips.
|
||||||
|
6. Previously observed or plausible regressions.
|
||||||
|
7. Representative integration and end-to-end workflows.
|
||||||
|
|
||||||
|
A package-level contract comprises behavior relied upon by another package or major collaborator.
|
||||||
|
|
||||||
|
Choose tests for requested behavior and established contracts. Tests must not
|
||||||
|
introduce new restrictions, guarantees, or threat scenarios merely because they
|
||||||
|
could be asserted. Follow the [agent policy](agents.md) when deciding whether a
|
||||||
|
behavior belongs to the contract; current implementation behavior alone is not
|
||||||
|
sufficient authority.
|
||||||
|
|
||||||
|
For established behavior involving **data integrity, destructive operations,
|
||||||
|
compatibility, security, concurrency, idempotency, or recovery**, favor durable
|
||||||
|
tests for realistic failures whose consequences warrant protection. Identify
|
||||||
|
the failure and the existing contract it would violate. These categories call
|
||||||
|
for attention, not an automatic test inventory or permission to strengthen the
|
||||||
|
application's guarantees. Account for protection already provided at other layers.
|
||||||
|
|
||||||
|
Do not add tests merely because a function, branch, or line exists. Do not add a test when the same meaningful risk is already adequately protected elsewhere.
|
||||||
|
|
||||||
|
## Choose the right test boundary
|
||||||
|
|
||||||
|
Choose the narrowest stable boundary that expresses the behavior clearly and
|
||||||
|
provides durable confidence with minimal incidental coupling.
|
||||||
|
|
||||||
|
This is often the package API, but it may instead be:
|
||||||
|
|
||||||
|
- a smaller pure function when dense domain logic is most clearly isolated there;
|
||||||
|
- a package-level operation when several internal collaborators jointly produce the behavior; or
|
||||||
|
- a larger integration boundary when correctness emerges from interaction with a real dependency.
|
||||||
|
|
||||||
|
## Test behavior, not implementation
|
||||||
|
|
||||||
|
A test should protect a selected decision, contract, or invariant.
|
||||||
|
|
||||||
|
A test is suspect when it primarily detects changes to private constants or
|
||||||
|
helpers, equivalent operation ordering, incidental formatting, equivalent
|
||||||
|
algorithms, or internal structure that preserves behavior.
|
||||||
|
|
||||||
|
Behavioral tests should normally remain stable through internal refactoring that preserves the contract.
|
||||||
|
|
||||||
|
## Expected effects of different changes
|
||||||
|
|
||||||
|
Use the following expectations when evaluating test failures and test maintenance:
|
||||||
|
|
||||||
|
| Change | Expected effect on tests |
|
||||||
|
|---|---|
|
||||||
|
| Internal refactor that preserves behavior | Existing tests should normally remain unchanged and continue to pass. |
|
||||||
|
| Change to an internal default with no contractual significance | Behavioral tests should normally remain unchanged; tests should derive expectations from configuration or relationships rather than duplicate the old value. |
|
||||||
|
| Intentional change to public behavior, policy, schema, or compatibility guarantees | The relevant tests should be reviewed and changed deliberately. |
|
||||||
|
| Accidental violation of a contract or invariant | Tests should fail; fix the production code rather than rewriting the tests to accept the defect. |
|
||||||
|
|
||||||
|
A test failing is not the same as a test needing to be edited. Many tests may correctly fail because of one production defect. The maintenance smell is a correct internal change that requires unrelated expectation updates throughout the suite.
|
||||||
|
|
||||||
|
## Separate mechanism from policy
|
||||||
|
|
||||||
|
Derive expectations from test-controlled configuration and relationships.
|
||||||
|
|
||||||
|
For this example, assume the selected contract rejects a request to start more
|
||||||
|
processes than a configured limit. Do not encode its production default indirectly:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Production default:
|
||||||
|
const maxConcurrency = 4
|
||||||
|
|
||||||
|
// Brittle test:
|
||||||
|
err := startProcesses(5)
|
||||||
|
require.Error(t, err)
|
||||||
|
```
|
||||||
|
|
||||||
|
Instead, test the mechanism relationally:
|
||||||
|
|
||||||
|
```go
|
||||||
|
const limit = 2
|
||||||
|
runner := NewRunner(limit)
|
||||||
|
|
||||||
|
require.NoError(t, runner.Start(limit))
|
||||||
|
require.ErrorIs(t, runner.Start(limit+1), ErrTooMuchConcurrency)
|
||||||
|
```
|
||||||
|
|
||||||
|
For this selected contract, the test should prove:
|
||||||
|
|
||||||
|
- the configured limit is accepted; and
|
||||||
|
- one beyond the configured limit is rejected.
|
||||||
|
|
||||||
|
Rejection is not a general requirement for concurrency control. If the selected
|
||||||
|
contract queues excess work or limits active workers while accepting larger
|
||||||
|
batches, test that behavior instead. Do not add rejection or a configurable
|
||||||
|
limit solely to reproduce this example.
|
||||||
|
|
||||||
|
The production default should be tested exactly only when its literal value is itself a public, operational, safety, protocol, or compatibility requirement.
|
||||||
|
|
||||||
|
Apply the same rule to limits, timeouts, capacities, retry counts, and ranges: test relationships and behavior.
|
||||||
|
|
||||||
|
For established concurrency limits, distinguish these behaviors where the contract requires them:
|
||||||
|
|
||||||
|
1. **Configuration handling:** values are accepted or rejected according to the selected contract.
|
||||||
|
2. **Runtime enforcement:** observed peak concurrency never exceeds the configured limit.
|
||||||
|
|
||||||
|
Use a test-controlled limit and measure the behavior relative to that limit.
|
||||||
|
|
||||||
|
## Assign each behavior a test owner
|
||||||
|
|
||||||
|
Where these layers exist, assign ownership as follows:
|
||||||
|
|
||||||
|
- Parser tests own parsing cases.
|
||||||
|
- Validator tests own validation rules.
|
||||||
|
- Domain tests own transformations and invariants.
|
||||||
|
- Adapter tests own external integration behavior.
|
||||||
|
- Orchestrator tests own coordination and failure propagation.
|
||||||
|
- CLI tests own argument and configuration mapping.
|
||||||
|
- End-to-end tests prove that representative assembled workflows work.
|
||||||
|
|
||||||
|
Give each layer its distinct responsibility and keep expectation updates localized to the contract being changed.
|
||||||
|
|
||||||
|
## Use test doubles deliberately
|
||||||
|
|
||||||
|
Choose the least elaborate test double that provides the required control or observation.
|
||||||
|
|
||||||
|
As a default:
|
||||||
|
|
||||||
|
1. Prefer real collaborators when they are fast and deterministic.
|
||||||
|
2. Use small in-memory fakes when realistic stateful behavior is helpful.
|
||||||
|
3. Use stubs when a dependency only needs to provide controlled responses.
|
||||||
|
4. Use mocks when the interaction itself is contractual.
|
||||||
|
|
||||||
|
Mocks are appropriate when the contract includes facts such as:
|
||||||
|
|
||||||
|
- a notification is sent exactly once;
|
||||||
|
- a transaction is committed only after successful writes;
|
||||||
|
- cancellation reaches a subprocess;
|
||||||
|
- an expensive API is called no more than once; or
|
||||||
|
- a security audit event is emitted.
|
||||||
|
|
||||||
|
## Go-specific guidance
|
||||||
|
|
||||||
|
Select techniques by behavior and risk:
|
||||||
|
|
||||||
|
- table-driven tests for meaningful behavioral categories and boundaries;
|
||||||
|
- `t.TempDir()` for real filesystem behavior;
|
||||||
|
- `httptest.Server` for realistic HTTP interactions;
|
||||||
|
- fuzz tests when exploring broad input spaces, such as parsers or path handling, adds useful protection beyond representative cases;
|
||||||
|
- golden files only when the complete output is intentionally stable;
|
||||||
|
- integration tests where correctness depends on component interaction; and
|
||||||
|
- a small number of representative end-to-end tests when assembled workflows expose meaningful risks not adequately covered at narrower boundaries.
|
||||||
|
|
||||||
|
Prefer `errors.Is`, `errors.As`, typed errors, or structured error fields. Use exact error-wording assertions only when the wording is contractual.
|
||||||
|
|
||||||
|
At CLI boundaries, prefer exit classifications, structured output, and the smallest stable semantic fragment needed to identify the error. Use complete diagnostic snapshots only when the wording is contractual.
|
||||||
|
|
||||||
|
Golden-file updates must require an explicit local flag. CI must not update golden files automatically, and reviewers must inspect the semantic diff before accepting an update.
|
||||||
|
|
||||||
|
Keep tests readable and direct. Size test helpers and fixture frameworks to the maintenance benefit they provide.
|
||||||
|
|
||||||
|
## Coverage
|
||||||
|
|
||||||
|
Use coverage to locate untested critical branches and unexpectedly weak packages. Evaluate test quality through meaningful behavioral protection and choose coverage according to risk.
|
||||||
|
|
||||||
|
Pure domain logic will often warrant higher coverage than CLI wiring or external adapters. Uneven coverage is acceptable when it reflects risk.
|
||||||
|
|
||||||
|
## Regression tests
|
||||||
|
|
||||||
|
A bug fix should normally include a regression test that fails before the fix and passes afterward.
|
||||||
|
|
||||||
|
Retain the test when the defect could realistically recur and its consequences justify the ongoing cost. Prefer the narrowest durable test of the violated contract or invariant.
|
||||||
|
|
||||||
|
Remove or consolidate a test when the underlying design has made recurrence impossible, its protection is redundant, or a stronger invariant test subsumes it.
|
||||||
|
|
||||||
|
## Deleting or rewriting tests
|
||||||
|
|
||||||
|
Delete or rewrite tests when maintenance cost exceeds their continuing
|
||||||
|
protective value.
|
||||||
|
|
||||||
|
Strong candidates include tests that:
|
||||||
|
|
||||||
|
- require updates after harmless internal changes;
|
||||||
|
- assert incidental private constants or snapshot large amounts of incidental output;
|
||||||
|
- verify mock choreography rather than outcomes;
|
||||||
|
- duplicate policy across layers, retest trivial helpers covered by package
|
||||||
|
behavior, or protect risks covered more effectively elsewhere;
|
||||||
|
- are flaky, misleading, obsolete, or disproportionately expensive to diagnose; or
|
||||||
|
- no longer correspond to a plausible failure mode.
|
||||||
|
|
||||||
|
Several brittle tests may encode one genuine requirement. Consolidate them into one durable behavior-level or invariant test.
|
||||||
|
|
||||||
|
## Reviewing a proposed test
|
||||||
|
|
||||||
|
Use the following questions when a proposed test needs closer evaluation. Significant test additions should be reviewable against them; written answers are optional for routine tests.
|
||||||
|
|
||||||
|
1. Which requested behavior or established contract does it protect, and what realistic defect would violate it?
|
||||||
|
2. How likely and consequential is that defect, and is it already protected elsewhere?
|
||||||
|
3. What is the narrowest stable boundary that can test it clearly?
|
||||||
|
4. Would a correct internal refactor or a change to an incidental default require test edits?
|
||||||
|
5. Does its confidence justify its maintenance, execution, and diagnostic cost, or would a smaller test suffice?
|
||||||
|
|
||||||
|
## Definition of sufficient
|
||||||
|
|
||||||
|
A test suite is sufficient when:
|
||||||
|
|
||||||
|
- important requested behavior and established contracts are protected against realistic, consequential failures;
|
||||||
|
- boundaries and component interactions have coverage where they introduce meaningful risks not protected elsewhere;
|
||||||
|
- failures provide useful, distinct signals;
|
||||||
|
- tests usually remain stable through legitimate internal changes; and
|
||||||
|
- additional tests would mostly repeat existing protection or preserve inconsequential implementation details.
|
||||||
|
|
||||||
|
Reassess sufficiency as the application, its users, and the consequences of
|
||||||
|
failure evolve.
|
||||||
159
docs/release.md
Normal file
159
docs/release.md
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
# ReleaseKit release procedure
|
||||||
|
|
||||||
|
ReleaseKit's deliverables are its source tag and a hosted Gitea page containing
|
||||||
|
the complete checked-in release note. The page is delivered asynchronously by
|
||||||
|
the prepared [Woodpecker workflow](../examples/woodpecker/releasekit-source-delivery.yml);
|
||||||
|
it is not a source-release completion check and carries no binary assets. The
|
||||||
|
authoritative repository is `origin` at
|
||||||
|
`https://gitea.maximumdirect.net/eric/ReleaseKit.git`, and the release branch
|
||||||
|
is `main`. A release completes when the intended annotated tag is successfully
|
||||||
|
pushed, or when one exact-object recovery query confirms that the push
|
||||||
|
succeeded. CI and consumer installation are not completion checks.
|
||||||
|
|
||||||
|
## Prepare a candidate
|
||||||
|
|
||||||
|
Use a clean clone on `main`. The chosen build toolchain is Go 1.26.8. Make that
|
||||||
|
local installation the active `go` command for preparation, building the release
|
||||||
|
executable, and candidate validation:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export GOTOOLCHAIN=local
|
||||||
|
go version
|
||||||
|
```
|
||||||
|
|
||||||
|
Record the reported version with the validation results. The
|
||||||
|
[Go support policy](policy/release.md#consumer-minimum-and-release-toolchain) owns
|
||||||
|
series selection, consumer minima, patch exceptions, and validation scope.
|
||||||
|
The maintained [source-delivery image](../examples/woodpecker/releasekit-source-delivery.yml)
|
||||||
|
and [consumer template image](../examples/woodpecker/tag-delivery.yml) follow the
|
||||||
|
chosen build toolchain; update them together when that selection changes.
|
||||||
|
|
||||||
|
The current consumer minimum is Go 1.26.0, declared in [go.mod](../go.mod).
|
||||||
|
Keep it for a release unless release preparation deliberately selects a newer
|
||||||
|
series under the [Go support policy](policy/release.md#consumer-minimum-and-release-toolchain).
|
||||||
|
When increasing it, update `go.mod` to the first stable version of the selected
|
||||||
|
series, or to a higher patch when a dependency or specific fix requires one.
|
||||||
|
Make module changes before committing the candidate. Minimum increases must fit the
|
||||||
|
[compatibility policy](policy/release.md#versioning-and-compatibility); before
|
||||||
|
v1.0.0, an increase belongs in a minor release.
|
||||||
|
|
||||||
|
Choose an unused stable `vMAJOR.MINOR.PATCH` version, and add
|
||||||
|
`docs/releases/<version>.md` with a first heading containing `ReleaseKit` and
|
||||||
|
the exact version. Summarize the change and any compatibility or upgrade impact.
|
||||||
|
End the note with the three license links at the immutable source tag:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/LICENSE) |
|
||||||
|
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/vX.Y.Z/docs/oss/attribution.md)
|
||||||
|
```
|
||||||
|
|
||||||
|
Replace every `vX.Y.Z` with the selected version. These are links to the same
|
||||||
|
release note's immutable source tree and also work when the note is used as a
|
||||||
|
hosted release body.
|
||||||
|
|
||||||
|
Commit the note and all candidate changes on `main`, then publish that commit
|
||||||
|
to `origin/main`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git push origin main
|
||||||
|
```
|
||||||
|
|
||||||
|
ReleaseKit checks that the worktree is clean, the candidate is on `main`, the
|
||||||
|
authoritative branch identifies that commit, and the version is unused locally
|
||||||
|
and on `origin`.
|
||||||
|
|
||||||
|
## Prepare dependencies, then publish
|
||||||
|
|
||||||
|
Dependency preparation is separate from the offline candidate validation. Run
|
||||||
|
it from the captured candidate source before the release command:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
GOTOOLCHAIN=local go mod download
|
||||||
|
```
|
||||||
|
|
||||||
|
Then run the single publication command from the repository root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./scripts/release vX.Y.Z
|
||||||
|
```
|
||||||
|
|
||||||
|
The command always runs the offline default test suite,
|
||||||
|
`go test -mod=readonly -count=1 ./...`, with toolchain and module network
|
||||||
|
access disabled. Any profile `checks` run afterward as additional product
|
||||||
|
checks; they should not repeat the standard suite. The command checks the
|
||||||
|
authoritative remote state, creates a local annotated tag from the captured
|
||||||
|
candidate and checked-in note, rechecks the tag and remote guards, and pushes
|
||||||
|
only that tag object. It prints the published version, commit, and tag object
|
||||||
|
on success. Exit status 0 means publication is confirmed; status 1 means a
|
||||||
|
known failure or conflict; status 2 means invalid input or profile; status 3
|
||||||
|
means the push outcome remains unknown and requires resolution.
|
||||||
|
|
||||||
|
The wrapper builds the native CLI into ignored `.releasekit/bin`, then invokes
|
||||||
|
it directly to preserve its exit status. The CLI comes from the source tree
|
||||||
|
being published, so this command also works
|
||||||
|
for ReleaseKit's first release before any released ReleaseKit executable
|
||||||
|
exists. It uses the local Go toolchain. Preparation must finish before the
|
||||||
|
offline validation begins.
|
||||||
|
|
||||||
|
## Resolve failures
|
||||||
|
|
||||||
|
A failed push triggers a URL-resolution check against the captured endpoint,
|
||||||
|
then at most one exact authoritative tag query. If the endpoint no longer
|
||||||
|
resolves to itself, recovery reports `unknown` without querying the rewritten
|
||||||
|
destination. An exact tag-object match confirms publication even when Git
|
||||||
|
reported an error. A proven absent tag is `not_published`; a different object
|
||||||
|
is a conflict; an unreadable query is `unknown`. The command retains its local
|
||||||
|
tag and reports the state, phase,
|
||||||
|
candidate commit, tag object, and captured publication endpoint when available.
|
||||||
|
Do not retry an unknown result until you resolve the authoritative ref at that
|
||||||
|
exact endpoint. Copy the reported endpoint value into the variable below using
|
||||||
|
normal shell quoting; retain the version and tag object from the same result.
|
||||||
|
The command checks that Git URL rewriting still resolves this value to itself;
|
||||||
|
the manual check below applies the same rule before querying:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
releasekit_endpoint='COPY_CAPTURED_ENDPOINT'
|
||||||
|
releasekit_version='vX.Y.Z'
|
||||||
|
test "$(git ls-remote --get-url -- "$releasekit_endpoint")" = "$releasekit_endpoint" &&
|
||||||
|
git ls-remote --refs -- "$releasekit_endpoint" "refs/tags/$releasekit_version"
|
||||||
|
```
|
||||||
|
|
||||||
|
A failed URL-equality check or remote query leaves the outcome unresolved.
|
||||||
|
Correct transport configuration before continuing. The reported endpoint may
|
||||||
|
be different from `origin`'s fetch URL or its current push URL; querying either
|
||||||
|
of those does not establish absence at the captured endpoint.
|
||||||
|
|
||||||
|
Compare the returned object ID with the tag object reported by the command.
|
||||||
|
An exact match confirms publication. If the ref is absent, the version was not
|
||||||
|
published; only then may you deliberately remove the unpublished local tag
|
||||||
|
with `git tag -d vX.Y.Z` before correcting the candidate or retrying. Do not
|
||||||
|
move, overwrite, or delete a tag that exists remotely. If a different object
|
||||||
|
uses the version, choose a new version after resolving the conflict.
|
||||||
|
|
||||||
|
If validation or a guard fails before this invocation pushes, correct and
|
||||||
|
commit the candidate, publish `main`, and run the command again. A retained
|
||||||
|
local tag still requires the authoritative-state check above before removal;
|
||||||
|
a concurrent publisher may already have published the version. The prepared
|
||||||
|
Woodpecker workflow builds the CLI from the tagged checkout, then uses
|
||||||
|
`ci-deliver` for page-only delivery. To activate it after configuring the
|
||||||
|
destination and secret, copy it to `.woodpecker/releasekit-source-delivery.yml`
|
||||||
|
and add the Woodpecker repository secret `releasekit_gitea_token`. If page
|
||||||
|
delivery fails or is uncertain, inspect the hosted release and retry the same
|
||||||
|
immutable version from its tag:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git fetch origin "refs/tags/vX.Y.Z:refs/tags/vX.Y.Z"
|
||||||
|
git checkout --detach "vX.Y.Z"
|
||||||
|
GOTOOLCHAIN=local go mod download
|
||||||
|
mkdir -p .releasekit/bin
|
||||||
|
GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off go build -o .releasekit/bin/releasekit ./cmd/releasekit
|
||||||
|
RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" .releasekit/bin/releasekit deliver "vX.Y.Z"
|
||||||
|
```
|
||||||
|
|
||||||
|
The root ignore file excludes `.releasekit/`. Delivery uses the committed note
|
||||||
|
and does not build consumer binaries, create a checksum manifest, or require a
|
||||||
|
previously released ReleaseKit executable. Keep source publication and hosted
|
||||||
|
page delivery status separate; retry only after resolving an uncertain remote
|
||||||
|
write. The workflow secret is named `releasekit_gitea_token` and is mapped to
|
||||||
|
`RELEASEKIT_GITEA_TOKEN` only in the delivery step.
|
||||||
64
docs/releases/v0.1.0.md
Normal file
64
docs/releases/v0.1.0.md
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
# ReleaseKit v0.1.0
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
ReleaseKit's initial release provides an opinionated Go library and executable
|
||||||
|
for candidate validation, annotated source-tag publication, version injection,
|
||||||
|
selected-target builds, and Gitea release delivery.
|
||||||
|
|
||||||
|
The root `releasekit` facade owns release orchestration. The separate `buildinfo`
|
||||||
|
facade supplies lightweight runtime version access. Both belong to one Go module
|
||||||
|
with a Go 1.25.0 minimum language version.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
- Run the standard offline Go test suite once, followed by optional
|
||||||
|
product-specific checks and selected-target build verification.
|
||||||
|
- Publish the exact annotated tag for a validated candidate already on
|
||||||
|
authoritative `main`, with bounded recovery after failed or ambiguous pushes.
|
||||||
|
- Cross-build selected Go targets with shared version injection, artifact names,
|
||||||
|
digests, and a native version smoke check. Source-only projects select no
|
||||||
|
binary targets.
|
||||||
|
- Deliver committed release notes and declared assets to Gitea, preserving
|
||||||
|
existing content and reporting partial, conflicting, and uncertain outcomes.
|
||||||
|
- Use one managed build-and-deliver operation or supply retained prebuilt
|
||||||
|
artifacts for retries and separate build/delivery environments.
|
||||||
|
- Prepare tagged CI checkouts and dependencies through the shared `ci-deliver`
|
||||||
|
command and maintained Woodpecker workflow.
|
||||||
|
|
||||||
|
See the [CLI contract](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/cli.md),
|
||||||
|
[configuration reference](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/config.md),
|
||||||
|
[consumer delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/consumers/delivery.md),
|
||||||
|
and [runtime version guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/consumers/runtime-version.md)
|
||||||
|
for supported behavior.
|
||||||
|
|
||||||
|
## Adoption and compatibility
|
||||||
|
|
||||||
|
Consumers can select this initial baseline with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.1.0
|
||||||
|
go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.1.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Profiles declare product identity, additional checks, selected binaries and
|
||||||
|
targets, and a Gitea destination. Applications obtain their embedded version
|
||||||
|
through `buildinfo.Version()`.
|
||||||
|
|
||||||
|
For consumers experimenting with earlier development revisions, rename the
|
||||||
|
`ReleaseRequest.Validate` callback to `AdditionalChecks` and remove repeated
|
||||||
|
standard-suite commands from profile `checks`. `DeliveryRequest.Build` now
|
||||||
|
accepts a `*BuildSpec` for managed builds; use `Prebuilt` for an existing
|
||||||
|
`BuildResult`.
|
||||||
|
|
||||||
|
Compatibility follows the [release policy](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/policy/release.md): before
|
||||||
|
v1.0.0, minor releases may change documented contracts with migration guidance;
|
||||||
|
patch releases preserve contracts within their minor line.
|
||||||
|
|
||||||
|
ReleaseKit's deliverables are this immutable source tag and the hosted page
|
||||||
|
containing this complete note. Consumer migration and live Woodpecker deployment
|
||||||
|
remain adoption work tracked in the [product roadmap](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/roadmap/releasekit.md).
|
||||||
|
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/LICENSE) |
|
||||||
|
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.1.0/docs/oss/attribution.md)
|
||||||
106
docs/releases/v0.2.0.md
Normal file
106
docs/releases/v0.2.0.md
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
# ReleaseKit v0.2.0
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
ReleaseKit adds declarative candidate validation and module-selected release
|
||||||
|
tooling for Woodpecker. Consumers can replace repeated release checks with typed
|
||||||
|
Go selections or equivalent profile settings, while retaining product-specific
|
||||||
|
assertions through `AdditionalChecks` and profile `checks`.
|
||||||
|
|
||||||
|
## New features
|
||||||
|
|
||||||
|
- A facade-owned `ValidationSpec` on `ReleaseRequest` and corresponding profile
|
||||||
|
`validation` object select shared checks for both `Check` and `Publish`.
|
||||||
|
Structured `ValidationError` diagnostics identify the failed check, relevant
|
||||||
|
paths and locations, compilation targets, directives, and size measurements.
|
||||||
|
Wrapping preserves underlying causes and cancellation.
|
||||||
|
- Race testing selects the race detector for the one standard Go suite. Separate
|
||||||
|
full vet automatically disables test-time vet and runs after successful tests.
|
||||||
|
Selected package-compilation targets run afterward with `CGO_ENABLED=0`,
|
||||||
|
independently of executable artifacts. Source-only libraries can check target
|
||||||
|
compatibility and retain page-only delivery.
|
||||||
|
- Go formatting checks inspect committed regular Go source and report formatting
|
||||||
|
differences while preserving files.
|
||||||
|
- Offline Markdown validation checks local destinations and supported heading
|
||||||
|
fragments, including inline/reference links, images, and autolinks. Heading
|
||||||
|
anchors support visible text, duplicate headings, and Unicode. Outside-checkout
|
||||||
|
destinations are reported as out of scope by default; consumers can select
|
||||||
|
boundary enforcement. Submodule contents remain out of scope.
|
||||||
|
- Independent module-distribution selections inspect committed workspace files
|
||||||
|
and filesystem module replacements. Versioned replacements are permitted.
|
||||||
|
- Optional file-size validation checks individual committed blobs, including
|
||||||
|
symlink text, with a configurable limit and literal file/directory exclusions.
|
||||||
|
Enabling the check selects a default limit of 1,000,000 bytes; only sizes
|
||||||
|
strictly greater than the selected limit fail.
|
||||||
|
- `ExpectedPushURL` and profile `expected_push_url` require an exact match with
|
||||||
|
Git's effective push destination during publication preflight. A mismatch
|
||||||
|
returns `ErrUnexpectedPushURL` before candidate validation or tag creation.
|
||||||
|
Local `Check` ignores the publication expectation.
|
||||||
|
- The maintained Woodpecker consumer template selects ReleaseKit from the
|
||||||
|
released application's module configuration. It verifies the event tag and
|
||||||
|
commit before building the tool, prepares tool dependencies in temporary module
|
||||||
|
metadata, and preserves tagged module files. Retries use the triggering tag's
|
||||||
|
dependency selection. ReleaseKit's self-bootstrap template also supports
|
||||||
|
fetching missing tool dependencies after tag verification.
|
||||||
|
|
||||||
|
See the [configuration reference](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/config.md),
|
||||||
|
[candidate check guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/consumers/check.md),
|
||||||
|
[publication guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/consumers/publish.md),
|
||||||
|
and [delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/consumers/delivery.md)
|
||||||
|
for supported behavior and adoption examples.
|
||||||
|
|
||||||
|
## Compatibility
|
||||||
|
|
||||||
|
The minimum Go version remains 1.25.0. The root orchestration facade and separate
|
||||||
|
lightweight `buildinfo` runtime facade keep their existing responsibilities.
|
||||||
|
Goldmark and `golang.org/x/mod` are new internal dependencies; prepare the module
|
||||||
|
cache before offline validation or builds.
|
||||||
|
|
||||||
|
Omitted validation selections preserve v0.1.0 defaults. Existing profiles and
|
||||||
|
product-specific checks continue to work. Race testing requires the native
|
||||||
|
toolchain's race prerequisites and reports an error when they are unavailable.
|
||||||
|
Markdown and file-size checks are enabled by non-nil Go specifications or profile
|
||||||
|
objects, including empty objects; omission or `null` disables them.
|
||||||
|
|
||||||
|
`ReleaseRequest` gains fields, so callers using positional struct literals must
|
||||||
|
convert them to keyed literals. Validation diagnostics now include structured
|
||||||
|
detail and additional context. Go callers can inspect `ValidationError` with
|
||||||
|
`errors.As` and underlying causes with `errors.Is`; CLI integrations should use
|
||||||
|
exit classifications rather than complete diagnostic strings.
|
||||||
|
|
||||||
|
Source publication still completes at confirmed publication of the intended
|
||||||
|
annotated tag. Hosted Gitea delivery retains its separate status. ReleaseKit's
|
||||||
|
deliverables remain the source tag and hosted note page.
|
||||||
|
|
||||||
|
## Upgrade guidance
|
||||||
|
|
||||||
|
1. Update the module dependency:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.2.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Consumers using a separately installed executable can update it with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.2.0
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Use v0.2.0 tooling before adding new profile fields. Select the shared checks
|
||||||
|
appropriate to the product and remove the corresponding duplicate commands
|
||||||
|
from additional checks. Retain assertions about product behavior. Package
|
||||||
|
compilation belongs under validation; executable deliverables use `build`.
|
||||||
|
|
||||||
|
3. For module-based CI, adopt the updated
|
||||||
|
[tag-delivery template](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/examples/woodpecker/tag-delivery.yml)
|
||||||
|
and remove the independent `RELEASEKIT_VERSION` workflow pin. Ensure the
|
||||||
|
application module declares ReleaseKit, align local tool bootstrap with that
|
||||||
|
selection, and retain the product's Go image, delivery profile, and secret
|
||||||
|
mapping. The
|
||||||
|
[Woodpecker guidance](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/consumers/delivery.md#woodpecker-tag-workflows)
|
||||||
|
describes temporary module metadata, older-tag retries, self-bootstrap, and
|
||||||
|
separately installed tools.
|
||||||
|
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/LICENSE) |
|
||||||
|
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.2.0/docs/oss/attribution.md)
|
||||||
117
docs/releases/v0.3.0.md
Normal file
117
docs/releases/v0.3.0.md
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
# ReleaseKit v0.3.0
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
ReleaseKit reduces repeated Git processes, validation memory retention, artifact
|
||||||
|
hashing, output copying, and runtime metadata parsing. It also improves
|
||||||
|
cancellation during validation shutdown and documents module-selected CLI
|
||||||
|
adoption and checksum recovery.
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
- Committed-file checks share one lazy Git batch reader per validation operation.
|
||||||
|
Metadata-only checks start no content reader. Cancellation remains active
|
||||||
|
through reader shutdown, and cleanup reaps the child before validation returns.
|
||||||
|
- Validation releases regular-file source bytes after inspection and reuses
|
||||||
|
compact or parsed results by blob identity for Go formatting, module
|
||||||
|
replacements, Markdown documents, and symlink targets. Findings retain each
|
||||||
|
source path's locations and destination context.
|
||||||
|
- Managed and prebuilt delivery use one local asset verification pass before
|
||||||
|
hosted requests, removing the adjacent declaration-time hashing pass. Changed
|
||||||
|
assets still fail verification; exact remote comparisons, additive retries,
|
||||||
|
and partial-delivery reporting retain their behavior.
|
||||||
|
- Go commands transfer completed output buffers without an additional full
|
||||||
|
copy. Status-only successes release their captures, while failures retain
|
||||||
|
complete diagnostics and underlying causes. Capture remains in memory;
|
||||||
|
allocation costs depend on output size and write chunking.
|
||||||
|
- The runtime version accessor caches its build-metadata fallback safely across
|
||||||
|
calls. Linker-injected versions retain precedence, and the development fallback
|
||||||
|
remains unchanged.
|
||||||
|
- Shutdown errors are attributed to the last validation check that actually read
|
||||||
|
content. Selecting a later check with no applicable files preserves that
|
||||||
|
attribution, and an earlier check failure remains the primary error.
|
||||||
|
- CLI-only consumers have documented adoption through versioned Go tool
|
||||||
|
dependencies. The Woodpecker template supports both tool dependencies and
|
||||||
|
ordinary package dependencies selected by the tagged consumer module.
|
||||||
|
- Synthetic-module workflow tests use isolated module caches. New checksum
|
||||||
|
investigation guidance explains how to distinguish stale local metadata from
|
||||||
|
a download failure while preserving checksum verification and published tags.
|
||||||
|
|
||||||
|
Performance gains depend on the consumer's workload. The changes preserve
|
||||||
|
complete in-memory diagnostics and existing validation selections.
|
||||||
|
|
||||||
|
## Compatibility
|
||||||
|
|
||||||
|
The declared minimum Go version increases from 1.25.0 to 1.26.0. Consumers
|
||||||
|
require Go 1.26.0 or newer; dependency versions are unchanged from v0.2.0.
|
||||||
|
ReleaseKit's maintainer build toolchain and maintained Woodpecker template images
|
||||||
|
use Go 1.26.8; consumers select a local toolchain compatible with their module
|
||||||
|
and the selected ReleaseKit version.
|
||||||
|
|
||||||
|
The root orchestration facade, separate lightweight `buildinfo` facade, public
|
||||||
|
signatures, CLI commands, and profile schema are unchanged. Existing v0.2.0
|
||||||
|
callers and profiles require no source or configuration migration.
|
||||||
|
|
||||||
|
Validation cleanup may now return the caller's cancellation cause where shutdown
|
||||||
|
previously remained blocked. Cleanup failures identify the check that used the
|
||||||
|
reader. Inspect structured validation errors with `errors.As` and underlying
|
||||||
|
causes with `errors.Is`.
|
||||||
|
|
||||||
|
Source publication and hosted delivery retain their separate completion states.
|
||||||
|
ReleaseKit's deliverables remain the source tag and hosted Gitea note page.
|
||||||
|
|
||||||
|
## Upgrade guidance
|
||||||
|
|
||||||
|
1. Use Go 1.26.0 or newer for local tooling and CI before selecting v0.3.0.
|
||||||
|
Updating ReleaseKit in a shared module graph can raise the consumer's declared
|
||||||
|
Go minimum. Select the dependency form appropriate to the consumer.
|
||||||
|
|
||||||
|
Go API consumers:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.3.0
|
||||||
|
go mod tidy
|
||||||
|
```
|
||||||
|
|
||||||
|
Consumers using ReleaseKit for repository release commands can register or
|
||||||
|
upgrade the CLI as a Go tool dependency:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go get -tool gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.3.0
|
||||||
|
go mod tidy
|
||||||
|
go tool releasekit version
|
||||||
|
```
|
||||||
|
|
||||||
|
Review and commit the resulting module changes. API and tool dependencies
|
||||||
|
share the consumer's module graph and selected ReleaseKit version.
|
||||||
|
|
||||||
|
A separately installed executable can be updated with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go install gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.3.0
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Retain existing validation and delivery selections. The performance changes
|
||||||
|
apply automatically. Prepare dependencies before offline checks or builds,
|
||||||
|
and run the consumer's ordinary tests after upgrading.
|
||||||
|
|
||||||
|
3. For module-selected Woodpecker delivery, commit the dependency upgrade before
|
||||||
|
tagging the consumer. Choose a compatible local Go image; delivery and retries
|
||||||
|
continue to use the triggering tag's module selection. CLI-only consumers can
|
||||||
|
use the tool declaration to retain ReleaseKit through `go mod tidy`.
|
||||||
|
|
||||||
|
4. If dependency preparation reports a checksum mismatch, follow the
|
||||||
|
[checksum investigation guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/delivery.md#investigating-module-checksum-mismatches).
|
||||||
|
Repair a confirmed stale cache entry while retaining checksum verification
|
||||||
|
and the application's recorded checksums.
|
||||||
|
|
||||||
|
See the
|
||||||
|
[adoption guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/adoption.md),
|
||||||
|
[candidate check guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/check.md),
|
||||||
|
[delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/delivery.md),
|
||||||
|
and [runtime version guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/consumers/runtime-version.md)
|
||||||
|
for supported behavior and usage.
|
||||||
|
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/LICENSE) |
|
||||||
|
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.3.0/docs/oss/attribution.md)
|
||||||
141
docs/releases/v0.4.0.md
Normal file
141
docs/releases/v0.4.0.md
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
# ReleaseKit v0.4.0
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
ReleaseKit supports releasing individual Go modules within a repository, with
|
||||||
|
module-specific validation, builds, tags, and Gitea release pages. Root-module
|
||||||
|
consumers retain the simple default configuration. This release also improves
|
||||||
|
path resolution, offline source inspection, failure diagnostics, and efficiency.
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
- `Check`, `Publish`, `Build`, and `Deliver` accept `ModuleDir` and expose the
|
||||||
|
resolved module directory, declared module path, and complete tag in their
|
||||||
|
results. Each operation resolves its module identity once. Product commands
|
||||||
|
receive repository and module context, and candidate callbacks receive module
|
||||||
|
identity.
|
||||||
|
- Release tags follow the selected module's physical location and declared major
|
||||||
|
version. For example, `v2.1.0` for
|
||||||
|
`example.com/project/integrations/core/v2` uses
|
||||||
|
`integrations/core/v2.1.0` whether its physical directory is
|
||||||
|
`integrations/core` or `integrations/core/v2`. Its note remains at that physical
|
||||||
|
module's `docs/releases/v2.1.0.md`. Binary version output and asset names retain
|
||||||
|
the semantic version; Git publication and Gitea delivery use the complete tag.
|
||||||
|
- Profiles add `module_dir`. Go checks and configured product commands run from
|
||||||
|
the selected module. Automatic committed-file inputs stop at independent
|
||||||
|
nested modules; vendored files remain included. Nested fixtures remain
|
||||||
|
available to the parent module's product tests.
|
||||||
|
- `ValidationSpec.SharedFiles` and profile `validation.shared_files` select
|
||||||
|
repository-relative literal files for optional file checks. Omission selects
|
||||||
|
the available root copyright, license, and attribution defaults; an explicit
|
||||||
|
list replaces them, and an explicit empty list selects none. Explicit files
|
||||||
|
must exist even with checks disabled. Selection preserves the enabled checks
|
||||||
|
and Go test scope; reference inspection can read destinations elsewhere in
|
||||||
|
the captured repository.
|
||||||
|
- Module releases receive separate Gitea pages, including source-only modules.
|
||||||
|
Relative build output and prebuilt delivery paths share the selected module
|
||||||
|
as their base. Prebuilt receipts bind artifacts to module identity, semantic
|
||||||
|
version, complete tag, source commit, and normalized build settings.
|
||||||
|
- `ci-deliver` accepts the complete event tag. Prepared mode verifies a checkout
|
||||||
|
already detached at that tag, and expected-module and expected-tag checks bind
|
||||||
|
delivery to the CI selection before building or contacting Gitea. The
|
||||||
|
multi-module example shares a module map between its local launcher and
|
||||||
|
Woodpecker workflow. The workflow verifies the tag before reading the mapping,
|
||||||
|
profile, or tool selection, preserving the tagged configuration for retries.
|
||||||
|
|
||||||
|
## Reliability and efficiency
|
||||||
|
|
||||||
|
- Operations resolve the containing Git checkout root when invoked from a child
|
||||||
|
directory. Working-tree and committed module paths resolve symlinks consistently,
|
||||||
|
including paths containing `..`. Committed identity comes from Git objects;
|
||||||
|
page-only delivery can use committed module metadata absent from the worktree.
|
||||||
|
Valid local main-module paths are accepted.
|
||||||
|
- Build failures preserve available identity and settings alongside completed
|
||||||
|
artifacts. Invalid versions retain the public error identity and the CLI's
|
||||||
|
usage-error status. Prebuilt delivery accepts equivalent checkout paths while
|
||||||
|
retaining source and module verification.
|
||||||
|
- Committed release-note and validation reads remain offline in partial clones.
|
||||||
|
Validation reads blob contents and sizes as needed for selected inputs and
|
||||||
|
referenced destinations. Unavailable blobs outside that inspection scope do
|
||||||
|
not prevent applicable checks.
|
||||||
|
- Module-file selection uses ancestor boundary lookups. Operations reuse Go
|
||||||
|
environment discovery while its inputs remain suitable for reuse and acquire
|
||||||
|
Go settings only when Go work needs them. Delivery reuses its local asset
|
||||||
|
verification when uploading missing assets, removing a repeated hashing pass.
|
||||||
|
|
||||||
|
These improvements depend on the repository and workload. Artifact verification,
|
||||||
|
exact remote comparisons, additive retries, and partial-delivery reporting retain
|
||||||
|
their behavior.
|
||||||
|
|
||||||
|
## Compatibility
|
||||||
|
|
||||||
|
This pre-1.0 minor release introduces a clean API and receipt cutover:
|
||||||
|
|
||||||
|
- `TaggedCheckoutRequest.Version` becomes `Tag`, containing the complete Git
|
||||||
|
tag. `VerifyOnly` adds verification of an already prepared checkout.
|
||||||
|
- `PrepareBuildDependencies` now accepts `DependencyPreparationRequest` with
|
||||||
|
repository and module directories.
|
||||||
|
- The private build receipt requires schema version 1 and module identity.
|
||||||
|
Existing receipts must be regenerated before prebuilt delivery.
|
||||||
|
- Root-module committed-file checks exclude independent nested modules. Select
|
||||||
|
those modules separately when their files need release validation.
|
||||||
|
|
||||||
|
The Go minimum remains 1.26.0. Root-module releases retain their existing note
|
||||||
|
path, unprefixed tags, profile defaults, and ordinary workflow without a module
|
||||||
|
map. The root orchestration facade and separate lightweight `buildinfo` facade
|
||||||
|
retain their roles; runtime version access requires no migration.
|
||||||
|
|
||||||
|
Source-tag publication remains the source-release completion point. Hosted page
|
||||||
|
and asset delivery remains asynchronous and can be retried from the same
|
||||||
|
immutable tag. ReleaseKit's deliverables remain its source tag and hosted note
|
||||||
|
page.
|
||||||
|
|
||||||
|
## Upgrade guidance
|
||||||
|
|
||||||
|
1. Select v0.4.0 in each consumer module that uses ReleaseKit. For API consumers:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go get gitea.maximumdirect.net/eric/ReleaseKit@v0.4.0
|
||||||
|
go mod tidy
|
||||||
|
```
|
||||||
|
|
||||||
|
For consumers using the CLI as a Go tool dependency:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go get -tool gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@v0.4.0
|
||||||
|
go mod tidy
|
||||||
|
```
|
||||||
|
|
||||||
|
Review and commit the resulting module and checksum changes together with
|
||||||
|
caller, profile, and workflow updates. Keep historical tag retries paired
|
||||||
|
with the tool and workflow recorded at that tag.
|
||||||
|
|
||||||
|
2. Update preparation API calls for `Tag` and `DependencyPreparationRequest`.
|
||||||
|
For nested modules, set `ModuleDir` or profile `module_dir` to the physical
|
||||||
|
module location, with its own `go.mod` declaration. Keep ordinary `Version`
|
||||||
|
arguments as semantic versions. Use result `ModuleDir`, `ModulePath`, and
|
||||||
|
`Tag` where module identity is needed. Product commands can distinguish their
|
||||||
|
contexts through `RELEASEKIT_REPOSITORY_DIR` and `RELEASEKIT_MODULE_DIR`.
|
||||||
|
|
||||||
|
3. Update `ci-deliver` invocations to pass the full event tag and required
|
||||||
|
`--commit OID`. Use `--prepared` after bootstrap verification and
|
||||||
|
`--expected-module DIR` for mapped launchers. Prepare and commit each binary
|
||||||
|
module's checksums before tagging so dependency preparation leaves tagged
|
||||||
|
source clean. Root-only consumers can retain the ordinary tag workflow.
|
||||||
|
|
||||||
|
4. Rebuild existing prebuilt outputs with the v0.4.0 `build` command before
|
||||||
|
`deliver --assets DIR`. Relative output and asset paths both resolve from the
|
||||||
|
selected module. Review optional shared-file selections and nested-module
|
||||||
|
validation coverage, then run the consumer's ordinary checks.
|
||||||
|
|
||||||
|
See the
|
||||||
|
[adoption guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/consumers/adoption.md),
|
||||||
|
[configuration reference](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/config.md),
|
||||||
|
[CLI contract](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/cli.md),
|
||||||
|
[delivery guide](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/consumers/delivery.md),
|
||||||
|
and [multi-module example](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/examples/multi-module/README.md)
|
||||||
|
for supported usage.
|
||||||
|
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/COPYRIGHT) |
|
||||||
|
[LICENSE](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/LICENSE) |
|
||||||
|
[ATTRIBUTION](https://gitea.maximumdirect.net/eric/ReleaseKit/src/tag/v0.4.0/docs/oss/attribution.md)
|
||||||
132
examples/multi-module/README.md
Normal file
132
examples/multi-module/README.md
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
# Multi-module release example
|
||||||
|
|
||||||
|
This example maps selectors and complete event tags to a physical Go module
|
||||||
|
directory and a repository-root profile. The library derives the release tag
|
||||||
|
from the selected module declaration and physical location; the table only
|
||||||
|
selects the corresponding profile and checkout directory.
|
||||||
|
|
||||||
|
Copy the contents of this directory into a consumer repository root, keeping
|
||||||
|
the listed module directories and profile paths at those locations, then run
|
||||||
|
the launcher from that checkout.
|
||||||
|
|
||||||
|
The sample modules declare Go 1.26.0, matching the current ReleaseKit consumer
|
||||||
|
minimum.
|
||||||
|
|
||||||
|
## Select the release tool
|
||||||
|
|
||||||
|
The module files are setup skeletons. Set `RELEASEKIT_TOOL_VERSION` to a released
|
||||||
|
ReleaseKit version containing module-release support, then register that tool in
|
||||||
|
each consumer module before running the launcher or workflow:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
: "${RELEASEKIT_TOOL_VERSION:?Select a ReleaseKit release with module-release support}"
|
||||||
|
for module_dir in . integrations/ckconfig integrations/core/v2; do
|
||||||
|
go -C "$module_dir" get -tool "gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit@${RELEASEKIT_TOOL_VERSION}"
|
||||||
|
go -C "$module_dir" mod tidy
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
Review and commit the generated tool, dependency, and checksum declarations.
|
||||||
|
The [adoption guide](../../docs/consumers/adoption.md) owns tool registration and
|
||||||
|
coordinated tool/workflow upgrades. The
|
||||||
|
[v0.4.0 release note](../../docs/releases/v0.4.0.md) describes module-release
|
||||||
|
support and migration from earlier versions.
|
||||||
|
|
||||||
|
## Module mapping and publication
|
||||||
|
|
||||||
|
`release-modules.tsv` is literal tab-separated text with four columns:
|
||||||
|
|
||||||
|
1. Local selector.
|
||||||
|
2. Shell pattern matched against a complete event tag.
|
||||||
|
3. Repository-relative physical module directory (`.` means the root module).
|
||||||
|
4. Repository-relative profile path.
|
||||||
|
|
||||||
|
The checked-in patterns are `v[01].*`, `integrations/ckconfig/v*`, and
|
||||||
|
`integrations/core/v2.*`. The helper passes pattern text to the shell's `case`
|
||||||
|
matcher without `eval`. A tag must match exactly one row; missing and ambiguous
|
||||||
|
matches are configuration errors. Module and profile paths may contain spaces.
|
||||||
|
The `core-v2` row places the Go module physically under `integrations/core/v2`
|
||||||
|
and declares a `/v2` module path. ReleaseKit derives the versioned tag under
|
||||||
|
`integrations/core`, while the table retains the full physical path.
|
||||||
|
|
||||||
|
Before running candidate checks offline, prepare each module's dependencies in
|
||||||
|
its own directory:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go -C . mod download
|
||||||
|
go -C integrations/ckconfig mod download
|
||||||
|
go -C integrations/core/v2 mod download
|
||||||
|
```
|
||||||
|
|
||||||
|
Commit each generated `go.sum` with its module files. The binary delivery
|
||||||
|
profile prepares application dependencies in the tagged module before building;
|
||||||
|
the committed sums keep that prepared checkout clean for delivery verification.
|
||||||
|
|
||||||
|
Then select a module and semantic version with the shared launcher:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./release.sh root v1.2.3
|
||||||
|
./release.sh ckconfig v1.2.3
|
||||||
|
./release.sh core-v2 v2.1.0
|
||||||
|
```
|
||||||
|
|
||||||
|
The launcher copies the selected module's `go.mod` and `go.sum` to temporary
|
||||||
|
alternate module files outside the checkout, resolves ReleaseKit from that
|
||||||
|
module's local dependency selection, and builds the tool there. It invokes
|
||||||
|
`publish` with the repository profile and `--expected-module` so the library
|
||||||
|
can verify that the profile agrees with the selected table row. The temporary
|
||||||
|
files and tool are removed on exit. As with any `publish` invocation, commit the
|
||||||
|
selected module's release note and prepare its repository before publishing.
|
||||||
|
|
||||||
|
If an integration depends on a sibling release, publish the dependency first,
|
||||||
|
then publish the integration with the version that consumes it. For example,
|
||||||
|
publish the core release before an integration that requires that release.
|
||||||
|
This declaration does not infer dependency order or rerun the standard suite.
|
||||||
|
|
||||||
|
The maintained [Woodpecker example](woodpecker.yml) uses the same map and
|
||||||
|
selector for root, `ckconfig`, and major-version tags. It verifies and detaches
|
||||||
|
the literal event tag before selecting the module, copies that module's metadata
|
||||||
|
outside the checkout, and builds the ReleaseKit version selected there. It then
|
||||||
|
uses `ci-deliver --prepared` with the mapped profile and expected physical module.
|
||||||
|
The `core-v2` profile demonstrates binary delivery; the other profiles are
|
||||||
|
page-only. Before enabling the workflow, configure each selected profile's
|
||||||
|
`delivery` destination and add the Woodpecker repository secret
|
||||||
|
`releasekit_gitea_token`; the workflow exposes it as
|
||||||
|
`RELEASEKIT_GITEA_TOKEN` only in the delivery step.
|
||||||
|
|
||||||
|
Retries use the selected tag's module files and matching workflow. Tags whose
|
||||||
|
tool predates this interface use their corresponding historical workflow.
|
||||||
|
|
||||||
|
## Local source verification
|
||||||
|
|
||||||
|
For verification before a compatible release is published, copy this example
|
||||||
|
into a disposable consumer checkout. Set `RELEASEKIT_SOURCE` to the absolute
|
||||||
|
path of a prepared ReleaseKit checkout, then select its source in those fixture
|
||||||
|
modules:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
: "${RELEASEKIT_SOURCE:?Set the absolute ReleaseKit checkout path}"
|
||||||
|
for module_dir in . integrations/ckconfig integrations/core/v2; do
|
||||||
|
go -C "$module_dir" mod edit \
|
||||||
|
-require=gitea.maximumdirect.net/eric/ReleaseKit@v0.0.0 \
|
||||||
|
-replace="gitea.maximumdirect.net/eric/ReleaseKit=$RELEASEKIT_SOURCE" \
|
||||||
|
-tool=gitea.maximumdirect.net/eric/ReleaseKit/cmd/releasekit
|
||||||
|
GOTOOLCHAIN=local GOWORK=off go -C "$module_dir" mod tidy
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
Here `v0.0.0` is a fixture placeholder resolved by the local replacement.
|
||||||
|
Keep these declarations in the disposable checkout. Add representative product
|
||||||
|
source and each selected product's module-local release note, then commit the
|
||||||
|
fixture and run the source-selected tool without publishing:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go tool releasekit check --config releasekit-root.json v1.2.3
|
||||||
|
go -C integrations/ckconfig tool releasekit check --config releasekit-ckconfig.json v1.2.3
|
||||||
|
go -C integrations/core/v2 tool releasekit check --config releasekit-core-v2.json v2.1.0
|
||||||
|
```
|
||||||
|
|
||||||
|
These commands use the repository-root profile paths even when invoked from a
|
||||||
|
child module. The core profile also verifies the native binary and injected
|
||||||
|
version. Prepared dependencies allow this verification with `GOPROXY=off` and
|
||||||
|
`GOSUMDB=off`.
|
||||||
3
examples/multi-module/go.mod
Normal file
3
examples/multi-module/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module example.com/multi-module-consumer
|
||||||
|
|
||||||
|
go 1.26.0
|
||||||
3
examples/multi-module/integrations/ckconfig/go.mod
Normal file
3
examples/multi-module/integrations/ckconfig/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module example.com/multi-module-consumer/integrations/ckconfig
|
||||||
|
|
||||||
|
go 1.26.0
|
||||||
3
examples/multi-module/integrations/core/v2/go.mod
Normal file
3
examples/multi-module/integrations/core/v2/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module example.com/multi-module-consumer/integrations/core/v2
|
||||||
|
|
||||||
|
go 1.26.0
|
||||||
11
examples/multi-module/integrations/core/v2/main.go
Normal file
11
examples/multi-module/integrations/core/v2/main.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/buildinfo"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Printf("core %s\n", buildinfo.Version())
|
||||||
|
}
|
||||||
4
examples/multi-module/release-modules.tsv
Normal file
4
examples/multi-module/release-modules.tsv
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# selector<TAB>tag pattern<TAB>module directory<TAB>profile path
|
||||||
|
root v[01].* . releasekit-root.json
|
||||||
|
ckconfig integrations/ckconfig/v* integrations/ckconfig releasekit-ckconfig.json
|
||||||
|
core-v2 integrations/core/v2.* integrations/core/v2 releasekit-core-v2.json
|
||||||
|
48
examples/multi-module/release.sh
Executable file
48
examples/multi-module/release.sh
Executable file
@@ -0,0 +1,48 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
echo "usage: release.sh SELECTOR VERSION" >&2
|
||||||
|
exit 2
|
||||||
|
}
|
||||||
|
|
||||||
|
[ "$#" -eq 2 ] || usage
|
||||||
|
selector=$1
|
||||||
|
version=$2
|
||||||
|
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
|
||||||
|
repository_dir=$(git -C "$script_dir" rev-parse --show-toplevel)
|
||||||
|
|
||||||
|
bootstrap_dir=$(mktemp -d "$(dirname "$repository_dir")/.releasekit-bootstrap.XXXXXX")
|
||||||
|
selection_file=$bootstrap_dir/module-selection.tsv
|
||||||
|
trap 'rm -rf "$bootstrap_dir"' EXIT
|
||||||
|
"$script_dir/select-module.sh" selector "$selector" > "$selection_file"
|
||||||
|
|
||||||
|
tab=$(printf '\t')
|
||||||
|
IFS="$tab" read -r selected_selector tag_pattern module_dir profile_path < "$selection_file"
|
||||||
|
module_path=$repository_dir
|
||||||
|
if [ "$module_dir" != . ]; then
|
||||||
|
module_path=$repository_dir/$module_dir
|
||||||
|
fi
|
||||||
|
|
||||||
|
cp "$module_path/go.mod" "$bootstrap_dir/releasekit.mod"
|
||||||
|
if [ -f "$module_path/go.sum" ]; then
|
||||||
|
cp "$module_path/go.sum" "$bootstrap_dir/releasekit.sum"
|
||||||
|
else
|
||||||
|
: > "$bootstrap_dir/releasekit.sum"
|
||||||
|
fi
|
||||||
|
|
||||||
|
releasekit_module=gitea.maximumdirect.net/eric/ReleaseKit
|
||||||
|
(
|
||||||
|
cd "$module_path"
|
||||||
|
export GOWORK=off
|
||||||
|
export GOTOOLCHAIN=local
|
||||||
|
go list -mod=mod -modfile="$bootstrap_dir/releasekit.mod" -m "$releasekit_module"
|
||||||
|
go build -mod=mod -modfile="$bootstrap_dir/releasekit.mod" \
|
||||||
|
-o "$bootstrap_dir/releasekit" "$releasekit_module/cmd/releasekit"
|
||||||
|
)
|
||||||
|
|
||||||
|
"$bootstrap_dir/releasekit" publish \
|
||||||
|
--repo "$repository_dir" \
|
||||||
|
--config "$profile_path" \
|
||||||
|
--expected-module "$module_dir" \
|
||||||
|
"$version"
|
||||||
4
examples/multi-module/releasekit-ckconfig.json
Normal file
4
examples/multi-module/releasekit-ckconfig.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"product": "Example Consumer Integration",
|
||||||
|
"module_dir": "integrations/ckconfig"
|
||||||
|
}
|
||||||
9
examples/multi-module/releasekit-core-v2.json
Normal file
9
examples/multi-module/releasekit-core-v2.json
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"product": "Example Consumer Core v2",
|
||||||
|
"module_dir": "integrations/core/v2",
|
||||||
|
"build": {
|
||||||
|
"main_package": ".",
|
||||||
|
"binary_name": "core",
|
||||||
|
"targets": ["linux/amd64"]
|
||||||
|
}
|
||||||
|
}
|
||||||
4
examples/multi-module/releasekit-root.json
Normal file
4
examples/multi-module/releasekit-root.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"product": "Example Consumer",
|
||||||
|
"module_dir": "."
|
||||||
|
}
|
||||||
70
examples/multi-module/select-module.sh
Executable file
70
examples/multi-module/select-module.sh
Executable file
@@ -0,0 +1,70 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
echo "usage: select-module.sh selector|tag VALUE" >&2
|
||||||
|
exit 2
|
||||||
|
}
|
||||||
|
|
||||||
|
[ "$#" -eq 2 ] || usage
|
||||||
|
mode=$1
|
||||||
|
value=$2
|
||||||
|
case "$mode" in
|
||||||
|
selector|tag) ;;
|
||||||
|
*) usage ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
|
||||||
|
mapping=${RELEASEKIT_MODULE_MAP:-$script_dir/release-modules.tsv}
|
||||||
|
[ -f "$mapping" ] || { echo "module map not found: $mapping" >&2; exit 2; }
|
||||||
|
|
||||||
|
tab=$(printf '\t')
|
||||||
|
matches=0
|
||||||
|
selected_selector=
|
||||||
|
selected_pattern=
|
||||||
|
selected_module=
|
||||||
|
selected_profile=
|
||||||
|
|
||||||
|
while IFS="$tab" read -r selector pattern module profile || [ -n "${selector:-}${pattern:-}${module:-}${profile:-}" ]; do
|
||||||
|
case "${selector:-}" in
|
||||||
|
''|\#*) continue ;;
|
||||||
|
esac
|
||||||
|
fields=$(awk -F '\t' '{ print NF }' <<EOF
|
||||||
|
$selector$tab$pattern$tab$module$tab$profile
|
||||||
|
EOF
|
||||||
|
)
|
||||||
|
[ "$fields" -eq 4 ] || { echo "module map row must have four tab-separated fields" >&2; exit 2; }
|
||||||
|
[ -n "$pattern" ] && [ -n "$module" ] && [ -n "$profile" ] || {
|
||||||
|
echo "module map row has an empty field for selector $selector" >&2
|
||||||
|
exit 2
|
||||||
|
}
|
||||||
|
|
||||||
|
matched=false
|
||||||
|
if [ "$mode" = selector ]; then
|
||||||
|
[ "$selector" = "$value" ] && matched=true
|
||||||
|
else
|
||||||
|
# The value remains a shell pattern in this case statement; it is never eval'd.
|
||||||
|
case "$value" in
|
||||||
|
$pattern) matched=true ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
if [ "$matched" = true ]; then
|
||||||
|
matches=$((matches + 1))
|
||||||
|
selected_selector=$selector
|
||||||
|
selected_pattern=$pattern
|
||||||
|
selected_module=$module
|
||||||
|
selected_profile=$profile
|
||||||
|
fi
|
||||||
|
done < "$mapping"
|
||||||
|
|
||||||
|
if [ "$matches" -ne 1 ]; then
|
||||||
|
if [ "$matches" -eq 0 ]; then
|
||||||
|
echo "no module map row matches $mode $value" >&2
|
||||||
|
else
|
||||||
|
echo "module map has ambiguous rows for $mode $value" >&2
|
||||||
|
fi
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '%s\t%s\t%s\t%s\n' \
|
||||||
|
"$selected_selector" "$selected_pattern" "$selected_module" "$selected_profile"
|
||||||
63
examples/multi-module/woodpecker.yml
Normal file
63
examples/multi-module/woodpecker.yml
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
when:
|
||||||
|
- event: tag
|
||||||
|
ref:
|
||||||
|
include:
|
||||||
|
- refs/tags/v[01].*
|
||||||
|
- refs/tags/integrations/ckconfig/v*
|
||||||
|
- refs/tags/integrations/core/v2.*
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: deliver
|
||||||
|
image: golang:1.26.8-bookworm
|
||||||
|
environment:
|
||||||
|
RELEASEKIT_GITEA_TOKEN:
|
||||||
|
from_secret: releasekit_gitea_token
|
||||||
|
commands:
|
||||||
|
- |
|
||||||
|
set -eu
|
||||||
|
test -n "$${CI_COMMIT_TAG}"
|
||||||
|
test -n "$${CI_COMMIT_SHA}"
|
||||||
|
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
tag_commit=$(git rev-parse --verify "refs/tags/$${CI_COMMIT_TAG}^{commit}")
|
||||||
|
expected_commit=$(printf '%s' "$${CI_COMMIT_SHA}" | tr '[:upper:]' '[:lower:]')
|
||||||
|
test "$(printf '%s' "$${tag_commit}" | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
git checkout --detach "$${tag_commit}"
|
||||||
|
test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
test -z "$(git status --porcelain --untracked-files=all)"
|
||||||
|
|
||||||
|
bootstrap_dir=$(mktemp -d "$${CI_WORKSPACE%/*}/.releasekit-bootstrap.XXXXXX")
|
||||||
|
trap 'rm -rf "$${bootstrap_dir}"' EXIT
|
||||||
|
selection_file="$${bootstrap_dir}/module-selection.tsv"
|
||||||
|
"$${CI_WORKSPACE}/select-module.sh" tag "$${CI_COMMIT_TAG}" > "$${selection_file}"
|
||||||
|
tab=$(printf '\t')
|
||||||
|
IFS="$${tab}" read -r selector tag_pattern module_dir profile_path < "$${selection_file}"
|
||||||
|
module_path="$${CI_WORKSPACE}"
|
||||||
|
if [ "$${module_dir}" != . ]; then
|
||||||
|
module_path="$${CI_WORKSPACE}/$${module_dir}"
|
||||||
|
fi
|
||||||
|
cp "$${module_path}/go.mod" "$${bootstrap_dir}/go.mod"
|
||||||
|
if [ -f "$${module_path}/go.sum" ]; then
|
||||||
|
cp "$${module_path}/go.sum" "$${bootstrap_dir}/go.sum"
|
||||||
|
else
|
||||||
|
: > "$${bootstrap_dir}/go.sum"
|
||||||
|
fi
|
||||||
|
cp "$${bootstrap_dir}/go.mod" "$${bootstrap_dir}/releasekit.mod"
|
||||||
|
cp "$${bootstrap_dir}/go.sum" "$${bootstrap_dir}/releasekit.sum"
|
||||||
|
|
||||||
|
export GOWORK=off
|
||||||
|
export GOTOOLCHAIN=local
|
||||||
|
releasekit_module=gitea.maximumdirect.net/eric/ReleaseKit
|
||||||
|
(
|
||||||
|
cd "$${module_path}"
|
||||||
|
go list -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" -m "$${releasekit_module}"
|
||||||
|
go build -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" \
|
||||||
|
-o "$${bootstrap_dir}/releasekit" "$${releasekit_module}/cmd/releasekit"
|
||||||
|
)
|
||||||
|
"$${bootstrap_dir}/releasekit" ci-deliver \
|
||||||
|
--repo "$${CI_WORKSPACE}" \
|
||||||
|
--config "$${profile_path}" \
|
||||||
|
--expected-module "$${module_dir}" \
|
||||||
|
--prepared \
|
||||||
|
--commit "$${CI_COMMIT_SHA}" \
|
||||||
|
"$${CI_COMMIT_TAG}"
|
||||||
15
examples/releasekit-binary.json
Normal file
15
examples/releasekit-binary.json
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"product": "Example",
|
||||||
|
"remote": "origin",
|
||||||
|
"build": {
|
||||||
|
"main_package": "./cmd/example",
|
||||||
|
"binary_name": "example",
|
||||||
|
"targets": ["linux/amd64", "linux/arm64", "darwin/arm64"]
|
||||||
|
},
|
||||||
|
"delivery": {
|
||||||
|
"base_url": "https://gitea.example",
|
||||||
|
"owner": "example",
|
||||||
|
"repository": "example",
|
||||||
|
"token_env": "RELEASEKIT_GITEA_TOKEN"
|
||||||
|
}
|
||||||
|
}
|
||||||
10
examples/releasekit.json
Normal file
10
examples/releasekit.json
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"product": "Example",
|
||||||
|
"remote": "origin",
|
||||||
|
"delivery": {
|
||||||
|
"base_url": "https://gitea.example",
|
||||||
|
"owner": "example",
|
||||||
|
"repository": "example",
|
||||||
|
"token_env": "RELEASEKIT_GITEA_TOKEN"
|
||||||
|
}
|
||||||
|
}
|
||||||
34
examples/woodpecker/releasekit-source-delivery.yml
Normal file
34
examples/woodpecker/releasekit-source-delivery.yml
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
when:
|
||||||
|
- event: tag
|
||||||
|
ref: refs/tags/v*
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: deliver
|
||||||
|
image: golang:1.26.8-bookworm
|
||||||
|
environment:
|
||||||
|
RELEASEKIT_GITEA_TOKEN:
|
||||||
|
from_secret: releasekit_gitea_token
|
||||||
|
commands:
|
||||||
|
- |
|
||||||
|
set -eu
|
||||||
|
test -n "$${CI_COMMIT_TAG}"
|
||||||
|
test -n "$${CI_COMMIT_SHA}"
|
||||||
|
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
tag_commit=$(git rev-parse "refs/tags/$${CI_COMMIT_TAG}^{commit}")
|
||||||
|
expected_commit=$(printf '%s' "$${CI_COMMIT_SHA}" | tr '[:upper:]' '[:lower:]')
|
||||||
|
test "$(printf '%s' "$${tag_commit}" | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
git checkout --detach "$${tag_commit}"
|
||||||
|
test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
test -z "$(git status --porcelain --untracked-files=all)"
|
||||||
|
|
||||||
|
bootstrap_dir=$(mktemp -d "$${CI_WORKSPACE%/*}/.releasekit-source.XXXXXX")
|
||||||
|
trap 'rm -rf "$${bootstrap_dir}"' EXIT
|
||||||
|
export GOWORK=off
|
||||||
|
export GOTOOLCHAIN=local
|
||||||
|
go build -mod=readonly -o "$${bootstrap_dir}/releasekit" ./cmd/releasekit
|
||||||
|
"$${bootstrap_dir}/releasekit" ci-deliver \
|
||||||
|
--repo "$${CI_WORKSPACE}" \
|
||||||
|
--prepared \
|
||||||
|
--commit "$${CI_COMMIT_SHA}" \
|
||||||
|
"$${CI_COMMIT_TAG}"
|
||||||
50
examples/woodpecker/tag-delivery.yml
Normal file
50
examples/woodpecker/tag-delivery.yml
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- GO_IMAGE: golang:1.26.8-bookworm
|
||||||
|
|
||||||
|
when:
|
||||||
|
- event: tag
|
||||||
|
ref: refs/tags/v*
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: deliver
|
||||||
|
image: ${GO_IMAGE}
|
||||||
|
environment:
|
||||||
|
RELEASEKIT_GITEA_TOKEN:
|
||||||
|
from_secret: releasekit_gitea_token
|
||||||
|
commands:
|
||||||
|
- |
|
||||||
|
set -eu
|
||||||
|
test -n "$${CI_COMMIT_TAG}"
|
||||||
|
test -n "$${CI_COMMIT_SHA}"
|
||||||
|
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
|
||||||
|
tag_commit=$(git rev-parse "refs/tags/$${CI_COMMIT_TAG}^{commit}")
|
||||||
|
expected_commit=$(printf '%s' "$${CI_COMMIT_SHA}" | tr '[:upper:]' '[:lower:]')
|
||||||
|
test "$(printf '%s' "$${tag_commit}" | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
git checkout --detach "$${tag_commit}"
|
||||||
|
test "$(git rev-parse HEAD | tr '[:upper:]' '[:lower:]')" = "$${expected_commit}"
|
||||||
|
test -z "$(git status --porcelain --untracked-files=all)"
|
||||||
|
|
||||||
|
bootstrap_dir=$(mktemp -d "$${CI_WORKSPACE%/*}/.releasekit-bootstrap.XXXXXX")
|
||||||
|
trap 'rm -rf "$${bootstrap_dir}"' EXIT
|
||||||
|
cp go.mod "$${bootstrap_dir}/go.mod"
|
||||||
|
if [ -f go.sum ]; then
|
||||||
|
cp go.sum "$${bootstrap_dir}/go.sum"
|
||||||
|
else
|
||||||
|
: > "$${bootstrap_dir}/go.sum"
|
||||||
|
fi
|
||||||
|
cp "$${bootstrap_dir}/go.mod" "$${bootstrap_dir}/releasekit.mod"
|
||||||
|
cp "$${bootstrap_dir}/go.sum" "$${bootstrap_dir}/releasekit.sum"
|
||||||
|
|
||||||
|
export GOWORK=off
|
||||||
|
export GOTOOLCHAIN=local
|
||||||
|
releasekit_module=gitea.maximumdirect.net/eric/ReleaseKit
|
||||||
|
go list -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" -m "$${releasekit_module}"
|
||||||
|
go build -mod=mod -modfile="$${bootstrap_dir}/releasekit.mod" \
|
||||||
|
-o "$${bootstrap_dir}/releasekit" "$${releasekit_module}/cmd/releasekit"
|
||||||
|
"$${bootstrap_dir}/releasekit" ci-deliver \
|
||||||
|
--repo "$${CI_WORKSPACE}" \
|
||||||
|
--prepared \
|
||||||
|
--commit "$${CI_COMMIT_SHA}" \
|
||||||
|
"$${CI_COMMIT_TAG}"
|
||||||
8
go.mod
Normal file
8
go.mod
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
module gitea.maximumdirect.net/eric/ReleaseKit
|
||||||
|
|
||||||
|
go 1.26.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/yuin/goldmark/v2 v2.1.6
|
||||||
|
golang.org/x/mod v0.40.0
|
||||||
|
)
|
||||||
4
go.sum
Normal file
4
go.sum
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
github.com/yuin/goldmark/v2 v2.1.6 h1:igy0q9JcqovoFXFx/XjtU8sHVhcUHavPj2sA3EoKJUE=
|
||||||
|
github.com/yuin/goldmark/v2 v2.1.6/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ=
|
||||||
|
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
|
||||||
|
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
|
||||||
6
ideas.md
Normal file
6
ideas.md
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
# ReleaseKit ideas
|
||||||
|
|
||||||
|
The [architecture policy](docs/policy/architecture.md) and
|
||||||
|
[ADRs](docs/adr/) record the adopted design decisions. The
|
||||||
|
[v0.2.0 release note](docs/releases/v0.2.0.md) summarizes the implemented
|
||||||
|
capabilities.
|
||||||
436
internal/apicheck/main.go
Normal file
436
internal/apicheck/main.go
Normal file
@@ -0,0 +1,436 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"go/importer"
|
||||||
|
"go/token"
|
||||||
|
"go/types"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const modulePath = "gitea.maximumdirect.net/eric/ReleaseKit"
|
||||||
|
|
||||||
|
var facades = []string{modulePath, modulePath + "/buildinfo"}
|
||||||
|
|
||||||
|
type listedPackage struct {
|
||||||
|
ImportPath string
|
||||||
|
Export string
|
||||||
|
Standard bool
|
||||||
|
Imports []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
os.Exit(run(context.Background(), ".", os.Stdout, os.Stderr))
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(ctx context.Context, dir string, stdout, stderr io.Writer) int {
|
||||||
|
if err := checkRepository(ctx, dir); err != nil {
|
||||||
|
fmt.Fprintln(stderr, err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stdout, "public API and dependency boundaries pass")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkRepository(ctx context.Context, dir string) error {
|
||||||
|
packages, err := listPackages(ctx, dir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := checkImportDirections(packages); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
lookup := make(map[string]string, len(packages))
|
||||||
|
for _, pkg := range packages {
|
||||||
|
if pkg.Export != "" {
|
||||||
|
lookup[pkg.ImportPath] = pkg.Export
|
||||||
|
}
|
||||||
|
}
|
||||||
|
apiImporter := importer.ForCompiler(token.NewFileSet(), "gc", func(path string) (io.ReadCloser, error) {
|
||||||
|
export, ok := lookup[path]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("no compiled export data for %q", path)
|
||||||
|
}
|
||||||
|
return os.Open(export)
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, path := range facades {
|
||||||
|
pkg, err := apiImporter.Import(path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("load facade %s: %w", path, err)
|
||||||
|
}
|
||||||
|
if violations := checkExports(pkg); len(violations) != 0 {
|
||||||
|
return fmt.Errorf("facade %s has invalid public contracts:\n %s", path, strings.Join(violations, "\n "))
|
||||||
|
}
|
||||||
|
if path == modulePath {
|
||||||
|
if violations := checkValidationTypes(pkg); len(violations) != 0 {
|
||||||
|
return fmt.Errorf("facade %s has invalid validation diagnostics:\n %s", path, strings.Join(violations, "\n "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkValidationTypes(pkg *types.Package) []string {
|
||||||
|
var violations []string
|
||||||
|
for _, name := range []string{"ValidationCheck", "ValidationFinding", "FileSizeMeasurement", "ValidationError"} {
|
||||||
|
object, ok := pkg.Scope().Lookup(name).(*types.TypeName)
|
||||||
|
if !ok {
|
||||||
|
violations = append(violations, fmt.Sprintf("missing facade-owned type %s", name))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
named, ok := types.Unalias(object.Type()).(*types.Named)
|
||||||
|
if !ok || named.Obj().Pkg() == nil || named.Obj().Pkg().Path() != pkg.Path() {
|
||||||
|
violations = append(violations, fmt.Sprintf("%s is not a facade-owned named type", name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validationError, ok := pkg.Scope().Lookup("ValidationError").(*types.TypeName)
|
||||||
|
if !ok {
|
||||||
|
return violations
|
||||||
|
}
|
||||||
|
named, ok := types.Unalias(validationError.Type()).(*types.Named)
|
||||||
|
if !ok {
|
||||||
|
return violations
|
||||||
|
}
|
||||||
|
structure, ok := named.Underlying().(*types.Struct)
|
||||||
|
if !ok {
|
||||||
|
return append(violations, "ValidationError is not a struct")
|
||||||
|
}
|
||||||
|
fields := map[string]string{
|
||||||
|
"Check": "ValidationCheck",
|
||||||
|
"Findings": "[]ValidationFinding",
|
||||||
|
"Measurement": "*FileSizeMeasurement",
|
||||||
|
}
|
||||||
|
for fieldName, expected := range fields {
|
||||||
|
fieldIndex := -1
|
||||||
|
for index := 0; index < structure.NumFields(); index++ {
|
||||||
|
if structure.Field(index).Name() == fieldName && structure.Field(index).Exported() {
|
||||||
|
fieldIndex = index
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fieldIndex < 0 || !validationFieldMatches(structure.Field(fieldIndex).Type(), expected, pkg.Path()) {
|
||||||
|
violations = append(violations, fmt.Sprintf("ValidationError.%s must expose %s", fieldName, expected))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cause := fieldByName(structure, "Cause"); cause == nil || !cause.Exported() || !types.Identical(cause.Type(), types.Universe.Lookup("error").Type()) {
|
||||||
|
violations = append(violations, "ValidationError.Cause must expose error")
|
||||||
|
}
|
||||||
|
return violations
|
||||||
|
}
|
||||||
|
|
||||||
|
func fieldByName(structure *types.Struct, name string) *types.Var {
|
||||||
|
for index := 0; index < structure.NumFields(); index++ {
|
||||||
|
if structure.Field(index).Name() == name {
|
||||||
|
return structure.Field(index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validationFieldMatches(fieldType types.Type, expected, packagePath string) bool {
|
||||||
|
switch expected {
|
||||||
|
case "[]ValidationFinding":
|
||||||
|
slice, ok := types.Unalias(fieldType).(*types.Slice)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
fieldType = slice.Elem()
|
||||||
|
case "*FileSizeMeasurement":
|
||||||
|
pointer, ok := types.Unalias(fieldType).(*types.Pointer)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
fieldType = pointer.Elem()
|
||||||
|
}
|
||||||
|
named, ok := types.Unalias(fieldType).(*types.Named)
|
||||||
|
return ok && named.Obj().Pkg() != nil && named.Obj().Pkg().Path() == packagePath && named.Obj().Name() == strings.TrimLeft(expected, "*[]")
|
||||||
|
}
|
||||||
|
|
||||||
|
func listPackages(ctx context.Context, dir string) ([]listedPackage, error) {
|
||||||
|
cmd := exec.CommandContext(ctx, "go", "list", "-deps", "-export", "-json", "./...")
|
||||||
|
cmd.Dir = dir
|
||||||
|
output, err := cmd.Output()
|
||||||
|
if err != nil {
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if errors.As(err, &exitErr) {
|
||||||
|
return nil, fmt.Errorf("go list -deps -export failed: %s", strings.TrimSpace(string(exitErr.Stderr)))
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("go list -deps -export: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(strings.NewReader(string(output)))
|
||||||
|
var packages []listedPackage
|
||||||
|
for {
|
||||||
|
var pkg listedPackage
|
||||||
|
if err := decoder.Decode(&pkg); errors.Is(err, io.EOF) {
|
||||||
|
break
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, fmt.Errorf("decode go list output: %w", err)
|
||||||
|
}
|
||||||
|
packages = append(packages, pkg)
|
||||||
|
}
|
||||||
|
return packages, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkImportDirections(packages []listedPackage) error {
|
||||||
|
byPath := make(map[string]listedPackage, len(packages))
|
||||||
|
for _, pkg := range packages {
|
||||||
|
byPath[pkg.ImportPath] = pkg
|
||||||
|
}
|
||||||
|
var violations []string
|
||||||
|
|
||||||
|
for _, pkg := range packages {
|
||||||
|
if !isInternalPackage(pkg.ImportPath) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, imported := range pkg.Imports {
|
||||||
|
commandDependency := strings.HasPrefix(imported, modulePath+"/cmd/")
|
||||||
|
owner := commandInternalRoot(pkg.ImportPath)
|
||||||
|
ownHelper := owner != "" && strings.HasPrefix(imported+"/", owner)
|
||||||
|
if imported == modulePath || imported == modulePath+"/buildinfo" || commandDependency && !ownHelper {
|
||||||
|
violations = append(violations, fmt.Sprintf("internal package %s imports public or command package %s", pkg.ImportPath, imported))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
seen := make(map[string]bool)
|
||||||
|
var visit func(string)
|
||||||
|
visit = func(path string) {
|
||||||
|
if seen[path] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[path] = true
|
||||||
|
pkg, ok := byPath[path]
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if path != modulePath+"/buildinfo" && !pkg.Standard {
|
||||||
|
if !strings.HasPrefix(path, modulePath+"/internal/") {
|
||||||
|
violations = append(violations, fmt.Sprintf("buildinfo depends on non-runtime package %s", path))
|
||||||
|
} else if forbiddenRuntimeDependency(path) {
|
||||||
|
violations = append(violations, fmt.Sprintf("buildinfo depends on excluded implementation package %s", path))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, imported := range pkg.Imports {
|
||||||
|
visit(imported)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
visit(modulePath + "/buildinfo")
|
||||||
|
|
||||||
|
if len(violations) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
sort.Strings(violations)
|
||||||
|
return errors.New(strings.Join(violations, "\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func isInternalPackage(path string) bool {
|
||||||
|
return strings.HasPrefix(path, modulePath+"/") &&
|
||||||
|
(strings.Contains(strings.TrimPrefix(path, modulePath), "/internal/") || strings.HasSuffix(path, "/internal"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// commandInternalRoot identifies the helper subtree owned by one executable.
|
||||||
|
func commandInternalRoot(path string) string {
|
||||||
|
if !strings.HasPrefix(path, modulePath+"/cmd/") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
relative := strings.TrimPrefix(path, modulePath+"/cmd/")
|
||||||
|
owner, _, ok := strings.Cut(relative+"/", "/internal/")
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return modulePath + "/cmd/" + owner + "/internal/"
|
||||||
|
}
|
||||||
|
|
||||||
|
func forbiddenRuntimeDependency(path string) bool {
|
||||||
|
for _, part := range strings.Split(strings.ToLower(path), "/") {
|
||||||
|
switch part {
|
||||||
|
case "orchestration", "orchestrator", "engine", "release", "process", "build", "builder", "gitea", "delivery", "cli":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
var allowedExternalTypes = map[string]bool{
|
||||||
|
"context.Context": true,
|
||||||
|
"io.Reader": true,
|
||||||
|
"io.Writer": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkExports(pkg *types.Package) []string {
|
||||||
|
checker := contractChecker{
|
||||||
|
packagePath: pkg.Path(),
|
||||||
|
checkedTypes: make(map[types.Type]bool),
|
||||||
|
allowedNamed: allowedExternalTypes,
|
||||||
|
violationsSet: make(map[string]bool),
|
||||||
|
}
|
||||||
|
for _, name := range pkg.Scope().Names() {
|
||||||
|
if !token.IsExported(name) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
object := pkg.Scope().Lookup(name)
|
||||||
|
switch obj := object.(type) {
|
||||||
|
case *types.TypeName:
|
||||||
|
checker.checkType(obj.Type(), name)
|
||||||
|
case *types.Func:
|
||||||
|
checker.checkType(obj.Type(), name)
|
||||||
|
case *types.Var:
|
||||||
|
checker.checkType(obj.Type(), name)
|
||||||
|
case *types.Const:
|
||||||
|
checker.checkType(obj.Type(), name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return checker.violations()
|
||||||
|
}
|
||||||
|
|
||||||
|
type contractChecker struct {
|
||||||
|
packagePath string
|
||||||
|
checkedTypes map[types.Type]bool
|
||||||
|
allowedNamed map[string]bool
|
||||||
|
violationsSet map[string]bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *contractChecker) violations() []string {
|
||||||
|
violations := make([]string, 0, len(c.violationsSet))
|
||||||
|
for violation := range c.violationsSet {
|
||||||
|
violations = append(violations, violation)
|
||||||
|
}
|
||||||
|
sort.Strings(violations)
|
||||||
|
return violations
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *contractChecker) violation(message string) {
|
||||||
|
c.violationsSet[message] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *contractChecker) checkType(typ types.Type, path string) {
|
||||||
|
if typ == nil || c.checkedTypes[typ] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.checkedTypes[typ] = true
|
||||||
|
|
||||||
|
switch typ := typ.(type) {
|
||||||
|
case *types.Basic:
|
||||||
|
case *types.Alias:
|
||||||
|
if params := typ.TypeParams(); params != nil {
|
||||||
|
for i := 0; i < params.Len(); i++ {
|
||||||
|
c.checkType(params.At(i), path+" type parameter")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if args := typ.TypeArgs(); args != nil {
|
||||||
|
for i := 0; i < args.Len(); i++ {
|
||||||
|
c.checkType(args.At(i), path+" type argument")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.checkType(types.Unalias(typ), path)
|
||||||
|
case *types.Named:
|
||||||
|
object := typ.Obj()
|
||||||
|
if object.Pkg() != nil && object.Pkg().Path() != c.packagePath {
|
||||||
|
key := object.Pkg().Path() + "." + object.Name()
|
||||||
|
if !c.allowedNamed[key] {
|
||||||
|
c.violation(fmt.Sprintf("%s exposes named type %s", path, key))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if params := typ.TypeParams(); params != nil {
|
||||||
|
for i := 0; i < params.Len(); i++ {
|
||||||
|
c.checkType(params.At(i), path+" type parameter")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if args := typ.TypeArgs(); args != nil {
|
||||||
|
for i := 0; i < args.Len(); i++ {
|
||||||
|
c.checkType(args.At(i), path+" type argument")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.checkType(typ.Underlying(), path)
|
||||||
|
for _, receiver := range []types.Type{typ, types.NewPointer(typ)} {
|
||||||
|
methodSet := types.NewMethodSet(receiver)
|
||||||
|
for i := 0; i < methodSet.Len(); i++ {
|
||||||
|
method := methodSet.At(i).Obj()
|
||||||
|
if !method.Exported() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
function, _ := method.(*types.Func)
|
||||||
|
if method.Pkg() != nil && method.Pkg().Path() != c.packagePath && !c.allowedMethod(function) {
|
||||||
|
c.violation(fmt.Sprintf("%s promotes method %s from %s", path, method.Name(), method.Pkg().Path()))
|
||||||
|
}
|
||||||
|
c.checkType(method.Type(), path+" method "+method.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case *types.Pointer:
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Array:
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Slice:
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Map:
|
||||||
|
c.checkType(typ.Key(), path)
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Chan:
|
||||||
|
c.checkType(typ.Elem(), path)
|
||||||
|
case *types.Struct:
|
||||||
|
for i := 0; i < typ.NumFields(); i++ {
|
||||||
|
field := typ.Field(i)
|
||||||
|
if field.Exported() || field.Embedded() {
|
||||||
|
c.checkType(field.Type(), path+" field "+field.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case *types.Interface:
|
||||||
|
typ.Complete()
|
||||||
|
for i := 0; i < typ.NumMethods(); i++ {
|
||||||
|
method := typ.Method(i)
|
||||||
|
if method.Pkg() != nil && method.Pkg().Path() != c.packagePath && !c.allowedMethod(method) {
|
||||||
|
c.violation(fmt.Sprintf("%s exposes method %s from %s", path, method.Name(), method.Pkg().Path()))
|
||||||
|
}
|
||||||
|
c.checkType(method.Type(), path+" method "+method.Name())
|
||||||
|
}
|
||||||
|
for i := 0; i < typ.NumEmbeddeds(); i++ {
|
||||||
|
c.checkType(typ.EmbeddedType(i), path+" embedded interface")
|
||||||
|
}
|
||||||
|
case *types.Signature:
|
||||||
|
if params := typ.TypeParams(); params != nil {
|
||||||
|
for i := 0; i < params.Len(); i++ {
|
||||||
|
c.checkType(params.At(i), path+" type parameter")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.checkType(typ.Params(), path+" parameter")
|
||||||
|
c.checkType(typ.Results(), path+" result")
|
||||||
|
if typ.Variadic() && typ.Params().Len() != 0 {
|
||||||
|
c.checkType(typ.Params().At(typ.Params().Len()-1).Type(), path+" variadic parameter")
|
||||||
|
}
|
||||||
|
case *types.Tuple:
|
||||||
|
for i := 0; i < typ.Len(); i++ {
|
||||||
|
c.checkType(typ.At(i).Type(), path)
|
||||||
|
}
|
||||||
|
case *types.TypeParam:
|
||||||
|
c.checkType(typ.Constraint(), path+" constraint")
|
||||||
|
case *types.Union:
|
||||||
|
for i := 0; i < typ.Len(); i++ {
|
||||||
|
c.checkType(typ.Term(i).Type(), path+" constraint term")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
c.violation(fmt.Sprintf("%s has uninspected type %T", path, typ))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *contractChecker) allowedMethod(method *types.Func) bool {
|
||||||
|
if method.Pkg() == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for typeName := range c.allowedNamed {
|
||||||
|
if strings.HasPrefix(typeName, method.Pkg().Path()+".") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
237
internal/apicheck/main_test.go
Normal file
237
internal/apicheck/main_test.go
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go/ast"
|
||||||
|
"go/importer"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"go/types"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExportedContractBoundaries(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
source string
|
||||||
|
wantError string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "leaked implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
func New() *implementation.State { return nil }
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "alias to implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type Alias = implementation.State
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "callback leaks implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type Callback func() *implementation.State
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "generic constraint leaks implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type Box[T interface{ Value() *implementation.State }] struct { value T }
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "generic instantiation leaks implementation type",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type Box[T any] struct { value T }
|
||||||
|
func New() Box[implementation.State] { return Box[implementation.State]{} }
|
||||||
|
`,
|
||||||
|
wantError: "exposes named type example.com/implementation.State",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "promoted implementation method",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type state = implementation.State
|
||||||
|
type Handle struct { state }
|
||||||
|
`,
|
||||||
|
wantError: "promotes method Promoted from example.com/implementation",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "promoted pointer implementation method",
|
||||||
|
source: `package facade
|
||||||
|
import "example.com/implementation"
|
||||||
|
type state = implementation.State
|
||||||
|
type Handle struct { state }
|
||||||
|
`,
|
||||||
|
wantError: "promotes method PointerPromoted from example.com/implementation",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
violations := checkFixture(t, test.source)
|
||||||
|
if !strings.Contains(strings.Join(violations, "\n"), test.wantError) {
|
||||||
|
t.Fatalf("checkExports() = %v, want an error containing %q", violations, test.wantError)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrivateImplementationFieldAndSelectedStandardTypes(t *testing.T) {
|
||||||
|
source := `package facade
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"example.com/implementation"
|
||||||
|
)
|
||||||
|
type Handle struct { state *implementation.State }
|
||||||
|
func Open(context.Context) *Handle { return nil }
|
||||||
|
`
|
||||||
|
if violations := checkFixture(t, source); len(violations) != 0 {
|
||||||
|
t.Fatalf("private implementation field and selected standard type were rejected: %v", violations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidationDiagnosticTypesBelongToFacade(t *testing.T) {
|
||||||
|
valid := `package facade
|
||||||
|
type ValidationCheck string
|
||||||
|
type ValidationFinding struct{}
|
||||||
|
type FileSizeMeasurement struct{}
|
||||||
|
type ValidationError struct {
|
||||||
|
Check ValidationCheck
|
||||||
|
Findings []ValidationFinding
|
||||||
|
Measurement *FileSizeMeasurement
|
||||||
|
Cause error
|
||||||
|
}
|
||||||
|
`
|
||||||
|
pkg := typecheck(t, token.NewFileSet(), modulePath, valid)
|
||||||
|
if violations := checkValidationTypes(pkg); len(violations) != 0 {
|
||||||
|
t.Fatalf("checkValidationTypes() = %v, want facade-owned diagnostics", violations)
|
||||||
|
}
|
||||||
|
|
||||||
|
implementation := typecheck(t, token.NewFileSet(), "example.com/implementation", `package implementation
|
||||||
|
type State string
|
||||||
|
`)
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
fixtureImporter := singlePackageImporter{path: "example.com/implementation", pkg: implementation}
|
||||||
|
invalid := strings.Replace(valid, "type ValidationCheck string", "import \"example.com/implementation\"\ntype ValidationCheck = implementation.State", 1)
|
||||||
|
pkg = typecheckWithImporter(t, fset, modulePath, invalid, fixtureImporter)
|
||||||
|
if violations := checkValidationTypes(pkg); !strings.Contains(strings.Join(violations, "\n"), "ValidationCheck is not a facade-owned named type") {
|
||||||
|
t.Fatalf("checkValidationTypes() = %v, want ownership violation", violations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActualRepositoryBoundaries(t *testing.T) {
|
||||||
|
if err := checkRepository(t.Context(), "../.."); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInternalPackagesCannotImportPublicFacades(t *testing.T) {
|
||||||
|
packages := []listedPackage{
|
||||||
|
{ImportPath: modulePath + "/internal/operations", Imports: []string{modulePath}},
|
||||||
|
{ImportPath: modulePath + "/cmd/releasekit/internal/cli", Imports: []string{modulePath + "/buildinfo"}},
|
||||||
|
{ImportPath: modulePath},
|
||||||
|
{ImportPath: modulePath + "/buildinfo"},
|
||||||
|
}
|
||||||
|
err := checkImportDirections(packages)
|
||||||
|
if err == nil ||
|
||||||
|
!strings.Contains(err.Error(), "internal package "+modulePath+"/internal/operations imports public or command package "+modulePath) ||
|
||||||
|
!strings.Contains(err.Error(), "internal package "+modulePath+"/cmd/releasekit/internal/cli imports public or command package "+modulePath+"/buildinfo") {
|
||||||
|
t.Fatalf("checkImportDirections() error = %v, want internal-to-facade violation", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRuntimeFacadeCannotDependOnExternalPackages(t *testing.T) {
|
||||||
|
packages := []listedPackage{
|
||||||
|
{ImportPath: modulePath + "/buildinfo", Imports: []string{"example.com/runtime"}},
|
||||||
|
{ImportPath: "example.com/runtime"},
|
||||||
|
}
|
||||||
|
err := checkImportDirections(packages)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "buildinfo depends on non-runtime package example.com/runtime") {
|
||||||
|
t.Fatalf("checkImportDirections() error = %v, want runtime dependency violation", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkFixture(t *testing.T, facadeSource string) []string {
|
||||||
|
t.Helper()
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
implementation := typecheck(t, fset, "example.com/implementation", `package implementation
|
||||||
|
type State struct{}
|
||||||
|
func (State) Promoted() {}
|
||||||
|
func (*State) PointerPromoted() {}
|
||||||
|
`)
|
||||||
|
fixtureImporter := singlePackageImporter{path: "example.com/implementation", pkg: implementation}
|
||||||
|
facade := typecheckWithImporter(t, fset, "example.com/facade", facadeSource, fixtureImporter)
|
||||||
|
return checkExports(facade)
|
||||||
|
}
|
||||||
|
|
||||||
|
type singlePackageImporter struct {
|
||||||
|
path string
|
||||||
|
pkg *types.Package
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i singlePackageImporter) Import(path string) (*types.Package, error) {
|
||||||
|
if path == i.path {
|
||||||
|
return i.pkg, nil
|
||||||
|
}
|
||||||
|
return importer.Default().Import(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func typecheck(t *testing.T, fset *token.FileSet, path, source string) *types.Package {
|
||||||
|
t.Helper()
|
||||||
|
return typecheckWithImporter(t, fset, path, source, importer.Default())
|
||||||
|
}
|
||||||
|
|
||||||
|
func typecheckWithImporter(t *testing.T, fset *token.FileSet, path, source string, imports types.Importer) *types.Package {
|
||||||
|
t.Helper()
|
||||||
|
file, err := parser.ParseFile(fset, path+".go", source, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var errors []error
|
||||||
|
config := types.Config{
|
||||||
|
Importer: imports,
|
||||||
|
Error: func(err error) {
|
||||||
|
errors = append(errors, err)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
pkg, err := config.Check(path, fset, []*ast.File{file}, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("typecheck %s: %v (%v)", path, err, errors)
|
||||||
|
}
|
||||||
|
return pkg
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCommandInternalCompositionPreservesLibraryBoundaries(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name, from, to string
|
||||||
|
reject bool
|
||||||
|
}{
|
||||||
|
{"command helpers", "/cmd/releasekit/internal/cli/parser", "/cmd/releasekit/internal/cli/settings", false},
|
||||||
|
{"other executable helpers", "/cmd/future/internal/parser", "/cmd/future/internal/settings", false},
|
||||||
|
{"helper root", "/cmd/releasekit/internal", "/cmd/releasekit/internal/cli", false},
|
||||||
|
{"controller uses facade", "/cmd/releasekit", "", false},
|
||||||
|
{"library imports controller", "/internal/build", "/cmd/releasekit", true},
|
||||||
|
{"library imports helper", "/internal/build", "/cmd/releasekit/internal/cli", true},
|
||||||
|
{"helper imports facade", "/cmd/releasekit/internal/cli", "", true},
|
||||||
|
{"helper imports runtime facade", "/cmd/releasekit/internal/cli", "/buildinfo", true},
|
||||||
|
{"helper imports controller", "/cmd/releasekit/internal/cli", "/cmd/releasekit", true},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
err := checkImportDirections([]listedPackage{{ImportPath: modulePath + test.from, Imports: []string{modulePath + test.to}}})
|
||||||
|
if (err != nil) != test.reject {
|
||||||
|
t.Fatalf("dependency %s -> %s: %v", test.from, test.to, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
92
internal/artifact/artifact.go
Normal file
92
internal/artifact/artifact.go
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
// Package artifact owns shared build artifact identity rules.
|
||||||
|
package artifact
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ManifestFilename = "SHA256SUMS"
|
||||||
|
|
||||||
|
// OutputDirectory resolves build output and prebuilt asset directories from
|
||||||
|
// the absolute selected module directory.
|
||||||
|
func OutputDirectory(moduleDir, directory string) string {
|
||||||
|
if directory == "" {
|
||||||
|
directory = "dist"
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(directory) {
|
||||||
|
directory = filepath.Join(moduleDir, directory)
|
||||||
|
}
|
||||||
|
return filepath.Clean(directory)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Target struct {
|
||||||
|
OS string
|
||||||
|
Arch string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Settings contains normalized inputs shared by build execution and evidence.
|
||||||
|
type Settings struct {
|
||||||
|
MainPackage string
|
||||||
|
BinaryName string
|
||||||
|
Targets []Target
|
||||||
|
}
|
||||||
|
|
||||||
|
type Declaration struct {
|
||||||
|
Target Target
|
||||||
|
Filename string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeSettings copies build inputs and removes duplicate targets while
|
||||||
|
// preserving their first occurrence.
|
||||||
|
func NormalizeSettings(mainPackage, binaryName string, targets []Target) Settings {
|
||||||
|
return Settings{
|
||||||
|
MainPackage: mainPackage,
|
||||||
|
BinaryName: binaryName,
|
||||||
|
Targets: NormalizeTargets(targets),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeTargets removes duplicate targets while preserving their first
|
||||||
|
// occurrence.
|
||||||
|
func NormalizeTargets(targets []Target) []Target {
|
||||||
|
seen := make(map[Target]struct{}, len(targets))
|
||||||
|
result := make([]Target, 0, len(targets))
|
||||||
|
for _, target := range targets {
|
||||||
|
if _, ok := seen[target]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[target] = struct{}{}
|
||||||
|
result = append(result, target)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidComponent reports whether value is a nonempty filename component under
|
||||||
|
// the build and receipt contracts.
|
||||||
|
func ValidComponent(value string) bool {
|
||||||
|
return value != "" && !strings.ContainsAny(value, "/\\\r\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filename returns the declared binary filename for one target.
|
||||||
|
func Filename(binaryName, version string, target Target) string {
|
||||||
|
filename := fmt.Sprintf("%s-%s-%s-%s", binaryName, version, target.OS, target.Arch)
|
||||||
|
if target.OS == "windows" {
|
||||||
|
filename += ".exe"
|
||||||
|
}
|
||||||
|
return filename
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExpectedBuild returns artifact declarations in target order. Callers retain
|
||||||
|
// responsibility for validating their boundary-specific build identity.
|
||||||
|
func ExpectedBuild(binaryName, version string, targets []Target) []Declaration {
|
||||||
|
declarations := make([]Declaration, 0, len(targets))
|
||||||
|
for _, target := range targets {
|
||||||
|
declarations = append(declarations, Declaration{
|
||||||
|
Target: target,
|
||||||
|
Filename: Filename(binaryName, version, target),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return declarations
|
||||||
|
}
|
||||||
58
internal/artifact/artifact_test.go
Normal file
58
internal/artifact/artifact_test.go
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
package artifact
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNormalizeTargetsPreservesOrderAndFirstOccurrence(t *testing.T) {
|
||||||
|
targets := []Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "windows", Arch: "arm64"},
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
}
|
||||||
|
want := []Target{{OS: "linux", Arch: "amd64"}, {OS: "windows", Arch: "arm64"}}
|
||||||
|
if got := NormalizeTargets(targets); !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("NormalizeTargets() = %#v, want %#v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeSettingsKeepsBuildInputsAndNormalizesTargets(t *testing.T) {
|
||||||
|
settings := NormalizeSettings("./cmd/app", "app", []Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "windows", Arch: "arm64"},
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
})
|
||||||
|
want := Settings{
|
||||||
|
MainPackage: "./cmd/app",
|
||||||
|
BinaryName: "app",
|
||||||
|
Targets: []Target{{OS: "linux", Arch: "amd64"}, {OS: "windows", Arch: "arm64"}},
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(settings, want) {
|
||||||
|
t.Fatalf("NormalizeSettings() = %#v, want %#v", settings, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpectedBuildUsesSharedNamesInTargetOrder(t *testing.T) {
|
||||||
|
targets := []Target{{OS: "windows", Arch: "arm64"}, {OS: "linux", Arch: "amd64"}}
|
||||||
|
want := []Declaration{
|
||||||
|
{Target: targets[0], Filename: "app-v1.2.3-windows-arm64.exe"},
|
||||||
|
{Target: targets[1], Filename: "app-v1.2.3-linux-amd64"},
|
||||||
|
}
|
||||||
|
if got := ExpectedBuild("app", "v1.2.3", targets); !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("ExpectedBuild() = %#v, want %#v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidComponentPreservesBuildAndReceiptRules(t *testing.T) {
|
||||||
|
for _, value := range []string{"", "path/name", `path\name`, "line\nbreak", "line\rbreak"} {
|
||||||
|
if ValidComponent(value) {
|
||||||
|
t.Errorf("ValidComponent(%q) = true, want false", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range []string{"app", "..", "nul\x00byte"} {
|
||||||
|
if !ValidComponent(value) {
|
||||||
|
t.Errorf("ValidComponent(%q) = false, want true", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
263
internal/build/build.go
Normal file
263
internal/build/build.go
Normal file
@@ -0,0 +1,263 @@
|
|||||||
|
// Package build compiles versioned application binaries for explicit targets.
|
||||||
|
package build
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/tempdir"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Target = artifact.Target
|
||||||
|
type Spec = artifact.Settings
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
Identity releaseidentity.Identity
|
||||||
|
Spec Spec
|
||||||
|
OutputDir string
|
||||||
|
Output io.Writer
|
||||||
|
ToolOwner *gotool.Owner
|
||||||
|
}
|
||||||
|
|
||||||
|
type Artifact struct {
|
||||||
|
Path string
|
||||||
|
Filename string
|
||||||
|
Target Target
|
||||||
|
SHA256 string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
RepositoryDir string
|
||||||
|
ModuleDir string
|
||||||
|
ModulePath string
|
||||||
|
Tag string
|
||||||
|
CandidateCommit string
|
||||||
|
SourceVerified bool
|
||||||
|
Settings artifact.Settings
|
||||||
|
Version string
|
||||||
|
MainPackage string
|
||||||
|
BinaryName string
|
||||||
|
OutputDir string
|
||||||
|
Targets []Target
|
||||||
|
Artifacts []Artifact
|
||||||
|
Compiler string
|
||||||
|
}
|
||||||
|
|
||||||
|
func BuildResolved(ctx context.Context, request Request) (Result, error) {
|
||||||
|
identity := request.Identity
|
||||||
|
settings := artifact.NormalizeSettings(request.Spec.MainPackage, request.Spec.BinaryName, request.Spec.Targets)
|
||||||
|
result := Result{
|
||||||
|
RepositoryDir: identity.RepositoryDir,
|
||||||
|
ModuleDir: identity.ModuleDir,
|
||||||
|
ModulePath: identity.ModulePath,
|
||||||
|
Tag: identity.Tag,
|
||||||
|
Settings: settings,
|
||||||
|
Version: identity.Version,
|
||||||
|
MainPackage: settings.MainPackage,
|
||||||
|
BinaryName: settings.BinaryName,
|
||||||
|
Targets: settings.Targets,
|
||||||
|
}
|
||||||
|
if !versioncontract.ValidStableVersion(identity.Version) {
|
||||||
|
return result, fmt.Errorf("%w: %q", candidate.ErrInvalidVersion, identity.Version)
|
||||||
|
}
|
||||||
|
if identity.RepositoryDir == "" || identity.ModuleDir == "" || identity.ModulePath == "" {
|
||||||
|
return result, errors.New("build requires a resolved module identity")
|
||||||
|
}
|
||||||
|
if len(result.Targets) != 0 {
|
||||||
|
if settings.MainPackage == "" {
|
||||||
|
return result, errors.New("build requires a main package when targets are selected")
|
||||||
|
}
|
||||||
|
if !artifact.ValidComponent(settings.BinaryName) {
|
||||||
|
return result, fmt.Errorf("unsafe binary name %q", settings.BinaryName)
|
||||||
|
}
|
||||||
|
for _, target := range result.Targets {
|
||||||
|
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
|
||||||
|
return result, fmt.Errorf("unsafe target %q/%q", target.OS, target.Arch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return result, fmt.Errorf("build canceled: %w", err)
|
||||||
|
}
|
||||||
|
repositoryDir, err := filepath.Abs(identity.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("resolve repository directory: %w", err)
|
||||||
|
}
|
||||||
|
result.RepositoryDir = repositoryDir
|
||||||
|
moduleDir, err := filepath.Abs(identity.ModuleDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("resolve module directory: %w", err)
|
||||||
|
}
|
||||||
|
result.ModuleDir = moduleDir
|
||||||
|
commit, err := gitCommit(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
result.CandidateCommit = commit
|
||||||
|
cleanBefore, err := cleanSource(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(result.Targets) == 0 {
|
||||||
|
result.OutputDir = artifact.OutputDirectory(moduleDir, request.OutputDir)
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
result.OutputDir = artifact.OutputDirectory(moduleDir, request.OutputDir)
|
||||||
|
declarations := artifact.ExpectedBuild(settings.BinaryName, identity.Version, settings.Targets)
|
||||||
|
filenames := make([]string, len(declarations))
|
||||||
|
for i, declaration := range declarations {
|
||||||
|
filenames[i] = declaration.Filename
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(result.OutputDir, 0o755); err != nil {
|
||||||
|
return result, fmt.Errorf("create build output directory %q: %w", result.OutputDir, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
owner := request.ToolOwner
|
||||||
|
if owner == nil {
|
||||||
|
owner = gotool.NewOwner(moduleDir)
|
||||||
|
}
|
||||||
|
goTool, err := owner.Acquire(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("prepare Go toolchain: %w", err)
|
||||||
|
}
|
||||||
|
compiler, err := goTool.Output(ctx, moduleDir, gotool.Native, gotool.Target{}, nil, "version")
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("identify Go compiler: %w", err)
|
||||||
|
}
|
||||||
|
result.Compiler = strings.TrimSpace(string(compiler))
|
||||||
|
goHost := goTool.HostTarget()
|
||||||
|
host := Target{OS: goHost.OS, Arch: goHost.Arch}
|
||||||
|
|
||||||
|
for index, target := range result.Targets {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return result, fmt.Errorf("build canceled: %w", err)
|
||||||
|
}
|
||||||
|
filename := filenames[index]
|
||||||
|
path := filepath.Join(result.OutputDir, filename)
|
||||||
|
if request.Output != nil {
|
||||||
|
fmt.Fprintf(request.Output, "building %s/%s as %s\n", target.OS, target.Arch, filename)
|
||||||
|
}
|
||||||
|
if err := buildTarget(ctx, goTool, moduleDir, settings.MainPackage, path, identity.Version, target); err != nil {
|
||||||
|
return result, fmt.Errorf("build target %s/%s: %w", target.OS, target.Arch, err)
|
||||||
|
}
|
||||||
|
artifact := Artifact{Path: path, Filename: filename, Target: target}
|
||||||
|
result.Artifacts = append(result.Artifacts, artifact)
|
||||||
|
if err := hashArtifact(&result.Artifacts[len(result.Artifacts)-1]); err != nil {
|
||||||
|
return result, fmt.Errorf("hash build output %q: %w", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var smokePath string
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
if artifact.Target == host {
|
||||||
|
smokePath = artifact.Path
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if smokePath == "" {
|
||||||
|
temporaryDir, err := tempdir.Outside(repositoryDir, "releasekit-native-smoke-")
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("create native smoke directory: %w", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(temporaryDir)
|
||||||
|
smokePath = filepath.Join(temporaryDir, settings.BinaryName)
|
||||||
|
if host.OS == "windows" {
|
||||||
|
smokePath += ".exe"
|
||||||
|
}
|
||||||
|
if request.Output != nil {
|
||||||
|
fmt.Fprintf(request.Output, "building temporary version check for %s/%s\n", host.OS, host.Arch)
|
||||||
|
}
|
||||||
|
if err := buildTarget(ctx, goTool, moduleDir, settings.MainPackage, smokePath, identity.Version, host); err != nil {
|
||||||
|
return result, fmt.Errorf("build native version check: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if request.Output != nil {
|
||||||
|
fmt.Fprintf(request.Output, "checking %s version output\n", settings.BinaryName)
|
||||||
|
}
|
||||||
|
if err := checkVersion(ctx, smokePath, settings.BinaryName, identity.Version); err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
commitAfter, err := gitCommit(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
cleanAfter, err := cleanSource(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
result.SourceVerified = cleanBefore && cleanAfter && commitAfter == commit
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitCommit(ctx context.Context, repositoryDir string) (string, error) {
|
||||||
|
command := exec.CommandContext(ctx, "git", "-C", repositoryDir, "rev-parse", "--verify", "HEAD^{commit}")
|
||||||
|
output, err := command.Output()
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return "", fmt.Errorf("read source commit: %w", ctx.Err())
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("read source commit: %w", err)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(output)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildTarget(ctx context.Context, goTool *gotool.Tool, moduleDir, mainPackage, outputPath, version string, target Target) error {
|
||||||
|
ldflags := "-s -w -X " + versioncontract.InjectedVersionLinkerSymbol + "=" + version
|
||||||
|
err := goTool.Run(ctx, moduleDir, gotool.Static, gotool.Target{OS: target.OS, Arch: target.Arch}, nil,
|
||||||
|
"build", "-o", outputPath, "-mod=readonly", "-trimpath", "-buildvcs=false", "-ldflags", ldflags, mainPackage)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashArtifact(artifact *Artifact) error {
|
||||||
|
file, err := os.Open(artifact.Path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
hash := sha256.New()
|
||||||
|
if _, err := io.Copy(hash, file); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
artifact.SHA256 = hex.EncodeToString(hash.Sum(nil))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkVersion(ctx context.Context, binaryPath, binaryName, version string) error {
|
||||||
|
command := exec.CommandContext(ctx, binaryPath, "version")
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return fmt.Errorf("run native version check: %w", ctx.Err())
|
||||||
|
}
|
||||||
|
return fmt.Errorf("run native version check: %w: %s", err, strings.TrimSpace(string(output)))
|
||||||
|
}
|
||||||
|
want := binaryName + " " + version + "\n"
|
||||||
|
if string(output) != want {
|
||||||
|
return fmt.Errorf("native version output = %q, want %q", output, want)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanSource(ctx context.Context, repositoryDir string) (bool, error) {
|
||||||
|
command := exec.CommandContext(ctx, "git", "-C", repositoryDir, "status", "--porcelain", "--untracked-files=all")
|
||||||
|
output, err := command.Output()
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("inspect build source: %w", err)
|
||||||
|
}
|
||||||
|
return len(output) == 0, nil
|
||||||
|
}
|
||||||
55
internal/build/candidate.go
Normal file
55
internal/build/candidate.go
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
package build
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/tempdir"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CandidateCallback(spec *Spec, output io.Writer) func(context.Context, candidate.Candidate, *gotool.Owner) error {
|
||||||
|
if spec == nil || len(spec.Targets) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
selected := *spec
|
||||||
|
selected.Targets = append([]Target(nil), spec.Targets...)
|
||||||
|
return func(ctx context.Context, captured candidate.Candidate, owner *gotool.Owner) error {
|
||||||
|
moduleSubdir, err := filepath.Rel(captured.RepositoryDir, captured.ModuleDir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("resolve captured module path: %w", err)
|
||||||
|
}
|
||||||
|
identity := releaseidentity.Identity{
|
||||||
|
Selection: releaseidentity.Selection{
|
||||||
|
RepositoryDir: captured.RepositoryDir,
|
||||||
|
ModuleDir: captured.ModuleDir,
|
||||||
|
ModuleSubdir: filepath.ToSlash(moduleSubdir),
|
||||||
|
},
|
||||||
|
ModulePath: captured.ModulePath,
|
||||||
|
Version: captured.Version,
|
||||||
|
Tag: captured.Tag,
|
||||||
|
NotePath: filepath.ToSlash(filepath.Join(moduleSubdir, "docs", "releases", captured.Version+".md")),
|
||||||
|
}
|
||||||
|
temporaryDir, err := tempdir.Outside(captured.RepositoryDir, "releasekit-candidate-build-")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create temporary candidate build output: %w", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(temporaryDir)
|
||||||
|
_, err = BuildResolved(ctx, Request{
|
||||||
|
Identity: identity,
|
||||||
|
Spec: selected,
|
||||||
|
OutputDir: temporaryDir,
|
||||||
|
Output: output,
|
||||||
|
ToolOwner: owner,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("build candidate: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
292
internal/candidate/check.go
Normal file
292
internal/candidate/check.go
Normal file
@@ -0,0 +1,292 @@
|
|||||||
|
// Package candidate captures and validates a committed local release candidate.
|
||||||
|
package candidate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrInvalidVersion = errors.New("invalid stable version")
|
||||||
|
|
||||||
|
type Candidate struct {
|
||||||
|
RepositoryDir string
|
||||||
|
ModuleDir string
|
||||||
|
ModulePath string
|
||||||
|
Tag string
|
||||||
|
Commit string
|
||||||
|
Version string
|
||||||
|
Note string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
RepositoryDir string
|
||||||
|
ModuleDir string
|
||||||
|
Product string
|
||||||
|
Version string
|
||||||
|
Validation validation.Settings
|
||||||
|
AdditionalChecks func(context.Context, Candidate) error
|
||||||
|
AfterValidate func(context.Context, Candidate, *gotool.Owner) error
|
||||||
|
Output io.Writer
|
||||||
|
ToolOwner *gotool.Owner
|
||||||
|
}
|
||||||
|
|
||||||
|
func Check(ctx context.Context, request Request) (Candidate, error) {
|
||||||
|
captured, err := Capture(ctx, request)
|
||||||
|
if err != nil {
|
||||||
|
return captured, err
|
||||||
|
}
|
||||||
|
request.ToolOwner = gotool.NewOwner(captured.ModuleDir)
|
||||||
|
if err := Validate(ctx, request, captured); err != nil {
|
||||||
|
return captured, err
|
||||||
|
}
|
||||||
|
if request.AfterValidate != nil {
|
||||||
|
callbackErr := request.AfterValidate(ctx, captured, request.ToolOwner)
|
||||||
|
if callbackErr != nil {
|
||||||
|
return captured, fmt.Errorf("after candidate validation: %w", callbackErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := Recheck(ctx, captured, ""); err != nil {
|
||||||
|
return captured, err
|
||||||
|
}
|
||||||
|
return captured, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture validates request identity and records one clean local candidate,
|
||||||
|
// including the note bytes from the captured commit. It does not run checks.
|
||||||
|
func Capture(ctx context.Context, request Request) (Candidate, error) {
|
||||||
|
captured := Candidate{Version: request.Version}
|
||||||
|
if !validStableVersion(request.Version) {
|
||||||
|
return captured, fmt.Errorf("%w: %q", ErrInvalidVersion, request.Version)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(request.Product) == "" {
|
||||||
|
return captured, errors.New("product is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return captured, fmt.Errorf("resolve repository directory: %w", err)
|
||||||
|
}
|
||||||
|
captured.RepositoryDir = repositoryDir
|
||||||
|
state, err := inspectLocalState(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return captured, err
|
||||||
|
}
|
||||||
|
captured.Commit = state.commit
|
||||||
|
if state.branch != "main" {
|
||||||
|
return captured, fmt.Errorf("release candidate must be on main; current branch is %q", state.branch)
|
||||||
|
}
|
||||||
|
if state.status != "" {
|
||||||
|
return captured, fmt.Errorf("release candidate worktree and index must be clean:\n%s", state.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
identity, err := releaseidentity.FromCommitted(ctx, repositoryDir, request.ModuleDir, request.Version, state.commit)
|
||||||
|
captured.ModuleDir = identity.ModuleDir
|
||||||
|
captured.ModulePath = identity.ModulePath
|
||||||
|
captured.Tag = identity.Tag
|
||||||
|
if err != nil {
|
||||||
|
return captured, fmt.Errorf("resolve selected module release identity: %w", err)
|
||||||
|
}
|
||||||
|
note, err := git.ReadCommitFile(ctx, identity.RepositoryDir, state.commit, identity.NotePath)
|
||||||
|
if err != nil {
|
||||||
|
return captured, fmt.Errorf("read committed release note %q: %w", identity.NotePath, err)
|
||||||
|
}
|
||||||
|
if err := validateNote(note, request.Product, request.Version); err != nil {
|
||||||
|
return captured, fmt.Errorf("release note %q: %w", identity.NotePath, err)
|
||||||
|
}
|
||||||
|
if exists, err := hasLocalTag(ctx, repositoryDir, identity.Tag); err != nil {
|
||||||
|
return captured, fmt.Errorf("inspect local tag %q: %w", identity.Tag, err)
|
||||||
|
} else if exists {
|
||||||
|
return captured, fmt.Errorf("local tag %q already exists", identity.Tag)
|
||||||
|
}
|
||||||
|
|
||||||
|
captured.Note = string(note)
|
||||||
|
return captured, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate runs the selected offline Go suite, followed by AdditionalChecks
|
||||||
|
// when supplied, for the captured candidate.
|
||||||
|
func Validate(ctx context.Context, request Request, captured Candidate) error {
|
||||||
|
owner := request.ToolOwner
|
||||||
|
if owner == nil {
|
||||||
|
owner = gotool.NewOwner(captured.ModuleDir)
|
||||||
|
}
|
||||||
|
if err := validation.Run(ctx, validation.Request{
|
||||||
|
RepositoryDir: captured.RepositoryDir,
|
||||||
|
ModuleDir: captured.ModuleDir,
|
||||||
|
Commit: captured.Commit,
|
||||||
|
Output: request.Output,
|
||||||
|
Settings: request.Validation,
|
||||||
|
ToolOwner: owner,
|
||||||
|
}); err != nil {
|
||||||
|
return fmt.Errorf("validate candidate %s: %w", captured.Commit, err)
|
||||||
|
}
|
||||||
|
if request.AdditionalChecks != nil {
|
||||||
|
callbackErr := request.AdditionalChecks(ctx, captured)
|
||||||
|
if callbackErr != nil {
|
||||||
|
return fmt.Errorf("validate candidate %s: %w", captured.Commit, callbackErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recheck verifies that the captured local source is unchanged. When
|
||||||
|
// expectedTagObject is empty, the selected local version tag must still be
|
||||||
|
// absent; otherwise the existing annotated tag must still have that object ID.
|
||||||
|
func Recheck(ctx context.Context, captured Candidate, expectedTagObject string) error {
|
||||||
|
current, err := inspectLocalState(ctx, captured.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("recheck local candidate state: %w", err)
|
||||||
|
}
|
||||||
|
if current.branch != "main" {
|
||||||
|
return fmt.Errorf("release candidate branch changed to %q", current.branch)
|
||||||
|
}
|
||||||
|
if current.commit != captured.Commit {
|
||||||
|
return fmt.Errorf("HEAD changed from %s to %s", captured.Commit, current.commit)
|
||||||
|
}
|
||||||
|
if current.status != "" {
|
||||||
|
return fmt.Errorf("worktree or index changed:\n%s", current.status)
|
||||||
|
}
|
||||||
|
if expectedTagObject == "" {
|
||||||
|
if exists, err := hasLocalTag(ctx, captured.RepositoryDir, captured.Tag); err != nil {
|
||||||
|
return fmt.Errorf("recheck local tag %q: %w", captured.Tag, err)
|
||||||
|
} else if exists {
|
||||||
|
return fmt.Errorf("local tag %q appeared during validation", captured.Tag)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
object, err := gitOutput(ctx, captured.RepositoryDir, "rev-parse", "--verify", "refs/tags/"+captured.Tag)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read local tag %q: %w", captured.Tag, err)
|
||||||
|
}
|
||||||
|
tagType, err := gitOutput(ctx, captured.RepositoryDir, "cat-file", "-t", "refs/tags/"+captured.Tag)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("inspect local tag %q: %w", captured.Tag, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(string(object)) != expectedTagObject || strings.TrimSpace(string(tagType)) != "tag" {
|
||||||
|
return fmt.Errorf("local tag %q no longer identifies annotated tag object %s", captured.Tag, expectedTagObject)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type localState struct {
|
||||||
|
branch string
|
||||||
|
commit string
|
||||||
|
status string
|
||||||
|
}
|
||||||
|
|
||||||
|
func inspectLocalState(ctx context.Context, repositoryDir string) (localState, error) {
|
||||||
|
branchOutput, err := gitOutput(ctx, repositoryDir, "branch", "--show-current")
|
||||||
|
if err != nil {
|
||||||
|
return localState{}, fmt.Errorf("inspect current branch: %w", err)
|
||||||
|
}
|
||||||
|
commitOutput, err := gitOutput(ctx, repositoryDir, "rev-parse", "--verify", "HEAD^{commit}")
|
||||||
|
if err != nil {
|
||||||
|
return localState{}, fmt.Errorf("capture HEAD commit: %w", err)
|
||||||
|
}
|
||||||
|
statusOutput, err := gitOutput(ctx, repositoryDir, "status", "--porcelain=v1", "--untracked-files=all")
|
||||||
|
if err != nil {
|
||||||
|
return localState{}, fmt.Errorf("inspect worktree and index: %w", err)
|
||||||
|
}
|
||||||
|
return localState{
|
||||||
|
branch: strings.TrimSpace(string(branchOutput)),
|
||||||
|
commit: strings.TrimSpace(string(commitOutput)),
|
||||||
|
status: strings.TrimSpace(string(statusOutput)),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitOutput(ctx context.Context, repositoryDir string, args ...string) ([]byte, error) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
commandArgs := append([]string{"git"}, args...)
|
||||||
|
err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: commandArgs,
|
||||||
|
Dir: repositoryDir,
|
||||||
|
Stdout: &stdout,
|
||||||
|
Stderr: &stderr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
message := strings.TrimSpace(stderr.String())
|
||||||
|
if message != "" {
|
||||||
|
return nil, fmt.Errorf("git %s: %s: %w", strings.Join(args, " "), message, err)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
|
||||||
|
}
|
||||||
|
return stdout.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasLocalTag(ctx context.Context, repositoryDir, tag string) (bool, error) {
|
||||||
|
var stderr bytes.Buffer
|
||||||
|
err := process.Run(ctx, process.Invocation{
|
||||||
|
Args: []string{"git", "show-ref", "--verify", "--quiet", "refs/tags/" + tag},
|
||||||
|
Dir: repositoryDir,
|
||||||
|
Stderr: &stderr,
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
message := strings.TrimSpace(stderr.String())
|
||||||
|
if message != "" {
|
||||||
|
return false, fmt.Errorf("%s: %w", message, err)
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func validStableVersion(version string) bool {
|
||||||
|
return versioncontract.ValidStableVersion(version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateNote(note []byte, product, version string) error {
|
||||||
|
line := string(note)
|
||||||
|
if firstLine, _, ok := strings.Cut(line, "\n"); ok {
|
||||||
|
line = firstLine
|
||||||
|
}
|
||||||
|
line = strings.TrimSuffix(line, "\r")
|
||||||
|
if !strings.HasPrefix(line, "# ") {
|
||||||
|
return errors.New("first line must be a level-one Markdown heading")
|
||||||
|
}
|
||||||
|
elements := strings.Fields(strings.TrimPrefix(line, "# "))
|
||||||
|
productElements := strings.Fields(product)
|
||||||
|
if !containsSequence(elements, productElements) || !containsSequence(elements, []string{version}) {
|
||||||
|
return fmt.Errorf("first heading must contain product %q and exact version %q as title elements", product, version)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateReleaseNote checks the title contract for a committed release note.
|
||||||
|
func ValidateReleaseNote(note []byte, product, version string) error {
|
||||||
|
return validateNote(note, product, version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsSequence(elements, sequence []string) bool {
|
||||||
|
if len(sequence) == 0 || len(sequence) > len(elements) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for start := 0; start+len(sequence) <= len(elements); start++ {
|
||||||
|
match := true
|
||||||
|
for i, element := range sequence {
|
||||||
|
if elements[start+i] != element {
|
||||||
|
match = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if match {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
706
internal/candidate/check_test.go
Normal file
706
internal/candidate/check_test.go
Normal file
@@ -0,0 +1,706 @@
|
|||||||
|
package candidate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/validation"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testVersion = "v1.2.3"
|
||||||
|
|
||||||
|
func TestValidStableVersion(t *testing.T) {
|
||||||
|
for _, version := range []string{
|
||||||
|
"v0.0.0",
|
||||||
|
"v1.2.3",
|
||||||
|
"v123456789012345678901234567890.0.9",
|
||||||
|
} {
|
||||||
|
if !validStableVersion(version) {
|
||||||
|
t.Errorf("validStableVersion(%q) = false", version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, version := range []string{
|
||||||
|
"",
|
||||||
|
"1.2.3",
|
||||||
|
"V1.2.3",
|
||||||
|
"v01.2.3",
|
||||||
|
"v1.02.3",
|
||||||
|
"v1.2.03",
|
||||||
|
"v1.2",
|
||||||
|
"v1.2.3-alpha",
|
||||||
|
"v1..3",
|
||||||
|
"v+1.2.3",
|
||||||
|
} {
|
||||||
|
if validStableVersion(version) {
|
||||||
|
t.Errorf("validStableVersion(%q) = true", version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckCapturesCandidateAndCallsAdditionalChecksOnce(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
writeTestFile(t, repository, "guide.md", "# Guide\n[section](#guide)\n")
|
||||||
|
gitRun(t, repository, "add", "guide.md")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add Markdown guide")
|
||||||
|
calls := 0
|
||||||
|
var seen Candidate
|
||||||
|
candidate, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Validation: validation.Settings{Markdown: &validation.MarkdownSettings{}},
|
||||||
|
AdditionalChecks: func(_ context.Context, captured Candidate) error {
|
||||||
|
calls++
|
||||||
|
seen = captured
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
commit := gitOutputForTest(t, repository, "rev-parse", "HEAD")
|
||||||
|
if calls != 1 {
|
||||||
|
t.Fatalf("validation callback called %d times, want 1", calls)
|
||||||
|
}
|
||||||
|
if seen != candidate {
|
||||||
|
t.Fatalf("callback candidate = %#v, returned candidate = %#v", seen, candidate)
|
||||||
|
}
|
||||||
|
if candidate.RepositoryDir != repository || candidate.ModuleDir != repository || candidate.ModulePath != "example.com/candidate" || candidate.Tag != testVersion || candidate.Commit != commit || candidate.Version != testVersion {
|
||||||
|
t.Fatalf("Check() candidate = %#v", candidate)
|
||||||
|
}
|
||||||
|
if tags := gitOutputForTest(t, repository, "tag", "--list"); tags != "" {
|
||||||
|
t.Fatalf("Check created local tags: %q", tags)
|
||||||
|
}
|
||||||
|
if refs := gitOutputForTest(t, repository, "for-each-ref", "--format=%(refname)", "refs/remotes"); refs != "" {
|
||||||
|
t.Fatalf("Check created remote-tracking refs: %q", refs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCaptureUsesNestedMajorModuleNoteAndTag(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRoot release.\n")
|
||||||
|
moduleDir := "integrations/ckconfig/v2"
|
||||||
|
writeTestFile(t, repository, moduleDir+"/go.mod", "module example.com/ckconfig/v2\n\ngo 1.25.0\n")
|
||||||
|
writeTestFile(t, repository, moduleDir+"/docs/releases/v2.3.4.md", "# Example Product v2.3.4\n\nNested release.\n")
|
||||||
|
gitRun(t, repository, "add", moduleDir)
|
||||||
|
gitRun(t, repository, "commit", "-m", "add nested major module")
|
||||||
|
|
||||||
|
captured, err := Capture(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
ModuleDir: moduleDir,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: "v2.3.4",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if captured.RepositoryDir != repository || captured.ModuleDir != filepath.Join(repository, moduleDir) || captured.ModulePath != "example.com/ckconfig/v2" || captured.Tag != "integrations/ckconfig/v2.3.4" {
|
||||||
|
t.Fatalf("nested candidate identity = %#v", captured)
|
||||||
|
}
|
||||||
|
if !strings.Contains(captured.Note, "Nested release.") || strings.Contains(captured.Note, "Root release.") {
|
||||||
|
t.Fatalf("captured note = %q, want nested module note", captured.Note)
|
||||||
|
}
|
||||||
|
|
||||||
|
gitRun(t, repository, "tag", captured.Tag)
|
||||||
|
conflicted, err := Capture(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
ModuleDir: moduleDir,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: "v2.3.4",
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), captured.Tag) {
|
||||||
|
t.Fatalf("Capture() with existing nested tag returned %#v, %v", conflicted, err)
|
||||||
|
}
|
||||||
|
if conflicted.ModulePath != captured.ModulePath || conflicted.Tag != captured.Tag || conflicted.Commit != captured.Commit {
|
||||||
|
t.Fatalf("capture failure lost identity evidence: %#v", conflicted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCaptureKeepsRepositoryWideCleanlinessGuardForNestedSelection(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
moduleDir := "integrations/ckconfig"
|
||||||
|
writeTestFile(t, repository, moduleDir+"/go.mod", "module example.com/ckconfig\n")
|
||||||
|
writeTestFile(t, repository, moduleDir+"/docs/releases/"+testVersion+".md", "# Example Product v1.2.3\n")
|
||||||
|
gitRun(t, repository, "add", moduleDir)
|
||||||
|
gitRun(t, repository, "commit", "-m", "add nested module")
|
||||||
|
writeTestFile(t, repository, "sibling/untracked.txt", "dirty\n")
|
||||||
|
captured, err := Capture(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
ModuleDir: moduleDir,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "must be clean") {
|
||||||
|
t.Fatalf("Capture() = %#v, %v; want repository-wide dirty-state rejection", captured, err)
|
||||||
|
}
|
||||||
|
if captured.Commit == "" {
|
||||||
|
t.Fatalf("dirty-state error lost captured commit: %#v", captured)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckStopsBeforeProductAndBuildCallbacksWhenGoFormatFails(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
writeTestFile(t, repository, "unformatted.go", "package candidate\nfunc Value( ) int{return 1}\n")
|
||||||
|
gitRun(t, repository, "add", "unformatted.go")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add unformatted Go source")
|
||||||
|
productCalls := 0
|
||||||
|
buildCalls := 0
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Validation: validation.Settings{GoFormat: true},
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
productCalls++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
AfterValidate: func(context.Context, Candidate, *gotool.Owner) error {
|
||||||
|
buildCalls++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
var failure *validation.Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != validation.GoFormat {
|
||||||
|
t.Fatalf("Check error = %v, want go-format failure", err)
|
||||||
|
}
|
||||||
|
if productCalls != 0 || buildCalls != 0 {
|
||||||
|
t.Fatalf("product callback calls = %d, build callback calls = %d; want neither after formatting failure", productCalls, buildCalls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckStopsBeforeProductAndBuildCallbacksWhenMarkdownBoundaryFails(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
writeTestFile(t, repository, "guide.md", "[outside](../../outside.md)\n")
|
||||||
|
gitRun(t, repository, "add", "guide.md")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add outside Markdown destination")
|
||||||
|
productCalls := 0
|
||||||
|
buildCalls := 0
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Validation: validation.Settings{
|
||||||
|
Markdown: &validation.MarkdownSettings{EnforceCheckoutBoundary: true},
|
||||||
|
},
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
productCalls++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
AfterValidate: func(context.Context, Candidate, *gotool.Owner) error {
|
||||||
|
buildCalls++
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
var failure *validation.Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != validation.MarkdownLinks {
|
||||||
|
t.Fatalf("Check() error = %v, want markdown-links failure", err)
|
||||||
|
}
|
||||||
|
if productCalls != 0 || buildCalls != 0 {
|
||||||
|
t.Fatalf("product callback calls = %d, build callback calls = %d; want neither after Markdown failure", productCalls, buildCalls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckReportsCommittedWorkspaceFilesWhenGoWorkspaceIsDisabled(t *testing.T) {
|
||||||
|
t.Setenv("GOWORK", "off")
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
writeTestFile(t, repository, "go.work", "go 1.25.0\n")
|
||||||
|
writeTestFile(t, repository, "nested/go.work.sum", "workspace-sum\n")
|
||||||
|
if err := os.MkdirAll(filepath.Join(repository, "linked"), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink("../go.work", filepath.Join(repository, "linked", "go.work")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gitRun(t, repository, "add", "go.work", "nested/go.work.sum", "linked/go.work")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add workspace files")
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Validation: validation.Settings{ModuleDistribution: validation.ModuleDistributionSettings{
|
||||||
|
WorkspaceFiles: true,
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
var failure *validation.Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != validation.WorkspaceFiles {
|
||||||
|
t.Fatalf("Check error = %v, want workspace-files failure", err)
|
||||||
|
}
|
||||||
|
want := map[string]bool{
|
||||||
|
"go.work": false,
|
||||||
|
"linked/go.work": false,
|
||||||
|
"nested/go.work.sum": false,
|
||||||
|
}
|
||||||
|
if len(failure.Findings) != len(want) {
|
||||||
|
t.Fatalf("workspace findings = %#v, want %d paths", failure.Findings, len(want))
|
||||||
|
}
|
||||||
|
for _, finding := range failure.Findings {
|
||||||
|
if _, ok := want[finding.Path]; !ok {
|
||||||
|
t.Errorf("unexpected workspace path %q", finding.Path)
|
||||||
|
}
|
||||||
|
want[finding.Path] = true
|
||||||
|
}
|
||||||
|
for path, found := range want {
|
||||||
|
if !found {
|
||||||
|
t.Errorf("workspace path %q was not reported", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRunsDefaultOfflineGoValidation(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
var output bytes.Buffer
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Output: &output,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Check() with default validation: %v\n%s", err, output.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRefreshesGoSettingsAfterAdditionalChecks(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
t.Setenv("GOENV", "off")
|
||||||
|
t.Setenv("GOMODCACHE", filepath.Join(t.TempDir(), "initial-module-cache"))
|
||||||
|
selectedCache := filepath.Join(t.TempDir(), "callback-module-cache")
|
||||||
|
var observed string
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
t.Setenv("GOMODCACHE", selectedCache)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
AfterValidate: func(ctx context.Context, captured Candidate, owner *gotool.Owner) error {
|
||||||
|
tool, err := owner.Acquire(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
output, err := tool.Output(ctx, captured.ModuleDir, gotool.Native, gotool.Target{}, nil, "env", "GOMODCACHE")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
observed = strings.TrimSpace(string(output))
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if observed != selectedCache {
|
||||||
|
t.Fatalf("Go settings after additional checks = %q, want %q", observed, selectedCache)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckNeedsNoGoDiscoveryAfterFinalCallback(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
gitPath, err := exec.LookPath("git")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gitOnly := t.TempDir()
|
||||||
|
if err := os.Symlink(gitPath, filepath.Join(gitOnly, "git")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository, Product: "Example Product", Version: testVersion,
|
||||||
|
AfterValidate: func(context.Context, Candidate, *gotool.Owner) error {
|
||||||
|
t.Setenv("PATH", gitOnly)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("completed Go work was rediscovered after final callback: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckSharesGoDiscoveryWithAfterValidateCallback(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
t.Skip("the controlled Go command fixture uses a POSIX shell")
|
||||||
|
}
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
logPath := installCandidateGoShim(t)
|
||||||
|
t.Setenv("GOENV", "off")
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AfterValidate: func(ctx context.Context, captured Candidate, owner *gotool.Owner) error {
|
||||||
|
tool, err := owner.Acquire(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = tool.Output(ctx, captured.ModuleDir, gotool.Native, gotool.Target{}, nil, "version")
|
||||||
|
return err
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
contents, err := os.ReadFile(logPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
commands := strings.Split(strings.TrimSpace(string(contents)), "\n")
|
||||||
|
var discoveries, suites, callbacks int
|
||||||
|
for _, command := range commands {
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(command, "env "):
|
||||||
|
discoveries++
|
||||||
|
case strings.HasPrefix(command, "test "):
|
||||||
|
suites++
|
||||||
|
case command == "version":
|
||||||
|
callbacks++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if discoveries != 2 || suites != 1 || callbacks != 1 {
|
||||||
|
t.Fatalf("Go invocations = %q; discovery=%d suite=%d callback=%d, want 2, 1, 1", commands, discoveries, suites, callbacks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func installCandidateGoShim(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
directory := t.TempDir()
|
||||||
|
logPath := filepath.Join(directory, "go-commands")
|
||||||
|
settings := map[string]string{
|
||||||
|
"GOHOSTOS": runtime.GOOS, "GOHOSTARCH": runtime.GOARCH, "GOENV": "off",
|
||||||
|
"CC": "", "CXX": "", "CGO_CFLAGS": "", "CGO_CPPFLAGS": "", "CGO_CXXFLAGS": "",
|
||||||
|
"CGO_ENABLED": "1", "CGO_LDFLAGS": "", "GOCACHE": "", "GOCACHEPROG": "",
|
||||||
|
"GOMODCACHE": "", "GOPATH": "", "GOROOT": "", "GOTMPDIR": "", "PKG_CONFIG": "",
|
||||||
|
}
|
||||||
|
encoded, err := json.Marshal(settings)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
script := fmt.Sprintf(`#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
printf '%%s\n' "$*" >> "$RELEASEKIT_GO_LOG"
|
||||||
|
if [ "${1-}" = "env" ]; then
|
||||||
|
printf '%%s\n' '%s'
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
if [ "${1-}" = "version" ]; then
|
||||||
|
echo 'go version fixture'
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
exit 0
|
||||||
|
`, encoded)
|
||||||
|
shimPath := filepath.Join(directory, "go")
|
||||||
|
if err := os.WriteFile(shimPath, []byte(script), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
path := directory
|
||||||
|
if current := os.Getenv("PATH"); current != "" {
|
||||||
|
path += string(os.PathListSeparator) + current
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", path)
|
||||||
|
t.Setenv("RELEASEKIT_GO_LOG", logPath)
|
||||||
|
return logPath
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultValidationDoesNotInheritGOFLAGSRunFilter(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n")
|
||||||
|
writeTestFile(t, repository, "failure_test.go", "package candidate\nimport \"testing\"\nfunc TestExpectedFailure(t *testing.T) { t.Fatal(\"expected fixture failure\") }\n")
|
||||||
|
gitRun(t, repository, "add", "failure_test.go")
|
||||||
|
gitRun(t, repository, "commit", "-m", "add failing validation fixture")
|
||||||
|
|
||||||
|
for _, source := range []string{"process environment", "Go environment file"} {
|
||||||
|
t.Run(source, func(t *testing.T) {
|
||||||
|
unsetCandidateEnv(t, "GOFLAGS", "GOOS", "GOARCH")
|
||||||
|
goEnv := filepath.Join(t.TempDir(), "go-env")
|
||||||
|
if source == "Go environment file" {
|
||||||
|
if err := os.WriteFile(goEnv, []byte("GOFLAGS=-run=^$\nGOOS=windows\nGOARCH=arm64\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := os.WriteFile(goEnv, nil, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("GOFLAGS", "-run=^$")
|
||||||
|
t.Setenv("GOOS", "windows")
|
||||||
|
t.Setenv("GOARCH", "arm64")
|
||||||
|
}
|
||||||
|
t.Setenv("GOENV", goEnv)
|
||||||
|
var output bytes.Buffer
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
Output: &output,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(output.String(), "TestExpectedFailure") {
|
||||||
|
t.Fatalf("Check() error = %v, output = %q; wanted the failing standard test to run", err, output.String())
|
||||||
|
}
|
||||||
|
var failure *validation.Failure
|
||||||
|
if !errors.As(err, &failure) || failure.Check != validation.GoTest {
|
||||||
|
t.Fatalf("Check() error = %v; want a go-test validation failure", err)
|
||||||
|
}
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if !errors.As(err, &exitErr) {
|
||||||
|
t.Fatalf("Check() error = %v; want the Go process exit error preserved", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func unsetCandidateEnv(t *testing.T, keys ...string) {
|
||||||
|
t.Helper()
|
||||||
|
for _, key := range keys {
|
||||||
|
value, exists := os.LookupEnv(key)
|
||||||
|
if err := os.Unsetenv(key); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if exists {
|
||||||
|
_ = os.Setenv(key, value)
|
||||||
|
} else {
|
||||||
|
_ = os.Unsetenv(key)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRejectsInvalidVersionsBeforeGitAccess(t *testing.T) {
|
||||||
|
for _, version := range []string{"v01.2.3", "v1.2.3-alpha", "1.2.3"} {
|
||||||
|
t.Run(version, func(t *testing.T) {
|
||||||
|
_, err := Check(context.Background(), Request{Version: version})
|
||||||
|
if !errors.Is(err, ErrInvalidVersion) {
|
||||||
|
t.Fatalf("Check() error = %v, want ErrInvalidVersion", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRequiresMatchingCommittedNote(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
note string
|
||||||
|
}{
|
||||||
|
{name: "missing note"},
|
||||||
|
{name: "wrong product", note: "# Other Product v1.2.3\n"},
|
||||||
|
{name: "wrong version", note: "# Example Product v1.2.4\n"},
|
||||||
|
{name: "embedded product text", note: "# Example Products v1.2.3\n"},
|
||||||
|
{name: "not a level one heading", note: "## Example Product v1.2.3\n"},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repository := newRepository(t, test.note)
|
||||||
|
called := false
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
called = true
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Check() succeeded with an invalid committed note")
|
||||||
|
}
|
||||||
|
if called {
|
||||||
|
t.Fatal("validation ran before the committed note passed")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRejectsDirtyTrackedAndUntrackedState(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
value string
|
||||||
|
}{
|
||||||
|
{name: "tracked", path: "tracked.txt", value: "changed\n"},
|
||||||
|
{name: "untracked", path: "new file.txt", value: "untracked\n"},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, test.path), []byte(test.value), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err := Check(context.Background(), validRequest(repository))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "must be clean") {
|
||||||
|
t.Fatalf("Check() error = %v, want dirty state error", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRequiresMainBranchAndUnusedTag(t *testing.T) {
|
||||||
|
t.Run("detached HEAD", func(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
gitRun(t, repository, "checkout", "--detach", "HEAD")
|
||||||
|
_, err := Check(context.Background(), validRequest(repository))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "must be on main") {
|
||||||
|
t.Fatalf("Check() error = %v, want branch error", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("existing local tag", func(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
gitRun(t, repository, "tag", testVersion)
|
||||||
|
_, err := Check(context.Background(), validRequest(repository))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "already exists") {
|
||||||
|
t.Fatalf("Check() error = %v, want existing-tag error", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckStopsOnAdditionalCheckFailure(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
want := errors.New("selected check failed")
|
||||||
|
calls := 0
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
calls++
|
||||||
|
return want
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if !errors.Is(err, want) {
|
||||||
|
t.Fatalf("Check() error = %v, want wrapped callback error", err)
|
||||||
|
}
|
||||||
|
if calls != 1 {
|
||||||
|
t.Fatalf("validation callback called %d times, want 1", calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRechecksHeadAndWorktreeAfterCallback(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
validate func(*testing.T, string)
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "HEAD changes",
|
||||||
|
validate: func(t *testing.T, repository string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "later.txt"), []byte("later\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gitRun(t, repository, "add", "later.txt")
|
||||||
|
gitRun(t, repository, "-c", "commit.gpgsign=false", "commit", "-m", "advance HEAD")
|
||||||
|
},
|
||||||
|
want: "HEAD changed from",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "worktree changes",
|
||||||
|
validate: func(t *testing.T, repository string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(filepath.Join(repository, "later.txt"), []byte("later\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
want: "worktree or index changed",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
_, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
test.validate(t, repository)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), test.want) {
|
||||||
|
t.Fatalf("Check() error = %v, want text %q", err, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRechecksLocalTagAfterCallback(t *testing.T) {
|
||||||
|
repository := newRepository(t, "# Example Product v1.2.3\n")
|
||||||
|
captured, err := Check(context.Background(), Request{
|
||||||
|
RepositoryDir: repository,
|
||||||
|
Product: "Example Product",
|
||||||
|
Version: testVersion,
|
||||||
|
AdditionalChecks: func(context.Context, Candidate) error {
|
||||||
|
gitRun(t, repository, "tag", testVersion)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "appeared during validation") {
|
||||||
|
t.Fatalf("Check() error = %v, want tag recheck error", err)
|
||||||
|
}
|
||||||
|
if captured.RepositoryDir != repository || captured.ModuleDir != repository || captured.ModulePath != "example.com/candidate" || captured.Tag != testVersion || captured.Commit == "" {
|
||||||
|
t.Fatalf("tag recheck failure lost candidate evidence: %#v", captured)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validRequest(repository string) Request {
|
||||||
|
return Request{RepositoryDir: repository, Product: "Example Product", Version: testVersion, AdditionalChecks: func(context.Context, Candidate) error { return nil }}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRepository(t *testing.T, note string) string {
|
||||||
|
t.Helper()
|
||||||
|
repository := filepath.Join(t.TempDir(), "repository with spaces")
|
||||||
|
if err := os.Mkdir(repository, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
gitRun(t, repository, "init", "--initial-branch=main")
|
||||||
|
gitRun(t, repository, "config", "user.name", "ReleaseKit Test")
|
||||||
|
gitRun(t, repository, "config", "user.email", "releasekit@example.test")
|
||||||
|
gitRun(t, repository, "config", "commit.gpgsign", "false")
|
||||||
|
writeTestFile(t, repository, "go.mod", "module example.com/candidate\n\ngo 1.25.0\n")
|
||||||
|
writeTestFile(t, repository, "candidate_test.go", "package candidate\nimport \"testing\"\nfunc TestFixture(t *testing.T) {}\n")
|
||||||
|
writeTestFile(t, repository, "tracked.txt", "tracked\n")
|
||||||
|
if note != "" {
|
||||||
|
writeTestFile(t, repository, "docs/releases/"+testVersion+".md", note)
|
||||||
|
}
|
||||||
|
gitRun(t, repository, "add", "--all")
|
||||||
|
gitRun(t, repository, "commit", "-m", "candidate")
|
||||||
|
return repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeTestFile(t *testing.T, repository, name, contents string) {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(repository, filepath.FromSlash(name))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitRun(t *testing.T, repository string, args ...string) {
|
||||||
|
t.Helper()
|
||||||
|
commandArgs := append([]string{"git"}, args...)
|
||||||
|
command := exec.Command(commandArgs[0], commandArgs[1:]...)
|
||||||
|
command.Dir = repository
|
||||||
|
output, err := command.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%v: %v\n%s", commandArgs, err, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func gitOutputForTest(t *testing.T, repository string, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
commandArgs := append([]string{"git"}, args...)
|
||||||
|
command := exec.Command(commandArgs[0], commandArgs[1:]...)
|
||||||
|
command.Dir = repository
|
||||||
|
output, err := command.Output()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%v: %v", commandArgs, err)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(output))
|
||||||
|
}
|
||||||
69
internal/delivery/assets.go
Normal file
69
internal/delivery/assets.go
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
package delivery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||||
|
)
|
||||||
|
|
||||||
|
func declaredBuildAssets(result internalbuild.Result) ([]gitea.ExpectedAsset, error) {
|
||||||
|
settings := result.Settings
|
||||||
|
if len(settings.Targets) == 0 {
|
||||||
|
if len(result.Artifacts) != 0 {
|
||||||
|
return nil, fmt.Errorf("source-only build result contains artifacts")
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if len(result.Artifacts) != len(settings.Targets) {
|
||||||
|
return nil, fmt.Errorf("build result must contain one artifact for each selected target")
|
||||||
|
}
|
||||||
|
declarations := artifact.ExpectedBuild(settings.BinaryName, result.Version, settings.Targets)
|
||||||
|
wantByTarget := make(map[artifact.Target]string, len(declarations))
|
||||||
|
for _, declaration := range declarations {
|
||||||
|
target := declaration.Target
|
||||||
|
if !artifact.ValidComponent(target.OS) || !artifact.ValidComponent(target.Arch) {
|
||||||
|
return nil, fmt.Errorf("build result contains an invalid target")
|
||||||
|
}
|
||||||
|
if _, exists := wantByTarget[target]; exists {
|
||||||
|
return nil, fmt.Errorf("build result repeats target %q", target.OS+"/"+target.Arch)
|
||||||
|
}
|
||||||
|
wantByTarget[target] = declaration.Filename
|
||||||
|
}
|
||||||
|
assets := make([]gitea.ExpectedAsset, 0, len(result.Artifacts)+1)
|
||||||
|
seenTargets := make(map[artifact.Target]bool, len(result.Artifacts))
|
||||||
|
for _, artifact := range result.Artifacts {
|
||||||
|
wantName, ok := wantByTarget[artifact.Target]
|
||||||
|
if !ok || seenTargets[artifact.Target] || artifact.Filename != wantName {
|
||||||
|
return nil, fmt.Errorf("build artifact %q does not match a selected target and its declared name", artifact.Filename)
|
||||||
|
}
|
||||||
|
seenTargets[artifact.Target] = true
|
||||||
|
if filepath.Base(artifact.Path) != artifact.Filename {
|
||||||
|
return nil, fmt.Errorf("build artifact path %q does not end with filename %q", artifact.Path, artifact.Filename)
|
||||||
|
}
|
||||||
|
info, err := os.Stat(artifact.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("inspect build artifact %q: %w", artifact.Filename, err)
|
||||||
|
}
|
||||||
|
if !info.Mode().IsRegular() {
|
||||||
|
return nil, fmt.Errorf("build artifact %q is not a regular file", artifact.Filename)
|
||||||
|
}
|
||||||
|
assets = append(assets, gitea.ExpectedAsset{
|
||||||
|
Filename: artifact.Filename,
|
||||||
|
SHA256: artifact.SHA256,
|
||||||
|
Size: info.Size(),
|
||||||
|
Path: artifact.Path,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
manifest, err := gitea.BuildManifest(assets)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("build checksum manifest: %w", err)
|
||||||
|
}
|
||||||
|
if manifest.Filename != "" {
|
||||||
|
assets = append(assets, manifest)
|
||||||
|
}
|
||||||
|
return assets, nil
|
||||||
|
}
|
||||||
80
internal/delivery/assets_test.go
Normal file
80
internal/delivery/assets_test.go
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
package delivery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeclaredBuildAssetsGenerateManifestFromBuildResult(t *testing.T) {
|
||||||
|
output := t.TempDir()
|
||||||
|
first := []byte("first artifact")
|
||||||
|
second := []byte("second artifact")
|
||||||
|
firstPath := filepath.Join(output, "app-v1.2.3-linux-amd64")
|
||||||
|
secondPath := filepath.Join(output, "app-v1.2.3-darwin-arm64")
|
||||||
|
if err := os.WriteFile(firstPath, first, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(secondPath, second, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := declaredBuildAssets(internalbuild.Result{
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Settings: artifact.NormalizeSettings("./cmd/app", "app", []artifact.Target{
|
||||||
|
{OS: "linux", Arch: "amd64"}, {OS: "darwin", Arch: "arm64"},
|
||||||
|
}),
|
||||||
|
Artifacts: []internalbuild.Artifact{
|
||||||
|
{Path: firstPath, Filename: filepath.Base(firstPath), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest(first)},
|
||||||
|
{Path: secondPath, Filename: filepath.Base(secondPath), Target: internalbuild.Target{OS: "darwin", Arch: "arm64"}, SHA256: assetDigest(second)},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(result) != 3 || result[0].Filename != filepath.Base(firstPath) || result[1].Filename != filepath.Base(secondPath) || result[2].Filename != gitea.ManifestFilename {
|
||||||
|
t.Fatalf("assets = %#v", result)
|
||||||
|
}
|
||||||
|
want := assetDigest(second) + " app-v1.2.3-darwin-arm64\n" + assetDigest(first) + " app-v1.2.3-linux-amd64\n"
|
||||||
|
if string(result[2].Content) != want {
|
||||||
|
t.Fatalf("manifest = %q, want %q", result[2].Content, want)
|
||||||
|
}
|
||||||
|
if result[0].Size != int64(len(first)) || result[1].Size != int64(len(second)) {
|
||||||
|
t.Fatalf("sizes = %d, %d", result[0].Size, result[1].Size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredBuildAssetsRejectsArtifactDeclarationMismatch(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "app-v1.2.3-linux-arm64")
|
||||||
|
contents := []byte("built application")
|
||||||
|
if err := os.WriteFile(path, contents, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err := declaredBuildAssets(internalbuild.Result{
|
||||||
|
Version: "v1.2.3", Settings: artifact.NormalizeSettings("./cmd/app", "app", []artifact.Target{{OS: "linux", Arch: "amd64"}}),
|
||||||
|
Artifacts: []internalbuild.Artifact{{
|
||||||
|
Path: path, Filename: filepath.Base(path), Target: internalbuild.Target{OS: "linux", Arch: "amd64"}, SHA256: assetDigest(contents),
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "does not match a selected target") {
|
||||||
|
t.Fatalf("declaredBuildAssets() error = %v, want declaration mismatch", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeclaredBuildAssetsKeepsSourceOnlyBuildManifestFree(t *testing.T) {
|
||||||
|
assets, err := declaredBuildAssets(internalbuild.Result{})
|
||||||
|
if err != nil || len(assets) != 0 {
|
||||||
|
t.Fatalf("assets = %#v, error = %v", assets, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assetDigest(content []byte) string {
|
||||||
|
sum := sha256.Sum256(content)
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
254
internal/delivery/delivery.go
Normal file
254
internal/delivery/delivery.go
Normal file
@@ -0,0 +1,254 @@
|
|||||||
|
package delivery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/candidate"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/git"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gotool"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/releaseidentity"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/tempdir"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/versioncontract"
|
||||||
|
)
|
||||||
|
|
||||||
|
type State string
|
||||||
|
|
||||||
|
const (
|
||||||
|
NotAttempted State = "not_attempted"
|
||||||
|
Complete State = "complete"
|
||||||
|
Partial State = "partial"
|
||||||
|
Conflict State = "conflict"
|
||||||
|
Unknown State = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
RepositoryDir string
|
||||||
|
ModuleDir string
|
||||||
|
Product string
|
||||||
|
Version string
|
||||||
|
ExpectedTag string
|
||||||
|
Destination gitea.Destination
|
||||||
|
Build *internalbuild.Spec
|
||||||
|
Prebuilt *internalbuild.Result
|
||||||
|
Output io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
RepositoryDir string
|
||||||
|
ModuleDir string
|
||||||
|
ModulePath string
|
||||||
|
Tag string
|
||||||
|
CandidateCommit string
|
||||||
|
ReleaseURL string
|
||||||
|
State State
|
||||||
|
Matching []gitea.AssetIdentity
|
||||||
|
Uploaded []gitea.AssetIdentity
|
||||||
|
Pending []gitea.AssetIdentity
|
||||||
|
Conflicting []gitea.AssetIdentity
|
||||||
|
Uncertain []gitea.AssetIdentity
|
||||||
|
}
|
||||||
|
|
||||||
|
func Deliver(ctx context.Context, request Request) (Result, error) {
|
||||||
|
result := Result{State: NotAttempted}
|
||||||
|
if !versioncontract.ValidStableVersion(request.Version) {
|
||||||
|
return result, candidate.ErrInvalidVersion
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(request.Product) == "" {
|
||||||
|
return result, errors.New("product is required")
|
||||||
|
}
|
||||||
|
if request.Build != nil && request.Prebuilt != nil {
|
||||||
|
return result, errors.New("delivery cannot use both a managed build and prebuilt artifacts")
|
||||||
|
}
|
||||||
|
repositoryDir, err := git.RepositoryRoot(ctx, request.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("resolve repository directory: %w", err)
|
||||||
|
}
|
||||||
|
result.RepositoryDir = repositoryDir
|
||||||
|
commit, err := git.CaptureHead(ctx, repositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
result.CandidateCommit = commit
|
||||||
|
identity, err := releaseidentity.FromCommitted(ctx, repositoryDir, request.ModuleDir, request.Version, commit)
|
||||||
|
result.ModuleDir = identity.ModuleDir
|
||||||
|
result.ModulePath = identity.ModulePath
|
||||||
|
result.Tag = identity.Tag
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("resolve committed delivery identity: %w", err)
|
||||||
|
}
|
||||||
|
result.RepositoryDir = identity.RepositoryDir
|
||||||
|
result.ModuleDir = identity.ModuleDir
|
||||||
|
result.ModulePath = identity.ModulePath
|
||||||
|
result.Tag = identity.Tag
|
||||||
|
if request.ExpectedTag != "" && request.ExpectedTag != identity.Tag {
|
||||||
|
return result, fmt.Errorf("expected delivery tag %q does not match selected module tag %q", request.ExpectedTag, identity.Tag)
|
||||||
|
}
|
||||||
|
source, err := git.InspectTaggedSource(ctx, repositoryDir, identity.Tag)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("inspect tagged source: %w", err)
|
||||||
|
}
|
||||||
|
if source.Status != "" {
|
||||||
|
return result, fmt.Errorf("tagged checkout must be clean:\n%s", source.Status)
|
||||||
|
}
|
||||||
|
if source.Head != commit {
|
||||||
|
return result, fmt.Errorf("checkout HEAD changed from captured commit %s to %s", commit, source.Head)
|
||||||
|
}
|
||||||
|
if source.TagCommit != commit {
|
||||||
|
return result, fmt.Errorf("checkout HEAD %s does not match tag %s commit %s", source.Head, identity.Tag, source.TagCommit)
|
||||||
|
}
|
||||||
|
note, err := git.ReadCommitFile(ctx, repositoryDir, commit, identity.NotePath)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("read release note %q: %w", identity.NotePath, err)
|
||||||
|
}
|
||||||
|
if err := candidate.ValidateReleaseNote(note, request.Product, request.Version); err != nil {
|
||||||
|
return result, fmt.Errorf("release note %q: %w", identity.NotePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
build := request.Prebuilt
|
||||||
|
if request.Build != nil && len(request.Build.Targets) != 0 {
|
||||||
|
temporaryDir, err := tempdir.Outside(repositoryDir, "releasekit-delivery-build-*")
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("create temporary delivery build directory: %w", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(temporaryDir)
|
||||||
|
built, err := internalbuild.BuildResolved(ctx, internalbuild.Request{
|
||||||
|
Identity: identity,
|
||||||
|
Spec: *request.Build,
|
||||||
|
OutputDir: filepath.Join(temporaryDir, "assets"),
|
||||||
|
Output: request.Output,
|
||||||
|
ToolOwner: gotool.NewOwner(identity.ModuleDir),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("build delivery assets: %w", err)
|
||||||
|
}
|
||||||
|
build = &built
|
||||||
|
}
|
||||||
|
var assets []gitea.ExpectedAsset
|
||||||
|
if build != nil {
|
||||||
|
assets, err = declaredBuildAssets(*build)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := validateBuild(identity, commit, build, assets); err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
if len(assets) > 0 {
|
||||||
|
if err := gitea.VerifyLocalAssets(assets); err != nil {
|
||||||
|
return result, fmt.Errorf("verify build assets: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if build != nil && len(build.Settings.Targets) != 0 {
|
||||||
|
current, err := git.InspectTaggedSource(ctx, repositoryDir, identity.Tag)
|
||||||
|
if err != nil {
|
||||||
|
return result, fmt.Errorf("recheck tagged source after build: %w", err)
|
||||||
|
}
|
||||||
|
if current.Status != "" {
|
||||||
|
return result, fmt.Errorf("tagged checkout changed during build:\n%s", current.Status)
|
||||||
|
}
|
||||||
|
if current.Head != commit || current.TagCommit != commit {
|
||||||
|
return result, errors.New("tagged source changed during build")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
releaseResult, err := (gitea.Client{}).EnsureRelease(ctx, gitea.Request{
|
||||||
|
Destination: request.Destination,
|
||||||
|
Tag: identity.Tag,
|
||||||
|
Commit: commit,
|
||||||
|
Note: string(note),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
result.State = stateForError(err, false)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
result.ReleaseURL = releaseResult.Release.URL
|
||||||
|
if len(assets) == 0 {
|
||||||
|
result.State = Complete
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
inspection, err := (gitea.Client{}).InspectAssets(ctx, request.Destination, releaseResult.Release.ID, assets)
|
||||||
|
if err != nil {
|
||||||
|
result.State = NotAttempted
|
||||||
|
if releaseResult.WriteAttempted {
|
||||||
|
result.State = Partial
|
||||||
|
}
|
||||||
|
result.Uncertain = assetIdentities(assets)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
uploadResult, uploadErr := (gitea.Client{}).UploadVerifiedMissing(ctx, request.Destination, releaseResult.Release.ID, inspection)
|
||||||
|
result.Matching = uploadResult.Matching
|
||||||
|
result.Uploaded = uploadResult.Uploaded
|
||||||
|
result.Pending = uploadResult.Pending
|
||||||
|
result.Conflicting = uploadResult.Conflicting
|
||||||
|
result.Uncertain = uploadResult.Uncertain
|
||||||
|
result.State = State(uploadResult.State)
|
||||||
|
if result.State == NotAttempted && releaseResult.WriteAttempted {
|
||||||
|
result.State = Partial
|
||||||
|
}
|
||||||
|
return result, uploadErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateBuild(identity releaseidentity.Identity, commit string, build *internalbuild.Result, assets []gitea.ExpectedAsset) error {
|
||||||
|
if build == nil {
|
||||||
|
if len(assets) != 0 {
|
||||||
|
return errors.New("assets require a build identity")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
buildRepository, err := filepath.Abs(build.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("resolve build repository: %w", err)
|
||||||
|
}
|
||||||
|
buildModule, err := filepath.Abs(build.ModuleDir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("resolve build module: %w", err)
|
||||||
|
}
|
||||||
|
if buildRepository != identity.RepositoryDir || buildModule != identity.ModuleDir || build.ModulePath != identity.ModulePath || build.Tag != identity.Tag || build.CandidateCommit != commit || build.Version != identity.Version {
|
||||||
|
return errors.New("build result does not identify the selected tagged module")
|
||||||
|
}
|
||||||
|
if len(build.Settings.Targets) == 0 {
|
||||||
|
if len(assets) != 0 {
|
||||||
|
return errors.New("page-only delivery cannot include binary assets")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !build.SourceVerified {
|
||||||
|
return errors.New("build source was not verified as clean and unchanged during compilation")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(build.Settings.MainPackage) == "" || strings.TrimSpace(build.Settings.BinaryName) == "" || len(assets) != len(build.Settings.Targets)+1 || assets[len(assets)-1].Filename != gitea.ManifestFilename {
|
||||||
|
return errors.New("build result does not contain the selected artifacts and complete checksum manifest")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func stateForError(err error, pageCreated bool) State {
|
||||||
|
var failure *gitea.Failure
|
||||||
|
if errors.As(err, &failure) {
|
||||||
|
switch failure.Kind {
|
||||||
|
case gitea.FailureConflict:
|
||||||
|
return Conflict
|
||||||
|
case gitea.FailureUnknown:
|
||||||
|
return Unknown
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if pageCreated {
|
||||||
|
return Partial
|
||||||
|
}
|
||||||
|
return NotAttempted
|
||||||
|
}
|
||||||
|
|
||||||
|
func assetIdentities(assets []gitea.ExpectedAsset) []gitea.AssetIdentity {
|
||||||
|
result := make([]gitea.AssetIdentity, 0, len(assets))
|
||||||
|
for _, asset := range assets {
|
||||||
|
result = append(result, gitea.AssetIdentity{Filename: asset.Filename, SHA256: asset.SHA256})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
85
internal/delivery/performance_test.go
Normal file
85
internal/delivery/performance_test.go
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
package delivery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/artifact"
|
||||||
|
internalbuild "gitea.maximumdirect.net/eric/ReleaseKit/internal/build"
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/gitea"
|
||||||
|
)
|
||||||
|
|
||||||
|
const performanceArtifactSize = 16 << 20
|
||||||
|
|
||||||
|
func BenchmarkPerformanceAssetPreflight(b *testing.B) {
|
||||||
|
result, totalBytes := performanceBuildResult(b)
|
||||||
|
declarations, err := declaredBuildAssets(result)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
b.Run("Declarations", func(b *testing.B) {
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.SetBytes(totalBytes)
|
||||||
|
b.ResetTimer()
|
||||||
|
b.ReportMetric(float64(totalBytes), "bytes/op")
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
assets, err := declaredBuildAssets(result)
|
||||||
|
if err != nil || len(assets) != len(declarations) {
|
||||||
|
b.Fatalf("declaredBuildAssets() returned %d assets, err %v", len(assets), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
b.Run("DeclarationsAndLocalVerification", func(b *testing.B) {
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.SetBytes(totalBytes)
|
||||||
|
b.ResetTimer()
|
||||||
|
b.ReportMetric(float64(totalBytes), "bytes/op")
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
assets, err := declaredBuildAssets(result)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := gitea.VerifyLocalAssets(assets); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func performanceBuildResult(b *testing.B) (internalbuild.Result, int64) {
|
||||||
|
b.Helper()
|
||||||
|
outputDir := b.TempDir()
|
||||||
|
data := make([]byte, performanceArtifactSize)
|
||||||
|
for i := range data {
|
||||||
|
data[i] = byte((i*31 + i/251 + 17) % 251)
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256(data)
|
||||||
|
result := internalbuild.Result{
|
||||||
|
Version: "v1.2.3",
|
||||||
|
Settings: artifact.NormalizeSettings("./cmd/releasekit", "releasekit", []artifact.Target{
|
||||||
|
{OS: "linux", Arch: "amd64"},
|
||||||
|
{OS: "windows", Arch: "amd64"},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
for _, target := range result.Settings.Targets {
|
||||||
|
name := fmt.Sprintf("releasekit-v1.2.3-%s-%s", target.OS, target.Arch)
|
||||||
|
if target.OS == "windows" {
|
||||||
|
name += ".exe"
|
||||||
|
}
|
||||||
|
path := filepath.Join(outputDir, name)
|
||||||
|
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
result.Artifacts = append(result.Artifacts, internalbuild.Artifact{
|
||||||
|
Path: path, Filename: name, Target: target,
|
||||||
|
SHA256: hex.EncodeToString(digest[:]),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return result, 2 * performanceArtifactSize
|
||||||
|
}
|
||||||
222
internal/git/blob_reader.go
Normal file
222
internal/git/blob_reader.go
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/ReleaseKit/internal/process"
|
||||||
|
)
|
||||||
|
|
||||||
|
var errBlobObjectMissing = errors.New("Git object is missing")
|
||||||
|
|
||||||
|
// BlobReader reads requested blobs through one lazy git cat-file --batch
|
||||||
|
// process. Reads are serialized; callers must close the reader when finished.
|
||||||
|
type BlobReader struct {
|
||||||
|
repositoryDir string
|
||||||
|
parent context.Context
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
child *process.PipedProcess
|
||||||
|
stdout *bufio.Reader
|
||||||
|
stderr bytes.Buffer
|
||||||
|
closed bool
|
||||||
|
aborted bool
|
||||||
|
terminal error
|
||||||
|
closeErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewBlobReader creates a lazy reader for one repository. It starts no child
|
||||||
|
// process until the first valid blob is requested.
|
||||||
|
func NewBlobReader(ctx context.Context, repositoryDir string) *BlobReader {
|
||||||
|
return &BlobReader{repositoryDir: repositoryDir, parent: ctx}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read returns one blob body from the candidate repository. The returned bytes
|
||||||
|
// are newly allocated and owned by the caller.
|
||||||
|
func (reader *BlobReader) Read(ctx context.Context, objectID string) ([]byte, error) {
|
||||||
|
if !validObjectID(objectID) {
|
||||||
|
return nil, fmt.Errorf("invalid blob object ID %q", objectID)
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("read blob %s: %w", objectID, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
reader.mu.Lock()
|
||||||
|
defer reader.mu.Unlock()
|
||||||
|
if reader.terminal != nil {
|
||||||
|
return nil, reader.terminal
|
||||||
|
}
|
||||||
|
if reader.closed {
|
||||||
|
return nil, fmt.Errorf("read blob %s: Git blob reader is closed", objectID)
|
||||||
|
}
|
||||||
|
if err := reader.startLocked(); err != nil {
|
||||||
|
return nil, fmt.Errorf("read blob %s: %w", objectID, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
child := reader.child
|
||||||
|
callbackDone := make(chan struct{})
|
||||||
|
stopCancellation := context.AfterFunc(ctx, func() {
|
||||||
|
defer close(callbackDone)
|
||||||
|
child.Cancel()
|
||||||
|
_ = child.Stdin().Close()
|
||||||
|
_ = child.Stdout().Close()
|
||||||
|
})
|
||||||
|
body, err := reader.exchange(objectID)
|
||||||
|
if !stopCancellation() {
|
||||||
|
<-callbackDone
|
||||||
|
}
|
||||||
|
if contextErr := ctx.Err(); contextErr != nil {
|
||||||
|
err = contextErr
|
||||||
|
} else if contextErr := reader.parent.Err(); contextErr != nil {
|
||||||
|
err = contextErr
|
||||||
|
}
|
||||||
|
if errors.Is(err, errBlobObjectMissing) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, reader.abortLocked(objectID, err)
|
||||||
|
}
|
||||||
|
return body, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close closes a healthy session cleanly or reaps an aborted session. It is
|
||||||
|
// safe to call more than once.
|
||||||
|
func (reader *BlobReader) Close() error {
|
||||||
|
reader.mu.Lock()
|
||||||
|
defer reader.mu.Unlock()
|
||||||
|
if reader.closed {
|
||||||
|
return reader.closeErr
|
||||||
|
}
|
||||||
|
reader.closed = true
|
||||||
|
if reader.aborted {
|
||||||
|
reader.closeErr = reader.terminal
|
||||||
|
return reader.closeErr
|
||||||
|
}
|
||||||
|
if reader.child == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := reader.child.Stdin().Close(); err != nil {
|
||||||
|
reader.closeErr = reader.abortLocked("", fmt.Errorf("close Git cat-file input: %w", err))
|
||||||
|
return reader.closeErr
|
||||||
|
}
|
||||||
|
if _, err := io.Copy(io.Discard, reader.child.Stdout()); err != nil {
|
||||||
|
reader.closeErr = reader.abortLocked("", fmt.Errorf("finish Git cat-file output: %w", err))
|
||||||
|
return reader.closeErr
|
||||||
|
}
|
||||||
|
if err := reader.child.Wait(); err != nil {
|
||||||
|
reader.closeErr = reader.processError("close Git cat-file batch", err)
|
||||||
|
}
|
||||||
|
return reader.closeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (reader *BlobReader) startLocked() error {
|
||||||
|
if reader.child != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := reader.parent.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
child, err := process.StartPiped(reader.parent, process.Invocation{
|
||||||
|
Args: []string{"git", "cat-file", "--batch"},
|
||||||
|
Dir: reader.repositoryDir,
|
||||||
|
Env: map[string]string{
|
||||||
|
"GIT_NO_LAZY_FETCH": "1",
|
||||||
|
"GIT_ALLOW_PROTOCOL": "",
|
||||||
|
},
|
||||||
|
Stderr: &reader.stderr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
reader.child = child
|
||||||
|
reader.stdout = bufio.NewReader(child.Stdout())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (reader *BlobReader) exchange(objectID string) ([]byte, error) {
|
||||||
|
if _, err := io.WriteString(reader.child.Stdin(), objectID+"\n"); err != nil {
|
||||||
|
return nil, fmt.Errorf("write object request: %w", err)
|
||||||
|
}
|
||||||
|
header, err := reader.stdout.ReadString('\n')
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read object header: %w", err)
|
||||||
|
}
|
||||||
|
fields := strings.Fields(strings.TrimSuffix(header, "\n"))
|
||||||
|
if len(fields) == 2 && strings.EqualFold(fields[0], objectID) && fields[1] == "missing" {
|
||||||
|
return nil, fmt.Errorf("read blob %s: %w", objectID, errBlobObjectMissing)
|
||||||
|
}
|
||||||
|
if len(fields) != 3 {
|
||||||
|
return nil, fmt.Errorf("invalid Git blob header %q", strings.TrimSuffix(header, "\n"))
|
||||||
|
}
|
||||||
|
if !strings.EqualFold(fields[0], objectID) {
|
||||||
|
return nil, fmt.Errorf("Git blob response object ID %q does not match request %q", fields[0], objectID)
|
||||||
|
}
|
||||||
|
if fields[1] != "blob" {
|
||||||
|
return nil, fmt.Errorf("Git object %s has type %q, want blob", objectID, fields[1])
|
||||||
|
}
|
||||||
|
size, err := strconv.ParseInt(fields[2], 10, strconv.IntSize)
|
||||||
|
if err != nil || size < 0 {
|
||||||
|
if err == nil {
|
||||||
|
err = errors.New("negative object size")
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("invalid Git blob size %q: %w", fields[2], err)
|
||||||
|
}
|
||||||
|
body := make([]byte, int(size))
|
||||||
|
if _, err := io.ReadFull(reader.stdout, body); err != nil {
|
||||||
|
return nil, fmt.Errorf("read %d-byte Git blob body: %w", size, err)
|
||||||
|
}
|
||||||
|
framing, err := reader.stdout.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read Git blob framing: %w", err)
|
||||||
|
}
|
||||||
|
if framing != '\n' {
|
||||||
|
return nil, fmt.Errorf("invalid Git blob framing byte %q", framing)
|
||||||
|
}
|
||||||
|
return body, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (reader *BlobReader) abortLocked(objectID string, cause error) error {
|
||||||
|
if reader.aborted {
|
||||||
|
return reader.terminal
|
||||||
|
}
|
||||||
|
reader.aborted = true
|
||||||
|
var waitErr error
|
||||||
|
if reader.child != nil {
|
||||||
|
reader.child.Cancel()
|
||||||
|
_ = reader.child.Stdin().Close()
|
||||||
|
_ = reader.child.Stdout().Close()
|
||||||
|
waitErr = reader.child.Wait()
|
||||||
|
}
|
||||||
|
if contextErr := reader.parent.Err(); contextErr != nil {
|
||||||
|
cause = contextErr
|
||||||
|
}
|
||||||
|
reader.terminal = reader.processError("read blob "+objectID, errors.Join(cause, relevantProcessError(waitErr, cause)))
|
||||||
|
return reader.terminal
|
||||||
|
}
|
||||||
|
|
||||||
|
func (reader *BlobReader) processError(operation string, cause error) error {
|
||||||
|
message := strings.TrimSpace(reader.stderr.String())
|
||||||
|
if message != "" {
|
||||||
|
return fmt.Errorf("%s: %s: %w", operation, message, cause)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%s: %w", operation, cause)
|
||||||
|
}
|
||||||
|
|
||||||
|
func relevantProcessError(waitErr, cause error) error {
|
||||||
|
if waitErr == nil || errors.Is(cause, context.Canceled) || errors.Is(cause, context.DeadlineExceeded) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if errors.As(waitErr, &exitErr) && exitErr.ExitCode() == -1 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return waitErr
|
||||||
|
}
|
||||||
195
internal/git/blob_reader_test.go
Normal file
195
internal/git/blob_reader_test.go
Normal file
@@ -0,0 +1,195 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBlobReaderReadsLooseAndPackedObjects(t *testing.T) {
|
||||||
|
for _, packed := range []bool{false, true} {
|
||||||
|
name := "loose"
|
||||||
|
if packed {
|
||||||
|
name = "packed"
|
||||||
|
}
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
fixture := newRemoteFixture(t)
|
||||||
|
binary := []byte{0, '\n', 0xff, 'b', '\n', 0}
|
||||||
|
writeRepoFile(t, fixture.work, "empty.dat", "")
|
||||||
|
writeRepoFile(t, fixture.work, "binary.dat", string(binary))
|
||||||
|
gitRun(t, fixture.work, "add", ".")
|
||||||
|
gitRun(t, fixture.work, "commit", "-m", "add binary fixtures")
|
||||||
|
want := map[string][]byte{
|
||||||
|
gitText(t, fixture.work, "rev-parse", "HEAD:source.txt"): []byte("candidate"),
|
||||||
|
gitText(t, fixture.work, "rev-parse", "HEAD:empty.dat"): {},
|
||||||
|
gitText(t, fixture.work, "rev-parse", "HEAD:binary.dat"): binary,
|
||||||
|
}
|
||||||
|
if packed {
|
||||||
|
gitRun(t, fixture.work, "gc", "--aggressive", "--prune=now")
|
||||||
|
}
|
||||||
|
reader := NewBlobReader(t.Context(), fixture.work)
|
||||||
|
defer reader.Close()
|
||||||
|
for repeat := 0; repeat < 2; repeat++ {
|
||||||
|
for objectID, expected := range want {
|
||||||
|
got, err := reader.Read(t.Context(), objectID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Read(%s) error = %v", objectID, err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(got, expected) {
|
||||||
|
t.Errorf("Read(%s) = %v, want %v", objectID, got, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBlobReaderMissingObjectKeepsBatchSessionUsable(t *testing.T) {
|
||||||
|
fixture := newRemoteFixture(t)
|
||||||
|
objectID := gitText(t, fixture.work, "rev-parse", "HEAD:source.txt")
|
||||||
|
reader := NewBlobReader(t.Context(), fixture.work)
|
||||||
|
defer reader.Close()
|
||||||
|
missing := strings.Repeat("0", 40)
|
||||||
|
if _, err := reader.Read(t.Context(), missing); err == nil || !strings.Contains(err.Error(), "missing") {
|
||||||
|
t.Fatalf("Read(missing) error = %v, want contextual missing-object error", err)
|
||||||
|
}
|
||||||
|
contents, err := reader.Read(t.Context(), objectID)
|
||||||
|
if err != nil || string(contents) != "candidate" {
|
||||||
|
t.Fatalf("Read(existing) = %q, %v after missing request", contents, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBlobReaderPreservesHexCaseAndArbitraryBodyBytes(t *testing.T) {
|
||||||
|
installFakeGit(t, `while IFS= read -r object; do
|
||||||
|
upper=$(printf '%s' "$object" | tr 'a-f' 'A-F')
|
||||||
|
printf '%s blob 4\n' "$upper"
|
||||||
|
printf 'a\000b\n\n'
|
||||||
|
done`)
|
||||||
|
objectID := strings.Repeat("abcdef0123", 4)
|
||||||
|
reader := NewBlobReader(t.Context(), t.TempDir())
|
||||||
|
contents, err := reader.Read(t.Context(), objectID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if want := []byte{'a', 0, 'b', '\n'}; !bytes.Equal(contents, want) {
|
||||||
|
t.Fatalf("Read() = %v, want %v", contents, want)
|
||||||
|
}
|
||||||
|
if err := reader.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBlobReaderRejectsInvalidHeadersAndFraming(t *testing.T) {
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
name string
|
||||||
|
response string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "wrong object", response: `printf '%040d blob 0\n\n' 0`, want: "does not match request"},
|
||||||
|
{name: "wrong type", response: `printf '%s tree 0\n\n' "$object"`, want: `has type "tree"`},
|
||||||
|
{name: "invalid size", response: `printf '%s blob -1\n' "$object"`, want: "invalid Git blob size"},
|
||||||
|
{name: "invalid framing", response: `printf '%s blob 0\nx' "$object"`, want: "invalid Git blob framing"},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
installFakeGit(t, "IFS= read -r object\n"+testCase.response)
|
||||||
|
reader := NewBlobReader(t.Context(), t.TempDir())
|
||||||
|
_, err := reader.Read(t.Context(), strings.Repeat("d", 40))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), testCase.want) {
|
||||||
|
t.Fatalf("Read() error = %v, want %q", err, testCase.want)
|
||||||
|
}
|
||||||
|
if closeErr := reader.Close(); !strings.Contains(closeErr.Error(), testCase.want) {
|
||||||
|
t.Fatalf("Close() error = %v, want original protocol error", closeErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBlobReaderTruncatedBodyAbortsAndKeepsOriginalCause(t *testing.T) {
|
||||||
|
installFakeGit(t, `IFS= read -r object
|
||||||
|
printf '%s blob 8\n' "$object"
|
||||||
|
printf 'short'
|
||||||
|
exit 0`)
|
||||||
|
reader := NewBlobReader(t.Context(), t.TempDir())
|
||||||
|
_, err := reader.Read(t.Context(), strings.Repeat("a", 40))
|
||||||
|
if !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||||
|
t.Fatalf("Read() error = %v, want truncated-body cause", err)
|
||||||
|
}
|
||||||
|
if closeErr := reader.Close(); !errors.Is(closeErr, io.ErrUnexpectedEOF) {
|
||||||
|
t.Fatalf("Close() error = %v, want original read cause", closeErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBlobReaderCancellationDuringBodyReadReapsChild(t *testing.T) {
|
||||||
|
ready := filepath.Join(t.TempDir(), "ready")
|
||||||
|
installFakeGit(t, `IFS= read -r object
|
||||||
|
printf '%s blob 1048576\npartial' "$object"
|
||||||
|
: > "$RELEASEKIT_GIT_READER_READY"
|
||||||
|
exec sleep 60`)
|
||||||
|
t.Setenv("RELEASEKIT_GIT_READER_READY", ready)
|
||||||
|
ctx, cancel := context.WithCancel(t.Context())
|
||||||
|
reader := NewBlobReader(ctx, t.TempDir())
|
||||||
|
result := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
_, err := reader.Read(ctx, strings.Repeat("b", 40))
|
||||||
|
result <- err
|
||||||
|
}()
|
||||||
|
waitForFile(t, ready)
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case err := <-result:
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("Read() error = %v, want context cancellation", err)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("Read() did not return after cancellation")
|
||||||
|
}
|
||||||
|
if err := reader.Close(); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("Close() error = %v, want original cancellation cause", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBlobReaderPreservesGitFailureAndStderr(t *testing.T) {
|
||||||
|
installFakeGit(t, `printf 'fixture Git failure\n' >&2
|
||||||
|
exit 23`)
|
||||||
|
reader := NewBlobReader(t.Context(), t.TempDir())
|
||||||
|
_, err := reader.Read(t.Context(), strings.Repeat("c", 40))
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 23 {
|
||||||
|
t.Fatalf("Read() error = %v, want Git exit code 23", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "fixture Git failure") {
|
||||||
|
t.Fatalf("Read() error = %v, want captured Git stderr", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func installFakeGit(t *testing.T, script string) {
|
||||||
|
t.Helper()
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "git")
|
||||||
|
if err := os.WriteFile(path, []byte("#!/bin/sh\n"+script+"\n"), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForFile(t *testing.T, path string) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
if _, err := os.Stat(path); err == nil {
|
||||||
|
return
|
||||||
|
} else if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatal(fmt.Errorf("inspect readiness signal: %w", err))
|
||||||
|
}
|
||||||
|
time.Sleep(5 * time.Millisecond)
|
||||||
|
}
|
||||||
|
t.Fatal("child did not create readiness signal")
|
||||||
|
}
|
||||||
155
internal/git/path.go
Normal file
155
internal/git/path.go
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PathResolver traverses committed paths, sharing reference rules between
|
||||||
|
// release identity and validation. Lookups include both files and directories.
|
||||||
|
type PathResolver struct {
|
||||||
|
RepositoryDir string
|
||||||
|
Lookup func(context.Context, string) (TreeEntry, bool, error)
|
||||||
|
ReadLink func(context.Context, TreeEntry) (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DestinationKind classifies a committed local destination.
|
||||||
|
type DestinationKind string
|
||||||
|
|
||||||
|
const (
|
||||||
|
DestinationEntry DestinationKind = "entry"
|
||||||
|
DestinationDirectory DestinationKind = "directory"
|
||||||
|
DestinationMissing DestinationKind = "missing"
|
||||||
|
DestinationOutsideCheckout DestinationKind = "outside-checkout"
|
||||||
|
DestinationSubmodule DestinationKind = "submodule"
|
||||||
|
DestinationSymlinkCycle DestinationKind = "symlink-cycle"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Destination records the resolved identity and its classification.
|
||||||
|
type Destination struct {
|
||||||
|
Kind DestinationKind
|
||||||
|
Path string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveDestination resolves local destinations using the captured Git tree.
|
||||||
|
// Relative destinations start at the source directory; absolute destinations
|
||||||
|
// within the repository directory map back to committed paths.
|
||||||
|
func (resolver PathResolver) ResolveDestination(ctx context.Context, sourcePath, destination string) (Destination, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return Destination{}, err
|
||||||
|
}
|
||||||
|
directory := path.Dir(sourcePath)
|
||||||
|
if path.IsAbs(destination) {
|
||||||
|
relative, inside, err := resolver.relativeAbsoluteDestination(destination)
|
||||||
|
if err != nil {
|
||||||
|
return Destination{}, err
|
||||||
|
}
|
||||||
|
if !inside {
|
||||||
|
return Destination{Kind: DestinationOutsideCheckout, Path: destination}, nil
|
||||||
|
}
|
||||||
|
directory, destination = ".", relative
|
||||||
|
}
|
||||||
|
return resolver.resolveDestination(ctx, directory, strings.Split(destination, "/"), make(map[string]bool))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (resolver PathResolver) resolveDestination(ctx context.Context, directory string, components []string, active map[string]bool) (Destination, error) {
|
||||||
|
for index, component := range components {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return Destination{}, err
|
||||||
|
}
|
||||||
|
remaining := components[index+1:]
|
||||||
|
switch component {
|
||||||
|
case "", ".":
|
||||||
|
continue
|
||||||
|
case "..":
|
||||||
|
if directory == "." {
|
||||||
|
return Destination{Kind: DestinationOutsideCheckout, Path: unresolvedPath("..", remaining)}, nil
|
||||||
|
}
|
||||||
|
directory = path.Dir(directory)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
partial := path.Join(directory, component)
|
||||||
|
entry, exists, err := resolver.Lookup(ctx, partial)
|
||||||
|
if err != nil {
|
||||||
|
return Destination{}, err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return Destination{Kind: DestinationMissing, Path: unresolvedPath(partial, remaining)}, nil
|
||||||
|
}
|
||||||
|
if entry.Type == "tree" {
|
||||||
|
directory = partial
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if entry.Mode == "160000" {
|
||||||
|
return Destination{Kind: DestinationSubmodule, Path: unresolvedPath(partial, remaining)}, nil
|
||||||
|
}
|
||||||
|
if entry.Mode == "120000" {
|
||||||
|
if active[partial] {
|
||||||
|
return Destination{Kind: DestinationSymlinkCycle, Path: partial}, nil
|
||||||
|
}
|
||||||
|
linkText, err := resolver.ReadLink(ctx, entry)
|
||||||
|
if err != nil {
|
||||||
|
return Destination{}, fmt.Errorf("read committed symlink %q: %w", partial, err)
|
||||||
|
}
|
||||||
|
target := linkText
|
||||||
|
targetDirectory := directory
|
||||||
|
if path.IsAbs(target) {
|
||||||
|
relative, inside, err := resolver.relativeAbsoluteDestination(target)
|
||||||
|
if err != nil {
|
||||||
|
return Destination{}, err
|
||||||
|
}
|
||||||
|
if !inside {
|
||||||
|
return Destination{Kind: DestinationOutsideCheckout, Path: unresolvedPath(target, remaining)}, nil
|
||||||
|
}
|
||||||
|
targetDirectory, target = ".", relative
|
||||||
|
}
|
||||||
|
active[partial] = true
|
||||||
|
destination, err := resolver.resolveDestination(ctx, targetDirectory, strings.Split(target, "/"), active)
|
||||||
|
delete(active, partial)
|
||||||
|
if err != nil || len(remaining) == 0 {
|
||||||
|
return destination, err
|
||||||
|
}
|
||||||
|
switch destination.Kind {
|
||||||
|
case DestinationDirectory:
|
||||||
|
return resolver.resolveDestination(ctx, destination.Path, remaining, active)
|
||||||
|
case DestinationEntry:
|
||||||
|
destination.Kind = DestinationMissing
|
||||||
|
case DestinationSymlinkCycle:
|
||||||
|
return destination, nil
|
||||||
|
}
|
||||||
|
destination.Path = unresolvedPath(destination.Path, remaining)
|
||||||
|
return destination, nil
|
||||||
|
}
|
||||||
|
if len(remaining) != 0 {
|
||||||
|
return Destination{Kind: DestinationMissing, Path: unresolvedPath(partial, remaining)}, nil
|
||||||
|
}
|
||||||
|
return Destination{Kind: DestinationEntry, Path: partial}, nil
|
||||||
|
}
|
||||||
|
return Destination{Kind: DestinationDirectory, Path: directory}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (resolver PathResolver) relativeAbsoluteDestination(destination string) (string, bool, error) {
|
||||||
|
root, err := filepath.Abs(resolver.RepositoryDir)
|
||||||
|
if err != nil {
|
||||||
|
return "", false, fmt.Errorf("resolve candidate repository directory: %w", err)
|
||||||
|
}
|
||||||
|
root = filepath.ToSlash(root)
|
||||||
|
if destination == root {
|
||||||
|
return ".", true, nil
|
||||||
|
}
|
||||||
|
// Preserve the suffix for component traversal, including symlinks before '..'.
|
||||||
|
relative, inside := strings.CutPrefix(destination, strings.TrimSuffix(root, "/")+"/")
|
||||||
|
return relative, inside, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// unresolvedPath preserves components that could not be traversed. Cleaning
|
||||||
|
// them would hide missing entries, non-directories, or checkout boundaries.
|
||||||
|
func unresolvedPath(base string, remaining []string) string {
|
||||||
|
if len(remaining) == 0 {
|
||||||
|
return base
|
||||||
|
}
|
||||||
|
return base + "/" + strings.Join(remaining, "/")
|
||||||
|
}
|
||||||
59
internal/git/performance_test.go
Normal file
59
internal/git/performance_test.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package git
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func BenchmarkPerformanceBlobReader(b *testing.B) {
|
||||||
|
fixture := newRemoteFixture(b)
|
||||||
|
objectID := gitText(b, fixture.work, "rev-parse", "HEAD:source.txt")
|
||||||
|
const expectedBytes = int64(len("candidate"))
|
||||||
|
|
||||||
|
b.Run("new-session-per-read", func(b *testing.B) {
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.SetBytes(expectedBytes)
|
||||||
|
b.ResetTimer()
|
||||||
|
b.ReportMetric(float64(expectedBytes), "bytes/op")
|
||||||
|
b.ReportMetric(1, "blobs/op")
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
reader := NewBlobReader(context.Background(), fixture.work)
|
||||||
|
contents, err := reader.Read(context.Background(), objectID)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
if int64(len(contents)) != expectedBytes {
|
||||||
|
b.Fatalf("read %d bytes, want %d", len(contents), expectedBytes)
|
||||||
|
}
|
||||||
|
if err := reader.Close(); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
runtime.KeepAlive(contents)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
b.Run("shared-session", func(b *testing.B) {
|
||||||
|
reader := NewBlobReader(context.Background(), fixture.work)
|
||||||
|
b.Cleanup(func() {
|
||||||
|
if err := reader.Close(); err != nil {
|
||||||
|
b.Error(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.SetBytes(expectedBytes)
|
||||||
|
b.ResetTimer()
|
||||||
|
b.ReportMetric(float64(expectedBytes), "bytes/op")
|
||||||
|
b.ReportMetric(1, "blobs/op")
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
contents, err := reader.Read(context.Background(), objectID)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
if int64(len(contents)) != expectedBytes {
|
||||||
|
b.Fatalf("read %d bytes, want %d", len(contents), expectedBytes)
|
||||||
|
}
|
||||||
|
runtime.KeepAlive(contents)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user