Debian Codegraph @

lfs/util.go

raw symbols SCIP
1 package lfs
2
3 import (
4 "fmt"
5 "io"
6 "os"
7 "path/filepath"
8 "runtime"
9 "strings"
10
11 "github.com/git-lfs/git-lfs/v3/config"
12 "github.com/git-lfs/git-lfs/v3/errors"
13 "github.com/git-lfs/git-lfs/v3/tasklog"
14 "github.com/git-lfs/git-lfs/v3/tools"
15 "github.com/git-lfs/git-lfs/v3/tr"
16 )
17
18 type Platform int
19
20 const (
21 PlatformWindows = Platform(iota)
22 PlatformLinux = Platform(iota)
23 PlatformOSX = Platform(iota)
24 PlatformOther = Platform(iota) // most likely a *nix variant e.g. freebsd
25 PlatformUndetermined = Platform(iota)
26 )
27
28 var currentPlatform = PlatformUndetermined
29
30 func join(parts ...string) string {
31 return strings.Join(parts, "/")
32 }
33
34 func (f *GitFilter) CopyCallbackFile(event, filename string, index, totalFiles int) (tools.CopyCallback, *os.File, error) {
35 logPath, _ := f.cfg.Os.Get("GIT_LFS_PROGRESS")
36 if len(logPath) == 0 || len(filename) == 0 || len(event) == 0 {
37 return nil, nil, nil
38 }
39
40 if !filepath.IsAbs(logPath) {
41 return nil, nil, errors.New(tr.Tr.Get("GIT_LFS_PROGRESS must be an absolute path"))
42 }
43
44 cbDir := filepath.Dir(logPath)
45 if err := tools.MkdirAll(cbDir, f.cfg); err != nil {
46 return nil, nil, wrapProgressError(err, event, logPath)
47 }
48
49 file, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
50 if err != nil {
51 return nil, file, wrapProgressError(err, event, logPath)
52 }
53
54 var (
55 prevTotal int64
56 prevWritten int64
57 hasReachedTotal bool
58 )
59 deadline := f.clk.Now().Add(tasklog.DefaultLoggingThrottle)
60 cb := tools.CopyCallback(func(total int64, written int64, current int) error {
61 now := f.clk.Now()
62
63 if total == prevTotal {
64 if written == prevWritten {
65 return nil
66 }
67 } else {
68 hasReachedTotal = false
69 }
70
71 logOptional := total < 0 || written < total || hasReachedTotal
72 if logOptional && now.Before(deadline) {
73 return nil
74 }
75
76 writtenFraction := tools.FormatFraction(written, total)
77
78 _, err := fmt.Fprintf(file, "%s %d/%d %s %s\n", event, index, totalFiles, writtenFraction, filename)
79 file.Sync()
80
81 prevTotal = total
82 prevWritten = written
83 if !logOptional {
84 hasReachedTotal = true
85 }
86
87 deadline = now.Add(tasklog.DefaultLoggingThrottle)
88 return wrapProgressError(err, event, logPath)
89 })
90
91 return cb, file, nil
92 }
93
94 func wrapProgressError(err error, event, filename string) error {
95 if err != nil {
96 return errors.New(tr.Tr.Get("error writing Git LFS %s progress to %s: %s", event, filename, err.Error()))
97 }
98
99 return nil
100 }
101
102 var localDirSet = tools.NewStringSetFromSlice([]string{".", "./", ".\\"})
103
104 func GetPlatform() Platform {
105 if currentPlatform == PlatformUndetermined {
106 switch runtime.GOOS {
107 case "windows":
108 currentPlatform = PlatformWindows
109 case "linux":
110 currentPlatform = PlatformLinux
111 case "darwin":
112 currentPlatform = PlatformOSX
113 default:
114 currentPlatform = PlatformOther
115 }
116 }
117 return currentPlatform
118 }
119
120 type PathConverter interface {
121 Convert(string) string
122 }
123
124 // Convert filenames expressed relative to the current directory to be
125 // relative to the repo root. Useful when calling git with arguments that requires them
126 // to be rooted but the user is in a subdir of their repo & expects to use relative args
127 func NewCurrentToRepoPathConverter(cfg *config.Configuration) (PathConverter, error) {
128 r, c, p, err := pathConverterArgs(cfg)
129 if err != nil {
130 return nil, err
131 }
132
133 return &currentToRepoPathConverter{
134 repoDir: r,
135 currDir: c,
136 passthrough: p,
137 }, nil
138 }
139
140 type currentToRepoPathConverter struct {
141 repoDir string
142 currDir string
143 passthrough bool
144 }
145
146 func (p *currentToRepoPathConverter) Convert(filename string) string {
147 if p.passthrough {
148 return filename
149 }
150
151 var abs string
152 if filepath.IsAbs(filename) {
153 abs = tools.ResolveSymlinks(filename)
154 } else {
155 abs = join(p.currDir, filename)
156 }
157 reltoroot, err := filepath.Rel(p.repoDir, abs)
158 if err != nil {
159 // Can't do this, use absolute as best fallback
160 return abs
161 }
162 return filepath.ToSlash(reltoroot)
163 }
164
165 // Convert filenames expressed relative to the current directory to be relative
166 // to the repo root and convert them into wildmatch patterns.
167 func NewCurrentToRepoPatternConverter(cfg *config.Configuration) (PathConverter, error) {
168 r, c, p, err := pathConverterArgs(cfg)
169 if err != nil {
170 return nil, err
171 }
172
173 return &currentToRepoPatternConverter{
174 c: &currentToRepoPathConverter{
175 repoDir: r,
176 currDir: c,
177 passthrough: p,
178 },
179 }, nil
180 }
181
182 type currentToRepoPatternConverter struct {
183 c *currentToRepoPathConverter
184 }
185
186 func (p *currentToRepoPatternConverter) Convert(filename string) string {
187 pattern := p.c.Convert(filename)
188 if st, err := os.Stat(filename); err == nil && st.IsDir() {
189 pattern += "/"
190 }
191 if strings.HasPrefix(pattern, "./") {
192 pattern = pattern[2:]
193 if len(pattern) == 0 {
194 pattern = "**"
195 }
196 }
197 return pattern
198 }
199
200 func pathConverterArgs(cfg *config.Configuration) (string, string, bool, error) {
201 currDir, err := os.Getwd()
202 if err != nil {
203 return "", "", false, errors.New(tr.Tr.Get("unable to get working dir: %v", err))
204 }
205 currDir = tools.ResolveSymlinks(currDir)
206 return cfg.LocalWorkingDir(), currDir, cfg.LocalWorkingDir() == currDir, nil
207 }
208
209 // Are we running on Windows? Need to handle some extra path shenanigans
210 func IsWindows() bool {
211 return GetPlatform() == PlatformWindows
212 }
213
214 func CopyFileContents(cfg *config.Configuration, src string, dst string) error {
215 tmp, err := TempFile(cfg, filepath.Base(dst))
216 if err != nil {
217 return err
218 }
219 defer func() {
220 tmp.Close()
221 os.Remove(tmp.Name())
222 }()
223 in, err := os.Open(src)
224 if err != nil {
225 return err
226 }
227 defer in.Close()
228 _, err = io.Copy(tmp, in)
229 if err != nil {
230 return err
231 }
232 err = tmp.Close()
233 if err != nil {
234 return err
235 }
236 return os.Rename(tmp.Name(), dst)
237 }
238
239 func LinkOrCopy(cfg *config.Configuration, src string, dst string) error {
240 if src == dst {
241 return nil
242 }
243 err := os.Link(src, dst)
244 if err == nil {
245 return err
246 }
247 return CopyFileContents(cfg, src, dst)
248 }
249
250 // TempFile creates a temporary file in the temporary directory specified by the
251 // configuration that has the proper permissions for the repository. On
252 // success, it returns an open, non-nil *os.File, and the caller is responsible
253 // for closing and/or removing it. On failure, the temporary file is
254 // automatically cleaned up and an error returned.
255 //
256 // This function is designed to handle only temporary files that will be renamed
257 // into place later somewhere within the Git repository.
258 func TempFile(cfg *config.Configuration, pattern string) (*os.File, error) {
259 return tools.TempFile(cfg.TempDir(), pattern, cfg)
260 }