git-lfs/fs/cleanup.go
brian m. carlson ee362cd707
fs: gracefully handle missing temporary directory
When we are running in a repository where we lack write permissions,
we'll try to clean up temporary files nevertheless.  However, in such a
case, we may not have even been able to create a temporary directory if
one doesn't exist.

With the previous commit, we fixed the hang that occurred here, but we
print an error message like so:

  Error clearing old temp files: stat /tmp/repo/.git/lfs/tmp: no such file or directory

The user probably doesn't care about the fact that we don't have a
temporary directory in this case, and if there were no temporary files
to clean up because there was no temporary directory, then we've already
accomplished our goal.  Let's check for the temporary directory
existing, and if it doesn't, we'll just silently do nothing.
2020-08-06 21:15:06 +00:00

57 lines
1.1 KiB
Go

package fs
import (
"os"
"path/filepath"
"strings"
"time"
"github.com/git-lfs/git-lfs/tools"
"github.com/rubyist/tracerx"
)
func (f *Filesystem) cleanupTmp() error {
tmpdir := f.TempDir()
if len(tmpdir) == 0 {
return nil
}
// No temporary directory? No problem.
if _, err := os.Stat(tmpdir); err != nil && os.IsNotExist(err) {
return nil
}
var walkErr error
tools.FastWalkDir(tmpdir, func(parentDir string, info os.FileInfo, err error) {
if err != nil {
walkErr = err
}
if walkErr != nil || info.IsDir() {
return
}
path := filepath.Join(parentDir, info.Name())
parts := strings.SplitN(info.Name(), "-", 2)
oid := parts[0]
if len(parts) < 2 || len(oid) != 64 {
tracerx.Printf("Removing invalid tmp object file: %s", path)
os.RemoveAll(path)
return
}
fi, err := os.Stat(f.ObjectPathname(oid))
if err == nil && !fi.IsDir() {
tracerx.Printf("Removing existing tmp object file: %s", path)
os.RemoveAll(path)
return
}
if time.Since(info.ModTime()) > time.Hour {
tracerx.Printf("Removing old tmp object file: %s", path)
os.RemoveAll(path)
return
}
})
return walkErr
}