cmr

package module
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 16 Imported by: 0

README

create-merge-request

Create a Merge Request for changes to your GitLab™ project

GITLAB is a trademark of GitLab Inc. in the United States and other countries and regions

This is inspired by https://github.com/peter-evans/create-pull-request

TOC

[[TOC]]

Requirements

create-merge-request uses https://github.com/go-git/go-git for git operations. So this doesn't rely on the system git command.

Simple usage for GitLab CI

First of all, set the GitLab Access Token to CI/CD Variables named GITLAB_ACCESS_TOKEN

Example .gitlab-ci.yml

stages:
  - build

create_mr_for_changes:
  stage: build

  image: debian:stable-slim

  before_script:
    # Download and install latest create-merge-request
    - apt-get update
    - apt-get install -y curl
    - VERSION=$(curl -s --fail https://gitlab.com/sue445/create-merge-request/-/raw/main/VERSION?ref_type=heads)
    - pushd /tmp
    - curl --retry 3 -L -o create-merge-request.tar.gz https://gitlab.com/sue445/create-merge-request/-/releases/${VERSION}/downloads/create-merge-request_Linux_x86_64.tar.gz
    - tar xzvf create-merge-request.tar.gz
    - mv create-merge-request /usr/local/bin
    - popd

  script:
    # TODO: Add your changes
    - date > now.txt

    # Create Merge Request if repo is changed
    - create-merge-request

  rules:
    # Run only scheduled pipeline
    # ref. https://docs.gitlab.com/ee/ci/pipelines/schedules.html
    - if: $CI_PIPELINE_SOURCE == "schedule"

Here is the Merge Request actually created 👉 https://gitlab.com/sue445/create-merge-request-sandbox/-/merge_requests/2

Install

Download binary from https://gitlab.com/sue445/create-merge-request/-/releases

Command

$ create-merge-request --help
NAME:
   create-merge-request - Create a Merge Request for changes to your GitLab project

USAGE:
   create-merge-request [command options]

REQUIRED PARAMETERS:
   --gitlab-api-endpoint value  GitLab API Endpoint (e.g. https://gitlab.com/api/v4) [$GITLAB_API_ENDPOINT, $CI_API_V4_URL]
   --gitlab-access-token value  GitLab access token [$GITLAB_ACCESS_TOKEN]
   --gitlab-project value       GitLab Project Path (e.g. gitlab-org/gitlab) [$GITLAB_PROJECT, $CI_PROJECT_PATH]

OPTIONAL PARAMETERS:
   --author-email value                     author email for commit (default: ${GITLAB_USER_LOGIN}@noreply.${CI_SERVER_HOST} (e.g. create-merge-request@noreply.example.com))
   --author-name value                      author name for commit (default: create-merge-request) [$GITLAB_USER_NAME]
   --commit-message value, -m value         commit message (default: [create-merge-request] automated change)
   --source-branch value                    Merge Request branch name (default: create-merge-request/patch)
   --source-branch-suffix value             Merge Request branch name suffix (none,random,timestamp,short-commit-hash) (default: none)
   --target-branch value                    Send Merge Request to this branch (e.g. main, master) (default: main) [$CI_DEFAULT_BRANCH]
   --title value, -t value                  Merge Request title (default: Changes by create-merge-request)
   --description value                      Merge Request description (default: Automated changes by [create-merge-request](https://gitlab.com/sue445/create-merge-request))
   --labels value [ --labels value ]        Merge Request labels
   --assignees value [ --assignees value ]  Merge Request assignees (e.g. user1,user2)
   --reviewers value [ --reviewers value ]  Merge Request reviewers (e.g. user1,user2)
   --auto-merge                             Merge the Merge Request when the pipeline succeeds (default: disabled)
   --log-level value                        Log level (e.g. DEBUG, INFO, WARN, ERROR) (default: INFO)
   --help, -h                               show help
   --version, -v                            print the version
--source-branch-suffix

By default(--source-branch-suffix=none), if a branch already exists in repository, a new branch with the same name will not be created.

To change this behavior, set the following in the --source-branch-suffix.

  • random : Append a random string to the branch name specified in --source-branch. (e.g. create-merge-request/patch-xxxxxxx)
  • timestamp : Append an Unix Epoch Time to the branch name specified in --source-branch. (e.g. create-merge-request/patch-1719675225)
  • short-commit-hash : Append a git short hash to the branch name specified in --source-branch. (e.g. create-merge-request/patch-123abcd)
--auto-merge

You may want to merge immediately Merge Request when pipeline succeeds.

In such a case, please use --auto-merge

See more information 👉 https://docs.gitlab.com/ee/user/project/merge_requests/auto_merge.html

Trouble Shooting: 401 Unauthorized

The reason is that target branch (--target-branch, often main or master) that the Merge Request is merging into is protected.

https://docs.gitlab.com/ee/user/project/protected_branches.html

Please do one of the following.

  1. Change "Allowed to merge" from "Maintainers" to "Developers + Maintainers"
  2. Change Access Token role from Developer to Maintainer
Trouble Shooting: 405 Method Not Allowed

If "Merge a merge request API" is called immediately after the Merge Request is created, 405 error will be returned.

create-merge-request will automatically retry 405 errors, but if it still fails, the build may not have been triggered for the Merge Request.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertToMap added in v0.3.0

func ConvertToMap(keysAndValues []interface{}) map[string]interface{}

ConvertToMap convert from `[]interface{}` to `map[string]interface{}`

func Execute

func Execute(params *ExecuteParams) error

Execute runs create-merge-request

func GenerateRandomString added in v0.1.1

func GenerateRandomString() string

GenerateRandomString generate random string

func GetCurrentShortHash added in v0.1.1

func GetCurrentShortHash(gitRepo string) (string, error)

GetCurrentShortHash returns short hash of current revision

func GetUntrackedFiles

func GetUntrackedFiles(gitRepo string) (git.Status, error)

GetUntrackedFiles returns untracked files

func IsExecutableFile added in v0.2.3

func IsExecutableFile(file string) (bool, error)

IsExecutableFile checks whether a file is executable

func NewLogger added in v0.4.3

func NewLogger() *logrus.Logger

NewLogger returns a logger configured for timestamped output to stdout.

func ReadFileAsBase64 added in v0.2.2

func ReadFileAsBase64(file string) (string, error)

ReadFileAsBase64 reads a file and returns its contents as BASE64

func ReadTextFile added in v0.2.2

func ReadTextFile(file string) (string, error)

ReadTextFile reads a text file

func ToCommitActionOptions

func ToCommitActionOptions(filepath string, status *git.FileStatus) (*gitlab.CommitActionOptions, error)

ToCommitActionOptions convert git.FileStatus to gitlab.CommitActionOptions

Types

type AcceptMergeRequestParams added in v0.2.0

type AcceptMergeRequestParams struct {
	ProjectName     string
	MergeRequestIID int64
}

AcceptMergeRequestParams represents parameters of AcceptMergeRequest

type BranchSuffix added in v0.1.1

type BranchSuffix int

BranchSuffix represents branch suffix format

const (
	// None doesn't append suffix to branches
	None BranchSuffix = iota

	// Random append a random string to the branch name specified in `--source-branch`. (e.g. `create-merge-request/patch-xxxxxxx`)
	Random

	// Timestamp append an Unix Epoch Time to the branch name specified in `--source-branch`. (e.g. `create-merge-request/patch-1719675225`)
	Timestamp

	// ShortCommitHash append a git short hash to the branch name specified in `--source-branch`. (e.g. `create-merge-request/patch-123abcd`)
	ShortCommitHash
)

func ToBranchSuffix added in v0.1.1

func ToBranchSuffix(str string) (BranchSuffix, error)

ToBranchSuffix returns BranchSuffix from string

func (BranchSuffix) String added in v0.1.1

func (i BranchSuffix) String() string

type CommitFilesParams

type CommitFilesParams struct {
	ProjectName   string
	NewBranch     string
	StartBranch   string
	AuthorEmail   string
	AuthorName    string
	CommitMessage string
	Files         git.Status
}

CommitFilesParams represents parameters of CommitFiles

type CreateMergeRequestParams

type CreateMergeRequestParams struct {
	ProjectName  string
	SourceBranch string
	TargetBranch string
	Title        string
	Description  string
	Labels       []string
	Assignees    []string
	Reviewers    []string
}

CreateMergeRequestParams represents parameters of CreateMergeRequest

type CustomLogger added in v0.3.0

type CustomLogger struct {
	// contains filtered or unexported fields
}

CustomLogger adapts logrus to the LeveledLogger interface

func NewCustomLogger added in v0.3.0

func NewCustomLogger(logLevel string) (*CustomLogger, error)

NewCustomLogger returns new CustomLogger instance

logLevel : DEBUG, INFO, WARN, ERROR

func (*CustomLogger) Debug added in v0.3.0

func (l *CustomLogger) Debug(msg string, keysAndValues ...interface{})

Debug print debug log

func (*CustomLogger) Error added in v0.3.0

func (l *CustomLogger) Error(msg string, keysAndValues ...interface{})

Error print error log

func (*CustomLogger) Info added in v0.3.0

func (l *CustomLogger) Info(msg string, keysAndValues ...interface{})

Info print info log

func (*CustomLogger) Warn added in v0.3.0

func (l *CustomLogger) Warn(msg string, keysAndValues ...interface{})

Warn print warn log

type ExecuteParams

type ExecuteParams struct {
	GitLabParams GitLabParams
	ProjectName  string
	SourceBranch SourceBranch

	// commit params
	AuthorEmail   string
	AuthorName    string
	CommitMessage string

	// MR params
	TargetBranch string
	Title        string
	Description  string
	Labels       []string
	Assignees    []string
	Reviewers    []string
	AutoMerge    bool
}

ExecuteParams represents parameters of Execute

type GitLab

type GitLab struct {
	// contains filtered or unexported fields
}

GitLab represents GitLab client

func NewGitLab

func NewGitLab(params *GitLabParams) (*GitLab, error)

NewGitLab returns new GitLab instance

func (*GitLab) AcceptMergeRequest added in v0.2.0

func (g *GitLab) AcceptMergeRequest(params *AcceptMergeRequestParams) error

AcceptMergeRequest set auto-merge to MergeRequest

ref. https://docs.gitlab.com/ee/api/merge_requests.html#merge-a-merge-request

func (*GitLab) CreateMergeRequest

func (g *GitLab) CreateMergeRequest(params *CreateMergeRequestParams) (*gitlab.MergeRequest, error)

CreateMergeRequest create MergeRequest

ref. https://docs.gitlab.com/ee/api/merge_requests.html#create-mr

func (*GitLab) GetUserID

func (g *GitLab) GetUserID(username string) (int64, error)

GetUserID returns userID from username

ref. https://docs.gitlab.com/ee/api/users.html#list-users

func (*GitLab) GetUserIDs

func (g *GitLab) GetUserIDs(usernames []string) ([]int64, error)

GetUserIDs returns userIDs from usernames

func (*GitLab) IsExistsBranch added in v0.1.1

func (g *GitLab) IsExistsBranch(params *IsExistsBranchParams) (bool, error)

IsExistsBranch check whether branch is existing

ref. https://docs.gitlab.com/ee/api/branches.html#get-single-repository-branch

type GitLabParams

type GitLabParams struct {
	APIEndpoint  string
	PrivateToken string
	HTTPClient   *http.Client
	LogLevel     string
}

GitLabParams represents parameters of NewGitLab

type IsExistsBranchParams added in v0.1.1

type IsExistsBranchParams struct {
	ProjectName string
	Branch      string
}

IsExistsBranchParams represents parameters of IsExistsBranch

type SourceBranch added in v0.1.1

type SourceBranch struct {
	Name   string
	Suffix BranchSuffix
}

SourceBranch represents source branch options

func (*SourceBranch) GenerateBranchName added in v0.1.1

func (s *SourceBranch) GenerateBranchName(gitRepo string) (string, error)

GenerateBranchName returns source branch name from Name and Suffix

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL