packages feed

minici 0.1.9 → 0.1.10

raw patch · 16 files changed

+1593/−463 lines, 16 filesdep +megaparsecdep +timedep ~basedep ~containersdep ~template-haskell

Dependencies added: megaparsec, time

Dependency ranges changed: base, containers, template-haskell

Files

CHANGELOG.md view
@@ -1,12 +1,22 @@ # Revision history for MiniCI +## 0.1.10 -- 2026-11-28++* Added flexible expressions to select or watch commit ranges and tags.+* No longer relevant jobs (e.g. after not-fast-forward branch move) are automatically cancelled.+* Colon `:` is now accepted and preferred as job ID separator.+* Single file (blob) is supported as a subtree in repo checkout.+* Make sure to terminate processes started by task recipe after it finishes.+* Added job section to push commits to another repository.+* Support compilation with GHC 9.14.+ ## 0.1.9 -- 2025-12-29 -* Reuse job status and artifacts from previous runs-* Added `--rerun-*` command-line options to configure which jobs should be rerun-* Job section to publish artifacts to specified destination-* Accept literal text block for the `shell` section-* Prepare used artifacts for the `shell` command+* Job status and artifacts from previous runs are now reused.+* Added `--rerun-*` command-line options to configure which jobs should be rerun.+* Added job section to publish artifacts to specified destination.+* Literal text block is now accepted for the `shell` section.+* Used artifacts are now prepared for the `shell` command.  ## 0.1.8 -- 2025-07-06 
README.md view
@@ -62,18 +62,22 @@ minici run <commit>..<commit> ``` -or:-```-minici run --range=<commit>..<commit>-```+See [watch expressions](#watch-expressions) below for details of supported expressions. + To run jobs for commits that are in local `<branch>`, but not yet in its upstream: ``` minici run --since-upstream=<branch> ``` -For current branch, the name can be omitted:+or equivalently: ```+minici run '<branch>..upstream(<branch>)'+```++This is the default action the `run` command will perform without any+arguments, using the current branch as `<branch>` when executed as:+``` minici run ``` @@ -88,14 +92,60 @@ minici run --new-commits-on=<branch> ``` +or equivalently:+```+minici run '<branch>..watch(<branch>)'+```+ To watch new tags and run jobs for each tag matching given pattern: ``` minici run --new-tags=<pattern> ``` -The above options `--range`, `--since-upstream`, etc can be arbitrarily combined.+or equivalently:+```+minici run 'newtags(<pattern>)'+``` +The above expressions and options can be arbitrarily combined. ++Watch expressions+-----------------++The `run` command accepts `<range-expr>` to describe set of commits for which+to execute the jobs, potentially watching for changes in repository branches or+tags. The `<range-expr>` can be of the form:++* `<commit-expr>..<commit-expr>` giving range of commits;++* `<commit-expr>` giving single commit;++* `tags(<pattern>)` denoting list of all tags matching given `<pattern>`;++* `watch(<range-expr>)` is an expression initially equivalent to its parameter,+  but `minici` continues to watch the repository for changes affecting the+  expression and creates or cancels additional jobs as the value of the+  expression changes.++Where `<commit-expr>` can be:++* `<commit>`, e.g. the git commit hash;++* `highesttag(<pattern>)`, which from all the tags matching `<pattern>`, selects+  the highest one as given by natural/version sort (e.g. `v10.2` > `v9.4`);++* `lasttag(<pattern>)`, which from all the tags matching `<pattern>`, selects+  the last created one (as given by the `tagger` date in tag object);++* `upstream(<branch>)` refers to the upstream (remote) branch of the given `<branch>`;++* `watch(<commit-expr>)` is analogous to `watch` for `<range-expr>`.++And `<pattern>` is a shell glob pattern, as implemented+by the [Glob package](https://hackage.haskell.org/package/Glob/docs/System-FilePath-Glob.html#v:compile).++ Explicit script file -------------------- @@ -190,3 +240,43 @@  `path` : Path within the destination to publish this artifact to. If not given, artifact path from the work directory is used.+++Push commit to repo+-------------------++Another action that can be performed by a job is pushing a given commit to another repository.+The target repository must be declared at the top of the job file with the `writable` flag:++```+repo <name>:+  path: <path/to/repository>+  writable: true+```++The repository path can be given also on command line in the form `--writable-repo=<name>:<path>`.+The commits to push are then given in the `push` list within the job definition:++```+repo source_repo:++repo target_repo:+  writable: true++job push_job:+  push:+    - commit: source_repo.commit+      to: target_repo.branch("master")+```++Elements of the `push` list are dictionaries with following elements:++`commit`+: Commit to push, currently in the form `<repo>.commit`, denoting commit within `<repo>` used in the job.++`to`+: Destination branch, currently in the form `<repo>.branch("<branch name>")`.++If the target branch can be moved fast-forward to the source commit, the branch is moved and the job succeeds.+If the source commit is an ancestor of the tip of the target branch, the branch is not moved and the job also succeeds.+Otherwise, the target branch is not moved and the job fails.
minici.cabal view
@@ -1,6 +1,6 @@ cabal-version:      3.0 name:               minici-version:            0.1.9+version:            0.1.10 synopsis:           Minimalist CI framework to run checks on local machine description:     Runs defined jobs, for example to build and test a project, for each git@@ -23,11 +23,6 @@     README.md     CHANGELOG.md -flag ci-    description:    Options for CI testing-    default: False-    manual: True- source-repository head     type:       git     location:   https://code.erebosprotocol.net/minici@@ -40,12 +35,6 @@         -threaded         -fdefer-typed-holes -    if flag(ci)-        ghc-options:-            -Werror-            -- sometimes needed for backward/forward compatibility:-            -Wno-error=unused-imports-     other-modules:         Command         Command.Checkout@@ -58,11 +47,13 @@         Config         Destination         Eval+        Expr         FileUtils         Job         Job.Types         Output         Paths_minici+        Range         Repo         Terminal         Version@@ -97,23 +88,25 @@      build-depends:         ansi-terminal ^>= { 0.11, 1.0, 1.1 },-        base ^>= { 4.15, 4.16, 4.17, 4.18, 4.19, 4.20, 4.21 },+        base ^>= { 4.15, 4.16, 4.17, 4.18, 4.19, 4.20, 4.21, 4.22 },         bytestring ^>= { 0.10, 0.11, 0.12 },-        containers ^>= { 0.6, 0.7 },+        containers ^>= { 0.6, 0.7, 0.8 },         directory ^>= { 1.3 },         exceptions ^>= { 0.10 },         filepath ^>= { 1.4, 1.5 },         Glob ^>= { 0.10.2 },         hinotify ^>= { 0.4 },         HsYAML ^>= { 0.2 },+        megaparsec ^>= { 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8 },         mtl ^>= { 2.2, 2.3 },         parser-combinators ^>= { 1.3 },         process ^>= { 1.6 },         stm ^>= { 2.5 },-        template-haskell ^>= { 2.17, 2.18, 2.19, 2.20, 2.21, 2.22, 2.23 },+        template-haskell ^>= { 2.17, 2.18, 2.19, 2.20, 2.21, 2.22, 2.23, 2.24 },         temporary ^>= { 1.3 },         text ^>= { 1.2, 2.0, 2.1 },         th-compat ^>= { 0.1 },+        time ^>= { 1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16 },         unix ^>= { 2.7.2, 2.8.4 },      hs-source-dirs:   src
src/Command.hs view
@@ -37,7 +37,7 @@  data CommonOptions = CommonOptions     { optJobs :: Int-    , optRepo :: [ ( RepoName, FilePath ) ]+    , optRepo :: [ ( RepoName, ( Bool, FilePath ) ) ]     , optDestination :: [ ( DestinationName, Text ) ]     } @@ -99,6 +99,9 @@     T.hPutStrLn stderr err     exitFailure +instance MonadOutput CommandExec where+    getOutput = CommandExec (asks ciOutput)+ data CommandInput = CommandInput     { ciOptions :: CommonOptions     , ciRootPath :: FilePath@@ -142,14 +145,12 @@     eiContainingRepo <- asks ciContainingRepo     eiOtherRepos <- asks ciOtherRepos     eiDestinations <- asks ciDestinations+    eiOutput <- asks ciOutput     return EvalInput {..}  cmdEvalWith :: (EvalInput -> EvalInput) -> Eval a -> CommandExec a cmdEvalWith f ev = do     either (tfail . textEvalError) return =<< liftIO . runEval ev . f =<< getEvalInput--getOutput :: CommandExec Output-getOutput = CommandExec (asks ciOutput)  getStorageDir :: CommandExec FilePath getStorageDir = CommandExec (asks ciStorageDir)
src/Command/Extract.hs view
@@ -32,9 +32,8 @@             extractDestination <- return (last args)             return ExtractArguments {..}           where-            toArtifactRef tref = case T.breakOnEnd "." (T.pack tref) of-                (jobref', aref) | Just ( jobref, '.' ) <- T.unsnoc jobref'-                    -> return ( parseJobRef jobref, ArtifactName aref )+            toArtifactRef tref = case parseJobRefParts $ T.pack tref of+                parts@(_ : _) -> return ( JobRef $ init parts, ArtifactName $ last parts )                 _   -> throwError $ "too few parts in artifact ref ‘" <> tref <> "’"         _ -> throwError "too few arguments" 
src/Command/JobId.hs view
@@ -60,14 +60,19 @@         outputMessage out ""         forM_ ids $ \case             JobIdName name -> outputMessage out $ textJobName name <> " (job name)"-            JobIdCommit mbrepo cid -> outputMessage out $ T.concat+            JobIdRepo mbrepo (JobIdCommit cid) -> outputMessage out $ T.concat                 [ textCommitId cid, " (commit"                 , maybe "" (\name -> " from ‘" <> textRepoName name <> "’ repo") mbrepo                 , ")"                 ]-            JobIdTree mbrepo subtree cid -> outputMessage out $ T.concat+            JobIdRepo mbrepo (JobIdTree subtree cid) -> outputMessage out $ T.concat                 [ textTreeId cid, " (tree"                 , maybe "" (\name -> " from ‘" <> textRepoName name <> "’ repo") mbrepo                 , if not (null subtree) then ", subtree ‘" <> T.pack subtree <> "’" else ""+                , ")"+                ]+            JobIdRepo mbrepo (JobIdTag cid tid) -> outputMessage out $ T.concat+                [ textCommitId cid, "^", textTagId tid, " (commit following tag"+                , maybe "" (\name -> " from ‘" <> textRepoName name <> "’ repo") mbrepo                 , ")"                 ]
src/Command/Run.hs view
@@ -8,17 +8,16 @@ import Control.Monad import Control.Monad.IO.Class +import Data.Char import Data.Containers.ListUtils import Data.Either import Data.List import Data.Maybe import Data.Text (Text) import Data.Text qualified as T-import Data.Text.IO qualified as T  import System.Console.GetOpt import System.FilePath.Glob-import System.IO  import Command import Config@@ -26,6 +25,7 @@ import Job import Job.Types import Output+import Range import Repo import Terminal @@ -103,17 +103,22 @@     commandExec = cmdRun  -data JobSource = JobSource (TMVar (Maybe ( [ JobSet ], JobSource )))+data JobSource = JobSource (TMVar (Maybe ( [ JobSourceItem ], JobSource ))) +data JobSourceItem = JobSourceItem+    { jsiJobSet :: JobSet+    , jsiCancelAction :: Maybe (MVar (IO ()))+    }+ emptyJobSource :: MonadIO m => m JobSource emptyJobSource = JobSource <$> liftIO (newTMVarIO Nothing)  oneshotJobSource :: MonadIO m => [ JobSet ] -> m JobSource oneshotJobSource jobsets = do     next <- emptyJobSource-    JobSource <$> liftIO (newTMVarIO (Just ( jobsets, next )))+    JobSource <$> liftIO (newTMVarIO (Just ( map (`JobSourceItem` Nothing) jobsets, next ))) -takeJobSource :: JobSource -> STM (Maybe ( [ JobSet ], JobSource ))+takeJobSource :: JobSource -> STM (Maybe ( [ JobSourceItem ], JobSource )) takeJobSource (JobSource tmvar) = takeTMVar tmvar  mergeSources :: [ JobSource ] -> IO JobSource@@ -135,7 +140,7 @@     return $ JobSource tmvar    where-    select :: [ JobSource ] -> STM ( [ JobSet ], [ JobSource ] )+    select :: [ JobSource ] -> STM ( [ JobSourceItem ], [ JobSource ] )     select [] = retry     select (x@(JobSource tmvar) : xs) = do         tryTakeTMVar tmvar >>= \case@@ -162,14 +167,14 @@         Nothing -> return []     let cidPart = case jobRoot of             JobRootConfig {} -> []-            JobRootRepo {} -> map (JobIdTree Nothing "" . treeId) jobtree+            JobRootRepo {} -> map (JobIdRepo Nothing . JobIdTree "" . treeId) jobtree     forM_ names $ \name ->         case find ((name ==) . jobName) (configJobs config) of             Just _  -> return ()             Nothing -> tfail $ "job ‘" <> textJobName name <> "’ not found"      jset <- cmdEvalWith (\ei -> ei { eiCurrentIdRev = cidPart ++ eiCurrentIdRev ei }) $ do-        evalJobSetSelected names (map ( Nothing, ) jobtree) JobSet+        evalJobSetSelected names (map (( Nothing , ) . RepoRefCommit) $ maybeToList jcommit) JobSet             { jobsetId = ()             , jobsetConfig = Just config             , jobsetCommit = jcommit@@ -203,81 +208,67 @@         , jobsetJobsEither = Right $ configJobs config         } -rangeSource :: Text -> Text -> CommandExec JobSource-rangeSource base tip = do-    root <- getJobRoot-    repo <- getDefaultRepo-    commits <- listCommits repo (base <> ".." <> tip)-    jobsets <- forM commits $ \commit -> do-        tree <- getCommitTree commit-        cmdEvalWith (\ei -> ei-            { eiCurrentIdRev = JobIdTree Nothing (treeSubdir tree) (treeId tree) : eiCurrentIdRev ei-            }) . evalJobSet [ ( Nothing, tree) ] =<< loadJobSetFromRoot root commit-    oneshotJobSource jobsets --watchBranchSource :: Text -> CommandExec JobSource-watchBranchSource branch = do+watchExpressionSource :: RangeExpression -> CommandExec JobSource+watchExpressionSource expr = do     root <- getJobRoot     repo <- getDefaultRepo     einputBase <- getEvalInput-    getCurrentTip <- watchBranch repo branch-    let go prev tmvar = do+    let loop = isRangeExpressionDynamic expr+    let go running prev tmvar = do             cur <- atomically $ do-                getCurrentTip >>= \case-                    Just cur -> do-                        when (cur == prev) retry-                        return cur-                    Nothing -> retry+                cur <- evaluateRange expr+                when (cur == prev) retry+                return cur -            commits <- listCommits repo (textCommitId (commitId prev) <> ".." <> textCommitId (commitId cur))+            commits <- getAddedRangeCommits repo prev cur             jobsets <- forM commits $ \commit -> do                 tree <- getCommitTree commit                 let einput = einputBase-                        { eiCurrentIdRev = JobIdTree Nothing (treeSubdir tree) (treeId tree) : eiCurrentIdRev einputBase+                        { eiCurrentIdRev = JobIdRepo Nothing (JobIdTree (treeSubdir tree) (treeId tree)) : eiCurrentIdRev einputBase                         }-                either (fail . T.unpack . textEvalError) return =<<-                    flip runEval einput . evalJobSet [ ( Nothing, tree ) ] =<< loadJobSetFromRoot root commit+                dset <- loadJobSetFromRoot root commit+                let fset err = JobSet+                        { jobsetId = JobSetId $ reverse $+                            JobIdRepo Nothing (JobIdCommit (commitId commit)) : eiCurrentIdRev einputBase+                        , jobsetConfig = Nothing+                        , jobsetCommit = Just commit+                        , jobsetExplicitlyRequested = []+                        , jobsetJobsEither = Left $ T.unpack $ textEvalError err+                        }+                jsiJobSet <- fmap (either fset id) $ flip runEval einput $+                    evalJobSet [ ( Nothing, RepoRefCommit commit ) ] dset+                jsiCancelAction <- Just <$> newEmptyMVar+                return JobSourceItem {..}++            obsolete <- getAddedRangeCommits repo cur prev+            let ( cancel, keep ) = partition (maybe False (`elem` obsolete) . jobsetCommit . jsiJobSet) running+            mapM_ (mapM_ (join . readMVar) . jsiCancelAction) cancel+             nextvar <- newEmptyTMVarIO             atomically $ putTMVar tmvar $ Just ( jobsets, JobSource nextvar )-            go cur nextvar+            if loop+              then do+                go (reverse jobsets ++ keep) cur nextvar+              else do+                atomically $ putTMVar nextvar Nothing      liftIO $ do         tmvar <- newEmptyTMVarIO-        atomically getCurrentTip >>= \case-            Just commit ->-                void $ forkIO $ go commit tmvar-            Nothing -> do-                T.hPutStrLn stderr $ "Branch ‘" <> branch <> "’ not found"-                atomically $ putTMVar tmvar Nothing+        void $ forkIO $ go [] EmptyCommitRange tmvar         return $ JobSource tmvar +watchBranchSource :: Text -> CommandExec JobSource+watchBranchSource branch = do+    repo <- getDefaultRepo+    expr <- evaluateDeclaredRange repo $ RangeExpression (WatchedRef (TextRef branch)) (StaticRef (TextRef branch))+    watchExpressionSource expr+ watchTagSource :: Pattern -> CommandExec JobSource watchTagSource pat = do-    root <- getJobRoot-    chan <- watchTags =<< getDefaultRepo-    einputBase <- getEvalInput--    let go tmvar = do-            tag <- atomically $ readTChan chan-            if match pat $ T.unpack $ tagTag tag-              then do-                tree <- getCommitTree $ tagObject tag-                let einput = einputBase-                        { eiCurrentIdRev = JobIdTree Nothing (treeSubdir tree) (treeId tree) : eiCurrentIdRev einputBase-                        }-                jobset <- either (fail . T.unpack . textEvalError) return =<<-                    flip runEval einput . evalJobSet [ ( Nothing, tree ) ] =<< loadJobSetFromRoot root (tagObject tag)-                nextvar <- newEmptyTMVarIO-                atomically $ putTMVar tmvar $ Just ( [ jobset ], JobSource nextvar )-                go nextvar-              else do-                go tmvar--    liftIO $ do-        tmvar <- newEmptyTMVarIO-        void $ forkIO $ go tmvar-        return $ JobSource tmvar+    repo <- getDefaultRepo+    expr <- evaluateDeclaredRange repo $ WatchedTagsExpression (TagPattern pat True)+    watchExpressionSource expr  cmdRun :: RunCommand -> CommandExec () cmdRun (RunCommand RunOptions {..} args) = do@@ -285,44 +276,51 @@     output <- getOutput     storageDir <- getStorageDir -    ( rangeOptions, jobOptions ) <- partitionEithers . concat <$> sequence+    rangeOptions <- concat <$> sequence         [ forM roRanges $ \range -> case T.splitOn ".." range of             [ base, tip ]                 | not (T.null base) && not (T.null tip)-                -> return $ Left ( Just base, tip )+                -> return ( Just base, tip )             _ -> tfail $ "invalid range: " <> range-        , forM roSinceUpstream $ return . Left . ( Nothing, )-        , forM args $ \arg -> case T.splitOn ".." arg of-            [ base, tip ]-                | not (T.null base) && not (T.null tip)-                -> return $ Left ( Just base, tip )-            [ _ ] -> return $ Right arg-            _ -> tfail $ "invalid argument: " <> arg+        , forM roSinceUpstream $ return . ( Nothing, )         ] -    let ( refOptions, nameOptions ) = partition (T.elem '.') jobOptions+    let ( nameOptions, jobOptions ) = partition (T.all $ \c -> isAlphaNum c || c == '_') args+        ( refOptions, exprOptions ) = partitionEithers $ map splitRefs jobOptions+        splitRefs t = case parseJobRef t of+            JobRef [ e ] -> Right e+            JobRef [ e, "" ] -> Right e+            ref -> Left ref      argumentJobs <- argumentJobSource $ map JobName nameOptions-    refJobs <- refJobSource $ map parseJobRef refOptions+    refJobs <- refJobSource refOptions +    exprJobs <- forM exprOptions $ \trange ->+        case parseRangeExpression trange of+            Left err -> fail err+            Right expr -> do+                repo <- getDefaultRepo+                range <- evaluateDeclaredRange repo expr+                watchExpressionSource range+     defaultSource <- getJobRoot >>= \case-        _ | not (null rangeOptions && null roNewCommitsOn && null roNewTags && null jobOptions) -> do+        _ | not (null rangeOptions && null roNewCommitsOn && null roNewTags && null args) -> do             emptyJobSource          JobRootRepo repo -> do-            Just base <- findUpstreamRef repo "HEAD"-            rangeSource base "HEAD"+            watchExpressionSource =<< evaluateDeclaredRange repo (RangeExpression (StaticRef (TextRef "HEAD")) (StaticRef (UpstreamRef "HEAD")))          JobRootConfig config -> do             argumentJobSource (jobName <$> configJobs config) -    ranges <- forM rangeOptions $ \( mbBase, paramTip ) -> do-        ( base, tip ) <- case mbBase of-            Just base -> return ( base, paramTip )+    ranges <- forM rangeOptions $ \( mbBase, tip ) -> do+        repo <- getDefaultRepo+        range <- case mbBase of+            Just base ->+                evaluateDeclaredRange repo (RangeExpression (StaticRef (TextRef tip)) (StaticRef (TextRef base)))             Nothing -> do-                Just base <- flip findUpstreamRef paramTip =<< getDefaultRepo-                return ( base, paramTip )-        rangeSource base tip+                evaluateDeclaredRange repo (RangeExpression (StaticRef (TextRef tip)) (StaticRef (UpstreamRef tip)))+        watchExpressionSource range      branches <- mapM watchBranchSource roNewCommitsOn     tags <- mapM watchTagSource roNewTags@@ -330,7 +328,7 @@     liftIO $ do         mngr <- newJobManager storageDir optJobs -        source <- mergeSources $ concat [ [ defaultSource, argumentJobs, refJobs ], ranges, branches, tags ]+        source <- mergeSources $ concat [ [ defaultSource, argumentJobs, refJobs ], exprJobs, ranges, branches, tags ]         mbHeaderLine <- mapM (flip newLine "") (outputTerminal output)          threadCount <- newTVarIO (0 :: Int)@@ -345,26 +343,26 @@             loop names (Just ( [], next )) = do                 loop names =<< atomically (takeJobSource next) -            loop pnames (Just ( jobset : rest, next )) = do-                let names = nub $ (pnames ++) $ map jobName $ jobsetJobs jobset+            loop pnames (Just ( JobSourceItem {..} : rest, next )) = do+                let names = nub $ (pnames ++) $ map jobName $ jobsetJobs jsiJobSet                 when (names /= pnames) $ do                     forM_ mbHeaderLine $ \headerLine -> do                         redrawLine headerLine $ T.concat $                             T.replicate (8 + 50) " " :                             map ((" " <>) . fitToLength 7 . textJobName) names -                let commit = jobsetCommit jobset+                let commit = jobsetCommit jsiJobSet                     shortCid = T.pack $ take 7 $ maybe (repeat ' ') (showCommitId . commitId) commit                 shortDesc <- fitToLength 50 <$> maybe (return "") getCommitTitle commit -                case jobsetJobsEither jobset of+                case jobsetJobsEither jsiJobSet of                     Right jobs -> do-                        outs <- runJobs mngr output jobs $ case roRerun of-                            RerunExplicit -> \jid status -> jid `elem` jobsetExplicitlyRequested jobset || jobStatusFailed status+                        tasks <- runJobs mngr output jobs $ case roRerun of+                            RerunExplicit -> \jid status -> jid `elem` jobsetExplicitlyRequested jsiJobSet || jobStatusFailed status                             RerunFailed -> \_ status -> jobStatusFailed status                             RerunAll -> \_ _ -> True                             RerunNone -> \_ _ -> False-                        let findJob name = snd <$> find ((name ==) . jobName . fst) outs+                        let findJob name = taskStatus <$> find ((name ==) . jobName . taskJob) tasks                             statuses = map findJob names                         forM_ (outputTerminal output) $ \tout -> do                             line <- newLine tout ""@@ -375,14 +373,27 @@                             void $ forkIO $ do                                 void $ try @SomeException $ restore $ waitForJobStatuses statuses                                 changeCount (subtract 1)+                        case jsiCancelAction of+                            Just var -> putMVar var $ mapM_ cancelTask tasks+                            Nothing -> return ()                     Left err -> do+                        case jsiCancelAction of+                            Just var -> putMVar var $ return ()+                            Nothing -> return ()                         forM_ (outputTerminal output) $ flip newLine $                             "\ESC[91m" <> shortCid <> "\ESC[0m" <> " " <> shortDesc <> " \ESC[91m" <> T.pack err <> "\ESC[0m"                         outputEvent output $ TestMessage $ "jobset-fail " <> T.pack err                         outputEvent output $ LogMessage $ "Jobset failed: " <> shortCid <> " " <> T.pack err                 loop names (Just ( rest, next )) -        handle @SomeException (\_ -> cancelAllJobs mngr) $ do+        handle @SomeException+            (\e -> do+                if | Just UserInterrupt <- fromException e+                   -> outputEvent output RunInterruptedByUser+                   | otherwise+                   -> outputMessage output $ "exception in run loop: " <> T.pack (show e)+                cancelAllJobs mngr+            ) $ do             loop [] =<< atomically (takeJobSource source)             waitForJobs         waitForJobs@@ -394,39 +405,42 @@                        | otherwise     = T.take (maxlen - 1) str <> "…"     where len = T.length str -showStatus :: Bool -> JobStatus a -> Text-showStatus blink = \case-    JobQueued       -> " \ESC[94m…\ESC[0m     "-    JobWaiting uses -> "\ESC[94m~" <> fitToLength 6 (T.intercalate "," (map textJobName uses)) <> "\ESC[0m"-    JobSkipped      ->  " \ESC[0m-\ESC[0m     "-    JobRunning      -> " \ESC[96m" <> (if blink then "*" else "•") <> "\ESC[0m     "-    JobError fnote  -> "\ESC[91m" <> fitToLength 7 ("!! [" <> T.pack (maybe "?" (show . tfNumber) (footnoteTerminal fnote)) <> "]") <> "\ESC[0m"-    JobFailed       -> " \ESC[91m✗\ESC[0m     "-    JobCancelled    ->  " \ESC[0mC\ESC[0m     "-    JobDone _       -> " \ESC[92m✓\ESC[0m     "+showStatus :: Int -> Bool -> AnnotatedStatus -> Text+showStatus width blink ( status, fnotes ) = case status of+    JobQueued       -> " \ESC[94m…\ESC[0m" <> showNotes (width - 2)+    JobWaiting uses -> "\ESC[94m~" <> fitToLength (width - 1) (T.intercalate "," (map textJobName uses) <> showNotes (width - 1)) <> "\ESC[0m"+    JobSkipped      ->  " \ESC[0m-\ESC[0m" <> showNotes (width - 2)+    JobRunning      -> " \ESC[96m" <> (if blink then "*" else "•") <> "\ESC[0m" <> showNotes 5+    JobError _      -> "\ESC[91m!!\ESC[0m" <> showNotes (width - 2)+    JobFailed       -> " \ESC[91m✗\ESC[0m" <> showNotes (width - 2)+    JobCancelled    ->  " \ESC[0mC\ESC[0m" <> showNotes (width - 2)+    JobDone _       -> " \ESC[92m✓\ESC[0m" <> showNotes (width - 2)      JobDuplicate _ s -> case s of-        JobQueued    -> " \ESC[94m^\ESC[0m     "-        JobWaiting _ -> " \ESC[94m^\ESC[0m     "-        JobSkipped   ->  " \ESC[0m-\ESC[0m     "-        JobRunning   -> " \ESC[96m" <> (if blink then "*" else "^") <> "\ESC[0m     "-        _            -> showStatus blink s+        JobQueued    -> " \ESC[94m^\ESC[0m" <> showNotes (width - 2)+        JobWaiting _ -> " \ESC[94m^\ESC[0m" <> showNotes (width - 2)+        JobSkipped   ->  " \ESC[0m-\ESC[0m" <> showNotes (width - 2)+        JobRunning   -> " \ESC[96m" <> (if blink then "*" else "^") <> "\ESC[0m" <> showNotes (width - 2)+        _            -> showStatus width blink ( s, fnotes ) -    JobPreviousStatus (JobDone _) -> "\ESC[90m«\ESC[32m✓\ESC[0m     "-    JobPreviousStatus (JobFailed) -> "\ESC[90m«\ESC[31m✗\ESC[0m     "-    JobPreviousStatus s           -> "\ESC[90m«" <> T.init (showStatus blink s)+    JobPreviousStatus (JobDone _) -> "\ESC[90m«\ESC[32m✓\ESC[0m" <> showNotes (width - 2)+    JobPreviousStatus (JobFailed) -> "\ESC[90m«\ESC[31m✗\ESC[0m" <> showNotes (width - 2)+    JobPreviousStatus s           -> "\ESC[90m«\ESC[0m" <> showStatus (width - 1) blink ( s, fnotes )+  where+    showNotes w = fitToLength w $ T.concat $ " " : map showNote fnotes+    showNote fnote = "[" <> T.pack (maybe "?" (show . tfNumber) (footnoteTerminal fnote)) <> "]" -displayStatusLine :: TerminalOutput -> TerminalLine -> Text -> Text -> [ Maybe (TVar (JobStatus JobOutput)) ] -> IO ()+displayStatusLine :: TerminalOutput -> TerminalLine -> Text -> Text -> [ Maybe (STM AnnotatedStatus) ] -> IO () displayStatusLine tout line prefix1 prefix2 statuses = do     go "\0"   where     go prev = do-        (ss, cur) <- atomically $ do-            ss <- mapM (sequence . fmap readTVar) statuses+        ( ss, cur ) <- atomically $ do+            sns <- mapM sequence statuses             blink <- terminalBlinkStatus tout-            let cur = T.concat $ map (maybe "        " ((" " <>) . showStatus blink)) ss+            let cur = T.concat $ map (maybe "        " ((" " <>) . showStatus 7 blink)) sns             when (cur == prev) retry-            return (ss, cur)+            return ( map (fmap fst) sns, cur )          let prefix1' = if any (maybe False jobStatusFailed) ss                          then "\ESC[91m" <> prefix1 <> "\ESC[0m"@@ -437,9 +451,9 @@            then return ()            else go cur -waitForJobStatuses :: [ Maybe (TVar (JobStatus a)) ] -> IO ()+waitForJobStatuses :: [ Maybe (STM AnnotatedStatus) ] -> IO () waitForJobStatuses mbstatuses = do     let statuses = catMaybes mbstatuses     atomically $ do-        ss <- mapM readTVar statuses-        when (any (not . jobStatusFinished) ss) retry+        ss <- sequence statuses+        when (any (not . jobStatusFinished . fst) ss) retry
src/Config.hs view
@@ -27,6 +27,7 @@ import System.Process  import Destination+import Job import Job.Types import Repo @@ -101,6 +102,7 @@     jobArtifacts <- parseArtifacts j     jobUses <- maybe (return []) parseUses =<< j .:? "uses"     jobPublish <- maybe (return []) (parsePublish jobName) =<< j .:? "publish"+    jobPush <- maybe (return []) parsePush =<< j .:? "push"     return Job {..}  parseSingleCheckout :: Node Pos -> Parser [ JobCheckout Declared ]@@ -164,13 +166,33 @@         jpPath <- fmap T.unpack <$> m .:? "path"         return JobPublish {..} +parsePush :: Node Pos -> Parser [ JobPush Declared ]+parsePush = withSeq "Push list" $ mapM $+    withMap "Push specification" $ \m -> do+        source <- m .: "commit"+        jpushSource <- case T.split (== '.') source of+            [ repo, sel ]+                | sel == "commit"+                -> return $ currentCommitExpr (RepoName repo)+            _ -> mzero+        destination <- m .: "to"+        jpushDestination <- case T.split (== '.') destination of+            [ repo, sel ]+                | [ fn, bname, fn' ] <- T.split (== '"') sel+                , fn == "branch("+                , fn' == ")"+                -> return $ branchExpr (RepoName repo) bname+            _ -> mzero+        return JobPush {..} + parseRepo :: Text -> Node Pos -> Parser DeclaredRepo parseRepo name node = choice-    [ flip (withNull "Repo") node $ return $ DeclaredRepo (RepoName name) Nothing+    [ flip (withNull "Repo") node $ return $ DeclaredRepo (RepoName name) Nothing False     , flip (withMap "Repo") node $ \r -> DeclaredRepo         <$> pure (RepoName name)         <*> (fmap T.unpack <$> r .:? "path")+        <*> (fromMaybe False <$> r .:? "writable")     ]  parseDestination :: Text -> Node Pos -> Parser DeclaredDestination
src/Eval.hs view
@@ -1,7 +1,8 @@ module Eval (     EvalInput(..),     EvalError(..), textEvalError,-    Eval, runEval,+    Eval, runEval, eval,+    RepoRef(..),      evalJobSet,     evalJobSetSelected,@@ -11,10 +12,14 @@     loadJobSetById, ) where +import Control.Concurrent.STM import Control.Monad+import Control.Monad.Catch import Control.Monad.Except import Control.Monad.Reader +import Data.Bifunctor+import Data.Either import Data.List import Data.Maybe import Data.Text (Text)@@ -24,7 +29,10 @@  import Config import Destination+import Expr import Job.Types+import Output+import Range import Repo  data EvalInput = EvalInput@@ -34,6 +42,7 @@     , eiContainingRepo :: Maybe Repo     , eiOtherRepos :: [ ( RepoName, Repo ) ]     , eiDestinations :: [ ( DestinationName, Destination ) ]+    , eiOutput :: Output     }  data EvalError@@ -43,25 +52,70 @@ textEvalError (OtherEvalError text) = text  -type Eval a = ReaderT EvalInput (ExceptT EvalError IO) a+newtype Eval a = Eval (ReaderT EvalInput (ExceptT EvalError IO) a)+  deriving+    ( Functor, Applicative, Monad+    , MonadReader EvalInput+    , MonadError EvalError+    , MonadIO+    ) +instance MonadFail Eval where+    fail = throwError . OtherEvalError . T.pack++instance MonadOutput Eval where+    getOutput = asks eiOutput+ runEval :: Eval a -> EvalInput -> IO (Either EvalError a)-runEval action einput = runExceptT $ flip runReaderT einput action+runEval (Eval action) einput = runExceptT $ flip runReaderT einput action  -commonPrefix :: Eq a => [ a ] -> [ a ] -> [ a ]-commonPrefix (x : xs) (y : ys) | x == y = x : commonPrefix xs ys-commonPrefix _        _                 = []+eval :: forall ctx a. ctx -> Expr ctx a -> Eval a+eval ctx = \case+    Pure x -> return x+    App f x -> eval' f <*> eval' x+    GetContext -> return ctx+    AddDependency _ x -> eval' x+    ExprIO act x -> do+        x' <- eval' x+        liftIO (handleIOError (\e -> return $ Left e) (Right <$> act x')) >>= \case+            Left e -> throwError $ OtherEvalError $ "IO error: " <> T.pack (show e)+            Right y -> return y+  where+    eval' :: forall b. Expr ctx b -> Eval b+    eval' = eval ctx ++repoRefLimit :: RepoDepLevel -> RepoRef -> Eval RepoRef+repoRefLimit (RepoDepSubtree path) rref = do+    tree <- repoRefTree rref+    if  | treeSubdir tree == path -> do+            return $ RepoRefTree tree+        | splitDirectories (treeSubdir tree) `isPrefixOf` splitDirectories path -> do+            tree' <- getSubtree Nothing (makeRelative (treeSubdir tree) path) tree+            return $ RepoRefTree tree'+        | otherwise -> do+            throwError $ OtherEvalError $ "Can't get subtree ‘" <> T.pack path <> "’ from ‘" <> T.pack (treeSubdir tree) <> "’"++repoRefLimit RepoDepCommit rref = case rref of+    RepoRefTree _ -> throwError $ OtherEvalError $ "Can't get commit from subtree ref"+    RepoRefCommit commit -> return $ RepoRefCommit commit+    RepoRefTag commit _ -> return $ RepoRefCommit commit++repoRefLimit RepoDepTag rref = case rref of+    RepoRefTree _ -> throwError $ OtherEvalError $ "Can't get tag from subtree ref"+    RepoRefCommit _ -> throwError $ OtherEvalError $ "Can't get tag from commit ref"+    RepoRefTag commit tag -> return $ RepoRefTag commit tag++ checkIfAlreadyHasDefaultRepoId :: Eval Bool checkIfAlreadyHasDefaultRepoId = do     asks (any isDefaultRepoId . eiCurrentIdRev)   where     isDefaultRepoId (JobIdName _) = False-    isDefaultRepoId (JobIdCommit rname _) = isNothing rname-    isDefaultRepoId (JobIdTree rname _ _) = isNothing rname+    isDefaultRepoId (JobIdRepo rname _) = isNothing rname -collectJobSetRepos :: [ ( Maybe RepoName, Tree ) ] -> DeclaredJobSet -> Eval [ ( Maybe RepoName, Tree ) ]+collectJobSetRepos :: [ ( Maybe RepoName, RepoRef ) ] -> DeclaredJobSet -> Eval [ ( Maybe RepoName, RepoRef ) ] collectJobSetRepos revisionOverrides dset = do     jobs <- either (throwError . OtherEvalError . T.pack) return $ jobsetJobsEither dset     let someJobUsesDefaultRepo = any (any (isNothing . jcRepo) . jobCheckout) jobs@@ -73,39 +127,50 @@             Just tree -> return ( rname, tree )             Nothing -> do                 repo <- evalRepo rname-                tree <- getCommitTree =<< readCommit repo "HEAD"-                return ( rname, tree )+                commit <- readCommit repo "HEAD"+                return ( rname, RepoRefCommit commit ) -collectOtherRepos :: DeclaredJobSet -> DeclaredJob -> Eval [ ( Maybe ( RepoName, Maybe Text ), FilePath ) ]+getJobExprDependencies :: DeclaredJob -> [ JobSetDep ]+getJobExprDependencies job = concat+    [ concatMap (collectDependencies . jpushSource) $ jobPush job+    , concatMap (collectDependencies . jpushDestination) $ jobPush job+    ]++collectOtherRepos :: DeclaredJobSet -> DeclaredJob -> Eval [ ( Maybe ( RepoName, Maybe Text ), RepoDepLevel ) ] collectOtherRepos dset decl = do     jobs <- either (throwError . OtherEvalError . T.pack) return $ jobsetJobsEither dset     let gatherDependencies seen (d : ds)             | d `elem` seen = gatherDependencies seen ds             | Just job <- find ((d ==) . jobName) jobs-                            = gatherDependencies (d : seen) (map fst (jobRequiredArtifacts job) ++ ds)+            = do+                let allDeps = getJobExprDependencies job+                    checkoutRepoDeps = map (\JobCheckout {..} -> ( jcRepo, RepoDepSubtree $ fromMaybe "" jcSubtree )) $ jobCheckout job+                    artifactNameDeps = map fst (jobRequiredArtifacts job)+                let ( nameDeps, repoDeps ) = partitionEithers $ map depsToEithers allDeps+                    nameDeps' = artifactNameDeps ++ nameDeps+                    repoDeps' = checkoutRepoDeps ++ repoDeps+                (repoDeps' ++) <$> gatherDependencies (d : seen) (nameDeps' ++ ds)+             | otherwise     = gatherDependencies (d : seen) ds-        gatherDependencies seen [] = seen+        gatherDependencies _ [] = return [] -    let dependencies = gatherDependencies [] [ jobName decl ]-    dependencyRepos <- forM dependencies $ \name -> do-        job <- maybe (throwError $ OtherEvalError $ "job ‘" <> textJobName name <> "’ not found") return . find ((name ==) . jobName) $ jobs-        return $ jobCheckout job+        depsToEithers = \case+            SiblingJobDependency name -> Left name+            RepoDependency rname deplevel -> Right ( Just ( rname, Nothing ), deplevel )      alreadyHasDefaultRepoId <- checkIfAlreadyHasDefaultRepoId-    let checkouts =-            (if alreadyHasDefaultRepoId then filter (isJust . jcRepo) else id) $-                concat dependencyRepos+    dependencyRepos <-+        (if alreadyHasDefaultRepoId then filter (isJust . fst) else id) <$>+            gatherDependencies [] [ jobName decl ] -    let commonSubdir reporev = joinPath $ foldr1 commonPrefix $-            map (maybe [] splitDirectories . jcSubtree) . filter ((reporev ==) . jcRepo) $ checkouts+    let joinedLevel reporev = foldr1 (<>) $ map snd $ filter ((reporev ==) . fst) dependencyRepos     let canonicalRepoOrder = Nothing : maybe [] (map (Just . repoName) . configRepos) (jobsetConfig dset)-        getCheckoutsForName rname = map (\r -> ( r, commonSubdir r )) $ nub $ filter ((rname ==) . fmap fst) $ map jcRepo checkouts-    return $ concatMap getCheckoutsForName canonicalRepoOrder-+    let getDepLevelForName rname = map (\r -> ( r, joinedLevel r )) $ nub $ filter ((rname ==) . fmap fst) $ map fst dependencyRepos+    return $ concatMap getDepLevelForName canonicalRepoOrder  evalJobs     :: [ DeclaredJob ] -> [ Either JobName Job ]-    -> [ ( Maybe RepoName, Tree ) ] -> DeclaredJobSet -> [ JobName ] -> Eval [ Job ]+    -> [ ( Maybe RepoName, RepoRef ) ] -> DeclaredJobSet -> [ JobName ] -> Eval [ Job ] evalJobs _ _ _ JobSet { jobsetJobsEither = Left err } _ = throwError $ OtherEvalError $ T.pack err  evalJobs [] evaluated repos dset@JobSet { jobsetJobsEither = Right decl } (req : reqs)@@ -123,54 +188,75 @@  evalJobs (current : evaluating) evaluated repos dset reqs     | Just missing <- find (`notElem` (jobName current : map (either id jobName) evaluated)) $ map fst $ jobRequiredArtifacts current-    , d <- either (const Nothing) (find ((missing ==) . jobName)) (jobsetJobsEither dset)-    = evalJobs (fromJust d : current : evaluating) evaluated repos dset reqs+    , Right jset <- jobsetJobsEither dset+    , Just d <- find ((missing ==) . jobName) jset+    = evalJobs (d : current : evaluating) evaluated repos dset reqs  evalJobs (current : evaluating) evaluated repos dset reqs = do     EvalInput {..} <- ask     otherRepos <- collectOtherRepos dset current-    otherRepoTreesMb <- forM otherRepos $ \( mbrepo, commonPath ) -> do-        Just tree <- return $ lookup (fst <$> mbrepo) repos+    otherRepoTreesMb <- forM otherRepos $ \( mbrepo, deplevel ) -> do+        Just repoRef <- return $ lookup (fst <$> mbrepo) repos+        let repo = repoRefRepo repoRef         mbSubtree <- case snd =<< mbrepo of-            Just revisionOverride -> return . Just =<< getCommitTree =<< readCommit (treeRepo tree) revisionOverride+            Just revisionOverride+                | RepoDepSubtree path <- deplevel+                -> do+                    tree <- getCommitTree =<< readCommit repo revisionOverride+                    return $ Just ( JobIdTree path $ treeId tree, RepoRefTree tree )+                | RepoDepCommit <- deplevel+                -> do+                    commit <- readCommit repo revisionOverride+                    return $ Just ( JobIdCommit $ commitId commit, RepoRefCommit commit )+                | RepoDepTag <- deplevel+                -> do+                    [ cid, tid ] <- return $ T.split (== '^') revisionOverride+                    commit <- readCommit repo cid+                    tag <- readTag repo tid+                    return $ Just ( JobIdTag (commitId commit) (tagId tag), RepoRefTag commit tag )             Nothing-                | treeSubdir tree == commonPath -> do-                    return $ Just tree-                | splitDirectories (treeSubdir tree) `isPrefixOf` splitDirectories commonPath -> do-                    Just <$> getSubtree Nothing (makeRelative (treeSubdir tree) commonPath) tree-                | otherwise -> do-                    return Nothing-        return $ fmap (\subtree -> ( mbrepo, ( commonPath, subtree ) )) mbSubtree+                -> do+                    repoRef' <- repoRefLimit deplevel repoRef+                    idpart <- repoRefToIdPart repoRef'+                    return $ Just ( idpart, repoRef' )+        return $ fmap (\subtree -> ( mbrepo, subtree )) mbSubtree     let otherRepoTrees = catMaybes otherRepoTreesMb++    let jscRepos = maybe id ((:) . ( Nothing, )) eiContainingRepo $ map (first Just) eiOtherRepos+    let jscRepoRefs = map (\( repo, ( _, ref ) ) -> ( fst <$> repo, ref )) otherRepoTrees+    let ctx = JobSetContext {..}+     if all isJust otherRepoTreesMb       then do         let otherRepoIds = flip mapMaybe otherRepoTrees $ \case-                ( repo, ( subtree, tree )) -> do+                ( repo, ( idpart, _ ) ) -> do                     guard $ maybe True (isNothing . snd) repo -- use only checkouts without explicit revision in job id-                    Just $ JobIdTree (fst <$> repo) subtree (treeId tree)+                    Just $ JobIdRepo (fst <$> repo) idpart         let currentJobId = JobId $ reverse $ reverse otherRepoIds ++ JobIdName (jobId current) : eiCurrentIdRev          checkouts <- forM (jobCheckout current) $ \dcheckout -> do+            mbTree <- sequence $ msum+                [ repoRefTree . snd <$> lookup (jcRepo dcheckout) otherRepoTrees+                , repoRefTree <$> lookup (fst <$> jcRepo dcheckout) repos -- for containing repo if filtered from otherRepos+                ]             return dcheckout                 { jcRepo =-                    fromMaybe (error $ "expecting repo in either otherRepoTrees or repos: " <> show (textRepoName . fst <$> jcRepo dcheckout)) $-                    msum-                        [ snd <$> lookup (jcRepo dcheckout) otherRepoTrees-                        , lookup (fst <$> jcRepo dcheckout) repos -- for containing repo if filtered from otherRepos-                        ]+                    fromMaybe (error $ "expecting repo in either otherRepoTrees or repos: " <> show (textRepoName . fst <$> jcRepo dcheckout)) $ mbTree                 }          uses <- forM (jobUses current) $ \( jname, aname ) -> do-            Just (Right job) <- return $ find ((jname ==) . either id jobName) evaluated-            return ( jobId job, aname )+            case find ((jname ==) . either id jobName) evaluated of+                Just (Right job) -> return ( jobId job, aname )+                _ -> throwError $ OtherEvalError $ "artifact ‘" <> textArtifactName aname <> "’ in job ‘" <> textJobName jname <> "’ required by ‘" <> textJobName (jobName current) <> "’ not found"          destinations <- forM (jobPublish current) $ \dpublish -> do-            let ( jname, _ ) = jpArtifact dpublish+            let ( jname, aname ) = jpArtifact dpublish             jid <- if                 | jname == jobName current -> return currentJobId                 | otherwise -> do-                    Just (Right job) <- return $ find ((jname ==) . either id jobName) evaluated-                    return $ jobId job+                    case find ((jname ==) . either id jobName) evaluated of+                        Just (Right job) -> return $ jobId job+                        _ -> throwError $ OtherEvalError $ "artifact ‘" <> textArtifactName aname <> "’ in job ‘" <> textJobName jname <> "’ required by ‘" <> textJobName (jobName current) <> "’ not found"              case lookup (jpDestination dpublish) eiDestinations of                 Just dest -> return dpublish@@ -179,6 +265,14 @@                     }                 Nothing -> throwError $ OtherEvalError $ "no url defined for destination ‘" <> textDestinationName (jpDestination dpublish) <> "’" +        pushes <- forM (jobPush current) $ \JobPush {..} -> do+            commit <- eval ctx jpushSource+            branch <- eval ctx jpushDestination+            return JobPush+                { jpushSource = commit+                , jpushDestination = branch+                }+         let job = Job                 { jobId = currentJobId                 , jobName = jobName current@@ -187,23 +281,24 @@                 , jobArtifacts = jobArtifacts current                 , jobUses = uses                 , jobPublish = destinations+                , jobPush = pushes                 }         evalJobs evaluating (Right job : evaluated) repos dset reqs       else do         evalJobs evaluating (Left (jobName current) : evaluated) repos dset reqs -evalJobSet :: [ ( Maybe RepoName, Tree ) ] -> DeclaredJobSet -> Eval JobSet+evalJobSet :: [ ( Maybe RepoName, RepoRef ) ] -> DeclaredJobSet -> Eval JobSet evalJobSet revisionOverrides decl = evalJobSetSelected (either (const []) (map jobName) (jobsetJobsEither decl)) revisionOverrides decl -evalJobSetSelected :: [ JobName ] -> [ ( Maybe RepoName, Tree ) ] -> DeclaredJobSet -> Eval JobSet+evalJobSetSelected :: [ JobName ] -> [ ( Maybe RepoName, RepoRef ) ] -> DeclaredJobSet -> Eval JobSet evalJobSetSelected selected revisionOverrides decl = do     EvalInput {..} <- ask     repos <- collectJobSetRepos revisionOverrides decl     alreadyHasDefaultRepoId <- checkIfAlreadyHasDefaultRepoId-    let addedRepoIds =-            map (\( mbname, tree ) -> JobIdTree mbname (treeSubdir tree) (treeId tree)) $-            (if alreadyHasDefaultRepoId then filter (isJust . fst) else id) $-            repos+    addedRepoIds <-+        mapM (\( mbname, ref ) -> JobIdRepo mbname <$> repoRefToIdPart ref) $+        (if alreadyHasDefaultRepoId then filter (isJust . fst) else id) $+        repos      evaluated <- handleToEither $ evalJobs [] [] repos decl selected     let jobs = case liftM2 (,) evaluated (jobsetJobsEither decl) of@@ -212,7 +307,7 @@      let explicit = mapMaybe (\name -> jobId <$> find ((name ==) . jobName) (either (const []) id jobs)) $ jobsetExplicitlyRequested decl     return JobSet-        { jobsetId = JobSetId $ reverse $ reverse addedRepoIds ++ eiCurrentIdRev+        { jobsetId = JobSetId $ reverse $ reverse addedRepoIds ++ map promoteTreeToCommit eiCurrentIdRev         , jobsetConfig = jobsetConfig decl         , jobsetCommit = jobsetCommit decl         , jobsetExplicitlyRequested = explicit@@ -220,7 +315,18 @@         }   where     handleToEither = flip catchError (return . Left . T.unpack . textEvalError) . fmap Right+    promoteTreeToCommit = \case+        x@(JobIdRepo Nothing (JobIdTree {})) ->+            case lookup Nothing revisionOverrides of+                Just (RepoRefCommit commit) ->+                    JobIdRepo Nothing (JobIdCommit (commitId commit)) +                Just (RepoRefTag commit tag) ->+                    JobIdRepo Nothing (JobIdTag (commitId commit) (tagId tag))++                _ -> x+        x -> x+ evalRepo :: Maybe RepoName -> Eval Repo evalRepo Nothing = asks eiContainingRepo >>= \case     Just repo -> return repo@@ -230,7 +336,7 @@     Nothing -> throwError $ OtherEvalError $ "repo ‘" <> textRepoName name <> "’ not defined"  -canonicalJobName :: [ Text ] -> Config -> Maybe Tree -> Eval JobSet+canonicalJobName :: [ Text ] -> Config -> Maybe RepoRef -> Eval JobSet canonicalJobName (r : rs) config mbDefaultRepo = do     let name = JobName r         dset = JobSet@@ -244,13 +350,14 @@         Just djob -> do             otherRepos <- collectOtherRepos dset djob             ( overrides, rs' ) <- (\f -> foldM f ( [], rs ) otherRepos) $-                \( overrides, crs ) ( mbrepo, path ) -> if+                \( overrides, crs ) ( mbrepo, deplevel ) -> if                     | Just ( _, Just _ ) <- mbrepo -> do                         -- use only checkouts without explicit revision in job id                         return ( overrides, crs )                     | otherwise -> do-                        ( tree, crs' ) <- readTreeFromIdRef crs path =<< evalRepo (fst <$> mbrepo)-                        return ( ( fst <$> mbrepo, tree ) : overrides, crs' )+                        ( repoRef, crs' ) <- readRepoRefFromIdRef crs (repoDepPath deplevel) =<< evalRepo (fst <$> mbrepo)+                        ref' <- repoRefLimit deplevel repoRef+                        return ( ( fst <$> mbrepo, ref' ) : overrides, crs' )             case rs' of                 (r' : _) -> throwError $ OtherEvalError $ "unexpected job ref part ‘" <> r' <> "’"                 _ -> return ()@@ -258,21 +365,42 @@         Nothing -> throwError $ OtherEvalError $ "job ‘" <> r <> "’ not found" canonicalJobName [] _ _ = throwError $ OtherEvalError "expected job name" -readTreeFromIdRef :: [ Text ] -> FilePath -> Repo -> Eval ( Tree, [ Text ] )-readTreeFromIdRef (r : rs) subdir repo = do-    tryReadCommit repo r >>= \case-        Just commit -> return . (, rs) =<< getSubtree (Just commit) subdir =<< getCommitTree commit-        Nothing -> tryReadTree repo subdir r >>= \case-            Just tree -> return ( tree, rs )-            Nothing -> throwError $ OtherEvalError $ "failed to resolve ‘" <> r <> "’ to a commit or tree in " <> T.pack (show repo)-readTreeFromIdRef [] _ _ = throwError $ OtherEvalError $ "expected commit or tree reference"+readRepoRefFromIdRef :: [ Text ] -> FilePath -> Repo -> Eval ( RepoRef, [ Text ] )+readRepoRefFromIdRef (r : rs) subdir repo = do+    case parseRangeExpression r of+        Left err -> throwError $ OtherEvalError $ T.pack err+        Right (SingleRevisionExpression revDecl) -> do+            doEvaluateRev revDecl >>= \case+                Just commit+                    | subdir == "" -> return ( RepoRefCommit commit, rs )+                    | otherwise -> return . ( , rs ) . RepoRefTree =<< getSubtree (Just commit) subdir =<< getCommitTree commit+                Nothing -> tryReadTree repo subdir r >>= \case+                    Just tree -> return ( RepoRefTree tree, rs )+                    Nothing -> throwError $ OtherEvalError $ "failed to resolve ‘" <> r <> "’ to a commit or tree in " <> T.pack (show repo)+        Right _ -> throwError $ OtherEvalError $ "only single revision expression is supported in job ref now"+  where+    doEvaluateRev revDecl = do+        mbRevExpr <- (Just <$> evaluateDeclaredRevision repo revDecl) `catchError` (const $ return Nothing)+        case mbRevExpr of+            Just revExpr -> do+                when (isRevisionExpressionDynamic revExpr) $ do+                    throwError $ OtherEvalError $ "dynamic watch expression is not yet supported in job ref"+                liftIO (atomically (evaluateRevision revExpr)) >>= \case+                    Just commitRef -> getCommitFromRef repo commitRef+                    Nothing -> return Nothing+            Nothing -> do+                return Nothing ++readRepoRefFromIdRef [] _ _ = throwError $ OtherEvalError $ "expected commit or tree reference"+ canonicalCommitConfig :: [ Text ] -> Repo -> Eval JobSet canonicalCommitConfig rs repo = do-    ( tree, rs' ) <- readTreeFromIdRef rs "" repo+    ( rref, rs' ) <- readRepoRefFromIdRef rs "" repo+    tree <- repoRefTree rref     config <- either fail return =<< loadConfigForCommit tree-    local (\ei -> ei { eiCurrentIdRev = JobIdTree Nothing "" (treeId tree) : eiCurrentIdRev ei }) $-        canonicalJobName rs' config (Just tree)+    local (\ei -> ei { eiCurrentIdRev = JobIdRepo Nothing (JobIdTree "" (treeId tree)) : eiCurrentIdRev ei }) $+        canonicalJobName rs' config (Just rref)  evalJobReferenceToSet :: JobRef -> Eval JobSet evalJobReferenceToSet (JobRef rs) =@@ -297,33 +425,38 @@     otherRepos <- forM sid $ \case         JobIdName name -> do             throwError $ OtherEvalError $ "expected tree id, not a job name ‘" <> textJobName name <> "’"-        JobIdCommit name cid -> do-            repo <- evalRepo name-            tree <- getCommitTree =<< readCommitId repo cid-            return ( name, tree )-        JobIdTree name path tid -> do+        JobIdRepo name repoId -> do             repo <- evalRepo name-            tree <- readTreeId repo path tid+            tree <- case repoId of+                JobIdTree path tid -> readTreeId repo path tid+                JobIdCommit cid -> getCommitTree =<< readCommitId repo cid+                JobIdTag cid _ -> getCommitTree =<< readCommitId repo cid             return ( name, tree )     return ( dset, eiCurrentIdRev, otherRepos )  jobsetFromCommitConfig :: [ JobIdPart ] -> Repo -> Eval ( DeclaredJobSet, [ JobIdPart ], [ ( Maybe RepoName, Tree ) ] )-jobsetFromCommitConfig (JobIdTree name path tid : sid) repo = do+jobsetFromCommitConfig (JobIdRepo name (JobIdTree path tid) : sid) repo = do     when (isJust name) $ do         throwError $ OtherEvalError $ "expected default repo commit or tree id"     when (not (null path)) $ do         throwError $ OtherEvalError $ "expected root commit or tree id"     tree <- readTreeId repo path tid     config <- either fail return =<< loadConfigForCommit tree-    local (\ei -> ei { eiCurrentIdRev = JobIdTree Nothing (treeSubdir tree) (treeId tree) : eiCurrentIdRev ei }) $ do+    local (\ei -> ei { eiCurrentIdRev = JobIdRepo Nothing (JobIdTree (treeSubdir tree) (treeId tree)) : eiCurrentIdRev ei }) $ do         ( dset, idRev, otherRepos ) <- jobsetFromConfig sid config (Just tree)         return ( dset, idRev, ( Nothing, tree ) : otherRepos ) -jobsetFromCommitConfig (JobIdCommit name cid : sid) repo = do+jobsetFromCommitConfig (JobIdRepo name (JobIdCommit cid) : sid) repo = do     when (isJust name) $ do         throwError $ OtherEvalError $ "expected default repo commit or tree id"     tree <- getCommitTree =<< readCommitId repo cid-    jobsetFromCommitConfig (JobIdTree name (treeSubdir tree) (treeId tree) : sid) repo+    jobsetFromCommitConfig (JobIdRepo name (JobIdTree (treeSubdir tree) (treeId tree)) : sid) repo++jobsetFromCommitConfig (JobIdRepo name (JobIdTag cid _) : sid) repo = do+    when (isJust name) $ do+        throwError $ OtherEvalError $ "expected default repo commit or tree id"+    tree <- getCommitTree =<< readCommitId repo cid+    jobsetFromCommitConfig (JobIdRepo name (JobIdTree (treeSubdir tree) (treeId tree)) : sid) repo  jobsetFromCommitConfig (JobIdName name : _) _ = do     throwError $ OtherEvalError $ "expected commit or tree id, not a job name ‘" <> textJobName name <> "’"
+ src/Expr.hs view
@@ -0,0 +1,51 @@+module Expr (+    Expr(..),+    ExprContext(..),+    getContext,++    addDependency,+    collectDependencies,++    exprIO,+) where++import Data.Kind+++data Expr c a where+    Pure :: a -> Expr c a+    App :: Expr c (a -> b) -> Expr c a -> Expr c b+    GetContext :: Expr c c+    AddDependency :: ExprContext c => ExprDependency c -> Expr c a -> Expr c a+    ExprIO :: (a -> IO b) -> Expr c a -> Expr c b++instance Functor (Expr c) where+    fmap f x = Pure f <*> x++instance Applicative (Expr c) where+    pure = Pure+    (<*>) = App+++class Monoid (ExprDependency c) => ExprContext c where+    type ExprDependency c :: Type+++getContext :: Expr c c+getContext = GetContext+++addDependency :: ExprContext c => ExprDependency c -> Expr c a -> Expr c a+addDependency = AddDependency++collectDependencies :: ExprContext c => Expr c a -> ExprDependency c+collectDependencies = \case+    Pure {} -> mempty+    App f x -> collectDependencies f <> collectDependencies x+    GetContext {} -> mempty+    AddDependency d x -> d <> collectDependencies x+    ExprIO {} -> mempty+++exprIO :: (a -> IO b) -> Expr c a -> Expr c b+exprIO = ExprIO
src/Job.hs view
@@ -4,9 +4,10 @@     JobOutput(..),     JobName(..), stringJobName, textJobName,     ArtifactName(..),-    JobStatus(..),+    JobStatus(..), AnnotatedStatus,     jobStatusFinished, jobStatusFailed,     JobManager(..), newJobManager, cancelAllJobs,+    Task(..), TaskId, cancelTask,     runJobs, waitForRemainingTasks,      prepareJob,@@ -17,6 +18,9 @@      copyRecursive,     copyRecursiveForce,++    currentCommitExpr,+    branchExpr, ) where  import Control.Concurrent@@ -26,7 +30,9 @@ import Control.Monad.Catch import Control.Monad.Except import Control.Monad.IO.Class+import Control.Monad.Reader +import Data.Bifunctor import Data.List import Data.Map (Map) import Data.Map qualified as M@@ -43,11 +49,13 @@ import System.FilePath import System.FilePath.Glob import System.IO+import System.IO.Error import System.IO.Temp import System.Posix.Signals import System.Process  import Destination+import Expr import Job.Types import Output import Repo@@ -66,16 +74,17 @@     deriving (Eq)  -data JobStatus a = JobQueued-                 | JobDuplicate JobId (JobStatus a)-                 | JobPreviousStatus (JobStatus a)-                 | JobWaiting [JobName]-                 | JobRunning-                 | JobSkipped-                 | JobError OutputFootnote-                 | JobFailed-                 | JobCancelled-                 | JobDone a+data JobStatus a+    = JobQueued+    | JobDuplicate JobId (JobStatus a)+    | JobPreviousStatus (JobStatus a)+    | JobWaiting [JobName]+    | JobRunning+    | JobSkipped+    | JobError Text+    | JobFailed+    | JobCancelled+    | JobDone a     deriving (Eq)  jobStatusFinished :: JobStatus a -> Bool@@ -95,6 +104,12 @@     JobFailed      {}   -> True     _                   -> False +jobStatusCancelled :: JobStatus a -> Bool+jobStatusCancelled = \case+    JobCancelled {}  -> True+    JobDuplicate _ s -> jobStatusCancelled s+    _                -> False+ jobResult :: JobStatus a -> Maybe a jobResult = \case     JobDone x -> Just x@@ -115,12 +130,12 @@     JobCancelled -> "cancelled"     JobDone _ -> "done" -readJobStatus :: (MonadIO m) => Output -> Text -> m a -> m (Maybe (JobStatus a))-readJobStatus tout text readResult = case T.lines text of+readJobStatus :: (MonadIO m) => Text -> m a -> m (Maybe (JobStatus a))+readJobStatus text readResult = case T.lines text of     "queued" : _ -> return (Just JobQueued)     "running" : _ -> return (Just JobRunning)     "skipped" : _ -> return (Just JobSkipped)-    "error" : note : _ -> Just . JobError <$> liftIO (outputFootnote tout note)+    "error" : note : _ -> return (Just $ JobError note)     "failed" : _ -> return (Just JobFailed)     "cancelled" : _ -> return (Just JobCancelled)     "done" : _ -> Just . JobDone <$> readResult@@ -128,23 +143,47 @@  textJobStatusDetails :: JobStatus a -> Text textJobStatusDetails = \case-    JobError err -> footnoteText err <> "\n"+    JobError err -> err <> "\n"     JobPreviousStatus s -> textJobStatusDetails s     _ -> "" +printStatusError :: MonadIO m => Output -> JobStatus a -> m [ OutputFootnote ]+printStatusError tout = \case+    JobError note -> (: []) <$> liftIO (outputFootnote tout note)+    _ -> return [] + data JobManager = JobManager-    { jmSemaphore :: TVar Int+    { jmMaxRunningTasks :: Int     , jmDataDir :: FilePath-    , jmJobs :: TVar (Map JobId (TVar (JobStatus JobOutput)))+    , jmJobs :: TVar (Map JobId (TVar ManagedJobStatus))     , jmNextTaskId :: TVar TaskId-    , jmNextTask :: TVar (Maybe TaskId)     , jmReadyTasks :: TVar (Set TaskId)     , jmRunningTasks :: TVar (Map TaskId ThreadId)     , jmCancelled :: TVar Bool     , jmOpenStatusUpdates :: TVar Int     } +type AnnotatedStatus = ( JobStatus JobOutput, [ OutputFootnote ] )++data ManagedJobStatus = ManagedJobStatus+    { mjsStatus :: JobStatus JobOutput+    , mjsNotes :: [ OutputFootnote ]+    , mjsTaskCount :: Int+    , mjsThread :: Maybe ThreadId+    , mjsSuperseded :: Bool+    }++mjsAnnotatedStatus :: ManagedJobStatus -> AnnotatedStatus+mjsAnnotatedStatus ManagedJobStatus {..} = ( mjsStatus, mjsNotes )++data Task = Task+    { taskId :: TaskId+    , taskJob :: Job+    , taskManagedJob :: TVar ManagedJobStatus+    , taskStatus :: STM AnnotatedStatus+    }+ newtype TaskId = TaskId Int     deriving (Eq, Ord) @@ -154,12 +193,32 @@ instance Exception JobCancelledException  +newtype JobRun a = JobRun (ReaderT (Maybe Handle) (ExceptT (JobStatus JobOutput) IO) a)+  deriving+    ( Functor, Applicative, Monad+    , MonadReader (Maybe Handle)+    , MonadError (JobStatus JobOutput)+    , MonadThrow, MonadCatch, MonadMask+    , MonadIO+    )++instance MonadFail JobRun where+    fail err = do+        ask >>= \case+            Just logs -> do+                liftIO $ hPutStrLn logs err+                throwError JobFailed+            Nothing -> do+                throwError $ JobError $ T.pack err++fromJobRun :: JobRun a -> IO (Either (JobStatus JobOutput) a)+fromJobRun (JobRun act) = runExceptT $ flip runReaderT Nothing $ act++ newJobManager :: FilePath -> Int -> IO JobManager-newJobManager jmDataDir queueLen = do-    jmSemaphore <- newTVarIO queueLen+newJobManager jmDataDir jmMaxRunningTasks = do     jmJobs <- newTVarIO M.empty     jmNextTaskId <- newTVarIO (TaskId 0)-    jmNextTask <- newTVarIO Nothing     jmReadyTasks <- newTVarIO S.empty     jmRunningTasks <- newTVarIO M.empty     jmCancelled <- newTVarIO False@@ -174,6 +233,19 @@      mapM_ (`throwTo` JobCancelledException) threads +cancelTask :: Task -> IO ()+cancelTask Task {..} = do+    mbThread <- atomically $ do+        mjs <- readTVar taskManagedJob+        let count = mjsTaskCount mjs - 1+        writeTVar taskManagedJob mjs { mjsTaskCount = count }+        if count <= 0+          then return $ mjsThread mjs+          else return Nothing+    case mbThread of+        Just thread -> throwTo thread JobCancelledException+        Nothing -> return ()+ reserveTaskId :: JobManager -> STM TaskId reserveTaskId JobManager {..} = do     tid@(TaskId n) <- readTVar jmNextTaskId@@ -185,45 +257,37 @@     True -> cancel     False -> job   where-    acquire = liftIO $ do+    acquire = (`onException` release False) $ liftIO $ do         atomically $ do             writeTVar jmReadyTasks . S.insert tid =<< readTVar jmReadyTasks-            trySelectNext         threadId <- myThreadId         atomically $ do             readTVar jmCancelled >>= \case                 True -> return True-                False -> readTVar jmNextTask >>= \case-                    Just tid' | tid' == tid -> do-                        writeTVar jmNextTask Nothing-                        writeTVar jmRunningTasks . M.insert tid threadId =<< readTVar jmRunningTasks-                        return False+                False -> readTVar jmRunningTasks >>= \case+                    running | M.size running < jmMaxRunningTasks -> do+                        (S.minView <$> readTVar jmReadyTasks) >>= \case+                            Just ( tid', ready ) | tid' == tid -> do+                                writeTVar jmReadyTasks ready+                                writeTVar jmRunningTasks $ M.insert tid threadId running+                                return False+                            _ -> retry                     _ -> retry      release False = liftIO $ atomically $ do-        free <- readTVar jmSemaphore-        writeTVar jmSemaphore $ free + 1-        trySelectNext+        writeTVar jmReadyTasks . S.delete tid =<< readTVar jmReadyTasks+        writeTVar jmRunningTasks . M.delete tid =<< readTVar jmRunningTasks     release True = return () -    trySelectNext = do-        readTVar jmNextTask >>= \case-            Just _ -> return ()-            Nothing -> do-                readTVar jmSemaphore >>= \case-                    0   -> return ()-                    sem -> (S.minView <$> readTVar jmReadyTasks) >>= \case-                        Nothing -> return ()-                        Just ( tid', ready ) -> do-                            writeTVar jmReadyTasks ready-                            writeTVar jmSemaphore (sem - 1)-                            writeTVar jmNextTask (Just tid')-                            writeTVar jmRunningTasks . M.delete tid =<< readTVar jmRunningTasks +data PreviousManagedStatus+    = NewJob+    | DuplicateJob+    | RestartedJob  runJobs :: JobManager -> Output -> [ Job ]         -> (JobId -> JobStatus JobOutput -> Bool) -- ^ Rerun condition-        -> IO [ ( Job, TVar (JobStatus JobOutput) ) ]+        -> IO [ Task ] runJobs mngr@JobManager {..} tout jobs rerun = do     results <- atomically $ do         forM jobs $ \job -> do@@ -231,69 +295,115 @@             managed <- readTVar jmJobs             ( job, tid, ) <$> case M.lookup (jobId job) managed of                 Just origVar -> do-                    newTVar . JobDuplicate (jobId job) =<< readTVar origVar-+                    readTVar origVar >>= \mjs -> if+                        | mjsStatus mjs == JobCancelled || (mjsTaskCount mjs <= 0 && not (jobStatusFinished (mjsStatus mjs)))+                        -> do+                            -- Restart previously cancelled job+                            statusVar <- newTVar ManagedJobStatus+                                { mjsStatus = JobQueued+                                , mjsNotes = mjsNotes mjs+                                , mjsTaskCount = 1+                                , mjsThread = Nothing+                                , mjsSuperseded = False+                                }+                            writeTVar origVar mjs { mjsSuperseded = True }+                            writeTVar jmJobs $ M.insert (jobId job) statusVar managed+                            return ( RestartedJob, statusVar )+                        | otherwise -> do+                            writeTVar origVar mjs { mjsTaskCount = mjsTaskCount mjs + 1 }+                            return ( DuplicateJob, origVar )                 Nothing -> do-                    statusVar <- newTVar JobQueued+                    statusVar <- newTVar ManagedJobStatus+                        { mjsStatus = JobQueued+                        , mjsNotes = []+                        , mjsTaskCount = 1+                        , mjsThread = Nothing+                        , mjsSuperseded = False+                        }                     writeTVar jmJobs $ M.insert (jobId job) statusVar managed-                    return statusVar+                    return ( NewJob, statusVar ) -    forM_ results $ \( job, tid, outVar ) -> void $ forkIO $ do-        let handler e = do-                status <- if-                    | Just JobCancelledException <- fromException e -> do-                        return JobCancelled-                    | otherwise -> do-                        JobError <$> outputFootnote tout (T.pack $ displayException e)-                atomically $ writeTVar outVar status-                outputJobFinishedEvent tout job status-        handle handler $ do-            res <- runExceptT $ do-                duplicate <- liftIO $ atomically $ do-                    readTVar outVar >>= \case-                        JobDuplicate jid _ -> do-                            fmap ( jid, ) . M.lookup jid <$> readTVar jmJobs-                        _ -> do-                            return Nothing+    forM results $ \( taskJob, taskId, ( pms, taskManagedJob ) ) -> do+        case pms of+            DuplicateJob -> do+                let taskStatus = fmap (first (JobDuplicate (jobId taskJob))) $ mjsAnnotatedStatus <$> readTVar taskManagedJob+                outputEvent tout $ JobIsDuplicate (jobId taskJob)+                return Task {..} -                case duplicate of-                    Nothing -> do-                        let jdir = jmDataDir </> jobStorageSubdir (jobId job)-                        readStatusFile tout job jdir >>= \case-                            Just status | status /= JobCancelled && not (rerun (jobId job) status) -> do-                                let status' = JobPreviousStatus status-                                liftIO $ atomically $ writeTVar outVar status'-                                return status'-                            mbStatus -> do-                                when (isJust mbStatus) $ do-                                    liftIO $ removeDirectoryRecursive jdir-                                uses <- waitForUsedArtifacts tout job results outVar-                                runManagedJob mngr tid (return JobCancelled) $ do-                                    liftIO $ atomically $ writeTVar outVar JobRunning-                                    liftIO $ outputEvent tout $ JobStarted (jobId job)-                                    prepareJob jmDataDir job $ \checkoutPath -> do-                                        updateStatusFile mngr jdir outVar-                                        JobDone <$> runJob job uses checkoutPath jdir+            _ -> do+                let taskStatus = mjsAnnotatedStatus <$> readTVar taskManagedJob+                let handler e = do+                        ( status, notes ) <- if+                            | Just JobCancelledException <- fromException e -> do+                                return ( JobCancelled, [] )+                            | otherwise -> do+                                let err = T.pack $ displayException e+                                ( JobError err, ) . (: []) <$> outputFootnote tout err+                        join $ atomically $ do+                            mjs <- readTVar taskManagedJob+                            if jobStatusFinished (mjsStatus mjs)+                              then return $ return ()+                              else do+                                writeTVar taskManagedJob mjs { mjsStatus = status, mjsNotes = notes }+                                return $ do+                                    uninterruptibleMask_ $ do+                                        outputJobFinishedEvent tout taskJob status -                    Just ( jid, origVar ) -> do-                        let wait = do-                                status <- atomically $ do-                                    status <- readTVar origVar-                                    out <- readTVar outVar-                                    if status == out-                                      then retry-                                      else do-                                        writeTVar outVar $ JobDuplicate jid status-                                        return status-                                if jobStatusFinished status-                                  then return $ JobDuplicate jid status-                                  else wait-                        liftIO wait+                handlerInstalled <- newEmptyMVar+                void $ forkIO $ do+                    handle handler $ do+                        putMVar handlerInstalled ()+                        mtid <- myThreadId+                        res <- fromJobRun $ do+                            join $ liftIO $ atomically $ do+                                mjs <- readTVar taskManagedJob+                                if mjsTaskCount mjs <= 0+                                  then return $ throwError JobCancelled+                                  else do+                                      writeTVar taskManagedJob mjs { mjsThread = Just mtid }+                                      return $ return () -            atomically $ writeTVar outVar $ either id id res-            outputJobFinishedEvent tout job $ either id id res-    return $ map (\( job, _, var ) -> ( job, var )) results+                            let jdir = jmDataDir </> jobStorageSubdir (jobId taskJob)+                            pstatus <- case pms of+                                NewJob -> readStatusFile taskJob jdir+                                RestartedJob -> return (Just JobCancelled) +                            case pstatus of+                                Just status | status /= JobCancelled && not (rerun (jobId taskJob) status) -> do+                                    let status' = JobPreviousStatus status+                                    notes <- printStatusError tout status+                                    liftIO $ atomically $ do+                                        mjs <- readTVar taskManagedJob+                                        writeTVar taskManagedJob mjs { mjsStatus = status', mjsNotes = notes }+                                    return status'+                                mbStatus -> do+                                    when (isJust mbStatus) $ do+                                        liftIO $ removePathForcibly jdir+                                    liftIO $ outputEvent tout $ JobEnqueued (jobId taskJob)+                                    let extractResult ( tjob, tid, estatus ) = ( tjob, tid, fmap mjsAnnotatedStatus $ readTVar $ snd estatus )+                                    let results' = map extractResult results+                                    uses <- waitForUsedArtifacts taskJob results' taskManagedJob+                                    runManagedJob mngr taskId (return JobCancelled) $ do+                                        liftIO $ atomically $ do+                                            mjs <- readTVar taskManagedJob+                                            writeTVar taskManagedJob $ mjs { mjsStatus = JobRunning, mjsNotes = [] }+                                        liftIO $ outputEvent tout $ JobStarted (jobId taskJob)+                                        prepareJob jmDataDir taskJob $ \checkoutPath -> do+                                            updateStatusFile mngr jdir $ readTVar taskManagedJob+                                            JobDone <$> runJob taskJob uses checkoutPath jdir++                        let finalStatus = either id id res+                        mask_ $ do+                            rnotes <- either (printStatusError tout) (const $ return []) res+                            atomically $ do+                                mjs <- readTVar taskManagedJob+                                writeTVar taskManagedJob mjs+                                    { mjsStatus = finalStatus, mjsNotes = mjsNotes mjs ++ rnotes }+                            uninterruptibleMask_ $ do+                                outputJobFinishedEvent tout taskJob finalStatus+                takeMVar handlerInstalled+                return Task {..}+ waitForRemainingTasks :: JobManager -> IO () waitForRemainingTasks JobManager {..} = do     atomically $ do@@ -302,56 +412,64 @@  waitForUsedArtifacts     :: (MonadIO m, MonadError (JobStatus JobOutput) m)-    => Output -> Job-    -> [ ( Job, TaskId, TVar (JobStatus JobOutput) ) ]-    -> TVar (JobStatus JobOutput)+    => Job+    -> [ ( Job, TaskId, STM AnnotatedStatus ) ]+    -> TVar ManagedJobStatus     -> m [ ( ArtifactSpec Evaluated, ArtifactOutput ) ]-waitForUsedArtifacts tout job results outVar = do-    origState <- liftIO $ atomically $ readTVar outVar+waitForUsedArtifacts job results outVar = do+    ( origStatus, origNotes ) <- liftIO $ atomically $ mjsAnnotatedStatus <$> readTVar outVar     let ( selfSpecs, artSpecs ) = partition ((jobId job ==) . fst) $ jobRequiredArtifacts job      forM_ selfSpecs $ \( _, artName@(ArtifactName tname) ) -> do         when (not (artName `elem` map fst (jobArtifacts job))) $ do-            throwError . JobError =<< liftIO (outputFootnote tout $ "Artifact ‘" <> tname <> "’ not produced by the job")+            throwError $ JobError $ "Artifact ‘" <> tname <> "’ not produced by the job"      ujobs <- forM artSpecs $ \( ujobId, uartName ) -> do         case find (\( j, _, _ ) -> jobId j == ujobId) results of             Just ( _, _, var ) -> return ( var, ( ujobId, uartName ))-            Nothing -> throwError . JobError =<< liftIO (outputFootnote tout $ "Job ‘" <> textJobId ujobId <> "’ not found")+            Nothing -> throwError $ JobError $ "Job ‘" <> textJobId ujobId <> "’ not found"      let loop prev = do             ustatuses <- atomically $ do                 ustatuses <- forM ujobs $ \( uoutVar, uartSpec ) -> do-                    (, uartSpec) <$> readTVar uoutVar+                    (, uartSpec) <$> uoutVar                 when (Just (map fst ustatuses) == prev) retry                 let remains = map (fromMaybe (JobName "?") . lastJobNameId . fst . snd) $-                        filter (not . jobStatusFinished . fst) ustatuses-                writeTVar outVar $ if null remains then origState else JobWaiting remains+                        filter (not . jobStatusFinished . fst . fst) ustatuses+                mjs <- readTVar outVar+                writeTVar outVar $ if null remains+                    then mjs { mjsStatus = origStatus, mjsNotes = origNotes }+                    else mjs { mjsStatus = JobWaiting remains, mjsNotes = [] }                 return ustatuses-            if all (jobStatusFinished . fst) ustatuses+            if all (jobStatusFinished . fst . fst) ustatuses                then return ustatuses                else loop $ Just $ map fst ustatuses     ustatuses <- liftIO $ loop Nothing -    forM ustatuses $ \( ustatus, spec@( tjobId, uartName@(ArtifactName tartName)) ) -> do-        case jobResult ustatus of-            Just out -> case find ((==uartName) . aoutName) $ outArtifacts out of+    forM ustatuses $ \( ( ustatus, _ ), spec@( tjobId, uartName@(ArtifactName tartName)) ) -> if+        | Just out <- jobResult ustatus+        -> do+            case find ((==uartName) . aoutName) $ outArtifacts out of                 Just art -> return ( spec, art )-                Nothing -> throwError . JobError =<< liftIO (outputFootnote tout $ "Artifact ‘" <> textJobId tjobId <> "." <> tartName <> "’ not found")-            _ -> throwError JobSkipped+                Nothing -> throwError $ JobError $ "Artifact ‘" <> textJobId tjobId <> "." <> tartName <> "’ not found" +        | jobStatusCancelled ustatus+        -> throwError JobCancelled++        | otherwise+        -> throwError JobSkipped+ outputJobFinishedEvent :: Output -> Job -> JobStatus a -> IO () outputJobFinishedEvent tout job = \case-    JobDuplicate _ s    -> outputEvent tout $ JobIsDuplicate (jobId job) (textJobStatus s)     JobPreviousStatus s -> outputEvent tout $ JobPreviouslyFinished (jobId job) (textJobStatus s)     JobSkipped          -> outputEvent tout $ JobWasSkipped (jobId job)     s                   -> outputEvent tout $ JobFinished (jobId job) (textJobStatus s) -readStatusFile :: (MonadIO m, MonadCatch m) => Output -> Job -> FilePath -> m (Maybe (JobStatus JobOutput))-readStatusFile tout job jdir = do+readStatusFile :: (MonadIO m, MonadCatch m) => Job -> FilePath -> m (Maybe (JobStatus JobOutput))+readStatusFile job jdir = do     handleIOError (\_ -> return Nothing) $ do         text <- liftIO $ T.readFile (jdir </> "status")-        readJobStatus tout text $ do+        readJobStatus text $ do             artifacts <- forM (jobArtifacts job) $ \( aoutName@(ArtifactName tname), _ ) -> do                 let adir = jdir </> "artifacts" </> T.unpack tname                     aoutStorePath = adir </> "data"@@ -362,19 +480,20 @@                 { outArtifacts = artifacts                 } -updateStatusFile :: MonadIO m => JobManager -> FilePath -> TVar (JobStatus JobOutput) -> m ()-updateStatusFile JobManager {..} jdir outVar = liftIO $ do+updateStatusFile :: MonadIO m => JobManager -> FilePath -> STM ManagedJobStatus -> m ()+updateStatusFile JobManager {..} jdir getStatus = liftIO $ do     atomically $ writeTVar jmOpenStatusUpdates . (+ 1) =<< readTVar jmOpenStatusUpdates     void $ forkIO $ loop Nothing   where     loop prev = do-        status <- atomically $ do-            status <- readTVar outVar-            when (Just status == prev) retry-            return status-        T.writeFile (jdir </> "status") $ textJobStatus status <> "\n" <> textJobStatusDetails status-        if (not (jobStatusFinished status))-          then loop $ Just status+        ManagedJobStatus {..} <- atomically $ do+            mjs@ManagedJobStatus {..} <- getStatus+            when (Just mjsStatus == prev && not mjsSuperseded) retry+            return mjs+        when (not mjsSuperseded) $ do+            T.writeFile (jdir </> "status") $ textJobStatus mjsStatus <> "\n" <> textJobStatusDetails mjsStatus+        if not (jobStatusFinished mjsStatus) && not mjsSuperseded+          then loop $ Just mjsStatus           else atomically $ writeTVar jmOpenStatusUpdates . (subtract 1) =<< readTVar jmOpenStatusUpdates  jobStorageSubdir :: JobId -> FilePath@@ -389,7 +508,7 @@             checkoutAt subtree $ checkoutPath </> fromMaybe "" dest          liftIO $ forM_ (jobUses job) $ \( jid, aname ) -> do-            modifyError (userError . T.unpack) $ do+            either (throwError . userError . T.unpack) pure <=< runExceptT $ do                 wpath <- getArtifactWorkPath dir jid aname                 let target = checkoutPath </> wpath                 liftIO $ createDirectoryIfMissing True $ takeDirectory target@@ -425,39 +544,41 @@     liftIO $ copyRecursive (adir </> "data") tpath  -runJob :: Job -> [ ( ArtifactSpec Evaluated, ArtifactOutput) ] -> FilePath -> FilePath -> ExceptT (JobStatus JobOutput) IO JobOutput+runJob :: Job -> [ ( ArtifactSpec Evaluated, ArtifactOutput) ] -> FilePath -> FilePath -> JobRun JobOutput runJob job uses checkoutPath jdir = do-    bracket (liftIO $ openFile (jdir </> "log") WriteMode) (liftIO . hClose) $ \logs -> do+    bracket (liftIO $ openFile (jdir </> "log") WriteMode) (liftIO . hClose) $ \logs -> local (const $ Just logs) $ do         forM_ (fromMaybe [] $ jobRecipe job) $ \ep -> do             ( p, input ) <- case ep of                 Left p -> return ( p, "" )                 Right script -> do                     sh <- fromMaybe "/bin/sh" <$> liftIO (lookupEnv "SHELL")                     return ( proc sh [], script )-            (Just hin, _, _, hp) <- liftIO $ createProcess_ "" p+            ( Just hin, _, _, hp ) <- liftIO $ createProcess_ "" p                 { cwd = Just checkoutPath                 , std_in = CreatePipe                 , std_out = UseHandle logs                 , std_err = UseHandle logs+                , create_group = True                 }+            Just pid <- liftIO $ getPid hp             liftIO $ void $ forkIO $ do                 T.hPutStr hin input                 hClose hin-            liftIO (waitForProcess hp) >>= \case+            let killCreatedProcessGroup = do+                    handleJust (\case e | isDoesNotExistError e -> Just (); _ -> Nothing) return $ do+                        signalProcessGroup sigKILL pid+                    waitForProcess hp+            liftIO (waitForProcess hp `finally` killCreatedProcessGroup) >>= \case                 ExitSuccess -> return ()-                ExitFailure n-                    | fromIntegral n == -sigINT -> throwError JobCancelled-                    | otherwise -> throwError JobFailed+                ExitFailure _ -> throwError JobFailed          artifacts <- forM (jobArtifacts job) $ \( name@(ArtifactName tname), pathPattern ) -> do             let adir = jdir </> "artifacts" </> T.unpack tname             path <- liftIO (globDir1 pathPattern checkoutPath) >>= \case                 [ path ] -> return path-                found -> do-                    liftIO $ hPutStrLn logs $-                        (if null found then "no file" else "multiple files") <> " found matching pattern ‘" <>-                        decompile pathPattern <> "’ for artifact ‘" <> T.unpack tname <> "’"-                    throwError JobFailed+                found -> fail $+                    (if null found then "no file" else "multiple files") <> " found matching pattern ‘" <>+                    decompile pathPattern <> "’ for artifact ‘" <> T.unpack tname <> "’"             let target = adir </> "data"                 workPath = makeRelative checkoutPath path             liftIO $ do@@ -470,6 +591,9 @@                 , aoutStorePath = target                 } +        forM_ (jobPush job) $ \JobPush {..} -> do+            pushToBranch jpushDestination jpushSource+         forM_ (jobPublish job) $ \pub -> do             Just aout <- return $ lookup (jpArtifact pub) $ map (\aout -> ( ( jobId job, aoutName aout ), aout )) artifacts ++ uses             let ppath = case jpPath pub of@@ -482,3 +606,19 @@         return JobOutput             { outArtifacts = artifacts             }++++currentCommitExpr :: RepoName -> Expr JobSetContext Commit+currentCommitExpr rname =+    addDependency [ RepoDependency rname RepoDepCommit ] $+        (pure getCommit) <*> (lookup (Just rname) . jscRepoRefs <$> GetContext)+  where+    getCommit = \case+        Nothing -> error $ "currentCommitExpr: repo ‘" <> showRepoName rname <> "’ not found"+        Just (RepoRefTree _) -> error $ "currentCommitExpr: expected commit in ‘" <> showRepoName rname <> "’, but got a tree"+        Just (RepoRefCommit commit) -> commit+        Just (RepoRefTag commit _) -> commit++branchExpr :: RepoName -> Text -> Expr JobSetContext Branch+branchExpr rname bname = pure ((\repo -> Branch repo bname) . fromJust) <*> (lookup (Just rname) . jscRepos <$> GetContext)
src/Job/Types.hs view
@@ -1,21 +1,30 @@ module Job.Types where +import Control.Monad.IO.Class+ import Data.Containers.ListUtils import Data.Kind import Data.Text (Text) import Data.Text qualified as T +import System.FilePath import System.FilePath.Glob import System.Process  import {-# SOURCE #-} Config import Destination+import Expr import Repo   data Declared data Evaluated +type family ExprD d c a :: Type where+    ExprD Declared c a = Expr c a+    ExprD Evaluated c a = a++ data Job' d = Job     { jobId :: JobId' d     , jobName :: JobName@@ -24,6 +33,7 @@     , jobArtifacts :: [ ( ArtifactName, Pattern ) ]     , jobUses :: [ ArtifactSpec d ]     , jobPublish :: [ JobPublish d ]+    , jobPush :: [ JobPush d ]     }  type Job = Job' Evaluated@@ -66,13 +76,24 @@     , jpPath :: Maybe FilePath     } +data JobPush d = JobPush+    { jpushSource :: ExprD d JobSetContext Commit+    , jpushDestination :: ExprD d JobSetContext Branch+    } + data ArtifactName = ArtifactName Text     deriving (Eq, Ord, Show)  type ArtifactSpec d = ( JobId' d, ArtifactName ) +stringArtifactName :: ArtifactName -> String+stringArtifactName (ArtifactName name) = T.unpack name +textArtifactName :: ArtifactName -> Text+textArtifactName (ArtifactName name) = name++ data JobSet' d = JobSet     { jobsetId :: JobSetId' d     , jobsetConfig :: Maybe Config@@ -100,35 +121,60 @@  data JobIdPart     = JobIdName JobName-    | JobIdCommit (Maybe RepoName) CommitId-    | JobIdTree (Maybe RepoName) FilePath TreeId+    | JobIdRepo (Maybe RepoName) JobIdRepoPart     deriving (Eq, Ord) +data JobIdRepoPart+    = JobIdTree FilePath TreeId+    | JobIdCommit CommitId+    | JobIdTag CommitId TagId+    deriving (Eq, Ord)+ newtype JobRef = JobRef [ Text ]     deriving (Eq, Ord)  textJobIdPart :: JobIdPart -> Text textJobIdPart = \case     JobIdName name -> textJobName name-    JobIdCommit _ cid -> textCommitId cid-    JobIdTree _ _ tid -> textTreeId tid+    JobIdRepo _ (JobIdTree _ tid) -> textTreeId tid+    JobIdRepo _ (JobIdCommit cid) -> textCommitId cid+    JobIdRepo _ (JobIdTag cid tid) -> textCommitId cid <> "^" <> textTagId tid  textJobId :: JobId -> Text-textJobId (JobId ids) = T.intercalate "." $ map textJobIdPart ids+textJobId (JobId ids) = T.intercalate ":" $ map textJobIdPart ids +textJobSetId :: JobSetId -> Text+textJobSetId (JobSetId ids) = T.intercalate ":" $ map textJobIdPart ids+ parseJobRef :: Text -> JobRef-parseJobRef = JobRef . go 0 ""+parseJobRef = JobRef . parseJobRefParts++parseJobRefParts :: Text -> [ Text ]+parseJobRefParts = go [ ':', '.' ] 0 False ""   where-    go :: Int -> Text -> Text -> [ Text ]-    go plevel cur s = do+    go :: [ Char ] -> Int -> Bool -> Text -> Text -> [ Text ]+    go seps plevel pdrop cur s = do         let bchars | plevel > 0 = [ '(', ')' ]-                   | otherwise  = [ '.', '(', ')' ]+                   | otherwise  = seps ++ [ '(', ')' ]         let ( part, rest ) = T.break (`elem` bchars) s         case T.uncons rest of-            Just ( '.', rest' ) -> (cur <> part) : go plevel "" rest'-            Just ( '(', rest' ) -> go (plevel + 1) (cur <> part) rest'-            Just ( ')', rest' ) -> go (plevel - 1) (cur <> part) rest'-            _                   -> [ cur <> part ]+            Just ( '.', rest' )+                | Just ( '.', rest'' ) <- T.uncons rest'+                -> go seps plevel pdrop (cur <> part <> "..") rest''+            Just ( sep, rest' )+                | sep `elem` seps+                -> (cur <> part) : go [ sep ] plevel pdrop "" rest'+            Just ( '(', rest' )+                | T.null cur && T.null part+                -> go seps (plevel + 1) True (cur <> part) rest'+                | otherwise+                -> go seps (plevel + 1) pdrop (cur <> part <> "(") rest'+            Just ( ')', rest' )+                | T.null rest' && pdrop+                -> go seps (plevel - 1) False (cur <> part) rest'+                | otherwise+                -> go seps (plevel - 1) pdrop (cur <> part <> ")") rest'+            _   -> [ cur <> part ]  lastJobNameId :: JobId -> Maybe JobName lastJobNameId (JobId ids) = go Nothing ids@@ -136,3 +182,65 @@     go _ (JobIdName name : rest) = go (Just name) rest     go cur (_ : rest) = go cur rest     go cur [] = cur+++data JobSetDep+    = SiblingJobDependency JobName+    | RepoDependency RepoName RepoDepLevel++data RepoDepLevel+    = RepoDepSubtree FilePath+    | RepoDepCommit+    | RepoDepTag++instance Semigroup RepoDepLevel where+    RepoDepTag <> _ = RepoDepTag+    _ <> RepoDepTag = RepoDepTag++    RepoDepCommit <> _ = RepoDepCommit+    _ <> RepoDepCommit = RepoDepCommit++    RepoDepSubtree path <> RepoDepSubtree path' = RepoDepSubtree $+        joinPath $ commonPrefix (splitDirectories path) (splitDirectories path')+      where+        commonPrefix (x : xs) (y : ys) | x == y = x : commonPrefix xs ys+        commonPrefix _        _                 = []++repoDepPath :: RepoDepLevel -> FilePath+repoDepPath = \case+    RepoDepSubtree path -> path+    RepoDepCommit -> ""+    RepoDepTag -> ""+++data RepoRef+    = RepoRefTree Tree+    | RepoRefCommit Commit+    | RepoRefTag Commit (Tag Commit)++repoRefRepo :: RepoRef -> Repo+repoRefRepo = \case+    RepoRefTree tree -> treeRepo tree+    RepoRefCommit commit -> commitRepo commit+    RepoRefTag commit _ -> commitRepo commit++repoRefTree :: (MonadIO m, MonadFail m) => RepoRef -> m Tree+repoRefTree = \case+    RepoRefTree tree -> return tree+    RepoRefCommit commit -> getCommitTree commit+    RepoRefTag commit _ -> getCommitTree commit++repoRefToIdPart :: MonadIO m => RepoRef -> m JobIdRepoPart+repoRefToIdPart = \case+    RepoRefTree tree -> return $ JobIdTree (treeSubdir tree) (treeId tree)+    RepoRefCommit commit -> return $ JobIdCommit (commitId commit)+    RepoRefTag commit tag -> return $ JobIdTag (commitId commit) (tagId tag)+++data JobSetContext = JobSetContext+    { jscRepos :: [ ( Maybe RepoName, Repo ) ]+    , jscRepoRefs :: [ ( Maybe RepoName, RepoRef ) ]+    }++instance ExprContext JobSetContext where+    type ExprDependency JobSetContext = [ JobSetDep ]
src/Main.hs view
@@ -62,16 +62,11 @@         (ReqArg (\num opts -> return opts { optCommon = (optCommon opts) { optJobs = read num }}) "<num>")         ("number of jobs to run simultaneously (default " <> show (optJobs defaultCommonOptions) <> ")")     , Option [] [ "repo" ]-        (ReqArg (\value opts ->-            case span (/= ':') value of-                ( repo, ':' : path ) -> return opts-                    { optCommon = (optCommon opts)-                        { optRepo = ( RepoName $ T.pack repo, path ) : optRepo (optCommon opts)-                        }-                    }-                _ -> throwError $ "--repo: invalid value ‘" <> value <> "’"-        ) "<repo>:<path>")+        (repoOption "repo" False)         ("override or declare repo path")+    , Option [] [ "writable-repo" ]+        (repoOption "writable-repo" True)+        ("override or declare repo path and open it as writable")     , Option [] [ "destination" ]         (ReqArg (\value opts ->             case span (/= ':') value of@@ -97,6 +92,18 @@         "use test-style output to <path> or standard output"     ] +  where+    repoOption optname writable =+        (ReqArg (\value opts ->+            case span (/= ':') value of+                ( repo, ':' : path ) -> return opts+                    { optCommon = (optCommon opts)+                        { optRepo = ( RepoName $ T.pack repo, ( writable, path ) ) : optRepo (optCommon opts)+                        }+                    }+                _ -> throwError $ "--" <> optname <> ": invalid value ‘" <> value <> "’"+        ) "<repo>:<path>")+ data SomeCommandType = forall c. Command c => SC (Proxy c)  commands :: NE.NonEmpty SomeCommandType@@ -212,12 +219,12 @@                     Right config -> return ( path, JobRootConfig config )                     Left err -> reportFailure $ "Failed to parse job file ‘" <> path <> "’:" <> err                 False -> doesDirectoryExist path >>= \case-                    True -> openRepo path >>= \case+                    True -> openRepo False path >>= \case                         Just repo -> return ( path, JobRootRepo repo )                         Nothing -> reportFailure $ "Failed to open repository ‘" <> path <> "’"                     False -> reportFailure $ "File or directory ‘" <> path <> "’ not found"         Nothing -> do-            openRepo "." >>= \case+            openRepo False "." >>= \case                 Just repo -> return ( ".", JobRootRepo repo )                 Nothing -> findConfig >>= \case                     Just path -> BL.readFile path >>= return . parseConfig >>= \case@@ -253,11 +260,11 @@      ciContainingRepo <- case ciJobRoot of         JobRootRepo repo -> return (Just repo)-        JobRootConfig _  -> openRepo $ takeDirectory ciRootPath+        JobRootConfig _  -> openRepo False $ takeDirectory ciRootPath -    let openDeclaredRepo dir ( name, dpath ) = do+    let openDeclaredRepo dir ( name, ( writable, dpath ) ) = do             let path = dir </> dpath-            openRepo path >>= \case+            openRepo writable path >>= \case                 Just repo -> return ( name, repo )                 Nothing -> do                     absPath <- makeAbsolute path@@ -272,7 +279,7 @@                     Just repo -> return ( repoName decl, repo )                     Nothing                         | Just path <- repoPath decl-                        -> openDeclaredRepo (takeDirectory ciRootPath) ( repoName decl, path )+                        -> openDeclaredRepo (takeDirectory ciRootPath) ( repoName decl, ( repoWritable decl, path ) )                          | otherwise                         -> do
src/Output.hs view
@@ -3,6 +3,7 @@     OutputType(..),     OutputEvent(..),     OutputFootnote(..),+    MonadOutput(..),      withOutput,     outputTerminal,@@ -42,11 +43,13 @@     = OutputMessage Text     | TestMessage Text     | LogMessage Text+    | JobEnqueued JobId     | JobStarted JobId     | JobFinished JobId Text-    | JobIsDuplicate JobId Text+    | JobIsDuplicate JobId     | JobPreviouslyFinished JobId Text     | JobWasSkipped JobId+    | RunInterruptedByUser  data OutputFootnote = OutputFootnote     { footnoteText :: Text@@ -55,6 +58,10 @@     deriving (Eq)  +class Monad m => MonadOutput m where+    getOutput :: m Output++ withOutput :: [ OutputType ] -> (Output -> IO a) -> IO a withOutput types inner = do     lock <- newMVar ()@@ -104,6 +111,9 @@     LogMessage msg -> do         forM_ outLogs $ \h -> outStrLn out h msg +    JobEnqueued jid -> do+        forM_ outTest $ \h -> outStrLn out h ("job-enqueue " <> textJobId jid)+     JobStarted jid -> do         forM_ outLogs $ \h -> outStrLn out h ("Started " <> textJobId jid)         forM_ outTest $ \h -> outStrLn out h ("job-start " <> textJobId jid)@@ -112,9 +122,9 @@         forM_ outLogs $ \h -> outStrLn out h ("Finished " <> textJobId jid <> " (" <> status <> ")")         forM_ outTest $ \h -> outStrLn out h ("job-finish " <> textJobId jid <> " " <> status) -    JobIsDuplicate jid status -> do-        forM_ outLogs $ \h -> outStrLn out h ("Duplicate " <> textJobId jid <> " (" <> status <> ")")-        forM_ outTest $ \h -> outStrLn out h ("job-duplicate " <> textJobId jid <> " " <> status)+    JobIsDuplicate jid -> do+        forM_ outLogs $ \h -> outStrLn out h ("Duplicate " <> textJobId jid)+        forM_ outTest $ \h -> outStrLn out h ("job-duplicate " <> textJobId jid)      JobPreviouslyFinished jid status -> do         forM_ outLogs $ \h -> outStrLn out h ("Previously finished " <> textJobId jid <> " (" <> status <> ")")@@ -123,6 +133,11 @@     JobWasSkipped jid -> do         forM_ outLogs $ \h -> outStrLn out h ("Skipped " <> textJobId jid)         forM_ outTest $ \h -> outStrLn out h ("job-skip " <> textJobId jid)++    RunInterruptedByUser -> do+        forM_ outTerminal $ \term -> void $ newLine term "\rInterrupted by user"+        forM_ outLogs $ \h -> outStrLn out h "Interrupted by user"+        forM_ outTest $ \h -> outStrLn out h "run-user-interrupt"  outputFootnote :: Output -> Text -> IO OutputFootnote outputFootnote out@Output {..} footnoteText = do
+ src/Range.hs view
@@ -0,0 +1,358 @@+module Range (+    DeclaredRef(..),+    StaticRef',+    WatchedRef(..),+    WatchedRef',+    TagPattern(..),++    RevisionExpression'(..), RevisionExpression, DeclaredRevisionExpression,+    RangeExpression'(..), RangeExpression, DeclaredRangeExpression,+    CommitRange(..),+    evaluateDeclaredRevision, evaluateDeclaredRange,+    evaluateRevision, evaluateRange,+    getCommitFromRef,+    getRangeCommits, getAddedRangeCommits,++    isRangeExpressionDynamic,+    isRevisionExpressionDynamic,++    parseRangeExpression,+) where++import Control.Concurrent.STM+import Control.Monad+import Control.Monad.IO.Class++import Data.Bifunctor+import Data.Char+import Data.Function+import Data.Kind+import Data.List+import Data.List.NonEmpty qualified as NE+import Data.Maybe+import Data.Proxy+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.LocalTime+import Data.Void++import Text.Megaparsec+import Text.Megaparsec.Char++import System.FilePath.Glob as Glob+import System.IO.Error++import Job.Types+import Output+import Repo+++data DeclaredRef+    = TextRef Text+    | UpstreamRef Text+    | TagRef Pattern (Tag Commit -> Tag Commit -> Tag Commit)++type family StaticRef' d :: Type where+    StaticRef' Declared = DeclaredRef+    StaticRef' Evaluated = Commit++data WatchedRef+    = BranchRef (STM (Maybe Commit))+    | WatchedTagRef (WatchedTags (Tag Commit))++type family WatchedRef' d :: Type where+    WatchedRef' Declared = DeclaredRef+    WatchedRef' Evaluated = WatchedRef+++type family StaticTags' d :: Type where+    StaticTags' Declared = Pattern+    StaticTags' Evaluated = [ Tag Commit ]++data WatchedTags a = WatchedTags+    { wtPattern :: Pattern+    , wtUpdate :: Tag Commit -> a -> a+    , wtValue :: TVar a+    , wtChan :: TChan (Tag Commit)+    }++data TagPattern = TagPattern+    { tpPattern :: Pattern+    , tpOnlyNew :: Bool+    }++type family WatchedTags' d :: Type where+    WatchedTags' Declared = TagPattern+    WatchedTags' Evaluated = WatchedTags [ Tag Commit ]+++data RevisionExpression' d+    = StaticRef (StaticRef' d)+    | WatchedRef (WatchedRef' d)+    | ModifiedRevision Text (RevisionExpression' d)++type RevisionExpression = RevisionExpression' Evaluated+type DeclaredRevisionExpression = RevisionExpression' Declared++watchedRevision :: DeclaredRevisionExpression -> DeclaredRevisionExpression+watchedRevision = \case+    StaticRef r -> WatchedRef r+    WatchedRef r -> WatchedRef r+    ModifiedRevision m r -> ModifiedRevision m (watchedRevision r)+++data RangeExpression' d+    = SingleRevisionExpression (RevisionExpression' d)+    | RangeExpression (RevisionExpression' d) {- tip -} (RevisionExpression' d) {- except -}+    | StaticTagsExpression (StaticTags' d)+    | WatchedTagsExpression (WatchedTags' d)++type RangeExpression = RangeExpression' Evaluated+type DeclaredRangeExpression = RangeExpression' Declared++watchedRange :: DeclaredRangeExpression -> DeclaredRangeExpression+watchedRange = \case+    SingleRevisionExpression rev -> SingleRevisionExpression (watchedRevision rev)+    RangeExpression r1 r2 -> RangeExpression (watchedRevision r1) (watchedRevision r2)+    StaticTagsExpression pat -> WatchedTagsExpression TagPattern { tpOnlyNew = False, tpPattern = pat }+    WatchedTagsExpression pat -> WatchedTagsExpression pat+++data CommitRef = CommitRef Text {- suffix -} CommitId+    deriving (Eq)++data CommitRange+    = EmptyCommitRange+    | CommitRange CommitRef {- tip -} CommitRef {- except -}+    | CommitSet [ CommitRef ]+    deriving (Eq)++textCommitRef :: CommitRef -> Text+textCommitRef (CommitRef suffix cid) = textCommitId cid <> suffix+++evaluateDeclaredRevision :: (MonadIO m, MonadFail m, MonadOutput m) => Repo -> DeclaredRevisionExpression -> m RevisionExpression+evaluateDeclaredRevision repo = \case+    StaticRef (TextRef ref) -> StaticRef <$> readCommit repo ref+    StaticRef (UpstreamRef ref) ->+        findUpstreamRef repo ref >>= \case+            Just uref -> evaluateDeclaredRevision repo $ StaticRef (TextRef uref)+            Nothing -> fail $ "no upstream ref found for ‘" <> T.unpack ref <> "’ in ‘" <> show repo <> "’"+    StaticRef (TagRef pat sel) -> do+        filter (Glob.match pat . T.unpack . tagTag) <$> listTags repo >>= \case+            [] -> fail $ "no tag matching " <> show (decompile pat) <> " found"+            ts -> return $ StaticRef $ tagObject $ foldl1' sel ts++    WatchedRef (TextRef ref) -> do+        watchBranch repo ref >>= \case+            Right watched -> do+                output <- getOutput+                outputEvent output $ TestMessage $ "watch-branch-started " <> ref+                return $ WatchedRef $ BranchRef watched+            Left commit -> do+                return $ StaticRef commit++    WatchedRef (UpstreamRef ref) ->+        findUpstreamRef repo ref >>= \case+            Just uref -> evaluateDeclaredRevision repo $ WatchedRef (TextRef uref)+            Nothing -> fail $ "no upstream ref found for ‘" <> T.unpack ref <> "’ in ‘" <> show repo <> "’"++    WatchedRef (TagRef wtPattern wtUpdate) -> do+        wtChan <- watchTags repo+        value <- filter (Glob.match wtPattern . T.unpack . tagTag) <$> listTags repo >>= \case+            [] -> fail $ "no tag matching " <> show (decompile wtPattern) <> " found"+            ts -> return $ foldl1' wtUpdate ts+        wtValue <- liftIO $ newTVarIO value+        return $ WatchedRef $ WatchedTagRef WatchedTags {..}++    ModifiedRevision suffix rev -> ModifiedRevision suffix <$> evaluateDeclaredRevision repo rev++evaluateDeclaredRange :: (MonadIO m, MonadFail m, MonadOutput m) => Repo -> DeclaredRangeExpression -> m RangeExpression+evaluateDeclaredRange repo = \case+    SingleRevisionExpression a ->+        SingleRevisionExpression <$> evaluateDeclaredRevision repo a+    RangeExpression a b ->+        RangeExpression <$> evaluateDeclaredRevision repo a <*> evaluateDeclaredRevision repo b+    StaticTagsExpression pat ->+        StaticTagsExpression . filter (Glob.match pat . T.unpack . tagTag) <$> listTags repo+    WatchedTagsExpression TagPattern {..} -> do+        let wtPattern = tpPattern+        wtChan <- watchTags repo+        value <- if tpOnlyNew+            then return []+            else filter (Glob.match wtPattern . T.unpack . tagTag) <$> listTags repo+        wtValue <- liftIO $ newTVarIO value+        let wtUpdate = (:)+        output <- getOutput+        outputEvent output $ TestMessage $ "watch-tags-started " <> T.pack (decompile wtPattern)+        return $ WatchedTagsExpression WatchedTags {..}++evaluateRevision :: RevisionExpression -> STM (Maybe CommitRef)+evaluateRevision = \case+    StaticRef commit -> return $ Just $ CommitRef "" $ commitId commit+    WatchedRef (BranchRef getter) -> fmap (CommitRef "" . commitId) <$> getter+    WatchedRef (WatchedTagRef wt) -> Just . CommitRef "" . commitId . tagObject <$> updateWatchedTags wt+    ModifiedRevision suffix rev ->+        fmap (\(CommitRef suffix' ref) -> CommitRef (suffix' <> suffix) ref) <$> evaluateRevision rev++evaluateRange :: RangeExpression -> STM CommitRange+evaluateRange = \case+    SingleRevisionExpression revExpr -> do+        rev <- evaluateRevision revExpr+        return $ fromMaybe EmptyCommitRange $ CommitSet . (: []) <$> rev+    RangeExpression tipExpr exceptExpr -> do+        tip <- evaluateRevision tipExpr+        except <- evaluateRevision exceptExpr+        return $ fromMaybe EmptyCommitRange $ CommitRange <$> tip <*> except+    StaticTagsExpression tags -> do+        return $ CommitSet $ map (CommitRef "" . commitId . tagObject) tags+    WatchedTagsExpression wt -> do+        CommitSet . map (CommitRef "" . commitId . tagObject) <$> updateWatchedTags wt++getCommitFromRef :: MonadIO m => Repo -> CommitRef -> m (Maybe Commit)+getCommitFromRef repo = liftIO . tryReadCommit repo . textCommitRef++getCommitIdFromRef :: MonadIO m => Repo -> CommitRef -> m (Maybe CommitId)+getCommitIdFromRef repo = fmap (fmap commitId) . getCommitFromRef repo++getRangeCommits :: MonadIO m => Repo -> CommitRange -> m [ Commit ]+getRangeCommits repo = \case+    EmptyCommitRange -> do+        return []+    CommitRange tip except -> do+        tipId <- getCommitIdFromRef repo tip+        excId <- getCommitIdFromRef repo except+        listCommitsFrom repo (catMaybes [ tipId ]) (catMaybes [ excId ])+    CommitSet refs -> do+        return . catMaybes . map (either (const Nothing) Just) =<<+            mapM (liftIO . tryIOError . readCommitId repo) . catMaybes =<<+                mapM (getCommitIdFromRef repo) refs++getAddedRangeCommits :: MonadIO m => Repo -> CommitRange -> CommitRange -> m [ Commit ]+getAddedRangeCommits _    _ EmptyCommitRange = return []+getAddedRangeCommits repo EmptyCommitRange r = getRangeCommits repo r+getAddedRangeCommits repo (CommitRange ar br) (CommitRange ar' br') = do+    a <- getCommitIdFromRef repo ar+    b <- getCommitIdFromRef repo br+    a' <- getCommitIdFromRef repo ar'+    b' <- getCommitIdFromRef repo br'+    a'b <- fmap (map commitId) $ mergeBase repo $ catMaybes [ a', b ]+    (++)+        <$> listCommitsFrom repo a'b (catMaybes [ b' ]) -- added by moving B to B'+        <*> listCommitsFrom repo (catMaybes [ a' ]) (catMaybes [ a, b, b' ]) -- added by moving A to A'+getAddedRangeCommits repo prev cur = do+    prevList <- getRangeCommits repo prev+    curList <- getRangeCommits repo cur+    return $ filter (not . (`elem` prevList)) curList+++isRangeExpressionDynamic :: RangeExpression -> Bool+isRangeExpressionDynamic = \case+    SingleRevisionExpression x -> isRevisionExpressionDynamic x+    RangeExpression x y -> isRevisionExpressionDynamic x || isRevisionExpressionDynamic y+    StaticTagsExpression {} -> False+    WatchedTagsExpression {} -> True++isRevisionExpressionDynamic :: RevisionExpression -> Bool+isRevisionExpressionDynamic = \case+    StaticRef _ -> False+    WatchedRef _ -> True+    ModifiedRevision _ e -> isRevisionExpressionDynamic e++updateWatchedTags :: WatchedTags a -> STM a+updateWatchedTags wt@WatchedTags {..} = do+    tryReadTChan wtChan >>= \case+        Nothing -> readTVar wtValue+        Just tag -> do+            when (Glob.match wtPattern $ T.unpack $ tagTag tag) $ do+                writeTVar wtValue . (wtUpdate tag) =<< readTVar wtValue+            updateWatchedTags wt+++type RangeParser = Parsec Void Text++parseRangeExpression :: Text -> Either String DeclaredRangeExpression+parseRangeExpression = bimap errorBundlePretty id . runParser parser ""+  where+    parser :: RangeParser DeclaredRangeExpression+    parser = do+        range <- parseRange+        eof+        return range++    parseRange :: RangeParser DeclaredRangeExpression+    parseRange = do+        range <- parseRevision+        choice+          [ do+              SingleRevisionExpression rev1 <- return range+              _ <- string ".."+              SingleRevisionExpression rev2 <- parseRevision+              return $ RangeExpression rev2 rev1+          , do+              return range+          ]++    parseTextRef :: RangeParser Text+    parseTextRef = do+        fmap T.concat $ some $ choice+            [ takeWhile1P Nothing (\x -> isAlphaNum x || x `elem` [ '_', '-', '/' ])+            , try $ string "." <* notFollowedBy (char '.')+            ]++    parseRevision :: RangeParser DeclaredRangeExpression+    parseRevision = do+        tok <- parseTextRef++        range <- choice+            [ between (char '(') (char ')') $ do+                case tok of+                    "watch" -> watchedRange <$> parseRange+                    "tags" -> StaticTagsExpression <$> parseTagPattern+                    "newtags" -> do+                        tpPattern <- parseTagPattern+                        let tpOnlyNew = True+                        return $ WatchedTagsExpression TagPattern {..}+                    "highesttag" -> do+                        pat <- parseTagPattern+                        return $ SingleRevisionExpression $ StaticRef $ TagRef pat higherTag+                    "lasttag" -> do+                        pat <- parseTagPattern+                        return $ SingleRevisionExpression $ StaticRef $ TagRef pat laterTag+                    "upstream" -> do+                        ref <- parseTextRef+                        return $ SingleRevisionExpression $ StaticRef $ UpstreamRef ref+                    _ -> unexpected $ Tokens $ NE.fromList $ chunkToTokens @Text Proxy tok++            , do+                return $ SingleRevisionExpression $ StaticRef $ TextRef tok+            ]++        choice+            [ do+                SingleRevisionExpression rev <- return range+                suffix <- takeWhile1P Nothing (\x -> isNumber x || x `elem` [ '~', '^', '@', '{', '}' ])+                return $ SingleRevisionExpression $ ModifiedRevision suffix rev+            , do+                return range+            ]++    parseTagPattern = compile . T.unpack <$> takeWhile1P Nothing (\x -> isAlphaNum x || x `elem` [ '_', '-', '.', '[', ']', '*', '?' ])+++higherTag :: Tag a -> Tag a -> Tag a+higherTag t t'+    | components t < components t' = t'+    | otherwise                    = t+  where+    components = map component . T.groupBy ((==) `on` isDigit) . tagTag+    component s+        | Just ( c, _ ) <- T.uncons s, isDigit c+        = Left $ read @Integer $ T.unpack s+        | otherwise+        = Right s++laterTag :: Tag a -> Tag a -> Tag a+laterTag t t'+    | zonedTimeToUTC (tagTime t) < zonedTimeToUTC (tagTime t') = t'+    | otherwise                                                = t
src/Repo.hs view
@@ -2,18 +2,22 @@     Repo, getRepoWorkDir,     DeclaredRepo(..),     RepoName(..), textRepoName, showRepoName,-    Commit, commitId,+    Commit, commitId, commitRepo,     CommitId, textCommitId, showCommitId,     Tree, treeId, treeRepo, treeSubdir,     TreeId, textTreeId, showTreeId,     Tag(..),+    TagId, textTagId, showTagId,+    Branch(..),      openRepo,     readCommit, readCommitId, tryReadCommit,     readTree, readTreeId, tryReadTree,     readBranch,-    readTag,-    listCommits,+    readTag, tryReadTag,+    listCommits, listCommitsFrom,+    listTags,+    mergeBase,     findUpstreamRef,      getCommitTree,@@ -25,6 +29,7 @@     checkoutAt,     createWipCommit,     readCommittedFile,+    pushToBranch,      watchBranch,     watchTags,@@ -47,6 +52,8 @@ import Data.Text (Text) import Data.Text qualified as T import Data.Text.Encoding+import Data.Time.Format+import Data.Time.LocalTime  import System.Environment import System.Exit@@ -59,9 +66,9 @@ data Repo     = GitRepo         { gitDir :: FilePath+        , gitWritable :: Bool         , gitLock :: MVar ()-        , gitInotify :: MVar (Maybe ( INotify, TChan (Tag Commit) ))-        , gitWatchedBranches :: MVar (Map Text [ TVar (Maybe Commit) ])+        , gitInotify :: MVar (Maybe GitInotify)         }  instance Show Repo where@@ -73,6 +80,7 @@ data DeclaredRepo = DeclaredRepo     { repoName :: RepoName     , repoPath :: Maybe FilePath+    , repoWritable :: Bool     }  newtype RepoName = RepoName Text@@ -104,14 +112,23 @@     { treeRepo :: Repo -- ^ Repository in which the tree is tored     , treeId :: TreeId -- ^ Tree ID     , treeSubdir :: FilePath -- ^ Subdirectory represented by this tree (from the repo root)+    , treeIsDir :: Bool     }  data Tag a = Tag     { tagTag :: Text+    , tagId :: TagId     , tagObject :: a+    , tagTagger :: Text+    , tagTime :: ZonedTime     , tagMessage :: Text     } +data Branch = Branch+    { branchRepo :: Repo+    , branchName :: Text+    }+ instance Eq Repo where     (==) = (==) `on` gitLock @@ -138,20 +155,28 @@ showTreeId :: TreeId -> String showTreeId (TreeId tid) = BC.unpack tid +newtype TagId = TagId ByteString+    deriving (Eq, Ord) +textTagId :: TagId -> Text+textTagId (TagId tid) = decodeUtf8 tid++showTagId :: TagId -> String+showTagId (TagId tid) = BC.unpack tid++ runGitCommand :: MonadIO m => Repo -> [ String ] -> m String runGitCommand GitRepo {..} args = liftIO $ do     withMVar gitLock $ \_ -> do         readProcess "git" (("--git-dir=" <> gitDir) : args) ""  -openRepo :: FilePath -> IO (Maybe Repo)-openRepo path = do+openRepo :: Bool -> FilePath -> IO (Maybe Repo)+openRepo gitWritable path = do     findGitDir >>= \case         Just gitDir -> do             gitLock <- newMVar ()             gitInotify <- newMVar Nothing-            gitWatchedBranches <- newMVar M.empty             return $ Just GitRepo {..}         Nothing -> do             return Nothing@@ -190,9 +215,17 @@  tryReadTree :: (MonadIO m, MonadFail m) => Repo -> FilePath -> Text -> m (Maybe Tree) tryReadTree treeRepo treeSubdir ref = do-    fmap (fmap TreeId) (tryReadObjectId treeRepo "tree" ref) >>= \case-        Just treeId -> return $ Just Tree {..}-        Nothing -> return Nothing+    tryReadObjectId treeRepo "tree" ref >>= \case+        Just oid -> do+            let treeIsDir = True+                treeId = TreeId oid+            return $ Just Tree {..}+        Nothing -> tryReadObjectId treeRepo "blob" ref >>= \case+            Just oid -> do+                let treeIsDir = False+                    treeId = TreeId oid+                return $ Just Tree {..}+            Nothing -> return Nothing  tryReadObjectId :: (MonadIO m, MonadFail m) => Repo -> Text -> Text -> m (Maybe ByteString) tryReadObjectId GitRepo {..} otype ref = do@@ -212,18 +245,31 @@ readBranch :: MonadIO m => Repo -> Text -> m (Maybe Commit) readBranch repo branch = readCommitFromFile repo ("refs/heads" </> T.unpack branch) -readTag :: MonadIO m => Repo -> Text -> m (Maybe (Tag Commit))-readTag repo tag = do-    ( infoPart, message ) <-+readTag :: (MonadIO m, MonadFail m) => Repo -> Text -> m (Tag Commit)+readTag repo@GitRepo {..} tag = maybe (fail err) return =<< tryReadTag repo tag+  where err = "tag ‘" <> T.unpack tag <> "’ not found in ‘" <> gitDir <> "’"++tryReadTag :: (MonadIO m, MonadFail m) => Repo -> Text -> m (Maybe (Tag Commit))+tryReadTag repo tag = do+    mbTagId <- fmap TagId <$> tryReadObjectId repo "tag" tag+    mbCat <- forM mbTagId $ \tid ->         fmap (fmap (drop 1) . span (not . null) . lines) $-        runGitCommand repo [ "cat-file", "tag", T.unpack tag ]-    let info = map (fmap (drop 1) . span (/= ' ')) infoPart+        runGitCommand repo [ "cat-file", "tag", showTagId tid ]      sequence $ do+        tagId <- mbTagId+        ( infoPart, message ) <- mbCat+        let info = map (fmap (drop 1) . span (/= ' ')) infoPart+         otype <- lookup "type" info         guard (otype == "commit")         tagTag <- T.pack <$> lookup "tag" info         cid <- CommitId . BC.pack <$> lookup "object" info++        tagger <- T.pack <$> lookup "tagger" info+        let tagTagger = T.dropEnd 1 $ T.dropWhileEnd (/= ' ') $ T.dropEnd 1 $ T.dropWhileEnd (/= ' ') tagger+        tagTime <- parseTimeM False defaultTimeLocale "%s %z" $ T.unpack $ T.drop (T.length tagTagger + 1) tagger+         let tagMessage = T.pack $ unlines $ dropWhile null message         Just $ do             tagObject <- liftIO $ mkCommit repo cid@@ -231,12 +277,43 @@  listCommits :: MonadIO m => Repo -> Text -> m [ Commit ] listCommits commitRepo range = liftIO $ do-    out <- runGitCommand commitRepo [ "log", "--pretty=%H", "--first-parent", "--reverse", T.unpack range ]+    out <- runGitCommand commitRepo [ "rev-list", "--first-parent", "--reverse", T.unpack range ]     forM (lines out) $ \cid -> do         let commitId_ = CommitId (BC.pack cid)         commitDetails <- newMVar Nothing         return Commit {..} +listCommitsFrom :: MonadIO m => Repo -> [ CommitId ] -> [ CommitId ] -> m [ Commit ]+listCommitsFrom commitRepo from except = liftIO $ do+    out <- runGitCommand commitRepo $ concat+        [ [ "rev-list", "--first-parent", "--reverse" ]+        , map showCommitId from+        , "--not" : map showCommitId except+        ]+    forM (lines out) $ \cid -> do+        let commitId_ = CommitId (BC.pack cid)+        commitDetails <- newMVar Nothing+        return Commit {..}++listTags :: MonadIO m => Repo -> m [ Tag Commit ]+listTags repo = liftIO $ do+    out <- runGitCommand repo+        [ "for-each-ref", "refs/tags"+        , "--format=%(objecttype) %(refname:short)"+        ]+    fmap catMaybes $ forM (map words $ lines out) $ \case+        [ "tag", tname ] -> tryReadTag repo (T.pack tname)+        _ -> return Nothing++mergeBase :: MonadIO m => Repo -> [ CommitId ] -> m [ Commit ]+mergeBase commitRepo cids = liftIO $ do+    out <- runGitCommand commitRepo $ "merge-base" : "--all" : "--octopus" : map showCommitId cids+    forM (lines out) $ \cid -> do+        let commitId_ = CommitId (BC.pack cid)+        commitDetails <- newMVar Nothing+        return Commit {..}++ findUpstreamRef :: MonadIO m => Repo -> Text -> m (Maybe Text) findUpstreamRef repo@GitRepo {..} ref = liftIO $ do     deref <- readProcessWithExitCode "git" [ "--git-dir=" <> gitDir, "symbolic-ref", "--quiet", T.unpack ref ] "" >>= \case@@ -250,7 +327,20 @@             _ -> return Nothing         _ -> return Nothing +getGitRefPath :: MonadIO m => Repo -> Text -> m (Maybe FilePath)+getGitRefPath GitRepo {..} ref = liftIO $ do+    readProcessWithExitCode "git" [ "--git-dir=" <> gitDir, "rev-parse", "--symbolic-full-name", T.unpack ref ] "" >>= \case+        ( ExitSuccess, out, _ ) | [ path ] <- lines out -> return (Just path)+        ( _, _, _ ) -> return Nothing +isAncestor :: (MonadIO m, MonadFail m) => Repo -> CommitId -> CommitId -> m Bool+isAncestor GitRepo {..} cid cid' = liftIO $ do+    readProcessWithExitCode "git" [ "--git-dir=" <> gitDir, "merge-base", "--is-ancestor", showCommitId cid, showCommitId cid' ] "" >>= \case+        ( ExitSuccess, _, _ ) -> return True+        ( ExitFailure 1, _, _ ) -> return False+        ( code, _, _ ) -> fail $ "git merge-base --is-ancestor exited with error: " <> show code++ getCommitDetails :: (MonadIO m, MonadFail m) => Commit -> m CommitDetails getCommitDetails Commit {..} = do     liftIO $ do@@ -266,6 +356,7 @@                 Just treeId <- return $ TreeId . BC.pack <$> lookup "tree" info                 let treeRepo = commitRepo                     treeSubdir = ""+                    treeIsDir = True                 let commitTree = Tree {..}                 let commitTitle = T.pack title                 let commitMessage = T.pack $ unlines $ dropWhile null message@@ -292,10 +383,18 @@         [] -> return tree         _ -> readProcessWithExitCode "git" [ "--git-dir=" <> gitDir, "rev-parse", "--verify", "--quiet", showTreeId (treeId tree) <> ":" <> joinPath dirs ] "" >>= \case             ( ExitSuccess, out, _ ) | tid : _ <- lines out -> do+                isdir <- readProcessWithExitCode "git" [ "--git-dir=" <> gitDir, "cat-file", "-t", tid ] "" >>= \case+                    ( ExitSuccess, otype, _ )+                        | "tree" : _ <- lines otype -> return True+                        | "blob" : _ <- lines otype -> return False+                    _ -> do+                        fail $ "subtree ‘" <> path <> "’ " <> maybe "" ((" in revision ‘" <>) . (<> "’") . showCommitId . commitId) mbCommit <> " has unknown object type"+                 return Tree                     { treeRepo = treeRepo tree                     , treeId = TreeId (BC.pack tid)                     , treeSubdir = joinPath $ treeSubdir tree : dirs+                    , treeIsDir = isdir                     }             _ -> do                 fail $ "subtree ‘" <> path <> "’ not found" <> maybe "" ((" in revision ‘" <>) . (<> "’") . showCommitId . commitId) mbCommit@@ -316,8 +415,15 @@                             , curenv                             ]                         } input-        "" <- readGitProcess [ "read-tree", showTreeId treeId ] ""-        "" <- readGitProcess [ "checkout-index", "--all", "--prefix=" <> addTrailingPathSeparator dest ] ""+        dest' <- if treeIsDir+            then do+                "" <- readGitProcess [ "read-tree", showTreeId treeId ] ""+                return dest+            else do+                "" <- readGitProcess [ "read-tree", "--empty" ] ""+                "" <- readGitProcess [ "update-index", "--add", "--cacheinfo", "100644," <> showTreeId treeId <> "," <> takeFileName dest ] ""+                return $ takeDirectory dest+        "" <- readGitProcess [ "checkout-index", "--all", "--prefix=" <> addTrailingPathSeparator dest' ] ""         return ()  createWipCommit :: (MonadIO m, MonadMask m, MonadFail m) => Repo -> m Commit@@ -387,42 +493,120 @@                         return (Just content)             | otherwise -> error "createProcess must return stdout handle" +pushToBranch :: (MonadIO m, MonadFail m) => Branch -> Commit -> m ()+pushToBranch Branch {..} Commit {..} = do+    when (not $ gitWritable branchRepo) $ do+        -- throw IO exception to generate JobError instead of JobFailed+        liftIO $ fail $ "repo ‘" <> gitDir branchRepo <> "’ is not writable"+    join $ liftIO $+        withMVar (gitLock branchRepo) $ \_ ->+        withMVar (gitLock commitRepo) $ \_ -> do+            let cmd = (proc "git" [ "--git-dir=" <> gitDir commitRepo, "push", "--quiet", "--porcelain", gitDir branchRepo, showCommitId commitId_ <> ":refs/heads/" <> T.unpack branchName ])+                    { std_in = NoStream+                    , std_out = CreatePipe+                    , std_err = NoStream+                    }+            createProcess cmd >>= \( _, mbstdout, _, ph ) -> if+                | Just _ <- mbstdout -> do+                    waitForProcess ph >>= \case+                        ExitSuccess -> return $ return ()+                        ExitFailure 1 -> checkIfPushingAncestor+                        code -> return $ fail $ "git push exited with error: " <> show code+                | otherwise -> error "createProcess must return stdout handle"+  where+    checkIfPushingAncestor = do+        let cmd = (proc "git" [ "--git-dir=" <> gitDir commitRepo, "fetch", "--porcelain", gitDir branchRepo, "refs/heads/" <> T.unpack branchName ])+                { std_in = NoStream+                , std_out = CreatePipe+                , std_err = NoStream+                }+        createProcess cmd >>= \( _, mbstdout, _, ph ) -> if+            | Just stdout <- mbstdout -> do+                waitForProcess ph >>= \case+                    ExitSuccess -> do+                        content <- BC.hGetContents stdout+                        case map BC.words $ BC.lines content of+                            [ [ _, _, remoteTip, _ ] ] -> do+                                isAncestor commitRepo commitId_ (CommitId remoteTip) >>= \case+                                    True -> return $ return ()+                                    False -> return $ fail $+                                        "push of commit " <> showCommitId commitId_ <> " to branch ‘" <> T.unpack branchName <> "’ in ‘" <> gitDir branchRepo <> "’ failed"+                            _ -> return $ fail "unexpected output from git fetch"+                    code -> return $ fail $ "git fetch exited with error: " <> show code+            | otherwise -> error "createProcess must return stdout handle" -repoInotify :: Repo -> IO ( INotify, TChan (Tag Commit) )-repoInotify repo@GitRepo {..} = modifyMVar gitInotify $ \case-    cur@(Just info) ->-        return ( cur, info )++data GitInotify = GitInotify+    { giInotify :: INotify+    , giTags :: MVar (Maybe ( WatchDescriptor, TChan (Tag Commit) ))+    , giDirs :: MVar (Map FilePath ( WatchDescriptor, Map Text (TVar (Maybe Commit)) ))+    }++repoInotify :: Repo -> IO GitInotify+repoInotify GitRepo {..} = modifyMVar gitInotify $ \case+    cur@(Just gi) ->+        return ( cur, gi )     Nothing -> do-        inotify <- initINotify-        tagsChan <- newBroadcastTChanIO-        let info = ( inotify, tagsChan )+        giInotify <- initINotify+        giTags <- newMVar Nothing+        giDirs <- newMVar M.empty+        let gi = GitInotify {..}+        return ( Just gi, gi ) -        _ <- addWatch inotify [ MoveIn ] (BC.pack headsDir) $ \event -> do-            let branch = decodeUtf8 $ filePath event-            tvars <- fromMaybe [] . M.lookup branch <$> readMVar gitWatchedBranches-            when (not $ null tvars) $ do-                commit <- readBranch repo branch-                atomically $ do-                    mapM_ (`writeTVar` commit) tvars+watchBranch :: (MonadIO m, MonadFail m) => Repo -> Text -> m (Either Commit (STM (Maybe Commit)))+watchBranch repo@GitRepo {..} ref = liftIO $ do+    mbCommit <- tryReadCommit repo ref+    gi@GitInotify {..} <- repoInotify repo+    getGitRefPath repo ref >>= \case+        Just path -> Right <$> do+            let ( dir, sbranch ) = splitFileName path+                branch = T.pack sbranch+            modifyMVar giDirs $ \dirMap ->+                case M.lookup dir dirMap of+                    Just ( wd, branchMap ) ->+                        case M.lookup branch branchMap of+                            Just tvar -> do+                                return ( dirMap, readTVar tvar )+                            Nothing -> do+                                tvar <- newTVarIO mbCommit+                                return ( M.insert dir ( wd, M.insert branch tvar branchMap ) dirMap, readTVar tvar ) -        _ <- addWatch inotify [ MoveIn ] (BC.pack tagsDir) $ \event -> do-            readTag repo (decodeUtf8 $ filePath event) >>= \case-                Just tag -> atomically $ writeTChan tagsChan tag-                Nothing  -> return ()+                    Nothing -> do+                        wd <- addBranchWatch gi dir+                        tvar <- newTVarIO mbCommit+                        return ( M.insert dir ( wd, M.singleton branch tvar ) dirMap, readTVar tvar ) -        return ( Just info, info )-  where-    headsDir = gitDir </> "refs/heads"-    tagsDir = gitDir </> "refs/tags"+        Nothing | Just commit <- mbCommit -> do+            return $ Left commit -watchBranch :: MonadIO m => Repo -> Text -> m (STM (Maybe Commit))-watchBranch repo@GitRepo {..} branch = liftIO $ do-    var <- newTVarIO =<< readBranch repo branch-    void $ repoInotify repo-    modifyMVar_ gitWatchedBranches $ return . M.insertWith (++) branch [ var ]-    return $ readTVar var+        _ -> do+            fail $ "ref ‘" <> T.unpack ref <> "’ not found in ‘" <> gitDir <> "’"+  where+    addBranchWatch GitInotify {..} dir = do+        addWatch giInotify [ MoveIn ] (BC.pack $ gitDir </> dir) $ \event -> do+            let branch = decodeUtf8 $ filePath event+            withMVar giDirs $ \dirMap -> do+                Just ( _, branchMap ) <- return $ M.lookup dir dirMap+                case M.lookup branch branchMap of+                    Just tvar -> do+                        commit <- readCommitFromFile repo (dir </> T.unpack branch)+                        atomically $ writeTVar tvar commit+                    Nothing -> do+                        return ()  watchTags :: MonadIO m => Repo -> m (TChan (Tag Commit))-watchTags repo = liftIO $ do-    tagsChan <- snd <$> repoInotify repo-    atomically $ dupTChan tagsChan+watchTags repo@GitRepo {..} = liftIO $ do+    GitInotify {..} <- repoInotify repo+    chan <- modifyMVar giTags $ \case+        cur@(Just ( _, chan )) -> do+            return ( cur, chan )+        Nothing -> do+            chan <- newBroadcastTChanIO+            wd <- addWatch giInotify [ MoveIn ] (BC.pack tagsDir) $ \event -> do+                tryReadTag repo (decodeUtf8 $ filePath event) >>= \case+                    Just tag -> atomically $ writeTChan chan tag+                    Nothing  -> return ()+            return ( Just ( wd, chan ), chan )+    atomically $ dupTChan chan+  where+    tagsDir = gitDir </> "refs/tags"