Debian Codegraph @

commands/command_migrate.go

raw symbols SCIP
1 package commands
2
3 import (
4 "bufio"
5 "fmt"
6 "io"
7 "strings"
8
9 "github.com/git-lfs/git-lfs/v3/errors"
10 "github.com/git-lfs/git-lfs/v3/filepathfilter"
11 "github.com/git-lfs/git-lfs/v3/git"
12 "github.com/git-lfs/git-lfs/v3/git/githistory"
13 "github.com/git-lfs/git-lfs/v3/tasklog"
14 "github.com/git-lfs/git-lfs/v3/tr"
15 "github.com/git-lfs/gitobj/v2"
16 "github.com/spf13/cobra"
17 )
18
19 var (
20 // migrateIncludeRefs is a set of Git references to explicitly include
21 // in the migration.
22 migrateIncludeRefs []string
23 // migrateExcludeRefs is a set of Git references to explicitly exclude
24 // in the migration.
25 migrateExcludeRefs []string
26
27 // migrateYes indicates that an answer of 'yes' should be presumed
28 // whenever 'git lfs migrate' asks for user input.
29 migrateYes bool
30
31 // migrateSkipFetch assumes that the client has the latest copy of
32 // remote references, and thus should not contact the remote for a set
33 // of updated references.
34 migrateSkipFetch bool
35
36 // migrateImportAboveFmt indicates the presence of the --above=<size>
37 // flag and instructs 'git lfs migrate import' to import all files
38 // above the provided size.
39 migrateImportAboveFmt string
40
41 // migrateEverything indicates the presence of the --everything flag,
42 // and instructs 'git lfs migrate' to migrate all local references.
43 migrateEverything bool
44
45 // migrateVerbose enables verbose logging
46 migrateVerbose bool
47
48 // objectMapFile is the path to the map of old sha1 to new sha1
49 // commits
50 objectMapFilePath string
51
52 // migrateNoRewrite is the flag indicating whether or not the
53 // command should rewrite git history
54 migrateNoRewrite bool
55 // migrateCommitMessage is the message to use with the commit generated
56 // by the migrate command
57 migrateCommitMessage string
58
59 // exportRemote is the remote from which to download objects when
60 // performing an export
61 exportRemote string
62
63 // migrateFixup is the flag indicating whether or not to infer the
64 // included and excluded filepath patterns.
65 migrateFixup bool
66 )
67
68 // migrate takes the given command and arguments, *gitobj.ObjectDatabase, as well
69 // as a BlobRewriteFn to apply, and performs a migration.
70 func migrate(args []string, r *githistory.Rewriter, l *tasklog.Logger, opts *githistory.RewriteOptions) {
71 setupRepository()
72
73 opts, err := rewriteOptions(args, opts, l)
74 if err != nil {
75 ExitWithError(err)
76 }
77
78 _, err = r.Rewrite(opts)
79 if err != nil {
80 ExitWithError(err)
81 }
82 }
83
84 // getObjectDatabase creates a *git.ObjectDatabase from the filesystem pointed
85 // at the .git directory of the currently checked-out repository.
86 func getObjectDatabase() (*gitobj.ObjectDatabase, error) {
87 dir, err := git.GitCommonDir()
88 if err != nil {
89 return nil, errors.Wrap(err, tr.Tr.Get("cannot open root"))
90 }
91
92 return git.ObjectDatabase(cfg.OSEnv(), cfg.GitEnv(), dir, cfg.TempDir())
93 }
94
95 // rewriteOptions returns *githistory.RewriteOptions able to be passed to a
96 // *githistory.Rewriter that reflect the current arguments and flags passed to
97 // an invocation of git-lfs-migrate(1).
98 //
99 // It is merged with the given "opts". In other words, an identical "opts" is
100 // returned, where the Include and Exclude fields have been filled based on the
101 // following rules:
102 //
103 // The included and excluded references are determined based on the output of
104 // includeExcludeRefs (see below for documentation and detail).
105 //
106 // If any of the above could not be determined without error, that error will be
107 // returned immediately.
108 func rewriteOptions(args []string, opts *githistory.RewriteOptions, l *tasklog.Logger) (*githistory.RewriteOptions, error) {
109 include, exclude, err := includeExcludeRefs(l, args)
110 if err != nil {
111 return nil, err
112 }
113
114 return &githistory.RewriteOptions{
115 Include: include,
116 Exclude: exclude,
117
118 UpdateRefs: opts.UpdateRefs,
119 Verbose: opts.Verbose,
120 ObjectMapFilePath: opts.ObjectMapFilePath,
121
122 BlobFn: opts.BlobFn,
123 TreePreCallbackFn: opts.TreePreCallbackFn,
124 TreeCallbackFn: opts.TreeCallbackFn,
125 }, nil
126 }
127
128 // isSpecialGitRef checks if a ref spec is a special git ref to exclude from
129 // --everything
130 func isSpecialGitRef(refspec string) bool {
131 // Special refspecs.
132 switch refspec {
133 case "refs/stash":
134 return true
135 }
136
137 // Special refspecs from namespaces.
138 parts := strings.SplitN(refspec, "/", 3)
139 if len(parts) < 3 {
140 return false
141 }
142 prefix := strings.Join(parts[:2], "/")
143 switch prefix {
144 case "refs/notes", "refs/bisect", "refs/replace":
145 return true
146 }
147 return false
148 }
149
150 // includeExcludeRefs returns fully-qualified sets of references to include, and
151 // exclude, or an error if those could not be determined.
152 //
153 // They are determined based on the following rules:
154 //
155 // - Include all local refs/heads/<branch> references for each branch
156 // specified as an argument.
157 // - Include the currently checked out branch if no branches are given as
158 // arguments and the --include-ref= or --exclude-ref= flag(s) aren't given.
159 // - Include all references given in --include-ref=<ref>.
160 // - Exclude all references given in --exclude-ref=<ref>.
161 func includeExcludeRefs(l *tasklog.Logger, args []string) (include, exclude []string, err error) {
162 hardcore := len(migrateIncludeRefs) > 0 || len(migrateExcludeRefs) > 0
163
164 if len(args) == 0 && !hardcore && !migrateEverything {
165 // If no branches were given explicitly AND neither
166 // --include-ref or --exclude-ref flags were given, then add the
167 // currently checked out reference.
168 current, err := currentRefToMigrate()
169 if err != nil {
170 return nil, nil, err
171 }
172 args = append(args, current.Name)
173 }
174
175 if migrateEverything && len(args) > 0 {
176 return nil, nil, errors.New(tr.Tr.Get("Cannot use --everything with explicit reference arguments"))
177 }
178
179 for _, name := range args {
180 var excluded bool
181 if strings.HasPrefix("^", name) {
182 name = name[1:]
183 excluded = true
184 }
185
186 // Then, loop through each branch given, resolve that reference,
187 // and include it.
188 ref, err := git.ResolveRef(name)
189 if err != nil {
190 return nil, nil, err
191 }
192
193 if excluded {
194 exclude = append(exclude, ref.Refspec())
195 } else {
196 include = append(include, ref.Refspec())
197 }
198 }
199
200 if hardcore {
201 if migrateEverything {
202 return nil, nil, errors.New(tr.Tr.Get("Cannot use --everything with --include-ref or --exclude-ref"))
203 }
204
205 // If either --include-ref=<ref> or --exclude-ref=<ref> were
206 // given, append those to the include and excluded reference
207 // set, respectively.
208 include = append(include, migrateIncludeRefs...)
209 exclude = append(exclude, migrateExcludeRefs...)
210 } else if migrateEverything {
211 refs, err := git.AllRefsIn("")
212 if err != nil {
213 return nil, nil, err
214 }
215
216 for _, ref := range refs {
217 switch ref.Type {
218 case git.RefTypeLocalBranch, git.RefTypeLocalTag,
219 git.RefTypeRemoteBranch:
220
221 include = append(include, ref.Refspec())
222 case git.RefTypeOther:
223 if isSpecialGitRef(ref.Refspec()) {
224 continue
225 }
226 include = append(include, ref.Refspec())
227 }
228 }
229 } else {
230 bare, err := git.IsBare()
231 if err != nil {
232 return nil, nil, errors.Wrap(err, tr.Tr.Get("Unable to determine bareness"))
233 }
234
235 if !bare {
236 // Otherwise, if neither --include-ref=<ref> or
237 // --exclude-ref=<ref> were given, include no additional
238 // references, and exclude all remote references that
239 // are remote branches or remote tags.
240 remoteRefs, err := getRemoteRefs(l)
241 if err != nil {
242 return nil, nil, err
243 }
244
245 for remote, refs := range remoteRefs {
246 for _, ref := range refs {
247 exclude = append(exclude,
248 formatRefName(ref, remote))
249 }
250 }
251 }
252 }
253
254 return include, exclude, nil
255 }
256
257 // getRemoteRefs returns a fully qualified set of references belonging to all
258 // remotes known by the currently checked-out repository, or an error if those
259 // references could not be determined.
260 func getRemoteRefs(l *tasklog.Logger) (map[string][]*git.Ref, error) {
261 refs := make(map[string][]*git.Ref)
262
263 remotes, err := git.RemoteList()
264 if err != nil {
265 return nil, err
266 }
267
268 if !migrateSkipFetch {
269 if err := fetchRemoteRefs(l, remotes); err != nil {
270 return nil, err
271 }
272 }
273
274 for _, remote := range remotes {
275 var refsForRemote []*git.Ref
276 if migrateSkipFetch {
277 refsForRemote, err = git.CachedRemoteRefs(remote)
278 } else {
279 refsForRemote, err = git.RemoteRefs(remote, true)
280 }
281
282 if err != nil {
283 return nil, err
284 }
285
286 refs[remote] = refsForRemote
287 }
288
289 return refs, nil
290 }
291
292 func fetchRemoteRefs(l *tasklog.Logger, remotes []string) error {
293 w := l.Waiter(tr.Tr.Get("Fetching remote refs"))
294 defer w.Complete()
295
296 return git.Fetch(remotes...)
297 }
298
299 // formatRefName returns the fully-qualified name for the given Git reference
300 // "ref".
301 func formatRefName(ref *git.Ref, remote string) string {
302 if ref.Type == git.RefTypeRemoteBranch {
303 return strings.Join([]string{
304 "refs", "remotes", remote, ref.Name}, "/")
305 }
306 return ref.Refspec()
307
308 }
309
310 // currentRefToMigrate returns the fully-qualified name of the currently
311 // checked-out reference, or an error if the reference's type was not a local
312 // branch.
313 func currentRefToMigrate() (*git.Ref, error) {
314 current, err := git.CurrentRef()
315 if err != nil {
316 return nil, err
317 }
318
319 if current.Type == git.RefTypeOther ||
320 current.Type == git.RefTypeRemoteBranch {
321
322 return nil, errors.New(tr.Tr.Get("Cannot migrate non-local ref: %s", current.Name))
323 }
324 return current, nil
325 }
326
327 // getHistoryRewriter returns a history rewriter that includes the filepath
328 // filter given by the --include and --exclude arguments.
329 func getHistoryRewriter(cmd *cobra.Command, db *gitobj.ObjectDatabase, l *tasklog.Logger) *githistory.Rewriter {
330 include, exclude := getIncludeExcludeArgs(cmd)
331 filter := buildFilepathFilterWithPatternType(cfg, include, exclude, false, filepathfilter.GitAttributes)
332
333 return githistory.NewRewriter(db,
334 githistory.WithFilter(filter), githistory.WithLogger(l))
335 }
336
337 func ensureWorkingCopyClean(in io.Reader, out io.Writer) {
338 dirty, err := git.IsWorkingCopyDirty()
339 if err != nil {
340 ExitWithError(errors.Wrap(err,
341 tr.Tr.Get("Could not determine if working copy is dirty")))
342 }
343
344 if !dirty {
345 return
346 }
347
348 var proceed bool
349 if migrateYes {
350 proceed = true
351 } else {
352 answer := bufio.NewReader(in)
353 L:
354 for {
355 fmt.Fprint(out, tr.Tr.Get("override changes in your working copy? All uncommitted changes will be lost! [y/N] "))
356 s, err := answer.ReadString('\n')
357 if err != nil {
358 if err == io.EOF {
359 break L
360 }
361 ExitWithError(errors.Wrap(err,
362 tr.Tr.Get("Could not read answer")))
363 }
364
365 switch strings.TrimSpace(s) {
366 // TRANSLATORS: these are negative (no) responses.
367 case tr.Tr.Get("n"), tr.Tr.Get("N"), "":
368 proceed = false
369 break L
370 // TRANSLATORS: these are positive (yes) responses.
371 case tr.Tr.Get("y"), tr.Tr.Get("Y"):
372 proceed = true
373 break L
374 }
375
376 if !strings.HasSuffix(s, "\n") {
377 fmt.Fprintf(out, "\n")
378 }
379 }
380 }
381
382 if proceed {
383 fmt.Fprintln(out, tr.Tr.Get("changes in your working copy will be overridden ..."))
384 } else {
385 Exit(tr.Tr.Get("working copy must not be dirty"))
386 }
387 }
388
389 func init() {
390 info := NewCommand("info", migrateInfoCommand)
391 info.Flags().IntVar(&migrateInfoTopN, "top", 5, "--top=<n>")
392 info.Flags().StringVar(&migrateInfoAboveFmt, "above", "", "--above=<n>")
393 info.Flags().StringVar(&migrateInfoUnitFmt, "unit", "", "--unit=<unit>")
394 info.Flags().StringVar(&migrateInfoPointers, "pointers", "", "Ignore, dereference, or include LFS pointer files")
395 info.Flags().BoolVar(&migrateFixup, "fixup", false, "Infer filepaths based on .gitattributes")
396
397 importCmd := NewCommand("import", migrateImportCommand)
398 importCmd.Flags().StringVar(&migrateImportAboveFmt, "above", "", "--above=<n>")
399 importCmd.Flags().BoolVar(&migrateVerbose, "verbose", false, "Verbose logging")
400 importCmd.Flags().StringVar(&objectMapFilePath, "object-map", "", "Object map file")
401 importCmd.Flags().BoolVar(&migrateNoRewrite, "no-rewrite", false, "Add new history without rewriting previous")
402 importCmd.Flags().StringVarP(&migrateCommitMessage, "message", "m", "", "With --no-rewrite, an optional commit message")
403 importCmd.Flags().BoolVar(&migrateFixup, "fixup", false, "Infer filepaths based on .gitattributes")
404
405 exportCmd := NewCommand("export", migrateExportCommand)
406 exportCmd.Flags().BoolVar(&migrateVerbose, "verbose", false, "Verbose logging")
407 exportCmd.Flags().StringVar(&objectMapFilePath, "object-map", "", "Object map file")
408 exportCmd.Flags().StringVar(&exportRemote, "remote", "", "Remote from which to download objects")
409
410 RegisterCommand("migrate", nil, func(cmd *cobra.Command) {
411 cmd.PersistentFlags().StringVarP(&includeArg, "include", "I", "", "Include a list of paths")
412 cmd.PersistentFlags().StringVarP(&excludeArg, "exclude", "X", "", "Exclude a list of paths")
413
414 cmd.PersistentFlags().StringSliceVar(&migrateIncludeRefs, "include-ref", nil, "An explicit list of refs to include")
415 cmd.PersistentFlags().StringSliceVar(&migrateExcludeRefs, "exclude-ref", nil, "An explicit list of refs to exclude")
416 cmd.PersistentFlags().BoolVar(&migrateEverything, "everything", false, "Migrate all local references")
417 cmd.PersistentFlags().BoolVar(&migrateSkipFetch, "skip-fetch", false, "Assume up-to-date remote references.")
418
419 cmd.PersistentFlags().BoolVarP(&migrateYes, "yes", "y", false, "Don't prompt for answers.")
420
421 cmd.AddCommand(exportCmd, importCmd, info)
422 })
423 }