forked from Colelyman/gozette
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
81 lines (66 loc) · 2.17 KB
/
github.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
package main
import (
"context"
"os"
"time"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
var ctx context.Context
var sourceOwner = "Colelyman"
var authorName = "Cole Lyman"
var authorEmail = "[email protected]"
var sourceRepo = "colelyman-hugo"
var branch = "master"
func CommitEntry(path string, file string) error {
client := connectGitHub()
repo := getRef(client)
tree, err := getTree(path, file, client, repo)
if err != nil {
return err
}
err = pushCommit(client, repo, tree)
if err != nil {
return err
}
return nil
}
func connectGitHub() *github.Client {
ctx = context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.ExpandEnv("$GIT_API_TOKEN")},
)
tc := oauth2.NewClient(ctx, ts)
return github.NewClient(tc)
}
func getRef(client *github.Client) *github.Reference {
// refURL := strings.Split(os.ExpandEnv("$REPOSITORY_URL"), "/")
ref, _, err := client.Git.GetRef(ctx, sourceOwner, sourceRepo, "refs/heads/"+branch)
if err != nil {
panic(err)
}
return ref
}
// this function adds the new file to the repo
func getTree(path string, file string, client *github.Client, ref *github.Reference) (*github.Tree, error) {
tree, _, err := client.Git.CreateTree(ctx, sourceOwner, sourceRepo, *ref.Object.SHA, []github.TreeEntry{github.TreeEntry{Path: github.String(path), Type: github.String("blob"), Content: github.String(file), Mode: github.String(("100644"))}})
return tree, err
}
func pushCommit(client *github.Client, ref *github.Reference, tree *github.Tree) error {
parent, _, err := client.Repositories.GetCommit(ctx, sourceOwner, sourceRepo, *ref.Object.SHA)
if err != nil {
return err
}
parent.Commit.SHA = parent.SHA
date := time.Now()
author := &github.CommitAuthor{Date: &date, Name: &authorName, Email: &authorEmail}
message := "Added new micropub entry."
commit := &github.Commit{Author: author, Message: &message, Tree: tree, Parents: []github.Commit{*parent.Commit}}
newCommit, _, err := client.Git.CreateCommit(ctx, sourceOwner, sourceRepo, commit)
if err != nil {
return err
}
ref.Object.SHA = newCommit.SHA
_, _, err = client.Git.UpdateRef(ctx, sourceOwner, sourceRepo, ref, false)
return err
}