Commit 4e14f5fe authored by Silvan Mosberger's avatar Silvan Mosberger
Browse files

lib.path.subpath.components: init

parent 4dc542d8
Loading
Loading
Loading
Loading
+31 −0
Original line number Diff line number Diff line
@@ -336,6 +336,37 @@ in /* No rec! Add dependencies on this file at the top. */ {
              ${subpathInvalidReason path}''
      ) 0 subpaths;

  /*
  Split [a subpath](#function-library-lib.path.subpath.isValid) into its path component strings.
  Throw an error if the subpath isn't valid.
  Note that the returned path components are also valid subpath strings, though they are intentionally not [normalised](#function-library-lib.path.subpath.normalise).

  Laws:

  - Splitting a subpath into components and [joining](#function-library-lib.path.subpath.join) the components gives the same subpath but [normalised](#function-library-lib.path.subpath.normalise):

        subpath.join (subpath.components s) == subpath.normalise s

  Type:
    subpath.components :: String -> [ String ]

  Example:
    subpath.components "."
    => [ ]

    subpath.components "./foo//bar/./baz/"
    => [ "foo" "bar" "baz" ]

    subpath.components "/foo"
    => <error>
  */
  subpath.components =
    subpath:
    assert assertMsg (isValid subpath) ''
      lib.path.subpath.components: Argument is not a valid subpath string:
          ${subpathInvalidReason subpath}'';
    splitRelPath subpath;

  /* Normalise a subpath. Throw an error if the subpath isn't valid, see
  `lib.path.subpath.isValid`

+13 −0
Original line number Diff line number Diff line
@@ -204,6 +204,19 @@ let
      expr = (builtins.tryEval (subpath.normalise "..")).success;
      expected = false;
    };

    testSubpathComponentsExample1 = {
      expr = subpath.components ".";
      expected = [ ];
    };
    testSubpathComponentsExample2 = {
      expr = subpath.components "./foo//bar/./baz/";
      expected = [ "foo" "bar" "baz" ];
    };
    testSubpathComponentsExample3 = {
      expr = (builtins.tryEval (subpath.components "/foo")).success;
      expected = false;
    };
  };
in
  if cases == [] then "Unit tests successful"