-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
77 lines (67 loc) · 1.74 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
"io/ioutil"
"path"
"strconv"
"time"
)
var (
token string
owner string
repo string
images []string
)
func initVar() {
flag.StringVar(&token, "token", "", "GitHub personal access token")
flag.StringVar(&owner, "owner", "", "GitHub repository owner")
flag.StringVar(&repo, "repo", "", "GitHub repository name")
flag.Parse()
images = flag.Args()
if token == "" || owner == "" || repo == "" {
panic("token/owner/repo is empty")
}
}
func initClient() (context.Context, *github.Client) {
ctx := context.Background()
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
return ctx, client
}
func uploadImages(ctx context.Context, client *github.Client, images []string) []string {
urls := make([]string, len(images))
copy(urls, images)
for idx, image := range images {
data, err := ioutil.ReadFile(image)
if err != nil {
fmt.Printf("Error reading file %s: %v", image, err)
continue
}
suffix := path.Ext(image)
timestamp := time.Now().Unix()
_path := fmt.Sprintf("image/%d_%d%s", timestamp, idx, suffix)
message := strconv.FormatInt(timestamp, 10)
options := &github.RepositoryContentFileOptions{Message: &message, Content: data}
commit, _, err := client.Repositories.CreateFile(ctx, owner, repo, _path, options)
if err != nil {
fmt.Printf("Error committing file %s: %v", image, err)
continue
}
urls[idx] = *commit.Content.DownloadURL
}
return urls
}
func main() {
initVar()
ctx, client := initClient()
urls := uploadImages(ctx, client, images)
fmt.Println("Upload Success:")
for _, url := range urls {
fmt.Println(url)
}
}