Added urls.relative.

This commit is contained in:
Ryan Leonard 2017-03-16 09:24:54 -07:00
parent dacbed4bff
commit 6455b8b88d
2 changed files with 55 additions and 0 deletions

View File

@ -37,8 +37,24 @@ function join(paths) {
}, args[0]);
}
/**
* `path.relative` that works with either file paths or URLs.
* @param {string} from the origin path
* @param {string} to the destination path
* @return {string} A relative path from the origin to the destination.
*/
function relative(from, to) {
var localToRemote = !absoluteURL(from) && absoluteURL(to);
var differentDomains = absoluteURL(from) && absoluteURL(to) && urlBasename(from) !== urlBasename(to);
if(localToRemote || differentDomains) {
return to;
}
return path.relative(from, to);
}
module.exports = {
absoluteURL: absoluteURL,
urlBasename: urlBasename,
join: join,
relative: relative,
}

View File

@ -60,6 +60,7 @@ describe("urls.js", function() {
});
describe("join()", function() {
[
{from: ["/home/", "foo"], to: "/home/foo"},
{from: ["/home/", "foo/"], to: "/home/foo/"},
@ -78,4 +79,42 @@ describe("urls.js", function() {
});
describe("relative()", function() {
var situations = {
"Joining Local Paths": [
{from: "/home/foo/bar/", to: "/home/baz/foobar/", out: "../../baz/foobar"},
{from: "foo/bar/", to: "baz/foobar/", out: "../../baz/foobar"},
{from: "file.json", to: "baz/foobar/", out: "../baz/foobar"},
],
"Joining URLs": [
{from: "http://example.com/foo/bar/", to: "http://example.com/baz/foobar/", out: "../../baz/foobar"},
{from: "http://example.com/foo/", to: "http://example.com/bar/", out: "../bar"},
],
"File System to URL": [
{from: "/home/", to: "http://example.com", out: "http://example.com"},
{from: "./", to: "http://example.com", out: "http://example.com"},
{from: "./file.json", to: "http://example.com", out: "http://example.com"},
{from: "file.json", to: "sftp://example.com", out: "sftp://example.com"},
],
"Given Different URLs": [
{from: "http://example.com/", to: "http://one.example.com/", out: "http://one.example.com/"},
],
};
for(var situation in situations) {
var tests = situations[situation];
describe(situation, (function(situation, tests) {
return function() {
tests.forEach(function(details) {
it("relative(\""+details.from+"\", \""+details.to+"\") should produce "+details.out, function() {
urls.relative(details.from, details.to).should.equal(details.out);
});
});
};
})(situation, tests));
}
});
});