Debian Codegraph @

git/githistory/rewriter.go

raw symbols SCIP
1 package githistory
2
3 import (
4 "encoding/hex"
5 "fmt"
6 "os"
7 "path/filepath"
8 "strings"
9 "sync"
10
11 "github.com/git-lfs/git-lfs/v3/errors"
12 "github.com/git-lfs/git-lfs/v3/filepathfilter"
13 "github.com/git-lfs/git-lfs/v3/git"
14 "github.com/git-lfs/git-lfs/v3/tasklog"
15 "github.com/git-lfs/git-lfs/v3/tr"
16 "github.com/git-lfs/gitobj/v2"
17 )
18
19 // Rewriter allows rewriting topologically equivalent Git histories
20 // between two revisions.
21 type Rewriter struct {
22 // mu guards entries and commits (see below)
23 mu *sync.Mutex
24 // entries is a mapping of old tree entries to new (rewritten) ones.
25 // Since TreeEntry contains a []byte (and is therefore not a key-able
26 // type), a unique TreeEntry -> string function is used for map keys.
27 entries map[string]*gitobj.TreeEntry
28 // commits is a mapping of old commit SHAs to new ones, where the ASCII
29 // hex encoding of the SHA1 values are used as map keys.
30 commits map[string][]byte
31 // filter is an optional value used to specify which tree entries
32 // (blobs, subtrees) are modifiable given a BlobFn. If non-nil, this
33 // filter will cull out any unmodifiable subtrees and blobs.
34 filter *filepathfilter.Filter
35 // db is the *ObjectDatabase from which blobs, commits, and trees are
36 // loaded.
37 db *gitobj.ObjectDatabase
38 // logger is the *tasklog.Logger to which updates are written.
39 logger *tasklog.Logger
40 }
41
42 // RewriteOptions is an options type given to the Rewrite() function.
43 type RewriteOptions struct {
44 // Include is the list of refs of which commits reachable by that ref
45 // will be included.
46 Include []string
47 // Exclude is the list of refs of which commits reachable by that ref
48 // will be excluded.
49 Exclude []string
50
51 // UpdateRefs specifies whether the Rewriter should move refs from the
52 // original graph onto the migrated one. If true, the refs will be
53 // moved, and a reflog entry will be created.
54 UpdateRefs bool
55
56 // Verbose mode prints migrated objects.
57 Verbose bool
58
59 // ObjectMapFilePath is the path to the map of old sha1 to new sha1
60 // commits
61 ObjectMapFilePath string
62
63 // BlobFn specifies a function to rewrite blobs.
64 //
65 // It is called once per unique, unchanged path. That is to say, if
66 // /a/foo and /a/bar contain identical contents, the BlobFn will be
67 // called twice: once for /a/foo and once for /a/bar, but no more on
68 // each blob for subsequent revisions, so long as each entry remains
69 // unchanged.
70 BlobFn BlobRewriteFn
71 // TreePreCallbackFn specifies a function to be called before opening a
72 // tree for rewriting. It will be called on all trees throughout history
73 // in topological ordering through the tree, starting at the root.
74 TreePreCallbackFn TreePreCallbackFn
75 // TreeCallbackFn specifies a function to rewrite trees after they have
76 // been reassembled by calling the above BlobFn on all existing tree
77 // entries.
78 TreeCallbackFn TreeCallbackFn
79 }
80
81 // blobFn returns a usable BlobRewriteFn, either the one that was given in the
82 // *RewriteOptions, or a noopBlobFn.
83 func (r *RewriteOptions) blobFn() BlobRewriteFn {
84 if r.BlobFn == nil {
85 return noopBlobFn
86 }
87 return r.BlobFn
88 }
89
90 // treePreFn returns a usable TreePreCallbackFn, either the one that was given
91 // in the *RewriteOptions, or a noopTreePreFn.
92 func (r *RewriteOptions) treePreFn() TreePreCallbackFn {
93 if r.TreePreCallbackFn == nil {
94 return noopTreePreFn
95 }
96 return r.TreePreCallbackFn
97 }
98
99 // treeFn returns a usable TreeRewriteFn, either the one that was given in the
100 // *RewriteOptions, or a noopTreeFn.
101 func (r *RewriteOptions) treeFn() TreeCallbackFn {
102 if r.TreeCallbackFn == nil {
103 return noopTreeFn
104 }
105 return r.TreeCallbackFn
106 }
107
108 // BlobRewriteFn is a mapping function that takes a given blob and returns a
109 // new, modified blob. If it returns an error, the new blob will not be written
110 // and instead the error will be returned from the Rewrite() function.
111 //
112 // Invocations of an instance of BlobRewriteFn are not expected to store the
113 // returned blobs in the *git/gitobj.ObjectDatabase.
114 //
115 // The path argument is given to be an absolute path to the tree entry being
116 // rewritten, where the repository root is the root of the path given. For
117 // instance, a file "b.txt" in directory "dir" would be given as "/dir/b.txt",
118 // where as a file "a.txt" in the root would be given as "/a.txt".
119 //
120 // As above, the path separators are OS specific, and equivalent to the result
121 // of filepath.Join(...) or os.PathSeparator.
122 type BlobRewriteFn func(path string, b *gitobj.Blob) (*gitobj.Blob, error)
123
124 // TreePreCallbackFn specifies a function to call upon opening a new tree for
125 // rewriting.
126 //
127 // Unlike its sibling TreeCallbackFn, TreePreCallbackFn may not modify the given
128 // tree.
129 //
130 // TreePreCallbackFn can be nil, and will therefore exhibit behavior equivalent
131 // to only calling the BlobFn on existing tree entries.
132 //
133 // If the TreePreCallbackFn returns an error, it will be returned from the
134 // Rewrite() invocation.
135 type TreePreCallbackFn func(path string, t *gitobj.Tree) error
136
137 // TreeCallbackFn specifies a function to call before writing a re-written tree
138 // to the object database. The TreeCallbackFn can return a modified tree to be
139 // written to the object database instead of one generated from calling BlobFn
140 // on all of the tree entries.
141 //
142 // TreeCallbackFn can be nil, and will therefore exhibit behavior equivalent to
143 // only calling the BlobFn on existing tree entries.
144 //
145 // If the TreeCallbackFn returns an error, it will be returned from the
146 // Rewrite() invocation.
147 type TreeCallbackFn func(path string, t *gitobj.Tree) (*gitobj.Tree, error)
148
149 type rewriterOption func(*Rewriter)
150
151 var (
152 // WithFilter is an optional argument given to the NewRewriter
153 // constructor function to limit invocations of the BlobRewriteFn to
154 // only pathspecs that match the given *filepathfilter.Filter.
155 WithFilter = func(filter *filepathfilter.Filter) rewriterOption {
156 return func(r *Rewriter) {
157 r.filter = filter
158 }
159 }
160
161 // WithLogger logs updates caused by the *git/githistory.Rewriter to the
162 // be given to the provided logger, "l".
163 WithLogger = func(l *tasklog.Logger) rewriterOption {
164 return func(r *Rewriter) {
165 r.logger = l
166 }
167 }
168
169 // noopBlobFn is a no-op implementation of the BlobRewriteFn. It returns
170 // the blob that it was given, and returns no error.
171 noopBlobFn = func(path string, b *gitobj.Blob) (*gitobj.Blob, error) { return b, nil }
172 // noopTreePreFn is a no-op implementation of the TreePreRewriteFn. It
173 // returns the tree that it was given, and returns no error.
174 noopTreePreFn = func(path string, t *gitobj.Tree) error { return nil }
175 // noopTreeFn is a no-op implementation of the TreeRewriteFn. It returns
176 // the tree that it was given, and returns no error.
177 noopTreeFn = func(path string, t *gitobj.Tree) (*gitobj.Tree, error) { return t, nil }
178 )
179
180 // NewRewriter constructs a *Rewriter from the given *ObjectDatabase instance.
181 func NewRewriter(db *gitobj.ObjectDatabase, opts ...rewriterOption) *Rewriter {
182 rewriter := &Rewriter{
183 mu: new(sync.Mutex),
184 entries: make(map[string]*gitobj.TreeEntry),
185 commits: make(map[string][]byte),
186
187 db: db,
188 }
189
190 for _, opt := range opts {
191 opt(rewriter)
192 }
193 return rewriter
194 }
195
196 // Rewrite rewrites the range of commits given by
197 // *RewriteOptions.{Include,Exclude} using the BlobRewriteFn to rewrite
198 // the individual blobs.
199 func (r *Rewriter) Rewrite(opt *RewriteOptions) ([]byte, error) {
200 // First, obtain a list of commits to rewrite.
201 commits, err := r.commitsToMigrate(opt)
202 if err != nil {
203 return nil, err
204 }
205
206 var perc *tasklog.PercentageTask
207 if opt.UpdateRefs {
208 perc = r.logger.Percentage(tr.Tr.Get("Rewriting commits"), uint64(len(commits)))
209 } else {
210 perc = r.logger.Percentage(tr.Tr.Get("Examining commits"), uint64(len(commits)))
211 }
212 defer perc.Complete()
213
214 var vPerc *tasklog.PercentageTask
215 if opt.Verbose {
216 vPerc = perc
217 }
218
219 var objectMapFile *os.File
220 if len(opt.ObjectMapFilePath) > 0 {
221 objectMapFile, err = os.OpenFile(opt.ObjectMapFilePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
222 if err != nil {
223 return nil, errors.New(tr.Tr.Get("could not create object map file: %v", err))
224 }
225 defer objectMapFile.Close()
226 }
227
228 // Keep track of the last commit that we rewrote. Callers often want
229 // this so that they can perform a git-update-ref(1).
230 var tip []byte
231 for _, oid := range commits {
232 // Load the original commit to access the data necessary in
233 // order to rewrite it.
234 original, err := r.db.Commit(oid)
235 if err != nil {
236 return nil, err
237 }
238
239 // Rewrite the tree given at that commit.
240 rewrittenTree, err := r.rewriteTree(oid, original.TreeID, "", opt.blobFn(), opt.treePreFn(), opt.treeFn(), vPerc)
241 if err != nil {
242 return nil, err
243 }
244
245 // Create a new list of parents from the original commit to
246 // point at the rewritten parents in order to create a
247 // topologically equivalent DAG.
248 //
249 // This operation is safe since we are visiting the commits in
250 // reverse topological order and therefore have seen all parents
251 // before children (in other words, r.uncacheCommit(...) will
252 // always return a value, if the prospective parent is a part of
253 // the migration).
254 rewrittenParents := make([][]byte, 0, len(original.ParentIDs))
255 for _, originalParent := range original.ParentIDs {
256 rewrittenParent, ok := r.uncacheCommit(originalParent)
257 if !ok {
258 // If we haven't seen the parent before, this
259 // means that we're doing a partial migration
260 // and the parent that we're looking for isn't
261 // included.
262 //
263 // Use the original parent to properly link
264 // history across the migration boundary.
265 rewrittenParent = originalParent
266 }
267
268 rewrittenParents = append(rewrittenParents, rewrittenParent)
269 }
270
271 // Construct a new commit using the original header information,
272 // but the rewritten set of parents as well as root tree.
273 rewrittenCommit := &gitobj.Commit{
274 Author: original.Author,
275 Committer: original.Committer,
276 ExtraHeaders: original.ExtraHeaders,
277 Message: original.Message,
278
279 ParentIDs: rewrittenParents,
280 TreeID: rewrittenTree,
281 }
282
283 var newSha []byte
284
285 if original.Equal(rewrittenCommit) {
286 newSha = make([]byte, len(oid))
287 copy(newSha, oid)
288 } else {
289 newSha, err = r.db.WriteCommit(rewrittenCommit)
290 if err != nil {
291 return nil, err
292 }
293 if objectMapFile != nil {
294 if _, err := fmt.Fprintf(objectMapFile, "%x,%x\n", oid, newSha); err != nil {
295 return nil, err
296 }
297 }
298 }
299
300 // Cache that commit so that we can reassign children of this
301 // commit.
302 r.cacheCommit(oid, newSha)
303
304 // Increment the percentage displayed in the terminal.
305 perc.Count(1)
306
307 // Move the tip forward.
308 tip = newSha
309 }
310
311 if opt.UpdateRefs {
312 refs, err := r.refsToMigrate()
313 if err != nil {
314 return nil, errors.Wrap(err, tr.Tr.Get("could not find refs to update"))
315 }
316
317 root, _ := r.gitDirectory()
318
319 updater := &refUpdater{
320 cacheFn: r.uncacheCommit,
321 logger: r.logger,
322 refs: refs,
323 root: root,
324 db: r.db,
325 }
326
327 if err := updater.updateRefs(); err != nil {
328 return nil, errors.Wrap(err, tr.Tr.Get("could not update refs"))
329 }
330 }
331
332 return tip, err
333 }
334
335 // rewriteTree is a recursive function which rewrites a tree given by the ID
336 // "sha" and path "path". It uses the given BlobRewriteFn to rewrite all blobs
337 // within the tree, either calling that function or recurring down into subtrees
338 // by re-assigning the SHA.
339 //
340 // Once it is done assembling the entries in a given subtree, it then calls the
341 // TreeCallbackFn, "tfn" to perform a final traversal of the subtree before
342 // saving it to the object database.
343 //
344 // It returns the new SHA of the rewritten tree, or an error if the tree was
345 // unable to be rewritten.
346 func (r *Rewriter) rewriteTree(commitOID []byte, treeOID []byte, path string,
347 fn BlobRewriteFn, tpfn TreePreCallbackFn, tfn TreeCallbackFn,
348 perc *tasklog.PercentageTask) ([]byte, error) {
349
350 tree, err := r.db.Tree(treeOID)
351 if err != nil {
352 return nil, err
353 }
354
355 if err := tpfn("/"+path, tree); err != nil {
356 return nil, err
357 }
358
359 entries := make([]*gitobj.TreeEntry, 0, len(tree.Entries))
360 for _, entry := range tree.Entries {
361 var fullpath string
362 if len(path) > 0 {
363 fullpath = strings.Join([]string{path, entry.Name}, "/")
364 } else {
365 fullpath = entry.Name
366 }
367
368 if !r.allows(entry.Type(), fullpath) {
369 entries = append(entries, copyEntry(entry))
370 continue
371 }
372
373 // If this is a symlink, skip it
374 if entry.Filemode == 0120000 {
375 entries = append(entries, copyEntry(entry))
376 continue
377 }
378
379 if cached := r.uncacheEntry(fullpath, entry); cached != nil {
380 entries = append(entries, copyEntryMode(cached,
381 entry.Filemode))
382 continue
383 }
384
385 var oid []byte
386
387 switch entry.Type() {
388 case gitobj.BlobObjectType:
389 oid, err = r.rewriteBlob(commitOID, entry.Oid, fullpath, fn, perc)
390 case gitobj.TreeObjectType:
391 oid, err = r.rewriteTree(commitOID, entry.Oid, fullpath, fn, tpfn, tfn, perc)
392 default:
393 oid = entry.Oid
394
395 }
396 if err != nil {
397 return nil, err
398 }
399
400 entries = append(entries, r.cacheEntry(fullpath, entry, &gitobj.TreeEntry{
401 Filemode: entry.Filemode,
402 Name: entry.Name,
403 Oid: oid,
404 }))
405 }
406
407 rewritten, err := tfn("/"+path, &gitobj.Tree{Entries: entries})
408 if err != nil {
409 return nil, err
410 }
411
412 if tree.Equal(rewritten) {
413 return treeOID, nil
414 }
415 return r.db.WriteTree(rewritten)
416 }
417
418 func copyEntry(e *gitobj.TreeEntry) *gitobj.TreeEntry {
419 if e == nil {
420 return nil
421 }
422
423 oid := make([]byte, len(e.Oid))
424 copy(oid, e.Oid)
425
426 return &gitobj.TreeEntry{
427 Filemode: e.Filemode,
428 Name: e.Name,
429 Oid: oid,
430 }
431 }
432
433 func copyEntryMode(e *gitobj.TreeEntry, mode int32) *gitobj.TreeEntry {
434 copied := copyEntry(e)
435 copied.Filemode = mode
436
437 return copied
438 }
439
440 // gitDirectory returns a path to the .git directory on success.
441 func (r *Rewriter) gitDirectory() (string, bool) {
442 root, ok := r.db.Root()
443 if ok {
444 root = filepath.Join(root, "..")
445 }
446 return root, ok
447 }
448
449 func (r *Rewriter) allows(typ gitobj.ObjectType, abs string) bool {
450 switch typ {
451 case gitobj.BlobObjectType:
452 return r.Filter().Allows(strings.TrimPrefix(abs, "/"))
453 case gitobj.CommitObjectType, gitobj.TreeObjectType:
454 return true
455 default:
456 panic(fmt.Sprintf("git/githistory: %s", tr.Tr.Get("unknown entry type: %s", typ)))
457 }
458 }
459
460 // rewriteBlob calls the given BlobRewriteFn "fn" on a blob given in the object
461 // database by the SHA1 "from" []byte. It writes and returns the new blob SHA,
462 // or an error if either the BlobRewriteFn returned one, or if the object could
463 // not be loaded/saved.
464 func (r *Rewriter) rewriteBlob(commitOID, from []byte, path string, fn BlobRewriteFn, perc *tasklog.PercentageTask) ([]byte, error) {
465 blob, err := r.db.Blob(from)
466 if err != nil {
467 return nil, err
468 }
469
470 b, err := fn(path, blob)
471 if err != nil {
472 return nil, err
473 }
474
475 if !blob.Equal(b) {
476 sha, err := r.db.WriteBlob(b)
477 if err != nil {
478 return nil, err
479 }
480
481 // Close the source blob, so long as it is not equal to the
482 // rewritten blob. If the two are equal, as in the check above
483 // this comment, calling r.db.WriteBlob(b) will have already
484 // closed both "b" and "blob" since they are the same.
485 //
486 // Closing an *os.File twice causes an `os.ErrInvalid` to be
487 // returned.
488 if err = blob.Close(); err != nil {
489 return nil, err
490 }
491
492 if perc != nil {
493 perc.Entry(tr.Tr.Get(" commit %s: %s", hex.EncodeToString(commitOID), path))
494 }
495
496 return sha, nil
497 }
498
499 // Close the source blob, since it is identical to the rewritten blob,
500 // but neither were written.
501 if err := blob.Close(); err != nil {
502 return nil, err
503 }
504 return from, nil
505 }
506
507 // commitsToMigrate returns an in-memory copy of a list of commits according to
508 // the output of git-rev-list(1) (given the *RewriteOptions), where each
509 // outputted commit is 20 bytes of raw SHA1.
510 //
511 // If any error was encountered, it will be returned.
512 func (r *Rewriter) commitsToMigrate(opt *RewriteOptions) ([][]byte, error) {
513 waiter := r.logger.Waiter(tr.Tr.Get("Sorting commits"))
514 defer waiter.Complete()
515
516 scanner, err := git.NewRevListScanner(
517 opt.Include, opt.Exclude, r.scannerOpts())
518 if err != nil {
519 return nil, err
520 }
521
522 var commits [][]byte
523 for scanner.Scan() {
524 commits = append(commits, scanner.OID())
525 }
526
527 if err = scanner.Err(); err != nil {
528 return nil, err
529 }
530 if err = scanner.Close(); err != nil {
531 return nil, err
532 }
533 return commits, nil
534 }
535
536 // refsToMigrate returns a list of references to migrate, or an error if loading
537 // those references failed.
538 func (r *Rewriter) refsToMigrate() ([]*git.Ref, error) {
539 var refs []*git.Ref
540 var err error
541
542 if root, ok := r.gitDirectory(); ok {
543 refs, err = git.AllRefsIn(root)
544 } else {
545 refs, err = git.AllRefs()
546 }
547
548 if err != nil {
549 return nil, err
550 }
551
552 var local []*git.Ref
553 for _, ref := range refs {
554 if ref.Type == git.RefTypeRemoteBranch {
555 continue
556 }
557
558 local = append(local, ref)
559 }
560
561 return local, nil
562 }
563
564 // scannerOpts returns a *git.ScanRefsOptions instance to be given to the
565 // *git.RevListScanner.
566 //
567 // If the database this *Rewriter is operating in a given root (not in memory)
568 // it re-assigns the working directory to be there.
569 func (r *Rewriter) scannerOpts() *git.ScanRefsOptions {
570 opts := &git.ScanRefsOptions{
571 Mode: git.ScanRefsMode,
572 Order: git.TopoRevListOrder,
573 Reverse: true,
574 CommitsOnly: true,
575
576 SkippedRefs: make([]string, 0),
577 Mutex: new(sync.Mutex),
578 Names: make(map[string]string),
579 }
580
581 if root, ok := r.gitDirectory(); ok {
582 opts.WorkingDir = root
583 }
584 return opts
585 }
586
587 // Filter returns the filter used by this *Rewriter to filter subtrees, blobs
588 // (see above).
589 func (r *Rewriter) Filter() *filepathfilter.Filter {
590 return r.filter
591 }
592
593 // cacheEntry caches then given "from" entry so that it is always rewritten as
594 // a *TreeEntry equivalent to "to".
595 func (r *Rewriter) cacheEntry(path string, from, to *gitobj.TreeEntry) *gitobj.TreeEntry {
596 r.mu.Lock()
597 defer r.mu.Unlock()
598
599 r.entries[r.entryKey(path, from)] = to
600
601 return to
602 }
603
604 // uncacheEntry returns a *TreeEntry that is cached from the given *TreeEntry
605 // "from". That is to say, it returns the *TreeEntry that "from" should be
606 // rewritten to, or nil if none could be found.
607 func (r *Rewriter) uncacheEntry(path string, from *gitobj.TreeEntry) *gitobj.TreeEntry {
608 r.mu.Lock()
609 defer r.mu.Unlock()
610
611 return r.entries[r.entryKey(path, from)]
612 }
613
614 // entryKey returns a unique key for a given *TreeEntry "e".
615 func (r *Rewriter) entryKey(path string, e *gitobj.TreeEntry) string {
616 return fmt.Sprintf("%s:%x", path, e.Oid)
617 }
618
619 // cacheEntry caches then given "from" commit so that it is always rewritten as
620 // a *git/gitobj.Commit equivalent to "to".
621 func (r *Rewriter) cacheCommit(from, to []byte) {
622 r.mu.Lock()
623 defer r.mu.Unlock()
624
625 r.commits[hex.EncodeToString(from)] = to
626 }
627
628 // uncacheCommit returns a *git/gitobj.Commit that is cached from the given
629 // *git/gitobj.Commit "from". That is to say, it returns the *git/gitobj.Commit that
630 // "from" should be rewritten to and true, or nil and false if none could be
631 // found.
632 func (r *Rewriter) uncacheCommit(from []byte) ([]byte, bool) {
633 r.mu.Lock()
634 defer r.mu.Unlock()
635
636 c, ok := r.commits[hex.EncodeToString(from)]
637 return c, ok
638 }