Browse Source

重构代码结构

master
OhYee 2 years ago
parent
commit
31919c2362
Signed by: OhYee
GPG Key ID: 5A9E1F63ED274FBB
  1. 137
      lib/gitea/gitea.go
  2. 90
      lib/hook/hook.go
  3. 231
      main.go

137
lib/gitea/gitea.go

@ -0,0 +1,137 @@ @@ -0,0 +1,137 @@
package gitea
import (
"time"
"git.oyohyee.com/OhYee/action/lib/hook"
)
type Hook struct {
After string `json:"after"`
Before string `json:"before"`
Commits []struct {
Added []string `json:"added"`
Author struct {
Email string `json:"email"`
Name string `json:"name"`
Username string `json:"username"`
} `json:"author"`
Committer struct {
Email string `json:"email"`
Name string `json:"name"`
Username string `json:"username"`
} `json:"committer"`
ID string `json:"id"`
Message string `json:"message"`
Modified []interface{} `json:"modified"`
Removed []interface{} `json:"removed"`
Timestamp time.Time `json:"timestamp"`
URL string `json:"url"`
Verification interface{} `json:"verification"`
} `json:"commits"`
CompareURL string `json:"compare_url"`
HeadCommit interface{} `json:"head_commit"`
Pusher struct {
AvatarURL string `json:"avatar_url"`
Created time.Time `json:"created"`
Email string `json:"email"`
FullName string `json:"full_name"`
ID int `json:"id"`
IsAdmin bool `json:"is_admin"`
Language string `json:"language"`
LastLogin time.Time `json:"last_login"`
Login string `json:"login"`
Username string `json:"username"`
} `json:"pusher"`
Ref string `json:"ref"`
Repository struct {
AllowMergeCommits bool `json:"allow_merge_commits"`
AllowRebase bool `json:"allow_rebase"`
AllowRebaseExplicit bool `json:"allow_rebase_explicit"`
AllowSquashMerge bool `json:"allow_squash_merge"`
Archived bool `json:"archived"`
AvatarURL string `json:"avatar_url"`
CloneURL string `json:"clone_url"`
CreatedAt time.Time `json:"created_at"`
DefaultBranch string `json:"default_branch"`
Description string `json:"description"`
Empty bool `json:"empty"`
Fork bool `json:"fork"`
ForksCount int `json:"forks_count"`
FullName string `json:"full_name"`
HasIssues bool `json:"has_issues"`
HasProjects bool `json:"has_projects"`
HasPullRequests bool `json:"has_pull_requests"`
HasWiki bool `json:"has_wiki"`
HTMLURL string `json:"html_url"`
ID int `json:"id"`
IgnoreWhitespaceConflicts bool `json:"ignore_whitespace_conflicts"`
Internal bool `json:"internal"`
InternalTracker struct {
AllowOnlyContributorsToTrackTime bool `json:"allow_only_contributors_to_track_time"`
EnableIssueDependencies bool `json:"enable_issue_dependencies"`
EnableTimeTracker bool `json:"enable_time_tracker"`
} `json:"internal_tracker"`
Mirror bool `json:"mirror"`
MirrorInterval string `json:"mirror_interval"`
Name string `json:"name"`
OpenIssuesCount int `json:"open_issues_count"`
OpenPrCounter int `json:"open_pr_counter"`
OriginalURL string `json:"original_url"`
Owner struct {
AvatarURL string `json:"avatar_url"`
Created time.Time `json:"created"`
Email string `json:"email"`
FullName string `json:"full_name"`
ID int `json:"id"`
IsAdmin bool `json:"is_admin"`
Language string `json:"language"`
LastLogin time.Time `json:"last_login"`
Login string `json:"login"`
Username string `json:"username"`
} `json:"owner"`
Parent interface{} `json:"parent"`
Permissions struct {
Admin bool `json:"admin"`
Pull bool `json:"pull"`
Push bool `json:"push"`
} `json:"permissions"`
Private bool `json:"private"`
ReleaseCounter int `json:"release_counter"`
Size int `json:"size"`
SSHURL string `json:"ssh_url"`
StarsCount int `json:"stars_count"`
Template bool `json:"template"`
UpdatedAt time.Time `json:"updated_at"`
WatchersCount int `json:"watchers_count"`
Website string `json:"website"`
} `json:"repository"`
Secret string `json:"secret"`
Sender struct {
AvatarURL string `json:"avatar_url"`
Created time.Time `json:"created"`
Email string `json:"email"`
FullName string `json:"full_name"`
ID int `json:"id"`
IsAdmin bool `json:"is_admin"`
Language string `json:"language"`
LastLogin time.Time `json:"last_login"`
Login string `json:"login"`
Username string `json:"username"`
} `json:"sender"`
}
func (h *Hook) ToHook() *hook.Hook {
return &hook.Hook{
Type: "gitea",
Token: h.Secret,
Commit: h.After,
Branch: h.Ref,
Pusher: h.Pusher.Username,
Repo: h.Repository.FullName,
RepoOwner: h.Repository.Owner.Username,
RepoName: h.Repository.Name,
RepoGit: h.Repository.CloneURL,
RepoPage: h.Repository.HTMLURL,
}
}

