{-# LANGUAGE OverloadedStrings #-}
-- Copyright 2020 United States Government as represented by the Administrator
-- of the National Aeronautics and Space Administration. All Rights Reserved.
--
-- Disclaimers
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may
-- not use this file except in compliance with the License. You may obtain a
-- copy of the License at
--
--      https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations
-- under the License.
--
-- | Auxiliary functions for working with directories.
module System.Directory.Extra
    ( copyTemplate
    , CopyTemplateException(..)
    )
  where

-- External imports
import           Control.Exception         ( Exception, IOException, catch,
                                             throwIO )
import           Control.Monad             ( filterM, forM_ )
import           Data.Aeson                ( Value (..) )
import qualified Data.ByteString.Lazy      as B
import           Data.List                 ( isInfixOf )
import           Data.Text.Lazy            ( pack, unpack )
import           Data.Text.Lazy.Encoding   ( encodeUtf8 )
import           Distribution.Simple.Utils ( getDirectoryContentsRecursive )
import           System.Directory          ( createDirectoryIfMissing,
                                             doesFileExist )
import           System.FilePath           ( makeRelative, splitFileName,
                                             (</>) )
import           Text.Microstache          ( MustacheException (..), Template,
                                             compileMustacheFile,
                                             compileMustacheText,
                                             renderMustache )
import           Text.Parsec.Error         ( Message (..), errorMessages,
                                             errorPos )
import           Text.Parsec.Pos           ( sourceColumn, sourceLine )

{- HLINT ignore "Redundant <$>" -}
-- | Copy a template directory into a target location, expanding variables
-- provided in a map in a JSON value, both in the file contents and in the
-- filepaths themselves.
copyTemplate :: FilePath -> Value -> FilePath -> IO ()
copyTemplate :: [Char] -> Value -> [Char] -> IO ()
copyTemplate [Char]
templateDir Value
subst [Char]
targetDir = do

  -- Get all files (not directories) in the template dir. To keep a directory,
  -- create an empty file in it (e.g., .keep).
  tmplContents <- ([Char] -> [Char]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map ([Char]
templateDir [Char] -> [Char] -> [Char]
</>) ([[Char]] -> [[Char]])
-> ([[Char]] -> [[Char]]) -> [[Char]] -> [[Char]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Char] -> Bool) -> [[Char]] -> [[Char]]
forall a. (a -> Bool) -> [a] -> [a]
filter ([Char] -> [[Char]] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [[Char]
"..", [Char]
"."])
                    ([[Char]] -> [[Char]]) -> IO [[Char]] -> IO [[Char]]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> IO [[Char]]
getDirectoryContentsRecursiveE [Char]
templateDir

  tmplFiles <- filterM doesFileExist tmplContents

  -- Copy files to new locations, expanding their name and contents as
  -- mustache templates.
  forM_ tmplFiles $ \[Char]
fp -> do

    -- New file name in target directory, treating file
    -- name as mustache template.
    let fullPath :: [Char]
fullPath = [Char]
targetDir [Char] -> [Char] -> [Char]
</> [Char]
newFP
          where
            -- If file name has mustache markers, expand, otherwise use
            -- relative file path
            newFP :: [Char]
newFP = (ParseError -> [Char])
-> (Template -> [Char]) -> Either ParseError Template -> [Char]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ([Char] -> ParseError -> [Char]
forall a b. a -> b -> a
const [Char]
relFP)
                           (Text -> [Char]
unpack (Text -> [Char]) -> (Template -> Text) -> Template -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Template -> Value -> Text
`renderMustache` Value
subst))
                           Either ParseError Template
fpAsTemplateE

            -- Local file name within template dir
            relFP :: [Char]
relFP = [Char] -> [Char] -> [Char]
makeRelative [Char]
templateDir [Char]
fp

            -- Apply mustache substitutions to file name
            fpAsTemplateE :: Either ParseError Template
