/
dgit.go
163 lines (142 loc) · 3.74 KB
/
dgit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package cmd
import (
"archive/tar"
"compress/gzip"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/CiroLee/go-termts/utils"
"github.com/briandowns/spinner"
"github.com/spf13/cobra"
)
type UserAndRepo struct {
userName string
repository string
}
type RepoInfo struct {
Name string `json:"name"`
DefaultBranch string `json:"default_branch"`
}
var branchName string
var dst string
func init() {
dGitCmd.PersistentFlags().StringVar(&branchName, "branch", "", "branch name, default is repos's default branch")
dGitCmd.PersistentFlags().StringVar(&dst, "dst", "", "destination directory, default is current directory")
rootCmd.AddCommand(dGitCmd)
}
var loading = spinner.New(spinner.CharSets[26], 200*time.Millisecond)
var dGitCmd = &cobra.Command{
Use: "dgit",
Short: "download github repository",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
repoUrl, err := transRepoUrl(args[0])
if err != nil {
utils.CommonExit(err)
}
info, err := getUserAndRepo(repoUrl)
if err != nil {
log.Fatal(err)
}
if branchName == "" {
branchName = getDefaultBranch(info.userName, info.repository)
}
if dst == "" {
dst, _ = os.Getwd()
}
var downloadUrl = fmt.Sprintf("%s/archive/%s.tar.gz", repoUrl, branchName)
err = downloadRepository(downloadUrl, dst, info.repository, branchName)
if err != nil {
log.Fatal("download failed: ", err)
}
},
}
func downloadRepository(gitUrl, dst, repository, branch string) error {
loading.Prefix = "download"
loading.Start()
resp, err := http.Get(gitUrl)
if err != nil {
return err
}
defer resp.Body.Close()
unzipped, err := gzip.NewReader(resp.Body)
if err != nil {
return err
}
tarReader := tar.NewReader(unzipped)
for {
header, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
name := header.Name
branch = strings.ReplaceAll(branch, "/", "-")
if strings.HasPrefix(name, fmt.Sprintf("%s-%s", repository, branch)) {
name = strings.TrimPrefix(name, fmt.Sprintf("%s-%s/", repository, branch))
}
// process every file/folder in tar
switch header.Typeflag {
case tar.TypeDir:
// create dir
err := os.MkdirAll(filepath.Join(dst, name), 0755)
if err != nil {
return err
}
case tar.TypeReg:
// write file
outFile, err := os.Create(filepath.Join(dst, name))
if err != nil {
return err
}
if _, err := io.Copy(outFile, tarReader); err != nil {
outFile.Close()
return err
}
outFile.Close()
}
}
loading.Stop()
return nil
}
func getDefaultBranch(userName, repository string) string {
gitUrl := fmt.Sprintf("https://api.github.com/repos/%s/%s", userName, repository)
resp := utils.GetJson[RepoInfo](gitUrl, "wait")
return resp.DefaultBranch
}
func getUserAndRepo(repoUrl string) (UserAndRepo, error) {
parseURL, err := url.ParseRequestURI(repoUrl)
if err != nil {
return UserAndRepo{}, err
}
if parseURL.Hostname() != "github.com" {
log.Fatal("it is not an valid github repository url, please check")
}
rest := parseURL.Path[1:]
rest = strings.Replace(rest, ".git", "", 1)
userName := strings.Split(rest, "/")[0]
repo := strings.Split(rest, "/")[1]
return UserAndRepo{userName: userName, repository: repo}, nil
}
func transRepoUrl(url string) (string, error) {
if url == "" {
return "", errors.New("invalid repo url")
} else if strings.HasPrefix(url, "git@") && strings.HasSuffix(url, ".git") {
url, _ = strings.CutPrefix(url, "git@")
url, _ = strings.CutSuffix(url, ".git")
url = strings.ReplaceAll(url, ":", "/")
url = "https://" + url
} else if strings.HasPrefix(url, "https://") && strings.HasSuffix(url, ".git") {
url, _ = strings.CutSuffix(url, ".git")
}
return url, nil
}