|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "github.com/linuxsuren/cgit/pkg" |
| 7 | + "github.com/spf13/cobra" |
| 8 | + "net/url" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +type mirrorOption struct { |
| 13 | + enable bool |
| 14 | + remote string |
| 15 | +} |
| 16 | + |
| 17 | +// NewMirrorCmd returns the mirror command |
| 18 | +func NewMirrorCmd(ctx context.Context) (cmd *cobra.Command) { |
| 19 | + opt := mirrorOption{} |
| 20 | + |
| 21 | + cmd = &cobra.Command{ |
| 22 | + Use: "mirror", |
| 23 | + Short: "Toggle the git mirror", |
| 24 | + RunE: opt.runE, |
| 25 | + } |
| 26 | + |
| 27 | + flags := cmd.Flags() |
| 28 | + flags.BoolVarP(&opt.enable, "enable", "e", true, "Enable/disable the git mirror") |
| 29 | + flags.StringVarP(&opt.remote, "remote", "r", "origin", "The remote of git repository") |
| 30 | + return |
| 31 | +} |
| 32 | + |
| 33 | +func (o *mirrorOption) runE(cmd *cobra.Command, args []string) (err error) { |
| 34 | + var remoteURLStr string |
| 35 | + var remotePushURLStr string |
| 36 | + if remoteURLStr, err = pkg.ExecCommandWithOutput("git", "", "remote", "get-url", o.remote); err != nil { |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + if remotePushURLStr, err = pkg.ExecCommandWithOutput("git", "", "remote", "get-url", "--push", o.remote); err != nil { |
| 41 | + return |
| 42 | + } |
| 43 | + // remove the .git tail |
| 44 | + remoteURLStr = strings.TrimSuffix(remoteURLStr, ".git") |
| 45 | + |
| 46 | + gitProtocol := strings.HasPrefix(remoteURLStr, "git@") |
| 47 | + if gitProtocol { |
| 48 | + remoteURLStr = strings. ReplaceAll( remoteURLStr, "[email protected]:", "https://github.com/") |
| 49 | + } |
| 50 | + |
| 51 | + var remoteURL *url.URL |
| 52 | + if remoteURL, err = url.Parse(remoteURLStr); err != nil { |
| 53 | + cmd.Println("error with parse URL", remoteURLStr) |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + if o.enable { |
| 58 | + remoteURL.Host = "github.com.cnpmjs.org" |
| 59 | + } else { |
| 60 | + remoteURL.Host = "github.com" |
| 61 | + } |
| 62 | + |
| 63 | + targetRemoteURLStr := remoteURL.String() |
| 64 | + if strings.HasPrefix(remotePushURLStr, "git@") && !o.enable { |
| 65 | + // the mirror git server does not support git protocol |
| 66 | + targetRemoteURLStr = strings.ReplaceAll(targetRemoteURLStr, fmt.Sprintf("https://%s/", remoteURL.Host), |
| 67 | + fmt.Sprintf("git@%s:", remoteURL.Host)) |
| 68 | + targetRemoteURLStr += ".git" |
| 69 | + } |
| 70 | + |
| 71 | + if err = pkg.ExecCommandInDir("git", "", "remote", "set-url", o.remote, targetRemoteURLStr); err != nil { |
| 72 | + return |
| 73 | + } |
| 74 | + if err = pkg.ExecCommandInDir("git", "", "remote", "set-url", "--push", o.remote, remotePushURLStr); err != nil { |
| 75 | + return |
| 76 | + } |
| 77 | + return |
| 78 | +} |
0 commit comments