feat(client): deliver items only to clients with a matching label
- Add internal/labels: parse and validate the optional work-repo file
agent-lib.labels.json (version 1; unlabeled items go to every client;
names match across types)
- Add "labels" to the client config: absent = no filtering, [] = unlabeled
items only; labels from the admin default config are pinned and cannot be
overridden by user, env or flag configs; a broken admin config aborts
- Filter in prepare() before planning; deselected items follow the
upstream-deletion rules (unmodified removed, modified kept + warn,
--force removes) with reason "not selected for this client's labels"
- Abort sync before any change when the labels file does not validate;
names that match no item only warn on the client
- Report the active selection in sync output and status (--json: labels
object with client, source, labels_file, not_selected, unknown_names)
- validate checks the labels file, including that every name resolves to
an own, vendored or MCP item
- Document in README ("Client labels"), fleet handoff and the proposal;
revise the "client-side selection" non-goal
- Tests: labels parser, config precedence, planner deselection, e2e for
filter/remove/keep-modified/abort/unknown names, validate
Refs: agent_lib-fh4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
39952ceb02
commit
59735c3b24
16 files changed
+904
-38
No files matched your search
+78
-10
@@ -11,6 +11,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/m3tam3re/agent-lib/internal/gitsource"
|
||||
"github.com/m3tam3re/agent-lib/internal/labels"
|
||||
)
|
||||
|
||||
// ClientConfig is the client configuration for sync: fleet-provided or
|
||||
@@ -20,6 +21,14 @@ type ClientConfig struct {
|
||||
Ref string `json:"ref,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
TokenUser string `json:"token_user,omitempty"`
|
||||
// Labels restricts delivery to unlabeled items plus items carrying one
|
||||
// of these labels (see the labels package). nil = no filtering; an
|
||||
// empty list = only unlabeled items.
|
||||
Labels *[]string `json:"labels,omitempty"`
|
||||
|
||||
// LabelSource names where Labels came from: "admin", "user", "env",
|
||||
// "flag" or "" when no labels apply. Not part of the file format.
|
||||
LabelSource string `json:"-"`
|
||||
}
|
||||
|
||||
// ConfigEnv names the override environment variables.
|
||||
@@ -115,50 +124,102 @@ func (e *MissingConfigError) Error() string {
|
||||
// default — first existing file wins. Explicit flag/env paths that do not
|
||||
// exist are hard errors; a completely empty chain yields *MissingConfigError.
|
||||
func LoadClientConfig(flagPath string) (*ClientConfig, error) {
|
||||
path, ok, err := resolveConfigPath(flagPath)
|
||||
path, desc, ok, err := resolveConfigPath(flagPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, &MissingConfigError{Chain: ConfigSearchChain(flagPath)}
|
||||
}
|
||||
return readClientConfig(path)
|
||||
cfg, err := readClientConfig(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.LabelSource = labelSourceFor(cfg, desc)
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// LoadOptionalConfig behaves like LoadClientConfig but returns (nil, nil)
|
||||
// when no config exists anywhere — for runs that carry their own --repo.
|
||||
// Malformed existing configs are still hard errors.
|
||||
func LoadOptionalConfig(flagPath string) (*ClientConfig, error) {
|
||||
path, ok, err := resolveConfigPath(flagPath)
|
||||
path, desc, ok, err := resolveConfigPath(flagPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return readClientConfig(path)
|
||||
cfg, err := readClientConfig(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.LabelSource = labelSourceFor(cfg, desc)
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// resolveConfigPath walks the search chain and returns the config to read.
|
||||
// The flag and env legs must exist when set (explicit intent); the user and
|
||||
// admin legs are skipped when absent.
|
||||
func resolveConfigPath(flagPath string) (path string, found bool, err error) {
|
||||
func resolveConfigPath(flagPath string) (path, source string, found bool, err error) {
|
||||
if flagPath != "" {
|
||||
return flagPath, true, nil
|
||||
return flagPath, "flag", true, nil
|
||||
}
|
||||
if envPath := os.Getenv(ConfigEnv); envPath != "" {
|
||||
return envPath, true, nil
|
||||
return envPath, "env", true, nil
|
||||
}
|
||||
if p := UserConfigPath(); p != "" {
|
||||
if _, statErr := os.Stat(p); statErr == nil {
|
||||
return p, true, nil
|
||||
return p, "user", true, nil
|
||||
}
|
||||
}
|
||||
admin := DefaultConfigPath()
|
||||
if _, statErr := os.Stat(admin); statErr == nil {
|
||||
return admin, true, nil
|
||||
return admin, "admin", true, nil
|
||||
}
|
||||
return "", false, nil
|
||||
return "", "", false, nil
|
||||
}
|
||||
|
||||
func labelSourceFor(cfg *ClientConfig, source string) string {
|
||||
if cfg.Labels == nil {
|
||||
return ""
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
// ApplyAdminLabels enforces admin-pinned labels: when the admin default
|
||||
// config at adminPath exists and sets "labels", that value replaces
|
||||
// whatever the chosen config said — user-level, env and flag configs can
|
||||
// neither widen nor drop an admin selection. A missing admin file (or one
|
||||
// without "labels") leaves cfg untouched. An admin file that exists but
|
||||
// cannot be read or parsed is a hard error: the admin's intent is unknown,
|
||||
// so no selection may be guessed.
|
||||
func ApplyAdminLabels(cfg *ClientConfig, adminPath string) error {
|
||||
data, err := os.ReadFile(adminPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("reading admin config %s for labels: %w", adminPath, err)
|
||||
}
|
||||
var admin struct {
|
||||
Labels *[]string `json:"labels"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &admin); err != nil {
|
||||
return fmt.Errorf("admin config %s is not valid JSON: %w", adminPath, err)
|
||||
}
|
||||
if admin.Labels == nil {
|
||||
return nil
|
||||
}
|
||||
for _, l := range *admin.Labels {
|
||||
if !labels.ValidLabel(l) {
|
||||
return fmt.Errorf("admin config %s: label %q must be lowercase letters, digits and dashes", adminPath, l)
|
||||
}
|
||||
}
|
||||
pinned := append([]string{}, (*admin.Labels)...)
|
||||
cfg.Labels = &pinned
|
||||
cfg.LabelSource = "admin"
|
||||
return nil
|
||||
}
|
||||
|
||||
func readClientConfig(path string) (*ClientConfig, error) {
|
||||
@@ -173,6 +234,13 @@ func readClientConfig(path string) (*ClientConfig, error) {
|
||||
if cfg.RepoURL == "" {
|
||||
return nil, fmt.Errorf("client config %s: repo_url is required", path)
|
||||
}
|
||||
if cfg.Labels != nil {
|
||||
for _, l := range *cfg.Labels {
|
||||
if !labels.ValidLabel(l) {
|
||||
return nil, fmt.Errorf("client config %s: label %q must be lowercase letters, digits and dashes", path, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -163,3 +163,103 @@ func TestFillTokenAuthEnvOnlyFillsEmptyToken(t *testing.T) {
|
||||
t.Errorf("env must never override a config token: %+v", configured)
|
||||
}
|
||||
}
|
||||
|
||||
func writeRaw(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigLabelsAbsentEmptyAndSet(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cases := map[string]struct {
|
||||
body string
|
||||
want *[]string
|
||||
source string
|
||||
}{
|
||||
"absent": {`{"repo_url":"r"}`, nil, ""},
|
||||
"empty": {`{"repo_url":"r","labels":[]}`, &[]string{}, "flag"},
|
||||
"set": {`{"repo_url":"r","labels":["sales","lead"]}`, &[]string{"sales", "lead"}, "flag"},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
p := filepath.Join(dir, name+".json")
|
||||
writeRaw(t, p, tc.body)
|
||||
cfg, err := LoadClientConfig(p)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
if (cfg.Labels == nil) != (tc.want == nil) {
|
||||
t.Fatalf("%s: labels nil-ness mismatch: %v", name, cfg.Labels)
|
||||
}
|
||||
if tc.want != nil && strings.Join(*cfg.Labels, ",") != strings.Join(*tc.want, ",") {
|
||||
t.Errorf("%s: labels = %v", name, *cfg.Labels)
|
||||
}
|
||||
if cfg.LabelSource != tc.source {
|
||||
t.Errorf("%s: source = %q, want %q", name, cfg.LabelSource, tc.source)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigRejectsMalformedLabel(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "c.json")
|
||||
writeRaw(t, p, `{"repo_url":"r","labels":["Sales"]}`)
|
||||
if _, err := LoadClientConfig(p); err == nil {
|
||||
t.Fatal("an uppercase label must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminLabelsWinOverUserLabels(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
admin := filepath.Join(dir, "admin.json")
|
||||
writeRaw(t, admin, `{"repo_url":"r","labels":["finance"]}`)
|
||||
user := []string{"sales", "it"}
|
||||
cfg := &ClientConfig{RepoURL: "r", Labels: &user, LabelSource: "user"}
|
||||
if err := ApplyAdminLabels(cfg, admin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.LabelSource != "admin" || strings.Join(*cfg.Labels, ",") != "finance" {
|
||||
t.Fatalf("admin labels must replace user labels, got %v (%s)", *cfg.Labels, cfg.LabelSource)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminEmptyLabelsAlsoPin(t *testing.T) {
|
||||
admin := filepath.Join(t.TempDir(), "admin.json")
|
||||
writeRaw(t, admin, `{"repo_url":"r","labels":[]}`)
|
||||
user := []string{"sales"}
|
||||
cfg := &ClientConfig{Labels: &user, LabelSource: "user"}
|
||||
if err := ApplyAdminLabels(cfg, admin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Labels == nil || len(*cfg.Labels) != 0 {
|
||||
t.Fatalf("an admin [] must pin 'unlabeled only', got %v", cfg.Labels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminWithoutLabelsLeavesUserLabels(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
admin := filepath.Join(dir, "admin.json")
|
||||
writeRaw(t, admin, `{"repo_url":"r"}`)
|
||||
user := []string{"sales"}
|
||||
cfg := &ClientConfig{Labels: &user, LabelSource: "user"}
|
||||
if err := ApplyAdminLabels(cfg, admin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.LabelSource != "user" || strings.Join(*cfg.Labels, ",") != "sales" {
|
||||
t.Fatalf("without admin labels the user's labels apply, got %v (%s)", *cfg.Labels, cfg.LabelSource)
|
||||
}
|
||||
if err := ApplyAdminLabels(cfg, filepath.Join(dir, "missing.json")); err != nil {
|
||||
t.Fatalf("a missing admin config is not an error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminConfigBrokenIsFatal(t *testing.T) {
|
||||
admin := filepath.Join(t.TempDir(), "admin.json")
|
||||
writeRaw(t, admin, `{`)
|
||||
if err := ApplyAdminLabels(&ClientConfig{}, admin); err == nil {
|
||||
t.Fatal("an unreadable admin config must abort: its label intent is unknown")
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,16 @@ const (
|
||||
ActKeep Action = "keep"
|
||||
)
|
||||
|
||||
// ReasonNotSelected explains removals caused by the client's labels.
|
||||
const ReasonNotSelected = "not selected for this client's labels"
|
||||
|
||||
// PlanOptions tune planning. Force overwrites/removes locally modified
|
||||
// managed items; Deselected holds manifest keys filtered out by labels.
|
||||
type PlanOptions struct {
|
||||
Force bool
|
||||
Deselected map[string]bool
|
||||
}
|
||||
|
||||
// PlannedItem is one deployable inventory item with its repo-side hash.
|
||||
type PlannedItem struct {
|
||||
Type string
|
||||
@@ -51,7 +61,12 @@ type PlanEntry struct {
|
||||
// locally modified managed items are overwritten with the upstream version
|
||||
// (and removed after upstream deletion) instead of being skipped; items
|
||||
// agent-lib never managed are never touched, even with force.
|
||||
func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pathFor func(typ, name string) string, force bool) []PlanEntry {
|
||||
//
|
||||
// Deselected marks keys that exist upstream but are not selected for this
|
||||
// client's labels. Planning treats them exactly like upstream deletions —
|
||||
// only the reasons differ, so users learn why an item went away.
|
||||
func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pathFor func(typ, name string) string, opts PlanOptions) []PlanEntry {
|
||||
force := opts.Force
|
||||
invByKey := map[string]PlannedItem{}
|
||||
for _, it := range items {
|
||||
invByKey[manifestKey(it.Type, it.Name)] = it
|
||||
@@ -87,6 +102,10 @@ func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pat
|
||||
it, inInv := invByKey[key]
|
||||
rec := manifest.Items[key]
|
||||
fact := disk[key]
|
||||
gone := "upstream deleted"
|
||||
if opts.Deselected[key] {
|
||||
gone = ReasonNotSelected
|
||||
}
|
||||
|
||||
switch {
|
||||
case inInv && rec == nil:
|
||||
@@ -102,12 +121,12 @@ func Plan(items []PlannedItem, manifest *Manifest, disk map[string]DiskFact, pat
|
||||
case rec != nil && !fact.Exists:
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "already gone from disk; dropping manifest record")
|
||||
case rec != nil && fact.Hash == rec.Hash:
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "upstream deleted")
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, gone)
|
||||
case rec != nil && force:
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, "upstream deleted; forced removal of the locally modified copy")
|
||||
emit(ActRemove, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin}, gone+"; forced removal of the locally modified copy")
|
||||
case rec != nil:
|
||||
emit(ActSkip, PlannedItem{Type: rec.Type, Name: rec.Name, Origin: rec.Origin},
|
||||
"upstream deleted but the local copy was modified; keeping it")
|
||||
gone+" but the local copy was modified; keeping it")
|
||||
default:
|
||||
emit(ActLeave, PlannedItem{Type: typeOfKey(key), Name: nameOfKey(key)},
|
||||
"unmanaged local item; left untouched")
|
||||
|
||||
@@ -98,7 +98,7 @@ func TestPlanMatrix(t *testing.T) {
|
||||
diskFacts[key] = DiskFact{Exists: true, Hash: hashMod}
|
||||
}
|
||||
|
||||
plan := Plan(items, manifest, diskFacts, testPathFor, false)
|
||||
plan := Plan(items, manifest, diskFacts, testPathFor, PlanOptions{})
|
||||
if tc.disk == diskNone && tc.up == upAbsent {
|
||||
if len(plan) != 0 {
|
||||
t.Fatalf("a key present nowhere must produce no entry, got %+v", plan)
|
||||
@@ -151,7 +151,7 @@ func TestPlanForceMatrix(t *testing.T) {
|
||||
}
|
||||
disk := map[string]DiskFact{key: {Exists: true, Hash: hashMod}}
|
||||
|
||||
plan := Plan(items, manifest, disk, testPathFor, true)
|
||||
plan := Plan(items, manifest, disk, testPathFor, PlanOptions{Force: true})
|
||||
if len(plan) != 1 {
|
||||
t.Fatalf("want exactly 1 entry, got %d: %+v", len(plan), plan)
|
||||
}
|
||||
@@ -164,7 +164,7 @@ func TestPlanForceMatrix(t *testing.T) {
|
||||
t.Run("never-managed occupancy stays skipped", func(t *testing.T) {
|
||||
items := []PlannedItem{{Type: "skills", Name: "alpha", RelPath: "skills/alpha", Hash: hashV1}}
|
||||
disk := map[string]DiskFact{manifestKey("skills", "alpha"): {Exists: true, Hash: hashMod}}
|
||||
plan := Plan(items, NewManifest(), disk, testPathFor, true)
|
||||
plan := Plan(items, NewManifest(), disk, testPathFor, PlanOptions{Force: true})
|
||||
if len(plan) != 1 || plan[0].Action != ActSkip {
|
||||
t.Fatalf("force must not deploy over a never-managed item: %+v", plan)
|
||||
}
|
||||
@@ -199,7 +199,7 @@ func TestPlanMixedFixture(t *testing.T) {
|
||||
"agents/helper": {Exists: true, Hash: hashV1}, // unmodified × unchanged
|
||||
}
|
||||
|
||||
plan := Plan(items, manifest, disk, testPathFor, false)
|
||||
plan := Plan(items, manifest, disk, testPathFor, PlanOptions{})
|
||||
got := map[string]Action{}
|
||||
for _, e := range plan {
|
||||
got[e.Type+"/"+e.Name] = e.Action
|
||||
@@ -243,8 +243,8 @@ func TestPlanPureGuarantee(t *testing.T) {
|
||||
manifest := manifestWith(map[string]*ManifestItem{"skills/b": {Name: "b", Type: "skills", Hash: hashV1}})
|
||||
disk := map[string]DiskFact{"skills/b": {Exists: true, Hash: hashV1}}
|
||||
|
||||
p1 := Plan(items, manifest, disk, testPathFor, false)
|
||||
p2 := Plan(items, manifest, disk, testPathFor, false)
|
||||
p1 := Plan(items, manifest, disk, testPathFor, PlanOptions{})
|
||||
p2 := Plan(items, manifest, disk, testPathFor, PlanOptions{})
|
||||
if len(p1) != len(p2) {
|
||||
t.Fatal("same inputs must yield same plan length")
|
||||
}
|
||||
@@ -257,3 +257,31 @@ func TestPlanPureGuarantee(t *testing.T) {
|
||||
t.Error("planner must not mutate its inputs")
|
||||
}
|
||||
}
|
||||
|
||||
// Deselected items follow the upstream-deleted rules exactly; only the
|
||||
// reason tells the user that labels, not a deletion, caused the change.
|
||||
func TestPlanDeselectedFollowsDeletionRules(t *testing.T) {
|
||||
key := manifestKey("skills", "alpha")
|
||||
cases := []struct {
|
||||
name string
|
||||
disk DiskFact
|
||||
force bool
|
||||
action Action
|
||||
reason string
|
||||
}{
|
||||
{"clean copy removed", DiskFact{Exists: true, Hash: hashV1}, false, ActRemove, ReasonNotSelected},
|
||||
{"modified copy kept", DiskFact{Exists: true, Hash: hashMod}, false, ActSkip, ReasonNotSelected + " but the local copy was modified; keeping it"},
|
||||
{"modified copy forced", DiskFact{Exists: true, Hash: hashMod}, true, ActRemove, ReasonNotSelected + "; forced removal of the locally modified copy"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
manifest := NewManifest()
|
||||
manifest.Items[key] = &ManifestItem{Name: "alpha", Type: "skills", Hash: hashV1}
|
||||
plan := Plan(nil, manifest, map[string]DiskFact{key: tc.disk}, testPathFor,
|
||||
PlanOptions{Force: tc.force, Deselected: map[string]bool{key: true}})
|
||||
if len(plan) != 1 || plan[0].Action != tc.action || plan[0].Reason != tc.reason {
|
||||
t.Fatalf("got %+v, want %s %q", plan, tc.action, tc.reason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -15,14 +15,15 @@ type StatusEntry struct {
|
||||
|
||||
// StatusReport is the machine-readable local-state report.
|
||||
type StatusReport struct {
|
||||
Version string `json:"agent_lib_version"`
|
||||
DeployedRev string `json:"deployed_revision"`
|
||||
RepoRev string `json:"repository_revision"`
|
||||
InSync bool `json:"in_sync"`
|
||||
Drift bool `json:"problematic_drift"`
|
||||
Pending []StatusEntry `json:"pending_changes,omitempty"`
|
||||
Skipped []StatusEntry `json:"skipped_items,omitempty"`
|
||||
Unrecognized []StatusEntry `json:"unrecognized_items,omitempty"`
|
||||
Version string `json:"agent_lib_version"`
|
||||
DeployedRev string `json:"deployed_revision"`
|
||||
RepoRev string `json:"repository_revision"`
|
||||
InSync bool `json:"in_sync"`
|
||||
Drift bool `json:"problematic_drift"`
|
||||
Pending []StatusEntry `json:"pending_changes,omitempty"`
|
||||
Skipped []StatusEntry `json:"skipped_items,omitempty"`
|
||||
Unrecognized []StatusEntry `json:"unrecognized_items,omitempty"`
|
||||
Labels *LabelSelection `json:"labels,omitempty"`
|
||||
}
|
||||
|
||||
// Status reports the local state without mutating anything. Drift is true
|
||||
@@ -38,6 +39,7 @@ func Status(opts SyncOptions) (*StatusReport, error) {
|
||||
Version: version.Version,
|
||||
DeployedRev: p.manifest.Revision,
|
||||
RepoRev: p.pull.Rev,
|
||||
Labels: p.labels,
|
||||
}
|
||||
for _, e := range p.plan {
|
||||
item := e.Type + "/" + e.Name
|
||||
@@ -85,6 +87,12 @@ func PrintStatus(w io.Writer, r *StatusReport) bool {
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
}
|
||||
if r.Labels != nil {
|
||||
fmt.Fprintln(w, r.Labels.Summary())
|
||||
for _, n := range r.Labels.Unknown {
|
||||
fmt.Fprintf(w, " warning: labels file names %q, which matches no item\n", n)
|
||||
}
|
||||
}
|
||||
printSection("pending changes", r.Pending)
|
||||
printSection("skipped (local modifications)", r.Skipped)
|
||||
printSection("unrecognized local items", r.Unrecognized)
|
||||
|
||||
+103
-2
@@ -1,12 +1,17 @@
|
||||
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"
|
||||
)
|
||||
|
||||
@@ -29,6 +34,18 @@ type prepared struct {
|
||||
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
|
||||
@@ -66,11 +83,29 @@ func prepare(opts SyncOptions) (*prepared, error) {
|
||||
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)
|
||||
@@ -82,13 +117,48 @@ func prepare(opts SyncOptions) (*prepared, error) {
|
||||
path, _ := oc.DeployPath(typ, name)
|
||||
return path
|
||||
}
|
||||
plan := Plan(items, manifest, diskFacts(oc, manifest, items), pathFor, opts.Force)
|
||||
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}, nil
|
||||
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:
|
||||
@@ -101,6 +171,9 @@ func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
|
||||
return nil, err
|
||||
}
|
||||
cfg.FillTokenAuth()
|
||||
if err := ApplyAdminLabels(cfg, DefaultConfigPath()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
cfg, err := LoadOptionalConfig(opts.ConfigPath)
|
||||
@@ -115,6 +188,9 @@ func resolveRunConfig(opts SyncOptions) (*ClientConfig, error) {
|
||||
cfg.Ref = opts.Ref
|
||||
}
|
||||
cfg.FillTokenAuth()
|
||||
if err := ApplyAdminLabels(cfg, DefaultConfigPath()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -127,6 +203,7 @@ func Sync(opts SyncOptions, stdout io.Writer) (*SyncReport, error) {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -145,3 +222,27 @@ func safePath(dst string) bool {
|
||||
}
|
||||
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))
|
||||
}
|
||||
Reference in new issue
Block a user