git-lfs/commands/command_fsck.go

121 lines
2.5 KiB
Go
Raw Normal View History

2015-05-04 05:36:34 +00:00
package commands
import (
"crypto/sha256"
"encoding/hex"
"io"
"os"
"path/filepath"
2016-11-15 17:01:18 +00:00
"github.com/git-lfs/git-lfs/git"
"github.com/git-lfs/git-lfs/lfs"
"github.com/git-lfs/git-lfs/localstorage"
"github.com/spf13/cobra"
2015-05-04 05:36:34 +00:00
)
var (
2015-05-08 16:35:19 +00:00
fsckDryRun bool
2015-05-04 05:36:34 +00:00
)
// TODO(zeroshirts): 'git fsck' reports status (percentage, current#/total) as
// it checks... we should do the same, as we are rehashing potentially gigs and
// gigs of content.
//
// NOTE(zeroshirts): Ideally git would have hooks for fsck such that we could
// chain a lfs-fsck, but I don't think it does.
func fsckCommand(cmd *cobra.Command, args []string) {
lfs.InstallHooks(false)
requireInRepo()
2015-05-04 05:36:34 +00:00
ref, err := git.CurrentRef()
if err != nil {
ExitWithError(err)
2015-05-04 05:36:34 +00:00
}
var corruptOids []string
gitscanner := lfs.NewGitScanner(func(p *lfs.WrappedPointer, err error) {
if err == nil {
var pointerOk bool
pointerOk, err = fsckPointer(p.Name, p.Oid)
if !pointerOk {
corruptOids = append(corruptOids, p.Oid)
}
}
2015-05-04 05:36:34 +00:00
if err != nil {
Panic(err, "Error checking Git LFS files")
}
})
if err := gitscanner.ScanRef(ref.Sha, nil); err != nil {
ExitWithError(err)
}
2015-05-04 05:36:34 +00:00
if err := gitscanner.ScanIndex("HEAD", nil); err != nil {
ExitWithError(err)
}
2015-05-04 05:36:34 +00:00
gitscanner.Close()
2015-05-04 05:36:34 +00:00
if len(corruptOids) == 0 {
Print("Git LFS fsck OK")
return
}
2015-05-04 05:36:34 +00:00
if fsckDryRun {
return
}
storageConfig := localstorage.NewConfig(cfg.Git)
badDir := filepath.Join(storageConfig.LfsStorageDir, "bad")
Print("Moving corrupt objects to %s", badDir)
if err := os.MkdirAll(badDir, 0755); err != nil {
ExitWithError(err)
}
for _, oid := range corruptOids {
badFile := filepath.Join(badDir, oid)
if err := os.Rename(lfs.LocalMediaPathReadOnly(oid), badFile); err != nil {
ExitWithError(err)
2015-05-04 05:36:34 +00:00
}
}
}
func fsckPointer(name, oid string) (bool, error) {
path := lfs.LocalMediaPathReadOnly(oid)
Debug("Examining %v (%v)", name, path)
f, err := os.Open(path)
if pErr, pOk := err.(*os.PathError); pOk {
Print("Object %s (%s) could not be checked: %s", name, oid, pErr.Err)
return false, nil
}
if err != nil {
return false, err
}
oidHash := sha256.New()
_, err = io.Copy(oidHash, f)
f.Close()
2015-05-04 05:36:34 +00:00
if err != nil {
return false, err
}
recalculatedOid := hex.EncodeToString(oidHash.Sum(nil))
if recalculatedOid == oid {
return true, nil
2015-05-04 05:36:34 +00:00
}
Print("Object %s (%s) is corrupt", name, oid)
return false, nil
2015-05-04 05:36:34 +00:00
}
func init() {
RegisterCommand("fsck", fsckCommand, func(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&fsckDryRun, "dry-run", "d", false, "List corrupt objects without deleting them.")
})
2015-05-04 05:36:34 +00:00
}