Skip to content

Instantly share code, notes, and snippets.

@regevbr
Last active April 12, 2018 07:32
Show Gist options
  • Save regevbr/cf6d82dba1691123783ccfa22a304f9b to your computer and use it in GitHub Desktop.
Save regevbr/cf6d82dba1691123783ccfa22a304f9b to your computer and use it in GitHub Desktop.
gitlab ci push changes to protected branch using node.js
grunt:
only:
- master
script:
- 'git checkout -b CI${CI_JOB_ID}'
#make changes on local repo
- 'git add . || true'
- 'git commit -a -m "[ci skip] build" || true'
- 'git push https://<username>:<token>@gitlab.com/<team>/<project>.git HEAD:CI${CI_JOB_ID} || true'
- 'node ./mergeBranch.js CI${CI_JOB_ID}'
"use strict";
const request = require('request-promise');
const Promise = require('bluebird');
const gitlabToken = "<TOKEN>";
const projectId = "<PROJECT_ID>";
const baseUrl = "https://gitlab.com/api/v4/";
const asigneeId = <ASSIGNEE_ID>;
const targetBranch = "master";
const args = process.argv.slice(2);
const branch = args[0];
if (!branch) {
console.error('no branch provided');
process.exit(1);
}
const createPR = {
method: "POST",
headers: {
"PRIVATE-TOKEN": gitlabToken
},
json: true,
body: {
source_branch: branch,
target_branch: targetBranch,
assignee_id: asigneeId,
remove_source_branch: true,
title: branch,
squash: true,
allow_maintainer_to_push: true
},
url: baseUrl + "projects/" + projectId + "/merge_requests"
};
function createPullRequest() {
console.log("creating pull request", branch);
return request(createPR)
.then(function (result) {
const prid = result.iid;
console.log("pull request created", prid);
console.log("merging pull request");
const mergePR = {
method: "PUT",
headers: {
"PRIVATE-TOKEN": gitlabToken
},
json: true,
body: {
should_remove_source_branch: true,
merge_when_pipeline_succeeds: false,
merge_commit_message: '[ci skip] ci build'
},
url: baseUrl + "projects/" + projectId + "/merge_requests/" + prid + "/merge"
};
return request(mergePR);
});
}
createPullRequest()
.then(function () {
console.log("pull request merged");
process.exit(0);
})
.catch(function (err) {
console.log("failed", err.error.message);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment