Package.hs 20.9 KB
Newer Older
md9ms's avatar
md9ms committed
1
{-# OPTIONS -cpp #-}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
-----------------------------------------------------------------------------
-- |
-- Module      :  Distribution.Package
-- Copyright   :  Isaac Jones 2003-2004
-- 
-- Maintainer  :  Isaac Jones <ijones@syntaxpolice.org>
-- Stability   :  alpha
-- Portability :  
--
-- Explanation: <FIX>
-- WHERE DOES THIS MODULE FIT IN AT A HIGH-LEVEL <FIX>

{- Copyright (c) 2003-2004, Isaac Jones
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. -}

45
module Distribution.Package (
simonmar's avatar
simonmar committed
46
47
	PackageIdentifier(..), 
	showPackageId,
48
	PackageDescription(..),
md9ms's avatar
md9ms committed
49
        BuildInfo(..),
50
        Executable(..),
ijones's avatar
ijones committed
51
	emptyPackageDescription,
52
        parsePackageDesc,
ijones's avatar
ijones committed
53
        hasLibs,
ijones's avatar
ijones committed
54
#ifdef DEBUG        
55
        hunitTests,
ijones's avatar
ijones committed
56
        test
ijones's avatar
ijones committed
57
#endif
58
  ) where
59

md9ms's avatar
md9ms committed
60
61
62
63
import Control.Monad.State
import Control.Monad(when, foldM)
import Control.Monad.Error
import Data.Char(isSpace, toLower)
md9ms's avatar
md9ms committed
64
import Data.List(isPrefixOf)
65
import Data.Maybe(fromMaybe)
ijones's avatar
ijones committed
66

67
68
import Distribution.Version(Version(..), VersionRange(..),
                            showVersion, parseVersion, parseVersionRange)
md9ms's avatar
md9ms committed
69
import Distribution.Misc(License(..), Dependency(..), Extension(..))
md9ms's avatar
md9ms committed
70
import Distribution.Setup(CompilerFlavor(..))
71

72
73
import System.IO(openFile, IOMode(..), hGetContents)

ijones's avatar
ijones committed
74
75
import Text.ParserCombinators.Parsec

ijones's avatar
ijones committed
76
#ifdef DEBUG
ijones's avatar
ijones committed
77
import HUnit (Test(..), (~:), (~=?), assertEqual, assertBool, Assertion, runTestTT)
ijones's avatar
ijones committed
78
79
#endif

80
81
data PackageIdentifier
    = PackageIdentifier {pkgName::String, pkgVersion::Version}
simonmar's avatar
simonmar committed
82
      deriving (Read, Show, Eq)
83

simonmar's avatar
simonmar committed
84
showPackageId :: PackageIdentifier -> String
ijones's avatar
ijones committed
85
showPackageId (PackageIdentifier n (Version [] _)) = n -- if no version, don't show version.
simonmar's avatar
simonmar committed
86
87
88
showPackageId pkgid = 
  pkgName pkgid ++ '-': showVersion (pkgVersion pkgid)

89
90
91
92
93
94
95
96
97
98
-- | This data type is the internal representation of the file @pkg.descr@.
-- 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.
-- 
data PackageDescription
    =  PackageDescription {
	-- the following are required by all packages:
	package        :: PackageIdentifier,
99
        license        :: License,
100
101
102
        copyright      :: String,
        maintainer     :: String,
        stability      :: String,
103
        library        :: Maybe BuildInfo,
104
105
106
107
108
109
110
111
        executables    :: [Executable]
    }
    deriving (Show, Read, Eq)

data Executable = Executable {
        exeName    :: String,
        modulePath :: FilePath,
        buildInfo  :: BuildInfo
112
    }
ijones's avatar
ijones committed
113
114
    deriving (Show, Read, Eq)

115
116
117
118
119
120
121
122
123
124
125
126
127
128
data BuildInfo = BuildInfo {
        buildDepends    :: [Dependency],
        modules         :: [String],
	exposedModules  :: [String],
        cSources        :: [FilePath],
        hsSourceDir     :: FilePath,
        extensions      :: [Extension],
        extraLibs       :: [String],
        includeDirs     :: [FilePath],
        includes        :: [FilePath],
        options         :: [(CompilerFlavor,[String])]
    }
    deriving (Show,Read,Eq)

ijones's avatar
ijones committed
129
130
131
132
133
134
135
136
137
-- |Set the name for this package. Convenience function.
setPkgName :: String -> PackageDescription -> PackageDescription
setPkgName n desc@PackageDescription{package=pkgIdent}
    = desc{package=pkgIdent{pkgName=n}}

-- |Set the version for this package. Convenience function.
setPkgVersion :: Version -> PackageDescription -> PackageDescription
setPkgVersion v desc@PackageDescription{package=pkgIdent}
    = desc{package=pkgIdent{pkgVersion=v}}
138
139
140

emptyPackageDescription :: PackageDescription
emptyPackageDescription
ijones's avatar
ijones committed
141
    =  PackageDescription {package      = PackageIdentifier "" (Version [] []),
142
                      license      = AllRightsReserved,
143
144
145
                      copyright    = "",
                      maintainer   = "",
                      stability    = "",
146
147
                      library      = Nothing,
                      executables  = []
148
                     }
149

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
emptyBuildInfo :: BuildInfo
emptyBuildInfo = BuildInfo {
                      buildDepends   = [],
                      modules        = [],
		      exposedModules = [], -- Only used for libs
		      cSources       = [],
		      hsSourceDir    = ".", -- FIX: FileUtils.currentDir
                      extensions     = [],
                      extraLibs      = [],
                      includeDirs    = [],
                      includes       = [],
                      options        = []
                     }
                        
-- |Add options for a specific compiler. Convenience function.
setOptions :: CompilerFlavor -> [String] -> BuildInfo -> BuildInfo
setOptions c xs desc@BuildInfo{options=opts}
    = desc{options=(c,xs):opts}
ijones's avatar
ijones committed
168

ijones's avatar
ijones committed
169
170
171
172
173
174
175
176
-- |does this package have any libraries?
hasLibs :: PackageDescription -> Bool
hasLibs p = case library p of
            Just l  -> if null (cSources l) && null (modules l)
                       then False else True
            Nothing -> False


ijones's avatar
ijones committed
177
178
179
180
-- ------------------------------------------------------------
-- * Parsing
-- ------------------------------------------------------------

ijones's avatar
ijones committed
181
182
183
notImp :: String -> a
notImp s = error $ s ++ " not yet implemented"

184
-- |Parse the given package file.
185
parsePackageDesc :: FilePath -> IO PackageDescription
186
187
188
parsePackageDesc p = do h <- openFile p ReadMode
                        str <- hGetContents h
                        case parseDescription str of
md9ms's avatar
md9ms committed
189
                          Left  e -> error (showError e) -- FIXME
190
                          Right x -> return x
191

md9ms's avatar
md9ms committed
192
193
194
195
196
197
data PError = Parsec ParseError | FromString String
        deriving Show

instance Error PError where
        strMsg = FromString

md9ms's avatar
md9ms committed
198
199
200
showError (Parsec pe)    = show pe
showError (FromString s) = s

md9ms's avatar
md9ms committed
201
parseDescription :: String -> Either PError PackageDescription
202
203
204
205
206
207
208
parseDescription inp = do let (st:sts) = splitStanzas inp
                          pkg <- foldM parseBasicStanza emptyPackageDescription st
                          exes <- mapM parseExecutableStanza sts
                          return pkg{executables=exes}
  where -- The basic stanza, with library building info
        parseBasicStanza pkg (f@"name",      val) = return (setPkgName val pkg)
        parseBasicStanza pkg (f@"version",   val) =
md9ms's avatar
md9ms committed
209
210
          do v <- runP f parseVersion val
             return (setPkgVersion v pkg)
211
212
        parseBasicStanza pkg (f@"copyright", val) = return pkg{copyright=val}
        parseBasicStanza pkg (f@"license",   val) =
md9ms's avatar
md9ms committed
213
214
          do l <- runP f parseLicense val
             return pkg{license=l}
215
216
217
        parseBasicStanza pkg (f@"license-file", val) =
          do path <- runP f parseFilePath val
             return pkg{license=OtherLicense path}
218
219
220
221
222
223
224
225
        parseBasicStanza pkg (f@"maintainer", val) = return pkg{maintainer=val}
        parseBasicStanza pkg (f@"stability",  val) = return pkg{stability=val}
        parseBasicStanza pkg (field, val) =
          do let lib = fromMaybe emptyBuildInfo (library pkg)
             lib' <- parseExeHelp lib (field, val)
             return pkg{library=Just lib'}
        -- Stanzas for executables
        parseExecutableStanza (("executable",exeName):st) =
226
227
228
229
230
231
          case lookup "main-is" st of
            Just xs -> do path <- runP "main-is" parseFilePath xs
                          binfo <- foldM parseExeHelp emptyBuildInfo st
                          return $ Executable exeName path binfo
            Nothing -> throwError $ strMsg $
                "No 'Main-Is' field found for " ++ exeName ++ " stanza"
232
233
        parseExecutableStanza ((f,_):st) = throwError $ strMsg $
                "'Executable' stanza starts with field '" ++ f ++ "'"
234
        parseExeHelp binfo (f@"main-is", _) = return binfo
235
        parseExeHelp binfo (f@"extra-libs", val) =
md9ms's avatar
md9ms committed
236
          do xs <- runP f (parseCommaList word) val
237
238
             return binfo{extraLibs=xs}
        parseExeHelp binfo (f@"build-depends", val) =
md9ms's avatar
md9ms committed
239
          do xs <- runP f (parseCommaList parseDependency) val
240
             return binfo{buildDepends=xs}
md9ms's avatar
md9ms committed
241
        -- Paths and stuff
242
        parseExeHelp binfo (f@"c-sources", val) =
243
          do paths <- runP f (parseCommaList parseFilePath) val
244
245
             return binfo{cSources=paths}
        parseExeHelp binfo (f@"include-dirs", val) =
246
          do paths <- runP f (parseCommaList parseFilePath) val
247
248
             return binfo{includeDirs=paths}
        parseExeHelp binfo (f@"includes", val) =
249
          do paths <- runP f (parseCommaList parseFilePath) val
250
251
             return binfo{includes=paths}
        parseExeHelp binfo (f@"hs-source-dir", val) =
md9ms's avatar
md9ms committed
252
          do path <- runP f parseFilePath val
253
             return binfo{hsSourceDir=path}
md9ms's avatar
md9ms committed
254
        -- Module related
255
        parseExeHelp binfo (f@"modules", val) =
md9ms's avatar
md9ms committed
256
          do xs <- runP f (parseCommaList moduleName) val
257
258
             return binfo{modules=xs}
        parseExeHelp binfo (f@"exposed-modules", val) =
md9ms's avatar
md9ms committed
259
          do xs <- runP f (parseCommaList moduleName) val
260
261
             return binfo{exposedModules=xs}
        parseExeHelp binfo (f@"extensions", val) =
md9ms's avatar
md9ms committed
262
          do exts <- runP f (parseCommaList parseExtension) val
263
264
             return binfo{extensions=exts}
        parseExeHelp binfo (f, val) | "options-" `isPrefixOf` f =
md9ms's avatar
md9ms committed
265
266
267
          let compilers = [("ghc",GHC),("nhc",NHC),("hugs",Hugs)] -- FIXME
           in case lookup (drop 8 f) compilers of
                Just c -> do xs <- runP f (parseCommaList parseOption) val
268
                             return (setOptions c xs binfo)
md9ms's avatar
md9ms committed
269
                Nothing -> error $ "Unknown compiler (" ++ drop 8 f ++ ")"
270
        parseExeHelp binfo (field, val) = error $ "Unknown field :: " ++ field
md9ms's avatar
md9ms committed
271
272
273
274
275
        -- ...
        runP f p s = case parse p f s of
                       Left pe -> Left (Parsec pe)
                       Right a -> Right a

276
277
278
279
280
281
type Stanza = [(String,String)]

-- |Split a string into blank line-separated stanzas of
-- "Field: value" groups
splitStanzas :: String -> [Stanza]
splitStanzas = map merge . groupStanzas . filter validLine . lines
md9ms's avatar
md9ms committed
282
283
284
  where validLine s = case dropWhile isSpace s of
                        '-':'-':_ -> False      -- Comment
                        _         -> True
285
286
287
        groupStanzas [] = []
        groupStanzas xs = let (ys,zs) = break (all isSpace) xs
                           in ys : groupStanzas (dropWhile (all isSpace) zs)
md9ms's avatar
md9ms committed
288
289
290
291
292
293
294
295
        merge (x:(' ':s):ys) = case dropWhile isSpace s of
                                 "." -> merge ((x++"\n"):ys)
                                 s'  -> merge ((x++"\n"++s'):ys)
        merge (x:ys) = brk x : merge ys
        merge []     = []
        brk xs = case break (==':') xs of
                   (fld, ':':val) -> (map toLower fld, dropWhile isSpace val)
                   (fld, "")      -> error "FIXME"
