Utils.hs 47.2 KB
Newer Older
1
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
2
3
4
-----------------------------------------------------------------------------
-- |
-- Module      :  Distribution.Simple.Utils
ijones's avatar
ijones committed
5
-- Copyright   :  Isaac Jones, Simon Marlow 2003-2004
Duncan Coutts's avatar
Duncan Coutts committed
6
--                portions Copyright (c) 2007, Galois Inc.
7
--
Duncan Coutts's avatar
Duncan Coutts committed
8
-- Maintainer  :  cabal-devel@haskell.org
ijones's avatar
ijones committed
9
-- Portability :  portable
10
--
Duncan Coutts's avatar
Duncan Coutts committed
11
12
13
14
15
-- 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.
16

ijones's avatar
ijones committed
17
{- All rights reserved.
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

    * Neither the name of Isaac Jones nor the names of other
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}

module Distribution.Simple.Utils (
48
        cabalVersion,
49
50

        -- * logging and errors
51
52
        die,
        dieWithLocation,
53
        topHandler, topHandlerWith,
54
        warn, notice, setupMessage, info, debug,
55
        debugNoWrap, chattyTry,
56
57

        -- * running programs
58
        rawSystemExit,
tibbe's avatar
tibbe committed
59
        rawSystemExitCode,
60
        rawSystemExitWithEnv,
61
        rawSystemStdout,
62
        rawSystemStdInOut,
63
        rawSystemIOWithEnv,
64
        maybeExit,
65
        xargs,
66
        findProgramLocation,
67
        findProgramVersion,
68
69

        -- * copying files
70
        smartCopySources,
71
        createDirectoryIfMissingVerbose,
72
        copyFileVerbose,
73
        copyDirectoryRecursiveVerbose,
74
        copyFiles,
refold's avatar
refold committed
75
        copyFileTo,
76

77
78
79
        -- * installing files
        installOrdinaryFile,
        installExecutableFile,
refold's avatar
refold committed
80
        installMaybeExecutableFile,
81
        installOrdinaryFiles,
refold's avatar
refold committed
82
83
        installExecutableFiles,
        installMaybeExecutableFiles,
84
85
        installDirectoryContents,

86
87
88
89
        -- * File permissions
        setFileOrdinary,
        setFileExecutable,

90
        -- * file names
ijones's avatar
ijones committed
91
        currentDir,
92
93

        -- * finding files
94
        findFile,
95
        findFirstFile,
96
97
        findFileWithExtension,
        findFileWithExtension',
98
99
100
        findModuleFile,
        findModuleFiles,
        getDirectoryContentsRecursive,
101

102
103
104
        -- * environment variables
        isInSearchPath,

105
106
        -- * simple file globbing
        matchFileGlob,
Ian Lynagh's avatar
Ian Lynagh committed
107
        matchDirFileGlob,
108
109
        parseFileGlob,
        FileGlob(..),
110

111
112
113
        -- * modification time
        moreRecentFile,

Duncan Coutts's avatar
Duncan Coutts committed
114
        -- * temp files and dirs
115
116
117
        TempFileOptions(..), defaultTempFileOptions,
        withTempFile, withTempFileEx,
        withTempDirectory, withTempDirectoryEx,
118
119

        -- * .cabal and .buildinfo files
120
121
        defaultPackageDesc,
        findPackageDesc,
122
123
        defaultHookedPackageDesc,
        findHookedPackageDesc,
124

125
126
127
        -- * reading and writing files safely
        withFileContents,
        writeFileAtomic,
128
        rewriteFile,
129

130
131
132
        -- * Unicode
        fromUTF8,
        toUTF8,
133
        readUTF8File,
134
        withUTF8FileContents,
135
        writeUTF8File,
136
        normaliseLineEndings,
137

138
139
140
141
142
143
144
        -- * generic utils
        equating,
        comparing,
        isInfixOf,
        intercalate,
        lowercase,
        wrapText,
145
        wrapLine,
146
147
  ) where

148
import Control.Monad
149
    ( when, unless, filterM )
150
151
import Control.Concurrent.MVar
    ( newEmptyMVar, putMVar, takeMVar )
152
import Data.List
153
  ( nub, unfoldr, isPrefixOf, tails, intercalate )
154
import Data.Char as Char
155
156
    ( toLower, chr, ord )
import Data.Bits
157
    ( Bits((.|.), (.&.), shiftL, shiftR) )
158
159
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
160
161

import System.Directory
refold's avatar
refold committed
162
    ( Permissions(executable), getDirectoryContents, getPermissions
163
164
    , doesDirectoryExist, doesFileExist, removeFile, findExecutable
    , getModificationTime )
165
166
167
168
169
import System.Environment
    ( getProgName )
import System.Exit
    ( exitWith, ExitCode(..) )
import System.FilePath
170
171
    ( normalise, (</>), (<.>)
    , getSearchPath, takeDirectory, splitFileName
172
    , splitExtension, splitExtensions, splitDirectories )
173
import System.Directory
174
    ( createDirectory, renameFile, removeDirectoryRecursive )
175
import System.IO
176
177
    ( Handle, openFile, openBinaryFile, openBinaryTempFile
    , IOMode(ReadMode), hSetBinaryMode
178
    , hGetContents, stdin, stderr, stdout, hPutStr, hFlush, hClose )
179
import System.IO.Error as IO.Error
180
181
    ( isDoesNotExistError, isAlreadyExistsError
    , ioeSetFileName, ioeGetFileName, ioeGetErrorString )
