-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
91 lines (79 loc) · 2.21 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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/spf13/cobra"
)
type Repo struct {
FullName string `json:"full_name"`
}
var output string
func main() {
// reference: https://gist.github.com/Sanjo/4ed367c68acc27fd9a18
// parse arguments (cobra)
var rootCmd = &cobra.Command{
Use: "github-opml",
}
var cmdStarred = &cobra.Command{
Use: "starred [username]",
Short: "Generate OPML file for releases of starred repos of given user",
Run: processStarred,
}
cmdStarred.Flags().StringVarP(&output, "output", "o", "", "Output file [default: stdout]")
rootCmd.AddCommand(cmdStarred)
rootCmd.Execute()
}
func processStarred(cmd *cobra.Command, args []string) {
// read json API (loop)
if len(args) < 1 {
fmt.Fprintf(os.Stderr, "No username given. Call with --help for details on usage.\n")
os.Exit(1)
}
username := args[0]
page := 1
resultsPerPage := 100
starRepos := []Repo{}
for true {
url := fmt.Sprintf("https://api.github.com/users/%s/starred?page=%d&per_page=%d", username, page, resultsPerPage)
res, err := http.Get(url)
perror(err)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
perror(err)
var repos []Repo
err = json.Unmarshal(body, &repos)
for _, repo := range repos {
starRepos = append(starRepos, repo)
}
if len(repos) < resultsPerPage {
break
}
page++
}
// build OPML
fmt.Fprintf(os.Stderr, "Number of starred repos: %d\n", len(starRepos))
// TODO use xml package
xmlString := `<?xml version="1.0" encoding="utf-8" ?><opml version="1.1"><head>
<title>Generated by https://github.com/jojomi/github-opml</title>
<dateCreated>Wed, 16 Sep 2015 00:23:28 +0200</dateCreated></head><body>
<outline text="GitHub Star Releases">`
for _, repo := range starRepos {
releaseUrl := fmt.Sprintf("https://github.com/%s/releases.atom", repo.FullName)
xmlString += fmt.Sprintf("<outline title=\"%s\" text=\"%s\" type=\"atom\" xmlUrl=\"%s\" />", repo.FullName, repo.FullName, releaseUrl)
}
xmlString += `</outline></body></opml>`
// output to stdout or file
if output != "" {
ioutil.WriteFile(output, []byte(xmlString), 0640)
} else {
fmt.Println(xmlString)
}
}
func perror(err error) {
if err != nil {
panic(err)
}
}