Compare commits

..

5 Commits

13 changed files with 725 additions and 57 deletions

120
README.md
View File

@ -201,11 +201,13 @@ COMMANDS:
pipeline, pipelines, pl 流水线 API中文文档https://docs.gitlab.cn/jh/api/pipelines.html
project-level-variables, project-level-variable, plv 项目级别 CI/CD 变量 API中文文档https://docs.gitlab.cn/jh/api/project_level_variables.html
project, projects, p 项目 API中文文档https://docs.gitlab.cn/jh/api/projects.html
protected-branches, pb 受保护的分支 API中文文档https://docs.gitlab.cn/jh/api/protected_branches.html
mix-archive 归档(混合命令,多接口命令)
mix-create-project-level-variables 创建项目级别 CI/CD 变量(混合命令,多接口命令)
mix-delete, mix-rm 删除(混合命令,多接口命令)
mix-create-environments, mix-create-environment, mix-create-env 创建新环境(混合命令,多接口命令)
mix-export 导出(混合命令,多接口命令)
mix-protect-branches 保护仓库分支(混合命令,多接口命令)
mix-transfer 转移(混合命令,多接口命令)
mix-unarchive 取消归档(混合命令,多接口命令)
help, h Shows a list of commands or help for one command
@ -542,6 +544,7 @@ COPYRIGHT:
OPTIONS:
--base-url value 实例地址例如https://gitlab.xuxiaowei.com.cn/api/v4 (default: "https://gitlab.com/api/v4") [%CI_API_V4_URL%]
--token value your_access_token
--owned 当前用户明确拥有的项目。 (default: false)
--sort value 按照 asc 或者 desc 排序 (default: "desc")
--page value 页码默认1中文文档 https://docs.gitlab.cn/jh/api/rest/index.html#pagination (default: 1)
--per-page value 每页列出的项目数默认20最大100中文文档 https://docs.gitlab.cn/jh/api/rest/index.html#pagination (default: 20)
@ -553,6 +556,66 @@ COPYRIGHT:
--help, -h show help
```
- [protected-branches 受保护的分支 API](https://docs.gitlab.cn/jh/api/protected_branches.html)
```shell
$ go run main.go protected-branches --help
NAME:
gitlab-go protected-branches - 受保护的分支 API中文文档https://docs.gitlab.cn/jh/api/protected_branches.html
USAGE:
gitlab-go protected-branches command [command options]
COMMANDS:
list 列出受保护的分支
protect 保护仓库分支
help, h Shows a list of commands or help for one command
OPTIONS:
--base-url value 实例地址例如https://gitlab.xuxiaowei.com.cn/api/v4 (default: "https://gitlab.com/api/v4") [%CI_API_V4_URL%]
--token value your_access_token
--id value 项目 ID 或 URL 编码的路径
--search value 要搜索的受保护分支的名称或部分名称
--name value 分支或通配符的名称
--push-access-level value 允许推送的访问级别默认值40维护者角色合法值
0NoPermissions
5MinimalAccessPermissions
10GuestPermissions
20ReporterPermissions
30DeveloperPermissions
40MaintainerPermissions
50OwnerPermissions
60AdminPermissions
(default: 40)
--merge-access-level value 允许合并的访问级别默认值40维护者角色合法值
0NoPermissions
5MinimalAccessPermissions
10GuestPermissions
20ReporterPermissions
30DeveloperPermissions
40MaintainerPermissions
50OwnerPermissions
60AdminPermissions
(default: 40)
--unprotect-access-level value 允许取消保护的访问级别默认值40维护者角色合法值
0NoPermissions
5MinimalAccessPermissions
10GuestPermissions
20ReporterPermissions
30DeveloperPermissions
40MaintainerPermissions
50OwnerPermissions
60AdminPermissions
(default: 40)
--allow-force-push 启用后,可以推送到该分支的成员也可以强制推送 (default: false)
--code-owner-approval-required 如果分支在 CODEOWNERS https://docs.gitlab.cn/jh/user/project/codeowners/index.html 文件中则阻止推送到此分支。默认值false (default: false)
--page value 页码默认1中文文档 https://docs.gitlab.cn/jh/api/rest/index.html#pagination (default: 1)
--per-page value 每页列出的项目数默认20最大100中文文档 https://docs.gitlab.cn/jh/api/rest/index.html#pagination (default: 20)
--print-json 打印 JSON (default: false)
--print-time 打印时间 (default: false)
--help, -h show help
```
- mix-archive 归档(混合命令,多接口命令)
```shell
@ -632,6 +695,7 @@ COPYRIGHT:
多个数字使用英文逗号隔开1,2,3,7,8,15
支持范围5-10,
支持范围方向选择:-10小于等于10从 0 到 10214-大于等于214从 214 到 214 + 10000数据范围不超过 10000
--allow-failure 允许失败 (default: false)
--help, -h show help
```
@ -691,6 +755,62 @@ COPYRIGHT:
--help, -h show help
```
- 保护仓库分支(混合命令,多接口命令)
```shell
$ go run main.go mix-protect-branches --help
NAME:
gitlab-go mix-protect-branches - 保护仓库分支(混合命令,多接口命令)
USAGE:
gitlab-go mix-protect-branches command [command options]
COMMANDS:
all, a 保护所有仓库分支
help, h Shows a list of commands or help for one command
OPTIONS:
--base-url value 实例地址例如https://gitlab.xuxiaowei.com.cn/api/v4 (default: "https://gitlab.com/api/v4") [%CI_API_V4_URL%]
--token value your_access_token
--owned 当前用户明确拥有的项目。 (default: false)
--name value 分支或通配符的名称
--push-access-level value 允许推送的访问级别默认值40维护者角色合法值
0NoPermissions
5MinimalAccessPermissions
10GuestPermissions
20ReporterPermissions
30DeveloperPermissions
40MaintainerPermissions
50OwnerPermissions
60AdminPermissions
(default: 40)
--merge-access-level value 允许合并的访问级别默认值40维护者角色合法值
0NoPermissions
5MinimalAccessPermissions
10GuestPermissions
20ReporterPermissions
30DeveloperPermissions
40MaintainerPermissions
50OwnerPermissions
60AdminPermissions
(default: 40)
--unprotect-access-level value 允许取消保护的访问级别默认值40维护者角色合法值
0NoPermissions
5MinimalAccessPermissions
10GuestPermissions
20ReporterPermissions
30DeveloperPermissions
40MaintainerPermissions
50OwnerPermissions
60AdminPermissions
(default: 40)
--allow-force-push 启用后,可以推送到该分支的成员也可以强制推送 (default: false)
--code-owner-approval-required 如果分支在 CODEOWNERS https://docs.gitlab.cn/jh/user/project/codeowners/index.html 文件中则阻止推送到此分支。默认值false (default: false)
--print-json 打印 JSON (default: false)
--print-time 打印时间 (default: false)
--help, -h show help
```
- 转移(混合命令,多接口命令)
```shell

View File

@ -1,44 +1,51 @@
package constant
const (
Token = "token"
BaseUrl = "base-url"
BaseUrlDefault = "https://gitlab.com/api/v4"
Id = "id"
JobIdRange = "job-id-range"
IIdRange = "iid-range"
Repository = "repository"
TagName = "tag-name"
JobId = "job-id"
ArtifactsName = "artifacts-name"
Sort = "sort"
SortDefault = "desc"
Page = "page"
PerPage = "per-page"
PrintJson = "print-json"
PrintJsonDefault = false
PrintTime = "print-time"
PrintTimeDefault = false
Scope = "scope"
IssueId = "issue-id"
IssueIdRange = "issue-id-range"
Recursion = "recursion"
Owned = "owned"
NamespaceSource = "namespace-source"
NamespaceTarget = "namespace-target"
ExportFolder = "export-folder"
SkipProjectPath = "skip-project-path"
SkipProjectWikiPath = "skip-project-wiki-path"
AutoSkipExistFolder = "auto-skip-exist-folder"
AllowFailure = "allow-failure"
EnvName = "name"
EnvExternalUrl = "external-url"
EnvTier = "tier"
VariableKey = "key"
VariableValue = "value"
VariableType = "variable-type"
VariableProtected = "protected"
VariableMasked = "masked"
VariableRaw = "raw"
VariableEnvironmentScope = "environment-scope"
Token = "token"
BaseUrl = "base-url"
BaseUrlDefault = "https://gitlab.com/api/v4"
Id = "id"
JobIdRange = "job-id-range"
IIdRange = "iid-range"
Repository = "repository"
TagName = "tag-name"
JobId = "job-id"
ArtifactsName = "artifacts-name"
Sort = "sort"
SortDefault = "desc"
Page = "page"
PerPage = "per-page"
PrintJson = "print-json"
PrintJsonDefault = false
PrintTime = "print-time"
PrintTimeDefault = false
Scope = "scope"
IssueId = "issue-id"
IssueIdRange = "issue-id-range"
Recursion = "recursion"
Owned = "owned"
NamespaceSource = "namespace-source"
NamespaceTarget = "namespace-target"
ExportFolder = "export-folder"
SkipProjectPath = "skip-project-path"
SkipProjectWikiPath = "skip-project-wiki-path"
AutoSkipExistFolder = "auto-skip-exist-folder"
AllowFailure = "allow-failure"
EnvName = "name"
EnvExternalUrl = "external-url"
EnvTier = "tier"
VariableKey = "key"
VariableValue = "value"
VariableType = "variable-type"
VariableProtected = "protected"
VariableMasked = "masked"
VariableRaw = "raw"
VariableEnvironmentScope = "environment-scope"
ProtectedBranchesSearch = "search"
BranchName = "name"
PushAccessLevel = "push-access-level"
MergeAccessLevel = "merge-access-level"
UnprotectAccessLevel = "unprotect-access-level"
AllowForcePush = "allow-force-push"
CodeOwnerApprovalRequired = "code-owner-approval-required"
)

View File

@ -327,3 +327,82 @@ func VariableEnvironmentScope() cli.Flag {
Value: "*",
}
}
func ProtectedBranchesSearch() cli.Flag {
return &cli.StringFlag{
Name: constant.ProtectedBranchesSearch,
Usage: "要搜索的受保护分支的名称或部分名称",
}
}
func BranchName(required bool) cli.Flag {
return &cli.StringFlag{
Name: constant.BranchName,
Usage: "分支或通配符的名称",
Required: required,
}
}
func PushAccessLevel() cli.Flag {
return &cli.IntFlag{
Name: constant.PushAccessLevel,
Usage: "允许推送的访问级别默认值40维护者角色合法值\n\t" +
"0NoPermissions\n\t" +
"5MinimalAccessPermissions\n\t" +
"10GuestPermissions\n\t" +
"20ReporterPermissions\n\t" +
"30DeveloperPermissions\n\t" +
"40MaintainerPermissions\n\t" +
"50OwnerPermissions\n\t" +
"60AdminPermissions\n\t",
Value: 40,
}
}
func MergeAccessLevel() cli.Flag {
return &cli.IntFlag{
Name: constant.MergeAccessLevel,
Usage: "允许合并的访问级别默认值40维护者角色合法值\n\t" +
"0NoPermissions\n\t" +
"5MinimalAccessPermissions\n\t" +
"10GuestPermissions\n\t" +
"20ReporterPermissions\n\t" +
"30DeveloperPermissions\n\t" +
"40MaintainerPermissions\n\t" +
"50OwnerPermissions\n\t" +
"60AdminPermissions\n\t",
Value: 40,
}
}
func UnprotectAccessLevel() cli.Flag {
return &cli.IntFlag{
Name: constant.UnprotectAccessLevel,
Usage: "允许取消保护的访问级别默认值40维护者角色合法值\n\t" +
"0NoPermissions\n\t" +
"5MinimalAccessPermissions\n\t" +
"10GuestPermissions\n\t" +
"20ReporterPermissions\n\t" +
"30DeveloperPermissions\n\t" +
"40MaintainerPermissions\n\t" +
"50OwnerPermissions\n\t" +
"60AdminPermissions\n\t",
Value: 40,
}
}
func AllowForcePush() cli.Flag {
return &cli.BoolFlag{
Name: constant.AllowForcePush,
Usage: "启用后,可以推送到该分支的成员也可以强制推送",
Value: false,
}
}
func CodeOwnerApprovalRequired() cli.Flag {
return &cli.BoolFlag{
Name: constant.CodeOwnerApprovalRequired,
Usage: "如果分支在 CODEOWNERS https://docs.gitlab.cn/jh/user/project/codeowners/index.html 文件中则阻止推送到此分支。默认值false",
Value: false,
}
}

View File

@ -15,6 +15,7 @@ import (
"github.com/xuxiaowei-com-cn/gitlab-go/pipelines"
"github.com/xuxiaowei-com-cn/gitlab-go/project_level_variables"
"github.com/xuxiaowei-com-cn/gitlab-go/projects"
"github.com/xuxiaowei-com-cn/gitlab-go/protected_branches"
"gopkg.in/yaml.v3"
"log"
"os"
@ -80,11 +81,13 @@ func main() {
pipelines.Pipelines(),
project_level_variables.ProjectLevelVariables(),
projects.Projects(),
protected_branches.ProtectedBranches(),
mix.Archive(),
mix.CreateProjectLevelVariables(),
mix.Delete(),
mix.Environments(),
mix.Export(),
mix.ProtectBranches(),
mix.Transfer(),
mix.Unarchive(),
},

View File

@ -18,7 +18,8 @@ func DeleteJobs() *cli.Command {
Name: "job",
Aliases: []string{"jobs"},
Usage: "根据项目路径/ID、流水线IID范围删除作业产物和作业日志混合命令多接口命令立即删除",
Flags: append(flag.CommonTokenRequired(), flag.Sort(), flag.Page(), flag.PerPage(), flag.Id(true), flag.IIdRange(true)),
Flags: append(flag.CommonTokenRequired(), flag.Sort(), flag.Page(), flag.PerPage(), flag.Id(true),
flag.IIdRange(true), flag.AllowFailure()),
Action: func(context *cli.Context) error {
var baseUrl = context.String(constant.BaseUrl)
var token = context.String(constant.Token)
@ -27,6 +28,7 @@ func DeleteJobs() *cli.Command {
var page = context.Int(constant.Page)
var perPage = context.Int(constant.PerPage)
var iidRanges = context.StringSlice(constant.IIdRange)
var allowFailure = context.Bool(constant.AllowFailure)
fmt.Println(iidRanges)
gitClient, err := gitlab.NewClient(token, gitlab.WithBaseURL(baseUrl))
@ -45,7 +47,7 @@ func DeleteJobs() *cli.Command {
return nil
}
err = DeleteJobsRecursion(gitClient, id, page, perPage, sortStr, iids)
err = DeleteJobsRecursion(gitClient, id, page, perPage, sortStr, iids, allowFailure)
if err != nil {
return err
}
@ -55,7 +57,7 @@ func DeleteJobs() *cli.Command {
}
}
func DeleteJobsRecursion(gitClient *gitlab.Client, id interface{}, page int, perPage int, sort string, iids []int) error {
func DeleteJobsRecursion(gitClient *gitlab.Client, id interface{}, page int, perPage int, sort string, iids []int, allowFailure bool) error {
pipelineInfos, response, err := pipelines.ListProjectPipelines(gitClient, id, page, perPage, sort)
@ -78,26 +80,26 @@ func DeleteJobsRecursion(gitClient *gitlab.Client, id interface{}, page int, per
if iidsMin == pipelineInfo.IID {
// 等于最小值,删除最小值
iids = iids[1:]
err = ExecuteDeleteJobs(gitClient, id, pipelineInfo.ID, 1, 100)
err = ExecuteDeleteJobs(gitClient, id, pipelineInfo.ID, 1, 100, allowFailure)
if err != nil {
return err
}
} else if pipelineInfo.IID == iidsMax {
// 等于最大值
iids = iids[:len(iids)-1]
err = ExecuteDeleteJobs(gitClient, id, pipelineInfo.ID, 1, 100)
err = ExecuteDeleteJobs(gitClient, id, pipelineInfo.ID, 1, 100, allowFailure)
if err != nil {
return err
}
} else if iidsMin < pipelineInfo.IID {
// 大于最小值
err = jobsForExecute(&iids, pipelineInfo.IID, gitClient, id, pipelineInfo.ID)
err = jobsForExecute(&iids, pipelineInfo.IID, gitClient, id, pipelineInfo.ID, allowFailure)
if err != nil {
return err
}
} else if pipelineInfo.IID < iidsMax {
// 小于最大值
err = jobsForExecute(&iids, pipelineInfo.IID, gitClient, id, pipelineInfo.ID)
err = jobsForExecute(&iids, pipelineInfo.IID, gitClient, id, pipelineInfo.ID, allowFailure)
if err != nil {
return err
}
@ -115,7 +117,7 @@ func DeleteJobsRecursion(gitClient *gitlab.Client, id interface{}, page int, per
}
if len(pipelineInfos) > 0 {
err := DeleteJobsRecursion(gitClient, id, page+1, perPage, sort, iids)
err := DeleteJobsRecursion(gitClient, id, page+1, perPage, sort, iids, allowFailure)
if err != nil {
return err
}
@ -124,13 +126,16 @@ func DeleteJobsRecursion(gitClient *gitlab.Client, id interface{}, page int, per
return nil
}
func jobsForExecute(iids *[]int, pipelineInfoIId int, gitClient *gitlab.Client, id interface{}, pipelineInfoId int) error {
func jobsForExecute(iids *[]int, pipelineInfoIId int, gitClient *gitlab.Client, id interface{}, pipelineInfoId int, allowFailure bool) error {
for i := 0; i < len(*iids); i++ {
if (*iids)[i] == pipelineInfoIId {
fmt.Printf("数组中包含%d\n", pipelineInfoIId)
*iids = append((*iids)[:i], (*iids)[i+1:]...)
err := ExecuteDeleteJobs(gitClient, id, pipelineInfoId, 1, 100)
err := ExecuteDeleteJobs(gitClient, id, pipelineInfoId, 1, 100, allowFailure)
if err != nil {
if allowFailure {
return nil
}
return err
}
break
@ -139,7 +144,7 @@ func jobsForExecute(iids *[]int, pipelineInfoIId int, gitClient *gitlab.Client,
return nil
}
func ExecuteDeleteJobs(gitClient *gitlab.Client, id interface{}, pipelineInfoId int, page int, perPage int) error {
func ExecuteDeleteJobs(gitClient *gitlab.Client, id interface{}, pipelineInfoId int, page int, perPage int, allowFailure bool) error {
fmt.Printf("执行删除 %d \n", pipelineInfoId)
opt := &gitlab.ListJobsOptions{
@ -160,13 +165,16 @@ func ExecuteDeleteJobs(gitClient *gitlab.Client, id interface{}, pipelineInfoId
_, response, err = gitClient.Jobs.EraseJob(id, job.ID)
if err != nil {
if allowFailure {
return nil
}
return err
}
log.Printf("Delete Project %s Job %d Response StatusCode: %d\n", id, job.ID, response.Response.StatusCode)
}
if len(jobs) == perPage {
err = ExecuteDeleteJobs(gitClient, id, pipelineInfoId, page+1, perPage)
err = ExecuteDeleteJobs(gitClient, id, pipelineInfoId, page+1, perPage, allowFailure)
if err != nil {
return err
}

View File

@ -11,7 +11,8 @@ func Delete() *cli.Command {
Name: "mix-delete",
Aliases: []string{"mix-rm"},
Usage: "删除(混合命令,多接口命令)",
Flags: append(flag.Common(), flag.Sort(), flag.Page(), flag.PerPage(), flag.Id(false), flag.IIdRange(false)),
Flags: append(flag.Common(), flag.Sort(), flag.Page(), flag.PerPage(), flag.Id(false),
flag.IIdRange(false), flag.AllowFailure()),
Subcommands: []*cli.Command{
DeleteArtifacts(),
DeleteAllArtifacts(),

View File

@ -0,0 +1,21 @@
package mix
import (
"github.com/urfave/cli/v2"
"github.com/xuxiaowei-com-cn/gitlab-go/flag"
)
// ProtectBranches 保护仓库分支
func ProtectBranches() *cli.Command {
return &cli.Command{
Name: "mix-protect-branches",
Usage: "保护仓库分支(混合命令,多接口命令)",
Flags: append(flag.Common(), flag.Owned(false),
flag.BranchName(false), flag.PushAccessLevel(), flag.MergeAccessLevel(),
flag.UnprotectAccessLevel(), flag.AllowForcePush(), flag.CodeOwnerApprovalRequired(),
flag.PrintJson(), flag.PrintTime()),
Subcommands: []*cli.Command{
ProtectBranchesAll(),
},
}
}

View File

@ -0,0 +1,58 @@
package mix
import (
"github.com/urfave/cli/v2"
"github.com/xuxiaowei-com-cn/gitlab-go/constant"
"github.com/xuxiaowei-com-cn/gitlab-go/flag"
"github.com/xuxiaowei-com-cn/gitlab-go/projects"
"github.com/xuxiaowei-com-cn/gitlab-go/protected_branches"
"log"
)
// ProtectBranchesAll 保护所有仓库分支
func ProtectBranchesAll() *cli.Command {
return &cli.Command{
Name: "all",
Aliases: []string{"a"},
Usage: "保护所有仓库分支",
Flags: append(flag.CommonTokenRequired(), flag.Owned(true),
flag.BranchName(true), flag.PushAccessLevel(), flag.MergeAccessLevel(),
flag.UnprotectAccessLevel(), flag.AllowForcePush(), flag.CodeOwnerApprovalRequired(),
flag.AllowFailure(),
flag.PrintJson(), flag.PrintTime()),
Action: func(context *cli.Context) error {
var baseUrl = context.String(constant.BaseUrl)
var token = context.String(constant.Token)
var owned = context.Bool(constant.Owned)
var name = context.String(constant.BranchName)
var pushAccessLevel = context.Int(constant.PushAccessLevel)
var mergeAccessLevel = context.Int(constant.MergeAccessLevel)
var unprotectAccessLevel = context.Int(constant.UnprotectAccessLevel)
var allowForcePush = context.Bool(constant.AllowForcePush)
var codeOwnerApprovalRequired = context.Bool(constant.CodeOwnerApprovalRequired)
var printJson = context.Bool(constant.PrintJson)
var printTime = context.Bool(constant.PrintTime)
var allowFailure = context.Bool(constant.AllowFailure)
projectList, err := projects.ListProjects(owned, token, baseUrl, 1, 100)
if err != nil {
return err
}
for index, project := range projectList {
log.Printf("Project Index: %d, WebURL: %s", index, project.WebURL)
err = protected_branches.ProtectRepositoryBranches(baseUrl, token, project.ID, name,
pushAccessLevel, mergeAccessLevel, unprotectAccessLevel, allowForcePush, codeOwnerApprovalRequired,
printJson, printTime, allowFailure)
if err != nil {
return err
}
}
return nil
},
}
}

View File

@ -15,12 +15,13 @@ func List() *cli.Command {
return &cli.Command{
Name: "list",
Usage: "列出所有项目",
Flags: append(flag.Common(), flag.Sort(), flag.Page(), flag.PerPage(), flag.PrintJson(), flag.PrintTime(),
flag.Search(), flag.SearchNamespaces(),
Flags: append(flag.Common(), flag.Owned(true), flag.Sort(), flag.Page(), flag.PerPage(),
flag.PrintJson(), flag.PrintTime(), flag.Search(), flag.SearchNamespaces(),
flag.OrderBy(OrderByUsage)),
Action: func(context *cli.Context) error {
var baseUrl = context.String(constant.BaseUrl)
var token = context.String(constant.Token)
var owned = context.Bool(constant.Owned)
var sort = context.String(constant.Sort)
var page = context.Int(constant.Page)
var perPage = context.Int(constant.PerPage)
@ -43,6 +44,7 @@ func List() *cli.Command {
Sort: &sort,
Search: &search,
SearchNamespaces: &searchNamespaces,
Owned: &owned,
OrderBy: &orderBy,
}
projects, response, err := gitClient.Projects.ListProjects(opt)

View File

@ -18,8 +18,8 @@ func Projects() *cli.Command {
Name: "project",
Aliases: []string{"projects", "p"},
Usage: "项目 API中文文档https://docs.gitlab.cn/jh/api/projects.html",
Flags: append(flag.Common(), flag.Sort(), flag.Page(), flag.PerPage(), flag.PrintJson(), flag.PrintTime(),
flag.Search(), flag.SearchNamespaces(),
Flags: append(flag.Common(), flag.Owned(false), flag.Sort(), flag.Page(), flag.PerPage(),
flag.PrintJson(), flag.PrintTime(), flag.Search(), flag.SearchNamespaces(),
flag.OrderBy(OrderByUsage)),
Subcommands: []*cli.Command{
List(),

151
protected_branches/list.go Normal file
View File

@ -0,0 +1,151 @@
package protected_branches
import (
"encoding/json"
"fmt"
"github.com/urfave/cli/v2"
"github.com/xanzy/go-gitlab"
"github.com/xuxiaowei-com-cn/gitlab-go/constant"
"github.com/xuxiaowei-com-cn/gitlab-go/flag"
"log"
)
// List 列出受保护的分支 https://docs.gitlab.cn/jh/api/protected_branches.html#%E5%88%97%E5%87%BA%E5%8F%97%E4%BF%9D%E6%8A%A4%E7%9A%84%E5%88%86%E6%94%AF
func List() *cli.Command {
return &cli.Command{
Name: "list",
Usage: "列出受保护的分支",
Flags: append(flag.CommonTokenRequired(), flag.Id(true), flag.ProtectedBranchesSearch(),
flag.Page(), flag.PerPage(), flag.PrintJson(), flag.PrintTime()),
Action: func(context *cli.Context) error {
var baseUrl = context.String(constant.BaseUrl)
var token = context.String(constant.Token)
var id = context.String(constant.Id)
var search = context.String(constant.Search)
var page = context.Int(constant.Page)
var perPage = context.Int(constant.PerPage)
var printJson = context.Bool(constant.PrintJson)
var printTime = context.Bool(constant.PrintTime)
gitClient, err := gitlab.NewClient(token, gitlab.WithBaseURL(baseUrl))
if err != nil {
return err
}
opt := &gitlab.ListProtectedBranchesOptions{
Search: &search,
ListOptions: gitlab.ListOptions{
Page: page,
PerPage: perPage,
},
}
protectedBranchs, response, err := gitClient.ProtectedBranches.ListProtectedBranches(id, opt)
if err != nil {
return err
}
log.Printf("Page %d, PerPage: %d, Response StatusCode: %d\n", page, perPage, response.Response.StatusCode)
fmt.Println("")
if printJson {
if printTime {
for _, protectedBranch := range protectedBranchs {
jsonData, err := json.Marshal(protectedBranch)
if err != nil {
panic(err)
}
log.Printf("\n%s\n", string(jsonData))
fmt.Println("")
}
} else {
for _, protectedBranch := range protectedBranchs {
jsonData, err := json.Marshal(protectedBranch)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", string(jsonData))
fmt.Println("")
}
}
} else {
if printTime {
for _, protectedBranch := range protectedBranchs {
log.Printf("ID: %d\n", protectedBranch.ID)
log.Printf("Name: %s\n", protectedBranch.Name)
log.Printf("AllowForcePush: %t\n", protectedBranch.AllowForcePush)
log.Printf("CodeOwnerApprovalRequired: %t\n", protectedBranch.CodeOwnerApprovalRequired)
log.Printf("PushAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.PushAccessLevels {
log.Printf("PushAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
log.Printf("PushAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
log.Printf("PushAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
log.Printf("PushAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
log.Printf("PushAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
log.Printf("MergeAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.MergeAccessLevels {
log.Printf("MergeAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
log.Printf("MergeAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
log.Printf("MergeAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
log.Printf("MergeAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
log.Printf("MergeAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
log.Printf("UnprotectAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.UnprotectAccessLevels {
log.Printf("UnprotectAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
log.Printf("UnprotectAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
log.Printf("UnprotectAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
log.Printf("UnprotectAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
log.Printf("UnprotectAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
fmt.Println("")
}
} else {
for _, protectedBranch := range protectedBranchs {
fmt.Printf("ID: %d\n", protectedBranch.ID)
fmt.Printf("Name: %s\n", protectedBranch.Name)
fmt.Printf("AllowForcePush: %t\n", protectedBranch.AllowForcePush)
fmt.Printf("CodeOwnerApprovalRequired: %t\n", protectedBranch.CodeOwnerApprovalRequired)
fmt.Printf("PushAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.PushAccessLevels {
fmt.Printf("PushAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
fmt.Printf("PushAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
fmt.Printf("PushAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
fmt.Printf("PushAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
fmt.Printf("PushAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
fmt.Printf("MergeAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.MergeAccessLevels {
fmt.Printf("MergeAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
fmt.Printf("MergeAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
fmt.Printf("MergeAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
fmt.Printf("MergeAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
fmt.Printf("MergeAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
fmt.Printf("UnprotectAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.UnprotectAccessLevels {
fmt.Printf("UnprotectAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
fmt.Printf("UnprotectAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
fmt.Printf("UnprotectAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
fmt.Printf("UnprotectAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
fmt.Printf("UnprotectAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
fmt.Println("")
}
}
}
return nil
},
}
}

View File

@ -0,0 +1,195 @@
package protected_branches
import (
"encoding/json"
"errors"
"fmt"
"github.com/urfave/cli/v2"
"github.com/xanzy/go-gitlab"
"github.com/xuxiaowei-com-cn/gitlab-go/constant"
"github.com/xuxiaowei-com-cn/gitlab-go/flag"
"log"
)
// Protect 保护仓库分支 https://docs.gitlab.cn/jh/api/protected_branches.html#%E4%BF%9D%E6%8A%A4%E4%BB%93%E5%BA%93%E5%88%86%E6%94%AF
func Protect() *cli.Command {
return &cli.Command{
Name: "protect",
Usage: "保护仓库分支",
Flags: append(flag.CommonTokenRequired(), flag.Id(true),
flag.BranchName(true), flag.PushAccessLevel(), flag.MergeAccessLevel(),
flag.UnprotectAccessLevel(), flag.AllowForcePush(), flag.CodeOwnerApprovalRequired(),
flag.PrintJson(), flag.PrintTime()),
Action: func(context *cli.Context) error {
var baseUrl = context.String(constant.BaseUrl)
var token = context.String(constant.Token)
var id = context.String(constant.Id)
var name = context.String(constant.BranchName)
var pushAccessLevel = context.Int(constant.PushAccessLevel)
var mergeAccessLevel = context.Int(constant.MergeAccessLevel)
var unprotectAccessLevel = context.Int(constant.UnprotectAccessLevel)
var allowForcePush = context.Bool(constant.AllowForcePush)
var codeOwnerApprovalRequired = context.Bool(constant.CodeOwnerApprovalRequired)
var printJson = context.Bool(constant.PrintJson)
var printTime = context.Bool(constant.PrintTime)
return ProtectRepositoryBranches(baseUrl, token, id, name,
pushAccessLevel, mergeAccessLevel, unprotectAccessLevel, allowForcePush, codeOwnerApprovalRequired,
printJson, printTime, false)
},
}
}
func ProtectRepositoryBranches(baseUrl string, token string, id interface{}, name string,
pushAccessLevel int, mergeAccessLevel int, unprotectAccessLevel int, allowForcePush bool, codeOwnerApprovalRequired bool,
printJson bool, printTime bool, allowFailure bool) error {
gitClient, err := gitlab.NewClient(token, gitlab.WithBaseURL(baseUrl))
if err != nil {
return err
}
var pushAccessLevelValue gitlab.AccessLevelValue
switch pushAccessLevel {
case 0, 5, 10, 20, 30, 40, 50, 60:
pushAccessLevelValue = gitlab.AccessLevelValue(pushAccessLevel)
default:
return errors.New(fmt.Sprintf("pushAccessLevel%d 不合法", pushAccessLevel))
}
var mergeAccessLevelValue gitlab.AccessLevelValue
switch mergeAccessLevel {
case 0, 5, 10, 20, 30, 40, 50, 60:
mergeAccessLevelValue = gitlab.AccessLevelValue(mergeAccessLevel)
default:
return errors.New(fmt.Sprintf("mergeAccessLevel%d 不合法", mergeAccessLevel))
}
var unprotectAccessLevelValue gitlab.AccessLevelValue
switch unprotectAccessLevel {
case 0, 5, 10, 20, 30, 40, 50, 60:
unprotectAccessLevelValue = gitlab.AccessLevelValue(unprotectAccessLevel)
default:
return errors.New(fmt.Sprintf("unprotectAccessLevel%d 不合法", unprotectAccessLevel))
}
opt := &gitlab.ProtectRepositoryBranchesOptions{
Name: &name,
PushAccessLevel: &pushAccessLevelValue,
MergeAccessLevel: &mergeAccessLevelValue,
UnprotectAccessLevel: &unprotectAccessLevelValue,
AllowForcePush: &allowForcePush,
//AllowedToPush: &allowedToPush,
//AllowedToMerge: &allowedToMerge,
//AllowedToUnprotect: &allowedToUnprotect,
CodeOwnerApprovalRequired: &codeOwnerApprovalRequired,
}
protectedBranch, response, err := gitClient.ProtectedBranches.ProtectRepositoryBranches(id, opt)
if err != nil {
if allowFailure {
return nil
}
return err
}
log.Printf("Response StatusCode: %d\n", response.Response.StatusCode)
fmt.Println("")
if printJson {
if printTime {
jsonData, err := json.Marshal(protectedBranch)
if err != nil {
panic(err)
}
log.Printf("\n%s\n", string(jsonData))
fmt.Println("")
} else {
jsonData, err := json.Marshal(protectedBranch)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", string(jsonData))
fmt.Println("")
}
} else {
if printTime {
log.Printf("ID: %d\n", protectedBranch.ID)
log.Printf("Name: %s\n", protectedBranch.Name)
log.Printf("AllowForcePush: %t\n", protectedBranch.AllowForcePush)
log.Printf("CodeOwnerApprovalRequired: %t\n", protectedBranch.CodeOwnerApprovalRequired)
log.Printf("PushAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.PushAccessLevels {
log.Printf("PushAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
log.Printf("PushAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
log.Printf("PushAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
log.Printf("PushAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
log.Printf("PushAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
log.Printf("MergeAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.MergeAccessLevels {
log.Printf("MergeAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
log.Printf("MergeAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
log.Printf("MergeAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
log.Printf("MergeAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
log.Printf("MergeAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
log.Printf("UnprotectAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.UnprotectAccessLevels {
log.Printf("UnprotectAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
log.Printf("UnprotectAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
log.Printf("UnprotectAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
log.Printf("UnprotectAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
log.Printf("UnprotectAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
fmt.Println("")
} else {
fmt.Printf("ID: %d\n", protectedBranch.ID)
fmt.Printf("Name: %s\n", protectedBranch.Name)
fmt.Printf("AllowForcePush: %t\n", protectedBranch.AllowForcePush)
fmt.Printf("CodeOwnerApprovalRequired: %t\n", protectedBranch.CodeOwnerApprovalRequired)
fmt.Printf("PushAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.PushAccessLevels {
fmt.Printf("PushAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
fmt.Printf("PushAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
fmt.Printf("PushAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
fmt.Printf("PushAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
fmt.Printf("PushAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
fmt.Printf("MergeAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.MergeAccessLevels {
fmt.Printf("MergeAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
fmt.Printf("MergeAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
fmt.Printf("MergeAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
fmt.Printf("MergeAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
fmt.Printf("MergeAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
fmt.Printf("UnprotectAccessLevels: \n")
for index, branchAccessDescription := range protectedBranch.UnprotectAccessLevels {
fmt.Printf("UnprotectAccessLevels[%d] ID: %d\n", index, branchAccessDescription.ID)
fmt.Printf("UnprotectAccessLevels[%d] AccessLevel: %d\n", index, branchAccessDescription.AccessLevel)
fmt.Printf("UnprotectAccessLevels[%d] AccessLevelDescription: %s\n", index, branchAccessDescription.AccessLevelDescription)
fmt.Printf("UnprotectAccessLevels[%d] UserID: %d\n", index, branchAccessDescription.UserID)
fmt.Printf("UnprotectAccessLevels[%d] GroupID: %d\n", index, branchAccessDescription.GroupID)
}
fmt.Println("")
}
}
return nil
}

View File

@ -0,0 +1,23 @@
package protected_branches
import (
"github.com/urfave/cli/v2"
"github.com/xuxiaowei-com-cn/gitlab-go/flag"
)
// ProtectedBranches 受保护的分支 API https://docs.gitlab.cn/jh/api/protected_branches.html
func ProtectedBranches() *cli.Command {
return &cli.Command{
Name: "protected-branches",
Aliases: []string{"pb"},
Usage: "受保护的分支 API中文文档https://docs.gitlab.cn/jh/api/protected_branches.html",
Flags: append(flag.Common(), flag.Id(false), flag.ProtectedBranchesSearch(),
flag.BranchName(false), flag.PushAccessLevel(), flag.MergeAccessLevel(),
flag.UnprotectAccessLevel(), flag.AllowForcePush(), flag.CodeOwnerApprovalRequired(),
flag.Page(), flag.PerPage(), flag.PrintJson(), flag.PrintTime()),
Subcommands: []*cli.Command{
List(),
Protect(),
},
}
}