90
lib/hook/hook.go

@ -0,0 +1,90 @@ @@ -0,0 +1,90 @@
package hook
import (
"fmt"
"os"
"os/exec"
"strings"
"github.com/OhYee/goutils/file"
"github.com/OhYee/rainbow/log"
)
type Hook struct {
Type string `json:"type"`
Trigger string `json:"trigger"`
Token string `json:"token"`
Commit string `json:"commit"`
Branch string `json:"branch"`
Pusher string `json:"pusher"`
Repo string `json:"repo"`
RepoOwner string `json:"repo_owner"`
RepoName string `json:"repo_name"`
RepoGit string `json:"repo_git"`
RepoPage string `json:"page"`
Arg1 string `json:"arg1"`
Arg2 string `json:"arg2"`
Arg3 string `json:"arg3"`
Arg4 string `json:"arg4"`
Arg5 string `json:"arg5"`
}
func (hook *Hook) Handle(dirPath string) {
log.Debug.Println(dirPath)
if file.IsExist(dirPath) {
// 该文件需要处理
screenName := strings.ReplaceAll(hook.Repo, "/", "-")
// 环境变量
env := []string{
fmt.Sprintf("OHYEE_ACTION_TYPE=%s", hook.Type),
fmt.Sprintf("OHYEE_ACTION_TRIGGER=%s", hook.Trigger),
fmt.Sprintf("OHYEE_ACTION_TOKEN=%s", hook.Token),
fmt.Sprintf("OHYEE_ACTION_BRANCH=%s", hook.Branch),
fmt.Sprintf("OHYEE_ACTION_COMMIT=%s", hook.Commit),
fmt.Sprintf("OHYEE_ACTION_PUSHER=%s", hook.Pusher),
fmt.Sprintf("OHYEE_ACTION_REPO=%s", hook.Repo),
fmt.Sprintf("OHYEE_ACTION_REPO_OWNER=%s", hook.RepoOwner),
fmt.Sprintf("OHYEE_ACTION_REPO_NAME=%s", hook.RepoName),
fmt.Sprintf("OHYEE_ACTION_REPO_GIT=%s", hook.RepoGit),
fmt.Sprintf("OHYEE_ACTION_REPO_PAGE=%s", hook.RepoPage),
fmt.Sprintf("OHYEE_ACTION_ARG1=%s", hook.Arg1),
fmt.Sprintf("OHYEE_ACTION_ARG2=%s", hook.Arg2),
fmt.Sprintf("OHYEE_ACTION_ARG3=%s", hook.Arg3),
fmt.Sprintf("OHYEE_ACTION_ARG4=%s", hook.Arg4),
fmt.Sprintf("OHYEE_ACTION_ARG5=%s", hook.Arg5),
}
// 结束旧的的自动部署命令
runWrapper(dirPath, env, true, "screen", "-S", screenName, "-X", "quit")
// 执行新的自动部署命令
if _, ok := runWrapper(
dirPath,
env,
false,
"screen", "-dmLS", screenName,
"bash", "./.ohyee/action.bash",
); !ok {
return
}
}
}
func runWrapper(dir string, env []string, ignoreErr bool, command string, args ...string) (string, bool) {
res, err := run(dir, env, command, args...)
if err != nil && !ignoreErr {
log.Error.Println(err)
log.Error.Println(res)
return res, false
}
return res, true
}
func run(dir string, env []string, command string, args ...string) (string, error) {
log.Debug.Println(command, args)
cmd := exec.Command(command, args...)
cmd.Dir = dir
cmd.Env = append(cmd.Env, env...)
cmd.Env = append(cmd.Env, os.Environ()...)
res, err := cmd.CombinedOutput()
return string(res), err
}

231
main.go

