-
Notifications
You must be signed in to change notification settings - Fork 0
/
apps.go
117 lines (96 loc) · 2.54 KB
/
apps.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
package github
import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/go-git/go-git/v5"
"github.com/google/go-github/v54/github"
)
// GitHubApp is a struct to interact with GitHub App's API
type GitHubApp struct {
Config *GitHubAppConfig
Auth Auth
gitClient *git.Repository
githubClient *github.Client
worktree *git.Worktree
}
// Configuration for the GitHub App interaction
type GitHubAppConfig struct {
repoName string
RepoURL string
ApplicationID int64
InstallationID int64
LocalPath string
PrivateKey []byte
}
var githubAPIURL string = "https://api.github.com"
// extractRepoName extracts the repository name from the URL
func extractRepoName(gitURL string) (string, error) {
parsedURL, err := url.Parse(gitURL)
if err != nil {
return "", err
}
// Splitting the path based on slashes
parts := strings.Split(parsedURL.Path, "/")
// Ensure at least one segment exists
if len(parts) == 0 {
return "", fmt.Errorf("could not extract repository name")
}
// The last part of the URL is typically 'repo.git', so we need to further process it to extract 'repo'
repoName := parts[len(parts)-1]
// Removing .git extension if present
if strings.HasSuffix(repoName, ".git") {
repoName = repoName[:len(repoName)-len(".git")]
}
return repoName, nil
}
// Creates a new GitHubApp struct configured by GitHubAppConfig
func NewGitHubApp(cfg *GitHubAppConfig) (*GitHubApp, error) {
// check if application ID and installation ID are defined
if cfg.ApplicationID == 0 && cfg.InstallationID == 0 {
return nil, errors.New("provide App ID and Installation ID")
}
// set localPath if not passed
if cfg.LocalPath == "" {
cfg.LocalPath = "./"
}
var itr *ghinstallation.Transport
var err error
// get new key for github
itr, err = ghinstallation.New(http.DefaultTransport, cfg.ApplicationID, cfg.InstallationID, cfg.PrivateKey)
if err != nil {
return nil, err
}
repoName, err := extractRepoName(cfg.RepoURL)
if err != nil {
return nil, err
}
// set repoName
cfg.repoName = repoName
// initialise a new GitHubApp
ghApp := &GitHubApp{
Config: cfg,
githubClient: github.NewClient(&http.Client{Transport: itr}),
}
// authenticate
err = ghApp.authenticate()
if err != nil {
return nil, err
}
return ghApp, nil
}
func (ghApp *GitHubApp) authenticate() error {
err := ghApp.buildJWTToken()
if err != nil {
return err
}
tkn, err := ghApp.GetAccessToken()
if err != nil {
return err
}
ghApp.Auth.Token = tkn
return nil
}