git-lfs/lfs/setup.go

93 lines
1.9 KiB
Go
Raw Normal View History

2015-03-19 19:30:55 +00:00
package lfs
import (
"errors"
"fmt"
2015-03-19 19:30:55 +00:00
"github.com/github/git-lfs/git"
2014-06-04 14:29:19 +00:00
"io/ioutil"
"os"
"path/filepath"
"regexp"
)
2014-06-04 14:29:19 +00:00
var (
2014-06-05 18:48:23 +00:00
valueRegexp = regexp.MustCompile("\\Agit[\\-\\s]media")
prePushHook = []byte("#!/bin/sh\ngit lfs push --stdin \"$@\"\n")
2014-06-05 18:48:23 +00:00
NotInARepositoryError = errors.New("Not in a repository")
2014-06-04 14:29:19 +00:00
)
2014-06-05 18:48:23 +00:00
type HookExists struct {
Name string
Path string
}
func (e *HookExists) Error() string {
return fmt.Sprintf("Hook already exists: %s", e.Name)
}
func InstallHooks(force bool) error {
if !InRepo() {
2014-06-05 18:48:23 +00:00
return NotInARepositoryError
}
if err := os.MkdirAll(filepath.Join(LocalGitDir, "hooks"), 0755); err != nil {
return err
}
2014-06-04 14:29:19 +00:00
hookPath := filepath.Join(LocalGitDir, "hooks", "pre-push")
if _, err := os.Stat(hookPath); err == nil && !force {
2014-06-05 18:48:23 +00:00
return &HookExists{"pre-push", hookPath}
2014-06-04 14:29:19 +00:00
} else {
2014-06-05 18:48:23 +00:00
return ioutil.WriteFile(hookPath, prePushHook, 0755)
2014-06-04 14:29:19 +00:00
}
}
2014-06-05 18:48:23 +00:00
func InstallFilters() error {
var err error
err = setFilter("clean")
if err == nil {
err = setFilter("smudge")
}
if err == nil {
err = requireFilters()
}
return err
}
2014-06-05 18:48:23 +00:00
func setFilter(filterName string) error {
2015-03-19 19:30:55 +00:00
key := fmt.Sprintf("filter.lfs.%s", filterName)
value := fmt.Sprintf("git lfs %s %%f", filterName)
existing := git.Config.Find(key)
if shouldReset(existing) {
git.Config.UnsetGlobal(key)
git.Config.SetGlobal(key, value)
} else if existing != value {
2014-06-05 18:48:23 +00:00
return fmt.Errorf("The %s filter should be \"%s\" but is \"%s\"", filterName, value, existing)
}
2014-06-05 18:48:23 +00:00
return nil
}
2014-06-05 18:48:23 +00:00
func requireFilters() error {
2015-03-19 19:30:55 +00:00
key := "filter.lfs.required"
value := "true"
existing := git.Config.Find(key)
if shouldReset(existing) {
git.Config.UnsetGlobal(key)
git.Config.SetGlobal(key, value)
} else if existing != value {
2015-03-19 19:30:55 +00:00
return errors.New("Git LFS filters should be required but are not.")
}
2014-06-05 18:48:23 +00:00
return nil
}
func shouldReset(value string) bool {
if len(value) == 0 {
return true
}
return valueRegexp.MatchString(value)
}