Duncan Coutts's avatar
Duncan Coutts committed
182
183
import System.IO.Error
    ( ioeSetLocation, ioeGetLocation )
184
185
import System.IO.Unsafe
    ( unsafeInterleaveIO )
186
import qualified Control.Exception as Exception
187

188
import Distribution.Text
189
    ( display, simpleParse )
190
import Distribution.Package
191
    ( PackageIdentifier )
192
193
import Distribution.ModuleName (ModuleName)
import qualified Distribution.ModuleName as ModuleName
194
195
import Distribution.Version
    (Version(..))
196

197
import Control.Exception (IOException, evaluate, throwIO)
198
199
import System.Process (rawSystem)
import qualified System.Process as Process (CreateProcess(..))
Malcolm.Wallace's avatar
Malcolm.Wallace committed
200

201
import Control.Concurrent (forkIO)
202
203
import System.Process (runInteractiveProcess, waitForProcess, proc,
                       StdStream(..))
204
#if __GLASGOW_HASKELL__ >= 702
205
206
import System.Process (showCommandForUser)
#endif
simonmar's avatar
simonmar committed
207

208
209
210
211
212
#ifndef mingw32_HOST_OS
import System.Posix.Signals (installHandler, sigINT, sigQUIT, Handler(..))
import System.Process.Internals (defaultSignal, runGenProcess_)
#else
import System.Process (createProcess)
213
214
#endif

215
import Distribution.Compat.CopyFile
216
         ( copyFile, copyOrdinaryFile, copyExecutableFile
217
         , setFileOrdinary, setFileExecutable, setDirOrdinary )
218
import Distribution.Compat.TempFile
219
         ( openTempFile, createTempDirectory )
220
import Distribution.Compat.Exception
221
         ( tryIO, catchIO, catchExit )
222
import Distribution.Verbosity
223

224
225
#ifdef VERSION_base
import qualified Paths_Cabal (version)
226
227
#endif

228
229
-- We only get our own version number when we're building with ourselves
cabalVersion :: Version
230
#if defined(VERSION_base)
231
cabalVersion = Paths_Cabal.version
232
233
#elif defined(CABAL_VERSION)
cabalVersion = Version [CABAL_VERSION] []
234
#else
235
cabalVersion = Version [1,9999] []  --used when bootstrapping
236
237
#endif

238
239
-- ----------------------------------------------------------------------------
-- Exception and logging utils
ijones's avatar
ijones committed
240

241
242
dieWithLocation :: FilePath -> Maybe Int -> String -> IO a
dieWithLocation filename lineno msg =
243
244
245
246
247
248
  ioError . setLocation lineno
          . flip ioeSetFileName (normalise filename)
          $ userError msg
  where
    setLocation Nothing  err = err
    setLocation (Just n) err = ioeSetLocation err (show n)
simonmar's avatar
simonmar committed
249
250

die :: String -> IO a
251
252
die msg = ioError (userError msg)

253
254
topHandlerWith :: (Exception.IOException -> IO a) -> IO a -> IO a
topHandlerWith cont prog = catchIO prog handle
255
256
257
258
259
  where
    handle ioe = do
      hFlush stdout
      pname <- getProgName
      hPutStr stderr (mesage pname)
260
      cont ioe
261
262
263
264
265
266
267
268
269
      where
        mesage pname = wrapText (pname ++ ": " ++ file ++ detail)
        file         = case ioeGetFileName ioe of
                         Nothing   -> ""
                         Just path -> path ++ location ++ ": "
        location     = case ioeGetLocation ioe of
                         l@(n:_) | n >= '0' && n <= '9' -> ':' : l
                         _                              -> ""
        detail       = ioeGetErrorString ioe
simonmar's avatar
simonmar committed
270

271
272
273
topHandler :: IO a -> IO a
topHandler prog = topHandlerWith (const $ exitWith (ExitFailure 1)) prog

274
275
276
277
-- | Non fatal conditions that may be indicative of an error or problem.
--
-- We display these at the 'normal' verbosity level.
--
278
warn :: Verbosity -> String -> IO ()
279
warn verbosity msg =
280
281
  when (verbosity >= normal) $ do
    hFlush stdout
282
    hPutStr stderr (wrapText ("Warning: " ++ msg))
283
284
285
286
287
288
289
290
291
292
293

-- | 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.
--
notice :: Verbosity -> String -> IO ()
notice verbosity msg =
  when (verbosity >= normal) $
294
    putStr (wrapText msg)
295

296
297
setupMessage :: Verbosity -> String -> PackageIdentifier -> IO ()
setupMessage verbosity msg pkgid =
298
    notice verbosity (msg ++ ' ': display pkgid ++ "...")
299

300
-- | More detail on the operation of some action.
301
--
302
303
304
305
306
-- We display these messages when the verbosity level is 'verbose'
--
info :: Verbosity -> String -> IO ()
info verbosity msg =
  when (verbosity >= verbose) $
307
    putStr (wrapText msg)
308
309
310
311
312
313
314

-- | Detailed internal debugging information
--
-- We display these messages when the verbosity level is 'deafening'
--
debug :: Verbosity -> String -> IO ()
debug verbosity msg =
315
  when (verbosity >= deafening) $ do
316
    putStr (wrapText msg)
317
    hFlush stdout
318

319
320
321
322
323
324
325
326
-- | A variant of 'debug' that doesn't perform the automatic line
-- wrapping. Produces better output in some cases.
debugNoWrap :: Verbosity -> String -> IO ()
debugNoWrap verbosity msg =
  when (verbosity >= deafening) $ do
    putStrLn msg
    hFlush stdout

