-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
98 lines (79 loc) · 2.19 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
98
/*
Program that acts similar to cat()
except instead of using stdout it creates
a private gist in Github
Uses an environment variable GITHUB_API to
determine the users api key.
*/
package main
import (
"bytes"
"context"
"flag"
"fmt"
"io"
"os"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
const tokenEnv = "GITHUB_API"
type GistFiles map[github.GistFilename]github.GistFile
// Create GistFiles from stdin
func FromStdin(gistFiles GistFiles, fExt string) github.GistFile {
var stdOutBuff bytes.Buffer
_, err := io.Copy(&stdOutBuff, os.Stdin)
if err != nil {
fmt.Printf("Error copying stdin to buffer: %v\n", err)
os.Exit(1)
}
gistStr := stdOutBuff.String()
return github.GistFile{Content: &gistStr}
}
// Cats file content together into a gistFile
func FromFiles(gistFiles GistFiles, files []string, fExt string) github.GistFile {
var stdOutBuff bytes.Buffer
for _, fileName := range files {
file, err := os.Open(fileName)
if err != nil {
fmt.Printf("Error opening file %s: %v", fileName, err)
os.Exit(1)
}
if _, err := io.Copy(&stdOutBuff, file); err != nil {
fmt.Printf("Error copying file contents to buffer: %v\n", err)
}
}
gistStr := stdOutBuff.String()
return github.GistFile{Content: &gistStr}
}
func main() {
var public = flag.Bool("public", false, "makes the gist public")
var extension = flag.String("ext", "txt", "file extension to use")
flag.Parse()
apiToken := os.Getenv(tokenEnv)
if apiToken == "" {
fmt.Println("must set environment variable $GITHUB_API")
os.Exit(1)
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: apiToken})
client := github.NewClient(oauth2.NewClient(context.Background(), ts))
args := flag.Args()
gistFiles := make(GistFiles)
gistFilename := github.GistFilename(fmt.Sprintf("gistfile1.%s", *extension))
if len(args) == 0 {
gistFiles[gistFilename] = FromStdin(gistFiles, *extension)
} else {
gistFiles[gistFilename] = FromFiles(gistFiles, args, *extension)
}
gist := github.Gist{
Files: gistFiles,
Public: public,
}
g, _, err := client.Gists.Create(&gist)
if err == nil {
fmt.Println(*g.HTMLURL)
os.Exit(0)
} else {
fmt.Printf("Error creating new gist: %v\n", err)
os.Exit(1)
}
}