HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

ModuleCabal-3.12.1.0Haskell2010

Distribution.Simple.Utils

A large and somewhat miscellaneous collection of utility functions used throughout the rest of the Cabal lib and in other tools that use the Cabal lib like cabal-install. It has a very simple set of logging actions. It has low level functions for running programs, a bunch of wrappers for various directory and file functions that do extra logging.

  • 4 types
  • 1 class
  • 118 values
  • PackageCabal-3.12.1.0
  • Exports123
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceUtils.hs

logging and errors

21 declarations
valuewarn :: Verbosity -> String -> IO ()
#

Non fatal conditions that may be indicative of an error or problem.

We display these at the normal verbosity level.

valuewarnError :: Verbosity -> String -> IO ()
#

Like warn, but prepend Error: … instead of Waring: … before the the message. Useful when you want to highlight the condition is an error but do not want to quit the program yet.

valuenotice :: Verbosity -> String -> IO ()
#

Useful status messages.

We display these at the normal verbosity level.

This is for the ordinary helpful status messages that users see. Just enough information to know that things are working but not floods of detail.

valueinfo :: Verbosity -> String -> IO ()
#

More detail on the operation of some action.

We display these messages when the verbosity level is verbose

valuechattyTry
  1. :: String

    a description of the action we were attempting

  2. -> IO ()

    the action itself

  3. -> IO ()
#

Perform an IO action, catching any IO exceptions and printing an error if one occurs.

valueannotateIO :: Verbosity -> IO a -> IO a
#

Given a block of IO code that may raise an exception, annotate it with the metadata from the current scope. Use this as close to external code that raises IO exceptions as possible, since this function unconditionally wraps the error message with a trace (so it is NOT idempotent.)

Wrap output with a marker if +markoutput verbosity flag is set.

NB: Why is markoutput done with start/end markers, and not prefixes? Markers are more convenient to add (if we want to add prefixes, we have to lines and then map; here's it's just some concatenates). Note that even in the prefix case, we can't guarantee that the markers are unambiguous, because some of Cabal's output comes straight from external programs, where we don't have the ability to interpose on the output.

This is used by withMetadata

exceptions

2 declarations
valuehandleDoesNotExist :: a -> IO a -> IO a
#

Run an IO computation, returning e if it raises a "file does not exist" error.

running programs

13 declarations

Execute the given command with the given arguments, returning the command's exit code.

Create the process argument with proc to ensure consistent options with other rawSystem functions in this module.

Execute the given command with the given arguments, returning the command's exit code. action is executed while the command is running, and would typically be used to communicate with the process through pipes.

Create the process argument with proc to ensure consistent options with other rawSystem functions in this module.

valuerawSystemStdInOut
  1. :: KnownIODataMode mode
  2. => Verbosity
  3. -> FilePath

    Program location

  4. -> [String]

    Arguments

  5. -> Maybe FilePath

    New working dir or inherit

  6. -> Maybe [(String, String)]

    New environment or inherit

  7. -> Maybe IOData

    input text and binary mode

  8. -> IODataMode mode

    iodata mode, acts as proxy

  9. -> IO (mode, String, ExitCode)

    output, errors, exit

#

Execute the given command with the given arguments, returning the command's output, errors and exit code.

Optional arguments allow setting working directory, environment and command input.

Provides control over the binary/text mode of the input and output.

valuerawSystemIOWithEnvAndAction
  1. :: Verbosity
  2. -> FilePath
  3. -> [String]
  4. -> Maybe FilePath

    New working dir or inherit

  5. -> Maybe [(String, String)]

    New environment or inherit

  6. -> IO a

    action to perform after process is created, but before waitForProcess.

  7. -> Maybe Handle

    stdin

  8. -> Maybe Handle

    stdout

  9. -> Maybe Handle

    stderr

  10. -> IO (ExitCode, a)
#

Execute the given command with the given arguments, returning the command's exit code. action is executed while the command is running, and would typically be used to communicate with the process through pipes.

Optional arguments allow setting working directory, environment and input and output handles.

valuemaybeExit :: IO ExitCode -> IO ()
#

Helper to use with one of the rawSystem variants, and exit unless the command completes successfully.

valuexargs :: Int -> ([String] -> IO ()) -> [String] -> [String] -> IO ()
#

Like the Unix xargs program. Useful for when we've got very long command lines that might overflow an OS limit on command line length and so you need to invoke a command multiple times to get all the args in.

Use it with either of the rawSystem variants above. For example:

xargs (32*1024) (rawSystemExit verbosity) prog fixedArgs bigArgs
valuefindProgramVersion
  1. :: String

    version args

  2. -> (String -> String)

    function to select version number from program output

  3. -> Verbosity
  4. -> FilePath

    location

  5. -> IO (Maybe Version)
#

