From 0b349d8c2fc0aadf63b69883e845f314bad78f06 Mon Sep 17 00:00:00 2001 From: Lars Trieloff Date: Tue, 7 May 2019 14:23:31 +0000 Subject: [PATCH] feat(git): helper functions for getting the contents of a file at a ref --- src/git-utils.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/git-utils.js b/src/git-utils.js index a0eaf93c7..aa71136c0 100644 --- a/src/git-utils.js +++ b/src/git-utils.js @@ -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} 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} 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;