Main.curry 63 KB
Newer Older
Michael Hanus's avatar
Michael Hanus committed
1
2
3
4
5
6
--------------------------------------------------------------------------------
--- This is the main module of the Curry Package Manager.
--------------------------------------------------------------------------------

module CPM.Main where

Michael Hanus's avatar
Michael Hanus committed
7
import Char         ( toLower )
Michael Hanus's avatar
Michael Hanus committed
8
import Directory    ( doesFileExist, getAbsolutePath, doesDirectoryExist
Michael Hanus's avatar
Michael Hanus committed
9
                    , copyFile, createDirectory, createDirectoryIfMissing
Michael Hanus's avatar
Michael Hanus committed
10
11
                    , getCurrentDirectory, getDirectoryContents
                    , getModificationTime
Michael Hanus's avatar
Michael Hanus committed
12
                    , renameFile, removeFile, setCurrentDirectory )
Michael Hanus's avatar
Michael Hanus committed
13
import Distribution ( installDir, stripCurrySuffix, addCurrySubdir )
Michael Hanus's avatar
Michael Hanus committed
14
import Either
Michael Hanus's avatar
Michael Hanus committed
15
16
import FilePath     ( (</>), splitSearchPath, replaceExtension, takeExtension
                    , pathSeparator, isPathSeparator )
Michael Hanus's avatar
Michael Hanus committed
17
import IO           ( hFlush, stdout )
Michael Hanus's avatar
Michael Hanus committed
18
19
import List         ( groupBy, intercalate, isPrefixOf, isSuffixOf, nub, split
                    , splitOn )
Michael Hanus's avatar
Michael Hanus committed
20
import Sort         ( sortBy )
Michael Hanus's avatar
Michael Hanus committed
21
22
import System       ( getArgs, getEnviron, setEnviron, unsetEnviron, exitWith
                    , system )
Michael Hanus's avatar
Michael Hanus committed
23

Michael Hanus's avatar
Michael Hanus committed
24
import Boxes        ( table, render )
Michael Hanus's avatar
Michael Hanus committed
25
import OptParse
Michael Hanus's avatar
Michael Hanus committed
26
27
import Text.CSV     ( showCSV )

Michael Hanus's avatar
Michael Hanus committed
28
29
import CPM.ErrorLogger
import CPM.FileUtil ( fileInPath, joinSearchPath, safeReadFile, whenFileExists
Michael Hanus's avatar
Michael Hanus committed
30
                    , ifFileExists, inDirectory, removeDirectoryComplete
Michael Hanus's avatar
Michael Hanus committed
31
                    , copyDirectory, quote )
Michael Hanus's avatar
Michael Hanus committed
32
import CPM.Config   ( Config (..)
Michael Hanus's avatar
Michael Hanus committed
33
34
                    , readConfigurationWith, showCompilerVersion
                    , showConfiguration )
Michael Hanus's avatar
Michael Hanus committed
35
36
37
import CPM.PackageCache.Global ( GlobalCache, readGlobalCache, allPackages
                               , installFromZip, checkoutPackage
                               , uninstallPackage, packageInstalled )
Michael Hanus's avatar
Michael Hanus committed
38
import CPM.Package
Michael Hanus's avatar
Michael Hanus committed
39
40
import CPM.Package.Helpers ( cleanPackage, getLocalPackageSpec
                           , renderPackageInfo )
41
import CPM.Resolution ( isCompatibleToCompiler, showResult )
Michael Hanus's avatar
Michael Hanus committed
42
43
44
45
46
47
import CPM.Repository ( Repository, findVersion, listPackages
                      , findAllVersions, findLatestVersion
                      , useUpdateHelp, searchPackages, cleanRepositoryCache
                      , readPackageFromRepository )
import CPM.Repository.Update ( addPackageToRepository, updateRepository )
import CPM.Repository.Select
Michael Hanus's avatar
Michael Hanus committed
48
49
50
51
import CPM.PackageCache.Runtime ( dependencyPathsSeparate, writePackageConfig )
import CPM.PackageCopy
import CPM.Diff.API as APIDiff
import qualified CPM.Diff.Behavior as BDiff
Michael Hanus's avatar
Michael Hanus committed
52
import CPM.ConfigPackage (packagePath)
Michael Hanus's avatar
Michael Hanus committed
53
54
55
56
57
58

-- Banner of this tool:
cpmBanner :: String
cpmBanner = unlines [bannerLine,bannerText,bannerLine]
 where
 bannerText =
Michael Hanus's avatar
Michael Hanus committed
59
  "Curry Package Manager <curry-language.org/tools/cpm> (version of 19/06/2018)"
Michael Hanus's avatar
Michael Hanus committed
60
61
62
63
64
 bannerLine = take (length bannerText) (repeat '-')

main :: IO ()
main = do
  args <- getArgs
Michael Hanus's avatar
Michael Hanus committed
65
  parseResult <- return $ parse (unwords args) (optionParser args) "cypm"
Michael Hanus's avatar
Michael Hanus committed
66
67
68
  case parseResult of
    Left err -> do putStrLn cpmBanner
                   putStrLn err
Michael Hanus's avatar
Michael Hanus committed
69
                   --putStrLn "(use option -h for usage information)"
Michael Hanus's avatar
Michael Hanus committed
70
71
72
                   exitWith 1
    Right  r -> case applyParse r of
      Left err   -> do putStrLn cpmBanner
Michael Hanus's avatar
Michael Hanus committed
73
                       --printUsage "cypm" 80 (optionParser args)
Michael Hanus's avatar
Michael Hanus committed
74
75
76
77
78
79
                       putStrLn err
                       exitWith 1
      Right opts -> runWithArgs opts

runWithArgs :: Options -> IO ()
runWithArgs opts = do
Michael Hanus's avatar
Michael Hanus committed
80
  setLogLevel $ optLogLevel opts
Michael Hanus's avatar
Michael Hanus committed
81
  setWithShowTime (optWithTime opts)
Michael Hanus's avatar
Michael Hanus committed
82
  debugMessage "Reading CPM configuration..."
Michael Hanus's avatar
Michael Hanus committed
83
  config <- readConfigurationWith (optDefConfig opts) >>= \c ->
Michael Hanus's avatar
Michael Hanus committed
84
   case c of
Michael Hanus's avatar
Michael Hanus committed
85
    Left err -> do errorMessage $ "Error reading .cpmrc settings: " ++ err
Michael Hanus's avatar
Michael Hanus committed
86
87
                   exitWith 1
    Right c' -> return c'
Michael Hanus's avatar
Michael Hanus committed
88
  debugMessage ("Current configuration:\n" ++ showConfiguration config)
Michael Hanus's avatar
Michael Hanus committed
89
90
  (msgs, result) <- case optCommand opts of
    NoCommand   -> failIO "NoCommand"
Michael Hanus's avatar
Michael Hanus committed
91
    Config o    -> configCmd   o config
Michael Hanus's avatar
Michael Hanus committed
92
    Update o    -> updateCmd   o config
Michael Hanus's avatar
Michael Hanus committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
    Compiler o  -> compiler    o config
    Exec o      -> execCmd     o config
    Doc  o      -> docCmd      o config
    Test o      -> testCmd     o config
    Uninstall o -> uninstall   o config
    Deps o      -> depsCmd     o config
    PkgInfo   o -> infoCmd     o config
    Link o      -> linkCmd     o config
    Add  o      -> addCmd      o config
    New o       -> newPackage  o 
    List      o -> listCmd     o config
    Search    o -> searchCmd   o config
    Upgrade   o -> upgradeCmd  o config
    Diff      o -> diffCmd     o config
    Checkout  o -> checkoutCmd o config
    Install   o -> installCmd  o config
    Clean       -> cleanPackage config Info
Michael Hanus's avatar
Michael Hanus committed
110
111
112
113
114
115
116
117
118
119
  mapIO showLogEntry msgs
  let allOk =  all (levelGte Info) (map logLevelOf msgs) &&
               either (\le -> levelGte Info (logLevelOf le))
                      (const True)
                      result
  exitWith (if allOk then 0 else 1)

data Options = Options
  { optLogLevel  :: LogLevel
  , optDefConfig :: [(String,String)]
Michael Hanus's avatar
Michael Hanus committed
120
  , optWithTime  :: Bool
Michael Hanus's avatar
Michael Hanus committed
121
122
123
  , optCommand   :: Command }

data Command 
Michael Hanus's avatar
Michael Hanus committed
124
  = NoCommand
Michael Hanus's avatar
Michael Hanus committed
125
  | Config     ConfigOptions
Michael Hanus's avatar
Michael Hanus committed
126
  | Deps       DepsOptions
Michael Hanus's avatar
Michael Hanus committed
127
128
129
130
  | Checkout   CheckoutOptions
  | Install    InstallOptions
  | Uninstall  UninstallOptions
  | PkgInfo    InfoOptions
Michael Hanus's avatar
Michael Hanus committed
131
  | Compiler   ExecOptions
Michael Hanus's avatar
Michael Hanus committed
132
  | Update     UpdateOptions
Michael Hanus's avatar
Michael Hanus committed
133
134
135
136
  | List       ListOptions
  | Search     SearchOptions
  | Upgrade    UpgradeOptions
  | Link       LinkOptions
Michael Hanus's avatar
Michael Hanus committed
137
  | Add        AddOptions
Michael Hanus's avatar
Michael Hanus committed
138
  | Exec       ExecOptions
139
  | Doc        DocOptions
Michael Hanus's avatar
Michael Hanus committed
140
141
  | Test       TestOptions
  | Diff       DiffOptions
Michael Hanus's avatar
Michael Hanus committed
142
  | New        NewOptions
Michael Hanus's avatar
Michael Hanus committed
143
  | Clean
Michael Hanus's avatar
Michael Hanus committed
144

Michael Hanus's avatar
Michael Hanus committed
145
146
147
148
data ConfigOptions = ConfigOptions
  { configAll :: Bool  -- show also installed packages?
  }

Michael Hanus's avatar
Michael Hanus committed
149
150
151
152
data DepsOptions = DepsOptions
  { depsPath :: Bool  -- show CURRYPATH only?
  }

Michael Hanus's avatar
Michael Hanus committed
153
154
155
156
157
158
159
160
data CheckoutOptions = CheckoutOptions
  { coPackage    :: String
  , coVersion    :: Maybe Version
  , coPrerelease :: Bool }

data InstallOptions = InstallOptions
  { instTarget     :: Maybe String
  , instVersion    :: Maybe Version
Michael Hanus's avatar
Michael Hanus committed
161
  , instPrerelease :: Bool
Michael Hanus's avatar
Michael Hanus committed
162
163
  , instExecutable :: Bool
  , instExecOnly   :: Bool }
Michael Hanus's avatar
Michael Hanus committed
164
165
166
167
168
169
170
171

data UninstallOptions = UninstallOptions
  { uninstPackage :: Maybe String
  , uninstVersion :: Maybe Version }

