Debian Codegraph @

fs/fs.go

raw symbols SCIP
1 package fs
2
3 import (
4 "bufio"
5 "bytes"
6 "crypto/sha256"
7 "encoding/hex"
8 "errors"
9 "os"
10 "path/filepath"
11 "regexp"
12 "strconv"
13 "strings"
14 "sync"
15
16 "github.com/git-lfs/git-lfs/v3/tools"
17 "github.com/git-lfs/git-lfs/v3/tr"
18 "github.com/rubyist/tracerx"
19 )
20
21 var (
22 oidRE = regexp.MustCompile(`\A[[:alnum:]]{64}`)
23 EmptyObjectSHA256 = hex.EncodeToString(sha256.New().Sum(nil))
24 )
25
26 // Environment is a copy of a subset of the interface
27 // github.com/git-lfs/git-lfs/config.Environment.
28 //
29 // For more information, see config/environment.go.
30 type Environment interface {
31 Get(key string) (val string, ok bool)
32 }
33
34 // Object represents a locally stored LFS object.
35 type Object struct {
36 Oid string
37 Size int64
38 }
39
40 type Filesystem struct {
41 GitStorageDir string // parent of objects/lfs (may be same as GitDir but may not)
42 LFSStorageDir string // parent of lfs objects and tmp dirs. Default: ".git/lfs"
43 ReferenceDirs []string // alternative local media dirs (relative to clone reference repo)
44 lfsobjdir string
45 tmpdir string
46 logdir string
47 repoPerms os.FileMode
48 mu sync.Mutex
49 }
50
51 func (f *Filesystem) EachObject(fn func(Object) error) error {
52 var eachErr error
53 tools.FastWalkDir(f.LFSObjectDir(), func(parentDir string, info os.FileInfo, err error) {
54 if err != nil {
55 eachErr = err
56 return
57 }
58 if eachErr != nil || info.IsDir() {
59 return
60 }
61 if oidRE.MatchString(info.Name()) {
62 fn(Object{Oid: info.Name(), Size: info.Size()})
63 }
64 })
65 return eachErr
66 }
67
68 func (f *Filesystem) ObjectExists(oid string, size int64) bool {
69 if size == 0 {
70 return true
71 }
72 return tools.FileExistsOfSize(f.ObjectPathname(oid), size)
73 }
74
75 func (f *Filesystem) ObjectPath(oid string) (string, error) {
76 if len(oid) < 4 {
77 return "", errors.New(tr.Tr.Get("too short object ID: %q", oid))
78 }
79 if oid == EmptyObjectSHA256 {
80 return os.DevNull, nil
81 }
82 dir := f.localObjectDir(oid)
83 if err := tools.MkdirAll(dir, f); err != nil {
84 return "", errors.New(tr.Tr.Get("error trying to create local storage directory in %q: %s", dir, err))
85 }
86 return filepath.Join(dir, oid), nil
87 }
88
89 func (f *Filesystem) ObjectPathname(oid string) string {
90 if oid == EmptyObjectSHA256 {
91 return os.DevNull
92 }
93 return filepath.Join(f.localObjectDir(oid), oid)
94 }
95
96 func (f *Filesystem) DecodePathname(path string) string {
97 return string(DecodePathBytes([]byte(path)))
98 }
99
100 func (f *Filesystem) RepositoryPermissions(executable bool) os.FileMode {
101 if executable {
102 return tools.ExecutablePermissions(f.repoPerms)
103 }
104 return f.repoPerms
105 }
106
107 /**
108 * Revert non ascii characters escaped by git or windows (as octal sequences \000) back to bytes.
109 */
110 func DecodePathBytes(path []byte) []byte {
111 var expression = regexp.MustCompile(`\\[0-9]{3}`)
112 var buffer bytes.Buffer
113
114 // strip quotes if any
115 if len(path) > 2 && path[0] == '"' && path[len(path)-1] == '"' {
116 path = path[1 : len(path)-1]
117 }
118
119 base := 0
120 for _, submatches := range expression.FindAllSubmatchIndex(path, -1) {
121 buffer.Write(path[base:submatches[0]])
122
123 match := string(path[submatches[0]+1 : submatches[0]+4])
124
125 k, err := strconv.ParseUint(match, 8, 64)
126 if err != nil {
127 return path
128 } // abort on error
129
130 buffer.Write([]byte{byte(k)})
131 base = submatches[1]
132 }
133
134 buffer.Write(path[base:len(path)])
135
136 return buffer.Bytes()
137 }
138
139 func (f *Filesystem) localObjectDir(oid string) string {
140 return filepath.Join(f.LFSObjectDir(), oid[0:2], oid[2:4])
141 }
142
143 func (f *Filesystem) ObjectReferencePaths(oid string) []string {
144 if len(f.ReferenceDirs) == 0 {
145 return nil
146 }
147
148 var paths []string
149 for _, ref := range f.ReferenceDirs {
150 paths = append(paths, filepath.Join(ref, oid[0:2], oid[2:4], oid))
151 }
152 return paths
153 }
154
155 func (f *Filesystem) LFSObjectDir() string {
156 f.mu.Lock()
157 defer f.mu.Unlock()
158
159 if len(f.lfsobjdir) == 0 {
160 f.lfsobjdir = filepath.Join(f.LFSStorageDir, "objects")
161 tools.MkdirAll(f.lfsobjdir, f)
162 }
163
164 return f.lfsobjdir
165 }
166
167 func (f *Filesystem) LogDir() string {
168 f.mu.Lock()
169 defer f.mu.Unlock()
170
171 if len(f.logdir) == 0 {
172 f.logdir = filepath.Join(f.LFSStorageDir, "logs")
173 tools.MkdirAll(f.logdir, f)
174 }
175
176 return f.logdir
177 }
178
179 func (f *Filesystem) TempDir() string {
180 f.mu.Lock()
181 defer f.mu.Unlock()
182
183 if len(f.tmpdir) == 0 {
184 f.tmpdir = filepath.Join(f.LFSStorageDir, "tmp")
185 tools.MkdirAll(f.tmpdir, f)
186 }
187
188 return f.tmpdir
189 }
190
191 func (f *Filesystem) Cleanup() error {
192 if f == nil {
193 return nil
194 }
195 return f.cleanupTmp()
196 }
197
198 // New initializes a new *Filesystem with the given directories. gitdir is the
199 // path to the bare repo, workdir is the path to the repository working
200 // directory, and lfsdir is the optional path to the `.git/lfs` directory.
201 // repoPerms is the permissions for directories in the repository.
202 func New(env Environment, gitdir, workdir, lfsdir string, repoPerms os.FileMode) *Filesystem {
203 fs := &Filesystem{
204 GitStorageDir: resolveGitStorageDir(gitdir),
205 }
206
207 fs.ReferenceDirs = resolveReferenceDirs(env, fs.GitStorageDir)
208
209 if len(lfsdir) == 0 {
210 lfsdir = "lfs"
211 }
212
213 if filepath.IsAbs(lfsdir) {
214 fs.LFSStorageDir = lfsdir
215 } else {
216 fs.LFSStorageDir = filepath.Join(fs.GitStorageDir, lfsdir)
217 }
218
219 fs.repoPerms = repoPerms
220
221 return fs
222 }
223
224 func resolveReferenceDirs(env Environment, gitStorageDir string) []string {
225 var references []string
226
227 envAlternates, ok := env.Get("GIT_ALTERNATE_OBJECT_DIRECTORIES")
228 if ok {
229 splits := strings.Split(envAlternates, string(os.PathListSeparator))
230 for _, split := range splits {
231 if dir, ok := existsAlternate(split); ok {
232 references = append(references, dir)
233 }
234 }
235 }
236
237 cloneReferencePath := filepath.Join(gitStorageDir, "objects", "info", "alternates")
238 if tools.FileExists(cloneReferencePath) {
239 f, err := os.Open(cloneReferencePath)
240 if err != nil {
241 tracerx.Printf("could not open %s: %s",
242 cloneReferencePath, err)
243 return nil
244 }
245 defer f.Close()
246
247 scanner := bufio.NewScanner(f)
248 for scanner.Scan() {
249 text := strings.TrimSpace(scanner.Text())
250 if len(text) == 0 || strings.HasPrefix(text, "#") {
251 continue
252 }
253
254 if dir, ok := existsAlternate(text); ok {
255 references = append(references, dir)
256 }
257 }
258
259 if err := scanner.Err(); err != nil {
260 tracerx.Printf("could not scan %s: %s",
261 cloneReferencePath, err)
262 }
263 }
264 return references
265 }
266
267 // existsAlternate takes an object directory given in "objs" (read as a single,
268 // line from .git/objects/info/alternates). If that is a satisfiable alternates
269 // directory (i.e., it exists), the directory is returned along with "true". If
270 // not, the empty string and false is returned instead.
271 func existsAlternate(objs string) (string, bool) {
272 objs = strings.TrimSpace(objs)
273 if strings.HasPrefix(objs, "\"") {
274 var err error
275
276 unquote := strings.LastIndex(objs, "\"")
277 if unquote == 0 {
278 return "", false
279 }
280
281 objs, err = strconv.Unquote(objs[:unquote+1])
282 if err != nil {
283 return "", false
284 }
285 }
286
287 storage := filepath.Join(filepath.Dir(objs), "lfs", "objects")
288
289 if tools.DirExists(storage) {
290 return storage, true
291 }
292 return "", false
293 }
294
295 // From a git dir, get the location that objects are to be stored (we will store lfs alongside)
296 // Sometimes there is an additional level of redirect on the .git folder by way of a commondir file
297 // before you find object storage, e.g. 'git worktree' uses this. It redirects to gitdir either by GIT_DIR
298 // (during setup) or .git/git-dir: (during use), but this only contains the index etc, the objects
299 // are found in another git dir via 'commondir'.
300 func resolveGitStorageDir(gitDir string) string {
301 commondirpath := filepath.Join(gitDir, "commondir")
302 if tools.FileExists(commondirpath) && !tools.DirExists(filepath.Join(gitDir, "objects")) {
303 // no git-dir: prefix in commondir
304 storage, err := processGitRedirectFile(commondirpath, "")
305 if err == nil {
306 return storage
307 }
308 }
309 return gitDir
310 }
311
312 func processGitRedirectFile(file, prefix string) (string, error) {
313 data, err := os.ReadFile(file)
314 if err != nil {
315 return "", err
316 }
317
318 contents := string(data)
319 var dir string
320 if len(prefix) > 0 {
321 if !strings.HasPrefix(contents, prefix) {
322 // Prefix required & not found
323 return "", nil
324 }
325 dir = strings.TrimSpace(contents[len(prefix):])
326 } else {
327 dir = strings.TrimSpace(contents)
328 }
329
330 if !filepath.IsAbs(dir) {
331 // The .git file contains a relative path.
332 // Create an absolute path based on the directory the .git file is located in.
333 dir = filepath.Join(filepath.Dir(file), dir)
334 }
335
336 return dir, nil
337 }