Created
January 22, 2016 21:23
-
-
Save deanohyeah/df972fea8daa13e6b14f to your computer and use it in GitHub Desktop.
Nodejs script to start jenkins build and poll for status
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
var request = require('request'), | |
fs = require('fs'), | |
Promise = require('bluebird'), | |
baseUrl = '', | |
patchName = process.argv[2].toString(), | |
formData = { | |
file0: fs.createReadStream(`/Users/skytap/src/current/ui_nodejs/.hg/patches/${patchName}`), | |
json: '{"parameter":[{"name":"ui_nodejs/.hg/patches/test_patch","file":"file0"}]}' | |
}; | |
// wrap request with promise | |
function makeRequest(url, method, data) { | |
return new Promise(function (resolve, reject) { | |
request({method:method, url:baseUrl+url, formData: data}, function optionalCallback(err, response) { | |
if (err) { | |
reject(err) | |
}else { | |
try { | |
resolve(JSON.parse(response.body)) | |
} catch(err) { | |
resolve(); | |
} | |
} | |
}); | |
}); | |
}; | |
function startBuild() { | |
return makeRequest('/job/nodejs/build', 'POST', formData); | |
} | |
function fetchQueue() { | |
return makeRequest('/queue/api/json', 'GET'); | |
} | |
function fetchQueueItem(url) { | |
return makeRequest('/'+url+'api/json', 'GET'); | |
} | |
// poll queue status and notify when build starts | |
function pollQueueItem(data){ | |
if (data.executable) { | |
console.log('Building with patch at:'); | |
console.log(data.executable.url); | |
} else if (data.buildable){ | |
fetchQueue().then((queueData) => { | |
itemsInQueue = queueData.items.length | |
process.stdout.write(`${data.why}. Waiting for: ${(new Date() - data.buildableStartMilliseconds)/1000} seconds. ${itemsInQueue} ahead of you. \r`); | |
fetchQueueItem(data.url).then((data)=>{ | |
setTimeout(() => pollQueueItem(data), 30000) | |
}); | |
}); | |
} else { | |
process.stdout.write(data.why + "\r"); | |
fetchQueueItem(data.url).then((data)=>{ | |
setTimeout(() => pollQueueItem(data), 1000) | |
}) | |
} | |
} | |
startBuild().then((data) => fetchQueue()) | |
.then((data) => fetchQueueItem(data.items[0].url)) | |
.then((data) => pollQueueItem(data)) | |
.catch((error) => console.log(error)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment