const _ = require('lodash');
const simpleGit = require('simple-git');
const jira_matcher = /\d+-[A-Z]+(?!-?[a-zA-Z]{1,10})/g
const reverse = require('reverse-string');
/**
* Internal function that checks present working directory to see if its a git repository.
* @return {boolean}
*/
function isGitRepository(){
let checkDir = require('child_process').execSync;
console.log('Current working directory: ',process.cwd());
let isRepo = checkDir('git rev-parse --is-inside-work-tree').toString();
if (isRepo == 'true\n'){
return true;
} else {
return false;
}
}
exports.getJiraIds = function (po,callback) {
// See if it was requested on command line to determine jira'id
let isRequestingJiraIds = false;
_.each(po.arguments.rawArgs,(item)=>{
if (item == '-j' || item == '--jiraIds'){
isRequestingJiraIds = true;
}
});
if (po.missing_tags === false || _.isNil(po.missing_tags) && isRequestingJiraIds == true){
let tag = po.latest_tag_sha + '..' + po.current_sha;
if (po.current_sha == po.latest_tag_sha){
console.log('Evaluating identical commit_sha\'s for querying JIRA ID\'s from local git repository, skipping...');
callback(null);
} else {
let isGitRepo = isGitRepository();
if (isGitRepo == true){
console.log('Executing git log', tag,'--oneline --no-abbrev-commit')
simpleGit().raw([
'log',
tag,
'--oneline',
'--no-abbrev-commit'
], (err,results) => {
po.jira_ids = [];
if (err != null) {
console.log('Unable to get jira ids, error occurred:',err);
callback(null);
}
if (results != null){
let newArray = _.dropRight(_.split(results,'\n',results.length));
let notes = newArray.map((item)=>{
// Javascript has no look behind, reverse to fool it.
return reverse(item.substring(item.indexOf(' '),item.length).trim())
});
let jiraIds = notes.map((item)=>{
let results = item.match(jira_matcher);
if (results) {
return reverse(results.toString())
}
})
jiraIds = _.uniq(jiraIds.filter((n)=> {return n != undefined}));
let merged = _.map(jiraIds,(item)=>{
if (item.indexOf(',') != -1) {
return item.split(',');
} else {
return item;
}
})
po.jira_ids = _.flattenDeep(merged);
process.env.BUILD_JIRA_IDS = po.jira_ids;
console.log(po.jira_ids);
//console.log('Found jira id\'s:', po.jira_ids);
process.exit(0);
} else {
console.log('No jira id\'s found')
process.exit(0);
}
}
)
} else {
console.log('Unable to evaluate current directory for JIRA ID\'s - Please execute jobrunner from git repository');
process.exit(0);
}
}
}
else {
po.jira_ids = [];
callback(null);
}
};