Skip to content
quarry Artifact [5e505de004]
Login

Artifact [5e505de004]

Artifact 5e505de00472a6d0758a6f74c771cad690d7a5aeab0e2bbc1ada41f3ed664a14:


package api

import (
	"context"
	"fmt"
	"strings"

	"craftdesign.group/quarry/internal/cibridge"
)

// DeliverChanged answers the bridge's changed-paths route for the CI
// task taskID ("<run>.<job>"): the paths the run's check-in changed on
// its branch (QUARRY_CHANGED) and against its parent (QUARRY_TOUCHED),
// read from the forge's own record of the run, never from the request.
// The bridge has already shown the caller holds the task, so a runner
// reads these for the run it is running on this repository and no
// other, and not once the task is over. A premerge pair is asked about
// its branch tip, as the runner asked the API before.
func (d Deps) DeliverChanged(repo, taskID string) (cibridge.ChangedPaths, error) {
	var out cibridge.ChangedPaths
	if d.Secrets == nil {
		return out, fmt.Errorf("%w: this forge keeps no run records", ErrSecretRefused)
	}
	runID, _, ok := strings.Cut(taskID, ".")
	if !ok || runID == "" {
		return out, fmt.Errorf("%w: %q is not a task id", ErrSecretRefused, taskID)
	}
	run, found, err := d.Secrets.CIRunByID(repo, runID)
	if err != nil {
		return out, err
	}
	if !found {
		return out, fmt.Errorf("%w: no run %.12s in %s", ErrSecretRefused, runID, repo)
	}
	r, err := d.repo(repo)
	if err != nil {
		return out, err
	}
	checkin, isPair := run.Checkin, strings.HasPrefix(run.Checkin, "pair:")
	if isPair {
		branchTip, _, ok := parsePair(run.Checkin)
		if !ok {
			return out, fmt.Errorf("%w: run %.12s names a malformed pair", ErrSecretRefused, runID)
		}
		checkin = branchTip
	}
	if r.Index != nil {
		if m, err := r.Index.BranchOf([]string{checkin}); err == nil {
			out.Branch = m[checkin]
		}
	}
	if r.Index == nil || r.Zit == nil {
		return out, nil
	}
	ctx := context.Background()
	names := func(from, to string) ([]string, error) {
		brief, err := r.Zit.DiffBrief(ctx, from, to)
		if err != nil {
			return nil, err
		}
		paths := make([]string, 0, len(brief))
		for _, f := range brief {
			paths = append(paths, f.Name)
		}
		return paths, nil
	}
	// The branch's change since its fork point; a check-in on the root
	// line has none to give.
	if e, parents, err := diffRangeIn(r, checkin, "", true); err == nil && len(parents) > 0 {
		if out.Changed, err = names(parents[0], e.Hash); err != nil {
			return cibridge.ChangedPaths{}, err
		}
	}
	if !isPair {
		e, parents, err := diffRangeIn(r, checkin, "", false)
		if err != nil {
			return out, nil
		}
		if len(parents) == 0 {
			files, err := r.Zit.LsNames(ctx, e.Hash)
			if err != nil {
				return cibridge.ChangedPaths{}, err
			}
			out.Touched = make([]string, 0, len(files))
			for _, f := range files {
				out.Touched = append(out.Touched, f.Name)
			}
		} else if out.Touched, err = names(parents[0], e.Hash); err != nil {
			return cibridge.ChangedPaths{}, err
		}
	}
	return out, nil
}