okf-core-0.14.0.0: src/Okf/Index.hs
-- | Deterministic Markdown index rendering for OKF bundle directories, and the
-- bundle-root version declaration of specification §12.
module Okf.Index
( renderBundleIndexes,
renderBundleIndexesWith,
renderIndex,
renderRootIndex,
writeBundleIndexes,
writeBundleIndexesWith,
-- * OKF version declaration (specification §12)
OkfVersion (..),
VersionDeclaration (..),
BundleMetadata (..),
readBundleMetadata,
readBundleVersion,
checkBundleIndexes,
parseOkfVersion,
renderOkfVersion,
supportedOkfVersion,
frontmatterReferenceContext,
)
where
import Data.Aeson.Text qualified as Aeson.Text
import Data.Char qualified as Char
import Data.List qualified as List
import Data.Map.Strict qualified as Map
import Data.Text qualified as Text
import Data.Text.IO qualified as Text.IO
import Data.Text.Lazy qualified as Text.Lazy
import Okf.Bundle
import Okf.BundlePath (BundleEntry (..), listBundleDirectory, requireBundlePath)
import Okf.ConceptId (renderBundleLinkTarget)
import Okf.Document (Frontmatter, OKFDocument (..), frontmatterLookup, hasFrontmatterFence, optionalFieldValue, parseDocument, renderDocumentHeader, setField)
import Okf.Markdown (hasSectionHeading)
import Okf.Path (ReferenceContext (..))
import Okf.Prelude hiding (setField)
import System.Directory (doesDirectoryExist)
import System.FilePath ((</>))
import System.FilePath qualified as FilePath
import Text.Read (readMaybe)
-- | An OKF format version, written @\<major\>.\<minor\>@ (specification §12).
--
-- The derived 'Ord' compares major before minor, which is what §12's
-- "a minor version bump introduces backward-compatible additions" needs: a
-- consumer may read any declaration at or below the highest version it
-- understands within the same major.
data OkfVersion = OkfVersion
{ okfVersionMajor :: !Int,
okfVersionMinor :: !Int
}
deriving stock (Generic, Eq, Ord, Show)
-- | What a bundle's root @index.md@ says about the version it targets.
--
-- All three cases are readable. §12 makes the declaration a MAY, so an absent
-- one is the ordinary case rather than a defect, and a malformed one is worth a
-- strict-authoring diagnostic but never a refusal.
data VersionDeclaration
= VersionDeclared !OkfVersion
| VersionUndeclared
| -- | The key is present but its value is not @\<major\>.\<minor\>@. Carries
-- the value as the author wrote it, so a diagnostic can quote it back.
VersionUnparseable !Text
deriving stock (Generic, Eq, Show)
-- | Legacy root retry uses the actual declaration. An unreadable or future
-- declaration cannot opt a path into historical interpretation.
frontmatterReferenceContext :: VersionDeclaration -> ReferenceContext
frontmatterReferenceContext declaration =
FrontmatterReference $ case declaration of
VersionUndeclared -> True
VersionDeclared (OkfVersion 0 minor) -> minor <= 2
_ -> False
-- | The highest OKF version this library understands. Specification §12's
-- best-effort rule is applied against this value: see
-- @Okf.Validation.versionGate@, which is the one place that decides what a
-- declared version implies.
supportedOkfVersion :: OkfVersion
supportedOkfVersion = OkfVersion {okfVersionMajor = 0, okfVersionMinor = 3}
-- | Render a version back to its @\<major\>.\<minor\>@ text form.
renderOkfVersion :: OkfVersion -> Text
renderOkfVersion OkfVersion {okfVersionMajor, okfVersionMinor} =
Text.pack (show okfVersionMajor) <> "." <> Text.pack (show okfVersionMinor)
-- | Parse a @\<major\>.\<minor\>@ version. Exactly two dot-separated runs of
-- ASCII digits; anything else is unparseable.
parseOkfVersion :: Text -> Maybe OkfVersion
parseOkfVersion rawVersion =
case Text.splitOn "." (Text.strip rawVersion) of
[majorText, minorText] ->
OkfVersion <$> digits majorText <*> digits minorText
_ -> Nothing
where
digits component
| Text.null component = Nothing
| Text.all Char.isDigit component = readMaybe (Text.unpack component)
| otherwise = Nothing
-- | Bundle-scoped metadata declared in the root index. The raw mapping retains
-- extension keys and the original YAML text for regeneration.
data BundleMetadata = BundleMetadata
{ bundleTitle :: !(Maybe Text),
bundleDescription :: !(Maybe Text),
bundleLicense :: !(Maybe Text),
bundleVersion :: !VersionDeclaration,
bundleFrontmatter :: !Frontmatter
}
deriving stock (Generic, Eq, Show)
-- | Read a root header. Absent and headerless indexes yield 'Nothing'.
-- A delimited header that is malformed is a separate, path-specific failure.
readBundleMetadata :: FilePath -> IO (Either BundleError (Maybe BundleMetadata))
readBundleMetadata root = do
loaded <- readRootIndex root
pure $ do
source <- loaded
traverse parseHeader (source >>= hasHeader)
where
hasHeader source = if hasFrontmatterFence source then Just source else Nothing
parseHeader source = do
document <- first (InvalidConceptDocument "index.md") (parseDocument source)
let fm = frontmatter document
textMember key = case optionalFieldValue key fm of
Just (String value) -> Just value
_ -> Nothing
pure
BundleMetadata
{ bundleTitle = textMember "title",
bundleDescription = textMember "description",
bundleLicense = textMember "license",
bundleVersion = maybe VersionUndeclared declarationFromValue (frontmatterLookup "okf_version" fm),
bundleFrontmatter = fm
}
-- | Best-effort declaration reader retained for callers that only need the
-- version. Use 'readBundleMetadata' when malformed headers must be diagnosed.
readBundleVersion :: FilePath -> IO (Either BundleError VersionDeclaration)
readBundleVersion root = do
loaded <- readBundleMetadata root
pure $ case loaded of
Left (InvalidConceptDocument _ _) -> Right VersionUndeclared
Left error_ -> Left error_
Right metadata -> Right (maybe VersionUndeclared bundleVersion metadata)
readRootIndex :: FilePath -> IO (Either BundleError (Maybe Text))
readRootIndex root = tryBundleIo "index.md" $ do
exists <- doesDirectoryExist root
entries <- if exists then listBundleDirectory root "" else pure []
case [path | BundleFile path <- entries, path == "index.md"] of
[path] -> Just <$> (requireBundlePath root path >>= Text.IO.readFile)
_ -> pure Nothing
-- | Check the structure of every index present in the bounded inventory.
checkBundleIndexes :: FilePath -> VersionDeclaration -> BundleInventory -> IO [BundleError]
checkBundleIndexes root declaration inventory =
concat <$> traverse check indexes
where
indexes = filter ((== "index.md") . FilePath.takeFileName) (bundleInventoryFiles inventory)
requireHeading =
case declaration of
VersionDeclared version -> requiresIndexSection version
_ -> False
check path = do
loaded <- tryBundleIo path (requireBundlePath root path >>= Text.IO.readFile)
pure $ case loaded of
Left err -> [err]
Right source ->
case parseDocument source of
Left err -> [InvalidConceptDocument path err]
Right document ->
[InvalidReservedFile path "a nested index.md must not have YAML frontmatter" | path /= "index.md", hasFrontmatterFence source]
<> [InvalidReservedFile path "index.md must contain a section heading" | requireHeading, not (hasSectionHeading (body document))]
-- | Read the declared value, accepting both the quoted string form the
-- specification writes (@okf_version: "0.2"@) and the bare YAML number a
-- careless author writes (@okf_version: 0.2@). A bundle should not become
-- unreadable over a missing pair of quotes.
declarationFromValue :: Value -> VersionDeclaration
declarationFromValue value =
case parseOkfVersion rendered of
Just version -> VersionDeclared version
Nothing -> VersionUnparseable rendered
where
rendered = case value of
String text -> text
-- Everything else is quoted back through JSON so the diagnostic can show
-- what was written. A YAML number reaches here as @0.2@, which parses.
other -> Text.Lazy.toStrict (Aeson.Text.encodeToLazyText other)
-- | Render an @index.md@ for one bundle directory from its immediate concepts,
-- subdirectory names, and non-concept files.
--
-- Specification §8 says an index "enumerates the directory's contents to support
-- progressive disclosure". A directory holding only
-- @references\/attesters\/revenue.py@ has contents, and before the files
-- parameter existed its generated index was a single newline — which is exactly
-- the directory shape §6.3's @references\/@ convention encourages. See
-- @docs\/adr\/13-the-references-convention-and-non-markdown-files.md@.
--
-- The files given are those that are not concepts and not reserved: in practice
-- every regular file whose extension is not @.md@. Dotfiles are excluded by the
-- caller, so a stray @.DS_Store@ never reaches a committed index.
renderIndex :: [FilePath] -> [FilePath] -> [Concept] -> Text
renderIndex subdirectories files concepts =
Text.intercalate "\n" (filter (not . Text.null) [subdirectorySection, fileSection, conceptSections])
where
sortedSubdirectories = List.sort subdirectories
subdirectorySection
| null sortedSubdirectories = ""
| otherwise =
Text.unlines
( "# Subdirectories"
: ""
: (directoryBullet <$> sortedSubdirectories)
)
sortedFiles = List.sort files
fileSection
| null sortedFiles = ""
| otherwise = Text.unlines ("# Files" : "" : (fileBullet <$> sortedFiles))
groupedConcepts = Map.toAscList (foldr addConcept Map.empty concepts)
conceptSections =
Text.intercalate "\n" (sectionForType <$> groupedConcepts)
addConcept :: Concept -> Map.Map Text [Concept] -> Map.Map Text [Concept]
addConcept concept =
Map.insertWith (<>) (conceptType concept) [concept]
sectionForType :: (Text, [Concept]) -> Text
sectionForType (typeName, concepts) =
Text.unlines
( ("# " <> typeName)
: ""
: (conceptBullet <$> List.sortOn conceptSourcePath concepts)
)
-- | Render the bundle-root @index.md@, which is the one index permitted to
-- carry frontmatter (specification §8) and the one place a bundle declares the
-- version it targets (§12).
--
-- With no version this is exactly 'renderIndex', so a bundle that declares
-- nothing keeps a frontmatter-free root index. The value is quoted because §12
-- writes it quoted and because an unquoted @0.2@ is a YAML float whose text
-- form no serializer guarantees to preserve.
renderRootIndex :: Maybe OkfVersion -> [FilePath] -> [FilePath] -> [Concept] -> Text
renderRootIndex version subdirectories files concepts =
case version of
Nothing -> listing
Just declared ->
Text.unlines ["---", "okf_version: \"" <> renderOkfVersion declared <> "\"", "---"]
<> if Text.null listing then "" else "\n" <> listing
where
listing = addEmptySection (maybe False requiresIndexSection version) (renderIndex subdirectories files concepts)
requiresIndexSection :: OkfVersion -> Bool
requiresIndexSection (OkfVersion major minor) = major == 0 && minor >= 3
addEmptySection :: Bool -> Text -> Text
addEmptySection required listing
| required && Text.null listing = "# Files\n"
| otherwise = listing
directoryBullet :: FilePath -> Text
directoryBullet directory =
"- [" <> Text.pack directory <> "/](" <> renderBundleLinkTarget (directory </> "index.md") <> ")"
-- | A file has no frontmatter, so there is no title to prefer and no description
-- to append: the link text is the name.
fileBullet :: FilePath -> Text
fileBullet file =
"- [" <> Text.pack file <> "](" <> renderBundleLinkTarget file <> ")"
conceptBullet :: Concept -> Text
conceptBullet concept =
"- ["
<> fromMaybe (Text.pack (FilePath.dropExtension (FilePath.takeFileName (conceptSourcePath concept)))) (conceptTitle concept)
<> "]("
<> renderBundleLinkTarget (FilePath.takeFileName (conceptSourcePath concept))
<> ")"
<> maybe "" (" - " <>) (conceptDescription concept)
-- | Write deterministic @index.md@ files for every directory in a bundle,
-- preserving any version declaration the root index already carries.
writeBundleIndexes :: FilePath -> IO (Either BundleError ())
writeBundleIndexes = writeBundleIndexesWith Nothing
-- | 'writeBundleIndexes' with an explicit version declaration for the bundle
-- root. 'Just' overrides whatever the root index carries; 'Nothing' preserves
-- it.
writeBundleIndexesWith :: Maybe OkfVersion -> FilePath -> IO (Either BundleError ())
writeBundleIndexesWith override root = do
rendered <- renderBundleIndexesWith override root
case rendered of
Left bundleError -> pure (Left bundleError)
Right indexes -> do
checked <- traverse (\(relative, content) -> tryBundleIo relative ((,content) <$> requireBundlePath root relative)) indexes
case sequenceA checked of
Left err -> pure (Left err)
Right targets -> do
written <- traverse (\(absolute, content) -> tryBundleIo absolute (Text.IO.writeFile absolute content)) targets
pure (() <$ sequenceA written)
-- | Render every @index.md@ file that would be written for a bundle,
-- preserving any version declaration the root index already carries.
renderBundleIndexes :: FilePath -> IO (Either BundleError [(FilePath, Text)])
renderBundleIndexes = renderBundleIndexesWith Nothing
-- | Render indexes, preserving the original root header and applying any
-- explicit version override to that header. A malformed header prevents
-- regeneration until the author repairs it.
renderBundleIndexesWith :: Maybe OkfVersion -> FilePath -> IO (Either BundleError [(FilePath, Text)])
renderBundleIndexesWith override root = do
metadata <- readBundleMetadata root
case metadata of
Left err -> pure (Left err)
Right header -> do
walked <- walkBundle root
scanned <- walkBundleInventory root
pure $ do
concepts <- walked
inventory <- scanned
let directories = bundleInventoryDirectories inventory
assets = filter ((/= ".md") . FilePath.takeExtension) (bundleInventoryFiles inventory)
render = renderDirectoryIndex override header directories assets concepts
pure (map render directories)
-- | Render one directory using the same bounded tree as the concept reader.
renderDirectoryIndex :: Maybe OkfVersion -> Maybe BundleMetadata -> [FilePath] -> [FilePath] -> [Concept] -> FilePath -> (FilePath, Text)
renderDirectoryIndex override header directories assets concepts relativeDir =
(relativeDir </> "index.md", content)
where
parent = FilePath.normalise relativeDir
belongsHere path = FilePath.takeDirectory path == parent
subdirectories = [FilePath.takeFileName path | path <- directories, not (null path), belongsHere path]
files = [FilePath.takeFileName path | path <- assets, belongsHere path]
immediateConcepts = filter (belongsHere . conceptSourcePath) concepts
declared = case bundleVersion <$> header of
Just (VersionDeclared version) -> Just version
_ -> Nothing
requiredSection = maybe False requiresIndexSection (override <|> declared)
listing = addEmptySection requiredSection (renderIndex subdirectories files immediateConcepts)
content
| not (null relativeDir) = listing
| Just metadata <- header =
let fm = bundleFrontmatter metadata
updated = maybe fm (\version -> setField "okf_version" (String (renderOkfVersion version)) fm) override
in renderIndexWithHeader updated listing
| otherwise = renderRootIndex override subdirectories files immediateConcepts
renderIndexWithHeader :: Frontmatter -> Text -> Text
renderIndexWithHeader fm listing
| Text.null listing = header
| any (`Text.isSuffixOf` header) ["\n\n", "\n\r\n"] = header <> listing
| "\r\n" `Text.isSuffixOf` header = header <> "\r\n" <> listing
| "\n" `Text.isSuffixOf` header = header <> "\n" <> listing
| otherwise = header <> "\n\n" <> listing
where
header = renderDocumentHeader fm