-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Platform-agnostic library for filesystem operations -- -- This library provides a basic set of operations for manipulating files -- and directories in a portable way. @package directory @version 1.3.6.0 -- | Internal modules are always subject to change from version to version. module System.Directory.Internal.Prelude -- | A mirror image of first. -- -- The default definition may be overridden with a more efficient version -- if desired. second :: Arrow a => a b c -> a (d, b) (d, c) -- | killThread raises the ThreadKilled exception in the -- given thread (GHC only). -- --
--   killThread tid = throwTo tid ThreadKilled
--   
killThread :: ThreadId -> IO () -- | Creates a new thread to run the IO computation passed as the -- first argument, and returns the ThreadId of the newly created -- thread. -- -- The new thread will be a lightweight, unbound thread. Foreign -- calls made by this thread are not guaranteed to be made by any -- particular OS thread; if you need foreign calls to be made by a -- particular OS thread, then use forkOS instead. -- -- The new thread inherits the masked state of the parent (see -- mask). -- -- The newly created thread has an exception handler that discards the -- exceptions BlockedIndefinitelyOnMVar, -- BlockedIndefinitelyOnSTM, and ThreadKilled, and passes -- all other exceptions to the uncaught exception handler. forkIO :: IO () -> IO ThreadId -- | Put a value into an MVar. If the MVar is currently full, -- putMVar will wait until it becomes empty. -- -- There are two further important properties of putMVar: -- -- putMVar :: MVar a -> a -> IO () -- | Atomically read the contents of an MVar. If the MVar is -- currently empty, readMVar will wait until it is full. -- readMVar is guaranteed to receive the next putMVar. -- -- readMVar is multiple-wakeup, so when multiple readers are -- blocked on an MVar, all of them are woken up at the same time. -- -- Compatibility note: Prior to base 4.7, readMVar was a -- combination of takeMVar and putMVar. This mean that in -- the presence of other threads attempting to putMVar, -- readMVar could block. Furthermore, readMVar would not -- receive the next putMVar if there was already a pending thread -- blocked on takeMVar. The old behavior can be recovered by -- implementing 'readMVar as follows: -- --
--   readMVar :: MVar a -> IO a
--   readMVar m =
--     mask_ $ do
--       a <- takeMVar m
--       putMVar m a
--       return a
--   
readMVar :: MVar a -> IO a -- | Return the contents of the MVar. If the MVar is -- currently empty, takeMVar will wait until it is full. After a -- takeMVar, the MVar is left empty. -- -- There are two further important properties of takeMVar: -- -- takeMVar :: MVar a -> IO a -- | Create an MVar which is initially empty. newEmptyMVar :: IO (MVar a) -- | A variant of bracket where the return value from the first -- computation is not required. bracket_ :: IO a -> IO b -> IO c -> IO c -- | A specialised variant of bracket with just a computation to run -- afterward. finally :: IO a -> IO b -> IO a -- | When you want to acquire a resource, do some work with it, and then -- release the resource, it is a good idea to use bracket, because -- bracket will install the necessary exception handler to release -- the resource in the event that an exception is raised during the -- computation. If an exception is raised, then bracket will -- re-raise the exception (after performing the release). -- -- A common example is opening a file: -- --
--   bracket
--     (openFile "filename" ReadMode)
--     (hClose)
--     (\fileHandle -> do { ... })
--   
-- -- The arguments to bracket are in this order so that we can -- partially apply it, e.g.: -- --
--   withFile name mode = bracket (openFile name mode) hClose
--   
bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c -- | Like finally, but only performs the final action if there was -- an exception raised by the computation. onException :: IO a -> IO b -> IO a -- | Similar to catch, but returns an Either result which is -- (Right a) if no exception of type e was -- raised, or (Left ex) if an exception of type -- e was raised and its value is ex. If any other type -- of exception is raised then it will be propagated up to the next -- enclosing exception handler. -- --
--   try a = catch (Right `liftM` a) (return . Left)
--   
try :: Exception e => IO a -> IO (Either e a) -- | Executes an IO computation with asynchronous exceptions masked. -- That is, any thread which attempts to raise an exception in the -- current thread with throwTo will be blocked until asynchronous -- exceptions are unmasked again. -- -- The argument passed to mask is a function that takes as its -- argument another function, which can be used to restore the prevailing -- masking state within the context of the masked computation. For -- example, a common way to use mask is to protect the acquisition -- of a resource: -- --
--   mask $ \restore -> do
--       x <- acquire
--       restore (do_something_with x) `onException` release
--       release
--   
-- -- This code guarantees that acquire is paired with -- release, by masking asynchronous exceptions for the critical -- parts. (Rather than write this code yourself, it would be better to -- use bracket which abstracts the general pattern). -- -- Note that the restore action passed to the argument to -- mask does not necessarily unmask asynchronous exceptions, it -- just restores the masking state to that of the enclosing context. Thus -- if asynchronous exceptions are already masked, mask cannot be -- used to unmask exceptions again. This is so that if you call a library -- function with exceptions masked, you can be sure that the library call -- will not be able to unmask exceptions again. If you are writing -- library code and need to use asynchronous exceptions, the only way is -- to create a new thread; see forkIOWithUnmask. -- -- Asynchronous exceptions may still be received while in the masked -- state if the masked thread blocks in certain ways; see -- Control.Exception#interruptible. -- -- Threads created by forkIO inherit the MaskingState from -- the parent; that is, to start a thread in the -- MaskedInterruptible state, use mask_ $ forkIO .... -- This is particularly useful if you need to establish an exception -- handler in the forked thread before any asynchronous exceptions are -- received. To create a new thread in an unmasked state use -- forkIOWithUnmask. mask :: ((forall a. () => IO a -> IO a) -> IO b) -> IO b -- | A variant of throw that can only be used within the IO -- monad. -- -- Although throwIO has a type that is an instance of the type of -- throw, the two functions are subtly different: -- --
--   throw e   `seq` x  ===> throw e
--   throwIO e `seq` x  ===> x
--   
-- -- The first example will cause the exception e to be raised, -- whereas the second one won't. In fact, throwIO will only cause -- an exception to be raised when it is used within the IO monad. -- The throwIO variant should be used in preference to -- throw to raise an exception within the IO monad because -- it guarantees ordering with respect to other IO operations, -- whereas throw does not. throwIO :: Exception e => e -> IO a -- | This is the simplest of the exception-catching functions. It takes a -- single argument, runs it, and if an exception is raised the "handler" -- is executed, with the value of the exception passed as an argument. -- Otherwise, the result is returned as normal. For example: -- --
--   catch (readFile f)
--         (\e -> do let err = show (e :: IOException)
--                   hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
--                   return "")
--   
-- -- Note that we have to give a type signature to e, or the -- program will not typecheck as the type is ambiguous. While it is -- possible to catch exceptions of any type, see the section "Catching -- all exceptions" (in Control.Exception) for an explanation of -- the problems with doing so. -- -- For catching exceptions in pure (non-IO) expressions, see the -- function evaluate. -- -- Note that due to Haskell's unspecified evaluation order, an expression -- may throw one of several possible exceptions: consider the expression -- (error "urk") + (1 `div` 0). Does the expression throw -- ErrorCall "urk", or DivideByZero? -- -- The answer is "it might throw either"; the choice is -- non-deterministic. If you are catching any type of exception then you -- might catch either. If you are calling catch with type IO -- Int -> (ArithException -> IO Int) -> IO Int then the -- handler may get run with DivideByZero as an argument, or an -- ErrorCall "urk" exception may be propagated further up. If -- you call it again, you might get a the opposite behaviour. This is ok, -- because catch is an IO computation. catch :: Exception e => IO a -> (e -> IO a) -> IO a -- | The SomeException type is the root of the exception type -- hierarchy. When an exception of type e is thrown, behind the -- scenes it is encapsulated in a SomeException. data SomeException -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | Like replicateM, but discards the result. replicateM_ :: Applicative m => Int -> m a -> m () -- | Right-to-left composition of Kleisli arrows. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
--   (.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
--   (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
--   
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 <=< -- | Left-to-right composition of Kleisli arrows. -- -- '(bs >=> cs) a' can be understood as the -- do expression -- --
--   do b <- bs a
--      cs b
--   
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | Conditional execution of Applicative expressions. For example, -- --
--   when debug (putStrLn "Debugging")
--   
-- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | Reverse all the bits in the argument complement :: Bits a => a -> a -- | Bitwise "and" (.&.) :: Bits a => a -> a -> a infixl 7 .&. -- | Bitwise "or" (.|.) :: Bits a => a -> a -> a infixl 5 .|. -- | Convert a letter to the corresponding upper-case letter, if any. Any -- other character is returned unchanged. toUpper :: Char -> Char -- | Convert a letter to the corresponding lower-case letter, if any. Any -- other character is returned unchanged. toLower :: Char -> Char -- | Selects alphabetic Unicode characters (lower-case, upper-case and -- title-case letters, plus letters of caseless scripts and modifiers -- letters). This function is equivalent to isLetter. isAlpha :: Char -> Bool -- | Selects the first 128 characters of the Unicode character set, -- corresponding to the ASCII character set. isAscii :: Char -> Bool -- | for_ is traverse_ with its arguments flipped. For a -- version that doesn't ignore the results see for. -- --

Examples

-- -- Basic usage: -- --
--   >>> for_ [1..4] print
--   1
--   2
--   3
--   4
--   
for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and ignore the results. For a version that doesn't -- ignore the results see traverse. -- --

Examples

-- -- Basic usage: -- --
--   >>> traverse_ print ["Hello", "world", "!"]
--   "Hello"
--   "world"
--   "!"
--   
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () -- | on b u x y runs the binary function b -- on the results of applying unary function u to two -- arguments x and y. From the opposite perspective, it -- transforms two inputs and combines the outputs. -- --
--   ((+) `on` f) x y = f x + f y
--   
-- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- -- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 `on` -- | The catMaybes function takes a list of Maybes and -- returns a list of all the Just values. -- --

Examples

-- -- Basic usage: -- --
--   >>> catMaybes [Just 1, Nothing, Just 3]
--   [1,3]
--   
-- -- When constructing a list of Maybe values, catMaybes can -- be used to return all of the "success" results (if the list is the -- result of a map, then mapMaybe would be more -- appropriate): -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [Just 1,Nothing,Just 3]
--   
--   >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
--   [1,3]
--   
catMaybes :: [Maybe a] -> [a] -- | The maybeToList function returns an empty list when given -- Nothing or a singleton list when given Just. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: Maybe a -> [a] -- | The fromMaybe function takes a default value and a Maybe -- value. If the Maybe is Nothing, it returns the default -- values; otherwise, it returns the value contained in the Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: a -> Maybe a -> a -- | An associative operation. -- --
--   >>> [1,2,3] <> [4,5,6]
--   [1,2,3,4,5,6]
--   
(<>) :: Semigroup a => a -> a -> a infixr 6 <> -- | Identity of mappend -- --
--   >>> "Hello world" <> mempty
--   "Hello world"
--   
mempty :: Monoid a => a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. -- --
--   >>> mconcat ["Hello", " ", "Haskell", "!"]
--   "Hello Haskell!"
--   
mconcat :: Monoid a => [a] -> a -- | Write a new value into an IORef writeIORef :: IORef a -> a -> IO () -- | Read the value of an IORef readIORef :: IORef a -> IO a -- | Build a new IORef newIORef :: a -> IO (IORef a) -- | A mutable variable in the IO monad data IORef a -- | for is traverse with its arguments flipped. For a -- version that ignores the results see for_. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) -- | A value of type Ptr a represents a pointer to an -- object, or an array of objects, which may be marshalled to or from -- Haskell values of type a. -- -- The type a will often be an instance of class Storable -- which provides the marshalling operations. However this is not -- essential, and you can provide your own operations to access the -- pointer. For example you might write small foreign functions to get or -- set the fields of a C struct. data Ptr a -- | Temporarily store a list of storable values in memory (like -- with, but for multiple elements). withArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b -- | Temporarily allocate space for the given number of elements (like -- alloca, but for multiple elements). allocaArray :: Storable a => Int -> (Ptr a -> IO b) -> IO b -- | Converts a withXXX combinator into one marshalling a value -- wrapped into a Maybe, using nullPtr to represent -- Nothing. maybeWith :: (a -> (Ptr b -> IO c) -> IO c) -> Maybe a -> (Ptr b -> IO c) -> IO c -- | with val f executes the computation f, -- passing as argument a pointer to a temporarily allocated block of -- memory into which val has been marshalled (the combination of -- alloca and poke). -- -- The memory is freed when f terminates (either normally or via -- an exception), so the pointer passed to f must not be -- used after this. with :: Storable a => a -> (Ptr a -> IO b) -> IO b allocaBytesAligned :: Int -> Int -> (Ptr a -> IO b) -> IO b -- | allocaBytes n f executes the computation f, -- passing as argument a pointer to a temporarily allocated block of -- memory of n bytes. The block of memory is sufficiently -- aligned for any of the basic foreign types that fits into a memory -- block of the allocated size. -- -- The memory is freed when f terminates (either normally or via -- an exception), so the pointer passed to f must not be -- used after this. allocaBytes :: Int -> (Ptr a -> IO b) -> IO b -- | alloca f executes the computation f, passing -- as argument a pointer to a temporarily allocated block of memory -- sufficient to hold values of type a. -- -- The memory is freed when f terminates (either normally or via -- an exception), so the pointer passed to f must not be -- used after this. alloca :: Storable a => (Ptr a -> IO b) -> IO b -- | The member functions of this class facilitate writing values of -- primitive types to raw memory (which may have been allocated with the -- above mentioned routines) and reading values from blocks of raw -- memory. The class, furthermore, includes support for computing the -- storage requirements and alignment restrictions of storable types. -- -- Memory addresses are represented as values of type Ptr -- a, for some a which is an instance of class -- Storable. The type argument to Ptr helps provide some -- valuable type safety in FFI code (you can't mix pointers of different -- types without an explicit cast), while helping the Haskell type system -- figure out which marshalling method is needed for a given pointer. -- -- All marshalling between Haskell and a foreign language ultimately -- boils down to translating Haskell data structures into the binary -- representation of a corresponding data structure of the foreign -- language and vice versa. To code this marshalling in Haskell, it is -- necessary to manipulate primitive data types stored in unstructured -- memory blocks. The class Storable facilitates this manipulation -- on all types for which it is instantiated, which are the standard -- basic types of Haskell, the fixed size Int types -- (Int8, Int16, Int32, Int64), the fixed -- size Word types (Word8, Word16, Word32, -- Word64), StablePtr, all types from -- Foreign.C.Types, as well as Ptr. class Storable a -- | Computes the storage requirements (in bytes) of the argument. The -- value of the argument is not used. sizeOf :: Storable a => a -> Int -- | Computes the alignment constraint of the argument. An alignment -- constraint x is fulfilled by any address divisible by -- x. The value of the argument is not used. alignment :: Storable a => a -> Int -- | Read a value from a memory area regarded as an array of values of the -- same kind. The first argument specifies the start address of the array -- and the second the index into the array (the first element of the -- array has index 0). The following equality holds, -- --
--   peekElemOff addr idx = IOExts.fixIO $ \result ->
--     peek (addr `plusPtr` (idx * sizeOf result))
--   
-- -- Note that this is only a specification, not necessarily the concrete -- implementation of the function. peekElemOff :: Storable a => Ptr a -> Int -> IO a -- | Write a value to a memory area regarded as an array of values of the -- same kind. The following equality holds: -- --
--   pokeElemOff addr idx x = 
--     poke (addr `plusPtr` (idx * sizeOf x)) x
--   
pokeElemOff :: Storable a => Ptr a -> Int -> a -> IO () -- | Read a value from a memory location given by a base address and -- offset. The following equality holds: -- --
--   peekByteOff addr off = peek (addr `plusPtr` off)
--   
peekByteOff :: Storable a => Ptr b -> Int -> IO a -- | Write a value to a memory location given by a base address and offset. -- The following equality holds: -- --
--   pokeByteOff addr off x = poke (addr `plusPtr` off) x
--   
pokeByteOff :: Storable a => Ptr b -> Int -> a -> IO () -- | Read a value from the given memory location. -- -- Note that the peek and poke functions might require properly aligned -- addresses to function correctly. This is architecture dependent; thus, -- portable code should ensure that when peeking or poking values of some -- type a, the alignment constraint for a, as given by -- the function alignment is fulfilled. peek :: Storable a => Ptr a -> IO a -- | Write the given value to the given memory location. Alignment -- restrictions might apply; see peek. poke :: Storable a => Ptr a -> a -> IO () -- | Advances the given address by the given offset in bytes. plusPtr :: Ptr a -> Int -> Ptr b -- | The constant nullPtr contains a distinguished value of -- Ptr that is not associated with a valid memory location. nullPtr :: Ptr a -- | as throwErrnoIfMinus1_, but exceptions include the given path -- when appropriate. throwErrnoPathIfMinus1_ :: (Eq a, Num a) => String -> FilePath -> IO a -> IO () -- | Throw an IOException corresponding to the current value of -- getErrno if the IO action returns nullPtr. throwErrnoIfNull :: String -> IO (Ptr a) -> IO (Ptr a) -- | as throwErrnoIfMinus1, but discards the result. throwErrnoIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO () -- | as throwErrnoIfMinus1, but discards the result. throwErrnoIfMinus1_ :: (Eq a, Num a) => String -> IO a -> IO () -- | Marshal a Haskell string into a NUL terminated C wide string using -- temporary storage. -- -- withCWString :: String -> (CWString -> IO a) -> IO a -- | Marshal a C wide string with explicit length into a Haskell string. peekCWStringLen :: CWStringLen -> IO String -- | Marshal a Haskell string into a NUL terminated C string using -- temporary storage. -- -- withCString :: String -> (CString -> IO a) -> IO a -- | Marshal a NUL terminated C string into a Haskell string. peekCString :: CString -> IO String -- | A C string is a reference to an array of C characters terminated by -- NUL. type CString = Ptr CChar -- | A C wide string is a reference to an array of C wide characters -- terminated by NUL. type CWString = Ptr CWchar -- | Haskell type representing the C unsigned char type. (The -- concrete types of Foreign.C.Types#platform are -- platform-specific.) newtype CUChar CUChar :: Word8 -> CUChar -- | Haskell type representing the C unsigned short type. (The -- concrete types of Foreign.C.Types#platform are -- platform-specific.) newtype CUShort CUShort :: Word16 -> CUShort -- | Haskell type representing the C int type. (The concrete -- types of Foreign.C.Types#platform are platform-specific.) newtype CInt CInt :: Int32 -> CInt -- | Haskell type representing the C long type. (The concrete -- types of Foreign.C.Types#platform are platform-specific.) newtype CLong CLong :: Int64 -> CLong -- | Haskell type representing the C unsigned long type. (The -- concrete types of Foreign.C.Types#platform are -- platform-specific.) newtype CULong CULong :: Word64 -> CULong -- | Haskell type representing the C wchar_t type. (The -- concrete types of Foreign.C.Types#platform are -- platform-specific.) newtype CWchar CWchar :: Int32 -> CWchar -- | Haskell type representing the C time_t type. (The concrete -- types of Foreign.C.Types#platform are platform-specific.) newtype CTime CTime :: Int64 -> CTime -- | The Unicode encoding of the current locale, but allowing arbitrary -- undecodable bytes to be round-tripped through it. -- -- This TextEncoding is used to decode and encode command line -- arguments and environment variables on non-Windows platforms. -- -- On Windows, this encoding *should not* be used if possible because the -- use of code pages is deprecated: Strings should be retrieved via the -- "wide" W-family of UTF-16 APIs instead getFileSystemEncoding :: IO TextEncoding -- | An abstract type that contains a value for each variant of -- IOException. data IOErrorType OtherError :: IOErrorType InappropriateType :: IOErrorType UnsupportedOperation :: IOErrorType -- | Return the value of the environment variable var, or -- Nothing if there is no such value. -- -- For POSIX users, this is equivalent to getEnv. lookupEnv :: String -> IO (Maybe String) -- | Computation getEnv var returns the value of the -- environment variable var. For the inverse, the setEnv -- function can be used. -- -- This computation may fail with: -- -- getEnv :: String -> IO String -- | Computation getArgs returns a list of the program's command -- line arguments (not including the program name). getArgs :: IO [String] -- | The computation exitFailure is equivalent to exitWith -- (ExitFailure exitfail), where -- exitfail is implementation-dependent. exitFailure :: IO a -- | Like openTempFile, but opens the file in binary mode. See -- openBinaryFile for more comments. openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle) -- | withBinaryFile name mode act opens a file using -- openBinaryFile and passes the resulting handle to the -- computation act. The handle will be closed on exit from -- withBinaryFile, whether by normal termination or by raising an -- exception. withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r -- | Computation hClose hdl makes handle hdl -- closed. Before the computation finishes, if hdl is writable -- its buffer is flushed as for hFlush. Performing hClose -- on a handle that has already been closed has no effect; doing so is -- not an error. All other operations on a closed handle will fail. If -- hClose fails for any reason, any further operations (apart from -- hClose) on the handle will still fail as if hdl had -- been successfully closed. hClose :: Handle -> IO () -- | A handle managing output to the Haskell program's standard error -- channel. stderr :: Handle -- | hGetBuf hdl buf count reads data from the handle -- hdl into the buffer buf until either EOF is reached -- or count 8-bit bytes have been read. It returns the number of -- bytes actually read. This may be zero if EOF was reached before any -- data was read (or if count is zero). -- -- hGetBuf never raises an EOF exception, instead it returns a -- value smaller than count. -- -- If the handle is a pipe or socket, and the writing end is closed, -- hGetBuf will behave as if EOF was reached. -- -- hGetBuf ignores the prevailing TextEncoding and -- NewlineMode on the Handle, and reads bytes directly. hGetBuf :: Handle -> Ptr a -> Int -> IO Int -- | hPutBuf hdl buf count writes count 8-bit -- bytes from the buffer buf to the handle hdl. It -- returns (). -- -- hPutBuf ignores any text encoding that applies to the -- Handle, writing the bytes directly to the underlying file or -- device. -- -- hPutBuf ignores the prevailing TextEncoding and -- NewlineMode on the Handle, and writes bytes directly. -- -- This operation may fail with: -- -- hPutBuf :: Handle -> Ptr a -> Int -> IO () -- | The same as hPutStr, but adds a newline character. hPutStrLn :: Handle -> String -> IO () -- | Computation hPutStr hdl s writes the string s -- to the file or channel managed by hdl. -- -- This operation may fail with: -- -- hPutStr :: Handle -> String -> IO () -- | The action hFlush hdl causes any items buffered for -- output in handle hdl to be sent immediately to the operating -- system. -- -- This operation may fail with: -- -- hFlush :: Handle -> IO () -- | A handle managing output to the Haskell program's standard output -- channel. stdout :: Handle -- | Haskell defines operations to read and write characters from and to -- files, represented by values of type Handle. Each value of -- this type is a handle: a record used by the Haskell run-time -- system to manage I/O with file system objects. A handle has at -- least the following properties: -- -- -- -- Most handles will also have a current I/O position indicating where -- the next input or output operation will occur. A handle is -- readable if it manages only input or both input and output; -- likewise, it is writable if it manages only output or both -- input and output. A handle is open when first allocated. Once -- it is closed it can no longer be used for either input or output, -- though an implementation cannot re-use its storage while references -- remain to it. Handles are in the Show and Eq classes. -- The string produced by showing a handle is system dependent; it should -- include enough information to identify the handle for debugging. A -- handle is equal according to == only to itself; no attempt is -- made to compare the internal state of different handles for equality. data Handle -- | See openFile data IOMode ReadMode :: IOMode WriteMode :: IOMode -- | The catchIOError function establishes a handler that receives -- any IOException raised in the action protected by -- catchIOError. An IOException is caught by the most -- recent handler established by one of the exception handling functions. -- These handlers are not selective: all IOExceptions are caught. -- Exception propagation must be explicitly provided in a handler by -- re-raising any unwanted exceptions. For example, in -- --
--   f = catchIOError g (\e -> if IO.isEOFError e then return [] else ioError e)
--   
-- -- the function f returns [] when an end-of-file -- exception (cf. isEOFError) occurs in g; otherwise, the -- exception is propagated to the next outer handler. -- -- When an exception propagates outside the main program, the Haskell -- system prints the associated IOException value and exits the -- program. -- -- Non-I/O exceptions are not caught by this variant; to catch all -- exceptions, use catch from Control.Exception. catchIOError :: IO a -> (IOError -> IO a) -> IO a -- | Catch any IOException that occurs in the computation and throw -- a modified version. modifyIOError :: (IOError -> IOError) -> IO a -> IO a ioeSetFileName :: IOError -> FilePath -> IOError ioeSetLocation :: IOError -> String -> IOError ioeSetErrorString :: IOError -> String -> IOError ioeGetLocation :: IOError -> String ioeGetErrorString :: IOError -> String ioeGetErrorType :: IOError -> IOErrorType -- | I/O error where the operation failed because the user does not have -- sufficient operating system privilege to perform that operation. permissionErrorType :: IOErrorType -- | I/O error where the operation is not possible. illegalOperationErrorType :: IOErrorType -- | An error indicating that an IO operation failed because the -- user does not have sufficient operating system privilege to perform -- that operation. isPermissionError :: IOError -> Bool -- | An error indicating that an IO operation failed because the -- operation was not possible. Any computation which returns an IO -- result may fail with isIllegalOperation. In some cases, an -- implementation will not be able to distinguish between the possible -- error causes. In this case it should fail with -- isIllegalOperation. isIllegalOperation :: IOError -> Bool -- | An error indicating that an IO operation failed because one of -- its arguments does not exist. isDoesNotExistError :: IOError -> Bool -- | An error indicating that an IO operation failed because one of -- its arguments already exists. isAlreadyExistsError :: IOError -> Bool -- | Construct an IOException of the given type where the second -- argument describes the error location and the third and fourth -- argument contain the file handle and file path of the file involved in -- the error if applicable. mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError -- | The construct tryIOError comp exposes IO errors which -- occur within a computation, and which are not fully handled. -- -- Non-I/O exceptions are not caught by this variant; to catch all -- exceptions, use try from Control.Exception. tryIOError :: IO a -> IO (Either IOError a) -- | Construct an IOException value with a string describing the -- error. The fail method of the IO instance of the -- Monad class raises a userError, thus: -- --
--   instance Monad IO where
--     ...
--     fail s = ioError (userError s)
--   
userError :: String -> IOError -- | The Haskell 2010 type for exceptions in the IO monad. Any I/O -- operation may raise an IOException instead of returning a -- result. For a more general type of exception, including also those -- that arise in pure code, see Exception. -- -- In Haskell 2010, this is an opaque type. type IOError = IOException withFilePath :: FilePath -> (CString -> IO a) -> IO a type EpochTime = CTime -- | Wrap an IO computation to time out and return Nothing -- in case no result is available within n microseconds -- (1/10^6 seconds). In case a result is available before the -- timeout expires, Just a is returned. A negative timeout -- interval means "wait indefinitely". When specifying long timeouts, be -- careful not to exceed maxBound :: Int. -- --
--   >>> timeout 1000000 (threadDelay 1000 *> pure "finished on time")
--   Just "finished on time"
--   
-- --
--   >>> timeout 10000 (threadDelay 100000 *> pure "finished on time")
--   Nothing
--   
-- -- The design of this combinator was guided by the objective that -- timeout n f should behave exactly the same as f as -- long as f doesn't time out. This means that f has -- the same myThreadId it would have without the timeout wrapper. -- Any exceptions f might throw cancel the timeout and propagate -- further up. It also possible for f to receive exceptions -- thrown to it by another thread. -- -- A tricky implementation detail is the question of how to abort an -- IO computation. This combinator relies on asynchronous -- exceptions internally (namely throwing the computation the -- Timeout exception). The technique works very well for -- computations executing inside of the Haskell runtime system, but it -- doesn't work at all for non-Haskell code. Foreign function calls, for -- example, cannot be timed out with this combinator simply because an -- arbitrary C function cannot receive asynchronous exceptions. When -- timeout is used to wrap an FFI call that blocks, no timeout -- event can be delivered until the FFI call returns, which pretty much -- negates the purpose of the combinator. In practice, however, this -- limitation is less severe than it may sound. Standard I/O functions -- like hGetBuf, hPutBuf, Network.Socket.accept, or -- hWaitForInput appear to be blocking, but they really don't -- because the runtime system uses scheduling mechanisms like -- select(2) to perform asynchronous I/O, so it is possible to -- interrupt standard socket I/O or file I/O using this combinator. timeout :: Int -> IO a -> IO (Maybe a) -- | Uninhabited data type data Void -- | Internal modules are always subject to change from version to version. -- The contents of this module are also platform-dependent, hence what is -- shown in the Hackage documentation may differ from what is actually -- available on your system. module System.Directory.Internal -- | A generator with side-effects. newtype ListT m a ListT :: m (Maybe (a, ListT m a)) -> ListT m a [unListT] :: ListT m a -> m (Maybe (a, ListT m a)) emptyListT :: Applicative m => ListT m a maybeToListT :: Applicative m => m (Maybe a) -> ListT m a listToListT :: Applicative m => [a] -> ListT m a liftJoinListT :: Monad m => m (ListT m a) -> ListT m a listTHead :: Functor m => ListT m a -> m (Maybe a) listTToList :: Monad m => ListT m a -> m [a] andM :: Monad m => m Bool -> m Bool -> m Bool sequenceWithIOErrors_ :: [IO ()] -> IO () -- | Similar to try but only catches a specify kind of -- IOError as specified by the predicate. tryIOErrorType :: (IOError -> Bool) -> IO a -> IO (Either IOError a) -- | Attempt to perform the given action, silencing any IO exception thrown -- by it. ignoreIOExceptions :: IO () -> IO () specializeErrorString :: String -> (IOError -> Bool) -> IO a -> IO a ioeAddLocation :: IOError -> String -> IOError -- | Given a list of path segments, expand . and ... The -- path segments must not contain path separators. expandDots :: [FilePath] -> [FilePath] -- | Convert to the right kind of slashes. normalisePathSeps :: FilePath -> FilePath -- | Remove redundant trailing slashes and pick the right kind of slash. normaliseTrailingSep :: FilePath -> FilePath -- | Convert empty paths to the current directory, otherwise leave it -- unchanged. emptyToCurDir :: FilePath -> FilePath -- | Similar to normalise but empty paths stay empty. simplifyPosix :: FilePath -> FilePath -- | Similar to normalise but: -- -- -- -- The goal is to preserve the meaning of paths better than -- normalise. simplifyWindows :: FilePath -> FilePath data FileType File :: FileType -- | POSIX: either file or directory link; Windows: file link SymbolicLink :: FileType Directory :: FileType -- | Windows only: directory link DirectoryLink :: FileType -- | Check whether the given FileType is considered a directory by -- the operating system. This affects the choice of certain functions -- e.g. removeDirectory vs removeFile. fileTypeIsDirectory :: FileType -> Bool -- | Return whether the given FileType is a link. fileTypeIsLink :: FileType -> Bool data Permissions Permissions :: Bool -> Bool -> Bool -> Bool -> Permissions [readable] :: Permissions -> Bool [writable] :: Permissions -> Bool [executable] :: Permissions -> Bool [searchable] :: Permissions -> Bool -- | Truncate the destination file and then copy the contents of the source -- file to the destination file. If the destination file already exists, -- its attributes shall remain unchanged. Otherwise, its attributes are -- reset to the defaults. copyFileContents :: FilePath -> FilePath -> IO () -- | Copy all data from a file to a handle. copyFileToHandle :: FilePath -> Handle -> IO () -- | Copy data from one handle to another until end of file. copyHandleData :: Handle -> Handle -> IO () -- | Special directories for storing user-specific application data, -- configuration, and cache files, as specified by the XDG Base -- Directory Specification. -- -- Note: On Windows, XdgData and XdgConfig usually map to -- the same directory. data XdgDirectory -- | For data files (e.g. images). It uses the XDG_DATA_HOME -- environment variable. On non-Windows systems, the default is -- ~/.local/share. On Windows, the default is %APPDATA% -- (e.g. C:/Users/<user>/AppData/Roaming). Can be -- considered as the user-specific equivalent of /usr/share. XdgData :: XdgDirectory -- | For configuration files. It uses the XDG_CONFIG_HOME -- environment variable. On non-Windows systems, the default is -- ~/.config. On Windows, the default is %APPDATA% -- (e.g. C:/Users/<user>/AppData/Roaming). Can be -- considered as the user-specific equivalent of /etc. XdgConfig :: XdgDirectory -- | For non-essential files (e.g. cache). It uses the -- XDG_CACHE_HOME environment variable. On non-Windows systems, -- the default is ~/.cache. On Windows, the default is -- %LOCALAPPDATA% (e.g. -- C:/Users/<user>/AppData/Local). Can be -- considered as the user-specific equivalent of /var/cache. XdgCache :: XdgDirectory -- | Search paths for various application data, as specified by the XDG -- Base Directory Specification. -- -- The list of paths is split using searchPathSeparator, which on -- Windows is a semicolon. -- -- Note: On Windows, XdgDataDirs and XdgConfigDirs usually -- yield the same result. data XdgDirectoryList -- | For data files (e.g. images). It uses the XDG_DATA_DIRS -- environment variable. On non-Windows systems, the default is -- /usr/local/share/ and /usr/share/. On Windows, the -- default is %PROGRAMDATA% or %ALLUSERSPROFILE% (e.g. -- C:/ProgramData). XdgDataDirs :: XdgDirectoryList -- | For configuration files. It uses the XDG_CONFIG_DIRS -- environment variable. On non-Windows systems, the default is -- /etc/xdg. On Windows, the default is %PROGRAMDATA% -- or %ALLUSERSPROFILE% (e.g. C:/ProgramData). XdgConfigDirs :: XdgDirectoryList createDirectoryInternal :: FilePath -> IO () removePathInternal :: Bool -> FilePath -> IO () renamePathInternal :: FilePath -> FilePath -> IO () -- | On POSIX, equivalent to simplifyPosix. simplify :: FilePath -> FilePath c_free :: Ptr a -> IO () c_PATH_MAX :: Maybe Int c_realpath :: CString -> CString -> IO CString withRealpath :: CString -> (CString -> IO a) -> IO a canonicalizePathWith :: ((FilePath -> IO FilePath) -> FilePath -> IO FilePath) -> FilePath -> IO FilePath canonicalizePathSimplify :: FilePath -> IO FilePath findExecutablesLazyInternal :: ([FilePath] -> String -> ListT IO FilePath) -> String -> ListT IO FilePath exeExtensionInternal :: String getDirectoryContentsInternal :: FilePath -> IO [FilePath] getCurrentDirectoryInternal :: IO FilePath -- | Convert a path into an absolute path. If the given path is relative, -- the current directory is prepended and the path may or may not be -- simplified. If the path is already absolute, the path is returned -- unchanged. The function preserves the presence or absence of the -- trailing path separator. -- -- If the path is already absolute, the operation never fails. Otherwise, -- the operation may throw exceptions. -- -- Empty paths are treated as the current directory. prependCurrentDirectory :: FilePath -> IO FilePath setCurrentDirectoryInternal :: FilePath -> IO () linkToDirectoryIsDirectory :: Bool createSymbolicLink :: Bool -> FilePath -> FilePath -> IO () readSymbolicLink :: FilePath -> IO FilePath type Metadata = FileStatus getSymbolicLinkMetadata :: FilePath -> IO Metadata getFileMetadata :: FilePath -> IO Metadata fileTypeFromMetadata :: Metadata -> FileType fileSizeFromMetadata :: Metadata -> Integer accessTimeFromMetadata :: Metadata -> UTCTime modificationTimeFromMetadata :: Metadata -> UTCTime posix_accessTimeHiRes :: FileStatus -> POSIXTime posix_modificationTimeHiRes :: FileStatus -> POSIXTime type Mode = FileMode modeFromMetadata :: Metadata -> Mode allWriteMode :: FileMode hasWriteMode :: Mode -> Bool setWriteMode :: Bool -> Mode -> Mode setFileMode :: FilePath -> Mode -> IO () setFilePermissions :: FilePath -> Mode -> IO () getAccessPermissions :: FilePath -> IO Permissions setAccessPermissions :: FilePath -> Permissions -> IO () copyOwnerFromStatus :: FileStatus -> FilePath -> IO () copyGroupFromStatus :: FileStatus -> FilePath -> IO () tryCopyOwnerAndGroupFromStatus :: FileStatus -> FilePath -> IO () copyFileWithMetadataInternal :: (Metadata -> FilePath -> IO ()) -> (Metadata -> FilePath -> IO ()) -> FilePath -> FilePath -> IO () setTimes :: FilePath -> (Maybe POSIXTime, Maybe POSIXTime) -> IO () -- | Get the contents of the PATH environment variable. getPath :: IO [FilePath] -- | $HOME is preferred, because the user has control over it. However, -- POSIX doesn't define it as a mandatory variable, so fall back to -- getpwuid_r. getHomeDirectoryInternal :: IO FilePath getXdgDirectoryFallback :: IO FilePath -> XdgDirectory -> IO FilePath getXdgDirectoryListFallback :: XdgDirectoryList -> IO [FilePath] getAppUserDataDirectoryInternal :: FilePath -> IO FilePath getUserDocumentsDirectoryInternal :: IO FilePath getTemporaryDirectoryInternal :: IO FilePath -- | System-independent interface to directory manipulation. module System.Directory -- | createDirectory dir creates a new directory -- dir which is initially empty, or as near to empty as the -- operating system allows. -- -- The operation may fail with: -- -- createDirectory :: FilePath -> IO () -- | createDirectoryIfMissing parents dir creates a new -- directory dir if it doesn't exist. If the first argument is -- True the function will also create all parent directories if -- they are missing. createDirectoryIfMissing :: Bool -> FilePath -> IO () -- | removeDirectory dir removes an existing directory -- dir. The implementation may specify additional constraints -- which must be satisfied before a directory can be removed (e.g. the -- directory has to be empty, or may not be in use by other processes). -- It is not legal for an implementation to partially remove a directory -- unless the entire directory is removed. A conformant implementation -- need not support directory removal in all situations (e.g. removal of -- the root directory). -- -- The operation may fail with: -- -- removeDirectory :: FilePath -> IO () -- | removeDirectoryRecursive dir removes an existing -- directory dir together with its contents and subdirectories. -- Within this directory, symbolic links are removed without affecting -- their targets. -- -- On Windows, the operation fails if dir is a directory symbolic -- link. removeDirectoryRecursive :: FilePath -> IO () -- | Removes a file or directory at path together with its contents -- and subdirectories. Symbolic links are removed without affecting their -- targets. If the path does not exist, nothing happens. -- -- Unlike other removal functions, this function will also attempt to -- delete files marked as read-only or otherwise made unremovable due to -- permissions. As a result, if the removal is incomplete, the -- permissions or attributes on the remaining files may be altered. If -- there are hard links in the directory, then permissions on all related -- hard links may be altered. -- -- If an entry within the directory vanishes while -- removePathForcibly is running, it is silently ignored. -- -- If an exception occurs while removing an entry, -- removePathForcibly will still try to remove as many entries -- as it can before failing with an exception. The first exception that -- it encountered is re-thrown. removePathForcibly :: FilePath -> IO () -- | renameDirectory old new changes the name of an -- existing directory from old to new. If the new -- directory already exists, it is atomically replaced by the old -- directory. If the new directory is neither the old -- directory nor an alias of the old directory, it is removed as -- if by removeDirectory. A conformant implementation need not -- support renaming directories in all situations (e.g. renaming to an -- existing directory, or across different physical devices), but the -- constraints must be documented. -- -- On Win32 platforms, renameDirectory fails if the new -- directory already exists. -- -- The operation may fail with: -- -- renameDirectory :: FilePath -> FilePath -> IO () -- | listDirectory dir returns a list of all entries -- in dir without the special entries (. and -- ..). -- -- The operation may fail with: -- -- listDirectory :: FilePath -> IO [FilePath] -- | Similar to listDirectory, but always includes the special -- entries (. and ..). (This applies to Windows as -- well.) -- -- The operation may fail with the same exceptions as -- listDirectory. getDirectoryContents :: FilePath -> IO [FilePath] -- | Obtain the current working directory as an absolute path. -- -- In a multithreaded program, the current working directory is a global -- state shared among all threads of the process. Therefore, when -- performing filesystem operations from multiple threads, it is highly -- recommended to use absolute rather than relative paths (see: -- makeAbsolute). -- -- The operation may fail with: -- -- getCurrentDirectory :: IO FilePath -- | Change the working directory to the given path. -- -- In a multithreaded program, the current working directory is a global -- state shared among all threads of the process. Therefore, when -- performing filesystem operations from multiple threads, it is highly -- recommended to use absolute rather than relative paths (see: -- makeAbsolute). -- -- The operation may fail with: -- -- setCurrentDirectory :: FilePath -> IO () -- | Run an IO action with the given working directory and restore -- the original working directory afterwards, even if the given action -- fails due to an exception. -- -- The operation may fail with the same exceptions as -- getCurrentDirectory and setCurrentDirectory. withCurrentDirectory :: FilePath -> IO a -> IO a -- | Returns the current user's home directory. -- -- The directory returned is expected to be writable by the current user, -- but note that it isn't generally considered good practice to store -- application-specific data here; use getXdgDirectory or -- getAppUserDataDirectory instead. -- -- On Unix, getHomeDirectory behaves as follows: -- -- -- -- On Windows, the system is queried for a suitable path; a typical path -- might be C:/Users/<user>. -- -- The operation may fail with: -- -- getHomeDirectory :: IO FilePath -- | Special directories for storing user-specific application data, -- configuration, and cache files, as specified by the XDG Base -- Directory Specification. -- -- Note: On Windows, XdgData and XdgConfig usually map to -- the same directory. data XdgDirectory -- | For data files (e.g. images). It uses the XDG_DATA_HOME -- environment variable. On non-Windows systems, the default is -- ~/.local/share. On Windows, the default is %APPDATA% -- (e.g. C:/Users/<user>/AppData/Roaming). Can be -- considered as the user-specific equivalent of /usr/share. XdgData :: XdgDirectory -- | For configuration files. It uses the XDG_CONFIG_HOME -- environment variable. On non-Windows systems, the default is -- ~/.config. On Windows, the default is %APPDATA% -- (e.g. C:/Users/<user>/AppData/Roaming). Can be -- considered as the user-specific equivalent of /etc. XdgConfig :: XdgDirectory -- | For non-essential files (e.g. cache). It uses the -- XDG_CACHE_HOME environment variable. On non-Windows systems, -- the default is ~/.cache. On Windows, the default is -- %LOCALAPPDATA% (e.g. -- C:/Users/<user>/AppData/Local). Can be -- considered as the user-specific equivalent of /var/cache. XdgCache :: XdgDirectory -- | Obtain the paths to special directories for storing user-specific -- application data, configuration, and cache files, conforming to the -- XDG Base Directory Specification. Compared with -- getAppUserDataDirectory, this function provides a more -- fine-grained hierarchy as well as greater flexibility for the user. -- -- On Windows, XdgData and XdgConfig usually map to the -- same directory unless overridden. -- -- Refer to the docs of XdgDirectory for more details. -- -- The second argument is usually the name of the application. Since it -- will be integrated into the path, it must consist of valid path -- characters. Note: if the second argument is an absolute path, it will -- just return the second argument. -- -- Note: The directory may not actually exist, in which case you would -- need to create it with file mode 700 (i.e. only accessible by -- the owner). -- -- As of 1.3.5.0, the environment variable is ignored if set to a -- relative path, per revised XDG Base Directory Specification. See -- #100. getXdgDirectory :: XdgDirectory -> FilePath -> IO FilePath -- | Search paths for various application data, as specified by the XDG -- Base Directory Specification. -- -- The list of paths is split using searchPathSeparator, which on -- Windows is a semicolon. -- -- Note: On Windows, XdgDataDirs and XdgConfigDirs usually -- yield the same result. data XdgDirectoryList -- | For data files (e.g. images). It uses the XDG_DATA_DIRS -- environment variable. On non-Windows systems, the default is -- /usr/local/share/ and /usr/share/. On Windows, the -- default is %PROGRAMDATA% or %ALLUSERSPROFILE% (e.g. -- C:/ProgramData). XdgDataDirs :: XdgDirectoryList -- | For configuration files. It uses the XDG_CONFIG_DIRS -- environment variable. On non-Windows systems, the default is -- /etc/xdg. On Windows, the default is %PROGRAMDATA% -- or %ALLUSERSPROFILE% (e.g. C:/ProgramData). XdgConfigDirs :: XdgDirectoryList -- | Similar to getXdgDirectory but retrieves the entire list of XDG -- directories. -- -- On Windows, XdgDataDirs and XdgConfigDirs usually map to -- the same list of directories unless overridden. -- -- Refer to the docs of XdgDirectoryList for more details. getXdgDirectoryList :: XdgDirectoryList -> IO [FilePath] -- | Obtain the path to a special directory for storing user-specific -- application data (traditional Unix location). Newer applications may -- prefer the the XDG-conformant location provided by -- getXdgDirectory (migration guide). -- -- The argument is usually the name of the application. Since it will be -- integrated into the path, it must consist of valid path characters. -- -- -- -- Note: the directory may not actually exist, in which case you would -- need to create it. It is expected that the parent directory exists and -- is writable. -- -- The operation may fail with: -- -- getAppUserDataDirectory :: FilePath -> IO FilePath -- | Returns the current user's document directory. -- -- The directory returned is expected to be writable by the current user, -- but note that it isn't generally considered good practice to store -- application-specific data here; use getXdgDirectory or -- getAppUserDataDirectory instead. -- -- On Unix, getUserDocumentsDirectory returns the value of the -- HOME environment variable. On Windows, the system is queried -- for a suitable path; a typical path might be -- C:/Users/<user>/Documents. -- -- The operation may fail with: -- -- getUserDocumentsDirectory :: IO FilePath -- | Returns the current directory for temporary files. -- -- On Unix, getTemporaryDirectory returns the value of the -- TMPDIR environment variable or "/tmp" if the variable isn't -- defined. On Windows, the function checks for the existence of -- environment variables in the following order and uses the first path -- found: -- -- -- -- The operation may fail with: -- -- -- -- The function doesn't verify whether the path exists. getTemporaryDirectory :: IO FilePath -- | removeFile file removes the directory entry for an -- existing file file, where file is not itself a -- directory. The implementation may specify additional constraints which -- must be satisfied before a file can be removed (e.g. the file may not -- be in use by other processes). -- -- The operation may fail with: -- -- removeFile :: FilePath -> IO () -- | renameFile old new changes the name of an existing -- file system object from old to new. If the new -- object already exists, it is atomically replaced by the old -- object. Neither path may refer to an existing directory. A conformant -- implementation need not support renaming files in all situations (e.g. -- renaming across different physical devices), but the constraints must -- be documented. -- -- The operation may fail with: -- -- renameFile :: FilePath -> FilePath -> IO () -- | Rename a file or directory. If the destination path already exists, it -- is replaced atomically. The destination path must not point to an -- existing directory. A conformant implementation need not support -- renaming files in all situations (e.g. renaming across different -- physical devices), but the constraints must be documented. -- -- The operation may fail with: -- -- renamePath :: FilePath -> FilePath -> IO () -- | Copy a file with its permissions. If the destination file already -- exists, it is replaced atomically. Neither path may refer to an -- existing directory. No exceptions are thrown if the permissions could -- not be copied. copyFile :: FilePath -> FilePath -> IO () -- | Copy a file with its associated metadata. If the destination file -- already exists, it is overwritten. There is no guarantee of atomicity -- in the replacement of the destination file. Neither path may refer to -- an existing directory. If the source and/or destination are symbolic -- links, the copy is performed on the targets of the links. -- -- On Windows, it behaves like the Win32 function CopyFile, which -- copies various kinds of metadata including file attributes and -- security resource properties. -- -- On Unix-like systems, permissions, access time, and modification time -- are preserved. If possible, the owner and group are also preserved. -- Note that the very act of copying can change the access time of the -- source file, hence the access times of the two files may differ after -- the operation completes. copyFileWithMetadata :: FilePath -> FilePath -> IO () -- | Obtain the size of a file in bytes. getFileSize :: FilePath -> IO Integer -- | Make a path absolute, normalize the path, and remove as many -- indirections from it as possible. Any trailing path separators are -- discarded via dropTrailingPathSeparator. Additionally, on -- Windows the letter case of the path is canonicalized. -- -- Note: This function is a very big hammer. If you only need an -- absolute path, makeAbsolute is sufficient for removing -- dependence on the current working directory. -- -- Indirections include the two special directories . and -- .., as well as any symbolic links (and junction points on -- Windows). The input path need not point to an existing file or -- directory. Canonicalization is performed on the longest prefix of the -- path that points to an existing file or directory. The remaining -- portion of the path that does not point to an existing file or -- directory will still be normalized, but case canonicalization and -- indirection removal are skipped as they are impossible to do on a -- nonexistent path. -- -- Most programs should not worry about the canonicity of a path. In -- particular, despite the name, the function does not truly guarantee -- canonicity of the returned path due to the presence of hard links, -- mount points, etc. -- -- If the path points to an existing file or directory, then the output -- path shall also point to the same file or directory, subject to the -- condition that the relevant parts of the file system do not change -- while the function is still running. In other words, the function is -- definitively not atomic. The results can be utterly wrong if the -- portions of the path change while this function is running. -- -- Since some indirections (symbolic links on all systems, .. on -- non-Windows systems, and junction points on Windows) are dependent on -- the state of the existing filesystem, the function can only make a -- conservative attempt by removing such indirections from the longest -- prefix of the path that still points to an existing file or directory. -- -- Note that on Windows parent directories .. are always fully -- expanded before the symbolic links, as consistent with the rest of the -- Windows API (such as GetFullPathName). In contrast, on POSIX -- systems parent directories .. are expanded alongside symbolic -- links from left to right. To put this more concretely: if L -- is a symbolic link for R/P, then on Windows L\.. -- refers to ., whereas on other operating systems L/.. -- refers to R. -- -- Similar to normalise, passing an empty path is equivalent to -- passing the current directory. -- -- canonicalizePath can resolve at least 64 indirections in a -- single path, more than what is supported by most operating systems. -- Therefore, it may return the fully resolved path even though the -- operating system itself would have long given up. -- -- On Windows XP or earlier systems, junction expansion is not performed -- due to their lack of GetFinalPathNameByHandle. -- -- Changes since 1.2.3.0: The function has been altered to be more -- robust and has the same exception behavior as makeAbsolute. -- -- Changes since 1.3.0.0: The function no longer preserves the -- trailing path separator. File symbolic links that appear in the middle -- of a path are properly dereferenced. Case canonicalization and -- symbolic link expansion are now performed on Windows. canonicalizePath :: FilePath -> IO FilePath -- | Convert a path into an absolute path. If the given path is relative, -- the current directory is prepended and then the combined result is -- normalized. If the path is already absolute, the path is simply -- normalized. The function preserves the presence or absence of the -- trailing path separator unless the path refers to the root directory -- /. -- -- If the path is already absolute, the operation never fails. Otherwise, -- the operation may fail with the same exceptions as -- getCurrentDirectory. makeAbsolute :: FilePath -> IO FilePath -- | Construct a path relative to the current directory, similar to -- makeRelative. -- -- The operation may fail with the same exceptions as -- getCurrentDirectory. makeRelativeToCurrentDirectory :: FilePath -> IO FilePath -- | Test whether the given path points to an existing filesystem object. -- If the user lacks necessary permissions to search the parent -- directories, this function may return false even if the file does -- actually exist. doesPathExist :: FilePath -> IO Bool -- | The operation doesFileExist returns True if the argument -- file exists and is not a directory, and False otherwise. doesFileExist :: FilePath -> IO Bool -- | The operation doesDirectoryExist returns True if the -- argument file exists and is either a directory or a symbolic link to a -- directory, and False otherwise. doesDirectoryExist :: FilePath -> IO Bool -- | Given the name or path of an executable file, findExecutable -- searches for such a file in a list of system-defined locations, which -- generally includes PATH and possibly more. The full path to -- the executable is returned if found. For example, (findExecutable -- "ghc") would normally give you the path to GHC. -- -- The path returned by findExecutable name corresponds -- to the program that would be executed by createProcess -- when passed the same string (as a RawCommand, not a -- ShellCommand), provided that name is not a relative -- path with more than one segment. -- -- On Windows, findExecutable calls the Win32 function -- SearchPath, which may search other places before -- checking the directories in the PATH environment variable. -- Where it actually searches depends on registry settings, but notably -- includes the directory containing the current executable. -- -- On non-Windows platforms, the behavior is equivalent to -- findFileWith using the search directories from the -- PATH environment variable and testing each file for -- executable permissions. Details can be found in the documentation of -- findFileWith. findExecutable :: String -> IO (Maybe FilePath) -- | Search for executable files in a list of system-defined locations, -- which generally includes PATH and possibly more. -- -- On Windows, this only returns the first ocurrence, if any. Its -- behavior is therefore equivalent to findExecutable. -- -- On non-Windows platforms, the behavior is equivalent to -- findExecutablesInDirectories using the search directories from -- the PATH environment variable. Details can be found in the -- documentation of findExecutablesInDirectories. findExecutables :: String -> IO [FilePath] -- | Given a name or path, findExecutable appends the -- exeExtension to the query and searches for executable files in -- the list of given search directories and returns all occurrences. -- -- The behavior is equivalent to findFileWith using the given -- search directories and testing each file for executable permissions. -- Details can be found in the documentation of findFileWith. -- -- Unlike other similarly named functions, -- findExecutablesInDirectories does not use SearchPath -- from the Win32 API. The behavior of this function on Windows is -- therefore equivalent to those on non-Windows platforms. findExecutablesInDirectories :: [FilePath] -> String -> IO [FilePath] -- | Search through the given list of directories for the given file. -- -- The behavior is equivalent to findFileWith, returning only the -- first occurrence. Details can be found in the documentation of -- findFileWith. findFile :: [FilePath] -> String -> IO (Maybe FilePath) -- | Search through the given list of directories for the given file and -- returns all paths where the given file exists. -- -- The behavior is equivalent to findFilesWith. Details can be -- found in the documentation of findFilesWith. findFiles :: [FilePath] -> String -> IO [FilePath] -- | Search through a given list of directories for a file that has the -- given name and satisfies the given predicate and return the path of -- the first occurrence. The directories are checked in a left-to-right -- order. -- -- This is essentially a more performant version of findFilesWith -- that always returns the first result, if any. Details can be found in -- the documentation of findFilesWith. findFileWith :: (FilePath -> IO Bool) -> [FilePath] -> String -> IO (Maybe FilePath) -- | findFilesWith predicate dirs name searches through the list -- of directories (dirs) for files that have the given -- name and satisfy the given predicate ands return the -- paths of those files. The directories are checked in a left-to-right -- order and the paths are returned in the same order. -- -- If the name is a relative path, then for every search -- directory dir, the function checks whether dir -- </> name exists and satisfies the predicate. If so, -- dir </> name is returned as one of the results. -- In other words, the returned paths can be either relative or absolute -- depending on the search directories were used. If there are no search -- directories, no results are ever returned. -- -- If the name is an absolute path, then the function will -- return a single result if the file exists and satisfies the predicate -- and no results otherwise. This is irrespective of what search -- directories were given. findFilesWith :: (FilePath -> IO Bool) -> [FilePath] -> String -> IO [FilePath] -- | Filename extension for executable files (including the dot if any) -- (usually "" on POSIX systems and ".exe" on Windows -- or OS/2). exeExtension :: String -- | Create a file symbolic link. The target path can be either -- absolute or relative and need not refer to an existing file. The order -- of arguments follows the POSIX convention. -- -- To remove an existing file symbolic link, use removeFile. -- -- Although the distinction between file symbolic links and -- directory symbolic links does not exist on POSIX systems, on -- Windows this is an intrinsic property of every symbolic link and -- cannot be changed without recreating the link. A file symbolic link -- that actually points to a directory will fail to dereference and vice -- versa. Moreover, creating symbolic links on Windows may require -- privileges unavailable to users outside the Administrators group. -- Portable programs that use symbolic links should take both into -- consideration. -- -- On Windows, the function is implemented using -- CreateSymbolicLink. Since 1.3.3.0, the -- SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE flag is included -- if supported by the operating system. On POSIX, the function uses -- symlink and is therefore atomic. -- -- Windows-specific errors: This operation may fail with -- permissionErrorType if the user lacks the privileges to create -- symbolic links. It may also fail with illegalOperationErrorType -- if the file system does not support symbolic links. createFileLink :: FilePath -> FilePath -> IO () -- | Create a directory symbolic link. The target path can be either -- absolute or relative and need not refer to an existing directory. The -- order of arguments follows the POSIX convention. -- -- To remove an existing directory symbolic link, use -- removeDirectoryLink. -- -- Although the distinction between file symbolic links and -- directory symbolic links does not exist on POSIX systems, on -- Windows this is an intrinsic property of every symbolic link and -- cannot be changed without recreating the link. A file symbolic link -- that actually points to a directory will fail to dereference and vice -- versa. Moreover, creating symbolic links on Windows may require -- privileges unavailable to users outside the Administrators group. -- Portable programs that use symbolic links should take both into -- consideration. -- -- On Windows, the function is implemented using -- CreateSymbolicLink with -- SYMBOLIC_LINK_FLAG_DIRECTORY. Since 1.3.3.0, the -- SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE flag is also -- included if supported by the operating system. On POSIX, this is an -- alias for createFileLink and is therefore atomic. -- -- Windows-specific errors: This operation may fail with -- permissionErrorType if the user lacks the privileges to create -- symbolic links. It may also fail with illegalOperationErrorType -- if the file system does not support symbolic links. createDirectoryLink :: FilePath -> FilePath -> IO () -- | Remove an existing directory symbolic link. -- -- On Windows, this is an alias for removeDirectory. On POSIX -- systems, this is an alias for removeFile. -- -- See also: removeFile, which can remove an existing file -- symbolic link. removeDirectoryLink :: FilePath -> IO () -- | Check whether an existing path is a symbolic link. If -- path is a regular file or directory, False is -- returned. If path does not exist or is otherwise -- inaccessible, an exception is thrown (see below). -- -- On Windows, this checks for FILE_ATTRIBUTE_REPARSE_POINT. In -- addition to symbolic links, the function also returns true on junction -- points. On POSIX systems, this checks for S_IFLNK. -- -- The operation may fail with: -- -- pathIsSymbolicLink :: FilePath -> IO Bool -- | Retrieve the target path of either a file or directory symbolic link. -- The returned path may not be absolute, may not exist, and may not even -- be a valid path. -- -- On Windows systems, this calls DeviceIoControl with -- FSCTL_GET_REPARSE_POINT. In addition to symbolic links, the -- function also works on junction points. On POSIX systems, this calls -- readlink. -- -- Windows-specific errors: This operation may fail with -- illegalOperationErrorType if the file system does not support -- symbolic links. getSymbolicLinkTarget :: FilePath -> IO FilePath data Permissions emptyPermissions :: Permissions readable :: Permissions -> Bool writable :: Permissions -> Bool executable :: Permissions -> Bool searchable :: Permissions -> Bool setOwnerReadable :: Bool -> Permissions -> Permissions setOwnerWritable :: Bool -> Permissions -> Permissions setOwnerExecutable :: Bool -> Permissions -> Permissions setOwnerSearchable :: Bool -> Permissions -> Permissions -- | Get the permissions of a file or directory. -- -- On Windows, the writable permission corresponds to the -- "read-only" attribute. The executable permission is set if the -- file extension is of an executable file type. The readable -- permission is always set. -- -- On POSIX systems, this returns the result of access. -- -- The operation may fail with: -- -- getPermissions :: FilePath -> IO Permissions -- | Set the permissions of a file or directory. -- -- On Windows, this is only capable of changing the writable -- permission, which corresponds to the "read-only" attribute. Changing -- the other permissions has no effect. -- -- On POSIX systems, this sets the owner permissions. -- -- The operation may fail with: -- -- setPermissions :: FilePath -> Permissions -> IO () -- | Copy the permissions of one file to another. This reproduces the -- permissions more accurately than using getPermissions followed -- by setPermissions. -- -- On Windows, this copies only the read-only attribute. -- -- On POSIX systems, this is equivalent to stat followed by -- chmod. copyPermissions :: FilePath -> FilePath -> IO () -- | Obtain the time at which the file or directory was last accessed. -- -- The operation may fail with: -- -- -- -- Caveat for POSIX systems: This function returns a timestamp with -- sub-second resolution only if this package is compiled against -- unix-2.6.0.0 or later and the underlying filesystem supports -- them. getAccessTime :: FilePath -> IO UTCTime -- | Obtain the time at which the file or directory was last modified. -- -- The operation may fail with: -- -- -- -- Caveat for POSIX systems: This function returns a timestamp with -- sub-second resolution only if this package is compiled against -- unix-2.6.0.0 or later and the underlying filesystem supports -- them. getModificationTime :: FilePath -> IO UTCTime -- | Change the time at which the file or directory was last accessed. -- -- The operation may fail with: -- -- -- -- Some caveats for POSIX systems: -- -- setAccessTime :: FilePath -> UTCTime -> IO () -- | Change the time at which the file or directory was last modified. -- -- The operation may fail with: -- -- -- -- Some caveats for POSIX systems: -- -- setModificationTime :: FilePath -> UTCTime -> IO () -- | Deprecated: Use pathIsSymbolicLink instead isSymbolicLink :: FilePath -> IO Bool