store.go (9419B)
1 package store 2 3 import ( 4 "bytes" 5 "fmt" 6 "os" 7 "os/exec" 8 "path/filepath" 9 "slices" 10 "sort" 11 "strings" 12 "syscall" 13 "time" 14 ) 15 16 const DataDir = ".tracker" 17 18 type Store struct { 19 Root string 20 MS map[string]*Manuscript 21 dirty map[string]bool 22 files []string 23 } 24 25 // Now is replaceable in tests. 26 var Now = time.Now 27 28 func Today() string { return Now().Format("2006-01-02") } 29 30 // Load reads all manuscripts under root/.tracker without locking; writes 31 // are atomic renames, so a concurrent reader sees whole files. 32 func Load(root string) (*Store, error) { 33 s := &Store{Root: root, MS: map[string]*Manuscript{}, dirty: map[string]bool{}} 34 paths, err := filepath.Glob(filepath.Join(root, DataDir, "*.rec")) 35 if err != nil { 36 return nil, err 37 } 38 for _, p := range paths { 39 f, err := os.Open(p) 40 if err != nil { 41 return nil, err 42 } 43 recs, err := ParseRec(f) 44 f.Close() 45 if err != nil { 46 return nil, fmt.Errorf("%s: %v", p, err) 47 } 48 m, err := fromRecords(recs) 49 if err != nil { 50 return nil, fmt.Errorf("%s: %v", p, err) 51 } 52 s.MS[m.ID] = m 53 } 54 return s, nil 55 } 56 57 // Edit locks the tracker, loads it, runs fn, saves touched manuscripts and, 58 // if root is a git repository, commits the touched files with msg. 59 func Edit(root string, fn func(s *Store) (msg string, err error)) error { 60 if err := os.MkdirAll(filepath.Join(root, DataDir), 0o755); err != nil { 61 return err 62 } 63 lf, err := os.OpenFile(filepath.Join(root, DataDir, ".lock"), os.O_CREATE|os.O_RDWR, 0o644) 64 if err != nil { 65 return err 66 } 67 defer lf.Close() 68 if err := syscall.Flock(int(lf.Fd()), syscall.LOCK_EX); err != nil { 69 return err 70 } 71 defer syscall.Flock(int(lf.Fd()), syscall.LOCK_UN) 72 73 s, err := Load(root) 74 if err != nil { 75 return err 76 } 77 msg, err := fn(s) 78 if err != nil { 79 return err 80 } 81 for id := range s.dirty { 82 if err := s.save(s.MS[id]); err != nil { 83 return err 84 } 85 s.files = append(s.files, filepath.Join(DataDir, id+".rec")) 86 } 87 if msg == "" || len(s.files) == 0 { 88 return nil 89 } 90 return commit(root, msg, s.files) 91 } 92 93 // Touch marks a manuscript for saving. 94 func (s *Store) Touch(m *Manuscript) { s.dirty[m.ID] = true } 95 96 // TouchFile adds another file (relative to root) to the commit. 97 func (s *Store) TouchFile(rel string) { s.files = append(s.files, rel) } 98 99 func (s *Store) save(m *Manuscript) error { 100 p := filepath.Join(s.Root, DataDir, m.ID+".rec") 101 var buf bytes.Buffer 102 if err := WriteRec(&buf, m.records()); err != nil { 103 return err 104 } 105 tmp := p + ".tmp" 106 if err := os.WriteFile(tmp, buf.Bytes(), 0o644); err != nil { 107 return err 108 } 109 return os.Rename(tmp, p) 110 } 111 112 func commit(root, msg string, files []string) error { 113 if os.Getenv("MANUS_NOGIT") != "" { 114 return nil 115 } 116 if _, err := os.Stat(filepath.Join(root, ".git")); err != nil { 117 return nil 118 } 119 slices.Sort(files) 120 files = slices.Compact(files) 121 git := func(args ...string) error { 122 out, err := exec.Command("git", append([]string{"-C", root}, args...)...).CombinedOutput() 123 if err != nil { 124 return fmt.Errorf("git %s: %v: %s", args[0], err, bytes.TrimSpace(out)) 125 } 126 return nil 127 } 128 if err := git(append([]string{"add", "--"}, files...)...); err != nil { 129 return err 130 } 131 if exec.Command("git", append([]string{"-C", root, "diff", "--cached", "--quiet", "--"}, files...)...).Run() == nil { 132 return nil 133 } 134 return git(append([]string{"commit", "-q", "-m", "chore(tracker): " + msg, "--"}, files...)...) 135 } 136 137 func (s *Store) Get(id string) (*Manuscript, error) { 138 m, ok := s.MS[id] 139 if !ok { 140 return nil, fmt.Errorf("no manuscript %q", id) 141 } 142 return m, nil 143 } 144 145 func (s *Store) Task(r Ref) (*Manuscript, *Task, error) { 146 m, err := s.Get(r.MS) 147 if err != nil { 148 return nil, nil, err 149 } 150 t := m.Task(r.N) 151 if t == nil { 152 return nil, nil, fmt.Errorf("no task %s", r) 153 } 154 return m, t, nil 155 } 156 157 // IDs returns manuscript ids sorted by stage order, then id. 158 func (s *Store) IDs() []string { 159 ids := make([]string, 0, len(s.MS)) 160 for id := range s.MS { 161 ids = append(ids, id) 162 } 163 sort.Slice(ids, func(i, j int) bool { 164 a, b := slices.Index(Stages, s.MS[ids[i]].Get("stage")), slices.Index(Stages, s.MS[ids[j]].Get("stage")) 165 if a != b { 166 return a < b 167 } 168 return ids[i] < ids[j] 169 }) 170 return ids 171 } 172 173 // Path returns the absolute manuscript directory. 174 func (s *Store) Path(m *Manuscript) string { 175 d := m.Get("dir") 176 if d == "" { 177 d = m.ID 178 } 179 if filepath.IsAbs(d) { 180 return d 181 } 182 return filepath.Join(s.Root, d) 183 } 184 185 // SrcPath returns the absolute source directory. 186 func (s *Store) SrcPath(m *Manuscript) string { 187 return filepath.Join(s.Path(m), m.Get("src")) 188 } 189 190 // RepoPath returns the absolute git repository directory, or "". 191 func (s *Store) RepoPath(m *Manuscript) string { 192 if r := m.Get("repo"); r != "" { 193 return filepath.Join(s.Path(m), r) 194 } 195 return "" 196 } 197 198 // At returns the manuscript whose directory most specifically contains dir. 199 func (s *Store) At(dir string) *Manuscript { 200 var best *Manuscript 201 bestLen := -1 202 for _, m := range s.MS { 203 p := s.Path(m) 204 if (dir == p || strings.HasPrefix(dir, p+string(filepath.Separator))) && len(p) > bestLen { 205 best, bestLen = m, len(p) 206 } 207 } 208 return best 209 } 210 211 // Children returns revisions whose parent is id. 212 func (s *Store) Children(id string) []*Manuscript { 213 var c []*Manuscript 214 for _, cid := range s.IDs() { 215 if s.MS[cid].Get("parent") == id { 216 c = append(c, s.MS[cid]) 217 } 218 } 219 return c 220 } 221 222 // Lineage returns the revision chain ending at m, oldest first. 223 func (s *Store) Lineage(m *Manuscript) []*Manuscript { 224 chain := []*Manuscript{m} 225 seen := map[string]bool{m.ID: true} 226 for p := m.Get("parent"); p != "" && !seen[p]; { 227 pm, ok := s.MS[p] 228 if !ok { 229 break 230 } 231 seen[p] = true 232 chain = append([]*Manuscript{pm}, chain...) 233 p = pm.Get("parent") 234 } 235 return chain 236 } 237 238 // Inverse lists relations pointing at r, named from r's point of view. 239 func (s *Store) Inverse(r Ref) []Rel { 240 inv := map[string]string{"blocks": "blocked-by", "parent": "child", "relates": "relates", "duplicates": "duplicated-by"} 241 var out []Rel 242 for _, id := range s.IDs() { 243 for _, t := range s.MS[id].Tasks { 244 for _, rel := range t.Rels { 245 if rel.To == r { 246 out = append(out, Rel{inv[rel.Kind], Ref{id, t.ID}}) 247 } 248 } 249 } 250 } 251 return out 252 } 253 254 // Blockers returns unfinished tasks that block r. 255 func (s *Store) Blockers(r Ref) []Ref { 256 var out []Ref 257 for _, rel := range s.Inverse(r) { 258 if rel.Kind != "blocked-by" { 259 continue 260 } 261 if _, t, err := s.Task(rel.To); err == nil && t.Status != "done" { 262 out = append(out, rel.To) 263 } 264 } 265 return out 266 } 267 268 // EffectiveStatus is "blocked" when an unfinished task blocks an open one. 269 func (s *Store) EffectiveStatus(r Ref, t *Task) string { 270 if t.Status != "done" && len(s.Blockers(r)) > 0 { 271 return "blocked" 272 } 273 return t.Status 274 } 275 276 // SetStatus changes a task status and keeps the closed date consistent. 277 func SetStatus(t *Task, status string) error { 278 if err := ValidStatus(status); err != nil { 279 return err 280 } 281 t.Status = status 282 t.Closed = "" 283 if status == "done" { 284 t.Closed = Today() 285 } 286 return nil 287 } 288 289 // AddTask appends a new task to m and returns it. 290 func (s *Store) AddTask(m *Manuscript, title string) (*Task, error) { 291 title = strings.TrimSpace(title) 292 if title == "" || strings.Contains(title, "\n") { 293 return nil, fmt.Errorf("task title must be a single non-empty line") 294 } 295 t := &Task{ID: m.NextTaskID(), Title: title, Status: "todo", Created: Today()} 296 m.Tasks = append(m.Tasks, t) 297 s.Touch(m) 298 return t, nil 299 } 300 301 func (s *Store) Comment(m *Manuscript, t *Task, text string) error { 302 text = strings.TrimSpace(text) 303 if text == "" { 304 return fmt.Errorf("empty comment") 305 } 306 t.Comments = append(t.Comments, Comment{Now().Format("2006-01-02T15:04"), text}) 307 s.Touch(m) 308 return nil 309 } 310 311 // Relate adds (or with del removes) a relation from a to b. 312 func (s *Store) Relate(a Ref, kind string, b Ref, del bool) error { 313 kind, err := NormRelKind(kind) 314 if err != nil { 315 return err 316 } 317 ma, ta, err := s.Task(a) 318 if err != nil { 319 return err 320 } 321 if _, _, err := s.Task(b); err != nil { 322 return err 323 } 324 if a == b { 325 return fmt.Errorf("a task cannot relate to itself") 326 } 327 rel := Rel{kind, b} 328 i := slices.Index(ta.Rels, rel) 329 switch { 330 case del && i < 0: 331 return fmt.Errorf("%s has no relation %s %s", a, kind, b) 332 case del: 333 ta.Rels = slices.Delete(ta.Rels, i, i+1) 334 case i >= 0: 335 return nil 336 default: 337 if kind == "blocks" && s.reaches(b, a) { 338 return fmt.Errorf("%s blocks %s would create a cycle", a, b) 339 } 340 ta.Rels = append(ta.Rels, rel) 341 } 342 s.Touch(ma) 343 return nil 344 } 345 346 func (s *Store) reaches(from, to Ref) bool { 347 seen := map[Ref]bool{} 348 stack := []Ref{from} 349 for len(stack) > 0 { 350 r := stack[len(stack)-1] 351 stack = stack[:len(stack)-1] 352 if r == to { 353 return true 354 } 355 if seen[r] { 356 continue 357 } 358 seen[r] = true 359 if _, t, err := s.Task(r); err == nil { 360 for _, rel := range t.Rels { 361 if rel.Kind == "blocks" { 362 stack = append(stack, rel.To) 363 } 364 } 365 } 366 } 367 return false 368 } 369 370 // Create registers a new manuscript. 371 func (s *Store) Create(id string, fields map[string]string) (*Manuscript, error) { 372 if id == "" || strings.ContainsAny(id, "/# \t\n") || strings.HasPrefix(id, ".") { 373 return nil, fmt.Errorf("invalid manuscript id %q", id) 374 } 375 if _, ok := s.MS[id]; ok { 376 return nil, fmt.Errorf("manuscript %q already exists", id) 377 } 378 m := &Manuscript{ID: id, Fields: map[string]string{}} 379 for k, v := range fields { 380 if err := m.Set(k, v); err != nil { 381 return nil, err 382 } 383 } 384 s.MS[id] = m 385 s.Touch(m) 386 return m, nil 387 }