{-# LANGUAGE CPP, ForeignFunctionInterface #-}{-# OPTIONS_NHC98 -cpp #-}{-# OPTIONS_JHC -fcpp -fffi #-}------------------------------------------------------------------------------- |-- Module : Distribution.Simple.Utils-- Copyright : Isaac Jones, Simon Marlow 2003-2004-- portions Copyright (c) 2007, Galois Inc.---- Maintainer : cabal-devel@haskell.org-- Portability : portable---- 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.{- All rights reserved.
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. -}moduleDistribution.Simple.Utils(cabalVersion,cabalBootstrapping,-- * logging and errorsdie,dieWithLocation,topHandler,warn,notice,setupMessage,info,debug,chattyTry,-- * running programsrawSystemExit,rawSystemStdout,rawSystemStdInOut,maybeExit,xargs,findProgramLocation,findProgramVersion,-- * copying filessmartCopySources,createDirectoryIfMissingVerbose,copyFileVerbose,copyDirectoryRecursiveVerbose,copyFiles,-- * installing filesinstallOrdinaryFile,installExecutableFile,installOrdinaryFiles,installDirectoryContents,-- * file namescurrentDir,-- * finding filesfindFile,findFileWithExtension,findFileWithExtension',findModuleFile,findModuleFiles,getDirectoryContentsRecursive,-- * simple file globbingmatchFileGlob,matchDirFileGlob,parseFileGlob,FileGlob(..),-- * temp files and dirswithTempFile,withTempDirectory,-- * .cabal and .buildinfo filesdefaultPackageDesc,findPackageDesc,defaultHookedPackageDesc,findHookedPackageDesc,-- * reading and writing files safelywithFileContents,writeFileAtomic,rewriteFile,-- * UnicodefromUTF8,toUTF8,readUTF8File,withUTF8FileContents,writeUTF8File,normaliseLineEndings,-- * generic utilsequating,comparing,isInfixOf,intercalate,lowercase,wrapText,wrapLine,)whereimportControl.Monad(when,unless,filterM)#ifdef __GLASGOW_HASKELL__importControl.Concurrent.MVar(newEmptyMVar,putMVar,takeMVar)#endifimportData.List(nub,unfoldr,isPrefixOf,tails,intersperse)importData.CharasChar(toLower,chr,ord)importData.Bits(Bits((.|.),(.&.),shiftL,shiftR))importSystem.Directory(getDirectoryContents,doesDirectoryExist,doesFileExist,removeFile,findExecutable)importSystem.Environment(getProgName)importSystem.Cmd(rawSystem)importSystem.Exit(exitWith,ExitCode(..))importSystem.FilePath(normalise,(</>),(<.>),takeDirectory,splitFileName,splitExtension,splitExtensions)importSystem.Directory(createDirectoryIfMissing,renameFile,removeDirectoryRecursive)importSystem.IO(Handle,openFile,openBinaryFile,IOMode(ReadMode),hSetBinaryMode,hGetContents,stderr,stdout,hPutStr,hFlush,hClose)importSystem.IO.ErrorasIO.Error(isDoesNotExistError,ioeSetFileName,ioeGetFileName,ioeGetErrorString)#if !(defined(__HUGS__) || (defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 608))importSystem.IO.Error(ioeSetLocation,ioeGetLocation)#endifimportSystem.IO.Unsafe(unsafeInterleaveIO)importqualifiedControl.ExceptionasExceptionimportDistribution.Text(display,simpleParse)importDistribution.Package(PackageIdentifier)importDistribution.ModuleName(ModuleName)importqualifiedDistribution.ModuleNameasModuleNameimportDistribution.Version(Version(..))importControl.Exception(evaluate)#ifdef __GLASGOW_HASKELL__importControl.Concurrent(forkIO)importSystem.Process(runInteractiveProcess,waitForProcess)#elseimportSystem.Cmd(system)importSystem.Directory(getTemporaryDirectory)#endifimportDistribution.Compat.CopyFile(copyFile,copyOrdinaryFile,copyExecutableFile)importDistribution.Compat.TempFile(openTempFile,openNewBinaryFile,createTempDirectory)importDistribution.Compat.Exception(catchIO,catchExit,onException)importDistribution.Verbosity-- We only get our own version number when we're building with ourselvescabalVersion::Version#ifdef CABAL_VERSIONcabalVersion=Version[CABAL_VERSION][]#elsecabalVersion=error"Cabal was not bootstrapped correctly"#endifcabalBootstrapping::Bool#ifdef CABAL_VERSIONcabalBootstrapping=False#elsecabalBootstrapping=True#endif-- ------------------------------------------------------------------------------ Exception and logging utilsdieWithLocation::FilePath->MaybeInt->String->IOadieWithLocationfilenamelinenomsg=ioError.setLocationlineno.flipioeSetFileName(normalisefilename)$userErrormsgwhere#if defined(__HUGS__) || (defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 608)setLocation_err=err#elsesetLocationNothingerr=errsetLocation(Justn)err=ioeSetLocationerr(shown)#endifdie::String->IOadiemsg=ioError(userErrormsg)topHandler::IOa->IOatopHandlerprog=catchproghandlewherehandleioe=dohFlushstdoutpname<-getProgNamehPutStrstderr(mesagepname)exitWith(ExitFailure1)wheremesagepname=wrapText(pname++": "++file++detail)file=caseioeGetFileNameioeofNothing->""Justpath->path++location++": "#if defined(__HUGS__) || (defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 608)location=""#elselocation=caseioeGetLocationioeofl@(n:_)|n>='0'&&n<='9'->':':l_->""#endifdetail=ioeGetErrorStringioe-- | Non fatal conditions that may be indicative of an error or problem.---- We display these at the 'normal' verbosity level.--warn::Verbosity->String->IO()warnverbositymsg=when(verbosity>=normal)$dohFlushstdouthPutStrstderr(wrapText("Warning: "++msg))-- | 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()noticeverbositymsg=when(verbosity>=normal)$putStr(wrapTextmsg)setupMessage::Verbosity->String->PackageIdentifier->IO()setupMessageverbositymsgpkgid=noticeverbosity(msg++' ':displaypkgid++"...")-- | More detail on the operation of some action.---- We display these messages when the verbosity level is 'verbose'--info::Verbosity->String->IO()infoverbositymsg=when(verbosity>=verbose)$putStr(wrapTextmsg)-- | Detailed internal debugging information---- We display these messages when the verbosity level is 'deafening'--debug::Verbosity->String->IO()debugverbositymsg=when(verbosity>=deafening)$doputStr(wrapTextmsg)hFlushstdout-- | 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()chattyTrydescaction=catchIOaction$\exception->putStrLn$"Error while "++desc++": "++showexception-- ------------------------------------------------------------------------------- Helper functions-- | Wraps text to the default line width. Existing newlines are preserved.wrapText::String->StringwrapText=unlines.concatMap(mapunwords.wrapLine79.words).lines-- | Wraps a list of words to a list of lines of words of a particular width.wrapLine::Int->[String]->[[String]]wrapLinewidth=wrap0[]wherewrap::Int->[String]->[String]->[[String]]wrap0[](w:ws)|lengthw+1>width=wrap(lengthw)[w]wswrapcolline(w:ws)|col+lengthw+1>width=reverseline:wrap0[](w:ws)wrapcolline(w:ws)=letcol'=col+lengthw+1inwrapcol'(w:line)wswrap_[][]=[]wrap_line[]=[reverseline]-- ------------------------------------------------------------------------------- rawSystem variantsmaybeExit::IOExitCode->IO()maybeExitcmd=dores<-cmdunless(res==ExitSuccess)$exitWithresprintRawCommandAndArgs::Verbosity->FilePath->[String]->IO()printRawCommandAndArgsverbositypathargs|verbosity>=deafening=print(path,args)|verbosity>=verbose=putStrLn$unwords(path:args)|otherwise=return()-- Exit with the same exitcode if the subcommand failsrawSystemExit::Verbosity->FilePath->[String]->IO()rawSystemExitverbositypathargs=doprintRawCommandAndArgsverbositypathargshFlushstdoutexitcode<-rawSystempathargsunless(exitcode==ExitSuccess)$dodebugverbosity$path++" returned "++showexitcodeexitWithexitcode-- | Run a command and return its output.---- The output is assumed to be text in the locale encoding.--rawSystemStdout::Verbosity->FilePath->[String]->IOStringrawSystemStdoutverbositypathargs=do(output,errors,exitCode)<-rawSystemStdInOutverbositypathargsNothingFalsewhen(exitCode/=ExitSuccess)$dieerrorsreturnoutput-- | 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->FilePath->[String]->Maybe(String,Bool)-- ^ input text and binary mode->Bool-- ^ output in binary mode->IO(String,String,ExitCode)-- ^ output, errors, exitrawSystemStdInOutverbositypathargsinputoutputBinary=doprintRawCommandAndArgsverbositypathargs#ifdef __GLASGOW_HASKELL__Exception.bracket(runInteractiveProcesspathargsNothingNothing)(\(inh,outh,errh,_)->hCloseinh>>hCloseouth>>hCloseerrh)$\(inh,outh,errh,pid)->do-- output mode depends on what the caller wantshSetBinaryModeouthoutputBinary-- but the errors are always assumed to be text (in the current locale)hSetBinaryModeerrhFalse-- fork off a couple threads to pull on the stderr and stdout-- so if the process writes to stderr we do not block.err<-hGetContentserrhout<-hGetContentsouthmv<-newEmptyMVarletforcestr=(evaluate(lengthstr)>>return())`Exception.finally`putMVarmv()--TODO: handle exceptions like text decoding._<-forkIO$forceout_<-forkIO$forceerr-- push all the input, if anycaseinputofNothing->return()Just(inputStr,inputBinary)->do-- input mode depends on what the caller wantshSetBinaryModeinhinputBinaryhPutStrinhinputStrhCloseinh--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 ordertakeMVarmvtakeMVarmv-- wait for the program to terminateexitcode<-waitForProcesspidunless(exitcode==ExitSuccess)$debugverbosity$path++" returned "++showexitcode++ifnullerrthen""else" with error message:\n"++errreturn(out,err,exitcode)#elsetmpDir<-getTemporaryDirectorywithTempFiletmpDir".cmd.stdout"$\outNameoutHandle->withTempFiletmpDir".cmd.stdin"$\inNameinHandle->dohCloseoutHandlecaseinputofNothing->return()Just(inputStr,inputBinary)->dohSetBinaryModeinHandleinputBinaryhPutStrinHandleinputStrhCloseinHandleletquotename="'"++name++"'"cmd=unwords(mapquote(path:args))++" <"++quoteinName++" >"++quoteoutNameexitcode<-systemcmdunless(exitcode==ExitSuccess)$debugverbosity$path++" returned "++showexitcodeException.bracket(openFileoutNameReadMode)hClose$\hnd->dohSetBinaryModehndoutputBinaryoutput<-hGetContentshndlengthoutput`seq`return(output,"",exitcode)#endif-- | Look for a program on the path.findProgramLocation::Verbosity->FilePath->IO(MaybeFilePath)findProgramLocationverbosityprog=dodebugverbosity$"searching for "++prog++" in path."res<-findExecutableprogcaseresofNothing->debugverbosity("Cannot find "++prog++" on the path")Justpath->debugverbosity("found "++prog++" at "++path)returnres-- | 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(MaybeVersion)findProgramVersionversionArgselectVersionverbositypath=dostr<-rawSystemStdoutverbositypath[versionArg]`catchIO`(\_->return"")`catchExit`(\_->return"")letversion::MaybeVersionversion=simpleParse(selectVersionstr)caseversionofNothing->warnverbosity$"cannot determine version of "++path++" :\n"++showstrJustv->debugverbosity$path++" is version "++displayvreturnversion-- | 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--xargs::Int->([String]->IO())->[String]->[String]->IO()xargsmaxSizerawSystemFunfixedArgsbigArgs=letfixedArgSize=sum(maplengthfixedArgs)+lengthfixedArgschunkSize=maxSize-fixedArgSizeinmapM_(rawSystemFun.(fixedArgs++))(chunkschunkSizebigArgs)wherechunkslen=unfoldr$\s->ifnullsthenNothingelseJust(chunk[]lens)chunkacc_[]=(reverseacc,[])chunkacclen(s:ss)|len'<len=chunk(s:acc)(len-len'-1)ss|otherwise=(reverseacc,s:ss)wherelen'=lengths-- -------------------------------------------------------------- * File Utilities-- ------------------------------------------------------------------------------ Finding files-- | Find a file by looking in a search path. The file path must match exactly.--findFile::[FilePath]-- ^search locations->FilePath-- ^File Name->IOFilePathfindFilesearchPathfileName=findFirstFileid[path</>fileName|path<-nubsearchPath]>>=maybe(die$fileName++" doesn't exist")return-- | 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.--findFileWithExtension::[String]->[FilePath]->FilePath->IO(MaybeFilePath)findFileWithExtensionextensionssearchPathbaseName=findFirstFileid[path</>baseName<.>ext|path<-nubsearchPath,ext<-nubextensions]-- | Like 'findFileWithExtension' but returns which element of the search path-- the file was found in, and the file path relative to that base directory.--findFileWithExtension'::[String]->[FilePath]->FilePath->IO(Maybe(FilePath,FilePath))findFileWithExtension'extensionssearchPathbaseName=findFirstFile(uncurry(</>))[(path,baseName<.>ext)|path<-nubsearchPath,ext<-nubextensions]findFirstFile::(a->FilePath)->[a]->IO(Maybea)findFirstFilefile=findFirstwherefindFirst[]=returnNothingfindFirst(x:xs)=doexists<-doesFileExist(filex)ifexiststhenreturn(Justx)elsefindFirstxs-- | Finds the files corresponding to a list of Haskell module names.---- As 'findModuleFile' but for a list of module names.--findModuleFiles::[FilePath]-- ^ build prefix (location of objects)->[String]-- ^ search suffixes->[ModuleName]-- ^ modules->IO[(FilePath,FilePath)]findModuleFilessearchPathextensionsmoduleNames=mapM(findModuleFilesearchPathextensions)moduleNames-- | 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.--findModuleFile::[FilePath]-- ^ build prefix (location of objects)->[String]-- ^ search suffixes->ModuleName-- ^ module->IO(FilePath,FilePath)findModuleFilesearchPathextensionsmoduleName=maybenotFoundreturn=<<findFileWithExtension'extensionssearchPath(ModuleName.toFilePathmoduleName)wherenotFound=die$"Error: Could not find module: "++displaymoduleName++" with any suffix: "++showextensions++" in the search path: "++showsearchPath-- | 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.--getDirectoryContentsRecursive::FilePath->IO[FilePath]getDirectoryContentsRecursivetopdir=recurseDirectories[""]whererecurseDirectories::[FilePath]->IO[FilePath]recurseDirectories[]=return[]recurseDirectories(dir:dirs)=unsafeInterleaveIO$do(files,dirs')<-collect[][]=<<getDirectoryContents(topdir</>dir)files'<-recurseDirectories(dirs'++dirs)return(files++files')wherecollectfilesdirs'[]=return(reversefiles,reversedirs')collectfilesdirs'(entry:entries)|ignoreentry=collectfilesdirs'entriescollectfilesdirs'(entry:entries)=doletdirEntry=dir</>entryisDirectory<-doesDirectoryExist(topdir</>dirEntry)ifisDirectorythencollectfiles(dirEntry:dirs')entrieselsecollect(dirEntry:files)dirs'entriesignore['.']=Trueignore['.','.']=Trueignore_=False------------------ File globbingdataFileGlob-- | No glob at all, just an ordinary file=NoGlobFilePath-- | dir prefix and extension, like @\"foo\/bar\/\*.baz\"@ corresponds to-- @FileGlob \"foo\/bar\" \".baz\"@|FileGlobFilePathStringparseFileGlob::FilePath->MaybeFileGlobparseFileGlobfilepath=casesplitExtensionsfilepathof(filepath',ext)->casesplitFileNamefilepath'of(dir,"*")|'*'`elem`dir||'*'`elem`ext||nullext->Nothing|nulldir->Just(FileGlob"."ext)|otherwise->Just(FileGlobdirext)_|'*'`elem`filepath->Nothing|otherwise->Just(NoGlobfilepath)matchFileGlob::FilePath->IO[FilePath]matchFileGlob=matchDirFileGlob"."matchDirFileGlob::FilePath->FilePath->IO[FilePath]matchDirFileGlobdirfilepath=caseparseFileGlobfilepathofNothing->die$"invalid file glob '"++filepath++"'. Wildcards '*' are only allowed in place of the file"++" name, not in the directory name or file extension."++" If a wildcard is used it must be with an file extension."Just(NoGlobfilepath')->return[filepath']Just(FileGlobdir'ext)->dofiles<-getDirectoryContents(dir</>dir')case[dir'</>file|file<-files,let(name,ext')=splitExtensionsfile,not(nullname)&&ext'==ext]of[]->die$"filepath wildcard '"++filepath++"' does not match any files."matches->returnmatches------------------------------------------ Copying and installing files and dirs-- | Same as 'createDirectoryIfMissing' but logs at higher verbosity levels.--createDirectoryIfMissingVerbose::Verbosity->Bool->FilePath->IO()createDirectoryIfMissingVerboseverbosityparentsToodir=doletmsgParents=ifparentsToothen" (and its parents)"else""infoverbosity("Creating "++dir++msgParents)createDirectoryIfMissingparentsToodir-- | 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.--copyFileVerbose::Verbosity->FilePath->FilePath->IO()copyFileVerboseverbositysrcdest=doinfoverbosity("copy "++src++" to "++dest)copyFilesrcdest-- | 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.--installOrdinaryFile::Verbosity->FilePath->FilePath->IO()installOrdinaryFileverbositysrcdest=doinfoverbosity("Installing "++src++" to "++dest)copyOrdinaryFilesrcdest-- | 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.--installExecutableFile::Verbosity->FilePath->FilePath->IO()installExecutableFileverbositysrcdest=doinfoverbosity("Installing executable "++src++" to "++dest)copyExecutableFilesrcdest-- | 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()copyFilesverbositytargetDirsrcFiles=do-- Create parent directories for everythingletdirs=map(targetDir</>).nub.map(takeDirectory.snd)$srcFilesmapM_(createDirectoryIfMissingVerboseverbosityTrue)dirs-- Copy all the filessequence_[letsrc=srcBase</>srcFiledest=targetDir</>srcFileincopyFileVerboseverbositysrcdest|(srcBase,srcFile)<-srcFiles]-- | This is like 'copyFiles' but uses 'installOrdinaryFile'.--installOrdinaryFiles::Verbosity->FilePath->[(FilePath,FilePath)]->IO()installOrdinaryFilesverbositytargetDirsrcFiles=do-- Create parent directories for everythingletdirs=map(targetDir</>).nub.map(takeDirectory.snd)$srcFilesmapM_(createDirectoryIfMissingVerboseverbosityTrue)dirs-- Copy all the filessequence_[letsrc=srcBase</>srcFiledest=targetDir</>srcFileininstallOrdinaryFileverbositysrcdest|(srcBase,srcFile)<-srcFiles]-- | 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.--installDirectoryContents::Verbosity->FilePath->FilePath->IO()installDirectoryContentsverbositysrcDirdestDir=doinfoverbosity("copy directory '"++srcDir++"' to '"++destDir++"'.")srcFiles<-getDirectoryContentsRecursivesrcDirinstallOrdinaryFilesverbositydestDir[(srcDir,f)|f<-srcFiles]----------------------------------- Deprecated file copy functions{-# DEPRECATED smartCopySources
"Use findModuleFiles and copyFiles or installOrdinaryFiles" #-}smartCopySources::Verbosity->[FilePath]->FilePath->[ModuleName]->[String]->IO()smartCopySourcesverbositysearchPathtargetDirmoduleNamesextensions=findModuleFilessearchPathextensionsmoduleNames>>=copyFilesverbositytargetDir{-# DEPRECATED copyDirectoryRecursiveVerbose
"You probably want installDirectoryContents instead" #-}copyDirectoryRecursiveVerbose::Verbosity->FilePath->FilePath->IO()copyDirectoryRecursiveVerboseverbositysrcDirdestDir=doinfoverbosity("copy directory '"++srcDir++"' to '"++destDir++"'.")srcFiles<-getDirectoryContentsRecursivesrcDircopyFilesverbositydestDir[(srcDir,f)|f<-srcFiles]----------------------------- Temporary files and dirs-- | Use a temporary filename that doesn't already exist.--withTempFile::FilePath-- ^ Temp dir to create the file in->String-- ^ File name template. See 'openTempFile'.->(FilePath->Handle->IOa)->IOawithTempFiletmpDirtemplateaction=Exception.bracket(openTempFiletmpDirtemplate)(\(name,handle)->hClosehandle>>removeFilename)(uncurryaction)-- | 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@.--withTempDirectory::Verbosity->FilePath->String->(FilePath->IOa)->IOawithTempDirectory_verbositytargetDirtemplate=Exception.bracket(createTempDirectorytargetDirtemplate)(removeDirectoryRecursive)------------------------------------- Safely reading and writing files-- | 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->IOa)->IOawithFileContentsnameaction=Exception.bracket(openFilenameReadMode)hClose(\hnd->hGetContentshnd>>=action)-- | 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.--writeFileAtomic::FilePath->String->IO()writeFileAtomictargetFilecontent=do(tmpFile,tmpHandle)<-openNewBinaryFiletargetDirtemplatedohPutStrtmpHandlecontenthClosetmpHandlerenameFiletmpFiletargetFile`onException`dohClosetmpHandleremoveFiletmpFilewheretemplate=targetName<.>"tmp"targetDir|nulltargetDir_=currentDir|otherwise=targetDir_--TODO: remove this when takeDirectory/splitFileName is fixed-- to always return a valid dir(targetDir_,targetName)=splitFileNametargetFile-- | 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()rewriteFilepathnewContent=flipcatchmightNotExist$doexistingContent<-readFilepath_<-evaluate(lengthexistingContent)unless(existingContent==newContent)$writeFileAtomicpathnewContentwheremightNotExiste|isDoesNotExistErrore=writeFileAtomicpathnewContent|otherwise=ioErrore-- | 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.)currentDir::FilePathcurrentDir="."-- -------------------------------------------------------------- * Finding the description file-- -------------------------------------------------------------- |Package description file (/pkgname/@.cabal@)defaultPackageDesc::Verbosity->IOFilePathdefaultPackageDesc_verbosity=findPackageDesccurrentDir-- |Find a package description file in the given directory. Looks for-- @.cabal@ files.findPackageDesc::FilePath-- ^Where to look->IOFilePath-- ^<pkgname>.cabalfindPackageDescdir=dofiles<-getDirectoryContentsdir-- 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<-filterMdoesFileExist[dir</>file|file<-files,let(name,ext)=splitExtensionfile,not(nullname)&&ext==".cabal"]casecabalFilesof[]->noDesc[cabalFile]->returncabalFilemultiple->multiDescmultiplewherenoDesc::IOanoDesc=die$"No cabal file found.\n"++"Please create a package description file <pkgname>.cabal"multiDesc::[String]->IOamultiDescl=die$"Multiple cabal files found.\n"++"Please use only one of: "++showl-- |Optional auxiliary package information file (/pkgname/@.buildinfo@)defaultHookedPackageDesc::IO(MaybeFilePath)defaultHookedPackageDesc=findHookedPackageDesccurrentDir-- |Find auxiliary package information in the given directory.-- Looks for @.buildinfo@ files.findHookedPackageDesc::FilePath-- ^Directory to search->IO(MaybeFilePath)-- ^/dir/@\/@/pkgname/@.buildinfo@, if presentfindHookedPackageDescdir=dofiles<-getDirectoryContentsdirbuildInfoFiles<-filterMdoesFileExist[dir</>file|file<-files,let(name,ext)=splitExtensionfile,not(nullname)&&ext==buildInfoExt]casebuildInfoFilesof[]->returnNothing[f]->return(Justf)_->die("Multiple files with extension "++buildInfoExt)buildInfoExt::StringbuildInfoExt=".buildinfo"-- -------------------------------------------------------------- * Unicode stuff-- -------------------------------------------------------------- This is a modification of the UTF8 code from gtk2hs and the-- utf8-string package.fromUTF8::String->StringfromUTF8[]=[]fromUTF8(c:cs)|c<='\x7F'=c:fromUTF8cs|c<='\xBF'=replacementChar:fromUTF8cs|c<='\xDF'=twoBytesccs|c<='\xEF'=moreBytes30x800cs(ordc.&.0xF)|c<='\xF7'=moreBytes40x10000cs(ordc.&.0x7)|c<='\xFB'=moreBytes50x200000cs(ordc.&.0x3)|c<='\xFD'=moreBytes60x4000000cs(ordc.&.0x1)|otherwise=replacementChar:fromUTF8cswheretwoBytesc0(c1:cs')|ordc1.&.0xC0==0x80=letd=((ordc0.&.0x1F)`shiftL`6).|.(ordc1.&.0x3F)inifd>=0x80thenchrd:fromUTF8cs'elsereplacementChar:fromUTF8cs'twoBytes_cs'=replacementChar:fromUTF8cs'moreBytes::Int->Int->[Char]->Int->[Char]moreBytes1overlongcs'acc|overlong<=acc&&acc<=0x10FFFF&&(acc<0xD800||0xDFFF<acc)&&(acc<0xFFFE||0xFFFF<acc)=chracc:fromUTF8cs'|otherwise=replacementChar:fromUTF8cs'moreBytesbyteCountoverlong(cn:cs')acc|ordcn.&.0xC0==0x80=moreBytes(byteCount-1)overlongcs'((acc`shiftL`6).|.ordcn.&.0x3F)moreBytes__cs'_=replacementChar:fromUTF8cs'replacementChar='\xfffd'toUTF8::String->StringtoUTF8[]=[]toUTF8(c:cs)|c<='\x07F'=c:toUTF8cs|c<='\x7FF'=chr(0xC0.|.(w`shiftR`6)):chr(0x80.|.(w.&.0x3F)):toUTF8cs|c<='\xFFFF'=chr(0xE0.|.(w`shiftR`12)):chr(0x80.|.((w`shiftR`6).&.0x3F)):chr(0x80.|.(w.&.0x3F)):toUTF8cs|otherwise=chr(0xf0.|.(w`shiftR`18)):chr(0x80.|.((w`shiftR`12).&.0x3F)):chr(0x80.|.((w`shiftR`6).&.0x3F)):chr(0x80.|.(w.&.0x3F)):toUTF8cswherew=ordc-- | Ignore a Unicode byte order mark (BOM) at the beginning of the input--ignoreBOM::String->StringignoreBOM('\xFEFF':string)=stringignoreBOMstring=string-- | Reads a UTF8 encoded text file as a Unicode String---- Reads lazily using ordinary 'readFile'.--readUTF8File::FilePath->IOStringreadUTF8Filef=fmap(ignoreBOM.fromUTF8).hGetContents=<<openBinaryFilefReadMode-- | Reads a UTF8 encoded text file as a Unicode String---- Same behaviour as 'withFileContents'.--withUTF8FileContents::FilePath->(String->IOa)->IOawithUTF8FileContentsnameaction=Exception.bracket(openBinaryFilenameReadMode)hClose(\hnd->hGetContentshnd>>=action.ignoreBOM.fromUTF8)-- | Writes a Unicode String as a UTF8 encoded text file.---- Uses 'writeFileAtomic', so provides the same guarantees.--writeUTF8File::FilePath->String->IO()writeUTF8Filepath=writeFileAtomicpath.toUTF8-- | Fix different systems silly line ending conventionsnormaliseLineEndings::String->StringnormaliseLineEndings[]=[]normaliseLineEndings('\r':'\n':s)='\n':normaliseLineEndingss-- windowsnormaliseLineEndings('\r':s)='\n':normaliseLineEndingss-- old osxnormaliseLineEndings(c:s)=c:normaliseLineEndingss-- -------------------------------------------------------------- * Common utils-- ------------------------------------------------------------equating::Eqa=>(b->a)->b->b->Boolequatingpxy=px==pycomparing::Orda=>(b->a)->b->b->Orderingcomparingpxy=px`compare`pyisInfixOf::String->String->BoolisInfixOfneedlehaystack=any(isPrefixOfneedle)(tailshaystack)intercalate::[a]->[[a]]->[a]intercalatesep=concat.intersperseseplowercase::String->Stringlowercase=mapChar.toLower