| 1 | // Package tools contains other helper functions too small to justify their own package |
| 2 | // NOTE: Subject to change, do not rely on this package from outside git-lfs source |
| 3 | package tools |
| 4 | |
| 5 | import ( |
| 6 | "encoding/hex" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "os/user" |
| 11 | "path/filepath" |
| 12 | "runtime" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "sync/atomic" |
| 17 | |
| 18 | "github.com/git-lfs/git-lfs/v3/errors" |
| 19 | "github.com/git-lfs/git-lfs/v3/tr" |
| 20 | ) |
| 21 | |
| 22 | // FileOrDirExists determines if a file/dir exists, returns IsDir() results too. |
| 23 | func FileOrDirExists(path string) (exists bool, isDir bool) { |
| 24 | fi, err := os.Stat(path) |
| 25 | if err != nil { |
| 26 | return false, false |
| 27 | } else { |
| 28 | return true, fi.IsDir() |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // FileExists determines if a file (NOT dir) exists. |
| 33 | func FileExists(path string) bool { |
| 34 | ret, isDir := FileOrDirExists(path) |
| 35 | return ret && !isDir |
| 36 | } |
| 37 | |
| 38 | // DirExists determines if a dir (NOT file) exists. |
| 39 | func DirExists(path string) bool { |
| 40 | ret, isDir := FileOrDirExists(path) |
| 41 | return ret && isDir |
| 42 | } |
| 43 | |
| 44 | // FileExistsOfSize determines if a file exists and is of a specific size. |
| 45 | func FileExistsOfSize(path string, sz int64) bool { |
| 46 | fi, err := os.Stat(path) |
| 47 | |
| 48 | if err != nil { |
| 49 | return false |
| 50 | } |
| 51 | |
| 52 | return !fi.IsDir() && fi.Size() == sz |
| 53 | } |
| 54 | |
| 55 | // ResolveSymlinks ensures that if the path supplied is a symlink, it is |
| 56 | // resolved to the actual concrete path |
| 57 | func ResolveSymlinks(path string) string { |
| 58 | if len(path) == 0 { |
| 59 | return path |
| 60 | } |
| 61 | |
| 62 | if resolved, err := CanonicalizeSystemPath(path); err == nil { |
| 63 | return resolved |
| 64 | } |
| 65 | return path |
| 66 | } |
| 67 | |
| 68 | // RenameFileCopyPermissions moves srcfile to destfile, replacing destfile if |
| 69 | // necessary and also copying the permissions of destfile if it already exists |
| 70 | func RenameFileCopyPermissions(srcfile, destfile string) error { |
| 71 | info, err := os.Stat(destfile) |
| 72 | if os.IsNotExist(err) { |
| 73 | // no original file |
| 74 | } else if err != nil { |
| 75 | return err |
| 76 | } else { |
| 77 | if err := os.Chmod(srcfile, info.Mode()); err != nil { |
| 78 | return errors.New(tr.Tr.Get("can't set filemode on file %q: %v", srcfile, err)) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | if err := RobustRename(srcfile, destfile); err != nil { |
| 83 | return errors.New(tr.Tr.Get("cannot replace %q with %q: %v", destfile, srcfile, err)) |
| 84 | } |
| 85 | return nil |
| 86 | } |
| 87 | |
| 88 | // CleanPaths splits the given `paths` argument by the delimiter argument, and |
| 89 | // then "cleans" that path according to the path.Clean function (see |
| 90 | // https://golang.org/pkg/path#Clean). |
| 91 | // Note always cleans to '/' path separators regardless of platform (git friendly) |
| 92 | func CleanPaths(paths, delim string) (cleaned []string) { |
| 93 | // If paths is an empty string, splitting it will yield [""], which will |
| 94 | // become the path ".". To avoid this, bail out if trimmed paths |
| 95 | // argument is empty. |
| 96 | if paths = strings.TrimSpace(paths); len(paths) == 0 { |
| 97 | return |
| 98 | } |
| 99 | |
| 100 | for _, part := range strings.Split(paths, delim) { |
| 101 | part = strings.TrimSpace(part) |
| 102 | |
| 103 | // Remove trailing `/` or `\`, but only the first one. |
| 104 | for _, sep := range []string{`/`, `\`} { |
| 105 | if strings.HasSuffix(part, sep) { |
| 106 | part = strings.TrimSuffix(part, sep) |
| 107 | break |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | cleaned = append(cleaned, part) |
| 112 | } |
| 113 | |
| 114 | return cleaned |
| 115 | } |
| 116 | |
| 117 | // repositoryPermissionFetcher is an interface that matches the configuration |
| 118 | // object and can be used to fetch repository permissions. |
| 119 | type repositoryPermissionFetcher interface { |
| 120 | RepositoryPermissions(executable bool) os.FileMode |
| 121 | } |
| 122 | |
| 123 | // Mkdir makes a directory with the |
| 124 | // permissions specified by the core.sharedRepository setting. |
| 125 | func Mkdir(path string, config repositoryPermissionFetcher) error { |
| 126 | umask := 0777 & ^config.RepositoryPermissions(true) |
| 127 | return doWithUmask(int(umask), func() error { |
| 128 | return os.Mkdir(path, config.RepositoryPermissions(true)) |
| 129 | }) |
| 130 | } |
| 131 | |
| 132 | // MkdirAll makes a directory and any intervening directories with the |
| 133 | // permissions specified by the core.sharedRepository setting. |
| 134 | func MkdirAll(path string, config repositoryPermissionFetcher) error { |
| 135 | umask := 0777 & ^config.RepositoryPermissions(true) |
| 136 | return doWithUmask(int(umask), func() error { |
| 137 | return os.MkdirAll(path, config.RepositoryPermissions(true)) |
| 138 | }) |
| 139 | } |
| 140 | |
| 141 | var ( |
| 142 | // currentUser is a wrapper over user.Current(), but instead uses the |
| 143 | // value of os.Getenv("HOME") for the returned *user.User's "HomeDir" |
| 144 | // member. |
| 145 | currentUser func() (*user.User, error) = func() (*user.User, error) { |
| 146 | u := &user.User{} |
| 147 | u.HomeDir = os.Getenv("HOME") |
| 148 | return u, nil |
| 149 | } |
| 150 | lookupUser func(who string) (*user.User, error) = user.Lookup |
| 151 | lookupConfigHome func() string = func() string { |
| 152 | return os.Getenv("XDG_CONFIG_HOME") |
| 153 | } |
| 154 | ) |
| 155 | |
| 156 | // ExpandPath returns a copy of path with any references to the current user's |
| 157 | // home directory (spelled "~"), or a named user's home directory (spelled |
| 158 | // "~user") in the path, sanitized to the calling filesystem's path separator |
| 159 | // preference. |
| 160 | // |
| 161 | // If the "expand" argument is given as true, the resolved path to the named |
| 162 | // user's home directory will expanded with filepath.EvalSymlinks. |
| 163 | // |
| 164 | // If either the current or named user does not have a home directory, an error |
| 165 | // will be returned. |
| 166 | // |
| 167 | // Otherwise, the error returned will be nil, and the string returned will be |
| 168 | // the expanded path. |
| 169 | func ExpandPath(path string, expand bool) (string, error) { |
| 170 | if len(path) == 0 || path[0] != '~' { |
| 171 | return path, nil |
| 172 | } |
| 173 | |
| 174 | var username string |
| 175 | if slash := strings.Index(path[1:], "/"); slash > -1 { |
| 176 | username = path[1 : slash+1] |
| 177 | } else { |
| 178 | username = path[1:] |
| 179 | } |
| 180 | |
| 181 | var ( |
| 182 | who *user.User |
| 183 | err error |
| 184 | ) |
| 185 | if len(username) == 0 { |
| 186 | who, err = currentUser() |
| 187 | } else { |
| 188 | who, err = lookupUser(username) |
| 189 | } |
| 190 | |
| 191 | if err != nil { |
| 192 | return "", errors.Wrap(err, tr.Tr.Get("could not find user %s", username)) |
| 193 | } |
| 194 | |
| 195 | homedir := who.HomeDir |
| 196 | if expand { |
| 197 | homedir, err = filepath.EvalSymlinks(homedir) |
| 198 | if err != nil { |
| 199 | return "", errors.Wrap(err, tr.Tr.Get("cannot eval symlinks for %s", homedir)) |
| 200 | } |
| 201 | } |
| 202 | return filepath.Join(homedir, path[len(username)+1:]), nil |
| 203 | } |
| 204 | |
| 205 | // ExpandConfigPath returns a copy of path expanded as with ExpandPath. If the |
| 206 | // path is empty, the default path is looked up inside $XDG_CONFIG_HOME, or |
| 207 | // ~/.config if that is not set. |
| 208 | func ExpandConfigPath(path, defaultPath string) (string, error) { |
| 209 | if path != "" { |
| 210 | return ExpandPath(path, false) |
| 211 | } |
| 212 | |
| 213 | configHome := lookupConfigHome() |
| 214 | if configHome != "" { |
| 215 | return filepath.Join(configHome, defaultPath), nil |
| 216 | } |
| 217 | |
| 218 | return ExpandPath(fmt.Sprintf("~/.config/%s", defaultPath), false) |
| 219 | } |
| 220 | |
| 221 | // VerifyFileHash reads a file and verifies whether the SHA is correct |
| 222 | // Returns an error if there is a problem |
| 223 | func VerifyFileHash(oid, path string) error { |
| 224 | f, err := os.Open(path) |
| 225 | if err != nil { |
| 226 | return err |
| 227 | } |
| 228 | defer f.Close() |
| 229 | |
| 230 | h := NewLfsContentHash() |
| 231 | _, err = io.Copy(h, f) |
| 232 | if err != nil { |
| 233 | return err |
| 234 | } |
| 235 | |
| 236 | calcOid := hex.EncodeToString(h.Sum(nil)) |
| 237 | if calcOid != oid { |
| 238 | return errors.New(tr.Tr.Get("file %q has an invalid hash %s, expected %s", path, calcOid, oid)) |
| 239 | } |
| 240 | |
| 241 | return nil |
| 242 | } |
| 243 | |
| 244 | // FastWalkCallback is the signature for the callback given to FastWalkGitRepo() |
| 245 | type FastWalkCallback func(parentDir string, info os.FileInfo, err error) |
| 246 | |
| 247 | // FastWalkDir is a more optimal implementation of filepath.Walk. |
| 248 | // The callback guaranteed to be called sequentially. The function returns |
| 249 | // once all files and errors have triggered callbacks. |
| 250 | // It differs in the following ways: |
| 251 | // - Uses goroutines to parallelise large dirs and descent into subdirs |
| 252 | // - Does not provide sorted output; parents will always be before children but |
| 253 | // there are no other guarantees. Use parentDir argument in the callback to |
| 254 | // determine absolute path rather than tracking it yourself |
| 255 | // |
| 256 | // dir - Absolute path to the directory |
| 257 | func FastWalkDir(dir string, cb FastWalkCallback) { |
| 258 | fastWalkCallback(fastWalkDir(dir), cb) |
| 259 | } |
| 260 | |
| 261 | // fastWalkCallback calls the FastWalkCallback "cb" for all files found by the |
| 262 | // given *fastWalker, "walker". |
| 263 | func fastWalkCallback(walker *fastWalker, cb FastWalkCallback) { |
| 264 | for file := range walker.ch { |
| 265 | cb(file.ParentDir, file.Info, file.Err) |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | // Returned from FastWalk with parent directory context |
| 270 | // This is needed because FastWalk can provide paths out of order so the |
| 271 | // parent dir cannot be implied |
| 272 | type fastWalkInfo struct { |
| 273 | ParentDir string |
| 274 | Info os.FileInfo |
| 275 | Err error |
| 276 | } |
| 277 | |
| 278 | type fastWalker struct { |
| 279 | dir string |
| 280 | ch chan fastWalkInfo |
| 281 | limit int32 |
| 282 | cur *int32 |
| 283 | wg *sync.WaitGroup |
| 284 | } |
| 285 | |
| 286 | // fastWalkDir walks the contents of a dir |
| 287 | // |
| 288 | // dir - Absolute path to the directory |
| 289 | func fastWalkDir(dir string) *fastWalker { |
| 290 | limit, _ := strconv.Atoi(os.Getenv("LFS_FASTWALK_LIMIT")) |
| 291 | if limit < 1 { |
| 292 | limit = runtime.GOMAXPROCS(-1) * 20 |
| 293 | } |
| 294 | |
| 295 | c := int32(0) |
| 296 | w := &fastWalker{ |
| 297 | dir: dir, |
| 298 | limit: int32(limit), |
| 299 | cur: &c, |
| 300 | ch: make(chan fastWalkInfo, 256), |
| 301 | wg: &sync.WaitGroup{}, |
| 302 | } |
| 303 | |
| 304 | go func() { |
| 305 | defer w.Wait() |
| 306 | |
| 307 | dirFi, err := os.Stat(w.dir) |
| 308 | if err != nil { |
| 309 | w.ch <- fastWalkInfo{Err: err} |
| 310 | return |
| 311 | } |
| 312 | |
| 313 | w.Walk(true, "", dirFi) |
| 314 | }() |
| 315 | return w |
| 316 | } |
| 317 | |
| 318 | // Walk is the main recursive implementation of fast walk. Sends the file/dir |
| 319 | // and any contents to the channel. Increments waitg.Add(1) for each new |
| 320 | // goroutine launched internally |
| 321 | // |
| 322 | // dir - Relative path inside the directory being walked |
| 323 | func (w *fastWalker) Walk(isInitialDir bool, dir string, itemFi os.FileInfo) { |
| 324 | |
| 325 | var fullPath string // Absolute path to the current file or dir |
| 326 | var parentDir string // Absolute path to the parent of the current item |
| 327 | if isInitialDir { |
| 328 | fullPath = w.dir |
| 329 | } else { |
| 330 | parentDir = join(w.dir, dir) |
| 331 | fullPath = join(parentDir, itemFi.Name()) |
| 332 | } |
| 333 | |
| 334 | w.ch <- fastWalkInfo{ParentDir: parentDir, Info: itemFi} |
| 335 | |
| 336 | if !itemFi.IsDir() { |
| 337 | // Nothing more to do if this is not a dir |
| 338 | return |
| 339 | } |
| 340 | |
| 341 | var childDir string |
| 342 | if !isInitialDir { |
| 343 | childDir = join(dir, itemFi.Name()) |
| 344 | } |
| 345 | |
| 346 | // The absolute optimal way to scan would be File.Readdirnames but we |
| 347 | // still need the Stat() to know whether something is a dir, so use |
| 348 | // File.Readdir instead. Means we can provide os.FileInfo to callers like |
| 349 | // filepath.Walk as a bonus. |
| 350 | df, err := os.Open(fullPath) |
| 351 | if err != nil { |
| 352 | w.ch <- fastWalkInfo{Err: err} |
| 353 | return |
| 354 | } |
| 355 | |
| 356 | // The number of items in a dir we process in each goroutine |
| 357 | jobSize := 100 |
| 358 | for children, err := df.Readdir(jobSize); err == nil; children, err = df.Readdir(jobSize) { |
| 359 | // Parallelise all dirs, and chop large dirs into batches |
| 360 | w.walk(children, func(subitems []os.FileInfo) { |
| 361 | for _, childFi := range subitems { |
| 362 | w.Walk(false, childDir, childFi) |
| 363 | } |
| 364 | }) |
| 365 | } |
| 366 | |
| 367 | df.Close() |
| 368 | if err != nil && err != io.EOF { |
| 369 | w.ch <- fastWalkInfo{Err: err} |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | func (w *fastWalker) walk(children []os.FileInfo, fn func([]os.FileInfo)) { |
| 374 | cur := atomic.AddInt32(w.cur, 1) |
| 375 | if cur > w.limit { |
| 376 | fn(children) |
| 377 | atomic.AddInt32(w.cur, -1) |
| 378 | return |
| 379 | } |
| 380 | |
| 381 | w.wg.Add(1) |
| 382 | go func() { |
| 383 | fn(children) |
| 384 | w.wg.Done() |
| 385 | atomic.AddInt32(w.cur, -1) |
| 386 | }() |
| 387 | } |
| 388 | |
| 389 | func (w *fastWalker) Wait() { |
| 390 | w.wg.Wait() |
| 391 | close(w.ch) |
| 392 | } |
| 393 | |
| 394 | func join(paths ...string) string { |
| 395 | ne := make([]string, 0, len(paths)) |
| 396 | |
| 397 | for _, p := range paths { |
| 398 | if len(p) > 0 { |
| 399 | ne = append(ne, p) |
| 400 | } |
| 401 | } |
| 402 | return strings.Join(ne, "/") |
| 403 | } |
| 404 | |
| 405 | // SetFileWriteFlag changes write permissions on a file |
| 406 | // Used to make a file read-only or not. When writeEnabled = false, the write |
| 407 | // bit is removed for all roles. When writeEnabled = true, the behaviour is |
| 408 | // different per platform: |
| 409 | // On Mac & Linux, the write bit is set only on the owner as per default umask. |
| 410 | // All other bits are unaffected. |
| 411 | // On Windows, all the write bits are set since Windows doesn't support Unix permissions. |
| 412 | func SetFileWriteFlag(path string, writeEnabled bool) error { |
| 413 | stat, err := os.Stat(path) |
| 414 | if err != nil { |
| 415 | return err |
| 416 | } |
| 417 | mode := uint32(stat.Mode()) |
| 418 | |
| 419 | if (writeEnabled && (mode&0200) > 0) || |
| 420 | (!writeEnabled && (mode&0222) == 0) { |
| 421 | // no change needed |
| 422 | return nil |
| 423 | } |
| 424 | |
| 425 | if writeEnabled { |
| 426 | mode = mode | 0200 // set owner write only |
| 427 | // Go's own Chmod makes Windows set all though |
| 428 | } else { |
| 429 | mode = mode &^ 0222 // disable all write |
| 430 | } |
| 431 | return os.Chmod(path, os.FileMode(mode)) |
| 432 | } |
| 433 | |
| 434 | // TempFile creates a temporary file in specified directory with proper permissions for the repository. |
| 435 | // On success, it returns an open, non-nil *os.File, and the caller is responsible |
| 436 | // for closing and/or removing it. On failure, the temporary file is |
| 437 | // automatically cleaned up and an error returned. |
| 438 | // |
| 439 | // This function is designed to handle only temporary files that will be renamed |
| 440 | // into place later somewhere within the Git repository. |
| 441 | func TempFile(dir, pattern string, cfg repositoryPermissionFetcher) (*os.File, error) { |
| 442 | tmp, err := os.CreateTemp(dir, pattern) |
| 443 | if err != nil { |
| 444 | return nil, err |
| 445 | } |
| 446 | |
| 447 | perms := cfg.RepositoryPermissions(false) |
| 448 | err = os.Chmod(tmp.Name(), perms) |
| 449 | if err != nil { |
| 450 | tmp.Close() |
| 451 | os.Remove(tmp.Name()) |
| 452 | return nil, err |
| 453 | } |
| 454 | return tmp, nil |
| 455 | } |
| 456 | |
| 457 | // ExecutablePermissions takes a set of Unix permissions (which may or may not |
| 458 | // have the executable bits set) and maps them into a set of permissions in |
| 459 | // which the executable bits are set, using the same technique as Git does. |
| 460 | func ExecutablePermissions(perms os.FileMode) os.FileMode { |
| 461 | // Copy read bits to executable bits. |
| 462 | return perms | ((perms & 0444) >> 2) |
| 463 | } |
| 464 | |
| 465 | // CanonicalizePath takes a path and produces a canonical absolute path, |
| 466 | // performing any OS- or environment-specific path transformations (within the |
| 467 | // limitations of the Go standard library). If the path is empty, it returns |
| 468 | // the empty path with no error. If missingOk is true, then if the |
| 469 | // canonicalized path does not exist, an absolute path is given instead. |
| 470 | func CanonicalizePath(path string, missingOk bool) (string, error) { |
| 471 | path, err := TranslateCygwinPath(path) |
| 472 | if err != nil { |
| 473 | return "", err |
| 474 | } |
| 475 | if len(path) > 0 { |
| 476 | path, err := filepath.Abs(path) |
| 477 | if err != nil { |
| 478 | return "", err |
| 479 | } |
| 480 | result, err := CanonicalizeSystemPath(path) |
| 481 | if err != nil && os.IsNotExist(err) && missingOk { |
| 482 | return path, nil |
| 483 | } |
| 484 | return result, err |
| 485 | } |
| 486 | return "", nil |
| 487 | } |
| 488 | |
| 489 | const ( |
| 490 | windowsPrefix = `.\` |
| 491 | nixPrefix = `./` |
| 492 | ) |
| 493 | |
| 494 | // TrimCurrentPrefix removes a leading prefix of "./" or ".\" (referring to the |
| 495 | // current directory in a platform independent manner). |
| 496 | // |
| 497 | // It is useful for callers such as "git lfs track" and "git lfs untrack", that |
| 498 | // wish to compare filepaths and/or attributes patterns without cleaning across |
| 499 | // multiple platforms. |
| 500 | func TrimCurrentPrefix(p string) string { |
| 501 | if strings.HasPrefix(p, windowsPrefix) { |
| 502 | return strings.TrimPrefix(p, windowsPrefix) |
| 503 | } |
| 504 | return strings.TrimPrefix(p, nixPrefix) |
| 505 | } |