Last active
August 29, 2015 14:18
-
-
Save callumacrae/5fc4867dfd6f023bf303 to your computer and use it in GitHub Desktop.
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'; | |
const path = require('path'); | |
const git = require('nodegit'); | |
const promisify = require('promisify-node'); | |
const fs = promisify(require('graceful-fs')); | |
const winston = require('winston'); | |
const config = require('./config'); | |
let remoteCallbacks = { | |
certificateCheck: function () { | |
return 1; | |
}, | |
credentials: function (url, username) { | |
return git.Cred.sshKeyFromAgent(username); | |
} | |
}; | |
function getFileFromBranch(branch, filePath) { | |
let repo; | |
return git.Repository.open(config.git.cloneTo) | |
.catch(function (err) { | |
if (err.message.startsWith('Failed to resolve')) { | |
winston.info('Repo not found, cloning'); | |
return git.Clone(config.git.repo, config.git.cloneTo, { | |
remoteCallbacks: remoteCallbacks | |
}); | |
} else { | |
winston.error(err); | |
throw err; | |
} | |
}) | |
.then(function (repository) { | |
repo = repository; | |
winston.log('verbose', 'Changing branch'); | |
return repo.checkoutBranch(branch, { | |
checkoutStrategy: git.Checkout.STRATEGY.SAFE_CREATE | |
}); | |
}) | |
.catch(function (err) { | |
if (/Reference '([^']+)' not found/.test(err.message)) { | |
winston.info('Branch not found, fetching'); | |
return repo.fetch('origin', remoteCallbacks, true) | |
.then(function () { | |
return repo.getBranchCommit('origin/' + branch); | |
}) | |
.then(function (commit) { | |
return repo.createBranch(branch, commit, 0); | |
}) | |
.then(function (newBranch) { | |
repo.mergeBranches(newBranch, 'origin/' + branch); | |
}) | |
.then(function () { | |
return repo.checkoutBranch(branch, { | |
checkoutStrategy: git.Checkout.STRATEGY.SAFE_CREATE | |
}); | |
}); | |
} else { | |
winston.error(err); | |
throw err; | |
} | |
}) | |
.then(function () { | |
return fs.readFile(path.join(config.git.cloneTo, filePath)); | |
}); | |
} | |
module.exports = getFileFromBranch; |
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'; | |
const config = require('./src/config'); | |
const getFileFromBranch = require('./src/get-file'); | |
config.git.cloneTo = './test/fixtures/respository'; | |
getFileFromBranch('test', 'test.css') | |
.then(function (data) { | |
console.log(data.toString()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment