Skip to content

Use file-watching mechanism #570

@mitchellwrosen

Description

@mitchellwrosen

I managed to get a shake watch working with this:

import Control.Concurrent (newChan, readChan)
import Control.Exception (SomeAsyncException(..), fromException, throwIO, try)
import Data.Functor (void)
import Development.Shake
import System.Directory (getCurrentDirectory)
import System.Environment (getArgs, getEnvironment, withArgs)
import System.FSNotify (eventPath, watchTreeChan, withManager)

import qualified Data.Set as Set

main :: IO ()
main =
  -- Get the command line args before shake sees them. This is not ideal because
  -- you must run e.g.
  --
  --   shake watch -j2
  --
  -- as opposed to
  --
  --   shake -j2 watch
  --
  getArgs >>= \case
    "watch":args ->
      -- Strip off the "watch" arg for the real shake script.
      withArgs args $ do
        -- Run the real main under 'try', ignoring synchronous exceptions
        -- because we don't care if the build fails - we want to watch & rebuild
        -- regardless. Re-throw async exceptions.
        try realMain >>= \case
          Left (fromException -> Just (SomeAsyncException ex)) -> throwIO ex
          _ -> pure ()

        -- Get the list of files that shake considers to be alive. This assumes
        -- we've set
        --
        --   shakeLiveFiles = [".shake/live"]
        --
        cwd <- getCurrentDirectory
        files <- Set.fromList . map (cwd </>) . lines <$> readFile ".shake/live"

        -- Start watching the filesystem, and rebuild once any of these files
        -- changes.
        withManager $ \manager -> do
          chan <- newChan
          void (watchTreeChan manager "." ((`elem` files) . eventPath) chan)
          void (readChan chan) -- We block here

        -- Loop. Here my compiled shakefile is itself a build target, so I exec
        -- it rather than loop here, to get the latest & greatest shake
        -- executable.
        env <- getEnvironment
        executeFile "bin/Shakefile" False ("watch":args) (Just env)

    _ ->
      realMain

It works okay, but I really don't want to keep writing this code :)

Should/could something like this live inside shake? shake --watch?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions