All files jiraSubtaskHandling.js

86.34% Statements 139/161
76.32% Branches 87/114
89.66% Functions 26/29
86.08% Lines 136/158

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 3963x 3x 3x 3x                   49x 49x 49x             49x 49x   49x 49x     49x               49x 49x         47x 47x       47x 47x 51x     47x 51x 47x 1x 1x       46x 46x       46x 46x 50x 2x     48x     48x     46x 50x   46x 1x 1x         45x                   45x     25x   26x       45x     22x   22x                   45x       45x         45x       45x                 4x                 49x   2x       51x 51x 48x     3x 3x         48x 48x       47x               49x   47x 1x 1x   46x     2x 2x         55x 55x     1x               45x 23x     22x   22x 22x 22x   22x 22x         22x             22x         22x       22x 22x                 45x   22x     23x 25x 25x 25x 1x 1x     24x       24x 24x 24x 24x 16x       8x 8x         8x 8x       8x   25x           24x 24x   8x     16x 16x 16x               24x 24x     8x 8x   16x         16x   16x 16x     16x       16x       16x       8x                           8x 8x 8x 8x                     3x 1x 1x     2x 2x 1x 1x   1x       1x 1x 1x               3x  
const core       = require( '@actions/core' )
const JiraClient = require( 'jira-connector' )
const sliceInput = require ('./utils')
let DEBUG        = () => { }
 
