summaryrefslogtreecommitdiff
path: root/fi-prune-empty2/prune.go
blob: 517f9c5738450fa4290272759dcca95fd69e07af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright 2019-2021  Luke Shumaker <lukeshu@parabola.nu>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"fmt"

	"github.com/pkg/errors"
	"github.com/spf13/pflag"

	"git.lukeshu.com/go/libfastimport"
)

type PruneArg int

const (
	PruneNever PruneArg = iota
	PruneAuto
	PruneAlways
)

func (a *PruneArg) String() string {
	switch *a {
	case PruneNever:
		return "never"
	case PruneAuto:
		return "auto"
	case PruneAlways:
		return "always"
	default:
		panic("not reached")
	}
}

func (a *PruneArg) Set(str string) error {
	switch str {
	case "never":
		*a = PruneNever
	case "auto":
		*a = PruneAuto
	case "always":
		*a = PruneAlways
	default:
		return errors.Errorf("valid values are %q, got %q", []string{"never", "auto", "always"}, str)
	}
	return nil
}
func (a *PruneArg) Type() string {
	return "{never|auto|always}"
}

var _ pflag.Value = (*PruneArg)(nil)

type Pruner struct {
	pruneEmpty       PruneArg
	pruneFastForward PruneArg
	existingReplace  ExistingReplaceArg
	newReplace       NewReplaceArg

	srcRepo   *GitRepo
	dstStream *libfastimport.Backend

	replace map[Mark]Mark

	parents map[Mark]map[Mark]struct{}
	tree    map[Mark]Tree

	newhash2mark map[Hash]Mark
}

func NewPruner(
	pruneEmpty, pruneFastForward PruneArg,
	srcdir string, dst *libfastimport.Backend,
) *Pruner {
	return &Pruner{
		pruneEmpty:       pruneEmpty,
		pruneFastForward: pruneFastForward,

		srcRepo:   &GitRepo{Dir: srcdir},
		dstStream: dst,

		replace: make(map[Mark]Mark),

		parents: make(map[Mark]map[Mark]struct{}),
		tree:    make(map[Mark]Tree),

		newhash2mark: make(map[Hash]Mark),
	}
}

func (p *Pruner) debug(msg string) {
	p.dstStream.Do(libfastimport.CmdComment{
		Comment: " " + msg,
	})
}

func (p *Pruner) GotMark(mark Mark, hash Hash) bool {
	if omark, ok := p.newhash2mark[hash]; ok {
		p.replace[mark] = omark
		delete(p.tree, mark)
		return false
	}
	p.newhash2mark[hash] = mark
	return true
}

func (p *Pruner) FixCommitIsh(str string) string {
	mark, err := AsMark(str)
	if err != nil {
		return str
	}
	mark = p.FixMark(mark)
	if mark < 0 {
		return ""
	}
	return fmt.Sprintf(":%d", mark)
}

func (p *Pruner) FixMark(mark Mark) Mark {
	for {
		rmark, ok := p.replace[mark]
		if ok {
			mark = rmark
		} else {
			break
		}
	}
	return mark
}

func (p *Pruner) ProcessCommit(commit Commit) (*Commit, error) {
	shouldPrune, err := p.shouldPrune(commit)
	if err != nil {
		return nil, err
	}
	if shouldPrune {
		commit.Parents = p.pruneParents(commit.Parents)
		if len(commit.Parents) == 0 {
			p.replace[commit.Mark] = -1
		} else {
			p.replace[commit.Mark] = commit.Parents[0]
		}
		return nil, nil
	}

	p.parents[commit.Mark] = func() map[Mark]struct{} {
		parents := make(map[Mark]struct{}, len(commit.Parents))
		for _, parent := range commit.Parents {
			parents[parent] = struct{}{}
		}
		return parents
	}()
	p.tree[commit.Mark] = commit.Tree

	return &commit, nil
}

func (p *Pruner) wasEmpty(commit Commit) (bool, error) {
	commitHash := commit.OriginalOID
	// git rev-parse commit^@
	parents, err := p.srcRepo.Parents(commitHash)
	if err != nil {
		return false, err
	}
	if len(parents) != 1 {
		return false, nil
	}
	// git rev-parse commit^{tree}
	tree, err := p.srcRepo.Tree(commitHash)
	if err != nil {
		return false, err
	}
	// git rev-parse parent^{tree}
	parentTree, err := p.srcRepo.Tree(parents[0])
	if err != nil {
		return false, err
	}
	return (tree == parentTree), nil
}