327
328
329
330
331
332
-- | Perform an IO action, catching any IO exceptions and printing an error
--   if one occurs.
chattyTry :: String  -- ^ a description of the action we were attempting
          -> IO ()   -- ^ the action itself
          -> IO ()
chattyTry desc action =
333
  catchIO action $ \exception ->
334
    putStrLn $ "Error while " ++ desc ++ ": " ++ show exception
335

336
337
338
-- -----------------------------------------------------------------------------
-- Helper functions

339
340
-- | Wraps text to the default line width. Existing newlines are preserved.
wrapText :: String -> String
341
wrapText = unlines
342
343
344
345
         . map (intercalate "\n"
              . map unwords
              . wrapLine 79
              . words)
346
         . lines
347
348
349
350

-- | Wraps a list of words to a list of lines of words of a particular width.
wrapLine :: Int -> [String] -> [[String]]
wrapLine width = wrap 0 []
351
352
353
354
355
356
357
358
359
360
361
362
363
  where wrap :: Int -> [String] -> [String] -> [[String]]
        wrap 0   []   (w:ws)
          | length w + 1 > width
          = wrap (length w) [w] ws
        wrap col line (w:ws)
          | col + length w + 1 > width
          = reverse line : wrap 0 [] (w:ws)
        wrap col line (w:ws)
          = let col' = col + length w + 1
             in wrap col' (w:line) ws
        wrap _ []   [] = []
        wrap _ line [] = [reverse line]

simonmar's avatar
simonmar committed
364
365
366
367
368
-- -----------------------------------------------------------------------------
-- rawSystem variants
maybeExit :: IO ExitCode -> IO ()
maybeExit cmd = do
  res <- cmd
369
  unless (res == ExitSuccess) $ exitWith res
simonmar's avatar
simonmar committed
370

Ian Lynagh's avatar
Ian Lynagh committed
371
372
373
printRawCommandAndArgs :: Verbosity -> FilePath -> [String] -> IO ()
printRawCommandAndArgs verbosity path args
 | verbosity >= deafening = print (path, args)
374
 | verbosity >= verbose   =
375
#if __GLASGOW_HASKELL__ >= 702
376
377
378
379
                            putStrLn $ showCommandForUser path args
#else
                            putStrLn $ unwords (path : args)
#endif
Ian Lynagh's avatar
Ian Lynagh committed
380
381
 | otherwise              = return ()

382
383
384
385
386
387
388
389
390
391
392
printRawCommandAndArgsAndEnv :: Verbosity
                             -> FilePath
                             -> [String]
                             -> [(String, String)]
                             -> IO ()
printRawCommandAndArgsAndEnv verbosity path args env
 | verbosity >= deafening = do putStrLn ("Environment: " ++ show env)
                               print (path, args)
 | verbosity >= verbose   = putStrLn $ unwords (path : args)
 | otherwise              = return ()

393
394
395
396
397

-- This is taken directly from the process package.
-- The reason we need it is that runProcess doesn't handle ^C in the same
-- way that rawSystem handles it, but rawSystem doesn't allow us to pass
-- an environment.
398
syncProcess :: String -> Process.CreateProcess -> IO ExitCode
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#if mingw32_HOST_OS
syncProcess _fun c = do
  (_,_,_,p) <- createProcess c
  waitForProcess p
#else
syncProcess fun c = do
  -- The POSIX version of system needs to do some manipulation of signal
  -- handlers.  Since we're going to be synchronously waiting for the child,
  -- we want to ignore ^C in the parent, but handle it the default way
  -- in the child (using SIG_DFL isn't really correct, it should be the
  -- original signal handler, but the GHC RTS will have already set up
  -- its own handler and we don't want to use that).
  old_int  <- installHandler sigINT  Ignore Nothing
  old_quit <- installHandler sigQUIT Ignore Nothing
  (_,_,_,p) <- runGenProcess_ fun c
                (Just defaultSignal) (Just defaultSignal)
  r <- waitForProcess p
  _ <- installHandler sigINT  old_int Nothing
  _ <- installHandler sigQUIT old_quit Nothing
  return r
#endif  /* mingw32_HOST_OS */

simonmar's avatar
simonmar committed
421
-- Exit with the same exitcode if the subcommand fails
422
423
rawSystemExit :: Verbosity -> FilePath -> [String] -> IO ()
rawSystemExit verbosity path args = do
Ian Lynagh's avatar
Ian Lynagh committed
424
  printRawCommandAndArgs verbosity path args
425
  hFlush stdout
426
427
428
429
  exitcode <- rawSystem path args
  unless (exitcode == ExitSuccess) $ do
    debug verbosity $ path ++ " returned " ++ show exitcode
    exitWith exitcode
simonmar's avatar
simonmar committed
430

tibbe's avatar
tibbe committed
431
432
433
434
435
436
437
438
439
rawSystemExitCode :: Verbosity -> FilePath -> [String] -> IO ExitCode
rawSystemExitCode verbosity path args = do
  printRawCommandAndArgs verbosity path args
  hFlush stdout
  exitcode <- rawSystem path args
  unless (exitcode == ExitSuccess) $ do
    debug verbosity $ path ++ " returned " ++ show exitcode
  return exitcode

440
441
442
443
444
rawSystemExitWithEnv :: Verbosity
                     -> FilePath
                     -> [String]
                     -> [(String, String)]
                     -> IO ()
445
446
rawSystemExitWithEnv verbosity path args env = do
    printRawCommandAndArgsAndEnv verbosity path args env
447
    hFlush stdout
448
449
    exitcode <- syncProcess "rawSystemExitWithEnv" (proc path args)
                { Process.env = Just env }
450
451
452
453
    unless (exitcode == ExitSuccess) $ do
        debug verbosity $ path ++ " returned " ++ show exitcode
        exitWith exitcode

454
455
456
457
-- Closes the passed in handles before returning.
rawSystemIOWithEnv :: Verbosity
                   -> FilePath
                   -> [String]
458
459
                   -> Maybe FilePath           -- ^ New working dir or inherit
                   -> Maybe [(String, String)] -- ^ New environment or inherit
460
461
462
463
                   -> Maybe Handle  -- ^ stdin
                   -> Maybe Handle  -- ^ stdout
                   -> Maybe Handle  -- ^ stderr
                   -> IO ExitCode
464
465
466
rawSystemIOWithEnv verbosity path args mcwd menv inp out err = do
    maybe (printRawCommandAndArgs       verbosity path args)
          (printRawCommandAndArgsAndEnv verbosity path args) menv
467
    hFlush stdout
468
469
470
471
472
473
    exitcode <- syncProcess "rawSystemIOWithEnv" (proc path args)
                { Process.cwd     = mcwd
                , Process.env     = menv
                , Process.std_in  = mbToStd inp
                , Process.std_out = mbToStd out
                , Process.std_err = mbToStd err }
474
475
    unless (exitcode == ExitSuccess) $ do
      debug verbosity $ path ++ " returned " ++ show exitcode
476
    mapM_ maybeClose [inp, out, err]
477
    return exitcode
478
479
  where
  -- Also taken from System.Process
480
481
482
483
484
  maybeClose :: Maybe Handle -> IO ()
  maybeClose (Just  hdl)
    | hdl /= stdin && hdl /= stdout && hdl /= stderr = hClose hdl
  maybeClose _ = return ()

485
486
487
  mbToStd :: Maybe Handle -> StdStream
  mbToStd Nothing    = Inherit
  mbToStd (Just hdl) = UseHandle hdl
488

489
490
-- | Run a command and return its output.
--
491
-- The output is assumed to be text in the locale encoding.
492
--
493
494
rawSystemStdout :: Verbosity -> FilePath -> [String] -> IO String
rawSystemStdout verbosity path args = do
495
  (output, errors, exitCode) <- rawSystemStdInOut verbosity path args
496
                                                  Nothing Nothing
497
498
499
                                                  Nothing False
  when (exitCode /= ExitSuccess) $
    die errors
500
501
  return output

502
503
504
505
506
-- | Run a command and return its output, errors and exit status. Optionally
-- also supply some input. Also provides control over whether the binary/text
-- mode of the input and output.
--
rawSystemStdInOut :: Verbosity
507
508
509
510
511
512
                  -> FilePath                 -- ^ Program location
                  -> [String]                 -- ^ Arguments
                  -> Maybe FilePath           -- ^ New working dir or inherit
                  -> Maybe [(String, String)] -- ^ New environment or inherit
                  -> Maybe (String, Bool)     -- ^ input text and binary mode
                  -> Bool                     -- ^ output in binary mode
513
                  -> IO (String, String, ExitCode) -- ^ output, errors, exit
514
rawSystemStdInOut verbosity path args mcwd menv input outputBinary = do
Ian Lynagh's avatar
Ian Lynagh committed
515
  printRawCommandAndArgs verbosity path args
516

517
  Exception.bracket
518
     (runInteractiveProcess path args mcwd menv)
519
     (\(inh,outh,errh,_) -> hClose inh >> hClose outh >> hClose errh)
520
    $ \(inh,outh,errh,pid) -> do
521

522
523
524
525
      -- output mode depends on what the caller wants
      hSetBinaryMode outh outputBinary
      -- but the errors are always assumed to be text (in the current locale)
      hSetBinaryMode errh False
526

527
      -- fork off a couple threads to pull on the stderr and stdout
528
      -- so if the process writes to stderr we do not block.
529

530
      err <- hGetContents errh
531
      out <- hGetContents outh
532

533
      mv <- newEmptyMVar
534
      let force str = (evaluate (length str) >> return ())
535
            `Exception.finally` putMVar mv ()
536
          --TODO: handle exceptions like text decoding.
537
538
      _ <- forkIO $ force out
      _ <- forkIO $ force err
539
540
541
542
543
544
545
546
547
548
549
550
551

      -- push all the input, if any
      case input of
        Nothing -> return ()
        Just (inputStr, inputBinary) -> do
                -- input mode depends on what the caller wants
          hSetBinaryMode inh inputBinary
          hPutStr inh inputStr
          hClose inh
          --TODO: this probably fails if the process refuses to consume
          -- or if it closes stdin (eg if it exits)

      -- wait for both to finish, in either order
552
553
      takeMVar mv
      takeMVar mv
554
555
556

      -- wait for the program to terminate
      exitcode <- waitForProcess pid
557
558
559
560
      unless (exitcode == ExitSuccess) $
        debug verbosity $ path ++ " returned " ++ show exitcode
                       ++ if null err then "" else
                          " with error message:\n" ++ err
561
562
563
564
                       ++ case input of
                            Nothing       -> ""
                            Just ("",  _) -> ""
                            Just (inp, _) -> "\nstdin input:\n" ++ inp
565

566
      return (out, err, exitcode)
567
568
569


-- | Look for a program on the path.
570
571
findProgramLocation :: Verbosity -> FilePath -> IO (Maybe FilePath)
findProgramLocation verbosity prog = do
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
  debug verbosity $ "searching for " ++ prog ++ " in path."
  res <- findExecutable prog
  case res of
      Nothing   -> debug verbosity ("Cannot find " ++ prog ++ " on the path")
      Just path -> debug verbosity ("found " ++ prog ++ " at "++ path)
  return res


-- | 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.
--
findProgramVersion :: String             -- ^ version args
                   -> (String -> String) -- ^ function to select version
                                         --   number from program output
                   -> Verbosity
                   -> FilePath           -- ^ location
                   -> IO (Maybe Version)
findProgramVersion versionArg selectVersion verbosity path = do
  str <- rawSystemStdout verbosity path [versionArg]
         `catchIO`   (\_ -> return "")
         `catchExit` (\_ -> return "")
  let version :: Maybe Version
      version = simpleParse (selectVersion str)
  case version of
      Nothing -> warn verbosity $ "cannot determine version of " ++ path
                               ++ " :\n" ++ show str
      Just v  -> debug verbosity $ path ++ " is version " ++ display v
  return version


603
604
605
606
607
-- | 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:
608
--
609
-- > xargs (32*1024) (rawSystemExit verbosity) prog fixedArgs bigArgs
610
--
611
612
613
xargs :: Int -> ([String] -> IO ())
      -> [String] -> [String] -> IO ()
xargs maxSize rawSystemFun fixedArgs bigArgs =
614
  let fixedArgSize = sum (map length fixedArgs) + length fixedArgs
615
      chunkSize = maxSize - fixedArgSize
616
   in mapM_ (rawSystemFun . (fixedArgs ++)) (chunks chunkSize bigArgs)
617
618
619
620
621

  where chunks len = unfoldr $ \s ->
          if null s then Nothing
                    else Just (chunk [] len s)

Ian Lynagh's avatar
Ian Lynagh committed
622
        chunk acc _   []     = (reverse acc,[])
623
624
625
626
        chunk acc len (s:ss)
          | len' < len = chunk (s:acc) (len-len'-1) ss
          | otherwise  = (reverse acc, s:ss)
          where len' = length s
