-
-
Save sudcha2/6304dfbf4af8abe5900139e0963a5827 to your computer and use it in GitHub Desktop.
Commiting multiple files to github over API
This file contains hidden or 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
'use strict'; | |
var Octokat = require('octokat'); | |
var extend = require('lodash/object/assign'); | |
var defaults = { | |
branchName: 'master', | |
token: '', | |
username: '', | |
reponame: '' | |
}; | |
function init(options) { | |
options = extend({}, defaults, options); | |
var head; | |
var octo = new Octokat({ | |
token: options.token | |
}); | |
var repo = octo.repos(options.username, options.reponame); | |
function fetchHead() { | |
return repo.git.refs.heads(options.branchName).fetch(); | |
} | |
function fetchTree() { | |
return fetchHead().then(function(commit) { | |
head = commit; | |
return repo.git.trees(commit.object.sha).fetch(); | |
}); | |
} | |
function commit(files, message) { | |
return Promise.all(files.map(function(file) { | |
return repo.git.blobs.create({ | |
content: file.content, | |
encoding: 'utf-8' | |
}); | |
})).then(function(blobs) { | |
return fetchTree().then(function(tree) { | |
return repo.git.trees.create({ | |
tree: files.map(function(file, index) { | |
return { | |
path: file.path, | |
mode: '100644', | |
type: 'blob', | |
sha: blobs[index].sha | |
}; | |
}), | |
basetree: tree.sha | |
}); | |
}); | |
}).then(function(tree) { | |
return repo.git.commits.create({ | |
message: message, | |
tree: tree.sha, | |
parents: [ | |
head.object.sha | |
] | |
}); | |
}).then(function(commit) { | |
return repo.git.refs.heads(options.branchName).update({ | |
sha: commit.sha | |
}); | |
}); | |
} | |
return { | |
commit: commit | |
}; | |
} | |
module.exports = init; |
This file contains hidden or 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
'use strict'; | |
var github = require('./github'); | |
var api = github({ | |
username: 'YOUR_USERNAME', | |
token: 'API_TOKEN', // created here https://github.com/settings/applications#personal-access-tokens | |
reponame: 'BRANCH_NAME' | |
}); | |
api.commit([{ | |
path: 'test/file1.md', | |
content: '# File1' | |
}, { | |
path: 'test/file2.md', | |
content: '# File2' | |
}], 'test commit via api'); // returns a promise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment