| 1 | package command |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "regexp" |
| 6 | "strings" |
| 7 | |
| 8 | gogit "github.com/go-git/go-git/v5" |
| 9 | "github.com/go-git/go-git/v5/config" |
| 10 | "github.com/go-git/go-git/v5/plumbing/transport" |
| 11 | "github.com/go-git/go-git/v5/plumbing/transport/http" |
| 12 | gerr "github.com/isacikgoz/gitbatch/internal/errors" |
| 13 | "github.com/isacikgoz/gitbatch/internal/git" |
| 14 | ) |
| 15 | |
| 16 | var ( |
| 17 | fetchTryCount int |
| 18 | fetchMaxTry = 1 |
| 19 | ) |
| 20 | |
| 21 | // FetchOptions defines the rules for fetch operation |
| 22 | type FetchOptions struct { |
| 23 | // Name of the remote to fetch from. Defaults to origin. |
| 24 | RemoteName string |
| 25 | // Credentials holds the user and password information |
| 26 | Credentials *git.Credentials |
| 27 | // Before fetching, remove any remote-tracking references that no longer |
| 28 | // exist on the remote. |
| 29 | Prune bool |
| 30 | // Show what would be done, without making any changes. |
| 31 | DryRun bool |
| 32 | // Process logs the output to stdout |
| 33 | Progress bool |
| 34 | // Force allows the fetch to update a local branch even when the remote |
| 35 | // branch does not descend from it. |
| 36 | Force bool |
| 37 | // Mode is the command mode |
| 38 | CommandMode Mode |
| 39 | // There should be more room for authentication, tags and progress |
| 40 | } |
| 41 | |
| 42 | // Fetch branches refs from one or more other repositories, along with the |
| 43 | // objects necessary to complete their histories |
| 44 | func Fetch(r *git.Repository, o *FetchOptions) (err error) { |
| 45 | // here we configure fetch operation |
| 46 | // default mode is go-git (this may be configured) |
| 47 | mode := o.CommandMode |
| 48 | fetchTryCount = 0 |
| 49 | // prune and dry run is not supported from go-git yet, rely on old friend |
| 50 | if o.Prune || o.DryRun { |
| 51 | mode = ModeLegacy |
| 52 | } |
| 53 | switch mode { |
| 54 | case ModeLegacy: |
| 55 | err = fetchWithGit(r, o) |
| 56 | return err |
| 57 | case ModeNative: |
| 58 | // this should be the refspec as default, let's give it a try |
| 59 | // TODO: Fix for quick mode, maybe better read config file |
| 60 | var refspec string |
| 61 | if r.State.Branch == nil { |
| 62 | refspec = "+refs/heads/*:refs/remotes/origin/*" |
| 63 | } else { |
| 64 | refspec = "+" + "refs/heads/" + r.State.Branch.Name + ":" + "/refs/remotes/" + r.State.Remote.Name + "/" + r.State.Branch.Name |
| 65 | } |
| 66 | err = fetchWithGoGit(r, o, refspec) |
| 67 | return err |
| 68 | } |
| 69 | return nil |
| 70 | } |
| 71 | |
| 72 | // fetchWithGit is simply a bare git fetch <remote> command which is flexible |
| 73 | // for complex operations, but on the other hand, it ties the app to another |
| 74 | // tool. To avoid that, using native implementation is preferred. |
| 75 | func fetchWithGit(r *git.Repository, options *FetchOptions) (err error) { |
| 76 | args := make([]string, 0) |
| 77 | args = append(args, "fetch") |
| 78 | // parse options to command line arguments |
| 79 | if len(options.RemoteName) > 0 { |
| 80 | args = append(args, options.RemoteName) |
| 81 | } |
| 82 | if options.Prune { |
| 83 | args = append(args, "-p") |
| 84 | } |
| 85 | if options.Force { |
| 86 | args = append(args, "-f") |
| 87 | } |
| 88 | if options.DryRun { |
| 89 | args = append(args, "--dry-run") |
| 90 | } |
| 91 | if out, err := Run(r.AbsPath, "git", args); err != nil { |
| 92 | return gerr.ParseGitError(out, err) |
| 93 | } |
| 94 | r.SetWorkStatus(git.Success) |
| 95 | r.State.Message = "" |
| 96 | // till this step everything should be ok |
| 97 | return r.Refresh() |
| 98 | } |
| 99 | |
| 100 | // fetchWithGoGit is the primary fetch method and refspec is the main feature. |
| 101 | // RefSpec is a mapping from local branches to remote references The format of |
| 102 | // the refspec is an optional +, followed by <src>:<dst>, where <src> is the |
| 103 | // pattern for references on the remote side and <dst> is where those references |
| 104 | // will be written locally. The + tells Git to update the reference even if it |
| 105 | // isn’t a fast-forward. |
| 106 | func fetchWithGoGit(r *git.Repository, options *FetchOptions, refspec string) (err error) { |
| 107 | opt := &gogit.FetchOptions{ |
| 108 | RemoteName: options.RemoteName, |
| 109 | RefSpecs: []config.RefSpec{config.RefSpec(refspec)}, |
| 110 | Force: options.Force, |
| 111 | } |
| 112 | // if any credential is given, let's add it to the git.FetchOptions |
| 113 | if options.Credentials != nil { |
| 114 | protocol, err := git.AuthProtocol(r.State.Remote) |
| 115 | if err != nil { |
| 116 | return err |
| 117 | } |
| 118 | if protocol == git.AuthProtocolHTTP || protocol == git.AuthProtocolHTTPS { |
| 119 | opt.Auth = &http.BasicAuth{ |
| 120 | Username: options.Credentials.User, |
| 121 | Password: options.Credentials.Password, |
| 122 | } |
| 123 | } else { |
| 124 | return gerr.ErrInvalidAuthMethod |
| 125 | } |
| 126 | } |
| 127 | if options.Progress { |
| 128 | opt.Progress = os.Stdout |
| 129 | } |
| 130 | if err := r.Repo.Fetch(opt); err != nil { |
| 131 | if err == gogit.NoErrAlreadyUpToDate { |
| 132 | // Already up-to-date |
| 133 | // TODO: submit a PR for this kind of error, this type of catch is lame |
| 134 | } else if strings.Contains(err.Error(), "couldn't find remote ref") { |
| 135 | // we don't have remote ref, so lets pull other things.. maybe it'd be useful |
| 136 | rp := r.State.Remote.RefSpecs[0] |
| 137 | if fetchTryCount < fetchMaxTry { |
| 138 | fetchTryCount++ |
| 139 | _ = fetchWithGoGit(r, options, rp) |
| 140 | } else { |
| 141 | return err |
| 142 | } |
| 143 | // TODO: submit a PR for this kind of error, this type of catch is lame |
| 144 | } else if strings.Contains(err.Error(), "SSH_AUTH_SOCK") { |
| 145 | // The env variable SSH_AUTH_SOCK is not defined, maybe git can handle this |
| 146 | return fetchWithGit(r, options) |
| 147 | } else if err == transport.ErrAuthenticationRequired { |
| 148 | return gerr.ErrAuthenticationRequired |
| 149 | } else { |
| 150 | return fetchWithGit(r, options) |
| 151 | } |
| 152 | } |
| 153 | r.SetWorkStatus(git.Success) |
| 154 | |
| 155 | ref, _ := r.Repo.Head() |
| 156 | // TODO: fix this, refresh two times not cool |
| 157 | _ = r.Refresh() |
| 158 | uRef := "origin/HEAD" |
| 159 | if r.State.Branch != nil && r.State.Branch.Upstream != nil { |
| 160 | uRef = r.State.Branch.Upstream.Reference.Hash().String()[:7] |
| 161 | } |
| 162 | |
| 163 | msg, err := getFetchMessage(r, ref.Hash().String()[:7], uRef) |
| 164 | if err != nil { |
| 165 | msg = "couldn't get stat" |
| 166 | } |
| 167 | r.State.Message = msg |
| 168 | // till this step everything should be ok |
| 169 | return r.Refresh() |
| 170 | } |
| 171 | |
| 172 | func getFetchMessage(r *git.Repository, ref1, ref2 string) (string, error) { |
| 173 | msg := ref1 + ".." + ref2 + " " |
| 174 | if ref1 == ref2 { |
| 175 | msg = msg + "already up-to-date" |
| 176 | } else { |
| 177 | out, err := DiffStatRefs(r, ref1, ref2) |
| 178 | if err != nil { |
| 179 | return "", err |
| 180 | } |
| 181 | re := regexp.MustCompile(`\r?\n`) |
| 182 | lines := re.Split(out, -1) |
| 183 | last := lines[len(lines)-1] |
| 184 | if len(last) > 0 { |
| 185 | changes := strings.Split(last, ",") |
| 186 | msg = msg + changes[0][1:] |
| 187 | } |
| 188 | } |
| 189 | return msg, nil |
| 190 | } |