-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-branch.js
100 lines (83 loc) · 3.32 KB
/
create-branch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { Command } from 'commander';
import axios from 'axios';
import logSymbols from 'log-symbols';
const getSuccessLog = (props) => `
${logSymbols.success} ${props.repo}
Branch Name: ${props.branchName}
Author: ${props.commitAuthor}
Commit: ${props.commitHash}
Commit Link: ${props.commitLink}
`.trim();
const getErrorLog = (props) => `
${logSymbols.error} ${props.repo}
Error Message: ${props.errorMessage.trim()}
`.trim();
export const makeCreateBranchCommand = (config) => {
const program = new Command();
program
.name('create-branch')
.description('Create a branch on all repositories.')
.argument('<fromBranch>', 'Branch to create from.')
.argument('<branchName>', 'Branch name to create.')
.action(async(fromBranch, branchName) => {
if (!config) {
console.log('Missing configuration file. Please run "init" command and try again.');
return;
}
const repos = config.repos || [];
if (repos.length === 0) {
console.log('No repositories setup yet. Please run "repo add" command and try again.');
return;
}
const axiosInstance = axios.create({
baseURL: 'https://api.bitbucket.org/2.0',
headers: {
'Content-Type': 'application/json',
},
auth: {
username: config.auth.username,
password: config.auth.appPassword,
},
});
for (const repo of repos) {
const logProps = {
repo: repo,
branchName: branchName,
commitHash: '',
commitLink: '',
errorMessage: '',
};
let wasSuccessful = false;
try {
const response = await axiosInstance.request({
method: 'post',
url: `repositories/${repo}/refs/branches`,
data: JSON.stringify({
name: branchName,
target: {
hash: fromBranch,
},
}),
});
wasSuccessful = true;
const data = response.data;
logProps.commitHash = data.target.hash;
logProps.commitLink = data.target.links.html.href;
logProps.commitAuthor = data.target.author.raw;
} catch (error) {
if (error.response.data.error.message) {
logProps.errorMessage = error.response.data.error.message;
} else if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
logProps.errorMessage = error.response.data;
} else {
logProps.errorMessage = error;
}
}
console.log((wasSuccessful ? getSuccessLog(logProps) : getErrorLog(logProps)) + '\n');
}
})
;
return program;
};