package commands
import (
"bufio"
"io"
"os"
"strings"
"github.com/git-lfs/git-lfs/v3/git"
"github.com/git-lfs/git-lfs/v3/tr"
"github.com/rubyist/tracerx"
"github.com/spf13/cobra"
)
var (
prePushDryRun = false
)
func prePushCommand(cmd *cobra.Command, args []string) {
if len(args) == 0 {
Print(tr.Tr.Get("This should be run through Git's pre-push hook. Run `git lfs update` to install it."))
os.Exit(1)
}
if cfg.Os.Bool("GIT_LFS_SKIP_PUSH", false) {
return
}
requireGitVersion()
remote, _ := git.MapRemoteURL(args[0], true)
if err := cfg.SetValidPushRemote(remote); err != nil {
Exit(tr.Tr.Get("Invalid remote name %q: %s", args[0], err))
}
ctx := newUploadContext(prePushDryRun)
updates := prePushRefs(os.Stdin)
if err := uploadForRefUpdates(ctx, updates, false); err != nil {
ExitWithError(err)
}
}
func prePushRefs(r io.Reader) []*git.RefUpdate {
scanner := bufio.NewScanner(r)
refs := make([]*git.RefUpdate, 0, 1)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) == 0 {
continue
}
tracerx.Printf("pre-push: %s", line)
localRef, remoteRef := decodeRefs(line)
if git.IsZeroObjectID(localRef.Sha) {
continue
}
refs = append(refs, git.NewRefUpdate(cfg.Git, cfg.PushRemote(), localRef, remoteRef))
}
return refs
}
func decodeRefs(input string) (*git.Ref, *git.Ref) {
refs := strings.Split(strings.TrimSpace(input), " ")
for len(refs) < 4 {
refs = append(refs, "")
}
localRef := git.ParseRef(refs[0], refs[1])
remoteRef := git.ParseRef(refs[2], refs[3])
return localRef, remoteRef
}
func init() {
RegisterCommand("pre-push", prePushCommand, func(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&prePushDryRun, "dry-run", "d", false, "Do everything except actually send the updates")
})
}