How do I use TemplateHaskell's addDependentFile on a file relative to the file being compiled?

StackOverflow https://stackoverflow.com/questions/16163948

  •  11-04-2022
  •  | 
  •  

Question

I want that my TemplateHaskell expression, which uses IO and depends on the file MyDependency.txt, is recomputed when that file is being changed.

Therefore I am using addDependentFile "MyDependency.txt" to tell ghc to check that file for modification when compiling my code.

Unfortunately, this does not work because addDependentFile only works relative to the directory from which ghc is called.

How can I use it to depend on a file that is just next to (in the same directory as) the file I am compiling?

Was it helpful?

Solution

You can use location from Language.Haskell.TH.Syntax to extract the file name of the file being compiled, and use this to assemble the correct path:

-- | Uses 'addDependentFile' on a file relative to the current file
-- to mark it as being checked for changes when compiled with TemplateHaskell.
--
-- Returns an empty list of declarations so that it can be used with:
--
-- >$(addDependentFileRelative "MyDependency.txt")
addDependentFileRelative :: FilePath -> Q [Dec]
addDependentFileRelative relativeFile = do
    currentFilename <- loc_filename <$> location
    pwd             <- runIO getCurrentDirectory

    let invocationRelativePath = takeDirectory (pwd </> currentFilename) </> relativeFile

    addDependentFile invocationRelativePath

    return []

(public domain code)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top