Skip to content

Commit

Permalink
feat(git): helper functions for getting the contents of a file at a ref
Browse files Browse the repository at this point in the history
  • Loading branch information
trieloff committed May 7, 2019
1 parent 3f5ada0 commit 0b349d8
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/git-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,42 @@ class GitUtils {
static async getCurrentRevision(dir) {
return git.resolveRef({ dir, ref: 'HEAD' });
}

/**
* Returns the commit oid of the curent commit referenced by `ref`
*
* @param {string} dir git repo path
* @param {string} ref reference (branch, tag or commit sha)
* @returns {Promise<string>} commit oid of the curent commit referenced by `ref`
* @throws {GitError} `err.code === 'ResolveRefError'`: invalid reference
*/
static async resolveCommit(dir, ref) {
return git.resolveRef({ dir, ref })
.catch(async (err) => {
if (err.code === 'ResolveRefError') {
// fallback: is ref a shortened oid prefix?
const oid = await git.expandOid({ dir, oid: ref });
return git.resolveRef({ dir, ref: oid });
}
// re-throw
throw err;
});
}

/**
* Returns the contents of the file at revision `ref` and `pathName`
*
* @param {string} dir git repo path
* @param {string} ref reference (branch, tag or commit sha)
* @param {string} filePath relative path to file
* @returns {Promise<Buffer>} content of specified file
* @throws {GitError} `err.code === 'TreeOrBlobNotFoundError'`: resource not found
*/
static async getRawContent(dir, ref, pathName) {
return GitUtils.resolveCommit(dir, ref)
.then(oid => git.readObject({ dir, oid, filepath: pathName, format: 'content' }))
.then(obj => obj.object);
}
}

module.exports = GitUtils;

0 comments on commit 0b349d8

Please sign in to comment.