data InfoOptions = InfoOptions
  { infoPackage :: Maybe String
  , infoVersion :: Maybe Version
Michael Hanus's avatar
Michael Hanus committed
172
173
174
  , infoAll     :: Bool
  , infoPlain   :: Bool  -- plain output, no bold/color
  }
Michael Hanus's avatar
Michael Hanus committed
175
176

data ListOptions = ListOptions
Michael Hanus's avatar
Michael Hanus committed
177
  { listVers :: Bool   -- list all versions of each package
Michael Hanus's avatar
Michael Hanus committed
178
179
  , listCSV  :: Bool   -- list in CSV format
  , listCat  :: Bool   -- list all categories
180
  }
Michael Hanus's avatar
Michael Hanus committed
181
182

data SearchOptions = SearchOptions
Michael Hanus's avatar
Michael Hanus committed
183
184
185
  { searchQuery  :: String -- the term to search for
  , searchModule :: Bool   -- search for some module?
  , searchExec   :: Bool   -- search for some executable?
Michael Hanus's avatar
Michael Hanus committed
186
  }
Michael Hanus's avatar
Michael Hanus committed
187
188
189
190
191
192
193

data UpgradeOptions = UpgradeOptions
  { upgrTarget :: Maybe String }

data LinkOptions = LinkOptions
  { lnkSource :: String }

Michael Hanus's avatar
Michael Hanus committed
194
data AddOptions = AddOptions
Michael Hanus's avatar
Michael Hanus committed
195
196
197
198
  { addPackage    :: Bool
  , addDependency :: Bool
  , addSource     :: String
  , forceAdd      :: Bool
Michael Hanus's avatar
Michael Hanus committed
199
200
  }

Michael Hanus's avatar
Michael Hanus committed
201
202
203
data NewOptions = NewOptions
  { projectName :: String }

Michael Hanus's avatar
Michael Hanus committed
204
205
206
207
data UpdateOptions = UpdateOptions
  { indexURLs :: [String]   -- the URLs of additional index repositories
  }

Michael Hanus's avatar
Michael Hanus committed
208
data ExecOptions = ExecOptions
Michael Hanus's avatar
Michael Hanus committed
209
  { exeCommand :: String   -- the command to be executed
Michael Hanus's avatar
Michael Hanus committed
210
211
  }

212
data DocOptions = DocOptions
Michael Hanus's avatar
Michael Hanus committed
213
214
215
216
217
218
219
220
221
  { docDir        :: Maybe String    -- documentation directory
  , docModules    :: Maybe [String]  -- modules to be documented
  , docPrograms   :: Bool            -- generate documentation for programs
  , docManual     :: Bool            -- generate manual (if specified)
  , docGenImports :: Bool            -- generate documentation for imported pkgs
                                     -- (otherwise, use their standard docs)
  , docPackageURL :: String          -- the URL prefix where all repository
                                     -- packages are documented
}
222

Michael Hanus's avatar
Michael Hanus committed
223
224
225
226
227
228
229
230
231
232
data TestOptions = TestOptions
  { testModules :: Maybe [String] }

data DiffOptions = DiffOptions
  { diffVersion  :: Maybe Version
  , diffModules  :: Maybe [String]
  , diffAPI      :: Bool
  , diffBehavior :: Bool
  , diffUseAna   :: Bool }

Michael Hanus's avatar
Michael Hanus committed
233
234
235
236
237
configOpts :: Options -> ConfigOptions
configOpts s = case optCommand s of
  Config opts -> opts
  _           -> ConfigOptions False

Michael Hanus's avatar
Michael Hanus committed
238
239
240
241
242
depsOpts :: Options -> DepsOptions
depsOpts s = case optCommand s of
  Deps opts -> opts
  _         -> DepsOptions False

Michael Hanus's avatar
Michael Hanus committed
243
244
245
246
247
248
249
250
checkoutOpts :: Options -> CheckoutOptions
checkoutOpts s = case optCommand s of
  Checkout opts -> opts
  _             -> CheckoutOptions "" Nothing False

installOpts :: Options -> InstallOptions
installOpts s = case optCommand s of
  Install opts -> opts
Michael Hanus's avatar
Michael Hanus committed
251
  _            -> InstallOptions Nothing Nothing False True False
Michael Hanus's avatar
Michael Hanus committed
252
253
254
255
256
257
258
259
260

uninstallOpts :: Options -> UninstallOptions
uninstallOpts s = case optCommand s of
  Uninstall opts -> opts
  _              -> UninstallOptions Nothing Nothing

infoOpts :: Options -> InfoOptions
infoOpts s = case optCommand s of
  PkgInfo opts -> opts
Michael Hanus's avatar
Michael Hanus committed
261
  _            -> InfoOptions Nothing Nothing False False
Michael Hanus's avatar
Michael Hanus committed
262
263
264
265

listOpts :: Options -> ListOptions
listOpts s = case optCommand s of
  List opts -> opts
266
  _         -> ListOptions False False False
Michael Hanus's avatar
Michael Hanus committed
267
268
269
270

searchOpts :: Options -> SearchOptions
searchOpts s = case optCommand s of
  Search opts -> opts
Michael Hanus's avatar
Michael Hanus committed
271
  _           -> SearchOptions "" False False
Michael Hanus's avatar
Michael Hanus committed
272
273
274
275
276
277
278
279
280
281
282

upgradeOpts :: Options -> UpgradeOptions
upgradeOpts s = case optCommand s of
  Upgrade opts -> opts
  _            -> UpgradeOptions Nothing

linkOpts :: Options -> LinkOptions
linkOpts s = case optCommand s of
  Link opts -> opts
  _         -> LinkOptions ""

Michael Hanus's avatar
Michael Hanus committed
283
284
285
addOpts :: Options -> AddOptions
addOpts s = case optCommand s of
  Add opts -> opts
Michael Hanus's avatar
Michael Hanus committed
286
  _        -> AddOptions False False "" False
Michael Hanus's avatar
Michael Hanus committed
287

Michael Hanus's avatar
Michael Hanus committed
288
289
290
291
292
newOpts :: Options -> NewOptions
newOpts s = case optCommand s of
  New opts -> opts
  _        -> NewOptions ""

Michael Hanus's avatar
Michael Hanus committed
293
294
295
296
297
updateOpts :: Options -> UpdateOptions
updateOpts s = case optCommand s of
  Update opts -> opts
  _           -> UpdateOptions []

Michael Hanus's avatar
Michael Hanus committed
298
299
300
execOpts :: Options -> ExecOptions
execOpts s = case optCommand s of
  Exec opts -> opts
Michael Hanus's avatar
Michael Hanus committed
301
  _         -> ExecOptions ""
Michael Hanus's avatar
Michael Hanus committed
302

303
304
305
docOpts :: Options -> DocOptions
docOpts s = case optCommand s of
  Doc opts -> opts
Michael Hanus's avatar
Michael Hanus committed
306
307
308
309
310
311
  _        -> DocOptions Nothing Nothing True True False defaultBaseDocURL

-- The default URL prefix where all repository packages are documented.
-- Can be overwritten with a doc command option.
defaultBaseDocURL :: String
defaultBaseDocURL = "https://www.informatik.uni-kiel.de/~curry/cpm/DOC"
312

Michael Hanus's avatar
Michael Hanus committed
313

Michael Hanus's avatar
Michael Hanus committed
314
315
316
317
318
319
320
321
322
323
324
testOpts :: Options -> TestOptions
testOpts s = case optCommand s of
  Test opts -> opts
  _         -> TestOptions Nothing

diffOpts :: Options -> DiffOptions
diffOpts s = case optCommand s of
  Diff opts -> opts
  _         -> DiffOptions Nothing Nothing True True True

readLogLevel :: String -> Either String LogLevel
Michael Hanus's avatar
Michael Hanus committed
325
326
327
readLogLevel s = case map toLower s of
  "debug" -> Right Debug
  "info"  -> Right Info
Michael Hanus's avatar
Michael Hanus committed
328
  "quiet" -> Right Quiet
Michael Hanus's avatar
Michael Hanus committed
329
  _       -> Left $ "Illegal verbosity value: " ++ s
Michael Hanus's avatar
Michael Hanus committed
330
331
332
333
334
335
336
337
338
339
340
341

readRcOption :: String -> Either String (String,String)
readRcOption s =
  let (option,value) = break (=='=') s
  in if null value then Left $ "Error in option definition: '=' missing"
                   else Right $ (option, tail value)

readVersion' :: String -> Either String Version
readVersion' s = case readVersion s of
  Nothing -> Left $ "'" ++ s ++ "' is not a valid version"
  Just  v -> Right v

Michael Hanus's avatar
Michael Hanus committed
342
343
applyEither :: [Options -> Either String Options] -> Options
            -> Either String Options
Michael Hanus's avatar
Michael Hanus committed
344
345
346
347
348
349
350
351
applyEither [] z = Right z
applyEither (f:fs) z = case f z of
  Left err -> Left err
  Right z' -> applyEither fs z'

applyParse :: [Options -> Either String Options] -> Either String Options
applyParse fs = applyEither fs defaultOpts
 where
Michael Hanus's avatar
Michael Hanus committed
352
  defaultOpts = Options Info [] False NoCommand
Michael Hanus's avatar
Michael Hanus committed
353
354
355
356
357
358

(>.>) :: Either String a -> (a -> b) -> Either String b
a >.> f = case a of 
  Left err -> Left err
  Right  v -> Right $ f v

