Debian Codegraph @

plumbing/object/patch.go

raw
1 package object
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "strconv"
10 "strings"
11
12 "github.com/go-git/go-git/v5/plumbing"
13 "github.com/go-git/go-git/v5/plumbing/filemode"
14 fdiff "github.com/go-git/go-git/v5/plumbing/format/diff"
15 "github.com/go-git/go-git/v5/utils/diff"
16
17 dmp "github.com/sergi/go-diff/diffmatchpatch"
18 )
19
20 var (
21 ErrCanceled = errors.New("operation canceled")
22 )
23
24 func getPatch(message string, changes ...*Change) (*Patch, error) {
25 ctx := context.Background()
26 return getPatchContext(ctx, message, changes...)
27 }
28
29 func getPatchContext(ctx context.Context, message string, changes ...*Change) (*Patch, error) {
30 var filePatches []fdiff.FilePatch
31 for _, c := range changes {
32 select {
33 case <-ctx.Done():
34 return nil, ErrCanceled
35 default:
36 }
37
38 fp, err := filePatchWithContext(ctx, c)
39 if err != nil {
40 return nil, err
41 }
42
43 filePatches = append(filePatches, fp)
44 }
45
46 return &Patch{message, filePatches}, nil
47 }
48
49 func filePatchWithContext(ctx context.Context, c *Change) (fdiff.FilePatch, error) {
50 from, to, err := c.Files()
51 if err != nil {
52 return nil, err
53 }
54 fromContent, fIsBinary, err := fileContent(from)
55 if err != nil {
56 return nil, err
57 }
58
59 toContent, tIsBinary, err := fileContent(to)
60 if err != nil {
61 return nil, err
62 }
63
64 if fIsBinary || tIsBinary {
65 return &textFilePatch{from: c.From, to: c.To}, nil
66 }
67
68 diffs := diff.Do(fromContent, toContent)
69
70 var chunks []fdiff.Chunk
71 for _, d := range diffs {
72 select {
73 case <-ctx.Done():
74 return nil, ErrCanceled
75 default:
76 }
77
78 var op fdiff.Operation
79 switch d.Type {
80 case dmp.DiffEqual:
81 op = fdiff.Equal
82 case dmp.DiffDelete:
83 op = fdiff.Delete
84 case dmp.DiffInsert:
85 op = fdiff.Add
86 }
87
88 chunks = append(chunks, &textChunk{d.Text, op})
89 }
90
91 return &textFilePatch{
92 chunks: chunks,
93 from: c.From,
94 to: c.To,
95 }, nil
96
97 }
98
99 func fileContent(f *File) (content string, isBinary bool, err error) {
100 if f == nil {
101 return
102 }
103
104 isBinary, err = f.IsBinary()
105 if err != nil || isBinary {
106 return
107 }
108
109 content, err = f.Contents()
110
111 return
112 }
113
114 // Patch is an implementation of fdiff.Patch interface
115 type Patch struct {
116 message string
117 filePatches []fdiff.FilePatch
118 }
119
120 func (p *Patch) FilePatches() []fdiff.FilePatch {
121 return p.filePatches
122 }
123
124 func (p *Patch) Message() string {
125 return p.message
126 }
127
128 func (p *Patch) Encode(w io.Writer) error {
129 ue := fdiff.NewUnifiedEncoder(w, fdiff.DefaultContextLines)
130
131 return ue.Encode(p)
132 }
133
134 func (p *Patch) Stats() FileStats {
135 return getFileStatsFromFilePatches(p.FilePatches())
136 }
137
138 func (p *Patch) String() string {
139 buf := bytes.NewBuffer(nil)
140 err := p.Encode(buf)
141 if err != nil {
142 return fmt.Sprintf("malformed patch: %s", err.Error())
143 }
144
145 return buf.String()
146 }
147
148 // changeEntryWrapper is an implementation of fdiff.File interface
149 type changeEntryWrapper struct {
150 ce ChangeEntry
151 }
152
153 func (f *changeEntryWrapper) Hash() plumbing.Hash {
154 if !f.ce.TreeEntry.Mode.IsFile() {
155 return plumbing.ZeroHash
156 }
157
158 return f.ce.TreeEntry.Hash
159 }
160
161 func (f *changeEntryWrapper) Mode() filemode.FileMode {
162 return f.ce.TreeEntry.Mode
163 }
164 func (f *changeEntryWrapper) Path() string {
165 if !f.ce.TreeEntry.Mode.IsFile() {
166 return ""
167 }
168
169 return f.ce.Name
170 }
171
172 func (f *changeEntryWrapper) Empty() bool {
173 return !f.ce.TreeEntry.Mode.IsFile()
174 }
175
176 // textFilePatch is an implementation of fdiff.FilePatch interface
177 type textFilePatch struct {
178 chunks []fdiff.Chunk
179 from, to ChangeEntry
180 }
181
182 func (tf *textFilePatch) Files() (from fdiff.File, to fdiff.File) {
183 f := &changeEntryWrapper{tf.from}
184 t := &changeEntryWrapper{tf.to}
185
186 if !f.Empty() {
187 from = f
188 }
189
190 if !t.Empty() {
191 to = t
192 }
193
194 return
195 }
196
197 func (tf *textFilePatch) IsBinary() bool {
198 return len(tf.chunks) == 0
199 }
200
201 func (tf *textFilePatch) Chunks() []fdiff.Chunk {
202 return tf.chunks
203 }
204
205 // textChunk is an implementation of fdiff.Chunk interface
206 type textChunk struct {
207 content string
208 op fdiff.Operation
209 }
210
211 func (t *textChunk) Content() string {
212 return t.content
213 }
214
215 func (t *textChunk) Type() fdiff.Operation {
216 return t.op
217 }
218
219 // FileStat stores the status of changes in content of a file.
220 type FileStat struct {
221 Name string
222 Addition int
223 Deletion int
224 }
225
226 func (fs FileStat) String() string {
227 return printStat([]FileStat{fs})
228 }
229
230 // FileStats is a collection of FileStat.
231 type FileStats []FileStat
232
233 func (fileStats FileStats) String() string {
234 return printStat(fileStats)
235 }
236
237 // printStat prints the stats of changes in content of files.
238 // Original implementation: https://github.com/git/git/blob/1a87c842ece327d03d08096395969aca5e0a6996/diff.c#L2615
239 // Parts of the output:
240 // <pad><filename><pad>|<pad><changeNumber><pad><+++/---><newline>
241 // example: " main.go | 10 +++++++--- "
242 func printStat(fileStats []FileStat) string {
243 maxGraphWidth := uint(53)
244 maxNameLen := 0
245 maxChangeLen := 0
246
247 scaleLinear := func(it, width, max uint) uint {
248 if it == 0 || max == 0 {
249 return 0
250 }
251
252 return 1 + (it * (width - 1) / max)
253 }
254
255 for _, fs := range fileStats {
256 if len(fs.Name) > maxNameLen {
257 maxNameLen = len(fs.Name)
258 }
259
260 changes := strconv.Itoa(fs.Addition + fs.Deletion)
261 if len(changes) > maxChangeLen {
262 maxChangeLen = len(changes)
263 }
264 }
265
266 result := ""
267 for _, fs := range fileStats {
268 add := uint(fs.Addition)
269 del := uint(fs.Deletion)
270 np := maxNameLen - len(fs.Name)
271 cp := maxChangeLen - len(strconv.Itoa(fs.Addition+fs.Deletion))
272
273 total := add + del
274 if total > maxGraphWidth {
275 add = scaleLinear(add, maxGraphWidth, total)
276 del = scaleLinear(del, maxGraphWidth, total)
277 }
278
279 adds := strings.Repeat("+", int(add))
280 dels := strings.Repeat("-", int(del))
281 namePad := strings.Repeat(" ", np)
282 changePad := strings.Repeat(" ", cp)
283
284 result += fmt.Sprintf(" %s%s | %s%d %s%s\n", fs.Name, namePad, changePad, total, adds, dels)
285 }
286 return result
287 }
288
289 func getFileStatsFromFilePatches(filePatches []fdiff.FilePatch) FileStats {
290 var fileStats FileStats
291
292 for _, fp := range filePatches {
293 // ignore empty patches (binary files, submodule refs updates)
294 if len(fp.Chunks()) == 0 {
295 continue
296 }
297
298 cs := FileStat{}
299 from, to := fp.Files()
300 if from == nil {
301 // New File is created.
302 cs.Name = to.Path()
303 } else if to == nil {
304 // File is deleted.
305 cs.Name = from.Path()
306 } else if from.Path() != to.Path() {
307 // File is renamed.
308 cs.Name = fmt.Sprintf("%s => %s", from.Path(), to.Path())
309 } else {
310 cs.Name = from.Path()
311 }
312
313 for _, chunk := range fp.Chunks() {
314 s := chunk.Content()
315 if len(s) == 0 {
316 continue
317 }
318
319 switch chunk.Type() {
320 case fdiff.Add:
321 cs.Addition += strings.Count(s, "\n")
322 if s[len(s)-1] != '\n' {
323 cs.Addition++
324 }
325 case fdiff.Delete:
326 cs.Deletion += strings.Count(s, "\n")
327 if s[len(s)-1] != '\n' {
328 cs.Deletion++
329 }
330 }
331 }
332
333 fileStats = append(fileStats, cs)
334 }
335
336 return fileStats
337 }