Debian Codegraph @

commands/command_migrate_import.go

raw symbols SCIP
1 package commands
2
3 import (
4 "bufio"
5 "bytes"
6 "encoding/hex"
7 "fmt"
8 "os"
9 "path/filepath"
10 "strings"
11
12 "github.com/git-lfs/git-lfs/v3/errors"
13 "github.com/git-lfs/git-lfs/v3/filepathfilter"
14 "github.com/git-lfs/git-lfs/v3/git"
15 "github.com/git-lfs/git-lfs/v3/git/gitattr"
16 "github.com/git-lfs/git-lfs/v3/git/githistory"
17 "github.com/git-lfs/git-lfs/v3/lfs"
18 "github.com/git-lfs/git-lfs/v3/tasklog"
19 "github.com/git-lfs/git-lfs/v3/tools"
20 "github.com/git-lfs/git-lfs/v3/tools/humanize"
21 "github.com/git-lfs/git-lfs/v3/tr"
22 "github.com/git-lfs/gitobj/v2"
23 "github.com/spf13/cobra"
24 )
25
26 func migrateImportCommand(cmd *cobra.Command, args []string) {
27 ensureWorkingCopyClean(os.Stdin, os.Stderr)
28
29 l := tasklog.NewLogger(os.Stderr,
30 tasklog.ForceProgress(cfg.ForceProgress()),
31 )
32 defer l.Close()
33
34 db, err := getObjectDatabase()
35 if err != nil {
36 ExitWithError(err)
37 }
38 defer db.Close()
39
40 // To avoid confusion later, let's make sure that we've installed the
41 // necessary hooks so that a newly migrated repository is `git
42 // push`-able immediately following a `git lfs migrate import`.
43 installHooks(false)
44
45 if migrateNoRewrite {
46 if migrateFixup {
47 ExitWithError(errors.New(tr.Tr.Get("--no-rewrite and --fixup cannot be combined")))
48 }
49
50 if len(args) == 0 {
51 ExitWithError(errors.New(tr.Tr.Get("Expected one or more files with --no-rewrite")))
52 }
53
54 ref, err := git.CurrentRef()
55 if err != nil {
56 ExitWithError(errors.Wrap(err, tr.Tr.Get("Unable to find current reference")))
57 }
58
59 sha, _ := hex.DecodeString(ref.Sha)
60 commit, err := db.Commit(sha)
61 if err != nil {
62 ExitWithError(errors.Wrap(err, tr.Tr.Get("Unable to load commit")))
63 }
64
65 root := commit.TreeID
66
67 filter := gitattr.GetAttributeFilter(cfg.Git, cfg.LocalWorkingDir(), cfg.LocalGitDir())
68 if len(filter.Include()) == 0 {
69 ExitWithError(errors.New(tr.Tr.Get("No Git LFS filters found in '.gitattributes'")))
70 }
71
72 gf := lfs.NewGitFilter(cfg)
73
74 for _, file := range args {
75 if !filter.Allows(file) {
76 ExitWithError(errors.New(tr.Tr.Get("File %s did not match any Git LFS filters in '.gitattributes'", file)))
77 }
78 }
79
80 for _, file := range args {
81 root, err = rewriteTree(gf, db, root, file)
82 if err != nil {
83 ExitWithError(errors.Wrap(err, tr.Tr.Get("Could not rewrite %q", file)))
84 }
85 }
86
87 name, email := cfg.CurrentAuthor()
88 author := &gitobj.Signature{
89 Name: name,
90 Email: email,
91 When: cfg.CurrentAuthorTimestamp(),
92 }
93
94 name, email = cfg.CurrentCommitter()
95 committer := &gitobj.Signature{
96 Name: name,
97 Email: email,
98 When: cfg.CurrentCommitterTimestamp(),
99 }
100
101 oid, err := db.WriteCommit(&gitobj.Commit{
102 Author: author.String(),
103 Committer: committer.String(),
104 ParentIDs: [][]byte{sha},
105 Message: generateMigrateCommitMessage(cmd, strings.Join(args, ",")),
106 TreeID: root,
107 })
108
109 if err != nil {
110 ExitWithError(errors.Wrap(err, tr.Tr.Get("Unable to write commit")))
111 }
112
113 if err := git.UpdateRef(ref, oid, "git lfs migrate import --no-rewrite"); err != nil {
114 ExitWithError(errors.Wrap(err, tr.Tr.Get("Unable to update ref")))
115 }
116
117 if err := checkoutNonBare(l); err != nil {
118 ExitWithError(errors.Wrap(err, tr.Tr.Get("Could not checkout")))
119 }
120
121 return
122 }
123
124 if migrateFixup {
125 include, exclude := getIncludeExcludeArgs(cmd)
126 if include != nil || exclude != nil {
127 ExitWithError(errors.New(tr.Tr.Get("Cannot use --fixup with --include, --exclude")))
128 }
129 }
130
131 rewriter := getHistoryRewriter(cmd, db, l)
132
133 tracked := trackedFromFilter(rewriter.Filter())
134 exts := tools.NewOrderedSet()
135 gitfilter := lfs.NewGitFilter(cfg)
136
137 var fixups *gitattr.Tree
138 above, err := humanize.ParseBytes(migrateImportAboveFmt)
139 if err != nil {
140 ExitWithError(errors.Wrap(err, tr.Tr.Get("Cannot parse --above=<n>")))
141 }
142 if above > 0 {
143 include, exclude := getIncludeExcludeArgs(cmd)
144 if include != nil || exclude != nil || migrateFixup {
145 ExitWithError(errors.New(tr.Tr.Get("Cannot use --above with --include, --exclude, --fixup")))
146 }
147 }
148
149 migrate(args, rewriter, l, &githistory.RewriteOptions{
150 Verbose: migrateVerbose,
151 ObjectMapFilePath: objectMapFilePath,
152 BlobFn: func(path string, b *gitobj.Blob) (*gitobj.Blob, error) {
153 if filepath.Base(path) == ".gitattributes" {
154 return b, nil
155 }
156 if (above > 0) && (uint64(b.Size) < above) {
157 return b, nil
158 }
159
160 if migrateFixup {
161 var ok bool
162 attrs := fixups.Applied(path)
163 for _, attr := range attrs {
164 if attr.K == "filter" {
165 ok = attr.V == "lfs"
166 }
167 }
168
169 if !ok {
170 return b, nil
171 }
172 }
173
174 var buf bytes.Buffer
175
176 if _, err := clean(gitfilter, &buf, b.Contents, path, b.Size); err != nil {
177 return nil, err
178 }
179
180 if ext := filepath.Ext(path); len(ext) > 0 && above == 0 {
181 exts.Add(fmt.Sprintf("*%s filter=lfs diff=lfs merge=lfs -text", ext))
182 } else {
183 exts.Add(fmt.Sprintf("/%s filter=lfs diff=lfs merge=lfs -text", escapeGlobCharacters(path)))
184 }
185
186 return &gitobj.Blob{
187 Contents: &buf, Size: int64(buf.Len()),
188 }, nil
189 },
190
191 TreePreCallbackFn: func(path string, t *gitobj.Tree) error {
192 if migrateFixup && path == "/" {
193 var err error
194
195 fixups, err = gitattr.New(db, t)
196 if err != nil {
197 return err
198 }
199 if err = fixups.FindSpecialAttributes(cfg.GitEnv(), cfg.OSEnv(), cfg.LocalGitDir()); err != nil {
200 return err
201 }
202 }
203 return nil
204 },
205
206 TreeCallbackFn: func(path string, t *gitobj.Tree) (*gitobj.Tree, error) {
207 if path != "/" || migrateFixup {
208 // Avoid updating .gitattributes in non-root
209 // trees, or if --fixup is given.
210 return t, nil
211 }
212
213 ours := tracked
214 if ours.Cardinality() == 0 {
215 // If there were no explicitly tracked
216 // --include, --exclude filters, assume that the
217 // include set is the wildcard filepath
218 // extensions of files tracked.
219 ours = exts
220
221 if ours.Cardinality() == 0 {
222 // If it is still the case that we have
223 // no patterns to track, that means that
224 // we are in a tree that does not
225 // require .gitattributes changes.
226 //
227 // We can return early to avoid
228 // comparing and saving an identical
229 // tree.
230 return t, nil
231 }
232 }
233
234 theirs, err := trackedFromAttrs(db, t)
235 if err != nil {
236 return nil, err
237 }
238
239 // Create a blob of the attributes that are optionally
240 // present in the "t" tree's .gitattributes blob, and
241 // union in the patterns that we've tracked.
242 //
243 // Perform this Union() operation each time we visit a
244 // root tree such that if the underlying .gitattributes
245 // is present and has a diff between commits in the
246 // range of commits to migrate, those changes are
247 // preserved.
248 blob, err := trackedToBlob(db, theirs.Clone().Union(ours))
249 if err != nil {
250 return nil, err
251 }
252
253 // Finally, return a copy of the tree "t" that has the
254 // new .gitattributes file included/replaced.
255 return t.Merge(&gitobj.TreeEntry{
256 Name: ".gitattributes",
257 Filemode: 0100644,
258 Oid: blob,
259 }), nil
260 },
261
262 UpdateRefs: true,
263 })
264
265 if err := checkoutNonBare(l); err != nil {
266 ExitWithError(errors.Wrap(err, tr.Tr.Get("Could not checkout")))
267 }
268 }
269
270 // generateMigrateCommitMessage generates a commit message used with
271 // --no-rewrite, using --message (if given) or generating one if it isn't.
272 func generateMigrateCommitMessage(cmd *cobra.Command, patterns string) string {
273 if cmd.Flag("message").Changed {
274 return migrateCommitMessage
275 }
276 return tr.Tr.Get("%s: convert to Git LFS", patterns)
277 }
278
279 // checkoutNonBare forces a checkout of the current reference, so long as the
280 // repository is non-bare.
281 //
282 // It returns nil on success, and a non-nil error on failure.
283 func checkoutNonBare(l *tasklog.Logger) error {
284 if bare, _ := git.IsBare(); bare {
285 return nil
286 }
287
288 t := l.Waiter(tr.Tr.Get("Checkout"))
289 defer t.Complete()
290
291 return git.Checkout("", nil, true)
292 }
293
294 // trackedFromFilter returns an ordered set of strings where each entry is a
295 // line in the .gitattributes file. It adds/removes the filter/diff/merge=lfs
296 // attributes based on patterns included/excluded in the given filter.
297 func trackedFromFilter(filter *filepathfilter.Filter) *tools.OrderedSet {
298 tracked := tools.NewOrderedSet()
299
300 for _, include := range filter.Include() {
301 tracked.Add(fmt.Sprintf("%s filter=lfs diff=lfs merge=lfs -text", escapeAttrPattern(include)))
302 }
303
304 for _, exclude := range filter.Exclude() {
305 tracked.Add(fmt.Sprintf("%s !text -filter -merge -diff", escapeAttrPattern(exclude)))
306 }
307
308 return tracked
309 }
310
311 var (
312 // attrsCache maintains a cache from the hex-encoded SHA1 of a
313 // .gitattributes blob to the set of patterns parsed from that blob.
314 attrsCache = make(map[string]*tools.OrderedSet)
315 )
316
317 // trackedFromAttrs returns an ordered line-delimited set of the contents of a
318 // .gitattributes blob in a given tree "t".
319 //
320 // It returns an empty set if no attributes file could be found, or an error if
321 // it could not otherwise be opened.
322 func trackedFromAttrs(db *gitobj.ObjectDatabase, t *gitobj.Tree) (*tools.OrderedSet, error) {
323 var oid []byte
324
325 for _, e := range t.Entries {
326 if strings.ToLower(e.Name) == ".gitattributes" && e.Type() == gitobj.BlobObjectType {
327 if e.IsLink() {
328 return nil, errors.New(tr.Tr.Get("expected '.gitattributes' to be a file, got a symbolic link"))
329 } else {
330 oid = e.Oid
331 break
332 }
333 }
334 }
335
336 if oid == nil {
337 // TODO(@ttaylorr): make (*tools.OrderedSet)(nil) a valid
338 // receiver for non-mutative methods.
339 return tools.NewOrderedSet(), nil
340 }
341
342 sha1 := hex.EncodeToString(oid)
343
344 if s, ok := attrsCache[sha1]; ok {
345 return s, nil
346 }
347
348 blob, err := db.Blob(oid)
349 if err != nil {
350 return nil, err
351 }
352
353 attrs := tools.NewOrderedSet()
354
355 scanner := bufio.NewScanner(blob.Contents)
356 for scanner.Scan() {
357 attrs.Add(scanner.Text())
358 }
359
360 if err := scanner.Err(); err != nil {
361 return nil, err
362 }
363
364 attrsCache[sha1] = attrs
365
366 return attrsCache[sha1], nil
367 }
368
369 // trackedToBlob writes and returns the OID of a .gitattributes blob based on
370 // the patterns given in the ordered set of patterns, "patterns".
371 func trackedToBlob(db *gitobj.ObjectDatabase, patterns *tools.OrderedSet) ([]byte, error) {
372 var attrs bytes.Buffer
373
374 for pattern := range patterns.Iter() {
375 fmt.Fprintf(&attrs, "%s\n", pattern)
376 }
377
378 return db.WriteBlob(&gitobj.Blob{
379 Contents: &attrs,
380 Size: int64(attrs.Len()),
381 })
382 }
383
384 // rewriteTree replaces the blob at the provided path within the given tree with
385 // a git lfs pointer. It will recursively rewrite any subtrees along the path to the
386 // blob.
387 func rewriteTree(gf *lfs.GitFilter, db *gitobj.ObjectDatabase, root []byte, path string) ([]byte, error) {
388 tree, err := db.Tree(root)
389 if err != nil {
390 return nil, err
391 }
392
393 splits := strings.SplitN(path, "/", 2)
394
395 switch len(splits) {
396 case 1:
397 // The path points to an entry at the root of this tree, so it must be a blob.
398 // Try to replace this blob with a Git LFS pointer.
399 index := findEntry(tree, splits[0])
400 if index < 0 {
401 return nil, errors.New(tr.Tr.Get("unable to find entry %s in tree", splits[0]))
402 }
403
404 blobEntry := tree.Entries[index]
405 blob, err := db.Blob(blobEntry.Oid)
406 if err != nil {
407 return nil, err
408 }
409
410 var buf bytes.Buffer
411
412 if _, err := clean(gf, &buf, blob.Contents, blobEntry.Name, blob.Size); err != nil {
413 return nil, err
414 }
415
416 newOid, err := db.WriteBlob(&gitobj.Blob{
417 Contents: &buf,
418 Size: int64(buf.Len()),
419 })
420
421 if err != nil {
422 return nil, err
423 }
424
425 tree = tree.Merge(&gitobj.TreeEntry{
426 Name: splits[0],
427 Filemode: blobEntry.Filemode,
428 Oid: newOid,
429 })
430 return db.WriteTree(tree)
431
432 case 2:
433 // The path points to an entry in a subtree contained at the root of the tree.
434 // Recursively rewrite the subtree.
435 head, tail := splits[0], splits[1]
436
437 index := findEntry(tree, head)
438 if index < 0 {
439 return nil, errors.New(tr.Tr.Get("unable to find entry %s in tree", head))
440 }
441
442 subtreeEntry := tree.Entries[index]
443 if subtreeEntry.Type() != gitobj.TreeObjectType {
444 return nil, errors.New(tr.Tr.Get("expected %s to be a tree, got %s", head, subtreeEntry.Type()))
445 }
446
447 rewrittenSubtree, err := rewriteTree(gf, db, subtreeEntry.Oid, tail)
448 if err != nil {
449 return nil, err
450 }
451
452 tree = tree.Merge(&gitobj.TreeEntry{
453 Filemode: subtreeEntry.Filemode,
454 Name: subtreeEntry.Name,
455 Oid: rewrittenSubtree,
456 })
457
458 return db.WriteTree(tree)
459
460 default:
461 return nil, errors.New(tr.Tr.Get("error parsing path %s", path))
462 }
463 }
464
465 // findEntry searches a tree for the desired entry, and returns the index of that
466 // entry within the tree's Entries array
467 func findEntry(t *gitobj.Tree, name string) int {
468 for i, entry := range t.Entries {
469 if entry.Name == name {
470 return i
471 }
472 }
473
474 return -1
475 }