Michael Hanus's avatar
Michael Hanus committed
359
360
optionParser :: [String] -> ParseSpec (Options -> Either String Options)
optionParser allargs = optParser 
Michael Hanus's avatar
Michael Hanus committed
361
  (   option (\s a -> readLogLevel s >.> \ll -> a { optLogLevel = ll })
Michael Hanus's avatar
Michael Hanus committed
362
363
364
365
       (  long "verbosity"
       <> short "v"
       <> metavar "LEVEL"
       <> help "Log level for the application. Valid values: info|debug|quiet" )
Michael Hanus's avatar
Michael Hanus committed
366
367
368
369
370
371
  <.> option (\s a -> readRcOption s >.> \kv ->
                      a { optDefConfig = optDefConfig a ++ [kv] })
        (  long "define"
        <> short "d"
        <> metavar "DEFINITION"
        <> help "Overwrite definition of cpmrc file with 'option=value'." )
Michael Hanus's avatar
Michael Hanus committed
372
373
374
375
  <.> flag (\a -> Right $ a { optWithTime = True })
        (  long "time"
        <> short "t"
        <> help "Show elapsed time with every log output" )
Michael Hanus's avatar
Michael Hanus committed
376
  <.> commands (metavar "COMMAND")
Michael Hanus's avatar
Michael Hanus committed
377
378
379
380
381
        (   command "config"
                    (help "Show current configuration of CPM")
                    (\a -> Right $ a { optCommand = Config (configOpts a) })
                    configArgs
        <|> command "checkout" (help "Checkout a package.") Right
Michael Hanus's avatar
Michael Hanus committed
382
                    (checkoutArgs Checkout)
Michael Hanus's avatar
Michael Hanus committed
383
        <|> command "install" (help "Install a package with its dependencies.")
Michael Hanus's avatar
Michael Hanus committed
384
                     (\a -> Right $ a { optCommand = Install (installOpts a) })
Michael Hanus's avatar
Michael Hanus committed
385
                     installArgs
Michael Hanus's avatar
Michael Hanus committed
386
        <|> command "uninstall" (help "Uninstall a package")
Michael Hanus's avatar
Michael Hanus committed
387
388
                 (\a -> Right $ a { optCommand = Uninstall (uninstallOpts a) })
                 uninstallArgs
Michael Hanus's avatar
Michael Hanus committed
389
        <|> command "deps" (help "Calculate dependencies")
Michael Hanus's avatar
Michael Hanus committed
390
391
                           (\a -> Right $ a { optCommand = Deps (depsOpts a) })
                           depsArgs
Michael Hanus's avatar
Michael Hanus committed
392
        <|> command "clean" (help "Clean the current package")
Michael Hanus's avatar
Michael Hanus committed
393
                            (\a -> Right $ a { optCommand = Clean }) []
Michael Hanus's avatar
Michael Hanus committed
394
        <|> command "new" (help "Create a new package") Right newArgs
Michael Hanus's avatar
Michael Hanus committed
395
396
397
398
        <|> command "update"
                    (help "Update the package index")
                    (\a -> Right $ a { optCommand = Update (updateOpts a) })
                    updateArgs
Michael Hanus's avatar
Michael Hanus committed
399
400
        <|> command "curry"
           (help "Load package spec and start Curry with correct dependencies.")
Michael Hanus's avatar
Michael Hanus committed
401
402
                 (\a -> Right $ a { optCommand = Compiler (execOpts a) })
                 curryArgs
Michael Hanus's avatar
Michael Hanus committed
403
404
405
406
        <|> command "exec"
                    (help "Execute a command with the CURRYPATH set")
                    (\a -> Right $ a { optCommand = Exec (execOpts a) })
                    execArgs
Michael Hanus's avatar
Michael Hanus committed
407
        <|> command "info" (help "Print package information")
Michael Hanus's avatar
Michael Hanus committed
408
409
                    (\a -> Right $ a { optCommand = PkgInfo (infoOpts a) })
                    infoArgs
410
411
412
413
        <|> command "doc"
           (help "Generation documentation for current package (with CurryDoc)")
                    (\a -> Right $ a { optCommand = Doc (docOpts a) })
                    docArgs
Michael Hanus's avatar
Michael Hanus committed
414
415
        <|> command "test" (help "Test the current package (with CurryCheck)")
                    (\a -> Right $ a { optCommand = Test (testOpts a) })
Michael Hanus's avatar
Michael Hanus committed
416
                    testArgs
Michael Hanus's avatar
Michael Hanus committed
417
418
419
        <|> command "diff"
                    (help "Diff the current package against another version")
                    (\a -> Right $ a { optCommand = Diff (diffOpts a) })
Michael Hanus's avatar
Michael Hanus committed
420
                    diffArgs
Michael Hanus's avatar
Michael Hanus committed
421
        <|> command "list" (help "List all packages of the repository")
Michael Hanus's avatar
Michael Hanus committed
422
423
                    (\a -> Right $ a { optCommand = List (listOpts a) })
                    listArgs
Michael Hanus's avatar
Michael Hanus committed
424
        <|> command "search" (help "Search the package repository") Right
Michael Hanus's avatar
Michael Hanus committed
425
                    searchArgs
Michael Hanus's avatar
Michael Hanus committed
426
427
        <|> command "upgrade" (help "Upgrade one or more packages")
                    (\a -> Right $ a { optCommand = Upgrade (upgradeOpts a) })
Michael Hanus's avatar
Michael Hanus committed
428
                    upgradeArgs
Michael Hanus's avatar
Michael Hanus committed
429
        <|> command "link" (help "Link a package to the local cache") Right
Michael Hanus's avatar
Michael Hanus committed
430
                    linkArgs
Michael Hanus's avatar
Michael Hanus committed
431
432
433
434
        <|> command "add"
              (help "Add a package (as dependency or to the local repository)")
              Right
              addArgs ) )
Michael Hanus's avatar
Michael Hanus committed
435
 where
Michael Hanus's avatar
Michael Hanus committed
436
437
438
439
440
441
442
443
  configArgs =
    flag (\a -> Right $ a { optCommand = Config (configOpts a)
                                                { configAll = True } })
         (  short "a"
         <> long "all"
         <> help "Show also names of installed packages"
         <> optional )

Michael Hanus's avatar
Michael Hanus committed
444
445
446
447
448
449
450
451
  depsArgs =
    flag (\a -> Right $ a { optCommand = Deps (depsOpts a)
                                              { depsPath = True } })
         (  short "p"
         <> long "path"
         <> help "Show value of CURRYPATH only"
         <> optional )

Michael Hanus's avatar
Michael Hanus committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
  checkoutArgs cmd =
        arg (\s a -> Right $ a { optCommand = cmd (checkoutOpts a)
                                                  { coPackage = s } })
          (  metavar "PACKAGE"
          <> help "The package name" )
    <.> arg (\s a -> readVersion' s >.> \v ->
                     a { optCommand = cmd (checkoutOpts a)
                                          { coVersion = Just v } })
          (  metavar "VERSION"
          <> help "The package version"
          <> optional)
    <.> flag (\a -> Right $ a { optCommand = cmd (checkoutOpts a)
                                                 { coPrerelease = True } })
          (  short "p"
          <> long "pre"
          <> help "Try pre-release versions when searching for newest version.")

  installArgs =
        arg (\s a -> Right $ a { optCommand = Install (installOpts a)
                                                      { instTarget = Just s } })
          (  metavar "TARGET"
          <> help "A package name or the path to a file"
          <> optional)
    <.> arg (\s a -> readVersion' s >.> \v ->
             a { optCommand = Install (installOpts a) { instVersion = Just v } })
          (  metavar "VERSION"
          <> help "The package version"
          <> optional)
    <.> flag (\a -> Right $ a { optCommand = Install (installOpts a)
                                               { instPrerelease = True } })
          (  short "p"
          <> long "pre"
          <> help "Try pre-release versions when searching for newest version.")
    <.> flag (\a -> Right $ a { optCommand = Install (installOpts a)
                                               { instExecutable = False } })
          (  short "n"
          <> long "noexec"
          <> help "Do not install executable.")
Michael Hanus's avatar
Michael Hanus committed
490
491
492
493
494
    <.> flag (\a -> Right $ a { optCommand = Install (installOpts a)
                                               { instExecOnly = True } })
          (  short "x"
          <> long "exec"
          <> help "Install executable only (do not re-install dependencies).")
Michael Hanus's avatar
Michael Hanus committed
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515

  uninstallArgs =
        arg (\s a -> Right $ a { optCommand =
             Uninstall (uninstallOpts a) { uninstPackage = Just s } })
          (  metavar "PACKAGE"
          <> help "The package to be uninstalled"
          <> optional)
    <.> arg (\s a -> readVersion' s >.> \v ->
                     a { optCommand = Uninstall (uninstallOpts a)
                                                { uninstVersion = Just v } })
          (  metavar "VERSION"
          <> help "The version to be uninstalled"
          <> optional)

  newArgs =
   arg (\s a -> Right $ a { optCommand = New (newOpts a)
                                             { projectName = s } })
       (  metavar "PROJECT"
       <> help "The name of the new project" )

  curryArgs =
Michael Hanus's avatar
Michael Hanus committed
516
517
    rest (\_ a -> Right $ a { optCommand = Compiler (execOpts a)
                                            { exeCommand = unwords remargs } })
Michael Hanus's avatar
Michael Hanus committed
518
519
520
         (  metavar "ARGS"
         <> help "The options to pass to the compiler"
         <> optional )
Michael Hanus's avatar
Michael Hanus committed
521
522
    where
     remargs = tail (snd (break (=="curry") allargs))
Michael Hanus's avatar
Michael Hanus committed
523

Michael Hanus's avatar
Michael Hanus committed
524
525
526
527
528
529
530
531
532
  updateArgs =
    option (\s a -> let opts = updateOpts a
                    in Right $ a { optCommand = Update opts
                                          { indexURLs = s : indexURLs opts } })
         (  short "u"
         <> long "url"
         <> metavar "URL"
         <> help "URL of the central package index" )

Michael Hanus's avatar
Michael Hanus committed
533
  execArgs =
Michael Hanus's avatar
Michael Hanus committed
534
535
    rest (\_ a -> Right $ a { optCommand = Exec (execOpts a)
                                            { exeCommand = unwords remargs } })
Michael Hanus's avatar
Michael Hanus committed
536
         (  metavar "CMD"
Michael Hanus's avatar
Michael Hanus committed
537
         <> help "The command to be executed."
Michael Hanus's avatar
Michael Hanus committed
538
         <> optional )
Michael Hanus's avatar
Michael Hanus committed
539
540
    where
     remargs = tail (snd (break (=="exec") allargs))
Michael Hanus's avatar
Michael Hanus committed
541
542
543
544
545

  infoArgs =
        arg (\s a -> Right $ a { optCommand = PkgInfo (infoOpts a)
                                                { infoPackage = Just s } })
          (  metavar "PACKAGE"
Michael Hanus's avatar
Michael Hanus committed
546
          <> help ("The package name. If no name is specified, CPM tries " ++
Michael Hanus's avatar
Michael Hanus committed
547
548
549
550
551
552
553
                   "to read a package specification in the current directory.")
          <> optional) 
    <.> arg (\s a -> readVersion' s >.> \v -> a
                                 { optCommand = PkgInfo (infoOpts a)
                                                  { infoVersion = Just v } })
          (  metavar "VERSION"
          <> help ("The package version. If no version is specified, " ++
Michael Hanus's avatar
Michael Hanus committed
554
                   "CPM uses the latest version of the specified package.")
Michael Hanus's avatar
Michael Hanus committed
555
556
557
558
559
          <> optional )
    <.> flag (\a -> Right $ a { optCommand = PkgInfo (infoOpts a)
                                               { infoAll = True } })
          (  short "a"
          <> long "all"
Michael Hanus's avatar
Michael Hanus committed
560
561
562
563
564
565
          <> help "Show all infos" )
    <.> flag (\a -> Right $ a { optCommand = PkgInfo (infoOpts a)
                                               { infoPlain = True } })
          (  short "p"
          <> long "plain"
          <> help "Plain output (no control characters for bold or colors)"
Michael Hanus's avatar
Michael Hanus committed
566
567
          <> optional )

568
569
  docArgs =
    option (\s a -> Right $ a { optCommand =
Michael Hanus's avatar
Michael Hanus committed
570
                                  Doc (docOpts a) { docDir = Just s } })
