| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "sort" |
| 12 | "strings" |
| 13 | |
| 14 | "github.com/spf13/cobra" |
| 15 | |
| 16 | "the-valley/flow/internal/config" |
| 17 | "the-valley/flow/internal/git" |
| 18 | "the-valley/flow/internal/location" |
| 19 | "the-valley/flow/internal/project" |
| 20 | "the-valley/flow/internal/run" |
| 21 | "the-valley/flow/internal/selfupdate" |
| 22 | "the-valley/flow/internal/tmux" |
| 23 | ) |
| 24 | |
| 25 | var namingCmd = &cobra.Command{ |
| 26 | Use: "naming", |
| 27 | Short: "Which names flow gives new state, and where its state is", |
| 28 | } |
| 29 | |
| 30 | var namingStatusCmd = &cobra.Command{ |
| 31 | Use: "status", |
| 32 | Short: "Report the naming generation, where state is, and what blocks advancing", |
| 33 | Long: `Reports the host's naming_generation and what this build gives new state |
| 34 | under it; where each kind of state is, under the legacy names (~/.klaus) or |
| 35 | the flow names (~/.valley/flow), and any kind found in both; the live |
| 36 | sessions, with the build and generation that created each (legacy when a |
| 37 | session records none); for each registered project, whether its worktrees' |
| 38 | commit hooks are the current ones; self-update's current and previous |
| 39 | builds; and what blocks advancing to the next generation, each with its |
| 40 | reason. It changes nothing. |
| 41 | |
| 42 | It sees only this machine's flow state: other machines, and timers or |
| 43 | helpers that run outside flow, are for the operator to check.`, |
| 44 | Args: cobra.NoArgs, |
| 45 | RunE: func(cmd *cobra.Command, args []string) error { |
| 46 | cmd.SilenceUsage = true |
| 47 | l, err := location.Host() |
| 48 | if err != nil { |
| 49 | return err |
| 50 | } |
| 51 | // The host config's generation: Load refuses one that is none. |
| 52 | cfg, err := config.Load("") |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | l.Gen = cfg.Generation() |
| 57 | r := buildNamingReport(cmd.Context(), namingInputs{ |
| 58 | layout: l, |
| 59 | tmux: run.TmuxDepsFor(cmd.Context(), tmux.NewExecClient()), |
| 60 | }) |
| 61 | if asJSON, _ := cmd.Flags().GetBool("json"); asJSON { |
| 62 | enc := json.NewEncoder(cmd.OutOrStdout()) |
| 63 | enc.SetIndent("", " ") |
| 64 | return enc.Encode(r) |
| 65 | } |
| 66 | printNamingReport(cmd.OutOrStdout(), r, l.Home) |
| 67 | return nil |
| 68 | }, |
| 69 | } |
| 70 | |
| 71 | // namingSupportCmd is how a build says which generations it supports: the |
| 72 | // operator asks a rollback target with it, since naming status runs no |
| 73 | // program the self-update state names. |
| 74 | var namingSupportCmd = &cobra.Command{ |
| 75 | Use: "_naming-support", |
| 76 | Short: "Print the naming generations this build operates and allocates, as JSON", |
| 77 | Hidden: true, |
| 78 | Args: cobra.NoArgs, |
| 79 | RunE: func(cmd *cobra.Command, args []string) error { |
| 80 | return json.NewEncoder(cmd.OutOrStdout()).Encode(thisBuildSupport()) |
| 81 | }, |
| 82 | } |
| 83 | |
| 84 | func init() { |
| 85 | namingStatusCmd.Flags().Bool("json", false, "Print the report as JSON") |
| 86 | namingCmd.AddCommand(namingStatusCmd) |
| 87 | rootCmd.AddCommand(namingCmd) |
| 88 | rootCmd.AddCommand(namingSupportCmd) |
| 89 | } |
| 90 | |
| 91 | // namingSupport is which generations a build operates (finds, reads and |
| 92 | // writes state of) and, for each it can be set to, which generation's |
| 93 | // names it gives new state. |
| 94 | type namingSupport struct { |
| 95 | Operates []location.Generation `json:"operates"` |
| 96 | Allocates map[location.Generation]location.Generation `json:"allocates"` |
| 97 | } |
| 98 | |
| 99 | func thisBuildSupport() namingSupport { |
| 100 | s := namingSupport{Operates: location.Operates(), Allocates: map[location.Generation]location.Generation{}} |
| 101 | for _, g := range location.Generations { |
| 102 | s.Allocates[g] = location.Allocates(g) |
| 103 | } |
| 104 | return s |
| 105 | } |
| 106 | |
| 107 | type namingInputs struct { |
| 108 | layout location.Layout |
| 109 | tmux run.TmuxDeps |
| 110 | } |
| 111 | |
| 112 | type namingReport struct { |
| 113 | Generation location.Generation `json:"generation"` |
| 114 | Allocates location.Generation `json:"allocates"` // the names this build gives new state under Generation |
| 115 | Operates []location.Generation `json:"operates"` |
| 116 | Places []namingPlace `json:"places"` |
| 117 | Sessions []namingSession `json:"live_sessions"` |
| 118 | Projects []namingProject `json:"projects"` |
| 119 | SelfUpdate namingSelfUpdate `json:"self_update"` |
| 120 | Next location.Generation `json:"next,omitempty"` |
| 121 | Blockers []namingBlocker `json:"blockers"` |
| 122 | Unseen string `json:"unseen"` |
| 123 | } |
| 124 | |
| 125 | // namingPlace is where one kind of state is. |
| 126 | type namingPlace struct { |
| 127 | Kind string `json:"kind"` |
| 128 | Paths []string `json:"paths,omitempty"` // where it is, or where it goes |
| 129 | Exists bool `json:"exists"` |
| 130 | Error string `json:"error,omitempty"` |
| 131 | } |
| 132 | |
| 133 | type namingSession struct { |
| 134 | ID string `json:"id"` |
| 135 | Dir string `json:"dir"` |
| 136 | CreatedBy string `json:"created_by,omitempty"` // empty: a build that recorded none |
| 137 | Generation string `json:"generation"` |
| 138 | Error string `json:"error,omitempty"` // its runs could not be read, so it may be live |
| 139 | } |
| 140 | |
| 141 | type namingProject struct { |
| 142 | Name string `json:"name"` |
| 143 | Path string `json:"path"` |
| 144 | Declarations []string `json:"declarations,omitempty"` |
| 145 | Hooks []git.WorktreeHooks `json:"hooks"` |
| 146 | Error string `json:"error,omitempty"` |
| 147 | } |
| 148 | |
| 149 | type namingSelfUpdate struct { |
| 150 | State string `json:"state,omitempty"` |
| 151 | Current *selfupdate.Install `json:"current,omitempty"` |
| 152 | Previous *selfupdate.Install `json:"previous,omitempty"` |
| 153 | Error string `json:"error,omitempty"` |
| 154 | } |
| 155 | |
| 156 | type namingBlocker struct { |
| 157 | What string `json:"what"` |
| 158 | Reason string `json:"reason"` |
| 159 | } |
| 160 | |
| 161 | const namingUnseen = "Not seen from here: other machines, and timers or helpers outside flow." |
| 162 | |
| 163 | func buildNamingReport(ctx context.Context, in namingInputs) namingReport { |
| 164 | l := in.layout |
| 165 | gen, _ := l.Generation() |
| 166 | r := namingReport{ |
| 167 | Generation: gen, |
| 168 | Allocates: location.Allocates(gen), |
| 169 | Operates: location.Operates(), |
| 170 | Next: gen.Next(), |
| 171 | Sessions: []namingSession{}, |
| 172 | Projects: []namingProject{}, |
| 173 | Blockers: []namingBlocker{}, |
| 174 | Unseen: namingUnseen, |
| 175 | } |
| 176 | |
| 177 | place := func(kind string, resolve func() (string, error)) { |
| 178 | p := namingPlace{Kind: kind} |
| 179 | path, err := resolve() |
| 180 | var conflict *location.ConflictError |
| 181 | switch { |
| 182 | case errors.As(err, &conflict): |
| 183 | p.Paths, p.Exists, p.Error = conflict.Paths, true, err.Error() |
| 184 | case err != nil: |
| 185 | p.Error = err.Error() |
| 186 | default: |
| 187 | _, statErr := os.Lstat(path) |
| 188 | p.Paths, p.Exists = []string{path}, statErr == nil |
| 189 | } |
| 190 | r.Places = append(r.Places, p) |
| 191 | } |
| 192 | place("host config", l.HostConfig) |
| 193 | place("project registry", l.Registry) |
| 194 | place("shared memory", l.Memory) |
| 195 | place("self-update state", l.SelfUpdateState) |
| 196 | |
| 197 | sessions, sessErr := l.Sessions() |
| 198 | sp := namingPlace{Kind: "sessions"} |
| 199 | for _, root := range l.SessionRoots() { |
| 200 | if _, err := os.Stat(root); err == nil { |
| 201 | sp.Paths, sp.Exists = append(sp.Paths, root), true |
| 202 | } |
| 203 | } |
| 204 | if sessErr != nil { |
| 205 | sp.Error = sessErr.Error() |
| 206 | } |
| 207 | if len(sp.Paths) == 0 { |
| 208 | if root, err := l.NewSessionsRoot(); err == nil { |
| 209 | sp.Paths = []string{root} |
| 210 | } |
| 211 | } |
| 212 | r.Places = append(r.Places, sp) |
| 213 | |
| 214 | if logs := l.SyncLogs(); len(logs) > 0 { |
| 215 | r.Places = append(r.Places, namingPlace{Kind: "sync log", Paths: logs, Exists: true}) |
| 216 | } else { |
| 217 | place("sync log", l.SyncLog) |
| 218 | } |
| 219 | place("consult snapshots", l.ConsultSnapshots) |
| 220 | locks := namingPlace{Kind: "global review locks", Paths: l.ReviewLockDirs()} |
| 221 | for _, d := range locks.Paths { |
| 222 | if _, err := os.Stat(d); err == nil { |
| 223 | locks.Exists = true |
| 224 | } |
| 225 | } |
| 226 | r.Places = append(r.Places, locks) |
| 227 | |
| 228 | for _, s := range sessions { |
| 229 | live, err := sessionLive(s.Dir, in.tmux) |
| 230 | if err != nil { |
| 231 | // A session whose runs can't be read may be live: say so. |
| 232 | r.Sessions = append(r.Sessions, namingSession{ID: s.ID, Dir: s.Dir, Generation: string(location.Legacy), Error: err.Error()}) |
| 233 | continue |
| 234 | } |
| 235 | if !live { |
| 236 | continue |
| 237 | } |
| 238 | ns := namingSession{ID: s.ID, Dir: s.Dir, Generation: string(location.Legacy)} |
| 239 | if st, err := run.NewHomeDirStoreFromPath(s.Dir).Load(s.ID); err == nil { |
| 240 | ns.CreatedBy = st.CreatedBy |
| 241 | if st.NamingGeneration != "" { |
| 242 | ns.Generation = st.NamingGeneration |
| 243 | } |
| 244 | } |
| 245 | r.Sessions = append(r.Sessions, ns) |
| 246 | } |
| 247 | |
| 248 | if regPath, err := l.Registry(); err == nil { |
| 249 | reg, err := project.LoadFrom(regPath) |
| 250 | if err != nil { |
| 251 | for i := range r.Places { |
| 252 | if r.Places[i].Kind == "project registry" { |
| 253 | r.Places[i].Error = err.Error() |
| 254 | } |
| 255 | } |
| 256 | } else { |
| 257 | names := make([]string, 0, len(reg.Projects)) |
| 258 | paths := reg.List() // ~ expanded |
| 259 | for name := range paths { |
| 260 | names = append(names, name) |
| 261 | } |
| 262 | sort.Strings(names) |
| 263 | for _, name := range names { |
| 264 | r.Projects = append(r.Projects, namingProjectOf(ctx, name, paths[name])) |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | r.SelfUpdate = namingSelfUpdateOf(l) |
| 270 | if r.Next != "" { |
| 271 | r.Blockers = namingBlockers(r) |
| 272 | } |
| 273 | return r |
| 274 | } |
| 275 | |
| 276 | // sessionLive reports whether a session's coordinator, or any of its runs' |
| 277 | // agents, is still running in tmux. |
| 278 | func sessionLive(dir string, td run.TmuxDeps) (bool, error) { |
| 279 | states, unparsed, unreadable, err := run.NewHomeDirStoreFromPath(dir).Audit() |
| 280 | if err != nil { |
| 281 | return false, err |
| 282 | } |
| 283 | if len(unparsed) > 0 { |
| 284 | return false, fmt.Errorf("run records %s don't parse", strings.Join(unparsed, ", ")) |
| 285 | } |
| 286 | if len(unreadable) > 0 { |
| 287 | msgs := make([]string, len(unreadable)) |
| 288 | for i, e := range unreadable { |
| 289 | msgs[i] = e.Error() |
| 290 | } |
| 291 | return false, fmt.Errorf("run records can't be read: %s", strings.Join(msgs, "; ")) |
| 292 | } |
| 293 | for _, s := range states { |
| 294 | if s.Type == "session" { |
| 295 | for _, p := range []*string{s.CoordinatorPane, s.DashboardPane} { |
| 296 | if p != nil && td.PaneExists(*p) && !td.PaneIsIdle(*p) { |
| 297 | return true, nil |
| 298 | } |
| 299 | } |
| 300 | continue |
| 301 | } |
| 302 | if s.IsAgentRunningWith(td) { |
| 303 | return true, nil |
| 304 | } |
| 305 | } |
| 306 | return false, nil |
| 307 | } |
| 308 | |
| 309 | func namingProjectOf(ctx context.Context, name, path string) namingProject { |
| 310 | p := namingProject{Name: name, Path: path, Hooks: []git.WorktreeHooks{}} |
| 311 | for _, file := range location.ProjectFiles { |
| 312 | if f, err := location.ProjectFile(path, file); err == nil { |
| 313 | if _, err := os.Lstat(f); err == nil { |
| 314 | p.Declarations = append(p.Declarations, f) |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | hooks, err := git.InstalledHooks(ctx, path) |
| 319 | if err != nil { |
| 320 | p.Error = err.Error() |
| 321 | return p |
| 322 | } |
| 323 | p.Hooks = hooks |
| 324 | return p |
| 325 | } |
| 326 | |
| 327 | func namingSelfUpdateOf(l location.Layout) namingSelfUpdate { |
| 328 | var su namingSelfUpdate |
| 329 | path, err := l.SelfUpdateState() |
| 330 | if err != nil { |
| 331 | su.Error = err.Error() |
| 332 | return su |
| 333 | } |
| 334 | su.State = path |
| 335 | st, err := selfupdate.LoadFile(path) |
| 336 | if err != nil { |
| 337 | su.Error = err.Error() |
| 338 | return su |
| 339 | } |
| 340 | su.Current, su.Previous = st.Current, st.Previous |
| 341 | return su |
| 342 | } |
| 343 | |
| 344 | // namingBlockers is what keeps the host from advancing to r.Next, each with |
| 345 | // its reason. |
| 346 | func namingBlockers(r namingReport) []namingBlocker { |
| 347 | next := r.Next |
| 348 | b := []namingBlocker{} |
| 349 | if location.Allocates(next) != next { |
| 350 | b = append(b, namingBlocker{ |
| 351 | What: "this build", |
| 352 | Reason: fmt.Sprintf("it gives new state %s names under every setting", location.Allocates(next)), |
| 353 | }) |
| 354 | } |
| 355 | for _, p := range r.Places { |
| 356 | if p.Error != "" { |
| 357 | b = append(b, namingBlocker{What: p.Kind, Reason: p.Error}) |
| 358 | } |
| 359 | } |
| 360 | for _, s := range r.Sessions { |
| 361 | if s.Error != "" { |
| 362 | b = append(b, namingBlocker{What: "session " + s.ID, Reason: "its runs could not be read, so it may be live: " + s.Error}) |
| 363 | continue |
| 364 | } |
| 365 | if s.CreatedBy == "" { |
| 366 | b = append(b, namingBlocker{ |
| 367 | What: "session " + s.ID, |
| 368 | Reason: "it was created by a build that records no naming generation; let it finish", |
| 369 | }) |
| 370 | } |
| 371 | } |
| 372 | for _, p := range r.Projects { |
| 373 | var stale int |
| 374 | for _, h := range p.Hooks { |
| 375 | if !h.Current { |
| 376 | stale++ |
| 377 | } |
| 378 | } |
| 379 | if p.Error != "" { |
| 380 | b = append(b, namingBlocker{What: "project " + p.Name, Reason: "its commit hooks could not be read: " + p.Error}) |
| 381 | } else if stale > 0 { |
| 382 | b = append(b, namingBlocker{ |
| 383 | What: "project " + p.Name, |
| 384 | Reason: fmt.Sprintf("%d of its %d worktrees with flow's hooks have older ones; a run or session resume there installs the current ones", stale, len(p.Hooks)), |
| 385 | }) |
| 386 | } |
| 387 | } |
| 388 | if su := r.SelfUpdate; su.Error != "" && !placeFailed(r, "self-update state") { |
| 389 | b = append(b, namingBlocker{What: "self-update state", Reason: "the rollback target could not be read from it: " + su.Error}) |
| 390 | } |
| 391 | // The report runs no program the state file names, so what the |
| 392 | // rollback target supports is for the operator to ask it. |
| 393 | if prev := r.SelfUpdate.Previous; prev != nil { |
| 394 | b = append(b, namingBlocker{ |
| 395 | What: "self-update's previous build " + installLabel(prev), |
| 396 | Reason: fmt.Sprintf("it is the rollback target, and must operate %s state: %s _naming-support lists what it operates", |
| 397 | next, filepath.Join(prev.StorePath, "bin", "klaus")), |
| 398 | }) |
| 399 | } |
| 400 | return b |
| 401 | } |
| 402 | |
| 403 | // placeFailed reports whether r's place of kind already carries an error, |
| 404 | // which is a blocker of its own. |
| 405 | func placeFailed(r namingReport, kind string) bool { |
| 406 | for _, p := range r.Places { |
| 407 | if p.Kind == kind && p.Error != "" { |
| 408 | return true |
| 409 | } |
| 410 | } |
| 411 | return false |
| 412 | } |
| 413 | |
| 414 | func installLabel(i *selfupdate.Install) string { |
| 415 | if i.Commit != "" { |
| 416 | return shortSHA(i.Commit) |
| 417 | } |
| 418 | return i.StorePath |
| 419 | } |
| 420 | |
| 421 | func printNamingReport(w io.Writer, r namingReport, home string) { |
| 422 | tilde := func(p string) string { |
| 423 | if home != "" && (p == home || strings.HasPrefix(p, home+string(filepath.Separator))) { |
| 424 | return "~" + p[len(home):] |
| 425 | } |
| 426 | return p |
| 427 | } |
| 428 | tildes := func(ps []string) string { |
| 429 | out := make([]string, len(ps)) |
| 430 | for i, p := range ps { |
| 431 | out[i] = tilde(p) |
| 432 | } |
| 433 | return strings.Join(out, ", ") |
| 434 | } |
| 435 | |
| 436 | head := fmt.Sprintf("naming generation %s · new state gets %s names", r.Generation, r.Allocates) |
| 437 | switch { |
| 438 | case r.Next == "": |
| 439 | fmt.Fprintf(w, "✓ %s\n", head) |
| 440 | case len(r.Blockers) == 0: |
| 441 | fmt.Fprintf(w, "✓ %s · nothing here blocks %s\n", head, r.Next) |
| 442 | default: |
| 443 | fmt.Fprintf(w, "◇ %s · %d %s %s\n", head, len(r.Blockers), plural(len(r.Blockers), "blocks", "block"), r.Next) |
| 444 | } |
| 445 | |
| 446 | fmt.Fprintln(w, "\nWhere state is") |
| 447 | for _, p := range r.Places { |
| 448 | line := tildes(p.Paths) |
| 449 | if !p.Exists { |
| 450 | line += " (none yet)" |
| 451 | } |
| 452 | if p.Error != "" && len(p.Paths) == 0 { |
| 453 | line = p.Error |
| 454 | } |
| 455 | fmt.Fprintf(w, " %-20s %s\n", p.Kind, line) |
| 456 | if p.Error != "" && len(p.Paths) > 0 { |
| 457 | fmt.Fprintf(w, " %-20s ✗ %s\n", "", p.Error) |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | fmt.Fprintln(w, "\nLive sessions") |
| 462 | if len(r.Sessions) == 0 { |
| 463 | fmt.Fprintln(w, " none") |
| 464 | } |
| 465 | for _, s := range r.Sessions { |
| 466 | by := "a build that recorded none" |
| 467 | if s.CreatedBy != "" { |
| 468 | by = s.CreatedBy |
| 469 | } |
| 470 | if s.Error != "" { |
| 471 | fmt.Fprintf(w, " %s · ✗ %s\n", s.ID, s.Error) |
| 472 | continue |
| 473 | } |
| 474 | fmt.Fprintf(w, " %s · created by %s · %s names\n", s.ID, by, s.Generation) |
| 475 | } |
| 476 | |
| 477 | fmt.Fprintln(w, "\nCommit hooks") |
| 478 | if len(r.Projects) == 0 { |
| 479 | fmt.Fprintln(w, " no registered projects") |
| 480 | } |
| 481 | for _, p := range r.Projects { |
| 482 | var stale int |
| 483 | for _, h := range p.Hooks { |
| 484 | if !h.Current { |
| 485 | stale++ |
| 486 | } |
| 487 | } |
| 488 | switch { |
| 489 | case p.Error != "": |
| 490 | fmt.Fprintf(w, " %s · ✗ %s\n", p.Name, p.Error) |
| 491 | case len(p.Hooks) == 0: |
| 492 | fmt.Fprintf(w, " %s · no worktrees with flow's hooks\n", p.Name) |
| 493 | case stale == 0: |
| 494 | fmt.Fprintf(w, " %s · ✓ %d %s current\n", p.Name, len(p.Hooks), plural(len(p.Hooks), "worktree", "worktrees")) |
| 495 | default: |
| 496 | fmt.Fprintf(w, " %s · ◇ %d of %d worktrees older\n", p.Name, stale, len(p.Hooks)) |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | fmt.Fprintln(w, "\nSelf-update") |
| 501 | switch su := r.SelfUpdate; { |
| 502 | case su.Error != "": |
| 503 | fmt.Fprintf(w, " ✗ %s\n", su.Error) |
| 504 | case su.Current == nil && su.Previous == nil: |
| 505 | fmt.Fprintln(w, " nothing installed by self-update") |
| 506 | default: |
| 507 | for _, row := range []struct { |
| 508 | label string |
| 509 | i *selfupdate.Install |
| 510 | }{{"current", su.Current}, {"previous", su.Previous}} { |
| 511 | if row.i != nil { |
| 512 | fmt.Fprintf(w, " %-9s %s %s\n", row.label, installLabel(row.i), tilde(row.i.StorePath)) |
| 513 | } |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | if r.Next != "" { |
| 518 | fmt.Fprintf(w, "\nBlocks advancing to %s\n", r.Next) |
| 519 | if len(r.Blockers) == 0 { |
| 520 | fmt.Fprintln(w, " nothing found here") |
| 521 | } |
| 522 | for _, b := range r.Blockers { |
| 523 | fmt.Fprintf(w, " ◇ %s: %s\n", b.What, b.Reason) |
| 524 | } |
| 525 | } |
| 526 | fmt.Fprintf(w, "\n%s\n", r.Unseen) |
| 527 | } |
| 528 | |
| 529 | func plural(n int, one, many string) string { |
| 530 | if n == 1 { |
| 531 | return one |
| 532 | } |
| 533 | return many |
| 534 | } |