forked from
tangled.org/core
Monorepo for Tangled
1package types
2
3import (
4 "net/url"
5
6 "github.com/bluekeyes/go-gitdiff/gitdiff"
7 "tangled.org/core/appview/filetree"
8)
9
10type DiffOpts struct {
11 Split bool `json:"split"`
12}
13
14func (d DiffOpts) Encode() string {
15 values := make(url.Values)
16 if d.Split {
17 values.Set("diff", "split")
18 } else {
19 values.Set("diff", "unified")
20 }
21 return values.Encode()
22}
23
24// A nicer git diff representation.
25type NiceDiff struct {
26 Commit Commit `json:"commit"`
27 Stat DiffStat `json:"stat"`
28 Diff []Diff `json:"diff"`
29}
30
31type Diff struct {
32 Name struct {
33 Old string `json:"old"`
34 New string `json:"new"`
35 } `json:"name"`
36 TextFragments []gitdiff.TextFragment `json:"text_fragments"`
37 IsBinary bool `json:"is_binary"`
38 IsNew bool `json:"is_new"`
39 IsDelete bool `json:"is_delete"`
40 IsCopy bool `json:"is_copy"`
41 IsRename bool `json:"is_rename"`
42}
43
44func (d Diff) Stats() DiffFileStat {
45 var stats DiffFileStat
46 for _, f := range d.TextFragments {
47 stats.Insertions += f.LinesAdded
48 stats.Deletions += f.LinesDeleted
49 }
50 return stats
51}
52
53type DiffStat struct {
54 Insertions int64 `json:"insertions"`
55 Deletions int64 `json:"deletions"`
56 FilesChanged int `json:"files_changed"`
57}
58
59type DiffFileStat struct {
60 Insertions int64
61 Deletions int64
62}
63
64type DiffTree struct {
65 Rev1 string `json:"rev1"`
66 Rev2 string `json:"rev2"`
67 Patch string `json:"patch"`
68 Diff []*gitdiff.File `json:"diff"`
69}
70
71type DiffFileName struct {
72 Old string
73 New string
74}
75
76func (d NiceDiff) ChangedFiles() []DiffFileRenderer {
77 drs := make([]DiffFileRenderer, len(d.Diff))
78 for i, s := range d.Diff {
79 drs[i] = s
80 }
81 return drs
82}
83
84func (d NiceDiff) FileTree() *filetree.FileTreeNode {
85 fs := make([]string, len(d.Diff))
86 for i, s := range d.Diff {
87 fs[i] = s.Id()
88 }
89 return filetree.FileTree(fs)
90}
91
92func (d NiceDiff) Stats() DiffStat {
93 return d.Stat
94}
95
96func (d Diff) Id() string {
97 if d.IsDelete {
98 return d.Name.Old
99 }
100 return d.Name.New
101}
102
103func (d Diff) Names() DiffFileName {
104 var n DiffFileName
105 if d.IsDelete {
106 n.Old = d.Name.Old
107 return n
108 } else if d.IsCopy || d.IsRename {
109 n.Old = d.Name.Old
110 n.New = d.Name.New
111 return n
112 } else {
113 n.New = d.Name.New
114 return n
115 }
116}
117
118func (d Diff) CanRender() string {
119 if d.IsBinary {
120 return "This is a binary file and will not be displayed."
121 }
122
123 return ""
124}
125
126func (d Diff) Split() SplitDiff {
127 fragments := make([]SplitFragment, len(d.TextFragments))
128 for i, fragment := range d.TextFragments {
129 leftLines, rightLines := SeparateLines(&fragment)
130 fragments[i] = SplitFragment{
131 Header: fragment.Header(),
132 LeftLines: leftLines,
133 RightLines: rightLines,
134 }
135 }
136
137 return SplitDiff{
138 Name: d.Id(),
139 TextFragments: fragments,
140 }
141}