571
572
573
574
575
576
577
578
579
580
581
582
          (  long "docdir"
          <> short "d"
          <> help "The documentation directory (default: 'cdoc')"
          <> optional )
    <.>
    option (\s a -> Right $ a { optCommand = Doc (docOpts a)
                                      { docModules = Just $ splitOn "," s } })
          (  long "modules"
          <> short "m"
          <> help ("The modules to be documented, " ++
                   "separate multiple modules by comma")
          <> optional )
Michael Hanus's avatar
Michael Hanus committed
583
584
585
586
587
588
589
590
591
592
593
594
    <.> flag (\a -> Right $ a { optCommand = Doc (docOpts a)
                                               { docManual = False } })
          (  short "p"
          <> long "programs"
          <> help "Generate only program documentation (with CurryDoc)"
          <> optional )
    <.> flag (\a -> Right $ a { optCommand = Doc (docOpts a)
                                               { docPrograms = False } })
          (  short "t"
          <> long "text"
          <> help "Generate only manual (according to package specification)"
          <> optional )
Michael Hanus's avatar
Michael Hanus committed
595
596
597
598
599
600
601
602
603
604
605
606
607
    <.> flag (\a -> Right $ a { optCommand = Doc (docOpts a)
                                               { docGenImports = True } })
          (  short "f"
          <> long "full"
          <> help "Generate full program documentation (i.e., also imported packages)"
          <> optional )
    <.> option (\s a -> Right $ a { optCommand =
                                      Doc (docOpts a) { docPackageURL = s } })
          (  long "url"
          <> short "u"
          <> help ("The URL prefix where all repository packages are " ++
                   "documented. Default: " ++ defaultBaseDocURL)
          <> optional )
608

Michael Hanus's avatar
Michael Hanus committed
609
610
611
612
613
614
615
616
617
618
619
620
621
  testArgs =
    option (\s a -> Right $ a { optCommand = Test (testOpts a)
                                      { testModules = Just $ splitOn "," s } })
          (  long "modules"
          <> short "m"
          <> help "The modules to be tested, separate multiple modules by comma"
          <> optional )

  diffArgs =
       arg (\s a -> readVersion' s >.> \v ->
                 a { optCommand = Diff (diffOpts a) { diffVersion = Just v } })
           (  metavar "VERSION"
           <> help ("The other package version. If no version is specified, " ++
Michael Hanus's avatar
Michael Hanus committed
622
                    "CPM diffs against the latest repository version.")
Michael Hanus's avatar
Michael Hanus committed
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
           <> optional )
   <.> option (\s a -> Right $ a { optCommand = Diff (diffOpts a)
                                     { diffModules = Just $ splitOn "," s } })
         (  long "modules"
         <> short "m"
         <> help "The modules to compare, separate multiple modules by comma"
         <> optional )
   <.> flag (\a -> Right $ a { optCommand = Diff (diffOpts a)
                          { diffAPI = True, diffBehavior = False } })
         (  long "api-only"
         <> short "a"
         <> help "Diff only the API")
   <.> flag (\a -> Right $ a { optCommand = Diff (diffOpts a)
                          { diffAPI = False, diffBehavior = True } })
         (  long "behavior-only"
         <> short "b"
         <> help "Diff only the behavior")
   <.> flag (\a -> Right $ a { optCommand = Diff (diffOpts a)
                                            { diffUseAna = False } })
         (  long "unsafe"
         <> short "u"
         <> help
         "Do not use automatic termination analysis for safe behavior checking")

  listArgs =
Michael Hanus's avatar
Michael Hanus committed
648
        flag (\a -> Right $ a { optCommand =
Michael Hanus's avatar
Michael Hanus committed
649
650
651
                                  List (listOpts a) { listVers = True } })
          (  short "v"
          <> long "versions"
Michael Hanus's avatar
Michael Hanus committed
652
          <> help "Show all versions" ) 
Michael Hanus's avatar
Michael Hanus committed
653
654
    <.> flag (\a -> Right $ a { optCommand =
                                  List (listOpts a) { listCSV = True } })
Michael Hanus's avatar
Michael Hanus committed
655
656
657
          (  short "t"
          <> long "csv"
          <> help "Show in CSV table format" )
Michael Hanus's avatar
Michael Hanus committed
658
659
    <.> flag (\a -> Right $ a { optCommand =
                                  List (listOpts a) { listCat = True } })
Michael Hanus's avatar
Michael Hanus committed
660
661
662
663
664
          (  short "c"
          <> long "category"
          <> help "Show all categories" )

  searchArgs =
Michael Hanus's avatar
Michael Hanus committed
665
666
667
668
        flag (\a -> Right $ a { optCommand = Search (searchOpts a)
                                               { searchModule = True } })
             (  short "m"
             <> long "module"
Michael Hanus's avatar
Michael Hanus committed
669
670
671
672
673
674
             <> help "Search for an exported module" )
    <.> flag (\a -> Right $ a { optCommand = Search (searchOpts a)
                                               { searchExec = True } })
             (  short "x"
             <> long "exec"
             <> help "Search for the name of an executable" )
Michael Hanus's avatar
Michael Hanus committed
675
676
677
678
    <.> arg (\s a -> Right $ a { optCommand = Search (searchOpts a)
                                                { searchQuery = s } }) 
            (  metavar "QUERY"
            <> help "The search term" )
Michael Hanus's avatar
Michael Hanus committed
679
680
681
682
683
684
685
686
687
688
689
690

  upgradeArgs =
    arg (\s a -> Right $ a { optCommand = Upgrade (upgradeOpts a)
                                            { upgrTarget = Just s } })
        (  metavar "PACKAGE"
        <> help "The package to upgrade" 
        <> optional )

  linkArgs =
    arg (\s a -> Right $ a { optCommand = Link (linkOpts a) { lnkSource = s } })
        (  metavar "SOURCE"
        <> help "The directory to link" )
Michael Hanus's avatar
Michael Hanus committed
691

Michael Hanus's avatar
Michael Hanus committed
692
693
  addArgs =
       flag (\a -> Right $ a { optCommand =
Michael Hanus's avatar
Michael Hanus committed
694
695
696
697
698
699
700
701
702
703
                                 Add (addOpts a) { addPackage = True } })
            (  short "p"
            <> long "package"
            <> help "Add a local package to the local repository" )
   <.> flag (\a -> Right $ a { optCommand =
                                 Add (addOpts a) { addDependency = True } })
            (  short "d"
            <> long "dependency"
            <> help "Add a dependency to the current package" )
   <.> flag (\a -> Right $ a { optCommand =
Michael Hanus's avatar
Michael Hanus committed
704
705
706
707
708
709
                                 Add (addOpts a) { forceAdd = True } })
            (  short "f"
            <> long "force"
            <> help "Force, i.e., overwrite existing package" )
   <.> arg (\s a -> Right $ a { optCommand =
                                  Add (addOpts a) { addSource = s } })
Michael Hanus's avatar
Michael Hanus committed
710
711
           (  metavar "PACKAGE"
           <> help "The package directory or name to be added" )
Michael Hanus's avatar
Michael Hanus committed
712

Michael Hanus's avatar
Michael Hanus committed
713
-- Check if operating system executables we depend on are present on the
Michael Hanus's avatar
Michael Hanus committed
714
715
716
717
718
719
720
-- current system. Since this takes some time, it is only checked with
-- the `update` command.
checkRequiredExecutables :: IO ()
checkRequiredExecutables = do
  debugMessage "Checking whether all required executables can be found..."
  missingExecutables <- checkExecutables listOfExecutables
  unless (null missingExecutables) $ do
Michael Hanus's avatar
Michael Hanus committed
721
722
723
724
    errorMessage $ "The following programs could not be found on the PATH " ++
                   "(they are required for CPM to work):\n" ++
                   intercalate ", " missingExecutables
    exitWith 1
Michael Hanus's avatar
Michael Hanus committed
725
  debugMessage "All required executables found."
Michael Hanus's avatar
Michael Hanus committed
726
727
728
729
730
 where
  listOfExecutables = 
    [ "curl"  
    , "git"   
    , "unzip" 
Michael Hanus's avatar
Michael Hanus committed
731
    , "tar"
Michael Hanus's avatar
Michael Hanus committed
732
733
734
735
736
    , "cp"
    , "rm"
    , "ln"
    , "readlink" ]

Michael Hanus's avatar
Michael Hanus committed
737
738
739
740
741
checkExecutables :: [String] -> IO [String]
checkExecutables executables = do
  present <- mapIO fileInPath executables
  return $ map fst $ filter (not . snd) (zip executables present)

Michael Hanus's avatar
Michael Hanus committed
742
743
744
745
746
------------------------------------------------------------------------------
-- `config` command: show current CPM configuration
configCmd :: ConfigOptions -> Config -> IO (ErrorLogger ())
configCmd opts cfg = do
  if configAll opts
Michael Hanus's avatar
Michael Hanus committed
747
748
    then getBaseRepository cfg >>= \repo ->
         readGlobalCache cfg repo |>= \gc ->
Michael Hanus's avatar
Michael Hanus committed
749
750
751
752
753
754
755
         putStrLn configS >>
         putStrLn "Installed packages:\n" >>
         putStrLn (unwords (map packageId (allPackages gc))) >> succeedIO ()
    else putStrLn configS >> succeedIO ()
 where
  configS = unlines
             [cpmBanner, "Current configuration:", "", showConfiguration cfg]
Michael Hanus's avatar
Michael Hanus committed
756

Michael Hanus's avatar
Michael Hanus committed
757
758
------------------------------------------------------------------------------
-- `update` command:
Michael Hanus's avatar
Michael Hanus committed
759
760
761
762
763
764
765
updateCmd :: UpdateOptions -> Config -> IO (ErrorLogger ())
updateCmd opts cfg = do
  let cfg' = if null (indexURLs opts)
               then cfg
               else cfg { packageIndexURL = head (indexURLs opts) }
                    -- TODO: allow merging from several package indices
  checkRequiredExecutables >> updateRepository cfg'
Michael Hanus's avatar
Michael Hanus committed
766
767
768
769
770
771

------------------------------------------------------------------------------
-- `deps` command:
depsCmd :: DepsOptions -> Config -> IO (ErrorLogger ())
depsCmd opts cfg =
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
772
773
774
  loadPackageSpec specDir |>= \pkg ->
  checkCompiler cfg pkg >>
  if depsPath opts -- show CURRYPATH only?
Michael Hanus's avatar
Michael Hanus committed
775
776
777
    then getCurryLoadPath cfg specDir |>= \loadpath ->
         putStrLn loadpath >> succeedIO ()
    else resolveDependencies cfg specDir |>= \result ->
Michael Hanus's avatar
Michael Hanus committed
778
         putStrLn (showResult result) >> succeedIO ()
Michael Hanus's avatar
Michael Hanus committed
779