fpAsTemplateE = PName -> Text -> Either ParseError Template
compileMustacheText PName
"fp" ([Char] -> Text
pack [Char]
relFP)

    -- File contents, treated as a mustache template.
    contents <- Text -> ByteString
encodeUtf8 (Text -> ByteString)
-> (Template -> Text) -> Template -> ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Template -> Value -> Text
`renderMustache` Value
subst)
                           (Template -> ByteString) -> IO Template -> IO ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> IO Template
compileMustacheFileE [Char]
fp

    -- Create target directory if necessary
    let dirName = ([Char], [Char]) -> [Char]
forall a b. (a, b) -> a
fst (([Char], [Char]) -> [Char]) -> ([Char], [Char]) -> [Char]
forall a b. (a -> b) -> a -> b
$ [Char] -> ([Char], [Char])
splitFileName [Char]
fullPath
    createDirectoryIfMissingE True dirName

    -- Write expanded contents to expanded file path
    -- Capture exceptions here
    writeFileE fullPath contents

-- | Exception detected during the template expansion process.
newtype CopyTemplateException = CopyTemplateException String

instance Show CopyTemplateException where
  show :: CopyTemplateException -> [Char]
show (CopyTemplateException [Char]
s) = [Char]
s

instance Exception CopyTemplateException

-- | Wrap 'getDirectoryContentsRecursive' and throw any 'IOException' as a
-- 'CopyTemplateException'.
getDirectoryContentsRecursiveE :: FilePath -> IO [FilePath]
getDirectoryContentsRecursiveE :: [Char] -> IO [[Char]]
getDirectoryContentsRecursiveE [Char]
s =
    IO [[Char]] -> (IOException -> IO [[Char]]) -> IO [[Char]]
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
catch ([Char] -> IO [[Char]]
getDirectoryContentsRecursive [Char]
s) IOException -> IO [[Char]]
handler
  where
    handler :: IOException -> IO [FilePath]
    handler :: IOException -> IO [[Char]]
handler IOException
e = CopyTemplateException -> IO [[Char]]
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO ([Char] -> CopyTemplateException
CopyTemplateException (IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e))