func (p *Pruner) wasFastForward(commit Commit) (bool, error) {
	commitHash := commit.OriginalOID
	// git rev-parse commit^@
	parents, err := p.srcRepo.Parents(commitHash)
	if err != nil {
		return false, err
	}
	if len(parents) < 2 {
		return false, nil
	}
	// git merge-base --independent parents
	independentParentsBytes, err := p.srcRepo.Cmd(append([]string{"merge-base", "--independent"}, AsArgs(parents...)...)...).Output()
	if err != nil {
		return false, err
	}
	independentParents, err := LinesAsHashes(independentParentsBytes)
	if err != nil {
		return false, err
	}
	if len(independentParents) != 1 {
		return false, nil
	}
	// git rev-parse commit^{tree}
	tree, err := p.srcRepo.Tree(commitHash)
	if err != nil {
		return false, err
	}
	// git rev-parse parent^{tree}
	parentTree, err := p.srcRepo.Tree(independentParents[0])
	if err != nil {
		return false, err
	}
	return (tree == parentTree), nil
}

// isEmpty returns whether `git commit` would require `--allow-empty`
// in order to create that commit.
func (p *Pruner) isEmpty(commit Commit) (bool, error) {
	switch len(commit.Parents) {
	case 0:
		return len(commit.Tree) == 0, nil
	case 1:
		return TreesEqual(commit.Tree, p.tree[commit.Parents[0]]), nil
	default:
		return false, nil
	}
}

func (p *Pruner) isAncestor(ancestor, descendant Mark) bool {
	isDescendentMemo := make(map[Mark]bool)
	var isDescendent func(desc Mark) bool
	isDescendent = func(desc Mark) bool {
		if ret, ok := isDescendentMemo[desc]; ok {
			return ret
		}
		ret := false
		for descParent := range p.parents[desc] {
			if descParent == ancestor || isDescendent(descParent) {
				ret = true
				break
			}
		}
		isDescendentMemo[desc] = ret
		return ret
	}
	return isDescendent(descendant)
}

// pruneParents prunes "duplicate" parents of a commit.  It is
// equivalent to running `git merge-base --independent` in the
// destination repo (note: it isn't possible for us to run anything in
// the destination repo).
func (p *Pruner) pruneParents(arg []Mark) []Mark {
	var ret []Mark
outer:
	for _, candidateDescendant := range arg {
	inner:
		for _, other := range arg {
			if other == candidateDescendant {
				continue inner
			}
			// Make sure candidateDescendent isn't an ancestor of anything else.
			if p.isAncestor(candidateDescendant, other) {
				continue outer
			}
		}
		ret = append(ret, candidateDescendant)
	}
	return ret
}

func (p *Pruner) isFastForward(commit Commit) (bool, error) {
	if len(commit.Parents) < 2 {
		return false, nil
	}
	commit.Parents = p.pruneParents(commit.Parents)
	return p.isEmpty(commit)
}

func (p *Pruner) shouldPrune(commit Commit) (bool, error) {
	if commit.ExcludedParents {
		// If there are any excluded parents, then we can't
		// reason about it.  Keep the commit.
		return false, nil
	}
	switch p.pruneEmpty {
	case PruneAlways:
		isEmpty, err := p.isEmpty(commit)
		if err != nil {
			return false, err
		}
		if isEmpty {
			return true, nil
		}
	case PruneAuto:
		isEmpty, err := p.isEmpty(commit)
		if err != nil {
			return false, err
		}
		wasEmpty, err := p.wasEmpty(commit)
		if err != nil {
			return false, err
		}
		if isEmpty && !wasEmpty {
			return true, nil
		}
	}
	switch p.pruneFastForward {
	case PruneAlways:
		isFastForward, err := p.isFastForward(commit)
		if err != nil {
			return false, err
		}
		if isFastForward {
			return true, nil
		}
	case PruneAuto:
		isFastForward, err := p.isFastForward(commit)
		if err != nil {
			return false, err
		}
		wasFastForward, err := p.wasFastForward(commit)
		if err != nil {
			return false, err
		}
		if isFastForward && !wasFastForward {
			return true, nil
		}
	}
	return false, nil
}