Skip to content

Instantly share code, notes, and snippets.

@paazmaya
Created October 26, 2015 14:12
Show Gist options
  • Save paazmaya/e346e56ae9ddc7743e8e to your computer and use it in GitHub Desktop.
Save paazmaya/e346e56ae9ddc7743e8e to your computer and use it in GitHub Desktop.
Download images that are attached in the comments of a specific GitHub issue
/**
* Get the files attached on a GitHub issue and its comments
*
* @see https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue
* @see https://developer.github.com/v3/media/#comment-body-properties
*/
'use strict';
const fs = require('fs');
const got = require('got');
const token = process.env.GITHUB_TOKEN;
const ghOptions = {
headers: {
'user-agent': 'Get Issue Comments Tool',
authorization: 'token ' + token,
accept: 'application/vnd.github.full+json'
},
json: true
};
// https://github.com/nodejs/evangelism/issues/179
var owner = 'nodejs',
repo = 'evangelism',
issue = 179;
// GET /repos/:owner/:repo/issues/:number/comments
var url = 'https://api.github.com/repos/' + owner + '/' + repo + '/issues/' + issue + '/comments';
got(url, ghOptions, (error, body, response) => {
if (error) {
console.log(error.response.body);
}
else {
fs.writeFileSync('comments.json', JSON.stringify(body, null, ' '), 'utf8');
var bodies = processComments(body);
var images = findImages(bodies);
console.log('Found ' + images.length + ' images in ' + bodies.length + ' comments');
downloadImages(images);
}
});
function processComments(data) {
return data.map(function (item) {
return item.body;
});
}
function findImages(data) {
var images = [],
re = /[\/\:\w-_\.]+\.(png|jpg)/g;
data.forEach(function (item) {
var list;
while ((list = re.exec(item)) !== null) {
images.push(list[0]);
}
});
return images;
}
function downloadImages(list) {
list.forEach(function (item) {
var name = path.basename(item);
got(item, {stream: true}).pipe(fs.createWriteStream(name));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment