Files
agent-lib/internal/client/sync.go
T

248 lines
7.3 KiB
Go
Raw Normal View History

package client
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/m3tam3re/agent-lib/internal/gitsource"
"github.com/m3tam3re/agent-lib/internal/labels"
"github.com/m3tam3re/agent-lib/internal/target"
)
// SyncOptions parameterize a client sync run. RepoURL (with optional Ref)
// is the inline --repo override: it works without any config file and beats
// a repo_url discovered in the config chain. Force switches the planner
// from skip+warn to overwrite for locally modified managed items.
type SyncOptions struct {
ConfigPath string
RepoURL string
Ref string
Force bool
}
// prepared is everything sync and status share: the pulled repository, the
// planned action list, and the local state — before any mutation.
type prepared struct {
paths StatePaths
pull *PullResult
manifest *Manifest
items []PlannedItem
plan []PlanEntry
labels *LabelSelection
}
// LabelSelection describes an active label filter for one run: the client
// labels, where they came from, which items were left out and which names
// in the labels file match no item. nil when the client carries no labels.
type LabelSelection struct {
Client []string `json:"client"`
Source string `json:"source"`
File bool `json:"labels_file"`
NotSelected []string `json:"not_selected,omitempty"`
Unknown []string `json:"unknown_names,omitempty"`
}
// prepare pulls, inventories, hashes and plans — the complete read-only
// front half of a client run.
func prepare(opts SyncOptions) (*prepared, error) {
if opts.RepoURL == "" && opts.Ref != "" {
return nil, fmt.Errorf("--ref requires --repo (it only overrides the repository to pull)")
}
cfg, err := resolveRunConfig(opts)
if err != nil {
return nil, err
}
paths, err := ResolveStatePaths()
if err != nil {
return nil, err
}
if err := os.MkdirAll(paths.Root, 0o755); err != nil {
return nil, err
}
pull, err := Pull(paths.CacheDir, cfg.RepoURL, cfg.Ref, cfg.Token, cfg.TokenUser)
if err != nil {
return nil, err
}
inv, err := BuildInventory(pull.Tree, pull.Rev)
if err != nil {
return nil, err
}
oc, err := target.NewOpenCode()
if err != nil {
return nil, err
}
manifest, err := LoadManifest(paths.Manifest)
if err != nil {
return nil, err
}
lf, err := readLabelsFile(pull.Tree)
if err != nil {
return nil, err
}
var sel *LabelSelection
if cfg.Labels != nil {
sel = &LabelSelection{Client: append([]string{}, (*cfg.Labels)...), Source: cfg.LabelSource, File: lf != nil}
if lf != nil {
sel.Unknown = unknownLabelNames(lf, inv)
}
}
items := make([]PlannedItem, 0, len(inv.Items))
deselected := map[string]bool{}
for _, it := range inv.Deployable() {
if _, ok := oc.DeployPath(it.Type, it.Name); !ok {
continue
}
if sel != nil && !lf.Selected(it.Name, sel.Client) {
deselected[manifestKey(it.Type, it.Name)] = true
sel.NotSelected = append(sel.NotSelected, it.Type+"/"+it.Name)
continue
}
hash, err := HashItem(pull.Tree, it)
if err != nil {
return nil, fmt.Errorf("hashing %s/%s: %w", it.Type, it.Name, err)
}
items = append(items, PlannedItem{Type: it.Type, Name: it.Name, Origin: it.Origin, RelPath: it.RelPath, Hash: hash})
}
pathFor := func(typ, name string) string {
path, _ := oc.DeployPath(typ, name)
return path
}
plan := Plan(items, manifest, diskFacts(oc, manifest, items), pathFor, PlanOptions{Force: opts.Force, Deselected: deselected})
for _, e := range plan {
if !safePath(e.DstPath) {
return nil, fmt.Errorf("refusing unsafe deploy path %q", e.DstPath)
}
}
return &prepared{paths: paths, pull: pull, manifest: manifest, items: items, plan: plan, labels: sel}, nil
}
// readLabelsFile loads the labels file from the pulled revision. A missing
// file restricts nothing (nil); a file that exists but does not validate
// aborts the run before any mutation — never fall back to "everything".
func readLabelsFile(tree *gitsource.GitTree) (*labels.File, error) {
data, err := tree.ReadFile(labels.FileName)
if err != nil {
if errors.Is(err, object.ErrFileNotFound) {
return nil, nil
}
return nil, fmt.Errorf("reading %s: %w", labels.FileName, err)
}
lf, err := labels.Parse(data)
if err != nil {
return nil, fmt.Errorf("work repository %w — sync aborted, nothing changed", err)
}
return lf, nil
}
// unknownLabelNames lists names in the labels file that match no inventory
// item of any type (MCP fragments included). Not fatal on the client: the
// curator-side validate is the hard gate.
func unknownLabelNames(lf *labels.File, inv *Inventory) []string {
known := map[string]bool{}
for _, it := range inv.Items {
known[it.Name] = true
}
var out []string
for _, n := range lf.Names() {
if !known[n] {
out = append(out, n)
}
}
return out
}
// resolveRunConfig applies the --repo inline override to the config chain:
// with --repo, any discovered config only contributes auth (and ref, unless
// --ref is also given); without --repo, a config with a repo_url is required.
func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
if opts.RepoURL == "" {
cfg, err := LoadClientConfig(opts.ConfigPath)
if err != nil {
return nil, err
}
cfg.FillTokenAuth()
if err := ApplyAdminLabels(cfg, DefaultConfigPath()); err != nil {
return nil, err
}
return cfg, nil
}
cfg, err := LoadOptionalConfig(opts.ConfigPath)
if err != nil {
return nil, err
}
if cfg == nil {
cfg = &ClientConfig{}
}
cfg.RepoURL = opts.RepoURL
if opts.Ref != "" {
cfg.Ref = opts.Ref
}
cfg.FillTokenAuth()
if err := ApplyAdminLabels(cfg, DefaultConfigPath()); err != nil {
return nil, err
}
return cfg, nil
}
// Sync pulls the work repository, plans the sync as a pure function over
// (inventory, manifest, disk facts) and executes the plan. Validation and
// hashing happen before the first mutation; unreachable repositories fail
// cleanly with the previous state intact.
func Sync(opts SyncOptions, stdout io.Writer) (*SyncReport, error) {
p, err := prepare(opts)
if err != nil {
return nil, err
}
printLabelSelection(stdout, p.labels)
return ExecutePlan(p.pull.Tree, p.plan, p.manifest, p.paths, p.pull.Rev, stdout)
}
// safePath rejects destinations that escape the user's home directory.
func safePath(dst string) bool {
home, err := os.UserHomeDir()
if err != nil {
return false
}
if dst == home {
return false
}
rel, err := filepath.Rel(home, dst)
if err != nil {
return false
}
return rel != ".." && rel != "." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
// printLabelSelection reports an active label filter in one line, plus a
// warning line per labels-file name that matches no item.
func printLabelSelection(w io.Writer, sel *LabelSelection) {
if sel == nil {
return
}
fmt.Fprintln(w, sel.Summary())
for _, n := range sel.Unknown {
fmt.Fprintf(w, "warning: %s names %q, which matches no item in the repository\n", labels.FileName, n)
}
}
// Summary renders the selection as one human-readable line.
func (s *LabelSelection) Summary() string {
client := strings.Join(s.Client, ", ")
if client == "" {
client = "(none — unlabeled items only)"
}
if !s.File {
return fmt.Sprintf("labels: %s (%s) — repository has no %s, nothing filtered", client, s.Source, labels.FileName)
}
return fmt.Sprintf("labels: %s (%s) — %d item(s) not selected", client, s.Source, len(s.NotSelected))
}