Look for a program and try to find it's version number. It can accept either an absolute path or the name of a program binary, in which case we will look for the program on the path.

IOData re-export

datadata IOData
#

Represents either textual or binary data passed via I/O functions which support binary/text mode

Constructors

Instances1NFData
  • NFData IODataDefined in Cabal-3.12.1.0 · Distribution.Utils.IOData
classclass NFData mode => KnownIODataMode mode where
#

Methods

Instances2KnownIODataMode

copying files

4 declarations
valuecopyFileVerbose :: Verbosity -> FilePath -> FilePath -> IO ()
#

Copies a file without copying file permissions. The target file is created with default permissions. Any existing target file is replaced.

At higher verbosity levels it logs an info message.

valuecopyFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)] -> IO ()
#

Copies a bunch of files to a target directory, preserving the directory structure in the target location. The target directories are created if they do not exist.

The files are identified by a pair of base directory and a path relative to that base. It is only the relative part that is preserved in the destination.

For example:

copyFiles normal "dist/src"
   [("", "src/Foo.hs"), ("dist/build/", "src/Bar.hs")]

This would copy "src/Foo.hs" to "dist/src/src/Foo.hs" and copy "dist/build/src/Bar.hs" to "dist/src/src/Bar.hs".

This operation is not atomic. Any IO failure during the copy (including any missing source files) leaves the target in an unknown state so it is best to use it with a freshly created directory so that it can be simply deleted if anything goes wrong.

valuecopyFileTo :: Verbosity -> FilePath -> FilePath -> IO ()
#

Given a relative path to a file, copy it to the given directory, preserving the relative path and creating the parent directories if needed.

installing files

8 declarations

Install an ordinary file. This is like a file copy but the permissions are set appropriately for an installed file. On Unix it is "-rw-r--r--" while on Windows it uses the default permissions for the target directory.

Install an executable file. This is like a file copy but the permissions are set appropriately for an installed file. On Unix it is "-rwxr-xr-x" while on Windows it uses the default permissions for the target directory.

File permissions

3 declarations

file names

4 declarations
valuecurrentDir :: FilePath
#

The path name that represents the current directory. In Unix, it's ".", but this is system-specific. (E.g. AmigaOS uses the empty string "" for the current directory.)

valueexeExtensions :: [String]
#

List of possible executable file extensions on the current build platform.

finding files

11 declarations

Find a file by looking in a search path with one of a list of possible file extensions. The file base name should be given and it will be tried with each of the extensions in each element of the search path.

List all the files in a directory and all subdirectories.

The order places files in sub-directories after all the files in their parent directories. The list is generated lazily so is not well defined if the source directory structure changes before the list is used.

environment variables

2 declarations

modification time

2 declarations

Compare the modification times of two files to see if the first is newer than the second. The first file must exist but the second need not. The expected use case is when the second file is generated using the first. In this use case, if the result is True then the second file is out of date.

temp files and dirs

7 declarations

Create and use a temporary directory.

Creates a new temporary directory inside the given directory, making use of the template. The temp directory is deleted after use. For example:

withTempDirectory verbosity "src" "sdist." $ \tmpDir -> do ...

The tmpDir will be a new subdirectory of the given directory, e.g. src/sdist.342.

.cabal and .buildinfo files

6 declarations

reading and writing files safely

4 declarations
valuewithFileContents :: FilePath -> (String -> IO a) -> IO a
#

Gets the contents of a file, but guarantee that it gets closed.

The file is read lazily but if it is not fully consumed by the action then the remaining input is truncated and the file is closed.

valuewriteFileAtomic :: FilePath -> ByteString -> IO ()
#

Writes a file atomically.

The file is either written successfully or an IO exception is raised and the original file is left unchanged.

On windows it is not possible to delete a file that is open by a process. This case will give an IO exception but the atomic property is not affected.

valuerewriteFileEx :: Verbosity -> FilePath -> String -> IO ()
#

Write a file but only if it would have new content. If we would be writing the same as the existing content then leave the file as is so that we do not update the file's modification time.

NB: Before Cabal-3.0 the file content was assumed to be ASCII-representable. Since Cabal-3.0 the file is assumed to be UTF-8 encoded.

Unicode

8 declarations
valuefromUTF8BS :: ByteString -> String
#

Decode String from UTF8-encoded BS.ByteString

Invalid data in the UTF8 stream (this includes code-points U+D800 through U+DFFF) will be decoded as the replacement character (U+FFFD).

BOM

1 declaration

generic utils

19 declarations
valuedropWhileEndLE :: (a -> Bool) -> [a] -> [a]
#

dropWhileEndLE p is equivalent to reverse . dropWhile p . reverse, but quite a bit faster. The difference between "Data.List.dropWhileEnd" and this version is that the one in Data.List is strict in elements, but spine-lazy, while this one is spine-strict but lazy in elements. That's what LE stands for - "lazy in elements".