async function handleSubtask( issueChanges, useSubtaskMode, fnDEBUG ) {
	//ISSUE CHANGE will be:
	//      {
	//             event:          payload.action,
	//             jiraKeys:       jiraKeys,
	//             changes:        changedValues,
	//             details:        payload.issue
	//         }
	DEBUG = fnDEBUG
	try {
		Iif( !issueChanges.jiraKeysToAttachTo
			&& !issueChanges.jiraKeysToReplace ) {
			//we have no parent task in JIRA, this should never happen
			console.log( `WARNING: no JIRA parent story is labelled.` )
			return null
		}
		
		const jiraProjectKey = core.getInput( 'JIRA_PROJECTKEY' )
		console.log( `- we are pushed to project with key ${ jiraProjectKey }` )
		
		const jiraIssueTypeName = core.getInput( 'JIRA_ISSUETYPE_NAME' )
		console.log( `-- using issue type ${ jiraIssueTypeName }` )
		
		//Let's login to JIRA first
		const jiraSession = new JiraClient( {
												host:       core.getInput( 'JIRA_BASEURL' ),
												basic_auth: {
													email:     core.getInput( 'JIRA_USEREMAIL' ),
													api_token: core.getInput( 'JIRA_APITOKEN' ),
												},
											} )
		
		console.log( '-- login in JIRA' )
		await loginToJiraAndCheckMyself( jiraSession )
		
		//PROJECT_KEY HANDLING
		// we allow list of keys, so we have to slice the input, then ensure that those project
		// exist in JIRA, then ensure that the Issue Type listed for them exists too
		const arrayProjectKeys = sliceInput( jiraProjectKey )
		Iif( arrayProjectKeys.length === 0 ) {
			arrayProjectKeys.push( jiraProjectKey )
		}
		
		console.log( '--- filter only projects that exist' )
		const isValidProjectKeys = await Promise.all( arrayProjectKeys.map( async ( currentProjectKey ) => {
			return await checkProjectExist( jiraSession, currentProjectKey )
		} ) )
		
		const validProjectKeys = arrayProjectKeys.filter( ( currentIsValid,
															currentIndex ) => isValidProjectKeys[ currentIndex ] )
		if( validProjectKeys.length === 0 ) {
			console.log( '---! none of the project key listed are link to project that exist' )
			throw 'No project exist in JIRA'
		}
		
		
		const arrayIssueTypes = sliceInput( jiraIssueTypeName )
		Iif( arrayIssueTypes.length === 0 ) {
			arrayIssueTypes.push( jiraIssueTypeName )
		}
		
		console.log( '--- checking issue type exist' )
		const foundIssueType = await Promise.all( arrayProjectKeys.map( async ( currentProjectKey, currentIndex ) => {
			if( !isValidProjectKeys[ currentIndex ] ) {
				return null
			}
			
			const indexToUse = currentIndex >= arrayIssueTypes.length
							   ? arrayIssueTypes.length - 1
							   : currentIndex
			return await findIssueTypeRequested( jiraSession, currentProjectKey, arrayIssueTypes[ indexToUse ] )
		} ) )
		
		const validProjectWithIssueType = arrayProjectKeys.filter( ( currentProjectKey,
																	 currentIndex ) => foundIssueType[ currentIndex ] !==
																					   null )
		if( validProjectWithIssueType.length === 0 ) {
			console.log( '---! none of the project have the Issue Type ' + jiraIssueTypeName )
			throw 'No Issue Type exist for those project in JIRA'
		}
		// const isSubtaskType = jiraIssuetypeFound.subtask
		
		
		Iif( issueChanges.jiraKeysToAttachTo.length === 0
			&& issueChanges.jiraKeysToReplace.length === 0 ) {
			console.log( `ERROR: no label match the project keys ${ jiraProjectKey } -- this should have be trapped before, \n` +
						 'please log an issue at https://github.com/b-yond-infinite-network/sync-jira-subtask-to-gh-issues-action/issues' )
			return
		}
		
		//MULTI PROJECT HANDLING
		// when we have multi-project we have to match the issue that are left after validation of
		// the Issue Types compatibility
		const finalJIRAKeysToAttachTo = issueChanges.jiraKeysToAttachTo.length === 0
										? []
										: issueChanges.jiraKeysToAttachTo.filter( currentIssueToAttachTo =>
																					  validProjectWithIssueType.find(
																						  currentProjectKey =>
																							  currentIssueToAttachTo.jiraIssueKey.startsWith(
																								  currentProjectKey +
																								  '-' ),
																					  ) !== 'undefined' )
		const finalJIRAKeysToReplace  = issueChanges.jiraKeysToReplace.length === 0
										? []
										: issueChanges.jiraKeysToReplace.filter( currentIssueToAttachTo =>
																					 validProjectWithIssueType.find(
																						 currentProjectKey =>
																							 currentIssueToAttachTo.jiraIssueKey.startsWith(
																								 currentProjectKey +
																								 '-' ) ||
																							 currentIssueToAttachTo.jiraIssueKey.startsWith(
																								 'own' +
																								 currentProjectKey +
																								 '-' ),
																					 ) !== 'undefined' )
		//
		// Prioritizing sub-XXX label as a force sync
		const { jiraIssueToReplace, jiraIssueToAttachTo } = await listToUpdateDirectly( jiraSession,
																						finalJIRAKeysToReplace,
																						finalJIRAKeysToAttachTo )
		
		const summaryToLookFor            = ( issueChanges.changes && issueChanges.changes.title
											  ? issueChanges.changes.title.from
											  : issueChanges.details.title
												? issueChanges.details.title
												: '#' + issueChanges.details.number )
		const jiraIssueToUpdateFromParent = await listToUpdateByAttachingToParent( jiraSession,
																				   useSubtaskMode,
																				   jiraIssueToAttachTo,
																				   summaryToLookFor )
		return !jiraIssueToReplace || jiraIssueToReplace.length === 0
			   ? !jiraIssueToUpdateFromParent || jiraIssueToUpdateFromParent.length === 0
				 ? null
				 : jiraIssueToUpdateFromParent
			   : !jiraIssueToUpdateFromParent || jiraIssueToUpdateFromParent.length === 0
				 ? jiraIssueToReplace
				 : [ ...jiraIssueToReplace, ...jiraIssueToUpdateFromParent ]
	}
	catch( error ) {
		core.setFailed( error.message
						? error.message
						: error.body && error.body.message
						  ? error.body.message
						  : JSON.stringify( error ) )
	}
}
 
async function loginToJiraAndCheckMyself( jiraSession ) {
	try { await jiraSession.myself.getMyself() }
	
	catch( myselfError ) { manageJIRAAPIError( myselfError, jiraSession ) }
}
 
async function checkProjectExist( jiraSession, jiraProjectKey ) {
	try {
		await jiraSession.project.getProject( { projectIdOrKey: jiraProjectKey } )
		return true
	}
	catch( projectError ) {
		core.warning( `The JIRA Project ${ jiraProjectKey } does not exist or you don't have access.\nPlease contact your JIRA administrator to gain access.` )
		return false
	}
}
 
async function findIssueTypeRequested( jiraSession, jiraProjectKey, issuetypeToFind ) {
	try {
		const foundData = await jiraSession.issue.getCreateMetadata( {
																		 projectKeys:    jiraProjectKey,
																		 issuetypeNames: issuetypeToFind,
																	 } )
		Iif( !foundData
			|| !foundData.projects
			|| foundData.projects.length === 0
			|| !foundData.projects[ 0 ].issuetypes
			|| !foundData.projects[ 0 ].issuetypes.length === 0 ) {
			return null
		}
		
		const issueTypefound = foundData.projects[ 0 ].issuetypes.find( currentIssueType => currentIssueType.name ===
																							issuetypeToFind )
		if( !issueTypefound ) {
			console.log( `### Issue Type ${ issuetypeToFind } is invalid in JIRA project ${ jiraProjectKey }` )
			throw `The JIRA issue type specified does not exist or is disabled on this project`
		}
		return issueTypefound
	}
	catch( errorGetCreateMetadata ) {
		core.warning( `### Issue Type ${ issuetypeToFind } is invalid in JIRA project ${ jiraProjectKey }\nPlease contact your JIRA administrator to gain access.` )
		return null
	}
}
 
async function findIssue( jiraSession, jiraIssueKey ) {
	try {
		return await jiraSession.issue.getIssue( { issueKey: jiraIssueKey } )
	}
	catch( issueError ) {
		manageJIRAAPIError( issueError,
							jiraSession,
							`### issue ${ jiraIssueKey } is inaccessible in JIRA\n==> action skipped for label ${ jiraIssueKey }` )
	}
}
 
 
async function listToUpdateDirectly( jiraSession, issuesToReplace, issuesToAttachTo ) {
	if( issuesToReplace.length === 0 ) {
		return { jiraIssueToReplace: null, jiraIssueToAttachTo: issuesToAttachTo }
	}
	
	let listOfIssueKeyLabelToRemoveFromFullList = []
	
	const jiraIssueToUpdateDirectly = await Promise.all( issuesToReplace.map( async currentJIRAIssueKeyAndType => {
		const issueKeyWithoutSub = currentJIRAIssueKeyAndType.jiraIssueKey.replace( 'own', '' )
		console.log( `Adding own-ed JIRA Issue ${ issueKeyWithoutSub } to the list of JIRA Issues to upgrade` )
		
		const foundJIRAIssue = await findIssue( jiraSession, issueKeyWithoutSub )
		Iif( !foundJIRAIssue ) {
			console.log( `--! Issue ${ issueKeyWithoutSub } is not in JIRA -- skipping it` )
			return null
		}
		
		const foundParentKey = foundJIRAIssue
							   && foundJIRAIssue.fields
							   && foundJIRAIssue.fields.parent
							   && foundJIRAIssue.fields.parent.key
							   ? foundJIRAIssue.fields.parent.key
							   : null
		
		Iif( foundParentKey && issuesToAttachTo
			&& issuesToAttachTo.findIndex( currentIssue => currentIssue.jiraIssueKey === foundParentKey ) !== -1 ) {
			console.log( `--- ignoring parent labelling ${ foundParentKey } and upgrading ${ issueKeyWithoutSub } directly` )
			listOfIssueKeyLabelToRemoveFromFullList.push( foundParentKey )
		}
		return foundJIRAIssue
	} ) )
	
	
	return {
		jiraIssueToReplace:  jiraIssueToUpdateDirectly.filter( currentSubtaskOrIssue => currentSubtaskOrIssue !==
																						null ),
		jiraIssueToAttachTo: issuesToAttachTo.filter( currentJIRAIssueKeyAndType => !listOfIssueKeyLabelToRemoveFromFullList.includes(
			currentJIRAIssueKeyAndType.jiraIssueKey ) ),
	}
}
 