Michael Hanus's avatar
Michael Hanus committed
780
781
------------------------------------------------------------------------------
-- `info` command:
Michael Hanus's avatar
Michael Hanus committed
782
783
784
785
786
787
788
789
790
791
infoCmd :: InfoOptions -> Config -> IO (ErrorLogger ())
infoCmd (InfoOptions Nothing (Just _) _ _) _ =
  failIO "Must specify package name"
infoCmd (InfoOptions Nothing Nothing allinfos plain) cfg =
  getLocalPackageSpec cfg "." |>= \specDir ->
  loadPackageSpec specDir |>= \p -> 
  printInfo cfg allinfos plain p
infoCmd (InfoOptions (Just pkgname) Nothing allinfos plain) cfg =
  getAllPackageVersions cfg pkgname False >>= \pkgs ->
  case pkgs of
Michael Hanus's avatar
Michael Hanus committed
792
793
    [] -> packageNotFoundFailure pkgname
    ps -> case filter (isCompatibleToCompiler cfg) ps of
Michael Hanus's avatar
Michael Hanus committed
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
           [] -> let lvers = showVersion (version (head ps))
                 in compatPackageNotFoundFailure cfg pkgname
                      ("Use 'info " ++ pkgname ++ " " ++ lvers ++
                       "' to print info about the latest version.")
           (rp:_) -> readPackageFromRepository cfg rp |>= \p ->
                     printInfo cfg allinfos plain p
infoCmd (InfoOptions (Just pkgname) (Just v) allinfos plain) cfg =
  getPackageVersion cfg pkgname v >>= \mbpkg ->
  case mbpkg of
    Nothing -> packageNotFoundFailure $ pkgname ++ "-" ++ showVersion v
    Just rp -> readPackageFromRepository cfg rp |>=  \p ->
               printInfo cfg allinfos plain p

printInfo :: Config -> Bool -> Bool -> Package -> IO (ErrorLogger ())
printInfo cfg allinfos plain pkg =
  packageInstalled cfg pkg >>= \isinstalled ->
  putStrLn (renderPackageInfo allinfos plain isinstalled pkg) >> succeedIO ()
Michael Hanus's avatar
Michael Hanus committed
811
812


Michael Hanus's avatar
Michael Hanus committed
813
814
------------------------------------------------------------------------------
-- `checkout` command:
Michael Hanus's avatar
Michael Hanus committed
815
816
817
checkoutCmd :: CheckoutOptions -> Config -> IO (ErrorLogger ())
checkoutCmd (CheckoutOptions pkgname Nothing pre) cfg =
 getRepoForPackages cfg [pkgname] >>= \repo ->
Michael Hanus's avatar
Michael Hanus committed
818
819
820
 case findAllVersions repo pkgname pre of
  [] -> packageNotFoundFailure pkgname
  ps -> case filter (isCompatibleToCompiler cfg) ps of
Michael Hanus's avatar
Michael Hanus committed
821
822
823
824
825
826
827
828
829
830
831
832
833
    []    -> compatPackageNotFoundFailure cfg pkgname useUpdateHelp
    (p:_) -> acquireAndInstallPackageWithDependencies cfg repo p |>
             checkoutPackage cfg p
checkoutCmd (CheckoutOptions pkgname (Just ver) _) cfg =
 getRepoForPackages cfg [pkgname] >>= \repo ->
 case findVersion repo pkgname ver of
  Nothing -> packageNotFoundFailure $ pkgname ++ "-" ++ showVersion ver
  Just  p -> acquireAndInstallPackageWithDependencies cfg repo p |>
             checkoutPackage cfg p

installCmd :: InstallOptions -> Config -> IO (ErrorLogger ())
installCmd (InstallOptions Nothing Nothing _ instexec False) cfg =
  getLocalPackageSpec cfg "." |>= \pkgdir ->
Michael Hanus's avatar
Michael Hanus committed
834
  cleanCurryPathCache pkgdir |>
Michael Hanus's avatar
Michael Hanus committed
835
836
837
838
839
  installLocalDependencies cfg pkgdir |>= \ (pkg,_) ->
  saveBaseVersionToCache cfg pkgdir >>
  getCurryLoadPath cfg pkgdir |>= \currypath ->
  writePackageConfig cfg pkgdir pkg currypath |>
  if instexec then installExecutable cfg pkg else succeedIO ()
Michael Hanus's avatar
Michael Hanus committed
840
-- Install executable only:
Michael Hanus's avatar
Michael Hanus committed
841
842
installCmd (InstallOptions Nothing Nothing _ _ True) cfg =
  getLocalPackageSpec cfg "." |>= \pkgdir ->
Michael Hanus's avatar
Michael Hanus committed
843
  loadPackageSpec pkgdir |>= \pkg ->
Michael Hanus's avatar
Michael Hanus committed
844
845
  installExecutable cfg pkg
installCmd (InstallOptions (Just pkg) vers pre _ _) cfg = do
Michael Hanus's avatar
Michael Hanus committed
846
847
848
  fileExists <- doesFileExist pkg
  if fileExists
    then installFromZip cfg pkg
Michael Hanus's avatar
Michael Hanus committed
849
850
    else installapp (CheckoutOptions pkg vers pre) cfg
installCmd (InstallOptions Nothing (Just _) _ _ _) _ =
Michael Hanus's avatar
Michael Hanus committed
851
852
  failIO "Must specify package name"

Michael Hanus's avatar
Michael Hanus committed
853
--- Installs the application (i.e., binary) provided by a package.
Michael Hanus's avatar
Michael Hanus committed
854
855
--- This is done by checking out the package into CPM's application packages
--- cache (default: $HOME/.cpm/app_packages, see APP_PACKAGE_PATH
856
857
--- in .cpmrc configuration file) and then install this package.
---
Michael Hanus's avatar
Michael Hanus committed
858
--- Internal note: the installed package should not be cleaned or removed
859
860
--- after the installation since its execution might refer (via the
--- config module) to some data stored in the package.
Michael Hanus's avatar
Michael Hanus committed
861
862
installapp :: CheckoutOptions -> Config -> IO (ErrorLogger ())
installapp opts cfg = do
Michael Hanus's avatar
Michael Hanus committed
863
864
865
  let apppkgdir = appPackageDir cfg
      copkgdir  = apppkgdir </> coPackage opts
  curdir <- getCurrentDirectory
Michael Hanus's avatar
Michael Hanus committed
866
  removeDirectoryComplete copkgdir
Michael Hanus's avatar
Michael Hanus committed
867
868
  debugMessage ("Change into directory " ++ apppkgdir)
  inDirectory apppkgdir
Michael Hanus's avatar
Michael Hanus committed
869
    ( checkoutCmd opts cfg |>
Michael Hanus's avatar
Michael Hanus committed
870
871
872
873
874
875
876
      log Debug ("Change into directory " ++ copkgdir) |>
      (setCurrentDirectory copkgdir >> succeedIO ()) |>
      loadPackageSpec "." |>= \pkg ->
      maybe (setCurrentDirectory curdir >>
             removeDirectoryComplete copkgdir >>
             failIO ("Package '" ++ name pkg ++
                     "' does not contain an executable, nothing installed."))
Michael Hanus's avatar
Michael Hanus committed
877
878
            (\_ -> installCmd (InstallOptions Nothing Nothing False True False)
                              cfg)
Michael Hanus's avatar
Michael Hanus committed
879
880
            (executableSpec pkg)
    )
Michael Hanus's avatar
Michael Hanus committed
881

882
883
884
885
--- Checks the compiler compatibility.
checkCompiler :: Config -> Package -> IO ()
checkCompiler cfg pkg =
  unless (isCompatibleToCompiler cfg pkg)
Michael Hanus's avatar
Michael Hanus committed
886
887
    (error $ "Current compiler '" ++ showCompilerVersion cfg ++
             "' incompatible to package specification!")
888

Michael Hanus's avatar
Michael Hanus committed
889
890
--- Installs the executable specified in the package in the
--- bin directory of CPM (compare .cpmrc).
Michael Hanus's avatar
Michael Hanus committed
891
892
installExecutable :: Config -> Package -> IO (ErrorLogger ())
installExecutable cfg pkg =
893
  checkCompiler cfg pkg >>
Michael Hanus's avatar
Michael Hanus committed
894
  maybe (succeedIO ())
Michael Hanus's avatar
Michael Hanus committed
895
        (\ (PackageExecutable name mainmod eopts) ->
Michael Hanus's avatar
Michael Hanus committed
896
897
898
           getLogLevel >>= \lvl ->
           getEnviron "PATH" >>= \path ->
           log Info ("Compiling main module: " ++ mainmod) |>
Michael Hanus's avatar
Michael Hanus committed
899
900
901
902
903
           let (cmpname,_,_) = compilerVersion cfg
               cmd = unwords $
                       [":set", if levelGte Debug lvl then "v1" else "v0"
                       , maybe "" id (lookup cmpname eopts)
                       , ":load", mainmod, ":save", ":quit"]
Michael Hanus's avatar
Michael Hanus committed
904
905
               bindir     = binInstallDir cfg
               binexec    = bindir </> name
Michael Hanus's avatar
Michael Hanus committed
906
           in compiler (ExecOptions cmd) cfg |>
Michael Hanus's avatar
Michael Hanus committed
907
908
909
              log Info ("Installing executable '" ++ name ++ "' into '" ++
                        bindir ++ "'") |>
              (whenFileExists binexec (backupExistingBin binexec) >>
Michael Hanus's avatar
Michael Hanus committed
910
               -- renaming might not work across file systems, hence we move:
Michael Hanus's avatar
Michael Hanus committed
911
               showExecCmd (unwords ["mv", mainmod, binexec]) >>
Michael Hanus's avatar
Michael Hanus committed
912
913
914
915
916
               checkPath path bindir))
        (executableSpec pkg)
 where
  backupExistingBin binexec = do
    let binexecbak = binexec ++ ".bak"
Michael Hanus's avatar
Michael Hanus committed
917
    showExecCmd $ "rm -f " ++ binexecbak
Michael Hanus's avatar
Michael Hanus committed
918
919
920
921
922
923
924
925
926
927
    renameFile binexec binexecbak
    infoMessage $ "Existing executable '" ++ binexec ++ "' saved to '" ++
                  binexecbak ++ "'."

  checkPath path bindir =
    if bindir `elem` splitSearchPath path
      then succeedIO ()
      else log Info $ "It is recommended to add '" ++bindir++ "' to your path!"


Michael Hanus's avatar
Michael Hanus committed
928
929
930
uninstall :: UninstallOptions -> Config -> IO (ErrorLogger ())
uninstall (UninstallOptions (Just pkgname) (Just ver)) cfg =
  uninstallPackage cfg pkgname ver