Example:

Example1 expression
safeTail $ Data.List.dropWhileEnd (<3) [undefined, 5, 4, 3, 2, 1]*** Exception: Prelude.undefined...
Example1 expression
safeTail $ dropWhileEndLE (<3) [undefined, 5, 4, 3, 2, 1][5,4,3]
Example1 expression
take 3 $ Data.List.dropWhileEnd (<3) [5, 4, 3, 2, 1, undefined][5,4,3]
Example1 expression
take 3 $ dropWhileEndLE (<3) [5, 4, 3, 2, 1, undefined]*** Exception: Prelude.undefined...
valuetakeWhileEndLE :: (a -> Bool) -> [a] -> [a]
#

takeWhileEndLE p is equivalent to reverse . takeWhile p . reverse, but is usually faster (as well as being easier to read).

valuecomparing :: Ord a => (b -> a) -> b -> b -> Ordering
#
comparing p x y = compare (p x) (p y)

Useful combinator for use in conjunction with the xxxBy family of functions from Data.List, for example:

  ... sortBy (comparing fst) ...
valueisInfixOf :: Eq a => [a] -> [a] -> Bool
#

The isInfixOf function takes two lists and returns True iff the first list is contained, wholly and intact, anywhere within the second.

Examples
Example1 expression
isInfixOf "Haskell" "I really like Haskell."True
Example1 expression
isInfixOf "Ial" "I really like Haskell."False

For the result to be True, the first list must be finite; for the result to be False, the second list must be finite:

Example1 expression
[20..50] `isInfixOf` [0..]True
Example1 expression
[0..] `isInfixOf` [20..50]False
Example1 expression
[0..] `isInfixOf` [0..]* Hangs forever *
valueintercalate :: [a] -> [[a]] -> [a]
#

intercalate xs xss is equivalent to (concat (intersperse xs xss)). It inserts the list xs in between the lists in xss and concatenates the result.

Laziness

intercalate has the following properties:

Example1 expression
take 5 (intercalate undefined ("Lorem" : undefined))"Lorem"
Example1 expression
take 6 (intercalate ", " ("Lorem" : undefined))"Lorem*** Exception: Prelude.undefined
Examples
Example1 expression
intercalate ", " ["Lorem", "ipsum", "dolor"]"Lorem, ipsum, dolor"
Example1 expression
intercalate [0, 1] [[2, 3], [4, 5, 6], []][2,3,0,1,4,5,6,0,1]
Example1 expression
intercalate [1, 2, 3] [[], []][1,2,3]
valuelistUnion :: Ord a => [a] -> [a] -> [a]
#

Like "Data.List.union", but has O(n log n) complexity instead of O(n^2).

valuelistUnionRight :: Ord a => [a] -> [a] -> [a]
#

A right-biased version of listUnion.

Example:

Example1 expression
listUnion [1,2,3,4,3] [2,1,1][1,2,3,4,3]
Example1 expression
listUnionRight [1,2,3,4,3] [2,1,1][4,3,2,1,1]
valueordNub :: Ord a => [a] -> [a]
#

Like nub, but has O(n log n) complexity instead of O(n^2). Code for ordNub and listUnion taken from Niklas Hambüchen's ordnub package.

valueordNubBy :: Ord b => (a -> b) -> [a] -> [a]
#

Like ordNub and nubBy. Selects a key for each element and takes the nub based on that key.

valueordNubRight :: Ord a => [a] -> [a]
#

A right-biased version of ordNub.

Example:

Example1 expression
ordNub [1,2,1] :: [Int][1,2]
Example1 expression
ordNubRight [1,2,1] :: [Int][2,1]
valuewrapText :: String -> String
#

Wraps text to the default line width. Existing newlines are preserved.

valuewrapLine :: Int -> [String] -> [[String]]
#

Wraps a list of words to a list of lines of words of a particular width.

FilePath stuff

3 declarations

isAbsoluteOnAnyPlatform and isRelativeOnAnyPlatform are like System.FilePath.isAbsolute and System.FilePath.isRelative but have platform independent heuristics. The System.FilePath exists in two versions, Windows and Posix. The two versions don't agree on what is a relative path and we don't know if we're given Windows or Posix paths. This results in false positives when running on Posix and inspecting Windows paths, like the hackage server does. System.FilePath.Posix.isAbsolute "C:\hello" == False System.FilePath.Windows.isAbsolute "/hello" == False This means that we would treat paths that start with "/" to be absolute. On Posix they are indeed absolute, while on Windows they are not.

The portable versions should be used when we might deal with paths that are from another OS than the host OS. For example, the Hackage Server deals with both Windows and Posix paths while performing the PackageDescription checks. In contrast, when we run 'cabal configure' we do expect the paths to be correct for our OS and we should not have to use the platform independent heuristics.