Debian Codegraph @

commands/commands.go

raw symbols SCIP
1 package commands
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "net"
8 "os"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "sync"
13 "time"
14
15 "github.com/git-lfs/git-lfs/v3/config"
16 "github.com/git-lfs/git-lfs/v3/errors"
17 "github.com/git-lfs/git-lfs/v3/filepathfilter"
18 "github.com/git-lfs/git-lfs/v3/git"
19 "github.com/git-lfs/git-lfs/v3/lfs"
20 "github.com/git-lfs/git-lfs/v3/lfsapi"
21 "github.com/git-lfs/git-lfs/v3/locking"
22 "github.com/git-lfs/git-lfs/v3/subprocess"
23 "github.com/git-lfs/git-lfs/v3/tools"
24 "github.com/git-lfs/git-lfs/v3/tq"
25 "github.com/git-lfs/git-lfs/v3/tr"
26 )
27
28 // Populate man pages
29 //go:generate go run ../docs/man/mangen.go
30
31 const (
32 defaultFilepathFilterCacheSize = 10000
33 )
34
35 var (
36 ErrorBuffer = &bytes.Buffer{}
37 ErrorWriter = newMultiWriter(os.Stderr, ErrorBuffer)
38 OutputWriter = newMultiWriter(os.Stdout, ErrorBuffer)
39 ManPages = make(map[string]string, 20)
40 tqManifest = make(map[string]tq.Manifest)
41
42 cfg *config.Configuration
43 apiClient *lfsapi.Client
44 global sync.Mutex
45 cleanupOnce sync.Once
46
47 oldEnv = make(map[string]string)
48
49 includeArg string
50 excludeArg string
51 )
52
53 // getTransferManifest builds a tq.Manifest from the global os and git
54 // environments.
55 func getTransferManifest() tq.Manifest {
56 return getTransferManifestOperationRemote("", "")
57 }
58
59 // getTransferManifestOperationRemote builds a tq.Manifest from the global os
60 // and git environments and operation-specific and remote-specific settings.
61 // Operation must be "download", "upload", or the empty string.
62 func getTransferManifestOperationRemote(operation, remote string) tq.Manifest {
63 c := getAPIClient()
64
65 global.Lock()
66 defer global.Unlock()
67
68 k := fmt.Sprintf("%s.%s", operation, remote)
69 if tqManifest[k] == nil {
70 tqManifest[k] = tq.NewManifest(cfg.Filesystem(), c, operation, remote)
71 }
72
73 return tqManifest[k]
74 }
75
76 func getAPIClient() *lfsapi.Client {
77 global.Lock()
78 defer global.Unlock()
79
80 if apiClient == nil {
81 apiClient = lfsapi.NewClient(cfg)
82 }
83 return apiClient
84 }
85
86 func closeAPIClient() error {
87 global.Lock()
88 defer global.Unlock()
89 if apiClient == nil {
90 return nil
91 }
92
93 err := apiClient.Close()
94 apiClient = nil
95
96 return err
97 }
98
99 func newLockClient() *locking.Client {
100 lockClient := locking.NewClient(cfg.PushRemote(), getAPIClient(), cfg)
101
102 tools.MkdirAll(cfg.LFSStorageDir(), cfg)
103 err := lockClient.SetupFileCache(cfg.LFSStorageDir())
104
105 if err != nil {
106 Exit(tr.Tr.Get("Unable to create lock system: %v", err.Error()))
107 }
108
109 // Configure dirs
110 lockClient.LocalWorkingDir = cfg.LocalWorkingDir()
111 lockClient.LocalGitDir = cfg.LocalGitDir()
112 lockClient.SetLockableFilesReadOnly = cfg.SetLockableFilesReadOnly()
113
114 return lockClient
115 }
116
117 // newDownloadCheckQueue builds a checking queue, checks that objects are there but doesn't download
118 func newDownloadCheckQueue(manifest tq.Manifest, remote string, options ...tq.Option) *tq.TransferQueue {
119 return newDownloadQueue(manifest, remote, append(options,
120 tq.DryRun(true),
121 )...)
122 }
123
124 // newDownloadQueue builds a DownloadQueue, allowing concurrent downloads.
125 func newDownloadQueue(manifest tq.Manifest, remote string, options ...tq.Option) *tq.TransferQueue {
126 return tq.NewTransferQueue(tq.Download, manifest, remote, append(options,
127 tq.RemoteRef(fetchRemoteRef()),
128 tq.WithBatchSize(cfg.TransferBatchSize()),
129 )...)
130 }
131
132 // fetchRemoteRef returns the remote ref for download operations by looking up
133 // the upstream tracking branch for the current local ref. Unlike pushRemoteRef,
134 // this does not use push.default logic, which is not meaningful for fetches.
135 func fetchRemoteRef() *git.Ref {
136 return git.TrackingRef(cfg.Git, cfg.CurrentRef())
137 }
138
139 func pushRemoteRef() *git.Ref {
140 return git.NewRefUpdate(cfg.Git, cfg.PushRemote(), cfg.CurrentRef(), nil).RemoteRef()
141 }
142
143 func buildFilepathFilter(config *config.Configuration, includeArg, excludeArg *string, useFetchOptions bool) *filepathfilter.Filter {
144 return buildFilepathFilterWithPatternType(config, includeArg, excludeArg, useFetchOptions, filepathfilter.GitIgnore)
145 }
146
147 func buildFilepathFilterWithPatternType(config *config.Configuration, includeArg, excludeArg *string, useFetchOptions bool, patternType filepathfilter.PatternType) *filepathfilter.Filter {
148 inc, exc := determineIncludeExcludePaths(config, includeArg, excludeArg, useFetchOptions)
149 return filepathfilter.New(inc, exc, patternType, config.Git, determineFilepathFilterCache(config))
150 }
151
152 func downloadTransfer(p *lfs.WrappedPointer) (name, path, oid string, size int64, missing bool, err error) {
153 path, err = cfg.Filesystem().ObjectPath(p.Oid)
154 return p.Name, path, p.Oid, p.Size, false, err
155 }
156
157 // Get user-readable manual install steps for hooks
158 func getHookInstallSteps() string {
159 hookDir, err := cfg.HookDir()
160 if err != nil {
161 ExitWithError(err)
162 }
163 hooks := lfs.LoadHooks(hookDir, cfg)
164 hookDir = filepath.ToSlash(hookDir)
165 workingDir := filepath.ToSlash(fmt.Sprintf("%s%c", cfg.LocalWorkingDir(), os.PathSeparator))
166 steps := make([]string, 0, len(hooks))
167 for _, h := range hooks {
168 steps = append(steps, fmt.Sprintf("%s\n\n%s",
169 tr.Tr.Get("Add the following to '%s/%s':", strings.TrimPrefix(hookDir, workingDir), h.Type),
170 tools.Indent(h.Contents)))
171 }
172
173 return strings.Join(steps, "\n\n")
174 }
175
176 func installHooks(force bool) error {
177 hookDir, err := cfg.HookDir()
178 if err != nil {
179 return err
180 }
181 hooks := lfs.LoadHooks(hookDir, cfg)
182 for _, h := range hooks {
183 if err := h.Install(force); err != nil {
184 return err
185 }
186 }
187
188 return nil
189 }
190
191 // uninstallHooks removes all hooks in range of the `hooks` var.
192 func uninstallHooks() error {
193 if !cfg.InRepo() {
194 return errors.New(tr.Tr.Get("Not in a Git repository"))
195 }
196
197 hookDir, err := cfg.HookDir()
198 if err != nil {
199 return err
200 }
201 hooks := lfs.LoadHooks(hookDir, cfg)
202 for _, h := range hooks {
203 if err := h.Uninstall(); err != nil {
204 return err
205 }
206 }
207
208 return nil
209 }
210
211 // ExitWithCode exits immediately with the given code.
212 func ExitWithCode(code int) {
213 Cleanup()
214 os.Exit(code)
215 }
216
217 // Error prints a formatted message to Stderr. It also gets printed to the
218 // panic log if one is created for this command.
219 func Error(format string, args ...interface{}) {
220 if len(args) == 0 {
221 fmt.Fprintln(ErrorWriter, format)
222 return
223 }
224 fmt.Fprintf(ErrorWriter, format+"\n", args...)
225 }
226
227 // Print prints a formatted message to Stdout. It also gets printed to the
228 // panic log if one is created for this command.
229 func Print(format string, args ...interface{}) {
230 if len(args) == 0 {
231 fmt.Fprintln(OutputWriter, format)
232 return
233 }
234 fmt.Fprintf(OutputWriter, format+"\n", args...)
235 }
236
237 // Exit prints a formatted message and exits.
238 func Exit(format string, args ...interface{}) {
239 Error(format, args...)
240 Cleanup()
241 os.Exit(2)
242 }
243
244 // ExitWithError either panics with a full stack trace for fatal errors, or
245 // simply prints the error message and exits immediately.
246 func ExitWithError(err error) {
247 errorWith(err, Panic, Exit)
248 }
249
250 // FullError prints either a full stack trace for fatal errors, or just the
251 // error message.
252 func FullError(err error) {
253 errorWith(err, LoggedError, Error)
254 }
255
256 func errorWith(err error, fatalErrFn func(error, string, ...interface{}), errFn func(string, ...interface{})) {
257 if errors.IsFatalError(err) {
258 fatalErrFn(err, "%s", err)
259 return
260 }
261
262 errFn("%s", err)
263 }
264
265 // LoggedError prints the given message formatted with its arguments (if any) to
266 // Stderr. If an empty string is passed as the "format" argument, only the
267 // standard error logging message will be printed, and the error's body will be
268 // omitted.
269 //
270 // It also writes a stack trace for the error to a log file without exiting.
271 func LoggedError(err error, format string, args ...interface{}) {
272 if len(format) > 0 {
273 Error(format, args...)
274 }
275 file := handlePanic(err)
276
277 if len(file) > 0 {
278 fmt.Fprintf(os.Stderr, "\n%s\n", tr.Tr.Get("Errors logged to '%s'.\nUse `git lfs logs last` to view the log.", file))
279 }
280 }
281
282 // Panic prints a formatted message, and writes a stack trace for the error to
283 // a log file before exiting.
284 func Panic(err error, format string, args ...interface{}) {
285 LoggedError(err, format, args...)
286 Cleanup()
287 os.Exit(2)
288 }
289
290 func Cleanup() {
291 cleanupOnce.Do(doCleanup)
292 }
293
294 func doCleanup() {
295 if err := closeAPIClient(); err != nil {
296 fmt.Fprintln(os.Stderr, tr.Tr.Get("Error closing API client: %s", err))
297 }
298
299 if err := cfg.Cleanup(); err != nil {
300 fmt.Fprintln(os.Stderr, tr.Tr.Get("Error clearing old temporary files: %s", err))
301 }
302 }
303
304 func requireStdin(msg string) {
305 var out string
306
307 stat, err := os.Stdin.Stat()
308 if err != nil {
309 out = tr.Tr.Get("Cannot read from STDIN: %s (%s)", msg, err)
310 } else if (stat.Mode() & os.ModeCharDevice) != 0 {
311 out = tr.Tr.Get("Cannot read from STDIN: %s", msg)
312 }
313
314 if len(out) > 0 {
315 Error(out)
316 ExitWithCode(1)
317 }
318 }
319
320 func requireInRepo() {
321 if !cfg.InRepo() {
322 Print(tr.Tr.Get("Not in a Git repository."))
323 ExitWithCode(128)
324 }
325 }
326
327 // requireWorkingCopy requires that the working directory be a work tree, i.e.,
328 // that it not be bare. If it is bare (or the state of the repository could not
329 // be determined), this function will terminate the program.
330 func requireWorkingCopy() {
331 if cfg.LocalWorkingDir() == "" {
332 Print(tr.Tr.Get("This operation must be run in a work tree."))
333 ExitWithCode(128)
334 }
335 }
336
337 func setupRepository() {
338 requireInRepo()
339 bare, err := git.IsBare()
340 if err != nil {
341 ExitWithError(errors.Wrap(
342 err, tr.Tr.Get("Could not determine bareness")))
343 }
344 verifyRepositoryVersion()
345
346 if !bare {
347 changeToWorkingCopy()
348 }
349 }
350
351 func verifyRepositoryVersion() {
352 key := "lfs.repositoryformatversion"
353 val := cfg.FindGitLocalKey(key)
354 if val == "" {
355 cfg.SetGitLocalKey(key, "0")
356 } else if val != "0" {
357 Print(tr.Tr.Get("Unknown repository format version: %s", val))
358 ExitWithCode(128)
359 }
360 }
361
362 func setupWorkingCopy() {
363 requireInRepo()
364 requireWorkingCopy()
365 verifyRepositoryVersion()
366 changeToWorkingCopy()
367 }
368
369 func changeToWorkingCopy() {
370 workingDir := cfg.LocalWorkingDir()
371 cwd, err := tools.Getwd()
372 if err != nil {
373 ExitWithError(errors.Wrap(
374 err, tr.Tr.Get("Could not determine current working directory")))
375 }
376 cwd, err = tools.CanonicalizeSystemPath(cwd)
377 if err != nil {
378 ExitWithError(errors.Wrap(
379 err, tr.Tr.Get("Could not canonicalize current working directory")))
380 }
381
382 // If the current working directory is not within the repository's
383 // working directory, then let's change directories accordingly. This
384 // should only occur if GIT_WORK_TREE is set.
385 if !(strings.HasPrefix(cwd, workingDir) && (cwd == workingDir || (len(cwd) > len(workingDir) && cwd[len(workingDir)] == os.PathSeparator))) {
386 os.Chdir(workingDir)
387 }
388 }
389
390 func canonicalizeEnvironment() {
391 vars := []string{"GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR"}
392 for _, v := range vars {
393 val, ok := os.LookupEnv(v)
394 if ok {
395 path, err := tools.CanonicalizePath(val, true)
396 // We have existing code which relies on users being
397 // able to pass invalid paths, so don't fail if the path
398 // cannot be canonicalized.
399 if err == nil {
400 oldEnv[v] = val
401 os.Setenv(v, path)
402 }
403 }
404 }
405 subprocess.ResetEnvironment()
406 }
407
408 func handlePanic(err error) string {
409 if err == nil {
410 return ""
411 }
412
413 return logPanic(err)
414 }
415
416 func logPanic(loggedError error) string {
417 var (
418 fmtWriter io.Writer = os.Stderr
419 lineEnding string = "\n"
420 )
421
422 now := time.Now()
423 name := now.Format("20060102T150405.999999999")
424 full := filepath.Join(cfg.LocalLogDir(), name+".log")
425
426 if err := tools.MkdirAll(cfg.LocalLogDir(), cfg); err != nil {
427 full = ""
428 fmt.Fprintf(fmtWriter, "%s\n\n", tr.Tr.Get("Unable to log panic to '%s': %s", cfg.LocalLogDir(), err.Error()))
429 } else if file, err := os.Create(full); err != nil {
430 filename := full
431 full = ""
432 defer func() {
433 fmt.Fprintf(fmtWriter, "%s\n\n", tr.Tr.Get("Unable to log panic to '%s'", filename))
434 logPanicToWriter(fmtWriter, err, lineEnding)
435 }()
436 } else {
437 fmtWriter = file
438 lineEnding = gitLineEnding(cfg.Git)
439 defer file.Close()
440 }
441
442 logPanicToWriter(fmtWriter, loggedError, lineEnding)
443
444 return full
445 }
446
447 func ipAddresses() []string {
448 ips := make([]string, 0, 1)
449 ifaces, err := net.Interfaces()
450 if err != nil {
451 ips = append(ips, tr.Tr.Get("Error getting network interface: %s", err.Error()))
452 return ips
453 }
454 for _, i := range ifaces {
455 if i.Flags&net.FlagUp == 0 {
456 continue // interface down
457 }
458 if i.Flags&net.FlagLoopback != 0 {
459 continue // loopback interface
460 }
461 addrs, _ := i.Addrs()
462 l := make([]string, 0, 1)
463 if err != nil {
464 ips = append(ips, tr.Tr.Get("Error getting IP address: %s", err.Error()))
465 continue
466 }
467 for _, addr := range addrs {
468 var ip net.IP
469 switch v := addr.(type) {
470 case *net.IPNet:
471 ip = v.IP
472 case *net.IPAddr:
473 ip = v.IP
474 }
475 if ip == nil || ip.IsLoopback() {
476 continue
477 }
478 l = append(l, ip.String())
479 }
480 if len(l) > 0 {
481 ips = append(ips, strings.Join(l, " "))
482 }
483 }
484 return ips
485 }
486
487 func logPanicToWriter(w io.Writer, loggedError error, le string) {
488 // log the version
489 gitV, err := git.Version()
490 if err != nil {
491 gitV = tr.Tr.Get("Error getting Git version: %s", err.Error())
492 }
493
494 fmt.Fprint(w, config.VersionDesc, le)
495 fmt.Fprint(w, gitV, le)
496
497 // log the command that was run
498 fmt.Fprint(w, le)
499 fmt.Fprintf(w, "$ %s", filepath.Base(os.Args[0]))
500 if len(os.Args) > 0 {
501 fmt.Fprintf(w, " %s", strings.Join(os.Args[1:], " "))
502 }
503 fmt.Fprint(w, le)
504
505 // log the error message and stack trace
506 w.Write(ErrorBuffer.Bytes())
507 fmt.Fprint(w, le)
508
509 fmt.Fprintf(w, "%+v%s", loggedError, le)
510
511 for key, val := range errors.Context(err) {
512 fmt.Fprintf(w, "%s=%v%s", key, val, le)
513 }
514
515 fmt.Fprint(w, le, tr.Tr.Get("Current time in UTC:"), le)
516 fmt.Fprint(w, time.Now().UTC().Format("2006-01-02 15:04:05"), le)
517
518 fmt.Fprint(w, le, tr.Tr.Get("Environment:"), le)
519
520 // log the environment
521 for _, env := range lfs.Environ(cfg, getTransferManifest(), oldEnv) {
522 fmt.Fprint(w, env, le)
523 }
524
525 fmt.Fprint(w, le, tr.Tr.Get("Client IP addresses:"), le)
526
527 for _, ip := range ipAddresses() {
528 fmt.Fprint(w, ip, le)
529 }
530 }
531
532 func determineIncludeExcludePaths(config *config.Configuration, includeArg, excludeArg *string, useFetchOptions bool) (include, exclude []string) {
533 if includeArg == nil {
534 if useFetchOptions {
535 include = config.FetchIncludePaths()
536 } else {
537 include = []string{}
538 }
539 } else {
540 include = tools.CleanPaths(*includeArg, ",")
541 }
542 if excludeArg == nil {
543 if useFetchOptions {
544 exclude = config.FetchExcludePaths()
545 } else {
546 exclude = []string{}
547 }
548 } else {
549 exclude = tools.CleanPaths(*excludeArg, ",")
550 }
551 return
552 }
553
554 func determineFilepathFilterCache(config *config.Configuration) filepathfilter.Option {
555 cacheSize := defaultFilepathFilterCacheSize
556
557 if configSize, ok := config.Git.Get("lfs.pathfiltercachesize"); ok {
558 switch configSize {
559 case "none":
560 return filepathfilter.DisableCache()
561 case "unlimited":
562 cacheSize = 0
563 default:
564 if s, err := strconv.Atoi(configSize); err == nil {
565 if s == 0 {
566 return filepathfilter.DisableCache()
567 } else if s > 0 {
568 cacheSize = s
569 }
570 }
571 }
572 }
573
574 return filepathfilter.EnableCache(cacheSize)
575 }
576
577 func buildProgressMeter(dryRun bool, d tq.Direction) *tq.Meter {
578 m := tq.NewMeter(cfg)
579 m.Logger = m.LoggerFromEnv(cfg.Os)
580 m.DryRun = dryRun
581 m.Direction = d
582 return m
583 }
584
585 func requireGitVersion() {
586 minimumGit := "2.0.0"
587
588 if !git.IsGitVersionAtLeast(minimumGit) {
589 gitver, err := git.Version()
590 if err != nil {
591 Exit(tr.Tr.Get("Error getting Git version: %s", err))
592 }
593 Exit(tr.Tr.Get("Git version %s or higher is required for Git LFS; your version: %s", minimumGit, gitver))
594 }
595 }