Michael Hanus's avatar
Michael Hanus committed
931
--- uninstalls an application (i.e., binary) provided by a package:
Michael Hanus's avatar
Michael Hanus committed
932
uninstall (UninstallOptions (Just pkgname) Nothing) cfg = do
Michael Hanus's avatar
Michael Hanus committed
933
934
935
936
937
938
939
940
  let copkgdir  = appPackageDir cfg </> pkgname
  codirexists <- doesDirectoryExist copkgdir
  if codirexists
    then loadPackageSpec copkgdir |>= uninstallPackageExecutable cfg |>
         removeDirectoryComplete copkgdir >>
         log Info ("Package '" ++ pkgname ++
                   "' uninstalled from application package cache.")
    else failIO $ "Package '" ++ pkgname ++ "' is not installed."
Michael Hanus's avatar
Michael Hanus committed
941
uninstall (UninstallOptions Nothing (Just _)) _ =
Michael Hanus's avatar
Michael Hanus committed
942
  log Error "Please provide a package and version number!"
Michael Hanus's avatar
Michael Hanus committed
943
944
uninstall (UninstallOptions Nothing Nothing) cfg =
  getLocalPackageSpec cfg "." |>= \pkgdir ->
Michael Hanus's avatar
Michael Hanus committed
945
946
947
948
  loadPackageSpec pkgdir |>= uninstallPackageExecutable cfg

uninstallPackageExecutable :: Config -> Package -> IO (ErrorLogger ())
uninstallPackageExecutable cfg pkg =
Michael Hanus's avatar
Michael Hanus committed
949
  maybe (succeedIO ())
Michael Hanus's avatar
Michael Hanus committed
950
        (\ (PackageExecutable name _ _) ->
Michael Hanus's avatar
Michael Hanus committed
951
952
953
954
955
956
957
958
959
           let binexec = binInstallDir cfg </> name
           in ifFileExists binexec
                (removeFile binexec >>
                 log Info ("Executable '" ++ binexec ++ "' removed"))
                (log Info $ "Executable '" ++ binexec ++ "' not installed"))
        (executableSpec pkg)

tryFindVersion :: String -> Version -> Repository -> IO (ErrorLogger Package)
tryFindVersion pkg ver repo = case findVersion repo pkg ver of
Michael Hanus's avatar
Michael Hanus committed
960
  Nothing -> packageNotFoundFailure $ pkg ++ "-" ++ showVersion ver
Michael Hanus's avatar
Michael Hanus committed
961
962
  Just  p -> succeedIO $ p

Michael Hanus's avatar
Michael Hanus committed
963
964
--- Lists all (compiler-compatible if `lall` is false) packages
--- in the given repository.
Michael Hanus's avatar
Michael Hanus committed
965
966
967
968
969
970
971
listCmd :: ListOptions -> Config -> IO (ErrorLogger ())
listCmd (ListOptions lv csv cat) cfg = do
  repo <- if cat then getRepositoryWithNameVersionCategory cfg
                 else getRepositoryWithNameVersionSynopsis cfg
  let listresult = if cat then renderCats (catgroups repo)
                          else renderPkgs (allpkgs repo)
  putStr listresult >> succeedIO ()
Michael Hanus's avatar
Michael Hanus committed
972
 where
973
  -- all packages (and versions if `lv`)
Michael Hanus's avatar
Michael Hanus committed
974
975
976
  allpkgs repo = concatMap (if lv then id else ((:[]) . filterCompatPkgs cfg))
                    (sortBy (\ps1 ps2 -> name (head ps1) <= name (head ps2))
                            (listPackages repo))
Michael Hanus's avatar
Michael Hanus committed
977

978
  -- all categories together with their package names:
Michael Hanus's avatar
Michael Hanus committed
979
  catgroups repo =
Michael Hanus's avatar
Michael Hanus committed
980
    let pkgid p = name p ++ '-' : showVersionIfCompatible cfg p
Michael Hanus's avatar
Michael Hanus committed
981
        newpkgs = map (filterCompatPkgs cfg) (listPackages repo)
Michael Hanus's avatar
Michael Hanus committed
982
983
984
        catpkgs = concatMap (\p -> map (\c -> (c, pkgid p)) (category p))
                            newpkgs
        nocatps = map pkgid (filter (null . category) newpkgs)
985
986
987
988
989
990
    in map (\cg -> (fst (head cg), map snd cg))
           (groupBy (\ (c1,_) (c2,_) -> c1==c2) (nub $ sortBy (<=) catpkgs)) ++
       if null nocatps then []
                       else [("???", nub $ sortBy (<=) nocatps)]

  renderPkgs pkgs =
Michael Hanus's avatar
Michael Hanus committed
991
    let (colsizes,rows) = packageVersionAsTable cfg pkgs
Michael Hanus's avatar
Michael Hanus committed
992
    in renderTable colsizes rows
993
994

  renderCats catgrps =
Michael Hanus's avatar
Michael Hanus committed
995
    let namelen = foldl max 8 $ map (length . fst) catgrps
996
997
        header = [ ["Category", "Packages"]
                 , ["--------", "--------"]]
Michael Hanus's avatar
Michael Hanus committed
998
        rows   = header ++ map (\ (c,ns) -> [c, unwords ns]) catgrps
Michael Hanus's avatar
Michael Hanus committed
999
    in renderTable [namelen + 2, 78 - namelen] rows
1000
  
Michael Hanus's avatar
Michael Hanus committed
1001
1002
  renderTable colsizes rows =
    if csv then showCSV (head rows : drop 2 rows)
Michael Hanus's avatar
Michael Hanus committed
1003
           else unlines [render (table rows colsizes), cpmInfo, useUpdateHelp]
Michael Hanus's avatar
Michael Hanus committed
1004

Michael Hanus's avatar
Michael Hanus committed
1005
1006
1007
1008
1009
1010
1011
1012
--- Returns the first package of a list of packages compatible to the
--- current compiler (according to the given configuration).
--- If there is no compatible package, returns the first one.
filterCompatPkgs :: Config -> [Package] -> Package
filterCompatPkgs cfg pkgs =
  let comppkgs = filter (isCompatibleToCompiler cfg) pkgs
  in if null comppkgs then head pkgs else head comppkgs

Michael Hanus's avatar
Michael Hanus committed
1013
1014
-- Format a list of packages by showing their names, synopsis, and versions
-- as table rows. Returns also the column sizes.
Michael Hanus's avatar
Michael Hanus committed
1015
1016
packageVersionAsTable :: Config -> [Package] -> ([Int],[[String]])
packageVersionAsTable cfg pkgs = (colsizes, rows)
Michael Hanus's avatar
Michael Hanus committed
1017
 where
Michael Hanus's avatar
Michael Hanus committed
1018
  namelen = foldl max 4 $ map (length . name) pkgs
Michael Hanus's avatar
Michael Hanus committed
1019
  colsizes = [namelen + 2, 68 - namelen, 10]
Michael Hanus's avatar
Michael Hanus committed
1020
1021
1022
  header  = [ ["Name", "Synopsis", "Version"]
            , ["----", "--------", "-------"]]
  rows    = header ++ map formatPkg pkgs
Michael Hanus's avatar
Michael Hanus committed
1023
1024
1025
  formatPkg p = [name p, synopsis p, showVersionIfCompatible cfg p]

--- Shows the version of a package if it is compatible with the
Michael Hanus's avatar
Michael Hanus committed
1026
--- current compiler, otherwise shows the version in brackets.
Michael Hanus's avatar
Michael Hanus committed
1027
1028
showVersionIfCompatible :: Config -> Package -> String
showVersionIfCompatible cfg p =
Michael Hanus's avatar
Michael Hanus committed
1029
1030
  let s = showVersion (version p)
  in if isCompatibleToCompiler cfg p then s else '(' : s ++ ")"
Michael Hanus's avatar
Michael Hanus committed
1031

Michael Hanus's avatar
Michael Hanus committed
1032
cpmInfo :: String
Michael Hanus's avatar
Michael Hanus committed
1033
cpmInfo = "Use 'cypm info PACKAGE' for more information about a package."
Michael Hanus's avatar
Michael Hanus committed
1034
1035


Michael Hanus's avatar
Michael Hanus committed
1036
--- Search in all (compiler-compatible) packages in the given repository.
Michael Hanus's avatar
Michael Hanus committed
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
searchCmd :: SearchOptions -> Config -> IO (ErrorLogger ())
searchCmd (SearchOptions q smod sexec) cfg = do
  let searchaction = if smod then searchExportedModules
                             else if sexec then searchExecutable
                                           else searchNameSynopsisModules
  allpkgs <- searchaction cfg q
  let results = sortBy (\p1 p2 -> name p1 <= name p2)
                       (map (filterCompatPkgs cfg)
                            (map (sortBy (\a b -> version a `vgt` version b))
                                 (groupBy (\a b -> name a == name b)
                                 allpkgs)))
      (colsizes,rows) = packageVersionAsTable cfg results
  putStr $ unlines $
             if null results
               then [ "No packages found for '" ++ q ++ "'", useUpdateHelp ]
               else [ render (table rows colsizes), cpmInfo, useUpdateHelp ]
  succeedIO ()
Michael Hanus's avatar
Michael Hanus committed
1054

Michael Hanus's avatar
Michael Hanus committed
1055
1056

--- `upgrade` command.
Michael Hanus's avatar
Michael Hanus committed
1057
1058
1059
upgradeCmd :: UpgradeOptions -> Config -> IO (ErrorLogger ())
upgradeCmd (UpgradeOptions Nothing) cfg =
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
1060
1061
  cleanCurryPathCache specDir |>
  log Info "Upgrading all packages" |>
Michael Hanus's avatar
Michael Hanus committed
1062
1063
1064
  upgradeAllPackages cfg specDir
upgradeCmd (UpgradeOptions (Just pkg)) cfg =
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
1065
  log Info ("Upgrade " ++ pkg) |>
Michael Hanus's avatar
Michael Hanus committed
1066
  upgradeSinglePackage cfg specDir pkg
Michael Hanus's avatar
Michael Hanus committed
1067
1068


Michael Hanus's avatar
Michael Hanus committed
1069
--- `link` command.
Michael Hanus's avatar
Michael Hanus committed
1070
linkCmd :: LinkOptions -> Config -> IO (ErrorLogger ())
Michael Hanus's avatar
Michael Hanus committed
1071
1072
linkCmd (LinkOptions src) cfg =
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
1073
  cleanCurryPathCache specDir |>
Michael Hanus's avatar
Michael Hanus committed
1074
  log Info ("Linking '" ++ src ++ "' into local package cache...") |>
Michael Hanus's avatar
Michael Hanus committed
1075
1076
  linkToLocalCache src specDir

Michael Hanus's avatar
Michael Hanus committed
1077
1078
--- `add` command:
--- Option `--package`: copy the given package to the repository index
Michael Hanus's avatar
Michael Hanus committed
1079
1080
--- and package installation directory so that it is available as
--- any other package.
Michael Hanus's avatar
Michael Hanus committed
1081
1082
--- Option `--dependency`: add the package name as a dependency to the
--- current package
Michael Hanus's avatar
Michael Hanus committed
1083
addCmd :: AddOptions -> Config -> IO (ErrorLogger ())
Michael Hanus's avatar
Michael Hanus committed
1084
addCmd (AddOptions addpkg adddep pkg force) config
Michael Hanus's avatar
Michael Hanus committed
1085
  | addpkg    = addPackageToRepository config pkg force True
