diff options
Diffstat (limited to 'lib/utils')
-rw-r--r-- | lib/utils/git.js | 21 | ||||
-rw-r--r-- | lib/utils/path.js | 39 |
2 files changed, 58 insertions, 2 deletions
diff --git a/lib/utils/git.js b/lib/utils/git.js index 5f17395..6eb9681 100644 --- a/lib/utils/git.js +++ b/lib/utils/git.js @@ -6,6 +6,7 @@ var path = require("path"); var crc = require("crc"); var exec = Q.denodeify(require("child_process").exec); var URI = require("URIjs"); +var pathUtil = require("./path"); var fs = require("./fs"); @@ -89,7 +90,6 @@ function cloneGitRepo(host, ref) { }); } - // Get file from a git repo function resolveFileFromGit(giturl) { if (_.isString(giturl)) giturl = parseGitUrl(giturl); @@ -104,9 +104,26 @@ function resolveFileFromGit(giturl) { }); }; +// Return root of git repo from a filepath +function resolveGitRoot(filepath) { + var relativeToGit, repoId + + // No git repo cloned, or file is not in a git repository + if (!GIT_TMP || !pathUtil.isInRoot(GIT_TMP, filepath)) return null; + + // Extract first directory (is the repo id) + relativeToGit = path.relative(GIT_TMP, filepath); + repoId = _.first(relativeToGit.split(path.sep)); + if (!repoId) return; + + // Return an absolute file + return path.resolve(GIT_TMP, repoId); +}; + module.exports = { checkUrl: checkGitUrl, parseUrl: parseGitUrl, - resolveFile: resolveFileFromGit + resolveFile: resolveFileFromGit, + resolveRoot: resolveGitRoot }; diff --git a/lib/utils/path.js b/lib/utils/path.js new file mode 100644 index 0000000..d5b98f7 --- /dev/null +++ b/lib/utils/path.js @@ -0,0 +1,39 @@ +var _ = require("lodash"); +var path = require('path'); + +// Return true if file path is inside a folder +function isInRoot(root, filename) { + filename = path.normalize(filename); + return (filename.substr(0, root.length) === root); +} + +// Resolve paths in a specific folder +// Throw error if file is outside this folder +function resolveInRoot(root) { + var input = _.chain(arguments) + .toArray() + .slice(1) + .reduce(function(current, p, i) { + // Handle path relative to book root ('/README.md') + if (p[0] == '/' || p[0] == '\\') return p.slice(1); + + return current? path.join(current, p) : path.normalize(p); + }, '') + .value(); + + var result = path.resolve(root, input); + + if (!isInRoot(root, result)) { + err = new Error("EACCESS: '" + result + "' not in '" + root + "'"); + err.code = "EACCESS"; + throw err; + } + + return result +}; + + +module.exports = { + isInRoot: isInRoot, + resolveInRoot: resolveInRoot +}; |