ijones's avatar
ijones committed
627
628
629
630
631

-- ------------------------------------------------------------
-- * File Utilities
-- ------------------------------------------------------------

632
633
634
635
636
----------------
-- Finding files

-- | Find a file by looking in a search path. The file path must match exactly.
--
ijones's avatar
ijones committed
637
638
639
findFile :: [FilePath]    -- ^search locations
         -> FilePath      -- ^File Name
         -> IO FilePath
640
641
642
643
644
645
findFile searchPath fileName =
  findFirstFile id
    [ path </> fileName
    | path <- nub searchPath]
  >>= maybe (die $ fileName ++ " doesn't exist") return

646
647
648
649
-- | 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.
--
650
651
652
653
654
655
656
657
658
659
findFileWithExtension :: [String]
                      -> [FilePath]
                      -> FilePath
                      -> IO (Maybe FilePath)
findFileWithExtension extensions searchPath baseName =
  findFirstFile id
    [ path </> baseName <.> ext
    | path <- nub searchPath
    , ext <- nub extensions ]

660
661
662
-- | Like 'findFileWithExtension' but returns which element of the search path
-- the file was found in, and the file path relative to that base directory.
--
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
findFileWithExtension' :: [String]
                       -> [FilePath]
                       -> FilePath
                       -> IO (Maybe (FilePath, FilePath))
findFileWithExtension' extensions searchPath baseName =
  findFirstFile (uncurry (</>))
    [ (path, baseName <.> ext)
    | path <- nub searchPath
    , ext <- nub extensions ]

findFirstFile :: (a -> FilePath) -> [a] -> IO (Maybe a)
findFirstFile file = findFirst
  where findFirst []     = return Nothing
        findFirst (x:xs) = do exists <- doesFileExist (file x)
                              if exists
                                then return (Just x)
                                else findFirst xs
ijones's avatar
ijones committed
680

681
682
683
684
-- | Finds the files corresponding to a list of Haskell module names.
--
-- As 'findModuleFile' but for a list of module names.
--
685
686
687
688
689
690
691
findModuleFiles :: [FilePath]   -- ^ build prefix (location of objects)
                -> [String]     -- ^ search suffixes
                -> [ModuleName] -- ^ modules
                -> IO [(FilePath, FilePath)]
findModuleFiles searchPath extensions moduleNames =
  mapM (findModuleFile searchPath extensions) moduleNames

692
693
694
695
696
-- | Find the file corresponding to a Haskell module name.
--
-- This is similar to 'findFileWithExtension'' but specialised to a module
-- name. The function fails if the file corresponding to the module is missing.
--
697
698
699
700
701
702
703
704
705
706
707
708
709
findModuleFile :: [FilePath]  -- ^ build prefix (location of objects)
               -> [String]    -- ^ search suffixes
               -> ModuleName  -- ^ module
               -> IO (FilePath, FilePath)
findModuleFile searchPath extensions moduleName =
      maybe notFound return
  =<< findFileWithExtension' extensions searchPath
                             (ModuleName.toFilePath moduleName)
  where
    notFound = die $ "Error: Could not find module: " ++ display moduleName
                  ++ " with any suffix: " ++ show extensions
                  ++ " in the search path: " ++ show searchPath

