------------------------------------------------------------------------------- |-- Module : Distribution.PackageDescription-- Copyright : Isaac Jones 2003-2005---- Maintainer : cabal-devel@haskell.org-- Portability : portable---- This defines the data structure for the @.cabal@ file format. There are-- several parts to this structure. It has top level info and then 'Library'-- and 'Executable' sections each of which have associated 'BuildInfo' data-- that's used to build the library or exe. To further complicate things there-- is both a 'PackageDescription' and a 'GenericPackageDescription'. This-- distinction relates to cabal configurations. When we initially read a-- @.cabal@ file we get a 'GenericPackageDescription' which has all the-- conditional sections. Before actually building a package we have to decide-- on each conditional. Once we've done that we get a 'PackageDescription'.-- It was done this way initially to avoid breaking too much stuff when the-- feature was introduced. It could probably do with being rationalised at some-- point to make it simpler.{- 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.PackageDescription(-- * Package descriptionsPackageDescription(..),emptyPackageDescription,BuildType(..),knownBuildTypes,-- ** LibrariesLibrary(..),emptyLibrary,withLib,hasLibs,libModules,-- ** ExecutablesExecutable(..),emptyExecutable,withExe,hasExes,exeModules,-- * Build informationBuildInfo(..),emptyBuildInfo,allBuildInfo,hcOptions,-- ** Supplementary build informationHookedBuildInfo,emptyHookedBuildInfo,updatePackageDescription,-- * package configurationGenericPackageDescription(..),Flag(..),FlagName(..),FlagAssignment,CondTree(..),ConfVar(..),Condition(..),-- * Source repositoriesSourceRepo(..),RepoKind(..),RepoType(..),)whereimportData.List(nub)importData.Monoid(Monoid(mempty,mappend))importText.PrettyPrint.HughesPJasDispimportqualifiedDistribution.Compat.ReadPasParseimportqualifiedData.CharasChar(isAlphaNum,toLower)importDistribution.Package(PackageName(PackageName),PackageIdentifier(PackageIdentifier),Dependency,Package(..))importDistribution.ModuleName(ModuleName)importDistribution.Version(Version(Version),VersionRange(AnyVersion))importDistribution.License(License(AllRightsReserved))importDistribution.Compiler(CompilerFlavor)importDistribution.System(OS,Arch)importDistribution.Text(Text(..),display)importLanguage.Haskell.Extension(Extension)-- ------------------------------------------------------------------------------- The PackageDescription type-- | This data type is the internal representation of the file @pkg.cabal@.-- It contains two kinds of information about the package: information-- which is needed for all packages, such as the package name and version, and-- information which is needed for the simple build system only, such as-- the compiler options and library name.--dataPackageDescription=PackageDescription{-- the following are required by all packages:package::PackageIdentifier,license::License,licenseFile::FilePath,copyright::String,maintainer::String,author::String,stability::String,testedWith::[(CompilerFlavor,VersionRange)],homepage::String,pkgUrl::String,bugReports::String,sourceRepos::[SourceRepo],synopsis::String,-- ^A one-line summary of this packagedescription::String,-- ^A more verbose description of this packagecategory::String,customFieldsPD::[(String,String)],-- ^Custom fields starting-- with x-, stored in a-- simple assoc-list.buildDepends::[Dependency],descCabalVersion::VersionRange,-- ^If this package depends on a specific version of Cabal, give that here.buildType::MaybeBuildType,-- componentslibrary::MaybeLibrary,executables::[Executable],dataFiles::[FilePath],dataDir::FilePath,extraSrcFiles::[FilePath],extraTmpFiles::[FilePath]}deriving(Show,Read,Eq)instancePackagePackageDescriptionwherepackageId=packageemptyPackageDescription::PackageDescriptionemptyPackageDescription=PackageDescription{package=PackageIdentifier(PackageName"")(Version[][]),license=AllRightsReserved,licenseFile="",descCabalVersion=AnyVersion,buildType=Nothing,copyright="",maintainer="",author="",stability="",testedWith=[],buildDepends=[],homepage="",pkgUrl="",bugReports="",sourceRepos=[],synopsis="",description="",category="",customFieldsPD=[],library=Nothing,executables=[],dataFiles=[],dataDir="",extraSrcFiles=[],extraTmpFiles=[]}-- | The type of build system used by this package.dataBuildType=Simple-- ^ calls @Distribution.Simple.defaultMain@|Configure-- ^ calls @Distribution.Simple.defaultMainWithHooks defaultUserHooks@,-- which invokes @configure@ to generate additional build-- information used by later phases.|Make-- ^ calls @Distribution.Make.defaultMain@|Custom-- ^ uses user-supplied @Setup.hs@ or @Setup.lhs@ (default)|UnknownBuildTypeString-- ^ a package that uses an unknown build type cannot actually-- be built. Doing it this way rather than just giving a-- parse error means we get better error messages and allows-- you to inspect the rest of the package description.deriving(Show,Read,Eq)knownBuildTypes::[BuildType]knownBuildTypes=[Simple,Configure,Make,Custom]instanceTextBuildTypewheredisp(UnknownBuildTypeother)=Disp.textotherdispother=Disp.text(showother)parse=doname<-Parse.munch1Char.isAlphaNumreturn$casenameof"Simple"->Simple"Configure"->Configure"Custom"->Custom"Make"->Make_->UnknownBuildTypename-- ----------------------------------------------------------------------------- The Library typedataLibrary=Library{exposedModules::[ModuleName],libExposed::Bool,-- ^ Is the lib to be exposed by default?libBuildInfo::BuildInfo}deriving(Show,Eq,Read)instanceMonoidLibrarywheremempty=Library{exposedModules=mempty,libExposed=True,libBuildInfo=mempty}mappendab=Library{exposedModules=combineexposedModules,libExposed=libExposeda&&libExposedb,-- so False propagateslibBuildInfo=combinelibBuildInfo}wherecombinefield=fielda`mappend`fieldbemptyLibrary::LibraryemptyLibrary=mempty-- |does this package have any libraries?hasLibs::PackageDescription->BoolhasLibsp=maybeFalse(buildable.libBuildInfo)(libraryp)-- |'Maybe' version of 'hasLibs'maybeHasLibs::PackageDescription->MaybeLibrarymaybeHasLibsp=libraryp>>=\lib->ifbuildable(libBuildInfolib)thenJustlibelseNothing-- |If the package description has a library section, call the given-- function with the library build info as argument.withLib::PackageDescription->a->(Library->IOa)->IOawithLibpkg_descraf=maybe(returna)f(maybeHasLibspkg_descr)-- |Get all the module names from the libraries in this packagelibModules::PackageDescription->[ModuleName]libModulesPackageDescription{library=lib}=maybe[]exposedModuleslib++maybe[](otherModules.libBuildInfo)lib-- ----------------------------------------------------------------------------- The Executable typedataExecutable=Executable{exeName::String,modulePath::FilePath,buildInfo::BuildInfo}deriving(Show,Read,Eq)instanceMonoidExecutablewheremempty=Executable{exeName=mempty,modulePath=mempty,buildInfo=mempty}mappendab=Executable{exeName=combine'exeName,modulePath=combinemodulePath,buildInfo=combinebuildInfo}wherecombinefield=fielda`mappend`fieldbcombine'field=case(fielda,fieldb)of("","")->""("",x)->x(x,"")->x(x,y)->error$"Ambiguous values for executable field: '"++x++"' and '"++y++"'"emptyExecutable::ExecutableemptyExecutable=mempty-- |does this package have any executables?hasExes::PackageDescription->BoolhasExesp=any(buildable.buildInfo)(executablesp)-- | Perform the action on each buildable 'Executable' in the package-- description.withExe::PackageDescription->(Executable->IOa)->IO()withExepkg_descrf=sequence_[fexe|exe<-executablespkg_descr,buildable(buildInfoexe)]-- |Get all the module names from the exes in this packageexeModules::PackageDescription->[ModuleName]exeModulesPackageDescription{executables=execs}=concatMap(otherModules.buildInfo)execs-- ----------------------------------------------------------------------------- The BuildInfo type-- Consider refactoring into executable and library versions.dataBuildInfo=BuildInfo{buildable::Bool,-- ^ component is buildable herebuildTools::[Dependency],-- ^ tools needed to build this bitcppOptions::[String],-- ^ options for pre-processing Haskell codeccOptions::[String],-- ^ options for C compilerldOptions::[String],-- ^ options for linkerpkgconfigDepends::[Dependency],-- ^ pkg-config packages that are usedframeworks::[String],-- ^support frameworks for Mac OS XcSources::[FilePath],hsSourceDirs::[FilePath],-- ^ where to look for the haskell module hierarchyotherModules::[ModuleName],-- ^ non-exposed or non-main modulesextensions::[Extension],extraLibs::[String],-- ^ what libraries to link with when compiling a program that uses your packageextraLibDirs::[String],includeDirs::[FilePath],-- ^directories to find .h filesincludes::[FilePath],-- ^ The .h files to be found in includeDirsinstallIncludes::[FilePath],-- ^ .h files to install with the packageoptions::[(CompilerFlavor,[String])],ghcProfOptions::[String],ghcSharedOptions::[String],customFieldsBI::[(String,String)]-- ^Custom fields starting-- with x-, stored in a-- simple assoc-list.}deriving(Show,Read,Eq)instanceMonoidBuildInfowheremempty=BuildInfo{buildable=True,buildTools=[],cppOptions=[],ccOptions=[],ldOptions=[],pkgconfigDepends=[],frameworks=[],cSources=[],hsSourceDirs=[],otherModules=[],extensions=[],extraLibs=[],extraLibDirs=[],includeDirs=[],includes=[],installIncludes=[],options=[],ghcProfOptions=[],ghcSharedOptions=[],customFieldsBI=[]}mappendab=BuildInfo{buildable=buildablea&&buildableb,buildTools=combineNubbuildTools,cppOptions=combinecppOptions,ccOptions=combineccOptions,ldOptions=combineldOptions,pkgconfigDepends=combineNubpkgconfigDepends,frameworks=combineNubframeworks,cSources=combineNubcSources,hsSourceDirs=combineNubhsSourceDirs,otherModules=combineNubotherModules,extensions=combineNubextensions,extraLibs=combineextraLibs,extraLibDirs=combineNubextraLibDirs,includeDirs=combineNubincludeDirs,includes=combineNubincludes,installIncludes=combineNubinstallIncludes,options=combineoptions,ghcProfOptions=combineghcProfOptions,ghcSharedOptions=combineghcSharedOptions,customFieldsBI=combinecustomFieldsBI}wherecombinefield=fielda`mappend`fieldbcombineNubfield=nub(combinefield)emptyBuildInfo::BuildInfoemptyBuildInfo=mempty-- | The 'BuildInfo' for the library (if there is one and it's buildable) and-- all the buildable executables. Useful for gathering dependencies.allBuildInfo::PackageDescription->[BuildInfo]allBuildInfopkg_descr=[bi|Justlib<-[librarypkg_descr],letbi=libBuildInfolib,buildablebi]++[bi|exe<-executablespkg_descr,letbi=buildInfoexe,buildablebi]typeHookedBuildInfo=(MaybeBuildInfo,[(String,BuildInfo)])emptyHookedBuildInfo::HookedBuildInfoemptyHookedBuildInfo=(Nothing,[])-- |Select options for a particular Haskell compiler.hcOptions::CompilerFlavor->BuildInfo->[String]hcOptionshcbi=[opt|(hc',opts)<-optionsbi,hc'==hc,opt<-opts]-- -------------------------------------------------------------- * Source repos-- -------------------------------------------------------------- | Information about the source revision control system for a package.---- When specifying a repo it is useful to know the meaning or intention of the-- information as doing so enables automation. There are two obvious common-- purposes: one is to find the repo for the latest development version, the-- other is to find the repo for this specific release. The 'ReopKind'-- specifies which one we mean (or another custom one).---- A package can specify one or the other kind or both. Most will specify just-- a head repo but some may want to specify a repo to reconstruct the sources-- for this package release.---- The required information is the 'RepoType' which tells us if it's using-- 'Darcs', 'Git' for example. The 'repoLocation' and other details are-- interpreted according to the repo type.--dataSourceRepo=SourceRepo{-- | The kind of repo. This field is required.repoKind::RepoKind,-- | The type of the source repository system for this repo, eg 'Darcs' or-- 'Git'. This field is required.repoType::MaybeRepoType,-- | The location of the repository. For most 'RepoType's this is a URL.-- This field is required.repoLocation::MaybeString,-- | 'CVS' can put multiple \"modules\" on one server and requires a-- module name in addition to the location to identify a particular repo.-- Logically this is part of the location but unfortunately has to be-- specified separately. This field is required for the 'CVS' 'RepoType' and-- should not be given otherwise.repoModule::MaybeString,-- | The name or identifier of the branch, if any. Many source control-- systems have the notion of multiple branches in a repo that exist in the-- same location. For example 'Git' and 'CVS' use this while systems like-- 'Darcs' use different locations for different branches. This field is-- optional but should be used if necessary to identify the sources,-- especially for the 'RepoThis' repo kind.repoBranch::MaybeString,-- | The tag identify a particular state of the repository. This should be-- given for the 'RepoThis' repo kind and not for 'RepoHead' kind.--repoTag::MaybeString,-- | Some repositories contain multiple projects in different subdirectories-- This field specifies the subdirectory where this packages sources can be-- found, eg the subdirectory containing the @.cabal@ file. It is interpreted-- relative to the root of the repository. This field is optional. If not-- given the default is \".\" ie no subdirectory.repoSubdir::MaybeFilePath}deriving(Eq,Read,Show)-- | What this repo info is for, what it represents.--dataRepoKind=-- | The repository for the \"head\" or development version of the project.-- This repo is where we should track the latest development activity or-- the usual repo people should get to contribute patches.RepoHead-- | The repository containing the sources for this exact package version-- or release. For this kind of repo a tag should be given to give enough-- information to re-create the exact sources.|RepoThis|RepoKindUnknownStringderiving(Eq,Ord,Read,Show)-- | An enumeration of common source control systems. The fields used in the-- 'SourceRepo' depend on the type of repo. The tools and methods used to-- obtain and track the repo depend on the repo type.--dataRepoType=Darcs|Git|SVN|CVS|Mercurial|GnuArch|Bazaar|Monotone|OtherRepoTypeStringderiving(Eq,Ord,Read,Show)knownRepoTypes::[RepoType]knownRepoTypes=[Darcs,Git,SVN,CVS,Mercurial,GnuArch,Bazaar,Monotone]repoTypeAliases::RepoType->[String]repoTypeAliasesBazaar=["bzr"]repoTypeAliasesMercurial=["hg"]repoTypeAliasesGnuArch=["arch"]repoTypeAliases_=[]instanceTextRepoKindwheredispRepoHead=Disp.text"head"dispRepoThis=Disp.text"this"disp(RepoKindUnknownother)=Disp.textotherparse=doname<-identreturn$caselowercasenameof"head"->RepoHead"this"->RepoThis_->RepoKindUnknownnameinstanceTextRepoTypewheredisp(OtherRepoTypeother)=Disp.textotherdispother=Disp.text(lowercase(showother))parse=fmapclassifyRepoTypeidentclassifyRepoType::String->RepoTypeclassifyRepoTypes=caselookup(lowercases)repoTypeMapofJustrepoType'->repoType'Nothing->OtherRepoTypeswhererepoTypeMap=[(name,repoType')|repoType'<-knownRepoTypes,name<-displayrepoType':repoTypeAliasesrepoType']ident::Parse.ReadPrStringident=Parse.munch1(\c->Char.isAlphaNumc||c=='_'||c=='-')lowercase::String->Stringlowercase=mapChar.toLower-- -------------------------------------------------------------- * Utils-- ------------------------------------------------------------updatePackageDescription::HookedBuildInfo->PackageDescription->PackageDescriptionupdatePackageDescription(mb_lib_bi,exe_bi)p=p{executables=updateExecutablesexe_bi(executablesp),library=updateLibrarymb_lib_bi(libraryp)}whereupdateLibrary::MaybeBuildInfo->MaybeLibrary->MaybeLibraryupdateLibrary(Justbi)(Justlib)=Just(lib{libBuildInfo=bi`mappend`libBuildInfolib})updateLibraryNothingmb_lib=mb_lib--the lib only exists in the buildinfo file. FIX: Is this--wrong? If there aren't any exposedModules, then the library--won't build anyway. add to sanity checker?updateLibrary(Justbi)Nothing=JustemptyLibrary{libBuildInfo=bi}updateExecutables::[(String,BuildInfo)]-- ^[(exeName, new buildinfo)]->[Executable]-- ^list of executables to update->[Executable]-- ^list with exeNames updatedupdateExecutablesexe_bi'executables'=foldrupdateExecutableexecutables'exe_bi'updateExecutable::(String,BuildInfo)-- ^(exeName, new buildinfo)->[Executable]-- ^list of executables to update->[Executable]-- ^libst with exeName updatedupdateExecutable_[]=[]updateExecutableexe_bi'@(name,bi)(exe:exes)|exeNameexe==name=exe{buildInfo=bi`mappend`buildInfoexe}:exes|otherwise=exe:updateExecutableexe_bi'exes-- ----------------------------------------------------------------------------- The GenericPackageDescription typedataGenericPackageDescription=GenericPackageDescription{packageDescription::PackageDescription,genPackageFlags::[Flag],condLibrary::Maybe(CondTreeConfVar[Dependency]Library),condExecutables::[(String,CondTreeConfVar[Dependency]Executable)]}deriving(Show,Eq)instancePackageGenericPackageDescriptionwherepackageId=packageId.packageDescription{-
-- XXX: I think we really want a PPrint or Pretty or ShowPretty class.
instance Show GenericPackageDescription where
show (GenericPackageDescription pkg flgs mlib exes) =
showPackageDescription pkg ++ "\n" ++
(render $ vcat $ map ppFlag flgs) ++ "\n" ++
render (maybe empty (\l -> showStanza "Library" (ppCondTree l showDeps)) mlib)
++ "\n" ++
(render $ vcat $
map (\(n,ct) -> showStanza ("Executable " ++ n) (ppCondTree ct showDeps)) exes)
where
ppFlag (MkFlag name desc dflt manual) =
showStanza ("Flag " ++ name)
((if (null desc) then empty else
text ("Description: " ++ desc)) $+$
text ("Default: " ++ show dflt) $+$
text ("Manual: " ++ show manual))
showDeps = fsep . punctuate comma . map showDependency
showStanza h b = text h <+> lbrace $+$ nest 2 b $+$ rbrace
-}-- | A flag can represent a feature to be included, or a way of linking-- a target against its dependencies, or in fact whatever you can think of.dataFlag=MkFlag{flagName::FlagName,flagDescription::String,flagDefault::Bool,flagManual::Bool}deriving(Show,Eq)-- | A 'FlagName' is the name of a user-defined configuration flagnewtypeFlagName=FlagNameStringderiving(Eq,Ord,Show)-- | A 'FlagAssignment' is a total or partial mapping of 'FlagName's to-- 'Bool' flag values. It represents the flags chosen by the user or-- discovered during configuration. For example @--flags=foo --flags=-bar@-- becomes @[("foo", True), ("bar", False)]@--typeFlagAssignment=[(FlagName,Bool)]-- | A @ConfVar@ represents the variable type used.dataConfVar=OSOS|ArchArch|FlagFlagName|ImplCompilerFlavorVersionRangederiving(Eq,Show)--instance Text ConfVar where-- disp (OS os) = "os(" ++ display os ++ ")"-- disp (Arch arch) = "arch(" ++ display arch ++ ")"-- disp (Flag (ConfFlag f)) = "flag(" ++ f ++ ")"-- disp (Impl c v) = "impl(" ++ display c-- ++ " " ++ display v ++ ")"-- | A boolean expression parameterized over the variable type used.dataConditionc=Varc|LitBool|CNot(Conditionc)|COr(Conditionc)(Conditionc)|CAnd(Conditionc)(Conditionc)deriving(Show,Eq)--instance Text c => Text (Condition c) where-- disp (Var x) = text (show x)-- disp (Lit b) = text (show b)-- disp (CNot c) = char '!' <> parens (ppCond c)-- disp (COr c1 c2) = parens $ sep [ppCond c1, text "||" <+> ppCond c2]-- disp (CAnd c1 c2) = parens $ sep [ppCond c1, text "&&" <+> ppCond c2]dataCondTreevca=CondNode{condTreeData::a,condTreeConstraints::c,condTreeComponents::[(Conditionv,CondTreevca,Maybe(CondTreevca))]}deriving(Show,Eq)--instance (Text v, Text c) => Text (CondTree v c a) where-- disp (CondNode _dat cs ifs) =-- (text "build-depends: " <+>-- disp cs)-- $+$-- (vcat $ map ppIf ifs)-- where-- ppIf (c,thenTree,mElseTree) =-- ((text "if" <+> ppCond c <> colon) $$-- nest 2 (ppCondTree thenTree disp))-- $+$ (maybe empty (\t -> text "else: " $$ nest 2 (ppCondTree t disp))-- mElseTree)