Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update a file on repository if it already exists #126

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions lib/GitHub.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ GitHub.prototype.readFile = function (path, getFullResponse) {

return getFullResponse ? {
content: content,
sha: res.sha,
file: {
content: res.content
}
Expand All @@ -70,24 +71,38 @@ GitHub.prototype.readFile = function (path, getFullResponse) {
return Promise.reject(errorHandler('PARSING_ERROR', errorData))
}
}).catch(err => {
return Promise.reject(errorHandler('GITHUB_READING_FILE', {err}))
return Promise.reject(errorHandler('GITHUB_READING_FILE', err))
})
}

GitHub.prototype.writeFile = function (filePath, data, branch, commitTitle) {
branch = branch || this.options.branch
commitTitle = commitTitle || 'Add Staticman file'

return this.api.repos.createFile({
var content = Buffer.from(data).toString('base64')
var requestData = {
user: this.options.username,
repo: this.options.repository,
path: filePath,
content: Buffer.from(data).toString('base64'),
content: content,
message: commitTitle,
branch: branch
}
var readFileResponse = this.readFile(filePath, true)

return readFileResponse.then(r => {
// If the file exists, get its sha and send an update request.
requestData['sha'] = r.sha

return this.api.repos.updateFile(requestData).catch(err => {
return Promise.reject(errorHandler('GITHUB_UPDATING_FILE', {err}))
})
}).catch(err => {
return Promise.reject(errorHandler('GITHUB_WRITING_FILE', {err}))
// If new file doesn't previously exists, create it on the repository.
return this.api.repos.createFile(requestData).catch(err => {
return Promise.reject(errorHandler('GITHUB_WRITING_FILE', {err}))
})
})

}

GitHub.prototype.writeFileAndSendPR = function (filePath, data, branch, commitTitle, commitBody) {
Expand Down