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