packages feed

sqitch-plan (empty) → 0.1.0.0

raw patch · 13 files changed

+1832/−0 lines, 13 filesdep +basedep +containersdep +hedgehog

Dependencies added: base, containers, hedgehog, process, sqitch-plan, tasty, tasty-hedgehog, tasty-hunit, text, time

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Changelog++## 0.1.0.0++First version: parse, query and render `sqitch.plan`.
+ LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Kronor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ README.md view
@@ -0,0 +1,56 @@+# sqitch-plan++Parse, query and render [sqitch](https://sqitch.org)'s `sqitch.plan` files.++```haskell+import Data.Text qualified as Text+import Data.Text.IO qualified as Text.IO+import Sqitch.Plan qualified as Plan++main :: IO ()+main = do+    src <- Text.IO.readFile "sqitch.plan"+    plan <- either (fail . Text.unpack . Plan.renderParseError) pure (Plan.parsePlan src)+    mapM_ (\c -> print (c.line, c.value.name, Plan.reworkTag c.value)) (Plan.changes plan)+```++- **The whole format**, following sqitch's own reader (`App::Sqitch::Plan`):+  `%pragma=value` lines, blank and `#` comment lines, change lines with+  `[dependencies]` (requires, `!conflicts`, `change@tag`, `@tag`,+  `project:change`, change IDs), planner timestamp, name and `<email>`, `# notes`, tag+  lines, and the legacy `+`/`-` operators. Sqitch's name rules are enforced, including the reserved `HEAD` / `ROOT`+  and the stricter rules for declaring tags. Notes built with `newChange` /+  `newTag` are escaped as sqitch escapes them; `noteText` undoes it.+- **Line numbers**: every entry is a `Located` value carrying its 1-based line.+- **Round trip**: whitespace is kept in each entry's `layout`, so+  `render <$> parsePlan src == Right src` for every plan the parser accepts.+  `newChange` / `newTag` build entries laid out the way `sqitch add` and+  `sqitch tag` write them, and `appendItems` adds them to a plan.+- **Queries**: `changes`, `tags`, `steps` (both, in order), `occurrences`,+  `lastOccurrence`, `changesAfter`, `isTagged`, `isReworked`, `reworkTag`,+  `reworks`, `pragmaValue` / `projectName` / `uri`.+- **Light**: depends on `base`, `text`, `containers` and `time` only.++## Install++sqitch-plan is not on Hackage yet. Pin a commit from a `cabal.project`:++```cabal+source-repository-package+  type:     git+  location: https://github.com/kronor-io/sqitch-plan+  tag:      <commit>+```++## Tests++`cabal test` round-trips a synthetic plan (`test/fixtures/shop.plan`) that+uses every construct of the format, with odd whitespace, and checks its+changes, tags, pragmas, dependencies, notes and reworks against expected+values written by hand. Small hand-written plans cover each grammar feature+and each error.++When run inside a git checkout, the tests also round-trip every+`*sqitch*.plan` file tracked there, so a project that vendors this package+gets its own plans checked. The package has been tested against large+real-world plans this way.
+ sqitch-plan.cabal view
@@ -0,0 +1,81 @@+cabal-version:      3.0+name:               sqitch-plan+version:            0.1.0.0+synopsis:           Parse and render sqitch.plan files+description:+  A parser and renderer for the plan files of+  <https://sqitch.org sqitch>, the database change manager. It reads the+  whole format (pragmas, changes with dependencies, tags, notes, comments+  and reworks), keeps each entry's line number, and writes a parsed plan+  back byte for byte.++homepage:           https://github.com/kronor-io/sqitch-plan+bug-reports:        https://github.com/kronor-io/sqitch-plan/issues+license:            MIT+license-file:       LICENSE+author:             José Lorenzo Rodríguez+maintainer:         lorenzo@kronor.io+copyright:          2026 Kronor+category:           Database+build-type:         Simple+tested-with:        GHC ==9.10.3 || ==9.12.4 || ==9.14.1+extra-doc-files:+  CHANGELOG.md+  README.md++extra-source-files:+  test/fixtures/*.changes+  test/fixtures/*.plan+  test/fixtures/*.tags++source-repository head+  type:     git+  location: https://github.com/kronor-io/sqitch-plan++-- The package sets its own extensions and warnings rather than relying on+-- a cabal.project to supply them.+common language+  default-language:   GHC2024+  default-extensions:+    BlockArguments+    DuplicateRecordFields+    LambdaCase+    OverloadedRecordDot+    OverloadedStrings++  ghc-options:+    -Wall -Wcompat -Widentities -Wincomplete-record-updates+    -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints+    -Wunused-packages++library+  import:          language+  hs-source-dirs:  src+  exposed-modules:+    Sqitch.Plan+    Sqitch.Plan.Parse+    Sqitch.Plan.Render+    Sqitch.Plan.Types++  build-depends:+    , base        >=4.20 && <5+    , containers  >=0.6  && <0.9+    , text        >=2.0  && <2.2+    , time        >=1.12 && <1.16++test-suite sqitch-plan-test+  import:         language+  type:           exitcode-stdio-1.0+  hs-source-dirs: test+  main-is:        Main.hs+  other-modules:  Properties+  build-depends:+    , base+    , hedgehog        >=1.4  && <1.8+    , process         >=1.6  && <1.7+    , sqitch-plan+    , tasty           >=1.4  && <1.6+    , tasty-hedgehog  >=1.4  && <1.5+    , tasty-hunit     >=0.10 && <0.11+    , text+    , time
+ src/Sqitch/Plan.hs view
@@ -0,0 +1,233 @@+-- | Sqitch's @sqitch.plan@ format: parse it, query it, write it back.+--+-- > import Sqitch.Plan qualified as Plan+-- >+-- > main = do+-- >     src <- Data.Text.IO.readFile "sqitch.plan"+-- >     plan <- either (fail . Text.unpack . Plan.renderParseError) pure (Plan.parsePlan src)+-- >     mapM_ (print . (.value.name)) (Plan.changes plan)+--+-- See @sqitch-plan(5)@ and @sqitchchanges(3)@ for the format itself.+module Sqitch.Plan (+    module Sqitch.Plan.Types,++    -- * Reading and writing+    parsePlan,+    ParseError (..),+    renderParseError,+    render,+    renderItem,+    renderDependency,+    validName,+    validChangeName,+    validTagName,+    isChangeId,++    -- * Pragmas+    pragmas,+    pragmaValue,+    syntaxVersion,+    projectName,+    uri,++    -- * Changes and tags+    Step (..),+    steps,+    changes,+    tags,+    occurrences,+    lastOccurrence,+    changesAfter,+    changesAfterLine,+    tagsAfterLine,+    isTagged,++    -- * Reworks+    Rework (..),+    isReworked,+    reworkTag,+    reworks,++    -- * Building+    newChange,+    newTag,+    appendItems,+) where++import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe, isNothing, listToMaybe, mapMaybe)+import Data.Text (Text)+import Data.Time (UTCTime)+import Sqitch.Plan.Parse+import Sqitch.Plan.Render+import Sqitch.Plan.Types+import Prelude+++----------------------------------------------------------------------------------------------------+-- Pragmas++pragmas :: Plan -> [Located Pragma]+pragmas = located (\case PragmaItem p -> Just p; _ -> Nothing)+++-- | The value of a pragma. If a plan repeats one the last wins, and a+-- pragma written without @=value@ counts as @1@, both as in sqitch. The+-- entry itself keeps what was written ('Pragma.value').+pragmaValue :: Text -> Plan -> Maybe Text+pragmaValue name plan =+    Map.lookup name (Map.fromList [(p.value.name, fromMaybe "1" p.value.value) | p <- pragmas plan])+++syntaxVersion, projectName, uri :: Plan -> Maybe Text+syntaxVersion = pragmaValue "syntax-version"+projectName = pragmaValue "project"+uri = pragmaValue "uri"+++----------------------------------------------------------------------------------------------------+-- Changes and tags++-- | A change or a tag: the lines that are deploy steps.+data Step = StepChange Change | StepTag Tag+    deriving stock (Eq, Show)+++-- | Changes and tags in plan order.+steps :: Plan -> [Located Step]+steps = located \case+    ChangeItem c -> Just (StepChange c)+    TagItem t -> Just (StepTag t)+    _ -> Nothing+++-- | Every change in plan order, which is deploy order. A reworked+-- change appears once per occurrence.+changes :: Plan -> [Located Change]+changes = located (\case ChangeItem c -> Just c; _ -> Nothing)+++tags :: Plan -> [Located Tag]+tags = located (\case TagItem t -> Just t; _ -> Nothing)+++-- | Every occurrence of a change name, in plan order: more than one+-- when the change has been reworked.+occurrences :: Text -> Plan -> [Located Change]+occurrences name = filter (\c -> c.value.name == name) . changes+++-- | The latest occurrence of a change: the one a deploy ends on.+lastOccurrence :: Text -> Plan -> Maybe (Located Change)+lastOccurrence name = listToMaybe . reverse . occurrences name+++-- | The changes after the last occurrence of the named one, or 'Nothing'+-- if the plan has no such change.+changesAfter :: Text -> Plan -> Maybe [Located Change]+changesAfter name plan = (\c -> changesAfterLine c.line plan) <$> lastOccurrence name plan+++-- | The changes below a line.+changesAfterLine :: Int -> Plan -> [Located Change]+changesAfterLine n = filter (\c -> c.line > n) . changes+++-- | The tags below a line.+tagsAfterLine :: Int -> Plan -> [Located Tag]+tagsAfterLine n = filter (\t -> t.line > n) . tags+++-- | Whether a tag follows the change's last occurrence. Sqitch can only+-- rework a change that is tagged.+isTagged :: Text -> Plan -> Bool+isTagged name plan = maybe False (\c -> not (null (tagsAfterLine c.line plan))) (lastOccurrence name plan)+++----------------------------------------------------------------------------------------------------+-- Reworks++-- | A change that occurs again after an earlier occurrence of itself.+data Rework = Rework+    { change :: Located Change+    -- ^ The later occurrence.+    , previous :: Located Change+    -- ^ The occurrence directly before it.+    , tag :: Maybe Text+    -- ^ 'reworkTag' of the later occurrence: the tag its scripts for+    -- the previous version are named after (@deploy/name\@tag.sql@).+    }+    deriving stock (Eq, Show)+++-- | Whether the plan has the change more than once.+isReworked :: Text -> Plan -> Bool+isReworked name plan = case occurrences name plan of+    _ : _ : _ -> True+    _ -> False+++-- | The tag a change requires its own earlier occurrence at: @v1@ in+-- @foo [foo\@v1] …@, which is what @sqitch rework@ writes. 'Nothing' for+-- a change that is not a rework, and also for one that depends on another+-- change at a tag (@foo [bar\@v1]@).+reworkTag :: Change -> Maybe Text+reworkTag c =+    listToMaybe+        [ t+        | d <- c.dependencies+        , d.kind == Requires+        , isNothing d.project+        , OnChange n (Just t) <- [d.target]+        , n == c.name+        ]+++-- | Every later occurrence of a change, in plan order.+reworks :: Plan -> [Rework]+reworks plan = go Map.empty (changes plan)+  where+    go _ [] = []+    go seen (c : cs) =+        let rest = go (Map.insert c.value.name c seen) cs+         in case Map.lookup c.value.name seen of+                Just previous -> Rework{change = c, previous, tag = reworkTag c.value} : rest+                Nothing -> rest+++----------------------------------------------------------------------------------------------------+-- Building++-- | A change as @sqitch add@ writes it.+newChange :: Text -> [Dependency] -> UTCTime -> Planner -> Maybe Text -> Change+newChange name dependencies timestamp planner note =+    Change+        { operator = Nothing+        , name+        , dependencies+        , timestamp+        , planner+        , note = defaultNote <$> note+        , layout = defaultEntryLayout+        }+++-- | A tag as @sqitch tag@ writes it.+newTag :: Text -> UTCTime -> Planner -> Maybe Text -> Tag+newTag name timestamp planner note =+    Tag{name, timestamp, planner, note = defaultNote <$> note, layout = defaultEntryLayout}+++-- | Add lines at the end of a plan, numbering them on from its last.+-- The plan then ends with a newline.+appendItems :: [Item] -> Plan -> Plan+appendItems items plan =+    let lastLine = maybe 0 (.line) (listToMaybe (reverse plan.entries))+        new = zipWith (\n i -> Located{line = n, value = i}) [lastLine + 1 ..] items+     in Plan{entries = plan.entries <> new, finalNewline = plan.finalNewline || not (null items)}+++----------------------------------------------------------------------------------------------------++located :: (Item -> Maybe a) -> Plan -> [Located a]+located f plan = mapMaybe (traverse f) plan.entries
+ src/Sqitch/Plan/Parse.hs view
@@ -0,0 +1,323 @@+-- | Reading a @sqitch.plan@.+--+-- The grammar follows sqitch's own reader (@App::Sqitch::Plan@), which+-- is line based:+--+-- * A line of only whitespace is blank.+-- * A line whose first non-blank character is @#@ is a comment.+-- * Anywhere else, the first @#@ starts the line's note.+-- * What precedes the note is a pragma (@%name=value@), a tag+--   (@\@name timestamp planner \<email\>@) or a change+--   (@[+|-]name [deps] timestamp planner \<email\>@).+--+-- Names follow sqitch's rules ('validName'): no whitespace or @:\@#\\@,+-- neither end is punctuation (@_@ is not punctuation), the last character+-- is a word character, and the name does not end in one of @~/=%^[]@ followed by digits, which sqitch reserves+-- for references like @HEAD^2@. A change or tag being declared is held+-- to more ('validChangeName', 'validTagName'); a dependency may refer to+-- the reserved names and to change IDs.+module Sqitch.Plan.Parse (+    parsePlan,+    ParseError (..),+    renderParseError,+    parseDependency,+    validName,+    validChangeName,+    validTagName,+    isChangeId,+) where++import Control.Monad (unless, when)+import Data.Char (GeneralCategory (ConnectorPunctuation), generalCategory, isAlphaNum, isDigit, isMark, isSpace)+import Data.Maybe (isJust)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Time (UTCTime, defaultTimeLocale, parseTimeM)+import Sqitch.Plan.Types+import Prelude+++-- | A line the parser could not read.+data ParseError = ParseError+    { line :: Int+    -- ^ 1-based.+    , message :: Text+    , source :: Text+    -- ^ The offending line, as written.+    }+    deriving stock (Eq, Show)+++-- | @line N: message@ followed by the line itself.+renderParseError :: ParseError -> Text+renderParseError e = "line " <> Text.pack (show e.line) <> ": " <> e.message <> "\n    " <> e.source+++-- | Read a whole plan. Every line becomes one entry, so+-- 'Sqitch.Plan.Render.render' gives the source back unchanged.+parsePlan :: Text -> Either ParseError Plan+parsePlan src+    | Text.null src = Right Plan{entries = [], finalNewline = False}+    | otherwise = do+        let finalNewline = "\n" `Text.isSuffixOf` src+            body = if finalNewline then Text.dropEnd 1 src else src+            readLine (n, l) = case parseLine l of+                Left message -> Left ParseError{line = n, message, source = l}+                Right item -> Right Located{line = n, value = item}+        entries <- traverse readLine (zip [1 ..] (Text.splitOn "\n" body))+        pure Plan{entries, finalNewline}+++isBlank :: Char -> Bool+isBlank = isSpace+++-- | Split off the longest suffix of characters satisfying the predicate.+spanEnd :: (Char -> Bool) -> Text -> (Text, Text)+spanEnd p t = (Text.dropWhileEnd p t, Text.takeWhileEnd p t)+++parseLine :: Text -> Either Text Item+parseLine raw+    | Text.all isBlank raw = Right (Blank raw)+    | otherwise =+        let (lead, rest) = Text.span isBlank raw+         in case Text.uncons rest of+                Just ('#', comment) -> Right (CommentItem Comment{indent = lead, text = comment})+                _ -> do+                    let (content0, notePart) = Text.breakOn "#" rest+                        (content, gap) = spanEnd isBlank content0+                        note = case Text.uncons notePart of+                            Just (_, afterNote) ->+                                let (afterHash, text) = Text.span isBlank afterNote+                                 in Just Note{gap, afterHash, text}+                            Nothing -> Nothing+                        trailing = if isJust note then "" else gap+                    case Text.uncons content of+                        Just ('%', p) -> PragmaItem <$> parsePragma lead p note trailing+                        Just ('@', t) -> TagItem <$> parseTag lead t note trailing+                        _ -> ChangeItem <$> parseChange lead content note trailing+++parsePragma :: Text -> Text -> Maybe Note -> Text -> Either Text Pragma+parsePragma leading p note trailing = do+    let (afterPercent, r1) = Text.span isBlank p+        (name, r2) = Text.break (\c -> c == '=' || isBlank c) r1+        (beforeEquals, r3) = Text.span isBlank r2+        layout afterEquals = PragmaLayout{leading, afterPercent, beforeEquals, afterEquals, trailing}+    when (Text.null name) $ Left "a pragma needs a name after the %"+    case Text.uncons r3 of+        Nothing -> Right Pragma{name, value = Nothing, note, layout = layout ""}+        Just ('=', r4) ->+            let (afterEquals, value) = Text.span isBlank r4+             in Right Pragma{name, value = Just value, note, layout = layout afterEquals}+        Just _ -> Left ("expected = after the pragma name " <> name)+++parseTag :: Text -> Text -> Maybe Note -> Text -> Either Text Tag+parseTag leading t note trailing = withName "tag" validTagName t \name r1 -> do+    let (afterName, r2) = Text.span isBlank r1+    when ("[" `Text.isPrefixOf` r2) $ Left "a tag cannot have dependencies"+    (timestamp, afterTimestamp, planner, beforeEmail) <- stampAndPlanner r2+    pure+        Tag+            { name+            , timestamp+            , planner+            , note+            , layout =+                EntryLayout+                    { leading+                    , afterOperator = ""+                    , afterName+                    , dependencyLayout = Nothing+                    , afterTimestamp+                    , beforeEmail+                    , trailing+                    }+            }+++parseChange :: Text -> Text -> Maybe Note -> Text -> Either Text Change+parseChange leading content note trailing =+    let withOperator op r = let (s, r') = Text.span isBlank r in (Just op, s, r')+        (operator, afterOperator, r0) = case Text.uncons content of+            Just ('+', r) -> withOperator Deploy r+            Just ('-', r) -> withOperator Revert r+            _ -> (Nothing, "", content)+     in withName "change" validChangeName r0 \name r1 -> parseChangeRest leading operator afterOperator name r1 note trailing+++parseChangeRest :: Text -> Maybe Operator -> Text -> Text -> Text -> Maybe Note -> Text -> Either Text Change+parseChangeRest leading operator afterOperator name r1 note trailing = do+    let (afterName, r2) = Text.span isBlank r1+    (dependencies, dependencyLayout, r3) <- case Text.uncons r2 of+        Just ('[', r) -> do+            let (inside, close) = Text.breakOn "]" r+                (afterBracket, r') = Text.span isBlank (Text.drop 1 close)+                (gaps, tokens) = splitBlanks inside+            when (Text.null close) $ Left "the dependency list has no closing ]"+            when (null tokens) $ Left "an empty dependency list; leave out the [] instead"+            deps <- traverse parseDependency tokens+            pure (deps, Just DependencyLayout{gaps, afterBracket}, r')+        _ -> pure ([], Nothing, r2)+    (timestamp, afterTimestamp, planner, beforeEmail) <- stampAndPlanner r3+    pure+        Change+            { operator+            , name+            , dependencies+            , timestamp+            , planner+            , note+            , layout =+                EntryLayout+                    { leading+                    , afterOperator+                    , afterName+                    , dependencyLayout+                    , afterTimestamp+                    , beforeEmail+                    , trailing+                    }+            }+++-- | Split a change or tag name off the start of a line and hand the rest+-- on, the way sqitch's backtracking line regex does. A name may contain+-- @[@ and @]@ (@foo[bar]baz@), so the longest valid name is tried first:+-- the whole first word, then each prefix ending before a @[@ in it. The+-- first that the rest of the line parses after wins.+withName :: Text -> (Text -> Bool) -> Text -> (Text -> Text -> Either Text a) -> Either Text a+withName what valid line k =+    let word = Text.takeWhile (not . isBlank) line+        cuts = Text.length word : reverse [i | (i, c) <- zip [0 ..] (Text.unpack word), c == '[']+        attempts = [k n rest | i <- cuts, let (n, rest) = Text.splitAt i line, valid n]+        shortest = Text.takeWhile (/= '[') word+     in case attempts of+            [] -> Left case checkName what valid shortest of+                Left e -> e+                Right () -> Text.concat ["invalid ", what, " name: ", word]+            first : _ -> foldr (\a next -> either (const next) Right a) first attempts+++-- | The whitespace runs and the words between them: one more run than+-- there are words, the first and last possibly empty.+splitBlanks :: Text -> ([Text], [Text])+splitBlanks s =+    let (g, r) = Text.span isBlank s+     in if Text.null r+            then ([g], [])+            else+                let (tok, r') = Text.break isBlank r+                    (gs, toks) = splitBlanks r'+                 in (g : gs, tok : toks)+++-- | The timestamp, planner name and @\<email\>@ that end a change or tag.+stampAndPlanner :: Text -> Either Text (UTCTime, Text, Planner, Text)+stampAndPlanner r = do+    -- The timestamp has a fixed width, so sqitch needs no blank after it.+    let (stamp, r1) = Text.splitAt 20 r+        (afterTimestamp, r2) = Text.span isBlank r1+        (nameAndGap, r3) = Text.break (== '<') r2+        (plannerName, beforeEmail) = spanEnd isBlank nameAndGap+    when (Text.null stamp) $ Left "missing the planned timestamp"+    timestamp <- parseTimestamp stamp+    when (Text.null plannerName) $ Left "missing the planner's name"+    when (Text.null beforeEmail && not (Text.null r3)) $ Left "the planner's name and <email> need a blank between them"+    case Text.uncons r3 of+        Just ('<', r4) -> do+            let (email, r5) = Text.break (== '>') r4+            when (Text.null email) $ Left "the planner's email is empty"+            case r5 of+                ">" -> pure (timestamp, afterTimestamp, Planner{name = plannerName, email}, beforeEmail)+                "" -> Left "the planner's <email> has no closing >"+                _ -> Left ("unexpected text after the planner's email: " <> Text.drop 1 r5)+        _ -> Left "missing the planner's <email>"+++parseTimestamp :: Text -> Either Text UTCTime+parseTimestamp t = case parseTimeM False defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ" (Text.unpack t) of+    Just u | formatTimestamp u == t -> Right u+    _ -> Left ("not a timestamp of the form 2026-01-31T23:59:59Z: " <> t)+++-- | One word of a change's @[…]@ list, as sqitch's+-- @App::Sqitch::Plan::Depend::parse@ reads it:+-- @[!][project:](change[\@tag] | \@tag | change-id)@.+parseDependency :: Text -> Either Text Dependency+parseDependency tok = do+    let (kind, r0) = case Text.uncons tok of+            Just ('!', r) -> (Conflicts, r)+            _ -> (Requires, tok)+        (project, r1) = case Text.breakOn ":" r0 of+            (p, rest) | not (Text.null rest) -> (Just p, Text.drop 1 rest)+            _ -> (Nothing, r0)+        bad :: Text -> Either Text a+        bad why = Left (Text.concat ["bad dependency ", tok, ": ", why])+        ref what n = unless (validName n) (bad (Text.concat ["invalid ", what, " name ", n]))+    mapM_ (ref "project") project+    target <-+        if isChangeId r1+            then pure (OnId r1)+            else case Text.breakOn "@" r1 of+                ("", "") -> bad "names neither a change nor a tag"+                ("", t) -> OnTag (Text.drop 1 t) <$ ref "tag" (Text.drop 1 t)+                (c, "") -> OnChange c Nothing <$ ref "change" c+                (c, t) -> OnChange c (Just (Text.drop 1 t)) <$ ref "change" c <* ref "tag" (Text.drop 1 t)+    pure Dependency{kind, project, target}+++checkName :: Text -> (Text -> Bool) -> Text -> Either Text ()+checkName what valid n+    | Text.null n = Left (Text.concat ["missing the ", what, " name"])+    | valid n = Right ()+    | otherwise = Left (Text.concat ["invalid ", what, " name: ", n])+++-- | Whether a change ID: exactly 40 lowercase hex digits.+isChangeId :: Text -> Bool+isChangeId t = Text.length t == 40 && Text.all isLowerHex t+++isLowerHex :: Char -> Bool+isLowerHex c = isDigit c || (c >= 'a' && c <= 'f')+++-- | Whether a name may be declared as a change: a 'validName' that is not+-- one of sqitch's reserved @HEAD@ and @ROOT@ and does not start with 40 hex+-- digits, which would read as a change ID.+validChangeName :: Text -> Bool+validChangeName n =+    validName n+        && n `notElem` ["HEAD", "ROOT"]+        && not (Text.length n >= 40 && Text.all isLowerHex (Text.take 40 n))+++-- | Whether a name may be declared as a tag: a 'validChangeName' without a+-- @/@.+validTagName :: Text -> Bool+validTagName n = validChangeName n && not (Text.elem '/' n)+++-- | Whether a name matches sqitch's name pattern. Dependencies may use+-- any such name, @HEAD@ and @ROOT@ included.+validName :: Text -> Bool+validName n = case (Text.uncons n, Text.unsnoc n) of+    (Just (first, _), Just (_, final)) ->+        not (isPunct first)+            && not (isPunct final)+            && isWordChar final+            && not (Text.any (\c -> isBlank c || c `elem` (":@#\\" :: String)) n)+            && not symbolicSuffix+    _ -> False+  where+    -- sqitch's pattern ends in @\\b@, read with Unicode semantics: the+    -- last character must be a Perl word character.+    isWordChar c = isAlphaNum c || isMark c || generalCategory c == ConnectorPunctuation+    isPunct c = c `elem` ("-!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~" :: String)+    symbolicSuffix =+        let digits = Text.takeWhileEnd isDigit n+            before = Text.dropEnd (Text.length digits) n+         in not (Text.null digits) && maybe False ((`elem` ("~/=%^[]" :: String)) . snd) (Text.unsnoc before)
+ src/Sqitch/Plan/Render.hs view
@@ -0,0 +1,101 @@+-- | Writing a plan back out. For any plan 'Sqitch.Plan.Parse.parsePlan'+-- accepts, @render <$> parsePlan src == Right src@.+module Sqitch.Plan.Render (+    render,+    renderItem,+    renderPragma,+    renderChange,+    renderTag,+    renderDependency,+) where++import Data.Text (Text)+import Data.Text qualified as Text+import Data.Time (UTCTime)+import Sqitch.Plan.Types+import Prelude+++render :: Plan -> Text+render p =+    Text.intercalate "\n" (map (renderItem . (.value)) p.entries)+        <> (if p.finalNewline then "\n" else "")+++-- | One line, without its newline.+renderItem :: Item -> Text+renderItem = \case+    Blank t -> t+    CommentItem c -> c.indent <> "#" <> c.text+    PragmaItem p -> renderPragma p+    ChangeItem c -> renderChange c+    TagItem t -> renderTag t+++renderPragma :: Pragma -> Text+renderPragma p =+    let l = p.layout+        value = maybe "" (\v -> l.beforeEquals <> "=" <> l.afterEquals <> v) p.value+     in l.leading <> "%" <> l.afterPercent <> p.name <> value <> ending p.note l.trailing+++renderChange :: Change -> Text+renderChange c =+    let l = c.layout+        operator = case c.operator of+            Nothing -> ""+            Just Deploy -> "+" <> l.afterOperator+            Just Revert -> "-" <> l.afterOperator+        deps = map renderDependency c.dependencies+        -- Sqitch rejects an empty @[]@, so a change without dependencies+        -- gets no brackets, whatever its layout says, and at least one+        -- space before its timestamp.+        dependencies = case l.dependencyLayout of+            _ | null deps -> if Text.null l.afterName then " " else l.afterName+            Nothing -> Text.concat [l.afterName, "[", Text.unwords deps, "] "]+            Just dl+                | length dl.gaps == length deps + 1 -> Text.concat [l.afterName, "[", interleave dl.gaps deps, "]", dl.afterBracket]+                | otherwise -> Text.concat [l.afterName, "[", Text.unwords deps, "]", dl.afterBracket]+     in l.leading <> operator <> c.name <> dependencies <> stampAndPlanner c.timestamp c.planner c.note l+++renderTag :: Tag -> Text+renderTag t =+    let l = t.layout+     in l.leading <> "@" <> t.name <> l.afterName <> stampAndPlanner t.timestamp t.planner t.note l+++-- | A dependency as it appears between the brackets. One whose names+-- contain @]@ renders, but no plan reader can parse it back: see+-- 'DependencyTarget'.+renderDependency :: Dependency -> Text+renderDependency d =+    (case d.kind of Conflicts -> "!"; Requires -> "")+        <> maybe "" (<> ":") d.project+        <> case d.target of+            OnChange c t -> c <> maybe "" ("@" <>) t+            OnTag t -> "@" <> t+            OnId i -> i+++stampAndPlanner :: UTCTime -> Planner -> Maybe Note -> EntryLayout -> Text+stampAndPlanner timestamp planner note l =+    formatTimestamp timestamp+        <> l.afterTimestamp+        <> planner.name+        <> l.beforeEmail+        <> "<"+        <> planner.email+        <> ">"+        <> ending note l.trailing+++ending :: Maybe Note -> Text -> Text+ending note trailing = maybe trailing (\n -> n.gap <> "#" <> n.afterHash <> n.text) note+++-- | @interleave [g0, g1, g2] [a, b] == g0 <> a <> g1 <> b <> g2@.+interleave :: [Text] -> [Text] -> Text+interleave (g : gs) (x : xs) = g <> x <> interleave gs xs+interleave gs [] = mconcat gs+interleave [] xs = Text.unwords xs
+ src/Sqitch/Plan/Types.hs view
@@ -0,0 +1,284 @@+-- | The shape of a @sqitch.plan@ file.+--+-- A plan is a sequence of lines. Each one is a pragma (@%name=value@), a+-- change, a tag (@\@name …@), a comment (@# …@) or blank. Every value+-- here keeps the whitespace it was written with in a @layout@ field, so+-- that "Sqitch.Plan.Render" can write a parsed plan back byte for byte.+-- A value built by hand can use the @default…Layout@ values, which+-- render the way @sqitch add@ and @sqitch tag@ write.+module Sqitch.Plan.Types (+    -- * Plans+    Plan (..),+    Located (..),+    Item (..),++    -- * Pragmas+    Pragma (..),+    PragmaLayout (..),++    -- * Changes and tags+    Change (..),+    Tag (..),+    Operator (..),+    Planner (..),+    Note (..),+    defaultNote,+    noteText,+    escapeNote,+    unescapeNote,+    EntryLayout (..),+    defaultEntryLayout,++    -- * Dependencies+    Dependency (..),+    DependencyTarget (..),+    DependencyKind (..),+    DependencyLayout (..),++    -- * Comments+    Comment (..),++    -- * Timestamps+    formatTimestamp,+) where++import Data.Text (Text)+import Data.Text qualified as Text+import Data.Time (UTCTime, defaultTimeLocale, formatTime)+import Prelude+++-- | A parsed plan: every line, in order.+data Plan = Plan+    { entries :: [Located Item]+    -- ^ One per line of the source, blank lines and comments included.+    , finalNewline :: Bool+    -- ^ Whether the source ended with a newline.+    }+    deriving stock (Eq, Show)+++-- | A value and the 1-based line it was read from.+data Located a = Located+    { line :: Int+    , value :: a+    }+    deriving stock (Eq, Show, Functor, Foldable, Traversable)+++-- | What a single line holds.+data Item+    = -- | A line of nothing but whitespace; the whitespace is kept.+      Blank Text+    | CommentItem Comment+    | PragmaItem Pragma+    | ChangeItem Change+    | TagItem Tag+    deriving stock (Eq, Show)+++-- | A line whose first non-blank character is @#@.+data Comment = Comment+    { indent :: Text+    -- ^ Whitespace before the @#@.+    , text :: Text+    -- ^ Everything after the @#@, as written.+    }+    deriving stock (Eq, Show)+++-- | A @%name=value@ line. Sqitch reads @syntax-version@, @project@ and+-- @uri@; it keeps any other.+data Pragma = Pragma+    { name :: Text+    , value :: Maybe Text+    -- ^ 'Nothing' when the line has no @=@ at all.+    , note :: Maybe Note+    , layout :: PragmaLayout+    }+    deriving stock (Eq, Show)+++data PragmaLayout = PragmaLayout+    { leading :: Text+    -- ^ Before the @%@.+    , afterPercent :: Text+    , beforeEquals :: Text+    , afterEquals :: Text+    , trailing :: Text+    -- ^ After the value, when there is no note.+    }+    deriving stock (Eq, Show)+++-- | A change line:+--+-- > [+|-]name [dependencies] 2026-01-01T00:00:00Z Planner Name <planner@example.com> # note+data Change = Change+    { operator :: Maybe Operator+    -- ^ Sqitch's legacy @+@ / @-@ prefix. Absent in every modern plan.+    , name :: Text+    , dependencies :: [Dependency]+    , timestamp :: UTCTime+    -- ^ When the change was planned, at whole-second precision.+    , planner :: Planner+    , note :: Maybe Note+    , layout :: EntryLayout+    }+    deriving stock (Eq, Show)+++-- | A tag line, which marks every change above it:+--+-- > @name 2026-01-01T00:00:00Z Planner Name <planner@example.com> # note+data Tag = Tag+    { name :: Text+    -- ^ Without the leading @\@@.+    , timestamp :: UTCTime+    , planner :: Planner+    , note :: Maybe Note+    , layout :: EntryLayout+    }+    deriving stock (Eq, Show)+++data Operator = Deploy | Revert+    deriving stock (Eq, Show)+++data Planner = Planner+    { name :: Text+    , email :: Text+    }+    deriving stock (Eq, Show)+++-- | The @# …@ that ends a pragma, change or tag line.+data Note = Note+    { gap :: Text+    -- ^ Whitespace before the @#@.+    , afterHash :: Text+    -- ^ Whitespace after the @#@.+    , text :: Text+    -- ^ The note itself, up to the end of the line, as written: newlines,+    -- carriage returns and backslashes escaped as @\\n@, @\\r@ and @\\\\@.+    -- 'noteText' gives the text they stand for.+    }+    deriving stock (Eq, Show)+++-- | A note as @sqitch add -n@ writes it: @ # text@, trimmed, with newlines,+-- carriage returns and backslashes escaped so it stays on one line.+defaultNote :: Text -> Note+defaultNote t = Note{gap = " ", afterHash = " ", text = escapeNote (Text.strip t)}+++-- | A note's text: trimmed, with its escapes undone.+noteText :: Note -> Text+noteText n = unescapeNote (Text.strip n.text)+++-- | Escape a note for a plan line the way sqitch's @format_note@ does:+-- newline as @\\n@, carriage return as @\\r@, backslash as @\\\\@.+escapeNote :: Text -> Text+escapeNote = Text.concatMap \case+    '\n' -> "\\n"+    '\r' -> "\\r"+    '\\' -> "\\\\"+    c -> Text.singleton c+++-- | Undo 'escapeNote'. Like sqitch, a backslash before anything other+-- than @n@, @r@ or another backslash is kept as is.+unescapeNote :: Text -> Text+unescapeNote t = case Text.breakOn "\\" t of+    (before, rest) -> case Text.unpack (Text.take 2 rest) of+        ['\\', 'n'] -> before <> "\n" <> unescapeNote (Text.drop 2 rest)+        ['\\', 'r'] -> before <> "\r" <> unescapeNote (Text.drop 2 rest)+        ['\\', '\\'] -> before <> "\\" <> unescapeNote (Text.drop 2 rest)+        "" -> before+        _ -> before <> Text.take 1 rest <> unescapeNote (Text.drop 1 rest)+++-- | The whitespace around the fields of a change or tag line.+data EntryLayout = EntryLayout+    { leading :: Text+    -- ^ Before the operator or name.+    , afterOperator :: Text+    , afterName :: Text+    , dependencyLayout :: Maybe DependencyLayout+    -- ^ 'Nothing' for a line without brackets. A change with+    -- dependencies but no layout gets the canonical one.+    , afterTimestamp :: Text+    , beforeEmail :: Text+    , trailing :: Text+    -- ^ After the @>@, when there is no note.+    }+    deriving stock (Eq, Show)+++defaultEntryLayout :: EntryLayout+defaultEntryLayout =+    EntryLayout+        { leading = ""+        , afterOperator = ""+        , afterName = " "+        , dependencyLayout = Nothing+        , afterTimestamp = " "+        , beforeEmail = " "+        , trailing = ""+        }+++-- | The whitespace inside and after a @[…]@ dependency list.+data DependencyLayout = DependencyLayout+    { gaps :: [Text]+    -- ^ One more than there are dependencies: before the first, between+    -- each pair, after the last. If the count does not match (the+    -- dependencies were edited) the renderer uses single spaces.+    , afterBracket :: Text+    }+    deriving stock (Eq, Show)+++-- | One entry of a change's @[…]@ list:+--+-- > [!][project:](change[@tag] | @tag | change-id)+--+-- A change that names itself at a tag (@foo [foo\@v1]@) is a rework: see+-- 'Sqitch.Plan.reworkTag'.+data Dependency = Dependency+    { kind :: DependencyKind+    , project :: Maybe Text+    , target :: DependencyTarget+    }+    deriving stock (Eq, Ord, Show)+++-- | What a dependency points at.+--+-- A name here may contain @[@ but not @]@: sqitch reads a dependency list+-- as @[^]]+@ between the brackets, so a plan line naming @foo[bar]baz@ as+-- a dependency cannot be read back, by sqitch or by this package, even+-- though @foo[bar]baz@ is a valid change name.+data DependencyTarget+    = -- | A change by name, optionally as of a tag: @foo@, @foo\@v1@.+      OnChange Text (Maybe Text)+    | -- | Whatever change a tag marks: @\@v1@.+      OnTag Text+    | -- | A change by its ID, 40 lowercase hex digits (a SHA-1).+      OnId Text+    deriving stock (Eq, Ord, Show)+++data DependencyKind+    = -- | The change must be deployed first.+      Requires+    | -- | Written @!name@: the change must not be deployed.+      Conflicts+    deriving stock (Eq, Ord, Show)+++-- | A planned time as a plan writes it: @2026-01-01T00:00:00Z@.+formatTimestamp :: UTCTime -> Text+formatTimestamp = Text.pack . formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ"
+ test/Main.hs view
@@ -0,0 +1,496 @@+module Main (main) where++import Control.Exception (SomeException, try)+import Data.Either (isLeft)+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.IO qualified as Text.IO+import Data.Time (UTCTime (..), fromGregorian)+import Properties (properties)+import Sqitch.Plan+import System.Process (readProcess)+import Test.Tasty+import Test.Tasty.HUnit+import Prelude+++main :: IO ()+main = do+    found <- gitPlans+    defaultMain $+        testGroup+            "sqitch-plan"+            [ roundTrips+            , fixtureTests+            , realWorld found+            , pragmaTests+            , changeTests+            , tagTests+            , reworkTests+            , queryTests+            , errorTests+            , buildingTests+            , changeIdTests+            , declarationTests+            , noteEscapeTests+            , emptyDependencyTests+            , grammarEdgeTests+            , properties+            ]+++-- | A synthetic plan with every construct the parser knows. Its changes+-- and tags, one @line name@ per entry, are written out by hand next to it.+shopPlan :: FilePath+shopPlan = "test/fixtures/shop.plan"+++-- | Every plan file in the git checkout the tests run in, if any:+-- whatever real plans sit next to the package. Outside a checkout (an+-- sdist build, say) there are none and the group is empty.+gitPlans :: IO [FilePath]+gitPlans = do+    top <- try (readProcess "git" ["rev-parse", "--show-toplevel"] "")+    case top of+        Left (_ :: SomeException) -> pure []+        Right out -> do+            let root = Text.unpack (Text.strip (Text.pack out))+            files <- try (readProcess "git" ["-C", root, "ls-files", "*sqitch*.plan"] "")+            pure case files of+                Left (_ :: SomeException) -> []+                Right ls -> [root <> "/" <> l | l <- lines ls, not (null l)]+++parseOk :: Text -> IO Plan+parseOk src = either (assertFailure . Text.unpack . renderParseError) pure (parsePlan src)+++roundTrips :: TestTree+roundTrips =+    testGroup "render . parse == id" $+        [ testCase shopPlan do+            src <- Text.IO.readFile shopPlan+            plan <- parseOk src+            render plan @?= src+        ]+            <> [ testCase (show src) (parseOk src >>= \p -> render p @?= src)+               | src <-+                    [ ""+                    , "\n"+                    , "\n\n"+                    , "%project=x"+                    , "  \t\n# comment\n  #indented comment\n"+                    , "% name = value   \n"+                    , "%flag # note\n"+                    , "foo 2026-01-01T00:00:00Z Ada <ada@example.com>"+                    , "foo  2026-01-01T00:00:00Z   Ada Lovelace  <ada@example.com>  #  note  \n"+                    , "foo 2026-01-01T00:00:00Z Ada <ada@example.com>#tight\n"+                    , "foo 2026-01-01T00:00:00Z Ada <ada@example.com>   \n"+                    , "  foo[ bar  baz ]2026-01-01T00:00:00Z Ada <ada@example.com>\n"+                    , "+ foo 2026-01-01T00:00:00Z Ada <ada@example.com>\n"+                    , "  @v1.0  2026-01-01T00:00:00Z Ada <ada@example.com> # a # b\n"+                    , "foo 2026-01-01T00:00:00Z Ada <ada@example.com>\r\n"+                    ]+               ]+++pragmaTests :: TestTree+pragmaTests =+    testGroup+        "pragmas"+        [ testCase "the three sqitch reads, and any other" do+            plan <- parseOk "%syntax-version=1.0.0\n%project=flipr\n%uri=https://github.com/sqitchers/sqitch-intro/\n%custom=yes\n"+            syntaxVersion plan @?= Just "1.0.0"+            projectName plan @?= Just "flipr"+            uri plan @?= Just "https://github.com/sqitchers/sqitch-intro/"+            pragmaValue "custom" plan @?= Just "yes"+            map (.line) (pragmas plan) @?= [1, 2, 3, 4]+        , testCase "spaces around = are not part of name or value" do+            plan <- parseOk "  %  project =  flipr  # the project\n"+            projectName plan @?= Just "flipr"+            map (fmap noteText . (.value.note)) (pragmas plan) @?= [Just "the project"]+        , testCase "a pragma without = has no value" do+            plan <- parseOk "%flag\n"+            map (.value.value) (pragmas plan) @?= [Nothing]+        , testCase "a pragma without = counts as 1, and a later one wins" do+            plan <- parseOk "%custom=old\n%custom\n%other\n"+            pragmaValue "custom" plan @?= Just "1"+            pragmaValue "other" plan @?= Just "1"+            pragmaValue "missing" plan @?= Nothing+            render plan @?= "%custom=old\n%custom\n%other\n"+        , testCase "the last of a repeated pragma wins" do+            plan <- parseOk "%project=a\n%project=b\n"+            projectName plan @?= Just "b"+        ]+++at :: Integer -> Int -> Int -> UTCTime+at y m d = UTCTime (fromGregorian y m d) 0+++changeTests :: TestTree+changeTests =+    testGroup+        "changes"+        [ testCase "every field" do+            plan <- parseOk "users [roles !legacy other:widgets @v1.0 flips@v1.1 !proj:x@y] 2013-12-30T00:00:00Z Marge N. O'Vera <marge@example.com> # Creates table to track our users.\n"+            [Located{line = 1, value = c}] <- pure (changes plan)+            c.operator @?= Nothing+            c.name @?= "users"+            c.timestamp @?= at 2013 12 30+            c.planner @?= Planner{name = "Marge N. O'Vera", email = "marge@example.com"}+            fmap noteText c.note @?= Just "Creates table to track our users."+            c.dependencies+                @?= [ Dependency{kind = Requires, project = Nothing, target = OnChange "roles" Nothing}+                    , Dependency{kind = Conflicts, project = Nothing, target = OnChange "legacy" Nothing}+                    , Dependency{kind = Requires, project = Just "other", target = OnChange "widgets" Nothing}+                    , Dependency{kind = Requires, project = Nothing, target = OnTag "v1.0"}+                    , Dependency{kind = Requires, project = Nothing, target = OnChange "flips" (Just "v1.1")}+                    , Dependency{kind = Conflicts, project = Just "proj", target = OnChange "x" (Just "y")}+                    ]+        , testCase "no note, no dependencies" do+            plan <- parseOk "appschema 2013-12-30T00:00:00Z Ada <ada@example.com>\n"+            map (\c -> (c.value.name, c.value.dependencies, c.value.note)) (changes plan) @?= [("appschema", [], Nothing)]+        , testCase "a # inside the note is part of it" do+            plan <- parseOk "foo 2026-01-01T00:00:00Z Ada <ada@example.com> # fixes #3217\n"+            map (fmap noteText . (.value.note)) (changes plan) @?= [Just "fixes #3217"]+        , testCase "a planner name may have spaces and non-ASCII letters" do+            plan <- parseOk "foo 2026-01-01T00:00:00Z María José Ñúñez <maria@example.com>\n"+            map (.value.planner.name) (changes plan) @?= ["María José Ñúñez"]+        , testCase "legacy + and - operators" do+            plan <- parseOk "+foo 2026-01-01T00:00:00Z Ada <ada@example.com>\n- bar 2026-01-01T00:00:00Z Ada <ada@example.com>\n"+            map (\c -> (c.value.operator, c.value.name)) (changes plan) @?= [(Just Deploy, "foo"), (Just Revert, "bar")]+        , testCase "blank and comment lines are kept but are not changes" do+            plan <- parseOk "# header\n\nfoo 2026-01-01T00:00:00Z Ada <ada@example.com>\n  # between\nbar 2026-01-01T00:00:00Z Ada <ada@example.com>\n"+            map (\c -> (c.line, c.value.name)) (changes plan) @?= [(3, "foo"), (5, "bar")]+            map (kindOf . (.value)) plan.entries+                @?= [ "comment  header"+                    , "blank "+                    , "change foo"+                    , "comment    between"+                    , "change bar"+                    ]+            map (.line) plan.entries @?= [1, 2, 3, 4, 5]+        ]+  where+    kindOf :: Item -> Text+    kindOf = \case+        Blank t -> "blank " <> t+        CommentItem c -> "comment " <> c.indent <> c.text+        PragmaItem p -> "pragma " <> p.name+        ChangeItem c -> "change " <> c.name+        TagItem t -> "tag " <> t.name+++tagTests :: TestTree+tagTests =+    testGroup+        "tags"+        [ testCase "a tag line" do+            plan <- parseOk "foo 2026-01-01T00:00:00Z Ada <ada@example.com>\n@v1.0 2026-01-02T00:00:00Z Ada <ada@example.com> # Tag v1.0.\n"+            [Located{line = 2, value = t}] <- pure (tags plan)+            t.name @?= "v1.0"+            t.timestamp @?= at 2026 1 2+            fmap noteText t.note @?= Just "Tag v1.0."+        , testCase "steps interleave changes and tags in plan order" do+            plan <- parseOk "a 2026-01-01T00:00:00Z Ada <a@x>\n@t1 2026-01-01T00:00:00Z Ada <a@x>\nb 2026-01-01T00:00:00Z Ada <a@x>\n"+            map (\s -> (s.line, stepName s.value)) (steps plan) @?= [(1, "a"), (2, "@t1"), (3, "b")]+        ]+  where+    stepName (StepChange c) = c.name+    stepName (StepTag t) = "@" <> t.name+++reworkPlan :: Text+reworkPlan =+    Text.unlines+        [ "%syntax-version=1.0.0"+        , "%project=r"+        , ""+        , "foo 2026-01-01T00:00:00Z Ada <a@x>"+        , "bar [foo] 2026-01-01T00:00:00Z Ada <a@x>"+        , "@v1 2026-01-02T00:00:00Z Ada <a@x>"+        , "foo [foo@v1] 2026-01-03T00:00:00Z Ada <a@x> # rework foo"+        , "baz [bar@v1] 2026-01-03T00:00:00Z Ada <a@x>"+        , "@v2 2026-01-04T00:00:00Z Ada <a@x>"+        , "foo [foo@v2 bar] 2026-01-05T00:00:00Z Ada <a@x>"+        , "qux 2026-01-05T00:00:00Z Ada <a@x>"+        ]+++reworkTests :: TestTree+reworkTests =+    testGroup+        "reworks"+        [ testCase "which changes are reworked" do+            plan <- parseOk reworkPlan+            isReworked "foo" plan @?= True+            isReworked "bar" plan @?= False+            isReworked "nope" plan @?= False+        , testCase "the tag a rework names its earlier self at" do+            plan <- parseOk reworkPlan+            map (\c -> (c.line, reworkTag c.value)) (changes plan)+                @?= [(4, Nothing), (5, Nothing), (7, Just "v1"), (8, Nothing), (10, Just "v2"), (11, Nothing)]+        , testCase "each later occurrence and the one before it" do+            plan <- parseOk reworkPlan+            map (\r -> (r.change.line, r.previous.line, r.tag)) (reworks plan) @?= [(7, 4, Just "v1"), (10, 7, Just "v2")]+        , testCase "occurrences" do+            plan <- parseOk reworkPlan+            map (.line) (occurrences "foo" plan) @?= [4, 7, 10]+            fmap (.line) (lastOccurrence "foo" plan) @?= Just 10+        ]+++queryTests :: TestTree+queryTests =+    testGroup+        "queries"+        [ testCase "changes after a change follow its last occurrence" do+            plan <- parseOk reworkPlan+            fmap (map (.value.name)) (changesAfter "bar" plan) @?= Just ["foo", "baz", "foo", "qux"]+            fmap (map (.value.name)) (changesAfter "foo" plan) @?= Just ["qux"]+            fmap (map (.value.name)) (changesAfter "qux" plan) @?= Just []+            fmap (map (.value.name)) (changesAfter "nope" plan) @?= Nothing+        , testCase "a change is tagged when a tag follows its last occurrence" do+            plan <- parseOk reworkPlan+            isTagged "bar" plan @?= True+            isTagged "baz" plan @?= True+            isTagged "foo" plan @?= False+            isTagged "qux" plan @?= False+            map (.value.name) (tagsAfterLine 5 plan) @?= ["v1", "v2"]+        ]+++errorTests :: TestTree+errorTests =+    testGroup+        "errors"+        [ testCase "reports the line" do+            fmap (.line) (either Just (const Nothing) (parsePlan "%project=x\n\nfoo 2026-01-01T00:00:00Z Ada\n")) @?= Just 3+        , rejects "no email" "foo 2026-01-01T00:00:00Z Ada\n"+        , rejects "unclosed email" "foo 2026-01-01T00:00:00Z Ada <ada@example.com\n"+        , rejects "text after the email" "foo 2026-01-01T00:00:00Z Ada <a@x> extra\n"+        , rejects "no planner" "foo 2026-01-01T00:00:00Z <a@x>\n"+        , rejects "no timestamp" "foo Ada <a@x>\n"+        , rejects "fractional seconds" "foo 2026-01-01T00:00:00.5Z Ada <a@x>\n"+        , rejects "unpadded month" "foo 2026-1-01T00:00:00Z Ada <a@x>\n"+        , rejects "a tag with dependencies" "@v1 [foo] 2026-01-01T00:00:00Z Ada <a@x>\n"+        , rejects "unclosed dependency list" "foo [bar 2026-01-01T00:00:00Z Ada <a@x>\n"+        , rejects "an empty dependency" "foo [!] 2026-01-01T00:00:00Z Ada <a@x>\n"+        , rejects "an empty project" "foo [:bar] 2026-01-01T00:00:00Z Ada <a@x>\n"+        , rejects "a pragma without a name" "%=x\n"+        , testCase "names" do+            map (\n -> (n, validName n)) ["foo", "foo/bar", "2022-08-26-x", "a_", "_a", "v1.0", "foo-1.0", "x^y"]+                @?= map (,True) ["foo", "foo/bar", "2022-08-26-x", "a_", "_a", "v1.0", "foo-1.0", "x^y"]+            map (\n -> (n, validName n)) ["", "-foo", "foo-", "foo.", "a:b", "a@b", "a#b", "a\\b", "a b", "foo^2", "foo~12", "foo/3", "x=1", "y%2"]+                @?= map (,False) ["", "-foo", "foo-", "foo.", "a:b", "a@b", "a#b", "a\\b", "a b", "foo^2", "foo~12", "foo/3", "x=1", "y%2"]+        ]+  where+    rejects what src = testCase what (assertBool ("parsed: " <> show src) (isLeft (parsePlan src)))+++buildingTests :: TestTree+buildingTests =+    testGroup+        "building"+        [ testCase "a new change renders like sqitch add" do+            let c =+                    newChange+                        "foo"+                        [Dependency{kind = Requires, project = Nothing, target = OnChange "foo" (Just "v1")}, Dependency{kind = Conflicts, project = Nothing, target = OnChange "bar" Nothing}]+                        (at 2026 1 1)+                        Planner{name = "Ada Lovelace", email = "ada@example.com"}+                        (Just "hello")+            renderItem (ChangeItem c) @?= "foo [foo@v1 !bar] 2026-01-01T00:00:00Z Ada Lovelace <ada@example.com> # hello"+            renderItem (ChangeItem (newChange "foo" [] (at 2026 1 1) Planner{name = "Ada", email = "a@x"} Nothing))+                @?= "foo 2026-01-01T00:00:00Z Ada <a@x>"+        , testCase "a new tag renders like sqitch tag" do+            renderItem (TagItem (newTag "v1" (at 2026 1 1) Planner{name = "Ada", email = "a@x"} (Just "release")))+                @?= "@v1 2026-01-01T00:00:00Z Ada <a@x> # release"+        , testCase "appending numbers on and parses back" do+            plan <- parseOk "%project=x\n\nfoo 2026-01-01T00:00:00Z Ada <a@x>\n"+            let plan' = appendItems [TagItem (newTag "v1" (at 2026 1 2) Planner{name = "Ada", email = "a@x"} Nothing)] plan+            render plan' @?= "%project=x\n\nfoo 2026-01-01T00:00:00Z Ada <a@x>\n@v1 2026-01-02T00:00:00Z Ada <a@x>\n"+            map (.line) (tags plan') @?= [4]+            reparsed <- parseOk (render plan')+            reparsed @?= plan'+        ]+++realWorld :: [FilePath] -> TestTree+realWorld paths =+    testGroup+        "render . parse == id, for the plans in this git checkout"+        [ testCase path (Text.IO.readFile path >>= \src -> parseOk src >>= \p -> render p @?= src)+        | path <- paths+        ]+++fixtureTests :: TestTree+fixtureTests =+    testGroup+        "shop.plan"+        [ testCase "changes, in order with their lines" do+            plan <- parseOk =<< Text.IO.readFile shopPlan+            expected <- Text.lines <$> Text.IO.readFile "test/fixtures/shop.changes"+            [Text.pack (show c.line) <> " " <> c.value.name | c <- changes plan] @?= expected+        , testCase "tags, in order with their lines" do+            plan <- parseOk =<< Text.IO.readFile shopPlan+            expected <- Text.lines <$> Text.IO.readFile "test/fixtures/shop.tags"+            [Text.pack (show t.line) <> " " <> t.value.name | t <- tags plan] @?= expected+        , testCase "pragmas" do+            plan <- parseOk =<< Text.IO.readFile shopPlan+            [(p.line, p.value.name, p.value.value) | p <- pragmas plan]+                @?= [ (1, "syntax-version", Just "1.0.0")+                    , (2, "project", Just "shop")+                    , (3, "uri", Just "https://example.com/shop/")+                    , (4, "custom-pragma", Just "some value")+                    , (5, "flag", Nothing)+                    ]+        , testCase "reworks, including one with further dependencies" do+            plan <- parseOk =<< Text.IO.readFile shopPlan+            [(r.change.line, r.previous.line, r.tag) | r <- reworks plan]+                @?= [(18, 12, Just "v1.0"), (24, 11, Just "v1.1"), (28, 18, Just "v1.1")]+            map renderDependency (concatMap (.value.dependencies) (drop 1 (occurrences "orders" plan)))+                @?= ["orders@v1.0", "pricing", "orders@v1.1", "invoices"]+        , testCase "cross-project and tag dependencies" do+            plan <- parseOk =<< Text.IO.readFile shopPlan+            map (\c -> map renderDependency c.value.dependencies) (filter (\c -> c.value.name `elem` ["audit", "pricing", "order_lines"]) (changes plan))+                @?= [ ["orders", "!legacy_lines"]+                    , ["payments:ledger", "payments:ledger@v2.0", "!payments:old_ledger"]+                    , ["@v1.0", "widgets@v1.0"]+                    ]+        , testCase "notes and planners" do+            plan <- parseOk =<< Text.IO.readFile shopPlan+            [(c.line, fmap noteText c.value.note) | c <- changes plan, c.line `elem` [12, 19, 21, 28]]+                @?= [ (12, Just "orders, see issue #12")+                    , (19, Just "odd spacing")+                    , (21, Just "no space before the hash")+                    , (28, Just "second rework, notes may hold # and ## too")+                    ]+            [c.value.planner | c <- changes plan, c.line == 14]+                @?= [Planner{name = "Jos\233 \209\250\241ez \216rsted", email = "jose@example.com"}]+        , testCase "legacy operators" do+            plan <- parseOk =<< Text.IO.readFile shopPlan+            [(c.value.name, op) | c <- changes plan, Just op <- [c.value.operator]]+                @?= [("invoices", Deploy), ("legacy_lines", Revert)]+        ]+++hexId :: Text+hexId = "0123456789abcdef0123456789abcdef01234567"+++changeIdTests :: TestTree+changeIdTests =+    testGroup+        "change IDs"+        [ testCase "40 lowercase hex digits are an ID, bare or project-qualified" do+            let src = "foo [" <> hexId <> " !other:" <> hexId <> " " <> Text.take 39 hexId <> " " <> Text.toUpper hexId <> "] 2026-01-01T00:00:00Z Ada <a@x>\n"+            plan <- parseOk src+            map (\c -> c.value.dependencies) (changes plan)+                @?= [+                        [ Dependency{kind = Requires, project = Nothing, target = OnId hexId}+                        , Dependency{kind = Conflicts, project = Just "other", target = OnId hexId}+                        , Dependency{kind = Requires, project = Nothing, target = OnChange (Text.take 39 hexId) Nothing}+                        , Dependency{kind = Requires, project = Nothing, target = OnChange (Text.toUpper hexId) Nothing}+                        ]+                    ]+            render plan @?= src+        , testCase "renderDependency writes an ID back" do+            renderDependency Dependency{kind = Conflicts, project = Just "p", target = OnId hexId} @?= "!p:" <> hexId+        ]+++declarationTests :: TestTree+declarationTests =+    testGroup+        "declared names"+        [ rejects "a change named HEAD" "HEAD 2026-01-01T00:00:00Z Ada <a@x>\n"+        , rejects "a change named ROOT" "ROOT 2026-01-01T00:00:00Z Ada <a@x>\n"+        , rejects "a tag named HEAD" "@HEAD 2026-01-01T00:00:00Z Ada <a@x>\n"+        , rejects "a change that starts with 40 hex digits" ("" <> hexId <> "_x 2026-01-01T00:00:00Z Ada <a@x>\n")+        , rejects "a tag that is 40 hex digits" ("@" <> hexId <> " 2026-01-01T00:00:00Z Ada <a@x>\n")+        , rejects "a tag with a /" "@v1/x 2026-01-01T00:00:00Z Ada <a@x>\n"+        , testCase "a change name may have a /" do+            plan <- parseOk "app/foo 2026-01-01T00:00:00Z Ada <a@x>\n"+            map (.value.name) (changes plan) @?= ["app/foo"]+        , testCase "dependencies may name HEAD, ROOT and tags with a /" do+            plan <- parseOk "foo [bar@HEAD @ROOT HEAD baz@v1/x] 2026-01-01T00:00:00Z Ada <a@x>\n"+            map (map renderDependency . (.value.dependencies)) (changes plan) @?= [["bar@HEAD", "@ROOT", "HEAD", "baz@v1/x"]]+        , testCase "the predicates" do+            map validChangeName ["HEAD", "ROOT", hexId, hexId <> "x", "head", Text.take 39 hexId, "a/b"] @?= [False, False, False, False, True, True, True]+            map validTagName ["v1", "v1/x", "HEAD"] @?= [True, False, False]+            map isChangeId [hexId, Text.toUpper hexId, Text.take 39 hexId, hexId <> "0"] @?= [True, False, False, False]+        ]+  where+    rejects what src = testCase what (assertBool ("parsed: " <> show src) (isLeft (parsePlan src)))+++noteEscapeTests :: TestTree+noteEscapeTests =+    testGroup+        "note escapes"+        [ testCase "a new change's note is escaped like sqitch's format_note" do+            let c = newChange "foo" [] (at 2026 1 1) Planner{name = "Ada", email = "a@x"} (Just "line one\nline two\r\nC:\\path")+            renderItem (ChangeItem c) @?= "foo 2026-01-01T00:00:00Z Ada <a@x> # line one\\nline two\\r\\nC:\\\\path"+            fmap noteText c.note @?= Just "line one\nline two\r\nC:\\path"+        , testCase "a new tag's note too" do+            renderItem (TagItem (newTag "v1" (at 2026 1 1) Planner{name = "Ada", email = "a@x"} (Just "a\nb")))+                @?= "@v1 2026-01-01T00:00:00Z Ada <a@x> # a\\nb"+        , testCase "a parsed note keeps its raw form and unescapes on reading" do+            let src = "foo 2026-01-01T00:00:00Z Ada <a@x> # two\\nlines and a \\\\ and \\q\n"+            plan <- parseOk src+            render plan @?= src+            map (fmap (.text) . (.value.note)) (changes plan) @?= [Just "two\\nlines and a \\\\ and \\q"]+            map (fmap noteText . (.value.note)) (changes plan) @?= [Just "two\nlines and a \\ and \\q"]+        , testCase "escape and unescape are inverses" do+            let t = "a\\b\nc\rd\\\\n"+            unescapeNote (escapeNote t) @?= t+        ]+++emptyDependencyTests :: TestTree+emptyDependencyTests =+    testGroup+        "empty dependency lists"+        [ testCase "removing every dependency drops the brackets" do+            plan <- parseOk "foo [bar] 2026-01-01T00:00:00Z Ada <a@x>\ntight[bar]2026-01-01T00:00:00Z Ada <a@x>\n"+            map (renderItem . ChangeItem . (\c -> c.value{dependencies = []})) (changes plan)+                @?= ["foo 2026-01-01T00:00:00Z Ada <a@x>", "tight 2026-01-01T00:00:00Z Ada <a@x>"]+        , testCase "[] and [ ] do not parse" do+            assertBool "[]" (isLeft (parsePlan "foo [] 2026-01-01T00:00:00Z Ada <a@x>\n"))+            assertBool "[ ]" (isLeft (parsePlan "foo [ ] 2026-01-01T00:00:00Z Ada <a@x>\n"))+        ]+++grammarEdgeTests :: TestTree+grammarEdgeTests =+    testGroup+        "names and timestamps by sqitch's grammar"+        [ testCase "a change name may contain brackets" do+            let src = "foo[bar]baz 2026-01-01T00:00:00Z Ada <a@x>\nqux[a]b[dep] 2026-01-01T00:00:00Z Ada <a@x>\nplain[dep] 2026-01-01T00:00:00Z Ada <a@x>\n"+            plan <- parseOk src+            map (\c -> (c.value.name, map renderDependency c.value.dependencies)) (changes plan)+                @?= [("foo[bar]baz", []), ("qux[a]b", ["dep"]), ("plain", ["dep"])]+            render plan @?= src+        , testCase "a tag name may contain brackets" do+            let src = "foo 2026-01-01T00:00:00Z Ada <a@x>\n@v1[rc]x 2026-01-01T00:00:00Z Ada <a@x>\n"+            plan <- parseOk src+            map (.value.name) (tags plan) @?= ["v1[rc]x"]+            render plan @?= src+            assertBool "tag with dependencies" (isLeft (parsePlan "@v1[rc] 2026-01-01T00:00:00Z Ada <a@x>\n"))+        , testCase "no blank is needed after the timestamp" do+            let src = "foo 2026-01-01T00:00:00ZAda Lovelace <a@x>\n@v1 2026-01-02T00:00:00ZAda <a@x>\n"+            plan <- parseOk src+            map (\c -> (c.value.timestamp, c.value.planner.name)) (changes plan) @?= [(at 2026 1 1, "Ada Lovelace")]+            map (\t -> (t.value.timestamp, t.value.planner.name)) (tags plan) @?= [(at 2026 1 2, "Ada")]+            render plan @?= src+        , testCase "the planner's name and email need a blank between them" do+            assertBool "Ada<a@x>" (isLeft (parsePlan "foo 2026-01-01T00:00:00Z Ada<a@x>\n"))+        , testCase "a name must end in a word character" do+            map validChangeName ["foo\9829", "foo_", "caf\233", "x\8255"] @?= [False, True, True, True]+            validTagName "v1\9829" @?= False+            assertBool "change" (isLeft (parsePlan "foo\9829 2026-01-01T00:00:00Z Ada <a@x>\n"))+            assertBool "tag" (isLeft (parsePlan "@v1\9829 2026-01-01T00:00:00Z Ada <a@x>\n"))+        ]
+ test/Properties.hs view
@@ -0,0 +1,183 @@+-- | Generated round trips. Names come from sqitch's name grammar, with+-- brackets, punctuation in the middle and non-ASCII word characters, and+-- appear wherever a plan allows one.+module Properties (properties) where++import Data.Text (Text)+import Data.Text qualified as Text+import Data.Time (UTCTime (..), fromGregorian, secondsToDiffTime)+import Hedgehog+import Hedgehog.Gen qualified as Gen+import Hedgehog.Range qualified as Range+import Sqitch.Plan+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.Hedgehog (testPropertyNamed)+import Prelude+++properties :: TestTree+properties =+    testGroup+        "generated plans"+        [ testPropertyNamed "built entries render to text that parses back to them" "prop_buildParse" prop_buildParse+        , testPropertyNamed "render . parse == id on that text" "prop_renderParse" prop_renderParse+        , testPropertyNamed "a built note reads back as its trimmed text" "prop_note" prop_note+        ]+++prop_buildParse :: Property+prop_buildParse = withTests 500 $ property do+    items <- forAll genItems+    let src = render (appendItems items Plan{entries = [], finalNewline = False})+    annotate (Text.unpack src)+    parsed <- evalEither (parsePlan src)+    map (shape . (.value)) parsed.entries === map shape items+++prop_renderParse :: Property+prop_renderParse = withTests 500 $ property do+    items <- forAll genItems+    let src = render (appendItems items Plan{entries = [], finalNewline = False})+    parsed <- evalEither (parsePlan src)+    render parsed === src+++prop_note :: Property+prop_note = property do+    t <- forAll genNoteText+    noteText (defaultNote t) === Text.strip t+++-- | What an entry means, without its layout.+data Shape+    = SPragma Text (Maybe Text)+    | SChange (Maybe Operator) Text [Dependency] UTCTime Planner (Maybe Text)+    | STag Text UTCTime Planner (Maybe Text)+    | SOther+    deriving stock (Eq, Show)+++shape :: Item -> Shape+shape = \case+    PragmaItem p -> SPragma p.name p.value+    ChangeItem c -> SChange c.operator c.name c.dependencies c.timestamp c.planner (noteText <$> c.note)+    TagItem t -> STag t.name t.timestamp t.planner (noteText <$> t.note)+    _ -> SOther+++-- | A header, then changes, tags and reworks of earlier changes at an+-- earlier tag.+genItems :: Gen [Item]+genItems = do+    project <- genName+    n <- Gen.int (Range.linear 1 20)+    body <- go n [] []+    pure ([pragma "syntax-version" "1.0.0", pragma "project" project, Blank ""] <> body)+  where+    pragma name value =+        PragmaItem+            Pragma+                { name+                , value = Just value+                , note = Nothing+                , layout = PragmaLayout{leading = "", afterPercent = "", beforeEquals = "", afterEquals = "", trailing = ""}+                }+    go :: Int -> [Text] -> [Text] -> Gen [Item]+    go 0 _ _ = pure []+    go k changeNames tagNames = do+        -- A rework names its change and a tag in its dependency list,+        -- which cannot hold a ]: sqitch cannot rework a change, or at a+        -- tag, whose name has one.+        let noBracket = filter (not . Text.elem ']')+            rework = case (noBracket changeNames, noBracket tagNames) of+                (cs@(_ : _), ts@(_ : _)) -> [(2, genRework cs ts)]+                _ -> []+            tag = [(1, genTag) | not (null changeNames)]+        item <- Gen.frequency ([(4, genChange)] <> tag <> rework)+        let (changeNames', tagNames') = case item of+                ChangeItem c -> (c.name : changeNames, tagNames)+                TagItem t -> (changeNames, t.name : tagNames)+                _ -> (changeNames, tagNames)+        (item :) <$> go (k - 1) changeNames' tagNames'+++genChange :: Gen Item+genChange = do+    c <- newChange <$> genName <*> Gen.list (Range.linear 0 5) genDependency <*> genTime <*> genPlanner <*> Gen.maybe genNoteText+    operator <- Gen.frequency [(9, pure Nothing), (1, Just <$> Gen.element [Deploy, Revert])]+    pure (ChangeItem c{operator})+++genRework :: [Text] -> [Text] -> Gen Item+genRework changeNames tagNames = do+    name <- Gen.element changeNames+    tag <- Gen.element tagNames+    others <- Gen.list (Range.linear 0 3) genDependency+    let self = Dependency{kind = Requires, project = Nothing, target = OnChange name (Just tag)}+    ChangeItem <$> (newChange name (self : others) <$> genTime <*> genPlanner <*> Gen.maybe genNoteText)+++genTag :: Gen Item+genTag = TagItem <$> (newTag <$> Gen.filter validTagName genName <*> genTime <*> genPlanner <*> Gen.maybe genNoteText)+++genDependency :: Gen Dependency+genDependency = do+    kind <- Gen.element [Requires, Conflicts]+    project <- Gen.maybe genReference+    target <-+        Gen.choice+            [ OnChange <$> genReference <*> pure Nothing+            , OnChange <$> genReference <*> (Just <$> genReference)+            , OnTag <$> genReference+            , OnId <$> Gen.text (Range.singleton 40) (oneOf "0123456789abcdef")+            ]+    pure Dependency{kind, project, target}+++-- | A name a dependency may use: any valid name, the reserved ones+-- included, except that sqitch cannot read a @]@ inside a dependency+-- list, and a bare 40-digit hex string reads as a change ID.+genReference :: Gen Text+genReference =+    Gen.filter (\n -> not (Text.elem ']' n) && not (isChangeId n)) $+        Gen.frequency [(9, genName), (1, Gen.element ["HEAD", "ROOT"])]+++-- | A declarable change name from sqitch's grammar: no blanks or+-- @:\@#\\@, no ASCII punctuation first or last, a word character last.+genName :: Gen Text+genName = Gen.filter validChangeName do+    final <- Gen.element wordChars+    Gen.choice+        [ pure (Text.singleton final)+        , do+            first <- Gen.element (wordChars <> "♥€")+            middle <- Gen.list (Range.linear 0 10) (Gen.element middleChars)+            pure (Text.pack (first : middle <> [final]))+        ]+  where+    wordChars = ['a' .. 'z'] <> ['A' .. 'Z'] <> ['0' .. '9'] <> "_éßøΩж日"+    middleChars = wordChars <> "-!\"$%&'()*+,./;<=>?[]^`{|}~♥€\x301"+++genPlanner :: Gen Planner+genPlanner = do+    words' <- Gen.list (Range.linear 1 3) (Gen.text (Range.linear 1 8) (oneOf "abcdefXYZéñØ.'-"))+    user <- Gen.text (Range.linear 1 8) Gen.alphaNum+    pure Planner{name = Text.unwords words', email = user <> "@example.com"}+++genNoteText :: Gen Text+genNoteText = Gen.text (Range.linear 0 30) (oneOf "abc XYZ#\\\n\r\t[]@:%é♥")+++genTime :: Gen UTCTime+genTime = do+    day <- fromGregorian <$> Gen.integral (Range.linear 1970 2100) <*> Gen.int (Range.linear 1 12) <*> Gen.int (Range.linear 1 28)+    secs <- Gen.integral (Range.linear 0 86399)+    pure (UTCTime day (secondsToDiffTime secs))+++oneOf :: String -> Gen Char+oneOf = Gen.element
+ test/fixtures/shop.changes view
@@ -0,0 +1,16 @@+10 schema+11 widgets+12 orders+13 order_lines+14 audit+17 pricing+18 orders+19 discounts+20 refunds+21 shipping+22 returns+24 widgets+25 invoices+26 legacy_lines+28 orders+30 reports
+ test/fixtures/shop.plan view
@@ -0,0 +1,30 @@+%syntax-version=1.0.0+%project=shop+%uri=https://example.com/shop/+% custom-pragma = some value   # a pragma with a note+%flag++# A synthetic plan: every construct the parser knows, laid out unevenly.+  #   an indented comment+   	+schema 2026-01-01T09:00:00Z Ada Lovelace <ada@example.com> # create the shop schema+widgets [schema] 2026-01-01T09:05:00Z Ada Lovelace <ada@example.com> # widgets table+orders [schema widgets] 2026-01-01T09:10:00Z Grace Hopper <grace@example.com> # orders, see issue #12+order_lines [orders !legacy_lines] 2026-01-01T09:15:00Z Grace Hopper <grace@example.com>+audit [payments:ledger payments:ledger@v2.0 !payments:old_ledger] 2026-01-02T10:00:00Z José Ñúñez Ørsted <jose@example.com> # cross-project dependencies+@v1.0 2026-01-03T00:00:00Z Ada Lovelace <ada@example.com> # first release++pricing [@v1.0 widgets@v1.0] 2026-01-04T08:00:00Z Ada Lovelace <ada@example.com> # depends on a tag and on a change at a tag+orders [orders@v1.0 pricing] 2026-01-04T08:30:00Z Grace Hopper <grace@example.com> # rework orders; it now also needs pricing+discounts  [ pricing   orders ]  2026-01-04T09:00:00Z   José Ñúñez Ørsted  <jose@example.com>  #  odd spacing  +refunds 2026-01-04T09:30:00Z Ada Lovelace <ada@example.com>   +shipping 2026-01-04T10:00:00Z Ada Lovelace <ada@example.com>#no space before the hash+	returns	2026-01-04T10:30:00Z	Ada Lovelace <ada@example.com>	# tabs+@v1.1 2026-01-05T00:00:00Z Grace Hopper <grace@example.com>+widgets [widgets@v1.1] 2026-01-06T12:00:00Z Ada Lovelace <ada@example.com> # rework widgets++invoices 2026-01-06T12:30:00Z Ada Lovelace <ada@example.com> # legacy deploy operator+- legacy_lines 2026-01-06T13:00:00Z Ada Lovelace <ada@example.com> # legacy revert operator+# a comment between changes+orders [orders@v1.1 invoices] 2026-01-07T08:00:00Z José Ñúñez Ørsted <jose@example.com> # second rework, notes may hold # and ## too+@v2.0 2026-01-08T00:00:00Z Ada Lovelace <ada@example.com> # release #2+reports [orders widgets] 2026-01-09T08:00:00Z Grace Hopper <grace@example.com>
+ test/fixtures/shop.tags view
@@ -0,0 +1,3 @@+15 v1.0+23 v1.1+29 v2.0