Michael Hanus's avatar
Michael Hanus committed
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
  | adddep    = addDependencyCmd pkg force config
  | otherwise = log Critical "Option --package or --dependency missing!"

useForce :: String
useForce = "Use option '-f' or '--force' to overwrite it."

--- `add --dependency` command: add the given package as a new
--- dependency to the current package.
addDependencyCmd :: String -> Bool -> Config -> IO (ErrorLogger ())
addDependencyCmd pkgname force config =
Michael Hanus's avatar
Michael Hanus committed
1096
1097
  getAllPackageVersions config pkgname False >>= \allpkgs ->
  case allpkgs of
Michael Hanus's avatar
Michael Hanus committed
1098
1099
    [] -> packageNotFoundFailure pkgname
    ps -> case filter (isCompatibleToCompiler config) ps of
Michael Hanus's avatar
Michael Hanus committed
1100
1101
1102
             []    -> compatPackageNotFoundFailure config pkgname useUpdateHelp
             (p:_) -> getLocalPackageSpec config "." |>=
                      addDepToLocalPackage (version p)
Michael Hanus's avatar
Michael Hanus committed
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
 where
  addDepToLocalPackage vers pkgdir =
    loadPackageSpec pkgdir |>= \pkgSpec ->
    let depexists = pkgname `elem` dependencyNames pkgSpec
        newdeps   = addDep [[VGte vers]] (dependencies pkgSpec)
        newpkg    = pkgSpec { dependencies = newdeps }
    in if force || not depexists
         then writePackageSpec newpkg (pkgdir </> "package.json") |>>
              log Info ("Dependency '" ++ pkgname ++ " >= " ++
                        showVersion vers ++
Michael Hanus's avatar
Michael Hanus committed
1113
                        "' added to package '" ++ pkgdir ++ "'")
Michael Hanus's avatar
Michael Hanus committed
1114
1115
1116
1117
1118
1119
1120
         else log Critical ("Dependency '" ++ pkgname ++
                            "' already exists!\n" ++ useForce)

  addDep vcs [] = [Dependency pkgname vcs]
  addDep vcs (Dependency pn pvcs : deps) =
    if pn == pkgname then Dependency pn vcs : deps
                     else Dependency pn pvcs : addDep vcs deps
Michael Hanus's avatar
Michael Hanus committed
1121

Michael Hanus's avatar
Michael Hanus committed
1122
------------------------------------------------------------------------------
1123
1124
1125
1126
--- `doc` command: run `curry doc` on the modules provided as an argument
--- or, if they are not given, on exported modules (if specified in the
--- package), on the main executable (if specified in the package),
--- or on all source modules of the package.
Michael Hanus's avatar
Michael Hanus committed
1127
1128
1129
docCmd :: DocOptions -> Config -> IO (ErrorLogger ())
docCmd opts cfg =
  getLocalPackageSpec cfg "." |>= \specDir ->
1130
  loadPackageSpec specDir |>= \pkg -> do
Michael Hanus's avatar
Michael Hanus committed
1131
  let docdir = maybe "cdoc" id (docDir opts) </> packageId pkg
Michael Hanus's avatar
Michael Hanus committed
1132
1133
  absdocdir <- getAbsolutePath docdir
  createDirectoryIfMissing True absdocdir
Michael Hanus's avatar
Michael Hanus committed
1134
  (if docManual opts then genPackageManual pkg specDir absdocdir
Michael Hanus's avatar
Michael Hanus committed
1135
                     else succeedIO ()) |>
Michael Hanus's avatar
Michael Hanus committed
1136
    (if docPrograms opts then genDocForPrograms opts cfg absdocdir specDir pkg
Michael Hanus's avatar
Michael Hanus committed
1137
1138
1139
                         else succeedIO ())

--- Generate manual according to  documentation specification of package.
Michael Hanus's avatar
Michael Hanus committed
1140
1141
genPackageManual :: Package -> String -> String -> IO (ErrorLogger ())
genPackageManual pkg specDir outputdir = case documentation pkg of
Michael Hanus's avatar
Michael Hanus committed
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
    Nothing -> succeedIO ()
    Just (PackageDocumentation docdir docmain doccmd) -> do
      let formatcmd = replaceSubString "OUTDIR" outputdir $
                        if null doccmd then formatCmd docmain
                                       else doccmd
      if null formatcmd
        then infoMessage $ "Cannot format documentation file '" ++
                           docmain ++ "' (unknown kind)"
        else do
          debugMessage $ "Executing command: " ++ formatcmd
Michael Hanus's avatar
Michael Hanus committed
1152
          inDirectory (specDir </> docdir) $ system formatcmd
Michael Hanus's avatar
Michael Hanus committed
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
          let outfile = outputdir </> replaceExtension docmain ".pdf"
          system ("chmod -f 644 " ++ quote outfile) -- make it readable
          infoMessage $ "Package documentation written to '" ++ outfile ++ "'."
      succeedIO ()
 where
  formatCmd docmain
    | ".tex" `isSuffixOf` docmain
    = let formatcmd = "pdflatex -output-directory=\"OUTDIR\" " ++ docmain
      in formatcmd ++ " && " ++ formatcmd
    | ".md" `isSuffixOf` docmain
    = "pandoc " ++ docmain ++
      " -o \"OUTDIR" </> replaceExtension docmain ".pdf" ++ "\""
    | otherwise = ""

--- Replace every occurrence of the first argument by the second argument
--- in a string (third argument).
replaceSubString :: String -> String -> String -> String
replaceSubString sub newsub s = replString s
1171
 where
Michael Hanus's avatar
Michael Hanus committed
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
  sublen = length sub

  replString [] = []
  replString ccs@(c:cs) =
    if take sublen ccs == sub
      then newsub ++ replString (drop sublen ccs)
      else c : replString cs

--- Generate program documentation:
--- run `curry doc` on the modules provided as an argument
--- or, if they are not given, on exported modules (if specified in the
--- package), on the main executable (if specified in the package),
--- or on all source modules of the package.
Michael Hanus's avatar
Michael Hanus committed
1185
1186
1187
genDocForPrograms :: DocOptions -> Config -> String -> String -> Package
                  -> IO (ErrorLogger ())
genDocForPrograms opts cfg docdir specDir pkg = do
Michael Hanus's avatar
Michael Hanus committed
1188
  abspkgdir <- getAbsolutePath specDir
Michael Hanus's avatar
Michael Hanus committed
1189
  checkCompiler cfg pkg
Michael Hanus's avatar
Michael Hanus committed
1190
  let exports = exportedModules pkg
Michael Hanus's avatar
Michael Hanus committed
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
      mainmod = maybe Nothing
                      (\ (PackageExecutable _ emain _) -> Just emain)
                      (executableSpec pkg)
  (docmods,apidoc) <-
     maybe (if null exports
              then maybe (curryModulesInDir (specDir </> "src") >>=
                          \ms -> return (ms,True))
                         (\m -> return ([m],False))
                         mainmod
              else return (exports,True))
           (\ms -> return (ms,True))
           (docModules opts)
  if null docmods
Michael Hanus's avatar
Michael Hanus committed
1204
    then log Info "No modules to be documented!"
Michael Hanus's avatar
Michael Hanus committed
1205
    else
Michael Hanus's avatar
Michael Hanus committed
1206
      getCurryLoadPath cfg specDir |>= \currypath ->
Michael Hanus's avatar
Michael Hanus committed
1207
      let pkgurls = path2packages abspkgdir currypath in
Michael Hanus's avatar
Michael Hanus committed
1208
      if apidoc
Michael Hanus's avatar
Michael Hanus committed
1209
1210
1211
1212
        then foldEL (\_ -> docModule currypath pkgurls) () docmods |>
             runDocCmd currypath pkgurls
                       (["--title", apititle, "--onlyindexhtml", docdir]
                        ++ docmods) |>
Michael Hanus's avatar
Michael Hanus committed
1213
             log Info ("Documentation generated in '"++docdir++"'")
Michael Hanus's avatar
Michael Hanus committed
1214
        else runDocCmd currypath pkgurls [docdir, head docmods]
Michael Hanus's avatar
Michael Hanus committed
1215
1216
 where
  apititle = "\"API Documentation of Package '" ++ name pkg ++ "'\""
Michael Hanus's avatar
Michael Hanus committed
1217

1218
1219
  currydoc = curryExec cfg ++ " doc"

Michael Hanus's avatar
Michael Hanus committed
1220
1221
  docModule currypath uses mod =
    runDocCmd currypath uses ["--noindexhtml", docdir, mod]
1222

Michael Hanus's avatar
Michael Hanus committed
1223
1224
1225
1226
1227
  runDocCmd currypath uses docparams = do
    let useopts = if docGenImports opts
                    then []
                    else map (\ (d,u) -> "--use "++d++"@"++u) uses
        cmd = unwords (currydoc : useopts ++ docparams)
1228
    infoMessage $ "Running CurryDoc: " ++ cmd
Michael Hanus's avatar
Michael Hanus committed
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
    execWithCurryPath (ExecOptions cmd) cfg currypath

  -- translates a path into a list of package paths and their doc URLs:
  path2packages absdir path =
    let dirs = splitSearchPath path
        importPkgDir = absdir </> ".cpm" </> "packages" ++ [pathSeparator]
        isImportedPackage d = importPkgDir `isPrefixOf` d
        impPkg2URL p =
          let (d,_) = break isPathSeparator (drop (length importPkgDir) p)
          in docPackageURL opts ++ "/" ++ d
    in map (\ip -> (ip,impPkg2URL ip)) (filter isImportedPackage dirs) ++
       if name pkg == "base"
         then [] -- in order to generate base package documentation
         else [(installDir </> "lib",
Michael Hanus's avatar
Michael Hanus committed
1243
                docPackageURL opts ++ "/base-" ++ compilerBaseVersion cfg)]
Michael Hanus's avatar
Michael Hanus committed
1244
1245

------------------------------------------------------------------------------
1246
1247
1248
--- `test` command: run `curry check` on the modules provided as an argument
--- or, if they are not provided, on the exported (if specified)
--- or all source modules of the package.
Michael Hanus's avatar
Michael Hanus committed
1249
1250
1251
testCmd :: TestOptions -> Config -> IO (ErrorLogger ())
testCmd opts cfg =
  getLocalPackageSpec cfg "." |>= \specDir ->
1252
1253
  loadPackageSpec specDir |>= \pkg -> do
    checkCompiler cfg pkg
Michael Hanus's avatar
Michael Hanus committed
1254
1255
    aspecDir <- getAbsolutePath specDir
    mainprogs <- curryModulesInDir (aspecDir </> "src")
