packages feed

hs-hath-1.4.0: src/Hath/Cache/FileStatus.hs

{-# LANGUAGE CPP #-}

-- | Cross-platform file status and mtime helpers (without following symlinks).
module Hath.Cache.FileStatus ( regularFile, touch ) where

import           Relude

#if defined(mingw32_HOST_OS)
import           Data.Time.Clock       ( getCurrentTime )
import           Data.Time.Clock.POSIX ( utcTimeToPOSIXSeconds )

import           System.Directory      ( doesFileExist
                                       , getFileSize
                                       , getModificationTime
                                       , pathIsSymbolicLink
                                       , setModificationTime
                                       )
#else
import           Foreign.C.Types       ( CTime(..) )

import qualified System.Posix.Files    as Posix
#endif

-- | @(sizeBytes, mtimeUnix)@ for a regular file, or 'Nothing' for symlinks and other types. Throws if missing.
regularFile :: FilePath -> IO (Maybe ( Int64, Int64 ))

touch :: FilePath -> IO ()

#if defined(mingw32_HOST_OS)
regularFile path = do
  link <- pathIsSymbolicLink path
  file <- doesFileExist path
  if link || not file
    then pure Nothing
    else do
      size <- getFileSize path
      mtime <- getModificationTime path
      pure $ Just ( fromIntegral size, floor (utcTimeToPOSIXSeconds mtime) )

touch path = getCurrentTime >>= setModificationTime path
#else
regularFile path = Posix.getSymbolicLinkStatus path <&> \st -> do
  guard (Posix.isRegularFile st)
  let CTime mtime = Posix.modificationTime st
  pure ( fromIntegral (Posix.fileSize st), mtime )

touch = Posix.touchFile
#endif