-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
97 lines (83 loc) · 2.15 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
)
type _params struct {
homedir string
update bool
params string
user string
disableCache bool
cleanCache bool
}
var params _params
func parseFlag() {
dir, err := os.UserHomeDir()
if err != nil {
panic("cannot find homedir")
}
params.homedir = dir
flag.BoolVar(¶ms.update, "u", false, "get and update repositories cache")
flag.StringVar(¶ms.params, "p", "", "print value by paramters")
flag.StringVar(¶ms.user, "user", "", "target user")
flag.BoolVar(¶ms.disableCache, "disablecache", false, "caching is disable")
flag.BoolVar(¶ms.cleanCache, "cleancache", false, "clean cache")
flag.Parse()
}
func printRepositories(p printer, repos []repository) {
for _, v := range repos {
p.Print(v)
}
}
func main() {
parseFlag()
if params.cleanCache {
p := filepath.Join(params.homedir, cacheFileName)
if err := os.Remove(p); err != nil {
fmt.Fprintf(os.Stderr, "failed to clean cache due to %v", err)
os.Exit(1)
}
os.Exit(0)
}
stdp := &ioprinter{w: os.Stdout, params: params.params}
if !params.update && !params.disableCache {
// try to read cache file.
p := filepath.Join(params.homedir, cacheFileName)
if caches, err := readCache(p); err == nil {
printRepositories(stdp, caches)
os.Exit(0)
}
}
tkn, err := getToken()
if err != nil {
fmt.Fprintf(os.Stderr, "failed to get github token due to %s\n", err)
os.Exit(1)
}
opts := []listOption{
withUser(params.user),
withToken(tkn),
}
var mp *multiprinter
repos, err := listGithubRepositories(opts...)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to get repositories due to %s\n", err)
os.Exit(1)
}
printers := make([]printer, 0, 1)
printers = append(printers, stdp)
if !params.disableCache {
cache := filepath.Join(params.homedir, cacheFileName)
f, err := os.OpenFile(cache, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err == nil {
defer f.Close()
printers = append(printers, &jsonprinter{f})
} else {
fmt.Fprintf(os.Stderr, "cannot open cache file due to %s", err)
}
}
mp = &multiprinter{printers: printers}
printRepositories(mp, repos)
}