ijones's avatar
ijones committed
296

297
-- |parse a module name
md9ms's avatar
md9ms committed
298
moduleName = many (alphaNum <|> oneOf "_'.") <?> "moduleName"
ijones's avatar
ijones committed
299

300
parseFilePath :: GenParser Char st FilePath
md9ms's avatar
md9ms committed
301
parseFilePath = parseReadS <|> (many1 (alphaNum <|> oneOf "-+/_."))
md9ms's avatar
md9ms committed
302
        <?> "parseFilePath"
303

md9ms's avatar
md9ms committed
304
305
306
307
308
309
310
parseReadS :: Read a => GenParser Char st a
parseReadS = do toks <- getInput
                case reads toks of
                  [(str,toks')] -> do setInput toks'
                                      return str
                  _             -> fail "Bad String"

311
parseDependency :: GenParser Char st Dependency
md9ms's avatar
md9ms committed
312
parseDependency = do name <- many1 (letter <|> digit <|> oneOf "-_")
313
                     skipMany parseWhite
314
                     ver <- parseVersionRange <|> return AnyVersion
315
316
                     skipMany parseWhite
                     return $ Dependency name ver
md9ms's avatar
md9ms committed
317
        <?> "parseDependency"
318

319
parseLicense :: GenParser Char st License
320
parseLicense = parseReadS
ijones's avatar
ijones committed
321

md9ms's avatar
md9ms committed
322
parseExtension :: GenParser Char st Extension
md9ms's avatar
md9ms committed
323
parseExtension = parseReadS
md9ms's avatar
md9ms committed
324

md9ms's avatar
md9ms committed
325
326
parseOption = many1 (letter <|> digit <|> oneOf "-+/\\._") -- FIXME

327
toStr c = c >>= \x -> return [x]
ijones's avatar
ijones committed
328
329

word :: GenParser Char st String
ijones's avatar
ijones committed
330
331
332
333
334
335
336
word = many1 letter <?> "word"

parseCommaList :: GenParser Char st a -- ^The parser for the stuff between commas
               -> GenParser Char st [a]
parseCommaList p
    = do words <- sepBy1 p separator
         return words
md9ms's avatar
md9ms committed
337
    where separator = spaces >> char ',' >> spaces
ijones's avatar
ijones committed
338
339

parseWhite = try parseSpaceNotNewline
340
            <|> (try (char '\n' >> parseWhite))
ijones's avatar
ijones committed
341
342
343
344
345
346

parseSpaceNotNewline = (satisfy isSpaceNotNewline <?> "space, not newline")
    where isSpaceNotNewline :: Char -> Bool
          isSpaceNotNewline '\n' = False
          isSpaceNotNewline n    = isSpace n

ijones's avatar
ijones committed
347
348
349
350
-- ------------------------------------------------------------
-- * Testing
-- ------------------------------------------------------------
#ifdef DEBUG
351
352
353
354
355
356
357
358
359
360
361
362
363
testPkgDesc = unlines [
        "-- Required",
        "Name: Cabal",
        "Version: 0.1.1.1.1-rain",
        "License: LGPL",
        "Copyright: Free Text String",
        "-- Optional - may be in source?",
        "Stability: Free Text String",
        "Build-Depends: haskell-src, HUnit>=1.0.0-rain",
        "Modules: Distribution.Package, Distribution.Version, Distribution.Simple.GHCPackageConfig",
        "C-Sources: not/even/rain.c, such/small/hands",
        "HS-Source-Dir: src",
        "Exposed-Modules: Distribution.Void, Foo.Bar",
md9ms's avatar
md9ms committed
364
        "Extensions: OverlappingInstances, TypeSynonymInstances",
365
366
        "Extra-Libs: libfoo, bar, bang",
        "Include-Dirs: your/slightest, look/will",
md9ms's avatar
md9ms committed
367
        "Includes: /easily/unclose, /me, \"funky, path\\\\name\"",
md9ms's avatar
md9ms committed
368
        "Options-ghc: -fTH",
369
370
371
372
        "Options-hugs: +TH",
        "",
        "-- Next is an executable",
        "Executable: somescript",
373
        "Main-is: SomeFile.hs",
374
375
376
        "Modules: Foo1, Util, Main",
        "HS-Source-Dir: scripts",
        "Extensions: OverlappingInstances"
377
        ]
ijones's avatar
ijones committed
378
379
380

testPkgDescAnswer = 
 PackageDescription {package = PackageIdentifier {pkgName = "Cabal",
ijones's avatar
ijones committed
381
                                                 pkgVersion = Version {versionBranch = [0,1,1,1,1],
md9ms's avatar
md9ms committed
382
                                                 versionTags = ["rain"]}},
ijones's avatar
ijones committed
383
                    license = LGPL,
ijones's avatar
ijones committed
384
                    copyright = "Free Text String",
ijones's avatar
ijones committed
385
                    maintainer = "",
ijones's avatar
ijones committed
386
                    stability = "Free Text String",
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402

                    library = Just $ BuildInfo {
                        buildDepends = [Dependency "haskell-src" AnyVersion,
                                        Dependency "HUnit"
                                         (UnionVersionRanges (ThisVersion (Version [1,0,0] ["rain"]))
                                          (LaterVersion (Version [1,0,0] ["rain"])))],

                        modules = ["Distribution.Package","Distribution.Version",
                                      "Distribution.Simple.GHCPackageConfig"],

                        cSources = ["not/even/rain.c", "such/small/hands"],
                        hsSourceDir = "src",
                        exposedModules = ["Distribution.Void", "Foo.Bar"],
                        extensions = [OverlappingInstances, TypeSynonymInstances],
                        extraLibs = ["libfoo", "bar", "bang"],
                        includeDirs = ["your/slightest", "look/will"],
md9ms's avatar
md9ms committed
403
                        includes = ["/easily/unclose", "/me", "funky, path\\name"],
404
405
                        options = [(Hugs,["+TH"]), (GHC,["-fTH"])] -- Note reversed order
                    },
406
407
                    executables = [Executable "somescript" "SomeFile.hs" (
                      emptyBuildInfo{
408
409
410
411
                        modules = ["Foo1","Util","Main"],
                        hsSourceDir = "scripts",
                        extensions = [OverlappingInstances]
                      })]
ijones's avatar
ijones committed
412
413
}

ijones's avatar
ijones committed
414
hunitTests :: [Test]
415
416
417
418
419
hunitTests = [TestLabel "newline before word (parsewhite)" $ TestCase $
              do assertRight "newline before word 1"
                  "foo" (parse (skipMany parseWhite>>char '\n'>>word) "" "   \n  \nfoo")
                 assertRight "newline before word 2"
                  "foo" (parse (skipMany parseWhite>>char '\n'>>word) "" "   \n \t    \n  \nfoo"),
ijones's avatar
ijones committed
420
421

              TestLabel "skip spaces not newlines" $ TestCase $
422
423
424
425
426
427
428
429
              do assertRight "spaces with newlines"
                  "foo" (parse (skipMany parseWhite>>word) "" "   \n  foo")
                 assertRight "spaces with newlines"
                  "foo" (parse (skipMany parseWhite>>word) "" "   \n \t\n   foo")
                 assertRight "no preceding spaces"
                  "foo" (parse (skipMany parseWhite>>word) "" "foo")
                 assertBool "newline before data without in-between spaces"
                  (isError (parse (skipMany parseWhite>>word) "" "   \n  \nfoo")),
ijones's avatar
ijones committed
430

md9ms's avatar
md9ms committed
431
432
433
434
435
436
--              TestLabel "basic fields" $ TestCase $
--              do let p1 = parse (do w1 <- parseField "Foo" False parseVersion
--                                    skipMany parseWhite
--                                    w2 <- parseField "Bar" True word
--                                    return (w1, w2)
--                                ) ""
md9ms's avatar
md9ms committed
437
--                     knownVal1 = (Version {versionBranch = [3,2], versionTags = ["one"]},"boo")
md9ms's avatar
md9ms committed
438
439
440
441
442
443
444
445
446
447
448
449
--                 assertRight "basic spaces 1"
--                   knownVal1 (p1 "Foo: 3.2-one\nBar: boo")
--                 assertRight "basic spaces 2"
--                   knownVal1 (p1 "Foo: 3.2-one \t   \nBar: boo")
--                 assertRight "basic spaces 3"
--                   knownVal1 (p1 "Foo : 3.2-one \t   \nBar:    boo  ")
--                 assertRight "basic spaces 3"
--                   knownVal1 (p1 "Foo:3.2-one \t   \nBar:    boo  ")
--                 assertRight "basic spaces with newline"
--                   knownVal1 (p1 "Foo:\n 3.2-one \t   \nBar:    boo  ")
--                 assertRight "basic spaces with newline"
--                   knownVal1 (p1 "Foo:\n 3.2-one \t \n  \nBar:    boo  "),
ijones's avatar
ijones committed
450

md9ms's avatar
md9ms committed
451
452
453
454
              TestLabel "license parsers" $ TestCase $
                 sequence_ [assertRight ("license " ++ show lVal) lVal
                                        (parse parseLicense "" (show lVal))
                           | lVal <- [GPL,LGPL,BSD3,BSD4]],
ijones's avatar
ijones committed
455
456
457
458

              TestLabel "Required fields" $ TestCase $
                 do assertRight "some fields"
                       emptyPackageDescription{package=(PackageIdentifier "foo"
md9ms's avatar
md9ms committed
459
                                                        (Version [0,0] ["asdf"]))}
ijones's avatar
ijones committed
460
461
462
463
                       (parseDescription "Name: foo\nVersion: 0.0-asdf")

                    assertRight "more fields foo"
                       emptyPackageDescription{package=(PackageIdentifier "foo"
md9ms's avatar
md9ms committed
464
                                                        (Version [0,0]["asdf"])),
ijones's avatar
ijones committed
465
466
467
468
469
                                               license=GPL}
                       (parseDescription "Name: foo\nVersion:0.0-asdf\nLicense: GPL")

                    assertRight "required fields for foo"
                       emptyPackageDescription{package=(PackageIdentifier "foo"
md9ms's avatar
md9ms committed
470
                                                        (Version [0,0]["asdf"])),
ijones's avatar
ijones committed
471
472
473
                                        license=GPL, copyright="2004 isaac jones"}
                       (parseDescription "Name: foo\nVersion:0.0-asdf\nCopyright: 2004 isaac jones\nLicense: GPL"),
                                          
474
             TestCase $ assertRight "no library" Nothing
475
                        (library `liftM` parseDescription "Name: foo\nVersion: 1\nLicense: GPL\nMaintainer: someone\n\nExecutable: script\nMain-is: SomeFile.hs\n"),
ijones's avatar
ijones committed
476
477
478
479

             TestLabel "Package description" $ TestCase $ 
                assertRight "entire package description" testPkgDescAnswer
                                                         (parseDescription testPkgDesc)
md9ms's avatar
md9ms committed
480

ijones's avatar
ijones committed
481
482
             ]

ijones's avatar
ijones committed
483

ijones's avatar
ijones committed
484
485
486
487
488
489
490
491
492
493
assertRight :: (Eq val) => String -> val -> (Either a val) -> Assertion
assertRight mes expected actual
    =  assertBool mes
           (case actual of
             (Right v) -> v == expected
             _         -> False)

isError (Left _) = True
isError _        = False

ijones's avatar
ijones committed
494
test = runTestTT (TestList hunitTests)
ijones's avatar
ijones committed
495
#endif