-- | Wrap 'createDirectoryIfMissing' and throw any 'IOException' as a
-- 'CopyTemplateException', possibly making the error message more
-- user-friendly.
createDirectoryIfMissingE :: Bool -> FilePath -> IO ()
createDirectoryIfMissingE :: Bool -> [Char] -> IO ()
createDirectoryIfMissingE Bool
parents [Char]
fp =
    IO () -> (IOException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
catch (Bool -> [Char] -> IO ()
createDirectoryIfMissing Bool
parents [Char]
fp) IOException -> IO ()
handler
  where
    handler :: IOException -> IO ()
    handler :: IOException -> IO ()
handler IOException
e
      | [Char]
"createDirectory: permission denied" [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e
      = CopyTemplateException -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO ()) -> CopyTemplateException -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$
          [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"Error creating target directory (permission denied)"

      | Bool
otherwise
      = CopyTemplateException -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO ()) -> CopyTemplateException -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$ [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e

-- | Wrap 'writeFile' and throw any 'IOException' as a 'CopyTemplateException',
-- possibly making the error message more user-friendly.
writeFileE :: FilePath -> B.ByteString -> IO ()
writeFileE :: [Char] -> ByteString -> IO ()
writeFileE [Char]
fp ByteString
contents =
    IO () -> (IOException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
catch ([Char] -> ByteString -> IO ()
B.writeFile [Char]
fp ByteString
contents) IOException -> IO ()
handler
  where
    handler :: IOException -> IO ()
    handler :: IOException -> IO ()
handler IOException
e
      | [Char]
"permission denied" [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e
      = CopyTemplateException -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO ()) -> CopyTemplateException -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$
          [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"Error creating target file (permission denied)"

      | [Char]
"resource exhausted" [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e
      = CopyTemplateException -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO ()) -> CopyTemplateException -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$
          [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"No space left on device"

      | Bool
otherwise
      = CopyTemplateException -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO ()) -> CopyTemplateException -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$ [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e

-- | Wrap 'compileMustacheFile' and throw any 'IOException' or
-- 'MustacheException' as a 'CopyTemplateException', possibly making the error
-- message more user-friendly.
compileMustacheFileE :: FilePath -> IO Template
compileMustacheFileE :: [Char] -> IO Template
compileMustacheFileE [Char]
fp = do
    IO Template -> (IOException -> IO Template) -> IO Template
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
catch (IO Template -> (MustacheException -> IO Template) -> IO Template
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
catch ([Char] -> IO Template
compileMustacheFile [Char]
fp) MustacheException -> IO Template
handler) IOException -> IO Template
handlerIO
  where
    handler :: MustacheException -> IO Template
    handler :: MustacheException -> IO Template
handler (MustacheParserException ParseError
p) = do
      let pos :: SourcePos
pos      = ParseError -> SourcePos
errorPos ParseError
p
          line :: Line
line     = SourcePos -> Line
sourceLine SourcePos
pos
          column :: Line
column   = SourcePos -> Line
sourceColumn SourcePos
pos
          messages :: [Char]
messages = [[Char]] -> [Char]
keepHead ([[Char]] -> [Char]) -> [[Char]] -> [Char]
forall a b. (a -> b) -> a -> b
$ (Message -> [Char]) -> [Message] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map Message -> [Char]
showMessage ([Message] -> [[Char]]) -> [Message] -> [[Char]]
forall a b. (a -> b) -> a -> b
$ ParseError -> [Message]
errorMessages ParseError
p
      CopyTemplateException -> IO Template
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO Template)
-> CopyTemplateException -> IO Template
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$
        [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
":" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ Line -> [Char]
forall a. Show a => a -> [Char]
show Line
line [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
":" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ Line -> [Char]
forall a. Show a => a -> [Char]
show Line
column [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
messages

    handler MustacheException
e = do
      CopyTemplateException -> IO Template
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO Template)
-> CopyTemplateException -> IO Template
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$ [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ MustacheException -> [Char]
forall a. Show a => a -> [Char]
show MustacheException
e

    handlerIO :: IOException -> IO Template
    handlerIO :: IOException -> IO Template
handlerIO IOException
e
      | [Char]
"hGetContents: invalid argument" [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e
      = CopyTemplateException -> IO Template
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO Template)
-> CopyTemplateException -> IO Template
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$
          [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"Invalid UTF-8 byte sequence"

      | [Char]
"invalid byte sequence" [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e
      = CopyTemplateException -> IO Template
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO Template)
-> CopyTemplateException -> IO Template
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$
          [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"Invalid UTF-8 byte sequence"

      | [Char]
"openFile: permission denied" [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e
      = CopyTemplateException -> IO Template
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO Template)
-> CopyTemplateException -> IO Template
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$ [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"Permission denied"

      | Bool
otherwise
      = CopyTemplateException -> IO Template
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CopyTemplateException -> IO Template)
-> CopyTemplateException -> IO Template
forall a b. (a -> b) -> a -> b
$ [Char] -> CopyTemplateException
CopyTemplateException ([Char] -> CopyTemplateException)
-> [Char] -> CopyTemplateException
forall a b. (a -> b) -> a -> b
$ [Char]
fp [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ IOException -> [Char]
forall a. Show a => a -> [Char]
show IOException
e

-- | Show a parse message.
showMessage :: Message -> String
showMessage :: Message -> [Char]
showMessage (SysUnExpect [Char]
s) = [Char]
"Unexpected " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
s
showMessage (UnExpect [Char]
s)    = [Char]
"Unexpected " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
s
showMessage (Expect [Char]
s)      = [Char]
"Expected " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
s
showMessage (Message [Char]
s)     = [Char]
s

-- | Keep the first element of a list of strings, returning the empty string if
-- the list is empty.
keepHead :: [String] -> String
keepHead :: [[Char]] -> [Char]
keepHead ([Char]
a:[[Char]]
_) = [Char]
a
keepHead [[Char]]
_     = [Char]
""