async function listToUpdateByAttachingToParent( jiraSession, useSubtaskMode, issueToAttachTo,
												summaryToLookForInSubtasks ) {
	if( !issueToAttachTo
		|| issueToAttachTo.length === 0 ) {
		return null
	}
	
	const jiraIssueToAttachTo = await Promise.all( issueToAttachTo.map( async ( currentJIRAIssueKeyAndtype ) => {
		console.log( `-- currently attaching to JIRA Issue: ${ currentJIRAIssueKeyAndtype.jiraIssueKey }` )
		const foundJIRAIssue = await findIssue( jiraSession, currentJIRAIssueKeyAndtype.jiraIssueKey )
		if( !foundJIRAIssue ) {
			console.log( `--! trying to attach to Issue that is not in JIRA ${ currentJIRAIssueKeyAndtype.jiraIssueKey } -- skipping it` )
			return null
		}
		
		Iif( !useSubtaskMode ) {
			return foundJIRAIssue
		}
		
		Eif( summaryToLookForInSubtasks ) {
			console.log( `-- Subtask mode using ${ summaryToLookForInSubtasks }` )
			const foundSubtask = findSubtaskByTitle( foundJIRAIssue, summaryToLookForInSubtasks )
			if( foundSubtask ) {
				return foundSubtask
			}
		}
		
		console.log( `-- Creation in JIRA with title: ${ summaryToLookForInSubtasks }` )
		const createdIssue = await createJIRAIssue( jiraSession,
													foundJIRAIssue.fields.project.key,
													currentJIRAIssueKeyAndtype.jiraIssueType,
													currentJIRAIssueKeyAndtype.jiraIssueKey,
													summaryToLookForInSubtasks )
		DEBUG( `Created issue with return info ${ createdIssue }` )
		Iif( !createdIssue ) {
			throw `Unable to create the the Jira Issue`
		}
		
		return findIssue( jiraSession, createdIssue.key )
	} ) )
	return jiraIssueToAttachTo.filter( currentSubtaskOrIssue => currentSubtaskOrIssue !== null )
}
 
 
function findSubtaskByTitle( jiraParentIssue, titleToLookFor ) {
	// - the story with the same title
	const jiraSubtasks = findAllSubtasks( jiraParentIssue )
	if( !jiraSubtasks
		|| jiraSubtasks.length === 0 ) {
		return null
	}
	
	const foundWithTitle = findSubtaskWithTitle( jiraSubtasks, titleToLookFor )
	Eif( foundWithTitle ) {
		return foundWithTitle
	}
	
	console.log( `--! no subtasks found with the title '${ titleToLookFor }' found, creating a new one` )
	return null
}
 
function findAllSubtasks( jiraParentIssue ) {
	console.log( `-- looking for subtask of JIRA Issue ${ jiraParentIssue.key }` )
	if( !jiraParentIssue.fields[ "subtasks" ]
		|| jiraParentIssue.fields[ "subtasks" ].length === 0 ) {
		// no subtask found means we will create one
		console.log( '--! no subtasks found, we will be creating a new one' )
		return null
	}
	return jiraParentIssue.fields[ "subtasks" ]
}
 
 
function findSubtaskWithTitle( jiraSubtasksIssuesArray, summaryToFind ) {
	console.log( `--- looking for one with summary "${ summaryToFind }"` )
	//filtering subtask to find our title
	const arrFoundSubtasksIssueWithTitle = jiraSubtasksIssuesArray.filter( currentJIRASubtaskObject => {
		return currentJIRASubtaskObject.fields.summary && currentJIRASubtaskObject.fields.summary === summaryToFind
	} )
	
	Iif( arrFoundSubtasksIssueWithTitle.length === 0 ) {
		return null
	}
	
	Iif( arrFoundSubtasksIssueWithTitle.length > 1 ) {
		console.log( '---! found more than one subtask with our title, returning the first' )
	}
	
	return arrFoundSubtasksIssueWithTitle[ 0 ]
}
 
async function createJIRAIssue( jiraSession, jiraProjectKey, jiraIssueTypeNameToUse, jiraParentIssueKey, title ) {
	const issueData = {
		"fields": {
			"project":   {
				"key": jiraProjectKey,
			},
			"issuetype": {
				"name": jiraIssueTypeNameToUse,
			},
			"parent":    {
				"key": jiraParentIssueKey,
			},
			"summary":   title,
		},
	}
	console.log( `-->Creating JIRA Issue of type : ${ JSON.stringify( jiraIssueTypeNameToUse ) } with title: ${ title }` )
	DEBUG( `Creating JIRA ${ JSON.stringify( jiraIssueTypeNameToUse ) } with datas ${ JSON.stringify( issueData ) }` )
	try {
		return await jiraSession.issue.createIssue( issueData )
	}
	catch( createError ) {
		manageJIRAAPIError( createError,
							jiraSession,
							'##### Unable to create Issue in JIRA',
							'Create Issue failed' )
	}
}
 
function manageJIRAAPIError( triggeredError, jiraSession, messageToLog, exceptionToRaise ) {
	if( triggeredError.message ) {
		console.log( `### JIRA API URL is invalid or inaccessible for ${ jiraSession.host }` )
		throw 'Invalid API URL'
	}
	else {
		const parsedError = JSON.parse( triggeredError )
		if( parsedError.statusCode === 401 ) {
			console.log( `### credentials unauthorized \n${ parsedError.body }` )
			throw 'Unauthorized'
		}
		Iif( !messageToLog ) {
			return
		}
		
		Eif( parsedError.statusCode === 404 ) {
			console.log( messageToLog )
			Iif( exceptionToRaise ) {
				throw exceptionToRaise
			}
		}
	}
}
 
 
module.exports = handleSubtask