-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathssh-keys.go
142 lines (120 loc) · 2.53 KB
/
ssh-keys.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
package main
import (
"context"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/google/go-github/github"
"github.com/raguay/goAlfred"
"gopkg.in/yaml.v2"
)
func recordHit(user string) error {
cache, err := readCache()
if err != nil {
return err
}
cache[user]++
err = writeCache(cache)
return err
}
func readCache() (map[string]int, error) {
src, err := ioutil.ReadFile(goAlfred.Cache() + "/cache.yml")
if err != nil {
if os.IsNotExist(err) {
return map[string]int{}, nil
}
return nil, err
}
var cache map[string]int
err = yaml.Unmarshal(src, &cache)
if err != nil {
return nil, err
}
return cache, nil
}
func writeCache(cache map[string]int) error {
src, err := yaml.Marshal(cache)
if err != nil {
return err
}
err = ioutil.WriteFile(goAlfred.Cache()+"/cache.yml", src, 0644)
if err != nil {
return err
}
return nil
}
func getKeys(ctx context.Context, user string, gh *github.Client) string {
var keys []string
err := recordHit(user)
if err != nil {
panic(err)
}
page := 0
for {
results, response, err := gh.Users.ListKeys(ctx, user, &github.ListOptions{Page: page, PerPage: 500})
if err != nil {
panic(err)
}
page = response.NextPage
for i := 0; i < len(results); i++ {
keys = append(keys, *results[i].Key)
}
if response.NextPage == response.LastPage {
break
}
}
return (strings.Join(keys, "\n") + "\n")
}
func findUser(ctx context.Context, user string, gh *github.Client) string {
results, _, err := gh.Search.Users(ctx, user, &github.SearchOptions{})
if err != nil {
panic(err)
}
cache, err := readCache()
if err != nil {
panic(err)
}
for i := 0; i < len(results.Users); i++ {
user := results.Users[i]
id := *user.ID
login := *user.Login
var name string
if user.Name != nil {
name = *user.Name
} else {
name = *user.Login
}
priority := cache[login]
goAlfred.AddResult(
fmt.Sprintf("%d", id), // uid
login, // arg string
login, // title
"Copy SSH keys for "+name+" to clipboard", // subtitle
"icon.png", // icon
"yes", // valid
"", // auto
"", // rtype
priority,
)
}
return (goAlfred.ToXML())
}
func main() {
if len(os.Args) > 2 {
// Load up creds if present
gh := github.NewClient(nil)
ctx := context.Background()
user := os.Args[2]
switch os.Args[1] {
case "login":
// TODO: save creds for authenticating to github
case "logout":
// TODO: delete creds
case "keys-for":
fmt.Print(getKeys(ctx, user, gh))
case "find-user":
fmt.Print(findUser(ctx, user, gh))
}
}
}