1256
    let tests = testsuites pkg mainprogs
Michael Hanus's avatar
Michael Hanus committed
1257
    if null tests
Michael Hanus's avatar
Michael Hanus committed
1258
      then log Info "No modules to be tested!"
Michael Hanus's avatar
Michael Hanus committed
1259
1260
      else foldEL (\_ -> execTest aspecDir) () tests
 where
Michael Hanus's avatar
Michael Hanus committed
1261
1262
  currycheck = curryExec cfg ++ " check"
  
Michael Hanus's avatar
Michael Hanus committed
1263
  execTest apkgdir (PackageTest dir mods ccopts script) = do
1264
1265
    let scriptcmd = "CURRYBIN=" ++ curryExec cfg ++ " && export CURRYBIN && " ++
                    "." </> script ++ if null ccopts then "" else ' ' : ccopts
Michael Hanus's avatar
Michael Hanus committed
1266
1267
1268
1269
1270
1271
        checkcmd  = currycheck ++ if null ccopts then "" else ' ' : ccopts
    unless (null mods) $ putStrLn $
      "Running CurryCheck (" ++ checkcmd ++ ")\n" ++
      "(in directory '" ++ dir ++ "', showing raw output) on modules:\n" ++
      unwords mods ++ "\n"
    unless (null script) $ putStrLn $
1272
      "Executing test script with command:\n" ++ scriptcmd ++ "\n" ++
Michael Hanus's avatar
Michael Hanus committed
1273
      "(in directory '" ++ dir ++ "', showing raw output):\n"
Michael Hanus's avatar
Michael Hanus committed
1274
    let currysubdir = apkgdir </> addCurrySubdir dir
Michael Hanus's avatar
Michael Hanus committed
1275
1276
1277
        testcmd = if not (null mods)
                    then unwords (checkcmd : mods)
                    else scriptcmd
Michael Hanus's avatar
Michael Hanus committed
1278
    debugMessage $ "Removing directory: " ++ currysubdir
Michael Hanus's avatar
Michael Hanus committed
1279
    showExecCmd (unwords ["rm", "-rf", currysubdir])
Michael Hanus's avatar
Michael Hanus committed
1280
    inDirectory (apkgdir </> dir) $
Michael Hanus's avatar
Michael Hanus committed
1281
      execWithPkgDir (ExecOptions testcmd) cfg apkgdir
Michael Hanus's avatar
Michael Hanus committed
1282
1283
1284
1285
1286
1287

  testsuites spec mainprogs = case testModules opts of
    Nothing -> maybe (let exports = exportedModules spec
                      in if null exports
                           then if null mainprogs
                                  then []
Michael Hanus's avatar
Michael Hanus committed
1288
1289
                                  else [PackageTest "src" mainprogs "" ""]
                           else [PackageTest "src" exports "" ""])
Michael Hanus's avatar
Michael Hanus committed
1290
                     id
Michael Hanus's avatar
Michael Hanus committed
1291
                     (testSuite spec)
Michael Hanus's avatar
Michael Hanus committed
1292
    Just ms -> [PackageTest "src" ms "" ""]
Michael Hanus's avatar
Michael Hanus committed
1293

1294
--- Get the names of all Curry modules contained in a directory.
Michael Hanus's avatar
Michael Hanus committed
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
--- Modules in subdirectories are returned as hierarchical modules.
curryModulesInDir :: String -> IO [String]
curryModulesInDir dir = getModules "" dir
 where
  getModules p d = do
    entries <- getDirectoryContents d
    let realentries = filter (\f -> length f >= 1 && head f /= '.') entries
        newprogs    = filter (\f -> takeExtension f == ".curry") realentries
    subdirs <- mapIO (\e -> doesDirectoryExist (d </> e) >>=
                            \b -> return $ if b then [e] else []) realentries
               >>= return . concat
    subdirentries <- mapIO (\s -> getModules (p ++ s ++ ".") (d </> s)) subdirs
    return $ map ((p ++) . stripCurrySuffix) newprogs ++ concat subdirentries


Michael Hanus's avatar
Michael Hanus committed
1310
1311
1312
diffCmd :: DiffOptions -> Config -> IO (ErrorLogger ())
diffCmd opts cfg =
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
1313
  loadPackageSpec specDir     |>= \localSpec ->
Michael Hanus's avatar
Michael Hanus committed
1314
  checkCompiler cfg localSpec >>
Michael Hanus's avatar
Michael Hanus committed
1315
1316
1317
1318
  let localname  = name localSpec
      localv     = version localSpec
      showlocalv = showVersion localv
  in
Michael Hanus's avatar
Michael Hanus committed
1319
1320
1321
  getRepoForPackageSpec cfg localSpec >>= \repo ->
  readGlobalCache cfg repo |>= \gc ->
  getDiffVersion repo localname |>= \diffv ->
Michael Hanus's avatar
Michael Hanus committed
1322
1323
1324
1325
  if diffv == localv
    then failIO $ "Cannot diff identical package versions " ++ showlocalv
    else putStrLn ("Comparing local version " ++ showlocalv ++
                   " and repository version " ++ showVersion diffv ++ ":\n") >>
Michael Hanus's avatar
Michael Hanus committed
1326
1327
         diffAPIIfEnabled      repo gc specDir localSpec diffv |> 
         diffBehaviorIfEnabled repo gc specDir localSpec diffv
Michael Hanus's avatar
Michael Hanus committed
1328
 where
Michael Hanus's avatar
Michael Hanus committed
1329
  getDiffVersion repo localname = case diffVersion opts of
1330
    Nothing -> case findLatestVersion cfg repo localname False of
Michael Hanus's avatar
Michael Hanus committed
1331
1332
1333
1334
1335
      Nothing -> failIO $
        "No other version of local package '" ++ localname ++
        "' compatible to '" ++ showCompilerVersion cfg ++
        "' found in package repository."
      Just p  -> succeedIO (version p)
Michael Hanus's avatar
Michael Hanus committed
1336
1337
    Just v  -> succeedIO v
 
Michael Hanus's avatar
Michael Hanus committed
1338
  diffAPIIfEnabled repo gc specDir localSpec diffversion =
Michael Hanus's avatar
Michael Hanus committed
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
    if diffAPI opts
    then (putStrLn "Running API diff...\n" >> succeedIO ()) |>
         APIDiff.compareModulesFromPackageAndDir cfg repo gc specDir
                          (name localSpec) diffversion (diffModules opts) |>=
         \diffResults ->
         let diffOut = APIDiff.showDifferences (map snd diffResults)
                                             (version localSpec) diffversion
         in unless (null diffOut) (putStrLn diffOut >> putStrLn "") >>
            succeedIO ()
    else succeedIO () 

Michael Hanus's avatar
Michael Hanus committed
1350
  diffBehaviorIfEnabled repo gc specDir localSpec diffversion =
Michael Hanus's avatar
Michael Hanus committed
1351
1352
1353
1354
1355
1356
1357
1358
    if diffBehavior opts
      then (putStrLn "Preparing behavior diff...\n" >> succeedIO ()) |>
           BDiff.preparePackageAndDir cfg repo gc specDir (name localSpec)
                                                          diffversion |>=
           \i -> BDiff.diffBehavior cfg repo gc i (diffUseAna opts)
                                    (diffModules opts)
      else succeedIO ()

Michael Hanus's avatar
Michael Hanus committed
1359
-- Implementation of the "curry" command.
Michael Hanus's avatar
Michael Hanus committed
1360
1361
1362
compiler :: ExecOptions -> Config -> IO (ErrorLogger ())
compiler o cfg =
  getLocalPackageSpec cfg "." |>= \pkgdir ->
Michael Hanus's avatar
Michael Hanus committed
1363
1364
  loadPackageSpec pkgdir |>= \pkg ->
  checkCompiler cfg pkg >>
Michael Hanus's avatar
Michael Hanus committed
1365
1366
  execWithPkgDir
    (ExecOptions $ unwords [curryExec cfg, "--nocypm", exeCommand o])
Michael Hanus's avatar
Michael Hanus committed
1367
    cfg pkgdir
Michael Hanus's avatar
Michael Hanus committed
1368

Michael Hanus's avatar
Michael Hanus committed
1369
1370
1371
execCmd :: ExecOptions -> Config -> IO (ErrorLogger ())
execCmd o cfg =
  getLocalPackageSpec cfg "." |>= execWithPkgDir o cfg
Michael Hanus's avatar
Michael Hanus committed
1372

Michael Hanus's avatar
Michael Hanus committed
1373
1374
1375
execWithPkgDir :: ExecOptions -> Config -> String -> IO (ErrorLogger ())
execWithPkgDir o cfg specDir =
  getCurryLoadPath cfg specDir |>= execWithCurryPath o cfg
Michael Hanus's avatar
Michael Hanus committed
1376
1377
1378

execWithCurryPath :: ExecOptions -> Config -> String -> IO (ErrorLogger ())
execWithCurryPath o _ currypath =
Michael Hanus's avatar
Michael Hanus committed
1379
1380
  log Debug ("Setting CURRYPATH to " ++ currypath) |>
  do setEnviron "CURRYPATH" currypath
Michael Hanus's avatar
Michael Hanus committed
1381
     ecode <- showExecCmd (exeCommand o)
Michael Hanus's avatar
Michael Hanus committed
1382
1383
1384
     unsetEnviron "CURRYPATH"
     unless (ecode==0) (exitWith ecode)
     succeedIO ()
Michael Hanus's avatar
Michael Hanus committed
1385

Michael Hanus's avatar
Michael Hanus committed
1386
1387
1388
computePackageLoadPath :: Config -> String -> IO (ErrorLogger String)
computePackageLoadPath cfg pkgdir =
  debugMessage "Computing load path for package..." >>
Michael Hanus's avatar
Michael Hanus committed
1389
  loadPackageSpec pkgdir |>= \pkg ->
Michael Hanus's avatar
Michael Hanus committed
1390
1391
1392
  loadBaseVersionFromCache pkgdir >>= \cbv ->
  let cfg' = if null cbv then cfg else cfg { baseVersion = cbv } in
  resolveAndCopyDependenciesForPackage cfg' pkgdir pkg |>= \allpkgs ->
Michael Hanus's avatar
Michael Hanus committed
1393
1394
  getAbsolutePath pkgdir >>= \abs -> succeedIO () |>
  let srcdirs = map (abs </>) (sourceDirsOf pkg)
Michael Hanus's avatar
Michael Hanus committed
1395
1396
      -- remove 'base' package if it is the same as in current config:
      pkgs = filter notCurrentBase allpkgs
Michael Hanus's avatar
Michael Hanus committed
1397
      currypath = joinSearchPath (srcdirs ++ dependencyPathsSeparate pkgs abs)
Michael Hanus's avatar
Michael Hanus committed
1398
1399
1400
1401
  in saveCurryPathToCache cfg' pkgdir currypath >> succeedIO currypath
 where
  notCurrentBase pkg = name pkg /= "base" ||