Debian Codegraph @

lib/pama/models/view.go

raw
1 package models
2
3 import (
4 "bytes"
5 "io"
6 "strings"
7 "text/template"
8
9 "git.sr.ht/~rjarry/aerc/lib/log"
10 )
11
12 var templateText = `
13 Project {{.Name}} {{if .IsActive}}[active]{{end}} {{if .IsWorktree}}[Linked worktree to {{.WorktreeParent}}]{{end}}
14 Directory {{.Root}}
15 Base {{with .Base.ID}}{{if ge (len .) 40}}{{printf "%-6.6s" .}}{{else}}{{.}}{{end}}{{end}}
16 {{$notes := .Notes}}{{$commits := .Commits}}
17 {{- range $index, $patch := .Patches}}
18 {{$patch}}:
19 {{- range (index $commits $patch)}}
20 {{with (index $notes .ID)}}[{{.}}] {{end}}{{. -}}
21 {{end}}
22 {{end -}}
23 `
24
25 var viewRenderer = template.Must(template.New("ProjectToText").Parse(templateText))
26
27 type view struct {
28 Name string
29 Root string
30 Base Commit
31 // Patches are the unique tag names.
32 Patches []string
33 // Commits is a map where the tag names are keys and the associated
34 // commits the values.
35 Commits map[string][]Commit
36 // Notes contain annotations of the commits where the commit hash is
37 // the key and the annotation is the value.
38 Notes map[string]string
39 // IsActive is true if the current project is selected.
40 IsActive bool
41 IsWorktree bool
42 WorktreeParent string
43 }
44
45 func newView(p Project, active bool, notes map[string]string) view {
46 v := view{
47 Name: p.Name,
48 Root: p.Root,
49 Base: p.Base,
50 Commits: make(map[string][]Commit),
51 Notes: notes,
52 IsActive: active,
53 IsWorktree: p.Worktree.Root != "" && p.Worktree.Name != "",
54 WorktreeParent: p.Worktree.Name,
55 }
56
57 for _, commit := range p.Commits {
58 patch := commit.Tag
59 commits, ok := v.Commits[patch]
60 if !ok {
61 v.Patches = append(v.Patches, patch)
62 }
63 commits = append(commits, commit)
64 v.Commits[patch] = commits
65 }
66
67 return v
68 }
69
70 func (v view) String() string {
71 var buf bytes.Buffer
72 err := viewRenderer.Execute(&buf, v)
73 if err != nil {
74 log.Errorf("failed to run template: %v", err)
75 }
76 return buf.String()
77 }
78
79 func (p Project) String() string {
80 return newView(p, false, nil).String()
81 }
82
83 func (p Project) NewReader(isActive bool, notes map[string]string) io.Reader {
84 return strings.NewReader(newView(p, isActive, notes).String())
85 }