packages feed

okf-core-0.14.0.0: src/Okf/Path.hs

-- | URI references in Markdown and path-valued OKF frontmatter.
module Okf.Path
  ( ReferenceContext (..),
    PathReference (..),
    classifyPathReference,
    classifyFileReference,
    collapseBundlePath,
    PathResolution (..),
    resolvePathReference,
    resolveFileReference,
    rootRelativeAlternative,
  )
where

import Control.Monad (foldM, guard)
import Data.ByteString.Char8 qualified as Bytes
import Data.Char (isControl)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as Text
import Network.URI (parseURIReference, unEscapeString, uriAuthority, uriPath, uriScheme)
import Okf.ConceptId (ConceptId, conceptIdToFilePath)
import Okf.Prelude
import System.FilePath ((</>))
import System.FilePath qualified as FilePath

data ReferenceContext
  = BodyReference
  | -- | The caller enables the root retry for eligible older declarations.
    FrontmatterReference !Bool
  deriving stock (Generic, Eq, Show)

data PathReference
  = ExternalUrl !Text
  | BundlePath !FilePath
  | EscapesBundle
  | MalformedPath
  deriving stock (Generic, Eq, Ord, Show)

data PathResolution
  = ResolvedExternal !Text
  | ResolvedInBundle !FilePath
  | DanglingInBundle !FilePath
  | UnresolvableEscape
  | UnresolvableMalformed
  deriving stock (Generic, Eq, Ord, Show)

-- | Classify relative to an existing concept ID.
classifyPathReference :: ConceptId -> Text -> PathReference
classifyPathReference = classifyFileReference . conceptIdToFilePath

-- | Decode one segment at a time before collapsing dot segments. Encoded
-- separators and control characters are invalid. URI schemes and network
-- authorities never produce local filesystem paths.
classifyFileReference :: FilePath -> Text -> PathReference
classifyFileReference source raw =
  case parseURIReference (Text.unpack (Text.strip raw)) of
    Nothing -> MalformedPath
    Just uri
      | not (null (uriScheme uri)) ->
          ExternalUrl (Text.toCaseFold (Text.dropEnd 1 (Text.pack (uriScheme uri))))
      | isJust (uriAuthority uri) -> EscapesBundle
      | null (uriPath uri) -> MalformedPath
      | otherwise ->
          case traverse decodeSegment (Text.splitOn "/" (Text.pack (uriPath uri))) of
            Nothing -> MalformedPath
            Just segments ->
              let decoded = FilePath.joinPath (filter (not . null) segments)
                  base = if headSlash (uriPath uri) then "" else FilePath.takeDirectory source
               in maybe EscapesBundle (BundlePath . FilePath.normalise) (collapseBundlePath (base </> decoded))
  where
    headSlash ('/' : _) = True
    headSlash _ = False
    decodeSegment bytes = do
      decoded <- either (const Nothing) Just (Text.decodeUtf8' (Bytes.pack (unEscapeString (Text.unpack bytes))))
      guard (not (Text.any (\c -> isControl c || c == '/' || c == '\\') decoded))
      pure (Text.unpack decoded)

-- | Resolve a concept-relative reference without an optional root retry.
resolvePathReference :: (FilePath -> Bool) -> ConceptId -> Text -> PathResolution
resolvePathReference exists source = resolveFileReference exists BodyReference (conceptIdToFilePath source)

-- | Resolve solely against the supplied bounded, case-sensitive inventory.
-- An eligible relative field retries from the root after a local miss.
resolveFileReference :: (FilePath -> Bool) -> ReferenceContext -> FilePath -> Text -> PathResolution
resolveFileReference exists context source raw =
  case classifyFileReference source raw of
    ExternalUrl scheme -> ResolvedExternal scheme
    BundlePath target
      | exists target -> ResolvedInBundle target
      | FrontmatterReference True <- context,
        Just alternative <- rootRelativeAlternative exists raw ->
          ResolvedInBundle alternative
      | otherwise -> DanglingInBundle target
    EscapesBundle -> UnresolvableEscape
    MalformedPath -> UnresolvableMalformed

-- | The target a relative reference would select from the root. Also used to
-- offer strict-mode repair hints when a bundle has disabled the legacy retry.
rootRelativeAlternative :: (FilePath -> Bool) -> Text -> Maybe FilePath
rootRelativeAlternative exists raw = do
  guard (not ("/" `Text.isPrefixOf` Text.strip raw))
  case classifyFileReference "" raw of
    BundlePath path | exists path -> Just path
    _ -> Nothing

-- | Fold dot segments, failing on the first attempt to climb above the root.
collapseBundlePath :: FilePath -> Maybe FilePath
collapseBundlePath path =
  FilePath.joinPath . reverse <$> foldM step [] (FilePath.splitDirectories path)
  where
    step acc "." = Just acc
    step [] ".." = Nothing
    step (_ : acc) ".." = Just acc
    step acc segment = Just (segment : acc)