710
711
712
713
714
715
-- | 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.
--
716
717
718
719
720
721
722
723
724
725
726
getDirectoryContentsRecursive :: FilePath -> IO [FilePath]
getDirectoryContentsRecursive topdir = recurseDirectories [""]
  where
    recurseDirectories :: [FilePath] -> IO [FilePath]
    recurseDirectories []         = return []
    recurseDirectories (dir:dirs) = unsafeInterleaveIO $ do
      (files, dirs') <- collect [] [] =<< getDirectoryContents (topdir </> dir)
      files' <- recurseDirectories (dirs' ++ dirs)
      return (files ++ files')

      where
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
727
728
        collect files dirs' []              = return (reverse files
                                                     ,reverse dirs')
729
730
731
732
733
734
735
736
737
738
739
740
741
        collect files dirs' (entry:entries) | ignore entry
                                            = collect files dirs' entries
        collect files dirs' (entry:entries) = do
          let dirEntry = dir </> entry
          isDirectory <- doesDirectoryExist (topdir </> dirEntry)
          if isDirectory
            then collect files (dirEntry:dirs') entries
            else collect (dirEntry:files) dirs' entries

        ignore ['.']      = True
        ignore ['.', '.'] = True
        ignore _          = False

742
743
744
745
746
747
748
------------------------
-- Environment variables

-- | Is this directory in the system search path?
isInSearchPath :: FilePath -> IO Bool
isInSearchPath path = fmap (elem path) getSearchPath

749
750
751
----------------
-- File globbing

752
753
754
755
data FileGlob
   -- | No glob at all, just an ordinary file
   = NoGlob FilePath

Duncan Coutts's avatar
Duncan Coutts committed
756
   -- | dir prefix and extension, like @\"foo\/bar\/\*.baz\"@ corresponds to
757
   --    @FileGlob \"foo\/bar\" \".baz\"@
758
759
760
761
762
763
   | FileGlob FilePath String

parseFileGlob :: FilePath -> Maybe FileGlob
parseFileGlob filepath = case splitExtensions filepath of
  (filepath', ext) -> case splitFileName filepath' of
    (dir, "*") | '*' `elem` dir
764
765
              || '*' `elem` ext
              || null ext            -> Nothing
766
767
768
769
770
771
               | null dir            -> Just (FileGlob "." ext)
               | otherwise           -> Just (FileGlob dir ext)
    _          | '*' `elem` filepath -> Nothing
               | otherwise           -> Just (NoGlob filepath)

matchFileGlob :: FilePath -> IO [FilePath]
772
matchFileGlob = matchDirFileGlob "."
773

Ian Lynagh's avatar
Ian Lynagh committed
774
775
matchDirFileGlob :: FilePath -> FilePath -> IO [FilePath]
matchDirFileGlob dir filepath = case parseFileGlob filepath of
776
  Nothing -> die $ "invalid file glob '" ++ filepath
Ian Lynagh's avatar
Ian Lynagh committed
777
778
                ++ "'. Wildcards '*' are only allowed in place of the file"
                ++ " name, not in the directory name or file extension."
779
                ++ " If a wildcard is used it must be with an file extension."
Ian Lynagh's avatar
Ian Lynagh committed
780
781
782
  Just (NoGlob filepath') -> return [filepath']
  Just (FileGlob dir' ext) -> do
    files <- getDirectoryContents (dir </> dir')
783
    case   [ dir' </> file
784
785
           | file <- files
           , let (name, ext') = splitExtensions file
786
787
788
789
           , not (null name) && ext' == ext ] of
      []      -> die $ "filepath wildcard '" ++ filepath
                    ++ "' does not match any files."
      matches -> return matches
Ian Lynagh's avatar
Ian Lynagh committed
790

791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
--------------------
-- Modification time

-- | 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.
--
moreRecentFile :: FilePath -> FilePath -> IO Bool
moreRecentFile a b = do
  exists <- doesFileExist b
  if not exists
    then return True
    else do tb <- getModificationTime b
            ta <- getModificationTime a
            return (ta > tb)

808
809
----------------------------------------
-- Copying and installing files and dirs
ijones's avatar
ijones committed
810

811
812
-- | Same as 'createDirectoryIfMissing' but logs at higher verbosity levels.
--
813
814
815
816
817
818
819
820
821
822
823
createDirectoryIfMissingVerbose :: Verbosity
                                -> Bool     -- ^ Create its parents too?
                                -> FilePath
                                -> IO ()
createDirectoryIfMissingVerbose verbosity create_parents path0
  | create_parents = createDirs (parents path0)
  | otherwise      = createDirs (take 1 (parents path0))
  where
    parents = reverse . scanl1 (</>) . splitDirectories . normalise

    createDirs []         = return ()
824
    createDirs (dir:[])   = createDir dir throwIO
825
826
827
    createDirs (dir:dirs) =
      createDir dir $ \_ -> do
        createDirs dirs
828
        createDir dir throwIO
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846

    createDir :: FilePath -> (IOException -> IO ()) -> IO ()
    createDir dir notExistHandler = do
      r <- tryIO $ createDirectoryVerbose verbosity dir
      case (r :: Either IOException ()) of
        Right ()                   -> return ()
        Left  e
          | isDoesNotExistError  e -> notExistHandler e
          -- createDirectory (and indeed POSIX mkdir) does not distinguish
          -- between a dir already existing and a file already existing. So we
          -- check for it here. Unfortunately there is a slight race condition
          -- here, but we think it is benign. It could report an exeption in
          -- the case that the dir did exist but another process deletes the
          -- directory and creates a file in its place before we can check
          -- that the directory did indeed exist.
          | isAlreadyExistsError e -> (do
              isDir <- doesDirectoryExist dir
              if isDir then return ()
847
                       else throwIO e
Duncan Coutts's avatar
Duncan Coutts committed
848
              ) `catchIO` ((\_ -> return ()) :: IOException -> IO ())
849
          | otherwise              -> throwIO e
850
851
852
853
854
855

createDirectoryVerbose :: Verbosity -> FilePath -> IO ()
createDirectoryVerbose verbosity dir = do
  info verbosity $ "creating " ++ dir
  createDirectory dir
  setDirOrdinary dir
856

857
858
859
860
861
-- | 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.
--
862
863
copyFileVerbose :: Verbosity -> FilePath -> FilePath -> IO ()
copyFileVerbose verbosity src dest = do
864
  info verbosity ("copy " ++ src ++ " to " ++ dest)
865
866
  copyFile src dest

867
868
869
870
-- | 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.
--
871
872
873
874
875
installOrdinaryFile :: Verbosity -> FilePath -> FilePath -> IO ()
installOrdinaryFile verbosity src dest = do
  info verbosity ("Installing " ++ src ++ " to " ++ dest)
  copyOrdinaryFile src dest

876
877
878
879
-- | 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.
--
880
881
882
883
884
installExecutableFile :: Verbosity -> FilePath -> FilePath -> IO ()
installExecutableFile verbosity src dest = do
  info verbosity ("Installing executable " ++ src ++ " to " ++ dest)
  copyExecutableFile src dest

refold's avatar
refold committed
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
-- | Install a file that may or not be executable, preserving permissions.
installMaybeExecutableFile :: Verbosity -> FilePath -> FilePath -> IO ()
installMaybeExecutableFile verbosity src dest = do
  perms <- getPermissions src
  if (executable perms) --only checks user x bit
    then installExecutableFile verbosity src dest
    else installOrdinaryFile   verbosity src dest

-- | Given a relative path to a file, copy it to the given directory, preserving
-- the relative path and creating the parent directories if needed.
copyFileTo :: Verbosity -> FilePath -> FilePath -> IO ()
copyFileTo verbosity dir file = do
  let targetFile = dir </> file
  createDirectoryIfMissingVerbose verbosity True (takeDirectory targetFile)
  installOrdinaryFile verbosity file targetFile

-- | Common implementation of 'copyFiles', 'installOrdinaryFiles',
-- 'installExecutableFiles' and 'installMaybeExecutableFiles'.
copyFilesWith :: (Verbosity -> FilePath -> FilePath -> IO ())
              -> Verbosity -> FilePath -> [(FilePath, FilePath)] -> IO ()
copyFilesWith doCopy verbosity targetDir srcFiles = do

  -- Create parent directories for everything
  let dirs = map (targetDir </>) . nub . map (takeDirectory . snd) $ srcFiles
  mapM_ (createDirectoryIfMissingVerbose verbosity True) dirs

  -- Copy all the files
  sequence_ [ let src  = srcBase   </> srcFile
                  dest = targetDir </> srcFile
               in doCopy verbosity src dest
            | (srcBase, srcFile) <- srcFiles ]

917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
-- | 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.
--
copyFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)] -> IO ()
refold's avatar
refold committed
939
copyFiles = copyFilesWith copyFileVerbose
940

941
942
-- | This is like 'copyFiles' but uses 'installOrdinaryFile'.
--
943
installOrdinaryFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)] -> IO ()
refold's avatar
refold committed
944
installOrdinaryFiles = copyFilesWith installOrdinaryFile
945

refold's avatar
refold committed
946
947
948
949
950
-- | This is like 'copyFiles' but uses 'installExecutableFile'.
--
installExecutableFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)]
                          -> IO ()
installExecutableFiles = copyFilesWith installExecutableFile
951

refold's avatar
refold committed
952
953
954
955
956
-- | This is like 'copyFiles' but uses 'installMaybeExecutableFile'.
--
installMaybeExecutableFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)]
                               -> IO ()
