Repository: smallSohoSolo/solo-ci Branch: master Commit: 58c867d31166 Files: 20 Total size: 34.2 KB Directory structure: gitextract_wdg33cnp/ ├── .gitignore ├── LICENSE ├── README-CN.md ├── README.md ├── conf/ │ ├── app.conf │ ├── config.go │ ├── nginx/ │ │ └── solo-ci-nginx.conf │ └── solo-ci.service ├── controllers/ │ └── project.go ├── init/ │ └── init.go ├── main.go ├── models/ │ ├── build.go │ ├── github_hook.go │ ├── gitlab_hook.go │ ├── models.go │ └── project.go ├── routers/ │ └── router.go ├── solocifile ├── test/ │ └── normal_test.go └── utils/ └── return_struct.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *~ .DS_Store .idea/ *.iml data.db solo-ci workspace ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README-CN.md ================================================ # Solo CI [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/solo-ci/Lobby) ### Description 一个轻量级的Golang CI/CD工具,全自动clone代码,构建,部署,只需要几行配置即可 ```json { "get_list":[ "github.com/asaskevich/govalidator" ], "zip_list":[ "conf" ], "after_script":"echo hello", "before_script":"pwd" } ``` ### Features - 完美集成Gitlab,Github(application/json) - 配置要求远低于主流CI工具(Jenkins etc.)内存占用低,可以运行在任何配置Linux主机中 - 一键开启,只需要Golang环境和Git环境,程序会自动获取自己所需要的环境 - 配制简单,只有四个配置项 - 一键clone,build,test,打包成tar - 支持自定义脚本,构建前构建后触发均可自定义,脚本执行目录为当前构建目录 - REST API支持,可以集成进任何系统 - 可以保存任意数量的构建,不丢任何构建 ### Use 1. go get github.com/astaxie/beego go get github.com/mattn/go-sqlite3 go get github.com/satori/go.uuid 2. 配置好主机的GOPATH,GOROOT,GIT环境 3. 下载编译好的二进制 4. 使用REST API新建项目 5. 在你的项目中写个简单的solo.json,并且在代码管理中配置webhook (配置地址请看REST API) 6. push!触发CI 7. 构建好的程序会存在workspace文件夹中 8. go get github.com/mattn/go-sqlite3需要预安装gcc, 必要时使用"sudo apt-get install build-essential"命令安装 ### REST API | Method | Url | Params | Description | | :----: | :--------------------------------------- | :--------------------------------------- | :---------- | | POST | http://your-ip:13233/v1/solohook/:project_id | - project_id(path) | 触发Webhook | | POST | http://your-ip:13233/v1/project | - name(form) | 创建项目 | | | | - type(form, gitlab or github or bitbucket) | | | | | - url(form) | | | | | - path(form,the position of solo-ci.json) | | | | | - branch(form) | | | | | - secret_token(form,not necessary) | | | | | - main_path(form,the position of main.go) | | | DELETE | http://your-ip:13233/v1/project/:project_id | - project_id(path) | 删除项目 | | PUT | http://your-ip:13233/v1/project/:project_id | - project_id(path) | 更新项目 | | | | - name(form) | | | | | - type(form, gitlab or github) | | | | | - url(form) | | | | | - path(form,the position of solo-ci.json) | | | | | - branch(form) | | | | | - secret_token(form,not necessary) | | | GET | http://your-ip:13233/v1/project/:project_id | - project_id(path) | 获取项目信息 | | GET | http://your-ip:13233/v1/project | - project_id(path) | 获取项目列表 | | | | - page (default 0) | | | | | - pageSize(default 20) | | ### 配置文件solo-ci.json - get_list:需要下载的Go包 - zip_list:构建完成需要打包进项目的文件或者目录 - before_script:构建之前执行的脚本 - after_script:构建之后执行的脚本 所有的选项都不是必须存在的,及时你什么都不写也可以,下面是一个空的配置文件例子 ```json { } ``` ### Next - Web GUI 支持 ================================================ FILE: README.md ================================================ # Solo CI [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/solo-ci/Lobby) ### Description [中文版](README-CN.md) A lightweight golang CI/CD tools, you only need write a simple config, it will clone, build, test, deploy ```json { "get_list":[ "github.com/asaskevich/govalidator" ], "zip_list":[ "conf" ], "after_script":"echo hello", "before_script":"pwd" } ``` ### Features - Support Gitlab, Github(application/json) webhook - Only need very small memory and cpu, it can run on every Linux host - You only need to start it ,it will get the env auto. - The simple config, if you want, you don't need to write it. - Auto clone, buil, test, clean, tar - Support after script and before script, it will run on the project path - Support REST API - Every build will be saved ### Use 1. go get github.com/astaxie/beego go get github.com/mattn/go-sqlite3 go get github.com/satori/go.uuid 2. GOPATH,GOROOT,GIT 3. Download solo-ci binary 4. Use REST API new a ci project 5. Write a config and configure your webhook 6. push! 7. The Build will save at workspace dir. 8. go-sqlite3 requires gcc pre-installed. use "sudo apt-get install build-essential" to install gcc if necessary ### REST API | Method | Url | Params | Description | | :----: | :--------------------------------------- | :--------------------------------------- | :--------------- | | POST | http://your-ip:13233/v1/solohook/:project_id | - project_id(path) | Run Webhook | | POST | http://your-ip:13233/v1/project | - name(form) | New a project | | | | - type(form, gitlab or github or bitbucket) | | | | | - url(form) | | | | | - path(form,the position of solo-ci.json) | | | | | - branch(form) | | | | | - secret_token(form,not necessary) | | | | | - main_path(form,the position of main.go) | | | DELETE | http://your-ip:13233/v1/project/:project_id | - project_id(path) | Delete project | | PUT | http://your-ip:13233/v1/project/:project_id | - project_id(path) | Update Project | | | | - name(form) | | | | | - type(form, gitlab or github) | | | | | - url(form) | | | | | - path(form,the position of solo-ci.json) | | | | | - branch(form) | | | | | - secret_token(form,not necessary) | | | GET | http://your-ip:13233/v1/project/:project_id | - project_id(path) | Get Project Info | | GET | http://your-ip:13233/v1/project | - project_id(path) | Get project list | | | | - page (default 0) | | | | | - pageSize(default 20) | | ### Config solo-ci.json - get_list:the go get list - zip_list:the file you want to tar - before_script:it will run before build - after_script:it will run after build If you don't want to write a config, you can write a blank config. ```json { } ``` ### Next - Support Web GUI ================================================ FILE: conf/app.conf ================================================ appname = solo-ci httpport = 13233 runmode = prod autorender = false copyrequestbody = true EnableDocs = false [dev] EnableErrorsShow = true Verbose = true [prod] EnableErrorsShow = false Verbose = false ================================================ FILE: conf/config.go ================================================ package conf var GOROOT = "" var GOPATH = "" ================================================ FILE: conf/nginx/solo-ci-nginx.conf ================================================ upstream solo-ci-public { server 127.0.0.1; keepalive 64; } server { listen 80; server_name solo-ci.float.pub; default_type 'text/plain'; # or browser will download page set $origin ''; if ( $http_origin ~ '.float.pub$' ) { set $origin $http_origin; } add_header 'Access-Control-Allow-Origin' $origin always; add_header 'Access-Control-Allow-Credentials' 'true' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always; add_header 'Access-Control-Max-Age' '86400' always; add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,src,token' always; root /data/repo/solo_ci_front; access_log /data/repo/solo_ci/logs/nginx-access.log; error_log /data/repo/solo_ci/logs/nginx-error.log; client_body_temp_path /data/logs/nginx/client_body_temp/ 1 2; proxy_temp_path /data/logs/nginx/proxy_temp/ 1 2; # global location settings location /status { return 200; } location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Nginx-Proxy true; proxy_set_header Connection ""; proxy_pass http://solo-ci-public; } location ~ /\. { deny all; access_log off; log_not_found off; } } ================================================ FILE: conf/solo-ci.service ================================================ [Unit] Description = SmallSohoSolo Service [Service] ExecStart = /data/repo/solo_ci/solo-ci ================================================ FILE: controllers/project.go ================================================ package controllers import ( "github.com/astaxie/beego" "solo-ci/models" "solo-ci/utils" "fmt" "github.com/astaxie/beego/orm" "io/ioutil" "encoding/json" ) type ProjectController struct { beego.Controller } func (obj *ProjectController) Add() { project := new(models.Project) if err := obj.ParseForm(project); err != nil { obj.Data["json"] = utils.GetClientErrRender() } else { id, err := project.Add() if err != nil { obj.Data["json"] = utils.GetErrorRender(err.Error(), 400) } else { obj.Data["json"] = utils.GetSuccessRender(map[string]string{"project_id":id}) } } obj.ServeJSON() } func (obj *ProjectController) Delete() { projectId := obj.Ctx.Input.Param(":project_id") fmt.Println(projectId) project := &models.Project{ProjectId:projectId} err := project.Delete() if err != nil { obj.Data["json"] = utils.GetErrorRender(err.Error(), 400) } else { obj.Data["json"] = utils.GetSuccessRender(nil) } obj.ServeJSON() } func (obj *ProjectController) Update() { projectId := obj.Ctx.Input.Param(":project_id") project := &models.Project{ProjectId:projectId} if err := obj.ParseForm(project); err != nil { obj.Data["json"] = utils.GetClientErrRender() } else { err := project.Update() if err != nil { obj.Data["json"] = utils.GetErrorRender(err.Error(), 400) } else { obj.Data["json"] = utils.GetSuccessRender(nil) } } obj.ServeJSON() } func (obj *ProjectController) Get() { projectId := obj.Ctx.Input.Param(":project_id") project := &models.Project{ProjectId:projectId} err := project.Get() if err != nil { obj.Data["json"] = utils.GetErrorRender(err.Error(), 400) } else { obj.Data["json"] = utils.GetSuccessRender(project) } obj.ServeJSON() } func (obj *ProjectController) GetList() { page, _ := obj.GetInt("page", 0) pageSize, _ := obj.GetInt("pageSize", 20) obj.Data["json"] = utils.GetSuccessRender(models.GetList(page, pageSize)) obj.ServeJSON() } func (obj *ProjectController) WebHook() { //告诉git 接受成功 obj.Data["json"] = utils.GetSuccessRender(nil) obj.ServeJSON() //执行脚本 project := new(models.Project) project.ProjectId = obj.Ctx.Input.Param(":project_id") o := orm.NewOrm() if err := o.Read(project, "project_id"); err != nil && project.Name == "" { beego.Info("This object", project.ProjectId, "not exist") return } switch project.Type { case "gitlab": gitlabHook := new(models.GitlabHook) bodyMsg, _ := ioutil.ReadAll(obj.Ctx.Request.Body) beego.Info(string(bodyMsg)) json.Unmarshal(bodyMsg, gitlabHook) if gitlabHook.Ref != "refs/heads/" + project.Branch { beego.Info("Branch not same") return } if project.SecretToken != "" && obj.Ctx.Request.Header.Get("X-Gitlab-Token") != project.SecretToken { beego.Info(project.ProjectId, "Secret token error") return } go models.NewBuild(project) case "github": //githubHook := new(models.GithubHook) //bodyMsg, _ := ioutil.ReadAll(obj.Ctx.Request.Body) //beego.Info(string(bodyMsg)) //json.Unmarshal(bodyMsg, githubHook) //if githubHook.Ref != "refs/heads/" + project.Branch { // beego.Info("Branch not same") // return //} //if project.SecretToken != "" && obj.Ctx.Request.Header.Get("X-Hub-Signature") != project.SecretToken { // beego.Info(project.ProjectId, "Secret token error") // return //} go models.NewBuild(project) default: beego.Info("Don't have this type") } } ================================================ FILE: init/init.go ================================================ package init import ( "os" "os/exec" "github.com/astaxie/beego" "solo-ci/conf" ) func init() { //创建工作区 if _, err := os.Stat("workspace"); os.IsNotExist(err) { os.Mkdir("workspace", 0766) } if _, err := os.Stat("data"); os.IsNotExist(err) { os.Mkdir("data", 0766) } //检查git _, err := exec.Command("git", "--version").CombinedOutput() if err != nil { beego.Info("Git not Install") } //检查golang conf.GOPATH = os.Getenv("GOPATH") conf.GOROOT = os.Getenv("GOROOT") if conf.GOPATH == "" { beego.Info("GOPATH not set") } if conf.GOROOT == "" { beego.Info("GOROOT not set") } beego.Info("check success!") } ================================================ FILE: main.go ================================================ package main import ( "github.com/astaxie/beego" _ "solo-ci/init" _ "solo-ci/routers" ) func main() { beego.Run() } ================================================ FILE: models/build.go ================================================ package models import ( "time" "os/exec" "bytes" "os" "io/ioutil" "solo-ci/conf" "github.com/astaxie/beego/orm" "fmt" "encoding/json" "github.com/astaxie/beego" ) type Build struct { Id int `orm:"pk;auto;unique" json:"id"` //主键 Name string `json:"name" json:"name"` Result string `json:"result" json:"result"` Project *Project `orm:"rel(fk)" json:"-"` IsSuccess bool `json:"is_success"` } type BuildConfig struct { GetList []string `json:"get_list"` //Go get list ZipList []string `json:"zip_list"` //需要打包的文件 AfterScript string `json:"after_script"` //build 之后 BeforeScript string `json:"before_script"` //build 之前 } func NewBuild(project *Project) { //创建build 记录 build := new(Build) build.Project = project build.Name = time.Now().Format("2006-01-02T15:04:05.000Z") buildPath := getBuildPath(project, build) var result bytes.Buffer //git clone errGit := RunScript(result, []*exec.Cmd{ exec.Command("git", "clone", "-b", project.Branch, project.Url, buildPath), }) if errGit != nil { saveBuild(build, false, errGit, result) return } //read config fileData, errFile := getFileData(project, build) if errFile != nil { saveBuild(build, false, errFile, result) return } buildConfig := new(BuildConfig) errConfig := json.Unmarshal(fileData, buildConfig) if errConfig != nil { fmt.Println(errConfig) saveBuild(build, false, errConfig, result) return } fmt.Println(buildConfig) //BeforeScript if buildConfig.BeforeScript != "" { in := bytes.NewBuffer(nil) cmd := exec.Command("sh") cmd.Stdin = in in.WriteString("cd " + buildPath + "\n") in.WriteString(buildConfig.BeforeScript) beforeResp, errBefore := cmd.CombinedOutput() if errBefore != nil { saveBuild(build, false, errBefore, result) return } result.Write(beforeResp) } //exec config getList := make([]*exec.Cmd, len(buildConfig.GetList)) for index, pack := range buildConfig.GetList { getList[index] = exec.Command(conf.GOROOT + "/bin/go", "get", pack) } errGet := RunScript(result, getList) if errGet != nil { beego.Error(errGet.Error()) saveBuild(build, false, errGet, result) return } //exec build and clean errBuild := RunScript(result, []*exec.Cmd{ exec.Command("ln", "-s", buildPath, conf.GOPATH + "/src"), exec.Command(conf.GOROOT + "/bin/go", "build", "-o", build.Name, project.MainPath), exec.Command(conf.GOROOT + "/bin/go", "clean", build.Name), exec.Command(conf.GOROOT + "/bin/go", "test", build.Name), exec.Command("mv", build.Name, "workspace/" + project.Name + "/" + build.Name + "/" + project.Name), exec.Command("rm", conf.GOPATH + "/src/" + build.Name), }) if errBuild != nil { saveBuild(build, false, errBuild, result) return } //pack os.Mkdir(buildPath + "/pack-" + project.Name, 0766) if len(buildConfig.ZipList) != 0 { zipLength := len(buildConfig.GetList) zipList := make([]*exec.Cmd, zipLength) for index, pack := range buildConfig.ZipList { zipList[index] = exec.Command("cp", "-R", buildPath + "/" + pack, buildPath + "/pack-" + project.Name + "/") } errZip := RunScript(result, zipList) if errZip != nil { saveBuild(build, false, errZip, result) return } } exec.Command("cp", "-R", buildPath + "/" + project.Name, buildPath + "/pack-" + project.Name + "/").Run() exec.Command("tar", "-zcvf", buildPath + "/" + project.Name + ".tar.gz", "-C", buildPath, "pack-" + project.Name).Run() exec.Command("rm", "-rf", buildPath + "/pack-" + project.Name).Run() //AfterScript if buildConfig.AfterScript != "" { in := bytes.NewBuffer(nil) cmd := exec.Command("sh") cmd.Stdin = in in.WriteString("cd " + buildPath + "\n") in.WriteString(buildConfig.AfterScript) afterResp, errAfter := cmd.CombinedOutput() if errAfter != nil { saveBuild(build, false, errAfter, result) return } result.Write(afterResp) } //finish saveBuild(build, true, nil, result) } func getBuildPath(project *Project, build *Build) (string) { workSpace := GetWorkSpacePath(project) os.Mkdir(workSpace + "/" + build.Name, 0766) return workSpace + "/" + build.Name } func RunScript(result bytes.Buffer, cmdList []*exec.Cmd) (error) { for _, cmd := range cmdList { out, err := cmd.CombinedOutput() result.Write(out) if err != nil { result.WriteString(err.Error()) return err } } return nil } func getFileData(project *Project, build *Build) ([]byte, error) { file, errFile := os.Open(getBuildPath(project, build) + "/" + project.Path) if errFile != nil { return nil, errFile } defer file.Close() return ioutil.ReadAll(file) } func saveBuild(build *Build, status bool, err error, result bytes.Buffer) { if err != nil { result.WriteString(err.Error()) } build.IsSuccess = status build.Result = result.String() orm.NewOrm().Insert(build) } ================================================ FILE: models/github_hook.go ================================================ package models //Github config type GithubHook struct { Ref string`json:"ref"` } ================================================ FILE: models/gitlab_hook.go ================================================ package models //Gitlab config type GitlabHook struct { ObjectKind string `json:"object_kind"` EventName string `json:"event_name"` Ref string`json:"ref"` GitlabProject *GitlabProject `json:"project"` } type GitlabProject struct { Name string `json:"name"` Description string `json:"description"` WebUrl string `json:"web_url"` AvatarUrl string `json:"avatar_url"` GitSshUrl string `json:"git_ssh_url"` GitHttpUrl string `json:"git_http_url"` } ================================================ FILE: models/models.go ================================================ package models import ( "github.com/astaxie/beego/orm" "time" _ "github.com/mattn/go-sqlite3" "github.com/astaxie/beego" ) func init() { orm.RegisterDriver("sqlite3", orm.DRSqlite) orm.RegisterDataBase("default", "sqlite3", "data/data.db") orm.DefaultTimeLoc = time.UTC orm.RegisterModel(new(Project), new(Build)) verbose, _ := beego.AppConfig.Bool("Verbose") orm.RunSyncdb("default", false, verbose) } ================================================ FILE: models/project.go ================================================ package models import ( "errors" "os" "os/exec" "path" "path/filepath" "github.com/astaxie/beego/orm" "github.com/satori/go.uuid" ) type Project struct { Id int `orm:"pk;auto;unique" json:"id"` ProjectId string `json:"project_id"` //uuid Name string `json:"name" form:"name"` //name Type string `json:"type" form:"type"` //github,gitlab Url string `json:"url" form:"url"` //仓库地址 Path string `json:"path" form:"path"` //file 地址 Branch string `json:"branch" form:"branch"` //分支 MainPath string `json:"main_path" form:"main_path"` //main 文件地址 SecretToken string `json:"secret_token" form:"secret_token"` Build []*Build `orm:"reverse(many)" json:"-"` } // return id,err func (obj *Project) Add() (string, error) { //tiny bug fix here, should handle err u, _ := uuid.NewV1() obj.ProjectId = u.String() o := orm.NewOrm() qs := o.QueryTable("project") qs = qs.Filter("name", obj.Name) if count, err := qs.Count(); count != 0 { if err == nil { err = errors.New("Already Exist") } return "", err } else { _, err := o.Insert(obj) if err != nil { return "", err } else { return obj.ProjectId, nil } } } //return id,err func (obj *Project) Delete() error { o := orm.NewOrm() _, err := o.Delete(obj) if err != nil { return err } else { return nil } } //return isSuccess,err func (obj *Project) Update() error { o := orm.NewOrm() _, err := o.Update(obj) if err != nil { return err } else { return nil } } //return obj list,err func (obj *Project) Get() error { o := orm.NewOrm() qs := o.QueryTable(obj) err := qs.One(obj) if err != nil { return err } else { return nil } return nil } func GetList(page int, pageSize int) []*Project { qs := orm.NewOrm().QueryTable("project") qs = qs.Limit(pageSize, page) var list []*Project qs.All(&list) return list } func GetWorkSpacePath(project *Project) string { execFileRelativePath, _ := exec.LookPath(os.Args[0]) execDirRelativePath, _ := path.Split(execFileRelativePath) execDirAbsPath, _ := filepath.Abs(execDirRelativePath) if _, err := os.Stat(execDirAbsPath + "/workspace/" + project.Name); os.IsNotExist(err) { os.Mkdir(execDirAbsPath+"/workspace/"+project.Name, 0766) } return execDirAbsPath + "/workspace/" + project.Name } ================================================ FILE: routers/router.go ================================================ package routers import ( "github.com/astaxie/beego" "solo-ci/controllers" "net/http" ) func init() { ns := beego.NewNamespace("/v1", beego.NSRouter("/solohook/:project_id", &controllers.ProjectController{}, "post:WebHook"), beego.NSRouter("/project",&controllers.ProjectController{},"post:Add"), beego.NSRouter("/project/:project_id",&controllers.ProjectController{},"delete:Delete"), beego.NSRouter("/project/:project_id",&controllers.ProjectController{},"put:Update"), beego.NSRouter("/project/:project_id",&controllers.ProjectController{},"get:Get"), beego.NSRouter("/project",&controllers.ProjectController{},"get:GetList"), ) beego.AddNamespace(ns) beego.ErrorHandler("404", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) }) } ================================================ FILE: solocifile ================================================ { } ================================================ FILE: test/normal_test.go ================================================ package test import ( "testing" ) func Test_NormalTest(t *testing.T) { t.Log("") } ================================================ FILE: utils/return_struct.go ================================================ package utils type RenderStruct struct { S int `json:"s"` M string `json:"m"` D interface{} `json:"d"` } func GetSuccessRender(list interface{}) (*RenderStruct) { render := new(RenderStruct) render.S = 200 render.M = "success" if list == nil { list = []string{} } render.D = list return render } func GetErrorRender(message string, code int) (*RenderStruct) { render := new(RenderStruct) render.S = code render.M = message render.D = []string{} return render } func GetClientErrRender() (*RenderStruct) { render := new(RenderStruct) render.S = 400 render.M = "input error" render.D = []string{} return render } func GetServerErrRender() (*RenderStruct) { render := new(RenderStruct) render.S = 500 render.M = "server error" render.D = []string{} return render }