mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-21 20:23:39 +09:00
Merge branch 'main' into feat/ingress-nginx-keepalive-time
Assisted-by: LLM Signed-off-by: Aleksei Sviridkin <f@lex.la>
This commit is contained in:
254 files changed
+32491
-1154
No files matched your search
@@ -543,7 +543,7 @@ jobs:
|
||||
# Covers a green full suite. It does not cover a tenant-Kubernetes suite
|
||||
# running into its node-join deadline, so a red there can end as a
|
||||
# cancelled job. Held to one figure across every lane that runs the suite.
|
||||
timeout-minutes: 215
|
||||
timeout-minutes: 265
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
@@ -771,21 +771,6 @@ jobs:
|
||||
name: cozyreport
|
||||
path: _out/cozyreport.tgz
|
||||
if-no-files-found: warn
|
||||
# Both halves, and in this order: the compose project owns the nodes and
|
||||
# the zpools outlive it.
|
||||
- name: Tear down sandbox
|
||||
if: always()
|
||||
run: |
|
||||
# Annotated, not fatal: same reasoning as the in-tree lane. The runner
|
||||
# is discarded after the job, so a dirty host has no next tenant, and
|
||||
# failing here would post the required "E2E Tests" status as a failure
|
||||
# indistinguishable from a real one.
|
||||
cleanup_rc=0
|
||||
make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete-cluster-container || cleanup_rc=$?
|
||||
make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete || true
|
||||
if [ "$cleanup_rc" -ne 0 ]; then
|
||||
echo "::error title=sandbox teardown::teardown exited $cleanup_rc; the host may hold a stale compose project or zpool"
|
||||
fi
|
||||
|
||||
# Flip the pending "E2E Tests" commit status posted by `resolve` to its
|
||||
# terminal state. Runs on failure too, so a failed publish or e2e turns the
|
||||
|
||||
@@ -137,7 +137,7 @@ jobs:
|
||||
# Covers a green full suite. It does not cover a tenant-Kubernetes suite
|
||||
# running into its node-join deadline, so a red there can end as a
|
||||
# cancelled job. Held to one figure across every lane that runs the suite.
|
||||
timeout-minutes: 215
|
||||
timeout-minutes: 265
|
||||
permissions:
|
||||
contents: read
|
||||
checks: write # Breakpoint action updates its dedicated "Breakpoint Open" Check Run.
|
||||
@@ -292,7 +292,7 @@ jobs:
|
||||
# collect-report packages cozyreport plus per-failed-test crust-gather
|
||||
# snapshots captured before Chainsaw cleanup.
|
||||
#
|
||||
# A ceiling of its own, not the job's 215 minutes. `Upload cozyreport.tgz`
|
||||
# A ceiling of its own, not the job's 265 minutes. `Upload cozyreport.tgz`
|
||||
# is the next step and the collector writes its tarball at the very end of
|
||||
# its run, so a read that never returns spends what is left of the job
|
||||
# budget, the job is cancelled, and the upload never runs -- the artifact
|
||||
|
||||
@@ -250,7 +250,7 @@ jobs:
|
||||
# Covers a green full suite. It does not cover a tenant-Kubernetes suite
|
||||
# running into its node-join deadline, so a red there can end as a
|
||||
# cancelled job. Held to one figure across every lane that runs the suite.
|
||||
timeout-minutes: 215
|
||||
timeout-minutes: 265
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
@@ -385,7 +385,7 @@ jobs:
|
||||
path: _out/chainsaw-report.xml
|
||||
if-no-files-found: ignore
|
||||
|
||||
# A ceiling of its own, not the job's 215 minutes. `Upload cozyreport.tgz`
|
||||
# A ceiling of its own, not the job's 265 minutes. `Upload cozyreport.tgz`
|
||||
# is the next step and the collector writes its tarball at the very end of
|
||||
# its run, so a read that never returns spends what is left of the job
|
||||
# budget, the job is cancelled, and the upload never runs -- the artifact
|
||||
|
||||
@@ -953,7 +953,7 @@ jobs:
|
||||
# Covers a green full suite. It does not cover a tenant-Kubernetes suite
|
||||
# running into its node-join deadline, so a red there can end as a
|
||||
# cancelled job. Held to one figure across every lane that runs the suite.
|
||||
timeout-minutes: 215
|
||||
timeout-minutes: 265
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
@@ -1224,7 +1224,7 @@ jobs:
|
||||
|
||||
# ▸ Collect debug information (always runs)
|
||||
#
|
||||
# A ceiling of its own, not the job's 215 minutes. `Upload
|
||||
# A ceiling of its own, not the job's 265 minutes. `Upload
|
||||
# cozyreport.tgz` is the next step and the collector writes its tarball
|
||||
# at the very end of its run, so a read that never returns spends what
|
||||
# is left of the job budget, the job is cancelled, and the upload never
|
||||
@@ -1235,7 +1235,7 @@ jobs:
|
||||
# 30 minutes is measured against the step: it takes 3-42s across sampled
|
||||
# runs, on failed e2e jobs as well as green ones. It RESERVES nothing --
|
||||
# `timeout-minutes` caps a step, it does not carve budget out of the job,
|
||||
# so a suite that has already burned 210 of the 215 leaves this step five
|
||||
# so a suite that has already burned 260 of the 265 leaves this step five
|
||||
# minutes and the upload is cancelled with everything else. What the cap
|
||||
# buys is that a hung read cannot be the reason.
|
||||
# `continue-on-error` because the ceiling must not change what the job
|
||||
@@ -1348,28 +1348,6 @@ jobs:
|
||||
Resume from inside: `breakpoint resume`. Otherwise the breakpoint
|
||||
exits 10 minutes after the last SSH session disconnects.
|
||||
|
||||
# ▸ Tear down environment (always runs)
|
||||
#
|
||||
# Both halves, and in this order: the compose project owns the nodes and
|
||||
# the zpools outlive it. A leftover pool makes the next run on a reused
|
||||
# host adopt storage that already carries a dead cluster's volumes.
|
||||
- name: Tear down sandbox
|
||||
if: always()
|
||||
run: |
|
||||
# Loud, but never the job's verdict. A failed teardown means a dirty
|
||||
# host, and this runner is discarded after the job, so there is no next
|
||||
# run to protect -- while failing the job here posts the required
|
||||
# "E2E Tests" status as a failure that no reader can tell apart from a
|
||||
# real one. The annotation is what a reused host (a developer machine)
|
||||
# needs; `delete-cluster-container` returning non-zero is not evidence
|
||||
# about the product.
|
||||
cleanup_rc=0
|
||||
make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete-cluster-container || cleanup_rc=$?
|
||||
make -C packages/core/testing SANDBOX_NAME=$SANDBOX_NAME delete || true
|
||||
if [ "$cleanup_rc" -ne 0 ]; then
|
||||
echo "::error title=sandbox teardown::teardown exited $cleanup_rc; the host may hold a stale compose project or zpool"
|
||||
fi
|
||||
|
||||
# Report the required "E2E Tests" gate as a commit status rather than relying
|
||||
# on a job named "E2E Tests". A required *job* that is skipped counts
|
||||
# as PASSED by branch protection — desired for docs-only PRs, but the exact
|
||||
|
||||
@@ -23,6 +23,7 @@ _repos
|
||||
/flux-shard-operator
|
||||
/kubeovn-plunger
|
||||
/lineage-controller-webhook
|
||||
/observability-proxy
|
||||
/securitygroup-controller
|
||||
|
||||
# User-specific stuff
|
||||
|
||||
@@ -17,6 +17,7 @@ build: build-deps
|
||||
make -C packages/system/cozystack-api image
|
||||
make -C packages/system/cozystack-controller image
|
||||
make -C packages/system/backup-controller image
|
||||
make -C packages/system/observability-proxy image
|
||||
make -C packages/system/backupstrategy-controller image
|
||||
make -C packages/system/lineage-controller-webhook image
|
||||
make -C packages/system/migration-controller image
|
||||
|
||||
Generated
+1
-1
@@ -58,7 +58,7 @@ type ConfigSpec struct {
|
||||
// Users configuration map. Passwords are always auto-generated and stored in the `<release>-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.
|
||||
// +kubebuilder:default:={}
|
||||
Users map[string]User `json:"users,omitempty"`
|
||||
// Databases configuration map.
|
||||
// Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.
|
||||
// +kubebuilder:default:={}
|
||||
Databases map[string]Database `json:"databases,omitempty"`
|
||||
// Backup configuration.
|
||||
|
||||
Generated
+3
@@ -74,6 +74,9 @@ type ConfigSpec struct {
|
||||
}
|
||||
|
||||
type Disk struct {
|
||||
// Boot priority of the disk, 1 being tried first. Unset falls back to the disk's position in `disks` (the first disk gets 1), so set it to boot from a disk other than the first, such as an attached installer or rescue ISO, without reordering the list. Effective boot orders must be unique across disks: when one disk is given a value that another takes from its position, set both.
|
||||
// +kubebuilder:validation:Minimum=1
|
||||
BootOrder *int `json:"bootOrder,omitempty"`
|
||||
// Disk bus type (e.g. "sata").
|
||||
Bus string `json:"bus,omitempty"`
|
||||
// Disk name.
|
||||
|
||||
+8
-1
@@ -61,7 +61,9 @@ func (in *ConfigSpec) DeepCopyInto(out *ConfigSpec) {
|
||||
if in.Disks != nil {
|
||||
in, out := &in.Disks, &out.Disks
|
||||
*out = make([]Disk, len(*in))
|
||||
copy(*out, *in)
|
||||
for i := range *in {
|
||||
(*in)[i].DeepCopyInto(&(*out)[i])
|
||||
}
|
||||
}
|
||||
if in.Networks != nil {
|
||||
in, out := &in.Networks, &out.Networks
|
||||
@@ -100,6 +102,11 @@ func (in *ConfigSpec) DeepCopy() *ConfigSpec {
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *Disk) DeepCopyInto(out *Disk) {
|
||||
*out = *in
|
||||
if in.BootOrder != nil {
|
||||
in, out := &in.BootOrder, &out.BootOrder
|
||||
*out = new(int)
|
||||
**out = **in
|
||||
}
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Disk.
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// Package v1alpha1 defines strategy.backups.cozystack.io API types.
|
||||
//
|
||||
// Group: strategy.backups.cozystack.io
|
||||
// Version: v1alpha1
|
||||
package v1alpha1
|
||||
|
||||
import (
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
SchemeBuilder.Register(func(s *runtime.Scheme) error {
|
||||
s.AddKnownTypes(GroupVersion,
|
||||
&Kubernetes{},
|
||||
&KubernetesList{},
|
||||
)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
const (
|
||||
KubernetesStrategyKind = "Kubernetes"
|
||||
)
|
||||
|
||||
// +kubebuilder:object:root=true
|
||||
// +kubebuilder:subresource:status
|
||||
// +kubebuilder:resource:scope=Cluster
|
||||
|
||||
// Kubernetes defines a backup strategy for a tenant Kubernetes application.
|
||||
// A tenant cluster keeps its state in two places the platform can reach: the
|
||||
// cluster's key prefix in the tenant's shared etcd DataStore, and host-side
|
||||
// objects (control-plane PKI Secrets, the application HelmReleases, and the
|
||||
// DataVolumes that back the tenant's PersistentVolumes). The strategy captures
|
||||
// the first with a one-shot Job and the second with Velero. The two are taken
|
||||
// one after another, so a backup is crash-consistent at best.
|
||||
type Kubernetes struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
metav1.ObjectMeta `json:"metadata,omitempty"`
|
||||
|
||||
Spec KubernetesSpec `json:"spec,omitempty"`
|
||||
Status KubernetesStatus `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
// +kubebuilder:object:root=true
|
||||
|
||||
// KubernetesList contains a list of Kubernetes backup strategies.
|
||||
type KubernetesList struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
metav1.ListMeta `json:"metadata,omitempty"`
|
||||
Items []Kubernetes `json:"items"`
|
||||
}
|
||||
|
||||
// KubernetesSpec specifies the desired behavior of a Kubernetes backup strategy.
|
||||
type KubernetesSpec struct {
|
||||
// Template holds a PodTemplateSpec for the Job that dumps the cluster's
|
||||
// key prefix from its etcd DataStore to object storage, writes it back on
|
||||
// restore, and deletes the object on cleanup. The Job runs in the
|
||||
// application namespace. Helm-like Go templates are supported in every
|
||||
// string field and are rendered against:
|
||||
// - `.Release.Name` and `.Release.Namespace` — the application's name and
|
||||
// namespace; `.Release.Prefix` is `kubernetes-`.
|
||||
// - `.Mode` — `"backup"`, `"restore"` or `"cleanup"`.
|
||||
// - `.ObjectKey` — the object-storage key of this backup's dump.
|
||||
// - `.Datastore.Prefix` — the cluster's key prefix, without slashes.
|
||||
// - `.Datastore.Endpoints` — comma-separated etcd client URLs.
|
||||
// - `.Datastore.CertificateSecret` — the Secret holding the cluster's
|
||||
// etcd client certificate (`ca.crt`, `server.crt`, `server.key`).
|
||||
// - `.Parameters` — the resolved BackupClass strategy parameters.
|
||||
//
|
||||
// Stored schemaless for the same CRD-size reason as redis_types.go.
|
||||
//
|
||||
// +kubebuilder:validation:Schemaless
|
||||
// +kubebuilder:pruning:PreserveUnknownFields
|
||||
Template corev1.PodTemplateSpec `json:"template"`
|
||||
|
||||
// Velero holds the Velero Backup and Restore specs for the host-side
|
||||
// objects and volumes. Rendered against `.Application` and `.Parameters`,
|
||||
// like the Velero strategy.
|
||||
//
|
||||
// +kubebuilder:validation:Schemaless
|
||||
// +kubebuilder:pruning:PreserveUnknownFields
|
||||
Velero VeleroTemplate `json:"velero"`
|
||||
|
||||
// CertificateWarningThreshold is how close to expiry a control-plane
|
||||
// certificate may be before a backup records a warning. Defaults to 720h.
|
||||
// +optional
|
||||
CertificateWarningThreshold *metav1.Duration `json:"certificateWarningThreshold,omitempty"`
|
||||
}
|
||||
|
||||
type KubernetesStatus struct {
|
||||
Conditions []metav1.Condition `json:"conditions,omitempty"`
|
||||
}
|
||||
+103
@@ -839,6 +839,109 @@ func (in *KafkaStatus) DeepCopy() *KafkaStatus {
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *Kubernetes) DeepCopyInto(out *Kubernetes) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
|
||||
in.Spec.DeepCopyInto(&out.Spec)
|
||||
in.Status.DeepCopyInto(&out.Status)
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Kubernetes.
|
||||
func (in *Kubernetes) DeepCopy() *Kubernetes {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(Kubernetes)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
|
||||
func (in *Kubernetes) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *KubernetesList) DeepCopyInto(out *KubernetesList) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
in.ListMeta.DeepCopyInto(&out.ListMeta)
|
||||
if in.Items != nil {
|
||||
in, out := &in.Items, &out.Items
|
||||
*out = make([]Kubernetes, len(*in))
|
||||
for i := range *in {
|
||||
(*in)[i].DeepCopyInto(&(*out)[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesList.
|
||||
func (in *KubernetesList) DeepCopy() *KubernetesList {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(KubernetesList)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
|
||||
func (in *KubernetesList) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *KubernetesSpec) DeepCopyInto(out *KubernetesSpec) {
|
||||
*out = *in
|
||||
in.Template.DeepCopyInto(&out.Template)
|
||||
in.Velero.DeepCopyInto(&out.Velero)
|
||||
if in.CertificateWarningThreshold != nil {
|
||||
in, out := &in.CertificateWarningThreshold, &out.CertificateWarningThreshold
|
||||
*out = new(v1.Duration)
|
||||
**out = **in
|
||||
}
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesSpec.
|
||||
func (in *KubernetesSpec) DeepCopy() *KubernetesSpec {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(KubernetesSpec)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *KubernetesStatus) DeepCopyInto(out *KubernetesStatus) {
|
||||
*out = *in
|
||||
if in.Conditions != nil {
|
||||
in, out := &in.Conditions, &out.Conditions
|
||||
*out = make([]v1.Condition, len(*in))
|
||||
for i := range *in {
|
||||
(*in)[i].DeepCopyInto(&(*out)[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesStatus.
|
||||
func (in *KubernetesStatus) DeepCopy() *KubernetesStatus {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(KubernetesStatus)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *MariaDB) DeepCopyInto(out *MariaDB) {
|
||||
*out = *in
|
||||
|
||||
@@ -9,16 +9,19 @@ go build ./cmd/backport-batch
|
||||
./backport-batch run --line release-1.7 [--onto SHA] [--date YYYY-MM-DD] [--no-workflow-files] [--push] [--policy REF]
|
||||
./backport-batch run --line release-1.7 --continue [--no-workflow-files] [--push] [--policy REF]
|
||||
./backport-batch run --line release-1.7 --defer 4321[,4322] --reason "fails the e2e of the app" [--push] [--policy REF]
|
||||
./backport-batch run --line release-1.7 --drop 4321[,4322] --reason "builds on the 1.8 storage rework" [--push] [--policy REF]
|
||||
./backport-batch run --line release-1.7 --undrop 4321[,4322] [--push] [--policy REF]
|
||||
./backport-batch check --line release-1.7 [--cut] [--policy REF]
|
||||
./backport-batch fold --line release-1.7 --original 4321 --commit SHA [--policy REF]
|
||||
./backport-batch verify --line release-1.7 [--head SHA]
|
||||
./backport-batch notify --line release-1.7 [--mention org/team|login] [--push]
|
||||
./backport-batch report --pr 5246 [--id ID] [--json]
|
||||
./backport-batch lines [--policy REF]
|
||||
```
|
||||
|
||||
[`hack/backport-batch-scheduled.sh`](../../hack/backport-batch-scheduled.sh) runs `lines`, then `run --continue --push`, `check` and `notify` for each line; [`backport-batch.yaml`](../../.github/workflows/backport-batch.yaml) runs it on schedule as the cozystack-ci App, with `--no-workflow-files`, which it hands to `run`.
|
||||
|
||||
Requires `git` and an authenticated `gh` on PATH, and a remote called `origin`. Every command but `notify` fetches `origin` first; `notify` reads only GitHub. The batch runs only for the lines `lines` prints.
|
||||
Requires `git` and an authenticated `gh` on PATH, and a remote called `origin`. Every command but `notify` and `report` fetches `origin` first; `notify` reads only GitHub, and `report` reads GitHub and, for a report that keeps drops, the clone's history. The batch runs only for the lines `lines` prints.
|
||||
|
||||
`run`, `check`, `fold` and `lines` read the `backport-policy` block of the policy page from `origin/main`, or from the ref `--policy` names, which is how a change to the page is tried before it merges; `verify` and `notify` do not read it and take no `--policy`. A line the block lists takes nothing merged into `main` before the day it gives, unless the original carries `backport/include`; any other line starts at its fork point. A page without exactly one readable block stops the run with exit 2.
|
||||
|
||||
@@ -28,38 +31,58 @@ Build the binary wherever an exit code matters: `go run` turns any non-zero exit
|
||||
|
||||
Switches the current working tree to `backport-batch/<line>-<yyyymmdd>`, created at `origin/<line>`, and picks onto it one original at a time, in the order they merged into `main`, as one unit each on the branch's first-parent line. A pull request merged into `main` with a merge commit `M` goes on as its own commits, `git rev-list --reverse --topo-order --no-merges M^1..M^2`, each picked with `git cherry-pick -x --signoff`, so each keeps its author, message and sign-offs and gains the `(cherry picked from commit …)` line; the merges that brought `main` into its branch are left out, since `main` already has what they brought. A merge commit then joins the picks to the batch: its first parent is the batch before the original, its second the last pick, and its message is `M`'s with a paragraph of its own, `Backported-from: M`. A pull request squash-merged into `main` goes on as one pick. When any commit of an original conflicts, the pick is aborted, the branch goes back to where it was before that original, and the original is recorded with the commit that failed and its files; the run goes on with the next one. A commit the branch already carries is skipped as empty, and an original none of whose commits changes anything is reported as carried. The tree has to be clean. A local branch of that name is reset to where the run starts; when that drops commits only it has, the run first prints its tip and the `git branch` command that restores them, and so does `--defer`. Signing follows your git configuration; hooks are off for the picks and the merge, so each commit carries its message as git writes it.
|
||||
|
||||
The pull request body goes to stdout, built from the line's own `.github/PULL_REQUEST_TEMPLATE.md`: the originals on the branch, each with how many commits it brought and which of them differ from the commit they were picked from by `git patch-id`, a resolution or a pick git had to fit, the deferred conflicts with the commit that failed and its files, the skipped pull requests counted by rule with the lists collapsed, the originals' release notes, and a `backport-batch` block of JSON that lists the deferred conflicts for `check`. The title is `fix(backport): batch for <line>, <date>`. A body that would pass GitHub's 65536-byte limit leaves out its longest skipped lists, and the run prints them on stderr instead.
|
||||
The pull request body goes to stdout, built from the line's own `.github/PULL_REQUEST_TEMPLATE.md`: the originals on the branch, each with how many commits it brought and which of them differ from the commit they were picked from by `git patch-id`, a resolution or a pick git had to fit, the deferred conflicts with the commit that failed and its files, what is parked and why, the skipped pull requests counted by rule with the lists collapsed, the originals' release notes, and two blocks of JSON. An original whose unit differs from it, a pick whose patch-id differs from its commit's or a unit whose net patch-id differs from the original merge's, as when a first commit came out empty because the line already had that change, keeps its release note out of the release-note block: it goes under "Check these notes", with a `git range-diff --creation-factor=999 <commit>^! <pick>^!` for each pick that differs, which pairs the two however much the pick lost, and the `git diff` of the original's merge and of its unit, and the record and the report mark it `changed`. The two blocks of JSON are the [line's record](#the-lines-record-and-reports) in `backport-batch`, which later runs, `check` and `notify` act on, and the run's report in `backport-batch-report`. The title is `fix(backport): batch for <line>, <date>`. A body that would pass GitHub's 65536-byte limit leaves out its longest skipped lists, and the run prints them on stderr instead; one that what it has to carry still puts over the limit is refused before anything is pushed.
|
||||
|
||||
`--onto SHA` continues a batch already pushed instead of starting a new one. SHA has to be the head the remote has for a batch branch of the line right now, read with `git ls-remote`, so a head someone pushed onto since is refused. What that branch carries stays, and only what it does not carry yet is picked on top, so the next push is a fast-forward. `--continue` takes SHA from the open batch pull request, and starts a new batch when none is open, which is what the scheduled run does.
|
||||
|
||||
`--no-workflow-files` is for a token that may not push a change to `.github/workflows/`, which the scheduled run's App token may not. An original that changes anything there is not picked: the body lists it under "Waiting for a maintainer" with those files, and the `backport-batch` block records it with `"workflows": true`, so `check`, `notify` and a run that continues the batch know it waits. It is never a conflict. A run without the flag, a maintainer's with their own token, picks it like any other original, onto the open batch when it continues one.
|
||||
|
||||
`--defer N[,N] --reason TEXT` takes originals out of the open batch pull request, usually the ones a failing check was pinned on. It builds the batch branch again off `origin/<line>` without their units: while the batch still sits on the line's head, the units before the first one it drops stay as they are, and every later one, a pushed resolution included, is picked again in its own shape, a merge's picks one by one and then the merge with its message. When dropping one leaves a later commit that no longer applies, the run stops and names that commit's original, to defer as well. It adds no new original. It also takes out an original that got `backport/skip` after the batch picked it, which a run never removes on its own and the body lists as still on the branch. The body records each deferred original with the reason in the `backport-batch` block; a run that continues this batch keeps them out, and the next batch tries them again. A batch that carries a merge commit other than an original's, as GitHub's update-branch button makes, is refused, since picking such a merge again would lose what it resolved.
|
||||
A clean pick can still carry only part of its original: git deletes a file the line never had without a word, and leaves alone a file the line lacks. So every path the original modifies or deletes, `M` or `D` in `git diff --name-status --no-renames M^1 M`, is judged at its counterpart on the line: the path itself, or the one a rename `git diff -M` finds between the line's fork point and `M^1` on `main`, between the fork point and the line, or both in turn. A modified path counts as left without effect when its counterpart exists neither before nor after the pick; when the pick leaves an existing file as it was, the file counts as there only when its blob is the original's, binary files included, or when `git merge-file` of the original's preimage, the line's file and the original's postimage merges cleanly back into the line's file. A deleted path counts as left without effect when its counterpart is absent before a pick that changes something, a deletion the line already made being no change of that pick, or still there after it, whatever the pick changed in it; when the original adds that path itself, as when the line made the same rename, it is judged as a modified file against what the original makes of that path. Picks that change nothing carry the original only when the line already has what it does to every file it modifies or deletes, so a change made where its branch merged `main`, which no pick brings, is still missing. What cannot be judged, a mode or type change, content `merge-file` refuses, or a rename git skipped looking for, is shown with the original and never counts against it. An original whose net merge onto the line, `git merge-tree --merge-base=M^1`, leaves something without effect is not tried, and one whose picks do is taken back off the branch: either is parked as partial, listed under "Parked" with those paths, and its release note stays out of the body. A conflict is never called partial. `backport/include` lifts no park.
|
||||
|
||||
`--push` pushes the branch, refusing anything but a fast-forward of what the remote has, then opens the draft pull request against the line with `gh pr create --draft`, or updates the open batch pull request with `gh pr edit`. When the branch it refuses to push over has no pull request open on it, as a run that stopped between its push and opening the pull request leaves it, the refusal names the `run --onto <its head> --push` that continues it. While a batch pull request is open on another branch it refuses, so a line never has two. It never pushes to or edits a batch pull request whose body has no `backport-batch` block either: someone wrote that body by hand, and the batch is theirs to merge or close. After `--defer` alone it replaces the branch, with `--force-with-lease=refs/heads/<branch>:<head>`, where head is what `git ls-remote` reads for the branch and has to be the head the rebuild started from: a commit pushed since is never dropped, by the tool's check or, if one lands between that check and the push, by the remote.
|
||||
Before it tries an original, `run` looks at what the original [builds on](#what-an-original-builds-on) that the branch lacks, in merge order, so what became of each prerequisite in this run is known. A prerequisite the line or the open batch carries, or that this run picked or found empty, counts as there; once earlier picks moved the branch, the original is judged at the branch's head, so a line another unit brought counts too. Of what is left, a direct push, an original rules 2 to 4, the line's start, `backport/skip` or a drop keep out, and one that is itself parked never come: the original is parked, not tried, and listed under "Parked" with what it builds on. In the scheduled mode an original that changes a workflow, whose missing dependencies that never come are only tests or docs and whose workflow lines build on nothing missing, waits for a maintainer instead, with a note saying so. Prerequisites still to come, a conflict, a deferral, a wait for a maintainer, one rule 6 holds, make the original wait: it is listed under "Waiting on another original", recorded with `needs`, the prerequisites of the kind that decides, in the order not on the line, waiting for a maintainer, deferred, rule 6, and tried again by a later run. A reason given with `--defer` comes before all of this, and a partial park before any of it.
|
||||
|
||||
`--defer N[,N] --reason TEXT` takes originals out of the open batch pull request, usually the ones a failing check was pinned on. It builds the batch branch again off `origin/<line>` without their units: while the batch still sits on the line's head, the units before the first one it drops stay as they are, and every later one, a pushed resolution included, is picked again in its own shape, a merge's picks one by one and then the merge with its message. When dropping one leaves a later commit that no longer applies, the run stops and names that commit's original, to defer as well. It adds no new original. It also takes out an original that got `backport/skip` after the batch picked it, which a run never removes on its own and the body lists as still on the branch. The body records each deferred original with the reason in the `backport-batch` block; a run that continues this batch keeps them out, and the next batch tries them again. A batch that carries a merge commit other than an original's, as GitHub's update-branch button makes, is refused, since picking such a merge again would lose what it resolved. When it takes out everything the batch carries, there is nothing left to push, and `--push` closes the batch pull request instead, as [the line's record](#the-lines-record-and-reports) describes.
|
||||
|
||||
`--drop N[,N] --reason TEXT` drops originals from the line: where `--defer` holds one out of this batch, a drop keeps it out of every later batch of the line too, until `--undrop N[,N]` withdraws it. A drop is recorded in the [line's record](#the-lines-record-and-reports), so both need an open batch pull request that carries one, and exit 2 without it; once a batch merges, its drops are carried into the next batch's record. A dropped original the open batch carries is taken off it as `--defer` would, and the rebuild is pushed the same way; any other drop or undrop changes only the record, so the batch stays as it is even when the line moved since. An undropped original is missing until the next run tries it. A drop names the original's merge commit on `main` as well as its number, and a record whose drop does not match what that merge commit merged stops every command with exit 2. An original the line already carries cannot be dropped, and neither can a number that merged into `main` before the line branched. The order is the rules', then the drop: what `backport/skip`, rules 2 to 4 or the line itself decide comes first, with the drop kept on record beside it, and `backport/include` does not lift a drop. The body lists dropped originals under their own heading among the skipped ones, `check` prints a note for each, and `fold` refuses one.
|
||||
|
||||
`--push` pushes the branch, refusing anything but a fast-forward of what the remote has, then opens the draft pull request against the line with `gh pr create --draft`, or updates the open batch pull request with `gh pr edit`, and prints its URL on stderr. On the open batch it first posts the run's report as a comment, so a body never names a report nobody can read; a new batch carries the report in the body it opens with, and the comment follows. Before every write to the pull request it reads the pull request again, and stops with exit 2 once it is merged or closed. When the branch it refuses to push over has no pull request open on it, as a run that stopped between its push and opening the pull request leaves it, the refusal names the `run --onto <its head> --push` that continues it. While a batch pull request is open on another branch it refuses, so a line never has two. It never pushes to or edits a batch pull request whose body has no `backport-batch` block either: someone wrote that body by hand, and the batch is theirs to merge or close. After `--defer` alone it replaces the branch, with `--force-with-lease=refs/heads/<branch>:<head>`, where head is what `git ls-remote` reads for the branch and has to be the head the rebuild started from: a commit pushed since is never dropped, by the tool's check or, if one lands between that check and the push, by the remote. A record that says the batch is being closed is acted on before anything else, and only by `run --push`.
|
||||
|
||||
### check
|
||||
|
||||
Exits 1 and prints the URL of every pull request the rules take that is neither on the line nor on the open batch pull request, 0 when there is none, and 2 when it cannot tell. A pull request that the open batch lists as deferred, a conflict or one taken out with `--defer`, prints as a warning and does not fail the check: deferring is a maintainer's call. So does one it lists as waiting for a maintainer because it changes workflows.
|
||||
Exits 1 and prints the URL of every pull request the rules take that is neither on the line nor on the open batch pull request, 0 when there is none, and 2 when it cannot tell. A pull request that the [line's record](#the-lines-record-and-reports) lists as deferred, a conflict or one taken out with `--defer`, prints as a warning and does not fail the check: deferring is a maintainer's call. That holds once the batch that recorded it merged or closed too. So does one the open batch lists as waiting for a maintainer because it changes workflows; once that batch is gone, nothing lists it any more, and it is missing. One a maintainer dropped from the line prints as a note, `#N is dropped from <line> on #M (<reason>)`.
|
||||
|
||||
`--cut` makes it the gate before a patch release or an rc is cut from a line. A cut tags the line, so a pull request that is only on the open batch pull request fails it too, with one line each: `#N is only on open batch PR #M, merge it before the cut`. One that waits there for a maintainer fails it as well, since nobody decided to leave it out: bring it over, or take it out with `run --defer` and a reason. Everything else is as without it. The scheduled run checks without `--cut`, since its batch is open by design.
|
||||
`--cut` makes it the gate before a patch release or an rc is cut from a line. A cut tags the line, so a pull request that is only on the open batch pull request fails it too, with one line each: `#N is only on open batch PR #M, merge it before the cut`. One that waits there for a maintainer fails it as well, since nobody decided to leave it out, also when it is all the batch has left: bring it over, or take it out with `run --defer` and a reason. Everything else is as without it, and a cut that passes says `no change the policy takes is missing before the cut`. The scheduled run checks without `--cut`, since its batch is open by design.
|
||||
|
||||
An original with `backport/skip` that the open batch picked before the label came prints a warning in either mode, naming the batch and `run --defer`, which takes it out; it fails neither.
|
||||
|
||||
Every other original the policy takes that neither the line nor the open batch carries is decided in merge order, as [`run`](#run) decides it, with the open batch's found picks counting as there and the mode the open record saved, the scheduled run's when no batch is open, whose workflow waits on a closed record wait on nothing any more, so the original is judged as the scheduled run judges it: deferred for a reason, a warning; parked, a note naming what it builds on; in the scheduled mode a workflow original whose tests alone build on what never comes, waiting as the open batch lists it, or missing with none; and one that waits on other originals by the prerequisite that decides it: missing, which fails both modes, waiting for a maintainer, which warns and fails `--cut`, deferred, which warns, or held by rule 6, a note. A wait on one that waits itself inherits what decides that one.
|
||||
|
||||
A unit on the open batch that leaves part of its original without effect, judged as [`run`](#run) judges a pick, at the unit's own first parent and whatever its original's rule, label or drop, prints a warning naming what it leaves out, and fails `--cut` ahead of any skip, drop or stale warning: take it out with `run --defer`. An original that is parked as partial prints as a note, `#N is parked: only part of it applies`, and fails neither. That includes one the open record parks as partial that the net merge at the line's head finds whole, since `run`'s picker found it after the picks before it: `check` and the operations that only change the record keep it parked while its net merge onto what the batch carries now still leaves something without effect, and call it missing once that went, as when the pick that made it partial was taken off. A park only the commit-by-commit replay sees, which no net merge shows, reads as missing in `check` until the next run.
|
||||
|
||||
### fold
|
||||
|
||||
Checks a hand-made resolution of a deferred conflict before it is pushed onto the batch, in the shape the run gives an original. For a merged pull request `--commit` is a merge whose first parent is the head of the open batch pull request and whose message names the original in exactly one `Backported-from:` trailer; its second parent ends a straight line from that head of picks of the pull request's own commits, in their order, each ending in the `(cherry picked from commit …)` line of the commit it came from, none claiming another commit of the same original, a commit of another pull request never among them. For a squash-merged one it is a single commit on that head whose `(cherry picked from commit …)` line names the original's commit on `main`. Either has to change something, and only files the original changes. The [conflict task](../../docs/release/backport-tasks/resolve-conflict.md) gives the commands. fold prints `ok` and exits 0, or prints why not and exits 1. It never commits or pushes; push one checked resolution at a time, since the next one has to sit on the new head.
|
||||
Checks a hand-made resolution of a deferred conflict before it is pushed onto the batch, in the shape the run gives an original. For a merged pull request `--commit` is a merge whose first parent is the head of the open batch pull request and whose message names the original in exactly one `Backported-from:` trailer; its second parent ends a straight line from that head of picks of the pull request's own commits, in their order, each ending in the `(cherry picked from commit …)` line of the commit it came from, none claiming another commit of the same original, a commit of another pull request never among them. For a squash-merged one it is a single commit on that head whose `(cherry picked from commit …)` line names the original's commit on `main`. An original parked for what it builds on folds like any other when the resolution is complete. Either has to change something, and only files the original changes or the paths a rename on `main` or on the line gave them, and has to leave nothing the original modifies or deletes without effect, judged as [`run`](#run) judges a pick: a resolution that ports what the line has and leaves out what it lacks is refused, since such a port goes to the line as a pull request of its own. The [conflict task](../../docs/release/backport-tasks/resolve-conflict.md) gives the commands. fold prints `ok` and exits 0, or prints why not and exits 1. It never commits or pushes; push one checked resolution at a time, since the next one has to sit on the new head.
|
||||
|
||||
### verify
|
||||
|
||||
Holds every unit of a batch to the shape fold checks for one, the clean picks as well as resolutions: it walks the batch's first-parent line from `origin/<line>` to `--head`, or to the head of the open batch pull request, and requires each unit to be one original, merged into `main` after the line branched, in that shape, and no original twice. A commit that carries no original fails it, and so does a merge of the line into the batch. It prints one line per unit, and exits 0 when all pass, 1 when one does not, and 2 when it cannot tell. With `--head` it reads git alone, nothing from GitHub. fold runs only where someone resolved a conflict and chose to run it; [`pr-labeler.yaml`](../../.github/workflows/pr-labeler.yaml) runs verify on every push to a batch pull request, from a build of `main`, with the batch head fetched as data.
|
||||
Holds every unit of a batch to the shape fold checks for one, the clean picks as well as resolutions: it walks the batch's first-parent line from `origin/<line>` to `--head`, or to the head of the open batch pull request, and requires each unit to be one original, merged into `main` after the line branched, in that shape, and no original twice. A commit that carries no original fails it, and so does a merge of the line into the batch, and a unit that leaves part of its original without effect, judged as [`run`](#run) judges a pick. It prints one line per unit, and exits 0 when all pass, 1 when one does not, and 2 when it cannot tell. With `--head` it reads git alone, nothing from GitHub. fold runs only where someone resolved a conflict and chose to run it; [`pr-labeler.yaml`](../../.github/workflows/pr-labeler.yaml) runs verify on every push to a batch pull request, from a build of `main`, with the batch head fetched as data.
|
||||
|
||||
### notify
|
||||
|
||||
Reads the open batch pull request of the line, trusted as described below, and prints one line for each thing that waits on it: a batch open for three days or more, the shortest gap between two scheduled runs, so one the previous run already saw; the conflicts it deferred; and the originals waiting for a maintainer because they change workflows. Nothing open prints nothing.
|
||||
Reads the [line's record](#the-lines-record-and-reports) first, as the other commands do, and exits 2 when it cannot read it or when it says the open batch is being closed, with a batch open or not. Then it reads the open batch pull request of the line, trusted as described below, and prints one line for each thing that waits on it: a batch open for three days or more, the shortest gap between two scheduled runs, so one the previous run already saw; the conflicts it deferred; and the originals waiting for a maintainer because they change workflows. Nothing open prints nothing.
|
||||
|
||||
An original the record has wait on others is listed once, as `#M, after #F`, where what decides its wait is listed: after a deferred conflict with the conflicts, after a workflow wait with the waits; one waiting on what is missing or held by rule 6 is not listed. A unit on the batch that carries only part of its original is listed apart, to be taken out before the cut.
|
||||
|
||||
Each park the record of the open batch holds is named once. `run` marks a park `announced` when the line's record it found, open or closed, holds the same park announced: the same merge, kind, prerequisites, commits and files; a park that changed is news again. `notify` lists the parks not yet marked, and with `--push`, once the comment is written, marks them in the record with `gh pr edit --body-file`, only while the pull request is open and its body still carries the record `notify` read. A mark that fails after the comment exits 2, and the next `notify` names those parks once more. With no batch open nothing is named, and the next batch's first `notify` names what it parks.
|
||||
|
||||
With `--push` it writes the same into one comment on the batch pull request: the conflicts, each to be resolved as the [conflict task](../../docs/release/backport-tasks/resolve-conflict.md) describes, and the originals that wait because they change workflows.
|
||||
|
||||
The comment starts with `<!-- backport-batch:notify -->` and is one per pull request: a later run edits it in place rather than adding another, and once nothing waits it says so. Only a comment whose author the batch trusts counts as it, so one someone else wrote with the same first line is neither edited nor believed. It mentions `--mention`, an `org/team` or a login, with or without `@`, only while something waits. A failed batch CI is not among what it reports: the run has no trigger on the batch's CI finishing.
|
||||
|
||||
### report
|
||||
|
||||
Prints a report a batch pull request keeps: the one its body carries, or the one `--id` names. It reads the report comments the batch trusts and falls back to the body, recomputes the report's ID from what it says, and exits 2 when a trusted comment does not match its ID, when a report says anything a run does not write or is for another line than the pull request's, or when the pull request keeps no such report. A report comment counts only when its author is one the batch trusts with a record, so anyone else's comment, whatever ID it carries, is not read. It prints what the classification was made of, whether the pull request's head or body shows the report was published, which it calls unconfirmed when neither does, and one line per original with its category and what the report recorded about it; `--json` prints the report as stored. A report whose comment the run never got to post is printed from the body, with a note that the next `run --push` posts it, or, on a merged or closed batch, that it is kept in the body only. It writes nothing. It reads GitHub, and for a report that keeps drops also the clone's history, without fetching: each drop is bound to `main` as the record's drops are, over the heads of `main` and the line the report was made from, so a drop of an original the report classified has to name that original's merge, and any other a merge of its number on `main`'s first-parent line. A clone without those heads exits 2, asking for a fetch.
|
||||
|
||||
### lines
|
||||
|
||||
Prints the release lines the batch runs for, newest first: of the `release-X.Y` branches on `origin`, the newest that have a stable `vX.Y.Z` tag there, as many as `released-lines` in the policy block says, two when it says nothing, and every branch newer than the newest of them. The tags are read with `git ls-remote`; a tag with a pre-release suffix does not count. `run`, `check` and `fold` refuse any other line, and rule 6 holds each line to the next newer one among them.
|
||||
@@ -94,10 +117,33 @@ Only the line's own commits count, the ones after the point where it branched fr
|
||||
|
||||
Titles and bodies are read from the merge commits on `main`, which hold them as a maintainer merged them; the live pull request stays editable by its author.
|
||||
|
||||
## What an original builds on
|
||||
|
||||
An original the policy takes can build on code its line does not have: another pull request merged into `main` after the line branched that the line never got, or a commit pushed to `main` directly. For each original the policy takes that neither the line nor the open batch carries, `run` reads what it builds on from git alone, in two ways:
|
||||
|
||||
- A file it modifies or deletes whose counterpart, as [`run`](#run) follows renames, the line does not have is named by the first-parent commit on `main` that added it since the line branched: `git --literal-pathspecs log --first-parent --diff-merges=first-parent --no-renames --diff-filter=A -1 <fork point>..M^1 -- <path>`. A file nothing added since the fork point is shown with the original, since no other pull request brought it.
|
||||
- A line it removes or changes in a file the line has is given by `git blame --porcelain -w`, at `M^1` named by its full commit, to a commit, which counts through the first-parent commit on `main` that brought it: each commit of `main`'s first-parent line since the fork point brings itself and every commit of the range reachable from its other parents that no earlier one brought. A commit from before the fork point, which the line has, and the original's own count for nothing. The commit counts only while one of its lines, with its edges trimmed and nothing else, is absent from the line's version of the file, so a hand backport under another commit clears it. A file the line already has as the original makes it, the same blob or a clean `git merge-file` back into the line's file, builds on nothing.
|
||||
|
||||
Lines a tool wrote are not blamed: a generated file whole, `zz_generated*`, one with a `Code generated … DO NOT EDIT` marker in its first 100 lines, `go.sum` and the package-manager lock files, and in an ApplicationDefinition under `packages/system/*-rd/cozyrds/` the keys `hack/update-crd.sh` writes, found by their indentation. Controller-gen CRDs and `values.schema.json` are blamed like any other file. Each `git log`, `git diff` and `git blame` the detector and the rename detection run has two minutes, and rename detection that runs out of time counts as skipped, and an original has at most 256 files, missing or blamed, 20 000 blamed lines and 8 MiB per file read for it. Evidence it cannot read, past one of those bounds, a binary file, a symlink, a submodule, a commit blame names that did not come through `main`, a path that is not UTF-8, or a rename git skipped looking for, is shown with the original, whatever becomes of it, under its line in the body and in the report's `diag`. Output of git the tool cannot read whole stops it with exit 2, and is never taken for an absent dependency. A dependency carried only by lines an original adds is not seen. `run` prints how long reading the line took on stderr. What follows from a dependency, a park or a wait, is in [`run`](#run) and [`check`](#check).
|
||||
|
||||
## The line's record and reports
|
||||
|
||||
The line's record is the `backport-batch` block of its newest batch pull request: the newest pull request against the line from a `backport-batch/<line>-<yyyymmdd>` branch of this repository, opened by an author the batch trusts as above, whether it is open, merged or closed. `run`, `check`, `fold` and `notify` find it in GitHub's list of the line's pull requests, newest first, reading at most ten pages of 100. A batch pull request a person opened without the block is passed over. A block whose author the batch does not trust, a bot's batch without its block, a block that cannot be read whole, a closed record newer than the open batch, or ten pages with no record stop the command with exit 2, naming the pull request, rather than fall back to an older record.
|
||||
|
||||
The record is written only while its pull request is open: a merged or closed batch pull request is never edited or commented on again. What it recorded keeps counting, so a conflict or a deferral a merged batch recorded still prints as a warning. A workflow original it listed as waiting is missing, since no open batch lists it. A run that picks nothing while no batch is open has nowhere to write: it prints the body, says that its classification is not retained, and exits 0.
|
||||
|
||||
The record is only as trustworthy as the body it sits in. Anyone with write access can edit any body, the bot's included, and neither the bot's authorship nor anything in the block proves who edited it last. A hand edit that leaves a readable record is believed; one that breaks it stops every command with exit 2, naming the pull request. A reason or a file name in the record counts only in the form a run writes it, one line with no control, zero-width or bidi character, so text someone typed into the body never reaches a terminal, a body or a comment as they typed it. When the newest batch pull request is deleted and no later one exists, nothing shows it was there: the older record governs, and what was recorded since is lost.
|
||||
|
||||
The record holds only what later commands act on. Version 3, which this tool writes, adds what is parked and why, with the merge commit each park is bound to, the units on the batch that do only part of their original, the picks that differ from theirs, and what each wait on another original waits on; it reads versions 1 to 3, and a tool that reads only 1 and 2 refuses version 3 with exit 2. Every run that classifies the line also makes a report, one line of JSON in a `backport-batch-report` block: every original merged into `main` since the line branched in exactly one category, picked, missing, deferred with what it was deferred for, or skipped with the rule that skipped it, each drop the record keeps with the merge commit it is bound to, its reason and the batch pull request that recorded it, the commits on `main` that merged no pull request, the labels, and what the classification was made of: the heads of `main`, the line and the newer line, the policy, the batch head it describes, the tool's commit, the Actions run and the flags. Its ID is a hash of all that but the time and the run, so two runs that find the same make the same report, and it names no pull request, so a new batch's report is whole before GitHub numbers the pull request. The body carries the latest report beside the record, and a comment on the open batch pull request keeps each one: `<!-- backport-batch:report <id> -->` and the same block, folded away. A report already posted is not posted again, and the tool never edits or deletes such a comment, so a report the next run replaces in the body is still read back by `report`, also after the batch merged. A comment that looks like one but whose author the batch does not trust is not read. When a run stops after writing the body but before posting its comment, the next `run --push` on the open batch posts that report first, byte for byte; once the batch is closed nothing is written to it, and the report stays in its body. A run that picks nothing while no batch is open keeps no report.
|
||||
|
||||
A `--defer` that leaves the batch carrying nothing closes it, and writes everything while the pull request is still open: the report comment, then the body, whose record keeps the deferrals and says the batch is closing, with its number, branch and the head the rebuild started from. It then reads the pull request and the branch again, closes the pull request while both are at that head, and deletes the branch with `--force-with-lease` on it, printing `closed <url>`. The next batch tries what was deferred again. A close that stops part way is finished by the next `run --push`, before it does anything else: it closes and deletes when the pull request is open at the frozen head, deletes the branch when the pull request is closed and the branch still at that head, and goes on as usual once both are gone. A run that finishes a close stops there, with exit 0, or with exit 2 when it was asked for `--defer`, `--drop` or `--undrop`, which it does not apply. It never takes a head it did not freeze: with the branch moved, it stops with exit 2 and names both heads. `run` without `--push`, `check` and `fold` stop with exit 2 while the pull request is still open; once it is closed they go on, warning about a branch the close left, and `notify` says nothing. A closed pull request is never written to, so its record says it was closing for good, and a closed pull request whose branch is gone counts as closed.
|
||||
|
||||
One way for the branch to move is a new batch of the same day: it reuses the branch name, and if its push succeeds and opening its pull request fails, the closed batch is still the newest record while its branch now holds the new batch. The next run stops on it, naming the branch, and so does `--onto` with its head. Check what it carries before deleting it with `git push origin --delete backport-batch/<line>-<yyyymmdd>`: the next run picks again what the tool put there from the line, but not a commit someone pushed onto it, such as a resolved conflict. Separate writes to GitHub are not atomic: the re-reads and the leases refuse a race they see, but cannot prevent one.
|
||||
|
||||
## What CI verifies
|
||||
|
||||
The tool does not build or test anything. CI on the batch pull request runs the line's own build and tests against what was picked, and `verify` against its shape, and a maintainer reviews and merges it. A deferred conflict waits for the next batch unless someone resolves it, checks the resolution with `fold` and pushes it, and then CI runs again.
|
||||
|
||||
## Untrusted text
|
||||
|
||||
Titles, release notes and file names in the body come from whoever opened the originals. A title, a reason or a file name goes into a code span whose fence no backtick inside can close, and the release notes go into the `release-note` block with every run of three backticks or tildes defused, so GitHub acts on no mention, reference, link or HTML in them. Inside that block, in case a note is copied out of it, links lose any target outside this repository, and closing keywords, cross-repository references and mentions have their `@`, `#` and `://` swapped for fullwidth signs, which act on nothing however the backticks around them pair up. Zero-width, bidi and control characters are dropped first, and everything the tool prints passes the same filter, so nothing it relays can drive a terminal. Commit messages are read through `git cat-file --batch`, which gives each object's length, and end at their first NUL as `git log` shows them, so a message cannot pass for a second commit or hide a trailer from a reader of the log. Every value handed to git comes after `--end-of-options` or `--`, refs pass `git check-ref-format`, SHAs have to be 40 hex digits, and nothing runs through a shell.
|
||||
Titles, release notes and file names in the body come from whoever opened the originals, and a reason from whoever ran `--defer`. A title, a reason or a file name goes into a code span whose fence no backtick inside can close, and the release notes go into the `release-note` block with every run of three backticks or tildes defused, so GitHub acts on no mention, reference, link or HTML in them. Inside that block, in case a note is copied out of it, links lose any target outside this repository, and closing keywords, cross-repository references and mentions have their `@`, `#` and `://` swapped for fullwidth signs, which act on nothing however the backticks around them pair up. The record and the report are one line of JSON each, whose encoding leaves no newline, `<`, `>` or `&` in them, so nothing in a file name or a reason ends their block or opens HTML, and a report comment names no one: numbers are bare, and its only text outside the block is the line, the date and the report's ID. Zero-width, bidi and control characters are dropped first, and everything the tool prints passes the same filter, so nothing it relays can drive a terminal. Commit messages are read through `git cat-file --batch`, which gives each object's length, and end at their first NUL as `git log` shows them, so a message cannot pass for a second commit or hide a trailer from a reader of the log. Every value handed to git comes after `--end-of-options` or `--`, refs pass `git check-ref-format`, SHAs have to be 40 hex digits, and nothing runs through a shell.
|
||||
+475
-46
@@ -33,6 +33,8 @@ type pick struct {
|
||||
files []string
|
||||
// failed is the commit whose pick conflicted.
|
||||
failed string
|
||||
// needs are the originals still to come it waits on.
|
||||
needs []int
|
||||
// more counts the conflicting files a recorded conflict no longer names.
|
||||
more int
|
||||
reason string
|
||||
@@ -75,8 +77,10 @@ func (a *app) run(args []string) int {
|
||||
cont := fs.Bool("continue", false, "continue the open batch pull request, or start a batch when none is open")
|
||||
dateArg := fs.String("date", "", "batch date, YYYY-MM-DD (default: today, UTC)")
|
||||
deferArg := fs.String("defer", "", "originals to take out of the open batch, N[,N]; rebuilds it without them")
|
||||
dropArg := fs.String("drop", "", "originals to drop from the line, N[,N]; recorded on the open batch, and taken off it")
|
||||
undropArg := fs.String("undrop", "", "originals whose drop to withdraw, N[,N]")
|
||||
noWorkflows := fs.Bool("no-workflow-files", false, "leave an original that changes "+workflowsDir+" to a maintainer, for a token that cannot push one")
|
||||
reasonArg := fs.String("reason", "", "why --defer takes them out, recorded in the batch body")
|
||||
reasonArg := fs.String("reason", "", "why --defer takes them out or --drop drops them, recorded in the batch body")
|
||||
push := fs.Bool("push", false, "push the branch and open or update the draft batch PR")
|
||||
if err := parse(fs, args); err != nil {
|
||||
return 2
|
||||
@@ -96,9 +100,30 @@ func (a *app) run(args []string) int {
|
||||
return a.fail(fmt.Errorf("--onto: %w", err))
|
||||
}
|
||||
}
|
||||
var deferred []int
|
||||
reason := ""
|
||||
var deferred, drops []int
|
||||
reason, ops := "", 0
|
||||
for _, op := range []string{*deferArg, *dropArg, *undropArg} {
|
||||
if op != "" {
|
||||
ops++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case ops > 1:
|
||||
return a.fail(errors.New("--defer, --drop and --undrop each change the open batch pull request on their own; give one"))
|
||||
case *dropArg != "" || *undropArg != "":
|
||||
if *onto != "" || *cont || *dateArg != "" {
|
||||
return a.fail(errors.New("--drop and --undrop change the open batch pull request; each takes no --onto, --continue or --date"))
|
||||
}
|
||||
if *undropArg != "" && *reasonArg != "" {
|
||||
return a.fail(errors.New("--undrop takes no --reason"))
|
||||
}
|
||||
list := *dropArg + *undropArg
|
||||
if drops, err = parseNumbers(map[bool]string{true: "--drop", false: "--undrop"}[*dropArg != ""], list); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if reason = capped(oneLine(clean(*reasonArg, false)), titleLimit); *dropArg != "" && reason == "" {
|
||||
return a.fail(errors.New("--drop needs a --reason, which the line's record keeps"))
|
||||
}
|
||||
case *deferArg != "" || *reasonArg != "":
|
||||
if deferred, reason, err = parseDefer(*deferArg, *reasonArg); err != nil {
|
||||
return a.fail(err)
|
||||
@@ -115,10 +140,23 @@ func (a *app) run(args []string) int {
|
||||
if err := fetch(); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
started := time.Now()
|
||||
b, err := a.prepare(l)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if goOn, code := a.resumeClose(b, *push, deferred != nil || drops != nil); !goOn {
|
||||
return code
|
||||
}
|
||||
if err := b.analyze(); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
// The scheduled job has half an hour for every line; this says where it
|
||||
// goes.
|
||||
fmt.Fprintf(a.stderr, "prepared %s in %s, %s of it judging partial units and what originals build on\n", l.branch(), time.Since(started).Round(time.Millisecond), b.detecting.Round(time.Millisecond))
|
||||
if drops != nil {
|
||||
return a.redrop(b, drops, reason, *undropArg != "", *push)
|
||||
}
|
||||
if deferred != nil {
|
||||
return a.rebuild(b, deferred, reason, *push)
|
||||
}
|
||||
@@ -147,10 +185,8 @@ func (a *app) run(args []string) int {
|
||||
// Continuing the open batch keeps out what was deferred from it by hand;
|
||||
// a new batch tries those again.
|
||||
held := map[int]deferredEntry{}
|
||||
if carried != nil && b.pr != nil && b.pr.Head.Ref == branch {
|
||||
if held, err = parseDeferred(b.pr.Body, l); err != nil {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d: %w", b.pr.Number, err))
|
||||
}
|
||||
if carried != nil && b.src.open && b.pr.Head.Ref == branch {
|
||||
held = b.src.rec.deferred()
|
||||
}
|
||||
if err := a.warnReset(branch, start); err != nil {
|
||||
return a.fail(err)
|
||||
@@ -160,24 +196,72 @@ func (a *app) run(args []string) int {
|
||||
}
|
||||
|
||||
r := newReport(b)
|
||||
r.opts = runOptions{NoWorkflowFiles: *noWorkflows, Mode: modeNew}
|
||||
// A drop is a decision about the line, not about one batch: a new batch
|
||||
// keeps the ones the closed batch recorded.
|
||||
r.dropped = b.src.rec.dropped()
|
||||
if carried != nil {
|
||||
r.opts.Mode = modeContinue
|
||||
if r.stale, err = keptOut(b, carried); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
}
|
||||
// cls is what each original became in this run, to an original that
|
||||
// builds on it; the rules decide the rest.
|
||||
mode := analysisMode{noWorkflowFiles: *noWorkflows}
|
||||
cls := map[*verdict]edgeClass{}
|
||||
classOf := func(f *verdict) edgeClass {
|
||||
if c, ok := b.ruleClass(f); ok {
|
||||
return c
|
||||
}
|
||||
if c, ok := cls[f]; ok {
|
||||
return c
|
||||
}
|
||||
return edgeMissing
|
||||
}
|
||||
for _, v := range b.qualifying() {
|
||||
on := false
|
||||
if carried != nil {
|
||||
if on, err = b.onBranch(carried, v); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case carried != nil && found(carried, v):
|
||||
case on:
|
||||
r.onBranch = append(r.onBranch, v)
|
||||
cls[v] = edgeSatisfied
|
||||
continue
|
||||
case held[v.o.number].Reason != "":
|
||||
r.held = append(r.held, pick{v: v, status: "held", reason: held[v.o.number].Reason})
|
||||
cls[v] = edgeDeferred
|
||||
continue
|
||||
case v.onBatch != "":
|
||||
v.rule, v.reason = ruleOnLine, fmt.Sprintf("on the open batch pull request #%d", b.pr.Number)
|
||||
r.skipped[ruleOnLine] = append(r.skipped[ruleOnLine], v)
|
||||
continue
|
||||
}
|
||||
if v.partial != nil {
|
||||
// Judged at the line's head; what the batch picked since may
|
||||
// supply what it lacked there.
|
||||
if err := a.partialAtHead(b, v); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if v.partial != nil {
|
||||
r.parked = append(r.parked, v)
|
||||
cls[v] = edgeNever
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(v.deps) > 0 {
|
||||
kind, err := a.dependsAt(b, r, v, mode, classOf)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if kind != edgeSatisfied {
|
||||
cls[v] = kind
|
||||
continue
|
||||
}
|
||||
}
|
||||
if *noWorkflows {
|
||||
files, err := workflowFiles(v.commits)
|
||||
if err != nil {
|
||||
@@ -185,18 +269,30 @@ func (a *app) run(args []string) int {
|
||||
}
|
||||
if len(files) > 0 {
|
||||
r.waiting = append(r.waiting, pick{v: v, status: "waiting", files: files})
|
||||
cls[v] = edgeWorkflow
|
||||
continue
|
||||
}
|
||||
}
|
||||
p, err := pickOriginal(v)
|
||||
p, err := pickOriginal(v, func(base, head string) ([]string, error) {
|
||||
omitted, diag, err := b.omittedEffects(v, base, head)
|
||||
v.addDiag(diag...)
|
||||
return omitted, err
|
||||
})
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
switch p.status {
|
||||
case "partial":
|
||||
v.partial = p.files
|
||||
v.park = &parkedEntry{Original: v.o.number, Merge: v.o.merge, Kind: parkPartial, Files: sortedClean(p.files)}
|
||||
r.parked = append(r.parked, v)
|
||||
cls[v] = edgeNever
|
||||
case "picked":
|
||||
r.onBranch = append(r.onBranch, v)
|
||||
cls[v] = edgeSatisfied
|
||||
case "conflict":
|
||||
r.deferred = append(r.deferred, p)
|
||||
cls[v] = edgeDeferred
|
||||
case "empty":
|
||||
v.rule, v.reason = ruleOnLine, "the earlier picks already carry it"
|
||||
r.skipped[ruleOnLine] = append(r.skipped[ruleOnLine], v)
|
||||
@@ -214,22 +310,83 @@ func (a *app) run(args []string) int {
|
||||
if !descends {
|
||||
return a.fail(fmt.Errorf("%.12s does not descend from --onto %.12s", head, *onto))
|
||||
}
|
||||
if err := b.markPartial(r, carried.head); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
}
|
||||
return a.finish(b, r, branch, date, *push, false)
|
||||
}
|
||||
|
||||
// keptOut lists the originals with backport/skip that the batch picked before
|
||||
// the label came: a run never takes a commit off the batch, --defer does.
|
||||
// dependsAt decides, from what v builds on that the branch lacks, whether
|
||||
// the run leaves it out: waiting for a maintainer in the scheduled mode
|
||||
// when only tests or docs build on what never comes, parked when anything
|
||||
// else never comes, or waiting on prerequisites still to come. What is
|
||||
// there, the line's, the batch's, or what this run picked or found empty,
|
||||
// counts for nothing; once earlier picks moved the branch, v is judged at
|
||||
// its head. It returns what v became to an original that builds on it,
|
||||
// edgeSatisfied when the run goes on to pick it.
|
||||
func (a *app) dependsAt(b *batch, r *report, v *verdict, mode analysisMode, classOf func(*verdict) edgeClass) (edgeClass, error) {
|
||||
deps := v.deps
|
||||
head, err := resolve("HEAD")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if head != b.lineHead {
|
||||
if deps, err = b.depsAt(v, head); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
never, pending := edges(deps, classOf)
|
||||
primary, err := workflowPrimary(mode, v, never, pending)
|
||||
switch {
|
||||
case err != nil:
|
||||
return 0, err
|
||||
case primary:
|
||||
files, err := workflowFiles(v.commits)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
v.addDiag(testsOnly(v, never, b.line))
|
||||
r.waiting = append(r.waiting, pick{v: v, status: "waiting", files: files})
|
||||
return edgeWorkflow, nil
|
||||
case len(never) > 0:
|
||||
v.park = dependencyPark(v, never)
|
||||
r.parked = append(r.parked, v)
|
||||
return edgeNever, nil
|
||||
case len(pending) > 0:
|
||||
class, needs := strongest(pending)
|
||||
r.needs = append(r.needs, pick{v: v, status: "waiting", needs: numbers(needs)})
|
||||
return class, nil
|
||||
}
|
||||
return edgeSatisfied, nil
|
||||
}
|
||||
|
||||
// partialAtHead judges v again where the run has got to, when earlier picks
|
||||
// moved the branch past the line's head.
|
||||
func (a *app) partialAtHead(b *batch, v *verdict) error {
|
||||
head, err := resolve("HEAD")
|
||||
if err != nil || head == b.lineHead {
|
||||
return err
|
||||
}
|
||||
return b.partialAt(v, head)
|
||||
}
|
||||
|
||||
// keptOut lists the originals with backport/skip, or dropped, that the batch
|
||||
// still carries: a run never takes a commit off the batch, --defer does.
|
||||
func keptOut(b *batch, carried *history) ([]*verdict, error) {
|
||||
var out []*verdict
|
||||
for _, v := range b.verdicts {
|
||||
if v.label != labelSkip {
|
||||
if v.rule != ruleSkipLabel && v.rule != ruleDropped {
|
||||
continue
|
||||
}
|
||||
if err := b.load(v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if found(carried, v) {
|
||||
on, err := b.onBranch(carried, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if on {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
@@ -244,7 +401,7 @@ func found(h *history, v *verdict) bool {
|
||||
// newReport starts the report of a run with what the rules left out and what
|
||||
// the labels overrode.
|
||||
func newReport(b *batch) *report {
|
||||
r := &report{line: b.line, newer: b.newer, skipped: map[int][]*verdict{}, other: len(b.other), start: b.start}
|
||||
r := &report{line: b.line, newer: b.newer, skipped: map[int][]*verdict{}, other: len(b.other), start: b.start, carried: b.src.rec}
|
||||
for _, v := range b.verdicts {
|
||||
if v.rule != 0 {
|
||||
r.skipped[v.rule] = append(r.skipped[v.rule], v)
|
||||
@@ -266,12 +423,32 @@ func (a *app) finish(b *batch, r *report, branch string, date time.Time, push, r
|
||||
if r.shapes, err = summarize(b, head, r.onBranch); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
title := prTitle(b.line, date.Format(time.DateOnly))
|
||||
if rebuilt && head == b.lineHead && b.pr != nil {
|
||||
// Deferring everything the batch carries leaves nothing to push: the
|
||||
// batch is closed, and its record says so first, with the head the
|
||||
// close is leased on.
|
||||
r.closing = &closing{PR: b.pr.Number, Branch: branch, Head: b.prHead}
|
||||
r.opts.Mode = modeClose
|
||||
}
|
||||
r.built = builtFrom{Main: b.mainHead, Line: b.lineHead, Newer: b.newerHead, Policy: b.policyAt, Batch: head, Tool: a.tool,
|
||||
Run: runURL(os.LookupEnv), At: a.now().UTC().Format(time.RFC3339), Options: r.opts}
|
||||
doc, err := buildReport(b, r)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
p := publication{branch: branch, head: head, title: prTitle(b.line, date.Format(time.DateOnly)), report: storedReport{doc: doc, raw: reportJSON(doc)}}
|
||||
p.record = r.lineRecord(doc)
|
||||
// A record the next command would refuse is never written.
|
||||
if err := p.record.validate(b.line); err != nil {
|
||||
return a.fail(fmt.Errorf("the record this run made %w", err))
|
||||
}
|
||||
r.blocks = recordBlock(p.record) + "\n\n" + reportBlock(p.report.raw)
|
||||
template, err := lineTemplate(b.lineHead)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
body, left := r.body(template)
|
||||
p.body = body
|
||||
fmt.Fprint(a.stdout, body)
|
||||
skipped := 0
|
||||
for _, items := range r.skipped {
|
||||
@@ -279,29 +456,44 @@ func (a *app) finish(b *batch, r *report, branch string, date time.Time, push, r
|
||||
}
|
||||
for _, rule := range left {
|
||||
for _, v := range r.skipped[rule] {
|
||||
fmt.Fprintf(a.stderr, "skipped by rule %d: %s %s (%s)\n", rule, v.o.url(), terminalSafe(v.o.title), terminalSafe(v.reason))
|
||||
fmt.Fprintf(a.stderr, "skipped by %s: %s %s (%s)\n", ruleName(rule), v.o.url(), terminalSafe(v.o.title), terminalSafe(v.reason))
|
||||
}
|
||||
}
|
||||
for _, p := range r.waiting {
|
||||
fmt.Fprintf(a.stderr, "waiting for a maintainer: %s %s changes %s\n", p.v.o.url(), terminalSafe(p.v.o.title), terminalSafe(strings.Join(p.files, ", ")))
|
||||
}
|
||||
fmt.Fprintf(a.stderr, "%s at %.12s: %d on the branch, %d deferred, %d waiting for a maintainer, %d skipped\ntitle: %s\n",
|
||||
branch, head, len(r.onBranch), len(r.deferred)+len(r.held), len(r.waiting), skipped, title)
|
||||
fmt.Fprintf(a.stderr, "%s at %.12s: %d on the branch, %d deferred, %d waiting for a maintainer, %d skipped\ntitle: %s\nreport: %s\n",
|
||||
branch, head, len(r.onBranch), len(r.deferred)+len(r.held), len(r.waiting), skipped, p.title, doc.ID)
|
||||
if !push {
|
||||
return 0
|
||||
}
|
||||
if head == b.lineHead && b.pr == nil {
|
||||
// Picking nothing is not a failure of the run; check still reports
|
||||
// whatever the line lacks.
|
||||
// whatever the line lacks. Merged and closed batches are never
|
||||
// written, so there is nowhere to keep what the run found.
|
||||
fmt.Fprintf(a.stderr, "%s carries nothing beyond %s; nothing to push\n", branch, b.line.branch())
|
||||
fmt.Fprintf(a.stderr, "no batch pull request is open on %s; this run's classification is not retained\n", b.line.branch())
|
||||
return 0
|
||||
}
|
||||
if err := a.publish(b, branch, head, title, body, rebuilt); err != nil {
|
||||
if err := a.publish(b, p, rebuilt); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// lineRecord is the record a run leaves for the line: what later commands
|
||||
// act on, with the full classification left to the report it names.
|
||||
func (r *report) lineRecord(doc reportDoc) lineRecord {
|
||||
built := doc.Built
|
||||
dropped := slices.Clone(r.dropped)
|
||||
if dropped == nil {
|
||||
dropped = []droppedEntry{}
|
||||
}
|
||||
slices.SortFunc(dropped, func(a, b droppedEntry) int { return a.Original - b.Original })
|
||||
return lineRecord{Version: recordVersion, Line: doc.Line, Built: &built, Report: doc.ID, Closing: r.closing, Deferred: slices.Clone(doc.Primary.Deferred), Dropped: dropped, Stale: slices.Clone(doc.Overlays.Stale),
|
||||
Parked: carryAnnounced(doc.Primary.Parked, r.carried), Partial: slices.Clone(doc.Overlays.Partial), Changed: slices.Clone(doc.Overlays.Changed)}
|
||||
}
|
||||
|
||||
// branchDate is the date a batch branch was opened under.
|
||||
func branchDate(branch string) (time.Time, error) {
|
||||
m := batchBranchRE.FindStringSubmatch(branch)
|
||||
@@ -446,80 +638,312 @@ func lineTemplate(lineHead string) (string, error) {
|
||||
return git("show", "--end-of-options", lineHead+":"+template)
|
||||
}
|
||||
|
||||
// publication is what a run publishes: the branch at head, and the body that
|
||||
// carries the record and the report.
|
||||
type publication struct {
|
||||
branch, head, title, body string
|
||||
report storedReport
|
||||
record lineRecord
|
||||
}
|
||||
|
||||
// publish pushes the batch branch, then opens the draft batch pull request or
|
||||
// updates the open one. A run pushes only a fast-forward of what the remote
|
||||
// has. A rebuild replaces the branch, and only the head it was rebuilt from:
|
||||
// the lease is that head, as ls-remote reads it now, so a commit pushed since
|
||||
// is never dropped.
|
||||
func (a *app) publish(b *batch, branch, head, title, body string, rebuilt bool) error {
|
||||
if b.pr != nil && b.pr.Head.Ref != branch {
|
||||
//
|
||||
// The report goes up as a comment before the push and the body that names
|
||||
// it, so no write leaves a body naming a report nobody can read; a new batch
|
||||
// carries the report in the body it is opened with, and the comment follows.
|
||||
// Everything is rendered and measured before the first write.
|
||||
func (a *app) publish(b *batch, p publication, rebuilt bool) error {
|
||||
if b.pr != nil && b.pr.Head.Ref != p.branch {
|
||||
return fmt.Errorf("the open batch pull request #%d is on %s; continue it with --onto %s", b.pr.Number, b.pr.Head.Ref, b.prHead)
|
||||
}
|
||||
// A body without the block was written by hand, and the tool's would
|
||||
// replace it whole, title included; such a batch is the maintainer's.
|
||||
if b.pr != nil && !strings.Contains("\n"+strings.ReplaceAll(b.pr.Body, "\r\n", "\n")+"\n", "\n"+deferredFence+"\n") {
|
||||
if b.pr != nil && !b.src.open {
|
||||
return fmt.Errorf("batch pull request #%d has no %s block, so backport-batch did not write it; merge or close it, and the next run opens a batch of its own", b.pr.Number, deferredFence)
|
||||
}
|
||||
if head == b.lineHead {
|
||||
if rebuilt {
|
||||
return fmt.Errorf("without what is deferred, %s carries nothing beyond %s; close batch pull request #%d instead", branch, b.line.branch(), b.pr.Number)
|
||||
if p.head == b.lineHead {
|
||||
if rebuilt && p.record.Closing != nil {
|
||||
return a.closeBatch(b, p)
|
||||
}
|
||||
return fmt.Errorf("%s carries nothing beyond %s; nothing to push", branch, b.line.branch())
|
||||
return fmt.Errorf("%s carries nothing beyond %s; nothing to push", p.branch, b.line.branch())
|
||||
}
|
||||
heads, err := remoteBatchHeads(b.line)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pushed, onRemote := heads[branch]
|
||||
pushed, onRemote := heads[p.branch]
|
||||
lease := ""
|
||||
switch {
|
||||
case rebuilt:
|
||||
if !onRemote || pushed != b.prHead {
|
||||
return fmt.Errorf("%s on %s is at %.12s, not at %.12s, which the rebuild started from; run again", branch, remote, pushed, b.prHead)
|
||||
return fmt.Errorf("%s on %s is at %.12s, not at %.12s, which the rebuild started from; run again", p.branch, remote, pushed, b.prHead)
|
||||
}
|
||||
lease = pushed
|
||||
case onRemote && pushed != head:
|
||||
case onRemote && pushed != p.head:
|
||||
have, err := lookup(pushed)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
descends := false
|
||||
if have != "" {
|
||||
if descends, err = isAncestor(pushed, head); err != nil {
|
||||
if descends, err = isAncestor(pushed, p.head); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !descends {
|
||||
refusal := fmt.Sprintf("%s on %s is at %.12s, which %.12s does not descend from; refusing a non-fast-forward push", branch, remote, pushed, head)
|
||||
refusal := fmt.Sprintf("%s on %s is at %.12s, which %.12s does not descend from; refusing a non-fast-forward push", p.branch, remote, pushed, p.head)
|
||||
// A run that stopped between its push and opening the pull request
|
||||
// leaves the branch, and the next run that day builds it anew.
|
||||
if b.pr == nil {
|
||||
switch c := b.src.carrier; {
|
||||
case b.pr != nil:
|
||||
case c != nil && !b.src.open && c.Head.Ref == p.branch:
|
||||
// Continuing a batch that merged or closed would publish
|
||||
// what nobody can merge any more.
|
||||
refusal += fmt.Sprintf("; it is the branch of batch pull request #%d, which is %s; the next run picks again what the tool put on it, but not a commit someone pushed there, such as a resolved conflict: check what %.12s carries, then delete it with git push origin --delete %s and run again", c.Number, prState(c), pushed, p.branch)
|
||||
default:
|
||||
refusal += fmt.Sprintf("; no batch pull request is open on it, and backport-batch run --line %s --onto %s --push continues it and opens one", b.line.branch(), pushed)
|
||||
}
|
||||
return errors.New(refusal)
|
||||
}
|
||||
}
|
||||
if pushed != head {
|
||||
if _, err := git(pushArgs(branch, head, lease)...); err != nil {
|
||||
if err := p.fits(); err != nil {
|
||||
return err
|
||||
}
|
||||
if b.pr != nil {
|
||||
if err := a.keepReports(b, &p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
f, err := os.CreateTemp("", "backport-batch-body-*.md")
|
||||
if pushed != p.head {
|
||||
if _, err := git(pushArgs(p.branch, p.head, lease)...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
name, err := writeTemp("backport-batch-body-*.md", p.body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
if _, err := f.WriteString(body); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(name)
|
||||
if b.pr == nil {
|
||||
return a.gh.createPull(b.line.branch(), branch, title, f.Name())
|
||||
n, url, err := a.gh.createPull(b.line.branch(), p.branch, p.title, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(a.stderr, "opened draft %s\n", url)
|
||||
if err := a.postReport(n, p.report); err != nil {
|
||||
return fmt.Errorf("posting report %.12s on #%d: %w; the body keeps it, and the next run --push posts it", p.report.doc.ID, n, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return a.gh.editPull(b.pr.Number, title, f.Name())
|
||||
if err := a.stillOpen(b.pr.Number); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.gh.editPull(b.pr.Number, p.title, name); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(a.stderr, "updated %s\n", pullURL(b.pr))
|
||||
return nil
|
||||
}
|
||||
|
||||
// fits says why GitHub would not take the comment or the body.
|
||||
func (p *publication) fits() error {
|
||||
if _, err := reportComment(p.report); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(p.body) > bodyLimit {
|
||||
return fmt.Errorf("the body is %d bytes with only what it cannot leave out, over GitHub's %d; nothing is published", len(p.body), bodyLimit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// keepReports makes sure the open batch's comments keep both the report its
|
||||
// body carries now and the one this run made, in that order, each once.
|
||||
// When this run's report is one already kept, the body carries the kept
|
||||
// bytes, which differ only in when and in which job it was made.
|
||||
func (a *app) keepReports(b *batch, p *publication) error {
|
||||
pr := b.pr
|
||||
posted, bad, err := findReports(a.gh, pr.Number, b.line)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, why := range bad {
|
||||
a.warn("batch pull request #%d: %s; it does not count as a report", pr.Number, why)
|
||||
}
|
||||
earlier, err := bodyReport(pr.Body, b.line)
|
||||
if err != nil {
|
||||
return fmt.Errorf("batch pull request #%d: %w", pr.Number, err)
|
||||
}
|
||||
kept, ok := posted[p.report.doc.ID]
|
||||
if !ok && earlier != nil && earlier.doc.ID == p.report.doc.ID {
|
||||
kept, ok = *earlier, true
|
||||
}
|
||||
if ok {
|
||||
p.body = strings.Replace(p.body, reportBlock(p.report.raw), reportBlock(kept.raw), 1)
|
||||
p.report = kept
|
||||
if err := p.fits(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if earlier != nil {
|
||||
if _, ok := posted[earlier.doc.ID]; !ok {
|
||||
if err := a.postReport(pr.Number, *earlier); err != nil {
|
||||
return fmt.Errorf("posting the earlier report %.12s on #%d: %w", earlier.doc.ID, pr.Number, err)
|
||||
}
|
||||
posted[earlier.doc.ID] = *earlier
|
||||
}
|
||||
}
|
||||
if _, ok := posted[p.report.doc.ID]; !ok {
|
||||
if err := a.postReport(pr.Number, p.report); err != nil {
|
||||
return fmt.Errorf("posting report %.12s on #%d: %w", p.report.doc.ID, pr.Number, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pullURL is where a pull request is on GitHub.
|
||||
func pullURL(pr *pullRequest) string {
|
||||
if pullURLRE.MatchString(pr.HTMLURL) {
|
||||
return pr.HTMLURL
|
||||
}
|
||||
return fmt.Sprintf("%spull/%d", ourRepoURL, pr.Number)
|
||||
}
|
||||
|
||||
// closeBatch closes the open batch that --defer left carrying nothing. Every
|
||||
// write happens while it is open: the report, then the body whose record
|
||||
// says it is closing and at which head. The close and the deletion of its
|
||||
// branch then go only while both are still at that head.
|
||||
func (a *app) closeBatch(b *batch, p publication) error {
|
||||
c := *p.record.Closing
|
||||
if err := p.fits(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.keepReports(b, &p); err != nil {
|
||||
return err
|
||||
}
|
||||
name, err := writeTemp("backport-batch-body-*.md", p.body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(name)
|
||||
if err := a.stillOpen(c.PR); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.gh.editPull(c.PR, p.title, name); err != nil {
|
||||
return fmt.Errorf("recording the close of #%d: %w", c.PR, err)
|
||||
}
|
||||
return a.finishClose(b.line, pullURL(b.pr), c)
|
||||
}
|
||||
|
||||
// finishClose closes the batch pull request a record says is closing, and
|
||||
// deletes its branch, each only while it is at the head the record froze.
|
||||
func (a *app) finishClose(l line, url string, c closing) error {
|
||||
pr, err := a.gh.pull(c.PR)
|
||||
if err != nil {
|
||||
return fmt.Errorf("closing #%d, reading it again: %w", c.PR, err)
|
||||
}
|
||||
if st := prState(&pr); st != "open" || pr.Head.SHA != c.Head {
|
||||
return fmt.Errorf("closing #%d: it is %s at %.12s, not open at %.12s, which its record froze", c.PR, st, terminalSafe(pr.Head.SHA), c.Head)
|
||||
}
|
||||
heads, err := remoteBatchHeads(l)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h := heads[c.Branch]; h != c.Head {
|
||||
return fmt.Errorf("closing #%d: %s on %s is at %.12s, not at %.12s, which its record froze", c.PR, c.Branch, remote, h, c.Head)
|
||||
}
|
||||
if err := a.gh.closePull(c.PR); err != nil {
|
||||
return fmt.Errorf("closing #%d: %w; backport-batch run --line %s --push finishes it", c.PR, err, l.branch())
|
||||
}
|
||||
if err := a.deleteBranch(l, c); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(a.stderr, "closed %s: without what is deferred it carries nothing beyond %s; the next batch tries them again\n", url, l.branch())
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteBranch deletes the branch of a closed batch, leased on the head it
|
||||
// was closed at: one someone pushed since is a person's to delete or keep.
|
||||
func (a *app) deleteBranch(l line, c closing) error {
|
||||
heads, err := remoteBatchHeads(l)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch h, ok := heads[c.Branch]; {
|
||||
case !ok:
|
||||
return nil
|
||||
case h != c.Head:
|
||||
return movedBranch(c, h)
|
||||
}
|
||||
if _, err := git(deleteArgs(c.Branch, c.Head)...); err != nil {
|
||||
return fmt.Errorf("deleting %s, left by the close of #%d: %w; backport-batch run --line %s --push deletes it", c.Branch, c.PR, err, l.branch())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// takenBranch is the refusal for a branch a close left that an open batch
|
||||
// pull request now uses, whatever it holds, or nil.
|
||||
func takenBranch(b *batch, c closing) error {
|
||||
if b.pr == nil || b.pr.Head.Ref != c.Branch {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("batch pull request #%d is open on %s, which the close of #%d left; the branch is that pull request's now, and the close leaves it alone", b.pr.Number, c.Branch, c.PR)
|
||||
}
|
||||
|
||||
func movedBranch(c closing, h string) error {
|
||||
return fmt.Errorf("batch pull request #%d was closed at %.12s, but %s is at %.12s now; the next run picks again what the tool put on it, but not a commit someone pushed there, such as a resolved conflict: check what %.12s carries, then delete it with git push origin --delete %s, and run again", c.PR, c.Head, c.Branch, h, h, c.Branch)
|
||||
}
|
||||
|
||||
// resumeClose finishes a close the record says is under way, before a run
|
||||
// does anything else, and only under --push. It says whether the run may go
|
||||
// on: only once the batch is closed and its branch gone. A run that finishes
|
||||
// one stops there, and fails when it was asked to change the batch.
|
||||
func (a *app) resumeClose(b *batch, push, changing bool) (bool, int) {
|
||||
if b.src.rec == nil || b.src.rec.Closing == nil {
|
||||
return true, 0
|
||||
}
|
||||
c := *b.src.rec.Closing
|
||||
heads, err := remoteBatchHeads(b.line)
|
||||
if err != nil {
|
||||
return false, a.fail(err)
|
||||
}
|
||||
h, onRemote := heads[c.Branch]
|
||||
switch {
|
||||
case b.src.open && h != c.Head:
|
||||
return false, a.fail(fmt.Errorf("batch pull request #%d is being closed, but %s is at %.12s, not at %.12s, which its record froze; a person closes it, or pushes the branch back, by hand", c.PR, c.Branch, h, c.Head))
|
||||
case b.src.open && !push:
|
||||
return false, a.fail(fmt.Errorf("batch pull request #%d is being closed: closing it and deleting %s are left; backport-batch run --line %s --push finishes it", c.PR, c.Branch, b.line.branch()))
|
||||
case b.src.open:
|
||||
if err := a.finishClose(b.line, pullURL(b.src.carrier), c); err != nil {
|
||||
return false, a.fail(err)
|
||||
}
|
||||
return false, a.finished(c, changing)
|
||||
case !onRemote:
|
||||
return true, 0
|
||||
case takenBranch(b, c) != nil:
|
||||
return false, a.fail(takenBranch(b, c))
|
||||
case h != c.Head:
|
||||
return false, a.fail(movedBranch(c, h))
|
||||
case !push:
|
||||
return false, a.fail(fmt.Errorf("batch pull request #%d was closed, but %s is still at %.12s; backport-batch run --line %s --push deletes it", c.PR, c.Branch, h, b.line.branch()))
|
||||
}
|
||||
if err := a.deleteBranch(b.line, c); err != nil {
|
||||
return false, a.fail(err)
|
||||
}
|
||||
fmt.Fprintf(a.stderr, "deleted %s, which the close of #%d left\n", c.Branch, c.PR)
|
||||
return false, a.finished(c, changing)
|
||||
}
|
||||
|
||||
// finished is the exit of a run that finished a close: a change it was asked
|
||||
// for needs an open batch pull request, and none is left to make it on.
|
||||
func (a *app) finished(c closing, changing bool) int {
|
||||
if !changing {
|
||||
return 0
|
||||
}
|
||||
return a.fail(fmt.Errorf("finished the close of #%d and made no other change: what this run was asked to change needs an open batch pull request, which the next run opens", c.PR))
|
||||
}
|
||||
|
||||
// pushArgs pushes head to branch: as a fast-forward, which the remote checks,
|
||||
@@ -531,3 +955,8 @@ func pushArgs(branch, head, lease string) []string {
|
||||
}
|
||||
return append(args, "--end-of-options", remote, head+":refs/heads/"+branch)
|
||||
}
|
||||
|
||||
// deleteArgs deletes branch, only while the remote has it at lease.
|
||||
func deleteArgs(branch, lease string) []string {
|
||||
return []string{"push", "--quiet", "--force-with-lease=refs/heads/" + branch + ":" + lease, "--end-of-options", remote, ":refs/heads/" + branch}
|
||||
}
|
||||
@@ -258,9 +258,17 @@ func TestRunPush(t *testing.T) {
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
gh := &fakeGH{}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 0 {
|
||||
code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push")
|
||||
if code != 0 {
|
||||
t.Fatalf("run --push = %d\n%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, "opened draft https://github.com/cozystack/cozystack/pull/90\n") {
|
||||
t.Errorf("the run does not print the pull request it opened:\n%s", stderr)
|
||||
}
|
||||
l, _ := parseLine("release-1.1")
|
||||
if _, err := parseDeferred(stdout, l); err != nil || !strings.HasPrefix(stdout, "## What this PR does") || strings.Contains(stdout, "https://github.com/cozystack/cozystack/pull/90") {
|
||||
t.Errorf("stdout is no longer the body alone (%v):\n%s", err, stdout)
|
||||
}
|
||||
head := f.git("rev-parse", "HEAD")
|
||||
if got := f.remoteHead(batchBranch1); got != head {
|
||||
t.Errorf("remote %s = %q, want %s", batchBranch1, got, head)
|
||||
@@ -272,9 +280,13 @@ func TestRunPush(t *testing.T) {
|
||||
f.git("switch", "-q", "main")
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, gh.bodies[0])}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--onto", head, "--push"); code != 0 {
|
||||
code, _, stderr = f.exec(gh, "run", "--line", "release-1.1", "--onto", head, "--push")
|
||||
if code != 0 {
|
||||
t.Fatalf("run --onto --push = %d\n%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, "updated https://github.com/cozystack/cozystack/pull/90\n") {
|
||||
t.Errorf("the run does not print the pull request it updated:\n%s", stderr)
|
||||
}
|
||||
if got := f.subjects("origin/release-1.1", f.remoteHead(batchBranch1)); !slices.Equal(got, []string{"fix(app): five (#5)", "fix(app): six (#6)"}) {
|
||||
t.Errorf("the pushed batch carries %q, want #5 then #6", got)
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ import (
|
||||
|
||||
// A maintainer's run by hand continues the batch pull request the scheduled
|
||||
// run opened as its bot, with nothing set: it edits that pull request rather
|
||||
// than opening a second one for the line.
|
||||
// than opening a second one for the line. A record another bot wrote is no
|
||||
// record the batch trusts, and the run stops rather than reach past it.
|
||||
func TestHandRunContinuesTheBotsBatch(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, author string
|
||||
@@ -44,12 +45,12 @@ func TestHandRunContinuesTheBotsBatch(t *testing.T) {
|
||||
f.now = f.now.AddDate(0, 0, 3)
|
||||
|
||||
code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if code != 0 {
|
||||
if tc.continued && code != 0 || !tc.continued && (code != 2 || !strings.Contains(stderr, "batch pull request #90 (open) carries a ```backport-batch block but was opened by \"renovate[bot]\"")) {
|
||||
t.Fatalf("run --continue = %d\n%s", code, stderr)
|
||||
}
|
||||
continued := slices.Equal(gh.edited, []string{"#90 fix(backport): batch for release-1.1, 2026-10-26"}) && len(gh.created) == 1
|
||||
if continued != tc.continued {
|
||||
t.Errorf("edited %q, created %q; want the batch of %s continued=%v\n%s", gh.edited, gh.created, tc.author, tc.continued, stderr)
|
||||
if continued != tc.continued || len(gh.created) != 1 {
|
||||
t.Errorf("edited %q, created %q; want the batch of %s continued=%v and no second one\n%s", gh.edited, gh.created, tc.author, tc.continued, stderr)
|
||||
}
|
||||
if !tc.continued && !strings.Contains(stderr, "ignoring #90") {
|
||||
t.Errorf("the run does not say it ignores #90:\n%s", stderr)
|
||||
|
||||
+178
-78
@@ -176,6 +176,9 @@ type deferredEntry struct {
|
||||
More int `json:"more,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Workflows bool `json:"workflows,omitempty"`
|
||||
// Needs, from version 3, are the originals still to come that it waits
|
||||
// on, those of the kind that decides the wait.
|
||||
Needs []int `json:"needs,omitempty"`
|
||||
}
|
||||
|
||||
// How many conflicting files of one original the body names, in the list and
|
||||
@@ -190,25 +193,11 @@ type deferredRecord struct {
|
||||
Deferred []deferredEntry `json:"deferred"`
|
||||
}
|
||||
|
||||
// deferredBlock is the machine-readable list of what the batch defers. One
|
||||
// line of JSON: encoding/json escapes newlines and <, > and &, so nothing in a
|
||||
// file name or a reason can end the fence or open HTML. It leaves bidi and
|
||||
// zero-width characters as they are, so file names go through clean first,
|
||||
// as the reason does.
|
||||
// deferredBlock is a version 1 record, which batches carried before records
|
||||
// had a version. encoding/json leaves bidi and zero-width characters as they
|
||||
// are, so file names go through clean first, as the reason does.
|
||||
func deferredBlock(l line, conflicts, held, waiting []pick) string {
|
||||
rec := deferredRecord{Line: l.branch(), Deferred: []deferredEntry{}}
|
||||
for _, p := range conflicts {
|
||||
files := cleanFiles(p.files[:min(len(p.files), filesKept)])
|
||||
rec.Deferred = append(rec.Deferred, deferredEntry{Original: p.v.o.number, Commit: p.failed, Files: files, More: len(p.files) - len(files) + p.more})
|
||||
}
|
||||
for _, p := range held {
|
||||
rec.Deferred = append(rec.Deferred, deferredEntry{Original: p.v.o.number, Files: []string{}, Reason: capped(oneLine(clean(p.reason, false)), titleLimit)})
|
||||
}
|
||||
for _, p := range waiting {
|
||||
files := cleanFiles(p.files[:min(len(p.files), filesKept)])
|
||||
rec.Deferred = append(rec.Deferred, deferredEntry{Original: p.v.o.number, Files: files, More: len(p.files) - len(files) + p.more, Workflows: true})
|
||||
}
|
||||
data, _ := json.Marshal(rec)
|
||||
data, _ := json.Marshal(deferredRecord{Line: l.branch(), Deferred: deferredEntries(conflicts, held, waiting, nil)})
|
||||
return deferredFence + "\n" + string(data) + "\n```"
|
||||
}
|
||||
|
||||
@@ -220,54 +209,13 @@ func cleanFiles(files []string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// parseDeferred reads what a batch body defers: exactly one block, for this
|
||||
// line, naming each original once.
|
||||
// parseDeferred reads what a batch body's record defers.
|
||||
func parseDeferred(body string, l line) (map[int]deferredEntry, error) {
|
||||
var blocks []string
|
||||
lines := strings.Split(strings.ReplaceAll(body, "\r\n", "\n"), "\n")
|
||||
for i := 0; i < len(lines); i++ {
|
||||
if strings.TrimSpace(lines[i]) != deferredFence {
|
||||
continue
|
||||
}
|
||||
if i+2 >= len(lines) || strings.TrimSpace(lines[i+2]) != "```" {
|
||||
return nil, fmt.Errorf("the %s block is not one line of JSON", deferredFence)
|
||||
}
|
||||
blocks = append(blocks, lines[i+1])
|
||||
i += 2
|
||||
rec, err := parseRecord(body, l)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(blocks) {
|
||||
case 0:
|
||||
return map[int]deferredEntry{}, nil
|
||||
case 1:
|
||||
default:
|
||||
return nil, fmt.Errorf("the body holds %d %s blocks", len(blocks), deferredFence)
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(blocks[0]))
|
||||
dec.DisallowUnknownFields()
|
||||
var rec deferredRecord
|
||||
if err := dec.Decode(&rec); err != nil {
|
||||
return nil, fmt.Errorf("reading the %s block: %w", deferredFence, err)
|
||||
}
|
||||
if rec.Line != l.branch() {
|
||||
return nil, fmt.Errorf("the %s block is for %q, not %s", deferredFence, rec.Line, l.branch())
|
||||
}
|
||||
out := map[int]deferredEntry{}
|
||||
for _, d := range rec.Deferred {
|
||||
if d.Original <= 0 {
|
||||
return nil, fmt.Errorf("the %s block names original %d", deferredFence, d.Original)
|
||||
}
|
||||
if d.Commit != "" && checkSHA(d.Commit) != nil {
|
||||
return nil, fmt.Errorf("the %s block names commit %q for #%d", deferredFence, d.Commit, d.Original)
|
||||
}
|
||||
if d.Workflows && (d.Commit != "" || d.Reason != "") {
|
||||
return nil, fmt.Errorf("the %s block has #%d wait for a maintainer and defers it as well", deferredFence, d.Original)
|
||||
}
|
||||
if _, dup := out[d.Original]; dup {
|
||||
return nil, fmt.Errorf("the %s block names #%d twice", deferredFence, d.Original)
|
||||
}
|
||||
out[d.Original] = d
|
||||
}
|
||||
return out, nil
|
||||
return rec.deferred(), nil
|
||||
}
|
||||
|
||||
// prTitle is built from the line and the date alone, never from carried text.
|
||||
@@ -276,7 +224,7 @@ func prTitle(l line, date string) string {
|
||||
}
|
||||
|
||||
// skipRules are the rules a skipped original is reported under, in order.
|
||||
var skipRules = []int{ruleBeforeStart, ruleOnLine, ruleType, ruleBreaking, ruleTouches, ruleNewer}
|
||||
var skipRules = []int{ruleBeforeStart, ruleOnLine, ruleType, ruleBreaking, ruleTouches, ruleNewer, ruleDropped}
|
||||
|
||||
// report is what one run put on the batch branch and what it left out.
|
||||
type report struct {
|
||||
@@ -286,6 +234,7 @@ type report struct {
|
||||
deferred []pick // conflicts
|
||||
held []pick // what --defer took out, with the reason
|
||||
waiting []pick // what changes workflows, left to a maintainer
|
||||
needs []pick // what waits on other originals still to come
|
||||
skipped map[int][]*verdict
|
||||
other int
|
||||
// overrides are the originals a backport/ label kept out or let in, and
|
||||
@@ -293,8 +242,53 @@ type report struct {
|
||||
overrides []*verdict
|
||||
stale []*verdict
|
||||
start time.Time
|
||||
// shapes says, for an original on the branch, what it brought.
|
||||
shapes map[*verdict]string
|
||||
// shapes says, for an original on the branch, what it brought, and
|
||||
// partialFiles what a partial unit leaves without effect.
|
||||
shapes map[*verdict]unitShape
|
||||
partialFiles map[*verdict][]string
|
||||
// missing are originals the policy takes that the run neither tried nor
|
||||
// found anywhere.
|
||||
missing []*verdict
|
||||
// opts is how the run was asked to classify, and built what it read.
|
||||
opts runOptions
|
||||
built builtFrom
|
||||
// blocks are the record and the report the body ends with.
|
||||
blocks string
|
||||
// closing is the close of the open batch this run leaves carrying
|
||||
// nothing.
|
||||
closing *closing
|
||||
// dropped are the maintainers' drops the record keeps.
|
||||
dropped []droppedEntry
|
||||
// parked are what the batch leaves out because it cannot land whole,
|
||||
// each with its park, and partial the originals on the branch whose unit
|
||||
// does only part of what they do on main.
|
||||
parked []*verdict
|
||||
partial []*verdict
|
||||
// carried is the line's record this run found, whose announcements the
|
||||
// parks that did not change keep.
|
||||
carried *lineRecord
|
||||
}
|
||||
|
||||
// ruleName is how output names what kept an original out: the policy's
|
||||
// number for its own rules, and words for what the policy does not number.
|
||||
func ruleName(rule int) string {
|
||||
switch rule {
|
||||
case ruleSkipLabel:
|
||||
return labelSkip
|
||||
case ruleBeforeStart:
|
||||
return "rule 1, before the line's start"
|
||||
case ruleDropped:
|
||||
return "a maintainer's drop"
|
||||
}
|
||||
return "rule " + strconv.Itoa(rule)
|
||||
}
|
||||
|
||||
// listTitle titles the list of what a rule skipped, a drop among them.
|
||||
func (r *report) listTitle(rule int) string {
|
||||
if rule == ruleDropped {
|
||||
return "Dropped from " + codeSpan(r.line.branch()) + " by a maintainer"
|
||||
}
|
||||
return r.ruleTitle(rule)
|
||||
}
|
||||
|
||||
func (r *report) ruleTitle(rule int) string {
|
||||
@@ -319,16 +313,16 @@ func (r *report) ruleTitle(rule int) string {
|
||||
// in details written out.
|
||||
func (r *report) what(details map[int]bool) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "Backports to %s from `main`, picked by the rules of the [backport policy](%s) in merge order. A merged pull request comes as its own commits, picked with `git cherry-pick -x` so each keeps its author, message and sign-offs, and a merge commit that carries the original's merge message with a `%s:` trailer naming it; a squash-merged one comes as one pick. `backport-batch verify` checks that shape. A pick listed as changed differs from the commit it came from; `git range-diff <merge>^1..<merge>^2 <batch merge>^1..<batch merge>^2` shows how. A conflict or a failing check here is a [backport task](%sREADME.md).\n\n", codeSpan(r.line.branch()), policyURL, batchTrailer, tasksURL)
|
||||
fmt.Fprintf(&b, "Backports to %s from `main`, picked by the rules of the [backport policy](%s) in merge order. A merged pull request comes as its own commits, picked with `git cherry-pick -x` so each keeps its author, message and sign-offs, and a merge commit that carries the original's merge message with a `%s:` trailer naming it; a squash-merged one comes as one pick. `backport-batch verify` checks that shape. A pick listed as changed differs from the commit it came from, and its release note waits under Check these notes. A conflict or a failing check here is a [backport task](%sREADME.md).\n\n", codeSpan(r.line.branch()), policyURL, batchTrailer, tasksURL)
|
||||
if len(r.onBranch) == 0 {
|
||||
b.WriteString("Nothing is picked yet.\n")
|
||||
}
|
||||
for _, v := range r.onBranch {
|
||||
shape := ""
|
||||
if s := r.shapes[v]; s != "" {
|
||||
shape = ", " + s
|
||||
if s, ok := r.shapes[v]; ok {
|
||||
shape = ", " + s.String()
|
||||
}
|
||||
fmt.Fprintf(&b, "- %s %s%s\n", prLink(v.o.number), titleSpan(v.o.title), shape)
|
||||
fmt.Fprintf(&b, "- %s %s%s\n%s", prLink(v.o.number), titleSpan(v.o.title), shape, diagItems(v))
|
||||
}
|
||||
if len(r.deferred) > 0 {
|
||||
fmt.Fprintf(&b, "\n### Deferred conflicts\n\nThese do not pick cleanly onto this branch. Each names the first of its commits that conflicted and the files it conflicted in, and nothing of it is on the branch. Each moves to the next batch, unless a resolution checked with `backport-batch fold` is pushed here first, as [resolving a conflict](%sresolve-conflict.md) describes.\n\n", tasksURL)
|
||||
@@ -344,13 +338,13 @@ func (r *report) what(details map[int]bool) string {
|
||||
if p.failed != "" {
|
||||
at = " at " + codeSpan(p.failed[:12])
|
||||
}
|
||||
fmt.Fprintf(&b, "- %s %s%s: %s\n", prLink(p.v.o.number), titleSpan(p.v.o.title), at, strings.Join(files, ", "))
|
||||
fmt.Fprintf(&b, "- %s %s%s: %s\n%s", prLink(p.v.o.number), titleSpan(p.v.o.title), at, strings.Join(files, ", "), diagItems(p.v))
|
||||
}
|
||||
}
|
||||
if len(r.held) > 0 {
|
||||
b.WriteString("\n### Deferred to the next batch\n\nTaken out of this batch with `backport-batch run --defer`, each for the reason given. This pull request keeps them out; the next batch picks them again.\n\n")
|
||||
for _, p := range r.held {
|
||||
fmt.Fprintf(&b, "- %s %s: %s\n", prLink(p.v.o.number), titleSpan(p.v.o.title), titleSpan(p.reason))
|
||||
fmt.Fprintf(&b, "- %s %s: %s\n%s", prLink(p.v.o.number), titleSpan(p.v.o.title), titleSpan(p.reason), diagItems(p.v))
|
||||
}
|
||||
}
|
||||
if len(r.waiting) > 0 {
|
||||
@@ -363,7 +357,41 @@ func (r *report) what(details map[int]bool) string {
|
||||
if more := len(p.files) - len(files) + p.more; more > 0 {
|
||||
files = append(files, fmt.Sprintf("%d more", more))
|
||||
}
|
||||
fmt.Fprintf(&b, "- %s %s: %s\n", prLink(p.v.o.number), titleSpan(p.v.o.title), strings.Join(files, ", "))
|
||||
fmt.Fprintf(&b, "- %s %s: %s\n%s", prLink(p.v.o.number), titleSpan(p.v.o.title), strings.Join(files, ", "), diagItems(p.v))
|
||||
}
|
||||
}
|
||||
if changed := r.changed(); len(changed) > 0 {
|
||||
b.WriteString("\n### Check these notes\n\nThese picks differ from their originals, so their release notes are left out of the release-note block until someone checks that each still holds for this line. Each comes with what to compare: every pick that differs against the commit it came from, and the original's change against the unit's.\n")
|
||||
for _, v := range changed {
|
||||
s := r.shapes[v]
|
||||
fmt.Fprintf(&b, "\n%s %s, carried by %s:\n\n", prLink(v.o.number), titleSpan(v.o.title), codeSpan(s.unit[:12]))
|
||||
if n := releaseNote(v.o.body); n != "" {
|
||||
fmt.Fprintf(&b, "```text\n%s\n```\n\n", neutralNote(n))
|
||||
} else {
|
||||
b.WriteString("It has no release note.\n\n")
|
||||
}
|
||||
for _, p := range s.pairs {
|
||||
fmt.Fprintf(&b, "- %s\n", codeSpan(fmt.Sprintf("git range-diff --creation-factor=999 %s^! %s^!", p.source[:12], p.pick[:12])))
|
||||
}
|
||||
fmt.Fprintf(&b, "- %s\n- %s\n", codeSpan(fmt.Sprintf("git diff %s^1 %s", v.o.merge[:12], v.o.merge[:12])), codeSpan(fmt.Sprintf("git diff %s^1 %s", s.unit[:12], s.unit[:12])))
|
||||
}
|
||||
}
|
||||
if len(r.partial) > 0 {
|
||||
fmt.Fprintf(&b, "\n### Still on this branch: only part of it applies\n\nEach of these is on this branch but leaves files of its original as they were on %s, so it carries only part of what it does on `main`. Take each out with `backport-batch run --defer` before the cut; what applies of it goes as a pull request of its own.\n\n", codeSpan(r.line.branch()))
|
||||
for _, v := range r.partial {
|
||||
fmt.Fprintf(&b, "- %s %s: leaves %s without effect\n", prLink(v.o.number), titleSpan(v.o.title), fileSpans(r.partialFiles[v]))
|
||||
}
|
||||
}
|
||||
if len(r.parked) > 0 {
|
||||
fmt.Fprintf(&b, "\n### Parked\n\nThese cannot land on %s whole, so the batch does not pick them: each would leave part of it without effect there, or builds on a change that never reaches the line. A maintainer ports what applies as a pull request of its own, or drops the original with `backport-batch run --drop`; `backport/include` does not lift a park.\n\n", codeSpan(r.line.branch()))
|
||||
for _, v := range r.parked {
|
||||
fmt.Fprintf(&b, "- %s %s: %s\n%s", prLink(v.o.number), titleSpan(v.o.title), parkReason(*v.park), diagItems(v))
|
||||
}
|
||||
}
|
||||
if len(r.needs) > 0 {
|
||||
fmt.Fprintf(&b, "\n### Waiting on another original\n\nThese build on another original that has not reached %s yet, so the batch does not try them; each names the one it waits on, and the batch tries it again once that one is there.\n\n", codeSpan(r.line.branch()))
|
||||
for _, p := range r.needs {
|
||||
fmt.Fprintf(&b, "- %s %s: after %s\n%s", prLink(p.v.o.number), titleSpan(p.v.o.title), prLinks(p.needs), diagItems(p.v))
|
||||
}
|
||||
}
|
||||
if len(r.overrides) > 0 {
|
||||
@@ -382,7 +410,7 @@ func (r *report) what(details map[int]bool) string {
|
||||
if !details[rule] {
|
||||
left = ", too many to list here; the run's output lists them"
|
||||
}
|
||||
fmt.Fprintf(&b, "- %s: %d%s\n", r.ruleTitle(rule), len(items), left)
|
||||
fmt.Fprintf(&b, "- %s: %d%s\n", r.listTitle(rule), len(items), left)
|
||||
}
|
||||
if r.other > 0 {
|
||||
fmt.Fprintf(&b, "- Commits on `main` that merged no pull request: %d\n", r.other)
|
||||
@@ -390,20 +418,24 @@ func (r *report) what(details map[int]bool) string {
|
||||
for _, rule := range skipRules {
|
||||
items := r.skipped[rule]
|
||||
if len(items) > 0 && details[rule] {
|
||||
fmt.Fprintf(&b, "\n<details><summary>%s</summary>\n\n", r.ruleTitle(rule))
|
||||
fmt.Fprintf(&b, "\n<details><summary>%s</summary>\n\n", r.listTitle(rule))
|
||||
for _, v := range items {
|
||||
fmt.Fprintf(&b, "- %s %s, %s\n", prLink(v.o.number), titleSpan(v.o.title), titleSpan(v.reason))
|
||||
}
|
||||
b.WriteString("\n</details>\n")
|
||||
}
|
||||
}
|
||||
b.WriteString("\n" + deferredBlock(r.line, r.deferred, r.held, r.waiting) + "\n")
|
||||
b.WriteString("\n" + r.blocks + "\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// outcome is what became of an original a label overrode.
|
||||
func (r *report) outcome(v *verdict) string {
|
||||
switch {
|
||||
case slices.Contains(r.partial, v):
|
||||
return "still on this branch, but only part of it applies; take it out with `backport-batch run --defer`"
|
||||
case slices.Contains(r.stale, v) && v.rule == ruleDropped:
|
||||
return "dropped, but still on this branch; take it out with `backport-batch run --defer`"
|
||||
case slices.Contains(r.stale, v):
|
||||
return "still on this branch, picked before the label; take it out with `backport-batch run --defer`"
|
||||
case v.label == labelSkip:
|
||||
@@ -416,15 +448,83 @@ func (r *report) outcome(v *verdict) string {
|
||||
return "deferred to the next batch"
|
||||
case slices.ContainsFunc(r.waiting, func(p pick) bool { return p.v == v }):
|
||||
return "waiting for a maintainer: it changes " + codeSpan(workflowsDir)
|
||||
case slices.Contains(r.parked, v):
|
||||
return "parked: " + parkReason(*v.park)
|
||||
case slices.ContainsFunc(r.needs, func(p pick) bool { return p.v == v }):
|
||||
i := slices.IndexFunc(r.needs, func(p pick) bool { return p.v == v })
|
||||
return "waiting on " + prLinks(r.needs[i].needs)
|
||||
case v.rule != 0:
|
||||
return "skipped by rule " + strconv.Itoa(v.rule) + ", " + titleSpan(v.reason)
|
||||
return "skipped by " + ruleName(v.rule) + ", " + titleSpan(v.reason)
|
||||
}
|
||||
return "not picked"
|
||||
}
|
||||
|
||||
// diagItems lists, under an original's line, what could not be judged about
|
||||
// it or what it was seen to build on, each as a code span.
|
||||
func diagItems(v *verdict) string {
|
||||
var b strings.Builder
|
||||
for _, d := range v.diag {
|
||||
fmt.Fprintf(&b, " - %s\n", titleSpan(d))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// fileSpans lists files as code spans, the first few of them.
|
||||
func fileSpans(files []string) string {
|
||||
var out []string
|
||||
for _, f := range files[:min(len(files), filesListed)] {
|
||||
out = append(out, codeSpan(f))
|
||||
}
|
||||
if more := len(files) - len(out); more > 0 {
|
||||
out = append(out, fmt.Sprintf("%d more", more))
|
||||
}
|
||||
return strings.Join(out, ", ")
|
||||
}
|
||||
|
||||
// prLinks links to pull requests by number.
|
||||
func prLinks(numbers []int) string {
|
||||
var out []string
|
||||
for _, n := range numbers {
|
||||
out = append(out, prLink(n))
|
||||
}
|
||||
return strings.Join(out, ", ")
|
||||
}
|
||||
|
||||
// parkReason says why a park leaves its original out, for the body.
|
||||
func parkReason(p parkedEntry) string {
|
||||
if p.Kind == parkPartial {
|
||||
return "only part of it applies; it would leave " + fileSpans(p.Files) + " without effect"
|
||||
}
|
||||
var needs []string
|
||||
for _, n := range p.Needs {
|
||||
needs = append(needs, prLink(n))
|
||||
}
|
||||
for _, c := range p.Commits {
|
||||
needs = append(needs, codeSpan(c[:12]))
|
||||
}
|
||||
return "builds on " + strings.Join(needs, ", ") + ", which never reaches this line"
|
||||
}
|
||||
|
||||
// changed lists the originals on the branch whose unit differs from them, in
|
||||
// merge order.
|
||||
func (r *report) changed() []*verdict {
|
||||
var out []*verdict
|
||||
for _, v := range r.onBranch {
|
||||
if s, ok := r.shapes[v]; ok && s.changed() {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// notes are the release notes of what the branch carries as its originals
|
||||
// made it; a changed pick's note waits under Check these notes.
|
||||
func (r *report) notes() string {
|
||||
var notes []string
|
||||
for _, v := range r.onBranch {
|
||||
if s, ok := r.shapes[v]; ok && s.changed() {
|
||||
continue
|
||||
}
|
||||
if n := releaseNote(v.o.body); n != "" {
|
||||
notes = append(notes, neutralNote(n))
|
||||
}
|
||||
|
||||
@@ -286,7 +286,7 @@ func TestBodyFollowsTheTemplate(t *testing.T) {
|
||||
l, _ := parseLine("release-1.6")
|
||||
template := "<!-- tips -->\n\n## What this PR does\n\n\n### Screenshots\n\n<!-- shots -->\n\n### Downstream repositories\n\n- [ ] No downstream repository is affected by this change\n\n### Release note\n\n```release-note\n\n```\n"
|
||||
o := &original{number: 7, title: "fix(x): y", body: "```release-note\nfix(x): note\n```"}
|
||||
r := &report{line: l, onBranch: []*verdict{{o: o}}, skipped: map[int][]*verdict{}}
|
||||
r := &report{line: l, onBranch: []*verdict{{o: o}}, skipped: map[int][]*verdict{}, blocks: deferredBlock(l, nil, nil, nil)}
|
||||
body, _ := r.body(template)
|
||||
for _, want := range []string{"## What this PR does\n\nBackports to", "- [#7](https://github.com/cozystack/cozystack/pull/7) `fix(x): y`", "### Downstream repositories\n\n- [ ] No downstream", "```release-note\nfix(x): note\n```", deferredFence} {
|
||||
if !strings.Contains(body, want) {
|
||||
@@ -305,7 +305,7 @@ func TestBodyFollowsTheTemplate(t *testing.T) {
|
||||
for i := range 40 {
|
||||
many = append(many, &verdict{o: &original{number: i + 1, title: "fix(x): y", body: "```release-note\n" + long + "\n```"}})
|
||||
}
|
||||
r = &report{line: l, onBranch: many, skipped: map[int][]*verdict{ruleType: many}}
|
||||
r = &report{line: l, onBranch: many, skipped: map[int][]*verdict{ruleType: many}, blocks: deferredBlock(l, nil, nil, nil)}
|
||||
if body, _ := r.body(template); len(body) > bodyLimit || !strings.Contains(body, "truncated") || !strings.Contains(body, deferredFence) {
|
||||
t.Errorf("a body over the limit is %d bytes (limit %d), truncated=%v", len(body), bodyLimit, strings.Contains(body, "truncated"))
|
||||
}
|
||||
@@ -322,7 +322,7 @@ func TestBodyFollowsTheTemplate(t *testing.T) {
|
||||
for i := range 80 {
|
||||
conflict.files = append(conflict.files, fmt.Sprintf("chart/f%02d.yaml", i))
|
||||
}
|
||||
r = &report{line: l, onBranch: many[:1], deferred: []pick{conflict}, skipped: map[int][]*verdict{ruleType: lots, ruleOnLine: few}}
|
||||
r = &report{line: l, onBranch: many[:1], deferred: []pick{conflict}, skipped: map[int][]*verdict{ruleType: lots, ruleOnLine: few}, blocks: deferredBlock(l, []pick{conflict}, nil, nil)}
|
||||
body, left := r.body(template)
|
||||
if !slices.Equal(left, []int{ruleType}) {
|
||||
t.Errorf("left out the lists of rules %v, want only rule 2", left)
|
||||
@@ -366,3 +366,17 @@ func TestBodyLinksTaskPagesThatExist(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A body that what it has to carry pushes over GitHub's limit is refused
|
||||
// before anything is written, the replay of an earlier report included,
|
||||
// although the report alone would fit a comment.
|
||||
func TestBodyRefusesMandatoryContentOverTheLimit(t *testing.T) {
|
||||
f, gh, head := bigWaits(t, 4)
|
||||
code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--no-workflow-files", "--push")
|
||||
if code != 2 || !strings.Contains(stderr, "with only what it cannot leave out, over GitHub's 65536") {
|
||||
t.Errorf("run --push = %d, want a refusal of the body:\n%s", code, stderr)
|
||||
}
|
||||
if f.remoteHead(batchBranch1) != head || len(gh.issueComments) != 0 || len(gh.edited) != 0 {
|
||||
t.Errorf("the refused run moved the batch to %.12s, wrote %d comments and edited %q", f.remoteHead(batchBranch1), len(gh.issueComments), gh.edited)
|
||||
}
|
||||
}
|
||||
+234
-39
@@ -18,7 +18,9 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// check says whether every original the policy takes is on the line, on the
|
||||
@@ -46,59 +48,242 @@ func (a *app) check(args []string) int {
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
deferred := map[int]deferredEntry{}
|
||||
if b.pr != nil {
|
||||
if deferred, err = parseDeferred(b.pr.Body, l); err != nil {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d: %w", b.pr.Number, err))
|
||||
if err := a.warnLeftBranch(b); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
// The scheduled run's mode, as the open batch saved it; with none open,
|
||||
// the scheduled run's, which is what the next batch is built in.
|
||||
mode := analysisMode{noWorkflowFiles: true}
|
||||
if b.src.open {
|
||||
mode.noWorkflowFiles = b.src.savedNoWorkflowFiles()
|
||||
}
|
||||
disp, err := b.dispositions(mode, *cut)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
var missing, failing []string
|
||||
for _, v := range b.verdicts {
|
||||
d, ok := disp[v]
|
||||
switch {
|
||||
case !ok:
|
||||
case d.kind == outcomeMissing:
|
||||
missing = append(missing, d.text)
|
||||
case d.kind == outcomeUnmerged || d.kind == outcomeWaiting:
|
||||
failing = append(failing, d.text)
|
||||
case d.kind == outcomeWarning:
|
||||
a.warn("%s", d.text)
|
||||
case d.kind == outcomeNote:
|
||||
fmt.Fprintf(a.stderr, "note: %s\n", d.text)
|
||||
}
|
||||
}
|
||||
var missing, unmerged, waiting []*verdict
|
||||
for _, v := range b.qualifying() {
|
||||
e, isDeferred := deferred[v.o.number]
|
||||
switch {
|
||||
case v.onBatch != "":
|
||||
if *cut {
|
||||
unmerged = append(unmerged, v)
|
||||
}
|
||||
case isDeferred && e.Workflows && *cut:
|
||||
waiting = append(waiting, v)
|
||||
case isDeferred && e.Workflows:
|
||||
a.warn("waiting on #%d for a maintainer, since it changes %s: %s %s", b.pr.Number, workflowsDir, v.o.url(), terminalSafe(v.o.title))
|
||||
case isDeferred && e.Reason != "":
|
||||
a.warn("deferred on #%d to the next batch: %s %s (%s)", b.pr.Number, v.o.url(), terminalSafe(v.o.title), terminalSafe(e.Reason))
|
||||
case isDeferred:
|
||||
a.warn("deferred conflict on #%d: %s %s", b.pr.Number, v.o.url(), terminalSafe(v.o.title))
|
||||
default:
|
||||
missing = append(missing, v)
|
||||
if len(missing)+len(failing) == 0 {
|
||||
if *cut {
|
||||
fmt.Fprintf(a.stdout, "%s: no change the policy takes is missing before the cut\n", l.branch())
|
||||
} else {
|
||||
fmt.Fprintf(a.stdout, "%s: every change the policy takes is on the line or on the batch\n", l.branch())
|
||||
}
|
||||
return 0
|
||||
}
|
||||
where := "and no batch pull request is open"
|
||||
if b.pr != nil {
|
||||
where = "nor on batch pull request #" + strconv.Itoa(b.pr.Number)
|
||||
}
|
||||
switch {
|
||||
case len(missing) == 0 && len(unmerged) == 0 && len(waiting) == 0 && *cut:
|
||||
fmt.Fprintf(a.stdout, "%s: every change the policy takes is on the line\n", l.branch())
|
||||
return 0
|
||||
case len(missing) == 0 && len(unmerged) == 0:
|
||||
fmt.Fprintf(a.stdout, "%s: every change the policy takes is on the line or on the batch\n", l.branch())
|
||||
return 0
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
fmt.Fprintf(a.stdout, "%s: %d changes the policy takes are not on the line, %s:\n", l.branch(), len(missing), where)
|
||||
for _, v := range missing {
|
||||
fmt.Fprintf(a.stdout, " %s %s\n", v.o.url(), terminalSafe(v.o.title))
|
||||
for _, text := range missing {
|
||||
fmt.Fprintf(a.stdout, " %s\n", text)
|
||||
}
|
||||
}
|
||||
for _, v := range unmerged {
|
||||
fmt.Fprintf(a.stdout, "%s: #%d is only on open batch PR #%d, merge it before the cut: %s %s\n", l.branch(), v.o.number, b.pr.Number, v.o.url(), terminalSafe(v.o.title))
|
||||
}
|
||||
for _, v := range waiting {
|
||||
fmt.Fprintf(a.stdout, "%s: #%d changes %s and waits on batch PR #%d for a maintainer, bring it over or defer it before the cut: %s %s\n", l.branch(), v.o.number, workflowsDir, b.pr.Number, v.o.url(), terminalSafe(v.o.title))
|
||||
for _, text := range failing {
|
||||
fmt.Fprintf(a.stdout, "%s: %s\n", l.branch(), text)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// warnLeftBranch names the branch a closed batch's close left behind.
|
||||
func (a *app) warnLeftBranch(b *batch) error {
|
||||
if b.src.open || b.src.rec == nil || b.src.rec.Closing == nil {
|
||||
return nil
|
||||
}
|
||||
c := b.src.rec.Closing
|
||||
heads, err := remoteBatchHeads(b.line)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch h, ok := heads[c.Branch]; {
|
||||
case !ok:
|
||||
case takenBranch(b, *c) != nil:
|
||||
a.warn("%v", takenBranch(b, *c))
|
||||
case h == c.Head:
|
||||
a.warn("batch pull request #%d is closed, but its branch %s is still at %.12s; backport-batch run --line %s --push deletes it", c.PR, c.Branch, h, b.line.branch())
|
||||
default:
|
||||
a.warn("%v", movedBranch(*c, h))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// outcome is what check makes of one original.
|
||||
type outcome int
|
||||
|
||||
const (
|
||||
// outcomeMissing fails check and the cut: nothing accounts for an
|
||||
// original the line lacks.
|
||||
outcomeMissing outcome = iota + 1
|
||||
// outcomeUnmerged and outcomeWaiting fail the cut only: the cut would not
|
||||
// carry what is only on the open batch, nor what waits there.
|
||||
outcomeUnmerged
|
||||
outcomeWaiting
|
||||
outcomeWarning
|
||||
outcomeNote
|
||||
)
|
||||
|
||||
type disposition struct {
|
||||
kind outcome
|
||||
text string
|
||||
}
|
||||
|
||||
// dispositions says what check reports about each original that needs a line
|
||||
// of its own; the others pass in silence. The text is what follows the line's
|
||||
// name, or the original alone for one that is missing. Originals are taken in
|
||||
// merge order, each by the first of: a unit on the batch that does only part
|
||||
// of it, a reason a person deferred it for, a park, a wait for a maintainer
|
||||
// or on other originals, and what the record says of it.
|
||||
func (b *batch) dispositions(mode analysisMode, cut bool) (map[*verdict]disposition, error) {
|
||||
if c := b.src.closingOpen(); c != nil {
|
||||
return nil, fmt.Errorf("batch pull request #%d is being closed; backport-batch run --line %s --push finishes it", c.PR, b.line.branch())
|
||||
}
|
||||
var stale []*verdict
|
||||
if b.pr != nil {
|
||||
var err error
|
||||
if stale, err = keptOut(b, b.picks); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// A record a closed batch left still says what a maintainer decided, but
|
||||
// nothing waits on a batch that is gone.
|
||||
deferred, on := b.src.rec.deferred(), ""
|
||||
if c := b.src.carrier; c != nil {
|
||||
on = fmt.Sprintf("#%d", c.Number)
|
||||
if !b.src.open {
|
||||
on += " (" + prState(c) + ")"
|
||||
}
|
||||
}
|
||||
if err := b.analyze(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if b.pr != nil {
|
||||
if err := b.keepRecordedPartials(b.prHead); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
held := map[int]string{}
|
||||
for n, e := range deferred {
|
||||
if e.Reason != "" {
|
||||
held[n] = e.Reason
|
||||
}
|
||||
}
|
||||
states, err := b.classify(mode, held, deferred, b.src.open)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// waitsOn names what an original waits on, as check says it.
|
||||
waitsOn := func(s *state) string {
|
||||
var names []string
|
||||
for _, f := range s.needs {
|
||||
names = append(names, fmt.Sprintf("#%d", f.o.number))
|
||||
}
|
||||
return strings.Join(names, " and ")
|
||||
}
|
||||
out := map[*verdict]disposition{}
|
||||
for _, v := range b.verdicts {
|
||||
named := v.o.url() + " " + terminalSafe(v.o.title)
|
||||
e, isDeferred := deferred[v.o.number]
|
||||
s := states[v]
|
||||
if s == nil {
|
||||
s = &state{kind: stOwn}
|
||||
}
|
||||
switch {
|
||||
case b.partialUnits[v] != nil && cut:
|
||||
out[v] = disposition{outcomeUnmerged, fmt.Sprintf("#%d is on batch #%d, but only part of it applies to %s: it leaves %s without effect; take it out with backport-batch run --defer before the cut: %s", v.o.number, b.pr.Number, b.line.branch(), quotedFiles(b.partialUnits[v]), named)}
|
||||
case b.partialUnits[v] != nil:
|
||||
out[v] = disposition{outcomeWarning, fmt.Sprintf("#%d is on batch #%d, but only part of it applies to %s: it leaves %s without effect; take it out with backport-batch run --defer: %s", v.o.number, b.pr.Number, b.line.branch(), quotedFiles(b.partialUnits[v]), named)}
|
||||
case slices.Contains(stale, v):
|
||||
out[v] = disposition{outcomeWarning, fmt.Sprintf("#%d is still on batch #%d; take it out with backport-batch run --defer: %s", v.o.number, b.pr.Number, named)}
|
||||
case v.rule == ruleDropped:
|
||||
d := b.drops[v.o.number]
|
||||
out[v] = disposition{outcomeNote, fmt.Sprintf("#%d is dropped from %s on #%d (%s): %s", v.o.number, b.line.branch(), d.On, terminalSafe(d.Reason), named)}
|
||||
case v.rule != 0:
|
||||
case v.onBatch != "":
|
||||
if cut {
|
||||
out[v] = disposition{outcomeUnmerged, fmt.Sprintf("#%d is only on open batch PR #%d, merge it before the cut: %s", v.o.number, b.pr.Number, named)}
|
||||
}
|
||||
case s.kind == stHeld:
|
||||
out[v] = disposition{outcomeWarning, fmt.Sprintf("deferred on %s to the next batch: %s (%s)", on, named, terminalSafe(e.Reason))}
|
||||
case s.kind == stPartial:
|
||||
out[v] = disposition{outcomeNote, fmt.Sprintf("#%d is parked: only part of it applies to %s, which would leave %s without effect; port what applies as a pull request of its own: %s", v.o.number, b.line.branch(), quotedFiles(v.park.Files), named)}
|
||||
case s.kind == stWorkflowPrimary && s.class == edgeMissing:
|
||||
out[v] = disposition{outcomeMissing, named}
|
||||
case s.kind == stParked:
|
||||
out[v] = disposition{outcomeNote, fmt.Sprintf("#%d is parked: it builds on %s, which never reaches %s; port what applies as a pull request of its own, or drop it: %s", v.o.number, parkNames(*v.park), b.line.branch(), named)}
|
||||
case s.kind == stNeeds && s.wait == edgeMissing:
|
||||
out[v] = disposition{outcomeMissing, fmt.Sprintf("%s (it waits on %s, which is not on the line either)", named, waitsOn(s))}
|
||||
case s.kind == stNeeds && s.wait == edgeWorkflow && cut:
|
||||
out[v] = disposition{outcomeWaiting, fmt.Sprintf("#%d waits on %s, which changes %s and waits on batch PR %s for a maintainer; bring it over, or defer both, before the cut: %s", v.o.number, waitsOn(s), workflowsDir, on, named)}
|
||||
case s.kind == stNeeds && s.wait == edgeWorkflow:
|
||||
out[v] = disposition{outcomeWarning, fmt.Sprintf("#%d waits on %s, which waits on %s for a maintainer: %s", v.o.number, waitsOn(s), on, named)}
|
||||
case s.kind == stNeeds && s.wait == edgeDeferred:
|
||||
what := "a deferred conflict on " + on
|
||||
if f := s.needs[0]; deferred[f.o.number].Reason != "" {
|
||||
what = "deferred on " + on + " to the next batch"
|
||||
} else if states[f] != nil && states[f].kind == stNeeds {
|
||||
what = "which waits itself"
|
||||
}
|
||||
out[v] = disposition{outcomeWarning, fmt.Sprintf("#%d waits on %s, %s: %s", v.o.number, waitsOn(s), what, named)}
|
||||
case s.kind == stNeeds:
|
||||
newer := "the newer line"
|
||||
if b.newer != nil {
|
||||
newer = b.newer.branch()
|
||||
}
|
||||
out[v] = disposition{outcomeNote, fmt.Sprintf("#%d waits on %s, which is not on %s yet: %s", v.o.number, waitsOn(s), newer, named)}
|
||||
case isDeferred && e.Workflows && !b.src.open:
|
||||
out[v] = disposition{outcomeMissing, named}
|
||||
case isDeferred && e.Workflows && cut:
|
||||
out[v] = disposition{outcomeWaiting, fmt.Sprintf("#%d changes %s and waits on batch PR %s for a maintainer, bring it over or defer it before the cut: %s", v.o.number, workflowsDir, on, named)}
|
||||
case isDeferred && e.Workflows:
|
||||
out[v] = disposition{outcomeWarning, fmt.Sprintf("waiting on %s for a maintainer, since it changes %s: %s", on, workflowsDir, named)}
|
||||
case isDeferred && len(e.Needs) == 0:
|
||||
out[v] = disposition{outcomeWarning, fmt.Sprintf("deferred conflict on %s: %s", on, named)}
|
||||
default:
|
||||
out[v] = disposition{outcomeMissing, named}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// parkNames names what a park waits on for a terminal.
|
||||
func parkNames(p parkedEntry) string {
|
||||
var out []string
|
||||
for _, n := range p.Needs {
|
||||
out = append(out, fmt.Sprintf("#%d", n))
|
||||
}
|
||||
for _, c := range p.Commits {
|
||||
out = append(out, c[:12])
|
||||
}
|
||||
return strings.Join(out, ", ")
|
||||
}
|
||||
|
||||
// quotedFiles names files for a terminal, each quoted, the first few of them.
|
||||
func quotedFiles(files []string) string {
|
||||
var out []string
|
||||
for _, f := range files[:min(len(files), filesListed)] {
|
||||
out = append(out, strconv.Quote(f))
|
||||
}
|
||||
if more := len(files) - len(out); more > 0 {
|
||||
out = append(out, fmt.Sprintf("%d more", more))
|
||||
}
|
||||
return strings.Join(out, ", ")
|
||||
}
|
||||
|
||||
// terminalSafe keeps a title from carrying escape sequences into a terminal.
|
||||
func terminalSafe(s string) string { return capped(oneLine(clean(s, false)), titleLimit) }
|
||||
|
||||
@@ -130,6 +315,12 @@ func (a *app) fold(args []string) int {
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if c := b.src.closingOpen(); c != nil {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d is being closed; backport-batch run --line %s --push finishes it", c.PR, l.branch()))
|
||||
}
|
||||
if err := a.warnLeftBranch(b); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
why, err := refuseFold(b, *number, *commit)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
@@ -156,7 +347,7 @@ func refuseFold(b *batch, n int, commit string) (string, error) {
|
||||
case v.rule == ruleSkipLabel:
|
||||
return fmt.Sprintf("#%d carries %s", n, labelSkip), nil
|
||||
case v.rule != 0:
|
||||
return fmt.Sprintf("#%d is not one the batch takes: rule %d, %s", n, v.rule, v.reason), nil
|
||||
return fmt.Sprintf("#%d is not one the batch takes: %s, %s", n, ruleName(v.rule), terminalSafe(v.reason)), nil
|
||||
case b.pr == nil:
|
||||
return fmt.Sprintf("no batch pull request is open on %s", b.line.branch()), nil
|
||||
case v.onBatch != "":
|
||||
@@ -192,5 +383,9 @@ func refuseFold(b *batch, n int, commit string) (string, error) {
|
||||
case carried != v:
|
||||
return fmt.Sprintf("%.12s carries #%d, not #%d", commit, carried.o.number, n), nil
|
||||
}
|
||||
return "", nil
|
||||
omitted, _, err := b.omittedEffects(v, u.parents[0], u.commit)
|
||||
if err != nil || len(omitted) == 0 {
|
||||
return "", err
|
||||
}
|
||||
return leftOut(v, b.line, omitted), nil
|
||||
}
|
||||
@@ -17,6 +17,7 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode"
|
||||
@@ -140,12 +141,22 @@ func TestCheck(t *testing.T) {
|
||||
{
|
||||
name: "a batch opened by a member with read access claims nothing",
|
||||
arrange: func(s *state) {
|
||||
batch(s, "body\n\n"+deferred6+"\n", s.mc5)
|
||||
batch(s, "body\n\n", s.mc5)
|
||||
s.gh.perms = map[string]string{"maintainer": "read"}
|
||||
},
|
||||
code: 1,
|
||||
listed: []string{"/pull/5 ", "/pull/6 "},
|
||||
},
|
||||
{
|
||||
// An older record is never taken in place of a newer one nobody
|
||||
// can vouch for.
|
||||
name: "a record by a member with read access stops it",
|
||||
arrange: func(s *state) {
|
||||
batch(s, "body\n\n"+deferred6+"\n", s.mc5)
|
||||
s.gh.perms = map[string]string{"maintainer": "read"}
|
||||
},
|
||||
code: 2,
|
||||
},
|
||||
{
|
||||
name: "a deferred list for another line",
|
||||
arrange: func(s *state) { batch(s, strings.Replace(deferred6, "release-1.1", "release-1.0", 1), s.mc5) },
|
||||
@@ -186,6 +197,219 @@ func TestCheck(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Every category an original can be in, through the commands that put it
|
||||
// there, with what check and check --cut make of it: the exit code, and the
|
||||
// warning or note on stderr that leaves it 0.
|
||||
func TestCheckDispositions(t *testing.T) {
|
||||
plain := func(t *testing.T) *fixture {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
return f
|
||||
}
|
||||
// conflicting has #5 conflict on the line, beside #6, which picks.
|
||||
conflicting := func(t *testing.T) *fixture {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): a line-only five", map[string]string{"app/five.txt": "line\n"})
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
return f
|
||||
}
|
||||
must := func(t *testing.T, f *fixture, gh *fakeGH, args ...string) {
|
||||
t.Helper()
|
||||
if code, _, stderr := f.exec(gh, args...); code != 0 {
|
||||
t.Fatalf("%q = %d\n%s", args, code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
if len(gh.bodies) > 0 {
|
||||
reopen(f, gh)
|
||||
}
|
||||
}
|
||||
sixOnLine := func(f *fixture) { pickOnLine(f, 6, map[string]string{"app/six.txt": "6\n"}) }
|
||||
cases := []struct {
|
||||
name string
|
||||
arrange func(t *testing.T) (*fixture, *fakeGH)
|
||||
line string
|
||||
check int
|
||||
cut int
|
||||
checkErr string // on stderr from check
|
||||
cutOut string // on stdout from check --cut
|
||||
cutErr string // on stderr from check --cut
|
||||
notCutOut string
|
||||
}{
|
||||
{
|
||||
name: "missing",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) { return plain(t), &fakeGH{} },
|
||||
check: 1, cut: 1, cutOut: "/pull/5 ",
|
||||
},
|
||||
{
|
||||
name: "carried",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f := plain(t)
|
||||
pickOnLine(f, 5, map[string]string{"app/five.txt": "5\n"})
|
||||
sixOnLine(f)
|
||||
return f, &fakeGH{}
|
||||
},
|
||||
check: 0, cut: 0, notCutOut: "/pull/5",
|
||||
},
|
||||
{
|
||||
name: "picked, on the open batch",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f, gh := plain(t), &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
return f, gh
|
||||
},
|
||||
check: 0, cut: 1, cutOut: "#5 is only on open batch PR #90",
|
||||
},
|
||||
{
|
||||
name: "deferred conflict, open record",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f, gh := conflicting(t), &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
sixOnLine(f)
|
||||
return f, gh
|
||||
},
|
||||
check: 0, cut: 0, checkErr: "warning: deferred conflict on #90: https://github.com/cozystack/cozystack/pull/5 ", cutErr: "warning: deferred conflict on #90",
|
||||
},
|
||||
{
|
||||
name: "deferred with a reason, open record",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f, gh := plain(t), &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
must(t, f, gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "fails the app e2e", "--push")
|
||||
sixOnLine(f)
|
||||
return f, gh
|
||||
},
|
||||
check: 0, cut: 0, checkErr: "warning: deferred on #90 to the next batch: https://github.com/cozystack/cozystack/pull/5 ", cutErr: "(fails the app e2e)",
|
||||
},
|
||||
{
|
||||
name: "workflow wait, open record, beside a pick",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f, gh := workflowWorld(t), &fakeGH{}
|
||||
must(t, f, gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push")
|
||||
return f, gh
|
||||
},
|
||||
check: 0, cut: 1, checkErr: "warning: waiting on #90 for a maintainer", cutOut: "#5 changes .github/workflows/ and waits on batch PR #90",
|
||||
},
|
||||
{
|
||||
name: "workflow wait, open record, alone",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f, gh := workflowWorld(t), &fakeGH{}
|
||||
must(t, f, gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push")
|
||||
pickOnLine(f, 6, map[string]string{"app/six.txt": "6\n", ".github/renovate.json": "{}\n"})
|
||||
return f, gh
|
||||
},
|
||||
check: 0, cut: 1, checkErr: "warning: waiting on #90 for a maintainer", cutOut: "#5 changes .github/workflows/ and waits on batch PR #90",
|
||||
},
|
||||
{
|
||||
name: "backport/skip, not picked",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f := plain(t)
|
||||
sixOnLine(f)
|
||||
return f, &fakeGH{labels: map[string][]int{labelSkip: {5}}}
|
||||
},
|
||||
check: 0, cut: 0, notCutOut: "/pull/5",
|
||||
},
|
||||
{
|
||||
name: "backport/skip after the pick, still on the open batch",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f, gh := plain(t), &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
sixOnLine(f)
|
||||
gh.labels = map[string][]int{labelSkip: {5}}
|
||||
return f, gh
|
||||
},
|
||||
check: 0, cut: 0, checkErr: "warning: #5 is still on batch #90; take it out with backport-batch run --defer", cutErr: "still on batch #90",
|
||||
},
|
||||
{
|
||||
name: "rule 6",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
return f, &fakeGH{}
|
||||
},
|
||||
line: "release-1.0",
|
||||
check: 0, cut: 0, notCutOut: "/pull/5",
|
||||
},
|
||||
{
|
||||
name: "rules 2 to 4",
|
||||
arrange: func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "feat(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
return f, &fakeGH{}
|
||||
},
|
||||
check: 0, cut: 0, notCutOut: "/pull/5",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, gh := tc.arrange(t)
|
||||
line := tc.line
|
||||
if line == "" {
|
||||
line = "release-1.1"
|
||||
}
|
||||
code, stdout, stderr := f.exec(gh, "check", "--line", line)
|
||||
if code != tc.check || !strings.Contains(stderr, tc.checkErr) {
|
||||
t.Errorf("check = %d, want %d with %q\nstdout:\n%s\nstderr:\n%s", code, tc.check, tc.checkErr, stdout, stderr)
|
||||
}
|
||||
code, stdout, stderr = f.exec(gh, "check", "--line", line, "--cut")
|
||||
if code != tc.cut || !strings.Contains(stdout, tc.cutOut) || !strings.Contains(stderr, tc.cutErr) {
|
||||
t.Errorf("check --cut = %d, want %d with %q, %q\nstdout:\n%s\nstderr:\n%s", code, tc.cut, tc.cutOut, tc.cutErr, stdout, stderr)
|
||||
}
|
||||
if tc.notCutOut != "" && strings.Contains(stdout, tc.notCutOut) {
|
||||
t.Errorf("check --cut lists %q:\n%s", tc.notCutOut, stdout)
|
||||
}
|
||||
if tc.cut == 0 && !strings.Contains(stdout, "no change the policy takes is missing before the cut") {
|
||||
t.Errorf("check --cut passes without saying so:\n%s", stdout)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Output names a rule as the policy does: the numbers the tool keeps for
|
||||
// what is no rule of the policy never reach a reader.
|
||||
func TestOutputNamesNoInternalRule(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
f.setPolicy("release-1.1: 2099-01-01\n")
|
||||
gh := &fakeGH{labels: map[string][]int{labelInclude: {6}}}
|
||||
head := openBatch(t, f, gh)
|
||||
internal := regexp.MustCompile(`rule 1[0-9][0-9]`)
|
||||
for _, args := range [][]string{
|
||||
{"fold", "--line", "release-1.1", "--original", "5", "--commit", head},
|
||||
{"run", "--line", "release-1.1", "--defer", "5", "--reason", "x"},
|
||||
} {
|
||||
code, stdout, stderr := f.exec(gh, args...)
|
||||
f.git("switch", "-q", "main")
|
||||
if code == 0 || !strings.Contains(stdout+stderr, "#5 is not one the batch takes: rule 1, before the line's start, merged ") {
|
||||
t.Errorf("%s = %d, want a refusal naming rule 1:\n%s%s", args[0], code, stdout, stderr)
|
||||
}
|
||||
if m := internal.FindString(stdout + stderr); m != "" {
|
||||
t.Errorf("%s prints %q:\n%s%s", args[0], m, stdout, stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A refusal fold prints is one line with no control sequence, whatever the
|
||||
// reason it repeats says: a drop's reason comes from a pull request body, a
|
||||
// rule 4 reason from file names an original's author chose.
|
||||
func TestFoldRefusalPrintsNothingThatDrivesATerminal(t *testing.T) {
|
||||
l, _ := parseLine("release-1.1")
|
||||
for _, reason := range []string{"dropped on #90: x\n\x1b[2Jrefused: forged", "touches \"app/a\x1b]0;x\x07\nok\""} {
|
||||
b := &batch{line: l, verdicts: []*verdict{{o: &original{number: 5}, rule: ruleDropped, reason: reason}}}
|
||||
why, err := refuseFold(b, 5, strings.Repeat("a", 40))
|
||||
if err != nil || why == "" || strings.ContainsFunc(why, func(r rune) bool { return unicode.IsControl(r) || unicode.Is(unicode.Cf, r) }) {
|
||||
t.Errorf("refuseFold = %q, %v; want one clean line", why, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type errString string
|
||||
|
||||
func (e errString) Error() string { return string(e) }
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// pickOnLine lands original n on release-1.1 as a maintainer's pick of its
|
||||
// merge commit, with the -x line git appends, so the line carries it.
|
||||
func pickOnLine(f *fixture, n int, files map[string]string) {
|
||||
f.t.Helper()
|
||||
mc, _, _ := strings.Cut(f.git("log", "--first-parent", "--format=%H", "--grep", fmt.Sprintf("(#%d)$", n), "main"), "\n")
|
||||
f.onLine("release-1.1", fmt.Sprintf("fix: original %d\n\n(cherry picked from commit %s)", n, mc), files)
|
||||
}
|
||||
|
||||
// A workflow original that waits on the open batch fails the cut, also when
|
||||
// it is all the batch has left: the pick beside it was labelled
|
||||
// backport/skip after the pick, or reached the line by hand.
|
||||
func TestCutFailsWhenOnlyAWorkflowWaitIsLeft(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
leave func(f *fixture, gh *fakeGH)
|
||||
}{
|
||||
{"skip after the pick", func(_ *fixture, gh *fakeGH) { gh.labels = map[string][]int{labelSkip: {6}} }},
|
||||
{"picked onto the line by hand", func(f *fixture, _ *fakeGH) {
|
||||
pickOnLine(f, 6, map[string]string{"app/six.txt": "6\n", ".github/renovate.json": "{}\n"})
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := workflowWorld(t)
|
||||
gh := &fakeGH{}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 {
|
||||
t.Fatalf("run --push = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
tc.leave(f, gh)
|
||||
code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut")
|
||||
if code != 1 || !strings.Contains(stdout, "#5 changes .github/workflows/ and waits on batch PR #90 for a maintainer") {
|
||||
t.Errorf("check --cut = %d, want 1 naming #5:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
if strings.Contains(stdout, "on the line or on the batch") {
|
||||
t.Errorf("check --cut passes the line while #5 waits:\n%s", stdout)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A conflict the batch deferred is still deferred once that batch merged:
|
||||
// the next run picks nothing, opens nothing and writes nothing to the merged
|
||||
// pull request, and check reads the merged batch's record.
|
||||
func TestCheckAfterTheBatchMerged(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): a line-only five", map[string]string{"app/five.txt": "line\n"})
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
mergeBatch(f, gh)
|
||||
written := len(gh.created) + len(gh.edited) + len(gh.issueComments)
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 0 {
|
||||
t.Fatalf("run --continue --push = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
if got := len(gh.created) + len(gh.edited) + len(gh.issueComments); got != written || f.remoteHead(batchBranch1) != "" {
|
||||
t.Errorf("the run picked nothing and still wrote: created %q, edited %q", gh.created, gh.edited)
|
||||
}
|
||||
for _, cut := range []bool{false, true} {
|
||||
args := []string{"check", "--line", "release-1.1"}
|
||||
if cut {
|
||||
args = append(args, "--cut")
|
||||
}
|
||||
code, stdout, stderr := f.exec(gh, args...)
|
||||
if code != 0 || !strings.Contains(stderr, "warning: deferred conflict on #90 (merged): https://github.com/cozystack/cozystack/pull/5 ") {
|
||||
t.Errorf("%q = %d, want 0 with #5 a deferred conflict:\nstdout:\n%s\nstderr:\n%s", args, code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A workflow original waits only while a batch is open to list it: once the
|
||||
// batch that listed it merged, it is missing.
|
||||
func TestWorkflowWaitAfterTheBatchMergedIsMissing(t *testing.T) {
|
||||
f := workflowWorld(t)
|
||||
gh := &fakeGH{}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 {
|
||||
t.Fatalf("run --push = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
mergeBatch(f, gh)
|
||||
for _, cut := range []bool{false, true} {
|
||||
args := []string{"check", "--line", "release-1.1"}
|
||||
if cut {
|
||||
args = append(args, "--cut")
|
||||
}
|
||||
if code, stdout, stderr := f.exec(gh, args...); code != 1 || !strings.Contains(stdout, "/pull/5 ") {
|
||||
t.Errorf("%q = %d, want 1 with #5 missing:\nstdout:\n%s\nstderr:\n%s", args, code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
-20
@@ -27,23 +27,29 @@ import (
|
||||
// parseDefer reads --defer N[,N] and the --reason that has to come with it.
|
||||
func parseDefer(list, reason string) ([]int, string, error) {
|
||||
if list == "" {
|
||||
return nil, "", errors.New("--reason goes with --defer")
|
||||
return nil, "", errors.New("--reason goes with --defer or --drop")
|
||||
}
|
||||
reason = capped(oneLine(clean(reason, false)), titleLimit)
|
||||
if reason == "" {
|
||||
return nil, "", errors.New("--defer needs a --reason, which the batch body records")
|
||||
}
|
||||
numbers, err := parseNumbers("--defer", list)
|
||||
return numbers, reason, err
|
||||
}
|
||||
|
||||
// parseNumbers reads the N[,N] list a flag takes, each once.
|
||||
func parseNumbers(flag, list string) ([]int, error) {
|
||||
var numbers []int
|
||||
for _, s := range strings.Split(list, ",") {
|
||||
n, err := strconv.Atoi(strings.TrimPrefix(strings.TrimSpace(s), "#"))
|
||||
if err != nil || n <= 0 {
|
||||
return nil, "", fmt.Errorf("--defer %q is not a list of pull request numbers", list)
|
||||
return nil, fmt.Errorf("%s %q is not a list of pull request numbers", flag, list)
|
||||
}
|
||||
if !slices.Contains(numbers, n) {
|
||||
numbers = append(numbers, n)
|
||||
}
|
||||
}
|
||||
return numbers, reason, nil
|
||||
return numbers, nil
|
||||
}
|
||||
|
||||
// rebuild takes the originals in numbers out of the open batch: it builds the
|
||||
@@ -54,17 +60,8 @@ func (a *app) rebuild(b *batch, numbers []int, reason string, push bool) int {
|
||||
if b.pr == nil {
|
||||
return a.fail(fmt.Errorf("no batch pull request is open on %s; --defer rebuilds the open one", b.line.branch()))
|
||||
}
|
||||
branch := b.pr.Head.Ref
|
||||
date, err := branchDate(branch)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
recorded, err := parseDeferred(b.pr.Body, b.line)
|
||||
if err != nil {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d: %w", b.pr.Number, err))
|
||||
}
|
||||
hold := map[int]string{}
|
||||
for n, e := range recorded {
|
||||
for n, e := range b.recorded() {
|
||||
if e.Reason != "" {
|
||||
hold[n] = e.Reason
|
||||
}
|
||||
@@ -81,12 +78,20 @@ func (a *app) rebuild(b *batch, numbers []int, reason string, push bool) int {
|
||||
switch v := b.find(n); {
|
||||
case v == nil:
|
||||
return a.fail(fmt.Errorf("#%d did not merge into main after %s branched", n, b.line.branch()))
|
||||
case v.rule != 0 && !slices.Contains(stale, v):
|
||||
return a.fail(fmt.Errorf("#%d is not one the batch takes: rule %d, %s", n, v.rule, terminalSafe(v.reason)))
|
||||
case v.rule != 0 && !slices.Contains(stale, v) && b.partialUnits[v] == nil:
|
||||
return a.fail(fmt.Errorf("#%d is not one the batch takes: %s, %s", n, ruleName(v.rule), terminalSafe(v.reason)))
|
||||
}
|
||||
hold[n] = reason
|
||||
}
|
||||
start, replay, err := rebuildPlan(b, hold)
|
||||
return a.reassemble(b, hold, hold, b.src.rec.dropped(), modeDefer, push)
|
||||
}
|
||||
|
||||
// reassemble builds the open batch again off the line's head without the
|
||||
// units of the originals in out, and reports it with hold deferred for their
|
||||
// reasons and drops kept.
|
||||
func (a *app) reassemble(b *batch, out, hold map[int]string, drops []droppedEntry, mode string, push bool) int {
|
||||
branch := b.pr.Head.Ref
|
||||
start, replay, err := rebuildPlan(b, out)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
@@ -102,7 +107,7 @@ func (a *app) rebuild(b *batch, numbers []int, reason string, push bool) int {
|
||||
case err != nil:
|
||||
return a.fail(err)
|
||||
case failed != "":
|
||||
return a.fail(fmt.Errorf("without what is deferred, %.12s%s no longer applies (%s); defer it as well", failed, originName(b, u), strings.Join(files, ", ")))
|
||||
return a.fail(fmt.Errorf("without what is deferred, %.12s%s no longer applies (%s); defer it as well", failed, originName(b, u), terminalSafe(strings.Join(files, ", "))))
|
||||
}
|
||||
}
|
||||
head, err := resolve("HEAD")
|
||||
@@ -113,24 +118,90 @@ func (a *app) rebuild(b *batch, numbers []int, reason string, push bool) int {
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
return a.reclassify(b, picks, hold, drops, mode, push)
|
||||
}
|
||||
|
||||
// reclassify reports the open batch as picks shows it, after an operation
|
||||
// that adds no original: what the record held stays held, and an original
|
||||
// the batch neither carries nor records is missing until a run tries it.
|
||||
func (a *app) reclassify(b *batch, picks *history, hold map[int]string, drops []droppedEntry, mode string, push bool) int {
|
||||
date, err := branchDate(b.pr.Head.Ref)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
recorded := b.recorded()
|
||||
r := newReport(b)
|
||||
// None of these changes how the batch is assembled, so the record keeps
|
||||
// the flag the batch was assembled with.
|
||||
r.opts = runOptions{NoWorkflowFiles: b.src.savedNoWorkflowFiles(), Mode: mode}
|
||||
r.dropped = drops
|
||||
if r.stale, err = keptOut(b, picks); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
// What the rebuild took off is no longer there for what builds on it.
|
||||
units, err := b.unitsOn(picks.head)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
for _, v := range b.verdicts {
|
||||
v.batched = units[v]
|
||||
}
|
||||
on := map[*verdict]bool{}
|
||||
for _, v := range b.qualifying() {
|
||||
if on[v], err = b.onBranch(picks, v); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if !on[v] {
|
||||
v.onBatch = ""
|
||||
}
|
||||
}
|
||||
if err := b.keepRecordedPartials(picks.head); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
states, err := b.classify(analysisMode{noWorkflowFiles: r.opts.NoWorkflowFiles}, hold, recorded, true)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
for _, v := range b.qualifying() {
|
||||
e := recorded[v.o.number]
|
||||
s := states[v]
|
||||
if s == nil {
|
||||
s = &state{kind: stOwn}
|
||||
}
|
||||
switch {
|
||||
case found(picks, v):
|
||||
case on[v]:
|
||||
r.onBranch = append(r.onBranch, v)
|
||||
case hold[v.o.number] != "":
|
||||
r.held = append(r.held, pick{v: v, status: "held", reason: hold[v.o.number]})
|
||||
case s.kind == stPartial || s.kind == stParked:
|
||||
r.parked = append(r.parked, v)
|
||||
case s.kind == stNeeds:
|
||||
r.needs = append(r.needs, pick{v: v, status: "waiting", needs: numbers(s.needs)})
|
||||
case s.kind == stWorkflowPrimary && !e.Workflows:
|
||||
r.missing = append(r.missing, v)
|
||||
case e.Workflows:
|
||||
r.waiting = append(r.waiting, pick{v: v, status: "waiting", files: e.Files, more: e.More})
|
||||
case len(e.Files) > 0:
|
||||
case len(e.Files) > 0 && len(e.Needs) == 0:
|
||||
r.deferred = append(r.deferred, pick{v: v, status: "conflict", files: e.Files, more: e.More, failed: e.Commit})
|
||||
default:
|
||||
// Merged into main since the batch was assembled, or recorded
|
||||
// nowhere: a rebuild adds no original, the next run tries it.
|
||||
r.missing = append(r.missing, v)
|
||||
}
|
||||
}
|
||||
return a.finish(b, r, branch, date, push, true)
|
||||
if err := b.markPartial(r, picks.head); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
return a.finish(b, r, b.pr.Head.Ref, date, push, true)
|
||||
}
|
||||
|
||||
// recorded is what the open batch's record defers; a closed batch's record
|
||||
// holds nothing back on this one.
|
||||
func (b *batch) recorded() map[int]deferredEntry {
|
||||
if !b.src.open {
|
||||
return map[int]deferredEntry{}
|
||||
}
|
||||
return b.src.rec.deferred()
|
||||
}
|
||||
|
||||
// rebuildPlan is where the rebuild of the open batch without the originals in
|
||||
|
||||
@@ -261,8 +261,8 @@ func TestDeferLeasesTheHeadItRebuilt(t *testing.T) {
|
||||
|
||||
pr := f.batchPR(90, "release-1.1", batchBranch1, gh.prs[0].Body)
|
||||
a := &app{gh: gh}
|
||||
b := &batch{line: l, lineHead: lineHead, pr: &pr, prHead: head}
|
||||
err := a.publish(b, batchBranch1, rebuilt, "title", "body", true)
|
||||
b := &batch{line: l, lineHead: lineHead, pr: &pr, prHead: head, src: recordSource{carrier: &pr, open: true, code: &pr}}
|
||||
err := a.publish(b, publication{branch: batchBranch1, head: rebuilt, title: "title", body: "body"}, true)
|
||||
if err == nil || !strings.Contains(err.Error(), "which the rebuild started from") {
|
||||
t.Errorf("publish over a head pushed since = %v, want a refusal", err)
|
||||
}
|
||||
@@ -378,3 +378,332 @@ func TestSkipAfterThePick(t *testing.T) {
|
||||
t.Errorf("check = %d\n%s", code, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// closeWorld is a batch carrying #5 alone, opened and pushed.
|
||||
func closeWorld(t *testing.T) (*fixture, *fakeGH, string) {
|
||||
t.Helper()
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
gh := &fakeGH{}
|
||||
h1 := openBatch(t, f, gh)
|
||||
return f, gh, h1
|
||||
}
|
||||
|
||||
// Deferring everything a batch carries closes it: the record says why and
|
||||
// what it froze while the pull request is still open, then the pull request
|
||||
// is closed and its branch deleted, leased on that head. The next batch
|
||||
// tries what was deferred again.
|
||||
func TestDeferEverythingClosesTheBatch(t *testing.T) {
|
||||
f, gh, h1 := closeWorld(t)
|
||||
var log []string
|
||||
gh.after = map[string]func(){
|
||||
"createComment": func() { log = append(log, "comment") },
|
||||
"editPull": func() { log = append(log, "edit") },
|
||||
"closePull": func() { log = append(log, "close, branch at "+f.remoteHead(batchBranch1)) },
|
||||
}
|
||||
code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "fails the app e2e", "--push")
|
||||
if code != 0 || !strings.Contains(stderr, "closed https://github.com/cozystack/cozystack/pull/90: without what is deferred it carries nothing beyond release-1.1; the next batch tries them again") {
|
||||
t.Fatalf("run --defer of the last pick = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
if want := []string{"comment", "edit", "close, branch at " + h1}; !slices.Equal(log, want) || f.remoteHead(batchBranch1) != "" || gh.find(90).State != "closed" {
|
||||
t.Errorf("writes %q, branch at %q, #90 %s; want %q, the branch deleted and #90 closed", log, f.remoteHead(batchBranch1), gh.find(90).State, want)
|
||||
}
|
||||
rec, err := parseRecord(gh.find(90).Body, notifyLine)
|
||||
if err != nil || rec.Closing == nil || *rec.Closing != (closing{PR: 90, Branch: batchBranch1, Head: h1}) || rec.Built.Options.Mode != modeClose || rec.deferred()[5].Reason != "fails the app e2e" {
|
||||
t.Errorf("the closed batch's record is %+v, %v; want #5 deferred and the close it froze", rec, err)
|
||||
}
|
||||
if !strings.Contains(stdout, `"closing":{"pr":90,"branch":"`+batchBranch1+`","head":"`+h1+`"}`) {
|
||||
t.Errorf("the body printed does not say what the close froze:\n%s", stdout)
|
||||
}
|
||||
code, _, stderr = f.exec(gh, "check", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stderr, "warning: deferred on #90 (closed) to the next batch: https://github.com/cozystack/cozystack/pull/5 ") {
|
||||
t.Errorf("check = %d, want 0 with #5 deferred:\n%s", code, stderr)
|
||||
}
|
||||
gh.nextPR = 91
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if got := f.subjects("origin/release-1.1", f.remoteHead(batchBranch1)); !slices.Equal(got, []string{"fix(app): five (#5)"}) || gh.find(91) == nil {
|
||||
t.Errorf("the next batch carries %q, want #5 tried again on a new pull request", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A close that stopped part way is finished by run --push, and by nothing
|
||||
// else, and never past a head it did not freeze; nothing is ever written to
|
||||
// the closed pull request.
|
||||
func TestCloseRecovery(t *testing.T) {
|
||||
deferAll := []string{"run", "--line", "release-1.1", "--defer", "5", "--reason", "fails the app e2e", "--push"}
|
||||
push := []string{"run", "--line", "release-1.1", "--continue", "--push"}
|
||||
// moveBranch pushes a commit onto the batch branch, or recreates it, as
|
||||
// someone else would.
|
||||
moveBranch := func(f *fixture, base string) string {
|
||||
f.git("switch", "-q", "--detach", base)
|
||||
f.git("commit", "-q", "--allow-empty", "-m", "pushed since")
|
||||
h2 := f.git("rev-parse", "HEAD")
|
||||
f.git("push", "-q", "origin", "HEAD:refs/heads/"+batchBranch1)
|
||||
f.git("switch", "-q", "main")
|
||||
return h2
|
||||
}
|
||||
writes := func(gh *fakeGH) int { return len(gh.issueComments) + len(gh.edited) }
|
||||
|
||||
t.Run("stopped after the record, then the branch moved", func(t *testing.T) {
|
||||
f, gh, h1 := closeWorld(t)
|
||||
gh.after = map[string]func(){"editPull": func() { gh.fail = map[string]error{"pull": errString("HTTP 502")} }}
|
||||
if code, _, stderr := f.exec(gh, deferAll...); code != 2 || !strings.Contains(stderr, "HTTP 502") {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
h2 := moveBranch(f, h1)
|
||||
before := writes(gh)
|
||||
if code, _, stderr := f.exec(gh, push...); code != 2 || !strings.Contains(stderr, h2[:12]) {
|
||||
t.Errorf("run --push over a moved branch = %d, want 2 naming it:\n%s", code, stderr)
|
||||
}
|
||||
if gh.find(90).State != "open" || f.remoteHead(batchBranch1) != h2 || writes(gh) != before {
|
||||
t.Error("the run acted on a branch that moved since the close froze it")
|
||||
}
|
||||
})
|
||||
// GitHub and the remote are read apart, and either may be the first to
|
||||
// show that someone pushed while the record was written.
|
||||
for _, seen := range []string{"by the remote", "by GitHub"} {
|
||||
t.Run("the branch moved while the record was written, seen "+seen, func(t *testing.T) {
|
||||
f, gh, h1 := closeWorld(t)
|
||||
gh.after = map[string]func(){"editPull": func() {
|
||||
gh.remoteHead = func(string) string { return "" }
|
||||
if seen == "by GitHub" {
|
||||
gh.find(90).Head.SHA = strings.Repeat("b", 40)
|
||||
} else {
|
||||
moveBranch(f, h1)
|
||||
}
|
||||
}}
|
||||
code, _, stderr := f.exec(gh, deferAll...)
|
||||
f.git("switch", "-q", "main")
|
||||
if code != 2 || !strings.Contains(stderr, "which its record froze") || gh.find(90).State != "open" || f.remoteHead(batchBranch1) == "" {
|
||||
t.Errorf("run = %d, #90 %s, branch %q; want 2, #90 open and the branch kept:\n%s", code, gh.find(90).State, f.remoteHead(batchBranch1), stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("the close failed", func(t *testing.T) {
|
||||
f, gh, _ := closeWorld(t)
|
||||
gh.fail = map[string]error{"closePull": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, deferAll...); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
before := writes(gh)
|
||||
// Anything but run --push leaves it as it is.
|
||||
for _, args := range [][]string{
|
||||
{"run", "--line", "release-1.1", "--continue"},
|
||||
{"check", "--line", "release-1.1"},
|
||||
{"fold", "--line", "release-1.1", "--original", "5", "--commit", strings.Repeat("a", 40)},
|
||||
{"notify", "--line", "release-1.1", "--push"},
|
||||
} {
|
||||
if code, _, stderr := f.exec(gh, args...); code != 2 || !strings.Contains(stderr, "being closed") {
|
||||
t.Errorf("%q = %d, want 2:\n%s", args, code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
}
|
||||
if writes(gh) != before || gh.find(90).State != "open" {
|
||||
t.Error("a command other than run --push wrote to the batch")
|
||||
}
|
||||
code, _, stderr := f.exec(gh, push...)
|
||||
if code != 0 || gh.find(90).State != "closed" || f.remoteHead(batchBranch1) != "" || writes(gh) != before {
|
||||
t.Errorf("run --push = %d, #90 %s, branch %q, %d writes; want the close finished and nothing else\n%s", code, gh.find(90).State, f.remoteHead(batchBranch1), writes(gh)-before, stderr)
|
||||
}
|
||||
})
|
||||
// A run that finishes a close stops there: the change it was asked for
|
||||
// needs an open batch pull request, and none is left to make it on.
|
||||
t.Run("a change asked for while the close was left", func(t *testing.T) {
|
||||
f, gh, _ := closeWorld(t)
|
||||
gh.fail = map[string]error{"closePull": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, deferAll...); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
code, _, stderr := f.exec(gh, deferAll...)
|
||||
f.git("switch", "-q", "main")
|
||||
if code != 2 || !strings.Contains(stderr, "finished the close of #90 and made no other change") || gh.find(90).State != "closed" || f.remoteHead(batchBranch1) != "" {
|
||||
t.Errorf("run --defer = %d, #90 %s, branch %q; want 2, the close finished and nothing deferred:\n%s", code, gh.find(90).State, f.remoteHead(batchBranch1), stderr)
|
||||
}
|
||||
})
|
||||
t.Run("closed by hand while the close writes", func(t *testing.T) {
|
||||
f, gh, h1 := closeWorld(t)
|
||||
gh.after = map[string]func(){"createComment": func() { gh.find(90).State = "closed" }}
|
||||
code, _, stderr := f.exec(gh, deferAll...)
|
||||
f.git("switch", "-q", "main")
|
||||
if code != 2 || !strings.Contains(stderr, "batch pull request #90 is closed now; nothing is written to it") || len(gh.edited) != 0 || f.remoteHead(batchBranch1) != h1 {
|
||||
t.Errorf("run = %d, edited %q, branch %q; want 2, no edit and the branch kept:\n%s", code, gh.edited, f.remoteHead(batchBranch1), stderr)
|
||||
}
|
||||
})
|
||||
t.Run("the delete failed", func(t *testing.T) {
|
||||
f, gh, h1 := closeWorld(t)
|
||||
gh.after = map[string]func(){"closePull": func() { f.refusePushes(true) }}
|
||||
if code, _, stderr := f.exec(gh, deferAll...); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
f.refusePushes(false)
|
||||
code, _, stderr := f.exec(gh, "check", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stderr, "warning: batch pull request #90 is closed, but its branch "+batchBranch1+" is still at "+h1[:12]) {
|
||||
t.Errorf("check = %d, want 0 naming the branch:\n%s", code, stderr)
|
||||
}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue"); code != 2 {
|
||||
t.Errorf("run without --push = %d, want 2:\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
if code, _, stderr := f.exec(gh, push...); code != 0 || f.remoteHead(batchBranch1) != "" {
|
||||
t.Errorf("run --push = %d, branch %q; want it deleted\n%s", code, f.remoteHead(batchBranch1), stderr)
|
||||
}
|
||||
mustRun(t, f, gh, "check", "--line", "release-1.1")
|
||||
})
|
||||
// A batch pull request a person opens on the branch a close left owns
|
||||
// it: neither recovery nor check offers to delete it, moved or not. One
|
||||
// on another branch does not stop the delete.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
branch string
|
||||
moved bool
|
||||
}{
|
||||
{"a batch opened on the branch the close left", batchBranch1, false},
|
||||
{"a batch opened on the branch the close left, moved since", batchBranch1, true},
|
||||
{"a batch opened on another branch", "backport-batch/release-1.1-20261027", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, gh, h1 := closeWorld(t)
|
||||
gh.after = map[string]func(){"closePull": func() { f.refusePushes(true) }}
|
||||
if code, _, stderr := f.exec(gh, deferAll...); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
f.refusePushes(false)
|
||||
gh.after = nil
|
||||
if tc.branch != batchBranch1 {
|
||||
f.git("push", "-q", "origin", h1+":refs/heads/"+tc.branch)
|
||||
}
|
||||
left := h1
|
||||
if tc.moved {
|
||||
left = moveBranch(f, h1)
|
||||
}
|
||||
gh.prs = append(gh.prs, f.batchPR(91, "release-1.1", tc.branch, "a maintainer's batch"))
|
||||
taken := tc.branch == batchBranch1
|
||||
_, _, stderr := f.exec(gh, "check", "--line", "release-1.1")
|
||||
f.git("switch", "-q", "main")
|
||||
if named := strings.Contains(stderr, "batch pull request #91 is open on "+batchBranch1); named != taken || taken == strings.Contains(stderr, "--push deletes it") || taken && strings.Contains(stderr, "git push origin --delete") {
|
||||
t.Errorf("check names the branch as #91's: %v, want %v, and offers no delete of it:\n%s", named, taken, stderr)
|
||||
}
|
||||
code, _, stderr := f.exec(gh, push...)
|
||||
f.git("switch", "-q", "main")
|
||||
if taken && (code != 2 || !strings.Contains(stderr, "batch pull request #91 is open on "+batchBranch1) || strings.Contains(stderr, "git push origin --delete") || f.remoteHead(batchBranch1) != left || gh.find(91).State != "open") {
|
||||
t.Errorf("run --push = %d, branch %q; want 2, no delete offered and #91's branch kept:\n%s", code, f.remoteHead(batchBranch1), stderr)
|
||||
}
|
||||
if !taken && (code != 0 || f.remoteHead(batchBranch1) != "") {
|
||||
t.Errorf("run --push = %d, branch %q; want the left branch deleted:\n%s", code, f.remoteHead(batchBranch1), stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("the branch moved after the close", func(t *testing.T) {
|
||||
f, gh, h1 := closeWorld(t)
|
||||
var h2 string
|
||||
gh.after = map[string]func(){"closePull": func() { h2 = moveBranch(f, h1) }}
|
||||
if code, _, stderr := f.exec(gh, deferAll...); code != 2 || !strings.Contains(stderr, "is at "+h2[:12]+" now") {
|
||||
t.Fatalf("run = %d, want 2 naming where the branch moved\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
// What was pushed onto the branch may be work the next run cannot
|
||||
// pick again, so the refusal promises nothing about deleting it.
|
||||
if code, _, stderr := f.exec(gh, push...); code != 2 || !strings.Contains(stderr, h1[:12]) || !strings.Contains(stderr, h2[:12]) || !strings.Contains(stderr, "#90") || strings.Contains(stderr, "nothing on it is lost") || !strings.Contains(stderr, "check what "+h2[:12]+" carries") {
|
||||
t.Errorf("run --push = %d, want 2 naming both heads and #90, and what to check before deleting:\n%s", code, stderr)
|
||||
}
|
||||
if f.remoteHead(batchBranch1) != h2 {
|
||||
t.Error("the run moved a branch it did not freeze")
|
||||
}
|
||||
if _, err := git(deleteArgs(batchBranch1, h1)...); err == nil || f.remoteHead(batchBranch1) != h2 {
|
||||
t.Error("the remote took a delete whose lease names a head it no longer has")
|
||||
}
|
||||
})
|
||||
t.Run("a batch of the same day that opened no pull request", func(t *testing.T) {
|
||||
f, gh, _ := closeWorld(t)
|
||||
if code, _, stderr := f.exec(gh, deferAll...); code != 0 || f.remoteHead(batchBranch1) != "" {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
// The same day, a new batch reuses the branch name, pushes, and
|
||||
// fails to open its pull request.
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh.fail = map[string]error{"createPull": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, push...); code != 2 {
|
||||
t.Fatalf("the same-day run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
h2 := f.remoteHead(batchBranch1)
|
||||
for _, args := range [][]string{push, {"run", "--line", "release-1.1", "--onto", h2, "--push"}} {
|
||||
if code, _, stderr := f.exec(gh, args...); code != 2 || !strings.Contains(stderr, "git push origin --delete "+batchBranch1) {
|
||||
t.Errorf("%q = %d, want 2 naming the branch to delete:\n%s", args, code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
}
|
||||
if f.remoteHead(batchBranch1) != h2 || len(gh.created) != 1 {
|
||||
t.Errorf("the branch moved to %.12s or a pull request was opened: %q", f.remoteHead(batchBranch1), gh.created)
|
||||
}
|
||||
f.git("push", "-q", "origin", "--delete", batchBranch1)
|
||||
gh.nextPR = 91
|
||||
mustRun(t, f, gh, push...)
|
||||
if gh.find(91) == nil {
|
||||
t.Error("after the branch was deleted the next run opened no batch")
|
||||
}
|
||||
})
|
||||
t.Run("a preview", func(t *testing.T) {
|
||||
f, gh, _ := closeWorld(t)
|
||||
gh.fail = map[string]error{"closePull": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, deferAll...); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
before := writes(gh)
|
||||
code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "x")
|
||||
if code != 2 || !strings.Contains(stderr, "run --line release-1.1 --push finishes") || writes(gh) != before || gh.find(90).State != "open" {
|
||||
t.Errorf("a preview = %d, want 2 naming the step left and nothing written:\n%s", code, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A batch that merged on GitHub and left its branch behind is named when a
|
||||
// run of the same day refuses to push over that branch.
|
||||
func TestRefusalNamesTheMergedBatchsBranch(t *testing.T) {
|
||||
f, gh, _ := closeWorld(t)
|
||||
head := f.remoteHead(batchBranch1)
|
||||
mergeBatch(f, gh)
|
||||
// A commit pushed onto the batch after it merged is left on its branch.
|
||||
f.git("switch", "-q", "--detach", head)
|
||||
f.git("commit", "-q", "--allow-empty", "-m", "pushed after the merge")
|
||||
pushed := f.git("rev-parse", "HEAD")
|
||||
f.git("push", "-q", "origin", "HEAD:refs/heads/"+batchBranch1)
|
||||
f.git("switch", "-q", "main")
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if code != 2 || !strings.Contains(stderr, "it is the branch of batch pull request #90, which is merged") || strings.Contains(stderr, "--onto") || !strings.Contains(stderr, "check what "+pushed[:12]+" carries") {
|
||||
t.Errorf("run --push = %d, want a refusal naming #90:\n%s", code, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A rebuild that stops names the files that no longer apply on the line of
|
||||
// its refusal, whatever the files are called.
|
||||
func TestDeferRefusalNamesFilesOnOneLine(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
name := "app/x\nwarning: forged.txt"
|
||||
f.pr(5, "fix(app): five", "", map[string]string{name: "five\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{name: "five and six\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
f.onLine("release-1.1", "fix(chart): a line-only value", map[string]string{"chart/values.yaml": "replicas: 3\nimage: app:1\n"})
|
||||
code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "x", "--push")
|
||||
f.git("switch", "-q", "main")
|
||||
if code != 2 || !strings.Contains(stderr, "no longer applies") {
|
||||
t.Fatalf("run --defer 5 = %d, want the refusal:\n%s", code, stderr)
|
||||
}
|
||||
for _, ln := range strings.Split(stderr, "\n") {
|
||||
if strings.HasPrefix(ln, "warning: forged") {
|
||||
t.Errorf("the refusal split onto a line of its own: %q", ln)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,912 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"path"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// What an original builds on that its line lacks is read from git alone, in
|
||||
// two ways: a file it modifies or deletes that the line does not have, named
|
||||
// by the first-parent commit on main that added it (V1), and a line it
|
||||
// removes or changes that git blame gives to a commit the line lacks, kept
|
||||
// only while that line's text is absent from the line's file (V2c). Either
|
||||
// names the first-parent commit that brought the evidence to main: the merge
|
||||
// of another original, or a commit that merged no pull request.
|
||||
|
||||
// Bounds per original, past which the evidence is incomplete rather than
|
||||
// read at any cost.
|
||||
const (
|
||||
maxDepFiles = 256
|
||||
maxBlamedLines = 20000
|
||||
maxDepBlob = 8 << 20
|
||||
gitDeadline = 2 * time.Minute
|
||||
)
|
||||
|
||||
// dependency is a first-parent commit on main an original builds on, with
|
||||
// the original's paths the evidence is in.
|
||||
type dependency struct {
|
||||
merge string
|
||||
// v is the original merge merged, nil for a commit that merged none.
|
||||
v *verdict
|
||||
paths []string
|
||||
// added says some of the evidence is a file the line lacks (V1).
|
||||
added bool
|
||||
}
|
||||
|
||||
// errDeadline is a git call that ran out of time: incomplete evidence, not
|
||||
// a failure.
|
||||
var errDeadline = errors.New("git took longer than " + gitDeadline.String())
|
||||
|
||||
// gitTimed runs git under the deadline the detector gives each call.
|
||||
func gitTimed(args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), gitDeadline)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "git", args...)
|
||||
cmd.Env = append(cmd.Environ(), commandEnv...)
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &out, &errOut
|
||||
err := cmd.Run()
|
||||
switch {
|
||||
case ctx.Err() != nil:
|
||||
return "", errDeadline
|
||||
case err != nil:
|
||||
return "", fmt.Errorf("git %s: %w: %s", quotedArgs(args), err, terminalSafe(errOut.String()))
|
||||
}
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
// quotedArgs names a git command's arguments for an error, each quoted: a
|
||||
// file name can hold a newline, and the error reaches a terminal and a CI
|
||||
// log, which would take the rest for a line of their own.
|
||||
func quotedArgs(args []string) string {
|
||||
out := make([]string, len(args))
|
||||
for i, a := range args {
|
||||
out[i] = strconv.Quote(a)
|
||||
}
|
||||
return strings.Join(out, " ")
|
||||
}
|
||||
|
||||
// gitStatusTimed is gitStatus under the detector's deadline: a non-zero
|
||||
// exit is an answer, and running out of time is errDeadline.
|
||||
func gitStatusTimed(args ...string) (stdout, stderr string, code int, err error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), gitDeadline)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "git", args...)
|
||||
cmd.Env = append(cmd.Environ(), commandEnv...)
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &out, &errOut
|
||||
err = cmd.Run()
|
||||
var ee *exec.ExitError
|
||||
switch {
|
||||
case ctx.Err() != nil:
|
||||
return "", "", -1, errDeadline
|
||||
case errors.As(err, &ee):
|
||||
return out.String(), errOut.String(), ee.ExitCode(), nil
|
||||
case err != nil:
|
||||
return "", "", -1, fmt.Errorf("git %s: %w", quotedArgs(args), err)
|
||||
}
|
||||
return out.String(), errOut.String(), 0, nil
|
||||
}
|
||||
|
||||
// broughtBy maps every commit in base..mainHead to the first-parent commit
|
||||
// that brought it to main: each first-parent commit claims itself, then
|
||||
// every commit of the range reachable from its other parents that no
|
||||
// earlier one claimed. A commit outside the map is an ancestor of base.
|
||||
func broughtBy(base, mainHead string) (map[string]string, error) {
|
||||
first, err := revList("--first-parent", "--reverse", "--end-of-options", base+".."+mainHead)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := git("rev-list", "--parents", "--topo-order", "--end-of-options", base+".."+mainHead)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parents := map[string][]string{}
|
||||
for ln := range strings.Lines(out) {
|
||||
f := strings.Fields(ln)
|
||||
if len(f) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, sha := range f {
|
||||
if checkSHA(sha) != nil {
|
||||
return nil, fmt.Errorf("rev-list: %q is not a commit", sha)
|
||||
}
|
||||
}
|
||||
parents[f[0]] = f[1:]
|
||||
}
|
||||
by := map[string]string{}
|
||||
for _, fp := range first {
|
||||
if _, ok := parents[fp]; !ok {
|
||||
return nil, fmt.Errorf("rev-list: %s is on main's first-parent line but not in its range", fp)
|
||||
}
|
||||
by[fp] = fp
|
||||
stack := slices.Clone(parents[fp][min(1, len(parents[fp])):])
|
||||
for len(stack) > 0 {
|
||||
c := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
if _, inRange := parents[c]; !inRange || by[c] != "" {
|
||||
continue
|
||||
}
|
||||
by[c] = fp
|
||||
stack = append(stack, parents[c]...)
|
||||
}
|
||||
}
|
||||
return by, nil
|
||||
}
|
||||
|
||||
// hunk is an old range of a diff, a,+b in git blame's terms.
|
||||
type hunk struct{ start, count int }
|
||||
|
||||
var hunkRE = regexp.MustCompile(`^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@`)
|
||||
|
||||
// oldRanges reads the removed or changed line ranges of a -U0 diff of one
|
||||
// file, and whether git called it binary. A header it cannot read is an
|
||||
// error, never evidence of absence.
|
||||
func oldRanges(diff string) ([]hunk, bool, error) {
|
||||
var out []hunk
|
||||
for ln := range strings.Lines(diff) {
|
||||
ln = strings.TrimSuffix(ln, "\n")
|
||||
switch {
|
||||
case strings.HasPrefix(ln, "Binary files ") && strings.HasSuffix(ln, " differ"):
|
||||
return nil, true, nil
|
||||
case strings.HasPrefix(ln, "@@"):
|
||||
m := hunkRE.FindStringSubmatch(ln)
|
||||
if m == nil {
|
||||
return nil, false, fmt.Errorf("unreadable hunk header %q", terminalSafe(ln))
|
||||
}
|
||||
start, _ := strconv.Atoi(m[1])
|
||||
count := 1
|
||||
if m[2] != "" {
|
||||
count, _ = strconv.Atoi(m[2])
|
||||
}
|
||||
if count > 0 {
|
||||
out = append(out, hunk{start, count})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, false, nil
|
||||
}
|
||||
|
||||
// blameArgs blames ranges of file at rev, a full commit, which git takes for
|
||||
// a revision whatever follows: blame refuses --end-of-options.
|
||||
func blameArgs(rev, file string, ranges []hunk) ([]string, error) {
|
||||
if err := checkSHA(rev); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args := []string{"blame", "--porcelain", "-w"}
|
||||
for _, r := range ranges {
|
||||
args = append(args, "-L", fmt.Sprintf("%d,+%d", r.start, r.count))
|
||||
}
|
||||
return append(args, rev, "--", file), nil
|
||||
}
|
||||
|
||||
// blamedLine is one line git blame gives to a commit.
|
||||
type blamedLine struct{ commit, text string }
|
||||
|
||||
// parseBlame reads git blame --porcelain: a header per line, the commit's
|
||||
// fields the first time it appears, and the line itself after a tab.
|
||||
// Anything else is an error, never evidence of absence.
|
||||
func parseBlame(out string) ([]blamedLine, error) {
|
||||
var lines []blamedLine
|
||||
commit := ""
|
||||
for ln := range strings.Lines(out) {
|
||||
ln = strings.TrimSuffix(ln, "\n")
|
||||
switch {
|
||||
case strings.HasPrefix(ln, "\t"):
|
||||
if commit == "" {
|
||||
return nil, errors.New("git blame: a line with no header")
|
||||
}
|
||||
lines = append(lines, blamedLine{commit: commit, text: ln[1:]})
|
||||
commit = ""
|
||||
case commit == "":
|
||||
f := strings.Fields(ln)
|
||||
if len(f) < 3 || len(f) > 4 || checkSHA(f[0]) != nil {
|
||||
return nil, fmt.Errorf("git blame: unreadable header %q", terminalSafe(ln))
|
||||
}
|
||||
for _, n := range f[1:] {
|
||||
if v, err := strconv.Atoi(n); err != nil || v <= 0 {
|
||||
return nil, fmt.Errorf("git blame: unreadable header %q", terminalSafe(ln))
|
||||
}
|
||||
}
|
||||
commit = f[0]
|
||||
}
|
||||
}
|
||||
if commit != "" {
|
||||
return nil, errors.New("git blame: a header with no line")
|
||||
}
|
||||
return lines, nil
|
||||
}
|
||||
|
||||
var generatedMarkerRE = regexp.MustCompile(`Code generated .* DO NOT EDIT`)
|
||||
|
||||
// generatedFiles are written whole by a tool, whatever they hold.
|
||||
var generatedFiles = []string{"go.sum", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"}
|
||||
|
||||
// cozyRDGenerated are the keys hack/update-crd.sh writes into an
|
||||
// ApplicationDefinition, the rest of which people write.
|
||||
var cozyRDGenerated = []string{
|
||||
"apiVersion", "kind", "metadata.name", "spec.application.openAPISchema", "spec.release.prefix",
|
||||
"spec.release.chartRef.kind", "spec.release.chartRef.name", "spec.release.chartRef.namespace",
|
||||
"spec.dashboard.description", "spec.dashboard.icon", "spec.dashboard.keysOrder",
|
||||
}
|
||||
|
||||
var yamlKeyRE = regexp.MustCompile(`^( *)([A-Za-z0-9_.-]+):(?:\s|$)`)
|
||||
|
||||
// generatedLines says which lines of a file at a commit a tool wrote: all of
|
||||
// them for a generated file, the keys hack/update-crd.sh sets for an
|
||||
// ApplicationDefinition, found by indentation, and none otherwise. ok is
|
||||
// false for an ApplicationDefinition the scan cannot read, whose lines are
|
||||
// then not blamed at all.
|
||||
func generatedLines(file string, blob []byte) (skip map[int]bool, whole, ok bool) {
|
||||
base := path.Base(file)
|
||||
if strings.HasPrefix(base, "zz_generated") || slices.Contains(generatedFiles, base) {
|
||||
return nil, true, true
|
||||
}
|
||||
lines := strings.Split(string(blob), "\n")
|
||||
for _, ln := range lines[:min(len(lines), 100)] {
|
||||
if generatedMarkerRE.MatchString(ln) {
|
||||
return nil, true, true
|
||||
}
|
||||
}
|
||||
if rd, _ := path.Match(cozyRDGlob, file); !rd {
|
||||
return nil, false, true
|
||||
}
|
||||
skip = map[int]bool{}
|
||||
type key struct {
|
||||
indent int
|
||||
name string
|
||||
}
|
||||
var stack []key
|
||||
genIndent := -1
|
||||
for i, ln := range lines {
|
||||
n := i + 1
|
||||
trimmed := strings.TrimLeft(ln, " ")
|
||||
indent := len(ln) - len(trimmed)
|
||||
switch {
|
||||
case strings.HasPrefix(trimmed, "\t") || strings.HasPrefix(ln, "---") && i > 0:
|
||||
return nil, false, false
|
||||
case trimmed == "" || strings.HasPrefix(trimmed, "#"):
|
||||
if genIndent >= 0 {
|
||||
skip[n] = true
|
||||
}
|
||||
continue
|
||||
case genIndent >= 0 && indent > genIndent:
|
||||
skip[n] = true
|
||||
continue
|
||||
}
|
||||
genIndent = -1
|
||||
m := yamlKeyRE.FindStringSubmatch(ln)
|
||||
if m == nil {
|
||||
continue
|
||||
}
|
||||
for len(stack) > 0 && stack[len(stack)-1].indent >= indent {
|
||||
stack = stack[:len(stack)-1]
|
||||
}
|
||||
stack = append(stack, key{indent, m[2]})
|
||||
var names []string
|
||||
for _, k := range stack {
|
||||
names = append(names, k.name)
|
||||
}
|
||||
if slices.Contains(cozyRDGenerated, strings.Join(names, ".")) {
|
||||
skip[n] = true
|
||||
genIndent = indent
|
||||
}
|
||||
}
|
||||
return skip, false, true
|
||||
}
|
||||
|
||||
// trimmedLines is the set of a blob's lines with their edges trimmed, which
|
||||
// is all a reformat of indentation or trailing space changes.
|
||||
func trimmedLines(blob []byte) map[string]bool {
|
||||
set := map[string]bool{}
|
||||
for ln := range strings.Lines(string(blob)) {
|
||||
set[strings.TrimSpace(ln)] = true
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// shown is a path as a diagnostic names it.
|
||||
func shown(p string) string { return strconv.Quote(p) }
|
||||
|
||||
// incomplete is a diagnostic about evidence the detector could not read.
|
||||
func incomplete(format string, args ...any) string {
|
||||
return oneLineText("incomplete evidence: " + fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// dependencies reads what v builds on that target lacks, with what it could
|
||||
// not read. V1 looks at the paths whose counterpart target lacks, V2c at
|
||||
// the ones it has.
|
||||
func (b *batch) dependencies(v *verdict, target string) ([]dependency, []string, error) {
|
||||
if err := b.load(v); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if b.brought == nil {
|
||||
var err error
|
||||
if b.brought, err = broughtBy(b.base, b.mainHead); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
corr, unknown, err := b.correspondence(v, target)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var diag []string
|
||||
for _, p := range unknown {
|
||||
diag = append(diag, incomplete("git skipped rename detection for %s", shown(p)))
|
||||
}
|
||||
var at []string
|
||||
for _, c := range corr {
|
||||
at = append(at, c)
|
||||
}
|
||||
have, err := treeEntries(target, at)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
parent, err := resolve(v.o.merge + "^1")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
byMerge := map[string]*dependency{}
|
||||
add := func(merge, p string, added bool) {
|
||||
d := byMerge[merge]
|
||||
if d == nil {
|
||||
d = &dependency{merge: merge, v: b.findMerge(merge)}
|
||||
byMerge[merge] = d
|
||||
}
|
||||
if !slices.Contains(d.paths, p) {
|
||||
d.paths = append(d.paths, p)
|
||||
}
|
||||
d.added = d.added || added
|
||||
}
|
||||
files, blamed := 0, 0
|
||||
for _, c := range v.changes {
|
||||
cp, ok := corr[c.path]
|
||||
if !ok || c.status != 'M' && c.status != 'D' {
|
||||
continue
|
||||
}
|
||||
if !utf8.ValidString(c.path) {
|
||||
diag = append(diag, incomplete("a path that is not UTF-8, %s", shown(c.path)))
|
||||
continue
|
||||
}
|
||||
if files++; files > maxDepFiles {
|
||||
diag = append(diag, incomplete("more than %d files to read", maxDepFiles))
|
||||
break
|
||||
}
|
||||
cur, present := have[cp]
|
||||
if !present {
|
||||
out, err := gitTimed("--literal-pathspecs", "log", "--first-parent", "--diff-merges=first-parent", "--no-renames", "--diff-filter=A", "--format=%H", "--no-patch", "-1", "--end-of-options", b.base+".."+parent, "--", c.path)
|
||||
switch {
|
||||
case errors.Is(err, errDeadline):
|
||||
diag = append(diag, incomplete("%s, finding what added %s", err, shown(c.path)))
|
||||
continue
|
||||
case err != nil:
|
||||
return nil, nil, err
|
||||
}
|
||||
adder := strings.TrimSpace(out)
|
||||
if adder == "" {
|
||||
diag = append(diag, oneLineText(fmt.Sprintf("%s is not on the line, and nothing merged into main since it branched added it", shown(c.path))))
|
||||
continue
|
||||
}
|
||||
if checkSHA(adder) != nil {
|
||||
return nil, nil, fmt.Errorf("git log for %s: %q is not a commit", shown(c.path), terminalSafe(adder))
|
||||
}
|
||||
add(adder, c.path, true)
|
||||
continue
|
||||
}
|
||||
found, more, err := b.blamed(v, parent, c.path, cur, target, maxBlamedLines-blamed)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
blamed += more.lines
|
||||
diag = append(diag, more.diag...)
|
||||
for merge := range found {
|
||||
add(merge, c.path, false)
|
||||
}
|
||||
if more.capped {
|
||||
break
|
||||
}
|
||||
}
|
||||
var deps []dependency
|
||||
for _, d := range byMerge {
|
||||
slices.Sort(d.paths)
|
||||
deps = append(deps, *d)
|
||||
// The rules decide before the line is looked at, so whether the
|
||||
// line carries a prerequisite they keep out is asked here.
|
||||
if f := d.v; f != nil && f.rule != 0 && f.rule != ruleOnLine && f.rule != ruleNewer && b.lineHist != nil {
|
||||
if _, asked := b.lineCarries[f]; !asked {
|
||||
if err := b.load(f); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
how, err := b.lineHist.carries(f.o, f.commits)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if b.lineCarries == nil {
|
||||
b.lineCarries = map[*verdict]bool{}
|
||||
}
|
||||
b.lineCarries[f] = how != ""
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.SortFunc(deps, func(x, y dependency) int { return strings.Compare(x.merge, y.merge) })
|
||||
return deps, diag, nil
|
||||
}
|
||||
|
||||
// blameResult is what blaming one file read: how many lines, what it could
|
||||
// not read, and whether the original's line budget ran out.
|
||||
type blameResult struct {
|
||||
lines int
|
||||
diag []string
|
||||
capped bool
|
||||
}
|
||||
|
||||
// blamed gives each line of file that v removes or changes, at parent, to
|
||||
// the first-parent commit that brought it, and keeps the commits one of
|
||||
// whose lines target's counterpart of the file, cur, lacks.
|
||||
func (b *batch) blamed(v *verdict, parent, file string, cur treeEntry, target string, budget int) (map[string]bool, blameResult, error) {
|
||||
var res blameResult
|
||||
entries, err := treeEntries(parent, []string{file})
|
||||
if err != nil {
|
||||
return nil, res, err
|
||||
}
|
||||
pre := entries[file]
|
||||
switch {
|
||||
case pre.mode == "120000" || cur.mode == "120000":
|
||||
res.diag = append(res.diag, incomplete("%s is a symlink", shown(file)))
|
||||
return nil, res, nil
|
||||
case pre.kind == "commit" || cur.kind == "commit":
|
||||
res.diag = append(res.diag, incomplete("%s is a submodule", shown(file)))
|
||||
return nil, res, nil
|
||||
case !pre.regular() || !cur.regular():
|
||||
res.diag = append(res.diag, incomplete("%s is no file git can blame", shown(file)))
|
||||
return nil, res, nil
|
||||
}
|
||||
// A file the line already has as the original makes it builds on
|
||||
// nothing the line lacks, whoever wrote the lines it replaced.
|
||||
if v.o.merge != "" && cur.oid != pre.oid {
|
||||
post, err := treeEntries(v.o.merge, []string{file})
|
||||
if err != nil {
|
||||
return nil, res, err
|
||||
}
|
||||
if p1, ok := post[file]; ok && p1.regular() {
|
||||
if cur.oid == p1.oid {
|
||||
return nil, res, nil
|
||||
}
|
||||
applied, _, err := b.alreadyApplied(pre.oid, cur.oid, p1.oid)
|
||||
if err != nil {
|
||||
return nil, res, err
|
||||
}
|
||||
if applied {
|
||||
return nil, res, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, oid := range []string{pre.oid, cur.oid} {
|
||||
out, err := git("cat-file", "-s", oid)
|
||||
if err != nil {
|
||||
return nil, res, err
|
||||
}
|
||||
size, err := strconv.Atoi(strings.TrimSpace(out))
|
||||
if err != nil {
|
||||
return nil, res, fmt.Errorf("git cat-file -s %s: %q is no size", oid, terminalSafe(out))
|
||||
}
|
||||
if size > maxDepBlob {
|
||||
res.diag = append(res.diag, incomplete("%s is larger than %d bytes", shown(file), maxDepBlob))
|
||||
return nil, res, nil
|
||||
}
|
||||
}
|
||||
diff, err := gitTimed("--literal-pathspecs", "diff", "--no-ext-diff", "--no-textconv", "--no-renames", "-U0", "--end-of-options", parent, v.o.merge, "--", file)
|
||||
if errors.Is(err, errDeadline) {
|
||||
res.diag = append(res.diag, incomplete("%s, diffing %s", err, shown(file)))
|
||||
return nil, res, nil
|
||||
} else if err != nil {
|
||||
return nil, res, err
|
||||
}
|
||||
ranges, binary, err := oldRanges(diff)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, res, fmt.Errorf("the diff of %s in #%d: %w", shown(file), v.o.number, err)
|
||||
case binary:
|
||||
res.diag = append(res.diag, incomplete("%s is binary", shown(file)))
|
||||
return nil, res, nil
|
||||
case len(ranges) == 0:
|
||||
return nil, res, nil
|
||||
}
|
||||
blobs, err := readObjects([]string{pre.oid, cur.oid}, "blob")
|
||||
if err != nil {
|
||||
return nil, res, err
|
||||
}
|
||||
skip, whole, ok := generatedLines(file, blobs[pre.oid])
|
||||
switch {
|
||||
case whole:
|
||||
return nil, res, nil
|
||||
case !ok:
|
||||
res.diag = append(res.diag, incomplete("%s, whose generated keys could not be told apart", shown(file)))
|
||||
return nil, res, nil
|
||||
}
|
||||
var kept []hunk
|
||||
for _, r := range ranges {
|
||||
for n := r.start; n < r.start+r.count; n++ {
|
||||
if skip[n] {
|
||||
continue
|
||||
}
|
||||
if l := len(kept) - 1; l >= 0 && kept[l].start+kept[l].count == n {
|
||||
kept[l].count++
|
||||
} else {
|
||||
kept = append(kept, hunk{n, 1})
|
||||
}
|
||||
res.lines++
|
||||
}
|
||||
}
|
||||
if res.lines > budget {
|
||||
res.diag = append(res.diag, incomplete("more than %d lines to blame", maxBlamedLines))
|
||||
res.capped = true
|
||||
return nil, res, nil
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
return nil, res, nil
|
||||
}
|
||||
args, err := blameArgs(parent, file, kept)
|
||||
if err != nil {
|
||||
return nil, res, err
|
||||
}
|
||||
out, err := gitTimed(args...)
|
||||
if errors.Is(err, errDeadline) {
|
||||
res.diag = append(res.diag, incomplete("%s, blaming %s", err, shown(file)))
|
||||
return nil, res, nil
|
||||
} else if err != nil {
|
||||
return nil, res, err
|
||||
}
|
||||
lines, err := parseBlame(out)
|
||||
if err != nil {
|
||||
return nil, res, fmt.Errorf("blaming %s for #%d: %w", shown(file), v.o.number, err)
|
||||
}
|
||||
onTarget := trimmedLines(blobs[cur.oid])
|
||||
found := map[string]bool{}
|
||||
unmapped := false
|
||||
for _, ln := range lines {
|
||||
merge, inRange := b.brought[ln.commit]
|
||||
switch {
|
||||
case !inRange:
|
||||
// An ancestor of the line's fork point, which the line has, or
|
||||
// a commit main does not have at all.
|
||||
before, err := b.beforeBase(ln.commit)
|
||||
if err != nil {
|
||||
return nil, res, err
|
||||
}
|
||||
unmapped = unmapped || !before
|
||||
case merge == v.o.merge:
|
||||
case !onTarget[strings.TrimSpace(ln.text)]:
|
||||
found[merge] = true
|
||||
}
|
||||
}
|
||||
if unmapped {
|
||||
res.diag = append(res.diag, incomplete("git blame gives lines of %s to a commit that did not come through main", shown(file)))
|
||||
}
|
||||
return found, res, nil
|
||||
}
|
||||
|
||||
// timed adds what has passed since start to the time the detector took.
|
||||
func (b *batch) timed(start time.Time) { b.detecting += time.Since(start) }
|
||||
|
||||
// beforeBase says whether commit is an ancestor of the line's fork point,
|
||||
// once per commit.
|
||||
func (b *batch) beforeBase(commit string) (bool, error) {
|
||||
if ok, seen := b.ancestors[commit]; seen {
|
||||
return ok, nil
|
||||
}
|
||||
ok, err := isAncestor(commit, b.base)
|
||||
if err == nil {
|
||||
if b.ancestors == nil {
|
||||
b.ancestors = map[string]bool{}
|
||||
}
|
||||
b.ancestors[commit] = ok
|
||||
}
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// analyze reads what every original the policy takes and nothing carries
|
||||
// builds on that the line lacks, and keeps it with the original, for the
|
||||
// parks and waits that follow from it.
|
||||
func (b *batch) analyze() error {
|
||||
defer b.timed(time.Now())
|
||||
for _, v := range b.qualifying() {
|
||||
if v.onBatch != "" {
|
||||
continue
|
||||
}
|
||||
deps, diag, err := b.dependencies(v, b.lineHead)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v.deps = deps
|
||||
v.addDiag(diag...)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// analysisMode is how a classification treats an original that changes a
|
||||
// workflow: as the scheduled run does, whose token cannot push one, or as a
|
||||
// maintainer's run.
|
||||
type analysisMode struct{ noWorkflowFiles bool }
|
||||
|
||||
// edgeClass is what a prerequisite is to an original that builds on it,
|
||||
// from what never matters to what decides first.
|
||||
type edgeClass int
|
||||
|
||||
const (
|
||||
edgeSatisfied edgeClass = iota
|
||||
// edgeNewer is held by rule 6 on this line.
|
||||
edgeNewer
|
||||
// edgeDeferred is a deferred conflict, or deferred for a reason.
|
||||
edgeDeferred
|
||||
// edgeWorkflow waits on the open batch for a maintainer.
|
||||
edgeWorkflow
|
||||
// edgeMissing is on neither the line, the batch nor the record.
|
||||
edgeMissing
|
||||
// edgeNever never reaches the line.
|
||||
edgeNever
|
||||
)
|
||||
|
||||
// edge is a dependency whose prerequisite has not reached the line, with
|
||||
// what that prerequisite is.
|
||||
type edge struct {
|
||||
dep dependency
|
||||
class edgeClass
|
||||
}
|
||||
|
||||
// ruleClass is what the rules alone make of a prerequisite, or ok false when
|
||||
// it depends on what this classification makes of it: one the line or the
|
||||
// open batch carries is there, whatever its label, drop or rule says, and a
|
||||
// direct push and an original the rules keep out never come.
|
||||
func (b *batch) ruleClass(f *verdict) (edgeClass, bool) {
|
||||
switch {
|
||||
case f == nil:
|
||||
return edgeNever, true
|
||||
case f.rule == ruleOnLine || f.onBatch != "" || f.batched != "" || b.lineCarries[f]:
|
||||
return edgeSatisfied, true
|
||||
case f.rule == ruleNewer:
|
||||
return edgeNewer, true
|
||||
case f.rule != 0:
|
||||
return edgeNever, true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// edges sorts dependencies by what classOf says of each prerequisite into
|
||||
// those that never come and those still to come, dropping the ones there.
|
||||
func edges(deps []dependency, classOf func(*verdict) edgeClass) (never, pending []edge) {
|
||||
for _, d := range deps {
|
||||
switch c := classOf(d.v); c {
|
||||
case edgeSatisfied:
|
||||
case edgeNever:
|
||||
never = append(never, edge{d, c})
|
||||
default:
|
||||
pending = append(pending, edge{d, c})
|
||||
}
|
||||
}
|
||||
return never, pending
|
||||
}
|
||||
|
||||
// strongest is the class of prerequisite that decides a wait, and the
|
||||
// prerequisites of that class, in merge order.
|
||||
func strongest(pending []edge) (edgeClass, []*verdict) {
|
||||
top := edgeSatisfied
|
||||
for _, e := range pending {
|
||||
top = max(top, e.class)
|
||||
}
|
||||
var out []*verdict
|
||||
for _, e := range pending {
|
||||
if e.class == top && !slices.Contains(out, e.dep.v) {
|
||||
out = append(out, e.dep.v)
|
||||
}
|
||||
}
|
||||
return top, out
|
||||
}
|
||||
|
||||
// auxiliary says whether a path holds tests or documentation, which an
|
||||
// original can change without building on what it needs to work.
|
||||
func auxiliary(p string) bool {
|
||||
parts := strings.Split(p, "/")
|
||||
base := parts[len(parts)-1]
|
||||
for _, d := range parts[:len(parts)-1] {
|
||||
if d == "test" || d == "tests" || d == "testdata" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(base, "_test.go"), strings.Contains(base, ".test."), strings.Contains(base, ".spec."), strings.HasSuffix(base, ".bats"):
|
||||
return true
|
||||
case len(parts) > 1 && parts[0] == "docs":
|
||||
return true
|
||||
}
|
||||
return len(parts) == 1 && strings.HasSuffix(base, ".md")
|
||||
}
|
||||
|
||||
// workflowPrimary says whether v waits for a maintainer rather than parks:
|
||||
// in the scheduled mode, an original that changes a workflow, all of whose
|
||||
// missing dependencies that never come are tests or docs, and whose
|
||||
// workflow lines build on nothing still missing. The workflow is what it is
|
||||
// for, and a maintainer brings over what applies. Only what is still
|
||||
// missing counts: never and pending are what is left once what is there was
|
||||
// taken out.
|
||||
func workflowPrimary(mode analysisMode, v *verdict, never, pending []edge) (bool, error) {
|
||||
if !mode.noWorkflowFiles || len(never) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
for _, e := range never {
|
||||
if slices.ContainsFunc(e.dep.paths, func(p string) bool { return !auxiliary(p) }) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
for _, e := range append(slices.Clone(never), pending...) {
|
||||
if slices.ContainsFunc(e.dep.paths, func(p string) bool { return strings.HasPrefix(p, workflowsDir) }) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
files, err := workflowFiles(v.commits)
|
||||
return len(files) > 0, err
|
||||
}
|
||||
|
||||
// testsOnly is the note a workflow original gets that waits for a
|
||||
// maintainer although its tests build on what never comes.
|
||||
func testsOnly(v *verdict, never []edge, l line) string {
|
||||
var who []string
|
||||
for _, e := range never {
|
||||
if e.dep.v != nil {
|
||||
who = append(who, fmt.Sprintf("#%d", e.dep.v.o.number))
|
||||
} else {
|
||||
who = append(who, e.dep.merge[:12])
|
||||
}
|
||||
}
|
||||
slices.Sort(who)
|
||||
return oneLineText(fmt.Sprintf("only its tests or docs build on %s, which never reaches %s", strings.Join(slices.Compact(who), ", "), l.branch()))
|
||||
}
|
||||
|
||||
// dependencyPark is the park of v for prerequisites that never come.
|
||||
func dependencyPark(v *verdict, never []edge) *parkedEntry {
|
||||
p := &parkedEntry{Original: v.o.number, Merge: v.o.merge, Kind: parkDependency}
|
||||
for _, e := range never {
|
||||
if e.dep.v != nil {
|
||||
p.Needs = append(p.Needs, e.dep.v.o.number)
|
||||
} else {
|
||||
p.Commits = append(p.Commits, e.dep.merge)
|
||||
}
|
||||
}
|
||||
slices.Sort(p.Needs)
|
||||
p.Needs = slices.Compact(p.Needs)
|
||||
slices.Sort(p.Commits)
|
||||
p.Commits = slices.Compact(p.Commits)
|
||||
return p
|
||||
}
|
||||
|
||||
// depsAt is what v builds on that target lacks, read once per target: the
|
||||
// run asks again at its head once earlier picks moved the branch.
|
||||
func (b *batch) depsAt(v *verdict, target string) ([]dependency, error) {
|
||||
key := target + " " + v.o.merge
|
||||
if d, ok := b.depCache[key]; ok {
|
||||
return d, nil
|
||||
}
|
||||
deps, diag, err := b.dependencies(v, target)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.addDiag(diag...)
|
||||
if b.depCache == nil {
|
||||
b.depCache = map[string][]dependency{}
|
||||
}
|
||||
b.depCache[key] = deps
|
||||
return deps, nil
|
||||
}
|
||||
|
||||
// stateKind is what a classification makes of an original the policy takes
|
||||
// that nothing carries, in the order that decides it.
|
||||
type stateKind int
|
||||
|
||||
const (
|
||||
// stHeld is deferred for a reason a person gave.
|
||||
stHeld stateKind = iota + 1
|
||||
// stPartial would leave part of it without effect on the line.
|
||||
stPartial
|
||||
// stWorkflowPrimary waits for a maintainer, though its tests build on
|
||||
// what never comes.
|
||||
stWorkflowPrimary
|
||||
// stParked builds on what never comes.
|
||||
stParked
|
||||
// stNeeds waits on prerequisites still to come.
|
||||
stNeeds
|
||||
// stOwn is what the record says of it, or missing.
|
||||
stOwn
|
||||
)
|
||||
|
||||
// state is a classification of one original: what it is, what it is to an
|
||||
// original that builds on it, and for a wait the class that decides it and
|
||||
// the prerequisites of that class.
|
||||
type state struct {
|
||||
kind stateKind
|
||||
class edgeClass
|
||||
wait edgeClass
|
||||
needs []*verdict
|
||||
}
|
||||
|
||||
// classify decides, in merge order, what becomes of every original the
|
||||
// policy takes that neither the line nor the open batch carries, as an
|
||||
// operation that picks nothing sees it: check, and the ones that only
|
||||
// change the record. held are the reasons people deferred originals for,
|
||||
// recorded what the record defers, and listed says the record's workflow
|
||||
// waits still wait on an open batch. Parks it finds go into each verdict.
|
||||
func (b *batch) classify(mode analysisMode, held map[int]string, recorded map[int]deferredEntry, listed bool) (map[*verdict]*state, error) {
|
||||
states := map[*verdict]*state{}
|
||||
classOf := func(f *verdict) edgeClass {
|
||||
if c, ok := b.ruleClass(f); ok {
|
||||
return c
|
||||
}
|
||||
if s := states[f]; s != nil {
|
||||
return s.class
|
||||
}
|
||||
return edgeMissing
|
||||
}
|
||||
for _, v := range b.qualifying() {
|
||||
if v.onBatch != "" {
|
||||
continue
|
||||
}
|
||||
s := &state{}
|
||||
states[v] = s
|
||||
e := recorded[v.o.number]
|
||||
never, pending := edges(v.deps, classOf)
|
||||
primary, err := workflowPrimary(mode, v, never, pending)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case held[v.o.number] != "":
|
||||
s.kind, s.class = stHeld, edgeDeferred
|
||||
case v.park != nil && v.park.Kind == parkPartial:
|
||||
s.kind, s.class = stPartial, edgeNever
|
||||
case primary:
|
||||
s.kind, s.class = stWorkflowPrimary, edgeMissing
|
||||
if listed && e.Workflows {
|
||||
s.class = edgeWorkflow
|
||||
}
|
||||
case len(never) > 0:
|
||||
v.park = dependencyPark(v, never)
|
||||
s.kind, s.class = stParked, edgeNever
|
||||
case len(pending) > 0:
|
||||
s.kind = stNeeds
|
||||
s.wait, s.needs = strongest(pending)
|
||||
s.class = s.wait
|
||||
case listed && e.Workflows:
|
||||
s.kind, s.class = stOwn, edgeWorkflow
|
||||
case !e.Workflows && len(e.Needs) == 0 && (e.Commit != "" || len(e.Files) > 0):
|
||||
s.kind, s.class = stOwn, edgeDeferred
|
||||
default:
|
||||
s.kind, s.class = stOwn, edgeMissing
|
||||
}
|
||||
}
|
||||
return states, nil
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// depsOf reads what original n builds on that the line lacks.
|
||||
func depsOf(t testing.TB, f *fixture, n int) ([]dependency, []string) {
|
||||
t.Helper()
|
||||
f.git("fetch", "-q", "origin")
|
||||
b, err := shapeOf(line11)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deps, diag, err := b.dependencies(b.find(n), b.lineHead)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return deps, diag
|
||||
}
|
||||
|
||||
// depNames lists dependencies as #N or a short commit, with their paths.
|
||||
func depNames(deps []dependency) []string {
|
||||
var out []string
|
||||
for _, d := range deps {
|
||||
who := d.merge[:12]
|
||||
if d.v != nil {
|
||||
who = fmt.Sprintf("#%d", d.v.o.number)
|
||||
}
|
||||
out = append(out, fmt.Sprintf("%s %v %v", who, d.paths, d.added))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Every commit main gained since the line branched is brought by one commit
|
||||
// of its first-parent line: a pull request's own commits by its merge, a
|
||||
// direct push by itself, and a commit from before the fork point by none.
|
||||
func TestBroughtBy(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
base := f.git("rev-parse", "origin/release-1.1")
|
||||
mc3 := f.prCommits(3, "feat(app): three", "",
|
||||
change{files: map[string]string{"app/3.txt": "3\n"}},
|
||||
change{mergeMain: true},
|
||||
change{files: map[string]string{"app/3.txt": "3b\n"}})
|
||||
f.write("app/push.txt", "pushed\n")
|
||||
f.git("add", "-A")
|
||||
f.git("commit", "-q", "-m", "chore: a direct push")
|
||||
f.git("push", "-q", "origin", "main")
|
||||
push := f.git("rev-parse", "HEAD")
|
||||
mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
by, err := broughtBy(base, mc5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
moved := f.git("rev-parse", mc3+"^1")
|
||||
for _, c := range strings.Fields(f.git("rev-list", mc3+"^1.."+mc3+"^2")) {
|
||||
if c == moved {
|
||||
continue
|
||||
}
|
||||
if by[c] != mc3 {
|
||||
t.Errorf("%.12s, a commit of #3's branch, is brought by %.12s, want #3's merge", c, by[c])
|
||||
}
|
||||
}
|
||||
for c, want := range map[string]string{mc3: mc3, moved: moved, push: push, mc5: mc5, f.git("rev-parse", mc5+"^2"): mc5} {
|
||||
if by[c] != want {
|
||||
t.Errorf("%.12s is brought by %.12s, want %.12s", c, by[c], want)
|
||||
}
|
||||
}
|
||||
if _, ok := by[base]; ok {
|
||||
t.Errorf("the fork point %.12s is in the map", base)
|
||||
}
|
||||
}
|
||||
|
||||
// V1: a file the original changes that the line does not have names the
|
||||
// first-parent commit on main that added it, a merge or a direct push.
|
||||
func TestDependenciesV1(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): x", "", map[string]string{"app/x.txt": appFile})
|
||||
f.write("app/y.txt", appFile)
|
||||
f.git("add", "-A")
|
||||
f.git("commit", "-q", "-m", "chore: y, pushed")
|
||||
f.git("push", "-q", "origin", "main")
|
||||
push := f.git("rev-parse", "HEAD")
|
||||
f.pr(5, "fix(app): fix x and y", "", map[string]string{"app/x.txt": "fixed\n", "app/y.txt": "fixed\n"})
|
||||
deps, diag := depsOf(t, f, 5)
|
||||
want := []string{push[:12] + " [app/y.txt] true", "#3 [app/x.txt] true"}
|
||||
slices.Sort(want)
|
||||
got := depNames(deps)
|
||||
slices.Sort(got)
|
||||
if !slices.Equal(got, want) || len(diag) != 0 {
|
||||
t.Errorf("dependencies = %q, %q; want %q", got, diag, want)
|
||||
}
|
||||
}
|
||||
|
||||
// v2World gives the line app/a.txt as the base had it, and main a feat that
|
||||
// changes its second line and a fix of that same line.
|
||||
func v2World(t testing.TB, onLine string) *fixture {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
if onLine != "" {
|
||||
f.onLine("release-1.1", "fix(app): a, by hand", map[string]string{"app/a.txt": onLine})
|
||||
}
|
||||
f.pr(3, "feat(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(5, "fix(app): an excited two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
return f
|
||||
}
|
||||
|
||||
// V2c: a line the original changes that blame gives to another original is
|
||||
// a dependency only while the line's file lacks that line's text.
|
||||
func TestDependenciesV2c(t *testing.T) {
|
||||
if deps, diag := depsOf(t, v2World(t, ""), 5); !slices.Equal(depNames(deps), []string{"#3 [app/a.txt] false"}) || len(diag) != 0 {
|
||||
t.Errorf("dependencies = %q, %q; want #3 through app/a.txt", depNames(deps), diag)
|
||||
}
|
||||
if deps, _ := depsOf(t, v2World(t, strings.Replace(appFile, "two", "TWO", 1)), 5); len(deps) != 0 {
|
||||
t.Errorf("dependencies with #3's line on the line by hand = %q; want none", depNames(deps))
|
||||
}
|
||||
}
|
||||
|
||||
// The content check trims a line's edges and nothing else: a reindented line
|
||||
// is there, a line with a space inside it is not.
|
||||
func TestDependenciesTrimOnlyEdges(t *testing.T) {
|
||||
if deps, _ := depsOf(t, v2World(t, strings.Replace(appFile, "two", " TWO\t", 1)), 5); len(deps) != 0 {
|
||||
t.Errorf("dependencies with #3's line reindented = %q; want none", depNames(deps))
|
||||
}
|
||||
if deps, _ := depsOf(t, v2World(t, strings.Replace(appFile, "two", "T WO", 1)), 5); !slices.Equal(depNames(deps), []string{"#3 [app/a.txt] false"}) {
|
||||
t.Errorf("dependencies with a space inside #3's line = %q; want #3", depNames(deps))
|
||||
}
|
||||
}
|
||||
|
||||
// Lines a tool wrote are not blamed: a generated file whole, and the keys
|
||||
// hack/update-crd.sh writes into an ApplicationDefinition, while the keys a
|
||||
// person writes there are.
|
||||
func TestDependenciesSkipGeneratedRanges(t *testing.T) {
|
||||
const rd = "packages/system/app-rd/cozyrds/app.yaml"
|
||||
rdFile := func(schema, category string) string {
|
||||
return "apiVersion: cozystack.io/v1alpha1\nkind: ApplicationDefinition\nmetadata:\n name: app\nspec:\n application:\n kind: App\n openAPISchema: |-\n {\"v\":" + schema + "}\n dashboard:\n category: " + category + "\n keysOrder: [[\"spec\", \"" + schema + "\"]]\n"
|
||||
}
|
||||
world := func(t *testing.T, before, feat, fix map[string]string) *fixture {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: generated files", "", before)
|
||||
f.lines()
|
||||
f.pr(3, "feat(api): regenerate", "", feat)
|
||||
f.pr(5, "fix(api): regenerate again", "", fix)
|
||||
return f
|
||||
}
|
||||
gen := "// Code generated by controller-gen. DO NOT EDIT.\n\npackage v1\n\nvar a = 1\n"
|
||||
f := world(t,
|
||||
map[string]string{"api/zz_generated.deepcopy.go": "package v1\n\nvar a = 1\n", "api/types_gen.go": gen, rd: rdFile("1", "A")},
|
||||
map[string]string{"api/zz_generated.deepcopy.go": "package v1\n\nvar a = 2\n", "api/types_gen.go": strings.Replace(gen, "= 1", "= 2", 1), rd: rdFile("2", "A")},
|
||||
map[string]string{"api/zz_generated.deepcopy.go": "package v1\n\nvar a = 3\n", "api/types_gen.go": strings.Replace(gen, "= 1", "= 3", 1), rd: rdFile("3", "A")})
|
||||
if deps, diag := depsOf(t, f, 5); len(deps) != 0 || len(diag) != 0 {
|
||||
t.Errorf("dependencies through generated lines = %q, %q; want none", depNames(deps), diag)
|
||||
}
|
||||
f = world(t, map[string]string{rd: rdFile("1", "A")}, map[string]string{rd: rdFile("2", "B")}, map[string]string{rd: rdFile("3", "C")})
|
||||
if deps, _ := depsOf(t, f, 5); !slices.Equal(depNames(deps), []string{"#3 [" + rd + "] false"}) {
|
||||
t.Errorf("dependencies through a key a person writes = %q; want #3", depNames(deps))
|
||||
}
|
||||
}
|
||||
|
||||
// Evidence the detector cannot read, a binary file or a symlink, is a
|
||||
// diagnostic and never a dependency.
|
||||
func TestDependenciesIncompleteNeverParks(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: an image", "", map[string]string{"app/a.bin": "a\x00one"})
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): a new image", "", map[string]string{"app/a.bin": "a\x00two"})
|
||||
f.pr(5, "fix(app): a fixed image", "", map[string]string{"app/a.bin": "a\x00three"})
|
||||
if deps, diag := depsOf(t, f, 5); len(deps) != 0 || !slices.Equal(diag, []string{`incomplete evidence: "app/a.bin" is binary`}) {
|
||||
t.Errorf("dependencies = %q, %q; want none and a diagnostic", depNames(deps), diag)
|
||||
}
|
||||
}
|
||||
|
||||
// Output of git the detector cannot read whole is an error, never taken
|
||||
// for an absent dependency.
|
||||
func TestDependenciesMalformedOutputIsAnError(t *testing.T) {
|
||||
sha := strings.Repeat("a", 40)
|
||||
for name, out := range map[string]string{
|
||||
"a short header": sha + " 1\n\tline\n",
|
||||
"a header of no commit": "aaaa 1 1 1\n\tline\n",
|
||||
"a header of no number": sha + " x 1 1\n\tline\n",
|
||||
"a line with no header": "\tline\n",
|
||||
"a header with no line": sha + " 1 1 1\nauthor x\n",
|
||||
} {
|
||||
if _, err := parseBlame(out); err == nil {
|
||||
t.Errorf("%s: parseBlame accepted %q", name, out)
|
||||
}
|
||||
}
|
||||
if lines, err := parseBlame(sha + " 2 2 1\nauthor x\nfilename a\n\ttwo\n" + sha + " 4 4\n\tfour\n"); err != nil || len(lines) != 2 || lines[1].text != "four" {
|
||||
t.Errorf("parseBlame of sound output = %+v, %v", lines, err)
|
||||
}
|
||||
if _, _, err := oldRanges("@@ -x +1 @@\n"); err == nil {
|
||||
t.Error("oldRanges accepted an unreadable hunk header")
|
||||
}
|
||||
}
|
||||
|
||||
// Paths go to git as they are: a name a pathspec would read as a pattern
|
||||
// means only itself.
|
||||
func TestDependenciesLiteralPaths(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): a bracketed file", "", map[string]string{"app/[x].txt": appFile})
|
||||
f.pr(4, "feat(app): x", "", map[string]string{"app/x.txt": appFile})
|
||||
f.pr(5, "fix(app): fix the bracketed file", "", map[string]string{"app/[x].txt": "fixed\n"})
|
||||
if deps, _ := depsOf(t, f, 5); !slices.Equal(depNames(deps), []string{"#3 [app/[x].txt] true"}) {
|
||||
t.Errorf("dependencies = %q; want #3 alone", depNames(deps))
|
||||
}
|
||||
}
|
||||
|
||||
// A file with no final newline blames its last line like any other.
|
||||
func TestDependenciesNoFinalNewline(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a", "", map[string]string{"app/a.txt": "one\ntwo"})
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): a loud two", "", map[string]string{"app/a.txt": "one\nTWO"})
|
||||
f.pr(5, "fix(app): an excited two", "", map[string]string{"app/a.txt": "one\nTWO!"})
|
||||
if deps, diag := depsOf(t, f, 5); !slices.Equal(depNames(deps), []string{"#3 [app/a.txt] false"}) || len(diag) != 0 {
|
||||
t.Errorf("dependencies = %q, %q; want #3", depNames(deps), diag)
|
||||
}
|
||||
}
|
||||
|
||||
// Blame takes the revision as a full commit name, which git cannot read as
|
||||
// an option, and refuses --end-of-options, so the tool passes none.
|
||||
func TestBlameInvocation(t *testing.T) {
|
||||
sha := strings.Repeat("a", 40)
|
||||
args, err := blameArgs(sha, "-x", []hunk{{2, 3}, {9, 1}})
|
||||
if want := []string{"blame", "--porcelain", "-w", "-L", "2,+3", "-L", "9,+1", sha, "--", "-x"}; err != nil || !slices.Equal(args, want) {
|
||||
t.Errorf("blameArgs = %q, %v; want %q", args, err, want)
|
||||
}
|
||||
for _, rev := range []string{"HEAD", "--output=x", strings.Repeat("a", 39)} {
|
||||
if _, err := blameArgs(rev, "a", nil); err == nil {
|
||||
t.Errorf("blameArgs took %q for a revision", rev)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What the detector could not read shows with the original whatever became
|
||||
// of it: picked, waiting for a maintainer, or a deferred conflict, in the
|
||||
// body and in the report.
|
||||
func TestDiagnosticsShowOnEveryOutcome(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: images", "", map[string]string{"app/p.bin": "p\x00one", "app/w.bin": "w\x00one", "app/c.bin": "c\x00one", "app/c.txt": "old\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): c, on the line", map[string]string{"app/c.txt": "line\n"})
|
||||
f.pr(5, "fix(app): picked", "", map[string]string{"app/p.bin": "p\x00two"})
|
||||
f.pr(6, "fix(ci): waiting", "", map[string]string{"app/w.bin": "w\x00two", ".github/workflows/six.yaml": "on: push\n"})
|
||||
f.pr(7, "fix(app): conflicting", "", map[string]string{"app/c.bin": "c\x00two", "app/c.txt": "seven\n"})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1", "--no-workflow-files")
|
||||
if code != 0 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
for _, s := range []struct{ section, file string }{{"[#5]", "p.bin"}, {"### Deferred conflicts", "c.bin"}, {"### Waiting for a maintainer", "w.bin"}} {
|
||||
_, after, ok := strings.Cut(stdout, s.section)
|
||||
if want := " - `incomplete evidence: \"app/" + s.file + "\" is binary`"; !ok || !strings.Contains(after, want) {
|
||||
t.Errorf("the body does not show %q after %s:\n%s", want, s.section, stdout)
|
||||
}
|
||||
}
|
||||
for n, file := range map[int]string{5: "p.bin", 6: "w.bin", 7: "c.bin"} {
|
||||
if want := fmt.Sprintf(`"%d":["incomplete evidence: \"app/%s\" is binary"]`, n, file); !strings.Contains(stdout, want) {
|
||||
t.Errorf("the report lacks %s:\n%s", want, stdout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkAnalyze reads what forty originals build on, over a history
|
||||
// where half of them build on a feat the line lacks.
|
||||
func BenchmarkAnalyze(b *testing.B) {
|
||||
f := newFixture(b)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
for n := 10; n < 50; n++ {
|
||||
file := fmt.Sprintf("app/f%d.txt", n)
|
||||
if n%2 == 0 {
|
||||
f.pr(n, "feat(app): "+file, "", map[string]string{file: appFile})
|
||||
continue
|
||||
}
|
||||
prev := fmt.Sprintf("app/f%d.txt", n-1)
|
||||
f.pr(n, "fix(app): "+prev, "", map[string]string{prev: strings.Replace(appFile, "two", fmt.Sprint(n), 1), "app/a.txt": strings.Replace(appFile, "three", fmt.Sprint(n), 1)})
|
||||
}
|
||||
f.git("fetch", "-q", "origin")
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
bt, err := shapeOf(line11)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if err := bt.analyze(); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Files the line lacks count toward the files an original may have read
|
||||
// for it, like the ones blamed.
|
||||
func TestDependenciesCapMissingFiles(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
added, fixed := map[string]string{}, map[string]string{}
|
||||
for i := range maxDepFiles + 1 {
|
||||
added[fmt.Sprintf("app/f%03d.txt", i)] = "v1\n"
|
||||
fixed[fmt.Sprintf("app/f%03d.txt", i)] = "v2\n"
|
||||
}
|
||||
f.pr(3, "feat(app): many files", "", added)
|
||||
f.pr(5, "fix(app): all of them", "", fixed)
|
||||
if _, diag := depsOf(t, f, 5); !slices.ContainsFunc(diag, func(d string) bool { return strings.Contains(d, fmt.Sprintf("more than %d files", maxDepFiles)) }) {
|
||||
t.Errorf("diag = %q, want the file cap", diag)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A drop is a maintainer's decision that an original stays off one line,
|
||||
// for a reason, where the rules would take it. It is kept in the line's
|
||||
// record and carried from batch to batch, bound to the original's merge
|
||||
// commit on main, so a record cannot point it at another original. It is
|
||||
// written only to the open batch's record, like everything else there.
|
||||
|
||||
// onLine says whether the line carries v, whatever rule decided it.
|
||||
func (b *batch) onLine(v *verdict) (bool, error) {
|
||||
if v.rule == ruleOnLine {
|
||||
return true, nil
|
||||
}
|
||||
if err := b.load(v); err != nil {
|
||||
return false, err
|
||||
}
|
||||
how, err := b.lineHist.carries(v.o, v.commits)
|
||||
return how != "", err
|
||||
}
|
||||
|
||||
// carried says whether the open batch has a unit of v, by the mapping the
|
||||
// rebuild takes units off with: found needs every commit of a merged
|
||||
// original, and one whose pick came out empty is missing from it.
|
||||
func (b *batch) carried(v *verdict) (bool, error) {
|
||||
units, err := batchUnits(b.prHead, b.lineHead)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, u := range units {
|
||||
if o := b.unitOriginal(u); o != nil && o.o.number == v.o.number {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// redrop drops the originals in numbers from the line, for reason, or with
|
||||
// undrop withdraws their drops. What the open batch carries of a dropped
|
||||
// original comes off it, as --defer takes it off; otherwise only the record
|
||||
// changes, and the batch stays as it is even when the line moved since.
|
||||
func (a *app) redrop(b *batch, numbers []int, reason string, undrop bool, push bool) int {
|
||||
if !b.src.open {
|
||||
return a.fail(fmt.Errorf("no open batch pull request on %s carries a record; a drop is recorded on one", b.line.branch()))
|
||||
}
|
||||
drops := map[int]droppedEntry{}
|
||||
for _, d := range b.src.rec.Dropped {
|
||||
drops[d.Original] = d
|
||||
}
|
||||
mode, today := modeDrop, a.now().UTC().Format(time.DateOnly)
|
||||
if undrop {
|
||||
mode = modeUndrop
|
||||
}
|
||||
for _, n := range numbers {
|
||||
v := b.find(n)
|
||||
_, isDropped := drops[n]
|
||||
switch {
|
||||
case undrop && !isDropped:
|
||||
return a.fail(fmt.Errorf("#%d is not dropped from %s", n, b.line.branch()))
|
||||
case undrop:
|
||||
delete(drops, n)
|
||||
case v == nil:
|
||||
return a.fail(fmt.Errorf("#%d did not merge into main after %s branched", n, b.line.branch()))
|
||||
default:
|
||||
// backport/skip and rules 1 to 4 decide before the line is
|
||||
// looked at, so whether it carries the original is asked here.
|
||||
on, err := b.onLine(v)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if on {
|
||||
return a.fail(fmt.Errorf("#%d is already on %s; a drop cannot remove code the line has", n, b.line.branch()))
|
||||
}
|
||||
drops[n] = droppedEntry{Original: n, Merge: v.o.merge, Reason: reason, On: b.pr.Number, Date: today}
|
||||
}
|
||||
}
|
||||
active := map[int]droppedEntry{}
|
||||
for n, d := range drops {
|
||||
if b.find(n) != nil {
|
||||
active[n] = d
|
||||
}
|
||||
}
|
||||
b.drops = active
|
||||
out := map[int]string{}
|
||||
for _, n := range numbers {
|
||||
v := b.find(n)
|
||||
if v == nil {
|
||||
continue
|
||||
}
|
||||
if err := b.judge(v, active); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if err := b.load(v); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if err := b.rejudged(v); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if undrop {
|
||||
continue
|
||||
}
|
||||
on, err := b.carried(v)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if on {
|
||||
out[n] = "dropped"
|
||||
}
|
||||
}
|
||||
hold := map[int]string{}
|
||||
for n, e := range b.recorded() {
|
||||
if e.Reason != "" {
|
||||
hold[n] = e.Reason
|
||||
}
|
||||
}
|
||||
list := slices.SortedFunc(maps.Values(drops), func(x, y droppedEntry) int { return cmp.Compare(x.Original, y.Original) })
|
||||
if len(out) > 0 {
|
||||
maps.Copy(out, hold)
|
||||
return a.reassemble(b, out, hold, list, mode, push)
|
||||
}
|
||||
if err := a.warnReset(b.pr.Head.Ref, b.prHead); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if _, err := git("switch", "--quiet", "--no-track", "-C", b.pr.Head.Ref, "--end-of-options", b.prHead); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
return a.reclassify(b, b.picks, hold, list, mode, push)
|
||||
}
|
||||
|
||||
// bindDrops holds each drop the record keeps to the original it names: a
|
||||
// drop of an original merged since the line branched has to name that
|
||||
// original's merge commit, and one of an earlier original a merge of it on
|
||||
// main's first-parent line. The first apply; the others are kept and carried
|
||||
// on, and decide nothing.
|
||||
func (b *batch) bindDrops(merges []*original) (map[int]droppedEntry, error) {
|
||||
return bindEntries(b.src.rec.dropped(), merges, b.mainHead, func(d droppedEntry) string {
|
||||
return fmt.Sprintf("batch pull request #%d drops #%d by %.12s", b.src.carrier.Number, d.Original, d.Merge)
|
||||
})
|
||||
}
|
||||
|
||||
// waitOrder refuses a record whose waits or parks need an original merged
|
||||
// after the one that needs it: a dependency is always on main first.
|
||||
func (b *batch) waitOrder(merges []*original) error {
|
||||
if b.src.rec == nil {
|
||||
return nil
|
||||
}
|
||||
at := map[int]int{}
|
||||
for i, o := range merges {
|
||||
at[o.number] = i
|
||||
}
|
||||
check := func(n int, needs []int) error {
|
||||
i, ok := at[n]
|
||||
for _, f := range needs {
|
||||
if j, known := at[f]; ok && known && j >= i {
|
||||
return fmt.Errorf("batch pull request #%d has #%d wait on #%d, which merged after it", b.src.carrier.Number, n, f)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, d := range b.src.rec.Deferred {
|
||||
if err := check(d.Original, d.Needs); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, p := range b.src.rec.Parked {
|
||||
if err := check(p.Original, p.Needs); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// bindEntries binds drops to main: one whose original is among merges, the
|
||||
// originals main merged since the line branched, has to name that
|
||||
// original's merge exactly; any other has to be a merge of its number on
|
||||
// main's first-parent line up to mainHead, as an inherited drop is. It
|
||||
// returns the drops whose originals are among merges; about says what an
|
||||
// error is about.
|
||||
func bindEntries(drops []droppedEntry, merges []*original, mainHead string, about func(droppedEntry) string) (map[int]droppedEntry, error) {
|
||||
byMerge, byNumber := map[string]*original{}, map[int]*original{}
|
||||
for _, o := range merges {
|
||||
byMerge[o.merge], byNumber[o.number] = o, o
|
||||
}
|
||||
active := map[int]droppedEntry{}
|
||||
for _, d := range drops {
|
||||
at := about(d)
|
||||
if o := byMerge[d.Merge]; o != nil {
|
||||
if o.number != d.Original {
|
||||
return nil, fmt.Errorf("%s, which merged #%d", at, o.number)
|
||||
}
|
||||
active[d.Original] = d
|
||||
continue
|
||||
}
|
||||
if o := byNumber[d.Original]; o != nil {
|
||||
return nil, fmt.Errorf("%s, but #%d merged as %.12s", at, d.Original, o.merge)
|
||||
}
|
||||
ok, err := mergedOnMain(d.Merge, mainHead, d.Original)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s, which is no merge of it on main", at)
|
||||
}
|
||||
}
|
||||
return active, nil
|
||||
}
|
||||
|
||||
// bindDrops binds each drop a report keeps to main exactly as the record's
|
||||
// drops are bound, over the window the report classified: main and the
|
||||
// line at the heads it was made from. Its errors read after "report <id>".
|
||||
func (d *reportDoc) bindDrops() error {
|
||||
if len(d.Overlays.Dropped) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, h := range []struct{ name, head string }{{"main", d.Built.Main}, {d.Line, d.Built.Line}} {
|
||||
have, err := lookup(h.head)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if have == "" {
|
||||
return fmt.Errorf("was made on %s at %.12s, which this clone does not have; fetch %s and run again", h.name, h.head, h.name)
|
||||
}
|
||||
}
|
||||
out, err := git("merge-base", "--end-of-options", d.Built.Main, d.Built.Line)
|
||||
if err != nil {
|
||||
return fmt.Errorf("was made from a line that shares no history with main: %w", err)
|
||||
}
|
||||
merges, _, err := mainMerges(strings.TrimSpace(out), d.Built.Main)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
active, err := bindEntries(d.Overlays.Dropped, merges, d.Built.Main, func(e droppedEntry) string {
|
||||
return fmt.Sprintf("drops #%d by %.12s", e.Original, e.Merge)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// A drop decides only for an original the report classified, and only
|
||||
// once every earlier rule has passed it by; an inherited one decides
|
||||
// nothing.
|
||||
where, err := d.categories()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range d.Primary.Skipped.Dropped {
|
||||
if _, ok := active[n]; !ok {
|
||||
return fmt.Errorf("has #%d dropped, but no drop of it binds to an original it classified", n)
|
||||
}
|
||||
}
|
||||
for n := range active {
|
||||
switch c := where[n]; c {
|
||||
case "skipped.dropped", "skipped.skip-label", "skipped.before-start", "skipped.type", "skipped.breaking", "skipped.touches", "skipped.on-line":
|
||||
default:
|
||||
return fmt.Errorf("drops #%d, which it has %s, though a drop decides before that", n, or(c, "nowhere"))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mergedOnMain says whether merge is on main's first-parent line up to
|
||||
// mainHead and its message names pull request n, as mainMerges reads one.
|
||||
func mergedOnMain(merge, mainHead string, n int) (bool, error) {
|
||||
have, err := lookup(merge)
|
||||
if err != nil || have == "" {
|
||||
return false, err
|
||||
}
|
||||
if ok, err := isAncestor(merge, mainHead); err != nil || !ok {
|
||||
return false, err
|
||||
}
|
||||
line, err := revList("--first-parent", "--end-of-options", mainHead)
|
||||
if err != nil || !slices.Contains(line, merge) {
|
||||
return false, err
|
||||
}
|
||||
msgs, err := commitMessages([]string{merge})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
number, _, _ := mergedPR(msgs[merge].message)
|
||||
return number == n, nil
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// recordOf is the record the open batch #90 carries now.
|
||||
func recordOf(t *testing.T, gh *fakeGH) *lineRecord {
|
||||
t.Helper()
|
||||
rec, err := parseRecord(gh.find(90).Body, notifyLine)
|
||||
if err != nil || rec == nil {
|
||||
t.Fatalf("#90 carries no readable record: %v", err)
|
||||
}
|
||||
return rec
|
||||
}
|
||||
|
||||
func dropped(rec *lineRecord) []int {
|
||||
var out []int
|
||||
for _, d := range rec.Dropped {
|
||||
out = append(out, d.Original)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A drop takes a picked original off the batch and keeps it off the line:
|
||||
// a run that continues the batch does not pick it, and nor does the next
|
||||
// batch, which carries the drop over from the merged one.
|
||||
func TestDropTakesAnOriginalOffTheLine(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
mc6 := f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
stdout := mustRun(t, f, gh, "run", "--line", "release-1.1", "--drop", "6", "--reason", "needs the rework of #4", "--push")
|
||||
if got := f.subjects("origin/release-1.1", f.remoteHead(batchBranch1)); !slices.Equal(got, []string{"fix(app): five (#5)"}) {
|
||||
t.Errorf("after the drop the batch carries %q, want #5 alone", got)
|
||||
}
|
||||
rec := recordOf(t, gh)
|
||||
if want := (droppedEntry{Original: 6, Merge: mc6, Reason: "needs the rework of #4", On: 90, Date: "2026-10-26"}); len(rec.Dropped) != 1 || rec.Dropped[0] != want || rec.Built.Options.Mode != modeDrop {
|
||||
t.Errorf("the record drops %+v (%s), want %+v", rec.Dropped, rec.Built.Options.Mode, want)
|
||||
}
|
||||
if s := bodyReportOf(t, stdout); !slices.Equal(s.doc.Primary.Skipped.Dropped, []int{6}) || !slices.Equal(droppedNumbers(s.doc.Overlays.Dropped), []int{6}) {
|
||||
t.Errorf("the report has %v dropped and %v as the decision", s.doc.Primary.Skipped.Dropped, s.doc.Overlays.Dropped)
|
||||
}
|
||||
if !strings.Contains(stdout, "<details><summary>Dropped from `release-1.1` by a maintainer</summary>") {
|
||||
t.Errorf("the body does not list #6 as dropped:\n%s", stdout)
|
||||
}
|
||||
code, _, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut")
|
||||
if code != 1 || !strings.Contains(stderr, "note: #6 is dropped from release-1.1 on #90 (needs the rework of #4): https://github.com/cozystack/cozystack/pull/6 ") {
|
||||
t.Errorf("check --cut = %d, want #5 to fail it and a note on #6:\n%s", code, stderr)
|
||||
}
|
||||
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if got := f.subjects("origin/release-1.1", f.remoteHead(batchBranch1)); !slices.Equal(got, []string{"fix(app): five (#5)", "fix(app): seven (#7)"}) || !slices.Equal(dropped(recordOf(t, gh)), []int{6}) {
|
||||
t.Errorf("the continued batch carries %q and drops %v", got, dropped(recordOf(t, gh)))
|
||||
}
|
||||
|
||||
mergeBatch(f, gh)
|
||||
f.now = f.now.AddDate(0, 0, 3)
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
gh.nextPR = 91
|
||||
stdout = mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
rec, err := parseRecord(stdout, notifyLine)
|
||||
if got := f.subjects("origin/release-1.1", f.remoteHead("backport-batch/release-1.1-20261029")); err != nil || !slices.Equal(got, []string{"fix(app): eight (#8)"}) || !slices.Equal(dropped(rec), []int{6}) {
|
||||
t.Errorf("the next batch carries %q and drops %v (%v); want #8 alone, #6 still dropped", got, rec, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Dropping an original the batch does not carry changes only the record:
|
||||
// the batch is not rebuilt, so a line that moved since does not move it.
|
||||
func TestDropIsRecordOnlyWhenTheLineMoved(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): a line-only seven", map[string]string{"app/seven.txt": "line\n"})
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
gh := &fakeGH{}
|
||||
head := openBatch(t, f, gh)
|
||||
if recordOf(t, gh).deferred()[7].Commit == "" {
|
||||
t.Fatal("#7 is not a recorded conflict")
|
||||
}
|
||||
f.onLine("release-1.1", "fix(chart): a line-only value", map[string]string{"chart/values.yaml": "replicas: 3\nimage: app:1\n"})
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--drop", "7", "--reason", "needs #4", "--push")
|
||||
rec := recordOf(t, gh)
|
||||
if f.remoteHead(batchBranch1) != head || !slices.Equal(dropped(rec), []int{7}) || len(rec.deferred()) != 0 || len(gh.edited) != 1 {
|
||||
t.Errorf("the batch moved to %.12s (from %.12s), the record drops %v and defers %v; want only the record changed", f.remoteHead(batchBranch1), head, dropped(rec), rec.deferred())
|
||||
}
|
||||
}
|
||||
|
||||
// A drop is written to the open batch's record, and to no other: with no
|
||||
// batch open, or none ever, it is refused and nothing is written.
|
||||
func TestDropNeedsAnOpenBatch(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): a line-only seven", map[string]string{"app/seven.txt": "line\n"})
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
gh := &fakeGH{}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--drop", "5", "--reason", "r", "--push"); code != 2 || !strings.Contains(stderr, "no open batch pull request on release-1.1 carries a record; a drop is recorded on one") {
|
||||
t.Errorf("a drop on a line that never had a batch = %d:\n%s", code, stderr)
|
||||
}
|
||||
openBatch(t, f, gh)
|
||||
mergeBatch(f, gh)
|
||||
written := len(gh.edited) + len(gh.issueComments)
|
||||
for _, args := range [][]string{{"--drop", "7", "--reason", "r", "--push"}, {"--undrop", "7", "--push"}} {
|
||||
if code, _, stderr := f.exec(gh, append([]string{"run", "--line", "release-1.1"}, args...)...); code != 2 || !strings.Contains(stderr, "carries a record; a drop is recorded on one") {
|
||||
t.Errorf("%q after the batch merged = %d:\n%s", args, code, stderr)
|
||||
}
|
||||
}
|
||||
if len(gh.edited)+len(gh.issueComments) != written {
|
||||
t.Error("a refused drop wrote to GitHub")
|
||||
}
|
||||
}
|
||||
|
||||
// A drop is a decision kept beside whatever else decides an original: the
|
||||
// rule, label or carry that applies first is its category, and the drop
|
||||
// stays on record. backport/include does not lift it.
|
||||
func TestDropOverlay(t *testing.T) {
|
||||
setup := func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
f.pr(7, "feat(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
gh := &fakeGH{labels: map[string][]int{labelInclude: {7}}}
|
||||
openBatch(t, f, gh)
|
||||
return f, gh
|
||||
}
|
||||
category := func(t *testing.T, gh *fakeGH, n int) string {
|
||||
t.Helper()
|
||||
s := bodyReportOf(t, gh.find(90).Body)
|
||||
where, err := s.doc.categories()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return where[n]
|
||||
}
|
||||
merge := func(f *fixture, n int) string {
|
||||
mc, _, _ := strings.Cut(f.git("log", "--first-parent", "--format=%H", "--grep", fmt.Sprintf("(#%d)$", n), "main"), "\n")
|
||||
return mc
|
||||
}
|
||||
drop := func(t *testing.T, f *fixture, gh *fakeGH, n string) {
|
||||
t.Helper()
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--drop", n, "--reason", "not for 1.1", "--push")
|
||||
}
|
||||
t.Run("then backport/skip", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
drop(t, f, gh, "6")
|
||||
gh.labels[labelSkip] = []int{6}
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if got := category(t, gh, 6); got != "skipped.skip-label" || !slices.Equal(dropped(recordOf(t, gh)), []int{6}) {
|
||||
t.Errorf("#6 is %q, dropped %v", got, dropped(recordOf(t, gh)))
|
||||
}
|
||||
})
|
||||
t.Run("then picked onto the line by hand", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
drop(t, f, gh, "6")
|
||||
pickOnLine(f, 6, map[string]string{"app/six.txt": "6\n"})
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if got := category(t, gh, 6); got != "skipped.on-line" || !slices.Equal(dropped(recordOf(t, gh)), []int{6}) {
|
||||
t.Errorf("#6 is %q, dropped %v", got, dropped(recordOf(t, gh)))
|
||||
}
|
||||
})
|
||||
t.Run("a feat backport/include let in", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
drop(t, f, gh, "7")
|
||||
if got := category(t, gh, 7); got != "skipped.dropped" || slices.Contains(f.subjects("origin/release-1.1", f.remoteHead(batchBranch1)), "feat(app): seven (#7)") {
|
||||
t.Errorf("#7 is %q; want it dropped and off the batch", got)
|
||||
}
|
||||
if !strings.Contains(gh.find(90).Body, "`backport/include`, skipped by a maintainer's drop") {
|
||||
t.Errorf("the overrides do not say what became of #7:\n%s", gh.find(90).Body)
|
||||
}
|
||||
})
|
||||
t.Run("undropped", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
drop(t, f, gh, "6")
|
||||
head := f.remoteHead(batchBranch1)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--undrop", "6", "--push")
|
||||
if got := category(t, gh, 6); got != "missing" || len(recordOf(t, gh).Dropped) != 0 || f.remoteHead(batchBranch1) != head || recordOf(t, gh).Built.Options.Mode != modeUndrop {
|
||||
t.Errorf("#6 is %q, dropped %v; want it missing until the next run, the batch where it was", got, dropped(recordOf(t, gh)))
|
||||
}
|
||||
if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/6 ") {
|
||||
t.Errorf("check = %d, want #6 missing:\n%s", code, stdout)
|
||||
}
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if got := category(t, gh, 6); got != "picked" {
|
||||
t.Errorf("after the next run #6 is %q, want it picked again", got)
|
||||
}
|
||||
})
|
||||
t.Run("a new original during a change to the record alone", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
drop(t, f, gh, "7")
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--undrop", "7", "--push")
|
||||
if got := category(t, gh, 8); got != "missing" {
|
||||
t.Errorf("#8 is %q, want missing until a run tries it", got)
|
||||
}
|
||||
})
|
||||
// A stored drop is bound to the merge it names: one that names another
|
||||
// original's, or one of no merge of it, is refused; one of an original
|
||||
// merged before the line branched is kept and decides nothing.
|
||||
t.Run("a stored drop of an earlier commit that names the original", func(t *testing.T) {
|
||||
// Before release-1.1 branched, a commit on main already ended in
|
||||
// (#6); the drop has to name the merge of #6 the line can take.
|
||||
f := newFixture(t)
|
||||
f.release("release-1.0")
|
||||
f.tag("v1.0.0")
|
||||
early := f.squash(6, "docs: what six will change", "", map[string]string{"docs/six.md": "6\n"})
|
||||
f.release("release-1.1")
|
||||
f.tag("v1.1.0")
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
drop(t, f, gh, "6")
|
||||
gh.find(90).Body = strings.Replace(gh.find(90).Body, `{"original":6,"merge":"`+merge(f, 6)+`"`, `{"original":6,"merge":"`+early+`"`, 1)
|
||||
if code, _, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 2 || !strings.Contains(stderr, "but #6 merged as") {
|
||||
t.Errorf("check = %d, want 2 naming the merge of #6:\n%s", code, stderr)
|
||||
}
|
||||
})
|
||||
t.Run("a stored drop of a commit inside a pull request", func(t *testing.T) {
|
||||
// A commit of a pull request's own branch can end in its number too,
|
||||
// but only the merge on main's first-parent line is the original.
|
||||
f := newFixture(t)
|
||||
f.release("release-1.0")
|
||||
f.tag("v1.0.0")
|
||||
mc3 := f.prCommits(3, "feat(app): three", "", change{files: map[string]string{"app/three.txt": "3\n"}, message: "feat(app): the part of three (#3)"})
|
||||
inner := f.git("rev-parse", mc3+"^2")
|
||||
f.release("release-1.1")
|
||||
f.tag("v1.1.0")
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
drop(t, f, gh, "6")
|
||||
gh.find(90).Body = strings.Replace(gh.find(90).Body, `{"original":6,"merge":"`+merge(f, 6)+`"`, `{"original":3,"merge":"`+inner+`"`, 1)
|
||||
if code, _, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 2 || !strings.Contains(stderr, "which is no merge of it on main") {
|
||||
t.Errorf("check = %d, want 2:\n%s", code, stderr)
|
||||
}
|
||||
})
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
original func(f *fixture) (int, string)
|
||||
refused bool
|
||||
}{
|
||||
{"another original's merge", func(f *fixture) (int, string) { return 6, merge(f, 5) }, true},
|
||||
{"a commit that merged no pull request", func(f *fixture) (int, string) { return 6, f.git("rev-list", "--max-parents=0", "main") }, true},
|
||||
{"a merge from before the line branched, of another pull request", func(f *fixture) (int, string) { return 2, merge(f, 1) }, true},
|
||||
{"a merge from before the line branched", func(f *fixture) (int, string) { return 1, merge(f, 1) }, false},
|
||||
} {
|
||||
t.Run("a stored drop of "+tc.name, func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
drop(t, f, gh, "6")
|
||||
n, mc := tc.original(f)
|
||||
gh.find(90).Body = strings.Replace(gh.find(90).Body, `{"original":6,"merge":"`+merge(f, 6)+`"`, fmt.Sprintf(`{"original":%d,"merge":"%s"`, n, mc), 1)
|
||||
code, _, stderr := f.exec(gh, "check", "--line", "release-1.1")
|
||||
switch {
|
||||
case tc.refused && (code != 2 || !strings.Contains(stderr, fmt.Sprintf("drops #%d by %.12s", n, mc))):
|
||||
t.Errorf("check = %d, want 2 naming the drop:\n%s", code, stderr)
|
||||
case !tc.refused && code == 2:
|
||||
t.Errorf("check = %d, want the drop kept:\n%s", code, stderr)
|
||||
case !tc.refused:
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if !slices.Equal(dropped(recordOf(t, gh)), []int{1}) || category(t, gh, 6) != "picked" {
|
||||
t.Errorf("the next run drops %v and puts #6 in %q; want #1's drop carried on and #6 picked", dropped(recordOf(t, gh)), category(t, gh, 6))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// What a drop cannot do is refused before anything is touched.
|
||||
func TestDropRefuses(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{labels: map[string][]int{labelSkip: {7, 9}}}
|
||||
head := openBatch(t, f, gh)
|
||||
f.onLine("release-1.1", "fix(app): five\n\n(cherry picked from commit "+mc5+")", map[string]string{"app/five.txt": "5\n"})
|
||||
// The line carries these too, by hand, while backport/skip and rule 2
|
||||
// decide them before the line is looked at.
|
||||
mc7 := f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
mc8 := f.pr(8, "feat(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
f.onLine("release-1.1", "fix(app): seven\n\n(cherry picked from commit "+mc7+")", map[string]string{"app/seven.txt": "7\n"})
|
||||
f.onLine("release-1.1", "feat(app): eight\n\n(cherry picked from commit "+mc8+")", map[string]string{"app/eight.txt": "8\n"})
|
||||
// #9 is on the line only through a pick of its own commit, which a later
|
||||
// line change has since moved away from what main has.
|
||||
mc9 := f.pr(9, "fix(app): nine", "", map[string]string{"app/nine.txt": "9\n"})
|
||||
f.onLine("release-1.1", "fix(app): nine\n\n(cherry picked from commit "+f.git("rev-parse", mc9+"^2")+")", map[string]string{"app/nine.txt": "9\n"})
|
||||
f.onLine("release-1.1", "fix(app): nine, as the line needs it", map[string]string{"app/nine.txt": "nine on release-1.1\n"})
|
||||
for _, tc := range []struct {
|
||||
args []string
|
||||
why string
|
||||
}{
|
||||
{[]string{"--drop", "4242", "--reason", "r"}, "#4242 did not merge into main"},
|
||||
{[]string{"--drop", "5", "--reason", "r"}, "already on release-1.1; a drop cannot remove code the line has"},
|
||||
{[]string{"--drop", "7", "--reason", "r"}, "#7 is already on release-1.1; a drop cannot remove code the line has"},
|
||||
{[]string{"--drop", "8", "--reason", "r"}, "#8 is already on release-1.1; a drop cannot remove code the line has"},
|
||||
{[]string{"--drop", "9", "--reason", "r"}, "#9 is already on release-1.1; a drop cannot remove code the line has"},
|
||||
{[]string{"--drop", "6"}, "--drop needs a --reason"},
|
||||
{[]string{"--drop", "6", "--reason", "r", "--defer", "6"}, "give one"},
|
||||
{[]string{"--drop", "6", "--reason", "r", "--continue"}, "takes no --onto, --continue or --date"},
|
||||
{[]string{"--drop", "6", "--reason", "r", "--onto", head}, "takes no --onto, --continue or --date"},
|
||||
{[]string{"--drop", "6", "--reason", "r", "--date", "2026-10-26"}, "takes no --onto, --continue or --date"},
|
||||
{[]string{"--undrop", "6", "--reason", "r"}, "--undrop takes no --reason"},
|
||||
{[]string{"--undrop", "6"}, "#6 is not dropped from release-1.1"},
|
||||
{[]string{"--drop", "6", "--undrop", "6", "--reason", "r"}, "give one"},
|
||||
{[]string{"--drop", "six", "--reason", "r"}, "not a list of pull request numbers"},
|
||||
} {
|
||||
code, _, stderr := f.exec(gh, append(append([]string{"run", "--line", "release-1.1"}, tc.args...), "--push")...)
|
||||
f.git("switch", "-q", "main")
|
||||
if code != 2 || !strings.Contains(stderr, tc.why) {
|
||||
t.Errorf("run %q = %d, want 2 with %q:\n%s", tc.args, code, tc.why, stderr)
|
||||
}
|
||||
}
|
||||
if f.remoteHead(batchBranch1) != head || len(gh.edited) != 0 || len(reportsPosted(gh)) != 1 {
|
||||
t.Errorf("a refused drop moved the batch to %.12s or wrote %q", f.remoteHead(batchBranch1), gh.edited)
|
||||
}
|
||||
}
|
||||
|
||||
// A drop or an undrop asked for while a close was left changes nothing: the
|
||||
// run finishes the close, and no open batch pull request is left to record
|
||||
// it on.
|
||||
func TestDropDuringAnUnfinishedClose(t *testing.T) {
|
||||
deferAll := []string{"run", "--line", "release-1.1", "--defer", "5", "--reason", "fails the app e2e", "--push"}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
stop func(f *fixture, gh *fakeGH)
|
||||
refused bool
|
||||
args []string
|
||||
}{
|
||||
{"a drop after the close failed", func(f *fixture, gh *fakeGH) { gh.fail = map[string]error{"closePull": errString("HTTP 502")} }, false, []string{"--drop", "6", "--reason", "not for 1.1"}},
|
||||
{"an undrop after the delete failed", func(f *fixture, gh *fakeGH) {
|
||||
gh.after = map[string]func(){"closePull": func() { f.refusePushes(true) }}
|
||||
}, true, []string{"--undrop", "6"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, gh, _ := closeWorld(t)
|
||||
tc.stop(f, gh)
|
||||
if code, _, stderr := f.exec(gh, deferAll...); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
if tc.refused {
|
||||
f.refusePushes(false)
|
||||
}
|
||||
gh.after = nil
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
code, _, stderr := f.exec(gh, append([]string{"run", "--line", "release-1.1", "--push"}, tc.args...)...)
|
||||
f.git("switch", "-q", "main")
|
||||
rec, err := parseRecord(gh.find(90).Body, notifyLine)
|
||||
if code != 2 || !strings.Contains(stderr, "finished the close of #90 and made no other change") || gh.find(90).State != "closed" || f.remoteHead(batchBranch1) != "" || err != nil || len(rec.Dropped) != 0 {
|
||||
t.Errorf("run %q = %d, #90 %s, branch %q, record %+v, %v; want 2, the close finished and nothing dropped:\n%s", tc.args, code, gh.find(90).State, f.remoteHead(batchBranch1), rec, err, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The batch carries an original whose first commit the line already had, so
|
||||
// its pick came out empty and its unit holds the rest: a drop still takes
|
||||
// that unit off.
|
||||
func TestDropTakesOffAUnitWithAnEmptyPick(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): the first part, on its own", map[string]string{"app/already.txt": "first\n"})
|
||||
f.prCommits(5, "fix(app): a fix in two parts", "",
|
||||
change{files: map[string]string{"app/already.txt": "first\n"}},
|
||||
change{files: map[string]string{"app/new.txt": "second\n"}},
|
||||
)
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--drop", "5", "--reason", "not for 1.1", "--push")
|
||||
head := f.remoteHead(batchBranch1)
|
||||
if got := f.subjects("origin/release-1.1", head); !slices.Equal(got, []string{"fix(app): six (#6)"}) || f.git("ls-tree", "--name-only", head, "--", "app/new.txt") != "" {
|
||||
t.Errorf("after the drop the batch carries %q, want #6 alone and nothing of #5", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A report keeps each drop the record keeps, with the merge commit it is
|
||||
// bound to, its reason and the batch pull request that recorded it, so an
|
||||
// earlier report still says why after the drop is withdrawn.
|
||||
func TestReportKeepsEachDrop(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
mc6 := f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
stdout := mustRun(t, f, gh, "run", "--line", "release-1.1", "--drop", "6", "--reason", "needs the rework of #4", "--push")
|
||||
dropped := bodyReportOf(t, stdout)
|
||||
want := `"overlays":{"dropped":[{"original":6,"merge":"` + mc6 + `","reason":"needs the rework of #4","on":90,"date":"2026-10-26"}]`
|
||||
if !strings.Contains(dropped.raw, want) {
|
||||
t.Errorf("the report does not keep the drop with its merge and reason:\n%s", dropped.raw)
|
||||
}
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--undrop", "6", "--push")
|
||||
if raw := bodyReportOf(t, gh.find(90).Body).raw; !strings.Contains(raw, `"overlays":{"dropped":[],`) {
|
||||
t.Errorf("the report after the undrop still keeps a drop:\n%s", raw)
|
||||
}
|
||||
code, out, stderr := f.exec(gh, "report", "--pr", "90", "--id", dropped.doc.ID)
|
||||
if code != 0 || !strings.Contains(out, "dropped: #6, merged as "+mc6[:12]+", on #90: needs the rework of #4\n") {
|
||||
t.Errorf("report --id of the earlier report = %d, want it to show the drop:\n%s%s", code, out, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A report's drop is held to the record's rules and bound to main as the
|
||||
// record's drops are: a reason a run does not write, another original's
|
||||
// merge, or an earlier commit on main that names the same number is
|
||||
// refused, however the ID was made to match, in the body and in a trusted
|
||||
// report comment alike.
|
||||
func TestReportRefusesAForgedDrop(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.release("release-1.0")
|
||||
f.tag("v1.0.0")
|
||||
early := f.squash(6, "docs: what six will change", "", map[string]string{"docs/six.md": "6\n"})
|
||||
f.release("release-1.1")
|
||||
f.tag("v1.1.0")
|
||||
mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
mc6 := f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--drop", "6", "--reason", "not for 1.1", "--push")
|
||||
body, comments := gh.find(90).Body, slices.Clone(gh.issueComments)
|
||||
s := bodyReportOf(t, body)
|
||||
for _, tc := range []struct{ name, old, new, why string }{
|
||||
{"a reason of two lines", `"reason":"not for 1.1"`, `"reason":"not for 1.1\nwarning: forged"`, "which is no reason a run writes"},
|
||||
{"another original's merge", `"merge":"` + mc6 + `"`, `"merge":"` + mc5 + `"`, "which merged #5"},
|
||||
{"an earlier commit that names the same number", `"merge":"` + mc6 + `"`, `"merge":"` + early + `"`, "but #6 merged as " + mc6[:12]},
|
||||
} {
|
||||
raw := strings.Replace(s.raw, tc.old, tc.new, 1)
|
||||
if raw == s.raw {
|
||||
t.Fatalf("the report holds no %s to change:\n%s", tc.old, s.raw)
|
||||
}
|
||||
var d reportDoc
|
||||
if err := decodeStrict(raw, &d); err != nil {
|
||||
t.Fatalf("the changed report does not decode: %v", err)
|
||||
}
|
||||
d.ID = reportID(d)
|
||||
forged := storedReport{doc: d, raw: reportJSON(d)}
|
||||
refused := func(t *testing.T, args ...string) {
|
||||
t.Helper()
|
||||
code, out, stderr := f.exec(gh, append([]string{"report", "--pr", "90"}, args...)...)
|
||||
if code != 2 || !strings.Contains(stderr, tc.why) || strings.Contains(out+stderr, "\nwarning: forged") {
|
||||
t.Errorf("report of a forged drop = %d, want 2 with %q:\n%s%s", code, tc.why, out, stderr)
|
||||
}
|
||||
}
|
||||
t.Run(tc.name+", in the body", func(t *testing.T) {
|
||||
gh.find(90).Body = strings.Replace(body, reportBlock(s.raw), reportBlock(forged.raw), 1)
|
||||
defer func() { gh.find(90).Body = body }()
|
||||
refused(t)
|
||||
})
|
||||
t.Run(tc.name+", in a comment", func(t *testing.T) {
|
||||
text, err := reportComment(forged)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := issueComment{ID: 9000, Body: text}
|
||||
c.User.Login, c.User.Type = "maintainer", "User"
|
||||
gh.issueComments = append(slices.Clone(comments), c)
|
||||
defer func() { gh.issueComments = comments }()
|
||||
refused(t, "--id", d.ID)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// droppedNumbers are the originals a report's drops name.
|
||||
func droppedNumbers(es []droppedEntry) []int {
|
||||
var out []int
|
||||
for _, e := range es {
|
||||
out = append(out, e.Original)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// dropWorld has #3 merged before release-1.1 branched, an earlier commit on
|
||||
// main that names #6, and a batch with #5 and #6 from which #6 is dropped.
|
||||
func dropWorld(t *testing.T) (f *fixture, gh *fakeGH, inherited, mc5, mc6 string) {
|
||||
t.Helper()
|
||||
f = newFixture(t)
|
||||
f.release("release-1.0")
|
||||
f.tag("v1.0.0")
|
||||
inherited = f.prCommits(3, "feat(app): three", "", change{files: map[string]string{"app/three.txt": "3\n"}, message: "feat(app): part of three (#3)"})
|
||||
f.squash(6, "docs: what six will change", "", map[string]string{"docs/six.md": "6\n"})
|
||||
f.release("release-1.1")
|
||||
f.tag("v1.1.0")
|
||||
mc5 = f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
mc6 = f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh = &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--drop", "6", "--reason", "not for 1.1", "--push")
|
||||
return f, gh, inherited, mc5, mc6
|
||||
}
|
||||
|
||||
// A report's drops and its categories hold each other up: an original it
|
||||
// has dropped needs a drop that binds to it, and a drop of an original it
|
||||
// classified needs that original dropped or decided by an earlier rule. A
|
||||
// drop inherited from before the line branched decides nothing and stays
|
||||
// readable. Each holds in the body and in a trusted report comment.
|
||||
func TestReportTiesDropsToTheirCategory(t *testing.T) {
|
||||
f, gh, inherited, mc5, _ := dropWorld(t)
|
||||
body, comments := gh.find(90).Body, slices.Clone(gh.issueComments)
|
||||
s := bodyReportOf(t, body)
|
||||
kept := func(n int, merge string) droppedEntry {
|
||||
return droppedEntry{Original: n, Merge: merge, Reason: "carried from an earlier batch", On: 89, Date: "2026-10-25"}
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
change func(d *reportDoc)
|
||||
why string
|
||||
}{
|
||||
{"an inherited drop in place of the classified one", func(d *reportDoc) { d.Overlays.Dropped[0] = kept(3, inherited) }, "has #6 dropped, but keeps no drop of it"},
|
||||
{"an inherited drop classified as dropped", func(d *reportDoc) {
|
||||
d.Primary.Skipped.Dropped = append(d.Primary.Skipped.Dropped, 3)
|
||||
d.Overlays.Dropped = append(d.Overlays.Dropped, kept(3, inherited))
|
||||
}, "has #3 dropped, but no drop of it binds to an original it classified"},
|
||||
{"a drop of an original it picked", func(d *reportDoc) { d.Overlays.Dropped = append(d.Overlays.Dropped, kept(5, mc5)) }, "drops #5, which it has picked"},
|
||||
{"an inherited drop beside the classified one", func(d *reportDoc) { d.Overlays.Dropped = append(d.Overlays.Dropped, kept(3, inherited)) }, ""},
|
||||
} {
|
||||
var d reportDoc
|
||||
if err := decodeStrict(s.raw, &d); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tc.change(&d)
|
||||
d.canonical()
|
||||
d.ID = reportID(d)
|
||||
forged := storedReport{doc: d, raw: reportJSON(d)}
|
||||
check := func(t *testing.T, args ...string) {
|
||||
t.Helper()
|
||||
code, out, stderr := f.exec(gh, append([]string{"report", "--pr", "90"}, args...)...)
|
||||
switch {
|
||||
case tc.why == "" && (code != 0 || !strings.Contains(out, "#6 skipped.dropped") || !strings.Contains(out, "dropped: #3, merged as "+inherited[:12]) || strings.Contains(out, "#3 skipped.dropped")):
|
||||
t.Errorf("report of a sound report = %d, want it read with #3's drop beside #6's:\n%s%s", code, out, stderr)
|
||||
case tc.why != "" && (code != 2 || out != "" || !strings.Contains(stderr, tc.why)):
|
||||
t.Errorf("report = %d, want 2 with %q:\n%s%s", code, tc.why, out, stderr)
|
||||
}
|
||||
}
|
||||
t.Run(tc.name+", in the body", func(t *testing.T) {
|
||||
gh.find(90).Body = strings.Replace(body, reportBlock(s.raw), reportBlock(forged.raw), 1)
|
||||
defer func() { gh.find(90).Body = body }()
|
||||
check(t)
|
||||
})
|
||||
t.Run(tc.name+", in a comment", func(t *testing.T) {
|
||||
text, err := reportComment(forged)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := issueComment{ID: 9001, Body: text}
|
||||
c.User.Login, c.User.Type = "maintainer", "User"
|
||||
gh.issueComments = append(slices.Clone(comments), c)
|
||||
defer func() { gh.issueComments = comments }()
|
||||
check(t, "--id", d.ID)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A clean pick can still carry only part of an original: git deletes a file
|
||||
// the line never had without a word, and leaves alone a file the line lacks.
|
||||
// What follows tells such a unit from a whole one, by what it leaves without
|
||||
// effect of the files the original modifies or deletes.
|
||||
|
||||
// treeEntry is one record of git ls-tree.
|
||||
type treeEntry struct{ mode, kind, oid string }
|
||||
|
||||
// regular says whether git can merge the entry as text: a file, not a
|
||||
// symlink, a submodule or a tree.
|
||||
func (e treeEntry) regular() bool {
|
||||
return e.kind == "blob" && (e.mode == "100644" || e.mode == "100755")
|
||||
}
|
||||
|
||||
// treeEntries reads the entries paths have at treeish, from full ls-tree
|
||||
// records: a path that is a tree there, or absent, has none.
|
||||
func treeEntries(treeish string, paths []string) (map[string]treeEntry, error) {
|
||||
out := map[string]treeEntry{}
|
||||
want := map[string]bool{}
|
||||
for _, p := range paths {
|
||||
want[p] = true
|
||||
}
|
||||
const chunk = 500
|
||||
for len(paths) > 0 {
|
||||
n := min(chunk, len(paths))
|
||||
args := append([]string{"--literal-pathspecs", "ls-tree", "-r", "-z", "--full-tree", "--end-of-options", treeish, "--"}, paths[:n]...)
|
||||
raw, stderr, code, err := gitStatus(args...)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, fmt.Errorf("git ls-tree %s did not run", terminalSafe(treeish))
|
||||
case code != 0:
|
||||
// The paths stay out of the error: they are file names someone
|
||||
// chose, and the error reaches a terminal.
|
||||
return nil, fmt.Errorf("git ls-tree %s: exit %d: %s", terminalSafe(treeish), code, terminalSafe(stderr))
|
||||
}
|
||||
for _, rec := range splitNUL(raw) {
|
||||
meta, path, ok := strings.Cut(rec, "\t")
|
||||
f := strings.Fields(meta)
|
||||
if !ok || len(f) != 3 || checkSHA(f[2]) != nil {
|
||||
return nil, fmt.Errorf("git ls-tree %s: unreadable record %q", treeish, terminalSafe(rec))
|
||||
}
|
||||
if want[path] {
|
||||
out[path] = treeEntry{mode: f[0], kind: f[1], oid: f[2]}
|
||||
}
|
||||
}
|
||||
paths = paths[n:]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// renameSet is what git diff -M found renamed between two commits, old path
|
||||
// to new, and whether it looked at every candidate.
|
||||
type renameSet struct {
|
||||
moved map[string]string
|
||||
complete bool
|
||||
}
|
||||
|
||||
// renames reads the renames between from and to, once per pair. git says on
|
||||
// stderr when it skipped inexact detection for too many files; complete is
|
||||
// then false, and no path may be called absent for want of a rename.
|
||||
func (b *batch) renames(from, to string) (renameSet, error) {
|
||||
key := from + ".." + to
|
||||
if s, ok := b.renameCache[key]; ok {
|
||||
return s, nil
|
||||
}
|
||||
// -l0 lifts git's own limit, which the picker's merge does not share:
|
||||
// a rename the pick follows has to be one the checks of its shape see.
|
||||
stdout, stderr, code, err := gitStatusTimed("diff", "--no-ext-diff", "--no-textconv", "-M", "-l"+strconv.Itoa(b.renameLimit), "--name-status", "-z", "--diff-filter=R", "--end-of-options", from, to)
|
||||
switch {
|
||||
case errors.Is(err, errDeadline):
|
||||
// Out of time is rename detection skipped: no path is called
|
||||
// absent for want of it.
|
||||
s := renameSet{moved: map[string]string{}}
|
||||
if b.renameCache == nil {
|
||||
b.renameCache = map[string]renameSet{}
|
||||
}
|
||||
b.renameCache[key] = s
|
||||
return s, nil
|
||||
case err != nil:
|
||||
return renameSet{}, err
|
||||
case code != 0:
|
||||
return renameSet{}, fmt.Errorf("git diff -M %s %s: exit %d: %s", from, to, code, strings.TrimSpace(stderr))
|
||||
}
|
||||
f := splitNUL(stdout)
|
||||
if len(f)%3 != 0 {
|
||||
return renameSet{}, fmt.Errorf("unreadable renames between %s and %s", from, to)
|
||||
}
|
||||
s := renameSet{moved: map[string]string{}, complete: !strings.Contains(stderr, "detection was skipped")}
|
||||
for i := 0; i < len(f); i += 3 {
|
||||
if !strings.HasPrefix(f[i], "R") {
|
||||
return renameSet{}, fmt.Errorf("unreadable renames between %s and %s: %q", from, to, terminalSafe(f[i]))
|
||||
}
|
||||
s.moved[f[i+1]] = f[i+2]
|
||||
}
|
||||
if b.renameCache == nil {
|
||||
b.renameCache = map[string]renameSet{}
|
||||
}
|
||||
b.renameCache[key] = s
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// effectPaths are the paths v modifies or deletes; what it adds has nothing
|
||||
// to correspond to.
|
||||
func effectPaths(v *verdict) []string {
|
||||
var out []string
|
||||
for _, c := range v.changes {
|
||||
if c.status == 'M' || c.status == 'D' {
|
||||
out = append(out, c.path)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// correspondence maps a path of the original (at M^1) to the path holding the
|
||||
// same file on target, through a main-side rename base..M^1, a line-side
|
||||
// rename base..target, or both composed through the base path. A path with
|
||||
// no counterpart maps to itself, and one git skipped rename detection for is
|
||||
// left out and named in unknown: it is not known to be absent.
|
||||
func (b *batch) correspondence(v *verdict, target string) (map[string]string, []string, error) {
|
||||
paths := effectPaths(v)
|
||||
have, err := treeEntries(target, paths)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
corr := map[string]string{}
|
||||
var missing []string
|
||||
for _, p := range paths {
|
||||
if _, ok := have[p]; ok {
|
||||
corr[p] = p
|
||||
} else {
|
||||
missing = append(missing, p)
|
||||
}
|
||||
}
|
||||
if len(missing) == 0 {
|
||||
return corr, nil, nil
|
||||
}
|
||||
onMain, err := b.renames(b.base, v.o.merge+"^1")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
onLine, err := b.renames(b.base, target)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
fromBase := map[string]string{}
|
||||
for old, now := range onMain.moved {
|
||||
fromBase[now] = old
|
||||
}
|
||||
candidates := map[string]string{}
|
||||
var names []string
|
||||
for _, p := range missing {
|
||||
q := p
|
||||
if old, ok := fromBase[p]; ok {
|
||||
q = old
|
||||
}
|
||||
r := q
|
||||
if now, ok := onLine.moved[q]; ok {
|
||||
r = now
|
||||
}
|
||||
if r != p {
|
||||
candidates[p] = r
|
||||
names = append(names, r)
|
||||
}
|
||||
}
|
||||
found, err := treeEntries(target, names)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var unknown []string
|
||||
for _, p := range missing {
|
||||
if r, ok := candidates[p]; ok {
|
||||
if _, ok := found[r]; ok {
|
||||
corr[p] = r
|
||||
continue
|
||||
}
|
||||
}
|
||||
if !onMain.complete || !onLine.complete {
|
||||
unknown = append(unknown, p)
|
||||
continue
|
||||
}
|
||||
corr[p] = p
|
||||
}
|
||||
return corr, unknown, nil
|
||||
}
|
||||
|
||||
// omittedEffects lists the paths v modifies or deletes that the change from
|
||||
// before to after leaves without effect, each judged at its corresponding
|
||||
// path c(p) on before. A modified path is omitted when c(p) exists on neither
|
||||
// side, applied when the change touches it, and when the change leaves an
|
||||
// existing file alone, satisfied only if the line already has what the
|
||||
// original makes of it. A deleted path is omitted when c(p) is absent before:
|
||||
// a deletion the line already did is no change this unit makes. diag says
|
||||
// what could not be judged, which is never counted as omitted.
|
||||
func (b *batch) omittedEffects(v *verdict, before, after string) ([]string, []string, error) {
|
||||
if err := b.load(v); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
corr, unknown, err := b.correspondence(v, before)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var diag []string
|
||||
for _, p := range unknown {
|
||||
diag = append(diag, "git skipped rename detection, so where "+strconv.Quote(p)+" is on the line is not known")
|
||||
}
|
||||
added := map[string]bool{}
|
||||
for _, c := range v.changes {
|
||||
if c.status == 'A' {
|
||||
added[c.path] = true
|
||||
}
|
||||
}
|
||||
// A deleted path whose counterpart the original adds itself is a rename
|
||||
// the line already made the same way: it is judged as a modified file,
|
||||
// against what the original makes of that path.
|
||||
var at, own, moved []string
|
||||
movedTo := map[string]string{}
|
||||
for _, c := range v.changes {
|
||||
cp, ok := corr[c.path]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
at = append(at, cp)
|
||||
switch {
|
||||
case c.status == 'M':
|
||||
own = append(own, c.path)
|
||||
case c.status == 'D' && cp != c.path && added[cp]:
|
||||
own, moved = append(own, c.path), append(moved, cp)
|
||||
movedTo[c.path] = cp
|
||||
}
|
||||
}
|
||||
bef, err := treeEntries(before, at)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
aft, err := treeEntries(after, at)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pre, err := treeEntries(v.o.merge+"^1", own)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
post, err := treeEntries(v.o.merge, append(slices.Clone(own), moved...))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// A change that makes none is judged by its trees, whatever names them:
|
||||
// a commit and the tree a net merge wrote can be the same change.
|
||||
same := before == after
|
||||
if !same {
|
||||
bt, err := resolveTree(before)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
at, err := resolveTree(after)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
same = bt == at
|
||||
}
|
||||
var omitted []string
|
||||
// modified judges a path whose counterpart cp should end up as the
|
||||
// original's postimage p1 of it.
|
||||
modified := func(path, cp string, p0, p1 treeEntry) error {
|
||||
be, inBefore := bef[cp]
|
||||
ae, inAfter := aft[cp]
|
||||
switch {
|
||||
case !inBefore && !inAfter:
|
||||
omitted = append(omitted, path)
|
||||
return nil
|
||||
case inBefore != inAfter || be != ae:
|
||||
return nil
|
||||
case be.oid == p1.oid && (p0.mode == p1.mode || be.mode == p1.mode):
|
||||
return nil
|
||||
case !be.regular() || !p0.regular() || !p1.regular() || p0.mode != p1.mode:
|
||||
diag = append(diag, "the mode or type of "+strconv.Quote(path)+" changes, which only a person can judge")
|
||||
return nil
|
||||
}
|
||||
applied, unsupported, err := b.alreadyApplied(p0.oid, be.oid, p1.oid)
|
||||
switch {
|
||||
case err != nil:
|
||||
return fmt.Errorf("judging %s of #%d: %w", strconv.Quote(path), v.o.number, err)
|
||||
case unsupported:
|
||||
diag = append(diag, "git cannot merge "+strconv.Quote(path)+" as text, so whether the line has its change is not known")
|
||||
case !applied:
|
||||
omitted = append(omitted, path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, c := range v.changes {
|
||||
cp, ok := corr[c.path]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case c.status == 'D' && movedTo[c.path] != "":
|
||||
if err := modified(c.path, cp, pre[c.path], post[cp]); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
case c.status == 'D':
|
||||
// Absent before: the line already made the deletion, which is
|
||||
// no change of a unit that makes others, and is all of one
|
||||
// that makes none. Still there after: the deletion did not
|
||||
// happen, whatever the unit changed in the file; keeping what
|
||||
// the line made of it is a port of its own.
|
||||
_, inBefore := bef[cp]
|
||||
_, inAfter := aft[cp]
|
||||
if !inBefore && !same || inAfter {
|
||||
omitted = append(omitted, c.path)
|
||||
}
|
||||
case c.status == 'M':
|
||||
if err := modified(c.path, cp, pre[c.path], post[c.path]); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range diag {
|
||||
diag[i] = oneLineText(diag[i])
|
||||
}
|
||||
return omitted, diag, nil
|
||||
}
|
||||
|
||||
// alreadyApplied says whether cur, a file the unit leaves alone, already
|
||||
// holds the original's change from pre to post: it is post itself, or git
|
||||
// merge-file of the three merges cleanly back into cur. unsupported is
|
||||
// content merge-file refuses, such as differing binary files, which says
|
||||
// nothing either way.
|
||||
func (b *batch) alreadyApplied(pre, cur, post string) (applied, unsupported bool, err error) {
|
||||
if cur == post {
|
||||
return true, false, nil
|
||||
}
|
||||
b.mergeFiles++
|
||||
blobs, err := readObjects([]string{pre, cur, post}, "blob")
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
dir, err := os.MkdirTemp("", "backport-batch-merge-file-*")
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
names := map[string]string{}
|
||||
for _, f := range []struct{ name, oid string }{{"cur", cur}, {"pre", pre}, {"post", post}} {
|
||||
names[f.name] = filepath.Join(dir, f.name)
|
||||
if err := os.WriteFile(names[f.name], blobs[f.oid], 0o600); err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
}
|
||||
stdout, stderr, code, err := gitStatus("merge-file", "-p", names["cur"], names["pre"], names["post"])
|
||||
switch {
|
||||
case err != nil:
|
||||
return false, false, err
|
||||
case code == 0:
|
||||
return stdout == string(blobs[cur]), false, nil
|
||||
case code > 0 && code < 128:
|
||||
// The number of conflicts.
|
||||
return false, false, nil
|
||||
case strings.Contains(stderr, "Cannot merge binary files"):
|
||||
return false, true, nil
|
||||
}
|
||||
return false, false, fmt.Errorf("git merge-file: exit %d: %s", code, strings.TrimSpace(stderr))
|
||||
}
|
||||
|
||||
// unitsOn maps each original the batch head carries a unit of to that unit,
|
||||
// by its Backported-from trailer or appended -x line: found needs every
|
||||
// commit of a merged original, and misses one whose first pick came out
|
||||
// empty because the line already had that change.
|
||||
func (b *batch) unitsOn(head string) (map[*verdict]string, error) {
|
||||
if m, ok := b.unitCache[head]; ok {
|
||||
return m, nil
|
||||
}
|
||||
units, err := batchUnits(head, b.lineHead)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m := map[*verdict]string{}
|
||||
for _, u := range units {
|
||||
if v := b.unitOriginal(u); v != nil && m[v] == "" {
|
||||
m[v] = u.commit
|
||||
}
|
||||
}
|
||||
if b.unitCache == nil {
|
||||
b.unitCache = map[string]map[*verdict]string{}
|
||||
}
|
||||
b.unitCache[head] = m
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// onBranch says whether the batch head h carries v.
|
||||
func (b *batch) onBranch(h *history, v *verdict) (bool, error) {
|
||||
if found(h, v) {
|
||||
return true, nil
|
||||
}
|
||||
m, err := b.unitsOn(h.head)
|
||||
return m[v] != "", err
|
||||
}
|
||||
|
||||
// partialStates finds what applies only in part on the line. Every unit on
|
||||
// the open batch is checked against its own first parent, whatever the rules
|
||||
// now say of its original: one that leaves an effect out fails the cut until
|
||||
// it is taken out. Every original the policy takes and nothing carries is
|
||||
// checked against the tree its clean net merge onto the line writes, so a
|
||||
// partial one is found with no record and no adder; a conflict is never
|
||||
// called partial.
|
||||
func (b *batch) partialStates() error {
|
||||
defer b.timed(time.Now())
|
||||
b.partialUnits = map[*verdict][]string{}
|
||||
if b.pr != nil {
|
||||
var err error
|
||||
if b.partialUnits, err = b.unitsPartial(b.prHead); err != nil {
|
||||
return err
|
||||
}
|
||||
on, err := b.unitsOn(b.prHead)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for v, commit := range on {
|
||||
v.batched = commit
|
||||
if v.rule == 0 && v.onBatch == "" {
|
||||
v.onBatch = commit
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, v := range b.qualifying() {
|
||||
if v.onBatch != "" {
|
||||
continue
|
||||
}
|
||||
if err := b.partialAt(v, b.lineHead); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// unitsPartial maps each original whose unit between the line's head and
|
||||
// head leaves part of it without effect to what it leaves.
|
||||
func (b *batch) unitsPartial(head string) (map[*verdict][]string, error) {
|
||||
units, err := batchUnits(head, b.lineHead)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[*verdict][]string{}
|
||||
for _, u := range units {
|
||||
v := b.unitOriginal(u)
|
||||
if v == nil || len(u.parents) == 0 {
|
||||
continue
|
||||
}
|
||||
omitted, diag, err := b.omittedEffects(v, u.parents[0], u.commit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.addDiag(diag...)
|
||||
if len(omitted) > 0 {
|
||||
out[v] = append(out[v], omitted...)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// markPartial puts every original on the branch at head whose unit there
|
||||
// does only part of it among the partial units, and so among the stale
|
||||
// ones: still on the batch, and to be taken out before the cut.
|
||||
func (b *batch) markPartial(r *report, head string) error {
|
||||
units := b.partialUnits
|
||||
if b.pr == nil || head != b.prHead {
|
||||
var err error
|
||||
if units, err = b.unitsPartial(head); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
r.partialFiles = map[*verdict][]string{}
|
||||
for _, v := range b.verdicts {
|
||||
files := units[v]
|
||||
if len(files) == 0 {
|
||||
continue
|
||||
}
|
||||
r.partial = append(r.partial, v)
|
||||
r.partialFiles[v] = files
|
||||
if !slices.Contains(r.stale, v) {
|
||||
r.stale = append(r.stale, v)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// keepRecordedPartials judges again, at head, what the batch carries now,
|
||||
// each original the open record parks as partial that the line's head
|
||||
// judges whole: the run's picker found it partial after the picks before
|
||||
// it, which check and an operation that picks nothing do not replay. It
|
||||
// stays parked while its net merge onto head still leaves something
|
||||
// without effect, and is the line's again once that went, as when the pick
|
||||
// that made it partial was taken off.
|
||||
func (b *batch) keepRecordedPartials(head string) error {
|
||||
if !b.src.open || b.src.rec == nil {
|
||||
return nil
|
||||
}
|
||||
for _, p := range b.src.rec.Parked {
|
||||
v := b.find(p.Original)
|
||||
if p.Kind != parkPartial || v == nil || v.rule != 0 || v.onBatch != "" || v.park != nil || v.o.merge != p.Merge {
|
||||
continue
|
||||
}
|
||||
if err := b.partialAt(v, head); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rejudged reads again what partialStates and analyze read for v once its
|
||||
// rules changed, as a withdrawn drop changes them: it is back where the
|
||||
// line puts it.
|
||||
func (b *batch) rejudged(v *verdict) error {
|
||||
if b.pr != nil {
|
||||
on, err := b.unitsOn(b.prHead)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v.batched = on[v]
|
||||
if v.rule == 0 && v.onBatch == "" {
|
||||
v.onBatch = on[v]
|
||||
}
|
||||
}
|
||||
if v.rule != 0 || v.onBatch != "" {
|
||||
return nil
|
||||
}
|
||||
if err := b.partialAt(v, b.lineHead); err != nil {
|
||||
return err
|
||||
}
|
||||
deps, diag, err := b.dependencies(v, b.lineHead)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v.deps = deps
|
||||
v.addDiag(diag...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// partialAt judges v's clean net merge onto head, and parks it, or clears
|
||||
// the park, by what that merge leaves without effect.
|
||||
func (b *batch) partialAt(v *verdict, head string) error {
|
||||
tree, err := b.netTree(head, v.o)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v.partial = nil
|
||||
if v.park != nil && v.park.Kind == parkPartial {
|
||||
v.park = nil
|
||||
}
|
||||
if tree == "" {
|
||||
return nil
|
||||
}
|
||||
omitted, diag, err := b.omittedEffects(v, head, tree)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v.addDiag(diag...)
|
||||
if len(omitted) > 0 {
|
||||
v.partial = omitted
|
||||
v.park = &parkedEntry{Original: v.o.number, Merge: v.o.merge, Kind: parkPartial, Files: sortedClean(omitted)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// netTree is the tree a clean net merge of o onto head writes, "" for a
|
||||
// conflict; the line's head reuses what judging the originals merged.
|
||||
func (b *batch) netTree(head string, o *original) (string, error) {
|
||||
if head == b.lineHead && b.lineHist != nil {
|
||||
return b.lineHist.netTree(o)
|
||||
}
|
||||
tree, _, err := noopPick(head, o)
|
||||
return tree, err
|
||||
}
|
||||
|
||||
// addDiag keeps what could not be judged of v, each line once.
|
||||
func (v *verdict) addDiag(lines ...string) {
|
||||
for _, ln := range lines {
|
||||
if ln != "" && !slices.Contains(v.diag, ln) {
|
||||
v.diag = append(v.diag, ln)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sortedClean(files []string) []string {
|
||||
out := cleanFiles(files)
|
||||
slices.Sort(out)
|
||||
return slices.Compact(out)
|
||||
}
|
||||
|
||||
// leftOut is the refusal for a unit that leaves paths of v without effect.
|
||||
func leftOut(v *verdict, l line, omitted []string) string {
|
||||
quoted := make([]string, len(omitted))
|
||||
for i, p := range omitted {
|
||||
quoted[i] = strconv.Quote(p)
|
||||
}
|
||||
return fmt.Sprintf("#%d leaves %s without effect on %s; port only what the line has as a pull request of its own", v.o.number, strings.Join(quoted, ", "), l.branch())
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const appFile = "one\ntwo\nthree\nfour\nfive\n"
|
||||
|
||||
// renameWorld is the sign-off's rename history: the line keeps app/old.txt,
|
||||
// main renames it to app/new.txt with #3, a feat, and #5 fixes app/new.txt.
|
||||
func renameWorld(t *testing.T) (*fixture, string) {
|
||||
t.Helper()
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: an app file", "", map[string]string{"app/old.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): rename the app file", "", map[string]string{"app/old.txt": "", "app/new.txt": appFile})
|
||||
mc5 := f.pr(5, "fix(app): fix the app file", "", map[string]string{"app/new.txt": strings.Replace(appFile, "three", "THREE", 1)})
|
||||
return f, mc5
|
||||
}
|
||||
|
||||
// emptyBatch pushes the line's head as the batch branch and opens a batch
|
||||
// pull request on it with body, for a fold to land on.
|
||||
func emptyBatch(f *fixture, gh *fakeGH, body string) *foldWorld {
|
||||
f.t.Helper()
|
||||
f.git("fetch", "-q", "origin")
|
||||
f.git("push", "-q", "origin", "origin/release-1.1:refs/heads/"+batchBranch1)
|
||||
f.git("fetch", "-q", "origin")
|
||||
gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, body)}
|
||||
return &foldWorld{f: f, gh: gh, head: f.git("rev-parse", "origin/"+batchBranch1)}
|
||||
}
|
||||
|
||||
// A fix of a file main renamed picks onto the file's old name on the line,
|
||||
// and every check of the batch's shape takes the old name as the same file:
|
||||
// verify, a hand fold, and a rebuild by --defer.
|
||||
func TestRenamePickThroughFoldAndVerify(t *testing.T) {
|
||||
f, mc5 := renameWorld(t)
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
head := openBatch(t, f, gh)
|
||||
if got := f.subjects("origin/release-1.1", head); !slices.Equal(got, []string{"fix(app): fix the app file (#5)", "fix(app): six (#6)"}) {
|
||||
t.Fatalf("the batch carries %q, want #5 and #6", got)
|
||||
}
|
||||
if got := f.git("show", head+":app/old.txt"); !strings.Contains(got, "THREE") {
|
||||
t.Fatalf("#5 did not land on app/old.txt: %q", got)
|
||||
}
|
||||
if code, out, stderr := f.exec(gh, "verify", "--line", "release-1.1", "--head", head); code != 0 {
|
||||
t.Errorf("verify = %d\n%s\n%s", code, out, stderr)
|
||||
}
|
||||
t.Setenv("GIT_COMMITTER_DATE", "2026-10-27T06:00:00Z")
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "6", "--reason", "fails the e2e", "--push"); code != 0 {
|
||||
t.Fatalf("run --defer 6 --push = %d\n%s", code, stderr)
|
||||
}
|
||||
if code, out, stderr := f.exec(gh, "verify", "--line", "release-1.1", "--head", f.remoteHead(batchBranch1)); code != 0 {
|
||||
t.Errorf("verify after the rebuild = %d\n%s\n%s", code, out, stderr)
|
||||
}
|
||||
|
||||
f, mc5 = renameWorld(t)
|
||||
w := emptyBatch(f, &fakeGH{}, "")
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"app/old.txt": strings.Replace(appFile, "three", "THREE", 1)})
|
||||
fold := w.merge(w.head, pick, "fix(app): fix the app file (#5)\n\n"+batchTrailer+": "+mc5)
|
||||
if code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold); code != 0 || out != "ok\n" {
|
||||
t.Errorf("fold of #5 onto app/old.txt = %d, %q\n%s", code, out, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// shaped reads the line from the fixture's remote as verify does.
|
||||
func shaped(t *testing.T, f *fixture) *batch {
|
||||
t.Helper()
|
||||
f.git("fetch", "-q", "origin")
|
||||
b, err := shapeOf(line11)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// commitOn writes files onto parent and returns the commit, leaving every
|
||||
// branch where it was.
|
||||
func commitOn(f *fixture, parent string, files map[string]string) string {
|
||||
f.t.Helper()
|
||||
f.git("switch", "-q", "--detach", parent)
|
||||
f.apply(files)
|
||||
f.git("commit", "-q", "--allow-empty", "-m", "a unit")
|
||||
sha := f.git("rev-parse", "HEAD")
|
||||
f.git("switch", "-q", "main")
|
||||
return sha
|
||||
}
|
||||
|
||||
// A path of the original is followed to where the line keeps the same file:
|
||||
// through a rename on main, on the line, or both, composed through the path
|
||||
// at the base. Where git skipped rename detection the path is unknown, never
|
||||
// absent.
|
||||
func TestCorrespondence(t *testing.T) {
|
||||
corr := func(t *testing.T, f *fixture, n int, limit ...int) (map[string]string, []string) {
|
||||
t.Helper()
|
||||
b := shaped(t, f)
|
||||
if len(limit) > 0 {
|
||||
b.renameLimit = limit[0]
|
||||
}
|
||||
v := b.find(n)
|
||||
if err := b.load(v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, unknown, err := b.correspondence(v, b.lineHead)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c, unknown
|
||||
}
|
||||
t.Run("renamed on main", func(t *testing.T) {
|
||||
f, _ := renameWorld(t)
|
||||
if c, unknown := corr(t, f, 5); c["app/new.txt"] != "app/old.txt" || len(unknown) != 0 {
|
||||
t.Errorf("correspondence = %v, %v; want app/new.txt on app/old.txt", c, unknown)
|
||||
}
|
||||
})
|
||||
t.Run("renamed on the line", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: an app file", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): the line renames it", map[string]string{"app/a.txt": "", "app/line.txt": appFile})
|
||||
f.pr(5, "fix(app): fix it", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
if c, unknown := corr(t, f, 5); c["app/a.txt"] != "app/line.txt" || len(unknown) != 0 {
|
||||
t.Errorf("correspondence = %v, %v; want app/a.txt on app/line.txt", c, unknown)
|
||||
}
|
||||
})
|
||||
t.Run("renamed on both", func(t *testing.T) {
|
||||
f, _ := renameWorld(t)
|
||||
f.onLine("release-1.1", "fix(app): the line renames it its own way", map[string]string{"app/old.txt": "", "app/release.txt": appFile})
|
||||
if c, unknown := corr(t, f, 5); c["app/new.txt"] != "app/release.txt" || len(unknown) != 0 {
|
||||
t.Errorf("correspondence = %v, %v; want app/new.txt on app/release.txt", c, unknown)
|
||||
}
|
||||
})
|
||||
t.Run("not renamed, absent", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): x", "", map[string]string{"app/x.txt": appFile})
|
||||
f.pr(5, "fix(app): fix x", "", map[string]string{"app/x.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
if c, unknown := corr(t, f, 5); c["app/x.txt"] != "app/x.txt" || len(unknown) != 0 {
|
||||
t.Errorf("correspondence = %v, %v; want app/x.txt on itself", c, unknown)
|
||||
}
|
||||
})
|
||||
t.Run("rename detection skipped", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: two app files", "", map[string]string{"app/a.txt": appFile, "app/b.txt": appFile + "six\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): the line renames both, changed", map[string]string{"app/a.txt": "", "app/b.txt": "", "app/x.txt": appFile + "x\n", "app/y.txt": appFile + "six\ny\n"})
|
||||
f.pr(5, "fix(app): fix a", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
// Past the limit, git says it skipped looking; a configured limit
|
||||
// of its own does not decide for the tool.
|
||||
f.git("config", "diff.renameLimit", "1")
|
||||
if c, unknown := corr(t, f, 5, 0); c["app/a.txt"] != "app/x.txt" || len(unknown) != 0 {
|
||||
t.Errorf("correspondence under diff.renameLimit=1 = %v, %v; want app/a.txt on app/x.txt", c, unknown)
|
||||
}
|
||||
if c, unknown := corr(t, f, 5, 1); !slices.Equal(unknown, []string{"app/a.txt"}) || c["app/a.txt"] != "" {
|
||||
t.Errorf("correspondence past the limit = %v, %v; want app/a.txt unknown", c, unknown)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// What a change leaves without effect: a modified file the line lacks on both
|
||||
// sides of it, a deleted file the line never had. A mode change that only a
|
||||
// person can judge is a diagnostic, not an omission.
|
||||
func TestOmittedEffects(t *testing.T) {
|
||||
omitted := func(t *testing.T, f *fixture, n int, files map[string]string) ([]string, []string) {
|
||||
t.Helper()
|
||||
b := shaped(t, f)
|
||||
after := commitOn(f, b.lineHead, files)
|
||||
om, diag, err := b.omittedEffects(b.find(n), b.lineHead, after)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return om, diag
|
||||
}
|
||||
t.Run("a modified file missing before and after", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): x", "", map[string]string{"app/x.txt": appFile})
|
||||
f.pr(5, "fix(app): fix x and five", "", map[string]string{"app/x.txt": "fixed\n", "app/five.txt": "5\n"})
|
||||
if om, diag := omitted(t, f, 5, map[string]string{"app/five.txt": "5\n"}); !slices.Equal(om, []string{"app/x.txt"}) || len(diag) != 0 {
|
||||
t.Errorf("omitted = %q, %q; want app/x.txt", om, diag)
|
||||
}
|
||||
})
|
||||
t.Run("a deleted file absent before", func(t *testing.T) {
|
||||
f, _ := policyWorld(t)
|
||||
if om, _ := omitted(t, f, 5, map[string]string{"chart/tests/values_test.yaml": "suite: values\n"}); !slices.Equal(om, []string{"chart/templates/policy.yaml", "chart/tests/policy_test.yaml"}) {
|
||||
t.Errorf("omitted = %q; want both policy files", om)
|
||||
}
|
||||
})
|
||||
t.Run("a mode change", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a script", "", map[string]string{"app/run.sh": "#!/bin/sh\n", "app/b.txt": "old\n"})
|
||||
f.lines()
|
||||
f.git("switch", "-q", "-c", "pr-5")
|
||||
if err := os.Chmod(filepath.Join(f.dir, "app/run.sh"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.write("app/b.txt", "fixed\n")
|
||||
f.git("add", "-A")
|
||||
f.git("commit", "-q", "-m", "run it")
|
||||
f.git("switch", "-q", "main")
|
||||
f.git("merge", "-q", "--no-ff", "-m", "fix(app): make the script runnable (#5)", "pr-5")
|
||||
f.git("push", "-q", "origin", "main")
|
||||
om, diag := omitted(t, f, 5, map[string]string{"app/b.txt": "fixed\n"})
|
||||
if len(om) != 0 || len(diag) != 1 || !strings.Contains(diag[0], `the mode or type of "app/run.sh" changes`) {
|
||||
t.Errorf("omitted = %q, %q; want a diagnostic for app/run.sh and nothing omitted", om, diag)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// What git says when it fails names file names as text, never as lines a
|
||||
// terminal or a CI log would take for its own.
|
||||
func TestGitErrorsQuoteFileNames(t *testing.T) {
|
||||
newFixture(t)
|
||||
const evil = "x\n::warning::forged"
|
||||
if _, err := gitTimed("log", "--no-such-option", "--", evil); err == nil || strings.Contains(err.Error(), "\n::warning") {
|
||||
t.Errorf("gitTimed error = %v, want the path quoted", err)
|
||||
}
|
||||
if _, err := treeEntries("no-such-revision", []string{evil}); err == nil || strings.Contains(err.Error(), "\n::warning") {
|
||||
t.Errorf("treeEntries error = %v, want the path quoted", err)
|
||||
}
|
||||
}
|
||||
|
||||
// fixedWorld is the sign-off's two-file case: the base has a and b as old,
|
||||
// #5 fixes both, and the line already has a as onLine says, if anything.
|
||||
func fixedWorld(t *testing.T, a, old, onLine, fixed string) (*fixture, string) {
|
||||
t.Helper()
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a and b", "", map[string]string{a: old, "app/b.txt": "old\n"})
|
||||
f.lines()
|
||||
if onLine != "" {
|
||||
f.onLine("release-1.1", "fix(app): a, on the line", map[string]string{a: onLine})
|
||||
}
|
||||
mc5 := f.pr(5, "fix(app): a and b", "", map[string]string{a: fixed, "app/b.txt": "fixed\n"})
|
||||
return f, mc5
|
||||
}
|
||||
|
||||
// The line can already have what an original does to a file: then a pick
|
||||
// that leaves the file alone carries the original whole. The check-time
|
||||
// pass, the picker, fold and verify all take it, binary files included,
|
||||
// without asking git merge-file what blob equality settles. A different fix
|
||||
// on the line, or a deletion of what the line never had, is still left out.
|
||||
func TestAlreadyAppliedFileIsNotOmitted(t *testing.T) {
|
||||
const textPost = "one\nfixed\nthree\nfour\nfive\n"
|
||||
accepted := func(t *testing.T, a, old, onLine, fixed string) {
|
||||
t.Helper()
|
||||
f, _ := fixedWorld(t, a, old, onLine, fixed)
|
||||
if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/5 ") || strings.Contains(stderr, "parked") {
|
||||
t.Errorf("check = %d, want #5 missing and not parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
gh := &fakeGH{}
|
||||
head := openBatch(t, f, gh)
|
||||
if got := f.subjects("origin/release-1.1", head); !slices.Equal(got, []string{"fix(app): a and b (#5)"}) {
|
||||
t.Errorf("picked %q, want #5", got)
|
||||
}
|
||||
if code, out, stderr := f.exec(gh, "verify", "--line", "release-1.1", "--head", head); code != 0 {
|
||||
t.Errorf("verify = %d\n%s\n%s", code, out, stderr)
|
||||
}
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || strings.Contains(stdout, "only part of it applies") {
|
||||
t.Errorf("check --cut = %d, want #5 only on the batch, whole:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f, mc5 := fixedWorld(t, a, old, onLine, fixed)
|
||||
w := emptyBatch(f, &fakeGH{}, "")
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"app/b.txt": "fixed\n"})
|
||||
fold := w.merge(w.head, pick, "fix(app): a and b (#5)\n\n"+batchTrailer+": "+mc5)
|
||||
if code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold); code != 0 {
|
||||
t.Errorf("fold = %d, %q\n%s", code, out, stderr)
|
||||
}
|
||||
}
|
||||
t.Run("the line has the original's file", func(t *testing.T) {
|
||||
accepted(t, "app/a.txt", "old\n", "fixed\n", "fixed\n")
|
||||
})
|
||||
t.Run("the line has the fix beside lines of its own", func(t *testing.T) {
|
||||
accepted(t, "app/a.txt", strings.Replace(textPost, "fixed", "old", 1), textPost+"line only\n", textPost)
|
||||
})
|
||||
t.Run("the line has the original's binary file", func(t *testing.T) {
|
||||
accepted(t, "app/a.bin", "old\x00payload", "fixed\x00payload", "fixed\x00payload")
|
||||
f, _ := fixedWorld(t, "app/a.bin", "old\x00payload", "fixed\x00payload", "fixed\x00payload")
|
||||
b := shaped(t, f)
|
||||
om, diag, err := b.omittedEffects(b.find(5), b.lineHead, commitOn(f, b.lineHead, map[string]string{"app/b.txt": "fixed\n"}))
|
||||
if err != nil || len(om)+len(diag) != 0 || b.mergeFiles != 0 {
|
||||
t.Errorf("omitted = %q, %q, %v, merge-file ran %d times; want nothing, and merge-file never asked", om, diag, err, b.mergeFiles)
|
||||
}
|
||||
})
|
||||
t.Run("an earlier unit of the batch brought the file", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a and b", "", map[string]string{"app/a.txt": "old\n", "app/b.txt": "old\n"})
|
||||
f.lines()
|
||||
f.pr(4, "fix(app): a", "", map[string]string{"app/a.txt": "fixed\n"})
|
||||
f.squash(40, "chore: put a back for now", "", map[string]string{"app/a.txt": "old\n"})
|
||||
f.pr(5, "fix(app): a and b", "", map[string]string{"app/a.txt": "fixed\n", "app/b.txt": "fixed\n"})
|
||||
gh := &fakeGH{}
|
||||
head := openBatch(t, f, gh)
|
||||
if got := f.subjects("origin/release-1.1", head); !slices.Equal(got, []string{"fix(app): a (#4)", "fix(app): a and b (#5)"}) {
|
||||
t.Errorf("picked %q, want #4 and #5", got)
|
||||
}
|
||||
if code, out, stderr := f.exec(gh, "verify", "--line", "release-1.1", "--head", head); code != 0 {
|
||||
t.Errorf("verify = %d\n%s\n%s", code, out, stderr)
|
||||
}
|
||||
})
|
||||
t.Run("the line has a different fix", func(t *testing.T) {
|
||||
f, mc5 := fixedWorld(t, "app/a.txt", "old\n", "other\n", "fixed\n")
|
||||
w := emptyBatch(f, &fakeGH{}, "")
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"app/b.txt": "fixed\n"})
|
||||
fold := w.merge(w.head, pick, "fix(app): a and b (#5)\n\n"+batchTrailer+": "+mc5)
|
||||
if code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold); code != 1 || !strings.Contains(out, `leaves "app/a.txt" without effect`) {
|
||||
t.Errorf("fold = %d, %q, want it refused for app/a.txt\n%s", code, out, stderr)
|
||||
}
|
||||
})
|
||||
t.Run("the line has a different binary file", func(t *testing.T) {
|
||||
f, _ := fixedWorld(t, "app/a.bin", "old\x00payload", "other\x00payload", "fixed\x00payload")
|
||||
b := shaped(t, f)
|
||||
om, diag, err := b.omittedEffects(b.find(5), b.lineHead, commitOn(f, b.lineHead, map[string]string{"app/b.txt": "fixed\n"}))
|
||||
if err != nil || len(om) != 0 || len(diag) != 1 || !strings.Contains(diag[0], `cannot merge "app/a.bin" as text`) {
|
||||
t.Errorf("omitted = %q, %q, %v; want a diagnostic for app/a.bin, nothing omitted", om, diag, err)
|
||||
}
|
||||
})
|
||||
t.Run("a deletion of what the line never had", func(t *testing.T) {
|
||||
f, mc5 := policyWorld(t)
|
||||
w := emptyBatch(f, &fakeGH{}, "")
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"chart/tests/values_test.yaml": "suite: values\n"})
|
||||
fold := w.merge(w.head, pick, "fix(chart): remove the policy a rebase brought back (#5)\n\n"+batchTrailer+": "+mc5)
|
||||
if code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold); code != 1 || !strings.Contains(out, "without effect") {
|
||||
t.Errorf("fold = %d, %q, want it refused\n%s", code, out, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A change that makes none, whatever names its two sides, leaves a deletion
|
||||
// the line already made as it is: the original is there, not partial.
|
||||
func TestDeletionAlreadyMadeByNoChange(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): the line drops the policy", map[string]string{"app/policy.yaml": ""})
|
||||
f.pr(5, "fix(app): drop the policy", "", map[string]string{"app/policy.yaml": ""})
|
||||
b := shaped(t, f)
|
||||
tree := f.git("rev-parse", b.lineHead+"^{tree}")
|
||||
for _, after := range []string{b.lineHead, tree} {
|
||||
if om, _, err := b.omittedEffects(b.find(5), b.lineHead, after); err != nil || len(om) != 0 {
|
||||
t.Errorf("omitted against %.12s = %q, %v; want nothing", after, om, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -32,13 +33,15 @@ import (
|
||||
// main and release lines shaped the way GitHub leaves them: every pull request
|
||||
// lands as a merge commit whose message is its title, its number and its body.
|
||||
type fixture struct {
|
||||
t *testing.T
|
||||
t testing.TB
|
||||
dir string
|
||||
remote string
|
||||
now time.Time
|
||||
// tool is the commit the tool says it was built from.
|
||||
tool string
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T) *fixture {
|
||||
func newFixture(t testing.TB) *fixture {
|
||||
t.Helper()
|
||||
// A hook or an outer repository can export these into the test process.
|
||||
for _, key := range []string{"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES"} {
|
||||
@@ -251,15 +254,114 @@ type fakeGH struct {
|
||||
issueComments []issueComment
|
||||
// bot is what BACKPORT_BATCH_BOT would say.
|
||||
bot string
|
||||
// listed counts the pages of recentPulls read.
|
||||
listed int
|
||||
// closedWrites names every write the tool attempted on a pull request
|
||||
// that is no longer open; exec fails the test on one.
|
||||
closedWrites []string
|
||||
// fail makes the next call of an operation, by its method name, fail.
|
||||
fail map[string]error
|
||||
// nextPR is the number createPull gives, 90 when unset.
|
||||
nextPR int
|
||||
// remoteHead reads a branch's head off the fixture's remote: GitHub
|
||||
// reports an open pull request at what its branch has.
|
||||
remoteHead func(string) string
|
||||
// commented lists the pull request each comment went to, in order.
|
||||
commented []int
|
||||
// after runs once an operation, by its method name, has succeeded: what
|
||||
// someone else does on GitHub meanwhile.
|
||||
after map[string]func()
|
||||
}
|
||||
|
||||
// live is pr as GitHub reports it now: an open one at the head its branch
|
||||
// has on the remote.
|
||||
func (g *fakeGH) live(pr pullRequest) pullRequest {
|
||||
if g.remoteHead != nil && (pr.State == "" || pr.State == "open") {
|
||||
if head := g.remoteHead(pr.Head.Ref); head != "" {
|
||||
pr.Head.SHA = head
|
||||
}
|
||||
}
|
||||
return pr
|
||||
}
|
||||
|
||||
// inject is the failure a test set for the next call of op, once.
|
||||
func (g *fakeGH) inject(op string) error {
|
||||
err := g.fail[op]
|
||||
delete(g.fail, op)
|
||||
return err
|
||||
}
|
||||
|
||||
func (g *fakeGH) pull(n int) (pullRequest, error) {
|
||||
if err := g.inject("pull"); err != nil {
|
||||
return pullRequest{}, err
|
||||
}
|
||||
for _, pr := range g.prs {
|
||||
if pr.Number == n {
|
||||
return g.live(pr), nil
|
||||
}
|
||||
}
|
||||
return pullRequest{}, fmt.Errorf("HTTP 404: no pull request #%d", n)
|
||||
}
|
||||
|
||||
// isOpen says whether the fake has pull request n open, or does not know it.
|
||||
func (g *fakeGH) isOpen(n int) bool {
|
||||
for _, pr := range g.prs {
|
||||
if pr.Number == n {
|
||||
return pr.State == "" || pr.State == "open"
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// write refuses a write to a pull request that is no longer open, which the
|
||||
// tool must never attempt.
|
||||
func (g *fakeGH) write(n int, what string) error {
|
||||
if g.isOpen(n) {
|
||||
return nil
|
||||
}
|
||||
g.closedWrites = append(g.closedWrites, fmt.Sprintf("%s on #%d", what, n))
|
||||
return fmt.Errorf("#%d is closed", n)
|
||||
}
|
||||
|
||||
// recentPulls pages every pull request against base, newest first, as the
|
||||
// REST listing sorted by creation does; a higher number is a newer one.
|
||||
func (g *fakeGH) recentPulls(base string, page int) ([]pullRequest, error) {
|
||||
g.listed++
|
||||
var all []pullRequest
|
||||
for _, pr := range g.prs {
|
||||
if pr.Base.Ref == base {
|
||||
all = append(all, pr)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(all, func(a, b pullRequest) int { return b.Number - a.Number })
|
||||
from := min(len(all), (page-1)*recentPullsPage)
|
||||
return slices.Clone(all[from:min(len(all), from+recentPullsPage)]), g.err
|
||||
}
|
||||
|
||||
func (g *fakeGH) batchBot() string { return g.bot }
|
||||
|
||||
func (g *fakeGH) comments(int) ([]issueComment, error) {
|
||||
defer func() {
|
||||
if f := g.after["comments"]; f != nil {
|
||||
f()
|
||||
}
|
||||
}()
|
||||
return slices.Clone(g.issueComments), nil
|
||||
}
|
||||
|
||||
func (g *fakeGH) createComment(number int, bodyFile string) error {
|
||||
if err := g.write(number, "a comment"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := g.inject("createComment"); err != nil {
|
||||
return err
|
||||
}
|
||||
g.commented = append(g.commented, number)
|
||||
defer func() {
|
||||
if f := g.after["createComment"]; f != nil {
|
||||
f()
|
||||
}
|
||||
}()
|
||||
data, err := os.ReadFile(bodyFile)
|
||||
var c issueComment
|
||||
c.ID, c.Body = int64(1000+len(g.issueComments)), string(data)
|
||||
@@ -302,21 +404,99 @@ func (g *fakeGH) permission(login string) (string, error) {
|
||||
func (g *fakeGH) openPulls(base string) ([]pullRequest, error) {
|
||||
var out []pullRequest
|
||||
for _, pr := range g.prs {
|
||||
if pr.Base.Ref == base {
|
||||
out = append(out, pr)
|
||||
if pr.Base.Ref == base && (pr.State == "" || pr.State == "open") {
|
||||
out = append(out, g.live(pr))
|
||||
}
|
||||
}
|
||||
return out, g.err
|
||||
}
|
||||
|
||||
func (g *fakeGH) createPull(base, head, title, bodyFile string) error {
|
||||
// createPull opens the pull request on the fake, as the maintainer, at the
|
||||
// head the remote has, numbered nextPR.
|
||||
func (g *fakeGH) createPull(base, head, title, bodyFile string) (int, string, error) {
|
||||
if err := g.inject("createPull"); err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
g.created = append(g.created, base+" "+head+" "+title)
|
||||
return g.readBody(bodyFile)
|
||||
if err := g.readBody(bodyFile); err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
n := cmp.Or(g.nextPR, 90)
|
||||
var pr pullRequest
|
||||
pr.Number, pr.Body, pr.State = n, g.bodies[len(g.bodies)-1], "open"
|
||||
pr.HTMLURL = fmt.Sprintf("https://github.com/%s/pull/%d", upstreamRepo, n)
|
||||
pr.User.Login, pr.User.Type = "maintainer", "User"
|
||||
pr.Head.Ref = head
|
||||
if g.remoteHead != nil {
|
||||
pr.Head.SHA = g.remoteHead(head)
|
||||
}
|
||||
pr.Head.Repo = &struct {
|
||||
FullName string `json:"full_name"`
|
||||
}{upstreamRepo}
|
||||
pr.Base.Ref, pr.Base.Repo.FullName = base, upstreamRepo
|
||||
g.prs = append(slices.DeleteFunc(g.prs, func(p pullRequest) bool { return p.Number == n }), pr)
|
||||
return n, pr.HTMLURL, nil
|
||||
}
|
||||
|
||||
func (g *fakeGH) editPull(number int, title, bodyFile string) error {
|
||||
if err := g.write(number, "an edit"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := g.inject("editPull"); err != nil {
|
||||
return err
|
||||
}
|
||||
g.edited = append(g.edited, fmt.Sprintf("#%d %s", number, title))
|
||||
return g.readBody(bodyFile)
|
||||
if err := g.readBody(bodyFile); err != nil {
|
||||
return err
|
||||
}
|
||||
if pr := g.find(number); pr != nil {
|
||||
pr.Body = g.bodies[len(g.bodies)-1]
|
||||
}
|
||||
if f := g.after["editPull"]; f != nil {
|
||||
f()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *fakeGH) editBody(number int, bodyFile string) error {
|
||||
if err := g.write(number, "a body edit"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := g.inject("editBody"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := g.readBody(bodyFile); err != nil {
|
||||
return err
|
||||
}
|
||||
if pr := g.find(number); pr != nil {
|
||||
pr.Body = g.bodies[len(g.bodies)-1]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *fakeGH) closePull(number int) error {
|
||||
if err := g.write(number, "a close"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := g.inject("closePull"); err != nil {
|
||||
return err
|
||||
}
|
||||
if pr := g.find(number); pr != nil {
|
||||
pr.State = "closed"
|
||||
}
|
||||
if f := g.after["closePull"]; f != nil {
|
||||
f()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *fakeGH) find(n int) *pullRequest {
|
||||
for i := range g.prs {
|
||||
if g.prs[i].Number == n {
|
||||
return &g.prs[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *fakeGH) readBody(path string) error {
|
||||
@@ -338,18 +518,55 @@ func (f *fixture) batchPR(n int, base, branch, body string) pullRequest {
|
||||
FullName string `json:"full_name"`
|
||||
}{upstreamRepo}
|
||||
pr.Base.Ref, pr.Base.Repo.FullName = base, upstreamRepo
|
||||
pr.State = "open"
|
||||
return pr
|
||||
}
|
||||
|
||||
// exec runs the tool in the fixture with gh faked, on the fixture's date.
|
||||
// botBatchPR is batchPR opened by the bot the scheduled batch runs as.
|
||||
func (f *fixture) botBatchPR(gh *fakeGH, n int, base, branch, body string) pullRequest {
|
||||
f.t.Helper()
|
||||
gh.bot = defaultBatchBot
|
||||
pr := f.batchPR(n, base, branch, body)
|
||||
pr.User.Login, pr.User.Type, pr.AuthorAssociation = defaultBatchBot, "Bot", "CONTRIBUTOR"
|
||||
return pr
|
||||
}
|
||||
|
||||
// mergeBatch merges the open batch into release-1.1 with a merge commit, as
|
||||
// GitHub does, and deletes its branch, as the repository's
|
||||
// delete_branch_on_merge does. The pull request stays, merged, with its body
|
||||
// and comments.
|
||||
func mergeBatch(f *fixture, gh *fakeGH) {
|
||||
f.t.Helper()
|
||||
f.git("fetch", "-q", "origin")
|
||||
f.git("switch", "-q", "--detach", "origin/release-1.1")
|
||||
f.git("merge", "-q", "--no-ff", "-m", "Merge pull request #90 from cozystack/"+batchBranch1, "origin/"+batchBranch1)
|
||||
f.git("push", "-q", "origin", "HEAD:refs/heads/release-1.1", ":refs/heads/"+batchBranch1)
|
||||
f.git("switch", "-q", "main")
|
||||
for i := range gh.prs {
|
||||
if gh.prs[i].Number == 90 {
|
||||
at := "2026-10-26T12:00:00Z"
|
||||
gh.prs[i].State, gh.prs[i].MergedAt = "closed", &at
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// exec runs the tool in the fixture with gh faked, on the fixture's date, and
|
||||
// fails the test when the tool wrote to a pull request that is not open.
|
||||
func (f *fixture) exec(gh *fakeGH, args ...string) (int, string, string) {
|
||||
f.t.Helper()
|
||||
if gh == nil {
|
||||
gh = &fakeGH{}
|
||||
}
|
||||
if gh.remoteHead == nil {
|
||||
gh.remoteHead = f.remoteHead
|
||||
}
|
||||
var stdout, stderr bytes.Buffer
|
||||
a := &app{gh: gh, stdout: &stdout, stderr: &stderr, now: func() time.Time { return f.now }}
|
||||
a := &app{gh: gh, stdout: &stdout, stderr: &stderr, now: func() time.Time { return f.now }, tool: f.tool}
|
||||
written := len(gh.closedWrites)
|
||||
code := a.main(args)
|
||||
if len(gh.closedWrites) > written {
|
||||
f.t.Errorf("%v wrote to a pull request that is not open: %q", args, gh.closedWrites[written:])
|
||||
}
|
||||
return code, stdout.String(), stderr.String()
|
||||
}
|
||||
|
||||
|
||||
@@ -330,3 +330,93 @@ func TestFold(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A resolution of an original a maintainer dropped from the line is refused:
|
||||
// the drop is the decision that it does not go there.
|
||||
func TestFoldRefusesADroppedOriginal(t *testing.T) {
|
||||
w := newFoldWorld(t)
|
||||
sha := strings.Repeat("a", 40)
|
||||
rec := strings.Replace(v2(""), `"dropped":[{"original":8,"merge":"`+sha+`"`, `"dropped":[{"original":5,"merge":"`+w.mc5+`"`, 1)
|
||||
rec = strings.Replace(rec, `"deferred":[{"original":5,"commit":"`+sha+`","files":["app/five.txt"]},`, `"deferred":[`, 1)
|
||||
rec = strings.Replace(rec, `"stale":[9]`, `"stale":[]`, 1)
|
||||
w.gh.prs[0].Body = "text\n\n" + deferredFence + "\n" + rec + "\n```\n"
|
||||
if _, err := parseRecord(w.gh.prs[0].Body, notifyLine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, stdout, stderr := w.f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", w.resolution())
|
||||
if code != 1 || !strings.Contains(stdout, "#5 is not one the batch takes: a maintainer's drop, dropped on #90: needs #4") {
|
||||
t.Errorf("fold = %d, %q, %s; want a refusal naming the drop", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A resolution that ports what the line has of #5 and leaves alone a file
|
||||
// the line lacks is no fold: what #5 does to that file would be lost, and a
|
||||
// line-only port is a pull request of its own.
|
||||
func TestFoldRefusesAnOmittedEffect(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): a feature the line never gets", "", map[string]string{"app/feature2.txt": "v1\n"})
|
||||
mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/feature2.txt": "v2\n", "app/five.txt": "5\n"})
|
||||
w := emptyBatch(f, &fakeGH{}, "")
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"app/five.txt": "5\n"})
|
||||
fold := w.merge(w.head, pick, "fix(app): five (#5)\n\n"+batchTrailer+": "+mc5)
|
||||
code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold)
|
||||
if code != 1 || out != "refused: #5 leaves \"app/feature2.txt\" without effect on release-1.1; port only what the line has as a pull request of its own\n" {
|
||||
t.Errorf("fold = %d, %q, want it refused for app/feature2.txt\n%s", code, out, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A resolution that keeps a file the original deletes leaves the deletion
|
||||
// without effect.
|
||||
func TestFoldRefusesAKeptDeletion(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: x", "", map[string]string{"app/x.txt": "x\n"})
|
||||
f.lines()
|
||||
mc5 := f.pr(5, "fix(app): five, and x goes", "", map[string]string{"app/x.txt": "", "app/five.txt": "5\n"})
|
||||
w := emptyBatch(f, &fakeGH{}, "")
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"app/five.txt": "5\n"})
|
||||
fold := w.merge(w.head, pick, "fix(app): five, and x goes (#5)\n\n"+batchTrailer+": "+mc5)
|
||||
if code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold); code != 1 || !strings.Contains(out, `leaves "app/x.txt" without effect`) {
|
||||
t.Errorf("fold that keeps app/x.txt = %d, %q\n%s", code, out, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// An original parked for what it builds on can still land as a complete
|
||||
// hand adaptation: every file it changes, changed, in the batch's shape.
|
||||
func TestFoldAcceptsACompleteAdaptationOfAParkedOriginal(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
mc5 := f.pr(5, "fix(app): an excited two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
w := emptyBatch(f, &fakeGH{}, "")
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"app/a.txt": strings.Replace(appFile, "two", "two!", 1)})
|
||||
fold := w.merge(w.head, pick, "fix(app): an excited two (#5)\n\n"+batchTrailer+": "+mc5)
|
||||
if code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold); code != 0 || out != "ok\n" {
|
||||
t.Errorf("fold of an adaptation of #5 = %d, %q\n%s", code, out, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A fold that keeps a file the original deletes leaves the deletion without
|
||||
// effect, whatever it changes in the file: a port that keeps what the line
|
||||
// made of it, or the file with a line added, is a pull request of its own.
|
||||
func TestFoldRefusesAChangedKeptDeletion(t *testing.T) {
|
||||
for name, kept := range map[string]string{
|
||||
"the line's own content": "line only\n",
|
||||
"the file, one line more": "feature\nline only\n# reviewed\n",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a feature", "", map[string]string{"app/x.txt": "feature\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): a line-only setting beside the feature", map[string]string{"app/x.txt": "feature\nline only\n"})
|
||||
mc5 := f.pr(5, "fix(app): drop the feature, and five", "", map[string]string{"app/x.txt": "", "app/five.txt": "5\n"})
|
||||
w := emptyBatch(f, &fakeGH{}, "")
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"app/x.txt": kept, "app/five.txt": "5\n"})
|
||||
fold := w.merge(w.head, pick, "fix(app): drop the feature, and five (#5)\n\n"+batchTrailer+": "+mc5)
|
||||
if code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold); code != 1 || !strings.Contains(out, `leaves "app/x.txt" without effect`) {
|
||||
t.Errorf("fold = %d, %q, want it refused\n%s", code, out, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -21,12 +21,21 @@ import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// openPullsCap is the page size of the open pull request listing. The REST
|
||||
// listing stops at it in silence, so a full page is an error, not an answer.
|
||||
const openPullsCap = 100
|
||||
|
||||
// recentPullsPage is the page size of the listing of every pull request
|
||||
// against a line, newest first, and recentPullsPages how many pages of it a
|
||||
// search for the line's record reads.
|
||||
const (
|
||||
recentPullsPage = 100
|
||||
recentPullsPages = 10
|
||||
)
|
||||
|
||||
// searchResultCap is the most results GitHub search returns for one query,
|
||||
// however far it is paginated. gh pr list answers a --label filter through
|
||||
// search, so a listing that long has to be taken as cut short.
|
||||
@@ -43,6 +52,7 @@ var (
|
||||
batchBranchRE = regexp.MustCompile(`^backport-batch/(release-\d+\.\d+)-(\d{8})$`)
|
||||
loginRE = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$`)
|
||||
botLoginRE = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\[bot\]$`)
|
||||
pullURLRE = regexp.MustCompile(`^https://[^/\s]+/[^/\s]+/[^/\s]+/pull/([1-9][0-9]{0,8})$`)
|
||||
)
|
||||
|
||||
// batchBotEnv names the GitHub App bot the scheduled batch opens its pull
|
||||
@@ -66,10 +76,12 @@ func batchBotLogin(lookup func(string) (string, bool)) string {
|
||||
// pullRequest is the REST view of a pull request: unlike gh pr list, it
|
||||
// carries the author's association with the repository.
|
||||
type pullRequest struct {
|
||||
Number int `json:"number"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
Body string `json:"body"`
|
||||
AuthorAssociation string `json:"author_association"`
|
||||
Number int `json:"number"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
Body string `json:"body"`
|
||||
State string `json:"state"`
|
||||
MergedAt *string `json:"merged_at"`
|
||||
AuthorAssociation string `json:"author_association"`
|
||||
User struct {
|
||||
Login string `json:"login"`
|
||||
Type string `json:"type"`
|
||||
@@ -102,13 +114,22 @@ type issueComment struct {
|
||||
// github is the part of GitHub the tool talks to: gh outside tests.
|
||||
type github interface {
|
||||
openPulls(base string) ([]pullRequest, error)
|
||||
// recentPulls is one page of every pull request against base, open,
|
||||
// merged or closed, newest first.
|
||||
recentPulls(base string, page int) ([]pullRequest, error)
|
||||
// permission is login's permission on the repository as GitHub's
|
||||
// legacy field gives it: admin, write, read or none.
|
||||
permission(login string) (string, error)
|
||||
// labelled lists the pull requests merged into main that carry label.
|
||||
labelled(label string) ([]int, error)
|
||||
createPull(base, head, title, bodyFile string) error
|
||||
// pull reads one pull request as it is now.
|
||||
pull(number int) (pullRequest, error)
|
||||
// createPull opens the draft and returns its number and URL.
|
||||
createPull(base, head, title, bodyFile string) (int, string, error)
|
||||
editPull(number int, title, bodyFile string) error
|
||||
// editBody replaces the body of pull request number and nothing else.
|
||||
editBody(number int, bodyFile string) error
|
||||
closePull(number int) error
|
||||
comments(number int) ([]issueComment, error)
|
||||
createComment(number int, bodyFile string) error
|
||||
editComment(id int64, bodyFile string) error
|
||||
@@ -136,6 +157,38 @@ func (ghCLI) openPulls(base string) ([]pullRequest, error) {
|
||||
return prs, nil
|
||||
}
|
||||
|
||||
func (ghCLI) recentPulls(base string, page int) ([]pullRequest, error) {
|
||||
out, err := capture("gh", "api", "-X", "GET", "repos/{owner}/{repo}/pulls",
|
||||
"-f", "state=all", "-f", "base="+base, "-f", "sort=created", "-f", "direction=desc",
|
||||
"-f", "per_page="+strconv.Itoa(recentPullsPage), "-f", "page="+strconv.Itoa(page))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var prs []pullRequest
|
||||
if err := json.Unmarshal([]byte(out), &prs); err != nil {
|
||||
return nil, fmt.Errorf("reading the pull requests against %s: %w", base, err)
|
||||
}
|
||||
return prs, nil
|
||||
}
|
||||
|
||||
// permCache asks GitHub for a login's permission once per command: the open
|
||||
// batch's author is asked when it is chosen and again when its record is.
|
||||
type permCache struct {
|
||||
github
|
||||
perms map[string]string
|
||||
}
|
||||
|
||||
func (c *permCache) permission(login string) (string, error) {
|
||||
if p, ok := c.perms[login]; ok {
|
||||
return p, nil
|
||||
}
|
||||
p, err := c.github.permission(login)
|
||||
if err == nil {
|
||||
c.perms[login] = p
|
||||
}
|
||||
return p, err
|
||||
}
|
||||
|
||||
func (ghCLI) permission(login string) (string, error) {
|
||||
if !loginRE.MatchString(login) {
|
||||
return "", fmt.Errorf("%q is not a GitHub login", login)
|
||||
@@ -175,9 +228,33 @@ func (ghCLI) labelled(label string) ([]int, error) {
|
||||
return numbers, nil
|
||||
}
|
||||
|
||||
func (ghCLI) createPull(base, head, title, bodyFile string) error {
|
||||
_, err := capture("gh", "pr", "create", "--draft", "--base", base, "--head", head, "--title", title, "--body-file", bodyFile)
|
||||
return err
|
||||
func (ghCLI) pull(number int) (pullRequest, error) {
|
||||
var pr pullRequest
|
||||
out, err := capture("gh", "api", "repos/{owner}/{repo}/pulls/"+strconv.Itoa(number))
|
||||
if err != nil {
|
||||
return pr, err
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &pr); err != nil {
|
||||
return pr, fmt.Errorf("reading pull request #%d: %w", number, err)
|
||||
}
|
||||
if pr.Number != number {
|
||||
return pr, fmt.Errorf("asked for pull request #%d, GitHub answered with #%d", number, pr.Number)
|
||||
}
|
||||
return pr, nil
|
||||
}
|
||||
|
||||
func (ghCLI) createPull(base, head, title, bodyFile string) (int, string, error) {
|
||||
out, err := capture("gh", "pr", "create", "--draft", "--base", base, "--head", head, "--title", title, "--body-file", bodyFile)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
url := strings.TrimSpace(out)
|
||||
m := pullURLRE.FindStringSubmatch(url)
|
||||
if m == nil {
|
||||
return 0, "", fmt.Errorf("gh pr create printed %q, not the URL of a pull request", url)
|
||||
}
|
||||
n, err := strconv.Atoi(m[1])
|
||||
return n, url, err
|
||||
}
|
||||
|
||||
func (ghCLI) editPull(number int, title, bodyFile string) error {
|
||||
@@ -185,6 +262,16 @@ func (ghCLI) editPull(number int, title, bodyFile string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (ghCLI) editBody(number int, bodyFile string) error {
|
||||
_, err := capture("gh", "pr", "edit", strconv.Itoa(number), "--body-file", bodyFile)
|
||||
return err
|
||||
}
|
||||
|
||||
func (ghCLI) closePull(number int) error {
|
||||
_, err := capture("gh", "pr", "close", strconv.Itoa(number))
|
||||
return err
|
||||
}
|
||||
|
||||
func (ghCLI) comments(number int) ([]issueComment, error) {
|
||||
out, err := capture("gh", "api", "--paginate", "--slurp", "repos/{owner}/{repo}/issues/"+strconv.Itoa(number)+"/comments")
|
||||
if err != nil {
|
||||
|
||||
@@ -205,6 +205,9 @@ type history struct {
|
||||
picks []pickRef
|
||||
batches map[string]string
|
||||
backports map[int]string
|
||||
// trees caches what a net merge of an original onto head writes, by its
|
||||
// merge commit: "" for a conflict.
|
||||
trees map[string]string
|
||||
}
|
||||
|
||||
func readHistory(head, base string, textUntil time.Time) (*history, error) {
|
||||
@@ -225,7 +228,7 @@ func readHistory(head, base string, textUntil time.Time) (*history, error) {
|
||||
// readPicks reads only the messages of head's commits outside base, which is
|
||||
// all a batch branch is asked about; textUntil is the batch-only day.
|
||||
func readPicks(head, base string, textUntil time.Time) (*history, error) {
|
||||
h := &history{head: head, reachable: map[string]bool{}, appended: map[string]string{}, batches: map[string]string{}, backports: map[int]string{}}
|
||||
h := &history{head: head, reachable: map[string]bool{}, appended: map[string]string{}, batches: map[string]string{}, backports: map[int]string{}, trees: map[string]string{}}
|
||||
oids, err := revList("--end-of-options", head, "^"+base)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -332,34 +335,54 @@ func (h *history) carries(o *original, commits []string) (string, error) {
|
||||
if c, ok := h.backports[o.number]; ok {
|
||||
return `named by "Backport of" in ` + c[:12], nil
|
||||
}
|
||||
noop, err := noopPick(h.head, o)
|
||||
tree, err := h.netTree(o)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if noop {
|
||||
headTree, err := resolveTree(h.head)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if tree == headTree {
|
||||
return "a pick would change nothing", nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// noopPick reports whether cherry-picking the original onto head would leave
|
||||
// head's tree as it is: the content is there, whatever names it.
|
||||
func noopPick(head string, o *original) (bool, error) {
|
||||
// netTree is noopPick's tree for o onto the branch's head, read once.
|
||||
func (h *history) netTree(o *original) (string, error) {
|
||||
if tree, ok := h.trees[o.merge]; ok {
|
||||
return tree, nil
|
||||
}
|
||||
tree, _, err := noopPick(h.head, o)
|
||||
if err == nil {
|
||||
h.trees[o.merge] = tree
|
||||
}
|
||||
return tree, err
|
||||
}
|
||||
|
||||
// noopPick merges the original onto head as one change and returns the tree
|
||||
// that writes for a clean merge, "" for a conflict, and whether the tree is
|
||||
// head's own: the content is there, whatever names it.
|
||||
func noopPick(head string, o *original) (string, bool, error) {
|
||||
stdout, stderr, code, err := gitStatus("merge-tree", "--write-tree", "--no-messages", "--merge-base="+o.merge+"^1", "--end-of-options", head, o.merge)
|
||||
switch {
|
||||
case err != nil:
|
||||
return false, err
|
||||
return "", false, err
|
||||
case code == 1:
|
||||
return false, nil
|
||||
return "", false, nil
|
||||
case code != 0:
|
||||
return false, fmt.Errorf("git merge-tree for #%d: exit %d: %s", o.number, code, strings.TrimSpace(stderr))
|
||||
return "", false, fmt.Errorf("git merge-tree for #%d: exit %d: %s", o.number, code, strings.TrimSpace(stderr))
|
||||
}
|
||||
tree, _, _ := strings.Cut(stdout, "\n")
|
||||
if err := checkSHA(tree); err != nil {
|
||||
return "", false, fmt.Errorf("git merge-tree for #%d: %w", o.number, err)
|
||||
}
|
||||
headTree, err := resolveTree(head)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return "", false, err
|
||||
}
|
||||
return tree == headTree, nil
|
||||
return tree, tree == headTree, nil
|
||||
}
|
||||
|
||||
func resolveTree(commit string) (string, error) {
|
||||
|
||||
@@ -202,6 +202,9 @@ func TestCarriedByTheBatch(t *testing.T) {
|
||||
{name: "the batch's bot", edit: func(pr *pullRequest, gh *fakeGH) {
|
||||
gh.bot = "cozystack-ci[bot]"
|
||||
pr.User.Login, pr.User.Type, pr.AuthorAssociation = "cozystack-ci[bot]", "Bot", "CONTRIBUTOR"
|
||||
// The bot writes the record into every body it opens.
|
||||
l, _ := parseLine("release-1.1")
|
||||
pr.Body = deferredBlock(l, nil, nil, nil)
|
||||
}, carried: true, notAsked: true},
|
||||
{name: "the batch's bot when no bot is configured", edit: func(pr *pullRequest, _ *fakeGH) {
|
||||
pr.User.Login, pr.User.Type = "cozystack-ci[bot]", "Bot"
|
||||
|
||||
+19
-13
@@ -207,29 +207,35 @@ func mainMerges(base, mainHead string) ([]*original, []string, error) {
|
||||
var merges []*original
|
||||
var other []string
|
||||
for _, m := range list {
|
||||
// The subject is the first paragraph, its lines joined, as git reads it.
|
||||
msg := strings.TrimRight(msgs[m.oid].message, "\n")
|
||||
subject, body, _ := strings.Cut(msg, "\n\n")
|
||||
subject = strings.ReplaceAll(subject, "\n", " ")
|
||||
o := &original{merge: m.oid, parents: m.parents, merged: msgs[m.oid].committed}
|
||||
if pr := mergePRRE.FindStringSubmatch(subject); pr != nil {
|
||||
o.number, _ = strconv.Atoi(pr[1])
|
||||
body = strings.TrimLeft(body, "\n")
|
||||
o.title, body, _ = strings.Cut(body, "\n")
|
||||
} else if pr := prNumberRE.FindStringSubmatchIndex(subject); pr != nil {
|
||||
o.number, _ = strconv.Atoi(subject[pr[2]:pr[3]])
|
||||
o.title = strings.TrimSpace(subject[:pr[0]])
|
||||
}
|
||||
o.number, o.title, o.body = mergedPR(msgs[m.oid].message)
|
||||
if o.number <= 0 || o.parents > 2 {
|
||||
other = append(other, m.oid)
|
||||
continue
|
||||
}
|
||||
o.body = strings.TrimLeft(body, "\n")
|
||||
merges = append(merges, o)
|
||||
}
|
||||
return merges, other, nil
|
||||
}
|
||||
|
||||
// mergedPR reads the pull request a commit on main's first-parent line
|
||||
// merged from its message, with its title and body; 0 when it names none.
|
||||
func mergedPR(message string) (int, string, string) {
|
||||
// The subject is the first paragraph, its lines joined, as git reads it.
|
||||
subject, body, _ := strings.Cut(strings.TrimRight(message, "\n"), "\n\n")
|
||||
subject = strings.ReplaceAll(subject, "\n", " ")
|
||||
number, title := 0, ""
|
||||
if pr := mergePRRE.FindStringSubmatch(subject); pr != nil {
|
||||
number, _ = strconv.Atoi(pr[1])
|
||||
body = strings.TrimLeft(body, "\n")
|
||||
title, body, _ = strings.Cut(body, "\n")
|
||||
} else if pr := prNumberRE.FindStringSubmatchIndex(subject); pr != nil {
|
||||
number, _ = strconv.Atoi(subject[pr[2]:pr[3]])
|
||||
title = strings.TrimSpace(subject[:pr[0]])
|
||||
}
|
||||
return number, title, strings.TrimLeft(body, "\n")
|
||||
}
|
||||
|
||||
// prCommits lists what an original brings to a line, one pick each: for a
|
||||
// merged pull request every commit of its own, oldest first, leaving out the
|
||||
// merges that brought main into its branch, whose content main already has;
|
||||
|
||||
+123
-30
@@ -34,10 +34,13 @@ Usage:
|
||||
backport-batch run --line release-X.Y [--onto SHA] [--date YYYY-MM-DD] [--no-workflow-files] [--push] [--policy REF]
|
||||
backport-batch run --line release-X.Y --continue [--no-workflow-files] [--push] [--policy REF]
|
||||
backport-batch run --line release-X.Y --defer N[,N] --reason TEXT [--push] [--policy REF]
|
||||
backport-batch run --line release-X.Y --drop N[,N] --reason TEXT [--push] [--policy REF]
|
||||
backport-batch run --line release-X.Y --undrop N[,N] [--push] [--policy REF]
|
||||
backport-batch check --line release-X.Y [--cut] [--policy REF]
|
||||
backport-batch fold --line release-X.Y --original N --commit SHA [--policy REF]
|
||||
backport-batch verify --line release-X.Y [--head SHA]
|
||||
backport-batch notify --line release-X.Y [--mention org/team|login] [--push]
|
||||
backport-batch report --pr N [--id ID] [--json]
|
||||
backport-batch lines [--policy REF]
|
||||
|
||||
run Builds backport-batch/<line>-<yyyymmdd> in this working tree, off
|
||||
@@ -53,7 +56,13 @@ run Builds backport-batch/<line>-<yyyymmdd> in this working tree, off
|
||||
--defer rebuilds the open batch off origin/<line> without those
|
||||
originals and records them as deferred, for --reason: the batch keeps
|
||||
them out, the next one tries them again. --push replaces the branch,
|
||||
leased on the head the rebuild started from.
|
||||
leased on the head the rebuild started from; when nothing is left it
|
||||
closes the batch PR instead, after recording why in it.
|
||||
--drop drops originals from the line for --reason: the line's record
|
||||
keeps them out of this batch and every later one. One the open batch
|
||||
carries is taken off it as --defer would; otherwise only the record
|
||||
changes. --undrop withdraws a drop. Both need an open batch PR whose
|
||||
record they change.
|
||||
check Exits 1 while a change the policy takes is neither on the line nor on
|
||||
the open batch PR, 0 when nothing is, 2 when it cannot tell. With --cut,
|
||||
the gate before an rc or a patch is cut, it also exits 1 while a change
|
||||
@@ -69,11 +78,18 @@ notify Prints what waits on the open batch PR for a maintainer: a batch
|
||||
open for 3 days or more, its deferred conflicts, and the originals
|
||||
that change workflows. --push keeps one comment on the PR that says
|
||||
what waits, mentioning --mention.
|
||||
report Prints a report batch PR N keeps: the one its body carries, or the
|
||||
one --id names, read from its comments or its body. --json prints the
|
||||
report as it is stored. It writes nothing, so it reads merged and
|
||||
closed batches too.
|
||||
lines Prints the release lines the batch runs for, newest first.
|
||||
|
||||
The policy is docs/release/backports.md. run, check, fold and lines read its
|
||||
policy block from that page on origin/main, or on --policy REF. Every command
|
||||
but notify, which reads only GitHub, fetches origin first.
|
||||
but notify and report fetches origin first. notify reads only GitHub; report
|
||||
reads GitHub, and for a report that keeps drops also this clone's history,
|
||||
which has to hold the main and line heads the report was made from: report
|
||||
never fetches on its own.
|
||||
|
||||
BACKPORT_BATCH_BOT names the bot the scheduled batch writes as,
|
||||
<app>[bot], cozystack-ci[bot] when unset: a batch pull request or a notify
|
||||
@@ -93,15 +109,18 @@ type app struct {
|
||||
now func() time.Time
|
||||
// policyRef is where the policy page is read from; origin/main when empty.
|
||||
policyRef string
|
||||
// tool is the commit backport-batch was built from, for the record.
|
||||
tool string
|
||||
}
|
||||
|
||||
func main() {
|
||||
a := &app{gh: ghCLI{bot: batchBotLogin(os.LookupEnv)}, stdout: os.Stdout, stderr: os.Stderr, now: time.Now}
|
||||
a := &app{gh: ghCLI{bot: batchBotLogin(os.LookupEnv)}, stdout: os.Stdout, stderr: os.Stderr, now: time.Now, tool: toolVersion()}
|
||||
os.Exit(a.main(os.Args[1:]))
|
||||
}
|
||||
|
||||
func (a *app) main(args []string) int {
|
||||
a.stdout, a.stderr = textWriter{a.stdout}, textWriter{a.stderr}
|
||||
a.gh = &permCache{github: a.gh, perms: map[string]string{}}
|
||||
if len(args) == 0 {
|
||||
fmt.Fprint(a.stderr, usageText)
|
||||
return 2
|
||||
@@ -120,6 +139,8 @@ func (a *app) main(args []string) int {
|
||||
return a.verify(args[1:])
|
||||
case "notify":
|
||||
return a.notify(args[1:])
|
||||
case "report":
|
||||
return a.report(args[1:])
|
||||
case "lines":
|
||||
return a.lines(args[1:])
|
||||
case "-h", "--help", "help":
|
||||
@@ -186,10 +207,22 @@ type verdict struct {
|
||||
// and by load for anything else.
|
||||
commits []string
|
||||
changes []fileChange
|
||||
// onBatch is the commit of the open batch pull request that picks it.
|
||||
// onBatch is the commit of the open batch pull request that picks it,
|
||||
// and batched the unit of the open batch that carries it whatever the
|
||||
// rules now say of it.
|
||||
onBatch string
|
||||
batched string
|
||||
// label is the maintainer override the original carries, if any.
|
||||
label string
|
||||
// partial lists what its clean net merge onto the line would leave
|
||||
// without effect, and park why the batch leaves it out, if it does.
|
||||
partial []string
|
||||
park *parkedEntry
|
||||
// deps is what it builds on that the line lacks.
|
||||
deps []dependency
|
||||
// diag is what could not be judged about it, shown whatever became of
|
||||
// it.
|
||||
diag []string
|
||||
}
|
||||
|
||||
// batch is everything read about a line before anything is written.
|
||||
@@ -198,16 +231,50 @@ type batch struct {
|
||||
newer *line
|
||||
lineHead string
|
||||
mainHead string
|
||||
base string
|
||||
other []string
|
||||
verdicts []*verdict
|
||||
pr *pullRequest
|
||||
prHead string
|
||||
// newerHead is the newer line's head, and policyAt the commit the
|
||||
// policy was read from.
|
||||
newerHead string
|
||||
policyAt string
|
||||
base string
|
||||
other []string
|
||||
verdicts []*verdict
|
||||
pr *pullRequest
|
||||
prHead string
|
||||
// picks is what the open batch pull request carries beyond the line.
|
||||
picks *history
|
||||
// src is the line's record and where it was found, and drops its drops
|
||||
// that name an original of this batch.
|
||||
src recordSource
|
||||
drops map[int]droppedEntry
|
||||
// lineHist and newerHist are what the line and the newer line carry,
|
||||
// read once for every original judged.
|
||||
lineHist, newerHist *history
|
||||
// start is when the line started under the policy, zero for its fork point.
|
||||
start time.Time
|
||||
// textUntil is the batch-only day: what a commit's text says counts as
|
||||
// evidence only on commits from before it.
|
||||
textUntil time.Time
|
||||
// partialUnits are the originals whose unit on the open batch leaves
|
||||
// what it lists without effect.
|
||||
partialUnits map[*verdict][]string
|
||||
// What one command read once and asks again: renames by commit pair,
|
||||
// units by batch head, and how often git merge-file ran.
|
||||
renameCache map[string]renameSet
|
||||
unitCache map[string]map[*verdict]string
|
||||
mergeFiles int
|
||||
// renameLimit is the -l rename detection runs with; 0, git's widest.
|
||||
renameLimit int
|
||||
// brought maps main's commits since the fork point to the first-parent
|
||||
// commit that brought each, and ancestors says which commits blame
|
||||
// named are older than the fork point.
|
||||
brought map[string]string
|
||||
ancestors map[string]bool
|
||||
// detecting is how long judging partial units and dependencies took.
|
||||
detecting time.Duration
|
||||
depCache map[string][]dependency
|
||||
// lineCarries says, for a prerequisite the rules keep out, whether the
|
||||
// line carries it all the same.
|
||||
lineCarries map[*verdict]bool
|
||||
}
|
||||
|
||||
// fetch moves to the top of the working tree first: every path the batch
|
||||
@@ -224,18 +291,20 @@ func fetch() error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *app) policy(mainHead string) (*policy, error) {
|
||||
// policy reads the policy and says from which commit.
|
||||
func (a *app) policy(mainHead string) (*policy, string, error) {
|
||||
at := mainHead
|
||||
if a.policyRef != "" {
|
||||
if strings.HasPrefix(a.policyRef, "-") {
|
||||
return nil, fmt.Errorf("--policy %q is not a ref", a.policyRef)
|
||||
return nil, "", fmt.Errorf("--policy %q is not a ref", a.policyRef)
|
||||
}
|
||||
var err error
|
||||
if at, err = resolve(a.policyRef); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
return readPolicy(at)
|
||||
pol, err := readPolicy(at)
|
||||
return pol, at, err
|
||||
}
|
||||
|
||||
// prepare reads the line, main and the open batch pull request, each pinned to
|
||||
@@ -246,7 +315,7 @@ func (a *app) prepare(l line) (*batch, error) {
|
||||
if b.mainHead, err = resolve("refs/remotes/" + remote + "/main"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pol, err := a.policy(b.mainHead)
|
||||
pol, policyAt, err := a.policy(b.mainHead)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -260,7 +329,7 @@ func (a *app) prepare(l line) (*batch, error) {
|
||||
if b.lineHead, err = resolve("refs/remotes/" + remote + "/" + l.branch()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.start, b.textUntil = pol.starts[l.branch()], pol.batchOnly
|
||||
b.start, b.textUntil, b.policyAt = pol.starts[l.branch()], pol.batchOnly, policyAt
|
||||
out, err := git("merge-base", "--end-of-options", b.mainHead, b.lineHead)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s shares no history with main: %w", l.branch(), err)
|
||||
@@ -271,17 +340,14 @@ func (a *app) prepare(l line) (*batch, error) {
|
||||
return nil, err
|
||||
}
|
||||
b.other = other
|
||||
lineHist, err := readHistory(b.lineHead, b.mainHead, b.textUntil)
|
||||
if err != nil {
|
||||
if b.lineHist, err = readHistory(b.lineHead, b.mainHead, b.textUntil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var newerHist *history
|
||||
if b.newer != nil {
|
||||
newerHead, err := resolve("refs/remotes/" + remote + "/" + b.newer.branch())
|
||||
if err != nil {
|
||||
if b.newerHead, err = resolve("refs/remotes/" + remote + "/" + b.newer.branch()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if newerHist, err = readHistory(newerHead, b.mainHead, b.textUntil); err != nil {
|
||||
if b.newerHist, err = readHistory(b.newerHead, b.mainHead, b.textUntil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -300,29 +366,51 @@ func (a *app) prepare(l line) (*batch, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var prPicks *history
|
||||
if pr != nil {
|
||||
b.pr = pr
|
||||
if b.prHead, err = batchHead(pr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if prPicks, err = readPicks(b.prHead, b.lineHead, b.textUntil); err != nil {
|
||||
if b.picks, err = readPicks(b.prHead, b.lineHead, b.textUntil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if b.src, err = findLineRecord(a.gh, l, pr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if b.drops, err = b.bindDrops(merges); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := b.waitOrder(merges); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, o := range merges {
|
||||
v, err := judge(o, labels[o.number], b.start, lineHist, b.newer, newerHist)
|
||||
if err != nil {
|
||||
v := &verdict{o: o, label: labels[o.number]}
|
||||
if err := b.judge(v, b.drops); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if v.rule == 0 && prPicks != nil {
|
||||
v.onBatch, _ = prPicks.found(v.o, v.commits)
|
||||
}
|
||||
b.verdicts = append(b.verdicts, v)
|
||||
}
|
||||
if err := b.partialStates(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// judge judges v again under drops, and finds it on the open batch when the
|
||||
// policy takes it.
|
||||
func (b *batch) judge(v *verdict, drops map[int]droppedEntry) error {
|
||||
j, err := judge(v.o, v.label, b.start, b.lineHist, b.newer, b.newerHist, drops)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*v = *j
|
||||
if v.rule == 0 && b.picks != nil {
|
||||
v.onBatch, _ = b.picks.found(v.o, v.commits)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// overrides maps each pull request merged into main that carries a backport/
|
||||
// label to the one that decides; backport/skip wins over backport/include.
|
||||
func overrides(gh github) (map[int]string, error) {
|
||||
@@ -344,8 +432,9 @@ func overrides(gh github) (map[int]string, error) {
|
||||
// started under the policy after it branched takes nothing merged before that
|
||||
// start. backport/skip keeps an original out whatever the rules say, and
|
||||
// backport/include lifts the start and rules 2 to 4, but not what the line or
|
||||
// the newer line carries.
|
||||
func judge(o *original, label string, start time.Time, lineHist *history, newer *line, newerHist *history) (*verdict, error) {
|
||||
// the newer line carries. A maintainer's drop keeps out what the line does
|
||||
// not carry, include or not.
|
||||
func judge(o *original, label string, start time.Time, lineHist *history, newer *line, newerHist *history, drops map[int]droppedEntry) (*verdict, error) {
|
||||
v := &verdict{o: o, label: label}
|
||||
if label == labelSkip {
|
||||
v.rule, v.reason = ruleSkipLabel, labelSkip
|
||||
@@ -388,6 +477,10 @@ func judge(o *original, label string, start time.Time, lineHist *history, newer
|
||||
v.rule, v.reason = ruleOnLine, how
|
||||
return v, nil
|
||||
}
|
||||
if d, ok := drops[o.number]; ok {
|
||||
v.rule, v.reason = ruleDropped, fmt.Sprintf("dropped on #%d: %s", d.On, d.Reason)
|
||||
return v, nil
|
||||
}
|
||||
if newer != nil {
|
||||
how, err := newerHist.carries(o, v.commits)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// releaseNoteBlock is the release-note block of a body.
|
||||
func releaseNoteBlock(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
m := regexp.MustCompile("(?s)```release-note\n(.*?)\n```").FindStringSubmatch(body)
|
||||
if m == nil {
|
||||
t.Fatalf("no release-note block in:\n%s", body)
|
||||
}
|
||||
return m[1]
|
||||
}
|
||||
|
||||
// A pick that differs from its original keeps its release note out of the
|
||||
// release-note block, under Check these notes with what to compare: one git
|
||||
// had to fit to a line that already had part of the change, and one whose
|
||||
// first commit came out empty because the line had resized the value itself.
|
||||
func TestChangedOriginalNoteIsSetApart(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): two, on the line", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.onLine("release-1.1", "fix(chart): two replicas, on the line", map[string]string{"chart/values.yaml": "replicas: 2\nimage: app:1\n"})
|
||||
f.pr(5, "fix(app): two and four", "```release-note\nfix(app): two and four are loud.\n```\n", map[string]string{"app/a.txt": strings.NewReplacer("two", "TWO", "four", "FOUR").Replace(appFile)})
|
||||
f.prCommits(6, "fix(chart): two replicas and six", "```release-note\nfix(chart): two replicas by default.\n```\n",
|
||||
change{files: map[string]string{"chart/values.yaml": "replicas: 2\nimage: app:1\n"}},
|
||||
change{files: map[string]string{"app/six.txt": "6\n"}})
|
||||
f.pr(7, "fix(app): seven", "```release-note\nfix(app): seven is calm.\n```\n", map[string]string{"app/seven.txt": "7\n"})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1")
|
||||
if code != 0 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): two and four (#5)", "fix(chart): two replicas and six (#6)", "fix(app): seven (#7)"}) {
|
||||
t.Fatalf("picked %q, want #5, #6 and #7", got)
|
||||
}
|
||||
notes := releaseNoteBlock(t, stdout)
|
||||
if !strings.Contains(notes, "seven is calm") || strings.Contains(notes, "two and four are loud") || strings.Contains(notes, "two replicas by default") {
|
||||
t.Errorf("the release-note block keeps a changed pick's note, or loses #7's:\n%s", notes)
|
||||
}
|
||||
_, check, ok := strings.Cut(stdout, "### Check these notes")
|
||||
check, _, _ = strings.Cut(check, "\n#")
|
||||
if !ok || !strings.Contains(check, "two and four are loud") || !strings.Contains(check, "two replicas by default") || strings.Contains(check, "seven is calm") {
|
||||
t.Errorf("Check these notes does not list #5 and #6 alone:\n%s", stdout)
|
||||
}
|
||||
if !strings.Contains(stdout, `"changed":[5,6]`) {
|
||||
t.Errorf("the record or the report does not mark #5 and #6 changed:\n%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// The command printed for a changed pick pairs the pick with the commit it
|
||||
// came from, however much the pick lost: the default creation factor leaves
|
||||
// a pick that carries only #5088's test unpaired.
|
||||
func TestRangeDiffCommandPairsThePick(t *testing.T) {
|
||||
f, mc5 := policyWorld(t)
|
||||
gh := &fakeGH{}
|
||||
head := handBatch(f, gh, mc5)
|
||||
code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue")
|
||||
if code != 0 {
|
||||
t.Fatalf("run --continue = %d\n%s", code, stderr)
|
||||
}
|
||||
m := regexp.MustCompile("`git range-diff --creation-factor=999 ([0-9a-f]{12})\\^! ([0-9a-f]{12})\\^!`").FindStringSubmatch(stdout)
|
||||
if m == nil {
|
||||
t.Fatalf("the body prints no range-diff for #5's pick:\n%s", stdout)
|
||||
}
|
||||
src, pick := f.git("rev-parse", mc5+"^2"), f.git("rev-parse", head+"^2")
|
||||
if !strings.HasPrefix(src, m[1]) || !strings.HasPrefix(pick, m[2]) {
|
||||
t.Errorf("the range-diff names %s and %s, want #5's commit %.12s and its pick %.12s", m[1], m[2], src, pick)
|
||||
}
|
||||
out, err := exec.Command("git", "range-diff", "--no-color", "--creation-factor=999", m[1]+"^!", m[2]+"^!").Output()
|
||||
if want := "1: " + f.git("rev-parse", "--short", src) + " ! 1: " + f.git("rev-parse", "--short", pick); err != nil || !strings.HasPrefix(string(out), want) {
|
||||
t.Errorf("the printed range-diff gives %q, %v; want it to start %q", out, err, want)
|
||||
}
|
||||
if out := f.git("range-diff", "--no-color", mc5+"^1.."+mc5+"^2", head+"^1.."+head+"^2"); !strings.Contains(out, " < ") {
|
||||
t.Errorf("the default creation factor pairs #5's pick after all, so the test shows nothing:\n%s", out)
|
||||
}
|
||||
}
|
||||
+162
-15
@@ -70,6 +70,15 @@ func (a *app) notify(args []string) int {
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
// With no batch open there is nothing to report on and nowhere to write,
|
||||
// but a record nobody can read is said all the same.
|
||||
src, err := findLineRecord(a.gh, l, pr)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if c := src.closingOpen(); c != nil {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d is being closed; backport-batch run --line %s --push finishes it", c.PR, l.branch()))
|
||||
}
|
||||
if pr == nil {
|
||||
return 0
|
||||
}
|
||||
@@ -77,21 +86,49 @@ func (a *app) notify(args []string) int {
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
deferred, err := parseDeferred(pr.Body, l)
|
||||
if err != nil {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d: %w", pr.Number, err))
|
||||
deferred := map[int]deferredEntry{}
|
||||
var partial []int
|
||||
var parks []parkedEntry
|
||||
if src.open {
|
||||
deferred, partial = src.rec.deferred(), src.rec.Partial
|
||||
for _, p := range src.rec.Parked {
|
||||
if !p.Announced {
|
||||
parks = append(parks, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
// An original that waits on others is listed once, after what decides
|
||||
// its wait, where that one is listed.
|
||||
var conflicts, waiting []int
|
||||
after := map[int][]int{}
|
||||
for n, e := range deferred {
|
||||
switch {
|
||||
case e.Workflows:
|
||||
switch place := placement(deferred, n, map[int]bool{}); {
|
||||
case place == "workflow":
|
||||
waiting = append(waiting, n)
|
||||
case e.Reason == "":
|
||||
case place == "conflict":
|
||||
conflicts = append(conflicts, n)
|
||||
}
|
||||
if len(e.Needs) > 0 {
|
||||
after[n] = e.Needs
|
||||
}
|
||||
}
|
||||
slices.Sort(conflicts)
|
||||
slices.Sort(waiting)
|
||||
item := func(n int) string {
|
||||
if needs := after[n]; len(needs) > 0 {
|
||||
return fmt.Sprintf("\n- %s, after %s", prLink(n), prLinks(needs))
|
||||
}
|
||||
return "\n- " + prLink(n)
|
||||
}
|
||||
count := func(ns []int) int {
|
||||
c := 0
|
||||
for _, n := range ns {
|
||||
if len(after[n]) == 0 {
|
||||
c++
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
today := a.now().UTC().Truncate(24 * time.Hour)
|
||||
days := int(today.Sub(opened).Hours() / 24)
|
||||
@@ -101,28 +138,135 @@ func (a *app) notify(args []string) int {
|
||||
fmt.Fprintf(a.stdout, "%s: batch pull request #%d has been open since %s, %d days\n", l.branch(), pr.Number, opened.Format(time.DateOnly), days)
|
||||
text = append(text, fmt.Sprintf("This batch has been open since %s, %d days, through at least one scheduled run. Merge it, or close it and the next run starts a new one; until then each run adds what the rules take to it.", opened.Format(time.DateOnly), days))
|
||||
}
|
||||
if len(conflicts) > 0 {
|
||||
fmt.Fprintf(a.stdout, "%s: %d deferred conflicts on #%d wait for a maintainer\n", l.branch(), len(conflicts), pr.Number)
|
||||
if len(partial) > 0 {
|
||||
fmt.Fprintf(a.stdout, "%s: %d units on #%d carry only part of their originals\n", l.branch(), len(partial), pr.Number)
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "These conflicts wait for a maintainer, as [resolving a conflict](%sresolve-conflict.md) describes; unresolved, each goes to the next batch:\n", tasksURL)
|
||||
b.WriteString("These are on the batch but carry only part of their originals on this line; take each out with `backport-batch run --defer` before the cut, and port what applies as a pull request of its own:\n")
|
||||
for _, n := range partial {
|
||||
b.WriteString(item(n))
|
||||
}
|
||||
text = append(text, b.String())
|
||||
}
|
||||
if len(conflicts) > 0 {
|
||||
fmt.Fprintf(a.stdout, "%s: %d deferred conflicts on #%d wait for a maintainer\n", l.branch(), count(conflicts), pr.Number)
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "These conflicts wait for a maintainer, as [resolving a conflict](%sresolve-conflict.md) describes; unresolved, each goes to the next batch, and so does what waits on one:\n", tasksURL)
|
||||
for _, n := range conflicts {
|
||||
fmt.Fprintf(&b, "\n- %s", prLink(n))
|
||||
b.WriteString(item(n))
|
||||
}
|
||||
text = append(text, b.String())
|
||||
}
|
||||
if len(waiting) > 0 {
|
||||
fmt.Fprintf(a.stdout, "%s: %d originals on #%d change %s and wait for a maintainer\n", l.branch(), len(waiting), pr.Number, workflowsDir)
|
||||
if count(waiting) == len(waiting) {
|
||||
fmt.Fprintf(a.stdout, "%s: %d originals on #%d change %s and wait for a maintainer\n", l.branch(), len(waiting), pr.Number, workflowsDir)
|
||||
} else {
|
||||
fmt.Fprintf(a.stdout, "%s: %d originals on #%d change %s or wait on one that does\n", l.branch(), len(waiting), pr.Number, workflowsDir)
|
||||
}
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "These change `%s`, which the batch's token may not push, and wait for a maintainer to bring them over, as [changes to workflows](%s#changes-to-workflows) describes:\n", workflowsDir, policyURL)
|
||||
fmt.Fprintf(&b, "These change `%s`, which the batch's token may not push, and wait for a maintainer to bring them over, as [changes to workflows](%s#changes-to-workflows) describes, or wait on one that does:\n", workflowsDir, policyURL)
|
||||
for _, n := range waiting {
|
||||
fmt.Fprintf(&b, "\n- %s", prLink(n))
|
||||
b.WriteString(item(n))
|
||||
}
|
||||
text = append(text, b.String())
|
||||
}
|
||||
if len(parks) > 0 {
|
||||
fmt.Fprintf(a.stdout, "%s: %d parked originals on #%d, named once\n", l.branch(), len(parks), pr.Number)
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "These cannot land on this line whole, so the batch parked them; each is named here once. A maintainer ports what applies as a pull request of its own, as [fixes that exist only on a release line](%s#fixes-that-exist-only-on-a-release-line) describes, or drops the original with `backport-batch run --drop`:\n", policyURL)
|
||||
for _, p := range parks {
|
||||
fmt.Fprintf(&b, "\n- %s: %s", prLink(p.Original), parkReason(p))
|
||||
}
|
||||
text = append(text, b.String())
|
||||
}
|
||||
if !*push {
|
||||
return 0
|
||||
}
|
||||
return a.comment(pr, *mention, today, text)
|
||||
if code := a.comment(pr, *mention, today, text); code != 0 || len(parks) == 0 {
|
||||
return code
|
||||
}
|
||||
if err := a.announced(pr, src.rec, parks); err != nil {
|
||||
return a.fail(fmt.Errorf("%w; the next notify names them again", err))
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// announced marks parks as named in the record of the open batch pull
|
||||
// request, which the comment just named: only while it is open and its body
|
||||
// still carries the record notify read, so a run that rewrote the body
|
||||
// meanwhile loses nothing; the next notify names those parks again.
|
||||
func (a *app) announced(pr *pullRequest, rec *lineRecord, parks []parkedEntry) error {
|
||||
marked := *rec
|
||||
marked.Parked = slices.Clone(rec.Parked)
|
||||
for i, p := range marked.Parked {
|
||||
if slices.ContainsFunc(parks, func(q parkedEntry) bool { return q.Original == p.Original && parkEvent(q) == parkEvent(p) }) {
|
||||
marked.Parked[i].Announced = true
|
||||
}
|
||||
}
|
||||
now, err := a.gh.pull(pr.Number)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if st := prState(&now); st != "open" {
|
||||
return fmt.Errorf("batch pull request #%d is %s now; nothing is written to it", pr.Number, st)
|
||||
}
|
||||
lines, err := fencedLines(now.Body, deferredFence)
|
||||
if err != nil || len(lines) != 1 {
|
||||
return fmt.Errorf("batch pull request #%d no longer carries the record notify read", pr.Number)
|
||||
}
|
||||
read, err := parseRecord(now.Body, notifyLineOf(rec))
|
||||
if err != nil || recordBlock(*read) != recordBlock(*rec) {
|
||||
return fmt.Errorf("batch pull request #%d no longer carries the record notify read", pr.Number)
|
||||
}
|
||||
// GitHub keeps the CRLF line ends a body edited on the web has; the
|
||||
// record is found, and the body written back, with LF ones.
|
||||
body := strings.ReplaceAll(now.Body, "\r\n", "\n")
|
||||
block := deferredFence + "\n" + lines[0] + "\n```"
|
||||
if strings.Count(body, block) != 1 {
|
||||
return fmt.Errorf("batch pull request #%d carries the record notify read, but not as one block it can mark", pr.Number)
|
||||
}
|
||||
body = strings.Replace(body, block, recordBlock(marked), 1)
|
||||
name, err := writeTemp("backport-batch-body-*.md", body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(name)
|
||||
return a.gh.editBody(pr.Number, name)
|
||||
}
|
||||
|
||||
// notifyLineOf is the line a record is for, which it was read against.
|
||||
func notifyLineOf(rec *lineRecord) line {
|
||||
l, _ := parseLine(rec.Line)
|
||||
return l
|
||||
}
|
||||
|
||||
// placement says under which list notify names original n of the record:
|
||||
// workflow for a wait for a maintainer, conflict for a deferred conflict, ""
|
||||
// for neither, a deferral for a reason among them. One that waits on others
|
||||
// goes where what decides its wait goes, followed down the record; one that
|
||||
// is not in the record is held by rule 6 or missing, and waits on nobody.
|
||||
func placement(deferred map[int]deferredEntry, n int, seen map[int]bool) string {
|
||||
e, ok := deferred[n]
|
||||
switch {
|
||||
case !ok || seen[n]:
|
||||
return ""
|
||||
case e.Workflows:
|
||||
return "workflow"
|
||||
case e.Reason != "":
|
||||
return ""
|
||||
case len(e.Needs) == 0:
|
||||
return "conflict"
|
||||
}
|
||||
seen[n] = true
|
||||
place := ""
|
||||
for _, f := range e.Needs {
|
||||
switch p := placement(deferred, f, seen); {
|
||||
case p == "workflow":
|
||||
return p
|
||||
case p == "conflict":
|
||||
place = p
|
||||
}
|
||||
}
|
||||
return place
|
||||
}
|
||||
|
||||
// comment writes what waits into the one notify comment on the batch pull
|
||||
@@ -173,6 +317,9 @@ func (a *app) comment(pr *pullRequest, mention string, today time.Time, text []s
|
||||
if err := f.Close(); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if err := a.stillOpen(pr.Number); err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if ours != nil {
|
||||
err = a.gh.editComment(ours.ID, f.Name())
|
||||
} else {
|
||||
@@ -198,7 +345,7 @@ func (a *app) lines(args []string) int {
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
pol, err := a.policy(mainHead)
|
||||
pol, _, err := a.policy(mainHead)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -148,7 +149,8 @@ func TestNotifyFindsTheBotsComment(t *testing.T) {
|
||||
ours.User.Login, ours.User.Type = bot, "Bot"
|
||||
other := issueComment{ID: 8, Body: notifyMarker + "\nplanted"}
|
||||
other.User.Login, other.User.Type = "renovate[bot]", "Bot"
|
||||
pr := notifyPR("20261019", "")
|
||||
// The bot writes the record into every body it opens.
|
||||
pr := notifyPR("20261019", deferredBlock(notifyLine, nil, nil, nil))
|
||||
pr.User.Login, pr.User.Type = bot, "Bot"
|
||||
gh := &fakeGH{prs: []pullRequest{pr}, issueComments: []issueComment{ours, other}, bot: bot}
|
||||
if code, stdout, stderr := notifyRun(gh, "--push"); code != 0 || !strings.Contains(stdout, "has been open since") {
|
||||
@@ -172,7 +174,7 @@ func TestNotifyFailsOnAnUnreadablePermission(t *testing.T) {
|
||||
}
|
||||
|
||||
const bot = "cozystack-ci[bot]"
|
||||
pr := notifyPR("20261019", "")
|
||||
pr := notifyPR("20261019", deferredBlock(notifyLine, nil, nil, nil))
|
||||
pr.User.Login, pr.User.Type = bot, "Bot"
|
||||
ours := issueComment{ID: 7, Body: notifyMarker + "\nearlier"}
|
||||
ours.User.Login, ours.User.Type = "maintainer", "User"
|
||||
@@ -203,6 +205,32 @@ func TestNotifyRefuses(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// notify reads the line's record the way the other commands do, and stays
|
||||
// silent with no batch open, but a record it cannot read, or one that says
|
||||
// its open batch is being closed, stops it.
|
||||
func TestNotifyValidatesTheRecord(t *testing.T) {
|
||||
sha := strings.Repeat("a", 40)
|
||||
closingRecord := strings.Replace(v2(""), `"closing":null`, `"closing":{"pr":91,"branch":"backport-batch/release-1.1-20261002","head":"`+sha+`"}`, 1)
|
||||
block := func(json string) string { return "text\n\n" + deferredFence + "\n" + json + "\n```\n" }
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
pr pullRequest
|
||||
code int
|
||||
quiet bool
|
||||
}{
|
||||
{"a clean closed record", recordPR(91, "closed", "maintainer", block(v2(""))), 0, true},
|
||||
{"a malformed record", recordPR(91, "closed", "maintainer", block(`{"line":`)), 2, false},
|
||||
{"a closed record that was closing", recordPR(91, "closed", "maintainer", block(closingRecord)), 0, true},
|
||||
{"an open record that is closing", recordPR(91, "open", "maintainer", block(closingRecord)), 2, false},
|
||||
} {
|
||||
gh := &fakeGH{prs: []pullRequest{tc.pr}}
|
||||
code, stdout, stderr := notifyRun(gh, "--push")
|
||||
if code != tc.code || tc.quiet && (stdout != "" || stderr != "") || len(gh.issueComments) != 0 {
|
||||
t.Errorf("%s: notify = %d, %q, %q, %d comments; want %d and nothing written", tc.name, code, stdout, stderr, len(gh.issueComments), tc.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The maintainer's example: with 1.6 and 1.7 released, release-1.8 joins them
|
||||
// when it branches, and 1.8.0 drops 1.6.
|
||||
func TestSupportedLines(t *testing.T) {
|
||||
@@ -286,3 +314,183 @@ func TestRunWithNothingToPick(t *testing.T) {
|
||||
t.Errorf("pushed %q and opened %q with nothing picked", f.remoteHead(batchBranch1), gh.created)
|
||||
}
|
||||
}
|
||||
|
||||
// notify writes its comment only after GitHub says the batch is still open,
|
||||
// so a batch closed while notify reads it is not written to, whether the
|
||||
// comment would be new or an update of its own.
|
||||
func TestNotifyWritesNothingOnABatchClosedMeanwhile(t *testing.T) {
|
||||
for _, update := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "a new comment", true: "an update"}[update], func(t *testing.T) {
|
||||
gh := &fakeGH{prs: []pullRequest{notifyPR("20261023", recordBody(5))}}
|
||||
if update {
|
||||
ours := issueComment{ID: 7, Body: notifyMarker + "\nearlier"}
|
||||
ours.User.Login, ours.User.Type = "maintainer", "User"
|
||||
gh.issueComments = []issueComment{ours}
|
||||
}
|
||||
gh.after = map[string]func(){"comments": func() { gh.find(90).State = "closed" }}
|
||||
code, _, stderr := notifyRun(gh, "--push")
|
||||
if code != 2 || !strings.Contains(stderr, "batch pull request #90 is closed now; nothing is written to it") || len(gh.closedWrites) != 0 || update && gh.issueComments[0].Body != notifyMarker+"\nearlier" {
|
||||
t.Errorf("notify = %d, closed writes %q, comments %+v; want 2 and nothing written:\n%s", code, gh.closedWrites, gh.issueComments, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// parkedBody is an open batch body whose version 3 record parks p.
|
||||
func parkedBody(p ...parkedEntry) string {
|
||||
sha := strings.Repeat("a", 40)
|
||||
rec := lineRecord{Version: recordVersion, Line: "release-1.1", Report: strings.Repeat("b", 64),
|
||||
Built: &builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{Mode: modeContinue}},
|
||||
Deferred: []deferredEntry{}, Dropped: []droppedEntry{}, Stale: []int{}, Parked: p}
|
||||
return "batch\n\n" + recordBlock(rec) + "\n"
|
||||
}
|
||||
|
||||
// notifyAt runs notify at a time of day, with gh faked.
|
||||
func notifyAt(gh *fakeGH, at time.Time, args ...string) (int, string, string) {
|
||||
var stdout, stderr bytes.Buffer
|
||||
a := &app{gh: gh, stdout: &stdout, stderr: &stderr, now: func() time.Time { return at }}
|
||||
code := a.main(append([]string{"notify", "--line", "release-1.1"}, args...))
|
||||
return code, stdout.String(), stderr.String()
|
||||
}
|
||||
|
||||
// A park is announced once on the open batch: notify names it in its
|
||||
// comment and marks it announced in the record; a later notify is silent
|
||||
// about it. A mark that fails to land repeats the announcement once, the
|
||||
// next day. With no batch open nothing is announced, and the first notify of
|
||||
// the next batch does it.
|
||||
func TestNotifyAnnouncesAParkOnce(t *testing.T) {
|
||||
park := parkedEntry{Original: 5, Merge: strings.Repeat("c", 40), Kind: parkDependency, Needs: []int{3}}
|
||||
parked := func(gh *fakeGH) []parkedEntry {
|
||||
t.Helper()
|
||||
rec, err := parseRecord(gh.prs[0].Body, notifyLine)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return rec.Parked
|
||||
}
|
||||
gh := &fakeGH{prs: []pullRequest{notifyPR("20261026", parkedBody(park))}}
|
||||
code, stdout, stderr := notifyRun(gh, "--push")
|
||||
if code != 0 || !strings.Contains(stdout, "release-1.1: 1 parked originals on #90, named once") || len(gh.issueComments) != 1 || !strings.Contains(gh.issueComments[0].Body, "- [#5](https://github.com/cozystack/cozystack/pull/5): builds on [#3](") {
|
||||
t.Fatalf("notify = %d, want #5 announced:\n%s\n%s\n%v", code, stdout, stderr, gh.issueComments)
|
||||
}
|
||||
if p := parked(gh); len(p) != 1 || !p[0].Announced {
|
||||
t.Errorf("the record parks %+v, want #5 marked announced", p)
|
||||
}
|
||||
if code, stdout, _ = notifyRun(gh, "--push"); code != 0 || strings.Contains(stdout, "parked") || strings.Contains(gh.issueComments[0].Body, "[#5]") {
|
||||
t.Errorf("notify again = %d, want nothing about #5:\n%s\n%s", code, stdout, gh.issueComments[0].Body)
|
||||
}
|
||||
|
||||
gh = &fakeGH{prs: []pullRequest{notifyPR("20261026", parkedBody(park))}, fail: map[string]error{"editBody": errors.New("HTTP 502")}}
|
||||
if code, _, _ := notifyRun(gh, "--push"); code != 2 || len(gh.issueComments) != 1 || parked(gh)[0].Announced {
|
||||
t.Fatalf("notify with a failing mark = %d, want 2 after the comment, the record unmarked", code)
|
||||
}
|
||||
code, _, stderr = notifyAt(gh, time.Date(2026, 10, 27, 0, 5, 0, 0, time.UTC), "--push")
|
||||
if code != 0 || !strings.Contains(gh.issueComments[0].Body, "[#5](") || !parked(gh)[0].Announced {
|
||||
t.Errorf("notify the next day = %d, want #5 named once more and marked:\n%s\n%s", code, stderr, gh.issueComments[0].Body)
|
||||
}
|
||||
|
||||
// Closed, or rewritten by a run, between the comment and the mark: the
|
||||
// mark is not written, and the next notify names #5 again.
|
||||
gh = &fakeGH{prs: []pullRequest{notifyPR("20261026", parkedBody(park))}}
|
||||
gh.after = map[string]func(){"createComment": func() { gh.prs[0].State = "closed" }}
|
||||
if code, _, _ := notifyRun(gh, "--push"); code != 2 || len(gh.closedWrites) != 0 || parked(gh)[0].Announced {
|
||||
t.Errorf("notify on a batch closed meanwhile = %d, writes %q; want 2 and no mark", code, gh.closedWrites)
|
||||
}
|
||||
gh = &fakeGH{prs: []pullRequest{notifyPR("20261026", parkedBody(park))}}
|
||||
rewritten := parkedBody(park, parkedEntry{Original: 6, Merge: strings.Repeat("d", 40), Kind: parkPartial, Files: []string{"x"}})
|
||||
gh.after = map[string]func(){"createComment": func() { gh.prs[0].Body = rewritten }}
|
||||
if code, _, _ := notifyRun(gh, "--push"); code != 2 || gh.prs[0].Body != rewritten || len(gh.bodies) != 0 {
|
||||
t.Errorf("notify on a body rewritten meanwhile = %d; want 2 and the new body left as it is", code)
|
||||
}
|
||||
|
||||
// A body someone edited on the web comes back with CRLF line ends; the
|
||||
// mark lands all the same.
|
||||
gh = &fakeGH{prs: []pullRequest{notifyPR("20261026", strings.ReplaceAll(parkedBody(park), "\n", "\r\n"))}}
|
||||
if code, _, stderr := notifyRun(gh, "--push"); code != 0 || !parked(gh)[0].Announced {
|
||||
t.Errorf("notify on a CRLF body = %d, want #5 marked:\n%s", code, stderr)
|
||||
}
|
||||
|
||||
closed := notifyPR("20261026", parkedBody(park))
|
||||
at := "2026-10-26T12:00:00Z"
|
||||
closed.State, closed.MergedAt = "closed", &at
|
||||
gh = &fakeGH{prs: []pullRequest{closed}}
|
||||
if code, stdout, _ := notifyRun(gh, "--push"); code != 0 || stdout != "" || len(gh.issueComments) != 0 || len(gh.bodies) != 0 {
|
||||
t.Errorf("notify with no batch open = %d, %q, %d comments, %d edits; want nothing", code, stdout, len(gh.issueComments), len(gh.bodies))
|
||||
}
|
||||
next := notifyPR("20261027", parkedBody(park))
|
||||
next.Number = 91
|
||||
gh.prs = append(gh.prs, next)
|
||||
if code, _, _ := notifyRun(gh, "--push"); code != 0 || len(gh.issueComments) != 1 || !strings.Contains(gh.issueComments[0].Body, "[#5](") {
|
||||
t.Errorf("the next batch's notify = %d, want #5 announced on it: %v", code, gh.issueComments)
|
||||
}
|
||||
}
|
||||
|
||||
// A park carries its announcement into the next record only while it is
|
||||
// the same park: the same merge, kind, prerequisites, commits and files.
|
||||
func TestParkEventIdentity(t *testing.T) {
|
||||
a, b := strings.Repeat("a", 40), strings.Repeat("b", 40)
|
||||
was := parkedEntry{Original: 5, Merge: a, Kind: parkDependency, Commits: []string{a}, Announced: true}
|
||||
carrier := &lineRecord{Parked: []parkedEntry{was}}
|
||||
for name, tc := range map[string]struct {
|
||||
now parkedEntry
|
||||
announced bool
|
||||
}{
|
||||
"the same park": {parkedEntry{Original: 5, Merge: a, Kind: parkDependency, Commits: []string{a}}, true},
|
||||
"another unnumbered commit": {parkedEntry{Original: 5, Merge: a, Kind: parkDependency, Commits: []string{b}}, false},
|
||||
"another kind": {parkedEntry{Original: 5, Merge: a, Kind: parkPartial, Files: []string{"x"}}, false},
|
||||
"another prerequisite": {parkedEntry{Original: 5, Merge: a, Kind: parkDependency, Commits: []string{a}, Needs: []int{3}}, false},
|
||||
"another merge": {parkedEntry{Original: 5, Merge: b, Kind: parkDependency, Commits: []string{a}}, false},
|
||||
"another original": {parkedEntry{Original: 6, Merge: a, Kind: parkDependency, Commits: []string{a}}, false},
|
||||
} {
|
||||
got := carryAnnounced([]parkedEntry{tc.now}, carrier)
|
||||
if got[0].Announced != tc.announced {
|
||||
t.Errorf("%s: announced = %v, want %v", name, got[0].Announced, tc.announced)
|
||||
}
|
||||
}
|
||||
if got := carryAnnounced([]parkedEntry{was}, nil); got[0].Announced {
|
||||
t.Error("a park with no carrier came out announced")
|
||||
}
|
||||
unannounced := was
|
||||
unannounced.Announced = false
|
||||
if got := carryAnnounced([]parkedEntry{was}, &lineRecord{Parked: []parkedEntry{unannounced}}); got[0].Announced {
|
||||
t.Error("a park the carrier holds unannounced came out announced")
|
||||
}
|
||||
}
|
||||
|
||||
// A park keeps its announcement through a continuation and into the next
|
||||
// batch, so notify does not name it again.
|
||||
func TestRolloverKeepsTheAnnouncement(t *testing.T) {
|
||||
f := featWorld(t)
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
if code, _, stderr := f.exec(gh, "notify", "--line", "release-1.1", "--push"); code != 0 || !strings.Contains(notifyComment(gh), "[#5](") {
|
||||
t.Fatalf("notify = %d, want #5 announced:\n%s", code, stderr)
|
||||
}
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 0 || !strings.Contains(stdout, `"needs":[3],"announced":true`) {
|
||||
t.Fatalf("run --continue = %d, want #5's park still announced:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
mergeBatch(f, gh)
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
gh.nextPR = 91
|
||||
f.now = f.now.Add(24 * time.Hour)
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 0 || !strings.Contains(stdout, `"needs":[3],"announced":true`) {
|
||||
t.Fatalf("the next batch's run = %d, want #5's park announced from the merged batch:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
gh.issueComments = nil
|
||||
if code, stdout, _ := f.exec(gh, "notify", "--line", "release-1.1", "--push"); code != 0 || strings.Contains(stdout, "parked") || strings.Contains(notifyComment(gh), "[#5](") {
|
||||
t.Errorf("notify on the next batch = %d, want nothing about #5:\n%s\n%s", code, stdout, notifyComment(gh))
|
||||
}
|
||||
}
|
||||
|
||||
// notifyComment is the notify comment on the fake, or "".
|
||||
func notifyComment(gh *fakeGH) string {
|
||||
for _, c := range slices.Backward(gh.issueComments) {
|
||||
if strings.HasPrefix(c.Body, notifyMarker) {
|
||||
return c.Body
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -196,6 +196,13 @@ func TestGHCLI(t *testing.T) {
|
||||
if want := "api -X GET repos/{owner}/{repo}/pulls -f state=open -f base=release-1.6 -f per_page=100"; called() != want {
|
||||
t.Errorf("gh %q, want gh %q", called(), want)
|
||||
}
|
||||
write("[]")
|
||||
if _, err := (ghCLI{}).recentPulls("release-1.6", 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := "api -X GET repos/{owner}/{repo}/pulls -f state=all -f base=release-1.6 -f sort=created -f direction=desc -f per_page=100 -f page=2"; called() != want {
|
||||
t.Errorf("gh %q, want gh %q", called(), want)
|
||||
}
|
||||
var page []string
|
||||
for i := range openPullsCap {
|
||||
page = append(page, fmt.Sprintf(`{"number":%d}`, i+1))
|
||||
@@ -230,13 +237,34 @@ func TestGHCLI(t *testing.T) {
|
||||
|
||||
// A batch pull request carries no label: the release workflows act on a
|
||||
// pull request cozystack-ci[bot] opened only when it has the release label.
|
||||
write("")
|
||||
if err := (ghCLI{}).createPull("release-1.7", batchBranch1, "fix(backport): batch", "/tmp/body.md"); err != nil {
|
||||
t.Fatal(err)
|
||||
write("https://github.com/cozystack/cozystack/pull/5300\n")
|
||||
if n, url, err := (ghCLI{}).createPull("release-1.7", batchBranch1, "fix(backport): batch", "/tmp/body.md"); err != nil || n != 5300 || url != "https://github.com/cozystack/cozystack/pull/5300" {
|
||||
t.Errorf("createPull = %d, %q, %v; want the pull request gh printed", n, url, err)
|
||||
}
|
||||
if want := "pr create --draft --base release-1.7 --head " + batchBranch1 + " --title fix(backport): batch --body-file /tmp/body.md"; called() != want {
|
||||
t.Errorf("gh %q, want gh %q", called(), want)
|
||||
}
|
||||
write("Warning: 1 uncommitted change\n")
|
||||
if _, _, err := (ghCLI{}).createPull("release-1.7", batchBranch1, "fix(backport): batch", "/tmp/body.md"); err == nil {
|
||||
t.Error("createPull took output that is no pull request URL")
|
||||
}
|
||||
write(`{"number":90,"state":"closed","merged_at":"2026-10-26T12:00:00Z","head":{"ref":"x","sha":"y"}}`)
|
||||
if pr, err := (ghCLI{}).pull(90); err != nil || pr.State != "closed" || pr.MergedAt == nil {
|
||||
t.Errorf("pull = %+v, %v; want #90 merged", pr, err)
|
||||
}
|
||||
if want := "api repos/{owner}/{repo}/pulls/90"; called() != want {
|
||||
t.Errorf("gh %q, want gh %q", called(), want)
|
||||
}
|
||||
if _, err := (ghCLI{}).pull(91); err == nil {
|
||||
t.Error("pull took GitHub's answer about another pull request")
|
||||
}
|
||||
write("")
|
||||
if err := (ghCLI{}).closePull(90); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := "pr close 90"; called() != want {
|
||||
t.Errorf("gh %q, want gh %q", called(), want)
|
||||
}
|
||||
write("")
|
||||
if err := (ghCLI{}).editPull(90, "fix(backport): batch", "/tmp/body.md"); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,796 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var line11, _ = parseLine("release-1.1")
|
||||
|
||||
// handBatch pushes a batch carrying merges in the batch's shape, as a run
|
||||
// made one before the partial guard, and opens its pull request with a
|
||||
// record that defers nothing.
|
||||
func handBatch(f *fixture, gh *fakeGH, merges ...string) string {
|
||||
f.t.Helper()
|
||||
f.git("fetch", "-q", "origin")
|
||||
f.git("switch", "-q", "--detach", "origin/release-1.1")
|
||||
for _, mc := range merges {
|
||||
if parents := strings.Fields(f.git("rev-list", "--parents", "-n", "1", mc)); len(parents) == 2 {
|
||||
f.git("cherry-pick", "-x", mc)
|
||||
continue
|
||||
}
|
||||
base := f.git("rev-parse", "HEAD")
|
||||
for _, c := range strings.Fields(f.git("rev-list", "--reverse", "--no-merges", mc+"^1.."+mc+"^2")) {
|
||||
f.git("cherry-pick", "-x", c)
|
||||
}
|
||||
merge := f.joined(base, "HEAD", f.git("log", "-1", "--format=%B", mc)+"\n\n"+batchTrailer+": "+mc)
|
||||
f.git("update-ref", "HEAD", merge)
|
||||
}
|
||||
f.git("push", "-q", "origin", "HEAD:refs/heads/"+batchBranch1)
|
||||
f.git("switch", "-q", "main")
|
||||
gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, "batch\n\n"+deferredBlock(line11, nil, nil, nil)+"\n")}
|
||||
return f.remoteHead(batchBranch1)
|
||||
}
|
||||
|
||||
// policyWorld is #5088's shape: #3, a feat the line never gets, adds a
|
||||
// policy and its test; #5 deletes both again and adds a test of its own.
|
||||
func policyWorld(t *testing.T) (*fixture, string) {
|
||||
t.Helper()
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(3, "feat(chart): a network policy", "", map[string]string{"chart/templates/policy.yaml": "kind: NetworkPolicy\n", "chart/tests/policy_test.yaml": "suite: policy\n"})
|
||||
mc5 := f.pr(5, "fix(chart): remove the policy a rebase brought back", "```release-note\nfix(chart): the stray network policy is gone.\n```\n",
|
||||
map[string]string{"chart/templates/policy.yaml": "", "chart/tests/policy_test.yaml": "", "chart/tests/values_test.yaml": "suite: values\n"})
|
||||
return f, mc5
|
||||
}
|
||||
|
||||
// A clean pick that would delete files the line never had, and so carry only
|
||||
// #5's test, is withheld: #5 is parked as partial, with the paths it would
|
||||
// leave without effect, and its release note stays out of the body.
|
||||
func TestPartialPickIsWithheld(t *testing.T) {
|
||||
f, mc5 := policyWorld(t)
|
||||
f.pr(6, "fix(app): six", "```release-note\nfix(app): six works.\n```\n", map[string]string{"app/six.txt": "6\n"})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1")
|
||||
if code != 0 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): six (#6)"}) {
|
||||
t.Errorf("picked %q, want only #6", got)
|
||||
}
|
||||
want := `"parked":[{"original":5,"merge":"` + mc5 + `","kind":"partial","files":["chart/templates/policy.yaml","chart/tests/policy_test.yaml"]}]`
|
||||
if !strings.Contains(stdout, want) {
|
||||
t.Errorf("the record does not park #5 as partial (%s):\n%s", want, stdout)
|
||||
}
|
||||
if !strings.Contains(stdout, "### Parked") || !strings.Contains(stdout, "`chart/templates/policy.yaml`") {
|
||||
t.Errorf("the body does not say #5 is parked and why:\n%s", stdout)
|
||||
}
|
||||
if strings.Contains(stdout, "stray network policy") || !strings.Contains(stdout, "six works") {
|
||||
t.Errorf("the release notes are not #6's alone:\n%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// A file the line removed itself, which no original added after the line
|
||||
// branched, still leaves #5's deletion without effect: check finds it with no
|
||||
// record and parks it, and run picks nothing.
|
||||
func TestPartialWithoutAnAdder(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: add a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): the line drops the policy", map[string]string{"app/policy.yaml": ""})
|
||||
f.pr(5, "fix(app): drop the policy", "", map[string]string{"app/policy.yaml": "", "app/policy_test.txt": "gone\n"})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1")
|
||||
if code != 0 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
if got := f.subjects("origin/release-1.1", "HEAD"); len(got) != 0 {
|
||||
t.Errorf("picked %q, want nothing", got)
|
||||
}
|
||||
if !strings.Contains(stdout, "### Parked") {
|
||||
t.Errorf("the body does not park #5:\n%s", stdout)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
code, stdout, stderr = f.exec(nil, "check", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stderr, "note: #5 is parked: only part of it applies to release-1.1") {
|
||||
t.Errorf("check = %d, want 0 with a parked-partial note:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// The picker judges what its picks did, not what the original's merge did:
|
||||
// #5's first commit deletes a file the line no longer has and comes out
|
||||
// empty, its second adds a test, and the unit left would be the test alone.
|
||||
func TestPartialByAnEmptyOwnCommit(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: add a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): the line drops the policy", map[string]string{"app/policy.yaml": ""})
|
||||
f.prCommits(5, "fix(app): drop the policy and test it", "```release-note\nfix(app): no more policy.\n```\n",
|
||||
change{files: map[string]string{"app/policy.yaml": ""}},
|
||||
change{files: map[string]string{"app/policy_test.txt": "gone\n"}})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1")
|
||||
if code != 0 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
if got := f.subjects("origin/release-1.1", "HEAD"); len(got) != 0 {
|
||||
t.Errorf("picked %q, want #5 withheld", got)
|
||||
}
|
||||
if strings.Contains(stdout, "no more policy") || !strings.Contains(stdout, "### Parked") {
|
||||
t.Errorf("#5's note is in the body, or #5 is not parked:\n%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// A batch built before the guard can already carry a partial unit. It fails
|
||||
// the cut and verify whatever its label says, and --defer takes it off,
|
||||
// closing a batch it was the last unit of.
|
||||
func TestExistingPartialUnitFailsTheCut(t *testing.T) {
|
||||
f, mc5 := policyWorld(t)
|
||||
gh := &fakeGH{}
|
||||
head := handBatch(f, gh, mc5)
|
||||
code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut")
|
||||
if code != 1 || !strings.Contains(stdout, "#5 is on batch #90, but only part of it applies to release-1.1") {
|
||||
t.Errorf("check --cut = %d, want 1 naming the partial unit:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
code, stdout, stderr = f.exec(gh, "verify", "--line", "release-1.1", "--head", head)
|
||||
if code != 1 || !strings.Contains(stdout, `#5 leaves "chart/templates/policy.yaml", "chart/tests/policy_test.yaml" without effect on release-1.1`) {
|
||||
t.Errorf("verify = %d, want 1 naming what #5 leaves out:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
gh.labels = map[string][]int{labelSkip: {5}}
|
||||
code, stdout, stderr = f.exec(gh, "check", "--line", "release-1.1", "--cut")
|
||||
if code != 1 || !strings.Contains(stdout, "#5 is on batch #90, but only part of it applies to release-1.1") {
|
||||
t.Errorf("check --cut with backport/skip = %d, want the partial unit to still fail it:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
code, _, stderr = f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "only part of it applies", "--push")
|
||||
if code != 0 || prState(gh.find(90)) != "closed" || f.remoteHead(batchBranch1) != "" {
|
||||
t.Errorf("run --defer 5 --push = %d, #90 %s, branch at %q; want the batch closed and its branch gone:\n%s", code, prState(gh.find(90)), f.remoteHead(batchBranch1), stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// An original whose first pick came out empty, because the line already had
|
||||
// that change, is on the batch all the same: check does not call it missing,
|
||||
// a continuation keeps it picked, and so does a rebuild without another
|
||||
// original.
|
||||
func TestOnBatchAfterAnEmptyFirstPick(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a and b", "", map[string]string{"app/a.txt": "old\n", "app/b.txt": "old\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): a, on the line first", map[string]string{"app/a.txt": "fixed\n"})
|
||||
f.prCommits(5, "fix(app): a and b", "",
|
||||
change{files: map[string]string{"app/a.txt": "fixed\n"}},
|
||||
change{files: map[string]string{"app/b.txt": "fixed\n"}})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
head := openBatch(t, f, gh)
|
||||
if got := f.subjects("origin/release-1.1", head); !slices.Equal(got, []string{"fix(app): a and b (#5)", "fix(app): six (#6)"}) {
|
||||
t.Fatalf("the batch carries %q, want #5 and #6", got)
|
||||
}
|
||||
code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1")
|
||||
if code != 0 {
|
||||
t.Errorf("check = %d, want 0 with #5 on the batch:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
code, stdout, _ = f.exec(gh, "check", "--line", "release-1.1", "--cut")
|
||||
if code != 1 || !strings.Contains(stdout, "#5 is only on open batch PR #90") {
|
||||
t.Errorf("check --cut = %d, want #5 only on the batch:\n%s", code, stdout)
|
||||
}
|
||||
code, stdout, stderr = f.exec(gh, "run", "--line", "release-1.1", "--continue")
|
||||
if code != 0 || !strings.Contains(stdout, `"picked":[5,6]`) {
|
||||
t.Errorf("run --continue = %d, want #5 and #6 picked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
code, stdout, stderr = f.exec(gh, "run", "--line", "release-1.1", "--defer", "6", "--reason", "fails the e2e")
|
||||
if code != 0 || !strings.Contains(stdout, `"picked":[5]`) || !strings.Contains(stdout, `"missing":[]`) {
|
||||
t.Errorf("run --defer 6 = %d, want #5 still picked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// featWorld is #5071's shape: #3, a feat the line never gets, adds a file,
|
||||
// and #5 fixes that file; #6 is a plain fix beside it.
|
||||
func featWorld(t *testing.T) *fixture {
|
||||
t.Helper()
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): tap", "", map[string]string{"app/tap.go": appFile})
|
||||
f.pr(5, "fix(app): fix the tap", "```release-note\nfix(app): the tap works.\n```\n", map[string]string{"app/tap.go": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
return f
|
||||
}
|
||||
|
||||
// A fix of a file a feat added on main, which the line never gets, is
|
||||
// parked, not tried, and check takes the park as a note.
|
||||
func TestParkAFixOfAFeatureTheLineLacks(t *testing.T) {
|
||||
f := featWorld(t)
|
||||
gh := &fakeGH{}
|
||||
code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push")
|
||||
if code != 0 {
|
||||
t.Fatalf("run --push = %d\n%s", code, stderr)
|
||||
}
|
||||
if strings.Contains(stdout, "### Deferred conflicts") || !strings.Contains(stdout, `"parked":[{"original":5,`) || !strings.Contains(stdout, `"kind":"dependency","needs":[3]`) {
|
||||
t.Errorf("#5 is not parked on #3:\n%s", stdout)
|
||||
}
|
||||
if !strings.Contains(stdout, "### Parked") || !strings.Contains(stdout, "builds on [#3]") {
|
||||
t.Errorf("the body does not say #5 builds on #3:\n%s", stdout)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
code, stdout, stderr = f.exec(gh, "check", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stderr, "note: #5 is parked: it builds on #3, which never reaches release-1.1") {
|
||||
t.Errorf("check = %d, want 0 with a note that #5 is parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// backport/include lifts no park.
|
||||
func TestIncludeDoesNotLiftThePark(t *testing.T) {
|
||||
f := featWorld(t)
|
||||
code, stdout, stderr := f.exec(&fakeGH{labels: map[string][]int{labelInclude: {5}}}, "run", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stdout, `"parked":[{"original":5,`) || !strings.Contains(stdout, "`backport/include`, parked: builds on") {
|
||||
t.Errorf("run with backport/include on #5 = %d, want #5 still parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A prerequisite that is itself parked, but adapted onto the batch by hand,
|
||||
// satisfies what builds on it: #3 is parked on #2, a feat, and #5 changes a
|
||||
// line #3 wrote.
|
||||
func TestAdaptedPrerequisiteSatisfiesItsDependent(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a and b", "", map[string]string{"app/a.txt": appFile, "app/b.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(20, "feat(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
mc3 := f.pr(3, "fix(app): an excited two, a loud three", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/b.txt": strings.Replace(appFile, "three", "THREE", 1)})
|
||||
f.pr(5, "fix(app): an excited three", "", map[string]string{"app/b.txt": strings.Replace(appFile, "three", "THREE!", 1)})
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, `"kind":"dependency","needs":[3]`) {
|
||||
t.Fatalf("run = %d, want #5 parked as long as #3 is:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
w := emptyBatch(f, &fakeGH{}, "batch\n\n"+deferredBlock(line11, nil, nil, nil)+"\n")
|
||||
// #3 adapted by hand: every file it changes, changed, in the batch's
|
||||
// shape.
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc3+"^2"), map[string]string{"app/a.txt": strings.Replace(appFile, "two", "two!", 1), "app/b.txt": strings.Replace(appFile, "three", "THREE", 1)})
|
||||
fold := w.merge(w.head, pick, "fix(app): an excited two, a loud three (#3)\n\n"+batchTrailer+": "+mc3)
|
||||
f.git("push", "-q", "origin", fold+":refs/heads/"+batchBranch1)
|
||||
w.gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, w.gh.prs[0].Body)}
|
||||
code, stdout, stderr := f.exec(w.gh, "check", "--line", "release-1.1")
|
||||
if code != 1 || strings.Contains(stderr, "#5 is parked") || strings.Contains(stdout+stderr, "waits on") || !strings.Contains(stdout, "/pull/5 ") {
|
||||
t.Errorf("check = %d, want #5 missing, not parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
code, stdout, stderr = f.exec(w.gh, "run", "--line", "release-1.1", "--continue")
|
||||
if code != 0 || !strings.Contains(stdout, `"picked":[3,5]`) {
|
||||
t.Errorf("run --continue = %d, want #5 picked after #3's adaptation:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// What an earlier unit of the batch brought counts: #3 writes the line #8
|
||||
// changes, a feat takes it back and another feat, #6, writes it again, so
|
||||
// blame names #6, which never comes; once #3 is picked the branch has the
|
||||
// line all the same.
|
||||
func TestContentFromAnotherUnitSatisfies(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(3, "fix(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(4, "feat(app): a quiet two", "", map[string]string{"app/a.txt": appFile})
|
||||
f.pr(6, "feat(app): a loud two again", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(8, "fix(app): an excited two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1")
|
||||
if code != 0 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
if got := f.subjects("origin/release-1.1", "HEAD"); !slices.Equal(got, []string{"fix(app): a loud two (#3)", "fix(app): an excited two (#8)"}) {
|
||||
t.Errorf("picked %q, want #3 and #8:\n%s", got, stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// auxWorld is #5142's shape: #3, a feat, adds a bats test; #5 fixes a
|
||||
// workflow and that test, so all it builds on that never comes is a test;
|
||||
// #6 is a plain fix.
|
||||
func auxWorld(t *testing.T) *fixture {
|
||||
t.Helper()
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a workflow", "", map[string]string{".github/workflows/release.yaml": "on: push\njobs: {}\n"})
|
||||
f.lines()
|
||||
f.pr(3, "feat(ci): test the changelog", "", map[string]string{"hack/changelog.bats": "@test x {\n true\n}\n"})
|
||||
f.pr(5, "fix(ci): run the release on tags", "", map[string]string{".github/workflows/release.yaml": "on: [push, tag]\njobs: {}\n", "hack/changelog.bats": "@test x {\n false\n}\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
return f
|
||||
}
|
||||
|
||||
// A workflow original whose only missing dependency is a test waits for a
|
||||
// maintainer in the scheduled run, whose token cannot push workflows, and
|
||||
// check holds the cut on it. A maintainer's own run parks it. With no batch
|
||||
// open, or one whose body carries no record, it is missing; a record from
|
||||
// before the mode was saved says the scheduled mode by listing a wait.
|
||||
func TestWorkflowModeCarriesToCheck(t *testing.T) {
|
||||
f := auxWorld(t)
|
||||
gh := &fakeGH{}
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 || strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `{"original":5,"files":[".github/workflows/release.yaml"],"workflows":true}`) {
|
||||
t.Fatalf("scheduled run = %d, want #5 waiting, not parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#5 changes .github/workflows/ and waits on batch PR #90") {
|
||||
t.Errorf("check --cut = %d, want #5 waiting:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
v1 := "batch\n\n" + deferredBlock(line11, nil, nil, []pick{{v: &verdict{o: &original{number: 5}}, files: []string{".github/workflows/release.yaml"}}}) + "\n"
|
||||
gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, v1)}
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#5 changes .github/workflows/ and waits on batch PR #90") {
|
||||
t.Errorf("check --cut with a version 1 record = %d, want #5 waiting:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
gh.prs = []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, "a batch someone wrote")}
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/5 ") || strings.Contains(stderr, "parked") {
|
||||
t.Errorf("check under a batch with no record = %d, want #5 missing:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
|
||||
f = auxWorld(t)
|
||||
if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/5 ") || strings.Contains(stderr, "parked") {
|
||||
t.Errorf("check with no batch = %d, want #5 missing:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
gh = &fakeGH{}
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":5,`) {
|
||||
t.Fatalf("a maintainer's run = %d, want #5 parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "note: #5 is parked") {
|
||||
t.Errorf("check after a maintainer's run = %d, want 0 with #5 parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// Evidence found only in a test file still parks an original that changes
|
||||
// no workflow: #4973's shape.
|
||||
func TestTestOnlyEvidenceParksOtherOriginals(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: nodes", "", map[string]string{"app/nodes.go": "package app\n", "app/nodes_test.go": "package app\n\nfunc a() {}\n"})
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): proxmox nodes", "", map[string]string{"app/nodes_test.go": "package app\n\nfunc a() { proxmox() }\n"})
|
||||
f.pr(5, "fix(app): nodes", "", map[string]string{"app/nodes.go": "package app\n\nvar fixed = true\n", "app/nodes_test.go": "package app\n\nfunc a() { proxmox(); fixed() }\n"})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1")
|
||||
if code != 0 || strings.Contains(stdout, "### Deferred conflicts") || !strings.Contains(stdout, `"parked":[{"original":5,`) {
|
||||
t.Errorf("run = %d, want #5 parked on #3:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// What an original builds on through lines it adds is not seen: #4973's
|
||||
// $isProxmox. The original is picked; CI on the batch is what catches it.
|
||||
func TestAddedLinesDependencyIsNotSeen(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: nodes", "", map[string]string{"app/nodes.tpl": "a\nb\n"})
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): define isProxmox", "", map[string]string{"app/proxmox.tpl": "isProxmox\n"})
|
||||
f.pr(5, "fix(app): use isProxmox", "", map[string]string{"app/nodes.tpl": "a\nif isProxmox\nb\n"})
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `"picked":[5]`) {
|
||||
t.Errorf("run = %d, want #5 picked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// With no batch open, check reads a closed record whatever its version and
|
||||
// whatever mode it saved as the scheduled run's: the workflow original it
|
||||
// left waiting is missing, not parked, while its drops and its other
|
||||
// deferrals still count.
|
||||
func TestClosedRecordModeFallback(t *testing.T) {
|
||||
for _, version := range []int{2, 3} {
|
||||
for _, saved := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("version %d, noWorkflowFiles %v", version, saved), func(t *testing.T) {
|
||||
f := auxWorld(t)
|
||||
mc6 := f.git("log", "--first-parent", "--format=%H", "-1", "--grep", "(#6)$", "main")
|
||||
mc7 := f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
sha := f.git("rev-parse", "origin/main")
|
||||
rec := lineRecord{Version: version, Line: "release-1.1", Report: strings.Repeat("b", 64),
|
||||
Built: &builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{NoWorkflowFiles: saved, Mode: modeContinue}},
|
||||
Deferred: []deferredEntry{{Original: 5, Files: []string{".github/workflows/release.yaml"}, Workflows: true}, {Original: 7, Commit: f.git("rev-parse", mc7+"^2"), Files: []string{"app/seven.txt"}}},
|
||||
Dropped: []droppedEntry{{Original: 6, Merge: mc6, Reason: "not for this line", On: 90, Date: "2026-10-26"}}, Stale: []int{}}
|
||||
pr := f.batchPR(90, "release-1.1", batchBranch1, "batch\n\n"+recordBlock(rec)+"\n")
|
||||
at := "2026-10-26T12:00:00Z"
|
||||
pr.State, pr.MergedAt = "closed", &at
|
||||
code, stdout, stderr := f.exec(&fakeGH{prs: []pullRequest{pr}}, "check", "--line", "release-1.1")
|
||||
if code != 1 || !strings.Contains(stdout, "/pull/5 ") || strings.Contains(stderr, "#5 is parked") {
|
||||
t.Errorf("check = %d, want #5 missing and not parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, "note: #6 is dropped") || !strings.Contains(stderr, "warning: deferred conflict on #90 (merged): https://github.com/cozystack/cozystack/pull/7 ") {
|
||||
t.Errorf("check lost the closed record's drop or deferral:\n%s", stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Withdrawing a drop puts the original back where the rules and the line
|
||||
// put it: a partial original is parked again, in the record as in check.
|
||||
func TestUndropRestoresThePark(t *testing.T) {
|
||||
for name, world := range map[string]func(*testing.T) *fixture{
|
||||
"partial": func(t *testing.T) *fixture {
|
||||
f, _ := policyWorld(t)
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
return f
|
||||
},
|
||||
"dependency": featWorld,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f := world(t)
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--drop", "5", "--reason", "not for 1.1", "--push")
|
||||
reopen(f, gh)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--undrop", "5", "--push")
|
||||
reopen(f, gh)
|
||||
if rec := recordOf(t, gh); len(rec.Parked) != 1 || rec.Parked[0].Original != 5 || rec.Parked[0].Kind != name {
|
||||
t.Errorf("after the undrop the record parks %+v, want #5 parked %s", rec.Parked, name)
|
||||
}
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "note: #5 is parked") {
|
||||
t.Errorf("check = %d, want #5 parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A prerequisite the open batch carries is there for what builds on it,
|
||||
// whatever its label now says: check and run agree that #7 is not parked.
|
||||
func TestPrerequisiteStillOnTheBatchSatisfies(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
gh.labels = map[string][]int{labelSkip: {5}}
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || strings.Contains(stderr, "#7 is parked") || !strings.Contains(stdout, "/pull/7 ") {
|
||||
t.Errorf("check = %d, want #7 missing, not parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue"); code != 0 || !strings.Contains(stdout, `"picked":[7]`) {
|
||||
t.Errorf("run --continue = %d, want #7 picked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// The picker judges what its picks did where the run has got to: #4
|
||||
// deletes the file #5 also deletes, so after #4 #5 would bring only its
|
||||
// test, which the net merge at the line's head cannot see.
|
||||
func TestPartialByAnEarlierPick(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"})
|
||||
f.lines()
|
||||
f.pr(4, "fix(app): drop the policy", "", map[string]string{"app/policy.yaml": "", "app/four.txt": "4\n"})
|
||||
f.pr(40, "feat(app): the policy again", "", map[string]string{"app/policy.yaml": "allow: all\n"})
|
||||
f.pr(5, "fix(app): drop the policy and test it", "", map[string]string{"app/policy.yaml": "", "app/policy_test.txt": "gone\n"})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stdout, `"picked":[4]`) || !strings.Contains(stdout, `"parked":[{"original":5,`) {
|
||||
t.Errorf("run = %d, want #4 picked and #5 parked as partial:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// What an earlier pick brought clears a partial park the line's head
|
||||
// gave: the line removed the policy, #4 brings it back, and #5's deletion
|
||||
// then has something to delete.
|
||||
func TestPartialClearedByAnEarlierPick(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): the line drops the policy", map[string]string{"app/policy.yaml": ""})
|
||||
f.pr(3, "feat(app): no policy", "", map[string]string{"app/policy.yaml": ""})
|
||||
f.pr(4, "fix(app): the policy, back", "", map[string]string{"app/policy.yaml": "allow: some\n"})
|
||||
f.pr(5, "fix(app): drop the policy and test it", "", map[string]string{"app/policy.yaml": "", "app/policy_test.txt": "gone\n"})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stdout, `"picked":[4,5]`) {
|
||||
t.Errorf("run = %d, want #4 and #5 picked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A reason a person deferred an original for comes before its partial
|
||||
// park.
|
||||
func TestReasonComesBeforeThePartialPark(t *testing.T) {
|
||||
f, _ := policyWorld(t)
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "waits for the policy rework", "--push")
|
||||
reopen(f, gh)
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "warning: deferred on #90 to the next batch: https://github.com/cozystack/cozystack/pull/5 ") || strings.Contains(stderr, "#5 is parked") {
|
||||
t.Errorf("check = %d, want #5 deferred for its reason:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// The workflow exception holds only while what never comes is tests or
|
||||
// docs, and while the workflow lines build on nothing missing: a
|
||||
// workflow original that also fixes a file a feat added, or whose workflow
|
||||
// line another original still to come wrote, parks in the scheduled run too.
|
||||
func TestWorkflowExceptionNeedsTestsOnly(t *testing.T) {
|
||||
t.Run("a never dependency outside tests", func(t *testing.T) {
|
||||
f := auxWorld(t)
|
||||
f.pr(20, "feat(app): tap", "", map[string]string{"app/tap.go": appFile})
|
||||
f.pr(7, "fix(ci): test the tap, and fix it", "", map[string]string{".github/workflows/tap.yaml": "on: push\n", "app/tap.go": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1", "--no-workflow-files"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":7,`) {
|
||||
t.Errorf("scheduled run = %d, want #7 parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
t.Run("a workflow line still to come", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a workflow", "", map[string]string{".github/workflows/release.yaml": "on: push\njobs: {}\n", "app/four.txt": "old\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): four, the line's way", map[string]string{"app/four.txt": "line\n"})
|
||||
f.pr(3, "feat(ci): test the changelog", "", map[string]string{"hack/changelog.bats": "@test x {\n true\n}\n"})
|
||||
f.pr(4, "fix(ci): four", "", map[string]string{"app/four.txt": "four\n", ".github/workflows/release.yaml": "on: [push]\njobs: {}\n"})
|
||||
f.pr(5, "fix(ci): run the release on tags", "", map[string]string{".github/workflows/release.yaml": "on: [push, tag]\njobs: {}\n", "hack/changelog.bats": "@test x {\n false\n}\n"})
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1", "--no-workflow-files"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":5,`) {
|
||||
t.Errorf("scheduled run = %d, want #5 parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// What a rebuild takes off the batch is no longer there for what builds on
|
||||
// it: deferring #5 makes #7, which merged after the batch was built, wait
|
||||
// on it.
|
||||
func TestRebuildTakesThePrerequisiteAway(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "fails the e2e"); code != 0 || !strings.Contains(stdout, `{"original":7,"files":[],"needs":[5]}`) {
|
||||
t.Errorf("run --defer 5 = %d, want #7 waiting on #5:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A file the line renamed the way the original does is the original's own
|
||||
// rename, not a deletion left without effect.
|
||||
func TestSameRenameOnBothSidesIsWhole(t *testing.T) {
|
||||
const long = "l01\nl02\nl03\nl04\nl05\nl06\nl07\nl08\nl09\nl10\nl11\nl12\n"
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a file", "", map[string]string{"app/p.txt": long})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): the line renames p to q", map[string]string{"app/p.txt": "", "app/q.txt": long})
|
||||
f.pr(5, "fix(app): rename p to q, and fix l10", "", map[string]string{"app/p.txt": "", "app/q.txt": strings.Replace(long, "l10", "L10", 1)})
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, `"picked":[5]`) {
|
||||
t.Errorf("run = %d, want #5 picked whole:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A partial park only the picker saw, where the net merge at the line's
|
||||
// head looks whole, holds in check and in the operations that pick nothing
|
||||
// as the open record keeps it: check does not call the original missing.
|
||||
func TestPickerParkHoldsInCheck(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a policy", "", map[string]string{"app/policy.yaml": "allow: all\n"})
|
||||
f.lines()
|
||||
f.pr(4, "fix(app): drop the policy", "", map[string]string{"app/policy.yaml": "", "app/four.txt": "4\n"})
|
||||
f.pr(40, "feat(app): the policy again", "", map[string]string{"app/policy.yaml": "allow: all\n"})
|
||||
f.pr(5, "fix(app): drop the policy and test it", "", map[string]string{"app/policy.yaml": "", "app/policy_test.txt": "gone\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "note: #5 is parked: only part of it applies") {
|
||||
t.Errorf("check = %d, want #5 parked as the record says:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "6", "--reason", "fails the e2e"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":5,`) {
|
||||
t.Errorf("run --defer 6 = %d, want #5 still parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
// Deferring #4, which made #5 partial, ends the park: #5 applies whole
|
||||
// on what the batch carries now.
|
||||
f.git("switch", "-q", "main")
|
||||
code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "4", "--reason", "fails the e2e", "--push")
|
||||
if code != 0 || strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `"missing":[5]`) {
|
||||
t.Errorf("run --defer 4 = %d, want #5 missing, no longer parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
reopen(f, gh)
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || strings.Contains(stderr, "#5 is parked") || !strings.Contains(stdout, "/pull/5 ") {
|
||||
t.Errorf("check after deferring #4 = %d, want #5 missing:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A workflow original that waits for a maintainer only as the open record
|
||||
// lists it: one merged since the batch was built is missing, and so is
|
||||
// what waits on it.
|
||||
func TestUnlistedWorkflowWaitIsMissing(t *testing.T) {
|
||||
f := auxWorld(t)
|
||||
gh := &fakeGH{}
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push")
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
f.pr(8, "fix(ci): run the new release on tags", "", map[string]string{".github/workflows/new.yaml": "on: tag\n", "hack/changelog.bats": "@test x {\n false\n}\n# eight\n", "app/eight.txt": appFile + "TWO\n"})
|
||||
f.pr(9, "fix(app): nine", "", map[string]string{"app/eight.txt": appFile + "TWO!\n"})
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/9 fix(app): nine (it waits on #8, which is not on the line either)") {
|
||||
t.Errorf("check = %d, want #9 missing, waiting on #8:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// The line's own rename stands for the original's only with the original's
|
||||
// change in it: a fold that leaves the renamed file as it was is refused.
|
||||
func TestSameRenameStillNeedsItsFix(t *testing.T) {
|
||||
const long = "l01\nl02\nl03\nl04\nl05\nl06\nl07\nl08\nl09\nl10\nl11\nl12\n"
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a file", "", map[string]string{"app/p.txt": long})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): the line renames p to q", map[string]string{"app/p.txt": "", "app/q.txt": long})
|
||||
mc5 := f.pr(5, "fix(app): rename p to q, fix l10, and five", "", map[string]string{"app/p.txt": "", "app/q.txt": strings.Replace(long, "l10", "L10", 1), "app/five.txt": "5\n"})
|
||||
w := emptyBatch(f, &fakeGH{}, "")
|
||||
pick := w.pick(w.head, f.git("rev-parse", mc5+"^2"), map[string]string{"app/five.txt": "5\n"})
|
||||
fold := w.merge(w.head, pick, "fix(app): rename p to q, fix l10, and five (#5)\n\n"+batchTrailer+": "+mc5)
|
||||
if code, out, stderr := f.exec(w.gh, "fold", "--line", "release-1.1", "--original", "5", "--commit", fold); code != 1 || !strings.Contains(out, `leaves "app/p.txt" without effect`) {
|
||||
t.Errorf("fold without the fix in q = %d, %q\n%s", code, out, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A prerequisite the line carries is there, though the rules would keep it
|
||||
// out: a feat carried by a hand adaptation does not park what builds on it.
|
||||
func TestCarriedExcludedPrerequisiteSatisfies(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
mc3 := f.pr(3, "feat(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.onLine("release-1.1", "feat(app): a loud two, adapted\n\n(cherry picked from commit "+mc3+")", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "Two", 1)})
|
||||
f.pr(5, "fix(app): an excited two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"parked":[{`) {
|
||||
t.Errorf("run = %d, want #5 not parked on the carried #3:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.1"); code != 1 || strings.Contains(stderr, "#5 is parked") {
|
||||
t.Errorf("check = %d, want #5 missing, not parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// With no batch open, a workflow wait a closed record keeps waits on
|
||||
// nothing: the original is judged as the scheduled run judges it, so one
|
||||
// that also builds on a feat the line lacks is parked, in check as in run.
|
||||
func TestClosedWorkflowWaitIsJudgedAsRunJudgesIt(t *testing.T) {
|
||||
f := auxWorld(t)
|
||||
f.pr(20, "feat(app): tap", "", map[string]string{"app/tap.go": appFile})
|
||||
f.pr(7, "fix(ci): test the tap, and fix it", "", map[string]string{".github/workflows/tap.yaml": "on: push\n", "app/tap.go": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
sha := f.git("rev-parse", "origin/main")
|
||||
rec := lineRecord{Version: 2, Line: "release-1.1", Report: strings.Repeat("b", 64),
|
||||
Built: &builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{NoWorkflowFiles: true, Mode: modeContinue}},
|
||||
Deferred: []deferredEntry{{Original: 7, Files: []string{".github/workflows/tap.yaml"}, Workflows: true}}, Dropped: []droppedEntry{}, Stale: []int{}}
|
||||
pr := f.batchPR(90, "release-1.1", batchBranch1, "batch\n\n"+recordBlock(rec)+"\n")
|
||||
at := "2026-10-26T12:00:00Z"
|
||||
pr.State, pr.MergedAt = "closed", &at
|
||||
gh := &fakeGH{prs: []pullRequest{pr}}
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); strings.Contains(stdout, "/pull/7 ") || !strings.Contains(stderr, "note: #7 is parked: it builds on #20") {
|
||||
t.Errorf("check --cut = %d, want #7 parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files"); code != 0 || !strings.Contains(stdout, `"parked":[{"original":7,`) {
|
||||
t.Errorf("scheduled run = %d, want #7 parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A pick that comes out empty is judged too: #5's own commit did half its
|
||||
// fix, which the line has, and a merge of main into its branch did the
|
||||
// rest, which no pick carries; #5 is not on the line.
|
||||
func TestEmptyPicksStillJudged(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: b", "", map[string]string{"app/b.txt": "old\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): b, half of it", map[string]string{"app/b.txt": "middle\n"})
|
||||
f.git("switch", "-q", "-c", "pr-5", "main")
|
||||
f.apply(map[string]string{"app/b.txt": "middle\n"})
|
||||
f.git("commit", "-q", "-m", "b, half of it")
|
||||
f.git("switch", "-q", "main")
|
||||
f.apply(map[string]string{"app/main.txt": "moved\n"})
|
||||
f.git("commit", "-q", "-m", "chore: move main along")
|
||||
f.git("switch", "-q", "pr-5")
|
||||
f.git("merge", "-q", "--no-ff", "--no-commit", "main")
|
||||
f.apply(map[string]string{"app/b.txt": "fixed\n"})
|
||||
f.git("commit", "-q", "-m", "Merge branch 'main' into pr-5")
|
||||
f.git("switch", "-q", "main")
|
||||
f.git("merge", "-q", "--no-ff", "-m", "fix(app): b (#5)", "pr-5")
|
||||
f.git("push", "-q", "origin", "main")
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"on-line":[5]`) || !strings.Contains(stdout, `"parked":[{"original":5,`) {
|
||||
t.Errorf("run = %d, want #5 parked as partial, not on the line:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// --defer takes off a unit that does only part of its original whatever
|
||||
// rule now keeps that original out, as check tells it to.
|
||||
func TestDeferTakesOffAPartialExcludedUnit(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(3, "feat(chart): a network policy", "", map[string]string{"chart/templates/policy.yaml": "kind: NetworkPolicy\n"})
|
||||
mc5 := f.pr(5, "feat(chart): remove the policy, and test values", "", map[string]string{"chart/templates/policy.yaml": "", "chart/tests/values_test.yaml": "suite: values\n"})
|
||||
gh := &fakeGH{}
|
||||
handBatch(f, gh, mc5)
|
||||
if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "only part of it applies") {
|
||||
t.Fatalf("check --cut = %d, want the partial unit to fail it:\n%s", code, stdout)
|
||||
}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "only part of it applies", "--push"); code != 0 || prState(gh.find(90)) != "closed" {
|
||||
t.Errorf("run --defer 5 --push = %d, #90 %s; want the unit taken off and the batch closed:\n%s", code, prState(gh.find(90)), stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A stored wait on an original merged after the one that waits cannot be
|
||||
// what a run wrote.
|
||||
func TestForwardWaitIsRefused(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
sha := f.git("rev-parse", "origin/main")
|
||||
rec := lineRecord{Version: recordVersion, Line: "release-1.1", Report: strings.Repeat("b", 64),
|
||||
Built: &builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{Mode: modeContinue}},
|
||||
Deferred: []deferredEntry{{Original: 5, Files: []string{}, Needs: []int{7}}}, Dropped: []droppedEntry{}, Stale: []int{}}
|
||||
f.git("push", "-q", "origin", "origin/release-1.1:refs/heads/"+batchBranch1)
|
||||
gh := &fakeGH{prs: []pullRequest{f.batchPR(90, "release-1.1", batchBranch1, "batch\n\n"+recordBlock(rec)+"\n")}}
|
||||
if code, _, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 2 || !strings.Contains(stderr, "#5 wait on #7") {
|
||||
t.Errorf("check = %d, want 2 for a wait on a later original:\n%s", code, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// The workflow exception looks only at what still keeps the original from
|
||||
// the line: a workflow line its prerequisite wrote, which the open batch
|
||||
// carries though that prerequisite is labelled backport/skip, does not
|
||||
// stop it, in check as in run.
|
||||
func TestWorkflowExceptionIgnoresWhatIsThere(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a workflow", "", map[string]string{".github/workflows/release.yaml": "on: push\njobs: {}\n"})
|
||||
f.lines()
|
||||
f.pr(3, "feat(ci): test the changelog", "", map[string]string{"hack/changelog.bats": "@test x {\n true\n}\n"})
|
||||
f.pr(4, "fix(ci): run the release on pushes", "", map[string]string{".github/workflows/release.yaml": "on: [push]\njobs: {}\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
f.pr(7, "fix(ci): run the release on tags too", "", map[string]string{".github/workflows/release.yaml": "on: [push, tag]\njobs: {}\n", "hack/changelog.bats": "@test x {\n false\n}\n"})
|
||||
gh := &fakeGH{}
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--push")
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
gh.labels = map[string][]int{labelSkip: {4}}
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--no-workflow-files", "--push"); code != 0 || !strings.Contains(stdout, `{"original":7,"files":[".github/workflows/release.yaml"],"workflows":true}`) {
|
||||
t.Fatalf("scheduled run = %d, want #7 waiting for a maintainer:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#7 changes .github/workflows/ and waits on batch PR #90") {
|
||||
t.Errorf("check --cut = %d, want #7 waiting, as run has it:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// An empty pick leaves a deletion undone that only a merge of main into the
|
||||
// original's branch made: the original is not on the line.
|
||||
func TestEmptyPickLeavesADeletionUndone(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a and b", "", map[string]string{"app/a.txt": "old feature\n", "app/b.txt": "old\n"})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): b, already", map[string]string{"app/b.txt": "fixed\n"})
|
||||
f.git("switch", "-q", "-c", "pr-5", "main")
|
||||
f.apply(map[string]string{"app/b.txt": "fixed\n"})
|
||||
f.git("commit", "-q", "-m", "b")
|
||||
f.git("switch", "-q", "main")
|
||||
f.apply(map[string]string{"app/main.txt": "moved\n"})
|
||||
f.git("commit", "-q", "-m", "chore: move main along")
|
||||
f.git("switch", "-q", "pr-5")
|
||||
f.git("merge", "-q", "--no-ff", "--no-commit", "main")
|
||||
f.git("rm", "-q", "app/a.txt")
|
||||
f.git("commit", "-q", "-m", "Merge branch 'main' into pr-5")
|
||||
f.git("switch", "-q", "main")
|
||||
f.git("merge", "-q", "--no-ff", "-m", "fix(app): b, and a goes (#5)", "pr-5")
|
||||
f.git("push", "-q", "origin", "main")
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"on-line":[5]`) || !strings.Contains(stdout, `"parked":[{"original":5,`) {
|
||||
t.Errorf("run = %d, want #5 parked as partial, not on the line:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A file the line already has as the original makes it builds on nothing
|
||||
// the line lacks: #5 fixes a.txt, which the line fixed the same way, and
|
||||
// b.txt, so it picks whole and is not parked on the feat that wrote a.txt.
|
||||
func TestAlreadyAppliedFileBuildsOnNothing(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: a and b", "", map[string]string{"app/a.txt": appFile, "app/b.txt": "old\n"})
|
||||
f.lines()
|
||||
f.pr(3, "feat(app): a loud two", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.onLine("release-1.1", "fix(app): two, the line's way", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
f.pr(5, "fix(app): an excited two, and b", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/b.txt": "fixed\n"})
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `"picked":[5]`) {
|
||||
t.Errorf("run = %d, want #5 picked, not parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A line's record is the backport-batch block of its newest batch pull
|
||||
// request, read whatever that pull request's state and written only while it
|
||||
// is open: a merged or closed pull request is never written again, so what it
|
||||
// recorded stays what the line's later commands act on until a newer batch
|
||||
// carries a record of its own.
|
||||
|
||||
// lineRecord is the one line of JSON in the block. Version 1, the block
|
||||
// before it had a version, holds only line and deferred; version 3 adds what
|
||||
// is parked and which units on the batch do only part of their original.
|
||||
type lineRecord struct {
|
||||
Version int `json:"version"`
|
||||
Line string `json:"line"`
|
||||
Built *builtFrom `json:"built,omitempty"`
|
||||
Report string `json:"report,omitempty"`
|
||||
Closing *closing `json:"closing"`
|
||||
Deferred []deferredEntry `json:"deferred"`
|
||||
Dropped []droppedEntry `json:"dropped"`
|
||||
Stale []int `json:"stale"`
|
||||
Parked []parkedEntry `json:"parked,omitempty"`
|
||||
Partial []int `json:"partial,omitempty"`
|
||||
// Changed are the picks that differ from their originals.
|
||||
Changed []int `json:"changed,omitempty"`
|
||||
}
|
||||
|
||||
// recordVersion is the version a run writes.
|
||||
const recordVersion = 3
|
||||
|
||||
// lineRecordV2 is version 2, which has none of version 3's keys.
|
||||
type lineRecordV2 struct {
|
||||
Version int `json:"version"`
|
||||
Line string `json:"line"`
|
||||
Built *builtFrom `json:"built,omitempty"`
|
||||
Report string `json:"report,omitempty"`
|
||||
Closing *closing `json:"closing"`
|
||||
Deferred []deferredEntry `json:"deferred"`
|
||||
Dropped []droppedEntry `json:"dropped"`
|
||||
Stale []int `json:"stale"`
|
||||
}
|
||||
|
||||
// The kinds of park: an original that builds on what never reaches the
|
||||
// line, and one whose clean pick would leave part of it without effect.
|
||||
const (
|
||||
parkDependency = "dependency"
|
||||
parkPartial = "partial"
|
||||
)
|
||||
|
||||
// parkedEntry is an original the batch leaves out because it cannot land on
|
||||
// the line whole: what it needs that never comes, or the paths it would
|
||||
// leave without effect. announced says notify has named it on the open
|
||||
// batch, for exactly this entry.
|
||||
type parkedEntry struct {
|
||||
Original int `json:"original"`
|
||||
Merge string `json:"merge"`
|
||||
Kind string `json:"kind"`
|
||||
Needs []int `json:"needs,omitempty"`
|
||||
Commits []string `json:"commits,omitempty"`
|
||||
Files []string `json:"files,omitempty"`
|
||||
Announced bool `json:"announced,omitempty"`
|
||||
}
|
||||
|
||||
// parkEvent is what makes a park the same park from one record to the
|
||||
// next: its merge, kind, prerequisites, commits and files. A park whose
|
||||
// event changed is news, and notify names it again.
|
||||
func parkEvent(p parkedEntry) string {
|
||||
data, _ := json.Marshal(struct {
|
||||
Merge string `json:"merge"`
|
||||
Kind string `json:"kind"`
|
||||
Needs []int `json:"needs"`
|
||||
Commits []string `json:"commits"`
|
||||
Files []string `json:"files"`
|
||||
}{p.Merge, p.Kind, p.Needs, p.Commits, p.Files})
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// carryAnnounced marks each park announced that the carrier's record holds
|
||||
// announced as the same event, a closed carrier's too, so a new batch does
|
||||
// not name again what an earlier one named.
|
||||
func carryAnnounced(parked []parkedEntry, carrier *lineRecord) []parkedEntry {
|
||||
out := slices.Clone(parked)
|
||||
for i := range out {
|
||||
out[i].Announced = false
|
||||
}
|
||||
if carrier == nil {
|
||||
return out
|
||||
}
|
||||
for i := range out {
|
||||
out[i].Announced = slices.ContainsFunc(carrier.Parked, func(c parkedEntry) bool {
|
||||
return c.Announced && c.Original == out[i].Original && parkEvent(c) == parkEvent(out[i])
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// validate holds a parked entry to what a run writes. Its errors read after
|
||||
// "the block" or "report <id>".
|
||||
func (p parkedEntry) validate() error {
|
||||
sortedUnique := func(n int, less func(i int) bool) bool {
|
||||
for i := 1; i < n; i++ {
|
||||
if !less(i) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
switch {
|
||||
case checkSHA(p.Merge) != nil:
|
||||
return fmt.Errorf("parks #%d by merge %q", p.Original, p.Merge)
|
||||
case !sortedUnique(len(p.Needs), func(i int) bool { return p.Needs[i-1] < p.Needs[i] }) || slices.ContainsFunc(p.Needs, func(n int) bool { return n <= 0 || n == p.Original }):
|
||||
return fmt.Errorf("parks #%d for originals %v, which are not what a run writes", p.Original, p.Needs)
|
||||
case !sortedUnique(len(p.Commits), func(i int) bool { return p.Commits[i-1] < p.Commits[i] }) || slices.ContainsFunc(p.Commits, func(c string) bool { return checkSHA(c) != nil }):
|
||||
return fmt.Errorf("parks #%d for commits %q, which are not what a run writes", p.Original, p.Commits)
|
||||
case !sortedUnique(len(p.Files), func(i int) bool { return p.Files[i-1] < p.Files[i] }) || !slices.Equal(p.Files, cleanFiles(p.Files)):
|
||||
return fmt.Errorf("parks #%d for files %q, which are not what a run writes", p.Original, p.Files)
|
||||
}
|
||||
switch p.Kind {
|
||||
case parkPartial:
|
||||
if len(p.Files) == 0 || len(p.Needs)+len(p.Commits) > 0 {
|
||||
return fmt.Errorf("parks #%d as partial with no files it leaves without effect, or with what it needs", p.Original)
|
||||
}
|
||||
case parkDependency:
|
||||
if len(p.Needs)+len(p.Commits) == 0 || len(p.Files) > 0 {
|
||||
return fmt.Errorf("parks #%d for a dependency it does not name, or with files", p.Original)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("parks #%d as %q, which is no kind of park", p.Original, p.Kind)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// builtFrom is what a classification was made of; batch is the head it
|
||||
// describes.
|
||||
type builtFrom struct {
|
||||
Main string `json:"main"`
|
||||
Line string `json:"line"`
|
||||
Newer string `json:"newer"`
|
||||
Policy string `json:"policy"`
|
||||
Batch string `json:"batch"`
|
||||
Tool string `json:"tool"`
|
||||
Run string `json:"run"`
|
||||
At string `json:"at"`
|
||||
Options runOptions `json:"options"`
|
||||
}
|
||||
|
||||
type runOptions struct {
|
||||
NoWorkflowFiles bool `json:"noWorkflowFiles"`
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
// The operations a record is written by: a run that assembles the batch, and
|
||||
// the ones that only change what the record says about it.
|
||||
const (
|
||||
modeNew = "new"
|
||||
modeContinue = "continue"
|
||||
modeDefer = "defer"
|
||||
modeDrop = "drop"
|
||||
modeUndrop = "undrop"
|
||||
modeClose = "close"
|
||||
)
|
||||
|
||||
var modes = []string{modeNew, modeContinue, modeDefer, modeDrop, modeUndrop, modeClose}
|
||||
|
||||
// closing is written into the record of an open batch that the run is about
|
||||
// to close: the head it froze, which the close and the branch's deletion are
|
||||
// leased on.
|
||||
type closing struct {
|
||||
PR int `json:"pr"`
|
||||
Branch string `json:"branch"`
|
||||
Head string `json:"head"`
|
||||
}
|
||||
|
||||
// droppedEntry is a maintainer's decision that an original stays off the
|
||||
// line, bound to its merge commit on main.
|
||||
type droppedEntry struct {
|
||||
Original int `json:"original"`
|
||||
Merge string `json:"merge"`
|
||||
Reason string `json:"reason"`
|
||||
On int `json:"on"`
|
||||
Date string `json:"date"`
|
||||
}
|
||||
|
||||
var (
|
||||
toolRE = regexp.MustCompile(`^[0-9a-f]{40}(\+dirty)?$`)
|
||||
reportIDRE = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
||||
)
|
||||
|
||||
// oneLineText is s as a run writes a reason: one line, cleaned and capped.
|
||||
// A record holding anything else was not written by a run, and its text
|
||||
// would reach a terminal, a body or a comment as someone else wrote it.
|
||||
func oneLineText(s string) string { return capped(oneLine(clean(s, false)), titleLimit) }
|
||||
|
||||
// fencedLines lists the one line of each block that fence opens.
|
||||
func fencedLines(body, fence string) ([]string, error) {
|
||||
var blocks []string
|
||||
lines := strings.Split(strings.ReplaceAll(body, "\r\n", "\n"), "\n")
|
||||
for i := 0; i < len(lines); i++ {
|
||||
if strings.TrimSpace(lines[i]) != fence {
|
||||
continue
|
||||
}
|
||||
if i+2 >= len(lines) || strings.TrimSpace(lines[i+2]) != "```" {
|
||||
return nil, fmt.Errorf("the %s block is not one line of JSON", fence)
|
||||
}
|
||||
blocks = append(blocks, lines[i+1])
|
||||
i += 2
|
||||
}
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
// decodeStrict reads exactly one JSON value into v, refusing a key v does not
|
||||
// have and anything after the value.
|
||||
func decodeStrict(data string, v any) error {
|
||||
dec := json.NewDecoder(strings.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil {
|
||||
return err
|
||||
}
|
||||
var rest json.RawMessage
|
||||
if dec.More() || dec.Decode(&rest) != io.EOF {
|
||||
return errors.New("something follows the JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseRecord reads the line's record from a batch body: nil when the body
|
||||
// has no block, an error when it has more than one or one it cannot vouch
|
||||
// for whole.
|
||||
func parseRecord(body string, l line) (*lineRecord, error) {
|
||||
blocks, err := fencedLines(body, deferredFence)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, err
|
||||
case len(blocks) == 0:
|
||||
return nil, nil
|
||||
case len(blocks) > 1:
|
||||
return nil, fmt.Errorf("the body holds %d %s blocks", len(blocks), deferredFence)
|
||||
}
|
||||
var head struct {
|
||||
Version *int `json:"version"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(blocks[0]), &head); err != nil {
|
||||
return nil, fmt.Errorf("reading the %s block: %w", deferredFence, err)
|
||||
}
|
||||
version := 1
|
||||
if head.Version != nil {
|
||||
version = *head.Version
|
||||
}
|
||||
var rec lineRecord
|
||||
switch version {
|
||||
case 1:
|
||||
var v1 struct {
|
||||
Version int `json:"version"`
|
||||
Line string `json:"line"`
|
||||
Deferred []deferredEntry `json:"deferred"`
|
||||
}
|
||||
err = decodeStrict(blocks[0], &v1)
|
||||
rec = lineRecord{Version: 1, Line: v1.Line, Deferred: v1.Deferred}
|
||||
case 2:
|
||||
var v2 lineRecordV2
|
||||
err = decodeStrict(blocks[0], &v2)
|
||||
rec = lineRecordWithout(v2)
|
||||
case 3:
|
||||
err = decodeStrict(blocks[0], &rec)
|
||||
default:
|
||||
return nil, fmt.Errorf("the %s block is version %d, which this backport-batch does not read; it reads 1 to %d", deferredFence, version, recordVersion)
|
||||
}
|
||||
if err == nil && version < 3 && slices.ContainsFunc(rec.Deferred, func(d deferredEntry) bool { return d.Needs != nil }) {
|
||||
err = fmt.Errorf("version %d has no waits on other originals", version)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading the %s block: %w", deferredFence, err)
|
||||
}
|
||||
if err := rec.validate(l); err != nil {
|
||||
return nil, fmt.Errorf("the %s block %w", deferredFence, err)
|
||||
}
|
||||
return &rec, nil
|
||||
}
|
||||
|
||||
// validate holds the record to what a run writes. Its errors read after
|
||||
// "the block".
|
||||
func (rec *lineRecord) validate(l line) error {
|
||||
if rec.Line != l.branch() {
|
||||
return fmt.Errorf("is for %q, not %s", rec.Line, l.branch())
|
||||
}
|
||||
seen := map[int]bool{}
|
||||
once := func(n int) error {
|
||||
if n <= 0 {
|
||||
return fmt.Errorf("names original %d", n)
|
||||
}
|
||||
if seen[n] {
|
||||
return fmt.Errorf("names #%d twice", n)
|
||||
}
|
||||
seen[n] = true
|
||||
return nil
|
||||
}
|
||||
for _, d := range rec.Deferred {
|
||||
if err := once(d.Original); err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Commit != "" && checkSHA(d.Commit) != nil {
|
||||
return fmt.Errorf("names commit %q for #%d", d.Commit, d.Original)
|
||||
}
|
||||
// A conflict names the commit that failed and its files, a deferral
|
||||
// its reason, and a wait its workflow files.
|
||||
kinds := 0
|
||||
for _, is := range []bool{d.Commit != "" || len(d.Files) > 0 && !d.Workflows && d.Reason == "" && len(d.Needs) == 0, d.Reason != "", d.Workflows, len(d.Needs) > 0} {
|
||||
if is {
|
||||
kinds++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case d.Workflows && (d.Commit != "" || d.Reason != ""):
|
||||
return fmt.Errorf("has #%d wait for a maintainer and defers it as well", d.Original)
|
||||
case kinds != 1:
|
||||
return fmt.Errorf("does not say whether #%d is a conflict, deferred for a reason or waiting", d.Original)
|
||||
case d.Reason != "" && strings.TrimSpace(d.Reason) == "":
|
||||
return fmt.Errorf("defers #%d for an empty reason", d.Original)
|
||||
case d.Reason != oneLineText(d.Reason):
|
||||
return fmt.Errorf("defers #%d for %q, which is no reason a run writes", d.Original, d.Reason)
|
||||
case !slices.Equal(d.Files, cleanFiles(d.Files)):
|
||||
return fmt.Errorf("names files of #%d that are not as a run writes them: %q", d.Original, d.Files)
|
||||
case d.More < 0:
|
||||
return fmt.Errorf("counts %d more files for #%d", d.More, d.Original)
|
||||
case len(d.Needs) > 0 && (len(d.Files) > 0 || d.More != 0):
|
||||
return fmt.Errorf("has #%d wait on other originals with files of its own", d.Original)
|
||||
}
|
||||
for i, n := range d.Needs {
|
||||
if n <= 0 || n == d.Original || i > 0 && d.Needs[i-1] >= n {
|
||||
return fmt.Errorf("has #%d wait on %v, which is not what a run writes", d.Original, d.Needs)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, d := range rec.Dropped {
|
||||
if err := once(d.Original); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := time.Parse(time.DateOnly, d.Date); err != nil || checkSHA(d.Merge) != nil || strings.TrimSpace(d.Reason) == "" || d.On <= 0 {
|
||||
return fmt.Errorf("drops #%d with a merge, reason, pull request or date it cannot have", d.Original)
|
||||
}
|
||||
if d.Reason != oneLineText(d.Reason) {
|
||||
return fmt.Errorf("drops #%d for %q, which is no reason a run writes", d.Original, d.Reason)
|
||||
}
|
||||
}
|
||||
for _, p := range rec.Parked {
|
||||
if err := once(p.Original); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
staleSeen := map[int]bool{}
|
||||
for _, n := range rec.Stale {
|
||||
if n <= 0 || staleSeen[n] {
|
||||
return fmt.Errorf("lists %d as still on the batch more than once or not at all", n)
|
||||
}
|
||||
staleSeen[n] = true
|
||||
}
|
||||
changedSeen := map[int]bool{}
|
||||
for _, n := range rec.Changed {
|
||||
if n <= 0 || changedSeen[n] {
|
||||
return fmt.Errorf("lists %d as a changed pick more than once or not at all", n)
|
||||
}
|
||||
changedSeen[n] = true
|
||||
}
|
||||
if err := rec.waitsHold(); err != nil {
|
||||
return err
|
||||
}
|
||||
// What is on the batch is neither deferred nor parked.
|
||||
left := map[int]bool{}
|
||||
for _, d := range rec.Deferred {
|
||||
left[d.Original] = true
|
||||
}
|
||||
for _, p := range rec.Parked {
|
||||
left[p.Original] = true
|
||||
if slices.Contains(p.Commits, p.Merge) {
|
||||
return fmt.Errorf("parks #%d for its own merge", p.Original)
|
||||
}
|
||||
}
|
||||
for _, list := range [][]int{rec.Partial, rec.Changed} {
|
||||
for _, n := range list {
|
||||
if left[n] {
|
||||
return fmt.Errorf("has #%d on the batch and left off it at once", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
partialSeen := map[int]bool{}
|
||||
for _, n := range rec.Partial {
|
||||
// A unit that does only part of its original is still on the batch.
|
||||
if !staleSeen[n] || partialSeen[n] {
|
||||
return fmt.Errorf("lists #%d as a partial unit more than once, or not as still on the batch", n)
|
||||
}
|
||||
partialSeen[n] = true
|
||||
}
|
||||
if rec.Version < 2 {
|
||||
return nil
|
||||
}
|
||||
if b := rec.Built; b == nil {
|
||||
return errors.New("does not say what it was built from")
|
||||
} else if err := b.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if !reportIDRE.MatchString(rec.Report) {
|
||||
return fmt.Errorf("names report %q", rec.Report)
|
||||
}
|
||||
if c := rec.Closing; c != nil {
|
||||
m := batchBranchRE.FindStringSubmatch(c.Branch)
|
||||
if c.PR <= 0 || m == nil || m[1] != l.branch() || checkSHA(c.Head) != nil {
|
||||
return fmt.Errorf("closes #%d on %q at %q, which is no batch of %s", c.PR, c.Branch, c.Head, l.branch())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *builtFrom) validate() error {
|
||||
for _, sha := range []string{b.Main, b.Line, b.Policy, b.Batch} {
|
||||
if checkSHA(sha) != nil {
|
||||
return fmt.Errorf("says it was built from %q", sha)
|
||||
}
|
||||
}
|
||||
if b.Newer != "" && checkSHA(b.Newer) != nil {
|
||||
return fmt.Errorf("says it was built from %q", b.Newer)
|
||||
}
|
||||
if b.Tool != "" && !toolRE.MatchString(b.Tool) {
|
||||
return fmt.Errorf("names tool %q", b.Tool)
|
||||
}
|
||||
if b.Run != "" && !runURLRE.MatchString(b.Run) {
|
||||
return fmt.Errorf("names run %q", b.Run)
|
||||
}
|
||||
if _, err := time.Parse(time.RFC3339, b.At); err != nil {
|
||||
return fmt.Errorf("was built at %q", b.At)
|
||||
}
|
||||
if !slices.Contains(modes, b.Options.Mode) {
|
||||
return fmt.Errorf("was written by %q, which is no operation of backport-batch", b.Options.Mode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var runURLRE = regexp.MustCompile(`^https://[^/\s]+/[^/\s]+/[^/\s]+/actions/runs/[0-9]+(/attempts/[0-9]+)?$`)
|
||||
|
||||
// waitsHold holds what waits and parks need to what the record says of the
|
||||
// originals they need: a wait needs ones still to come, so none parked or
|
||||
// dropped, a park ones that never come, so none deferred, and no wait ends
|
||||
// up waiting on itself. Its errors read after "the block".
|
||||
func (rec *lineRecord) waitsHold() error {
|
||||
deferred, never := map[int][]int{}, map[int]bool{}
|
||||
for _, d := range rec.Deferred {
|
||||
deferred[d.Original] = d.Needs
|
||||
}
|
||||
for _, p := range rec.Parked {
|
||||
never[p.Original] = true
|
||||
}
|
||||
for _, d := range rec.Dropped {
|
||||
never[d.Original] = true
|
||||
}
|
||||
for _, d := range rec.Deferred {
|
||||
for _, n := range d.Needs {
|
||||
if never[n] {
|
||||
return fmt.Errorf("has #%d wait on #%d, which never comes", d.Original, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, p := range rec.Parked {
|
||||
for _, n := range p.Needs {
|
||||
if _, ok := deferred[n]; ok {
|
||||
return fmt.Errorf("parks #%d for #%d, which is still to come", p.Original, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
needs := map[int][]int{}
|
||||
for _, d := range rec.Deferred {
|
||||
needs[d.Original] = d.Needs
|
||||
}
|
||||
for _, p := range rec.Parked {
|
||||
needs[p.Original] = p.Needs
|
||||
}
|
||||
return waitCycle(needs)
|
||||
}
|
||||
|
||||
// waitCycle refuses waits that lead back to where they started, which no
|
||||
// run writes: a prerequisite merged before what needs it.
|
||||
func waitCycle(needs map[int][]int) error {
|
||||
state := map[int]int{} // 1 on the path, 2 done
|
||||
var visit func(n int) error
|
||||
visit = func(n int) error {
|
||||
switch state[n] {
|
||||
case 1:
|
||||
return fmt.Errorf("has #%d wait on itself through what it waits on", n)
|
||||
case 2:
|
||||
return nil
|
||||
}
|
||||
state[n] = 1
|
||||
for _, f := range needs[n] {
|
||||
if err := visit(f); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
state[n] = 2
|
||||
return nil
|
||||
}
|
||||
for _, n := range slices.Sorted(maps.Keys(needs)) {
|
||||
if err := visit(n); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lineRecordWithout is a version 2 record as the newest version holds it.
|
||||
func lineRecordWithout(v2 lineRecordV2) lineRecord {
|
||||
return lineRecord{Version: v2.Version, Line: v2.Line, Built: v2.Built, Report: v2.Report, Closing: v2.Closing, Deferred: v2.Deferred, Dropped: v2.Dropped, Stale: v2.Stale}
|
||||
}
|
||||
|
||||
// recordBlock is the block that holds rec. One line of JSON: encoding/json
|
||||
// escapes newlines and <, > and &, so nothing in a file name or a reason can
|
||||
// end the fence or open HTML.
|
||||
func recordBlock(rec lineRecord) string {
|
||||
data, _ := json.Marshal(rec)
|
||||
return deferredFence + "\n" + string(data) + "\n```"
|
||||
}
|
||||
|
||||
// savedNoWorkflowFiles is the --no-workflow-files the open batch was last
|
||||
// assembled with, which an operation that only changes the record keeps. A
|
||||
// record from before it was saved says so by listing a wait.
|
||||
func (s recordSource) savedNoWorkflowFiles() bool {
|
||||
if !s.open || s.rec == nil {
|
||||
return false
|
||||
}
|
||||
if s.rec.Built != nil {
|
||||
return s.rec.Built.Options.NoWorkflowFiles
|
||||
}
|
||||
return slices.ContainsFunc(s.rec.Deferred, func(d deferredEntry) bool { return d.Workflows })
|
||||
}
|
||||
|
||||
// dropped is what the record drops, which every later record keeps.
|
||||
func (rec *lineRecord) dropped() []droppedEntry {
|
||||
if rec == nil {
|
||||
return nil
|
||||
}
|
||||
return slices.Clone(rec.Dropped)
|
||||
}
|
||||
|
||||
// deferred maps the originals the record defers to their entries.
|
||||
func (rec *lineRecord) deferred() map[int]deferredEntry {
|
||||
out := map[int]deferredEntry{}
|
||||
if rec != nil {
|
||||
for _, d := range rec.Deferred {
|
||||
out[d.Original] = d
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// recordSource is where a line's record was found.
|
||||
type recordSource struct {
|
||||
// carrier is the pull request whose block is the record, nil when the
|
||||
// line has none.
|
||||
carrier *pullRequest
|
||||
// open says the carrier is the open batch, so the record may be written.
|
||||
open bool
|
||||
rec *lineRecord
|
||||
// code is the open batch pull request, if any. One whose body someone
|
||||
// wrote by hand is the batch the line builds on but carries no record.
|
||||
code *pullRequest
|
||||
}
|
||||
|
||||
// closingOpen is the close the record says is under way on a batch that is
|
||||
// still open, or nil.
|
||||
func (s recordSource) closingOpen() *closing {
|
||||
if !s.open || s.rec == nil {
|
||||
return nil
|
||||
}
|
||||
return s.rec.Closing
|
||||
}
|
||||
|
||||
func prState(pr *pullRequest) string {
|
||||
switch {
|
||||
case pr.MergedAt != nil:
|
||||
return "merged"
|
||||
case pr.State == "" || pr.State == "open":
|
||||
return "open"
|
||||
case pr.State == "closed":
|
||||
return "closed"
|
||||
}
|
||||
return fmt.Sprintf("in state %q", pr.State)
|
||||
}
|
||||
|
||||
func hasRecord(body string) bool {
|
||||
return slices.ContainsFunc(strings.Split(body, "\n"), func(ln string) bool { return strings.TrimSpace(ln) == deferredFence })
|
||||
}
|
||||
|
||||
// findLineRecord finds the line's record: the block of the newest pull
|
||||
// request opened from a batch branch of this repository for the line by an
|
||||
// author the batch trusts, open, merged or closed. open is the open batch
|
||||
// pull request batchPull chose, or nil. Anything that leaves in doubt which
|
||||
// record is the newest is an error, never a fall back to an older one: a
|
||||
// newer block by an author the batch does not trust, a block the bot wrote
|
||||
// and someone removed, a record it cannot read, a closed record newer than
|
||||
// the open batch, or more pull requests than it reads.
|
||||
func findLineRecord(gh github, l line, open *pullRequest) (recordSource, error) {
|
||||
src := recordSource{code: open}
|
||||
for page := 1; src.carrier == nil; page++ {
|
||||
if page > recentPullsPages {
|
||||
return src, fmt.Errorf("none of the %d newest pull requests against %s is a batch pull request with a record, so the line's record cannot be told apart from none", recentPullsPages*recentPullsPage, l.branch())
|
||||
}
|
||||
prs, err := gh.recentPulls(l.branch(), page)
|
||||
if err != nil {
|
||||
return src, err
|
||||
}
|
||||
for i := range prs {
|
||||
pr := &prs[i]
|
||||
m := batchBranchRE.FindStringSubmatch(pr.Head.Ref)
|
||||
if m == nil || m[1] != l.branch() || pr.Base.Ref != l.branch() || pr.Head.Repo == nil || pr.Head.Repo.FullName != pr.Base.Repo.FullName {
|
||||
continue
|
||||
}
|
||||
if open != nil && pr.Number == open.Number {
|
||||
pr = open
|
||||
}
|
||||
if !hasRecord(pr.Body) {
|
||||
if pr.User.Type == "Bot" && gh.batchBot() != "" && pr.User.Login == gh.batchBot() {
|
||||
return src, fmt.Errorf("batch pull request #%d (%s) was opened by %s but carries no %s block; someone removed it, so the line's record is unknown", pr.Number, prState(pr), pr.User.Login, deferredFence)
|
||||
}
|
||||
continue
|
||||
}
|
||||
why, err := trusted(gh, *pr)
|
||||
if err != nil {
|
||||
return src, fmt.Errorf("batch pull request #%d: %w", pr.Number, err)
|
||||
}
|
||||
if why != "" {
|
||||
return src, fmt.Errorf("batch pull request #%d (%s) carries a %s block but was %s; an older record is not taken in its place", pr.Number, prState(pr), deferredFence, why)
|
||||
}
|
||||
rec, err := parseRecord(pr.Body, l)
|
||||
if err != nil {
|
||||
return src, fmt.Errorf("batch pull request #%d (%s): %w", pr.Number, prState(pr), err)
|
||||
}
|
||||
src.carrier, src.rec = pr, rec
|
||||
break
|
||||
}
|
||||
if len(prs) < recentPullsPage {
|
||||
break
|
||||
}
|
||||
}
|
||||
switch c := src.carrier; {
|
||||
case open != nil && hasRecord(open.Body) && (c == nil || c.Number < open.Number):
|
||||
return src, fmt.Errorf("GitHub does not list the open batch pull request #%d among the pull requests against %s; run again", open.Number, l.branch())
|
||||
case open != nil && hasRecord(open.Body) && c.Number > open.Number:
|
||||
return src, fmt.Errorf("batch pull request #%d (%s) carries a record newer than the open batch pull request #%d; close one of them by hand", c.Number, prState(c), open.Number)
|
||||
case open != nil && c == open:
|
||||
src.open = true
|
||||
case c != nil && prState(c) == "open":
|
||||
return src, fmt.Errorf("batch pull request #%d carries the line's record and is open, but is not the batch this run builds on", c.Number)
|
||||
}
|
||||
return src, nil
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The records the live batches carried before records had a version, as
|
||||
// GitHub returned them on 2026-11-09, read as version 1.
|
||||
func TestRecordReadsVersion1(t *testing.T) {
|
||||
for line, block := range map[string]string{
|
||||
"release-1.7": `{"line":"release-1.7","deferred":[{"original":4756,"commit":"647407545d630291cfe2a20880cce45af22edf0c","files":["packages/system/backupstrategy-controller/values.yaml"]},{"original":4867,"commit":"813c6180861efe1896c26d62a7afcbc1ff590ebc","files":[".github/renovate.json"]},{"original":5082,"commit":"e93db8848027450c2e23d21348409efa641cb6f1","files":["pkg/registry/core/tap/rest.go"]},{"original":4888,"files":[".github/workflows/cut-prerelease.yaml"],"workflows":true},{"original":4971,"files":[".github/workflows/e2e-proxmox.yaml"],"workflows":true}]}`,
|
||||
"release-1.6": `{"line":"release-1.6","deferred":[{"original":5071,"commit":"3fa534f3cf6cb5774a183f0202f7f5c13e9ae211","files":["internal/operator/tapmaterializer_reconciler.go","internal/operator/tapmaterializer_reconciler_test.go"]},{"original":5086,"commit":"5265ee662c591db409c8ef1ed8bb457cf29f5c22","files":["packages/apps/tenant/templates/gateway.yaml"]},{"original":5087,"commit":"8d8179f20a2c10de03face1472435d5083cde38d","files":["internal/controller/applicationdefinition_helmreconciler.go","internal/controller/applicationdefinition_helmreconciler_test.go"]},{"original":5142,"files":[".github/workflows/pull-requests-release.yaml",".github/workflows/update-releasenotes.yaml"],"workflows":true}]}`,
|
||||
} {
|
||||
l, _ := parseLine(line)
|
||||
rec, err := parseRecord("## What this PR does\n\ntext\n\n"+deferredFence+"\n"+block+"\n```\n\n### Release note\n", l)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: parseRecord = %v", line, err)
|
||||
}
|
||||
waits, conflicts := 0, 0
|
||||
for _, e := range rec.Deferred {
|
||||
switch {
|
||||
case e.Workflows:
|
||||
waits++
|
||||
case e.Commit != "":
|
||||
conflicts++
|
||||
}
|
||||
}
|
||||
if rec.Version != 1 || rec.Line != line || rec.Closing != nil || len(rec.Dropped) != 0 || waits+conflicts != len(rec.Deferred) || waits == 0 || conflicts == 0 {
|
||||
t.Errorf("%s: record = %+v; want version 1 with its conflicts and waits", line, rec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// v2 is a version 2 record with each value it may hold.
|
||||
func v2(extra string) string {
|
||||
sha := strings.Repeat("a", 40)
|
||||
return `{"version":2,"line":"release-1.1","built":{"main":"` + sha + `","line":"` + sha + `","newer":"","policy":"` + sha + `","batch":"` + sha + `","tool":"` + sha + `+dirty","run":"","at":"2026-10-26T06:00:00Z","options":{"noWorkflowFiles":true,"mode":"continue"}},` +
|
||||
`"report":"` + strings.Repeat("b", 64) + `","closing":null,"deferred":[{"original":5,"commit":"` + sha + `","files":["app/five.txt"]},{"original":6,"files":[],"reason":"fails the e2e"},{"original":7,"files":[".github/workflows/x.yaml"],"workflows":true}],` +
|
||||
`"dropped":[{"original":8,"merge":"` + sha + `","reason":"needs #4","on":90,"date":"2026-10-26"}],"stale":[9]` + extra + `}`
|
||||
}
|
||||
|
||||
// A record is read whole or not at all: anything it cannot vouch for stops
|
||||
// the command rather than being half believed.
|
||||
func TestRecordRefuses(t *testing.T) {
|
||||
l, _ := parseLine("release-1.1")
|
||||
block := func(json string) string { return "text\n\n" + deferredFence + "\n" + json + "\n```\n" }
|
||||
if rec, err := parseRecord(block(v2("")), l); err != nil || rec.Version != 2 || len(rec.Dropped) != 1 || rec.Built.Options.Mode != "continue" {
|
||||
t.Fatalf("parseRecord of a whole v2 record = %+v, %v", rec, err)
|
||||
}
|
||||
sha := strings.Repeat("a", 40)
|
||||
for name, json := range map[string]string{
|
||||
"version 4": strings.Replace(v2(""), `"version":2`, `"version":4`, 1),
|
||||
"trailing data": v2("") + `{}`,
|
||||
"trailing text": v2("") + ` x`,
|
||||
"an original listed twice": strings.Replace(v2(""), `"original":8`, `"original":5`, 1),
|
||||
"a needs entry with a commit": strings.Replace(v2(""), `{"original":6,"files":[],"reason":"fails the e2e"}`, `{"original":6,"commit":"`+sha+`","files":[],"needs":[4]}`, 1),
|
||||
"an empty reason": strings.Replace(v2(""), `"reason":"fails the e2e"`, `"reason":""`, 1),
|
||||
"an empty drop reason": strings.Replace(v2(""), `"reason":"needs #4"`, `"reason":" "`, 1),
|
||||
"a bad tool": strings.Replace(v2(""), `+dirty"`, `-dirty"`, 1),
|
||||
"an unknown mode": strings.Replace(v2(""), `"mode":"continue"`, `"mode":"rebase"`, 1),
|
||||
"a reason with a commit": strings.Replace(v2(""), `"reason":"fails the e2e"`, `"reason":"x","commit":"`+sha+`"`, 1),
|
||||
"a short merge": strings.Replace(v2(""), `"merge":"`+sha+`"`, `"merge":"abc"`, 1),
|
||||
"a bad date": strings.Replace(v2(""), `"date":"2026-10-26"`, `"date":"26.10.2026"`, 1),
|
||||
"a bad time": strings.Replace(v2(""), `"at":"2026-10-26T06:00:00Z"`, `"at":"yesterday"`, 1),
|
||||
"a short report": strings.Replace(v2(""), strings.Repeat("b", 64), "bbbb", 1),
|
||||
"a closing on another line": strings.Replace(v2(""), `"closing":null`, `"closing":{"pr":90,"branch":"backport-batch/release-1.0-20261026","head":"`+sha+`"}`, 1),
|
||||
"a closing without a head": strings.Replace(v2(""), `"closing":null`, `"closing":{"pr":90,"branch":"`+batchBranch1+`","head":""}`, 1),
|
||||
"a negative stale": strings.Replace(v2(""), `"stale":[9]`, `"stale":[-9]`, 1),
|
||||
"an unknown key": v2(`,"parked":[]`),
|
||||
"an entry of no kind": strings.Replace(v2(""), `{"original":6,"files":[],"reason":"fails the e2e"}`, `{"original":6,"files":[]}`, 1),
|
||||
"another line": strings.Replace(v2(""), `"line":"release-1.1"`, `"line":"release-1.0"`, 1),
|
||||
"an escape in a reason": strings.Replace(v2(""), `"reason":"fails the e2e"`, `"reason":"fails\u001b[2J the e2e"`, 1),
|
||||
"a newline in a reason": strings.Replace(v2(""), `"reason":"fails the e2e"`, `"reason":"fails\nwarning: forged"`, 1),
|
||||
"an escape in a drop": strings.Replace(v2(""), `"reason":"needs #4"`, `"reason":"needs\u001b]0;x\u0007 #4"`, 1),
|
||||
"a newline in a drop": strings.Replace(v2(""), `"reason":"needs #4"`, `"reason":"needs #4\nnote: forged"`, 1),
|
||||
"a reason past its length": strings.Replace(v2(""), `"reason":"needs #4"`, `"reason":"`+strings.Repeat("x", titleLimit+1)+`"`, 1),
|
||||
"a bidi file name": strings.Replace(v2(""), `"files":["app/five.txt"]`, `"files":["app/\u202efive.txt"]`, 1),
|
||||
} {
|
||||
if _, err := parseRecord(block(json), l); err == nil {
|
||||
t.Errorf("%s: parseRecord accepted it", name)
|
||||
}
|
||||
}
|
||||
closing := strings.Replace(v2(""), `"closing":null`, `"closing":{"pr":90,"branch":"`+batchBranch1+`","head":"`+sha+`"}`, 1)
|
||||
if rec, err := parseRecord(block(closing), l); err != nil || rec.Closing == nil || rec.Closing.PR != 90 {
|
||||
t.Errorf("a record that is closing = %+v, %v", rec, err)
|
||||
}
|
||||
}
|
||||
|
||||
// recordPR is a batch pull request on release-1.1 carrying body, numbered n,
|
||||
// in state, opened by login.
|
||||
func recordPR(n int, state, login, body string) pullRequest {
|
||||
pr := notifyPR("20261026", body)
|
||||
pr.Number, pr.State = n, state
|
||||
pr.Head.Ref = fmt.Sprintf("backport-batch/release-1.1-202610%02d", n%30+1)
|
||||
pr.User.Login = login
|
||||
if strings.HasSuffix(login, "[bot]") {
|
||||
pr.User.Type = "Bot"
|
||||
}
|
||||
return pr
|
||||
}
|
||||
|
||||
func recordBody(conflict int) string {
|
||||
return "text\n\n" + deferredFence + "\n" + fmt.Sprintf(`{"line":"release-1.1","deferred":[{"original":%d,"commit":"%s","files":["a"]}]}`, conflict, strings.Repeat("a", 40)) + "\n```\n"
|
||||
}
|
||||
|
||||
// The record is the block of the newest batch pull request that carries one,
|
||||
// whatever its state, among those a trusted author opened from a batch branch
|
||||
// of this repository; anything that leaves the newest record in doubt stops
|
||||
// the command rather than falling back to an older one.
|
||||
func TestFindLineRecord(t *testing.T) {
|
||||
const bot = defaultBatchBot
|
||||
other := func(n int) pullRequest {
|
||||
pr := recordPR(n, "closed", "maintainer", "")
|
||||
pr.Head.Ref = fmt.Sprintf("fix-%d", n)
|
||||
return pr
|
||||
}
|
||||
fork := recordPR(92, "closed", "maintainer", recordBody(92))
|
||||
fork.Head.Repo = &struct {
|
||||
FullName string `json:"full_name"`
|
||||
}{"someone/cozystack"}
|
||||
cases := []struct {
|
||||
name string
|
||||
prs []pullRequest
|
||||
open int // the open batch the caller found, or 0
|
||||
bot string
|
||||
carrier int // 0 for none
|
||||
isOpen bool
|
||||
refusal string
|
||||
pages int
|
||||
}{
|
||||
{name: "the open batch first", prs: []pullRequest{recordPR(92, "open", "maintainer", recordBody(92)), recordPR(91, "closed", "maintainer", recordBody(91))}, open: 92, carrier: 92, isOpen: true},
|
||||
{name: "the newest closed record", prs: []pullRequest{recordPR(91, "closed", bot, recordBody(91)), recordPR(90, "closed", bot, recordBody(90))}, bot: bot, carrier: 91},
|
||||
{name: "a person's batch without a block is passed over", prs: []pullRequest{recordPR(92, "closed", "maintainer", "picked by hand"), recordPR(91, "closed", "maintainer", recordBody(91))}, carrier: 91},
|
||||
{name: "the bot's batch without a block", prs: []pullRequest{recordPR(92, "closed", bot, "edited away"), recordPR(91, "closed", bot, recordBody(91))}, bot: bot, refusal: "carries no ```backport-batch block"},
|
||||
{name: "a fork is no batch", prs: []pullRequest{fork, recordPR(91, "closed", "maintainer", recordBody(91))}, carrier: 91},
|
||||
{name: "a newer record by someone untrusted", prs: []pullRequest{recordPR(92, "closed", "someone", recordBody(92)), recordPR(91, "closed", "maintainer", recordBody(91))}, refusal: "#92"},
|
||||
{name: "a closed record newer than the open batch", prs: []pullRequest{recordPR(92, "closed", "maintainer", recordBody(92)), recordPR(91, "open", "maintainer", recordBody(91))}, open: 91, refusal: "newer than the open batch pull request #91"},
|
||||
{name: "a record on the second page", prs: append(func() (out []pullRequest) {
|
||||
for n := 1000; n < 1000+recentPullsPage; n++ {
|
||||
out = append(out, other(n))
|
||||
}
|
||||
return out
|
||||
}(), recordPR(91, "closed", "maintainer", recordBody(91))), carrier: 91, pages: 2},
|
||||
{name: "ten full pages without a record", prs: func() (out []pullRequest) {
|
||||
for n := 1000; n < 1000+10*recentPullsPage+1; n++ {
|
||||
out = append(out, other(n))
|
||||
}
|
||||
return out
|
||||
}(), refusal: "pull requests", pages: 10},
|
||||
{name: "the bot's record when no bot is trusted", prs: []pullRequest{recordPR(91, "closed", bot, recordBody(91))}, refusal: "#91"},
|
||||
{name: "a hand-written open batch beside a closed record", prs: []pullRequest{recordPR(92, "open", "maintainer", "picked by hand"), recordPR(91, "closed", "maintainer", recordBody(91))}, open: 92, carrier: 91},
|
||||
{name: "no batch ever", prs: []pullRequest{other(5)}},
|
||||
{name: "an unreadable record", prs: []pullRequest{recordPR(91, "closed", "maintainer", "text\n\n"+deferredFence+"\n{\n```\n")}, refusal: "#91 (closed)"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
l, _ := parseLine("release-1.1")
|
||||
gh := &fakeGH{prs: tc.prs, bot: tc.bot}
|
||||
var open *pullRequest
|
||||
for i := range tc.prs {
|
||||
if tc.prs[i].Number == tc.open {
|
||||
open = &tc.prs[i]
|
||||
}
|
||||
}
|
||||
src, err := findLineRecord(gh, l, open)
|
||||
switch {
|
||||
case tc.refusal != "":
|
||||
if err == nil || !strings.Contains(err.Error(), tc.refusal) {
|
||||
t.Errorf("findLineRecord = %+v, %v; want a refusal with %q", src, err, tc.refusal)
|
||||
}
|
||||
case err != nil:
|
||||
t.Errorf("findLineRecord: %v", err)
|
||||
case tc.carrier == 0 && (src.carrier != nil || src.rec != nil):
|
||||
t.Errorf("found #%d, want no record", src.carrier.Number)
|
||||
case tc.carrier != 0 && (src.carrier == nil || src.carrier.Number != tc.carrier || src.rec == nil || src.open != tc.isOpen || src.rec.Deferred[0].Original != tc.carrier):
|
||||
t.Errorf("found %+v, want #%d open=%v", src, tc.carrier, tc.isOpen)
|
||||
}
|
||||
if tc.pages != 0 && gh.listed != tc.pages {
|
||||
t.Errorf("read %d pages, want %d", gh.listed, tc.pages)
|
||||
}
|
||||
if tc.open != 0 && src.code != open {
|
||||
t.Errorf("the batch to build on is %+v, want #%d", src.code, tc.open)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A run that picks nothing while no batch is open writes nothing, since
|
||||
// merged and closed batches are never written: it says its classification is
|
||||
// not kept, and check still reads the merged batch's record.
|
||||
func TestZeroPickRunLeavesNoRecord(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): a line-only five", map[string]string{"app/five.txt": "line\n", "app/seven.txt": "line\n"})
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
mergeBatch(f, gh)
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
edits, comments := len(gh.edited), len(gh.issueComments)
|
||||
|
||||
code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if code != 0 || !strings.Contains(stderr, "no batch pull request is open on release-1.1; this run's classification is not retained") {
|
||||
t.Errorf("run = %d, want 0 saying nothing is retained:\n%s", code, stderr)
|
||||
}
|
||||
if len(gh.created) != 1 || len(gh.edited) != edits || len(gh.issueComments) != comments || f.remoteHead(batchBranch1) != "" {
|
||||
t.Errorf("created %q, edited %q, %d comments, branch at %q; want nothing written", gh.created, gh.edited, len(gh.issueComments), f.remoteHead(batchBranch1))
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1")
|
||||
if code != 1 || !strings.Contains(stdout, "/pull/7 ") || strings.Contains(stdout, "/pull/5 ") || !strings.Contains(stderr, "deferred conflict on #90 (merged)") {
|
||||
t.Errorf("check = %d, want 1 for #7 alone and #5 still a deferred conflict:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// The open batch's author is asked for once although both the open batch and
|
||||
// its record are read.
|
||||
func TestRecordAsksForAPermissionOnce(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
gh.asked = nil
|
||||
if code, _, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 {
|
||||
t.Fatalf("check = %d\n%s", code, stderr)
|
||||
}
|
||||
if len(gh.asked) != 1 {
|
||||
t.Errorf("asked GitHub for %q, want the author once", gh.asked)
|
||||
}
|
||||
}
|
||||
|
||||
// The record and the report name what the classification was made of: the
|
||||
// heads it read, the policy, the tool, the job, the time and the flags.
|
||||
func TestRecordNamesItsInputs(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.onLine("release-1.1", "fix(app): five\n\n(cherry picked from commit "+mc5+")", map[string]string{"app/five.txt": "5\n"})
|
||||
f.tool = strings.Repeat("c", 40) + "+dirty"
|
||||
t.Setenv("GITHUB_SERVER_URL", "https://github.com")
|
||||
t.Setenv("GITHUB_REPOSITORY", "cozystack/cozystack")
|
||||
t.Setenv("GITHUB_RUN_ID", "123")
|
||||
t.Setenv("GITHUB_RUN_ATTEMPT", "2")
|
||||
gh := &fakeGH{}
|
||||
stdout := mustRun(t, f, gh, "run", "--line", "release-1.0", "--no-workflow-files", "--push")
|
||||
l, _ := parseLine("release-1.0")
|
||||
const branch = "backport-batch/release-1.0-20261026"
|
||||
rec, err := parseRecord(stdout, l)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := builtFrom{Main: f.git("rev-parse", "origin/main"), Line: f.git("rev-parse", "origin/release-1.0"), Newer: f.git("rev-parse", "origin/release-1.1"),
|
||||
Policy: f.git("rev-parse", "origin/main"), Batch: f.remoteHead(branch), Tool: f.tool, Run: "https://github.com/cozystack/cozystack/actions/runs/123/attempts/2",
|
||||
At: "2026-10-26T06:00:00Z", Options: runOptions{NoWorkflowFiles: true, Mode: modeNew}}
|
||||
if rec.Version != recordVersion || *rec.Built != want || bodyReportOf(t, stdout, l).doc.Built != want || rec.Report != bodyReportOf(t, stdout, l).doc.ID {
|
||||
t.Errorf("record = %+v, built %+v; want built %+v and the report it names", rec, rec.Built, want)
|
||||
}
|
||||
|
||||
// A policy from another ref, a run by hand that continues the batch.
|
||||
f.git("push", "-q", "origin", "origin/main:refs/heads/policy-draft")
|
||||
f.git("fetch", "-q", "origin")
|
||||
t.Setenv("GITHUB_RUN_ID", "")
|
||||
gh.prs = []pullRequest{f.batchPR(90, "release-1.0", branch, stdout)}
|
||||
mc6 := f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
f.onLine("release-1.1", "fix(app): six\n\n(cherry picked from commit "+mc6+")", map[string]string{"app/six.txt": "6\n"})
|
||||
stdout = mustRun(t, f, gh, "run", "--line", "release-1.0", "--continue", "--policy", "origin/policy-draft", "--push")
|
||||
if rec, err = parseRecord(stdout, l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b := rec.Built; b.Policy != f.git("rev-parse", "origin/policy-draft") || b.Main != f.git("rev-parse", "origin/main") || b.Run != "" || b.Options != (runOptions{Mode: modeContinue}) || b.Batch != f.remoteHead(branch) {
|
||||
t.Errorf("built %+v; want the draft's policy, no job and a continuation without the flag", b)
|
||||
}
|
||||
}
|
||||
|
||||
// What a run assembled with --no-workflow-files stays saved through the
|
||||
// operations that only change the record, which take no such flag: check
|
||||
// keeps failing the cut on the wait they leave in place.
|
||||
func TestMetadataOperationsKeepTheMode(t *testing.T) {
|
||||
for _, v1 := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("an open record of version 1: %v", v1), func(t *testing.T) {
|
||||
f := workflowWorld(t)
|
||||
f.onLine("release-1.1", "fix(app): a line-only nine", map[string]string{"app/nine.txt": "line\n"})
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
f.pr(9, "fix(app): nine", "", map[string]string{"app/nine.txt": "9\n"})
|
||||
gh := &fakeGH{}
|
||||
stdout := mustRun(t, f, gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push")
|
||||
reopen(f, gh)
|
||||
if v1 {
|
||||
waits := []pick{{v: &verdict{o: &original{number: 5}}, files: []string{".github/workflows/five.yaml"}}}
|
||||
gh.prs[0].Body = strings.Replace(stdout, strings.Split(strings.Split(stdout, deferredFence+"\n")[1], "\n")[0], strings.Split(deferredBlock(notifyLine, nil, nil, waits), "\n")[1], 1)
|
||||
} else if rec, err := parseRecord(stdout, notifyLine); err != nil || !rec.Built.Options.NoWorkflowFiles {
|
||||
t.Fatalf("the scheduled run saved %+v, %v", rec, err)
|
||||
}
|
||||
for _, op := range []struct {
|
||||
args []string
|
||||
mode string
|
||||
}{
|
||||
{[]string{"--drop", "9", "--reason", "needs #4"}, modeDrop},
|
||||
{[]string{"--undrop", "9"}, modeUndrop},
|
||||
{[]string{"--defer", "7", "--reason", "fails the e2e"}, modeDefer},
|
||||
} {
|
||||
stdout = mustRun(t, f, gh, append(append([]string{"run", "--line", "release-1.1"}, op.args...), "--push")...)
|
||||
rec, err := parseRecord(stdout, notifyLine)
|
||||
if err != nil || rec.Built.Options != (runOptions{NoWorkflowFiles: true, Mode: op.mode}) {
|
||||
t.Errorf("after %q the record is %+v, %v; want the flag kept", op.args, rec.Built, err)
|
||||
}
|
||||
reopen(f, gh)
|
||||
}
|
||||
var rec *lineRecord
|
||||
var err error
|
||||
reopen(f, gh)
|
||||
if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#5 changes .github/workflows/") {
|
||||
t.Errorf("check --cut = %d, want #5 still waiting:\n%s", code, stdout)
|
||||
}
|
||||
|
||||
// Deferring the last picks closes the batch, and its record
|
||||
// still says how the batch was assembled.
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--defer", "6,8", "--reason", "fails the e2e", "--push")
|
||||
rec, err = parseRecord(gh.find(90).Body, notifyLine)
|
||||
if err != nil || gh.find(90).State != "closed" || rec.Closing == nil || rec.Built.Options != (runOptions{NoWorkflowFiles: true, Mode: modeClose}) {
|
||||
t.Errorf("after the close the record is %+v, %v; want the flag kept", rec.Built, err)
|
||||
}
|
||||
if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "/pull/5 ") {
|
||||
t.Errorf("check --cut = %d, want #5 missing once no batch lists it:\n%s", code, stdout)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A state is named only when it is one GitHub uses; anything else is quoted.
|
||||
func TestPRStateNamesOnlyKnownStates(t *testing.T) {
|
||||
at := "2026-10-26T12:00:00Z"
|
||||
for _, tc := range []struct {
|
||||
pr pullRequest
|
||||
want string
|
||||
}{
|
||||
{pullRequest{State: "open"}, "open"},
|
||||
{pullRequest{State: ""}, "open"},
|
||||
{pullRequest{State: "closed"}, "closed"},
|
||||
{pullRequest{State: "closed", MergedAt: &at}, "merged"},
|
||||
{pullRequest{State: "open\n\x1b[2Jforged"}, `in state "open\n\x1b[2Jforged"`},
|
||||
} {
|
||||
if got := prState(&tc.pr); got != tc.want {
|
||||
t.Errorf("prState(%q) = %q, want %q", tc.pr.State, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// v3 is v2 as version 3, with extra after the stale list.
|
||||
func v3(extra string) string {
|
||||
return strings.Replace(v2(extra), `"version":2`, `"version":3`, 1)
|
||||
}
|
||||
|
||||
// Version 3 adds what is parked and which units do only part of their
|
||||
// original, each held to what a run writes, and version 2 has neither.
|
||||
func TestRecordVersion3(t *testing.T) {
|
||||
l, _ := parseLine("release-1.1")
|
||||
block := func(json string) string { return "text\n\n" + deferredFence + "\n" + json + "\n```\n" }
|
||||
sha, other := strings.Repeat("a", 40), strings.Repeat("c", 40)
|
||||
parked := `,"parked":[{"original":10,"merge":"` + sha + `","kind":"partial","files":["a","b"]},{"original":11,"merge":"` + sha + `","kind":"dependency","needs":[3,4],"commits":["` + other + `"],"announced":true}],"partial":[9]`
|
||||
waits := strings.Replace(v3(parked), `{"original":6,"files":[],"reason":"fails the e2e"}`, `{"original":6,"files":[],"needs":[3,5]}`, 1)
|
||||
rec, err := parseRecord(block(waits), l)
|
||||
if err != nil || rec.Version != 3 || len(rec.Parked) != 2 || !rec.Parked[1].Announced || !slices.Equal(rec.Partial, []int{9}) || !slices.Equal(rec.deferred()[6].Needs, []int{3, 5}) {
|
||||
t.Fatalf("parseRecord of a whole v3 record = %+v, %v", rec, err)
|
||||
}
|
||||
for name, json := range map[string]string{
|
||||
"version 1 with a wait": `{"line":"release-1.1","deferred":[{"original":6,"files":[],"needs":[3,5]}]}`,
|
||||
"a wait with files": strings.Replace(waits, `"files":[],"needs":[3,5]`, `"files":["a"],"needs":[3,5]`, 1),
|
||||
"a wait that is a conflict": strings.Replace(waits, `"files":[],"needs":[3,5]`, `"commit":"`+sha+`","files":[],"needs":[3,5]`, 1),
|
||||
"a wait on itself": strings.Replace(waits, `"needs":[3,5]`, `"needs":[3,6]`, 1),
|
||||
"an unsorted wait": strings.Replace(waits, `"needs":[3,5]`, `"needs":[5,3]`, 1),
|
||||
"a wait on nothing": strings.Replace(waits, `"needs":[3,5]`, `"needs":[0]`, 1),
|
||||
"a wait cycle": strings.Replace(strings.Replace(waits, `"needs":[3,5]`, `"needs":[12]`, 1), `"deferred":[`, `"deferred":[{"original":12,"files":[],"needs":[6]},`, 1),
|
||||
"a wait on a parked one": strings.Replace(waits, `"needs":[3,5]`, `"needs":[10]`, 1),
|
||||
"a wait on a dropped one": strings.Replace(waits, `"needs":[3,5]`, `"needs":[8]`, 1),
|
||||
"a park on a deferred one": strings.Replace(waits, `"needs":[3,4]`, `"needs":[3,5]`, 1),
|
||||
"a partial unit also deferred": strings.Replace(strings.Replace(waits, `"stale":[9]`, `"stale":[9,5]`, 1), `"partial":[9]`, `"partial":[9,5]`, 1),
|
||||
"a changed pick also parked": v3(parked + `,"changed":[10]`),
|
||||
"a changed pick also deferred": v3(parked + `,"changed":[5]`),
|
||||
"a park on its own merge": strings.Replace(waits, `"commits":["`+other+`"]`, `"commits":["`+sha+`"]`, 1),
|
||||
"a park cycle": strings.Replace(strings.Replace(waits, `"needs":[3,4]`, `"needs":[3,13]`, 1), `"parked":[`, `"parked":[{"original":13,"merge":"`+sha+`","kind":"dependency","needs":[11]},`, 1),
|
||||
} {
|
||||
if _, err := parseRecord(block(json), l); err == nil {
|
||||
t.Errorf("%s: parseRecord accepted it", name)
|
||||
}
|
||||
}
|
||||
for name, json := range map[string]string{
|
||||
"version 2 with a park": v2(parked),
|
||||
"version 4": strings.Replace(v3(""), `"version":3`, `"version":4`, 1),
|
||||
"a park of a deferred original": v3(strings.Replace(parked, `"original":10`, `"original":5`, 1)),
|
||||
"a park of a dropped original": v3(strings.Replace(parked, `"original":10`, `"original":8`, 1)),
|
||||
"a partial park with no files": v3(strings.Replace(parked, `"files":["a","b"]`, `"files":[]`, 1)),
|
||||
"a partial park that needs": v3(strings.Replace(parked, `"files":["a","b"]`, `"files":["a"],"needs":[3]`, 1)),
|
||||
"unsorted files": v3(strings.Replace(parked, `"files":["a","b"]`, `"files":["b","a"]`, 1)),
|
||||
"a file that drives a terminal": v3(strings.Replace(parked, `"files":["a","b"]`, `"files":["a\u001b[2J"]`, 1)),
|
||||
"a dependency park with no need": v3(strings.Replace(strings.Replace(parked, `"needs":[3,4],`, ``, 1), `"commits":["`+other+`"],`, ``, 1)),
|
||||
"unsorted needs": v3(strings.Replace(parked, `"needs":[3,4]`, `"needs":[4,3]`, 1)),
|
||||
"a park that needs itself": v3(strings.Replace(parked, `"needs":[3,4]`, `"needs":[3,11]`, 1)),
|
||||
"a short commit": v3(strings.Replace(parked, `"commits":["`+other+`"]`, `"commits":["abc"]`, 1)),
|
||||
"a short merge": v3(strings.Replace(parked, `"merge":"`+sha+`","kind":"partial"`, `"merge":"abc","kind":"partial"`, 1)),
|
||||
"an unknown kind": v3(strings.Replace(parked, `"kind":"partial"`, `"kind":"later"`, 1)),
|
||||
"a partial unit not on the batch": v3(strings.Replace(parked, `"partial":[9]`, `"partial":[10]`, 1)),
|
||||
"a partial unit twice": v3(strings.Replace(parked, `"partial":[9]`, `"partial":[9,9]`, 1)),
|
||||
"a changed pick twice": v3(parked + `,"changed":[4,4]`),
|
||||
"a changed pick that is none": v3(parked + `,"changed":[0]`),
|
||||
} {
|
||||
if _, err := parseRecord(block(json), l); err == nil {
|
||||
t.Errorf("%s: parseRecord accepted it", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,885 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"regexp"
|
||||
"runtime/debug"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A report is one classification of a line: where every original merged into
|
||||
// main since the line branched stands, and what it was made of. The batch
|
||||
// pull request's body carries the latest one beside the record, and an issue
|
||||
// comment the tool never edits keeps each one, so a later run that replaces
|
||||
// the body loses none of them. Its ID hashes the classification, not the pull
|
||||
// request it lands on, which a new batch does not have yet when the report is
|
||||
// made.
|
||||
|
||||
const (
|
||||
reportFence = "```backport-batch-report"
|
||||
reportMarker = "<!-- backport-batch:report "
|
||||
// reportFormat is the format a run writes. Format 2 adds parked
|
||||
// originals and partial units; format 1, which has neither, is read too.
|
||||
reportFormat = 2
|
||||
// reportLimit keeps a report comment well inside GitHub's 65536.
|
||||
reportLimit = 60000
|
||||
)
|
||||
|
||||
type reportDoc struct {
|
||||
Format int `json:"format"`
|
||||
ID string `json:"id"`
|
||||
Line string `json:"line"`
|
||||
Built builtFrom `json:"built"`
|
||||
Overrides reportOverrides `json:"overrides"`
|
||||
Primary reportPrimary `json:"primary"`
|
||||
Overlays reportOverlays `json:"overlays"`
|
||||
Diag map[string][]string `json:"diag"`
|
||||
Other []string `json:"other"`
|
||||
}
|
||||
|
||||
type reportOverrides struct {
|
||||
Include []int `json:"backport/include"`
|
||||
Skip []int `json:"backport/skip"`
|
||||
}
|
||||
|
||||
// reportPrimary puts every original in exactly one place.
|
||||
type reportPrimary struct {
|
||||
Picked []int `json:"picked"`
|
||||
Missing []int `json:"missing"`
|
||||
Deferred []deferredEntry `json:"deferred"`
|
||||
Parked []parkedEntry `json:"parked"`
|
||||
Skipped reportSkipped `json:"skipped"`
|
||||
}
|
||||
|
||||
type reportSkipped struct {
|
||||
OnLine []int `json:"on-line"`
|
||||
BeforeStart []int `json:"before-start"`
|
||||
Type []int `json:"type"`
|
||||
Breaking []int `json:"breaking"`
|
||||
Touches []int `json:"touches"`
|
||||
Newer []int `json:"newer"`
|
||||
SkipLabel []int `json:"skip-label"`
|
||||
Dropped []int `json:"dropped"`
|
||||
}
|
||||
|
||||
// reportOverlays mark originals that are also something else: stale ones
|
||||
// are excluded, or applied only in part, but still on the batch, partial
|
||||
// ones those whose unit there leaves part of them without effect, and each
|
||||
// drop is the record's entry, with the merge commit it is bound to and its
|
||||
// reason.
|
||||
type reportOverlays struct {
|
||||
Dropped []droppedEntry `json:"dropped"`
|
||||
Stale []int `json:"stale"`
|
||||
Changed []int `json:"changed"`
|
||||
Partial []int `json:"partial,omitempty"`
|
||||
}
|
||||
|
||||
func (s *reportSkipped) list(rule int) *[]int {
|
||||
switch rule {
|
||||
case ruleOnLine:
|
||||
return &s.OnLine
|
||||
case ruleBeforeStart:
|
||||
return &s.BeforeStart
|
||||
case ruleType:
|
||||
return &s.Type
|
||||
case ruleBreaking:
|
||||
return &s.Breaking
|
||||
case ruleTouches:
|
||||
return &s.Touches
|
||||
case ruleNewer:
|
||||
return &s.Newer
|
||||
case ruleSkipLabel:
|
||||
return &s.SkipLabel
|
||||
case ruleDropped:
|
||||
return &s.Dropped
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type namedList struct {
|
||||
name string
|
||||
list *[]int
|
||||
}
|
||||
|
||||
// lists names each skipped list as the report does.
|
||||
func (s *reportSkipped) lists() []namedList {
|
||||
return []namedList{
|
||||
{"on-line", &s.OnLine}, {"before-start", &s.BeforeStart}, {"type", &s.Type}, {"breaking", &s.Breaking},
|
||||
{"touches", &s.Touches}, {"newer", &s.Newer}, {"skip-label", &s.SkipLabel}, {"dropped", &s.Dropped},
|
||||
}
|
||||
}
|
||||
|
||||
func numbers(vs []*verdict) []int {
|
||||
out := []int{}
|
||||
for _, v := range vs {
|
||||
out = append(out, v.o.number)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// deferredEntries is what the record and the report say about the conflicts,
|
||||
// the deferrals and the waits of a run.
|
||||
func deferredEntries(conflicts, held, waiting, needs []pick) []deferredEntry {
|
||||
out := []deferredEntry{}
|
||||
for _, p := range conflicts {
|
||||
files := cleanFiles(p.files[:min(len(p.files), filesKept)])
|
||||
out = append(out, deferredEntry{Original: p.v.o.number, Commit: p.failed, Files: files, More: len(p.files) - len(files) + p.more})
|
||||
}
|
||||
for _, p := range held {
|
||||
out = append(out, deferredEntry{Original: p.v.o.number, Files: []string{}, Reason: capped(oneLine(clean(p.reason, false)), titleLimit)})
|
||||
}
|
||||
for _, p := range waiting {
|
||||
files := cleanFiles(p.files[:min(len(p.files), filesKept)])
|
||||
out = append(out, deferredEntry{Original: p.v.o.number, Files: files, More: len(p.files) - len(files) + p.more, Workflows: true})
|
||||
}
|
||||
for _, p := range needs {
|
||||
out = append(out, deferredEntry{Original: p.v.o.number, Files: []string{}, Needs: slices.Sorted(slices.Values(p.needs))})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// parkedEntries is what the record and the report say about what a run
|
||||
// parked; whether notify named it is the record's alone.
|
||||
func parkedEntries(vs []*verdict) []parkedEntry {
|
||||
out := []parkedEntry{}
|
||||
for _, v := range vs {
|
||||
p := *v.park
|
||||
p.Announced = false
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// buildReport makes the report of a run whose built is set. Every original
|
||||
// main merged since the line branched has to land in exactly one primary
|
||||
// category; one that does not is an error rather than a report that
|
||||
// silently drops it.
|
||||
func buildReport(b *batch, r *report) (reportDoc, error) {
|
||||
doc := reportDoc{Format: reportFormat, Line: b.line.branch(), Built: r.built, Diag: map[string][]string{}, Other: append([]string{}, b.other...)}
|
||||
doc.Overrides = reportOverrides{Include: []int{}, Skip: []int{}}
|
||||
for _, v := range r.overrides {
|
||||
switch v.label {
|
||||
case labelInclude:
|
||||
doc.Overrides.Include = append(doc.Overrides.Include, v.o.number)
|
||||
case labelSkip:
|
||||
doc.Overrides.Skip = append(doc.Overrides.Skip, v.o.number)
|
||||
}
|
||||
}
|
||||
doc.Primary = reportPrimary{Picked: numbers(r.onBranch), Missing: numbers(r.missing), Deferred: deferredEntries(r.deferred, r.held, r.waiting, r.needs), Parked: parkedEntries(r.parked)}
|
||||
for _, l := range doc.Primary.Skipped.lists() {
|
||||
*l.list = []int{}
|
||||
}
|
||||
for rule, vs := range r.skipped {
|
||||
list := doc.Primary.Skipped.list(rule)
|
||||
if list == nil {
|
||||
return doc, fmt.Errorf("the report has no place for what rule %d skipped", rule)
|
||||
}
|
||||
*list = append(*list, numbers(vs)...)
|
||||
}
|
||||
doc.Overlays = reportOverlays{Dropped: []droppedEntry{}, Stale: numbers(r.stale), Changed: numbers(r.changed())}
|
||||
if len(r.partial) > 0 {
|
||||
doc.Overlays.Partial = numbers(r.partial)
|
||||
}
|
||||
for _, v := range b.verdicts {
|
||||
if len(v.diag) > 0 {
|
||||
doc.Diag[strconv.Itoa(v.o.number)] = slices.Clone(v.diag)
|
||||
}
|
||||
}
|
||||
doc.Overlays.Dropped = append(doc.Overlays.Dropped, r.dropped...)
|
||||
doc.canonical()
|
||||
where, err := doc.categories()
|
||||
if err != nil {
|
||||
return doc, err
|
||||
}
|
||||
for _, v := range b.verdicts {
|
||||
if where[v.o.number] == "" {
|
||||
return doc, fmt.Errorf("the report of %s puts #%d nowhere", b.line.branch(), v.o.number)
|
||||
}
|
||||
delete(where, v.o.number)
|
||||
}
|
||||
for n := range where {
|
||||
return doc, fmt.Errorf("the report of %s names #%d, which main did not merge after the line branched", b.line.branch(), n)
|
||||
}
|
||||
doc.ID = reportID(doc)
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// canonical sorts every list, so equal classifications are equal bytes.
|
||||
func (d *reportDoc) canonical() {
|
||||
lists := []*[]int{&d.Primary.Picked, &d.Primary.Missing, &d.Overrides.Include, &d.Overrides.Skip, &d.Overlays.Stale, &d.Overlays.Changed, &d.Overlays.Partial}
|
||||
for _, l := range d.Primary.Skipped.lists() {
|
||||
lists = append(lists, l.list)
|
||||
}
|
||||
for _, l := range lists {
|
||||
slices.Sort(*l)
|
||||
}
|
||||
slices.SortFunc(d.Primary.Deferred, func(a, b deferredEntry) int { return cmp.Compare(a.Original, b.Original) })
|
||||
slices.SortFunc(d.Primary.Parked, func(a, b parkedEntry) int { return cmp.Compare(a.Original, b.Original) })
|
||||
slices.SortFunc(d.Overlays.Dropped, func(a, b droppedEntry) int { return cmp.Compare(a.Original, b.Original) })
|
||||
slices.Sort(d.Other)
|
||||
}
|
||||
|
||||
// categories maps each original the report names to its primary category,
|
||||
// refusing one named twice.
|
||||
func (d *reportDoc) categories() (map[int]string, error) {
|
||||
where := map[int]string{}
|
||||
put := func(n int, category string) error {
|
||||
if n <= 0 {
|
||||
return fmt.Errorf("the report puts original %d in %s", n, category)
|
||||
}
|
||||
if prev := where[n]; prev != "" {
|
||||
return fmt.Errorf("the report puts #%d in both %s and %s", n, prev, category)
|
||||
}
|
||||
where[n] = category
|
||||
return nil
|
||||
}
|
||||
for _, n := range d.Primary.Picked {
|
||||
if err := put(n, "picked"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, n := range d.Primary.Missing {
|
||||
if err := put(n, "missing"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, e := range d.Primary.Deferred {
|
||||
if err := put(e.Original, "deferred"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, e := range d.Primary.Parked {
|
||||
if err := put(e.Original, "parked"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, l := range d.Primary.Skipped.lists() {
|
||||
for _, n := range *l.list {
|
||||
if err := put(n, "skipped."+l.name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return where, nil
|
||||
}
|
||||
|
||||
// reportID hashes everything a report says but when and in which job it was
|
||||
// made, so a run that finds what the last one found makes the same report.
|
||||
func reportID(doc reportDoc) string {
|
||||
doc.ID, doc.Built.At, doc.Built.Run = "", "", ""
|
||||
data, _ := json.Marshal(doc)
|
||||
sum := sha256.Sum256(data)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// storedReport is a report as it was written, whose bytes a replay posts
|
||||
// unchanged.
|
||||
type storedReport struct {
|
||||
doc reportDoc
|
||||
raw string
|
||||
}
|
||||
|
||||
func reportJSON(doc reportDoc) string {
|
||||
data, _ := json.Marshal(doc)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func reportBlock(raw string) string { return reportFence + "\n" + raw + "\n```" }
|
||||
|
||||
// parseReport reads one report line of a batch pull request against l. An
|
||||
// ID that matches the content shows only that nobody changed it since it
|
||||
// was hashed, so everything it says is also held to what a run writes.
|
||||
func parseReport(raw string, l line) (reportDoc, error) {
|
||||
var doc reportDoc
|
||||
if err := decodeStrict(raw, &doc); err != nil {
|
||||
return doc, fmt.Errorf("reading the report: %w", err)
|
||||
}
|
||||
if doc.Format != 1 && doc.Format != reportFormat {
|
||||
return doc, fmt.Errorf("the report is format %d, which this backport-batch does not read", doc.Format)
|
||||
}
|
||||
if !reportIDRE.MatchString(doc.ID) || reportID(doc) != doc.ID {
|
||||
return doc, fmt.Errorf("report %.12s does not match what it says", terminalSafe(doc.ID))
|
||||
}
|
||||
if err := doc.validate(l); err != nil {
|
||||
return doc, fmt.Errorf("report %.12s %w", doc.ID, err)
|
||||
}
|
||||
if err := doc.bindDrops(); err != nil {
|
||||
return doc, fmt.Errorf("report %.12s %w", doc.ID, err)
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// validate holds a report to what a run writes. Its errors read after
|
||||
// "report <id>".
|
||||
func (d *reportDoc) validate(l line) error {
|
||||
if d.Line != l.branch() {
|
||||
return fmt.Errorf("is for %q, not %s", d.Line, l.branch())
|
||||
}
|
||||
if err := d.Built.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, sha := range d.Other {
|
||||
if checkSHA(sha) != nil {
|
||||
return fmt.Errorf("counts %q as a commit on main", sha)
|
||||
}
|
||||
}
|
||||
if _, err := d.categories(); err != nil {
|
||||
return err
|
||||
}
|
||||
// The deferred and dropped entries are the record's, held to the
|
||||
// record's rules.
|
||||
kept := lineRecord{Version: 1, Line: d.Line, Deferred: d.Primary.Deferred, Dropped: d.Overlays.Dropped}
|
||||
if err := kept.validate(l); err != nil {
|
||||
return err
|
||||
}
|
||||
for n, lines := range d.Diag {
|
||||
if k, err := strconv.Atoi(n); err != nil || k <= 0 || strconv.Itoa(k) != n {
|
||||
return fmt.Errorf("has diagnostics for %q, which is no original", n)
|
||||
}
|
||||
for _, ln := range lines {
|
||||
if ln != oneLineText(ln) {
|
||||
return fmt.Errorf("has a diagnostic for #%s that is not one clean line: %q", n, ln)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, p := range d.Primary.Parked {
|
||||
if p.Original <= 0 {
|
||||
return fmt.Errorf("names original %d", p.Original)
|
||||
}
|
||||
if err := p.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
// Whether notify named it is the record's to say, not the
|
||||
// classification's.
|
||||
if p.Announced {
|
||||
return fmt.Errorf("has #%d announced", p.Original)
|
||||
}
|
||||
}
|
||||
for _, list := range [][]int{d.Overrides.Include, d.Overrides.Skip, d.Overlays.Stale, d.Overlays.Changed, d.Overlays.Partial} {
|
||||
for _, n := range list {
|
||||
if n <= 0 {
|
||||
return fmt.Errorf("names original %d", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
return d.links()
|
||||
}
|
||||
|
||||
// links holds the fields of a report that speak of one another to agree as
|
||||
// a run writes them, so no field says something another contradicts. Its
|
||||
// errors read after "report <id>".
|
||||
func (d *reportDoc) links() error {
|
||||
where, err := d.categories()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Format 1 was written before anything was parked.
|
||||
if d.Format == 1 && len(d.Primary.Parked)+len(d.Overlays.Partial) > 0 {
|
||||
return errors.New("parks originals, which format 1 does not")
|
||||
}
|
||||
// What a dependency park needs never reaches the line: it is excluded
|
||||
// by a rule, a label, a drop or a park of its own, or a commit on main
|
||||
// that merged no pull request.
|
||||
other := map[string]bool{}
|
||||
for _, sha := range d.Other {
|
||||
other[sha] = true
|
||||
}
|
||||
for _, p := range d.Primary.Parked {
|
||||
for _, n := range p.Needs {
|
||||
switch c := where[n]; c {
|
||||
case "parked", "skipped.before-start", "skipped.type", "skipped.breaking", "skipped.touches", "skipped.skip-label", "skipped.dropped":
|
||||
default:
|
||||
return fmt.Errorf("parks #%d for #%d, which it has %s", p.Original, n, or(c, "nowhere"))
|
||||
}
|
||||
}
|
||||
if other[p.Merge] || slices.Contains(p.Commits, p.Merge) {
|
||||
return fmt.Errorf("parks #%d by a merge it counts as no pull request's, or for its own merge", p.Original)
|
||||
}
|
||||
for _, c := range p.Commits {
|
||||
if !other[c] {
|
||||
return fmt.Errorf("parks #%d for %.12s, which it does not count among main's commits that merged no pull request", p.Original, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
// A partial unit is still on the batch.
|
||||
stale := map[int]bool{}
|
||||
for _, n := range d.Overlays.Stale {
|
||||
stale[n] = true
|
||||
}
|
||||
for _, n := range d.Overlays.Partial {
|
||||
if !stale[n] {
|
||||
return fmt.Errorf("marks #%d partial on the batch, but not still on it", n)
|
||||
}
|
||||
}
|
||||
drops := map[int]bool{}
|
||||
for _, e := range d.Overlays.Dropped {
|
||||
drops[e.Original] = true
|
||||
}
|
||||
for _, n := range d.Primary.Skipped.Dropped {
|
||||
if !drops[n] {
|
||||
return fmt.Errorf("has #%d dropped, but keeps no drop of it", n)
|
||||
}
|
||||
}
|
||||
// Stale marks something a run took or excluded, and changed a pick.
|
||||
for _, n := range d.Overlays.Stale {
|
||||
if c := where[n]; c != "picked" && !strings.HasPrefix(c, "skipped.") {
|
||||
return fmt.Errorf("marks #%d stale, which it has %s", n, or(c, "nowhere"))
|
||||
}
|
||||
}
|
||||
for _, n := range d.Overlays.Changed {
|
||||
if c := where[n]; c != "picked" {
|
||||
return fmt.Errorf("marks #%d changed, which it has %s", n, or(c, "nowhere"))
|
||||
}
|
||||
}
|
||||
// backport/skip decides before any rule, and backport/include lifts
|
||||
// rules 1 to 4.
|
||||
skip := map[int]bool{}
|
||||
for _, n := range d.Overrides.Skip {
|
||||
skip[n] = true
|
||||
if where[n] != "skipped.skip-label" {
|
||||
return fmt.Errorf("has #%d labelled %s, which it has %s", n, labelSkip, or(where[n], "nowhere"))
|
||||
}
|
||||
}
|
||||
for _, n := range d.Primary.Skipped.SkipLabel {
|
||||
if !skip[n] {
|
||||
return fmt.Errorf("has #%d skipped for a %s label it does not list", n, labelSkip)
|
||||
}
|
||||
}
|
||||
for _, n := range d.Overrides.Include {
|
||||
switch c := where[n]; c {
|
||||
case "", "skipped.before-start", "skipped.type", "skipped.breaking", "skipped.touches", "skipped.skip-label":
|
||||
return fmt.Errorf("has #%d labelled %s, which it has %s", n, labelInclude, or(c, "nowhere"))
|
||||
}
|
||||
}
|
||||
for n := range d.Diag {
|
||||
if k, err := strconv.Atoi(n); err != nil || where[k] == "" {
|
||||
return fmt.Errorf("has diagnostics for %q, which it puts nowhere", n)
|
||||
}
|
||||
}
|
||||
for _, e := range d.Primary.Deferred {
|
||||
if e.Workflows && !d.Built.Options.NoWorkflowFiles {
|
||||
return fmt.Errorf("has #%d waiting for its workflow files, but was made bringing them over", e.Original)
|
||||
}
|
||||
// What a wait waits on is still to come: not on the line, deferred,
|
||||
// or held by rule 6.
|
||||
for _, n := range e.Needs {
|
||||
switch c := where[n]; c {
|
||||
case "missing", "deferred", "skipped.newer":
|
||||
default:
|
||||
return fmt.Errorf("has #%d wait on #%d, which it has %s", e.Original, n, or(c, "nowhere"))
|
||||
}
|
||||
}
|
||||
if d.Format == 1 && len(e.Needs) > 0 {
|
||||
return fmt.Errorf("has #%d wait on other originals, which format 1 does not", e.Original)
|
||||
}
|
||||
}
|
||||
needs := map[int][]int{}
|
||||
for _, e := range d.Primary.Deferred {
|
||||
needs[e.Original] = e.Needs
|
||||
}
|
||||
for _, p := range d.Primary.Parked {
|
||||
needs[p.Original] = p.Needs
|
||||
}
|
||||
if err := waitCycle(needs); err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Built.Options.Mode == modeClose && len(d.Primary.Picked)+len(d.Overlays.Stale) > 0 {
|
||||
return errors.New("closes the batch, but still has originals on it")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// bodyReport is the report a batch body against l carries, or nil.
|
||||
func bodyReport(body string, l line) (*storedReport, error) {
|
||||
blocks, err := fencedLines(body, reportFence)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, err
|
||||
case len(blocks) == 0:
|
||||
return nil, nil
|
||||
case len(blocks) > 1:
|
||||
return nil, fmt.Errorf("the body holds %d %s blocks", len(blocks), reportFence)
|
||||
}
|
||||
doc, err := parseReport(blocks[0], l)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storedReport{doc: doc, raw: blocks[0]}, nil
|
||||
}
|
||||
|
||||
// reportComment is the comment that keeps a report: a marker naming it, and
|
||||
// the report folded away in the same block the body carries. Nothing in it
|
||||
// mentions anyone: numbers are bare, and text sits inside the fence.
|
||||
//
|
||||
// Only checked values reach the summary GitHub renders: an ID of hex digits,
|
||||
// a release line and the date of a time that parses.
|
||||
func reportComment(s storedReport) (string, error) {
|
||||
if !reportIDRE.MatchString(s.doc.ID) {
|
||||
return "", fmt.Errorf("report %q has no ID", s.doc.ID)
|
||||
}
|
||||
if _, err := parseLine(s.doc.Line); err != nil {
|
||||
return "", fmt.Errorf("report %.12s: %w", s.doc.ID, err)
|
||||
}
|
||||
at, err := time.Parse(time.RFC3339, s.doc.Built.At)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("report %.12s was made at %q", s.doc.ID, s.doc.Built.At)
|
||||
}
|
||||
date := at.UTC().Format(time.DateOnly)
|
||||
c := reportMarker + s.doc.ID + " -->\n" +
|
||||
"<details><summary>Backport batch report for " + s.doc.Line + ", " + date + " (" + s.doc.ID[:12] + ")</summary>\n\n" +
|
||||
reportBlock(s.raw) + "\n</details>\n"
|
||||
if len(c) > reportLimit {
|
||||
return "", fmt.Errorf("the report comment is %d bytes, over the %d it may have", len(c), reportLimit)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
var reportMarkerRE = regexp.MustCompile(`^` + regexp.QuoteMeta(reportMarker) + `([0-9a-f]{64}) -->\n`)
|
||||
|
||||
// findReports reads the report comments on batch pull request n, against l,
|
||||
// by authors the batch trusts, as it trusts a record's author, by ID. One
|
||||
// whose content does not match the ID its marker gives, or is not what a run
|
||||
// writes, is returned apart, with why; a look-alike by anyone else is not
|
||||
// read, whatever it says.
|
||||
func findReports(gh github, n int, l line) (map[string]storedReport, map[string]string, error) {
|
||||
comments, err := gh.comments(n)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
found, bad := map[string]storedReport{}, map[string]string{}
|
||||
for _, c := range comments {
|
||||
if !strings.HasPrefix(c.Body, reportMarker) {
|
||||
continue
|
||||
}
|
||||
why, err := trustedAuthor(gh, c.User.Login, c.User.Type)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if why != "" {
|
||||
continue
|
||||
}
|
||||
m := reportMarkerRE.FindStringSubmatch(c.Body)
|
||||
if m == nil {
|
||||
bad[strconv.FormatInt(c.ID, 10)] = fmt.Sprintf("comment %d starts like a report but names none", c.ID)
|
||||
continue
|
||||
}
|
||||
blocks, err := fencedLines(c.Body, reportFence)
|
||||
if err == nil && len(blocks) != 1 {
|
||||
err = fmt.Errorf("it holds %d reports", len(blocks))
|
||||
}
|
||||
var doc reportDoc
|
||||
if err == nil {
|
||||
doc, err = parseReport(blocks[0], l)
|
||||
}
|
||||
if err == nil && doc.ID != m[1] {
|
||||
err = fmt.Errorf("its marker names %.12s", m[1])
|
||||
}
|
||||
if err != nil {
|
||||
bad[m[1]] = fmt.Sprintf("comment %d: %v", c.ID, err)
|
||||
continue
|
||||
}
|
||||
found[m[1]] = storedReport{doc: doc, raw: blocks[0]}
|
||||
}
|
||||
return found, bad, nil
|
||||
}
|
||||
|
||||
// toolVersion is the commit this binary was built from, with +dirty when its
|
||||
// tree had changes, or "" when the build did not record it, as go run does
|
||||
// not.
|
||||
func toolVersion() string {
|
||||
info, ok := debug.ReadBuildInfo()
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
rev, dirty := "", false
|
||||
for _, s := range info.Settings {
|
||||
switch s.Key {
|
||||
case "vcs.revision":
|
||||
rev = s.Value
|
||||
case "vcs.modified":
|
||||
dirty = s.Value == "true"
|
||||
}
|
||||
}
|
||||
if checkSHA(rev) != nil {
|
||||
return ""
|
||||
}
|
||||
if dirty {
|
||||
rev += "+dirty"
|
||||
}
|
||||
return rev
|
||||
}
|
||||
|
||||
// runURL is the Actions run the command runs in, from the variables GitHub
|
||||
// sets for it, or "" outside one.
|
||||
func runURL(lookup func(string) (string, bool)) string {
|
||||
get := func(key string) string { v, _ := lookup(key); return v }
|
||||
url := get("GITHUB_SERVER_URL") + "/" + get("GITHUB_REPOSITORY") + "/actions/runs/" + get("GITHUB_RUN_ID")
|
||||
if attempt := get("GITHUB_RUN_ATTEMPT"); attempt != "" && attempt != "1" {
|
||||
url += "/attempts/" + attempt
|
||||
}
|
||||
if !runURLRE.MatchString(url) {
|
||||
return ""
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
// report prints a report a batch pull request keeps, writing nothing, so it
|
||||
// works on merged and closed batches too. It reads GitHub, and for a report
|
||||
// that keeps drops also this clone's history at the heads the report was
|
||||
// made from, which it never fetches.
|
||||
func (a *app) report(args []string) int {
|
||||
fs := a.flags("report")
|
||||
number := fs.Int("pr", 0, "the batch pull request")
|
||||
id := fs.String("id", "", "the report, by its ID (default: the one the body carries)")
|
||||
asJSON := fs.Bool("json", false, "print the report's JSON")
|
||||
if err := parse(fs, args); err != nil {
|
||||
return 2
|
||||
}
|
||||
if *number <= 0 {
|
||||
return a.fail(fmt.Errorf("--pr %d is not a pull request number", *number))
|
||||
}
|
||||
if *id != "" && !reportIDRE.MatchString(*id) {
|
||||
return a.fail(fmt.Errorf("--id %q is not a report ID", *id))
|
||||
}
|
||||
pr, err := a.gh.pull(*number)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
l, err := parseLine(pr.Base.Ref)
|
||||
if m := batchBranchRE.FindStringSubmatch(pr.Head.Ref); err != nil || m == nil || m[1] != l.branch() || pr.Head.Repo == nil || pr.Head.Repo.FullName != pr.Base.Repo.FullName {
|
||||
return a.fail(fmt.Errorf("#%d is not a batch pull request of this repository", pr.Number))
|
||||
}
|
||||
why, err := trusted(a.gh, pr)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if why != "" {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d was %s, so what it says is not the batch's", pr.Number, why))
|
||||
}
|
||||
inBody, err := bodyReport(pr.Body, l)
|
||||
if err != nil {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d: %w", pr.Number, err))
|
||||
}
|
||||
if *id == "" {
|
||||
if inBody == nil {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d carries no report in its body; name one with --id", pr.Number))
|
||||
}
|
||||
*id = inBody.doc.ID
|
||||
}
|
||||
posted, bad, err := findReports(a.gh, pr.Number, l)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if why := bad[*id]; why != "" {
|
||||
return a.fail(fmt.Errorf("batch pull request #%d: the report %.12s is not what its comment says: %s", pr.Number, *id, why))
|
||||
}
|
||||
s, inComment := posted[*id]
|
||||
switch {
|
||||
case inComment:
|
||||
case inBody != nil && inBody.doc.ID == *id:
|
||||
s = *inBody
|
||||
default:
|
||||
return a.fail(fmt.Errorf("batch pull request #%d keeps no report %.12s", pr.Number, *id))
|
||||
}
|
||||
if *asJSON {
|
||||
fmt.Fprintln(a.stdout, s.raw)
|
||||
return 0
|
||||
}
|
||||
a.printReport(&pr, s, inBody, inComment)
|
||||
return 0
|
||||
}
|
||||
|
||||
// printReport prints a report. It was checked when it was read, and every
|
||||
// field still goes through terminalSafe, so nothing it carries spans lines
|
||||
// or drives a terminal.
|
||||
func (a *app) printReport(pr *pullRequest, s storedReport, inBody *storedReport, inComment bool) {
|
||||
d, b := s.doc, s.doc.Built
|
||||
safe := terminalSafe
|
||||
fmt.Fprintf(a.stdout, "report %s for %s, made %s by a %s run", safe(d.ID), safe(d.Line), safe(b.At), safe(b.Options.Mode))
|
||||
if b.Options.NoWorkflowFiles {
|
||||
fmt.Fprint(a.stdout, " with --no-workflow-files")
|
||||
}
|
||||
fmt.Fprintln(a.stdout)
|
||||
fmt.Fprintf(a.stdout, " main %s, line %s, newer line %s, policy %s\n batch %s, tool %s, run %s\n", safe(b.Main), safe(b.Line), safe(or(b.Newer, "none")), safe(b.Policy), safe(b.Batch), safe(or(b.Tool, "unknown")), safe(or(b.Run, "none")))
|
||||
current := "none"
|
||||
if inBody != nil {
|
||||
current = safe(inBody.doc.ID)
|
||||
}
|
||||
switch {
|
||||
case inBody != nil && inBody.doc.ID == d.ID:
|
||||
fmt.Fprintf(a.stdout, " #%d's body carries this report\n", pr.Number)
|
||||
case pr.Head.SHA == b.Batch:
|
||||
fmt.Fprintf(a.stdout, " #%d's head is %.12s, the batch this report describes, but its body carries report %.12s\n", pr.Number, safe(b.Batch), current)
|
||||
default:
|
||||
fmt.Fprintf(a.stdout, " publication unconfirmed: #%d's head is %.12s, not %.12s, and its body carries report %.12s\n", pr.Number, safe(pr.Head.SHA), safe(b.Batch), current)
|
||||
}
|
||||
if !inComment {
|
||||
if prState(pr) == "open" {
|
||||
fmt.Fprintln(a.stdout, " comment not posted; the next backport-batch run --push posts it")
|
||||
} else {
|
||||
fmt.Fprintf(a.stdout, " comment not posted; kept in the body only, since nothing is written to a %s pull request\n", prState(pr))
|
||||
}
|
||||
}
|
||||
type line struct {
|
||||
n int
|
||||
text string
|
||||
}
|
||||
var lines []line
|
||||
for _, n := range d.Primary.Picked {
|
||||
lines = append(lines, line{n, "picked"})
|
||||
}
|
||||
for _, n := range d.Primary.Missing {
|
||||
lines = append(lines, line{n, "missing"})
|
||||
}
|
||||
for _, e := range d.Primary.Deferred {
|
||||
text := "deferred: "
|
||||
switch {
|
||||
case e.Workflows:
|
||||
text += "waits for a maintainer, changes " + strings.Join(e.Files, ", ")
|
||||
case len(e.Needs) > 0:
|
||||
var needs []string
|
||||
for _, n := range e.Needs {
|
||||
needs = append(needs, "#"+strconv.Itoa(n))
|
||||
}
|
||||
text += "waits on " + strings.Join(needs, ", ")
|
||||
case e.Reason != "":
|
||||
text += e.Reason
|
||||
default:
|
||||
text += fmt.Sprintf("conflict at %.12s in %s", e.Commit, strings.Join(e.Files, ", "))
|
||||
}
|
||||
if e.More > 0 {
|
||||
text += fmt.Sprintf(" and %d more", e.More)
|
||||
}
|
||||
lines = append(lines, line{e.Original, text})
|
||||
}
|
||||
for _, e := range d.Primary.Parked {
|
||||
text := "parked: "
|
||||
switch {
|
||||
case e.Kind == parkPartial:
|
||||
text += "only part of it applies, it would leave " + strings.Join(e.Files, ", ") + " without effect"
|
||||
default:
|
||||
var needs []string
|
||||
for _, n := range e.Needs {
|
||||
needs = append(needs, "#"+strconv.Itoa(n))
|
||||
}
|
||||
for _, c := range e.Commits {
|
||||
needs = append(needs, c[:12])
|
||||
}
|
||||
text += "builds on " + strings.Join(needs, ", ") + ", which never reaches the line"
|
||||
}
|
||||
lines = append(lines, line{e.Original, text})
|
||||
}
|
||||
for _, l := range d.Primary.Skipped.lists() {
|
||||
for _, n := range *l.list {
|
||||
lines = append(lines, line{n, "skipped." + l.name})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(lines, func(x, y line) int { return cmp.Compare(x.n, y.n) })
|
||||
for _, l := range lines {
|
||||
fmt.Fprintf(a.stdout, "#%d %s\n", l.n, terminalSafe(l.text))
|
||||
}
|
||||
overlay := func(name string, list []int) {
|
||||
if len(list) > 0 {
|
||||
fmt.Fprintf(a.stdout, "%s: %s\n", name, strings.Trim(fmt.Sprint(list), "[]"))
|
||||
}
|
||||
}
|
||||
overlay("stale, still on the batch", d.Overlays.Stale)
|
||||
overlay("only part of it applies, still on the batch", d.Overlays.Partial)
|
||||
for _, e := range d.Overlays.Dropped {
|
||||
fmt.Fprintf(a.stdout, "dropped: #%d, merged as %.12s, on #%d: %s\n", e.Original, terminalSafe(e.Merge), e.On, terminalSafe(e.Reason))
|
||||
}
|
||||
overlay("changed in the pick", d.Overlays.Changed)
|
||||
for _, n := range slices.Sorted(maps.Keys(d.Diag)) {
|
||||
for _, ln := range d.Diag[n] {
|
||||
fmt.Fprintf(a.stdout, "#%s: %s\n", terminalSafe(n), terminalSafe(ln))
|
||||
}
|
||||
}
|
||||
if len(d.Other) > 0 {
|
||||
other := make([]string, len(d.Other))
|
||||
for i, sha := range d.Other {
|
||||
other[i] = safe(sha)
|
||||
}
|
||||
fmt.Fprintf(a.stdout, "commits on main that merged no pull request: %s\n", strings.Join(other, ", "))
|
||||
}
|
||||
}
|
||||
|
||||
func or(s, otherwise string) string {
|
||||
if s == "" {
|
||||
return otherwise
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// postReport writes a report comment on pull request n, after GitHub says
|
||||
// it is still open: nothing is written to a merged or closed one.
|
||||
func (a *app) postReport(n int, s storedReport) error {
|
||||
if err := a.stillOpen(n); err != nil {
|
||||
return err
|
||||
}
|
||||
c, err := reportComment(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name, err := writeTemp("backport-batch-report-*.md", c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(name)
|
||||
return a.gh.createComment(n, name)
|
||||
}
|
||||
|
||||
// stillOpen reads pull request n again and refuses to go on unless it is
|
||||
// open.
|
||||
func (a *app) stillOpen(n int) error {
|
||||
pr, err := a.gh.pull(n)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if st := prState(&pr); st != "open" {
|
||||
return fmt.Errorf("batch pull request #%d is %s now; nothing is written to it", n, st)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeTemp(pattern, content string) (string, error) {
|
||||
f, err := os.CreateTemp("", pattern)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := f.WriteString(content); err != nil {
|
||||
f.Close()
|
||||
os.Remove(f.Name())
|
||||
return "", err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
os.Remove(f.Name())
|
||||
return "", err
|
||||
}
|
||||
return f.Name(), nil
|
||||
}
|
||||
@@ -0,0 +1,778 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// reportsPosted lists the report IDs the comments carry, in the order they
|
||||
// were posted, whoever wrote them.
|
||||
func reportsPosted(gh *fakeGH) []string {
|
||||
var ids []string
|
||||
for _, c := range gh.issueComments {
|
||||
if m := reportMarkerRE.FindStringSubmatch(c.Body); m != nil {
|
||||
ids = append(ids, m[1])
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// bodyReportOf is the report a body on release-1.1, or on the line given,
|
||||
// carries, failing the test without one.
|
||||
func bodyReportOf(t *testing.T, body string, on ...line) storedReport {
|
||||
t.Helper()
|
||||
l := notifyLine
|
||||
if len(on) > 0 {
|
||||
l = on[0]
|
||||
}
|
||||
s, err := bodyReport(body, l)
|
||||
if err != nil || s == nil {
|
||||
t.Fatalf("the body carries no readable report: %v\n%s", err, body)
|
||||
}
|
||||
return *s
|
||||
}
|
||||
|
||||
// refusePushes makes the remote refuse every push, as a lost connection or
|
||||
// a protected branch would, until it is called with false.
|
||||
func (f *fixture) refusePushes(on bool) {
|
||||
f.t.Helper()
|
||||
hook := filepath.Join(f.remote, "hooks", "pre-receive")
|
||||
if !on {
|
||||
if err := os.Remove(hook); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(hook, []byte("#!/bin/sh\necho refused >&2\nexit 1\n"), 0o755); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustRun(t *testing.T, f *fixture, gh *fakeGH, args ...string) string {
|
||||
t.Helper()
|
||||
code, stdout, stderr := f.exec(gh, args...)
|
||||
if code != 0 {
|
||||
t.Fatalf("%q = %d\n%s", args, code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
return stdout
|
||||
}
|
||||
|
||||
// A report comment keeps each classification: one the next run replaced in
|
||||
// the body is still read back by its ID, also once the batch merged, which
|
||||
// nothing writes to.
|
||||
func TestReportSurvivesContinuation(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): a line-only five", map[string]string{"app/five.txt": "line\n"})
|
||||
mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
r1 := bodyReportOf(t, gh.prs[0].Body).doc.ID
|
||||
f.onLine("release-1.1", "fix(app): five, by hand\n\n(cherry picked from commit "+mc5+")", map[string]string{"app/five.txt": "5\n"})
|
||||
f.now = f.now.AddDate(0, 0, 1)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
r2 := bodyReportOf(t, gh.find(90).Body).doc.ID
|
||||
if r1 == r2 || !slices.Equal(reportsPosted(gh), []string{r1, r2}) {
|
||||
t.Fatalf("reports %q; want R1 %.12s, then R2 %.12s", reportsPosted(gh), r1, r2)
|
||||
}
|
||||
read := func(id, want string) {
|
||||
t.Helper()
|
||||
code, stdout, stderr := f.exec(gh, "report", "--pr", "90", "--id", id)
|
||||
if code != 0 || !strings.Contains(stdout, want) {
|
||||
t.Errorf("report --id %.12s = %d, want %q:\n%s%s", id, code, want, stdout, stderr)
|
||||
}
|
||||
}
|
||||
for _, merged := range []bool{false, true} {
|
||||
if merged {
|
||||
mergeBatch(f, gh)
|
||||
}
|
||||
read(r1, "#5 deferred: conflict at ")
|
||||
read(r2, "#5 skipped.on-line")
|
||||
read(r2, "#6 picked")
|
||||
}
|
||||
}
|
||||
|
||||
// Two runs that find the same post one report, and the body carries the one
|
||||
// kept, whatever time and job the second ran in. A look-alike someone else
|
||||
// wrote is no report, and a kept report edited since stops the reader.
|
||||
func TestReportDedupAndTrust(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
t.Setenv("GITHUB_SERVER_URL", "https://github.com")
|
||||
t.Setenv("GITHUB_REPOSITORY", "cozystack/cozystack")
|
||||
t.Setenv("GITHUB_RUN_ID", "100")
|
||||
t.Setenv("GITHUB_RUN_ATTEMPT", "1")
|
||||
|
||||
// The report the next run makes, read off a run that publishes nothing,
|
||||
// planted by someone the batch does not trust.
|
||||
preview := bodyReportOf(t, mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue"))
|
||||
planted, err := reportComment(preview)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
look := issueComment{ID: 7, Body: planted}
|
||||
look.User.Login, look.User.Type = "someone", "User"
|
||||
gh.issueComments = append(gh.issueComments, look)
|
||||
|
||||
f.now = f.now.AddDate(0, 0, 1)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
kept := bodyReportOf(t, gh.find(90).Body)
|
||||
if kept.doc.ID != preview.doc.ID {
|
||||
t.Fatalf("the run made %.12s, the preview %.12s", kept.doc.ID, preview.doc.ID)
|
||||
}
|
||||
f.now = f.now.AddDate(0, 0, 1)
|
||||
t.Setenv("GITHUB_RUN_ID", "101")
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
posted := reportsPosted(gh)
|
||||
if n := len(slices.DeleteFunc(slices.Clone(posted), func(id string) bool { return id != kept.doc.ID })); n != 2 || len(posted) != 3 {
|
||||
t.Errorf("reports %q; want the first, the look-alike and the run's own once", posted)
|
||||
}
|
||||
body := gh.find(90).Body
|
||||
again := bodyReportOf(t, body)
|
||||
rec, err := parseRecord(body, notifyLine)
|
||||
if err != nil || again.raw != kept.raw || rec.Report != again.doc.ID || !strings.Contains(again.raw, `"run":"https://github.com/cozystack/cozystack/actions/runs/100"`) {
|
||||
t.Errorf("the second run's body carries %s with record report %v (%v); want the kept bytes of run 100", again.raw, rec, err)
|
||||
}
|
||||
|
||||
// The reader takes the run's own comment, not the look-alike.
|
||||
if code, stdout, stderr := f.exec(gh, "report", "--pr", "90", "--id", kept.doc.ID); code != 0 || !strings.Contains(stdout, "#6 picked") {
|
||||
t.Errorf("report = %d:\n%s%s", code, stdout, stderr)
|
||||
}
|
||||
for i := range gh.issueComments {
|
||||
c := &gh.issueComments[i]
|
||||
if c.User.Login == "maintainer" && strings.Contains(c.Body, kept.doc.ID) {
|
||||
c.Body = strings.Replace(c.Body, `"picked":[5,6]`, `"picked":[5]`, 1)
|
||||
}
|
||||
}
|
||||
if code, stdout, stderr := f.exec(gh, "report", "--pr", "90", "--id", kept.doc.ID); code != 2 || !strings.Contains(stderr, "does not match") {
|
||||
t.Errorf("report of an edited comment = %d, want 2:\n%s%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// The report holds no pull request number, so a new batch's report is whole
|
||||
// before GitHub numbers the pull request, and the reader finds it on
|
||||
// whatever number it got.
|
||||
func TestFirstReportIDIsKnownBeforeTheNumber(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
gh := &fakeGH{nextPR: 4242}
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--push")
|
||||
inBody := bodyReportOf(t, gh.bodies[0])
|
||||
// Every list is one, empty or not, so equal reports are equal bytes:
|
||||
// main here has no commit that merged no pull request.
|
||||
if !strings.Contains(inBody.raw, `"other":[]`) {
|
||||
t.Errorf("the report writes its empty list of other commits as something else:\n%s", inBody.raw)
|
||||
}
|
||||
if !slices.Equal(gh.commented, []int{4242}) || !slices.Equal(reportsPosted(gh), []string{inBody.doc.ID}) {
|
||||
t.Fatalf("commented on %v with %q, want #4242 with %.12s", gh.commented, reportsPosted(gh), inBody.doc.ID)
|
||||
}
|
||||
found, bad, err := findReports(gh, 4242, notifyLine)
|
||||
if err != nil || len(bad) != 0 || found[inBody.doc.ID].raw != inBody.raw {
|
||||
t.Errorf("findReports = %v, %v, %v; want the body's report", found, bad, err)
|
||||
}
|
||||
if code, stdout, stderr := f.exec(gh, "report", "--pr", "4242"); code != 0 || !strings.Contains(stdout, "report "+inBody.doc.ID) || !strings.Contains(stdout, "#4242's body carries this report") {
|
||||
t.Errorf("report --pr 4242 = %d:\n%s%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// Every original main merged since the line branched is in exactly one
|
||||
// category of the report, a commit that merged no pull request is counted
|
||||
// apart, and the report says so whatever the run had to do.
|
||||
func TestReportPartition(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
gh := &fakeGH{labels: map[string][]int{labelSkip: {9}}}
|
||||
// onNewer puts an original on release-1.1, as the newer line's batch
|
||||
// would, so rule 6 lets it onto release-1.0.
|
||||
onNewer := func(mc string, files map[string]string) {
|
||||
f.onLine("release-1.1", "fix: by the newer batch\n\n(cherry picked from commit "+mc+")", files)
|
||||
}
|
||||
pr := func(n int, title string, files map[string]string, newer bool) {
|
||||
mc := f.pr(n, title, "", files)
|
||||
if newer {
|
||||
onNewer(mc, files)
|
||||
}
|
||||
}
|
||||
t.Setenv("GIT_COMMITTER_DATE", "2026-01-01T00:00:00Z")
|
||||
f.pr(4, "fix(app): four, before the start", "", map[string]string{"app/four.txt": "4\n"})
|
||||
os.Unsetenv("GIT_COMMITTER_DATE")
|
||||
f.setPolicy("release-1.0: 2026-06-01\n")
|
||||
f.onLine("release-1.0", "fix(app): a line-only eleven", map[string]string{"app/eleven.txt": "line\n"})
|
||||
pr(5, "fix(app): five", map[string]string{"app/five.txt": "5\n"}, true)
|
||||
pr(6, "fix(app): six, not on the newer line", map[string]string{"app/six.txt": "6\n"}, false)
|
||||
pr(7, "fix(app)!: seven", map[string]string{"app/seven.txt": "7\n"}, true)
|
||||
pr(8, "fix(platform): eight", map[string]string{migrationsDir + "42": "#!/bin/sh\n"}, true)
|
||||
pr(9, "fix(app): nine", map[string]string{"app/nine.txt": "9\n"}, true)
|
||||
mc10 := f.pr(10, "fix(app): ten", "", map[string]string{"app/ten.txt": "10\n"})
|
||||
onNewer(mc10, map[string]string{"app/ten.txt": "10\n"})
|
||||
f.onLine("release-1.0", "fix(app): ten\n\n(cherry picked from commit "+mc10+")", map[string]string{"app/ten.txt": "10\n"})
|
||||
pr(11, "fix(app): eleven", map[string]string{"app/eleven.txt": "11\n"}, true)
|
||||
pr(12, "fix(ci): twelve", map[string]string{".github/workflows/twelve.yaml": "on: push\n"}, true)
|
||||
pr(13, "fix(app): thirteen", map[string]string{"app/thirteen.txt": "13\n"}, true)
|
||||
f.git("switch", "-q", "main")
|
||||
f.write("app/direct.txt", "pushed\n")
|
||||
f.git("add", "-A")
|
||||
f.git("commit", "-q", "-m", "chore: a direct push")
|
||||
direct := f.git("rev-parse", "HEAD")
|
||||
f.git("push", "-q", "origin", "main")
|
||||
|
||||
stdout := mustRun(t, f, gh, "run", "--line", "release-1.0", "--no-workflow-files", "--push")
|
||||
const branch = "backport-batch/release-1.0-20261026"
|
||||
gh.prs = []pullRequest{f.batchPR(90, "release-1.0", branch, stdout)}
|
||||
pr(14, "fix(app): fourteen, after the batch", map[string]string{"app/fourteen.txt": "14\n"}, true)
|
||||
stdout = mustRun(t, f, gh, "run", "--line", "release-1.0", "--defer", "13", "--reason", "fails the e2e", "--push")
|
||||
// An active drop, of #5, which the batch carries, and one of a feat,
|
||||
// which rule 2 keeps out first.
|
||||
gh.prs = []pullRequest{f.batchPR(90, "release-1.0", branch, stdout)}
|
||||
stdout = mustRun(t, f, gh, "run", "--line", "release-1.0", "--drop", "5,1", "--reason", "not for 1.0", "--push")
|
||||
|
||||
l, _ := parseLine("release-1.0")
|
||||
s := bodyReportOf(t, stdout, l)
|
||||
got, err := s.doc.categories()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[int]string{1: "skipped.type", 4: "skipped.before-start", 5: "skipped.dropped", 6: "skipped.newer", 7: "skipped.breaking",
|
||||
8: "skipped.touches", 9: "skipped.skip-label", 10: "skipped.on-line", 11: "deferred", 12: "deferred", 13: "deferred",
|
||||
14: "missing", 9000: "skipped.type"}
|
||||
for n, category := range want {
|
||||
if got[n] != category {
|
||||
t.Errorf("#%d is %q, want %q", n, got[n], category)
|
||||
}
|
||||
delete(got, n)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Errorf("the report also names %v", got)
|
||||
}
|
||||
if gh.find(90).State != "closed" || !strings.Contains(stdout, `"mode":"close"`) {
|
||||
t.Errorf("dropping the batch's last pick left #90 %s; want it closed", gh.find(90).State)
|
||||
}
|
||||
if !slices.Equal(droppedNumbers(s.doc.Overlays.Dropped), []int{1, 5}) || len(s.doc.Primary.Picked) != 0 {
|
||||
t.Errorf("the report drops %v and picks %v; want #1 and #5 dropped, nothing picked", s.doc.Overlays.Dropped, s.doc.Primary.Picked)
|
||||
}
|
||||
if !slices.Contains(s.doc.Other, direct) {
|
||||
t.Errorf("the report does not count the direct push %.12s: %v", direct, s.doc.Other)
|
||||
}
|
||||
kinds := map[int]string{}
|
||||
for _, e := range s.doc.Primary.Deferred {
|
||||
kinds[e.Original] = fmt.Sprintf("commit=%v reason=%q workflows=%v", e.Commit != "", e.Reason, e.Workflows)
|
||||
}
|
||||
if kinds[11] != `commit=true reason="" workflows=false` || kinds[12] != `commit=false reason="" workflows=true` || kinds[13] != `commit=false reason="fails the e2e" workflows=false` {
|
||||
t.Errorf("the deferred entries are %v", kinds)
|
||||
}
|
||||
}
|
||||
|
||||
// A report too big for a comment is refused before anything is written: no
|
||||
// push, no comment, no edit, and no replay of the earlier report either.
|
||||
func TestReportTooLargeIsRefusedBeforePush(t *testing.T) {
|
||||
f, gh, head := bigWaits(t, 7)
|
||||
code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--no-workflow-files", "--push")
|
||||
if code != 2 || !strings.Contains(stderr, "the report comment is") {
|
||||
t.Errorf("run --push = %d, want a refusal of the report:\n%s", code, stderr)
|
||||
}
|
||||
if f.remoteHead(batchBranch1) != head || len(gh.issueComments) != 0 || len(gh.edited) != 0 {
|
||||
t.Errorf("the refused run moved the batch to %.12s, wrote %d comments and edited %q", f.remoteHead(batchBranch1), len(gh.issueComments), gh.edited)
|
||||
}
|
||||
}
|
||||
|
||||
// bigWaits opens a batch whose report comment failed, so its body keeps a
|
||||
// report no comment does, and then merges n originals that each wait on 50
|
||||
// workflow files with long names, which both the record and the report list
|
||||
// in full.
|
||||
func bigWaits(t *testing.T, n int) (*fixture, *fakeGH, string) {
|
||||
t.Helper()
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
gh := &fakeGH{fail: map[string]error{"createComment": errString("HTTP 502")}}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 2 || len(gh.created) != 1 {
|
||||
t.Fatalf("the first run = %d, want its comment to fail after the pull request opened\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
for i := range n {
|
||||
files := map[string]string{}
|
||||
for j := range filesKept {
|
||||
files[fmt.Sprintf(".github/workflows/%s-%02d-%02d.yaml", strings.Repeat("w", 170), i, j)] = "on: push\n"
|
||||
}
|
||||
f.pr(10+i, fmt.Sprintf("fix(ci): wait %d", i), "", files)
|
||||
}
|
||||
f.now = f.now.AddDate(0, 0, 1)
|
||||
return f, gh, f.remoteHead(batchBranch1)
|
||||
}
|
||||
|
||||
// A failure between any two writes leaves what was written readable, and the
|
||||
// next run, whatever changed meanwhile, replays a report the body kept but no
|
||||
// comment did, byte for byte, and posts nothing twice. A batch closed in
|
||||
// between is never written again.
|
||||
func TestReportReplayAfterEachFailure(t *testing.T) {
|
||||
setup := func(t *testing.T) (*fixture, *fakeGH) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
return f, &fakeGH{}
|
||||
}
|
||||
// change moves a label, main, the clock and the run's flags between
|
||||
// the failure and the retry, so the retry's report is another one.
|
||||
change := func(f *fixture, gh *fakeGH) []string {
|
||||
gh.labels = map[string][]int{labelSkip: {6}}
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
f.now = f.now.AddDate(0, 0, 1)
|
||||
return []string{"run", "--line", "release-1.1", "--continue", "--no-workflow-files", "--push"}
|
||||
}
|
||||
once := func(t *testing.T, gh *fakeGH, ids ...string) {
|
||||
t.Helper()
|
||||
posted := reportsPosted(gh)
|
||||
for _, id := range ids {
|
||||
if n := len(slices.DeleteFunc(slices.Clone(posted), func(p string) bool { return p != id })); n != 1 {
|
||||
t.Errorf("report %.12s is posted %d times: %q", id, n, posted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("a new batch whose pull request was not opened", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
gh.fail = map[string]error{"createPull": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
if len(gh.prs) != 0 || len(gh.issueComments) != 0 || f.remoteHead(batchBranch1) == "" {
|
||||
t.Errorf("after the failure: %d pull requests, %d comments, branch %q; want the branch alone", len(gh.prs), len(gh.issueComments), f.remoteHead(batchBranch1))
|
||||
}
|
||||
mustRun(t, f, gh, change(f, gh)...)
|
||||
if len(gh.prs) != 1 || len(reportsPosted(gh)) != 1 || bodyReportOf(t, gh.prs[0].Body).doc.ID != reportsPosted(gh)[0] {
|
||||
t.Errorf("the retry opened %d pull requests with reports %q", len(gh.prs), reportsPosted(gh))
|
||||
}
|
||||
})
|
||||
t.Run("a new batch whose report comment failed", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
gh.fail = map[string]error{"createComment": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 2 || !strings.Contains(stderr, "the body keeps it") {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
first := bodyReportOf(t, gh.find(90).Body)
|
||||
mustRun(t, f, gh, change(f, gh)...)
|
||||
second := bodyReportOf(t, gh.find(90).Body)
|
||||
want, err := reportComment(first)
|
||||
if err != nil || len(gh.issueComments) != 2 || gh.issueComments[0].Body != want || reportsPosted(gh)[1] != second.doc.ID || first.doc.ID == second.doc.ID {
|
||||
t.Errorf("comments %q; want the first report replayed as it was, then the retry's", reportsPosted(gh))
|
||||
}
|
||||
})
|
||||
t.Run("a continuation whose push failed", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
openBatch(t, f, gh)
|
||||
first := reportsPosted(gh)[0]
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
f.refusePushes(true)
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
f.refusePushes(false)
|
||||
attempted := reportsPosted(gh)[1]
|
||||
if bodyReportOf(t, gh.find(90).Body).doc.ID != first {
|
||||
t.Error("the body moved on although the push failed")
|
||||
}
|
||||
mustRun(t, f, gh, change(f, gh)...)
|
||||
once(t, gh, first, attempted)
|
||||
if len(reportsPosted(gh)) != 3 {
|
||||
t.Errorf("reports %q; want the first, the attempted and the retry's", reportsPosted(gh))
|
||||
}
|
||||
})
|
||||
t.Run("a continuation whose body edit failed", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
openBatch(t, f, gh)
|
||||
first := reportsPosted(gh)[0]
|
||||
before := f.remoteHead(batchBranch1)
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
gh.fail = map[string]error{"editPull": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
attempted := reportsPosted(gh)[1]
|
||||
if f.remoteHead(batchBranch1) == before || bodyReportOf(t, gh.find(90).Body).doc.ID != first {
|
||||
t.Error("the push or the body is not where the failure left them")
|
||||
}
|
||||
mustRun(t, f, gh, change(f, gh)...)
|
||||
once(t, gh, first, attempted)
|
||||
if last := reportsPosted(gh)[len(reportsPosted(gh))-1]; bodyReportOf(t, gh.find(90).Body).doc.ID != last || len(reportsPosted(gh)) != 3 {
|
||||
t.Errorf("reports %q; want the body to carry the retry's, posted last", reportsPosted(gh))
|
||||
}
|
||||
})
|
||||
t.Run("a batch closed while the run writes to it", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
openBatch(t, f, gh)
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
gh.after = map[string]func(){"createComment": func() { gh.find(90).State = "closed" }}
|
||||
code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if code != 2 || !strings.Contains(stderr, "batch pull request #90 is closed now; nothing is written to it") || len(gh.edited) != 0 {
|
||||
t.Errorf("run = %d, edited %q; want 2 and no edit of the closed pull request:\n%s", code, gh.edited, stderr)
|
||||
}
|
||||
})
|
||||
t.Run("a batch closed before its report was posted", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
gh.fail = map[string]error{"createComment": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
kept := bodyReportOf(t, gh.find(90).Body)
|
||||
gh.find(90).State = "closed"
|
||||
gh.nextPR = 91
|
||||
mustRun(t, f, gh, change(f, gh)...)
|
||||
if slices.Contains(gh.commented, 90) || slices.Contains(reportsPosted(gh), kept.doc.ID) {
|
||||
t.Errorf("commented on %v, posting %q; want nothing on the closed #90", gh.commented, reportsPosted(gh))
|
||||
}
|
||||
code, stdout, stderr := f.exec(gh, "report", "--pr", "90")
|
||||
if code != 0 || !strings.Contains(stdout, "report "+kept.doc.ID) || !strings.Contains(stdout, "kept in the body only") {
|
||||
t.Errorf("report --pr 90 = %d:\n%s%s", code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
// Every comment is posted only after GitHub says the batch is still
|
||||
// open, the replay's included, so a close between the two stops the
|
||||
// second.
|
||||
t.Run("a batch closed between the replay and the new report", func(t *testing.T) {
|
||||
f, gh := setup(t)
|
||||
gh.fail = map[string]error{"createComment": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
kept := bodyReportOf(t, gh.find(90).Body)
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
gh.after = map[string]func(){"createComment": func() { gh.find(90).State = "closed" }}
|
||||
code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push")
|
||||
if code != 2 || !strings.Contains(stderr, "batch pull request #90 is closed now; nothing is written to it") || !slices.Equal(reportsPosted(gh), []string{kept.doc.ID}) || len(gh.edited) != 0 {
|
||||
t.Errorf("run = %d, posted %q, edited %q; want 2 after the replay alone:\n%s", code, reportsPosted(gh), gh.edited, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The reader says how a report stands against the pull request as GitHub
|
||||
// shows it now, and claims publication only when the head or the body shows
|
||||
// it: a failed push, a push whose answer was lost, a body that was not
|
||||
// updated and a rebuild since all read as they are.
|
||||
func TestReportPublicationStatus(t *testing.T) {
|
||||
setup := func(t *testing.T) (*fixture, *fakeGH, string) {
|
||||
f := newFixture(t)
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "5\n"})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
return f, gh, reportsPosted(gh)[0]
|
||||
}
|
||||
status := func(t *testing.T, f *fixture, gh *fakeGH, id, want string) {
|
||||
t.Helper()
|
||||
code, stdout, stderr := f.exec(gh, "report", "--pr", "90", "--id", id)
|
||||
if code != 0 || !strings.Contains(stdout, want) {
|
||||
t.Errorf("report --id %.12s = %d, want %q:\n%s%s", id, code, want, stdout, stderr)
|
||||
}
|
||||
}
|
||||
t.Run("a push the remote refused, and one it took whose answer was lost", func(t *testing.T) {
|
||||
f, gh, first := setup(t)
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
f.refusePushes(true)
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.refusePushes(false)
|
||||
attempted := reportsPosted(gh)[1]
|
||||
status(t, f, gh, attempted, "publication unconfirmed: #90's head is ")
|
||||
status(t, f, gh, attempted, "its body carries report "+first[:12])
|
||||
// The same head reaching the remote is what a push GitHub took looks
|
||||
// like when its answer never came back.
|
||||
f.git("push", "-q", "origin", "HEAD:refs/heads/"+batchBranch1)
|
||||
f.git("switch", "-q", "main")
|
||||
status(t, f, gh, attempted, "the batch this report describes, but its body carries report "+first[:12])
|
||||
})
|
||||
t.Run("a push followed by a failed body edit", func(t *testing.T) {
|
||||
f, gh, first := setup(t)
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/seven.txt": "7\n"})
|
||||
gh.fail = map[string]error{"editPull": errString("HTTP 502")}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--continue", "--push"); code != 2 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
status(t, f, gh, reportsPosted(gh)[1], "the batch this report describes, but its body carries report "+first[:12])
|
||||
status(t, f, gh, first, "#90's body carries this report")
|
||||
})
|
||||
t.Run("a rebuild since", func(t *testing.T) {
|
||||
f, gh, first := setup(t)
|
||||
mustRun(t, f, gh, "run", "--line", "release-1.1", "--defer", "6", "--reason", "x", "--push")
|
||||
second := reportsPosted(gh)[1]
|
||||
status(t, f, gh, first, "publication unconfirmed: #90's head is ")
|
||||
status(t, f, gh, second, "#90's body carries this report")
|
||||
})
|
||||
}
|
||||
|
||||
// forged is a report on release-1.1 with what change sets, under an ID that
|
||||
// matches it: only checking what it says stands in its way.
|
||||
func forged(change func(d *reportDoc)) storedReport {
|
||||
sha := strings.Repeat("a", 40)
|
||||
d := reportDoc{Format: reportFormat, Line: "release-1.1", Diag: map[string][]string{}, Other: []string{sha},
|
||||
Built: builtFrom{Main: sha, Line: sha, Policy: sha, Batch: sha, At: "2026-10-26T06:00:00Z", Options: runOptions{Mode: modeNew}}}
|
||||
d.Primary.Picked = []int{5}
|
||||
change(&d)
|
||||
d.ID = reportID(d)
|
||||
return storedReport{doc: d, raw: reportJSON(d)}
|
||||
}
|
||||
|
||||
// reportRun runs report with gh faked; it reads nothing but GitHub.
|
||||
func reportRun(gh *fakeGH, args ...string) (int, string, string) {
|
||||
var stdout, stderr strings.Builder
|
||||
a := &app{gh: gh, stdout: &stdout, stderr: &stderr, now: func() time.Time { return time.Date(2026, 10, 26, 6, 0, 0, 0, time.UTC) }}
|
||||
code := a.main(append([]string{"report"}, args...))
|
||||
return code, stdout.String(), stderr.String()
|
||||
}
|
||||
|
||||
// A report is read only when everything it says is what a run writes, and
|
||||
// it is for the line of the pull request it sits on: an ID that matches its
|
||||
// content proves only that nobody changed it since it was hashed.
|
||||
func TestReportRefusesWhatItCannotVouchFor(t *testing.T) {
|
||||
for name, change := range map[string]func(d *reportDoc){
|
||||
"a line that is no release line": func(d *reportDoc) { d.Line = "release-1.1\n\x1b[2Jpicked" },
|
||||
"another line": func(d *reportDoc) { d.Line = "release-1.0" },
|
||||
"a main that is no commit": func(d *reportDoc) { d.Built.Main = "main\n#5 picked" },
|
||||
"a time that is none": func(d *reportDoc) { d.Built.At = "2026-10-26T<b>" },
|
||||
"an unknown operation": func(d *reportDoc) { d.Built.Options.Mode = "new\x1b[2J" },
|
||||
"a run that is no Actions run": func(d *reportDoc) { d.Built.Run = "javascript:alert(1)" },
|
||||
"a tool that is no commit": func(d *reportDoc) { d.Built.Tool = "v1\n" },
|
||||
"a commit on main that is none": func(d *reportDoc) { d.Other = []string{"HEAD\x1b]0;x\x07"} },
|
||||
"a deferred commit that is none": func(d *reportDoc) {
|
||||
d.Primary.Deferred = []deferredEntry{{Original: 6, Commit: "-x", Files: []string{"a"}}}
|
||||
},
|
||||
"an original named twice": func(d *reportDoc) { d.Primary.Missing = []int{5} },
|
||||
"an original that is none": func(d *reportDoc) { d.Primary.Skipped.Type = []int{-1} },
|
||||
"a diagnostic of two lines": func(d *reportDoc) { d.Diag = map[string][]string{"5": {"incomplete\n\x1b[2Jforged"}} },
|
||||
"a diagnostic of no original": func(d *reportDoc) { d.Diag = map[string][]string{"five": {"incomplete"}} },
|
||||
// Fields that speak of one another have to agree.
|
||||
"a drop category with no drop": func(d *reportDoc) { d.Primary.Skipped.Dropped = []int{6} },
|
||||
"a stale original it has missing": func(d *reportDoc) {
|
||||
d.Primary.Missing, d.Overlays.Stale = []int{7}, []int{7}
|
||||
},
|
||||
"a stale original it puts nowhere": func(d *reportDoc) { d.Overlays.Stale = []int{8} },
|
||||
"a changed original it defers": func(d *reportDoc) {
|
||||
d.Primary.Deferred = []deferredEntry{{Original: 9, Files: []string{}, Reason: "fails the e2e"}}
|
||||
d.Overlays.Changed = []int{9}
|
||||
},
|
||||
"a skip label on a picked original": func(d *reportDoc) { d.Overrides.Skip = []int{5} },
|
||||
"a skip-label category with no label": func(d *reportDoc) { d.Primary.Skipped.SkipLabel = []int{10} },
|
||||
"an include label on a rule 2 skip": func(d *reportDoc) {
|
||||
d.Primary.Skipped.Type, d.Overrides.Include = []int{11}, []int{11}
|
||||
},
|
||||
"both labels on one original": func(d *reportDoc) {
|
||||
d.Primary.Skipped.SkipLabel, d.Overrides.Include, d.Overrides.Skip = []int{12}, []int{12}, []int{12}
|
||||
},
|
||||
"a label on no original": func(d *reportDoc) { d.Overrides.Include = []int{13} },
|
||||
"a diagnostic of an original it puts nowhere": func(d *reportDoc) { d.Diag = map[string][]string{"14": {"incomplete"}} },
|
||||
"a workflow wait without the flag": func(d *reportDoc) {
|
||||
d.Primary.Deferred = []deferredEntry{{Original: 15, Files: []string{".github/workflows/ci.yaml"}, Workflows: true}}
|
||||
},
|
||||
"a close that still picks": func(d *reportDoc) { d.Built.Options.Mode = modeClose },
|
||||
"a park with no merge": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Kind: parkPartial, Files: []string{"a"}}}
|
||||
},
|
||||
"a parked original it picks": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 5, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a"}}}
|
||||
},
|
||||
"a park of an unknown kind": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: "later", Files: []string{"a"}}}
|
||||
},
|
||||
"a partial park that needs an original": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a"}, Needs: []int{5}}}
|
||||
},
|
||||
"a partial park of unsorted files": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"b", "a"}}}
|
||||
},
|
||||
"a partial park of a file that drives a terminal": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a\x1b[2J"}}}
|
||||
},
|
||||
"a park announced in the report": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a"}, Announced: true}}
|
||||
},
|
||||
"a park for an original it picks": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{5}}}
|
||||
},
|
||||
"a park that needs itself": func(d *reportDoc) {
|
||||
d.Primary.Skipped.Type = []int{17}
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{16, 17}}}
|
||||
},
|
||||
"a park for a commit that merged a pull request": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Commits: []string{strings.Repeat("c", 40)}}}
|
||||
},
|
||||
"a partial unit not on the batch": func(d *reportDoc) { d.Overlays.Partial = []int{5} },
|
||||
"a wait on an original it picks": func(d *reportDoc) {
|
||||
d.Primary.Deferred = []deferredEntry{{Original: 6, Files: []string{}, Needs: []int{5}}}
|
||||
},
|
||||
"a wait on an original it puts nowhere": func(d *reportDoc) {
|
||||
d.Primary.Deferred = []deferredEntry{{Original: 6, Files: []string{}, Needs: []int{19}}}
|
||||
},
|
||||
"a park on its own merge as a commit": func(d *reportDoc) {
|
||||
d.Other = append(d.Other, strings.Repeat("b", 40))
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Commits: []string{strings.Repeat("b", 40)}}}
|
||||
},
|
||||
"a park cycle": func(d *reportDoc) {
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{18}}, {Original: 18, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{16}}}
|
||||
},
|
||||
"a wait cycle": func(d *reportDoc) {
|
||||
d.Primary.Deferred = []deferredEntry{{Original: 6, Files: []string{}, Needs: []int{7}}, {Original: 7, Files: []string{}, Needs: []int{6}}}
|
||||
},
|
||||
"format 1 with a wait": func(d *reportDoc) {
|
||||
d.Format = 1
|
||||
d.Primary.Missing = []int{19}
|
||||
d.Primary.Deferred = []deferredEntry{{Original: 6, Files: []string{}, Needs: []int{19}}}
|
||||
},
|
||||
"format 1 with a park": func(d *reportDoc) {
|
||||
d.Format = 1
|
||||
d.Primary.Parked = []parkedEntry{{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"a"}}}
|
||||
},
|
||||
} {
|
||||
s := forged(change)
|
||||
c, _ := reportComment(storedReport{doc: forged(func(*reportDoc) {}).doc, raw: s.raw})
|
||||
comment := issueComment{ID: 1, Body: strings.Replace(c, forged(func(*reportDoc) {}).doc.ID, s.doc.ID, 1)}
|
||||
comment.User.Login, comment.User.Type = "maintainer", "User"
|
||||
for where, gh := range map[string]*fakeGH{
|
||||
"in the body": {prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(s.raw)+"\n")}},
|
||||
"in a comment": {prs: []pullRequest{notifyPR("20261026", "text")}, issueComments: []issueComment{comment}},
|
||||
} {
|
||||
if code, stdout, stderr := reportRun(gh, "--pr", "90", "--id", s.doc.ID); code != 2 || stdout != "" {
|
||||
t.Errorf("%s, %s: report = %d, want 2 and nothing printed:\n%s%s", name, where, code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if code, stdout, stderr := reportRun(&fakeGH{prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(forged(func(*reportDoc) {}).raw)+"\n")}}, "--pr", "90"); code != 0 || !strings.Contains(stdout, "#5 picked") {
|
||||
t.Errorf("report of a sound one = %d:\n%s%s", code, stdout, stderr)
|
||||
}
|
||||
// What a run wrote before anything was parked reads as it was written.
|
||||
format1 := forged(func(d *reportDoc) { d.Format, d.Primary.Parked = 1, []parkedEntry{} })
|
||||
if code, stdout, stderr := reportRun(&fakeGH{prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(format1.raw)+"\n")}}, "--pr", "90"); code != 0 || !strings.Contains(stdout, "#5 picked") {
|
||||
t.Errorf("report of a sound format 1 one = %d:\n%s%s", code, stdout, stderr)
|
||||
}
|
||||
parked := forged(func(d *reportDoc) {
|
||||
d.Primary.Skipped.Type = []int{17}
|
||||
d.Other = append(d.Other, strings.Repeat("c", 40))
|
||||
d.Primary.Parked = []parkedEntry{
|
||||
{Original: 16, Merge: strings.Repeat("b", 40), Kind: parkPartial, Files: []string{"chart/templates/policy.yaml"}},
|
||||
{Original: 18, Merge: strings.Repeat("b", 40), Kind: parkDependency, Needs: []int{16, 17}, Commits: []string{strings.Repeat("c", 40)}},
|
||||
}
|
||||
})
|
||||
if code, stdout, stderr := reportRun(&fakeGH{prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(parked.raw)+"\n")}}, "--pr", "90"); code != 0 || !strings.Contains(stdout, "#16 parked: only part of it applies") || !strings.Contains(stdout, "#18 parked: builds on #16, #17, cccccccccccc") {
|
||||
t.Errorf("report of sound parks = %d:\n%s%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// What report prints stays one line per field and carries nothing a
|
||||
// terminal acts on, whatever reached it.
|
||||
func TestReportPrintsNothingThatDrivesATerminal(t *testing.T) {
|
||||
const evil = "\n\x1b[2Jfake: #9 picked\u202e"
|
||||
s := forged(func(d *reportDoc) {
|
||||
d.Line, d.Built.At, d.Built.Options.Mode = "release-1.1"+evil, "2026-10-26"+evil, "new"+evil
|
||||
d.Built.Main, d.Built.Tool, d.Built.Run, d.Built.Newer = "main"+evil, "tool"+evil, "run"+evil, "newer"+evil
|
||||
d.Other = []string{"other" + evil}
|
||||
d.Primary.Deferred = []deferredEntry{{Original: 6, Reason: "why" + evil}}
|
||||
})
|
||||
var stdout strings.Builder
|
||||
a := &app{stdout: &stdout}
|
||||
pr := notifyPR("20261026", "")
|
||||
a.printReport(&pr, s, nil, true)
|
||||
for _, ln := range strings.Split(stdout.String(), "\n") {
|
||||
if strings.HasPrefix(ln, "fake") || strings.ContainsFunc(ln, func(r rune) bool { return r != '\t' && unicode.IsControl(r) || unicode.Is(unicode.Cf, r) }) {
|
||||
t.Errorf("report printed %q", ln)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The comment is made of what was checked: a line, a time and an ID that
|
||||
// carry no markup into the summary GitHub renders.
|
||||
func TestReportCommentIsBuiltFromCheckedFields(t *testing.T) {
|
||||
for name, change := range map[string]func(d *reportDoc){
|
||||
"markup in the line": func(d *reportDoc) { d.Line = "release-1.1</summary><img src=x onerror=alert(1)>" },
|
||||
"markup in the time": func(d *reportDoc) { d.Built.At = "<b>2026-10-26</b>T06:00:00Z" },
|
||||
"a mention": func(d *reportDoc) { d.Line = "release-1.1 @cozystack/maintainers" },
|
||||
} {
|
||||
if c, err := reportComment(forged(change)); err == nil {
|
||||
t.Errorf("%s: reportComment made\n%s", name, c)
|
||||
}
|
||||
}
|
||||
if _, err := reportComment(forged(func(*reportDoc) {})); err != nil {
|
||||
t.Errorf("reportComment of a sound report: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Anyone can comment on a public pull request: the reader takes a report
|
||||
// from a comment only when the batch trusts its author, whatever ID it
|
||||
// carries.
|
||||
func TestReportReaderTakesOnlyTrustedComments(t *testing.T) {
|
||||
s := forged(func(*reportDoc) {})
|
||||
c, err := reportComment(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
login, kind string
|
||||
read bool
|
||||
}{
|
||||
{"someone", "User", false},
|
||||
{"renovate[bot]", "Bot", false},
|
||||
{"github-actions[bot]", "Bot", false},
|
||||
{"maintainer", "User", true},
|
||||
{defaultBatchBot, "Bot", true},
|
||||
} {
|
||||
comment := issueComment{ID: 1, Body: c}
|
||||
comment.User.Login, comment.User.Type = tc.login, tc.kind
|
||||
gh := &fakeGH{prs: []pullRequest{notifyPR("20261026", "text")}, issueComments: []issueComment{comment}, bot: defaultBatchBot}
|
||||
code, stdout, stderr := reportRun(gh, "--pr", "90", "--id", s.doc.ID)
|
||||
if read := code == 0 && strings.Contains(stdout, "#5 picked"); read != tc.read || !tc.read && (code != 2 || !strings.Contains(stderr, "keeps no report")) {
|
||||
t.Errorf("a report by %s: report = %d, read %v, want %v:\n%s%s", tc.login, code, read, tc.read, stdout, stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A report whose ID is not one says so without repeating it as written.
|
||||
func TestReportErrorsRepeatNothingRaw(t *testing.T) {
|
||||
s := forged(func(*reportDoc) {})
|
||||
// Short enough that a cut to 12 characters keeps the forged line.
|
||||
raw := strings.Replace(s.raw, `"id":"`+s.doc.ID+`"`, `"id":"\nforged"`, 1)
|
||||
code, _, stderr := reportRun(&fakeGH{prs: []pullRequest{notifyPR("20261026", "text\n\n"+reportBlock(raw)+"\n")}}, "--pr", "90")
|
||||
for _, ln := range strings.Split(stderr, "\n") {
|
||||
if strings.HasPrefix(ln, "forged") {
|
||||
t.Errorf("report = %d, printed the forged line %q", code, ln)
|
||||
}
|
||||
}
|
||||
if code != 2 {
|
||||
t.Errorf("report = %d, want 2:\n%s", code, stderr)
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,9 @@ const (
|
||||
// Rule 1 for a line that started under the policy after it branched:
|
||||
// merged before that start.
|
||||
ruleBeforeStart = 101
|
||||
// Not a rule of the policy: a maintainer dropped the original from the
|
||||
// line with run --drop.
|
||||
ruleDropped = 102
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
+96
-22
@@ -17,6 +17,7 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
@@ -33,10 +34,11 @@ import (
|
||||
|
||||
// pickOriginal picks one original onto HEAD in that shape. A conflict on any
|
||||
// of its commits takes the branch back to where it was before the original,
|
||||
// so nothing of it is left half applied. Hooks are off so that each commit
|
||||
// carries its message and -x line as git writes them; signing is left to the
|
||||
// user's configuration.
|
||||
func pickOriginal(v *verdict) (pick, error) {
|
||||
// so nothing of it is left half applied, and so does a clean pick validate
|
||||
// finds leaving something of the original without effect: partial, with
|
||||
// those paths. Hooks are off so that each commit carries its message and -x
|
||||
// line as git writes them; signing is left to the user's configuration.
|
||||
func pickOriginal(v *verdict, validate func(base, head string) ([]string, error)) (pick, error) {
|
||||
p := pick{v: v}
|
||||
base, err := resolve("HEAD")
|
||||
if err != nil {
|
||||
@@ -59,10 +61,34 @@ func pickOriginal(v *verdict) (pick, error) {
|
||||
switch {
|
||||
case err != nil:
|
||||
return p, err
|
||||
case head == base && validate != nil:
|
||||
// Picks that change nothing carry the original only when the line
|
||||
// already has its changes: a change made where its branch merged
|
||||
// main is in no pick.
|
||||
omitted, err := validate(base, head)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
if len(omitted) > 0 {
|
||||
p.status, p.files = "partial", omitted
|
||||
return p, nil
|
||||
}
|
||||
p.status = "empty"
|
||||
return p, nil
|
||||
case head == base:
|
||||
p.status = "empty"
|
||||
return p, nil
|
||||
case v.o.parents < 2:
|
||||
}
|
||||
if validate != nil {
|
||||
omitted, err := validate(base, head)
|
||||
if err == nil && len(omitted) > 0 {
|
||||
p.status, p.files = "partial", omitted
|
||||
}
|
||||
if err != nil || len(omitted) > 0 {
|
||||
return p, errors.Join(err, resetTo(base))
|
||||
}
|
||||
}
|
||||
if v.o.parents < 2 {
|
||||
p.status, p.commit = "picked", head
|
||||
return p, nil
|
||||
}
|
||||
@@ -301,7 +327,8 @@ func checkMerge(b *batch, u unit) (string, *verdict, error) {
|
||||
}
|
||||
|
||||
// contained says why the change from base to tip is not inside the files v
|
||||
// changes, or "" when it is.
|
||||
// changes, or the paths a rename on main or on the line gave them at base,
|
||||
// or "" when it is.
|
||||
func contained(b *batch, v *verdict, base, tip string) (string, error) {
|
||||
if err := b.load(v); err != nil {
|
||||
return "", err
|
||||
@@ -313,7 +340,14 @@ func contained(b *batch, v *verdict, base, tip string) (string, error) {
|
||||
if len(changes) == 0 {
|
||||
return fmt.Sprintf("%.12s changes nothing", tip), nil
|
||||
}
|
||||
corr, _, err := b.correspondence(v, base)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
allowed := paths(v.changes)
|
||||
for _, c := range corr {
|
||||
allowed = append(allowed, c)
|
||||
}
|
||||
var extra []string
|
||||
for _, p := range paths(changes) {
|
||||
if !slices.Contains(allowed, p) {
|
||||
@@ -358,15 +392,50 @@ func replayUnit(u unit) (string, []string, error) {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
// summarize says, for each original the batch head carries in units, how many
|
||||
// commits it brought and which of them differ from the commit they were picked
|
||||
// from: a resolution, or a pick git had to fit to the line.
|
||||
func summarize(b *batch, head string, on []*verdict) (map[*verdict]string, error) {
|
||||
// pickPair is a pick on the batch and the commit it was picked from.
|
||||
type pickPair struct{ source, pick string }
|
||||
|
||||
// unitShape is what an original's unit on the batch brought: how many
|
||||
// commits, the picks that differ from the commit they came from, a
|
||||
// resolution or a pick git had to fit to the line, and whether the unit as a
|
||||
// whole makes another change than the original's merge.
|
||||
type unitShape struct {
|
||||
unit string
|
||||
commits int
|
||||
pairs []pickPair
|
||||
net bool
|
||||
}
|
||||
|
||||
// changed says whether the unit differs from its original, so its release
|
||||
// note may no longer hold.
|
||||
func (s unitShape) changed() bool { return len(s.pairs) > 0 || s.net }
|
||||
|
||||
// String is the shape as the body lists it.
|
||||
func (s unitShape) String() string {
|
||||
out := "1 commit"
|
||||
if s.commits != 1 {
|
||||
out = fmt.Sprintf("%d commits", s.commits)
|
||||
}
|
||||
if len(s.pairs) > 0 {
|
||||
var picks []string
|
||||
for _, p := range s.pairs {
|
||||
picks = append(picks, codeSpan(p.pick[:12]))
|
||||
}
|
||||
out += ", changed in the pick: " + strings.Join(picks, ", ")
|
||||
} else if s.net {
|
||||
out += ", changed as a whole: some of its change is not in the picks"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// summarize says, for each original the batch head carries in units, what
|
||||
// its unit brought.
|
||||
func summarize(b *batch, head string, on []*verdict) (map[*verdict]unitShape, error) {
|
||||
units, err := batchUnits(head, b.lineHead)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[*verdict]string{}
|
||||
out := map[*verdict]unitShape{}
|
||||
for _, u := range units {
|
||||
v := b.unitOriginal(u)
|
||||
if v == nil || !slices.Contains(on, v) {
|
||||
@@ -380,7 +449,7 @@ func summarize(b *batch, head string, on []*verdict) (map[*verdict]string, error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var changed []string
|
||||
s := unitShape{unit: u.commit, commits: len(picks)}
|
||||
for _, c := range picks {
|
||||
source := appendedSource(msgs[c].message)
|
||||
if source == "" {
|
||||
@@ -391,16 +460,20 @@ func summarize(b *batch, head string, on []*verdict) (map[*verdict]string, error
|
||||
return nil, err
|
||||
}
|
||||
if !same {
|
||||
changed = append(changed, codeSpan(c[:12]))
|
||||
s.pairs = append(s.pairs, pickPair{source: source, pick: c})
|
||||
}
|
||||
}
|
||||
s := "1 commit"
|
||||
if len(picks) != 1 {
|
||||
s = fmt.Sprintf("%d commits", len(picks))
|
||||
// A pick that came out empty leaves no pick to differ, only a net
|
||||
// change short of the original's.
|
||||
mine, err := patchIDRange(v.o.merge+"^1", v.o.merge)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(changed) > 0 {
|
||||
s += ", changed in the pick: " + strings.Join(changed, ", ")
|
||||
theirs, err := patchIDRange(u.parents[0], u.commit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.net = mine != theirs
|
||||
out[v] = s
|
||||
}
|
||||
return out, nil
|
||||
@@ -417,16 +490,17 @@ func plural(n int, word string) string {
|
||||
// parents, by git patch-id of their diffs without context, so that a pick
|
||||
// that only lands among other lines on the line counts as the same.
|
||||
func samePatch(a, b string) (bool, error) {
|
||||
pa, err := patchID(a)
|
||||
pa, err := patchIDRange(a+"^", a)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
pb, err := patchID(b)
|
||||
pb, err := patchIDRange(b+"^", b)
|
||||
return pa == pb, err
|
||||
}
|
||||
|
||||
func patchID(c string) (string, error) {
|
||||
diff, err := git("diff", "--no-ext-diff", "--no-textconv", "--unified=0", "--end-of-options", c+"^", c)
|
||||
// patchIDRange is the patch-id of the change from one revision to another.
|
||||
func patchIDRange(from, to string) (string, error) {
|
||||
diff, err := git("diff", "--no-ext-diff", "--no-textconv", "--unified=0", "--end-of-options", from, to)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -91,6 +91,15 @@ func (a *app) verify(args []string) int {
|
||||
if why == "" && seen[v] != "" {
|
||||
why = fmt.Sprintf("carries #%d again, which %.12s already carries", v.o.number, seen[v])
|
||||
}
|
||||
if why == "" {
|
||||
omitted, _, err := b.omittedEffects(v, u.parents[0], u.commit)
|
||||
if err != nil {
|
||||
return a.fail(err)
|
||||
}
|
||||
if len(omitted) > 0 {
|
||||
why = leftOut(v, l, omitted)
|
||||
}
|
||||
}
|
||||
if why != "" {
|
||||
refused = append(refused, why)
|
||||
fmt.Fprintf(a.stdout, "refused %.12s: %s\n", u.commit, why)
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// chainWorld has #5 conflict on the line and change a shared line, and #7
|
||||
// change that line again: #7 builds on #5.
|
||||
func chainWorld(t *testing.T) (*fixture, string) {
|
||||
t.Helper()
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: five and shared", "", map[string]string{"app/five.txt": "old\n", "app/shared.txt": appFile})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): five, the line's way", map[string]string{"app/five.txt": "line\n"})
|
||||
mc5 := f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "five\n", "app/shared.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/shared.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
return f, mc5
|
||||
}
|
||||
|
||||
// An original that builds on a deferred conflict waits for it: check warns,
|
||||
// notify lists it after the conflict, and once the conflict lands, the next
|
||||
// run picks it.
|
||||
func TestWaitForADeferredDependency(t *testing.T) {
|
||||
f, mc5 := chainWorld(t)
|
||||
gh := &fakeGH{}
|
||||
code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push")
|
||||
if code != 0 {
|
||||
t.Fatalf("run --push = %d\n%s", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stdout, `{"original":7,"files":[],"needs":[5]}`) || !strings.Contains(stdout, "### Waiting on another original") {
|
||||
t.Errorf("#7 does not wait on #5:\n%s", stdout)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
code, stdout, stderr = f.exec(gh, "check", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stderr, "warning: #7 waits on #5, a deferred conflict on #90: https://github.com/cozystack/cozystack/pull/7 ") {
|
||||
t.Errorf("check = %d, want a warning that #7 waits on #5:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
code, stdout, _ = f.exec(gh, "notify", "--line", "release-1.1", "--push")
|
||||
if code != 0 || !strings.Contains(gh.issueComments[len(gh.issueComments)-1].Body, "- [#7](https://github.com/cozystack/cozystack/pull/7), after [#5](https://github.com/cozystack/cozystack/pull/5)") {
|
||||
t.Errorf("notify = %d, want #7 listed after #5:\n%s\n%v", code, stdout, gh.issueComments)
|
||||
}
|
||||
// The batch merges, and #5 lands on the line by hand, resolved: the
|
||||
// next batch picks #7.
|
||||
mergeBatch(f, gh)
|
||||
f.onLine("release-1.1", "fix(app): five (#5)\n\n(cherry picked from commit "+mc5+")", map[string]string{"app/five.txt": "five\n", "app/shared.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
code, stdout, stderr = f.exec(gh, "run", "--line", "release-1.1", "--continue")
|
||||
if code != 0 || !strings.Contains(stdout, `"picked":[7]`) {
|
||||
t.Errorf("run --continue after #5 landed = %d, want #7 picked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// Of several prerequisites still to come, the strongest decides: one not on
|
||||
// the line at all, then one waiting for a maintainer, then a conflict or a
|
||||
// deferral, then one rule 6 holds; a chain inherits what its end decides.
|
||||
func TestWaitReduction(t *testing.T) {
|
||||
t.Run("a conflict and a workflow wait", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/five.txt": "old\n", "app/a.txt": appFile, "app/b.txt": appFile})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): five, the line's way", map[string]string{"app/five.txt": "line\n"})
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "five\n", "app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(6, "fix(ci): six", "", map[string]string{".github/workflows/six.yaml": "on: push\n", "app/b.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/b.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/eight.txt": "8\n"})
|
||||
gh := &fakeGH{}
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 || !strings.Contains(stdout, `{"original":7,"files":[],"needs":[6]}`) {
|
||||
t.Fatalf("run = %d, want #7 waiting on #6 alone:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#7 waits on #6, which changes .github/workflows/ and waits on batch PR #90 for a maintainer") {
|
||||
t.Errorf("check --cut = %d, want #7 to hold the cut:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
if code, stdout, _ := f.exec(gh, "notify", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, "2 originals on #90 change .github/workflows/ or wait on one that does") {
|
||||
t.Errorf("notify = %d, want #7 among the waits:\n%s", code, stdout)
|
||||
}
|
||||
})
|
||||
t.Run("a conflict and one not on the line", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/five.txt": "old\n", "app/a.txt": appFile, "app/b.txt": appFile})
|
||||
f.lines()
|
||||
f.onLine("release-1.1", "fix(app): five, the line's way", map[string]string{"app/five.txt": "line\n"})
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/five.txt": "five\n", "app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(6, "fix(app): six", "", map[string]string{"app/six.txt": "6\n"})
|
||||
gh := &fakeGH{}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 0 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
f.pr(9, "fix(app): nine", "", map[string]string{"app/b.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(10, "fix(app): ten", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/b.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/10 fix(app): ten (it waits on #9, which is not on the line either)") {
|
||||
t.Errorf("check = %d, want #10 to fail it, waiting on #9:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
t.Run("a prerequisite on the open batch", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
gh := &fakeGH{}
|
||||
if code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--push"); code != 0 || !strings.Contains(stdout, `"picked":[5,7]`) {
|
||||
t.Fatalf("run = %d, want #5 and #7 picked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || !strings.Contains(stdout, "#5 is only on open batch PR #90") || strings.Contains(stdout+stderr, "waits on") {
|
||||
t.Errorf("check --cut = %d, want #5 and #7 only on the batch and no wait:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
t.Run("a direct reason", func(t *testing.T) {
|
||||
f := featWorld(t)
|
||||
gh := &fakeGH{}
|
||||
openBatch(t, f, gh)
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "5", "--reason", "needs the tap", "--push"); code != 0 {
|
||||
t.Fatalf("run --defer = %d\n%s", code, stderr)
|
||||
}
|
||||
reopen(f, gh)
|
||||
if code, stdout, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "warning: deferred on #90 to the next batch: https://github.com/cozystack/cozystack/pull/5 ") || strings.Contains(stderr, "parked") {
|
||||
t.Errorf("check = %d, want #5 deferred for its reason, not parked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
t.Run("a prerequisite rule 6 holds", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
mc7 := f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/seven.txt": "7\n"})
|
||||
f.onLine("release-1.1", "fix(app): seven (#7)\n\n(cherry picked from commit "+mc7+")", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1), "app/seven.txt": "7\n"})
|
||||
if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.0"); code != 0 || !strings.Contains(stderr, "note: #7 waits on #5, which is not on release-1.1 yet") {
|
||||
t.Errorf("check of release-1.0 = %d, want a note that #7 waits on #5:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
t.Run("a chain", func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(4, "fix(app): four", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
f.pr(5, "fix(app): five", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!", 1)})
|
||||
f.pr(7, "fix(app): seven", "", map[string]string{"app/a.txt": strings.Replace(appFile, "two", "TWO!!", 1)})
|
||||
if code, stdout, stderr := f.exec(nil, "check", "--line", "release-1.1"); code != 1 || !strings.Contains(stdout, "/pull/7 fix(app): seven (it waits on #5, which is not on the line either)") {
|
||||
t.Errorf("check = %d, want #7 failing it through #5:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// run's report, check and notify give an original one disposition: a
|
||||
// workflow original whose only missing dependency is a test waits for a
|
||||
// maintainer, and one deferred for a reason stays deferred, though it
|
||||
// builds on what never comes; neither is parked.
|
||||
func TestDispositionOrderIsSharedByRunCheckNotify(t *testing.T) {
|
||||
f := auxWorld(t)
|
||||
f.pr(20, "feat(app): tap", "", map[string]string{"app/tap.go": appFile})
|
||||
f.pr(7, "fix(app): fix the tap", "", map[string]string{"app/tap.go": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
gh := &fakeGH{}
|
||||
if code, _, stderr := f.exec(gh, "run", "--line", "release-1.1", "--no-workflow-files", "--push"); code != 0 {
|
||||
t.Fatalf("run = %d\n%s", code, stderr)
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
code, stdout, stderr := f.exec(gh, "run", "--line", "release-1.1", "--defer", "7", "--reason", "waits for the tap", "--push")
|
||||
if code != 0 {
|
||||
t.Fatalf("run --defer = %d\n%s", code, stderr)
|
||||
}
|
||||
if strings.Contains(stdout, `"parked":[{`) || !strings.Contains(stdout, `{"original":5,"files":[".github/workflows/release.yaml"],"workflows":true}`) || !strings.Contains(stdout, `{"original":7,"files":[],"reason":"waits for the tap"}`) {
|
||||
t.Errorf("the report does not have #5 waiting and #7 deferred, unparked:\n%s", stdout)
|
||||
}
|
||||
reopen(f, gh)
|
||||
code, stdout, stderr = f.exec(gh, "check", "--line", "release-1.1")
|
||||
if code != 0 || strings.Contains(stderr, "parked") || !strings.Contains(stderr, "warning: waiting on #90 for a maintainer, since it changes .github/workflows/: https://github.com/cozystack/cozystack/pull/5 ") || !strings.Contains(stderr, "warning: deferred on #90 to the next batch: https://github.com/cozystack/cozystack/pull/7 ") {
|
||||
t.Errorf("check = %d, want #5 waiting and #7 deferred:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
code, stdout, _ = f.exec(gh, "notify", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stdout, "1 originals on #90 change .github/workflows/") || strings.Contains(stdout, "parked") || strings.Contains(stdout, "conflicts") {
|
||||
t.Errorf("notify = %d, want #5 waiting and nothing for #7:\n%s", code, stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// A never and a pending prerequisite together park.
|
||||
func TestParkWinsOverWait(t *testing.T) {
|
||||
f, _ := chainWorld(t)
|
||||
f.pr(20, "feat(app): tap", "", map[string]string{"app/tap.go": appFile})
|
||||
f.pr(8, "fix(app): eight", "", map[string]string{"app/shared.txt": strings.Replace(appFile, "two", "TWO!!", 1), "app/tap.go": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1")
|
||||
if code != 0 || !strings.Contains(stdout, `"kind":"dependency","needs":[20]`) || strings.Contains(stdout, `"original":8,"files":[],"needs"`) {
|
||||
t.Errorf("run = %d, want #8 parked on #20, not waiting on #7:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// A prerequisite picked earlier in the same batch satisfies what builds on
|
||||
// it, and so does one whose pick came out empty because an earlier pick
|
||||
// already carried it: #4280 and #3938.
|
||||
func TestDependencySatisfiedEarlierInTheBatch(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(3, "fix(kafka): delete hooks", "", map[string]string{"app/hooks.yaml": appFile})
|
||||
f.pr(4, "fix(kafka): fix the delete hook", "", map[string]string{"app/hooks.yaml": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, `"picked":[3,4]`) {
|
||||
t.Errorf("run = %d, want #3 and #4 picked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
|
||||
// #30 adds back the file #2 brought and a feat took away, so its pick
|
||||
// comes out empty after #2's, and #4 builds on #30.
|
||||
f = newFixture(t)
|
||||
f.squash(2, "chore: files", "", map[string]string{"app/a.txt": appFile})
|
||||
f.lines()
|
||||
f.pr(20, "fix(kafka): delete hooks, and two", "", map[string]string{"app/hooks.yaml": appFile, "app/two.txt": "2\n"})
|
||||
f.pr(21, "feat(kafka): no delete hooks", "", map[string]string{"app/hooks.yaml": ""})
|
||||
f.pr(30, "fix(kafka): delete hooks again", "", map[string]string{"app/hooks.yaml": appFile})
|
||||
f.pr(4, "fix(kafka): fix the delete hook", "", map[string]string{"app/hooks.yaml": strings.Replace(appFile, "two", "TWO", 1)})
|
||||
if code, stdout, stderr := f.exec(nil, "run", "--line", "release-1.1"); code != 0 || !strings.Contains(stdout, `"picked":[4,20]`) || strings.Contains(stdout, `"needs"`) {
|
||||
t.Errorf("run with #30's pick empty = %d, want #4 picked:\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
}
|
||||
@@ -110,7 +110,8 @@ func TestWorkflowChangesWaitUntilOnTheLine(t *testing.T) {
|
||||
if code != 0 || !strings.Contains(stdout, "1 originals on #90 change .github/workflows/ and wait for a maintainer") || strings.Contains(stdout, "deferred conflicts") {
|
||||
t.Errorf("notify = %d, %q; want #5 for a maintainer and no conflict\n%s", code, stdout, stderr)
|
||||
}
|
||||
if len(gh.issueComments) != 1 || !strings.Contains(gh.issueComments[0].Body, "[#5](") || !strings.Contains(gh.issueComments[0].Body, "#changes-to-workflows") || strings.Contains(gh.issueComments[0].Body, "These conflicts") {
|
||||
notes := slices.DeleteFunc(slices.Clone(gh.issueComments), func(c issueComment) bool { return !strings.HasPrefix(c.Body, notifyMarker) })
|
||||
if len(notes) != 1 || !strings.Contains(notes[0].Body, "[#5](") || !strings.Contains(notes[0].Body, "#changes-to-workflows") || strings.Contains(notes[0].Body, "These conflicts") {
|
||||
t.Errorf("the comment does not list #5 for a maintainer: %+v", gh.issueComments)
|
||||
}
|
||||
|
||||
@@ -173,8 +174,12 @@ func TestDeferKeepsWorkflowChangesWaiting(t *testing.T) {
|
||||
}
|
||||
f.git("switch", "-q", "main")
|
||||
reopen(f, gh)
|
||||
if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1", "--cut"); strings.Contains(stdout, "#5 changes") {
|
||||
t.Errorf("check --cut = %d, %q; a deferred #5 still stops the cut as waiting", code, stdout)
|
||||
// #6 and #7 are still only on the batch, which fails the cut; #5 does not.
|
||||
if code, stdout, _ := f.exec(gh, "check", "--line", "release-1.1", "--cut"); code != 1 || strings.Contains(stdout, "#5 changes") || !strings.Contains(stdout, "#6 is only on open batch PR #90") {
|
||||
t.Errorf("check --cut = %d, %q; want 1 for #6 and #7 alone, a deferred #5 no longer waiting", code, stdout)
|
||||
}
|
||||
if code, _, stderr := f.exec(gh, "check", "--line", "release-1.1"); code != 0 || !strings.Contains(stderr, "deferred on #90 to the next batch: https://github.com/cozystack/cozystack/pull/5 ") {
|
||||
t.Errorf("check = %d, want 0 with a warning about #5:\n%s", code, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Command observability-proxy serves tenant logs from the VictoriaLogs
|
||||
// stores behind a Kubernetes TokenReview and SubjectAccessReview, with the
|
||||
// tenant's namespace scope forced into every upstream request.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"k8s.io/client-go/informers"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
"k8s.io/client-go/tools/clientcmd"
|
||||
|
||||
"github.com/cozystack/cozystack/internal/observabilityproxy"
|
||||
)
|
||||
|
||||
type options struct {
|
||||
listenAddress string
|
||||
probeAddress string
|
||||
clusterDomain string
|
||||
rootTenant string
|
||||
kubeconfig string
|
||||
authCacheTTL time.Duration
|
||||
requestTimeout time.Duration
|
||||
tailIdleTimeout time.Duration
|
||||
shutdownTimeout time.Duration
|
||||
logs observabilityproxy.LogsLimits
|
||||
limiter observabilityproxy.LimiterConfig
|
||||
}
|
||||
|
||||
func parseFlags(args []string) (options, error) {
|
||||
var o options
|
||||
fs := flag.NewFlagSet("observability-proxy", flag.ContinueOnError)
|
||||
fs.SetOutput(io.Discard)
|
||||
fs.StringVar(&o.listenAddress, "listen-address", ":8080", "address of the API listener")
|
||||
fs.StringVar(&o.probeAddress, "probe-address", ":8081", "address serving /healthz, /readyz and /metrics")
|
||||
fs.StringVar(&o.clusterDomain, "cluster-domain", "cozy.local", "cluster DNS domain used to reach the stores")
|
||||
fs.StringVar(&o.rootTenant, "root-tenant", "tenant-root", "tenant namespace hosting the default store")
|
||||
fs.StringVar(&o.kubeconfig, "kubeconfig", "", "kubeconfig path; in-cluster config when empty")
|
||||
fs.DurationVar(&o.authCacheTTL, "auth-cache-ttl", 10*time.Second, "how long TokenReview and SubjectAccessReview answers are cached")
|
||||
fs.DurationVar(&o.requestTimeout, "request-timeout", time.Minute, "deadline for reading the request body, the token and access reviews, and every upstream endpoint but tail; 0 disables it")
|
||||
fs.DurationVar(&o.tailIdleTimeout, "tail-idle-timeout", 5*time.Minute, "close a tail after this long without a line")
|
||||
fs.DurationVar(&o.shutdownTimeout, "shutdown-timeout", 15*time.Second, "grace period for in-flight requests on shutdown")
|
||||
fs.DurationVar(&o.logs.DefaultRange, "logs-default-range", time.Hour, "window used when a logs request has no start")
|
||||
// One week covers an incident investigation and keeps a single query
|
||||
// to a fraction of the default one-month log retention.
|
||||
fs.DurationVar(&o.logs.MaxRange, "logs-max-range", 7*24*time.Hour, "longest [start, end] a logs request may span; wider windows are clamped")
|
||||
// Prometheus's cap on points per series in a range query.
|
||||
fs.IntVar(&o.logs.MaxBuckets, "logs-max-buckets", 11000, "most buckets hits and stats_query_range may return over a window")
|
||||
fs.IntVar(&o.logs.DefaultLimit, "logs-default-limit", 1000, "entries returned when a request sets no limit")
|
||||
fs.IntVar(&o.logs.MaxLimit, "logs-max-limit", 10000, "largest limit a request may set")
|
||||
fs.DurationVar(&o.logs.MaxTailResume, "logs-max-tail-resume", 15*time.Minute, "how far back a tail may resume with since or start_offset")
|
||||
fs.IntVar(&o.limiter.MaxConcurrentPerUser, "max-concurrent-per-user", 10, "concurrent non-tail requests per user; 0 disables")
|
||||
fs.Float64Var(&o.limiter.RatePerUser, "rate-limit-per-user", 10, "sustained requests per second per user; 0 disables")
|
||||
fs.IntVar(&o.limiter.RateBurst, "rate-limit-burst", 20, "request burst per user")
|
||||
fs.IntVar(&o.limiter.MaxTailsPerUser, "max-tails-per-user", 5, "open tails per user; 0 disables")
|
||||
fs.IntVar(&o.limiter.MaxTails, "max-tails", 200, "open tails in total; 0 disables")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return o, err
|
||||
}
|
||||
// Parsing stops at the first non-flag, so every flag after it would
|
||||
// be dropped silently.
|
||||
if fs.NArg() > 0 {
|
||||
return o, fmt.Errorf("unexpected argument %q", fs.Arg(0))
|
||||
}
|
||||
switch {
|
||||
case o.rootTenant == "":
|
||||
return o, errors.New("--root-tenant must not be empty")
|
||||
case o.clusterDomain == "":
|
||||
return o, errors.New("--cluster-domain must not be empty")
|
||||
case o.logs.DefaultRange <= 0 || o.logs.MaxRange < o.logs.DefaultRange:
|
||||
return o, errors.New("--logs-default-range must be positive and not above --logs-max-range")
|
||||
// Below four buckets (three steps once one is held back for
|
||||
// alignment), or a range under three seconds, the step cap that keeps
|
||||
// vlselect's step alignment inside the range cannot hold.
|
||||
case o.logs.MaxBuckets < 4:
|
||||
return o, errors.New("--logs-max-buckets must be at least 4")
|
||||
case o.logs.MaxRange < 3*time.Second:
|
||||
return o, errors.New("--logs-max-range must be at least 3s")
|
||||
case o.logs.DefaultLimit <= 0 || o.logs.MaxLimit < o.logs.DefaultLimit:
|
||||
return o, errors.New("--logs-default-limit must be positive and not above --logs-max-limit")
|
||||
case o.logs.MaxTailResume < 0:
|
||||
return o, errors.New("--logs-max-tail-resume must not be negative")
|
||||
case o.requestTimeout < 0 || o.tailIdleTimeout < 0 || o.authCacheTTL < 0 || o.shutdownTimeout < 0:
|
||||
return o, errors.New("timeouts and the auth cache TTL must not be negative")
|
||||
// NaN passes every comparison and +Inf never empties a bucket; either
|
||||
// would switch the rate limit off without saying so.
|
||||
case math.IsNaN(o.limiter.RatePerUser) || math.IsInf(o.limiter.RatePerUser, 0):
|
||||
return o, errors.New("--rate-limit-per-user must be a finite number")
|
||||
case o.limiter.RatePerUser < 0 || o.limiter.RateBurst < 0 || o.limiter.MaxConcurrentPerUser < 0 ||
|
||||
o.limiter.MaxTailsPerUser < 0 || o.limiter.MaxTails < 0:
|
||||
return o, errors.New("limits must not be negative; 0 disables a limit")
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, nil)))
|
||||
o, err := parseFlags(os.Args[1:])
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "observability-proxy: %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := run(o); err != nil {
|
||||
slog.Error("exiting", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(o options) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
restConfig, err := clientcmd.BuildConfigFromFlags("", o.kubeconfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("loading kubeconfig: %w", err)
|
||||
}
|
||||
client, err := kubernetes.NewForConfig(restConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("building client: %w", err)
|
||||
}
|
||||
|
||||
factory := informers.NewSharedInformerFactory(client, 0)
|
||||
namespaces := factory.Core().V1().Namespaces()
|
||||
lister := namespaces.Lister()
|
||||
factory.Start(ctx.Done())
|
||||
var ready atomic.Bool
|
||||
go func() {
|
||||
if cache.WaitForCacheSync(ctx.Done(), namespaces.Informer().HasSynced) {
|
||||
ready.Store(true)
|
||||
}
|
||||
}()
|
||||
|
||||
reg := prometheus.NewRegistry()
|
||||
reg.MustRegister(collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
|
||||
proxy := observabilityproxy.NewServer(observabilityproxy.Config{
|
||||
ClusterDomain: o.clusterDomain,
|
||||
Logs: o.logs,
|
||||
Limiter: o.limiter,
|
||||
RequestTimeout: o.requestTimeout,
|
||||
TailIdleTimeout: o.tailIdleTimeout,
|
||||
}, observabilityproxy.NewAuthorizer(client, o.authCacheTTL), observabilityproxy.NewStoreResolver(lister, namespaces.Informer().HasSynced, o.rootTenant), reg)
|
||||
|
||||
probes := http.NewServeMux()
|
||||
probes.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, "ok") })
|
||||
probes.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) {
|
||||
if !ready.Load() {
|
||||
http.Error(w, "namespace cache not synced", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, "ok")
|
||||
})
|
||||
probes.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
|
||||
|
||||
// No WriteTimeout on the API listener: it would cut live tails, which
|
||||
// the handler bounds with its own idle timeout instead.
|
||||
servers := []*http.Server{
|
||||
{Addr: o.listenAddress, Handler: proxy, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 2 * time.Minute},
|
||||
{Addr: o.probeAddress, Handler: probes, ReadHeaderTimeout: 10 * time.Second},
|
||||
}
|
||||
errs := make(chan error, len(servers))
|
||||
for _, srv := range servers {
|
||||
go func() {
|
||||
slog.Info("listening", "address", srv.Addr)
|
||||
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
|
||||
errs <- err
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
var runErr error
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case runErr = <-errs:
|
||||
}
|
||||
stop()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), o.shutdownTimeout)
|
||||
defer cancel()
|
||||
for _, srv := range servers {
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
// Open tails never go idle on their own; cut them so clients
|
||||
// reconnect with since to another replica.
|
||||
_ = srv.Close()
|
||||
}
|
||||
}
|
||||
return runErr
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseFlagsDefaults(t *testing.T) {
|
||||
o, err := parseFlags(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if o.listenAddress != ":8080" || o.probeAddress != ":8081" || o.clusterDomain != "cozy.local" || o.rootTenant != "tenant-root" {
|
||||
t.Errorf("contract defaults changed: %+v", o)
|
||||
}
|
||||
if o.authCacheTTL != 10*time.Second || o.logs.MaxTailResume != 15*time.Minute || o.logs.MaxRange != 7*24*time.Hour {
|
||||
t.Errorf("limit defaults changed: %+v", o)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFlagsOverrides(t *testing.T) {
|
||||
o, err := parseFlags([]string{"--cluster-domain=example.org", "--logs-max-range=24h", "--max-tails=3"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if o.clusterDomain != "example.org" || o.logs.MaxRange != 24*time.Hour || o.limiter.MaxTails != 3 {
|
||||
t.Errorf("overrides not applied: %+v", o)
|
||||
}
|
||||
// The smallest bucket count and range the step cap can satisfy.
|
||||
if _, err := parseFlags([]string{"--logs-max-buckets=4", "--logs-max-range=3s", "--logs-default-range=1s"}); err != nil {
|
||||
t.Errorf("smallest satisfiable step cap refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFlagsInvalid(t *testing.T) {
|
||||
for _, args := range [][]string{
|
||||
{"--root-tenant="},
|
||||
{"--cluster-domain="},
|
||||
{"--logs-default-range=48h", "--logs-max-range=24h"},
|
||||
{"--logs-max-buckets=3"},
|
||||
{"--logs-max-range=2s", "--logs-default-range=1s"},
|
||||
{"--shutdown-timeout=-1s"},
|
||||
{"--logs-default-limit=0"},
|
||||
{"--logs-default-limit=100", "--logs-max-limit=10"},
|
||||
{"--logs-max-tail-resume=-1m"},
|
||||
{"--request-timeout=-1s"},
|
||||
{"--tail-idle-timeout=-1s"},
|
||||
{"--auth-cache-ttl=-1s"},
|
||||
{"--rate-limit-per-user=-1"},
|
||||
{"--rate-limit-per-user=NaN"},
|
||||
{"--rate-limit-per-user=+Inf"},
|
||||
{"--rate-limit-burst=-1"},
|
||||
{"--max-concurrent-per-user=-1"},
|
||||
{"--max-tails-per-user=-1"},
|
||||
{"--max-tails=-1"},
|
||||
{"--unknown"},
|
||||
{"unexpected", "--root-tenant=tenant-x"},
|
||||
} {
|
||||
if _, err := parseFlags(args); err == nil {
|
||||
t.Errorf("parseFlags(%v) accepted", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,7 +134,7 @@ git log v0.37.1..v0.37.2 --pretty=format:"%h - %s (%an, %ar)"
|
||||
```
|
||||
|
||||
**⚠️ IMPORTANT: Check for backports.** They reach a release line in two shapes:
|
||||
- A backport batch ([`docs/release/backports.md`](../release/backports.md)): a merge commit titled `fix(backport): batch for release-X.Y, <date> (#BATCH_PR)`. Inside it each original is one merge commit that carries the original's merge message from `main`, `Merge pull request #ORIGINAL_PR from …` or `<original title> (#ORIGINAL_PR)`, and ends in a `Backported-from: <sha>` trailer, with the original's own commits, picked with `-x`, on its second parent; an original squash-merged into `main` is one commit with its subject, `<original title> (#ORIGINAL_PR)`, and a `(cherry picked from commit <sha>)` line. Read the original's number, title and author from those, list the batch with `git log --first-parent` inside it, and never write an entry for the batch PR itself or for a picked commit of an original.
|
||||
- A backport batch ([`docs/release/backports.md`](../release/backports.md)): a merge commit titled `fix(backport): batch for release-X.Y, <date> (#BATCH_PR)`. Inside it each original is one merge commit that carries the original's merge message from `main`, `Merge pull request #ORIGINAL_PR from …` or `<original title> (#ORIGINAL_PR)`, and ends in a `Backported-from: <sha>` trailer, with the original's own commits, picked with `-x`, on its second parent; an original squash-merged into `main` is one commit with its subject, `<original title> (#ORIGINAL_PR)`, and a `(cherry picked from commit <sha>)` line. Read the original's number, title and author from those, list the batch with `git log --first-parent` inside it, and never write an entry for the batch PR itself or for a picked commit of an original. An original whose pick differs from it is listed under "Check these notes" in the batch merge's message, which carries the batch PR's body, and in its record's `changed` list: write its entry from what its pick changed on the line, read with the `git range-diff` and `git diff` commands listed there, not from the original's release note.
|
||||
- A single backport PR, from before the batch (the retired label-driven bot) or a release-only fix: commits with "[Backport release-X.Y]" in the message, whose original PR number is in the backport commit message or PR description.
|
||||
- Use the original PR author (not the backport or batch PR author) when creating changelog entries
|
||||
- **MUST** combine the original and backport into a **single entry** with both PR numbers (e.g. `#1606, backport #1609`, where a batch's original reads `#1606, backport #BATCH_PR`). Do NOT list the original and the backport as two separate entries — that produces duplicates in the changelog.
|
||||
|
||||
@@ -14,7 +14,7 @@ go build ./cmd/backport-batch
|
||||
./backport-batch check --line release-X.Y --cut
|
||||
```
|
||||
|
||||
[`backport-batch check`](../../cmd/backport-batch/README.md) applies the rules to every pull request merged into `main` since the line branched, and looks for each one they take on the line and then on the open batch pull request: by picks whose `-x` lines name its merge commit or every commit of its own, by a pick that would change nothing, and, on commits from before the policy's batch-only day, by what their text says, such as `Backport of #N`. With `--cut` a change found only on the open batch pull request fails the check too, since a cut tags the line and would not carry it: merge the batch pull request first. A conflict the batch deferred, or an original deferred to the next batch, prints as a warning without failing the check. A change that reached the line by hand counts like any other, by what reached the line.
|
||||
[`backport-batch check`](../../cmd/backport-batch/README.md) applies the rules to every pull request merged into `main` since the line branched, and looks for each one they take on the line and then on the open batch pull request: by picks whose `-x` lines name its merge commit or every commit of its own, by a pick that would change nothing, and, on commits from before the policy's batch-only day, by what their text says, such as `Backport of #N`. With `--cut` a change found only on the open batch pull request fails the check too, since a cut tags the line and would not carry it: merge the batch pull request first. A conflict the batch deferred, or an original deferred to the next batch, prints as a warning without failing the check, also once that batch merged or closed. An original that waits on the open batch for a maintainer fails the cut, and so does a unit on the open batch that carries only part of its original. An original parked because it builds on a change the line never gets, or would land only in part, prints as a note; one that waits on another original fails, warns or notes by what it waits on. A change that reached the line by hand counts like any other, by what reached the line.
|
||||
|
||||
### Backporting code that touches monotonic counters
|
||||
|
||||
|
||||
@@ -10,9 +10,9 @@ The [backport batch](../backports.md) is built by [`backport-batch`](../../../cm
|
||||
### Rules for every task
|
||||
|
||||
- Push nothing but the branch of the open batch pull request, `backport-batch/<line>-<yyyymmdd>` in this repository, and only what the task's check accepted. Never push to `main` or a `release-*` branch, and never open a second batch pull request: the scheduled run continues the open one.
|
||||
- Change no file the original pull request does not change. A conflict that cannot be resolved inside those files is not resolved: the original stays deferred.
|
||||
- Change no file the original pull request does not change, or the path a rename on `main` or on the line gave it. A conflict that cannot be resolved inside those files is not resolved: the original stays deferred.
|
||||
- Never rewrite the batch branch by hand. A plain push to it is a fast-forward; only `backport-batch run --defer --push` replaces it, leased on the head it rebuilt.
|
||||
- Leave the batch pull request's title and body to the tool: it rewrites both on every run, and a hand edit is lost or, inside the `backport-batch` block, makes `check` refuse the body.
|
||||
- Leave the batch pull request's title and body to the tool: it rewrites both on every run, and a hand edit is lost or, inside the `backport-batch` block, makes `run`, `check`, `fold` and `notify` refuse the body, and inside the `backport-batch-report` block makes `run --push` and `backport-batch report` refuse it. Leave the tool's report comments as they are too: each keeps one classification of the line, and an edited one makes `backport-batch report` refuse it.
|
||||
- When the task cannot be done within these rules, push nothing and leave a comment on the batch pull request saying why, so the next maintainer to look finds it. Nothing is lost by waiting: a red batch does not merge, and a deferred original goes to the next batch.
|
||||
|
||||
### Getting the tool
|
||||
@@ -26,4 +26,4 @@ cd ../backport-task
|
||||
go build -o /tmp/backport-batch ./cmd/backport-batch
|
||||
```
|
||||
|
||||
Run it from that worktree. Every command but `notify` fetches `origin` first, and `run`, `check`, `fold` and `lines` read the policy from `origin/main`.
|
||||
Run it from that worktree. Every command but `notify` and `report` fetches `origin` first, and `run`, `check`, `fold` and `lines` read the policy from `origin/main`.
|
||||
@@ -33,6 +33,8 @@ It rebuilds the branch locally without those originals and prints the new body,
|
||||
|
||||
It replaces the batch branch only if nobody pushed onto it since the rebuild read it, and updates the pull request body. CI runs again on the new head; if it fails again on another original, repeat from step 1.
|
||||
|
||||
When the culprits are everything the batch carries, there is no branch left to push: the body printed without `--push` says the batch is closing, and `--push` records the deferrals in the batch pull request, closes it and deletes its branch, still only if nobody pushed onto it since. The next batch tries them again. If it stops part way, the next `run --push` on the line finishes the close, and says so.
|
||||
|
||||
### Never
|
||||
|
||||
- Defer an original the failure does not reach, to make the batch green by taking out more than the culprit.
|
||||
|
||||
@@ -4,7 +4,7 @@ The batch carries a pull request merged into `main` as its own commits, each pic
|
||||
|
||||
### Inputs
|
||||
|
||||
- The open batch pull request for the line, its branch `backport-batch/<line>-<yyyymmdd>` and its head commit, as GitHub shows them: `gh pr view <batch> --json headRefName,headRefOid`.
|
||||
- The open batch pull request for the line, its branch `backport-batch/<line>-<yyyymmdd>` and its head commit, as GitHub shows them: `gh pr view <batch> --json headRefName,headRefOid`. The resolution lands on that batch, so without an open batch pull request there is nothing to resolve onto: wait for the next batch, which lists the conflict again, or port the change as a pull request of its own against the line, as [fixes that exist only on a release line](../backports.md#fixes-that-exist-only-on-a-release-line) describes, and drop the original from the line.
|
||||
- The original's number `N` from the **Deferred conflicts** list, and its merge commit on `main`: `gh pr view N --json mergeCommit --jq .mergeCommit.oid`. It has two parents when the pull request was merged, one when it was squashed.
|
||||
- For a merged pull request, its own commits, oldest first, without the merges that brought `main` into its branch: `git rev-list --reverse --topo-order --no-merges <merge commit>^1..<merge commit>^2`.
|
||||
- The files the original changes, `git diff --name-only <merge commit>^1 <merge commit>`, which are the only files the resolution may touch.
|
||||
@@ -34,7 +34,7 @@ git add <resolved files>
|
||||
git -c core.hooksPath=/dev/null cherry-pick --continue --no-edit
|
||||
```
|
||||
|
||||
When the original builds on something the line does not have, a helper, a value or another pull request, the resolution would have to bring that along, which this task does not allow: abort with `git cherry-pick --abort`, go back with `git switch --detach "$base"`, and comment on the batch pull request which change the original depends on; it stays deferred until that change is on the line. A commit whose change the line already has stops the pick as empty; skip it with `git cherry-pick --skip`.
|
||||
When the original builds on something the line does not have, a helper, a value or another pull request, the resolution would have to bring that along, which this task does not allow: abort with `git cherry-pick --abort`, go back with `git switch --detach "$base"`, and comment on the batch pull request which change the original depends on; it stays deferred until that change is on the line. An original the batch parked because it builds on such a change is the same task, and lands only as a complete adaptation: every file it changes changed, unless the line already has that file as the original makes it. When that change will never reach the line, drop the original there instead, with `backport-batch run --line <line> --drop N --reason "<builds on …>" --push`, so later batches stop trying it. A commit whose change the line already has stops the pick as empty; skip it with `git cherry-pick --skip`. A resolution that ports only what the line has and leaves a file of the original as it was, one the line does not have for instance, is refused by `fold`: such a port goes to the line as a pull request of its own, as [fixes that exist only on a release line](../backports.md#fixes-that-exist-only-on-a-release-line) describes, and the original is dropped there.
|
||||
|
||||
For a merged pull request, join the picks to the batch head with the merge commit:
|
||||
|
||||
|
||||
@@ -21,6 +21,14 @@ The batch takes a pull request from `main` into release line X.Y when all of the
|
||||
|
||||
The batch reads the pull requests off `main`'s first-parent history, one per merge commit or squash commit that names its pull request. A commit there that names none, a direct push for instance, and a merge of more than two parents are never taken; the batch pull request counts them.
|
||||
|
||||
### What the batch leaves out on one line
|
||||
|
||||
A pull request the rules take for every line can still be wrong for one of them, for instance because it builds on code that line does not have. A maintainer drops it from that line with `./backport-batch run --line <line> --drop <number> --reason <why> --push`: the batch takes it off, if it carries it, and no later batch for that line picks it again. The drop is kept in the [line's record](#the-lines-record-and-reports), so it needs an open batch pull request to record it on; before a line's first batch pull request exists there is nothing to record it on, and the command refuses. `--undrop <number>` withdraws it, and the next batch tries the pull request again. A pull request the line already carries cannot be dropped. To land a hand-made port instead, open it as a pull request of its own, as [fixes that exist only on a release line](#fixes-that-exist-only-on-a-release-line) describes, and drop the original.
|
||||
|
||||
The batch also leaves a pull request out of a line on its own when it cannot land there whole. A pick that would leave part of what the pull request does on `main` without effect on the line, a change to a file the line does not have, or the deletion of a file the line never had or already removed, is not made: the pull request is parked, the batch pull request lists it under "Parked" with those files, and `check` prints it as a note without failing. A file the line already has as the pull request makes it counts as there, and so does a file `main` or the line renamed, under its other name. A unit already on the open batch that does only part of its original fails `check --cut` and `backport-batch verify`, whatever its label says, until `backport-batch run --defer` takes it out. What applies of a parked pull request goes to the line as a pull request of its own, as [fixes that exist only on a release line](#fixes-that-exist-only-on-a-release-line) describes.
|
||||
|
||||
A pull request is parked too when it builds on a change the line never gets: it changes a file a `feat` added on `main`, say, or a line such a change wrote, and the line has neither. `backport-batch` reads that from git, as [its README](../../cmd/backport-batch/README.md#what-an-original-builds-on) describes, and names the change in the batch pull request. One that builds on a change that is still to come, a deferred conflict, one waiting for a maintainer, one rule 6 holds or one not tried yet, waits for it instead, listed under "Waiting on another original", and the batch tries it again once that change is on the line; one picked earlier in the same batch counts as there. A complete hand adaptation of a parked pull request, every file it changes changed, still lands on the batch through [resolving a conflict](./backport-tasks/resolve-conflict.md).
|
||||
|
||||
### What waits for the next minor
|
||||
|
||||
`feat`, `chore` and `docs` pull requests, and dependency bumps (scope `deps`), ship with the next minor, not in a patch release; only a maintainer's `backport/include`, below, takes one. If a class of fixes should also wait for a minor, it gets a new rule on this page; a single pull request that the rules get wrong is what the overrides below are for.
|
||||
@@ -29,9 +37,11 @@ The batch reads the pull requests off `main`'s first-parent history, one per mer
|
||||
|
||||
A maintainer overrides the rules for one pull request with a label on the merged pull request on `main`:
|
||||
|
||||
- `backport/include` takes it although rules 2 to 4 keep it out, a `feat` for instance, or although it merged before its line started under this policy. It still has to pick cleanly or have its conflict resolved, pass CI on the batch, and, on an older line, already be on the newer one, and a line that already carries it does not take it again.
|
||||
- `backport/include` takes it although rules 2 to 4 keep it out, a `feat` for instance, or although it merged before its line started under this policy. It still has to pick cleanly or have its conflict resolved, pass CI on the batch, and, on an older line, already be on the newer one, and a line that already carries it does not take it again. It lifts no park, as [what the batch leaves out on one line](#what-the-batch-leaves-out-on-one-line) describes.
|
||||
- `backport/skip` keeps it out although the rules take it, and `backport-batch check` stops asking for it. An open batch that picked it before the label came keeps it until `backport-batch run --defer` takes it out; the batch pull request says so meanwhile.
|
||||
|
||||
A label decides for every line. To keep a pull request out of one line only, drop it there with `backport-batch run --drop`, as [what the batch leaves out on one line](#what-the-batch-leaves-out-on-one-line) describes; `backport/include` does not lift a drop.
|
||||
|
||||
`backport/skip` wins when a pull request carries both. Each run reads the labels afresh, and the batch pull request lists every override and what became of it.
|
||||
|
||||
### Which lines the batch runs for
|
||||
@@ -59,7 +69,7 @@ released-lines: 2
|
||||
|
||||
### Fixes that exist only on a release line
|
||||
|
||||
Some fixes go to a release line as a pull request of their own. Such pull requests are occasional, and maintainers open them: for a fix with no counterpart on `main`, for one that on `main` came as part of another pull request, or for one written for `main` rather than for the line. When the counterpart on `main` is a pull request of its own that the batch would take, the batch skips it as already on the line once picking it would change nothing there; otherwise a maintainer labels it `backport/skip`.
|
||||
Some fixes go to a release line as a pull request of their own. Such pull requests are occasional, and maintainers open them: for a fix with no counterpart on `main`, for one that on `main` came as part of another pull request, or for one written for `main` rather than for the line. When the counterpart on `main` is a pull request of its own that the batch would take, the batch skips it as already on the line once picking it would change nothing there; otherwise a maintainer labels it `backport/skip`. A port of only what a line has of a pull request from `main`, one that leaves out what the line lacks, is such a pull request as well: the batch carries no unit that does part of its original, and `backport-batch fold` refuses one.
|
||||
|
||||
A pull request opened against a `release-*` branch is closed automatically, with a comment that links to this page, when its author is a user account, not a bot, that GitHub names neither the repository's owner nor a member nor a collaborator, and whose access to the repository GitHub reports as read or none. Anyone with triage access or more keeps their pull request open. When GitHub's answer on the author's access cannot be read, the check closes nothing and fails, naming the read that failed. The check runs only when a pull request is opened, so a maintainer keeps a contributor's release-only fix by reopening it. [`hack/close-manual-backport.sh`](../../hack/close-manual-backport.sh) does this from [`pr-labeler.yaml`](../../.github/workflows/pr-labeler.yaml); run it with `--pr <number> --dry-run` to see what it would decide for a given pull request when it is opened.
|
||||
|
||||
@@ -81,15 +91,21 @@ A run by hand trusts the open batch pull request the scheduled run opened as `co
|
||||
|
||||
`./backport-batch lines` prints the lines, newest first. `run`, `check`, `fold` and `lines` read the policy block from this page on `main`, so until the page with its block is on `main` they need `--policy <ref>` naming a ref that has it, and the scheduled run, which passes none, fails.
|
||||
|
||||
`run` picks what the rules take onto `backport-batch/<line>-<yyyymmdd>` and opens a draft pull request against the line. A pull request merged into `main` with a merge commit goes onto the batch as its own commits, oldest first, each picked with `git cherry-pick -x --signoff` so it keeps its author, its message and its sign-offs and gains the sign-off of whoever runs the batch; commits that merged `main` into the pull request's branch are left out. A merge commit joins them to the batch: it carries the original's merge message from `main` and ends in a `Backported-from: <merge commit>` trailer. A pull request squash-merged into `main` goes on as one pick. When any commit of an original conflicts, nothing of that original stays on the batch. The batch pull request is merged into the line with a merge commit, so all of this reaches the line as it is. Its body lists the originals with how many commits each brought and which of them differ from the commit they came from, the conflicts it deferred with the commit that failed and its files, and what it skipped under which rule. While that pull request is open, the next run continues it, `--continue` reading its head, rather than opening another. CI on the batch pull request runs the line's build and tests, and a maintainer merges it. Since rule 6 reads the newer line itself, an older line takes a fix in the batch after the newer line's batch with that fix has merged.
|
||||
`run` picks what the rules take onto `backport-batch/<line>-<yyyymmdd>` and opens a draft pull request against the line. A pull request merged into `main` with a merge commit goes onto the batch as its own commits, oldest first, each picked with `git cherry-pick -x --signoff` so it keeps its author, its message and its sign-offs and gains the sign-off of whoever runs the batch; commits that merged `main` into the pull request's branch are left out. A merge commit joins them to the batch: it carries the original's merge message from `main` and ends in a `Backported-from: <merge commit>` trailer. A pull request squash-merged into `main` goes on as one pick. When any commit of an original conflicts, nothing of that original stays on the batch. The batch pull request is merged into the line with a merge commit, so all of this reaches the line as it is. Its body lists the originals with how many commits each brought and which of them differ from the commit they came from, whose release notes wait under "Check these notes" with what to compare, since a note may not hold for a pick that differs, the conflicts it deferred with the commit that failed and its files, what it parked and why, and what it skipped under which rule, and ends with the [line's record and the run's report](#the-lines-record-and-reports); `--push` prints the pull request's URL. While that pull request is open, the next run continues it, `--continue` reading its head, rather than opening another. CI on the batch pull request runs the line's build and tests, and a maintainer merges it. Since rule 6 reads the newer line itself, an older line takes a fix in the batch after the newer line's batch with that fix has merged.
|
||||
|
||||
A deferred conflict waits for the next batch. To land it sooner, pick the original's commits onto the batch head with `git cherry-pick -x`, resolving each conflict, and join them to the batch head with a merge commit that names the original; an original squash-merged into `main` is one pick of its commit there, with no merge. Check that merge or that pick with `./backport-batch fold --line <line> --original <number> --commit <sha>`, and push it onto the batch branch, as [resolving a conflict](./backport-tasks/resolve-conflict.md) describes. CI runs `backport-batch verify` on every push to a batch pull request, which holds every original on it to the same shape. When CI on the batch pull request fails, the original it comes from is taken out with `./backport-batch run --line <line> --defer <number> --reason <why> --push` and goes to the next batch, as [attributing a failed batch CI](./backport-tasks/failed-ci.md) describes; the rest of the batch merges without it.
|
||||
A deferred conflict waits for the next batch. To land it sooner, pick the original's commits onto the batch head with `git cherry-pick -x`, resolving each conflict, and join them to the batch head with a merge commit that names the original; an original squash-merged into `main` is one pick of its commit there, with no merge. Check that merge or that pick with `./backport-batch fold --line <line> --original <number> --commit <sha>`, and push it onto the batch branch, as [resolving a conflict](./backport-tasks/resolve-conflict.md) describes. CI runs `backport-batch verify` on every push to a batch pull request, which holds every original on it to the same shape. When CI on the batch pull request fails, the original it comes from is taken out with `./backport-batch run --line <line> --defer <number> --reason <why> --push` and goes to the next batch, as [attributing a failed batch CI](./backport-tasks/failed-ci.md) describes; the rest of the batch merges without it. When it is all the batch carries, `--push` records why in the batch pull request, closes it and deletes its branch, and the next batch tries it again. `--drop` and `--undrop` change the record of the open batch pull request in the same way, and need one.
|
||||
|
||||
Before a patch release or an rc is cut from a line, `./backport-batch check --line <line> --cut` has to exit 0. A cut tags the line, so the check fails while a pull request the rules take is not on the line, including one that is only on the open batch pull request: merge the batch pull request first. It prints the URLs, and prints what the batch deferred as warnings, since deferring is a maintainer's call. Without `--cut`, as the scheduled run uses it, a change on the open batch pull request counts as carried.
|
||||
Before a patch release or an rc is cut from a line, `./backport-batch check --line <line> --cut` has to exit 0. A cut tags the line, so the check fails while a pull request the rules take is not on the line, including one that is only on the open batch pull request: merge the batch pull request first. It prints the URLs, and prints what the batch deferred as warnings, since deferring is a maintainer's call; so is a pull request labelled `backport/skip` that the open batch still carries. An original that waits on the batch for a maintainer fails the cut, also when it is all the batch has left, and so does a unit on the batch that carries only part of its original, whatever its label. A cut that passes says so. Without `--cut`, as the scheduled run uses it, a change on the open batch pull request counts as carried.
|
||||
|
||||
### The line's record and reports
|
||||
|
||||
What the batch decided about a line, the conflicts it deferred, the originals taken out with `--defer` and those waiting for a maintainer, is kept in a `backport-batch` block in the body of the line's newest batch pull request, its record. `backport-batch` reads the record whether that pull request is open, merged or closed, and writes it only while the pull request is open: a merged or closed batch pull request is never edited or commented on again. So a conflict the batch deferred is still a warning in `check` after the batch merged, until a later batch tries it again. A run that picks nothing while no batch is open writes nothing, and says so. A record `backport-batch` cannot read, or one written by someone it does not trust, stops it rather than let it fall back to an older one; how it decides is in [its README](../../cmd/backport-batch/README.md#the-lines-record-and-reports).
|
||||
|
||||
Each run also reports where every pull request merged into `main` since the line branched stands, and what it read to decide. The body carries the latest report under the record, and a comment the tool posts on the open batch pull request keeps each one, so an earlier classification is still there after a later run replaced the body, and after the batch merged. Each drop in a report keeps its reason and the merge commit it is bound to. `./backport-batch report --pr <batch>` prints the report the body carries, and `--id <id>` an earlier one; it writes nothing and never fetches, and reads GitHub and, for a report that keeps drops, the clone's history at the heads the report was made from. A run that picks nothing while no batch is open has nowhere to keep its report: the next batch's report has the line's state.
|
||||
|
||||
### Changes to workflows
|
||||
|
||||
The scheduled run's token may not push a commit that changes `.github/workflows/`, so the scheduled run leaves such an original out (`run --no-workflow-files`). The batch pull request lists it under "Waiting for a maintainer", with the workflow files it changes, and so does the batch's comment. It is no conflict. The policy still takes it: `check` warns about it while it waits, and `check --cut` fails on it. When nothing else is picked there is no batch pull request to list it on, and `check` reports it as missing.
|
||||
The scheduled run's token may not push a commit that changes `.github/workflows/`, so the scheduled run leaves such an original out (`run --no-workflow-files`). That holds also for one whose only missing dependency that never comes is a test or documentation, which a maintainer's run, with the token that may push the workflow, parks instead: what lands of it then is a pull request of its own; `check` reads which of the two the open batch was assembled as from its record, and with no batch open takes the scheduled run's. The batch pull request lists it under "Waiting for a maintainer", with the workflow files it changes, and so does the batch's comment. It is no conflict. The policy still takes it: `check` warns about it while it waits, and `check --cut` fails on it. When nothing else is picked there is no batch pull request to list it on, and `check` reports it as missing.
|
||||
|
||||
A maintainer brings it over with their own token, one that may push workflow changes (the Workflows permission, or the classic `workflow` scope), by continuing the open batch without the flag:
|
||||
|
||||
@@ -101,7 +117,7 @@ That picks it onto the batch in the batch's shape, after what the batch carries,
|
||||
|
||||
### The scheduled run
|
||||
|
||||
[`backport-batch.yaml`](../../.github/workflows/backport-batch.yaml) runs [`hack/backport-batch-scheduled.sh`](../../hack/backport-batch-scheduled.sh) on Monday and Thursday. For each line the batch runs for, newest first, it continues the open batch pull request or opens one, runs `check`, and then `backport-batch notify`, which reports what waits on the batch. A batch open for three days or more, so one the previous run already saw, gets a comment on its pull request saying so and a line in the run's summary. The comment is one per pull request, updated in place on every run. It also lists the deferred conflicts, which a maintainer resolves as [resolving a conflict](./backport-tasks/resolve-conflict.md) describes, and the originals that wait because they change workflows. A failed batch CI waits for a maintainer too, as [attributing a failed batch CI](./backport-tasks/failed-ci.md) describes; the comment does not list it, and it shows on the batch pull request's checks. `hack/backport-batch-scheduled.sh --dry-run` does the same in the current worktree and changes nothing on GitHub. Its `check` sees the line without the batch the dry run just built, so it can exit 1 where the real run's check passes.
|
||||
[`backport-batch.yaml`](../../.github/workflows/backport-batch.yaml) runs [`hack/backport-batch-scheduled.sh`](../../hack/backport-batch-scheduled.sh) on Monday and Thursday. For each line the batch runs for, newest first, it continues the open batch pull request or opens one, runs `check`, and then `backport-batch notify`, which reports what waits on the batch. A batch open for three days or more, so one the previous run already saw, gets a comment on its pull request saying so and a line in the run's summary. The comment is one per pull request, updated in place on every run. It also lists the deferred conflicts, which a maintainer resolves as [resolving a conflict](./backport-tasks/resolve-conflict.md) describes, and the originals that wait because they change workflows, and names each parked original once: a park named on one batch is not named again on the next while it stays the same park, and with no batch open nothing is named until the next batch opens. A failed batch CI waits for a maintainer too, as [attributing a failed batch CI](./backport-tasks/failed-ci.md) describes; the comment does not list it, and it shows on the batch pull request's checks. `hack/backport-batch-scheduled.sh --dry-run` does the same in the current worktree and changes nothing on GitHub. Its `check` sees the line without the batch the dry run just built, so it can exit 1 where the real run's check passes.
|
||||
|
||||
The batch runs as the cozystack-ci GitHub App, which the release workflows already use, and needs no secret of its own. The job mints a token from `COZYSTACK_CI_APP_ID` and `COZYSTACK_CI_PRIVATE_KEY` for this repository alone, with Contents and Pull requests write and nothing more, and fails when either secret is missing. Its pushes start CI on the batch pull request, which a push with the job's own `GITHUB_TOKEN` would not. Its commits carry the App's bot, `cozystack-ci[bot]`, whose batch pull request and comment `backport-batch` trusts: `BACKPORT_BATCH_BOT`, which the job sets from the token, names it, and a run without the variable trusts `cozystack-ci[bot]` too. The App's installation has to grant this repository Contents and Pull requests read and write, which an organization admin sees among the organization's installed GitHub Apps. It has no Workflows permission, so a change to `.github/workflows/` waits for a maintainer, as [changes to workflows](#changes-to-workflows) describes.
|
||||
|
||||
|
||||
@@ -71,9 +71,6 @@ The script:
|
||||
had already replayed. The Pod log names each topic before its replay and
|
||||
again once it landed; empty or delete every topic it shows as started, not
|
||||
only the one the refusal names, then re-run.
|
||||
- The tarball in object storage is not managed by the Cozystack `Backup`
|
||||
lifecycle: deleting the `Backup` CR removes the reference but leaves the S3
|
||||
object in place. Tenants who need to reclaim space should delete the object
|
||||
(or set a bucket lifecycle policy).
|
||||
- The tarball in object storage is not managed by the Cozystack `Backup` lifecycle: deleting the `Backup` CR removes the reference but leaves the S3 object in place. Tenants who need to reclaim space should delete the object, or set a lifecycle rule on the bucket. A Simple or MultiZone Cozystack SeaweedFS applies such rules once a day only while its `lifecycle.enabled` is on, which is not the default; a Client instance applies none itself, so the SeaweedFS it connects to must have `lifecycle.enabled` on. Another object store applies them only if it implements bucket lifecycle.
|
||||
- Consumer-group offsets, topic configs, ACLs and users are not part of the
|
||||
backup; consumers start from the restored topic's fresh offsets.
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/bin/bash
|
||||
# Shared helpers for the tenant Kubernetes backup/restore walkthrough.
|
||||
# Source this file in other scripts: source "$(dirname "$0")/00-helpers.sh"
|
||||
|
||||
export RED='\033[0;31m'
|
||||
export GREEN='\033[0;32m'
|
||||
export YELLOW='\033[1;33m'
|
||||
export BLUE='\033[0;34m'
|
||||
export MAGENTA='\033[0;35m'
|
||||
export CYAN='\033[0;36m'
|
||||
export NC='\033[0m'
|
||||
export BOLD='\033[1m'
|
||||
|
||||
export NAMESPACE="${NAMESPACE:-tenant-root}"
|
||||
export CLUSTER_NAME="${CLUSTER_NAME:-backup-demo}"
|
||||
export POOL_NAME="${POOL_NAME:-md0}"
|
||||
export WORKER_DISK_SIZE="${WORKER_DISK_SIZE:-20Gi}"
|
||||
export BACKUPCLASS_NAME="${BACKUPCLASS_NAME:-cozy-default}"
|
||||
export BACKUPJOB_NAME="${BACKUPJOB_NAME:-kubernetes-backup-job}"
|
||||
export RESTOREJOB_INPLACE_NAME="${RESTOREJOB_INPLACE_NAME:-kubernetes-restore-inplace}"
|
||||
export RESTOREJOB_RECREATE_NAME="${RESTOREJOB_RECREATE_NAME:-kubernetes-restore-recreate}"
|
||||
export TENANT_API_PORT="${TENANT_API_PORT:-16443}"
|
||||
export MARKER_VALUE="${MARKER_VALUE:-roundtrip-7c2e91d4}"
|
||||
export RELEASE="kubernetes-${CLUSTER_NAME}"
|
||||
|
||||
log_info() { echo -e "${BLUE}i${NC} $*" >&2; }
|
||||
log_success() { echo -e "${GREEN}OK${NC} $*" >&2; }
|
||||
log_warning() { echo -e "${YELLOW}!${NC} $*" >&2; }
|
||||
log_error() { echo -e "${RED}x${NC} $*" >&2; }
|
||||
log_substep() { echo -e "${CYAN} -> $*${NC}" >&2; }
|
||||
|
||||
print_header() {
|
||||
echo -e "\n${MAGENTA}${BOLD}== $1 ==${NC}\n" >&2
|
||||
}
|
||||
|
||||
# shellcheck source-path=SCRIPTDIR source=../_lib/wait-helpers.sh
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh"
|
||||
|
||||
# The admin kubeconfig points at the in-cluster Service, so the walkthrough
|
||||
# reaches the tenant API through a port-forward to it and keeps the TLS server
|
||||
# name the certificate is issued for.
|
||||
TENANT_KUBECONFIG="$(dirname "${BASH_SOURCE[0]}")/.tenant-kubeconfig"
|
||||
export TENANT_KUBECONFIG
|
||||
|
||||
tenant_connect() {
|
||||
kubectl -n "$NAMESPACE" get secret "${RELEASE}-admin-kubeconfig" \
|
||||
-o jsonpath='{.data.super-admin\.svc}' | base64 -d > "$TENANT_KUBECONFIG"
|
||||
chmod 600 "$TENANT_KUBECONFIG"
|
||||
local cluster
|
||||
cluster=$(kubectl --kubeconfig "$TENANT_KUBECONFIG" config view -o jsonpath='{.clusters[0].name}')
|
||||
kubectl --kubeconfig "$TENANT_KUBECONFIG" config set-cluster "$cluster" \
|
||||
--server="https://127.0.0.1:${TENANT_API_PORT}" \
|
||||
--tls-server-name="${RELEASE}.${NAMESPACE}.svc" >/dev/null
|
||||
pkill -f "port-forward svc/${RELEASE} ${TENANT_API_PORT}:6443" 2>/dev/null || true
|
||||
kubectl -n "$NAMESPACE" port-forward "svc/${RELEASE}" "${TENANT_API_PORT}:6443" >/dev/null 2>&1 &
|
||||
for _ in $(seq 1 30); do
|
||||
tkubectl get --raw /readyz >/dev/null 2>&1 && return 0
|
||||
sleep 2
|
||||
done
|
||||
log_error "tenant API of ${RELEASE} is not reachable through the port-forward"
|
||||
return 1
|
||||
}
|
||||
|
||||
tenant_disconnect() {
|
||||
pkill -f "port-forward svc/${RELEASE} ${TENANT_API_PORT}:6443" 2>/dev/null || true
|
||||
}
|
||||
|
||||
tkubectl() {
|
||||
kubectl --kubeconfig "$TENANT_KUBECONFIG" "$@"
|
||||
}
|
||||
|
||||
# The CA fingerprint is what proves a restore brought back the cluster rather
|
||||
# than a new one: nodes, kubeconfigs and tokens all trust this CA.
|
||||
cluster_ca_fingerprint() {
|
||||
kubectl -n "$NAMESPACE" get secret "${RELEASE}-ca" -o jsonpath='{.data.ca\.crt}' \
|
||||
| base64 -d | openssl x509 -noout -fingerprint -sha256 | cut -d= -f2
|
||||
}
|
||||
|
||||
# wait_tenant_marker checks both halves of the backup: the ConfigMap comes back
|
||||
# with etcd, the file on the PVC with the volumes.
|
||||
wait_tenant_marker() {
|
||||
local timeout="${1:-900}" elapsed=0 cm data
|
||||
while true; do
|
||||
cm=$(tkubectl -n demo get configmap marker -o jsonpath='{.data.marker}' 2>/dev/null || true)
|
||||
data=$(tkubectl -n demo exec deploy/writer -- cat /data/marker 2>/dev/null || true)
|
||||
if [[ "$cm" == "$MARKER_VALUE" && "$data" == "$MARKER_VALUE" ]]; then
|
||||
log_success "marker present in etcd (ConfigMap) and on the volume"
|
||||
return 0
|
||||
fi
|
||||
(( elapsed >= timeout )) && { log_error "marker not restored: configmap='${cm}' volume='${data}'"; return 1; }
|
||||
sleep 10
|
||||
elapsed=$((elapsed + 10))
|
||||
done
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#!/bin/bash
|
||||
# Step 01: Create a tenant Kubernetes cluster with one worker pool and seed it
|
||||
# with a marker held in etcd (a ConfigMap) and on a PersistentVolume.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/00-helpers.sh"
|
||||
|
||||
print_header "Step 01: Create Kubernetes '${CLUSTER_NAME}' and seed a marker"
|
||||
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: apps.cozystack.io/v1alpha1
|
||||
kind: Kubernetes
|
||||
metadata:
|
||||
name: ${CLUSTER_NAME}
|
||||
namespace: ${NAMESPACE}
|
||||
spec:
|
||||
storageClass: replicated
|
||||
---
|
||||
apiVersion: apps.cozystack.io/v1alpha1
|
||||
kind: KubernetesNodes
|
||||
metadata:
|
||||
name: ${CLUSTER_NAME}-${POOL_NAME}
|
||||
namespace: ${NAMESPACE}
|
||||
spec:
|
||||
cluster: ${CLUSTER_NAME}
|
||||
minReplicas: 1
|
||||
maxReplicas: 1
|
||||
instanceType: u1.medium
|
||||
diskSize: ${WORKER_DISK_SIZE}
|
||||
EOF
|
||||
|
||||
wait_hr_ready "$RELEASE" 1200
|
||||
log_substep "Waiting for the worker node to join..."
|
||||
tenant_connect
|
||||
kubectl_ok=0
|
||||
for _ in $(seq 1 120); do
|
||||
if tkubectl wait --for=condition=Ready node --all --timeout=10s >/dev/null 2>&1 \
|
||||
&& [[ -n "$(tkubectl get nodes -o name)" ]] \
|
||||
&& [[ -n "$(tkubectl get storageclass -o name)" ]]; then
|
||||
kubectl_ok=1
|
||||
break
|
||||
fi
|
||||
sleep 15
|
||||
done
|
||||
(( kubectl_ok )) || { log_error "worker node or StorageClass did not appear"; exit 1; }
|
||||
|
||||
tkubectl apply -f - <<EOF
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: demo
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: marker
|
||||
namespace: demo
|
||||
data:
|
||||
marker: ${MARKER_VALUE}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: data
|
||||
namespace: demo
|
||||
spec:
|
||||
accessModes: [ReadWriteOnce]
|
||||
resources:
|
||||
requests:
|
||||
storage: 1Gi
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: writer
|
||||
namespace: demo
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: writer}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: writer}
|
||||
spec:
|
||||
containers:
|
||||
- name: writer
|
||||
image: busybox:1.36
|
||||
command: ["sh", "-c", "[ -f /data/marker ] || echo -n ${MARKER_VALUE} > /data/marker; sync; sleep infinity"]
|
||||
volumeMounts:
|
||||
- {name: data, mountPath: /data}
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim: {claimName: data}
|
||||
EOF
|
||||
|
||||
wait_tenant_marker 900
|
||||
cluster_ca_fingerprint > "$SCRIPT_DIR/.ca-fingerprint"
|
||||
log_success "cluster CA $(cat "$SCRIPT_DIR/.ca-fingerprint")"
|
||||
tenant_disconnect
|
||||
|
||||
echo -e "\n${GREEN}${BOLD}Next:${NC} ./02-create-backupjob.sh"
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
#!/bin/bash
|
||||
# Step 02: Back the cluster up through the cozy-default BackupClass. The
|
||||
# controller dumps the cluster's etcd prefix to the platform bucket with a
|
||||
# Job, then backs up its control-plane Secrets and volumes with Velero.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/00-helpers.sh"
|
||||
|
||||
print_header "Step 02: Create BackupJob '${BACKUPJOB_NAME}'"
|
||||
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: backups.cozystack.io/v1alpha1
|
||||
kind: BackupJob
|
||||
metadata:
|
||||
name: ${BACKUPJOB_NAME}
|
||||
namespace: ${NAMESPACE}
|
||||
spec:
|
||||
applicationRef:
|
||||
apiGroup: apps.cozystack.io
|
||||
kind: Kubernetes
|
||||
name: ${CLUSTER_NAME}
|
||||
backupClassName: ${BACKUPCLASS_NAME}
|
||||
EOF
|
||||
|
||||
wait_for_field backupjob "$BACKUPJOB_NAME" '{.status.phase}' Succeeded "$NAMESPACE" 1800 Failed
|
||||
|
||||
warn=$(kubectl -n "$NAMESPACE" get backupjob "$BACKUPJOB_NAME" \
|
||||
-o jsonpath='{.status.conditions[?(@.type=="CertificatesExpiring")].status}')
|
||||
if [[ "$warn" == "True" ]]; then
|
||||
log_warning "$(kubectl -n "$NAMESPACE" get backupjob "$BACKUPJOB_NAME" \
|
||||
-o jsonpath='{.status.conditions[?(@.type=="CertificatesExpiring")].message}')"
|
||||
fi
|
||||
log_success "Backup '$(kubectl -n "$NAMESPACE" get backupjob "$BACKUPJOB_NAME" -o jsonpath='{.status.backupRef.name}')' is Ready."
|
||||
|
||||
echo -e "\n${GREEN}${BOLD}Next:${NC} ./03-restore-in-place.sh"
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/bash
|
||||
# Step 03: Lose the demo namespace inside the live cluster and roll the cluster
|
||||
# back. The restore stops the control plane and the workers, writes the etcd
|
||||
# prefix and the volumes back, and returns the cluster to its replica counts.
|
||||
# Set RESTORE_OPTIONS='{"volumes":false}' (or '{"etcd":false}') to restore one
|
||||
# half only.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/00-helpers.sh"
|
||||
|
||||
print_header "Step 03: Restore '${CLUSTER_NAME}' in place"
|
||||
|
||||
tenant_connect
|
||||
log_substep "Deleting namespace demo inside the tenant cluster..."
|
||||
tkubectl delete namespace demo --wait=true --timeout=10m
|
||||
tenant_disconnect
|
||||
|
||||
backup_ref=$(kubectl -n "$NAMESPACE" get backupjob "$BACKUPJOB_NAME" -o jsonpath='{.status.backupRef.name}')
|
||||
options="${RESTORE_OPTIONS:-}"
|
||||
[[ -n "$options" ]] || options='{}'
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: backups.cozystack.io/v1alpha1
|
||||
kind: RestoreJob
|
||||
metadata:
|
||||
name: ${RESTOREJOB_INPLACE_NAME}
|
||||
namespace: ${NAMESPACE}
|
||||
spec:
|
||||
backupRef:
|
||||
name: ${backup_ref}
|
||||
options: ${options}
|
||||
EOF
|
||||
|
||||
wait_for_field restorejob "$RESTOREJOB_INPLACE_NAME" '{.status.phase}' Succeeded "$NAMESPACE" 2400 Failed
|
||||
wait_hr_ready "$RELEASE" 1200
|
||||
|
||||
tenant_connect
|
||||
wait_tenant_marker 1200
|
||||
[[ "$(cluster_ca_fingerprint)" == "$(cat "$SCRIPT_DIR/.ca-fingerprint")" ]] \
|
||||
|| { log_error "cluster CA changed across the restore"; exit 1; }
|
||||
log_success "same cluster CA, marker back in etcd and on the volume"
|
||||
tenant_disconnect
|
||||
|
||||
echo -e "\n${GREEN}${BOLD}Next:${NC} ./04-restore-after-delete.sh"
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
# Step 04: Delete the Kubernetes application and its worker pool, which also
|
||||
# deletes the cluster's etcd prefix and volumes, then rebuild it from the
|
||||
# backup under the same name and CA.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/00-helpers.sh"
|
||||
|
||||
print_header "Step 04: Delete '${CLUSTER_NAME}' and rebuild it from the backup"
|
||||
|
||||
kubectl -n "$NAMESPACE" delete kubernetesnodeses.apps.cozystack.io "${CLUSTER_NAME}-${POOL_NAME}" --ignore-not-found --wait=false
|
||||
kubectl -n "$NAMESPACE" delete kuberneteses.apps.cozystack.io "$CLUSTER_NAME" --wait=false
|
||||
wait_deleted helmrelease "$RELEASE" "$NAMESPACE" 1200
|
||||
wait_deleted tenantcontrolplane "$RELEASE" "$NAMESPACE" 600
|
||||
log_substep "Removing what the application's deletion leaves behind, so the rebuild proves itself..."
|
||||
kubectl -n "$NAMESPACE" delete secret "${RELEASE}-talos-ca" "${RELEASE}-talos-tls-cert" "${RELEASE}-admin-kubeconfig" --ignore-not-found
|
||||
|
||||
backup_ref=$(kubectl -n "$NAMESPACE" get backupjob "$BACKUPJOB_NAME" -o jsonpath='{.status.backupRef.name}')
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: backups.cozystack.io/v1alpha1
|
||||
kind: RestoreJob
|
||||
metadata:
|
||||
name: ${RESTOREJOB_RECREATE_NAME}
|
||||
namespace: ${NAMESPACE}
|
||||
spec:
|
||||
backupRef:
|
||||
name: ${backup_ref}
|
||||
EOF
|
||||
|
||||
wait_for_field restorejob "$RESTOREJOB_RECREATE_NAME" '{.status.phase}' Succeeded "$NAMESPACE" 2400 Failed
|
||||
wait_hr_ready "$RELEASE" 1200
|
||||
|
||||
tenant_connect
|
||||
wait_tenant_marker 1500
|
||||
[[ "$(cluster_ca_fingerprint)" == "$(cat "$SCRIPT_DIR/.ca-fingerprint")" ]] \
|
||||
|| { log_error "cluster CA changed across the rebuild"; exit 1; }
|
||||
log_success "cluster rebuilt with the same CA, marker back in etcd and on the volume"
|
||||
tenant_disconnect
|
||||
@@ -0,0 +1,68 @@
|
||||
# Tenant Kubernetes backup and restore
|
||||
|
||||
The `Kubernetes` strategy backs up a tenant Kubernetes application in two halves, taken one after the other, so a backup is crash-consistent at best:
|
||||
|
||||
- **etcd**: a Job dumps the cluster's key prefix from the tenant's etcd DataStore to the platform bucket. This is the cluster's API state.
|
||||
- **Velero**: the control-plane and Talos PKI Secrets, and the DataVolumes and PVCs that back the cluster's PersistentVolumes. Worker system disks are left out; workers are recreated and join with the restored PKI.
|
||||
|
||||
The Backup also records the HelmReleases of the cluster and of its worker pools. A backup warns, through a `CertificatesExpiring` condition on the BackupJob, when a control-plane CA expires before the backup's TTL runs out or a leaf certificate expires within `certificateWarningThreshold` (720h).
|
||||
|
||||
## Admin: prepare
|
||||
|
||||
Nothing to do when the platform default backups are on: `cozy-default` routes `Kubernetes` to the `cozy-default-kubernetes` strategy.
|
||||
|
||||
## User: back up
|
||||
|
||||
```yaml
|
||||
apiVersion: backups.cozystack.io/v1alpha1
|
||||
kind: BackupJob
|
||||
metadata:
|
||||
name: my-cluster-backup
|
||||
namespace: tenant-foo
|
||||
spec:
|
||||
applicationRef:
|
||||
apiGroup: apps.cozystack.io
|
||||
kind: Kubernetes
|
||||
name: my-cluster
|
||||
backupClassName: cozy-default
|
||||
```
|
||||
|
||||
A `Plan` with the same `applicationRef` schedules it.
|
||||
|
||||
## User: restore
|
||||
|
||||
A restore always goes into the application the backup was taken from.
|
||||
|
||||
```yaml
|
||||
apiVersion: backups.cozystack.io/v1alpha1
|
||||
kind: RestoreJob
|
||||
metadata:
|
||||
name: my-cluster-restore
|
||||
namespace: tenant-foo
|
||||
spec:
|
||||
backupRef:
|
||||
name: my-cluster-backup
|
||||
options:
|
||||
etcd: true # restore the API state (default)
|
||||
volumes: true # restore the PersistentVolume data (default)
|
||||
```
|
||||
|
||||
- **Cluster deleted**: the restore rebuilds it. It restores the PKI Secrets and the volumes, recreates the cluster, writes the etcd state under the new control plane's prefix, and then recreates the worker pools, so the cluster comes back on its old state and its old CA. The cluster and pool HelmReleases are recreated with the spec recorded at backup time, so a backup taken before a platform upgrade that changed the application's values brings back the older values, which the upgraded chart may need migrated by hand.
|
||||
- **Cluster live**: the restore rolls it back. It must be the cluster the backup was taken from: one deleted and created again under the same name has a new CA and service-account key, so the restore refuses it, and the way back to the backed-up cluster is to delete the application and run the restore again as a rebuild. It suspends the cluster's HelmReleases, stops the workers and the cluster-autoscaler when `volumes` are restored and then the control plane when `etcd` is, writes the selected halves back, and returns every replica count it changed. Workers are recreated, so expect the tenant's Pods to restart. Deleting the RestoreJob midway also returns the replica counts, unless its etcd write is under way.
|
||||
|
||||
Nothing is changed until the restore has confirmed that the backup's Velero half and etcd dump exist. If the etcd write fails partway, the control plane stays stopped and the RestoreJob points at the copy of the prefix it saved before writing; run a new RestoreJob to retry.
|
||||
|
||||
Restoring only one half leaves the other as it is now: `etcd` alone keeps the current volume contents, `volumes` alone keeps the current API objects.
|
||||
|
||||
The two halves differ in what a failed restore leaves behind. The etcd half saves the current prefix before it writes and can be retried from that copy. The volume half has no such copy: Velero cannot overwrite an existing claim, so a live-cluster restore deletes the current DataVolumes and PVCs before it restores them, and if the Velero restore then fails, the volume data exists only in the backup.
|
||||
|
||||
The etcd round trip scales with the number of keys under the cluster's prefix. The backup Job holds the whole dump in memory while it checks it, and the restore writes one key per `etcdctl` call: on a test cluster a 441-key restore took about 40 seconds including Pod start. At that rate the default `kubernetesBackupActiveDeadlineSeconds` (1h) covers a prefix of a few tens of thousands of keys. For a cluster with a larger API state, raise it together with the memory limit in `kubernetesBackupResources`.
|
||||
|
||||
## Walkthrough
|
||||
|
||||
```bash
|
||||
./run-all.sh # create, back up, roll back in place, rebuild after delete
|
||||
./cleanup.sh
|
||||
```
|
||||
|
||||
`NAMESPACE`, `CLUSTER_NAME` and `WORKER_DISK_SIZE` are read from the environment; see `00-helpers.sh`.
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/bash
|
||||
# Remove everything the walkthrough created. Deleting the BackupJob's Backup
|
||||
# removes its Velero backup and its etcd dump object.
|
||||
set -uo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/00-helpers.sh"
|
||||
|
||||
print_header "Cleanup"
|
||||
tenant_disconnect
|
||||
kubectl -n "$NAMESPACE" delete restorejob "$RESTOREJOB_INPLACE_NAME" "$RESTOREJOB_RECREATE_NAME" --ignore-not-found
|
||||
backup_ref=$(kubectl -n "$NAMESPACE" get backupjob "$BACKUPJOB_NAME" -o jsonpath='{.status.backupRef.name}' 2>/dev/null || true)
|
||||
kubectl -n "$NAMESPACE" delete backupjob "$BACKUPJOB_NAME" --ignore-not-found
|
||||
[[ -n "$backup_ref" ]] && kubectl -n "$NAMESPACE" delete backup "$backup_ref" --ignore-not-found
|
||||
kubectl -n "$NAMESPACE" delete kubernetesnodeses.apps.cozystack.io "${CLUSTER_NAME}-${POOL_NAME}" --ignore-not-found
|
||||
kubectl -n "$NAMESPACE" delete kuberneteses.apps.cozystack.io "$CLUSTER_NAME" --ignore-not-found
|
||||
rm -f "$TENANT_KUBECONFIG" "$SCRIPT_DIR/.ca-fingerprint"
|
||||
log_success "done"
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# End-to-end tenant Kubernetes backup/restore walkthrough. It proves the
|
||||
# restore brings back the same cluster: the CA fingerprint is unchanged, and a
|
||||
# marker kept in etcd and one kept on a PersistentVolume both come back, first
|
||||
# after rolling a live cluster back, then after rebuilding a deleted one.
|
||||
#
|
||||
# Needs the platform default backups (backupstrategy-controller with a Velero
|
||||
# BSL and the system bucket), so cozy-default routes Kubernetes to
|
||||
# cozy-default-kubernetes.
|
||||
#
|
||||
# Env knobs: see 00-helpers.sh. SKIP_RESTORE=1 stops after the backup.
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/00-helpers.sh"
|
||||
|
||||
kubectl wait --for=create kubernetes.strategy.backups.cozystack.io/cozy-default-kubernetes --timeout=15m >/dev/null \
|
||||
|| { log_error "cozy-default-kubernetes strategy is missing: enable the platform default backups first"; exit 1; }
|
||||
|
||||
steps=(01 02 03 04)
|
||||
[[ "${SKIP_RESTORE:-0}" == "1" ]] && steps=(01 02)
|
||||
for step in "${steps[@]}"; do
|
||||
script="$(find "$SCRIPT_DIR" -maxdepth 1 -type f -name "${step}-*.sh" | sort | head -n1)"
|
||||
[[ -n "$script" ]] || { echo "no script found for step $step" >&2; exit 1; }
|
||||
echo "=== Running $(basename "$script") ==="
|
||||
bash "$script"
|
||||
done
|
||||
|
||||
print_header "Walkthrough complete"
|
||||
@@ -55,9 +55,6 @@ The script:
|
||||
|
||||
- Both flows rely on the strategy template branching on `.Mode`. See
|
||||
`01-create-strategy.sh`.
|
||||
- The tarball in object storage is not managed by the Cozystack `Backup`
|
||||
lifecycle: deleting the `Backup` CR removes the reference but leaves the S3
|
||||
object in place. Tenants who need to reclaim space should delete the object
|
||||
(or set a bucket lifecycle policy).
|
||||
- The tarball in object storage is not managed by the Cozystack `Backup` lifecycle: deleting the `Backup` CR removes the reference but leaves the S3 object in place. Tenants who need to reclaim space should delete the object, or set a lifecycle rule on the bucket. A Simple or MultiZone Cozystack SeaweedFS applies such rules once a day only while its `lifecycle.enabled` is on, which is not the default; a Client instance applies none itself, so the SeaweedFS it connects to must have `lifecycle.enabled` on. Another object store applies them only if it implements bucket lifecycle.
|
||||
- `nats stream restore` recreates the stream's configuration from the snapshot;
|
||||
consumers are restored as captured at backup time.
|
||||
@@ -16,6 +16,7 @@ require (
|
||||
github.com/go-logr/logr v1.4.4
|
||||
github.com/go-logr/zapr v1.3.0
|
||||
github.com/go-task/slim-sprig/v3 v3.0.0
|
||||
github.com/google/cel-go v0.29.2
|
||||
github.com/minio/minio-go/v7 v7.0.98
|
||||
github.com/onsi/ginkgo/v2 v2.33.0
|
||||
github.com/onsi/gomega v1.43.1
|
||||
@@ -83,7 +84,6 @@ require (
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.8.0 // indirect
|
||||
github.com/go-openapi/testify/v2 v2.8.0 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/google/cel-go v0.29.2 // indirect
|
||||
github.com/google/gnostic-models v0.7.1 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/pprof v0.0.0-20260906184651-6331bc6350fe // indirect
|
||||
|
||||
+422
-109
@@ -1,14 +1,28 @@
|
||||
#!/usr/bin/env bats
|
||||
# Behavioural tests for the shipped Altinity (ClickHouse) backup/restore
|
||||
# strategy script, extracted from the rendered cozy-default-altinity Strategy
|
||||
# CR and EXECUTED against a stubbed clickhouse-backup HTTP API, with the real
|
||||
# jq doing the archive selection. Which archive a restore reads back is
|
||||
# decided by that selection over list/remote, so it is exercised against
|
||||
# several archives rather than string-matched.
|
||||
# Behavioural tests for the shipped ClickHouse (Altinity) strategy script,
|
||||
# extracted from the rendered cozy-default-altinity Strategy CR and EXECUTED
|
||||
# against a stubbed clickhouse-backup sidecar API.
|
||||
#
|
||||
# The script runs with `bash`, not `sh`, for the reason given in
|
||||
# hack/redis-backup-strategy.bats: it opens `set -euo pipefail`, which the
|
||||
# production image's busybox ash supports and the CI runner's dash rejects.
|
||||
# The contract pinned here is the start gate: the sidecar serialises its
|
||||
# operations and answers any new one with HTTP 423 while another is "in
|
||||
# progress", so a strategy Pod that starts its operation without waiting for
|
||||
# an idle sidecar burns a Job attempt in seconds. The gate has to fail the Pod
|
||||
# rather than proceed when the sidecar never becomes idle. Once started, an
|
||||
# operation the sidecar no longer lists (its action log lives in memory and a
|
||||
# restart empties it) has to fail the Pod too, since the Job has no deadline.
|
||||
# A Job retry must not start its operation twice: it takes over the
|
||||
# restore_remote, or the create_remote of the archive the controller named,
|
||||
# that the attempt before it left running, and a few lost polls do not end an
|
||||
# attempt in the first place.
|
||||
#
|
||||
# Which archive a restore reads back is decided by the script's own jq
|
||||
# selection over list/remote, so it is exercised against several archives
|
||||
# rather than string-matched: exactly the archive the Backup recorded, or for
|
||||
# a Backup that records none, the newest one stamped no later than its takenAt.
|
||||
#
|
||||
# Run from the repo root with make bats-unit-tests. The rendered script is run
|
||||
# with `bash`, not `sh`: it opens `set -euo pipefail`, which the production
|
||||
# image's busybox ash supports but the CI runner's /bin/sh (dash) rejects.
|
||||
|
||||
load test_helper
|
||||
|
||||
@@ -16,12 +30,13 @@ CHART=packages/system/backupstrategy-controller
|
||||
|
||||
# Render the shipped strategy's in-Pod script into $1 and substitute the
|
||||
# controller-render placeholders the way the driver fills them: $2 mode, $3
|
||||
# app (release and source application), $4 the archive name recorded on the
|
||||
# Backup (empty for a Backup that records none), $5 the Backup name, $6 its
|
||||
# takenAt in the archive-name layout. An empty render fails early, as does a
|
||||
# placeholder left unsubstituted.
|
||||
# app (release and source application), $4 the archive name the controller
|
||||
# chose or the Backup recorded (empty, the default, for none), $5 the Backup
|
||||
# name, $6 its takenAt in the archive-name layout (default: later than every
|
||||
# archive the stub lists). An empty render fails early, as does a placeholder
|
||||
# left unsubstituted: these tests EXECUTE it.
|
||||
render_script() {
|
||||
out=$1; mode=$2; app=$3; archive=$4; backup=$5; takenat=$6
|
||||
out=$1; mode=$2; app=$3; archive=${4-}; backup=${5-bkp}; takenat=${6-99991231T235959Z}
|
||||
helm template t "$CHART" -n cozy-backup-controller \
|
||||
--set backupStorage.bucketNameOverride=test-bucket 2>/dev/null \
|
||||
| yq eval 'select(.kind == "Altinity") | .spec.template.spec.containers[0].args[0]' - \
|
||||
@@ -39,56 +54,118 @@ render_script() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Stub the clickhouse-backup API behind curl, first on PATH. list/remote
|
||||
# serves $state/remote; actions serves $state/actions plus one success row per
|
||||
# operation the script has issued, and after its first read swaps in
|
||||
# $state/actions.next when a test seeds one (an operation that finishes while
|
||||
# the script waits). Every request is logged to $state/curl.log. sleep is
|
||||
# stubbed to fail after a few calls, so a script that never sees its
|
||||
# operation finish fails the test instead of hanging it.
|
||||
# A curl stub standing in for the sidecar API, put first on PATH next to a
|
||||
# no-op sleep. State lives in $1:
|
||||
# unreachable present: every request fails as a refused connection (7)
|
||||
# down a number: that many next requests fail the same way, as
|
||||
# before the sidecar has started
|
||||
# busy a number: that many GET /backup/actions answers still list
|
||||
# an operation of someone else "in progress"
|
||||
# op the command line of the sidecar's own operation, written
|
||||
# by an accepted POST the way the sidecar logs it ("--resume"
|
||||
# before the name of a create_remote asking for it), or
|
||||
# seeded by a test as the operation
|
||||
# an earlier attempt of the same Job started
|
||||
# op_left how many more GET /backup/actions answers list op as
|
||||
# "in progress" before it ends with op_result
|
||||
# op_duration op_left given to an operation a POST starts (default 0)
|
||||
# op_result the status op ends with (default success)
|
||||
# prior extra action-log rows, verbatim, older than op
|
||||
# remote present: the list/remote answer, verbatim, in place of the
|
||||
# one archive listed by default
|
||||
# restarted present: the action log no longer lists op, as after the
|
||||
# sidecar restarted and lost its in-memory log
|
||||
# fail_on_post a POST that is accepted makes that many following
|
||||
# GET /backup/actions requests fail (curl exit 7)
|
||||
# idle created by an answer that lists nothing in progress; a
|
||||
# POST is refused (423, curl -f exit 22) unless one was seen
|
||||
# since the last accepted POST, and while anything runs
|
||||
# accepted one line per POST the sidecar accepted
|
||||
# requests one line per request: method and URL
|
||||
# runaway created when the script exceeds 200 requests; that request
|
||||
# and every later one fails, so a polling loop that never ends
|
||||
# stops the test instead of hanging it
|
||||
make_stubs() {
|
||||
bin=$1; state=$2
|
||||
mkdir -p "$bin"
|
||||
: > "$state/remote"
|
||||
: > "$state/actions"
|
||||
mkdir -p "$bin" "$state"
|
||||
cat > "$bin/curl" <<STUB
|
||||
#!/usr/bin/env bash
|
||||
set -eu
|
||||
method=GET; url=""
|
||||
#!/bin/bash
|
||||
state="$state"
|
||||
method=GET
|
||||
url=
|
||||
prev=
|
||||
for a in "\$@"; do
|
||||
case "\$a" in POST) method=POST ;; http://*) url="\$a" ;; esac
|
||||
if [ "\$prev" = "-X" ]; then method=\$a; fi
|
||||
case "\$a" in http://*) url=\$a ;; esac
|
||||
prev=\$a
|
||||
done
|
||||
echo "\$method \$url" >> "$state/curl.log"
|
||||
echo "\$method \$url" >> "\$state/requests"
|
||||
if [ "\$(wc -l < "\$state/requests")" -gt 200 ]; then touch "\$state/runaway"; exit 7; fi
|
||||
if [ -e "\$state/unreachable" ]; then exit 7; fi
|
||||
num() { cat "\$state/\$1" 2>/dev/null || echo 0; }
|
||||
down=\$(num down)
|
||||
if [ "\$down" -gt 0 ]; then echo \$((down - 1)) > "\$state/down"; exit 7; fi
|
||||
running=0
|
||||
if [ -s "\$state/op" ] && [ ! -e "\$state/restarted" ] && [ "\$(num op_left)" -gt 0 ]; then running=1; fi
|
||||
case "\$method \$url" in
|
||||
"GET "*/backup/status) echo '{}' ;;
|
||||
"GET "*/backup/list/remote) cat "$state/remote" ;;
|
||||
"POST "*)
|
||||
if [ "\$(num busy)" -gt 0 ] || [ "\$running" = 1 ] || [ ! -e "\$state/idle" ]; then exit 22; fi
|
||||
case "\$url" in
|
||||
*/create_remote\?name=*)
|
||||
name=\${url#*name=}; name=\${name%%&*}
|
||||
case "\$url" in *[?\&]resume=true*) cmd="create_remote --resume \$name" ;; *) cmd="create_remote \$name" ;; esac
|
||||
;;
|
||||
*/restore_remote/*) cmd="restore_remote \${url##*/}" ;;
|
||||
*) exit 22 ;;
|
||||
esac
|
||||
echo "\$cmd" > "\$state/op"
|
||||
echo "\$cmd" >> "\$state/accepted"
|
||||
num op_duration > "\$state/op_left"
|
||||
num fail_on_post > "\$state/fail_polls"
|
||||
rm -f "\$state/idle"
|
||||
;;
|
||||
"GET "*/backup/actions)
|
||||
cat "$state/actions"
|
||||
if [ -f "$state/actions.done" ]; then cat "$state/actions.done"; fi
|
||||
if [ -f "$state/actions.next" ]; then mv "$state/actions.next" "$state/actions"; fi
|
||||
fail=\$(num fail_polls)
|
||||
if [ "\$fail" -gt 0 ]; then echo \$((fail - 1)) > "\$state/fail_polls"; exit 7; fi
|
||||
echo '{"command":"create_remote clickhouse-myapp-20260101T000000Z","status":"error","start":"2026-01-01 00:00:00","error":"old"}'
|
||||
cat "\$state/prior" 2>/dev/null || true
|
||||
inprog=0
|
||||
busy=\$(num busy)
|
||||
if [ "\$busy" -gt 0 ]; then
|
||||
echo \$((busy - 1)) > "\$state/busy"
|
||||
echo '{"command":"upload --resumable=1 clickhouse-myapp-20260101T000000Z","status":"in progress","start":"2026-01-01 00:01:00"}'
|
||||
inprog=1
|
||||
fi
|
||||
if [ -s "\$state/op" ] && [ ! -e "\$state/restarted" ]; then
|
||||
left=\$(num op_left)
|
||||
if [ "\$left" -gt 0 ]; then
|
||||
echo \$((left - 1)) > "\$state/op_left"
|
||||
status="in progress"
|
||||
inprog=1
|
||||
else
|
||||
status=\$(cat "\$state/op_result" 2>/dev/null || echo success)
|
||||
fi
|
||||
echo "{\"command\":\"\$(cat "\$state/op")\",\"status\":\"\$status\",\"start\":\"2026-01-01 00:02:00\",\"error\":\"boom\"}"
|
||||
fi
|
||||
if [ "\$inprog" = 0 ]; then touch "\$state/idle"; fi
|
||||
;;
|
||||
"POST "*/backup/create_remote*)
|
||||
name=\${url#*name=}; name=\${name%%&*}
|
||||
printf '{"command":"create_remote --resume %s","status":"success","start":"2099-01-01 00:00:00"}\n' "\$name" >> "$state/actions.done"
|
||||
"GET "*/backup/list/remote)
|
||||
if [ -e "\$state/remote" ]; then cat "\$state/remote"; else
|
||||
echo '{"name":"clickhouse-myapp-20260101T000000Z","created":"2026-01-01 00:00:00"}'
|
||||
fi
|
||||
;;
|
||||
"POST "*/backup/restore_remote/*)
|
||||
printf '{"command":"restore_remote %s","status":"success","start":"2099-01-01 00:00:00"}\n' "\${url##*/}" >> "$state/actions.done"
|
||||
;;
|
||||
*) echo "unexpected request: \$method \$url" >&2; exit 22 ;;
|
||||
esac
|
||||
exit 0
|
||||
STUB
|
||||
cat > "$bin/sleep" <<STUB
|
||||
#!/usr/bin/env bash
|
||||
n=\$(cat "$state/sleeps" 2>/dev/null || echo 0)
|
||||
echo \$((n + 1)) > "$state/sleeps"
|
||||
if [ "\$n" -ge 3 ]; then echo "sleep budget spent: the operation never finished" >&2; exit 1; fi
|
||||
cat > "$bin/sleep" <<'STUB'
|
||||
#!/bin/sh
|
||||
exit 0
|
||||
STUB
|
||||
chmod 0755 "$bin/curl" "$bin/sleep"
|
||||
export API_USERNAME=u API_PASSWORD=p
|
||||
}
|
||||
|
||||
# One list/remote row per argument, "name" or "name|desc"; created mirrors
|
||||
# the name's timestamp, which is the order the pre-fix selection sorted by.
|
||||
# the name's timestamp.
|
||||
remote_rows() {
|
||||
for row in "$@"; do
|
||||
name=${row%%|*}; desc="tar, regular"
|
||||
@@ -98,49 +175,216 @@ remote_rows() {
|
||||
done
|
||||
}
|
||||
|
||||
accepted() {
|
||||
if [ -e "$1/state/accepted" ]; then wc -l < "$1/state/accepted" | tr -d ' '; else echo 0; fi
|
||||
}
|
||||
|
||||
run_script() {
|
||||
tmp=$1
|
||||
API_USERNAME=u API_PASSWORD=p PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
|
||||
}
|
||||
|
||||
@test "an empty render fails the fixture instead of passing as a no-op" {
|
||||
tmp=$(mktemp -d)
|
||||
CHART=$tmp/no-such-chart
|
||||
if render_script "$tmp/s.sh" restore myapp "" bkp 20260304T050622Z 2>/dev/null; then
|
||||
if render_script "$tmp/s.sh" backup myapp 2>/dev/null; then
|
||||
echo "FAIL: render_script reported success with no chart"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "backup on an idle sidecar starts create_remote and waits for its success" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
render_script "$tmp/s.sh" backup myapp
|
||||
run_script "$tmp"
|
||||
grep -q '^POST .*/backup/create_remote?name=clickhouse-myapp-' "$tmp/state/requests"
|
||||
}
|
||||
|
||||
@test "backup waits until the running operation finishes before create_remote" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 3 > "$tmp/state/busy"
|
||||
render_script "$tmp/s.sh" backup myapp
|
||||
run_script "$tmp"
|
||||
grep -q '^create_remote --resume clickhouse-myapp-' "$tmp/state/accepted"
|
||||
[ "$(cat "$tmp/state/busy")" = 0 ]
|
||||
}
|
||||
|
||||
@test "restore on an idle sidecar starts restore_remote of the listed archive" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
run_script "$tmp"
|
||||
grep -q '^POST .*/backup/restore_remote/clickhouse-myapp-20260101T000000Z$' "$tmp/state/requests"
|
||||
}
|
||||
|
||||
@test "backup fails without starting create_remote when the sidecar stays busy" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 1000 > "$tmp/state/busy"
|
||||
render_script "$tmp/s.sh" backup myapp
|
||||
if run_script "$tmp"; then echo "FAIL: a busy sidecar must fail the Pod"; false; fi
|
||||
if grep -q '^POST ' "$tmp/state/requests"; then echo "FAIL: no operation may start on a busy sidecar"; false; fi
|
||||
}
|
||||
|
||||
@test "backup fails without starting create_remote when the sidecar never answers" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
touch "$tmp/state/unreachable"
|
||||
render_script "$tmp/s.sh" backup myapp
|
||||
if run_script "$tmp"; then echo "FAIL: an unreachable sidecar must fail the Pod"; false; fi
|
||||
if grep -q '^POST ' "$tmp/state/requests"; then echo "FAIL: no operation may start on an unreachable sidecar"; false; fi
|
||||
}
|
||||
|
||||
@test "restore fails without starting restore_remote when the sidecar never answers" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
touch "$tmp/state/unreachable"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
if run_script "$tmp" 2> "$tmp/err"; then echo "FAIL: an unreachable sidecar must fail the Pod"; false; fi
|
||||
if grep -q '^POST ' "$tmp/state/requests"; then echo "FAIL: no restore may start on an unreachable sidecar"; false; fi
|
||||
grep -q 'list/remote failed 60 times in a row' "$tmp/err"
|
||||
[ "$(grep -c '^GET .*/backup/list/remote$' "$tmp/state/requests")" = 60 ]
|
||||
}
|
||||
|
||||
@test "restore fails without starting restore_remote when the sidecar stays busy" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 1000 > "$tmp/state/busy"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
if run_script "$tmp"; then echo "FAIL: a busy sidecar must fail the Pod"; false; fi
|
||||
if grep -q '^POST ' "$tmp/state/requests"; then echo "FAIL: no restore may start on a busy sidecar"; false; fi
|
||||
}
|
||||
|
||||
@test "backup fails instead of polling forever when the sidecar restarts after create_remote" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
touch "$tmp/state/restarted"
|
||||
render_script "$tmp/s.sh" backup myapp
|
||||
if run_script "$tmp" 2> "$tmp/err"; then echo "FAIL: an operation lost from the action log must fail the Pod"; false; fi
|
||||
grep -q 'no longer in the sidecar action log' "$tmp/err"
|
||||
grep -q '^POST .*/backup/create_remote?name=clickhouse-myapp-' "$tmp/state/requests"
|
||||
if [ -e "$tmp/state/runaway" ]; then echo "FAIL: the script kept polling for an operation the sidecar no longer lists"; false; fi
|
||||
}
|
||||
|
||||
@test "restore waits for a sidecar that has not started yet" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 10 > "$tmp/state/down"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
run_script "$tmp"
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
}
|
||||
|
||||
@test "restore waits until another operation finishes, then starts its own" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 3 > "$tmp/state/busy"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
run_script "$tmp"
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
grep -qx 'restore_remote clickhouse-myapp-20260101T000000Z' "$tmp/state/accepted"
|
||||
}
|
||||
|
||||
@test "failed polls after restore_remote, short of six in a row, do not fail the attempt" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 3 > "$tmp/state/op_duration"
|
||||
echo 5 > "$tmp/state/fail_on_post"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
run_script "$tmp"
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
}
|
||||
|
||||
@test "a retry after an attempt lost its polls joins the running restore instead of starting another" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 20 > "$tmp/state/op_duration"
|
||||
echo 6 > "$tmp/state/fail_on_post"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
if run_script "$tmp"; then echo "FAIL: six failed polls in a row must fail the attempt"; false; fi
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
echo 0 > "$tmp/state/fail_polls"
|
||||
run_script "$tmp"
|
||||
if [ "$(accepted "$tmp")" != 1 ]; then echo "FAIL: the retry started restore_remote a second time"; false; fi
|
||||
[ "$(cat "$tmp/state/op_left")" = 0 ]
|
||||
}
|
||||
|
||||
@test "restore does not join an operation running on another archive" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 'restore_remote clickhouse-myapp-20251231T000000Z' > "$tmp/state/op"
|
||||
echo 3 > "$tmp/state/op_left"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
run_script "$tmp"
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
grep -qx 'restore_remote clickhouse-myapp-20260101T000000Z' "$tmp/state/accepted"
|
||||
}
|
||||
|
||||
# The sidecar never trims its action log, so a finished restore_remote row of
|
||||
# the same archive may belong to an earlier RestoreJob; only a running one may
|
||||
# be taken over.
|
||||
@test "restore starts restore_remote again when the log holds a finished one of the same archive" {
|
||||
for status in success error cancel; do
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo "{\"command\":\"restore_remote clickhouse-myapp-20260101T000000Z\",\"status\":\"$status\",\"start\":\"2026-01-01 00:01:30\"}" > "$tmp/state/prior"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
run_script "$tmp"
|
||||
if [ "$(accepted "$tmp")" != 1 ]; then echo "FAIL: a $status row of an earlier restore must not stand in for this one"; false; fi
|
||||
done
|
||||
}
|
||||
|
||||
@test "a restore that ends in error fails the Pod" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo error > "$tmp/state/op_result"
|
||||
render_script "$tmp/s.sh" restore myapp
|
||||
if run_script "$tmp"; then echo "FAIL: a failed restore must fail the Pod"; false; fi
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
}
|
||||
|
||||
@test "a cancelled backup fails the Pod instead of polling forever" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo cancel > "$tmp/state/op_result"
|
||||
render_script "$tmp/s.sh" backup myapp
|
||||
if run_script "$tmp"; then echo "FAIL: a cancelled operation must fail the Pod"; false; fi
|
||||
if [ -e "$tmp/state/runaway" ]; then echo "FAIL: the script kept polling a cancelled operation"; false; fi
|
||||
}
|
||||
|
||||
@test "restore reads back the archive the Backup recorded, not the newest one" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp"
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
render_script "$tmp/s.sh" restore myapp clickhouse-myapp-20260304T050607Z bkp-a 20260304T050622Z
|
||||
remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T050607Z \
|
||||
clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/remote"
|
||||
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
|
||||
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/curl.log"
|
||||
[ "$(grep -c '/backup/restore_remote/' "$tmp/curl.log")" -eq 1 ]
|
||||
rm -rf "$tmp"
|
||||
clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/state/remote"
|
||||
run_script "$tmp"
|
||||
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/state/requests"
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
}
|
||||
|
||||
@test "restore fails naming the recorded archive when remote storage lacks it" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp"
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
render_script "$tmp/s.sh" restore myapp clickhouse-myapp-20260304T050607Z bkp-a 20260304T050622Z
|
||||
remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T060000Z > "$tmp/remote"
|
||||
remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T060000Z > "$tmp/state/remote"
|
||||
out=""
|
||||
if out=$(PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" 2>&1); then
|
||||
if out=$(run_script "$tmp" 2>&1); then
|
||||
echo "FAIL: restore succeeded without the recorded archive: $out"
|
||||
false
|
||||
fi
|
||||
printf '%s\n' "$out" | grep -qF 'archive clickhouse-myapp-20260304T050607Z recorded on Backup bkp-a is not in remote storage'
|
||||
if grep -qF '/backup/restore_remote/' "$tmp/curl.log"; then
|
||||
echo "FAIL: restored another archive: $(cat "$tmp/curl.log")"
|
||||
if grep -qF '/backup/restore_remote/' "$tmp/state/requests"; then
|
||||
echo "FAIL: restored another archive: $(cat "$tmp/state/requests")"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "restore of a Backup without a recorded archive takes the newest one stamped by its takenAt, and warns" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp"
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
render_script "$tmp/s.sh" restore myapp "" bkp-a 20260304T050800Z
|
||||
# Each decoy sorts after the expected archive and is ruled out by one
|
||||
# filter: broken, not a bare timestamp after the prefix, or stamped after
|
||||
@@ -148,71 +392,140 @@ remote_rows() {
|
||||
remote_rows clickhouse-myapp-20260304T040000Z clickhouse-myapp-20260304T050607Z \
|
||||
"clickhouse-myapp-20260304T050700Z|broken (can't stat metadata.json)" \
|
||||
clickhouse-myapp-20260304T050710Z-copy \
|
||||
clickhouse-myapp-20260304T060000Z > "$tmp/remote"
|
||||
out=$(PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" 2>&1)
|
||||
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/curl.log"
|
||||
[ "$(grep -c '/backup/restore_remote/' "$tmp/curl.log")" -eq 1 ]
|
||||
myapp-20260304050720-0f3c9a1e5b7d \
|
||||
clickhouse-myapp-20260304T060000Z > "$tmp/state/remote"
|
||||
out=$(run_script "$tmp" 2>&1)
|
||||
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/restore_remote/clickhouse-myapp-20260304T050607Z' "$tmp/state/requests"
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
printf '%s\n' "$out" | grep -qF 'WARNING: Backup bkp-a records no archive name'
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "restore of a Backup without a recorded archive fails when no archive is stamped by its takenAt" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp"
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
render_script "$tmp/s.sh" restore myapp "" bkp-a 20260304T050800Z
|
||||
remote_rows clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/remote"
|
||||
remote_rows clickhouse-myapp-20260304T060000Z clickhouse-myapp-20260304T070000Z > "$tmp/state/remote"
|
||||
out=""
|
||||
if out=$(PATH="$tmp/bin:$PATH" bash "$tmp/s.sh" 2>&1); then
|
||||
if out=$(run_script "$tmp" 2>&1); then
|
||||
echo "FAIL: restore succeeded with every archive newer than takenAt: $out"
|
||||
false
|
||||
fi
|
||||
printf '%s\n' "$out" | grep -qF 'no archive of myapp stamped no later than 20260304T050800Z'
|
||||
if grep -qF '/backup/restore_remote/' "$tmp/curl.log"; then
|
||||
echo "FAIL: restored an archive newer than takenAt: $(cat "$tmp/curl.log")"
|
||||
if grep -qF '/backup/restore_remote/' "$tmp/state/requests"; then
|
||||
echo "FAIL: restored an archive newer than takenAt: $(cat "$tmp/state/requests")"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "backup writes the archive under the name the controller chose" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z "" ""
|
||||
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
|
||||
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/curl.log"
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "a retried backup waits on the attempt the sidecar is still running" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z "" ""
|
||||
printf '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"in progress","start":"2026-03-04 05:06:08"}\n' > "$tmp/actions"
|
||||
printf '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"success","start":"2026-03-04 05:06:08"}\n' > "$tmp/actions.next"
|
||||
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
|
||||
# The sidecar answers a second operation with 423 while one runs.
|
||||
if grep -qF 'POST ' "$tmp/curl.log"; then
|
||||
echo "FAIL: started another operation over the running one: $(cat "$tmp/curl.log")"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "a retried backup after a failed attempt resumes the same archive" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z "" ""
|
||||
printf '{"command":"create_remote clickhouse-myapp-20260304T050607Z","status":"error","start":"2026-03-04 05:06:08","error":"S3 PutObject 403"}\n' > "$tmp/actions"
|
||||
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
|
||||
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/curl.log"
|
||||
rm -rf "$tmp"
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z
|
||||
run_script "$tmp"
|
||||
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/state/requests"
|
||||
}
|
||||
|
||||
@test "backup falls back to a timestamped name when the controller supplies none" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp"
|
||||
render_script "$tmp/s.sh" backup myapp "" "" ""
|
||||
PATH="$tmp/bin:$PATH" bash "$tmp/s.sh"
|
||||
grep -qE '^POST http://[^ ]*/backup/create_remote\?name=clickhouse-myapp-[0-9]{8}T[0-9]{6}Z&resume=true$' "$tmp/curl.log"
|
||||
rm -rf "$tmp"
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
render_script "$tmp/s.sh" backup myapp ""
|
||||
run_script "$tmp"
|
||||
grep -qE '^POST http://[^ ]*/backup/create_remote\?name=clickhouse-myapp-[0-9]{8}T[0-9]{6}Z&resume=true$' "$tmp/state/requests"
|
||||
}
|
||||
|
||||
# The sidecar answers a second operation with 423 while one runs, so a retry
|
||||
# that POSTed over its predecessor's upload would burn every attempt left.
|
||||
@test "a retried backup takes over the upload of its archive the sidecar is still running" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 'create_remote --resume clickhouse-myapp-20260304T050607Z' > "$tmp/state/op"
|
||||
echo 3 > "$tmp/state/op_left"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z
|
||||
run_script "$tmp"
|
||||
if grep -q '^POST ' "$tmp/state/requests"; then
|
||||
echo "FAIL: started another operation over the running one: $(cat "$tmp/state/requests")"
|
||||
false
|
||||
fi
|
||||
[ "$(cat "$tmp/state/op_left")" = 0 ]
|
||||
}
|
||||
|
||||
@test "a taken-over backup that ends in error fails the Pod" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 'create_remote --resume clickhouse-myapp-20260304T050607Z' > "$tmp/state/op"
|
||||
echo 2 > "$tmp/state/op_left"
|
||||
echo error > "$tmp/state/op_result"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z
|
||||
if run_script "$tmp"; then echo "FAIL: a taken-over upload that failed must fail the Pod"; false; fi
|
||||
if grep -q '^POST ' "$tmp/state/requests"; then
|
||||
echo "FAIL: started another operation over the running one: $(cat "$tmp/state/requests")"
|
||||
false
|
||||
fi
|
||||
}
|
||||
|
||||
@test "a retried backup after a failed attempt resumes the same archive" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo '{"command":"create_remote clickhouse-myapp-20260304T050607Z","status":"error","start":"2026-01-01 00:01:30","error":"S3 PutObject 403"}' > "$tmp/state/prior"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z
|
||||
run_script "$tmp"
|
||||
grep -qxF 'POST http://chi-clickhouse-myapp-clickhouse-0-0.tenant-x.svc:7171/backup/create_remote?name=clickhouse-myapp-20260304T050607Z&resume=true' "$tmp/state/requests"
|
||||
}
|
||||
|
||||
@test "backup does not take over an upload running for another archive" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo 'create_remote --resume clickhouse-myapp-20260304T040000Z' > "$tmp/state/op"
|
||||
echo 3 > "$tmp/state/op_left"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z
|
||||
run_script "$tmp"
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
grep -qx 'create_remote --resume clickhouse-myapp-20260304T050607Z' "$tmp/state/accepted"
|
||||
}
|
||||
|
||||
# The archive is named per BackupJob, so a success row of exactly this
|
||||
# upload is an earlier attempt of the same BackupJob that finished while it
|
||||
# could not see it. Uploading again with resume would re-upload over the
|
||||
# finished archive and break it if that second upload dies halfway.
|
||||
@test "a retried backup takes the upload of its archive an earlier attempt finished as its result" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo '{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"success","start":"2026-01-01 00:01:30"}' > "$tmp/state/prior"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z
|
||||
run_script "$tmp"
|
||||
if grep -q '^POST ' "$tmp/state/requests"; then
|
||||
echo "FAIL: uploaded again over a finished archive: $(cat "$tmp/state/requests")"
|
||||
false
|
||||
fi
|
||||
}
|
||||
|
||||
@test "a retried backup resumes an upload of its archive that ended in error or was cancelled" {
|
||||
for status in error cancel; do
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo "{\"command\":\"create_remote --resume clickhouse-myapp-20260304T050607Z\",\"status\":\"$status\",\"start\":\"2026-01-01 00:01:30\"}" > "$tmp/state/prior"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z
|
||||
run_script "$tmp"
|
||||
if [ "$(accepted "$tmp")" != 1 ]; then echo "FAIL: a $status row must lead to a resumed upload"; false; fi
|
||||
done
|
||||
}
|
||||
|
||||
@test "a retried backup resumes when its latest upload failed after an earlier one succeeded" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
printf '%s\n' \
|
||||
'{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"success","start":"2026-01-01 00:01:00"}' \
|
||||
'{"command":"create_remote --resume clickhouse-myapp-20260304T050607Z","status":"error","start":"2026-01-01 00:01:30"}' > "$tmp/state/prior"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z
|
||||
run_script "$tmp"
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
}
|
||||
|
||||
@test "backup does not take another archive's finished upload as its own" {
|
||||
tmp=$(mktemp -d)
|
||||
make_stubs "$tmp/bin" "$tmp/state"
|
||||
echo '{"command":"create_remote --resume clickhouse-myapp-20260304T040000Z","status":"success","start":"2026-01-01 00:01:30"}' > "$tmp/state/prior"
|
||||
render_script "$tmp/s.sh" backup myapp clickhouse-myapp-20260304T050607Z
|
||||
run_script "$tmp"
|
||||
[ "$(accepted "$tmp")" = 1 ]
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
#!/usr/bin/env bats
|
||||
# The clickhouse-3-system-bucket-roundtrip Test edits the host CoreDNS Corefile
|
||||
# and must put it back. Its restore runs from an EXIT trap under `set +e`, so a
|
||||
# restore that fails without saying so leaves the rewrite in a cluster-wide
|
||||
# object and still reports a green run; the next run then refuses to start.
|
||||
# These run the restore against a stubbed kubectl.
|
||||
|
||||
load test_helper
|
||||
|
||||
LIB=hack/e2e-chainsaw/clickhouse/system-bucket-shared-state.sh
|
||||
HELPERS=examples/backups/clickhouse/00-helpers.sh
|
||||
|
||||
setup() {
|
||||
strict_setup
|
||||
STUB=$(mktemp -d)
|
||||
# A Corefile carrying the Test's marked block, as the run step leaves it.
|
||||
jq -n '{apiVersion: "v1", kind: "ConfigMap",
|
||||
metadata: {name: "coredns", namespace: "kube-system", resourceVersion: "7"},
|
||||
data: {Corefile: ".:53 {\n # === BEGIN e2e-clickhouse-system-bucket ===\n rewrite name exact s3.example.org root-ingress-controller.tenant-root.svc.cozy.local\n # === END e2e-clickhouse-system-bucket ===\n errors\n}\n"}}' \
|
||||
>"$STUB/coredns.json"
|
||||
# The secret lookup follows kubectl's contract: a name together with a
|
||||
# selector is refused, and a selector-only lookup prints the names in
|
||||
# OWNED_SECRETS, the Secrets carrying the owner label.
|
||||
cat >"$STUB/kubectl" <<'EOF'
|
||||
#!/bin/bash
|
||||
echo "$*" >>"$STUB/calls"
|
||||
case "$*" in
|
||||
*"get configmap coredns -o json"*) cat "$STUB/coredns.json" ;;
|
||||
replace*)
|
||||
cp "${@: -1}" "$STUB/replaced.json"
|
||||
if [ -n "${REPLACE_FAILS:-}" ]; then
|
||||
echo 'Error from server (Conflict): Operation cannot be fulfilled on configmaps "coredns": the object has been modified' >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
*"get secret"*)
|
||||
# Positionals are "get", "secret" and then any names.
|
||||
words=0 selector=
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
-l|--selector) selector=$2; shift 2 ;;
|
||||
-n|--namespace|-o|--output) shift 2 ;;
|
||||
-*) shift ;;
|
||||
*) words=$((words + 1)); shift ;;
|
||||
esac
|
||||
done
|
||||
if [ -n "${LOOKUP_FAILS:-}" ]; then
|
||||
echo 'Unable to connect to the server: dial tcp: i/o timeout' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -n "$selector" ] && [ "$words" -gt 2 ]; then
|
||||
echo 'error: name cannot be provided when a selector is specified' >&2
|
||||
exit 1
|
||||
fi
|
||||
[ "$selector" = cozystack.io/e2e-owner=clickhouse-system-bucket ] || exit 0
|
||||
for s in ${OWNED_SECRETS:-}; do echo "secret/$s"; done
|
||||
;;
|
||||
*"delete secret "*)
|
||||
if [ -n "${DELETE_FAILS:-}" ]; then
|
||||
echo 'Error from server (Forbidden): secrets "seaweedfs-s3-ingress-tls" is forbidden' >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
*) echo "unexpected kubectl $*" >&2; exit 2 ;;
|
||||
esac
|
||||
EOF
|
||||
chmod +x "$STUB/kubectl"
|
||||
export STUB
|
||||
}
|
||||
|
||||
restore() {
|
||||
PATH="$STUB:$PATH" NAMESPACE=tenant-root bash -c '
|
||||
set -euo pipefail
|
||||
source "$1"
|
||||
source "$2"
|
||||
set +e
|
||||
restore_shared_state
|
||||
' _ "$HELPERS" "$LIB"
|
||||
}
|
||||
|
||||
@test "a CoreDNS restore the API server refuses fails the restore" {
|
||||
export REPLACE_FAILS=1
|
||||
err=$(mktemp)
|
||||
if restore 2>"$err"; then
|
||||
echo "restore_shared_state returned 0 although kubectl replace was refused" >&2
|
||||
cat "$err" >&2
|
||||
false
|
||||
fi
|
||||
if grep -q 'Removed the s3.example.org rewrite' "$err"; then
|
||||
echo "restore_shared_state reported the rewrite removed although kubectl replace was refused:" >&2
|
||||
cat "$err" >&2
|
||||
false
|
||||
fi
|
||||
}
|
||||
|
||||
@test "a CoreDNS restore sends the Corefile back without the marked block" {
|
||||
restore
|
||||
jq -e '.data.Corefile == ".:53 {\n errors\n}\n"' "$STUB/replaced.json" >/dev/null || {
|
||||
echo "restored Corefile:" >&2
|
||||
jq -r '.data.Corefile' "$STUB/replaced.json" >&2
|
||||
false
|
||||
}
|
||||
# The resourceVersion read travels with the replace, so a concurrent
|
||||
# writer makes it fail rather than be overwritten.
|
||||
[ "$(jq -r '.metadata.resourceVersion' "$STUB/replaced.json")" = 7 ]
|
||||
}
|
||||
|
||||
@test "the restore deletes the Ingress TLS Secret the Test created" {
|
||||
OWNED_SECRETS=seaweedfs-s3-ingress-tls restore
|
||||
grep -qE '^-n tenant-root delete secret seaweedfs-s3-ingress-tls( |$)' "$STUB/calls" || {
|
||||
echo "restore_shared_state did not delete the Secret carrying the owner label; kubectl calls:" >&2
|
||||
cat "$STUB/calls" >&2
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@test "the restore leaves an Ingress TLS Secret without the owner label alone" {
|
||||
for owned in '' e2e-other seaweedfs-s3-ingress-tls-old; do
|
||||
: >"$STUB/calls"
|
||||
OWNED_SECRETS=$owned restore
|
||||
if grep -q 'delete secret' "$STUB/calls"; then
|
||||
echo "restore_shared_state deleted a Secret although the labelled ones are '$owned'; kubectl calls:" >&2
|
||||
cat "$STUB/calls" >&2
|
||||
false
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
@test "a Secret delete the API server refuses fails the restore" {
|
||||
err=$(mktemp)
|
||||
if OWNED_SECRETS=seaweedfs-s3-ingress-tls DELETE_FAILS=1 restore 2>"$err"; then
|
||||
echo "restore_shared_state returned 0 although kubectl delete secret was refused" >&2
|
||||
cat "$err" >&2
|
||||
false
|
||||
fi
|
||||
grep -qE '^-n tenant-root delete secret seaweedfs-s3-ingress-tls( |$)' "$STUB/calls" || {
|
||||
echo "restore_shared_state failed before it reached the Secret delete; kubectl calls:" >&2
|
||||
cat "$STUB/calls" "$err" >&2
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@test "a Secret lookup that fails fails the restore" {
|
||||
err=$(mktemp)
|
||||
if LOOKUP_FAILS=1 restore 2>"$err"; then
|
||||
echo "restore_shared_state returned 0 although it could not tell whether the Secret is left over" >&2
|
||||
cat "$err" >&2
|
||||
false
|
||||
fi
|
||||
grep -q 'could not list the Secrets labelled' "$err" || {
|
||||
echo "restore_shared_state failed without naming the Secret lookup:" >&2
|
||||
cat "$err" >&2
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@test "the run step's finally restores the shared objects" {
|
||||
# When the step ceiling fires, Chainsaw kills the shell and the EXIT trap
|
||||
# of system-bucket-roundtrip.sh never runs; the step's finally still does.
|
||||
# Chainsaw runs a script's content with sh from the suite's directory.
|
||||
suite=hack/e2e-chainsaw/clickhouse
|
||||
finally=$(yq 'select(.metadata.name == "clickhouse-3-system-bucket-roundtrip")
|
||||
| .spec.steps[] | select(.name == "run") | .finally[]
|
||||
| select(.description == "restore the host CoreDNS and the S3 Ingress TLS Secret") | .script.content' \
|
||||
"$suite/chainsaw-test.yaml")
|
||||
[ -n "$finally" ] || { echo "the run step has no finally restoring the shared objects" >&2; false; }
|
||||
(cd "$suite" && PATH="$STUB:$PATH" NAMESPACE=tenant-root sh -c "$finally")
|
||||
[ -f "$STUB/replaced.json" ] || {
|
||||
echo "the run step's finally did not put the Corefile back" >&2
|
||||
false
|
||||
}
|
||||
jq -e '.data.Corefile == ".:53 {\n errors\n}\n"' "$STUB/replaced.json" >/dev/null
|
||||
}
|
||||
|
||||
# The Altinity driver names the Backup after the BackupJob, and a Backup left
|
||||
# behind under that name records an earlier run's archive, which fails the next
|
||||
# run's BackupJob. It is reclaimed by name, whether or not the BackupJob
|
||||
# recorded it in status.backupRef.
|
||||
@test "the round-trip reclaims its Backup by name before and after the run" {
|
||||
suite=hack/e2e-chainsaw/clickhouse/chainsaw-test.yaml
|
||||
test='select(.metadata.name == "clickhouse-3-system-bucket-roundtrip") | .spec.steps[]'
|
||||
calls="$STUB/calls"
|
||||
# Nothing is left over from an earlier run, and no BackupJob recorded a
|
||||
# backupRef.
|
||||
cat >"$STUB/kubectl" <<'STUBEOF'
|
||||
#!/bin/bash
|
||||
echo "$*" >>"$STUB/calls"
|
||||
case "$*" in
|
||||
*" get secret "*) exit 1 ;;
|
||||
esac
|
||||
STUBEOF
|
||||
for selector in \
|
||||
'select(.name == "preconditions") | .try[].script.content' \
|
||||
'select(.name == "run") | .finally[] | select(.description == "system-bucket round-trip cleanup") | .script.content'; do
|
||||
: >"$calls"
|
||||
script=$(yq "$test | $selector" "$suite")
|
||||
[ -n "$script" ] || { echo "no script at: $selector" >&2; false; }
|
||||
PATH="$STUB:$PATH" NAMESPACE=tenant-root sh -c "$script"
|
||||
grep -qE '^-n tenant-root delete backup sysbucket-backup( |$)' "$calls" || {
|
||||
echo "the script at '$selector' does not delete Backup sysbucket-backup by name; kubectl calls:" >&2
|
||||
cat "$calls" >&2
|
||||
false
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
# cert-manager issues the Secret of a Certificate that still exists again as
|
||||
# soon as it is deleted. Chainsaw deletes the Certificate it applied, and waits
|
||||
# for it, before it runs the cleanup ops of the same step, so the Secret is
|
||||
# deleted there and nowhere earlier.
|
||||
@test "the Certificate's Secret is deleted after Chainsaw deletes the Certificate" {
|
||||
test='select(.metadata.name == "clickhouse-3-system-bucket-roundtrip") | .spec.steps[]'
|
||||
suite=hack/e2e-chainsaw/clickhouse/chainsaw-test.yaml
|
||||
applies=$(yq "$test | select(.name == \"create-certificate-and-probe\") | .try[] | select(has(\"apply\")) | .apply.file" "$suite")
|
||||
[ "$applies" = system-bucket-tls.yaml ] || {
|
||||
echo "step create-certificate-and-probe no longer applies system-bucket-tls.yaml alone: $applies" >&2
|
||||
false
|
||||
}
|
||||
deletes=$(yq -o=json -I=0 "$test | select(.name == \"create-certificate-and-probe\") | .cleanup" "$suite")
|
||||
[ "$deletes" = '[{"delete":{"ref":{"apiVersion":"v1","kind":"Secret","name":"e2e-system-bucket-s3-tls"}}}]' ] || {
|
||||
echo "the cleanup of step create-certificate-and-probe is not the one delete of Secret e2e-system-bucket-s3-tls: $deletes" >&2
|
||||
false
|
||||
}
|
||||
# The preconditions run before the apply, when Chainsaw holds no Certificate.
|
||||
if yq "$test | select(.name != \"preconditions\") | (.try[], .finally[]?) | .script.content // \"\"" "$suite" | grep -qE 'delete +(secret +e2e-system-bucket-s3-tls|certificate +e2e-system-bucket-s3)( |$)'; then
|
||||
echo "a step script deletes the Certificate or its Secret while Chainsaw still holds the Certificate" >&2
|
||||
false
|
||||
fi
|
||||
}
|
||||
|
||||
# Chainsaw registers an applied object for deletion only when its apply created
|
||||
# it; an object left by a run killed past its cleanup is patched and kept. The
|
||||
# Certificate would then outlive every later run, re-issuing its Secret after
|
||||
# each step cleanup, and a probe Pod whose `sleep` had ended never turns Ready
|
||||
# again, so the preconditions remove all three before the apply.
|
||||
@test "the preconditions remove the TLS objects and probe Pod a killed run left" {
|
||||
suite=hack/e2e-chainsaw/clickhouse/chainsaw-test.yaml
|
||||
test='select(.metadata.name == "clickhouse-3-system-bucket-roundtrip") | .spec.steps[]'
|
||||
calls="$STUB/calls"
|
||||
cat >"$STUB/kubectl" <<'STUBEOF'
|
||||
#!/bin/bash
|
||||
echo "$*" >>"$STUB/calls"
|
||||
case "$*" in
|
||||
*" get secret "*) exit 1 ;;
|
||||
esac
|
||||
STUBEOF
|
||||
: >"$calls"
|
||||
script=$(yq "$test | select(.name == \"preconditions\") | .try[].script.content" "$suite")
|
||||
PATH="$STUB:$PATH" NAMESPACE=tenant-root sh -c "$script"
|
||||
line_of() { grep -nE "^-n tenant-root delete $1 --ignore-not-found --wait=true( |$)" "$calls" | head -n1 | cut -d: -f1; }
|
||||
cert=$(line_of 'certificate e2e-system-bucket-s3')
|
||||
secret=$(line_of 'secret e2e-system-bucket-s3-tls')
|
||||
pod=$(line_of 'pod e2e-system-bucket-probe')
|
||||
[ -n "$cert" ] && [ -n "$secret" ] && [ -n "$pod" ] || {
|
||||
echo "the preconditions do not delete, and wait for, the Certificate, its Secret and the probe Pod; kubectl calls:" >&2
|
||||
cat "$calls" >&2
|
||||
false
|
||||
}
|
||||
[ "$cert" -lt "$secret" ] || {
|
||||
echo "the preconditions delete Secret e2e-system-bucket-s3-tls before its Certificate, which cert-manager then issues again" >&2
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -37,11 +37,11 @@ nginx_size_kib() {
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
conf=$(awk '
|
||||
/^COPY <<.EOF. \/etc\/nginx\/conf\.d\/default\.conf$/ { inblock = 1; next }
|
||||
/^COPY <<.EOF. \/etc\/nginx\/templates\/default\.conf\.template$/ { inblock = 1; next }
|
||||
inblock && /^EOF$/ { inblock = 0; next }
|
||||
inblock { print }
|
||||
' "$CONSOLE_CONTAINERFILE")
|
||||
[ -n "$conf" ] || { echo "no /etc/nginx/conf.d/default.conf heredoc found in $CONSOLE_CONTAINERFILE" >&2; exit 1; }
|
||||
[ -n "$conf" ] || { echo "no /etc/nginx/templates/default.conf.template heredoc found in $CONSOLE_CONTAINERFILE" >&2; exit 1; }
|
||||
|
||||
# An extraction that silently grabbed the wrong slice would let every
|
||||
# assertion below pass on an empty-ish config, so anchor on a line the
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
#!/usr/bin/env bats
|
||||
# The console nginx sends the logs and metrics roots of the observability
|
||||
# proxy to that proxy instead of the API server. The routing lives in the
|
||||
# nginx config baked into the console image, which no chart template and no
|
||||
# helm-unittest case can see, so it is pinned here.
|
||||
#
|
||||
# Four properties are checked. The location regex must take the four path
|
||||
# shapes the proxy serves and leave every ordinary Kubernetes API path to the
|
||||
# /apis and /api prefix locations; nginx runs the regex locations whenever the
|
||||
# longest prefix match is a plain prefix, so the prefix locations must not
|
||||
# carry ^~, which would stop that. The location must stream: tail and watch
|
||||
# style responses stall behind proxy buffering and die at the default 60s
|
||||
# read timeout. And the upstream must be a variable resolved per request,
|
||||
# because nginx resolves a literal upstream host once at startup and refuses
|
||||
# to start when it does not resolve, which is the case on every cluster that
|
||||
# does not run the proxy. Finally, when nginx cannot reach the proxy it
|
||||
# answers with the Kubernetes Status the console reads as not installed,
|
||||
# while the proxy's own 502 passes through; that check runs the extracted
|
||||
# locations in a real nginx and is skipped where none is installed.
|
||||
#
|
||||
# The regex is evaluated with perl, whose syntax nginx's PCRE accepts for the
|
||||
# constructs used here.
|
||||
# Run with: bats hack/console-nginx-observability-proxy.bats
|
||||
|
||||
load test_helper
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)"
|
||||
CONSOLE_CONTAINERFILE="packages/system/dashboard/images/console/Containerfile"
|
||||
|
||||
console_nginx_template() {
|
||||
awk '
|
||||
/^COPY <<.EOF. \/etc\/nginx\/templates\/default\.conf\.template$/ { inblock = 1; next }
|
||||
inblock && /^EOF$/ { inblock = 0; next }
|
||||
inblock { print }
|
||||
' "$REPO_ROOT/$CONSOLE_CONTAINERFILE"
|
||||
}
|
||||
|
||||
# Prints the regex of every `location ~ <regex> {` line, one per line.
|
||||
regex_locations() {
|
||||
printf '%s\n' "$1" | awk '$1 == "location" && $2 == "~" && $4 == "{" { print $3 }'
|
||||
}
|
||||
|
||||
# Prints the body of the location block whose regex is $2.
|
||||
location_body() {
|
||||
# Through ENVIRON rather than -v, which would expand the backslashes.
|
||||
printf '%s\n' "$1" | LOCATION_RE="$2" awk '
|
||||
$1 == "location" && $2 == "~" && $3 == ENVIRON["LOCATION_RE"] { inblock = 1; next }
|
||||
inblock && $1 == "}" { exit }
|
||||
inblock { print }
|
||||
'
|
||||
}
|
||||
|
||||
matches() {
|
||||
perl -e 'exit(($ARGV[1] =~ /$ARGV[0]/) ? 0 : 1)' "$1" "$2"
|
||||
}
|
||||
|
||||
@test "console nginx routes exactly the observability proxy roots to the proxy" {
|
||||
conf=$(console_nginx_template)
|
||||
[ -n "$conf" ] || { echo "no /etc/nginx/templates/default.conf.template heredoc in $CONSOLE_CONTAINERFILE" >&2; exit 1; }
|
||||
|
||||
regexes=$(regex_locations "$conf")
|
||||
[ "$(printf '%s\n' "$regexes" | grep -c .)" -eq 1 ] \
|
||||
|| { echo "expected exactly one regex location, got: $regexes" >&2; exit 1; }
|
||||
re=$regexes
|
||||
|
||||
for path in \
|
||||
/apis/cozystack.io/v1alpha1/namespaces/tenant-foo/logs/select/logsql/query \
|
||||
/apis/cozystack.io/v1alpha1/namespaces/tenant-foo/metrics/api/v1/query_range \
|
||||
/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-foo/postgreses/db/log/select/logsql/tail \
|
||||
/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-foo/vminstances/vm1/metrics/api/v1/query
|
||||
do
|
||||
matches "$re" "$path" || { echo "$path does not reach the proxy" >&2; exit 1; }
|
||||
done
|
||||
|
||||
for path in \
|
||||
/apis/cozystack.io/v1alpha1/namespaces/tenant-foo/logs \
|
||||
/apis/cozystack.io/v1alpha1/namespaces/tenant-foo/workloadmonitors/db \
|
||||
/apis/cozystack.io/v1alpha1/applicationdefinitions/postgres \
|
||||
/apis/cozystack.io/v1alpha1/watch/namespaces/tenant-foo/logs/ \
|
||||
/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-foo/postgreses \
|
||||
/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-foo/postgreses/log \
|
||||
/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-foo/postgreses/log/ \
|
||||
/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-foo/postgreses/db/status \
|
||||
/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-foo/postgreses/db/log \
|
||||
/apis/apps.cozystack.io/v1alpha1/watch/namespaces/tenant-foo/postgreses/db/log/ \
|
||||
/apis/metrics.k8s.io/v1beta1/namespaces/tenant-foo/pods/ \
|
||||
/api/v1/namespaces/tenant-foo/pods/db-0/log \
|
||||
/k8s/apis/cozystack.io/v1alpha1/namespaces/tenant-foo/logs/select/logsql/query
|
||||
do
|
||||
if matches "$re" "$path"; then
|
||||
echo "FAIL: $path would reach the proxy instead of the API server" >&2
|
||||
false
|
||||
fi
|
||||
done
|
||||
|
||||
# A ^~ on the /apis or /api prefix would stop nginx from trying the regex.
|
||||
if printf '%s\n' "$conf" | grep -Eq '^[[:space:]]*location[[:space:]]+\^~'; then
|
||||
echo "FAIL: a ^~ prefix location disables the regex location" >&2
|
||||
false
|
||||
fi
|
||||
}
|
||||
|
||||
@test "the observability proxy location streams, forwards the token and resolves per request" {
|
||||
conf=$(console_nginx_template)
|
||||
re=$(regex_locations "$conf")
|
||||
body=$(location_body "$conf" "$re")
|
||||
[ -n "$body" ] || { echo "no body found for location ~ $re" >&2; exit 1; }
|
||||
|
||||
for directive in \
|
||||
'proxy_http_version 1.1;' \
|
||||
'proxy_buffering off;' \
|
||||
'proxy_read_timeout 86400s;' \
|
||||
'proxy_send_timeout 86400s;'
|
||||
do
|
||||
printf '%s\n' "$body" | grep -Fqx " $directive" \
|
||||
|| { echo "the proxy location lacks '$directive'" >&2; exit 1; }
|
||||
done
|
||||
|
||||
# nginx forwards client headers unless told otherwise; the proxy needs the
|
||||
# Authorization header the gatekeeper set.
|
||||
if printf '%s\n' "$body" | grep -Eq 'proxy_set_header[[:space:]]+Authorization|proxy_pass_request_headers[[:space:]]+off'; then
|
||||
echo "FAIL: the proxy location drops or rewrites the Authorization header" >&2
|
||||
false
|
||||
fi
|
||||
|
||||
printf '%s\n' "$body" | grep -Eq '^[[:space:]]*resolver[[:space:]]+\$\{NGINX_LOCAL_RESOLVERS\}' \
|
||||
|| { echo "the proxy location sets no resolver from the pod's resolv.conf" >&2; exit 1; }
|
||||
printf '%s\n' "$body" | grep -Eq '^[[:space:]]*set[[:space:]]+\$observability_proxy[[:space:]]+observability-proxy\.cozy-observability-proxy\.svc\.\$\{CLUSTER_DOMAIN\}:80;' \
|
||||
|| { echo "the proxy location does not name the Service by its fully qualified name" >&2; exit 1; }
|
||||
printf '%s\n' "$body" | grep -Eq '^[[:space:]]*proxy_pass[[:space:]]+http://\$observability_proxy;' \
|
||||
|| { echo "the proxy location does not proxy_pass through the variable" >&2; exit 1; }
|
||||
}
|
||||
|
||||
@test "the console image defines every variable its nginx template substitutes" {
|
||||
cd "$REPO_ROOT"
|
||||
conf=$(console_nginx_template)
|
||||
|
||||
# The image's entrypoint substitutes only variables present in the
|
||||
# environment; one that is not would reach nginx as ${NAME} and fail it.
|
||||
grep -Eq '^ENV NGINX_ENTRYPOINT_LOCAL_RESOLVERS=1$' "$CONSOLE_CONTAINERFILE" \
|
||||
|| { echo "the image does not ask its entrypoint for NGINX_LOCAL_RESOLVERS" >&2; exit 1; }
|
||||
grep -Eq '^ENV CLUSTER_DOMAIN=cozy\.local$' "$CONSOLE_CONTAINERFILE" \
|
||||
|| { echo "the image has no CLUSTER_DOMAIN default" >&2; exit 1; }
|
||||
|
||||
used=$(printf '%s\n' "$conf" | grep -oE '\$\{[A-Za-z_][A-Za-z0-9_]*\}' | sort -u)
|
||||
expected=$(printf '%s\n' '${CLUSTER_DOMAIN}' '${NGINX_LOCAL_RESOLVERS}')
|
||||
[ "$used" = "$expected" ] \
|
||||
|| { echo "template substitutes: $used; the image defines: $expected" >&2; exit 1; }
|
||||
}
|
||||
|
||||
# Prints the named location $2 of the template $1, braces included.
|
||||
named_location() {
|
||||
printf '%s\n' "$1" | LOCATION_NAME="$2" awk '
|
||||
$1 == "location" && $2 == ENVIRON["LOCATION_NAME"] { inblock = 1 }
|
||||
inblock { print }
|
||||
inblock && $1 == "}" { exit }
|
||||
'
|
||||
}
|
||||
|
||||
free_port() {
|
||||
python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])'
|
||||
}
|
||||
|
||||
# Starts nginx with the observability locations of the console template, the
|
||||
# upstream pointed at 127.0.0.1:$1, and a stand-in proxy on 127.0.0.1:$2
|
||||
# that answers 502 itself. Prints the console port.
|
||||
start_console_nginx() {
|
||||
upstream_port=$1 standin_port=$2
|
||||
conf=$(console_nginx_template)
|
||||
re=$(regex_locations "$conf")
|
||||
console_port=$(free_port)
|
||||
{
|
||||
echo "pid $BATS_TEST_TMPDIR/nginx.pid;"
|
||||
echo "error_log $BATS_TEST_TMPDIR/error.log;"
|
||||
echo "events {}"
|
||||
echo "http {"
|
||||
echo " access_log off;"
|
||||
echo " client_body_temp_path $BATS_TEST_TMPDIR; proxy_temp_path $BATS_TEST_TMPDIR;"
|
||||
echo " fastcgi_temp_path $BATS_TEST_TMPDIR; uwsgi_temp_path $BATS_TEST_TMPDIR; scgi_temp_path $BATS_TEST_TMPDIR;"
|
||||
echo " server {"
|
||||
echo " listen 127.0.0.1:$console_port;"
|
||||
echo " location ~ $re {"
|
||||
# The test upstream is an address, so the resolver is never asked.
|
||||
location_body "$conf" "$re" \
|
||||
| sed -e 's/\${NGINX_LOCAL_RESOLVERS}/127.0.0.1/' \
|
||||
-e "s/^\([[:space:]]*set[[:space:]]*\$observability_proxy[[:space:]]\).*/\1127.0.0.1:$upstream_port;/"
|
||||
echo " }"
|
||||
named_location "$conf" "@observability_proxy_unavailable"
|
||||
echo " }"
|
||||
echo " server {"
|
||||
echo " listen 127.0.0.1:$standin_port;"
|
||||
echo " location / { return 502 'log store unreachable'; }"
|
||||
echo " }"
|
||||
echo "}"
|
||||
} > "$BATS_TEST_TMPDIR/nginx.conf"
|
||||
nginx -p "$BATS_TEST_TMPDIR" -c "$BATS_TEST_TMPDIR/nginx.conf" \
|
||||
|| { cat "$BATS_TEST_TMPDIR/error.log" >&2; return 1; }
|
||||
echo "$console_port"
|
||||
}
|
||||
|
||||
teardown() {
|
||||
if [ -f "${BATS_TEST_TMPDIR:-}/nginx.pid" ]; then
|
||||
kill "$(cat "$BATS_TEST_TMPDIR/nginx.pid")" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
@test "a cluster without the proxy answers the console's not-installed Status, the proxy's own 502 passes through" {
|
||||
command -v nginx >/dev/null 2>&1 || skip "nginx is not installed"
|
||||
command -v curl >/dev/null 2>&1 || skip "curl is not installed"
|
||||
path=/apis/cozystack.io/v1alpha1/namespaces/tenant-foo/logs/select/logsql/query
|
||||
|
||||
# Nothing listens on the upstream port: nginx itself fails the request.
|
||||
standin=$(free_port)
|
||||
port=$(start_console_nginx "$(free_port)" "$standin")
|
||||
out=$(curl --silent --show-error --include --max-time 10 "http://127.0.0.1:$port$path")
|
||||
printf '%s\n' "$out" | head -n 1 | grep -q ' 404' \
|
||||
|| { echo "FAIL: an unreachable proxy did not answer 404: $out" >&2; false; }
|
||||
printf '%s\n' "$out" | grep -iq '^content-type: application/json' \
|
||||
|| { echo "FAIL: the not-installed answer is not JSON: $out" >&2; false; }
|
||||
body=$(printf '%s\n' "$out" | tail -n 1)
|
||||
printf '%s' "$body" | python3 -c '
|
||||
import json, sys
|
||||
s = json.load(sys.stdin)
|
||||
assert s["kind"] == "Status" and s["apiVersion"] == "v1" and s["status"] == "Failure", s
|
||||
assert s["reason"] == "NotFound" and s["code"] == 404, s
|
||||
assert s["message"] == "the observability proxy is not available on this cluster", s
|
||||
' || { echo "FAIL: the not-installed body is not the expected Status: $body" >&2; false; }
|
||||
# The next nginx gets fresh ports, so the old master need not have
|
||||
# released its sockets; it is still stopped first to keep one running.
|
||||
pid=$(cat "$BATS_TEST_TMPDIR/nginx.pid")
|
||||
kill "$pid"
|
||||
for _ in $(seq 1 50); do kill -0 "$pid" 2>/dev/null || break; sleep 0.1; done
|
||||
rm -f "$BATS_TEST_TMPDIR/nginx.pid"
|
||||
|
||||
# The proxy answers 502 itself: the console must see that answer.
|
||||
standin=$(free_port)
|
||||
port=$(start_console_nginx "$standin" "$standin")
|
||||
out=$(curl --silent --show-error --include --max-time 10 "http://127.0.0.1:$port$path")
|
||||
printf '%s\n' "$out" | head -n 1 | grep -q ' 502' \
|
||||
|| { echo "FAIL: the proxy's own 502 did not pass through: $out" >&2; false; }
|
||||
printf '%s\n' "$out" | tail -n 1 | grep -qx 'log store unreachable' \
|
||||
|| { echo "FAIL: the proxy's own 502 body was replaced: $out" >&2; false; }
|
||||
}
|
||||
@@ -966,6 +966,37 @@ STUB
|
||||
}
|
||||
}
|
||||
|
||||
@test "PR E2E jobs clean up between preparation attempts but not after testing" {
|
||||
tmp="$(mktemp -d)"
|
||||
mkdir -p "$tmp/bin"
|
||||
cat >"$tmp/bin/make" <<'STUB'
|
||||
#!/bin/sh
|
||||
printf '%s\n' "$*" >>"$CLEANUP_CALLS"
|
||||
case "$*" in
|
||||
*prepare-env-container*)
|
||||
if [ ! -f "$CLEANUP_ATTEMPT" ]; then
|
||||
touch "$CLEANUP_ATTEMPT"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
STUB
|
||||
chmod +x "$tmp/bin/make"
|
||||
for wf in pull-requests e2e-fork; do
|
||||
workflow="$HACK_DIR/../.github/workflows/$wf.yaml"
|
||||
yq --unwrapScalar '.jobs.e2e.steps[] | select(.name == "Prepare environment") | .run' "$workflow" >"$tmp/prepare.sh"
|
||||
CLEANUP_CALLS="$tmp/$wf.calls" CLEANUP_ATTEMPT="$tmp/$wf.attempt" SANDBOX_NAME=test PATH="$tmp/bin:$PATH" bash -eu "$tmp/prepare.sh"
|
||||
printf '%s\n' 'SANDBOX_NAME=test prepare-env-container' '-C packages/core/testing SANDBOX_NAME=test delete-cluster-container' 'SANDBOX_NAME=test prepare-env-container' >"$tmp/expected"
|
||||
diff "$tmp/expected" "$tmp/$wf.calls"
|
||||
scripts="$(yq --unwrapScalar '.jobs.e2e.steps[] | select(.name != "Prepare environment") | .run // ""' "$workflow")"
|
||||
if printf '%s\n' "$scripts" | grep -Eq 'delete-cluster-container|docker[[:space:]]+(compose.*down|rm)|zpool[[:space:]]+destroy|make.*[[:space:]]delete([[:space:]]|$)'; then
|
||||
echo "FAIL: $wf destroys runner-local state outside preparation"
|
||||
false
|
||||
fi
|
||||
done
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "the step that runs this collector has a ceiling of its own everywhere" {
|
||||
# Every bound inside the script protects one read. None of them protects the
|
||||
# STEP: the tarball is written on the collector's last line, the upload is the
|
||||
|
||||
+1
-1
@@ -121,7 +121,7 @@
|
||||
# the number; do not expect to find it written here.
|
||||
#
|
||||
# TWO ceilings sit outside it, and they fail differently. The job is capped at
|
||||
# `timeout-minutes: 215`, and reaching that cancels every step still to come --
|
||||
# `timeout-minutes: 265`, and reaching that cancels every step still to come --
|
||||
# the artifact upload among them. The step running this script is capped at 30 of
|
||||
# its own, and reaching THAT ends only this step: the uploads after it still run,
|
||||
# and `continue-on-error` on that step keeps the overrun out of the job's result,
|
||||
|
||||
+1
-1
@@ -208,7 +208,7 @@ _cozy_on_exit() {
|
||||
# capture would read as a complete one listing fewer crash-loops than
|
||||
# actually occurred. This handler's whole worst case is ~1350s (330 + 390
|
||||
# + 630, each leg including its 30s kill grace) against a job capped at
|
||||
# 215 minutes with no per-step timeout —
|
||||
# 265 minutes with no per-step timeout —
|
||||
# deliberate, for the same reason recorded in hack/e2e-chainsaw/.chainsaw.yaml:
|
||||
# a bounded, honest wait beats a kill that collects nothing.
|
||||
if [ "$_prev_rc" -ne 0 ]; then
|
||||
|
||||
@@ -66,14 +66,14 @@ spec:
|
||||
# script: it SIGKILLs the shell alone, orphaned children hold the pipe open,
|
||||
# and the op overruns (#4268 measured 606s under a 300s ceiling), so the
|
||||
# nominal ~5m was a figure a busy catch could exceed, not a cap. Tests run
|
||||
# sequentially, and the E2E job is capped at 215 timeout-minutes. A cascade
|
||||
# sequentially, and the E2E job is capped at 265 timeout-minutes. A cascade
|
||||
# reddening many suites can therefore spend a large share of the job in
|
||||
# diagnostics. That is deliberate — the old ceiling
|
||||
# bought its speed by collecting nothing at all — and it is bounded: both legs
|
||||
# only approach their ceilings on a genuinely degraded cluster, a systemic
|
||||
# failure usually reds the install gate and skips the E2E step entirely, and
|
||||
# the report-upload steps are `if: always()`. That last point does NOT extend
|
||||
# to a job timeout: a 215-minute cap ends the job `cancelled`, and the ~4m48s
|
||||
# to a job timeout: a 265-minute cap ends the job `cancelled`, and the ~4m48s
|
||||
# grace window is consumed by the earlier `Collect report` step, so both
|
||||
# cozyreport.tgz and the job log are lost (measured on runs 29557003429 and
|
||||
# 29568562337). If this ever does start truncating runs, bound the number of
|
||||
|
||||
@@ -26,7 +26,7 @@ A suite is a directory directly under `hack/e2e-chainsaw/` in or below which Cha
|
||||
|
||||
A parked `chainsaw-test.yaml.disabled` is none of these: the directory is then not a suite, is selected by nothing and cannot be allowlisted.
|
||||
|
||||
Suites: `postgres`, `bucket`, `mariadb`, `mongodb`, `redis`, `valkey`, `qdrant`, `clickhouse`, `kafka`, `kafka-metadata`, `rabbitmq`, `etcd`, `openbao`, `harbor`, `foundationdb`, `external-dns`, `kuberture`, `vminstance`, `gateway`, `opensearch`, `monitoring`, `kubernetes-latest`, `kubernetes-previous`, `securitygroup`, `seaweedfs`, `computeplane`. `kubernetes-proxmox` is parked as `chainsaw-test.yaml.disabled` and runs only in `.github/workflows/e2e-proxmox.yaml`, which needs a Proxmox hypervisor.
|
||||
Suites: `postgres`, `bucket`, `mariadb`, `mongodb`, `redis`, `valkey`, `qdrant`, `clickhouse`, `kafka`, `kafka-metadata`, `rabbitmq`, `etcd`, `openbao`, `harbor`, `foundationdb`, `external-dns`, `kuberture`, `vminstance`, `gateway`, `opensearch`, `monitoring`, `kubernetes-latest`, `kubernetes-previous`, `securitygroup`, `seaweedfs`, `computeplane`, `observability-proxy`. `kubernetes-proxmox` is parked as `chainsaw-test.yaml.disabled` and runs only in `.github/workflows/e2e-proxmox.yaml`, which needs a Proxmox hypervisor.
|
||||
|
||||
## What Chainsaw buys over the BATS suite
|
||||
|
||||
@@ -63,7 +63,7 @@ Declarative suites assert on `status.conditions` and concrete fields. Inherently
|
||||
|
||||
## Running locally
|
||||
|
||||
Requires a cluster with Cozystack installed and a `tenant-test` namespace (the environment `hack/e2e-install-cozystack.bats` produces). `bucket` and `seaweedfs` additionally need `mc`, `nc`, and `jq` on the host; `kuberture`/`openbao`/`foundationdb`/`securitygroup`/`computeplane`/`kubernetes-latest`/`kubernetes-previous`/`vminstance` need `jq`.
|
||||
Requires a cluster with Cozystack installed and a `tenant-test` namespace (the environment `hack/e2e-install-cozystack.bats` produces). `bucket` and `seaweedfs` additionally need `mc`, `nc`, and `jq` on the host; `kuberture`/`openbao`/`foundationdb`/`securitygroup`/`computeplane`/`kubernetes-latest`/`kubernetes-previous`/`vminstance` need `jq`; `observability-proxy` needs `curl` and `nc`.
|
||||
|
||||
```bash
|
||||
# install chainsaw
|
||||
|
||||
@@ -91,7 +91,7 @@ spec:
|
||||
status:
|
||||
replicas: 1
|
||||
---
|
||||
# ClickHouse Altinity backup/restore E2E — the two backup Tests below sit in
|
||||
# ClickHouse Altinity backup/restore E2E — the three backup Tests below sit in
|
||||
# this suite alongside the plain `clickhouse` Test above. Chainsaw port of the
|
||||
# intended hack/e2e-apps/backup-clickhouse.bats (cozystack#2600), shaped like the
|
||||
# etcd/mariadb/postgres suites:
|
||||
@@ -107,8 +107,15 @@ spec:
|
||||
# driving the validated example scripts
|
||||
# (examples/backups/clickhouse). Also runs in
|
||||
# CI, in tenant-root.
|
||||
# clickhouse-3-system-bucket-roundtrip
|
||||
# — backup and in-place restore through the
|
||||
# shipped cozy-default BackupClass and the
|
||||
# platform system bucket, for a release
|
||||
# whose Pod started before its credentials
|
||||
# were projected. Runs in CI, in tenant-root.
|
||||
#
|
||||
# Why the split: the two Tests answer different questions at different cost. The
|
||||
# Why the split: the first two Tests answer different questions at different
|
||||
# cost, and the third covers the system-bucket path neither of them takes. The
|
||||
# contracts Test needs no object store, so it stays in the default tenant-test
|
||||
# namespace next to the other app suites and is the seconds-long guard on the
|
||||
# chart wiring the Altinity strategy depends on — the sidecar container/port and
|
||||
@@ -377,3 +384,217 @@ spec:
|
||||
set -eu
|
||||
cd ../../..
|
||||
NAMESPACE="$NAMESPACE" examples/backups/clickhouse/cleanup.sh
|
||||
---
|
||||
# Backup and in-place restore through the shipped cozy-default BackupClass and
|
||||
# the platform system bucket, for a ClickHouse whose Pod started before the
|
||||
# platform projected cozy-backups-creds into its namespace. The sidecar has to
|
||||
# pick those credentials up while running; until it could, the first BackupJob
|
||||
# of such a release failed with "no EC2 IMDS role found" and kept failing until
|
||||
# the Pod was restarted.
|
||||
#
|
||||
# Unlike clickhouse-2-backup-roundtrip this targets the system bucket as
|
||||
# advertised, https://s3.example.org, so system-bucket-roundtrip.sh makes that
|
||||
# name reachable from tenant-root for the duration of its own step and undoes
|
||||
# it on exit: see its header for the two shared objects it touches and the
|
||||
# cert-manager behaviour that relies on. Runs in tenant-root, where the system
|
||||
# bucket's SeaweedFS and its Ingress controller sit.
|
||||
#
|
||||
# The precondition step deletes tenant-root's projected cozy-backups-creds,
|
||||
# which any BackupJob that ran in tenant-root before this Test leaves there:
|
||||
# the projector runs for each BackupJob whatever its strategy, and Chainsaw
|
||||
# does not fix the order of the Tests in a suite, so the earlier one may come
|
||||
# from this suite or another. It writes the Secret again on the next
|
||||
# BackupJob, which is the moment under test.
|
||||
apiVersion: chainsaw.kyverno.io/v1alpha1
|
||||
kind: Test
|
||||
metadata:
|
||||
name: clickhouse-3-system-bucket-roundtrip
|
||||
spec:
|
||||
namespace: tenant-root
|
||||
catch:
|
||||
- events: {}
|
||||
- describe:
|
||||
apiVersion: helm.toolkit.fluxcd.io/v2
|
||||
kind: HelmRelease
|
||||
name: clickhouse-sysbucket
|
||||
- describe:
|
||||
apiVersion: cert-manager.io/v1
|
||||
kind: Certificate
|
||||
name: e2e-system-bucket-s3
|
||||
- describe:
|
||||
apiVersion: cert-manager.io/v1
|
||||
kind: Certificate
|
||||
name: seaweedfs-s3-ingress-tls
|
||||
- describe:
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
name: ingress-seaweedfs-s3
|
||||
- describe:
|
||||
apiVersion: backups.cozystack.io/v1alpha1
|
||||
kind: BackupJob
|
||||
name: sysbucket-backup
|
||||
- describe:
|
||||
apiVersion: backups.cozystack.io/v1alpha1
|
||||
kind: RestoreJob
|
||||
name: sysbucket-restore
|
||||
- podLogs:
|
||||
selector: app.kubernetes.io/instance=clickhouse-sysbucket
|
||||
container: clickhouse-backup
|
||||
tail: 200
|
||||
- podLogs:
|
||||
selector: app=clickhouse-sysbucket-keeper
|
||||
tail: 100
|
||||
steps:
|
||||
- name: preconditions
|
||||
try:
|
||||
# The deletes below wait up to 270s in all (30+30+60+30+30+30+60), so a
|
||||
# stuck one is named by its kubectl --timeout before the 5m ceiling kills
|
||||
# the shell with no object named. A new delete needs its own --timeout.
|
||||
- script:
|
||||
timeout: 5m
|
||||
content: |
|
||||
set -eu
|
||||
if kubectl -n "$NAMESPACE" get secret seaweedfs-s3-ingress-tls -o name >/dev/null 2>&1; then
|
||||
echo "Secret $NAMESPACE/seaweedfs-s3-ingress-tls already exists; this Test would have to replace it" >&2
|
||||
exit 1
|
||||
fi
|
||||
if kubectl -n kube-system get configmap coredns -o jsonpath='{.data.Corefile}' | grep -qF 'BEGIN e2e-clickhouse-system-bucket'; then
|
||||
echo "kube-system/coredns still carries the e2e-clickhouse-system-bucket block from an earlier run" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Fixed names in a persistent namespace: a leftover Succeeded job
|
||||
# would satisfy the waits in the run step without a new attempt, and
|
||||
# a leftover Backup of the BackupJob's name, recording an earlier
|
||||
# run's archive, fails the new BackupJob.
|
||||
kubectl -n "$NAMESPACE" delete restorejob sysbucket-restore --ignore-not-found --wait=true --timeout=30s
|
||||
kubectl -n "$NAMESPACE" delete backupjob sysbucket-backup --ignore-not-found --wait=true --timeout=30s
|
||||
kubectl -n "$NAMESPACE" delete backup sysbucket-backup --ignore-not-found --wait=true --timeout=60s
|
||||
kubectl -n "$NAMESPACE" delete secret cozy-backups-creds --ignore-not-found --wait=true --timeout=30s
|
||||
# Chainsaw reclaims only what its apply created, so objects a killed
|
||||
# run left would be patched and kept. The Certificate goes before its
|
||||
# Secret, which cert-manager issues again while the Certificate exists.
|
||||
kubectl -n "$NAMESPACE" delete certificate e2e-system-bucket-s3 --ignore-not-found --wait=true --timeout=30s
|
||||
kubectl -n "$NAMESPACE" delete secret e2e-system-bucket-s3-tls --ignore-not-found --wait=true --timeout=30s
|
||||
kubectl -n "$NAMESPACE" delete pod e2e-system-bucket-probe --ignore-not-found --wait=true --timeout=60s
|
||||
check:
|
||||
($error == null): true
|
||||
|
||||
- name: create-certificate-and-probe
|
||||
try:
|
||||
- apply:
|
||||
file: system-bucket-tls.yaml
|
||||
- assert:
|
||||
timeout: 2m
|
||||
resource:
|
||||
apiVersion: cert-manager.io/v1
|
||||
kind: Certificate
|
||||
metadata:
|
||||
name: e2e-system-bucket-s3
|
||||
status:
|
||||
(conditions[?type == 'Ready']):
|
||||
- status: "True"
|
||||
- assert:
|
||||
timeout: 3m
|
||||
resource:
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: e2e-system-bucket-probe
|
||||
status:
|
||||
(conditions[?type == 'Ready']):
|
||||
- status: "True"
|
||||
# The Certificate's Secret carries no owner reference, so it outlives the
|
||||
# Certificate, and cert-manager issues it again while the Certificate
|
||||
# exists. Chainsaw runs a step's cleanup ops after this step's cleaner has
|
||||
# deleted the Certificate and waited for it.
|
||||
cleanup:
|
||||
- delete:
|
||||
ref:
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
name: e2e-system-bucket-s3-tls
|
||||
|
||||
- name: create-clickhouse
|
||||
try:
|
||||
- apply:
|
||||
file: clickhouse-system-bucket.yaml
|
||||
# 11m: above the 600s install timeout cozystack-api gives this release;
|
||||
# see "Sizing an HR-Ready budget" in docs/agents/e2e-testing.md.
|
||||
- assert:
|
||||
timeout: 11m
|
||||
resource:
|
||||
apiVersion: helm.toolkit.fluxcd.io/v2
|
||||
kind: HelmRelease
|
||||
metadata:
|
||||
name: clickhouse-sysbucket
|
||||
status:
|
||||
(conditions[?type == 'Ready']):
|
||||
- status: "True"
|
||||
- assert:
|
||||
timeout: 5m
|
||||
resource:
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: chi-clickhouse-sysbucket-clickhouse-0-0
|
||||
status:
|
||||
readyReplicas: 1
|
||||
# The Pod is running with no projected credentials: the state the first
|
||||
# BackupJob of a fresh release meets.
|
||||
- error:
|
||||
timeout: 30s
|
||||
resource:
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: cozy-backups-creds
|
||||
|
||||
- name: run
|
||||
try:
|
||||
# Inner budgets of system-bucket-roundtrip.sh:
|
||||
# 280s probe: a 240s deadline for CoreDNS picking up the rewrite and
|
||||
# the Ingress serving the Test certificate, plus one last 30s
|
||||
# attempt and its 10s pause
|
||||
# 480s BackupJob to Succeeded, including the driver's 2m hold
|
||||
# 480s RestoreJob to Succeeded; no hold by then, the stamp is
|
||||
# already older than the backup's own 2m wait
|
||||
# 90s the EXIT trap: Corefile replace plus a 60s Secret delete
|
||||
# 1330s (22m10s)
|
||||
# 25m leaves 2m50s for the SQL and kubectl calls between those waits, so
|
||||
# an inner wait is what fires and names what stalled.
|
||||
- script:
|
||||
timeout: 25m
|
||||
content: |
|
||||
set -eu
|
||||
cd ../../..
|
||||
NAMESPACE="$NAMESPACE" hack/e2e-chainsaw/clickhouse/system-bucket-roundtrip.sh
|
||||
check:
|
||||
($error == null): true
|
||||
finally:
|
||||
# The script's EXIT trap puts the Corefile and the Ingress TLS Secret
|
||||
# back, but a step ceiling kills the shell before the trap runs. A no-op
|
||||
# when the trap already did it.
|
||||
- description: restore the host CoreDNS and the S3 Ingress TLS Secret
|
||||
script:
|
||||
timeout: 2m
|
||||
content: |
|
||||
set -eu
|
||||
cd ../../..
|
||||
# Chainsaw runs this under sh; the helpers are bash.
|
||||
NAMESPACE="$NAMESPACE" bash -euo pipefail -c '
|
||||
source examples/backups/clickhouse/00-helpers.sh
|
||||
source hack/e2e-chainsaw/clickhouse/system-bucket-shared-state.sh
|
||||
restore_shared_state
|
||||
'
|
||||
# Chainsaw did not apply these: the jobs come from the script and the
|
||||
# Backup from the controller, and deleting a BackupJob reclaims no Backup.
|
||||
- description: system-bucket round-trip cleanup
|
||||
script:
|
||||
timeout: 3m
|
||||
content: |
|
||||
set -eu
|
||||
kubectl -n "$NAMESPACE" delete restorejob sysbucket-restore --ignore-not-found --wait=true --timeout=30s
|
||||
kubectl -n "$NAMESPACE" delete backupjob sysbucket-backup --ignore-not-found --wait=true --timeout=30s
|
||||
# The driver names the Backup after the BackupJob; by name it is
|
||||
# found even when status.backupRef was never written.
|
||||
kubectl -n "$NAMESPACE" delete backup sysbucket-backup --ignore-not-found --wait=true --timeout=60s
|
||||
@@ -8,8 +8,8 @@
|
||||
# backup.enabled=true with placeholder S3 coordinates is deliberate: the
|
||||
# sidecar runs `clickhouse-backup server`, which starts its HTTP API without
|
||||
# validating S3 (ALLOW_EMPTY_BACKUPS=true, lazy connect — the same reason the
|
||||
# platform useSystemBucket flow marks the S3 secret keys optional so the Pod
|
||||
# starts before any bucket is projected). So the Pod becomes Ready and the
|
||||
# platform useSystemBucket flow can start the Pod before any bucket is
|
||||
# projected). So the Pod becomes Ready and the
|
||||
# chart<->strategy contract is assertable with no reachable object store. The
|
||||
# real S3 backup/restore round-trip lives in clickhouse-2-backup-roundtrip,
|
||||
# which runs in tenant-root against the in-cluster SeaweedFS.
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# ClickHouse on the platform system bucket for the
|
||||
# clickhouse-3-system-bucket-roundtrip Test. No S3 coordinates are given: the
|
||||
# sidecar reads them from the clickhouse-backup.yml key the platform projects
|
||||
# into cozy-backups-creds at the first BackupJob, after this Pod has started.
|
||||
# backup.endpointCA trusts the SeaweedFS CA that signs the certificate the Test
|
||||
# serves for s3.example.org.
|
||||
apiVersion: apps.cozystack.io/v1alpha1
|
||||
kind: ClickHouse
|
||||
metadata:
|
||||
name: sysbucket
|
||||
spec:
|
||||
size: 5Gi
|
||||
logStorageSize: 1Gi
|
||||
shards: 1
|
||||
replicas: 1
|
||||
# The round-trip runs SQL against this server; at nano's 128Mi the first
|
||||
# query OOM-kills it, so it takes the preset clickhouse-2 runs SQL on.
|
||||
resourcesPreset: small
|
||||
resources: {}
|
||||
backup:
|
||||
enabled: true
|
||||
useSystemBucket: true
|
||||
endpointCA:
|
||||
name: e2e-system-bucket-s3-tls
|
||||
key: ca.crt
|
||||
clickhouseKeeper:
|
||||
enabled: true
|
||||
replicas: 1
|
||||
size: 1Gi
|
||||
resourcesPreset: micro
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
#!/bin/bash
|
||||
# Backup and in-place restore of the `sysbucket` ClickHouse through the
|
||||
# cozy-default BackupClass, against the platform system bucket. Run from the
|
||||
# repository root by the clickhouse-3-system-bucket-roundtrip Test, which has
|
||||
# already started the release with no cozy-backups-creds in its namespace.
|
||||
#
|
||||
# The system bucket is addressed as https://s3.example.org, the S3 Ingress host
|
||||
# the COSI driver advertises. In CI that name does not resolve and its ACME
|
||||
# certificate is never issued, so for the duration of this script, and only of
|
||||
# this script, two shared objects are changed and the EXIT trap below puts both
|
||||
# back:
|
||||
#
|
||||
# - the S3 Ingress TLS Secret seaweedfs-s3-ingress-tls is created from the
|
||||
# Test's own certificate (SeaweedFS CA, s3.example.org). It relies on
|
||||
# cert-manager leaving a Secret's data alone while the Certificate that
|
||||
# names it has no completed issuance, verified with cert-manager v1.20.2:
|
||||
# a fresh ACME order would replace this certificate, and ingress-nginx
|
||||
# would then serve one the sidecar does not trust, which fails the probe
|
||||
# below rather than the backup.
|
||||
# - the host CoreDNS Corefile gets one marked `rewrite name exact` line for
|
||||
# s3.example.org. The host CoreDNS is Talos-managed and imports no snippet
|
||||
# files, so the block goes into the live Corefile the way ouroboros writes
|
||||
# its own; ouroboros is off in CI and no other suite uses this name.
|
||||
set -euo pipefail
|
||||
|
||||
source examples/backups/clickhouse/00-helpers.sh
|
||||
source hack/e2e-chainsaw/clickhouse/system-bucket-shared-state.sh
|
||||
|
||||
: "${NAMESPACE:?}"
|
||||
CLICKHOUSE_NAME=sysbucket
|
||||
BACKUPJOB_NAME=sysbucket-backup
|
||||
RESTOREJOB_NAME=sysbucket-restore
|
||||
CERT_SECRET=e2e-system-bucket-s3-tls
|
||||
PROBE_POD=e2e-system-bucket-probe
|
||||
DNS_TARGET="root-ingress-controller.${NAMESPACE}.svc.cozy.local"
|
||||
# Kubelet refreshes a ConfigMap volume within about a minute and CoreDNS's
|
||||
# reload plugin polls every 30s; the rest is the 30s answer cache.
|
||||
PROBE_TIMEOUT=240
|
||||
# Each covers the driver's 2m hold after the credentials change plus the
|
||||
# strategy Job itself.
|
||||
JOB_TIMEOUT=480
|
||||
|
||||
workdir=$(mktemp -d)
|
||||
|
||||
on_exit() {
|
||||
local rc=$?
|
||||
set +e
|
||||
restore_shared_state || rc=1
|
||||
rm -rf "$workdir"
|
||||
exit "$rc"
|
||||
}
|
||||
|
||||
if kubectl -n "$NAMESPACE" get secret "$INGRESS_SECRET" -o name >/dev/null 2>&1; then
|
||||
log_error "Secret ${NAMESPACE}/${INGRESS_SECRET} already exists; this Test serves its own certificate under that name and will not overwrite one it did not create"
|
||||
exit 1
|
||||
fi
|
||||
if corefile_has_block; then
|
||||
log_error "kube-system/coredns already carries the ${S3_HOST} rewrite block, left by an earlier run; remove it by hand"
|
||||
exit 1
|
||||
fi
|
||||
trap on_exit EXIT
|
||||
|
||||
log_step "Serving the Test certificate for ${S3_HOST} through the platform S3 Ingress"
|
||||
kubectl -n "$NAMESPACE" get secret "$CERT_SECRET" -o json \
|
||||
| jq --arg name "$INGRESS_SECRET" '{apiVersion, kind, type,
|
||||
metadata: {name: $name, labels: {"cozystack.io/e2e-owner": "clickhouse-system-bucket"}},
|
||||
data: {"tls.crt": .data["tls.crt"], "tls.key": .data["tls.key"], "ca.crt": .data["ca.crt"]}}' \
|
||||
| kubectl -n "$NAMESPACE" create -f -
|
||||
|
||||
log_step "Rewriting ${S3_HOST} to ${DNS_TARGET} in the host CoreDNS"
|
||||
kubectl -n kube-system get configmap coredns -o json >"$workdir/coredns.json"
|
||||
jq -e '.data.Corefile | startswith(".:53 {\n")' "$workdir/coredns.json" >/dev/null \
|
||||
|| { log_error "kube-system/coredns Corefile does not open with '.:53 {'; refusing to edit it"; exit 1; }
|
||||
# The resourceVersion read above travels with the replace, so a concurrent
|
||||
# writer makes it fail instead of being overwritten.
|
||||
jq --arg block "${DNS_BEGIN}"$'\n'" rewrite name exact ${S3_HOST} ${DNS_TARGET}"$'\n'"${DNS_END}" \
|
||||
'.data.Corefile |= sub("^\\.:53 \\{\n"; ".:53 {\n" + $block + "\n")' \
|
||||
"$workdir/coredns.json" >"$workdir/coredns-new.json"
|
||||
kubectl replace -f "$workdir/coredns-new.json" >/dev/null
|
||||
|
||||
log_step "Checking that ${S3_HOST} serves the Test certificate from inside ${NAMESPACE}"
|
||||
kubectl -n "$NAMESPACE" get secret "$CERT_SECRET" -o jsonpath='{.data.ca\.crt}' | base64 -d >"$workdir/ca.crt"
|
||||
want=$(kubectl -n "$NAMESPACE" get secret "$CERT_SECRET" -o jsonpath='{.data.tls\.crt}' | base64 -d \
|
||||
| openssl x509 -noout -fingerprint -sha256)
|
||||
deadline=$((SECONDS + PROBE_TIMEOUT))
|
||||
while true; do
|
||||
# --cacert makes curl verify both the chain and the host name; %{certs}
|
||||
# prints the chain it was served, leaf first.
|
||||
if served=$(timeout 30 kubectl -n "$NAMESPACE" exec -i "$PROBE_POD" -- sh -c \
|
||||
"cat >/tmp/ca.crt && curl -sS -o /dev/null --max-time 10 --cacert /tmp/ca.crt -w '%{certs}' https://${S3_HOST}/" \
|
||||
<"$workdir/ca.crt" 2>"$workdir/probe.err"); then
|
||||
got=$(printf '%s\n' "$served" | sed -n '/BEGIN CERTIFICATE/,/END CERTIFICATE/p;/END CERTIFICATE/q' \
|
||||
| openssl x509 -noout -fingerprint -sha256)
|
||||
if [ "$got" = "$want" ]; then
|
||||
log_success "${S3_HOST} resolves in ${NAMESPACE} and serves the Test certificate"
|
||||
break
|
||||
fi
|
||||
echo "served ${got}, want ${want}" >"$workdir/probe.err"
|
||||
fi
|
||||
if [ "$SECONDS" -ge "$deadline" ]; then
|
||||
log_error "${S3_HOST} did not serve the Test certificate within ${PROBE_TIMEOUT}s: $(cat "$workdir/probe.err")"
|
||||
kubectl -n kube-system get configmap coredns -o jsonpath='{.data.Corefile}' >&2 || true
|
||||
kubectl -n "$NAMESPACE" describe ingress ingress-seaweedfs-s3 >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
# TODO(e2e-replace-fixed-timeouts): no condition reports that the host
|
||||
# CoreDNS answers with the rewrite and the Ingress serves the Test
|
||||
# certificate, as seen from this namespace; poll until one does.
|
||||
sleep 10
|
||||
done
|
||||
|
||||
# A restarted Pod reads its credentials afresh at start, which is what the
|
||||
# old environment-based sidecar needed; the round-trip proves the fix only if
|
||||
# the sidecar that started without them is the one that serves both jobs.
|
||||
sidecar_identity() {
|
||||
kubectl -n "$NAMESPACE" get pod "chi-clickhouse-${CLICKHOUSE_NAME}-clickhouse-0-0-0" \
|
||||
-o jsonpath='{.metadata.uid} {.status.containerStatuses[?(@.name=="clickhouse-backup")].restartCount}'
|
||||
}
|
||||
sidecar_before=$(sidecar_identity)
|
||||
[[ "$sidecar_before" =~ ^[0-9a-f-]+\ [0-9]+$ ]] \
|
||||
|| { log_error "could not read the ClickHouse Pod uid and clickhouse-backup restart count (got '${sidecar_before}')"; exit 1; }
|
||||
|
||||
# Restore takes the archive this run's Backup recorded; a row no earlier run
|
||||
# wrote is what shows the data restored is that archive's.
|
||||
sentinel="before-backup-$(date -u +%Y%m%dT%H%M%SZ)-${RANDOM}"
|
||||
log_step "Writing the sentinel row ${sentinel}"
|
||||
clickhouse_query "$CLICKHOUSE_NAME" "CREATE TABLE IF NOT EXISTS default.sentinel (id UInt32, name String) ENGINE = MergeTree ORDER BY id"
|
||||
clickhouse_query "$CLICKHOUSE_NAME" "INSERT INTO default.sentinel VALUES (1, '${sentinel}')"
|
||||
|
||||
log_step "Backing up through cozy-default"
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: backups.cozystack.io/v1alpha1
|
||||
kind: BackupJob
|
||||
metadata:
|
||||
name: ${BACKUPJOB_NAME}
|
||||
namespace: ${NAMESPACE}
|
||||
spec:
|
||||
applicationRef:
|
||||
apiGroup: apps.cozystack.io
|
||||
kind: ClickHouse
|
||||
name: ${CLICKHOUSE_NAME}
|
||||
backupClassName: cozy-default
|
||||
EOF
|
||||
wait_for_field backupjob "$BACKUPJOB_NAME" '{.status.phase}' Succeeded "$NAMESPACE" "$JOB_TIMEOUT" Failed
|
||||
backup_ref=$(kubectl -n "$NAMESPACE" get backupjob "$BACKUPJOB_NAME" -o jsonpath='{.status.backupRef.name}')
|
||||
[ -n "$backup_ref" ] || { log_error "BackupJob ${BACKUPJOB_NAME} succeeded with an empty backupRef"; exit 1; }
|
||||
|
||||
# The sidecar started before this Secret existed; a backup that succeeded
|
||||
# against it is the behaviour under test, and the key it read is this one.
|
||||
endpoint=$(kubectl -n "$NAMESPACE" get secret cozy-backups-creds -o jsonpath='{.data.clickhouse-backup\.yml}' | base64 -d \
|
||||
| sed -n 's/^ *endpoint: *//p')
|
||||
[ "$endpoint" = "https://${S3_HOST}" ] \
|
||||
|| { log_error "cozy-backups-creds clickhouse-backup.yml endpoint is '${endpoint}', expected https://${S3_HOST}"; exit 1; }
|
||||
|
||||
log_step "Restoring in place through cozy-default"
|
||||
clickhouse_query "$CLICKHOUSE_NAME" "DROP TABLE IF EXISTS default.sentinel SYNC"
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: backups.cozystack.io/v1alpha1
|
||||
kind: RestoreJob
|
||||
metadata:
|
||||
name: ${RESTOREJOB_NAME}
|
||||
namespace: ${NAMESPACE}
|
||||
spec:
|
||||
backupRef:
|
||||
name: ${backup_ref}
|
||||
EOF
|
||||
wait_for_field restorejob "$RESTOREJOB_NAME" '{.status.phase}' Succeeded "$NAMESPACE" "$JOB_TIMEOUT" Failed
|
||||
|
||||
count=$(clickhouse_query "$CLICKHOUSE_NAME" "SELECT count() FROM default.sentinel WHERE name = '${sentinel}'" | tr -d '[:space:]')
|
||||
[ "$count" = 1 ] || { log_error "after restore default.sentinel holds ${count} row(s) named ${sentinel}; expected 1"; exit 1; }
|
||||
sidecar_after=$(sidecar_identity)
|
||||
[ "$sidecar_after" = "$sidecar_before" ] \
|
||||
|| { log_error "the ClickHouse Pod or its clickhouse-backup container restarted during the round-trip (uid restarts: '${sidecar_before}' then '${sidecar_after}')"; exit 1; }
|
||||
log_success "System-bucket round-trip verified: sentinel row ${sentinel} restored"
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/bin/bash
|
||||
# The two shared objects system-bucket-roundtrip.sh changes for the duration
|
||||
# of its run, and how to put them back. Sourced by that script, whose EXIT trap
|
||||
# restores them, and by the finally of its Chainsaw step, which restores them
|
||||
# when the step ceiling killed the script before the trap could run. Needs
|
||||
# NAMESPACE and log_success/log_error from examples/backups/clickhouse/00-helpers.sh.
|
||||
|
||||
S3_HOST=s3.example.org
|
||||
INGRESS_SECRET=seaweedfs-s3-ingress-tls
|
||||
OWNER_LABEL=cozystack.io/e2e-owner=clickhouse-system-bucket
|
||||
DNS_BEGIN=' # === BEGIN e2e-clickhouse-system-bucket ==='
|
||||
DNS_END=' # === END e2e-clickhouse-system-bucket ==='
|
||||
|
||||
corefile_has_block() {
|
||||
kubectl -n kube-system get configmap coredns -o jsonpath='{.data.Corefile}' | grep -qF -- "$DNS_BEGIN"
|
||||
}
|
||||
|
||||
remove_dns_block() {
|
||||
local dir
|
||||
dir=$(mktemp -d)
|
||||
kubectl -n kube-system get configmap coredns -o json >"$dir/coredns.json" || { rm -rf "$dir"; return 1; }
|
||||
local begins
|
||||
begins=$(jq -r '.data.Corefile' "$dir/coredns.json" | grep -cF -- "$DNS_BEGIN" || true)
|
||||
if [ "$begins" = 0 ]; then
|
||||
rm -rf "$dir"
|
||||
return 0
|
||||
fi
|
||||
if [ "$begins" != 1 ] || ! jq -r '.data.Corefile' "$dir/coredns.json" | grep -qF -- "$DNS_END"; then
|
||||
log_error "kube-system/coredns holds ${begins} '${DNS_BEGIN# *}' markers or no END marker; reconcile the Corefile by hand"
|
||||
rm -rf "$dir"
|
||||
return 1
|
||||
fi
|
||||
jq --arg b "$DNS_BEGIN" --arg e "$DNS_END" \
|
||||
'.data.Corefile |= (split("\n") | (index($b)) as $i | (index($e)) as $j | .[:$i] + .[$j+1:] | join("\n"))' \
|
||||
"$dir/coredns.json" >"$dir/coredns-clean.json"
|
||||
# Callers run this with errexit off, so a refused replace has to return.
|
||||
if ! kubectl replace -f "$dir/coredns-clean.json" >/dev/null; then
|
||||
log_error "could not remove the ${S3_HOST} rewrite from kube-system/coredns; remove the marked block by hand"
|
||||
rm -rf "$dir"
|
||||
return 1
|
||||
fi
|
||||
log_success "Removed the ${S3_HOST} rewrite from kube-system/coredns"
|
||||
rm -rf "$dir"
|
||||
}
|
||||
|
||||
# Returns non-zero when either object could not be put back.
|
||||
restore_shared_state() {
|
||||
local rc=0
|
||||
remove_dns_block || rc=1
|
||||
# kubectl refuses a name together with a selector, so the label is
|
||||
# looked up on its own and the name matched in what comes back.
|
||||
local owned
|
||||
if ! owned=$(kubectl -n "$NAMESPACE" get secret -l "$OWNER_LABEL" -o name); then
|
||||
log_error "could not list the Secrets labelled ${OWNER_LABEL} in ${NAMESPACE}; delete ${INGRESS_SECRET} by hand if it carries that label"
|
||||
rc=1
|
||||
elif printf '%s\n' "$owned" | grep -qxF "secret/$INGRESS_SECRET"; then
|
||||
kubectl -n "$NAMESPACE" delete secret "$INGRESS_SECRET" --wait=true --timeout=60s || rc=1
|
||||
fi
|
||||
return "$rc"
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# Certificate and probe Pod for the clickhouse-3-system-bucket-roundtrip Test.
|
||||
#
|
||||
# The certificate is signed by the SeaweedFS CA already present in tenant-root,
|
||||
# so its Secret carries that CA as ca.crt: the ClickHouse release trusts it via
|
||||
# backup.endpointCA, and the round-trip script copies the same key pair under
|
||||
# the name the platform's S3 Ingress serves for s3.example.org.
|
||||
apiVersion: cert-manager.io/v1
|
||||
kind: Certificate
|
||||
metadata:
|
||||
name: e2e-system-bucket-s3
|
||||
spec:
|
||||
secretName: e2e-system-bucket-s3-tls
|
||||
dnsNames:
|
||||
- s3.example.org
|
||||
issuerRef:
|
||||
kind: Issuer
|
||||
name: seaweedfs-ca-issuer
|
||||
---
|
||||
# Resolves and fetches s3.example.org from inside tenant-root, where the
|
||||
# ClickHouse sidecar runs, so the script can prove the DNS rewrite and the
|
||||
# served certificate before it spends minutes on a BackupJob. The image is the
|
||||
# one hack/e2e-install-cozystack.bats pre-pulls; it carries curl but no openssl.
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: e2e-system-bucket-probe
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
terminationGracePeriodSeconds: 0
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 65534
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: probe
|
||||
image: docker.io/alpine/k8s:1.36.2@sha256:44ef4942e171939b9c665a4a84beb80e2dcdb9a24330d4651cfdfd2e9deecc47
|
||||
command: [sleep, "3600"]
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities:
|
||||
drop: [ALL]
|
||||
@@ -35,7 +35,7 @@
|
||||
# and the teardown. This is the third suite in a full run that brings up a
|
||||
# tenant cluster, next to kubernetes-latest and kubernetes-previous. A failure
|
||||
# that stalls worker join everywhere reddens all three, and their red paths
|
||||
# together can exceed the E2E job's 215-minute cap, which cancels the job and
|
||||
# together can exceed the E2E job's 265-minute cap, which cancels the job and
|
||||
# loses its log and report. The cap is sized for the red path of the
|
||||
# kubernetes pair only; this suite is not counted in it, and that is an
|
||||
# accepted risk.
|
||||
|
||||
@@ -80,7 +80,8 @@ spec:
|
||||
# wait, all on the passing path. Raising the ceiling to cover them is not
|
||||
# available -- the guard in hack/run-kubernetes-serial-console_test.bats
|
||||
# holds COZY_OP_CEILING equal to BOTH suites' `timeout:`, and two suites
|
||||
# at 79m plus their 22m teardowns exceed the job's own 215-minute cap.
|
||||
# at 79m plus their 22m teardowns take 202m, which with the install and
|
||||
# the rest of a full run does not fit the job's own 265-minute cap.
|
||||
# What is available is a measurement: on the green run of this branch
|
||||
# (33724179053) the whole Test took 569.72s against this 4020s op, with
|
||||
# kubernetes-previous, which carries no OIDC fold, at 470.19s. The
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
# Namespace logs through the observability proxy, as the console reaches
|
||||
# them: every request goes through the console nginx (a port-forward to its
|
||||
# Service), which routes the logs root to the proxy, which authenticates the
|
||||
# bearer token, asks a SubjectAccessReview and forwards a rebuilt query to
|
||||
# the tenant's log store.
|
||||
#
|
||||
# Two sibling tenants, A (logsa) and B (logsb), both under tenant-test, so
|
||||
# both resolve to the root log store. A viewer of A reads A's logs and is
|
||||
# refused B's; parameters and headers a client adds cannot widen the scope
|
||||
# (the proxy forces the namespace filter and tenant 0:0); a live tail stays
|
||||
# open and keeps delivering lines past 60s.
|
||||
#
|
||||
# Not covered here: the OIDC gatekeeper (oauth2-proxy) in front of nginx,
|
||||
# because driving a Keycloak login needs a browser; and Fluent Bit writing
|
||||
# real pod logs, because the root log store is off in e2e and this suite
|
||||
# seeds its own (log-store.yaml).
|
||||
apiVersion: chainsaw.kyverno.io/v1alpha1
|
||||
kind: Test
|
||||
metadata:
|
||||
name: observability-proxy-logs
|
||||
spec:
|
||||
catch:
|
||||
- events: {}
|
||||
- podLogs:
|
||||
namespace: cozy-observability-proxy
|
||||
selector: app.kubernetes.io/name=observability-proxy
|
||||
tail: 100
|
||||
- podLogs:
|
||||
namespace: tenant-root
|
||||
selector: app.kubernetes.io/name=e2e-observability-log-store
|
||||
tail: 100
|
||||
- podLogs:
|
||||
namespace: cozy-dashboard
|
||||
selector: app.kubernetes.io/name=console
|
||||
tail: 100
|
||||
steps:
|
||||
- name: proxy-available
|
||||
try:
|
||||
- assert:
|
||||
resource:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: observability-proxy
|
||||
namespace: cozy-observability-proxy
|
||||
status:
|
||||
(conditions[?type == 'Available']):
|
||||
- status: "True"
|
||||
|
||||
- name: tenants
|
||||
try:
|
||||
- apply:
|
||||
resource:
|
||||
apiVersion: apps.cozystack.io/v1alpha1
|
||||
kind: Tenant
|
||||
metadata:
|
||||
name: logsa
|
||||
spec: {}
|
||||
- apply:
|
||||
resource:
|
||||
apiVersion: apps.cozystack.io/v1alpha1
|
||||
kind: Tenant
|
||||
metadata:
|
||||
name: logsb
|
||||
spec: {}
|
||||
# 16m: tenant-rd's 15m install timeout plus the 60s start margin; see
|
||||
# "Sizing an HR-Ready budget" in docs/agents/e2e-testing.md. Waited so
|
||||
# that cleanup does not uninstall a release whose install still runs.
|
||||
- assert:
|
||||
timeout: 16m
|
||||
resource:
|
||||
apiVersion: helm.toolkit.fluxcd.io/v2
|
||||
kind: HelmRelease
|
||||
metadata:
|
||||
name: tenant-logsa
|
||||
status:
|
||||
(conditions[?type == 'Ready']):
|
||||
- status: "True"
|
||||
- assert:
|
||||
timeout: 16m
|
||||
resource:
|
||||
apiVersion: helm.toolkit.fluxcd.io/v2
|
||||
kind: HelmRelease
|
||||
metadata:
|
||||
name: tenant-logsb
|
||||
status:
|
||||
(conditions[?type == 'Ready']):
|
||||
- status: "True"
|
||||
# The label names the store the proxy reads; the seeded store below
|
||||
# stands in for the root one, so both namespaces must resolve to it.
|
||||
- assert:
|
||||
resource:
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: tenant-test-logsa
|
||||
labels:
|
||||
namespace.cozystack.io/monitoring: tenant-root
|
||||
- assert:
|
||||
resource:
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: tenant-test-logsb
|
||||
labels:
|
||||
namespace.cozystack.io/monitoring: tenant-root
|
||||
|
||||
- name: viewer-and-store
|
||||
try:
|
||||
# Applying over a real root store would rewrite its Service; refuse to.
|
||||
- error:
|
||||
resource:
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: vlselect-generic
|
||||
namespace: tenant-root
|
||||
- apply:
|
||||
file: viewer.yaml
|
||||
- apply:
|
||||
file: log-store.yaml
|
||||
- assert:
|
||||
timeout: 3m
|
||||
resource:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: e2e-observability-log-store
|
||||
namespace: tenant-root
|
||||
status:
|
||||
(conditions[?type == 'Available']):
|
||||
- status: "True"
|
||||
|
||||
- name: seed-logs
|
||||
try:
|
||||
- script:
|
||||
# 30s forward + 3 x 15s ingests + 3 x 30s visibility polls, each
|
||||
# capped on its own, under a 4m op.
|
||||
timeout: 4m
|
||||
content: |
|
||||
set -eu
|
||||
. ./lib.sh
|
||||
trap 'for p in ${pf_pids:-}; do kill "$p" 2>/dev/null || true; done; rm -f "$body"' EXIT
|
||||
forward tenant-root vlselect-generic 19471:9471
|
||||
ingest tenant-test-logsa e2e-marker-a
|
||||
ingest tenant-test-logsb e2e-marker-b
|
||||
# Same namespace, another VictoriaLogs tenant: reachable only if a
|
||||
# client AccountID header got through.
|
||||
ingest tenant-test-logsa e2e-marker-account7 7
|
||||
# All three must be searchable, or an absence checked later
|
||||
# proves nothing.
|
||||
for m in e2e-marker-a:0 e2e-marker-b:0 e2e-marker-account7:7; do
|
||||
timeout 30 sh -ec "until curl --silent --fail --header 'AccountID: ${m#*:}' '$STORE/select/logsql/query?query=${m%:*}' | grep -q ${m%:*}; do sleep 1; done"
|
||||
done
|
||||
|
||||
- name: namespace-scope
|
||||
try:
|
||||
- script:
|
||||
# 30s forward + one 30s token request + 10 calls capped at 30s.
|
||||
timeout: 8m
|
||||
content: |
|
||||
set -eu
|
||||
. ./lib.sh
|
||||
trap 'for p in ${pf_pids:-}; do kill "$p" 2>/dev/null || true; done; rm -f "$body"' EXIT
|
||||
forward cozy-dashboard cozy-dashboard-console 18080:8080
|
||||
token=$(k -n tenant-test-logsa create token logs-viewer --duration=10m)
|
||||
auth="Authorization: Bearer $token"
|
||||
|
||||
code=$(call "$LOGS_A/query?query=*")
|
||||
expect 401 "$code" "no token"
|
||||
|
||||
code=$(call "$LOGS_A/query?query=*" --header "$auth")
|
||||
expect 200 "$code" "viewer reads A"
|
||||
grep -q e2e-marker-a "$body" || { echo "FAIL: A's own line is missing" >&2; cat "$body" >&2; exit 1; }
|
||||
absent e2e-marker-b "viewer reads A"
|
||||
absent e2e-marker-account7 "viewer reads A"
|
||||
|
||||
code=$(call "$LOGS_B/query?query=*" --header "$auth")
|
||||
expect 403 "$code" "viewer reads B"
|
||||
|
||||
code=$(call "$LOGS_A/query" --header "$auth" --get \
|
||||
--data-urlencode 'query=*' \
|
||||
--data-urlencode 'extra_stream_filters={kubernetes_namespace_name="tenant-test-logsb"}' \
|
||||
--data-urlencode 'extra_filters=kubernetes_namespace_name:tenant-test-logsb')
|
||||
expect 200 "$code" "client extra filters in the query string"
|
||||
absent e2e-marker-b "client extra filters in the query string"
|
||||
|
||||
code=$(call "$LOGS_A/query" --header "$auth" \
|
||||
--data-urlencode 'query=*' \
|
||||
--data-urlencode 'extra_stream_filters={kubernetes_namespace_name="tenant-test-logsb"}')
|
||||
expect 200 "$code" "client extra filters in a POST form"
|
||||
absent e2e-marker-b "client extra filters in a POST form"
|
||||
|
||||
code=$(call "$LOGS_A/query?query=*" --header "$auth" --header "AccountID: 7" --header "ProjectID: 0")
|
||||
expect 200 "$code" "client AccountID header"
|
||||
absent e2e-marker-account7 "client AccountID header"
|
||||
|
||||
code=$(call "$LOGS_A/query" --header "$auth" --get \
|
||||
--data-urlencode 'query={kubernetes_namespace_name="tenant-test-logsb"}')
|
||||
expect 200 "$code" "B's stream named in the query"
|
||||
absent e2e-marker-b "B's stream named in the query"
|
||||
|
||||
code=$(call "$LOGS_A/query" --header "$auth" --get \
|
||||
--data-urlencode 'query=options(ignore_global_time_filter=true) *')
|
||||
expect 400 "$code" "query options"
|
||||
|
||||
# nginx routes on the normalised path, which is B's logs root, and
|
||||
# forwards the raw one; the proxy must refuse it, not read B.
|
||||
code=$(call "$LOGS_A/../../../../tenant-test-logsb/logs/select/logsql/query?query=*" --path-as-is --header "$auth")
|
||||
expect 400 "$code" "dot segments toward B"
|
||||
|
||||
code=$(call "$LOGS_A/delete?query=*" --header "$auth")
|
||||
expect 404 "$code" "an endpoint outside the allowlist"
|
||||
|
||||
- name: tail-outlives-a-minute
|
||||
try:
|
||||
- script:
|
||||
# 2 x 30s forwards + 30s token + 3 x 15s ingests + the 70s hold +
|
||||
# the 30s delivery poll; the tail itself is cut at 150s.
|
||||
timeout: 6m
|
||||
content: |
|
||||
set -eu
|
||||
. ./lib.sh
|
||||
tail_out=$(mktemp)
|
||||
trap 'kill "${tail_pid:-}" 2>/dev/null || true; for p in ${pf_pids:-}; do kill "$p" 2>/dev/null || true; done; rm -f "$body" "$tail_out"' EXIT
|
||||
forward tenant-root vlselect-generic 19471:9471
|
||||
forward cozy-dashboard cozy-dashboard-console 18080:8080
|
||||
token=$(k -n tenant-test-logsa create token logs-viewer --duration=10m)
|
||||
|
||||
# The tail is not subscribed yet when the next ingest runs, so it
|
||||
# replays the last minute to include the early line.
|
||||
timeout 150 curl --silent --no-buffer --header "Authorization: Bearer $token" \
|
||||
"$CONSOLE$LOGS_A/tail?query=*&start_offset=1m" > "$tail_out" &
|
||||
tail_pid=$!
|
||||
ingest tenant-test-logsa e2e-tail-early
|
||||
ingest tenant-test-logsb e2e-tail-b
|
||||
# TODO(e2e-replace-fixed-timeouts): this hold stands in for a
|
||||
# duration assertion the harness lacks; the property under test is
|
||||
# that a tail survives a minute with the client sending nothing.
|
||||
sleep 70
|
||||
if ! kill -0 "$tail_pid" 2>/dev/null; then
|
||||
echo "FAIL: the tail closed before 70s" >&2
|
||||
cat "$tail_out" >&2
|
||||
exit 1
|
||||
fi
|
||||
ingest tenant-test-logsa e2e-tail-late
|
||||
# vlselect re-reads every second, five seconds behind now.
|
||||
timeout 30 sh -ec "until grep -q e2e-tail-late '$tail_out'; do sleep 1; done" || {
|
||||
echo "FAIL: a line written at 70s did not reach the open tail" >&2
|
||||
cat "$tail_out" >&2
|
||||
exit 1
|
||||
}
|
||||
grep -q e2e-tail-early "$tail_out" || { echo "FAIL: the early line is missing from the tail" >&2; exit 1; }
|
||||
if grep -q e2e-tail-b "$tail_out"; then
|
||||
echo "FAIL: the tail of A delivered B's line" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,58 @@
|
||||
# shellcheck shell=sh
|
||||
# Shared by the script steps of this suite, whose cwd is this directory.
|
||||
# Every call carries its own cap so a hang fails at a known budget rather
|
||||
# than at the op ceiling (docs/agents/e2e-testing.md, section 8).
|
||||
|
||||
k() { timeout 30 kubectl "$@"; }
|
||||
|
||||
STORE=http://localhost:19471
|
||||
CONSOLE=http://localhost:18080
|
||||
# shellcheck disable=SC2034 # read by the steps that source this file
|
||||
LOGS_A=/apis/cozystack.io/v1alpha1/namespaces/tenant-test-logsa/logs/select/logsql
|
||||
# shellcheck disable=SC2034
|
||||
LOGS_B=/apis/cozystack.io/v1alpha1/namespaces/tenant-test-logsb/logs/select/logsql
|
||||
|
||||
# forward <namespace> <service> <local>:<remote>. The caller's EXIT trap
|
||||
# kills every pid in pf_pids; the forward gets 30s to start listening.
|
||||
forward() {
|
||||
kubectl port-forward -n "$1" "service/$2" "$3" >/dev/null 2>&1 &
|
||||
pf_pids="${pf_pids:-} $!"
|
||||
timeout 30 sh -ec "until nc -z localhost ${3%%:*}; do sleep 1; done"
|
||||
}
|
||||
|
||||
# ingest <namespace> <message> [account]: one entry shaped as Fluent Bit
|
||||
# writes it, with kubernetes_namespace_name as a stream field.
|
||||
ingest() {
|
||||
printf '{"kubernetes_namespace_name":"%s","log":"%s"}\n' "$1" "$2" |
|
||||
timeout 15 curl --silent --show-error --fail --data-binary @- \
|
||||
--header 'Content-Type: application/json' --header "AccountID: ${3:-0}" --header "ProjectID: 0" \
|
||||
"$STORE/insert/jsonline?_stream_fields=kubernetes_namespace_name&_msg_field=log"
|
||||
}
|
||||
|
||||
# call <path> [curl args...]: a request through the console nginx, the way
|
||||
# the browser sends it. Prints the status; the body lands in $body.
|
||||
body=$(mktemp)
|
||||
call() {
|
||||
path=$1
|
||||
shift
|
||||
timeout 30 curl --silent --show-error --output "$body" --write-out '%{http_code}' "$@" "$CONSOLE$path"
|
||||
}
|
||||
|
||||
# expect <want-status> <got-status> <case>
|
||||
expect() {
|
||||
if [ "$1" != "$2" ]; then
|
||||
echo "FAIL: $3: HTTP $2, want $1" >&2
|
||||
cat "$body" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "ok: $3: HTTP $2"
|
||||
}
|
||||
|
||||
# absent <marker> <case>: the last body must not carry the marker.
|
||||
absent() {
|
||||
if grep -q "$1" "$body"; then
|
||||
echo "FAIL: $2: the response carries $1, which is outside the scope" >&2
|
||||
cat "$body" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
# A single-node VictoriaLogs under the name the proxy dials for a namespace
|
||||
# whose logs belong to the root tenant: vlselect-generic.tenant-root, port
|
||||
# 9471. The e2e install leaves root monitoring off, so the real one does not
|
||||
# exist; the suite seeds this one itself instead of waiting for Fluent Bit,
|
||||
# which keeps the test about the proxy's scope rather than log collection.
|
||||
# The version is the one victoria-metrics-operator v0.68.4 deploys.
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: e2e-observability-log-store
|
||||
namespace: tenant-root
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: e2e-observability-log-store
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/name: e2e-observability-log-store
|
||||
spec:
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 65534
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: victoria-logs
|
||||
image: docker.io/victoriametrics/victoria-logs:v1.47.0
|
||||
args:
|
||||
- -httpListenAddr=:9471
|
||||
- -storageDataPath=/storage
|
||||
- -retentionPeriod=1d
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 9471
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 128Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 256Mi
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
volumeMounts:
|
||||
- name: storage
|
||||
mountPath: /storage
|
||||
volumes:
|
||||
- name: storage
|
||||
emptyDir: {}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: vlselect-generic
|
||||
namespace: tenant-root
|
||||
spec:
|
||||
selector:
|
||||
app.kubernetes.io/name: e2e-observability-log-store
|
||||
ports:
|
||||
- name: http
|
||||
port: 9471
|
||||
targetPort: http
|
||||
@@ -0,0 +1,22 @@
|
||||
# The view level of tenant A and nothing else: a ServiceAccount of tenant A
|
||||
# bound to cozy:tenant:view in A's namespace only. Its token is a real bearer
|
||||
# token, so the proxy's TokenReview and SubjectAccessReview run unmocked.
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: logs-viewer
|
||||
namespace: tenant-test-logsa
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: logs-viewer
|
||||
namespace: tenant-test-logsa
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: ClusterRole
|
||||
name: cozy:tenant:view
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: logs-viewer
|
||||
namespace: tenant-test-logsa
|
||||
@@ -347,3 +347,148 @@ spec:
|
||||
set -eu
|
||||
cd ../../..
|
||||
NAMESPACE="$NAMESPACE" examples/backups/postgres/cleanup.sh
|
||||
---
|
||||
# A system database that a version before the refusal took over is handed back
|
||||
# by the next init-job run, and only what this chart marked changes hands.
|
||||
#
|
||||
# The helm-unittest and bats suites check the rendered SQL against a fake psql;
|
||||
# only a real PostgreSQL can say that the predicates select what they claim. The
|
||||
# state an older version left is rebuilt by hand as the superuser, since the
|
||||
# chart now refuses to produce it:
|
||||
# * postgres is commented as managed and owned by a postgres_admin role that
|
||||
# carries the cozystack:managed mark, as the chart left it: it must come back
|
||||
# to the superuser, and the role must be dropped;
|
||||
# * template1 is commented as managed, but its template1_admin carries only the
|
||||
# role comment, which a CREATEROLE holder can forge, and not the mark: the
|
||||
# comment must be cleared and everything that role owns or was granted must
|
||||
# stay as it is, in template1 and in a database cloned from it.
|
||||
apiVersion: chainsaw.kyverno.io/v1alpha1
|
||||
kind: Test
|
||||
metadata:
|
||||
name: postgres-3-system-databases
|
||||
spec:
|
||||
catch:
|
||||
- events: {}
|
||||
- describe:
|
||||
apiVersion: helm.toolkit.fluxcd.io/v2
|
||||
kind: HelmRelease
|
||||
name: postgres-sysdb
|
||||
- podLogs:
|
||||
selector: job-name=postgres-sysdb-init-job
|
||||
tail: 200
|
||||
steps:
|
||||
- name: create-postgres
|
||||
try:
|
||||
- apply:
|
||||
file: postgres-sysdb.yaml
|
||||
# 11m: above the 600s install timeout cozystack-api gives this release;
|
||||
# see "Sizing an HR-Ready budget" in docs/agents/e2e-testing.md.
|
||||
- assert:
|
||||
timeout: 11m
|
||||
resource:
|
||||
apiVersion: helm.toolkit.fluxcd.io/v2
|
||||
kind: HelmRelease
|
||||
metadata:
|
||||
name: postgres-sysdb
|
||||
status:
|
||||
(conditions[?type == 'Ready']):
|
||||
- status: "True"
|
||||
- assert:
|
||||
timeout: 2m
|
||||
resource:
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: postgres-sysdb-init-job
|
||||
status:
|
||||
(conditions[?type == 'Complete']):
|
||||
- status: "True"
|
||||
|
||||
- name: rebuild-taken-over-system-databases
|
||||
try:
|
||||
- script:
|
||||
timeout: 3m
|
||||
content: |
|
||||
set -eu
|
||||
pod=$(kubectl -n "$NAMESPACE" get pod \
|
||||
-l cnpg.io/cluster=postgres-sysdb,cnpg.io/instanceRole=primary -o name | head -n1)
|
||||
[ -n "$pod" ] || { echo "no primary pod for postgres-sysdb" >&2; exit 1; }
|
||||
sql() { kubectl -n "$NAMESPACE" exec -i "$pod" -c postgres -- psql -v ON_ERROR_STOP=1 -U postgres -d "$1"; }
|
||||
sql postgres <<'SQL'
|
||||
CREATE ROLE postgres_admin NOLOGIN;
|
||||
COMMENT ON ROLE postgres_admin IS 'role managed by helm';
|
||||
GRANT "cozystack:managed" TO postgres_admin WITH INHERIT FALSE, SET FALSE;
|
||||
COMMENT ON DATABASE postgres IS 'database managed by helm';
|
||||
ALTER DATABASE postgres OWNER TO postgres_admin;
|
||||
CREATE ROLE template1_admin NOLOGIN;
|
||||
COMMENT ON ROLE template1_admin IS 'role managed by helm';
|
||||
CREATE ROLE template1_readonly NOLOGIN;
|
||||
COMMENT ON DATABASE template1 IS 'database managed by helm';
|
||||
ALTER DATABASE template1 OWNER TO template1_admin;
|
||||
SQL
|
||||
sql template1 <<'SQL'
|
||||
ALTER SCHEMA public OWNER TO template1_admin;
|
||||
CREATE TABLE public.kept (id int);
|
||||
ALTER TABLE public.kept OWNER TO template1_admin;
|
||||
GRANT SELECT ON public.kept TO template1_readonly;
|
||||
SQL
|
||||
sql postgres <<'SQL'
|
||||
CREATE DATABASE sysdb_clone TEMPLATE template1;
|
||||
SQL
|
||||
# The next run must be a new Job: remove the completed one so the
|
||||
# assert below cannot match it.
|
||||
kubectl -n "$NAMESPACE" delete job postgres-sysdb-init-job --wait=true
|
||||
# Declaring a user is enough for an upgrade, and runs the init-job.
|
||||
kubectl -n "$NAMESPACE" patch postgres.apps.cozystack.io sysdb --type merge \
|
||||
-p '{"spec":{"users":{"sysdbuser":{},"sysdbprobe":{}}}}'
|
||||
check:
|
||||
($error == null): true
|
||||
- assert:
|
||||
timeout: 11m
|
||||
resource:
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: postgres-sysdb-init-job
|
||||
status:
|
||||
(conditions[?type == 'Complete']):
|
||||
- status: "True"
|
||||
|
||||
- name: verify-release
|
||||
try:
|
||||
- script:
|
||||
timeout: 2m
|
||||
content: |
|
||||
set -eu
|
||||
pod=$(kubectl -n "$NAMESPACE" get pod \
|
||||
-l cnpg.io/cluster=postgres-sysdb,cnpg.io/instanceRole=primary -o name | head -n1)
|
||||
q() { kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- psql -v ON_ERROR_STOP=1 -U postgres -tA -d "$1" -c "$2"; }
|
||||
fail=0
|
||||
expect() {
|
||||
got=$(q "$1" "$3")
|
||||
if [ "$got" != "$4" ]; then
|
||||
echo "FAIL: $2: got '$got', want '$4'" >&2
|
||||
fail=1
|
||||
fi
|
||||
}
|
||||
comment="SELECT coalesce(shobj_description(oid, 'pg_database'), '<none>') FROM pg_database WHERE datname = "
|
||||
owner="SELECT pg_get_userbyid(datdba) FROM pg_database WHERE datname = "
|
||||
expect postgres "postgres comment cleared" "$comment'postgres'" '<none>'
|
||||
expect postgres "postgres back to the superuser" "$owner'postgres'" postgres
|
||||
expect postgres "marked postgres_admin dropped" "SELECT count(*) FROM pg_roles WHERE rolname = 'postgres_admin'" 0
|
||||
expect postgres "template1 comment cleared" "$comment'template1'" '<none>'
|
||||
expect postgres "unmarked template1_admin still exists" "SELECT count(*) FROM pg_roles WHERE rolname = 'template1_admin'" 1
|
||||
expect postgres "template1 still owned by the unmarked role" "$owner'template1'" template1_admin
|
||||
for db in template1 sysdb_clone; do
|
||||
expect "$db" "$db public still owned by the unmarked role" \
|
||||
"SELECT pg_get_userbyid(nspowner) FROM pg_namespace WHERE nspname = 'public'" template1_admin
|
||||
expect "$db" "$db kept table still owned by the unmarked role" \
|
||||
"SELECT tableowner FROM pg_tables WHERE schemaname = 'public' AND tablename = 'kept'" template1_admin
|
||||
expect "$db" "$db grant to the unmarked readonly role kept" \
|
||||
"SELECT has_table_privilege('template1_readonly', 'public.kept', 'SELECT')" t
|
||||
done
|
||||
exit "$fail"
|
||||
check:
|
||||
($error == null): true
|
||||
# The Postgres CR was applied by chainsaw; deleting it removes the whole
|
||||
# cluster, the databases and roles built above included.
|
||||
@@ -0,0 +1,18 @@
|
||||
apiVersion: apps.cozystack.io/v1alpha1
|
||||
kind: Postgres
|
||||
metadata:
|
||||
name: sysdb
|
||||
spec:
|
||||
external: false
|
||||
size: 1Gi
|
||||
replicas: 1
|
||||
storageClass: ""
|
||||
quorum:
|
||||
minSyncReplicas: 0
|
||||
maxSyncReplicas: 0
|
||||
users:
|
||||
sysdbuser: {}
|
||||
databases:
|
||||
appdb: {}
|
||||
resources: {}
|
||||
resourcesPreset: "nano"
|
||||
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env bats
|
||||
# Behavioural tests for the monitoring-agents pre-delete hook:
|
||||
#
|
||||
# packages/system/monitoring-agents/templates/vm-cleanup-hook.yaml
|
||||
#
|
||||
# The script is extracted from the rendered chart and RUN against a fake
|
||||
# kubectl that keeps the VictoriaMetrics objects in a state file, with fake
|
||||
# `date` and `sleep` so the 60s grace period passes in an instant. The
|
||||
# helm-unittest suite in packages/system/monitoring-agents/tests/
|
||||
# uninstall_test.yaml matches the script text instead, and stayed green when the
|
||||
# ownership condition was removed, when the finalizer patch was made a no-op and
|
||||
# when the polling condition was inverted. Each of those turns this file red.
|
||||
#
|
||||
# What is pinned here:
|
||||
# * only objects whose Helm annotations name this release, by name and
|
||||
# namespace both, are deleted or patched: an object of another release, of
|
||||
# a same-named release in another namespace, or one Helm does not own, is
|
||||
# left alone;
|
||||
# * with the operator gone, the hook waits before touching finalizers, then
|
||||
# clears them, and nothing of this release is left behind;
|
||||
# * with the operator alive, it finalizes the objects itself and the hook
|
||||
# never patches a finalizer;
|
||||
# * a kind whose CRD is gone, or a release with nothing left, exits 0, since a
|
||||
# failing pre-delete hook would itself block the uninstall.
|
||||
#
|
||||
# Run from the repo root with make bats-unit-tests. Direct status checks
|
||||
# retain compatibility with cozytest, which has no Bats run/setup helpers.
|
||||
# Inline cleanup preserves Bats' TAP handler on failed assertions.
|
||||
|
||||
load test_helper
|
||||
|
||||
MA_CHART=packages/system/monitoring-agents
|
||||
MA_RELEASE=monitoring-agents
|
||||
MA_NAMESPACE=cozy-monitoring
|
||||
|
||||
# render_hook <job-name> <out>
|
||||
# Extract the named Job's shell script from the rendered chart into <out>. The
|
||||
# non-empty check must be an early `return 1`: hack/cozytest.sh rewrites every
|
||||
# line matching ^}$ into `return 0` plus `}`, helpers included, so a check left
|
||||
# in last-command position has its status discarded.
|
||||
render_hook() {
|
||||
helm template "$MA_RELEASE" "$MA_CHART" --namespace "$MA_NAMESPACE" \
|
||||
| yq eval "select(.kind == \"Job\" and .metadata.name == \"$1\") | .spec.template.spec.containers[0].command[2]" - > "$2"
|
||||
[ -s "$2" ] || return 1
|
||||
}
|
||||
|
||||
# write_fakes <dir>
|
||||
# Emit fake `kubectl`, `date` and `sleep` into <dir>.
|
||||
#
|
||||
# kubectl reads and writes $STATE, one object per line as
|
||||
# kind|release-name|release-namespace|namespace|name, where the two release
|
||||
# fields are the Helm annotations (empty when Helm does not own the object).
|
||||
# `get` prints this kind's objects in the hook's jsonpath format, or fails for a
|
||||
# kind listed in $MISSING_KINDS as kubectl does when the CRD is gone. `delete`
|
||||
# removes the object only when $OPERATOR_LIVE is 1, standing for an operator
|
||||
# that finalizes it; otherwise the object stays, Terminating. `patch` removes it
|
||||
# only when the payload actually clears the finalizers. Every call goes to $KLOG.
|
||||
#
|
||||
# date advances 1s per call from $CLOCK, so the 60s wait ends after sixty
|
||||
# of polls, and records each time it returns in $KLOG; sleep records itself,
|
||||
# and with $SLEEP_ADVANCES=1 also moves $CLOCK by its argument. The log thus
|
||||
# shows how much fake time passed before each patch.
|
||||
# No line below is a bare column-0 `}`, so cozytest.sh's parser leaves it alone.
|
||||
write_fakes() {
|
||||
cat > "$1/kubectl" <<'KEOF'
|
||||
#!/bin/sh
|
||||
echo "kubectl $*" >> "$KLOG"
|
||||
drop() {
|
||||
awk -F'|' -v k="$1" -v ns="$2" -v n="$3" '!($1 == k && $4 == ns && $5 == n)' "$STATE" > "$STATE.new"
|
||||
mv "$STATE.new" "$STATE"; }
|
||||
case "$1" in
|
||||
get)
|
||||
kind=${2%%.*}
|
||||
case " ${MISSING_KINDS:-} " in
|
||||
*" $kind "*)
|
||||
echo "error: the server doesn't have a resource type \"$kind\"" >&2
|
||||
exit 1 ;;
|
||||
esac
|
||||
awk -F'|' -v k="$kind" '$1 == k { print $2 "|" $3 "|" $4 "|" $5 }' "$STATE"
|
||||
exit 0 ;;
|
||||
-n)
|
||||
ns=$2 verb=$3 kind=${4%%.*} name=$5
|
||||
case "$verb" in
|
||||
delete)
|
||||
[ "${OPERATOR_LIVE:-0}" = 1 ] && drop "$kind" "$ns" "$name"
|
||||
echo "$kind \"$name\" deleted"
|
||||
exit 0 ;;
|
||||
patch)
|
||||
case "$*" in
|
||||
*'"finalizers":null'*) drop "$kind" "$ns" "$name" ;;
|
||||
esac
|
||||
echo "$kind \"$name\" patched"
|
||||
exit 0 ;;
|
||||
esac ;;
|
||||
esac
|
||||
echo "fake kubectl: unexpected call: $*" >&2
|
||||
exit 64
|
||||
KEOF
|
||||
cat > "$1/date" <<'KEOF'
|
||||
#!/bin/sh
|
||||
c=$(cat "$CLOCK" 2>/dev/null || echo 0)
|
||||
echo $((c + 1)) > "$CLOCK"
|
||||
echo "date $((1000000 + c))" >> "$KLOG"
|
||||
echo $((1000000 + c))
|
||||
KEOF
|
||||
cat > "$1/sleep" <<'KEOF'
|
||||
#!/bin/sh
|
||||
echo "sleep $*" >> "$KLOG"
|
||||
if [ "${SLEEP_ADVANCES:-0}" = 1 ]; then
|
||||
c=$(cat "$CLOCK" 2>/dev/null || echo 0)
|
||||
echo $((c + $1)) > "$CLOCK"
|
||||
fi
|
||||
KEOF
|
||||
chmod +x "$1/kubectl" "$1/date" "$1/sleep"
|
||||
}
|
||||
|
||||
# write_state <file>
|
||||
# Three objects of this release in two namespaces; a VMRule of another release;
|
||||
# a VMRule whose release name matches but whose release namespace does not, so
|
||||
# only the pair of annotations tells it apart; and a VMServiceScrape that
|
||||
# carries no Helm annotations.
|
||||
write_state() {
|
||||
cat > "$1" <<EOF
|
||||
vmagents|$MA_RELEASE|$MA_NAMESPACE|$MA_NAMESPACE|vmagent
|
||||
vmrules|$MA_RELEASE|$MA_NAMESPACE|$MA_NAMESPACE|alerts-node
|
||||
vmservicescrapes|$MA_RELEASE|$MA_NAMESPACE|cozy-victoria-metrics-operator|operator
|
||||
vmrules|other|$MA_NAMESPACE|$MA_NAMESPACE|foreign-rule
|
||||
vmrules|$MA_RELEASE|other-namespace|$MA_NAMESPACE|foreign-ns-rule
|
||||
vmservicescrapes|||$MA_NAMESPACE|unmanaged-scrape
|
||||
EOF
|
||||
}
|
||||
|
||||
# run_hook <dir>
|
||||
# Run the rendered hook with the fakes first on PATH; its status lands in $rc.
|
||||
run_hook() {
|
||||
export KLOG="$1/calls" STATE="$1/state" CLOCK="$1/clock"
|
||||
: > "$KLOG"
|
||||
rc=0
|
||||
PATH="$1:$PATH" sh "$1/hook.sh" > "$1/out" 2> "$1/err" || rc=$?
|
||||
}
|
||||
|
||||
@test "a render that produces no script fails instead of passing as a no-op" {
|
||||
# Guards the guard: every test below runs whatever render_hook produced, so an
|
||||
# empty render would satisfy the exit-0 assertions without executing a line of
|
||||
# the hook.
|
||||
tmp=$(mktemp -d)
|
||||
if render_hook no-such-job "$tmp/hook.sh"; then
|
||||
echo "FAIL: render_hook reported success for a Job name the chart never emits"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "vm cleanup hook clears the finalizers of this release's objects only, after the grace period" {
|
||||
tmp=$(mktemp -d)
|
||||
write_fakes "$tmp"
|
||||
write_state "$tmp/state"
|
||||
render_hook vm-objects-cleanup "$tmp/hook.sh"
|
||||
export OPERATOR_LIVE=0 MISSING_KINDS=""
|
||||
run_hook "$tmp"
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "FAIL: hook exited $rc"
|
||||
cat "$tmp/out" "$tmp/err"
|
||||
false
|
||||
fi
|
||||
for obj in "vmagents.operator.victoriametrics.com vmagent" \
|
||||
"vmrules.operator.victoriametrics.com alerts-node" \
|
||||
"vmservicescrapes.operator.victoriametrics.com operator"; do
|
||||
if ! grep -q -- " delete $obj --wait=false" "$tmp/calls"; then
|
||||
echo "FAIL: $obj was not deleted"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
done
|
||||
# The objects of this release must be gone, which the fake only does for a
|
||||
# patch that really clears the finalizers.
|
||||
if grep -q "^[a-z]*|$MA_RELEASE|$MA_NAMESPACE|" "$tmp/state"; then
|
||||
echo "FAIL: objects of this release are still there, Terminating"
|
||||
cat "$tmp/state" "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
# Another release's object, one of a same-named release in another
|
||||
# namespace, and an object Helm does not own are never touched.
|
||||
if grep -E -q -- ' (delete|patch) [a-z.]+ (foreign-rule|foreign-ns-rule|unmanaged-scrape)( |$)' "$tmp/calls"; then
|
||||
echo "FAIL: the hook touched an object this release does not own"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
if [ "$(grep -c '|' "$tmp/state")" -ne 3 ]; then
|
||||
echo "FAIL: the three objects this release does not own should remain"
|
||||
cat "$tmp/state"
|
||||
false
|
||||
fi
|
||||
# The operator gets its chance first: the hook polls and sleeps before the
|
||||
# first patch, and does not stop waiting before the 60s are up.
|
||||
first_patch=$(grep -n ' patch ' "$tmp/calls" | head -1 | cut -d: -f1)
|
||||
if [ -z "$first_patch" ]; then
|
||||
echo "FAIL: no finalizer was cleared"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
# The first date call sets the deadline; the last one before the first patch
|
||||
# is the time the hook gave up waiting.
|
||||
start=$(grep '^date ' "$tmp/calls" | head -1 | cut -d' ' -f2)
|
||||
waited_until=$(head -n "$first_patch" "$tmp/calls" | grep '^date ' | tail -1 | cut -d' ' -f2)
|
||||
if [ -z "$start" ] || [ $((waited_until - start)) -lt 60 ]; then
|
||||
echo "FAIL: finalizers cleared after $((waited_until - start))s; the 60s grace period was cut short"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "vm cleanup hook clears the finalizers before its Job's deadline" {
|
||||
# The grace-period test above keeps sleep free so a shortened wait shows; here
|
||||
# sleep costs its argument, so a poll interval long enough to overshoot the
|
||||
# Job's activeDeadlineSeconds fails instead of passing.
|
||||
tmp=$(mktemp -d)
|
||||
write_fakes "$tmp"
|
||||
write_state "$tmp/state"
|
||||
render_hook vm-objects-cleanup "$tmp/hook.sh"
|
||||
job_deadline=$(helm template "$MA_RELEASE" "$MA_CHART" --namespace "$MA_NAMESPACE" \
|
||||
| yq eval 'select(.kind == "Job" and .metadata.name == "vm-objects-cleanup") | .spec.activeDeadlineSeconds' -)
|
||||
export OPERATOR_LIVE=0 MISSING_KINDS="" SLEEP_ADVANCES=1
|
||||
run_hook "$tmp"
|
||||
unset SLEEP_ADVANCES
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "FAIL: hook exited $rc"
|
||||
cat "$tmp/out" "$tmp/err"
|
||||
false
|
||||
fi
|
||||
first_patch=$(grep -n ' patch ' "$tmp/calls" | head -1 | cut -d: -f1)
|
||||
start=$(grep '^date ' "$tmp/calls" | head -1 | cut -d' ' -f2)
|
||||
waited_until=$(head -n "${first_patch:-0}" "$tmp/calls" | grep '^date ' | tail -1 | cut -d' ' -f2)
|
||||
if [ -z "$first_patch" ] || [ -z "$job_deadline" ] || [ $((waited_until - start)) -ge "$job_deadline" ]; then
|
||||
echo "FAIL: first finalizer patch at $((waited_until - start))s, Job deadline ${job_deadline}s"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "vm cleanup hook leaves the finalizers to a live operator" {
|
||||
tmp=$(mktemp -d)
|
||||
write_fakes "$tmp"
|
||||
write_state "$tmp/state"
|
||||
render_hook vm-objects-cleanup "$tmp/hook.sh"
|
||||
export OPERATOR_LIVE=1 MISSING_KINDS=""
|
||||
run_hook "$tmp"
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "FAIL: hook exited $rc"
|
||||
cat "$tmp/out" "$tmp/err"
|
||||
false
|
||||
fi
|
||||
if ! grep -q ' delete vmagents.operator.victoriametrics.com vmagent ' "$tmp/calls"; then
|
||||
echo "FAIL: the VMAgent was not deleted"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
if grep -q ' patch ' "$tmp/calls"; then
|
||||
echo "FAIL: the hook cleared finalizers the live operator was handling"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "vm cleanup hook exits 0 and cleans the other kinds when a CRD is gone" {
|
||||
tmp=$(mktemp -d)
|
||||
write_fakes "$tmp"
|
||||
write_state "$tmp/state"
|
||||
render_hook vm-objects-cleanup "$tmp/hook.sh"
|
||||
export OPERATOR_LIVE=0 MISSING_KINDS="vmrules vmpodscrapes vmnodescrapes"
|
||||
run_hook "$tmp"
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "FAIL: hook exited $rc with a CRD gone, which would block the uninstall"
|
||||
cat "$tmp/out" "$tmp/err"
|
||||
false
|
||||
fi
|
||||
if grep -q "^vmagents|$MA_RELEASE|" "$tmp/state"; then
|
||||
echo "FAIL: the VMAgent was left Terminating because another kind's CRD was gone"
|
||||
cat "$tmp/state" "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "vm cleanup hook exits 0 without deleting anything when the release owns nothing" {
|
||||
tmp=$(mktemp -d)
|
||||
write_fakes "$tmp"
|
||||
printf 'vmrules|other|%s|%s|foreign-rule\nvmrules|%s|other-namespace|%s|foreign-ns-rule\n' \
|
||||
"$MA_NAMESPACE" "$MA_NAMESPACE" "$MA_RELEASE" "$MA_NAMESPACE" > "$tmp/state"
|
||||
render_hook vm-objects-cleanup "$tmp/hook.sh"
|
||||
export OPERATOR_LIVE=0 MISSING_KINDS=""
|
||||
run_hook "$tmp"
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "FAIL: hook exited $rc with nothing to clean"
|
||||
cat "$tmp/out" "$tmp/err"
|
||||
false
|
||||
fi
|
||||
if grep -E -q ' (delete|patch) ' "$tmp/calls"; then
|
||||
echo "FAIL: the hook deleted or patched with nothing of this release left"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bats
|
||||
|
||||
load test_helper
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)"
|
||||
|
||||
prepare_seed_capture() {
|
||||
strict_setup
|
||||
seed_tmp=$(mktemp -d)
|
||||
seed_old_path=$PATH
|
||||
mkdir -p "$seed_tmp/bin"
|
||||
export SEED_CAPTURE="$seed_tmp/seed"
|
||||
export PATH="$seed_tmp/bin:$PATH"
|
||||
cat > "$seed_tmp/bin/curl" <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
set -eu
|
||||
printf '%s\n' "$@" > "$SEED_CAPTURE.args"
|
||||
cat > "$SEED_CAPTURE.body"
|
||||
if ! grep --fixed-strings --line-regexp --quiet 'Content-Type: application/json' "$SEED_CAPTURE.args"; then
|
||||
echo 'seed request is missing its JSON content type' >&2
|
||||
exit 22
|
||||
fi
|
||||
EOF
|
||||
chmod +x "$seed_tmp/bin/curl"
|
||||
}
|
||||
|
||||
assert_seed_request() {
|
||||
local account=$1
|
||||
prepare_seed_capture
|
||||
# shellcheck source=e2e-chainsaw/observability-proxy/lib.sh
|
||||
. "$REPO_ROOT/hack/e2e-chainsaw/observability-proxy/lib.sh"
|
||||
if [ "$account" = 0 ]; then
|
||||
ingest tenant-test-logsa e2e-marker-a
|
||||
else
|
||||
ingest tenant-test-logsa e2e-marker-a "$account"
|
||||
fi
|
||||
grep --fixed-strings --line-regexp --quiet "AccountID: $account" "$SEED_CAPTURE.args"
|
||||
grep --fixed-strings --line-regexp --quiet 'ProjectID: 0' "$SEED_CAPTURE.args"
|
||||
grep --fixed-strings --line-regexp --quiet 'http://localhost:19471/insert/jsonline?_stream_fields=kubernetes_namespace_name&_msg_field=log' "$SEED_CAPTURE.args"
|
||||
grep --fixed-strings --line-regexp --quiet -- '--data-binary' "$SEED_CAPTURE.args"
|
||||
grep --fixed-strings --line-regexp --quiet '@-' "$SEED_CAPTURE.args"
|
||||
printf '%s\n' '{"kubernetes_namespace_name":"tenant-test-logsa","log":"e2e-marker-a"}' > "$SEED_CAPTURE.expected"
|
||||
cmp "$SEED_CAPTURE.expected" "$SEED_CAPTURE.body"
|
||||
rm "$body" "$SEED_CAPTURE.args" "$SEED_CAPTURE.body" "$SEED_CAPTURE.expected" "$seed_tmp/bin/curl"
|
||||
rmdir "$seed_tmp/bin" "$seed_tmp"
|
||||
export PATH="$seed_old_path"
|
||||
}
|
||||
|
||||
@test "observability seeds send JSON without consuming the body as form data" {
|
||||
assert_seed_request 0
|
||||
}
|
||||
|
||||
@test "observability seeds preserve an explicit VictoriaLogs account" {
|
||||
assert_seed_request 7
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
#!/usr/bin/env bats
|
||||
# Behavioural tests for the "release system databases" pass of the Postgres
|
||||
# init script:
|
||||
#
|
||||
# packages/apps/postgres/templates/init-script.yaml
|
||||
#
|
||||
# The pass is cut out of the rendered script and RUN against a fake psql that
|
||||
# records which database each session connects to. The helm-unittest suite in
|
||||
# packages/apps/postgres/tests/system_databases_test.yaml matches the SQL text,
|
||||
# and stayed green when the template0 guard was inverted: the rendered pass then
|
||||
# connected to template0, which accepts no connection, and skipped postgres and
|
||||
# template1, which are the two it exists to hand back.
|
||||
#
|
||||
# What is pinned here:
|
||||
# * no session ever connects to template0;
|
||||
# * postgres and template1 are each connected to and released;
|
||||
# * every taken-over system database, template0 included, has its comment
|
||||
# cleared;
|
||||
# * releasing template1 visits every other connectable database, for the
|
||||
# trigger it passed on to them, and a failed lookup of those databases
|
||||
# stops the pass before the comment that selects template1 is cleared;
|
||||
# * the session that releases a system database hands its public schema
|
||||
# and the database itself back only from a marked <db>_admin or
|
||||
# <db>_readonly owner (or cozystack:orphaned), before the reassignment,
|
||||
# an inherited public only from a marked template1_admin, and touches
|
||||
# only the roles that carry the
|
||||
# "cozystack:managed" mark, not a role that merely has one of the names.
|
||||
#
|
||||
# Run from the repo root with make bats-unit-tests. Direct status checks
|
||||
# retain compatibility with cozytest, which has no Bats run/setup helpers.
|
||||
# Inline cleanup preserves Bats' TAP handler on failed assertions.
|
||||
|
||||
load test_helper
|
||||
|
||||
PG_CHART=packages/apps/postgres
|
||||
|
||||
# render_pass <out>
|
||||
# Extract the release pass, from its banner to the next one, out of the rendered
|
||||
# init script. The non-empty check must be an early `return 1`: hack/cozytest.sh
|
||||
# rewrites every line matching ^}$ into `return 0` plus `}`, helpers included,
|
||||
# so a check left in last-command position has its status discarded.
|
||||
render_pass() {
|
||||
helm template pg-test "$PG_CHART" --namespace tenant-test --set-json '_cluster={"scheduling":{}}' 2>/dev/null \
|
||||
| yq eval 'select(.metadata.name == "pg-test-init-script") | .stringData["init.sh"]' - \
|
||||
| awk '/^echo "== release system databases"/ { f = 1 } /^echo "== delete databases"/ { f = 0 } f' > "$1"
|
||||
grep -q 'SYSTEM_DBS=' "$1" || return 1
|
||||
}
|
||||
|
||||
# write_fake_psql <dir>
|
||||
# Emit a fake psql. A `-c` query answers from $SYSTEM_DBS for the system
|
||||
# database lookup and from $OTHER_DBS for the connectable-database lookup,
|
||||
# which exits with $CLONE_LOOKUP_FAILS instead when that is set. A
|
||||
# session fed on stdin logs "connect <dbname>" ("connect -" without --dbname)
|
||||
# followed by its first line and every -v db= value, to $PLOG, and its whole
|
||||
# input under a "-- session <dbname> db=<value>" header to $PLOG.sql.
|
||||
# No line below is a bare column-0 `}`, so cozytest.sh's parser leaves it alone.
|
||||
write_fake_psql() {
|
||||
cat > "$1/psql" <<'PEOF'
|
||||
#!/bin/sh
|
||||
dbname=- query= vdb=
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--dbname) dbname=$2; shift ;;
|
||||
-c) query=$2; shift ;;
|
||||
-v) case "$2" in db=*) vdb=${2#db=} ;; esac; shift ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
if [ -n "$query" ]; then
|
||||
case "$query" in
|
||||
*"d.datname IN ('postgres', 'template0', 'template1')"*) printf '%s\n' $SYSTEM_DBS ;;
|
||||
*datallowconn*)
|
||||
if [ -n "${CLONE_LOOKUP_FAILS:-}" ]; then
|
||||
echo "fake psql: connectable-database lookup failed" >&2
|
||||
exit "$CLONE_LOOKUP_FAILS"
|
||||
fi
|
||||
printf '%s\n' $OTHER_DBS ;;
|
||||
*) echo "fake psql: unexpected query: $query" >&2; exit 64 ;;
|
||||
esac
|
||||
exit 0
|
||||
fi
|
||||
sql=$(cat)
|
||||
echo "connect $dbname db=$vdb $(printf '%s\n' "$sql" | head -n 1)" >> "$PLOG"
|
||||
printf -- '-- session %s db=%s\n%s\n' "$dbname" "$vdb" "$sql" >> "$PLOG.sql"
|
||||
PEOF
|
||||
chmod +x "$1/psql"
|
||||
}
|
||||
|
||||
# run_pass <dir>
|
||||
# Run the extracted pass with the fake psql first on PATH; status in $rc.
|
||||
run_pass() {
|
||||
export PLOG="$1/calls"
|
||||
: > "$PLOG"
|
||||
rc=0
|
||||
PATH="$1:$PATH" sh -e "$1/pass.sh" > "$1/out" 2> "$1/err" || rc=$?
|
||||
}
|
||||
|
||||
@test "a render that produces no release pass fails instead of passing as a no-op" {
|
||||
tmp=$(mktemp -d)
|
||||
if PG_CHART=packages/apps/no-such-chart render_pass "$tmp/pass.sh"; then
|
||||
echo "FAIL: render_pass reported success for a chart that does not exist"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "release pass connects to postgres and template1, never to template0" {
|
||||
tmp=$(mktemp -d)
|
||||
write_fake_psql "$tmp"
|
||||
render_pass "$tmp/pass.sh"
|
||||
export SYSTEM_DBS="postgres template0 template1" OTHER_DBS="postgres app"
|
||||
run_pass "$tmp"
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "FAIL: the pass exited $rc"
|
||||
cat "$tmp/out" "$tmp/err"
|
||||
false
|
||||
fi
|
||||
if grep -q '^connect template0 ' "$tmp/calls"; then
|
||||
echo "FAIL: the pass connected to template0, which accepts no connection"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
for db in postgres template1; do
|
||||
if ! grep -q "^connect $db db=$db DROP EVENT TRIGGER IF EXISTS trigger_auto_grant;" "$tmp/calls"; then
|
||||
echo "FAIL: $db was not connected to and released"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
done
|
||||
for db in postgres template0 template1; do
|
||||
if ! grep -q "^connect - db=$db COMMENT ON DATABASE :\"db\" IS NULL;" "$tmp/calls"; then
|
||||
echo "FAIL: the comment on $db was not cleared"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
done
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "release session hands public back and touches only marked roles" {
|
||||
tmp=$(mktemp -d)
|
||||
write_fake_psql "$tmp"
|
||||
render_pass "$tmp/pass.sh"
|
||||
export SYSTEM_DBS="postgres" OTHER_DBS="postgres"
|
||||
run_pass "$tmp"
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "FAIL: the pass exited $rc"
|
||||
cat "$tmp/out" "$tmp/err"
|
||||
false
|
||||
fi
|
||||
awk '/^-- session / { f = ($0 == "-- session postgres db=postgres") } f' "$tmp/calls.sql" > "$tmp/release.sql"
|
||||
# Each statement must end on its whole predicate: a clause appended after the
|
||||
# mark (an OR, say) would select an unmarked role again.
|
||||
reassign_where="WHERE EXISTS (SELECT FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid JOIN pg_roles u ON u.oid = m.member WHERE g.rolname = 'cozystack:managed' AND u.rolname = r)\\gexec"
|
||||
owner_marked="(o.rolname = 'cozystack:orphaned' OR o.rolname IN (:'db' || '_admin', :'db' || '_readonly') AND EXISTS (SELECT FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = o.oid))\\gexec"
|
||||
public_where="WHERE n.nspname = 'public' AND $owner_marked"
|
||||
database_where="WHERE d.datname = :'db' AND $owner_marked"
|
||||
public_line=$(grep -n 'ALTER SCHEMA public OWNER TO' "$tmp/release.sql" | head -1)
|
||||
database_line=$(grep -n 'ALTER DATABASE' "$tmp/release.sql" | head -1)
|
||||
reassign_line=$(grep -n 'REASSIGN OWNED BY' "$tmp/release.sql" | head -1)
|
||||
if [ "${public_line##*"$public_where"}" != "" ] || [ -z "$public_line" ]; then
|
||||
echo "FAIL: the release session does not hand public back only from a marked <db>_admin or <db>_readonly owner"
|
||||
cat "$tmp/release.sql"
|
||||
false
|
||||
fi
|
||||
if [ "${database_line##*"$database_where"}" != "" ] || [ -z "$database_line" ]; then
|
||||
echo "FAIL: the release session does not take the database back only from a marked owner"
|
||||
cat "$tmp/release.sql"
|
||||
false
|
||||
fi
|
||||
if [ "${reassign_line##*"$reassign_where"}" != "" ] || [ -z "$reassign_line" ]; then
|
||||
echo "FAIL: the release session does not reassign only roles carrying the cozystack:managed mark"
|
||||
cat "$tmp/release.sql"
|
||||
false
|
||||
fi
|
||||
# public and the database must be handed back before REASSIGN OWNED would
|
||||
# move them to cozystack:orphaned.
|
||||
if [ "${public_line%%:*}" -ge "${reassign_line%%:*}" ] || [ "${database_line%%:*}" -ge "${reassign_line%%:*}" ]; then
|
||||
echo "FAIL: public or the database is handed back after the reassignment has already moved it"
|
||||
cat "$tmp/release.sql"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "release pass of template1 visits every other connectable database" {
|
||||
tmp=$(mktemp -d)
|
||||
write_fake_psql "$tmp"
|
||||
render_pass "$tmp/pass.sh"
|
||||
export SYSTEM_DBS="template1" OTHER_DBS="postgres app"
|
||||
run_pass "$tmp"
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "FAIL: the pass exited $rc"
|
||||
cat "$tmp/out" "$tmp/err"
|
||||
false
|
||||
fi
|
||||
for db in postgres app; do
|
||||
if ! grep -q "^connect $db db= SELECT 'DROP EVENT TRIGGER IF EXISTS trigger_auto_grant'" "$tmp/calls"; then
|
||||
echo "FAIL: $db was not checked for the trigger inherited from template1"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
done
|
||||
# An inherited public changes hands only from a template1_admin the chart
|
||||
# marked; an owner that merely has the name keeps it.
|
||||
inherited_where="WHERE n.nspname = 'public' AND o.rolname = 'template1_admin' AND EXISTS (SELECT FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = o.oid)\\gexec"
|
||||
inherited_line=$(awk '/^-- session / { f = ($0 == "-- session app db=") } f' "$tmp/calls.sql" | grep 'ALTER SCHEMA public OWNER TO' | head -1)
|
||||
if [ -z "$inherited_line" ] || [ "${inherited_line##*"$inherited_where"}" != "" ]; then
|
||||
echo "FAIL: an inherited public is handed back without checking that a marked template1_admin owns it"
|
||||
cat "$tmp/calls.sql"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "release pass of template1 stops before clearing its comment when the clone lookup fails" {
|
||||
# Clearing the comment is what stops later runs from selecting template1, so
|
||||
# a lookup failure that let the pass go on would skip the clone repair for
|
||||
# good.
|
||||
tmp=$(mktemp -d)
|
||||
write_fake_psql "$tmp"
|
||||
render_pass "$tmp/pass.sh"
|
||||
export SYSTEM_DBS="template1" OTHER_DBS="postgres app" CLONE_LOOKUP_FAILS=73
|
||||
run_pass "$tmp"
|
||||
unset CLONE_LOOKUP_FAILS
|
||||
|
||||
if [ "$rc" -ne 73 ]; then
|
||||
echo "FAIL: the pass exited $rc instead of stopping on the failed lookup (73)"
|
||||
cat "$tmp/out" "$tmp/err" "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
if grep -q 'COMMENT ON DATABASE' "$tmp/calls"; then
|
||||
echo "FAIL: the comment on template1 was cleared although its clones were never visited"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
|
||||
@test "release pass of postgres alone leaves the other databases alone" {
|
||||
tmp=$(mktemp -d)
|
||||
write_fake_psql "$tmp"
|
||||
render_pass "$tmp/pass.sh"
|
||||
export SYSTEM_DBS="postgres" OTHER_DBS="postgres app"
|
||||
run_pass "$tmp"
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "FAIL: the pass exited $rc"
|
||||
cat "$tmp/out" "$tmp/err"
|
||||
false
|
||||
fi
|
||||
if grep -q '^connect app ' "$tmp/calls"; then
|
||||
echo "FAIL: the pass visited app although template1 was not taken over"
|
||||
cat "$tmp/calls"
|
||||
false
|
||||
fi
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
package backupcontroller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -57,6 +57,12 @@ const (
|
||||
// archive relies on.
|
||||
altinityArchiveTimeLayout = "20060102T150405Z"
|
||||
|
||||
// altinityArchiveRunTimeLayout and altinityArchiveUIDLength shape the
|
||||
// archive name of a run; see altinityArchiveName for why they are this
|
||||
// short.
|
||||
altinityArchiveRunTimeLayout = "20060102150405"
|
||||
altinityArchiveUIDLength = 12
|
||||
|
||||
// Polling cadence for the Altinity Job lifecycle. Mirrors the CNPG /
|
||||
// Velero strategy cadence so behaviour is uniform across drivers.
|
||||
altinityPollInterval = 5 * time.Second
|
||||
@@ -85,6 +91,76 @@ func validateAltinityApplicationRef(ref corev1.TypedLocalObjectReference) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// altinityCredentialsPropagation bounds how long kubelet takes to rewrite
|
||||
// the mounted cozy-backups-creds in the ClickHouse Pod after it changes:
|
||||
// its sync period (a minute by default) plus the Secret cache. About 75s was
|
||||
// measured; the margin covers the rest.
|
||||
const altinityCredentialsPropagation = 2 * time.Minute
|
||||
|
||||
// credentialsPropagationWait returns how long to hold back creating the
|
||||
// strategy Job named jobName in namespace, so that the clickhouse-backup
|
||||
// sidecar, which reads the projected credentials from a mounted file, sees
|
||||
// their latest content. A Job that already exists, or a namespace without
|
||||
// projected credentials, does not wait.
|
||||
func credentialsPropagationWait(ctx context.Context, c client.Client, secretName, namespace, jobName string) (time.Duration, error) {
|
||||
if secretName == "" {
|
||||
return 0, nil
|
||||
}
|
||||
if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: jobName}, &batchv1.Job{}); err == nil {
|
||||
return 0, nil
|
||||
} else if !apierrors.IsNotFound(err) {
|
||||
return 0, err
|
||||
}
|
||||
secret := &corev1.Secret{}
|
||||
if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: secretName}, secret); err != nil {
|
||||
if apierrors.IsNotFound(err) {
|
||||
return 0, nil
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
raw := secret.Annotations[credentialsUpdatedAtAnnotation]
|
||||
if raw == "" {
|
||||
return 0, nil
|
||||
}
|
||||
// The projector rewrites the stamp only when the content changes, so a
|
||||
// stamp this hold cannot use stays as it is: holding on it would block
|
||||
// every Job in the namespace for good.
|
||||
updatedAt, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
getLogger(ctx).Error(err, "ignoring unreadable credentials stamp", "secret", namespace+"/"+secretName, "annotation", credentialsUpdatedAtAnnotation)
|
||||
return 0, nil
|
||||
}
|
||||
if updatedAt.After(time.Now().Add(altinityCredentialsPropagation)) {
|
||||
getLogger(ctx).Error(nil, "ignoring a credentials stamp further ahead than clock skew explains", "secret", namespace+"/"+secretName, "annotation", credentialsUpdatedAtAnnotation, "value", raw)
|
||||
return 0, nil
|
||||
}
|
||||
return time.Until(updatedAt.Add(altinityCredentialsPropagation)), nil
|
||||
}
|
||||
|
||||
// clearCredentialsWait drops the Ready condition credentialsWaitCondition
|
||||
// left behind, once the job no longer waits. It reports whether it did.
|
||||
func clearCredentialsWait(conditions *[]metav1.Condition) bool {
|
||||
ready := apimeta.FindStatusCondition(*conditions, "Ready")
|
||||
if ready == nil || ready.Reason != credentialsWaitReason {
|
||||
return false
|
||||
}
|
||||
return apimeta.RemoveStatusCondition(conditions, "Ready")
|
||||
}
|
||||
|
||||
const credentialsWaitReason = "WaitingForCredentials"
|
||||
|
||||
// credentialsWaitCondition is the Ready condition of a job held back by
|
||||
// credentialsPropagationWait.
|
||||
func credentialsWaitCondition(secretName string, wait time.Duration) metav1.Condition {
|
||||
return metav1.Condition{
|
||||
Type: "Ready",
|
||||
Status: metav1.ConditionFalse,
|
||||
Reason: credentialsWaitReason,
|
||||
Message: fmt.Sprintf("waiting %s for the updated Secret %s to reach the ClickHouse backup sidecar",
|
||||
wait.Round(time.Second), secretName),
|
||||
}
|
||||
}
|
||||
|
||||
// jobNameForBackupJob returns the deterministic batch/v1.Job name used for
|
||||
// the backup pod that drives a BackupJob. Idempotency relies on this being
|
||||
// pure: a retried reconcile must hit the same Job name.
|
||||
@@ -117,11 +193,30 @@ func backupParameters(b *backupsv1alpha1.Backup) map[string]string {
|
||||
}
|
||||
|
||||
// altinityArchiveName mints the archive name for one BackupJob from its
|
||||
// persisted StartedAt, so every reconcile and every Pod retry of the Job
|
||||
// writes the same archive. It keeps the clickhouse-<release>-<timestamp>
|
||||
// shape, because a Backup that records no archive is restored by the
|
||||
// timestamp in that shape.
|
||||
// persisted StartedAt and its UID, so every reconcile and every Pod retry of
|
||||
// the Job writes the same archive and no other run writes it. StartedAt has
|
||||
// one-second resolution, and two Plans on one schedule start their runs in
|
||||
// the same second; the strategy takes a finished upload of its archive as an
|
||||
// earlier attempt of its own run, so a shared name would let one run report
|
||||
// the other's archive.
|
||||
//
|
||||
// The name is no longer than altinityArchiveNameBeforeUIDs, because it sits in
|
||||
// every object key, a key is capped at 1024 bytes, and the legacy
|
||||
// s3PathOverride prefix has no length limit of its own: the UID takes the room
|
||||
// that dropping "clickhouse-", "T" and "Z" frees. It goes after the timestamp
|
||||
// so names still sort chronologically, and the restore of a Backup that
|
||||
// records no archive, which accepts only clickhouse-<release>-<timestamp>,
|
||||
// never picks one of these.
|
||||
func altinityArchiveName(j *backupsv1alpha1.BackupJob) string {
|
||||
uid := strings.ReplaceAll(string(j.UID), "-", "")
|
||||
uid = uid[:min(len(uid), altinityArchiveUIDLength)]
|
||||
return fmt.Sprintf("%s-%s-%s", j.Spec.ApplicationRef.Name, j.Status.StartedAt.UTC().Format(altinityArchiveRunTimeLayout), uid)
|
||||
}
|
||||
|
||||
// altinityArchiveNameBeforeUIDs is the name a controller that did not append
|
||||
// the UID gave the same BackupJob, which a Job it created before an upgrade
|
||||
// still writes.
|
||||
func altinityArchiveNameBeforeUIDs(j *backupsv1alpha1.BackupJob) string {
|
||||
return fmt.Sprintf("clickhouse-%s-%s", j.Spec.ApplicationRef.Name, j.Status.StartedAt.UTC().Format(altinityArchiveTimeLayout))
|
||||
}
|
||||
|
||||
@@ -129,13 +224,16 @@ func altinityArchiveName(j *backupsv1alpha1.BackupJob) string {
|
||||
// the archive name. A Job created by a controller that predates archive
|
||||
// names, or rendered from a strategy that names its own archives, wrote an
|
||||
// archive under another name, and recording this one would point the Backup
|
||||
// at an archive that does not exist.
|
||||
// at an archive that does not exist. The name has to stand on its own: the
|
||||
// name without the UID starts the name with it, and a strategy may append to
|
||||
// either.
|
||||
func altinityJobCarriesArchive(job *batchv1.Job, archive string) bool {
|
||||
spec, err := json.Marshal(job.Spec.Template.Spec)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return bytes.Contains(spec, []byte(archive))
|
||||
whole := regexp.MustCompile(`(^|[^A-Za-z0-9._-])` + regexp.QuoteMeta(archive) + `($|[^A-Za-z0-9._-])`)
|
||||
return whole.Match(spec)
|
||||
}
|
||||
|
||||
// renderAltinityTemplate runs the strategy's PodTemplateSpec through the
|
||||
@@ -265,6 +363,18 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv
|
||||
return r.markBackupJobFailed(ctx, j, fmt.Sprintf("failed to template Altinity strategy: %v", err))
|
||||
}
|
||||
|
||||
wait, err := credentialsPropagationWait(ctx, r.Client, r.CredentialsConfig.TargetSecretName, j.Namespace, jobNameForBackupJob(j))
|
||||
if err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
if wait > 0 {
|
||||
apimeta.SetStatusCondition(&j.Status.Conditions, credentialsWaitCondition(r.CredentialsConfig.TargetSecretName, wait))
|
||||
if err := r.Status().Update(ctx, j); err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
return ctrl.Result{RequeueAfter: wait}, nil
|
||||
}
|
||||
|
||||
batchJob, err := r.ensureAltinityJob(ctx, j, j.Namespace, jobNameForBackupJob(j),
|
||||
altinityModeBackup,
|
||||
map[string]string{
|
||||
@@ -283,7 +393,10 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv
|
||||
return ctrl.Result{}, nil
|
||||
}
|
||||
if !altinityJobCarriesArchive(batchJob, archive) {
|
||||
archive = ""
|
||||
archive = altinityArchiveNameBeforeUIDs(j)
|
||||
if !altinityJobCarriesArchive(batchJob, archive) {
|
||||
archive = ""
|
||||
}
|
||||
}
|
||||
artifact, err := r.createAltinityBackupArtifact(ctx, j, resolved, archive)
|
||||
if err != nil {
|
||||
@@ -312,6 +425,11 @@ func (r *BackupJobReconciler) reconcileAltinity(ctx context.Context, j *backupsv
|
||||
return r.markBackupJobFailed(ctx, j, message)
|
||||
|
||||
default:
|
||||
if clearCredentialsWait(&j.Status.Conditions) {
|
||||
if err := r.Status().Update(ctx, j); err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
}
|
||||
return ctrl.Result{RequeueAfter: altinityPollInterval}, nil
|
||||
}
|
||||
}
|
||||
@@ -681,6 +799,18 @@ func (r *RestoreJobReconciler) reconcileAltinityRestore(ctx context.Context, res
|
||||
return r.markRestoreJobFailed(ctx, restoreJob, fmt.Sprintf("failed to template Altinity strategy: %v", err))
|
||||
}
|
||||
|
||||
wait, err := credentialsPropagationWait(ctx, r.Client, r.CredentialsConfig.TargetSecretName, targetNamespace, jobNameForRestoreJob(restoreJob))
|
||||
if err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
if wait > 0 {
|
||||
apimeta.SetStatusCondition(&restoreJob.Status.Conditions, credentialsWaitCondition(r.CredentialsConfig.TargetSecretName, wait))
|
||||
if err := r.Status().Update(ctx, restoreJob); err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
return ctrl.Result{RequeueAfter: wait}, nil
|
||||
}
|
||||
|
||||
batchJob, err := r.ensureAltinityRestoreJob(ctx, restoreJob, targetNamespace, jobNameForRestoreJob(restoreJob),
|
||||
altinityModeRestore,
|
||||
map[string]string{
|
||||
@@ -717,6 +847,11 @@ func (r *RestoreJobReconciler) reconcileAltinityRestore(ctx context.Context, res
|
||||
return r.markRestoreJobFailed(ctx, restoreJob, message)
|
||||
|
||||
default:
|
||||
if clearCredentialsWait(&restoreJob.Status.Conditions) {
|
||||
if err := r.Status().Update(ctx, restoreJob); err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
}
|
||||
return ctrl.Result{RequeueAfter: altinityPollInterval}, nil
|
||||
}
|
||||
}
|
||||
@@ -3,22 +3,26 @@ package backupcontroller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
batchv1 "k8s.io/api/batch/v1"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
dynamicfake "k8s.io/client-go/dynamic/fake"
|
||||
"k8s.io/client-go/kubernetes/scheme"
|
||||
"k8s.io/client-go/tools/record"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
|
||||
|
||||
strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1"
|
||||
backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1"
|
||||
@@ -730,14 +734,66 @@ func newAltinityArchiveStrategy(name string) *strategyv1alpha1.Altinity {
|
||||
func TestAltinityArchiveName_FromStartedAtInUTC(t *testing.T) {
|
||||
startedAt := metav1.NewTime(time.Date(2026, 3, 4, 8, 6, 7, 890000000, time.FixedZone("UTC+3", 3*3600)))
|
||||
j := &backupsv1alpha1.BackupJob{
|
||||
Spec: backupsv1alpha1.BackupJobSpec{ApplicationRef: newAltinityClickHouseRef("ch-test")},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt},
|
||||
ObjectMeta: metav1.ObjectMeta{UID: "0f3c9a1e-5b7d-4c2a-9e8f-1a2b3c4d5e6f"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{ApplicationRef: newAltinityClickHouseRef("ch-test")},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt},
|
||||
}
|
||||
if got, want := altinityArchiveName(j), "clickhouse-ch-test-20260304T050607Z"; got != want {
|
||||
if got, want := altinityArchiveName(j), "ch-test-20260304050607-0f3c9a1e5b7d"; got != want {
|
||||
t.Errorf("altinityArchiveName = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAltinityArchiveName_NoLongerThanTheNameWithoutUID pins the S3 key
|
||||
// budget: the archive name is part of every object key, a key may not exceed
|
||||
// 1024 bytes, and the legacy s3PathOverride prefix is unbounded, so a prefix
|
||||
// that fit the name without the UID must still fit this one.
|
||||
func TestAltinityArchiveName_NoLongerThanTheNameWithoutUID(t *testing.T) {
|
||||
startedAt := metav1.NewTime(time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC))
|
||||
for n := 1; n <= 63; n++ {
|
||||
j := &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{UID: "0f3c9a1e-5b7d-4c2a-9e8f-1a2b3c4d5e6f"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{ApplicationRef: newAltinityClickHouseRef(strings.Repeat("a", n))},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt},
|
||||
}
|
||||
name, legacy := altinityArchiveName(j), altinityArchiveNameBeforeUIDs(j)
|
||||
if len(name) > len(legacy) {
|
||||
t.Errorf("application name of %d characters: archive %q is longer than %q", n, name, legacy)
|
||||
}
|
||||
// The manifest key of a prefix that left the name without the UID
|
||||
// exactly at the limit.
|
||||
prefix := strings.Repeat("p", 1024-len("/"+legacy+"/metadata.json"))
|
||||
if key := prefix + "/" + name + "/metadata.json"; len(key) > 1024 {
|
||||
t.Errorf("application name of %d characters: manifest key is %d bytes", n, len(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAltinityArchiveName_DistinctForRunsStartedInTheSameSecond pins that two
|
||||
// BackupJobs of one application started within the same second, as two Plans
|
||||
// on the same schedule are, write different archives. With a shared name, the
|
||||
// strategy takes the other run's finished upload for an earlier attempt of its
|
||||
// own and records an archive missing what changed since that upload.
|
||||
func TestAltinityArchiveName_DistinctForRunsStartedInTheSameSecond(t *testing.T) {
|
||||
startedAt := metav1.NewTime(time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC))
|
||||
run := func(name, uid string) *backupsv1alpha1.BackupJob {
|
||||
return &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "tenant-test", UID: types.UID(uid)},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{ApplicationRef: newAltinityClickHouseRef("ch-test")},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt},
|
||||
}
|
||||
}
|
||||
daily := altinityArchiveName(run("daily-1", "11111111-1111-1111-1111-111111111111"))
|
||||
weekly := altinityArchiveName(run("weekly-1", "22222222-2222-2222-2222-222222222222"))
|
||||
if daily == weekly {
|
||||
t.Fatalf("two runs started in the same second share archive %q", daily)
|
||||
}
|
||||
for _, name := range []string{daily, weekly} {
|
||||
if !strings.HasPrefix(name, "ch-test-20260304050607-") {
|
||||
t.Errorf("archive %q does not start with the application and start time, so names stop sorting chronologically", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileAltinity_RecordsTheArchiveTheJobWasGiven drives one BackupJob
|
||||
// through Job creation and completion in separate reconciles. The archive
|
||||
// name has to come out of the persisted StartedAt both times: the Pod is
|
||||
@@ -748,7 +804,7 @@ func TestReconcileAltinity_RecordsTheArchiveTheJobWasGiven(t *testing.T) {
|
||||
strategy := newAltinityArchiveStrategy("clickhouse-strategy")
|
||||
startedAt := metav1.NewTime(time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC))
|
||||
backupJob := &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"},
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test", UID: "test-bj-uid"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
BackupClassName: "clickhouse-backup",
|
||||
@@ -765,7 +821,7 @@ func TestReconcileAltinity_RecordsTheArchiveTheJobWasGiven(t *testing.T) {
|
||||
}
|
||||
r, _, _ := newAltinityTestEnv(t, app, clientfake.NewClientBuilder().WithObjects(backupJob, strategy))
|
||||
ctx := context.Background()
|
||||
const want = "clickhouse-ch-test-20260304T050607Z"
|
||||
const want = "ch-test-20260304050607-testbjuid"
|
||||
|
||||
if _, err := r.reconcileAltinity(ctx, backupJob, resolved); err != nil {
|
||||
t.Fatalf("reconcileAltinity() creating the Job: %v", err)
|
||||
@@ -801,6 +857,90 @@ func TestReconcileAltinity_RecordsTheArchiveTheJobWasGiven(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileAltinity_RecordsTheArchiveOfAJobNamedBeforeUIDs covers a backup
|
||||
// Job created by a controller that named archives without the BackupJob's UID
|
||||
// and still running when the controller is upgraded: the Job is not
|
||||
// re-rendered, so its archive carries the old name, and the Backup has to
|
||||
// record that name rather than none.
|
||||
func TestReconcileAltinity_RecordsTheArchiveOfAJobNamedBeforeUIDs(t *testing.T) {
|
||||
const legacy = "clickhouse-ch-test-20260304T050607Z"
|
||||
cases := []struct {
|
||||
name string
|
||||
archive string // archive the Job's Pod was rendered with
|
||||
want string
|
||||
}{
|
||||
{name: "the name without the UID", archive: legacy, want: legacy},
|
||||
{name: "a longer name that starts with it", archive: legacy + "-copy", want: ""},
|
||||
{name: "a longer name that ends with it", archive: "copy-" + legacy, want: ""},
|
||||
{name: "a longer name that continues it after a period", archive: legacy + ".copy", want: ""},
|
||||
{name: "a longer name that leads into it with a period", archive: "copy." + legacy, want: ""},
|
||||
{name: "a longer name that continues it after an underscore", archive: legacy + "_copy", want: ""},
|
||||
{name: "a longer name that leads into it with an underscore", archive: "copy_" + legacy, want: ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := recordAltinityArchiveOfJobRenderedWith(t, tc.archive); got != tc.want {
|
||||
t.Errorf("Backup records archive %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// recordAltinityArchiveOfJobRenderedWith completes a backup Job whose Pod
|
||||
// carries the given archive in place of the one the controller rendered, and
|
||||
// returns the archive the resulting Backup records.
|
||||
func recordAltinityArchiveOfJobRenderedWith(t *testing.T, archive string) string {
|
||||
t.Helper()
|
||||
app := newAltinityClickHouseApp("ch-test", "tenant-test")
|
||||
strategy := newAltinityArchiveStrategy("clickhouse-strategy")
|
||||
startedAt := metav1.NewTime(time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC))
|
||||
backupJob := &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test", UID: "test-bj-uid"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
BackupClassName: "clickhouse-backup",
|
||||
},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt, Phase: backupsv1alpha1.BackupJobPhaseRunning},
|
||||
}
|
||||
resolved := &ResolvedBackupConfig{
|
||||
StrategyRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: new(strategyv1alpha1.GroupVersion.Group),
|
||||
Kind: strategyv1alpha1.AltinityStrategyKind,
|
||||
Name: "clickhouse-strategy",
|
||||
},
|
||||
}
|
||||
r, _, _ := newAltinityTestEnv(t, app, clientfake.NewClientBuilder().WithObjects(backupJob, strategy))
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := r.reconcileAltinity(ctx, backupJob, resolved); err != nil {
|
||||
t.Fatalf("reconcileAltinity() creating the Job: %v", err)
|
||||
}
|
||||
job := &batchv1.Job{}
|
||||
if err := r.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: jobNameForBackupJob(backupJob)}, job); err != nil {
|
||||
t.Fatalf("get backup Job: %v", err)
|
||||
}
|
||||
job.Spec.Template.Spec.Containers[0].Args[1] = "--archive=" + archive
|
||||
if err := r.Update(ctx, job); err != nil {
|
||||
t.Fatalf("render the backup Job with archive %q: %v", archive, err)
|
||||
}
|
||||
job.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}}
|
||||
if err := r.Status().Update(ctx, job); err != nil {
|
||||
t.Fatalf("mark backup Job complete: %v", err)
|
||||
}
|
||||
if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), backupJob); err != nil {
|
||||
t.Fatalf("refresh BackupJob: %v", err)
|
||||
}
|
||||
if _, err := r.reconcileAltinity(ctx, backupJob, resolved); err != nil {
|
||||
t.Fatalf("reconcileAltinity() on the completed Job: %v", err)
|
||||
}
|
||||
|
||||
created := &backupsv1alpha1.Backup{}
|
||||
if err := r.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: backupJob.Name}, created); err != nil {
|
||||
t.Fatalf("get Backup: %v", err)
|
||||
}
|
||||
return created.Spec.DriverMetadata[altinityArchiveMetaKey]
|
||||
}
|
||||
|
||||
// TestReconcileAltinity_RecordsNoArchiveTheJobWasNotGiven covers a Job whose
|
||||
// Pod never carried the driver's archive name: one created before the
|
||||
// upgrade that introduced the names, or rendered from a strategy that names
|
||||
@@ -869,13 +1009,13 @@ func TestReconcileAltinity_RecordsNoArchiveTheJobWasNotGiven(t *testing.T) {
|
||||
// A Backup recording this run's own archive is the one an earlier reconcile
|
||||
// created before its status write was lost, and is adopted.
|
||||
func TestReconcileAltinity_BackupNameAlreadyTaken(t *testing.T) {
|
||||
const thisRun = "clickhouse-ch-test-20260305T050607Z"
|
||||
const thisRun = "ch-test-20260305050607-testbjuid"
|
||||
cases := []struct {
|
||||
name string
|
||||
existing string // archive the existing Backup records; empty for none
|
||||
wantSucceeded bool
|
||||
}{
|
||||
{name: "earlier run's Backup records another archive", existing: "clickhouse-ch-test-20260304T050607Z"},
|
||||
{name: "earlier run's Backup records another archive", existing: "ch-test-20260304050607-earlierbjuid"},
|
||||
{name: "earlier run's Backup records no archive", existing: ""},
|
||||
{name: "this run's Backup from a reconcile whose status write was lost", existing: thisRun, wantSucceeded: true},
|
||||
}
|
||||
@@ -885,7 +1025,7 @@ func TestReconcileAltinity_BackupNameAlreadyTaken(t *testing.T) {
|
||||
strategy := newAltinityArchiveStrategy("clickhouse-strategy")
|
||||
startedAt := metav1.NewTime(time.Date(2026, 3, 5, 5, 6, 7, 0, time.UTC))
|
||||
backupJob := &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"},
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test", UID: "test-bj-uid"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
BackupClassName: "clickhouse-backup",
|
||||
@@ -1032,3 +1172,539 @@ func TestReconcileAltinityRestore_RendersTheBackupsArchive(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func projectedCredentials(namespace string, updatedAt time.Time) *corev1.Secret {
|
||||
return &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Namespace: namespace,
|
||||
Name: "cozy-backups-creds",
|
||||
Annotations: map[string]string{credentialsUpdatedAtAnnotation: updatedAt.UTC().Format(time.RFC3339)},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// The ClickHouse sidecar reads the projected credentials from a mounted
|
||||
// file that kubelet rewrites only some time after the Secret changes, so a
|
||||
// strategy Job started right after a projection would reach a sidecar with
|
||||
// no or stale credentials.
|
||||
func TestReconcileAltinity_WaitsForProjectedCredentialsToReachTheSidecar(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
secret *corev1.Secret
|
||||
jobExists bool
|
||||
wantWait bool
|
||||
}{
|
||||
{name: "credentials changed just now", secret: projectedCredentials("tenant-test", time.Now()), wantWait: true},
|
||||
{name: "credentials changed long ago", secret: projectedCredentials("tenant-test", time.Now().Add(-altinityCredentialsPropagation-time.Second))},
|
||||
{name: "no projected credentials", secret: nil},
|
||||
{name: "the Job already runs", secret: projectedCredentials("tenant-test", time.Now()), jobExists: true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
now := metav1.Now()
|
||||
backupJob := &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
BackupClassName: "clickhouse-backup",
|
||||
},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &now},
|
||||
}
|
||||
objs := []client.Object{backupJob, newAltinityStrategy("clickhouse-strategy")}
|
||||
if tc.secret != nil {
|
||||
objs = append(objs, tc.secret)
|
||||
}
|
||||
if tc.jobExists {
|
||||
objs = append(objs, &batchv1.Job{ObjectMeta: metav1.ObjectMeta{Namespace: "tenant-test", Name: jobNameForBackupJob(backupJob)}})
|
||||
}
|
||||
r, _, _ := newAltinityTestEnv(t, newAltinityClickHouseApp("ch-test", "tenant-test"), clientfake.NewClientBuilder().WithObjects(objs...))
|
||||
r.CredentialsConfig.TargetSecretName = "cozy-backups-creds"
|
||||
resolved := &ResolvedBackupConfig{
|
||||
StrategyRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: new(strategyv1alpha1.GroupVersion.Group),
|
||||
Kind: strategyv1alpha1.AltinityStrategyKind,
|
||||
Name: "clickhouse-strategy",
|
||||
},
|
||||
}
|
||||
ctx := context.Background()
|
||||
j := &backupsv1alpha1.BackupJob{}
|
||||
if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), j); err != nil {
|
||||
t.Fatalf("get BackupJob: %v", err)
|
||||
}
|
||||
res, err := r.reconcileAltinity(ctx, j, resolved)
|
||||
if err != nil {
|
||||
t.Fatalf("reconcileAltinity: %v", err)
|
||||
}
|
||||
jobs := &batchv1.JobList{}
|
||||
if err := r.List(ctx, jobs, client.InNamespace("tenant-test")); err != nil {
|
||||
t.Fatalf("list Jobs: %v", err)
|
||||
}
|
||||
ready := meta.FindStatusCondition(j.Status.Conditions, "Ready")
|
||||
if tc.wantWait {
|
||||
if len(jobs.Items) != 0 {
|
||||
t.Errorf("a strategy Job was created %d time(s) before the credentials could reach the sidecar", len(jobs.Items))
|
||||
}
|
||||
if res.RequeueAfter <= 0 || res.RequeueAfter > altinityCredentialsPropagation {
|
||||
t.Errorf("RequeueAfter = %v, want within (0, %v]", res.RequeueAfter, altinityCredentialsPropagation)
|
||||
}
|
||||
if ready == nil || ready.Reason != "WaitingForCredentials" {
|
||||
t.Errorf("Ready = %+v, want WaitingForCredentials", ready)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(jobs.Items) != 1 {
|
||||
t.Errorf("got %d strategy Jobs, want 1", len(jobs.Items))
|
||||
}
|
||||
if ready != nil && ready.Reason == "WaitingForCredentials" {
|
||||
t.Errorf("Ready = %+v, the job should not wait", ready)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcileAltinityRestore_WaitsForProjectedCredentialsToReachTheSidecar(t *testing.T) {
|
||||
now := metav1.Now()
|
||||
backup := &backupsv1alpha1.Backup{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "ch-backup", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.BackupSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
StrategyRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: new(strategyv1alpha1.GroupVersion.Group),
|
||||
Kind: strategyv1alpha1.AltinityStrategyKind,
|
||||
Name: "clickhouse-strategy",
|
||||
},
|
||||
TakenAt: now,
|
||||
},
|
||||
}
|
||||
restoreJob := &backupsv1alpha1.RestoreJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-rj", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.RestoreJobSpec{BackupRef: corev1.LocalObjectReference{Name: backup.Name}},
|
||||
Status: backupsv1alpha1.RestoreJobStatus{StartedAt: &now, Phase: backupsv1alpha1.RestoreJobPhaseRunning},
|
||||
}
|
||||
_, rr, _ := newAltinityTestEnv(t, newAltinityClickHouseApp("ch-test", "tenant-test"),
|
||||
clientfake.NewClientBuilder().WithObjects(newAltinityStrategy("clickhouse-strategy"), backup, restoreJob,
|
||||
projectedCredentials("tenant-test", time.Now())))
|
||||
rr.CredentialsConfig.TargetSecretName = "cozy-backups-creds"
|
||||
ctx := context.Background()
|
||||
rj := &backupsv1alpha1.RestoreJob{}
|
||||
if err := rr.Get(ctx, client.ObjectKeyFromObject(restoreJob), rj); err != nil {
|
||||
t.Fatalf("get RestoreJob: %v", err)
|
||||
}
|
||||
res, err := rr.reconcileAltinityRestore(ctx, rj, backup)
|
||||
if err != nil {
|
||||
t.Fatalf("reconcileAltinityRestore: %v", err)
|
||||
}
|
||||
jobs := &batchv1.JobList{}
|
||||
if err := rr.List(ctx, jobs, client.InNamespace("tenant-test")); err != nil {
|
||||
t.Fatalf("list Jobs: %v", err)
|
||||
}
|
||||
if len(jobs.Items) != 0 {
|
||||
t.Errorf("a restore Job was created before the credentials could reach the sidecar")
|
||||
}
|
||||
if res.RequeueAfter <= 0 {
|
||||
t.Errorf("RequeueAfter = %v, want a wait", res.RequeueAfter)
|
||||
}
|
||||
if ready := meta.FindStatusCondition(rj.Status.Conditions, "Ready"); ready == nil || ready.Reason != "WaitingForCredentials" {
|
||||
t.Errorf("Ready = %+v, want WaitingForCredentials", ready)
|
||||
}
|
||||
}
|
||||
|
||||
// Without credentials projection configured there is no Secret to wait
|
||||
// for; client-go refuses a Get with an empty name, so it must not be asked.
|
||||
func TestReconcileAltinity_NoProjectionConfiguredDoesNotWait(t *testing.T) {
|
||||
now := metav1.Now()
|
||||
backupJob := &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
BackupClassName: "clickhouse-backup",
|
||||
},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &now},
|
||||
}
|
||||
builder := clientfake.NewClientBuilder().
|
||||
WithObjects(backupJob, newAltinityStrategy("clickhouse-strategy")).
|
||||
WithInterceptorFuncs(interceptor.Funcs{
|
||||
Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
|
||||
if key.Name == "" {
|
||||
return errors.New("resource name may not be empty")
|
||||
}
|
||||
return cl.Get(ctx, key, obj, opts...)
|
||||
},
|
||||
})
|
||||
r, _, _ := newAltinityTestEnv(t, newAltinityClickHouseApp("ch-test", "tenant-test"), builder)
|
||||
resolved := &ResolvedBackupConfig{
|
||||
StrategyRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: new(strategyv1alpha1.GroupVersion.Group),
|
||||
Kind: strategyv1alpha1.AltinityStrategyKind,
|
||||
Name: "clickhouse-strategy",
|
||||
},
|
||||
}
|
||||
ctx := context.Background()
|
||||
j := &backupsv1alpha1.BackupJob{}
|
||||
if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), j); err != nil {
|
||||
t.Fatalf("get BackupJob: %v", err)
|
||||
}
|
||||
if _, err := r.reconcileAltinity(ctx, j, resolved); err != nil {
|
||||
t.Fatalf("reconcileAltinity: %v", err)
|
||||
}
|
||||
jobs := &batchv1.JobList{}
|
||||
if err := r.List(ctx, jobs, client.InNamespace("tenant-test")); err != nil {
|
||||
t.Fatalf("list Jobs: %v", err)
|
||||
}
|
||||
if len(jobs.Items) != 1 {
|
||||
t.Fatalf("got %d strategy Jobs, want 1", len(jobs.Items))
|
||||
}
|
||||
}
|
||||
|
||||
func projectedCredentialsStamped(namespace, stamp string) *corev1.Secret {
|
||||
return &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Namespace: namespace,
|
||||
Name: "cozy-backups-creds",
|
||||
Annotations: map[string]string{credentialsUpdatedAtAnnotation: stamp},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func waitingForCredentials() []metav1.Condition {
|
||||
return []metav1.Condition{credentialsWaitCondition("cozy-backups-creds", time.Minute)}
|
||||
}
|
||||
|
||||
// Once the hold is over and the Job runs, a Ready condition still saying the
|
||||
// job is waiting for credentials describes a state the job has left.
|
||||
func TestReconcileAltinity_ClearsTheCredentialsWaitOnceTheJobRuns(t *testing.T) {
|
||||
now := metav1.Now()
|
||||
backupJob := &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
BackupClassName: "clickhouse-backup",
|
||||
},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &now, Conditions: waitingForCredentials()},
|
||||
}
|
||||
r, _, _ := newAltinityTestEnv(t, newAltinityClickHouseApp("ch-test", "tenant-test"),
|
||||
clientfake.NewClientBuilder().WithObjects(backupJob, newAltinityStrategy("clickhouse-strategy"),
|
||||
projectedCredentials("tenant-test", time.Now().Add(-altinityCredentialsPropagation-time.Second))).
|
||||
WithStatusSubresource(&backupsv1alpha1.BackupJob{}))
|
||||
r.CredentialsConfig.TargetSecretName = "cozy-backups-creds"
|
||||
resolved := &ResolvedBackupConfig{
|
||||
StrategyRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: new(strategyv1alpha1.GroupVersion.Group),
|
||||
Kind: strategyv1alpha1.AltinityStrategyKind,
|
||||
Name: "clickhouse-strategy",
|
||||
},
|
||||
}
|
||||
ctx := context.Background()
|
||||
j := &backupsv1alpha1.BackupJob{}
|
||||
if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), j); err != nil {
|
||||
t.Fatalf("get BackupJob: %v", err)
|
||||
}
|
||||
if _, err := r.reconcileAltinity(ctx, j, resolved); err != nil {
|
||||
t.Fatalf("reconcileAltinity: %v", err)
|
||||
}
|
||||
jobs := &batchv1.JobList{}
|
||||
if err := r.List(ctx, jobs, client.InNamespace("tenant-test")); err != nil {
|
||||
t.Fatalf("list Jobs: %v", err)
|
||||
}
|
||||
if len(jobs.Items) != 1 {
|
||||
t.Fatalf("got %d strategy Jobs, want 1", len(jobs.Items))
|
||||
}
|
||||
stored := &backupsv1alpha1.BackupJob{}
|
||||
if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), stored); err != nil {
|
||||
t.Fatalf("get BackupJob: %v", err)
|
||||
}
|
||||
if ready := meta.FindStatusCondition(stored.Status.Conditions, "Ready"); ready != nil && ready.Reason == "WaitingForCredentials" {
|
||||
t.Errorf("stored Ready = %+v while the Job runs", ready)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcileAltinityRestore_ClearsTheCredentialsWaitOnceTheJobRuns(t *testing.T) {
|
||||
now := metav1.Now()
|
||||
backup := &backupsv1alpha1.Backup{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "ch-backup", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.BackupSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
StrategyRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: new(strategyv1alpha1.GroupVersion.Group),
|
||||
Kind: strategyv1alpha1.AltinityStrategyKind,
|
||||
Name: "clickhouse-strategy",
|
||||
},
|
||||
TakenAt: now,
|
||||
},
|
||||
}
|
||||
restoreJob := &backupsv1alpha1.RestoreJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-rj", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.RestoreJobSpec{BackupRef: corev1.LocalObjectReference{Name: backup.Name}},
|
||||
Status: backupsv1alpha1.RestoreJobStatus{StartedAt: &now, Phase: backupsv1alpha1.RestoreJobPhaseRunning,
|
||||
Conditions: waitingForCredentials()},
|
||||
}
|
||||
_, rr, _ := newAltinityTestEnv(t, newAltinityClickHouseApp("ch-test", "tenant-test"),
|
||||
clientfake.NewClientBuilder().WithObjects(newAltinityStrategy("clickhouse-strategy"), backup, restoreJob,
|
||||
projectedCredentials("tenant-test", time.Now().Add(-altinityCredentialsPropagation-time.Second))).
|
||||
WithStatusSubresource(&backupsv1alpha1.RestoreJob{}))
|
||||
rr.CredentialsConfig.TargetSecretName = "cozy-backups-creds"
|
||||
ctx := context.Background()
|
||||
rj := &backupsv1alpha1.RestoreJob{}
|
||||
if err := rr.Get(ctx, client.ObjectKeyFromObject(restoreJob), rj); err != nil {
|
||||
t.Fatalf("get RestoreJob: %v", err)
|
||||
}
|
||||
if _, err := rr.reconcileAltinityRestore(ctx, rj, backup); err != nil {
|
||||
t.Fatalf("reconcileAltinityRestore: %v", err)
|
||||
}
|
||||
stored := &backupsv1alpha1.RestoreJob{}
|
||||
if err := rr.Get(ctx, client.ObjectKeyFromObject(restoreJob), stored); err != nil {
|
||||
t.Fatalf("get RestoreJob: %v", err)
|
||||
}
|
||||
if ready := meta.FindStatusCondition(stored.Status.Conditions, "Ready"); ready != nil && ready.Reason == "WaitingForCredentials" {
|
||||
t.Errorf("stored Ready = %+v while the Job runs", ready)
|
||||
}
|
||||
}
|
||||
|
||||
// The stamp is only ever rewritten when the projected content changes, so a
|
||||
// value the hold cannot use must not hold the job: an unreadable one would
|
||||
// fail every reconcile, and one far in the future would wait again on each.
|
||||
// A stamp a little ahead, as a skewed clock writes it, still waits, but only
|
||||
// until that stamp plus the propagation time.
|
||||
func TestCredentialsPropagationWait_UnusableStampsDoNotHoldTheJob(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
stamp string
|
||||
wantMin time.Duration
|
||||
wantMax time.Duration
|
||||
}{
|
||||
{name: "unreadable", stamp: "garbage"},
|
||||
{name: "far in the future", stamp: "3000-01-01T00:00:00Z"},
|
||||
{name: "slightly ahead", stamp: time.Now().Add(30 * time.Second).UTC().Format(time.RFC3339),
|
||||
wantMin: altinityCredentialsPropagation, wantMax: altinityCredentialsPropagation + 31*time.Second},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c := clientfake.NewClientBuilder().WithObjects(projectedCredentialsStamped("tenant-test", tc.stamp)).Build()
|
||||
wait, err := credentialsPropagationWait(context.Background(), c, "cozy-backups-creds", "tenant-test", "job")
|
||||
if err != nil {
|
||||
t.Fatalf("credentialsPropagationWait: %v", err)
|
||||
}
|
||||
if wait < tc.wantMin || wait > tc.wantMax {
|
||||
t.Errorf("wait = %v, want within [%v, %v]", wait, tc.wantMin, tc.wantMax)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearCredentialsWait_KeepsAReadyConditionItDidNotSet(t *testing.T) {
|
||||
conditions := []metav1.Condition{{Type: "Ready", Status: metav1.ConditionFalse, Reason: "StrategyNotReady"}}
|
||||
if clearCredentialsWait(&conditions) {
|
||||
t.Errorf("clearCredentialsWait reported clearing a Ready condition with reason StrategyNotReady")
|
||||
}
|
||||
if ready := meta.FindStatusCondition(conditions, "Ready"); ready == nil || ready.Reason != "StrategyNotReady" {
|
||||
t.Errorf("Ready = %+v, want the StrategyNotReady condition kept", ready)
|
||||
}
|
||||
}
|
||||
|
||||
// A read the hold cannot complete must not release the Job: starting it
|
||||
// before the credentials reach the sidecar is the failure the hold prevents.
|
||||
func TestReconcileAltinity_UnreadableHoldStateDoesNotStartTheJob(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
fail func(key client.ObjectKey, obj client.Object) bool
|
||||
}{
|
||||
{name: "credentials Secret", fail: func(key client.ObjectKey, obj client.Object) bool {
|
||||
_, isSecret := obj.(*corev1.Secret)
|
||||
return isSecret && key.Name == "cozy-backups-creds"
|
||||
}},
|
||||
{name: "strategy Job", fail: func(key client.ObjectKey, obj client.Object) bool {
|
||||
_, isJob := obj.(*batchv1.Job)
|
||||
return isJob
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
now := metav1.Now()
|
||||
backupJob := &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
BackupClassName: "clickhouse-backup",
|
||||
},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &now},
|
||||
}
|
||||
builder := clientfake.NewClientBuilder().
|
||||
WithObjects(backupJob, newAltinityStrategy("clickhouse-strategy"),
|
||||
projectedCredentials("tenant-test", time.Now().Add(-altinityCredentialsPropagation-time.Second))).
|
||||
WithInterceptorFuncs(interceptor.Funcs{
|
||||
Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
|
||||
if tc.fail(key, obj) {
|
||||
return apierrors.NewInternalError(errors.New("etcd unavailable"))
|
||||
}
|
||||
return cl.Get(ctx, key, obj, opts...)
|
||||
},
|
||||
})
|
||||
r, _, _ := newAltinityTestEnv(t, newAltinityClickHouseApp("ch-test", "tenant-test"), builder)
|
||||
r.CredentialsConfig.TargetSecretName = "cozy-backups-creds"
|
||||
resolved := &ResolvedBackupConfig{
|
||||
StrategyRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: new(strategyv1alpha1.GroupVersion.Group),
|
||||
Kind: strategyv1alpha1.AltinityStrategyKind,
|
||||
Name: "clickhouse-strategy",
|
||||
},
|
||||
}
|
||||
ctx := context.Background()
|
||||
j := &backupsv1alpha1.BackupJob{}
|
||||
if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), j); err != nil {
|
||||
t.Fatalf("get BackupJob: %v", err)
|
||||
}
|
||||
if _, err := r.reconcileAltinity(ctx, j, resolved); err == nil {
|
||||
t.Errorf("reconcileAltinity returned no error although the %s could not be read", tc.name)
|
||||
}
|
||||
jobs := &batchv1.JobList{}
|
||||
if err := r.List(ctx, jobs, client.InNamespace("tenant-test")); err != nil {
|
||||
t.Fatalf("list Jobs: %v", err)
|
||||
}
|
||||
if len(jobs.Items) != 0 {
|
||||
t.Errorf("a strategy Job was created although the %s could not be read", tc.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcileAltinityRestore_UnreadableHoldStateDoesNotStartTheJob(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
fail func(key client.ObjectKey, obj client.Object) bool
|
||||
}{
|
||||
{name: "credentials Secret", fail: func(key client.ObjectKey, obj client.Object) bool {
|
||||
_, isSecret := obj.(*corev1.Secret)
|
||||
return isSecret && key.Name == "cozy-backups-creds"
|
||||
}},
|
||||
{name: "strategy Job", fail: func(key client.ObjectKey, obj client.Object) bool {
|
||||
_, isJob := obj.(*batchv1.Job)
|
||||
return isJob
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
now := metav1.Now()
|
||||
backup := &backupsv1alpha1.Backup{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "ch-backup", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.BackupSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
StrategyRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: new(strategyv1alpha1.GroupVersion.Group),
|
||||
Kind: strategyv1alpha1.AltinityStrategyKind,
|
||||
Name: "clickhouse-strategy",
|
||||
},
|
||||
TakenAt: now,
|
||||
},
|
||||
}
|
||||
restoreJob := &backupsv1alpha1.RestoreJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-rj", Namespace: "tenant-test"},
|
||||
Spec: backupsv1alpha1.RestoreJobSpec{BackupRef: corev1.LocalObjectReference{Name: backup.Name}},
|
||||
Status: backupsv1alpha1.RestoreJobStatus{StartedAt: &now, Phase: backupsv1alpha1.RestoreJobPhaseRunning},
|
||||
}
|
||||
builder := clientfake.NewClientBuilder().
|
||||
WithObjects(newAltinityStrategy("clickhouse-strategy"), backup, restoreJob,
|
||||
projectedCredentials("tenant-test", time.Now().Add(-altinityCredentialsPropagation-time.Second))).
|
||||
WithInterceptorFuncs(interceptor.Funcs{
|
||||
Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
|
||||
if tc.fail(key, obj) {
|
||||
return apierrors.NewInternalError(errors.New("etcd unavailable"))
|
||||
}
|
||||
return cl.Get(ctx, key, obj, opts...)
|
||||
},
|
||||
})
|
||||
_, rr, _ := newAltinityTestEnv(t, newAltinityClickHouseApp("ch-test", "tenant-test"), builder)
|
||||
rr.CredentialsConfig.TargetSecretName = "cozy-backups-creds"
|
||||
ctx := context.Background()
|
||||
rj := &backupsv1alpha1.RestoreJob{}
|
||||
if err := rr.Get(ctx, client.ObjectKeyFromObject(restoreJob), rj); err != nil {
|
||||
t.Fatalf("get RestoreJob: %v", err)
|
||||
}
|
||||
if _, err := rr.reconcileAltinityRestore(ctx, rj, backup); err == nil {
|
||||
t.Errorf("reconcileAltinityRestore returned no error although the %s could not be read", tc.name)
|
||||
}
|
||||
jobs := &batchv1.JobList{}
|
||||
if err := rr.List(ctx, jobs, client.InNamespace("tenant-test")); err != nil {
|
||||
t.Fatalf("list Jobs: %v", err)
|
||||
}
|
||||
if len(jobs.Items) != 0 {
|
||||
t.Errorf("a restore Job was created although the %s could not be read", tc.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A backup held for the credentials keeps the archive name it was given from
|
||||
// its persisted StartedAt: the held reconciles write the job's status, and the
|
||||
// Pod created after the hold, and the Backup recorded after it, must still
|
||||
// name the same archive, which is stamped no later than the Backup's takenAt.
|
||||
func TestReconcileAltinity_CredentialsWaitKeepsTheArchiveName(t *testing.T) {
|
||||
startedAt := metav1.NewTime(time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC))
|
||||
backupJob := &backupsv1alpha1.BackupJob{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test-bj", Namespace: "tenant-test", UID: "0f3c9a1e-5b7d-4c2a-9e8f-1a2b3c4d5e6f"},
|
||||
Spec: backupsv1alpha1.BackupJobSpec{
|
||||
ApplicationRef: newAltinityClickHouseRef("ch-test"),
|
||||
BackupClassName: "clickhouse-backup",
|
||||
},
|
||||
Status: backupsv1alpha1.BackupJobStatus{StartedAt: &startedAt, Phase: backupsv1alpha1.BackupJobPhaseRunning},
|
||||
}
|
||||
secret := projectedCredentials("tenant-test", time.Now())
|
||||
r, _, _ := newAltinityTestEnv(t, newAltinityClickHouseApp("ch-test", "tenant-test"),
|
||||
clientfake.NewClientBuilder().WithObjects(backupJob, newAltinityArchiveStrategy("clickhouse-strategy"), secret))
|
||||
r.CredentialsConfig.TargetSecretName = "cozy-backups-creds"
|
||||
resolved := &ResolvedBackupConfig{
|
||||
StrategyRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: new(strategyv1alpha1.GroupVersion.Group),
|
||||
Kind: strategyv1alpha1.AltinityStrategyKind,
|
||||
Name: "clickhouse-strategy",
|
||||
},
|
||||
}
|
||||
ctx := context.Background()
|
||||
const want = "ch-test-20260304050607-0f3c9a1e5b7d"
|
||||
reconcile := func(step string) {
|
||||
t.Helper()
|
||||
j := &backupsv1alpha1.BackupJob{}
|
||||
if err := r.Get(ctx, client.ObjectKeyFromObject(backupJob), j); err != nil {
|
||||
t.Fatalf("%s: get BackupJob: %v", step, err)
|
||||
}
|
||||
if _, err := r.reconcileAltinity(ctx, j, resolved); err != nil {
|
||||
t.Fatalf("%s: reconcileAltinity: %v", step, err)
|
||||
}
|
||||
}
|
||||
|
||||
reconcile("held")
|
||||
job := &batchv1.Job{}
|
||||
if err := r.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: jobNameForBackupJob(backupJob)}, job); !apierrors.IsNotFound(err) {
|
||||
t.Fatalf("the Job exists while the credentials wait should hold it: %v", err)
|
||||
}
|
||||
|
||||
if err := r.Get(ctx, client.ObjectKeyFromObject(secret), secret); err != nil {
|
||||
t.Fatalf("get projected Secret: %v", err)
|
||||
}
|
||||
secret.Annotations[credentialsUpdatedAtAnnotation] = time.Now().Add(-altinityCredentialsPropagation - time.Second).UTC().Format(time.RFC3339)
|
||||
if err := r.Update(ctx, secret); err != nil {
|
||||
t.Fatalf("age the credentials stamp: %v", err)
|
||||
}
|
||||
reconcile("after the wait")
|
||||
if err := r.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: jobNameForBackupJob(backupJob)}, job); err != nil {
|
||||
t.Fatalf("get backup Job: %v", err)
|
||||
}
|
||||
if got := job.Spec.Template.Spec.Containers[0].Args[1]; got != "--archive="+want {
|
||||
t.Fatalf("backup Pod was rendered with %q after the wait, want --archive=%s", got, want)
|
||||
}
|
||||
|
||||
job.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}}
|
||||
if err := r.Status().Update(ctx, job); err != nil {
|
||||
t.Fatalf("mark backup Job complete: %v", err)
|
||||
}
|
||||
reconcile("completed")
|
||||
created := &backupsv1alpha1.Backup{}
|
||||
if err := r.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: backupJob.Name}, created); err != nil {
|
||||
t.Fatalf("get Backup: %v", err)
|
||||
}
|
||||
if got := created.Spec.DriverMetadata[altinityArchiveMetaKey]; got != want {
|
||||
t.Errorf("Backup records archive %q, want %q", got, want)
|
||||
}
|
||||
if stamp := created.Spec.TakenAt.UTC().Format(altinityArchiveTimeLayout); stamp < "20260304T050607Z" {
|
||||
t.Errorf("Backup takenAt %s is earlier than its archive's stamp", stamp)
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ type s3ObjectInfo struct {
|
||||
|
||||
type s3ObjectLister interface {
|
||||
ListObjects(ctx context.Context, bucket, prefix string, recursive bool) ([]s3ObjectInfo, error)
|
||||
StatObject(ctx context.Context, bucket, key string) (int64, error)
|
||||
}
|
||||
|
||||
// s3Connection is what a driver resolves from its rendered strategy to
|
||||
@@ -53,6 +54,9 @@ type s3Connection struct {
|
||||
// what the writer of the backup trusted, no more.
|
||||
CAPEM []byte
|
||||
CAOnly bool
|
||||
// InsecureSkipVerify mirrors an explicit admin opt-in a strategy
|
||||
// already applies to its own uploads; it is never a fallback.
|
||||
InsecureSkipVerify bool
|
||||
}
|
||||
|
||||
// objectStore reads back what a backup wrote: the Secrets it was written
|
||||
@@ -104,14 +108,18 @@ func newMinioObjectLister(conn s3Connection) (s3ObjectLister, error) {
|
||||
Region: conn.Region,
|
||||
Secure: conn.Secure,
|
||||
}
|
||||
if conn.Secure && len(conn.CAPEM) > 0 {
|
||||
if conn.Secure && (len(conn.CAPEM) > 0 || conn.InsecureSkipVerify) {
|
||||
// Start from minio's transport to keep its proxy and timeout settings.
|
||||
tr, err := minio.DefaultTransport(true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tr.TLSClientConfig.RootCAs, err = endpointTrustPool(conn, tr.TLSClientConfig.RootCAs); err != nil {
|
||||
return nil, err
|
||||
if len(conn.CAPEM) > 0 {
|
||||
if tr.TLSClientConfig.RootCAs, err = endpointTrustPool(conn, tr.TLSClientConfig.RootCAs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
tr.TLSClientConfig.InsecureSkipVerify = true
|
||||
}
|
||||
opts.Transport = tr
|
||||
}
|
||||
@@ -148,6 +156,18 @@ func (l *minioObjectLister) ListObjects(ctx context.Context, bucket, prefix stri
|
||||
return collectObjects(ctx, l.client.ListObjects(ctx, bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: recursive}))
|
||||
}
|
||||
|
||||
func (l *minioObjectLister) StatObject(ctx context.Context, bucket, key string) (int64, error) {
|
||||
info, err := l.client.StatObject(ctx, bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// minio-go reports -1 when the response carries no Content-Length.
|
||||
if info.Size < 0 {
|
||||
return 0, fmt.Errorf("object %s/%s: the endpoint reported no size", bucket, key)
|
||||
}
|
||||
return info.Size, nil
|
||||
}
|
||||
|
||||
// collectObjects drains a minio listing. minio-go ends a listing whose
|
||||
// context is cancelled between pages by closing the channel without an
|
||||
// error item, so a cancelled context is checked once the channel closes:
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -37,6 +38,16 @@ type fakeS3Lister struct {
|
||||
bucket, prefix string
|
||||
recursive bool
|
||||
calls int
|
||||
|
||||
statSize int64
|
||||
statErr error
|
||||
statKey string
|
||||
}
|
||||
|
||||
func (f *fakeS3Lister) StatObject(_ context.Context, bucket, key string) (int64, error) {
|
||||
f.calls++
|
||||
f.bucket, f.statKey = bucket, key
|
||||
return f.statSize, f.statErr
|
||||
}
|
||||
|
||||
func (f *fakeS3Lister) ListObjects(_ context.Context, bucket, prefix string, recursive bool) ([]s3ObjectInfo, error) {
|
||||
@@ -167,6 +178,11 @@ func (blockingLister) ListObjects(ctx context.Context, _, _ string, _ bool) ([]s
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
func (blockingLister) StatObject(ctx context.Context, _, _ string) (int64, error) {
|
||||
<-ctx.Done()
|
||||
return 0, ctx.Err()
|
||||
}
|
||||
|
||||
// withShortProbeTimeout shortens the probe timeout and fails the test if fn
|
||||
// is not back well before the default timeout would have expired.
|
||||
func withShortProbeTimeout(t *testing.T, fn func()) {
|
||||
@@ -233,6 +249,76 @@ func TestFailBackupArtifact(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// unrelatedCAPEM mints a CA that signed nothing an httptest server serves:
|
||||
// every httptest server shares one certificate.
|
||||
func unrelatedCAPEM(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "unrelated CA"}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
}
|
||||
|
||||
// TestMinioObjectLister_EnforcesTheCA pins that a configured CA is the
|
||||
// trust the client verifies with, whether alone or on top of the system
|
||||
// roots: an endpoint whose certificate it did not sign is refused.
|
||||
func TestMinioObjectLister_EnforcesTheCA(t *testing.T) {
|
||||
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Length", "1")
|
||||
w.Header().Set("ETag", `"abc"`)
|
||||
w.Header().Set("Last-Modified", "Wed, 21 Oct 2026 10:00:00 GMT")
|
||||
}))
|
||||
defer srv.Close()
|
||||
// minio-go retries a TLS failure with backoff; a refusal needs no more
|
||||
// than the first attempt.
|
||||
stat := func(ca []byte, caOnly bool) error {
|
||||
l, err := newMinioObjectLister(s3Connection{
|
||||
Endpoint: strings.TrimPrefix(srv.URL, "https://"), Secure: true,
|
||||
AccessKey: "AKID", SecretKey: "secret", Region: "us-east-1",
|
||||
CAPEM: ca, CAOnly: caOnly,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("newMinioObjectLister: %v", err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
_, err = l.StatObject(ctx, "cozy-backups", "k")
|
||||
return err
|
||||
}
|
||||
signer := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw})
|
||||
for _, caOnly := range []bool{true, false} {
|
||||
if err := stat(signer, caOnly); err != nil {
|
||||
t.Errorf("CAOnly=%v: the CA that signed the endpoint: %v", caOnly, err)
|
||||
}
|
||||
if err := stat(unrelatedCAPEM(t), caOnly); err == nil {
|
||||
t.Errorf("CAOnly=%v: StatObject succeeded against a certificate the CA did not sign, want a TLS error", caOnly)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMinioObjectLister_StatWithoutSize pins that a HEAD answer without
|
||||
// Content-Length, which minio-go turns into size -1, is not a size.
|
||||
func TestMinioObjectLister_StatWithoutSize(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("ETag", `"abc"`)
|
||||
w.Header().Set("Last-Modified", "Wed, 21 Oct 2026 10:00:00 GMT")
|
||||
}))
|
||||
defer srv.Close()
|
||||
l, err := newMinioObjectLister(s3Connection{Endpoint: strings.TrimPrefix(srv.URL, "http://"), AccessKey: "AKID", SecretKey: "secret", Region: "us-east-1"})
|
||||
if err != nil {
|
||||
t.Fatalf("newMinioObjectLister: %v", err)
|
||||
}
|
||||
if size, err := l.StatObject(context.Background(), "cozy-backups", "k"); err == nil {
|
||||
t.Errorf("StatObject = %d, nil; want an error for a response without Content-Length", size)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEndpointTrustPool_CAOnly tells apart "the CA on top of the system
|
||||
// roots" and "the CA alone". The system pool holds the endpoint's
|
||||
// certificate, and the configured CA is an unrelated one, so the endpoint
|
||||
@@ -243,18 +329,7 @@ func TestEndpointTrustPool_CAOnly(t *testing.T) {
|
||||
system := x509.NewCertPool()
|
||||
system.AddCert(endpoint.Certificate())
|
||||
|
||||
// Every httptest server shares one certificate, so the unrelated CA is
|
||||
// minted here.
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "unrelated CA"}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unrelatedCA := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
unrelatedCA := unrelatedCAPEM(t)
|
||||
|
||||
verifies := func(caOnly bool) bool {
|
||||
pool, err := endpointTrustPool(s3Connection{CAPEM: unrelatedCA, CAOnly: caOnly}, system.Clone())
|
||||
|
||||
@@ -183,6 +183,9 @@ func (r *BackupReconciler) cleanupOnDelete(ctx context.Context, backup *backupsv
|
||||
// deletes the object and WAITS for that delete before the Backup is
|
||||
// removed, so no object is orphaned (see cleanupKafkaBackup).
|
||||
return r.cleanupKafkaBackup(ctx, backup)
|
||||
case strategyv1alpha1.KubernetesStrategyKind:
|
||||
// Owns two artifacts: the Velero backup and the etcd dump object.
|
||||
return r.cleanupKubernetesBackup(ctx, backup)
|
||||
case strategyv1alpha1.VeleroStrategyKind:
|
||||
return ctrl.Result{}, r.cleanupVeleroBackup(ctx, backup)
|
||||
default:
|
||||
|
||||
@@ -214,6 +214,8 @@ func (r *BackupJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
|
||||
return r.reconcileRedis(ctx, j, resolved)
|
||||
case strategyv1alpha1.KafkaStrategyKind:
|
||||
return r.reconcileKafka(ctx, j, resolved)
|
||||
case strategyv1alpha1.KubernetesStrategyKind:
|
||||
return r.reconcileKubernetes(ctx, j, resolved)
|
||||
default:
|
||||
logger.V(1).Info("BackupJob resolved StrategyRef.Kind not supported, skipping",
|
||||
"backupjob", j.Name,
|
||||
@@ -240,6 +242,7 @@ func supportedBackupStrategyKinds() []string {
|
||||
strategyv1alpha1.RabbitmqStrategyKind,
|
||||
strategyv1alpha1.RedisStrategyKind,
|
||||
strategyv1alpha1.KafkaStrategyKind,
|
||||
strategyv1alpha1.KubernetesStrategyKind,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,14 +318,6 @@ func (r *BackupJobReconciler) handleProjectionError(ctx context.Context, j *back
|
||||
}
|
||||
|
||||
// markBackupJobFailed records a terminal Failed phase on the BackupJob.
|
||||
//
|
||||
// Coupling note: a failure that fires before reconcileCNPG's StartedAt block
|
||||
// has set backupJob.Status.StartedAt leaves StartedAt nil. The CNPG path's
|
||||
// cnpgDefaultBackupDeadline check only fires once StartedAt is set, so an
|
||||
// early-failure retry that reaches the StartedAt block restarts the deadline
|
||||
// budget from the retry's StartedAt - intentional, since retries are
|
||||
// user-driven and a fresh budget is what users expect after correcting the
|
||||
// cause of the previous failure.
|
||||
func (r *BackupJobReconciler) markBackupJobFailed(ctx context.Context, backupJob *backupsv1alpha1.BackupJob, message string) (ctrl.Result, error) {
|
||||
logger := getLogger(ctx)
|
||||
now := metav1.Now()
|
||||
|
||||
Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user