@ -8,13 +8,13 @@ import ( @@ -8,13 +8,13 @@ import (
"math/rand"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"git.oyohyee.com/OhYee/action/lib/gitea"
"git.oyohyee.com/OhYee/action/lib/hook"
"github.com/OhYee/goutils/file"
"github.com/OhYee/rainbow/color"
"github.com/OhYee/rainbow/errors"
@ -37,15 +37,14 @@ func readJson(r io.Reader, res interface{}) (err error) { @@ -37,15 +37,14 @@ func readJson(r io.Reader, res interface{}) (err error) {
}
return
}
func (h handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hook := new(Hook)
func (serv handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h := new(hook.Hook)
switch r.URL.Path {
case "/gitea":
m := new(GiteaHook)
m := new(gitea.Hook)
readJson(r.Body, m)
hook = m.ToHook()
h = m.ToHook()
s, err := json.MarshalIndent(m, "", " ")
if err != nil {
@ -55,10 +54,10 @@ func (h handle) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -55,10 +54,10 @@ func (h handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Debug.Printf("%s\n", s)
case "/hook":
readJson(r.Body, hook)
hook.Type = "hook"
readJson(r.Body, h)
h.Type = "hook"
s, err := json.MarshalIndent(hook, "", " ")
s, err := json.MarshalIndent(h, "", " ")
if err != nil {
log.Error.Println(errors.ShowStack(errors.NewErr(err)))
return
@ -70,7 +69,7 @@ func (h handle) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -70,7 +69,7 @@ func (h handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("Can not solve request %s", r.RequestURI)))
}
go hook.handleGiteaWebHook(path.Join(h.Root, "repos", hook.RepoName))
go h.Handle(path.Join(serv.Root, "repos", h.RepoName))
}
var nocolor = color.New()
@ -144,216 +143,6 @@ func main() { @@ -144,216 +143,6 @@ func main() {
})
}
func runWrapper(dir string, env []string, ignoreErr bool, command string, args ...string) (string, bool) {
res, err := run(dir, env, command, args...)
if err != nil && !ignoreErr {
log.Error.Println(err)
log.Error.Println(res)
return res, false
}
return res, true
}
func run(dir string, env []string, command string, args ...string) (string, error) {
log.Debug.Println(command, args)
cmd := exec.Command(command, args...)
cmd.Dir = dir
cmd.Env = append(cmd.Env, env...)
cmd.Env = append(cmd.Env, os.Environ()...)
res, err := cmd.CombinedOutput()
return string(res), err
}
type GiteaHook struct {
After string `json:"after"`
Before string `json:"before"`
Commits []struct {
Added []string `json:"added"`
Author struct {
Email string `json:"email"`
Name string `json:"name"`
Username string `json:"username"`
} `json:"author"`
Committer struct {
Email string `json:"email"`
Name string `json:"name"`
Username string `json:"username"`
} `json:"committer"`
ID string `json:"id"`
Message string `json:"message"`
Modified []interface{} `json:"modified"`
Removed []interface{} `json:"removed"`
Timestamp time.Time `json:"timestamp"`
URL string `json:"url"`
Verification interface{} `json:"verification"`
} `json:"commits"`
CompareURL string `json:"compare_url"`
HeadCommit interface{} `json:"head_commit"`
Pusher struct {
AvatarURL string `json:"avatar_url"`
Created time.Time `json:"created"`
Email string `json:"email"`
FullName string `json:"full_name"`
ID int `json:"id"`
IsAdmin bool `json:"is_admin"`
Language string `json:"language"`
LastLogin time.Time `json:"last_login"`
Login string `json:"login"`
Username string `json:"username"`
} `json:"pusher"`
Ref string `json:"ref"`
Repository struct {
AllowMergeCommits bool `json:"allow_merge_commits"`
AllowRebase bool `json:"allow_rebase"`
AllowRebaseExplicit bool `json:"allow_rebase_explicit"`
AllowSquashMerge bool `json:"allow_squash_merge"`
Archived bool `json:"archived"`
AvatarURL string `json:"avatar_url"`
CloneURL string `json:"clone_url"`
CreatedAt time.Time `json:"created_at"`
DefaultBranch string `json:"default_branch"`
Description string `json:"description"`
Empty bool `json:"empty"`
Fork bool `json:"fork"`
ForksCount int `json:"forks_count"`
FullName string `json:"full_name"`
HasIssues bool `json:"has_issues"`
HasProjects bool `json:"has_projects"`
HasPullRequests bool `json:"has_pull_requests"`
HasWiki bool `json:"has_wiki"`
HTMLURL string `json:"html_url"`
ID int `json:"id"`
IgnoreWhitespaceConflicts bool `json:"ignore_whitespace_conflicts"`
Internal bool `json:"internal"`
InternalTracker struct {
AllowOnlyContributorsToTrackTime bool `json:"allow_only_contributors_to_track_time"`
EnableIssueDependencies bool `json:"enable_issue_dependencies"`
EnableTimeTracker bool `json:"enable_time_tracker"`
} `json:"internal_tracker"`
Mirror bool `json:"mirror"`
MirrorInterval string `json:"mirror_interval"`
Name string `json:"name"`
OpenIssuesCount int `json:"open_issues_count"`
OpenPrCounter int `json:"open_pr_counter"`
OriginalURL string `json:"original_url"`
Owner struct {
AvatarURL string `json:"avatar_url"`
Created time.Time `json:"created"`
Email string `json:"email"`
FullName string `json:"full_name"`
ID int `json:"id"`
IsAdmin bool `json:"is_admin"`
Language string `json:"language"`
LastLogin time.Time `json:"last_login"`
Login string `json:"login"`
Username string `json:"username"`
} `json:"owner"`
Parent interface{} `json:"parent"`
Permissions struct {
Admin bool `json:"admin"`
Pull bool `json:"pull"`
Push bool `json:"push"`
} `json:"permissions"`
Private bool `json:"private"`
ReleaseCounter int `json:"release_counter"`
Size int `json:"size"`
SSHURL string `json:"ssh_url"`
StarsCount int `json:"stars_count"`
Template bool `json:"template"`
UpdatedAt time.Time `json:"updated_at"`
WatchersCount int `json:"watchers_count"`
Website string `json:"website"`
} `json:"repository"`
Secret string `json:"secret"`
Sender struct {
AvatarURL string `json:"avatar_url"`
Created time.Time `json:"created"`
Email string `json:"email"`
FullName string `json:"full_name"`
ID int `json:"id"`
IsAdmin bool `json:"is_admin"`
Language string `json:"language"`
LastLogin time.Time `json:"last_login"`
Login string `json:"login"`
Username string `json:"username"`
} `json:"sender"`
}
func (hook *GiteaHook) ToHook() *Hook {
return &Hook{
Type: "gitea",
Token: hook.Secret,
Commit: hook.After,
Branch: hook.Ref,
Pusher: hook.Pusher.Username,
Repo: hook.Repository.FullName,
RepoOwner: hook.Repository.Owner.Username,
RepoName: hook.Repository.Name,
RepoGit: hook.Repository.CloneURL,
RepoPage: hook.Repository.HTMLURL,
}
}
type Hook struct {
Type string `json:"type"`
Trigger string `json:"trigger"`
Token string `json:"token"`
Commit string `json:"commit"`
Branch string `json:"branch"`
Pusher string `json:"pusher"`
Repo string `json:"repo"`
RepoOwner string `json:"repo_owner"`
RepoName string `json:"repo_name"`
RepoGit string `json:"repo_git"`
RepoPage string `json:"page"`
Arg1 string `json:"arg1"`
Arg2 string `json:"arg2"`
Arg3 string `json:"arg3"`
Arg4 string `json:"arg4"`
Arg5 string `json:"arg5"`
}
func (hook *Hook) handleGiteaWebHook(dirPath string) {
log.Debug.Println(dirPath)
if file.IsExist(dirPath) {
// 该文件需要处理
screenName := strings.ReplaceAll(hook.Repo, "/", "-")
// 环境变量
env := []string{
fmt.Sprintf("OHYEE_ACTION_TYPE=%s", hook.Type),
fmt.Sprintf("OHYEE_ACTION_TRIGGER=%s", hook.Trigger),
fmt.Sprintf("OHYEE_ACTION_TOKEN=%s", hook.Token),
fmt.Sprintf("OHYEE_ACTION_BRANCH=%s", hook.Branch),
fmt.Sprintf("OHYEE_ACTION_COMMIT=%s", hook.Commit),
fmt.Sprintf("OHYEE_ACTION_PUSHER=%s", hook.Pusher),
fmt.Sprintf("OHYEE_ACTION_REPO=%s", hook.Repo),
fmt.Sprintf("OHYEE_ACTION_REPO_OWNER=%s", hook.RepoOwner),
fmt.Sprintf("OHYEE_ACTION_REPO_NAME=%s", hook.RepoName),
fmt.Sprintf("OHYEE_ACTION_REPO_GIT=%s", hook.RepoGit),
fmt.Sprintf("OHYEE_ACTION_REPO_PAGE=%s", hook.RepoPage),
fmt.Sprintf("OHYEE_ACTION_ARG1=%s", hook.Arg1),
fmt.Sprintf("OHYEE_ACTION_ARG2=%s", hook.Arg2),
fmt.Sprintf("OHYEE_ACTION_ARG3=%s", hook.Arg3),
fmt.Sprintf("OHYEE_ACTION_ARG4=%s", hook.Arg4),
fmt.Sprintf("OHYEE_ACTION_ARG5=%s", hook.Arg5),
}
// 结束旧的的自动部署命令
runWrapper(dirPath, env, true, "screen", "-S", screenName, "-X", "quit")
// 执行新的自动部署命令
if _, ok := runWrapper(
dirPath,
env,
false,
"screen", "-dmLS", screenName,
"bash", "./.ohyee/action.bash",
); !ok {
return
}
}
}
func resetLog(l *log.Logger, f *os.File, prefix string) {
l.SetColor(nocolor)
l.SetOutput(f)

Loading…
Cancel
Save