Skip to content

Commit f9da65d

Browse files
authored
Merge pull request #4 from aymanbagabas/push-cmd
feat: add push command
2 parents 7e7057d + 9eba9e2 commit f9da65d

1 file changed

Lines changed: 102 additions & 0 deletions

File tree

cmd/ggit/push.go

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package main
2+
3+
import (
4+
"errors"
5+
6+
"github.com/go-git/go-git/v5"
7+
"github.com/go-git/go-git/v5/config"
8+
"github.com/go-git/go-git/v5/plumbing/transport"
9+
"github.com/spf13/cobra"
10+
"golang.org/x/term"
11+
)
12+
13+
var (
14+
pushProgress bool
15+
pushPrune bool
16+
pushQuiet bool
17+
pushForce bool
18+
)
19+
20+
func init() {
21+
pushCmd.Flags().BoolVarP(&pushQuiet, "quiet", "q", false, "Suppress all output unless an error occurs")
22+
pushCmd.Flags().BoolVarP(&pushProgress, "progress", "", true, "Force show push progress")
23+
pushCmd.Flags().BoolVarP(&pushPrune, "prune", "", false, "Prune remote branches")
24+
pushCmd.Flags().BoolVarP(&pushForce, "force", "f", false, "Force push")
25+
26+
rootCmd.AddCommand(pushCmd)
27+
rootCmd.CompletionOptions.HiddenDefaultCmd = true
28+
}
29+
30+
var pushCmd = &cobra.Command{
31+
Use: "push [<options>] [--] [<repository> [<refspec>...]]",
32+
Short: "Update remote refs along with associated objects",
33+
RunE: func(cmd *cobra.Command, args []string) error {
34+
r, err := git.PlainOpen(".")
35+
if err != nil {
36+
return err
37+
}
38+
39+
var ep *transport.Endpoint
40+
remoteName := git.DefaultRemoteName
41+
if len(args) > 0 {
42+
ep, err = transport.NewEndpoint(args[0])
43+
if err != nil {
44+
// We have a remote name
45+
remoteName = args[0]
46+
}
47+
}
48+
49+
var refspecs []config.RefSpec
50+
if len(args) > 1 {
51+
for _, arg := range args[1:] {
52+
refspecs = append(refspecs, config.RefSpec(arg))
53+
}
54+
}
55+
56+
remote, err := r.Remote(remoteName)
57+
if err != nil {
58+
return err
59+
}
60+
61+
if ep == nil {
62+
// Use the default remote URL
63+
urln := len(remote.Config().URLs) - 1
64+
if urln < 0 {
65+
return errors.New("no remote URLs")
66+
}
67+
68+
ep, err = transport.NewEndpoint(remote.Config().URLs[urln])
69+
if err != nil {
70+
return err
71+
}
72+
}
73+
74+
opts := git.PushOptions{
75+
Auth: defaultAuth(ep),
76+
RemoteName: remoteName,
77+
RefSpecs: refspecs,
78+
Prune: pushPrune,
79+
Force: pushForce,
80+
}
81+
82+
var isatty bool
83+
stderr := cmd.ErrOrStderr()
84+
if f, ok := stderr.(interface {
85+
Fd() uintptr
86+
}); ok {
87+
isatty = term.IsTerminal(int(f.Fd()))
88+
}
89+
90+
if !pushQuiet && (isatty || pushProgress) {
91+
opts.Progress = cmd.ErrOrStderr()
92+
}
93+
94+
err = remote.Push(&opts)
95+
if errors.Is(err, git.NoErrAlreadyUpToDate) {
96+
cmd.PrintErr("Everything up-to-date")
97+
return nil
98+
}
99+
100+
return err
101+
},
102+
}

0 commit comments

Comments
 (0)