fix relative path computation

This commit is contained in:
Valentin Gagarin 2024-11-27 12:51:38 +01:00
parent 0e7eef5ea2
commit f67c012dfe
2 changed files with 21 additions and 9 deletions

View file

@ -99,20 +99,22 @@ rec {
relativePath = path1': path2':
let
inherit (lib.path) subpath;
inherit (lib) lists;
inherit (lib) lists length take drop min max;
path1 = subpath.components path1';
prefix1 = with lib; take (length path1 - 1) path1;
prefix1 = take (length path1 - 1) path1;
path2 = subpath.components path2';
prefix2 = with lib; take (length path2 - 1) path2;
prefix2 = take (length path2 - 1) path2;
commonPrefixLength = with lists;
findFirstIndex (i: i.fst != i.snd)
(length prefix1)
(min (length prefix1) (length prefix2))
(zipLists prefix1 prefix2);
depth = max 0 (length prefix1 - commonPrefixLength);
relativeComponents = with lists;
[ "." ] ++ (replicate (length prefix1 - commonPrefixLength) "..") ++ (drop commonPrefixLength path2);
[ "." ] ++ (replicate depth "..") ++ (drop commonPrefixLength path2);
in
join "/" relativeComponents;

View file

@ -4,8 +4,18 @@ let
inherit (import ./. { }) lib;
in
{
test-relativePath = {
expr = with lib; relativePath "bar" "baz";
expected = "./baz";
};
test-relativePath = with lib;
let
testData = [
{ from = "bar"; to = "baz"; expected = "./baz"; }
{ from = "foo/bar"; to = "foo/baz"; expected = "./baz"; }
{ from = "foo"; to = "bar/baz"; expected = "./bar/baz"; }
{ from = "foo/bar"; to = "baz"; expected = "./../baz"; }
{ from = "foo/bar/baz"; to = "foo"; expected = "./../../foo"; }
];
in
{
expr = map (case: relativePath case.from case.to) testData;
expected = map (case: case.expected) testData;
};
}