packages feed

nova-nix-0.11.0.0 / src / Nix / Store / Path.hs

-- | Nix store path types and computation.---- == The Nix store model---- The Nix store is a flat directory of immutable, content-addressed-- packages.  Every entry looks like:---- @\/nix\/store\/\<hash\>-\<name\>@---- On Windows, this becomes:---- @C:\\nix\\store\\\<hash\>-\<name\>@---- The store is IMMUTABLE.  Once a path is registered, it never changes.-- Each path's files and directories are made read-only as the path is-- added ("Nix.Store.Metadata"); the store directory itself stays-- writable, so paths can be added and removed.  This immutability is-- what enables:---- * Atomic upgrades (install new version, switch symlink, done)-- * Rollbacks (old version still in store, just switch symlink back)-- * Concurrent installs (no file conflicts - different hashes = different dirs)-- * Garbage collection (delete unreferenced paths, everything else stays)-- * Binary substitution (if hash matches, the build output is identical)---- == References---- A store path can REFERENCE other store paths.  For example, a compiled-- binary references its shared libraries, its interpreter, etc.  Nix-- scans the output for store path strings to discover these references-- automatically.  The reference graph is what the garbage collector-- follows - anything reachable from a GC root is kept.module Nix.Store.Path  ( -- * Store directory    StoreDir (..),    defaultStoreDir,    defaultStoreDirText,    platformStoreDir,    platformStoreDirText,    windowsStoreDir,    -- * Store paths    StorePath (spHash, spName),    StoreWriteMode (..),    storePathToFilePath,    storePathToText,    storePathBasename,    isCanonicalStoreText,    isInStoreText,    storeTextToFilePath,    qualifyPathText,    storeDirDrive,    parseStorePath,    parseStorePathPrefix,    parseStorePathBaseName,    storePathBaseNameError,    -- * Name validation    StorePathNameError (..),    StorePathNameReason (..),    checkStorePathName,    validStorePathName,    storePathNameErrorText,    storePathNameReasonText,    storePathNameUpstreamText,    BadStorePath (..),    badStorePathText,    -- * Constants    storePathHashLen,  )whereimport Data.Char (isAsciiLower, isAsciiUpper, isDigit)import Data.Text (Text)import qualified Data.Text as Timport Nix.Store.Path.Internal (StorePath (..))import System.FilePath (isPathSeparator, (</>))import qualified System.Info-- | The base directory of the Nix store.newtype StoreDir = StoreDir {unStoreDir :: FilePath}  deriving (Eq, Show)-- | Default store directory on Unix: @\/nix\/store@.defaultStoreDir :: StoreDirdefaultStoreDir = StoreDir "/nix/store"-- | Default store directory as 'Text', for use in the evaluator.defaultStoreDirText :: TextdefaultStoreDirText = T.pack (unStoreDir defaultStoreDir)-- | Platform-appropriate store directory.-- Returns @C:\\nix\\store@ on Windows, @\/nix\/store@ on Unix.-- Use this for filesystem operations and operator-facing output.-- Use 'defaultStoreDir' for identity - hashing, ATerm text, and every-- eval-visible store-path string (including @builtins.storeDir@).platformStoreDir :: StoreDirplatformStoreDir = case System.Info.os of  "mingw32" -> windowsStoreDir  _ -> defaultStoreDir-- | Platform-appropriate store directory as 'Text'.-- Returns @C:\\nix\\store@ on Windows, @\/nix\/store@ on Unix.platformStoreDirText :: TextplatformStoreDirText = T.pack (unStoreDir platformStoreDir)-- | Default store directory on Windows: @C:\\nix\\store@.windowsStoreDir :: StoreDirwindowsStoreDir = StoreDir "C:\\nix\\store"-- | Convert a t'StorePath' to a full filesystem path under a t'StoreDir'.storePathToFilePath :: StoreDir -> StorePath -> FilePathstorePathToFilePath (StoreDir dir) sp =  dir </> T.unpack (storePathBasename sp)-- | Convert a t'StorePath' to 'Text' under a store directory, joined by-- @\/@ whatever the platform; the directory keeps its own spelling.-- Unlike 'storePathToFilePath', the result under 'defaultStoreDir' is the-- canonical text, safe for ATerm serialization and cross-platform-- round-trips.storePathToText :: StoreDir -> StorePath -> TextstorePathToText (StoreDir dir) sp =  T.pack dir <> "/" <> storePathBasename sp-- | A t'StorePath' with no store directory, @\<hash\>-\<name\>@: what-- upstream's @StorePath::to_string@ gives, the form a narinfo's-- @References@ and @Deriver@ fields hold, and how upstream's messages name-- a derivation where they do not print the whole path.storePathBasename :: StorePath -> TextstorePathBasename sp = spHash sp <> "-" <> spName sp-- | Whether path text lies under the canonical store dir: exactly-- @\/nix\/store@, or @\/nix\/store@ followed by a separator of either-- spelling.  This is the spelling writers put into eval-visible values.isCanonicalStoreText :: Text -> BoolisCanonicalStoreText txt = case T.stripPrefix defaultStoreDirText txt of  Just rest -> case T.uncons rest of    Nothing -> True    Just (c, _) -> c == '/' || c == '\\'  Nothing -> False-- | Whether path text names something in the canonical store dir, as-- upstream's @isInStore@ asks: the store dir followed by a separator and-- at least one more character, so not the store dir itself-- (@isInDir@ in file-system.cc).isInStoreText :: Text -> BoolisInStoreText txt = case T.stripPrefix defaultStoreDirText txt >>= T.uncons of  Just (separator, rest) -> (separator == '/' || separator == '\\') && not (T.null rest)  Nothing -> False-- | Resolve path-value text to the filesystem location it names: text-- under the canonical store dir resolves into the given store dir, and-- every other path is 'qualifyPathText' of it.  Writers emit the-- canonical spelling into eval values, so every reader that performs IO-- on a path value must resolve through this - on Windows the rooted-- @\/nix@ prefix, and any other rooted path with no drive, would-- otherwise resolve against the working drive.---- The store dir is a parameter rather than 'platformStoreDir' because a-- caller may have been given one (@--store@): reads resolve against the-- directory the writes go to, not the platform default.storeTextToFilePath :: StoreDir -> Text -> FilePathstoreTextToFilePath storeDir txt  | isCanonicalStoreText txt =      unStoreDir storeDir <> T.unpack (T.drop (T.length defaultStoreDirText) txt)  | otherwise = T.unpack (qualifyPathText storeDir txt)-- | Path-value text named on the drive the file system reads it on, in-- the value's own spelling: a rooted path with no drive of its own-- (@\/src\/f.nix@) gains the store directory's drive designator, so the-- same value names the same file whatever drive is current.  Store text-- is returned as it is: it names the store directory, not the store-- drive's @\\nix\\store@ (under @--store D:\\s@, @\/nix\/store\/...@ is-- under @D:\\s@ and @\/nix@ is @D:\/nix@).  A store directory with no-- drive (every POSIX one) leaves every path as it is, as does a path-- that is relative or already names a drive, and one that leads with two-- separators, which Windows reads as a UNC or device path naming its own-- root (a path value never does: canonicalization collapses them).---- The access policy checks this text and the reads open-- 'storeTextToFilePath' of it, so the path checked is the path opened.qualifyPathText :: StoreDir -> Text -> TextqualifyPathText storeDir txt  | isCanonicalStoreText txt = txt  | Just (lead, rest) <- T.uncons txt,    isPathSeparator lead,    not (maybe False (isPathSeparator . fst) (T.uncons rest)),    Just drive <- storeDirDrive storeDir =      drive <> txt  | otherwise = txt-- | The drive designator (@C:@) a store directory begins with, if any.-- 'Nix.Store.Handle.canonicalStoreDir' makes the directory absolute, so a-- store on a Windows drive always spells one, and a POSIX store, rooted-- at @\/@, never does.storeDirDrive :: StoreDir -> Maybe TextstoreDirDrive (StoreDir dir) = case dir of  letter : ':' : _ | isAsciiUpper letter || isAsciiLower letter -> Just (T.pack [letter, ':'])  _ -> Nothing-- | Length of the Nix base-32 hash component in store paths (32 chars).storePathHashLen :: IntstorePathHashLen = 32-- | Parse a full store path string like @\/nix\/store\/abc...-name@ into-- a t'StorePath'.  Returns 'Nothing' if the path doesn't match the-- expected format: store dir prefix + separator + 32-char hash + dash + name.-- Accepts both @\/@ and @\\@ as the separator after the store dir,-- so paths round-trip correctly regardless of which OS serialized them.parseStorePath :: StoreDir -> Text -> Maybe StorePathparseStorePath (StoreDir dir) path =  let dirText = T.pack dir      tryWithSep sep = T.stripPrefix (dirText <> sep) path >>= parseStorePathBaseName   in case tryWithSep "/" of        Just sp -> Just sp        Nothing -> tryWithSep "\\"-- | The store path a path inside the store belongs to: upstream's-- @toStorePath@, which cuts at the first separator after the store-- directory.  The path itself, a trailing-separator spelling of it, and-- anything beneath it all name it; a path outside the store, or the-- store directory itself, names nothing.  Both separators are accepted-- after the store directory, as 'parseStorePath' accepts them.parseStorePathPrefix :: StoreDir -> Text -> Maybe StorePathparseStorePathPrefix (StoreDir dir) path =  case [rest | sep <- ["/", "\\"], Just rest <- [T.stripPrefix (T.pack dir <> sep) path]] of    (rest : _) -> parseStorePathBaseName (T.takeWhile (\c -> c /= '/' && c /= '\\') rest)    [] -> Nothing-- | Parse a store path basename like @abc...-name@ - the form narinfo-- @References@ and @Deriver@ fields carry on the wire - into a-- t'StorePath': 32 nix-base32 hash chars, dash, valid non-empty name.---- Both components are charset-checked, as upstream does at its parse-- boundary: parsed text can come from a cache, and an unchecked-- component (separators, dots, drive colons in the hash or name slot)-- would later become a filesystem path via 'storePathToFilePath' that-- escapes the store root.parseStorePathBaseName :: Text -> Maybe StorePathparseStorePathBaseName basename  | T.length basename < storePathHashLen + 2 = Nothing  | otherwise =      let hashPart = T.take storePathHashLen basename          afterHash = T.drop storePathHashLen basename       in case T.uncons afterHash of            Just ('-', name)              | T.all isNixBase32Char hashPart && validStorePathName name ->                  Just (StorePath hashPart name)            _ -> Nothing-- | Why upstream refuses a base name as a store path: the @BadStorePath@-- text its @StorePath@ constructor throws (path.cc at 2.24.9), checking-- the length, then the hash's alphabet, then the name.  'Nothing' when-- none of those fails, which is every base name 'parseStorePathBaseName'-- accepts.  Upstream never looks at the character after the hash, so a-- base name wrong only there is refused here and read by upstream.storePathBaseNameError :: Text -> Maybe TextstorePathBaseNameError base  | T.length base < storePathHashLen + 1 = Just ("'" <> base <> "' is too short to be a valid store path")  | Just c <- T.find (not . isNixBase32Char) (T.take storePathHashLen base) =      Just ("store path '" <> base <> "' contains illegal base-32 character '" <> T.singleton c <> "'")  | Left err <- checkStorePathName (T.drop (storePathHashLen + 1) base) =      Just (invalidPathNameText base err)  | otherwise = Nothing-- | The nix-base32 alphabet: @0-9a-z@ without @e o u t@ (chosen upstream-- to avoid accidental words).  Hash components may contain nothing else.isNixBase32Char :: Char -> BoolisNixBase32Char c =  isDigit c    || (isAsciiLower c && c /= 'e' && c /= 'o' && c /= 'u' && c /= 't')-- | A rejected store-path name: the name itself plus the first rule it-- broke, so every boundary reports the same diagnosis.data StorePathNameError = StorePathNameError  { -- | The rejected name.    spneName :: !Text,    -- | The rule it broke.    spneReason :: !StorePathNameReason  }  deriving (Eq, Show)-- | Which path-construction scheme named an eval-time store write:-- upstream's text-path scheme (@builtins.toFile@), a recursive-- fixed-output path (source copies, @builtins.path@), or a flat-- fixed-output path (@builtins.fetchurl@).  Materialization re-derives-- the path from on-disk content under the same scheme before-- registering, so a tree that does not reproduce its path is refused-- instead of registered valid under a hash its bytes do not have.data StoreWriteMode = WriteText | WriteRecursive | WriteFlat  deriving (Eq, Show)-- | The store-path name rules, one constructor per rule.data StorePathNameReason  = -- | The name is empty.    NameEmpty  | -- | The name exceeds 'maxStorePathNameLen'; carries the actual length.    NameTooLong !Int  | -- | The name contains a character outside @[A-Za-z0-9+._?=-]@.    NameIllegalChar !Char  | -- | The first dash-separated component is the carried @.@ or @..@,    -- which would name a dot segment on disk.    NameDotSegment !Text  deriving (Eq, Show)-- | Upstream's store path name rules (its checkName boundary):-- 1-211 characters from @[A-Za-z0-9+._?=-]@, and the first dash-separated-- component may not be @.@ or @..@.  One rule rejects the traversal names-- and their @.-@ / @..-@ prefixed forms alike, while other dot-leading-- names (@.config-1.0@) stay valid.---- Enforced at BOTH boundaries: parse ('parseStorePathBaseName') and-- construction (the @makeStorePath@ family in "Nix.Hash"), so an unclean-- name cannot become a t'StorePath' from either side - in particular, no-- write sink can be handed a path that resolves outside the store root.checkStorePathName :: Text -> Either StorePathNameError ()checkStorePathName name  | T.null name = broke NameEmpty  | T.length name > maxStorePathNameLen = broke (NameTooLong (T.length name))  | firstDashComponent == "." || firstDashComponent == ".." = broke (NameDotSegment firstDashComponent)  | Just c <- T.find (not . isStorePathNameChar) name = broke (NameIllegalChar c)  | otherwise = Right ()  where    broke = Left . StorePathNameError name    firstDashComponent = T.takeWhile (/= '-') name    isStorePathNameChar c =      isAsciiLower c        || isAsciiUpper c        || isDigit c        || c == '+'        || c == '.'        || c == '_'        || c == '?'        || c == '='        || c == '-'-- | Boolean form of 'checkStorePathName', for the parse boundary.validStorePathName :: Text -> BoolvalidStorePathName = either (const False) (const True) . checkStorePathName-- | Render a rejection as @invalid store path name '<name>': <rule>@.storePathNameErrorText :: StorePathNameError -> TextstorePathNameErrorText (StorePathNameError name reason) =  "invalid store path name '" <> name <> "': " <> storePathNameReasonText reason-- | Render just the broken rule, for callers that frame the name-- themselves (e.g. @invalid derivation output name@).storePathNameReasonText :: StorePathNameReason -> TextstorePathNameReasonText reason = case reason of  NameEmpty -> "the name is empty"  NameTooLong len ->    "the name is "      <> T.pack (show len)      <> " characters, above the "      <> T.pack (show maxStorePathNameLen)      <> " maximum"  NameIllegalChar c -> "contains the illegal character " <> T.pack (show c)  NameDotSegment seg -> "the first dash-separated component may not be '" <> seg <> "'"-- | Upstream's own text for a rejected name, the message of the-- @BadStorePathName@ its @checkName@ throws (path.cc at 2.24.9), which its-- callers embed in theirs.storePathNameUpstreamText :: StorePathNameError -> TextstorePathNameUpstreamText (StorePathNameError name reason) = case reason of  NameEmpty -> "name must not be empty"  NameTooLong _ -> quoted <> " must be no longer than " <> T.pack (show maxStorePathNameLen) <> " characters"  NameIllegalChar c -> quoted <> " contains illegal character '" <> T.singleton c <> "'"  NameDotSegment segment    | segment == name -> quoted <> " is not valid"    | otherwise -> quoted <> " is not valid: first dash-separated component must not be '" <> segment <> "'"  where    quoted = "name '" <> name <> "'"-- | A store path refused where it is constructed: the hash part it would-- have had, and why its name is refused.  Upstream's @StorePath@-- constructor checks the name only once the hash exists (path.cc at-- 2.24.9), so its refusal names the whole base name.data BadStorePath = BadStorePath  { -- | The would-be hash part, in nix-base32.    bspHashPart :: !Text,    -- | Why the name is refused.    bspNameError :: !StorePathNameError  }  deriving (Eq, Show)-- | Upstream's @BadStorePath@ text for a refused construction:-- @path '\<hash\>-\<name\>' is not a valid store path: \<reason\>@.badStorePathText :: BadStorePath -> TextbadStorePathText (BadStorePath hashPart err) =  invalidPathNameText (hashPart <> "-" <> spneName err) err-- | Upstream's @checkPathName@ (path.cc at 2.24.9), which both of its-- @StorePath@ constructors raise, so a parsed base name and a constructed-- one are refused in the same words.invalidPathNameText :: Text -> StorePathNameError -> TextinvalidPathNameText base err =  "path '" <> base <> "' is not a valid store path: " <> storePathNameUpstreamText err-- | Upstream's maximum store path name length.maxStorePathNameLen :: IntmaxStorePathNameLen = 211