fix relative path computation

This commit is contained in:
Valentin Gagarin 2024-11-27 12:51:38 +01:00
parent a8dcc9f298
commit 25cfa6716a
2 changed files with 25 additions and 15 deletions

View file

@ -99,22 +99,22 @@ rec {
relativePath = path1': path2': relativePath = path1': path2':
let let
inherit (lib.path) subpath; inherit (lib.path) subpath;
inherit (lib) lists; inherit (lib) lists length take drop min max;
inherit (lists) replicate findFirstIndex zipLists;
path1 = subpath.components path1'; path1 = subpath.components path1';
prefix1 = with lib; take (length path1 - 1) path1;
path2 = subpath.components path2'; path2 = subpath.components path2';
prefix2 = with lib; take (length path2 - 1) path2; prefix1 = take (length path1 - 1) path1;
commonPrefixLength = with lists; common-prefix-length = findFirstIndex (i: i.fst != i.snd)
findFirstIndex (i: i.fst != i.snd) (min (length prefix1) (length path2 - 1))
(length prefix1) (zipLists prefix1 path2);
(zipLists prefix1 prefix2); parent-levels = max 0 (length prefix1 - common-prefix-length);
relative-components = [ "." ] ++
relativeComponents = with lists; (replicate parent-levels "..") ++
[ "." ] ++ (replicate (length prefix1 - commonPrefixLength) "..") ++ (drop commonPrefixLength path2); (drop common-prefix-length path2);
in in
join "/" relativeComponents; join "/" relative-components;
/** /**
Recursively list all Nix files from a directory, except the top-level `default.nix` Recursively list all Nix files from a directory, except the top-level `default.nix`

View file

@ -4,8 +4,18 @@ let
inherit (import ./. { }) lib; inherit (import ./. { }) lib;
in in
{ {
test-relativePath = { test-relativePath = with lib;
expr = with lib; relativePath "bar" "baz"; let
expected = "./baz"; 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;
};
} }