From 25cfa6716aa2242c9744cbcac49c37e3f45e1eb8 Mon Sep 17 00:00:00 2001 From: Valentin Gagarin Date: Wed, 27 Nov 2024 12:51:38 +0100 Subject: [PATCH] fix relative path computation --- website/lib.nix | 22 +++++++++++----------- website/tests.nix | 18 ++++++++++++++---- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/website/lib.nix b/website/lib.nix index 6dcff3a0..9485d46b 100644 --- a/website/lib.nix +++ b/website/lib.nix @@ -99,22 +99,22 @@ rec { relativePath = path1': path2': let inherit (lib.path) subpath; - inherit (lib) lists; + inherit (lib) lists length take drop min max; + inherit (lists) replicate findFirstIndex zipLists; path1 = subpath.components path1'; - prefix1 = with lib; take (length path1 - 1) path1; path2 = subpath.components path2'; - prefix2 = with lib; take (length path2 - 1) path2; + prefix1 = take (length path1 - 1) path1; - commonPrefixLength = with lists; - findFirstIndex (i: i.fst != i.snd) - (length prefix1) - (zipLists prefix1 prefix2); - - relativeComponents = with lists; - [ "." ] ++ (replicate (length prefix1 - commonPrefixLength) "..") ++ (drop commonPrefixLength path2); + common-prefix-length = findFirstIndex (i: i.fst != i.snd) + (min (length prefix1) (length path2 - 1)) + (zipLists prefix1 path2); + parent-levels = max 0 (length prefix1 - common-prefix-length); + relative-components = [ "." ] ++ + (replicate parent-levels "..") ++ + (drop common-prefix-length path2); in - join "/" relativeComponents; + join "/" relative-components; /** Recursively list all Nix files from a directory, except the top-level `default.nix` diff --git a/website/tests.nix b/website/tests.nix index 5fe31b60..58184a78 100644 --- a/website/tests.nix +++ b/website/tests.nix @@ -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; + }; }