installMaybeExecutableFiles = copyFilesWith installMaybeExecutableFile
957

958
959
960
961
-- | This installs all the files in a directory to a target location,
-- preserving the directory layout. All the files are assumed to be ordinary
-- rather than executable files.
--
962
963
964
965
966
967
installDirectoryContents :: Verbosity -> FilePath -> FilePath -> IO ()
installDirectoryContents verbosity srcDir destDir = do
  info verbosity ("copy directory '" ++ srcDir ++ "' to '" ++ destDir ++ "'.")
  srcFiles <- getDirectoryContentsRecursive srcDir
  installOrdinaryFiles verbosity destDir [ (srcDir, f) | f <- srcFiles ]

968
969
970
971
972
973
974
975
976
977
978
---------------------------------
-- Deprecated file copy functions

{-# DEPRECATED smartCopySources
      "Use findModuleFiles and copyFiles or installOrdinaryFiles" #-}
smartCopySources :: Verbosity -> [FilePath] -> FilePath
                 -> [ModuleName] -> [String] -> IO ()
smartCopySources verbosity searchPath targetDir moduleNames extensions =
      findModuleFiles searchPath extensions moduleNames
  >>= copyFiles verbosity targetDir

979
980
{-# DEPRECATED copyDirectoryRecursiveVerbose
      "You probably want installDirectoryContents instead" #-}
981
982
copyDirectoryRecursiveVerbose :: Verbosity -> FilePath -> FilePath -> IO ()
copyDirectoryRecursiveVerbose verbosity srcDir destDir = do
983
  info verbosity ("copy directory '" ++ srcDir ++ "' to '" ++ destDir ++ "'.")
984
985
  srcFiles <- getDirectoryContentsRecursive srcDir
  copyFiles verbosity destDir [ (srcDir, f) | f <- srcFiles ]
986

987
988
989
---------------------------
-- Temporary files and dirs

990
991
992
993
994
995
996
997
-- | Advanced options for 'withTempFile' and 'withTempDirectory'.
data TempFileOptions = TempFileOptions {
  optKeepTempFiles :: Bool  -- ^ Keep temporary files?
  }

defaultTempFileOptions :: TempFileOptions
defaultTempFileOptions = TempFileOptions { optKeepTempFiles = False }

998
999
-- | Use a temporary filename that doesn't already exist.
--
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
withTempFile :: FilePath    -- ^ Temp dir to create the file in
                -> String   -- ^ File name template. See 'openTempFile'.
                -> (FilePath -> Handle -> IO a) -> IO a
withTempFile tmpDir template action =
  withTempFileEx defaultTempFileOptions tmpDir template action

-- | A version of 'withTempFile' that additionally takes a 'TempFileOptions'
-- argument.
withTempFileEx :: TempFileOptions
                 -> FilePath -- ^ Temp dir to create the file in
                 -> String   -- ^ File name template. See 'openTempFile'.
                 -> (FilePath -> Handle -> IO a) -> IO a
withTempFileEx opts tmpDir template action =
1013
1014
  Exception.bracket
    (openTempFile tmpDir template)
1015
    (\(name, handle) -> do hClose handle
1016
                           unless (optKeepTempFiles opts) $ removeFile name)
1017
1018
    (uncurry action)

1019
-- | Create and use a temporary directory.
Duncan Coutts's avatar
Duncan Coutts committed
1020
--
1021
1022
1023
1024
1025
1026
1027
-- 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@.
Duncan Coutts's avatar
Duncan Coutts committed
1028
--
1029
withTempDirectory :: Verbosity
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
                     -> FilePath -> String -> (FilePath -> IO a) -> IO a
withTempDirectory verbosity targetDir template =
  withTempDirectoryEx verbosity defaultTempFileOptions targetDir template

-- | A version of 'withTempDirectory' that additionally takes a
-- 'TempFileOptions' argument.
withTempDirectoryEx :: Verbosity
                       -> TempFileOptions
                       -> FilePath -> String -> (FilePath -> IO a) -> IO a
withTempDirectoryEx _verbosity opts targetDir template =
1040
1041
  Exception.bracket
    (createTempDirectory targetDir template)
1042
    (unless (optKeepTempFiles opts) . removeDirectoryRecursive)
Duncan Coutts's avatar
Duncan Coutts committed
1043

1044
1045
1046
-----------------------------------
-- Safely reading and writing files

1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
-- | 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.
--
withFileContents :: FilePath -> (String -> IO a) -> IO a
withFileContents name action =
  Exception.bracket (openFile name ReadMode) hClose
                    (\hnd -> hGetContents hnd >>= action)

1057
1058
1059
1060
1061
1062
1063
1064
-- | Writes a file atomically.
--
-- The file is either written sucessfully 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.
--
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
writeFileAtomic :: FilePath -> BS.ByteString -> IO ()
writeFileAtomic targetPath content = do
  let (targetDir, targetFile) = splitFileName targetPath
  Exception.bracketOnError
    (openBinaryTempFile targetDir $ targetFile <.> "tmp")
    (\(tmpPath, handle) -> hClose handle >> removeFile tmpPath)
    (\(tmpPath, handle) -> do
        BS.hPut handle content
        hClose handle
        renameFile tmpPath targetPath)
1075

1076
1077
1078
1079
1080
1081
-- | 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.
--
rewriteFile :: FilePath -> String -> IO ()
rewriteFile path newContent =
1082
  flip catchIO mightNotExist $ do
1083
    existingContent <- readFile path
1084
    _ <- evaluate (length existingContent)
1085
    unless (existingContent == newContent) $
1086
      writeFileAtomic path (BS.Char8.pack newContent)
1087
  where
1088
1089
    mightNotExist e | isDoesNotExistError e = writeFileAtomic path
                                              (BS.Char8.pack newContent)
1090
                    | otherwise             = ioError e
1091
1092
1093
1094

-- | 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.)
ijones's avatar
ijones committed
1095
1096
currentDir :: FilePath
currentDir = "."
1097

1098
1099
1100
1101
-- ------------------------------------------------------------
-- * Finding the description file
-- ------------------------------------------------------------

ijones's avatar
ijones committed
1102
-- |Package description file (/pkgname/@.cabal@)
1103
defaultPackageDesc :: Verbosity -> IO FilePath
1104
defaultPackageDesc _verbosity = findPackageDesc currentDir
1105
1106

-- |Find a package description file in the given directory.  Looks for
ijones's avatar
ijones committed
1107
-- @.cabal@ files.
1108
findPackageDesc :: FilePath    -- ^Where to look
1109
                -> IO FilePath -- ^<pkgname>.cabal
1110
findPackageDesc dir
1111
 = do files <- getDirectoryContents dir
1112
1113
1114
1115
1116
1117
1118
1119
      -- to make sure we do not mistake a ~/.cabal/ dir for a <pkgname>.cabal
      -- file we filter to exclude dirs and null base file names:
      cabalFiles <- filterM doesFileExist
                       [ dir </> file
                       | file <- files
                       , let (name, ext) = splitExtension file
                       , not (null name) && ext == ".cabal" ]
      case cabalFiles of
1120
        []          -> noDesc
1121
        [cabalFile] -> return cabalFile
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
        multiple    -> multiDesc multiple