Main.curry 62.7 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
import CPM.PackageCache.Global ( GlobalCache, readGlobalCache, allPackages
Michael Hanus's avatar
Michael Hanus committed
36
                               , installFromZip, checkoutPackage
Michael Hanus's avatar
Michael Hanus committed
37
                               , uninstallPackage, packageInstalled )
Michael Hanus's avatar
Michael Hanus committed
38
import CPM.Package
39
import CPM.Resolution ( isCompatibleToCompiler, showResult )
Michael Hanus's avatar
Michael Hanus committed
40
41
import CPM.Repository ( Repository, findVersion, listPackages
                      , findAllVersions, findLatestVersion
42
                      , useUpdateHelp, searchPackages, cleanRepositoryCache
Michael Hanus's avatar
Michael Hanus committed
43
44
45
                      , readPackageFromRepository )
import CPM.Repository.Update ( addPackageToRepository, updateRepository )
import CPM.Repository.Select
Michael Hanus's avatar
Michael Hanus committed
46
47
48
49
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
50
import CPM.ConfigPackage (packagePath)
Michael Hanus's avatar
Michael Hanus committed
51
52
53
54
55
56

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

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

runWithArgs :: Options -> IO ()
runWithArgs opts = do
Michael Hanus's avatar
Michael Hanus committed
78
  setLogLevel $ optLogLevel opts
Michael Hanus's avatar
Michael Hanus committed
79
  setWithShowTime (optWithTime opts)
Michael Hanus's avatar
Michael Hanus committed
80
  debugMessage "Reading CPM configuration..."
Michael Hanus's avatar
Michael Hanus committed
81
  config <- readConfigurationWith (optDefConfig opts) >>= \c ->
Michael Hanus's avatar
Michael Hanus committed
82
   case c of
Michael Hanus's avatar
Michael Hanus committed
83
    Left err -> do errorMessage $ "Error reading .cpmrc settings: " ++ err
Michael Hanus's avatar
Michael Hanus committed
84
85
                   exitWith 1
    Right c' -> return c'
Michael Hanus's avatar
Michael Hanus committed
86
  debugMessage ("Current configuration:\n" ++ showConfiguration config)
Michael Hanus's avatar
Michael Hanus committed
87
88
  (msgs, result) <- case optCommand opts of
    NoCommand   -> failIO "NoCommand"
Michael Hanus's avatar
Michael Hanus committed
89
    Config o    -> configCmd   o config
Michael Hanus's avatar
Michael Hanus committed
90
    Update      -> updateCmd   config
Michael Hanus's avatar
Michael Hanus committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    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
Michael Hanus's avatar
Michael Hanus committed
107
    Clean       -> cleanPackage config Info
Michael Hanus's avatar
Michael Hanus committed
108
109
110
111
112
113
114
115
116
117
  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
118
  , optWithTime  :: Bool
Michael Hanus's avatar
Michael Hanus committed
119
120
121
  , optCommand   :: Command }

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

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

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

Michael Hanus's avatar
Michael Hanus committed
151
152
153
154
155
156
157
158
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
159
  , instPrerelease :: Bool
Michael Hanus's avatar
Michael Hanus committed
160
161
  , instExecutable :: Bool
  , instExecOnly   :: Bool }
Michael Hanus's avatar
Michael Hanus committed
162
163
164
165
166
167
168
169

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
170
171
172
  , infoAll     :: Bool
  , infoPlain   :: Bool  -- plain output, no bold/color
  }
Michael Hanus's avatar
Michael Hanus committed
173
174

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

data SearchOptions = SearchOptions
Michael Hanus's avatar
Michael Hanus committed
181
182
183
  { 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
184
  }
Michael Hanus's avatar
Michael Hanus committed
185
186
187
188
189
190
191

data UpgradeOptions = UpgradeOptions
  { upgrTarget :: Maybe String }

data LinkOptions = LinkOptions
  { lnkSource :: String }

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

Michael Hanus's avatar
Michael Hanus committed
199
200
201
data NewOptions = NewOptions
  { projectName :: String }

Michael Hanus's avatar
Michael Hanus committed
202
data ExecOptions = ExecOptions
Michael Hanus's avatar
Michael Hanus committed
203
  { exeCommand :: String   -- the command to be executed
Michael Hanus's avatar
Michael Hanus committed
204
205
  }

206
data DocOptions = DocOptions
Michael Hanus's avatar
Michael Hanus committed
207
208
209
210
211
212
  { 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)
Michael Hanus's avatar
Michael Hanus committed
213
214
215
  , docPackageURL :: String          -- the URL prefix where all repository
                                     -- packages are documented
}
216

Michael Hanus's avatar
Michael Hanus committed
217
218
219
220
221
222
223
224
225
226
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
227
228
229
230
231
configOpts :: Options -> ConfigOptions
configOpts s = case optCommand s of
  Config opts -> opts
  _           -> ConfigOptions False

Michael Hanus's avatar
Michael Hanus committed
232
233
234
235
236
depsOpts :: Options -> DepsOptions
depsOpts s = case optCommand s of
  Deps opts -> opts
  _         -> DepsOptions False

Michael Hanus's avatar
Michael Hanus committed
237
238
239
240
241
242
243
244
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
245
  _            -> InstallOptions Nothing Nothing False True False
Michael Hanus's avatar
Michael Hanus committed
246
247
248
249
250
251
252
253
254

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
255
  _            -> InfoOptions Nothing Nothing False False
Michael Hanus's avatar
Michael Hanus committed
256
257
258
259

listOpts :: Options -> ListOptions
listOpts s = case optCommand s of
  List opts -> opts
260
  _         -> ListOptions False False False
Michael Hanus's avatar
Michael Hanus committed
261
262
263
264

searchOpts :: Options -> SearchOptions
searchOpts s = case optCommand s of
  Search opts -> opts
Michael Hanus's avatar
Michael Hanus committed
265
  _           -> SearchOptions "" False False
Michael Hanus's avatar
Michael Hanus committed
266
267
268
269
270
271
272
273
274
275
276

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
277
278
279
addOpts :: Options -> AddOptions
addOpts s = case optCommand s of
  Add opts -> opts
Michael Hanus's avatar
Michael Hanus committed
280
  _        -> AddOptions False False "" False
Michael Hanus's avatar
Michael Hanus committed
281

Michael Hanus's avatar
Michael Hanus committed
282
283
284
285
286
newOpts :: Options -> NewOptions
newOpts s = case optCommand s of
  New opts -> opts
  _        -> NewOptions ""

Michael Hanus's avatar
Michael Hanus committed
287
288
289
execOpts :: Options -> ExecOptions
execOpts s = case optCommand s of
  Exec opts -> opts
Michael Hanus's avatar
Michael Hanus committed
290
  _         -> ExecOptions ""
Michael Hanus's avatar
Michael Hanus committed
291

292
293
294
docOpts :: Options -> DocOptions
docOpts s = case optCommand s of
  Doc opts -> opts
Michael Hanus's avatar
Michael Hanus committed
295
296
297
298
299
300
301
  _        -> 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"

302

Michael Hanus's avatar
Michael Hanus committed
303
304
305
306
307
308
309
310
311
312
313
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
314
315
316
readLogLevel s = case map toLower s of
  "debug" -> Right Debug
  "info"  -> Right Info
Michael Hanus's avatar
Michael Hanus committed
317
  "quiet" -> Right Quiet
Michael Hanus's avatar
Michael Hanus committed
318
  _       -> Left $ "Illegal verbosity value: " ++ s
Michael Hanus's avatar
Michael Hanus committed
319
320
321
322
323
324
325
326
327
328
329
330

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
331
332
applyEither :: [Options -> Either String Options] -> Options
            -> Either String Options
Michael Hanus's avatar
Michael Hanus committed
333
334
335
336
337
338
339
340
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
341
  defaultOpts = Options Info [] False NoCommand
Michael Hanus's avatar
Michael Hanus committed
342
343
344
345
346
347

(>.>) :: 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
348
349
optionParser :: [String] -> ParseSpec (Options -> Either String Options)
optionParser allargs = optParser 
Michael Hanus's avatar
Michael Hanus committed
350
  (   option (\s a -> readLogLevel s >.> \ll -> a { optLogLevel = ll })
Michael Hanus's avatar
Michael Hanus committed
351
352
353
354
       (  long "verbosity"
       <> short "v"
       <> metavar "LEVEL"
       <> help "Log level for the application. Valid values: info|debug|quiet" )
Michael Hanus's avatar
Michael Hanus committed
355
356
357
358
359
360
  <.> 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
361
362
363
364
  <.> 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
365
  <.> commands (metavar "COMMAND")
Michael Hanus's avatar
Michael Hanus committed
366
367
368
369
370
        (   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
371
                    (checkoutArgs Checkout)
Michael Hanus's avatar
Michael Hanus committed
372
        <|> command "install" (help "Install a package with its dependencies.")
Michael Hanus's avatar
Michael Hanus committed
373
                     (\a -> Right $ a { optCommand = Install (installOpts a) })
Michael Hanus's avatar
Michael Hanus committed
374
                     installArgs
Michael Hanus's avatar
Michael Hanus committed
375
        <|> command "uninstall" (help "Uninstall a package")
Michael Hanus's avatar
Michael Hanus committed
376
377
                 (\a -> Right $ a { optCommand = Uninstall (uninstallOpts a) })
                 uninstallArgs
Michael Hanus's avatar
Michael Hanus committed
378
        <|> command "deps" (help "Calculate dependencies")
Michael Hanus's avatar
Michael Hanus committed
379
380
                           (\a -> Right $ a { optCommand = Deps (depsOpts a) })
                           depsArgs
Michael Hanus's avatar
Michael Hanus committed
381
        <|> command "clean" (help "Clean the current package")
Michael Hanus's avatar
Michael Hanus committed
382
                            (\a -> Right $ a { optCommand = Clean }) []
Michael Hanus's avatar
Michael Hanus committed
383
        <|> command "new" (help "Create a new package") Right newArgs
Michael Hanus's avatar
Michael Hanus committed
384
385
        <|> command "update" (help "Update the package index")
                             (\a -> Right $ a { optCommand = Update }) []
Michael Hanus's avatar
Michael Hanus committed
386
387
        <|> command "curry"
           (help "Load package spec and start Curry with correct dependencies.")
Michael Hanus's avatar
Michael Hanus committed
388
389
                 (\a -> Right $ a { optCommand = Compiler (execOpts a) })
                 curryArgs
Michael Hanus's avatar
Michael Hanus committed
390
391
392
393
        <|> 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
394
        <|> command "info" (help "Print package information")
Michael Hanus's avatar
Michael Hanus committed
395
396
                    (\a -> Right $ a { optCommand = PkgInfo (infoOpts a) })
                    infoArgs
397
398
399
400
        <|> 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
401
402
        <|> command "test" (help "Test the current package (with CurryCheck)")
                    (\a -> Right $ a { optCommand = Test (testOpts a) })
Michael Hanus's avatar
Michael Hanus committed
403
                    testArgs
Michael Hanus's avatar
Michael Hanus committed
404
405
406
        <|> command "diff"
                    (help "Diff the current package against another version")
                    (\a -> Right $ a { optCommand = Diff (diffOpts a) })
Michael Hanus's avatar
Michael Hanus committed
407
                    diffArgs
Michael Hanus's avatar
Michael Hanus committed
408
        <|> command "list" (help "List all packages of the repository")
Michael Hanus's avatar
Michael Hanus committed
409
410
                    (\a -> Right $ a { optCommand = List (listOpts a) })
                    listArgs
Michael Hanus's avatar
Michael Hanus committed
411
        <|> command "search" (help "Search the package repository") Right
Michael Hanus's avatar
Michael Hanus committed
412
                    searchArgs
Michael Hanus's avatar
Michael Hanus committed
413
414
        <|> command "upgrade" (help "Upgrade one or more packages")
                    (\a -> Right $ a { optCommand = Upgrade (upgradeOpts a) })
Michael Hanus's avatar
Michael Hanus committed
415
                    upgradeArgs
Michael Hanus's avatar
Michael Hanus committed
416
        <|> command "link" (help "Link a package to the local cache") Right
Michael Hanus's avatar
Michael Hanus committed
417
                    linkArgs
Michael Hanus's avatar
Michael Hanus committed
418
419
420
421
        <|> command "add"
              (help "Add a package (as dependency or to the local repository)")
              Right
              addArgs ) )
Michael Hanus's avatar
Michael Hanus committed
422
 where
Michael Hanus's avatar
Michael Hanus committed
423
424
425
426
427
428
429
430
  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
431
432
433
434
435
436
437
438
  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
439
440
441
442
443
444
445
446
447
448
449
450
451
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
  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
477
478
479
480
481
    <.> 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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502

  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
503
504
    rest (\_ a -> Right $ a { optCommand = Compiler (execOpts a)
                                            { exeCommand = unwords remargs } })
Michael Hanus's avatar
Michael Hanus committed
505
506
507
         (  metavar "ARGS"
         <> help "The options to pass to the compiler"
         <> optional )
Michael Hanus's avatar
Michael Hanus committed
508
509
    where
     remargs = tail (snd (break (=="curry") allargs))
Michael Hanus's avatar
Michael Hanus committed
510
511

  execArgs =
Michael Hanus's avatar
Michael Hanus committed
512
513
    rest (\_ a -> Right $ a { optCommand = Exec (execOpts a)
                                            { exeCommand = unwords remargs } })
Michael Hanus's avatar
Michael Hanus committed
514
         (  metavar "CMD"
Michael Hanus's avatar
Michael Hanus committed
515
         <> help "The command to be executed."
Michael Hanus's avatar
Michael Hanus committed
516
         <> optional )
Michael Hanus's avatar
Michael Hanus committed
517
518
    where
     remargs = tail (snd (break (=="exec") allargs))
Michael Hanus's avatar
Michael Hanus committed
519
520
521
522
523

  infoArgs =
        arg (\s a -> Right $ a { optCommand = PkgInfo (infoOpts a)
                                                { infoPackage = Just s } })
          (  metavar "PACKAGE"
Michael Hanus's avatar
Michael Hanus committed
524
          <> help ("The package name. If no name is specified, CPM tries " ++
Michael Hanus's avatar
Michael Hanus committed
525
526
527
528
529
530
531
                   "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
532
                   "CPM uses the latest version of the specified package.")
Michael Hanus's avatar
Michael Hanus committed
533
534
535
536
537
          <> optional )
    <.> flag (\a -> Right $ a { optCommand = PkgInfo (infoOpts a)
                                               { infoAll = True } })
          (  short "a"
          <> long "all"
Michael Hanus's avatar
Michael Hanus committed
538
539
540
541
542
543
          <> 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
544
545
          <> optional )

546
547
  docArgs =
    option (\s a -> Right $ a { optCommand =
Michael Hanus's avatar
Michael Hanus committed
548
                                  Doc (docOpts a) { docDir = Just s } })
549
550
551
552
553
554
555
556
557
558
559
560
          (  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
561
562
563
564
565
566
567
568
569
570
571
572
    <.> 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
573
574
575
576
577
578
    <.> 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 )
Michael Hanus's avatar
Michael Hanus committed
579
580
581
582
583
584
585
    <.> 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 )
586

Michael Hanus's avatar
Michael Hanus committed
587
588
589
590
591
592
593
594
595
596
597
598
599
  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
600
                    "CPM diffs against the latest repository version.")
Michael Hanus's avatar
Michael Hanus committed
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
           <> 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
626
        flag (\a -> Right $ a { optCommand =
Michael Hanus's avatar
Michael Hanus committed
627
628
629
                                  List (listOpts a) { listVers = True } })
          (  short "v"
          <> long "versions"
Michael Hanus's avatar
Michael Hanus committed
630
          <> help "Show all versions" ) 
Michael Hanus's avatar
Michael Hanus committed
631
632
    <.> flag (\a -> Right $ a { optCommand =
                                  List (listOpts a) { listCSV = True } })
Michael Hanus's avatar
Michael Hanus committed
633
634
635
          (  short "t"
          <> long "csv"
          <> help "Show in CSV table format" )
Michael Hanus's avatar
Michael Hanus committed
636
637
    <.> flag (\a -> Right $ a { optCommand =
                                  List (listOpts a) { listCat = True } })
Michael Hanus's avatar
Michael Hanus committed
638
639
640
641
642
          (  short "c"
          <> long "category"
          <> help "Show all categories" )

  searchArgs =
Michael Hanus's avatar
Michael Hanus committed
643
644
645
646
        flag (\a -> Right $ a { optCommand = Search (searchOpts a)
                                               { searchModule = True } })
             (  short "m"
             <> long "module"
Michael Hanus's avatar
Michael Hanus committed
647
648
649
650
651
652
             <> 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
653
654
655
656
    <.> arg (\s a -> Right $ a { optCommand = Search (searchOpts a)
                                                { searchQuery = s } }) 
            (  metavar "QUERY"
            <> help "The search term" )
Michael Hanus's avatar
Michael Hanus committed
657
658
659
660
661
662
663
664
665
666
667
668

  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
669

Michael Hanus's avatar
Michael Hanus committed
670
671
  addArgs =
       flag (\a -> Right $ a { optCommand =
Michael Hanus's avatar
Michael Hanus committed
672
673
674
675
676
677
678
679
680
681
                                 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
682
683
684
685
686
687
                                 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
688
689
           (  metavar "PACKAGE"
           <> help "The package directory or name to be added" )
Michael Hanus's avatar
Michael Hanus committed
690

Michael Hanus's avatar
Michael Hanus committed
691
-- Check if operating system executables we depend on are present on the
Michael Hanus's avatar
Michael Hanus committed
692
693
694
695
696
697
698
-- 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
699
700
701
702
    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
703
  debugMessage "All required executables found."
Michael Hanus's avatar
Michael Hanus committed
704
705
706
707
708
709
710
711
712
713
 where
  listOfExecutables = 
    [ "curl"  
    , "git"   
    , "unzip" 
    , "cp"
    , "rm"
    , "ln"
    , "readlink" ]

Michael Hanus's avatar
Michael Hanus committed
714
715
716
717
718
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
719
720
721
722
723
------------------------------------------------------------------------------
-- `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
724
    then getBaseRepository cfg >>= \repo ->
Michael Hanus's avatar
Michael Hanus committed
725
726
727
728
729
730
731
732
         readGlobalCache cfg repo |>= \gc ->
         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
733

Michael Hanus's avatar
Michael Hanus committed
734
735
736
------------------------------------------------------------------------------
-- `update` command:
updateCmd :: Config -> IO (ErrorLogger ())
Michael Hanus's avatar
Michael Hanus committed
737
738
updateCmd cfg = checkRequiredExecutables >> updateRepository cfg

Michael Hanus's avatar
Michael Hanus committed
739
740
741
742
------------------------------------------------------------------------------
-- `deps` command:
depsCmd :: DepsOptions -> Config -> IO (ErrorLogger ())
depsCmd opts cfg =
Michael Hanus's avatar
Michael Hanus committed
743
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
744
745
746
  loadPackageSpec specDir |>= \pkg ->
  checkCompiler cfg pkg >>
  if depsPath opts -- show CURRYPATH only?
Michael Hanus's avatar
Michael Hanus committed
747
748
    then getCurryLoadPath cfg specDir |>= \loadpath ->
         putStrLn loadpath >> succeedIO ()
Michael Hanus's avatar
Michael Hanus committed
749
    else resolveDependencies cfg specDir |>= \result ->
Michael Hanus's avatar
Michael Hanus committed
750
         putStrLn (showResult result) >> succeedIO ()
Michael Hanus's avatar
Michael Hanus committed
751

Michael Hanus's avatar
Michael Hanus committed
752
753
------------------------------------------------------------------------------
-- `info` command:
Michael Hanus's avatar
Michael Hanus committed
754
755
756
757
infoCmd :: InfoOptions -> Config -> IO (ErrorLogger ())
infoCmd (InfoOptions Nothing (Just _) _ _) _ =
  failIO "Must specify package name"
infoCmd (InfoOptions Nothing Nothing allinfos plain) cfg =
Michael Hanus's avatar
Michael Hanus committed
758
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
759
760
761
762
763
  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
764
765
    [] -> packageNotFoundFailure pkgname
    ps -> case filter (isCompatibleToCompiler cfg) ps of
Michael Hanus's avatar
Michael Hanus committed
766
767
768
769
770
           [] -> 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 ->
Michael Hanus's avatar
Michael Hanus committed
771
772
773
774
775
                     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
Michael Hanus's avatar
Michael Hanus committed
776
    Just rp -> readPackageFromRepository cfg rp |>=  \p ->
Michael Hanus's avatar
Michael Hanus committed
777
               printInfo cfg allinfos plain p
Michael Hanus's avatar
Michael Hanus committed
778

Michael Hanus's avatar
Michael Hanus committed
779
780
781
782
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
783
784


Michael Hanus's avatar
Michael Hanus committed
785
786
------------------------------------------------------------------------------
-- `checkout` command:
Michael Hanus's avatar
Michael Hanus committed
787
788
789
checkoutCmd :: CheckoutOptions -> Config -> IO (ErrorLogger ())
checkoutCmd (CheckoutOptions pkgname Nothing pre) cfg =
 getRepoForPackages cfg [pkgname] >>= \repo ->
Michael Hanus's avatar
Michael Hanus committed
790
791
792
 case findAllVersions repo pkgname pre of
  [] -> packageNotFoundFailure pkgname
  ps -> case filter (isCompatibleToCompiler cfg) ps of
Michael Hanus's avatar
Michael Hanus committed
793
794
795
    []    -> compatPackageNotFoundFailure cfg pkgname useUpdateHelp
    (p:_) -> acquireAndInstallPackageWithDependencies cfg repo p |>
             checkoutPackage cfg p
Michael Hanus's avatar
Michael Hanus committed
796
797
798
799
checkoutCmd (CheckoutOptions pkgname (Just ver) _) cfg =
 getRepoForPackages cfg [pkgname] >>= \repo ->
 case findVersion repo pkgname ver of
  Nothing -> packageNotFoundFailure $ pkgname ++ "-" ++ showVersion ver
Michael Hanus's avatar
Michael Hanus committed
800
801
  Just  p -> acquireAndInstallPackageWithDependencies cfg repo p |>
             checkoutPackage cfg p
Michael Hanus's avatar
Michael Hanus committed
802

Michael Hanus's avatar
Michael Hanus committed
803
804
installCmd :: InstallOptions -> Config -> IO (ErrorLogger ())
installCmd (InstallOptions Nothing Nothing _ instexec False) cfg =
Michael Hanus's avatar
Michael Hanus committed
805
  getLocalPackageSpec cfg "." |>= \pkgdir ->
Michael Hanus's avatar
Michael Hanus committed
806
  cleanCurryPathCache pkgdir |>
Michael Hanus's avatar
Michael Hanus committed
807
  installLocalDependencies cfg pkgdir |>= \ (pkg,_) ->
Michael Hanus's avatar
Michael Hanus committed
808
  saveBaseVersionToCache cfg pkgdir >>
Michael Hanus's avatar
Michael Hanus committed
809
810
  getCurryLoadPath cfg pkgdir |>= \currypath ->
  writePackageConfig cfg pkgdir pkg currypath |>
Michael Hanus's avatar
Michael Hanus committed
811
  if instexec then installExecutable cfg pkg else succeedIO ()
Michael Hanus's avatar
Michael Hanus committed
812
-- Install executable only:
Michael Hanus's avatar
Michael Hanus committed
813
installCmd (InstallOptions Nothing Nothing _ _ True) cfg =
Michael Hanus's avatar
Michael Hanus committed
814
  getLocalPackageSpec cfg "." |>= \pkgdir ->
Michael Hanus's avatar
Michael Hanus committed
815
  loadPackageSpec pkgdir |>= \pkg ->
Michael Hanus's avatar
Michael Hanus committed
816
  installExecutable cfg pkg
Michael Hanus's avatar
Michael Hanus committed
817
installCmd (InstallOptions (Just pkg) vers pre _ _) cfg = do
Michael Hanus's avatar
Michael Hanus committed
818
819
820
  fileExists <- doesFileExist pkg
  if fileExists
    then installFromZip cfg pkg
Michael Hanus's avatar
Michael Hanus committed
821
822
    else installapp (CheckoutOptions pkg vers pre) cfg
installCmd (InstallOptions Nothing (Just _) _ _ _) _ =
Michael Hanus's avatar
Michael Hanus committed
823
824
  failIO "Must specify package name"

Michael Hanus's avatar
Michael Hanus committed
825
--- Installs the application (i.e., binary) provided by a package.
Michael Hanus's avatar
Michael Hanus committed
826
827
--- This is done by checking out the package into CPM's application packages
--- cache (default: $HOME/.cpm/app_packages, see APP_PACKAGE_PATH
828
829
--- in .cpmrc configuration file) and then install this package.
---
Michael Hanus's avatar
Michael Hanus committed
830
--- Internal note: the installed package should not be cleaned or removed
831
832
--- 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
833
834
installapp :: CheckoutOptions -> Config -> IO (ErrorLogger ())
installapp opts cfg = do
Michael Hanus's avatar
Michael Hanus committed
835
836
837
  let apppkgdir = appPackageDir cfg
      copkgdir  = apppkgdir </> coPackage opts
  curdir <- getCurrentDirectory
Michael Hanus's avatar
Michael Hanus committed
838
  removeDirectoryComplete copkgdir
Michael Hanus's avatar
Michael Hanus committed
839
840
  debugMessage ("Change into directory " ++ apppkgdir)
  inDirectory apppkgdir
Michael Hanus's avatar
Michael Hanus committed
841
    ( checkoutCmd opts cfg |>
Michael Hanus's avatar
Michael Hanus committed
842
843
844
845
846
847
848
      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
849
            (\_ -> installCmd (InstallOptions Nothing Nothing False True False)
Michael Hanus's avatar
Michael Hanus committed
850
                              cfg)
Michael Hanus's avatar
Michael Hanus committed
851
852
            (executableSpec pkg)
    )
Michael Hanus's avatar
Michael Hanus committed
853

854
855
856
857
--- Checks the compiler compatibility.
checkCompiler :: Config -> Package -> IO ()
checkCompiler cfg pkg =
  unless (isCompatibleToCompiler cfg pkg)
Michael Hanus's avatar
Michael Hanus committed
858
859
    (error $ "Current compiler '" ++ showCompilerVersion cfg ++
             "' incompatible to package specification!")
860

Michael Hanus's avatar
Michael Hanus committed
861
862
--- Installs the executable specified in the package in the
--- bin directory of CPM (compare .cpmrc).
Michael Hanus's avatar
Michael Hanus committed
863
864
installExecutable :: Config -> Package -> IO (ErrorLogger ())
installExecutable cfg pkg =
865
  checkCompiler cfg pkg >>
Michael Hanus's avatar
Michael Hanus committed
866
  maybe (succeedIO ())
Michael Hanus's avatar
Michael Hanus committed
867
        (\ (PackageExecutable name mainmod eopts) ->
Michael Hanus's avatar
Michael Hanus committed
868
869
870
           getLogLevel >>= \lvl ->
           getEnviron "PATH" >>= \path ->
           log Info ("Compiling main module: " ++ mainmod) |>
Michael Hanus's avatar
Michael Hanus committed
871
872
873
874
875
           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
876
877
               bindir     = binInstallDir cfg
               binexec    = bindir </> name
Michael Hanus's avatar
Michael Hanus committed
878
           in compiler (ExecOptions cmd) cfg |>
Michael Hanus's avatar
Michael Hanus committed
879
880
881
              log Info ("Installing executable '" ++ name ++ "' into '" ++
                        bindir ++ "'") |>
              (whenFileExists binexec (backupExistingBin binexec) >>
Michael Hanus's avatar
Michael Hanus committed
882
               -- renaming might not work across file systems, hence we move:
Michael Hanus's avatar
Michael Hanus committed
883
               showExecCmd (unwords ["mv", mainmod, binexec]) >>
Michael Hanus's avatar
Michael Hanus committed
884
885
886
887
888
               checkPath path bindir))
        (executableSpec pkg)
 where
  backupExistingBin binexec = do
    let binexecbak = binexec ++ ".bak"
Michael Hanus's avatar
Michael Hanus committed
889
    showExecCmd $ "rm -f " ++ binexecbak
Michael Hanus's avatar
Michael Hanus committed
890
891
892
893
894
895
896
897
898
899
    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
900
901
902
uninstall :: UninstallOptions -> Config -> IO (ErrorLogger ())
uninstall (UninstallOptions (Just pkgname) (Just ver)) cfg =
  uninstallPackage cfg pkgname ver
Michael Hanus's avatar
Michael Hanus committed
903
--- uninstalls an application (i.e., binary) provided by a package:
Michael Hanus's avatar
Michael Hanus committed
904
uninstall (UninstallOptions (Just pkgname) Nothing) cfg = do
Michael Hanus's avatar
Michael Hanus committed
905
906
907
908
909
910
911
912
  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
913
uninstall (UninstallOptions Nothing (Just _)) _ =
Michael Hanus's avatar
Michael Hanus committed
914
  log Error "Please provide a package and version number!"
Michael Hanus's avatar
Michael Hanus committed
915
uninstall (UninstallOptions Nothing Nothing) cfg =
Michael Hanus's avatar
Michael Hanus committed
916
  getLocalPackageSpec cfg "." |>= \pkgdir ->
Michael Hanus's avatar
Michael Hanus committed
917
918
919
920
  loadPackageSpec pkgdir |>= uninstallPackageExecutable cfg

uninstallPackageExecutable :: Config -> Package -> IO (ErrorLogger ())
uninstallPackageExecutable cfg pkg =
Michael Hanus's avatar
Michael Hanus committed
921
  maybe (succeedIO ())
Michael Hanus's avatar
Michael Hanus committed
922
        (\ (PackageExecutable name _ _) ->
Michael Hanus's avatar
Michael Hanus committed
923
924
925
926
927
928
929
930
931
           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
932
  Nothing -> packageNotFoundFailure $ pkg ++ "-" ++ showVersion ver
Michael Hanus's avatar
Michael Hanus committed
933
934
  Just  p -> succeedIO $ p

Michael Hanus's avatar
Michael Hanus committed
935
936
--- Lists all (compiler-compatible if `lall` is false) packages
--- in the given repository.
Michael Hanus's avatar
Michael Hanus committed
937
938
939
940
941
942
943
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
944
 where
945
  -- all packages (and versions if `lv`)
Michael Hanus's avatar
Michael Hanus committed
946
947
948
  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
949

950
  -- all categories together with their package names:
Michael Hanus's avatar
Michael Hanus committed
951
  catgroups repo =
Michael Hanus's avatar
Michael Hanus committed
952
    let pkgid p = name p ++ '-' : showVersionIfCompatible cfg p
Michael Hanus's avatar
Michael Hanus committed
953
        newpkgs = map (filterCompatPkgs cfg) (listPackages repo)
Michael Hanus's avatar
Michael Hanus committed
954
955
956
        catpkgs = concatMap (\p -> map (\c -> (c, pkgid p)) (category p))
                            newpkgs
        nocatps = map pkgid (filter (null . category) newpkgs)
957
958
959
960
961
962
    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
963
    let (colsizes,rows) = packageVersionAsTable cfg pkgs
Michael Hanus's avatar
Michael Hanus committed
964
    in renderTable colsizes rows
965
966

  renderCats catgrps =
Michael Hanus's avatar
Michael Hanus committed
967
    let namelen = foldl max 8 $ map (length . fst) catgrps
968
969
        header = [ ["Category", "Packages"]
                 , ["--------", "--------"]]
Michael Hanus's avatar
Michael Hanus committed
970
        rows   = header ++ map (\ (c,ns) -> [c, unwords ns]) catgrps
Michael Hanus's avatar
Michael Hanus committed
971
    in renderTable [namelen + 2, 78 - namelen] rows
972
  
Michael Hanus's avatar
Michael Hanus committed
973
974
  renderTable colsizes rows =
    if csv then showCSV (head rows : drop 2 rows)
Michael Hanus's avatar
Michael Hanus committed
975
           else unlines [render (table rows colsizes), cpmInfo, useUpdateHelp]
Michael Hanus's avatar
Michael Hanus committed
976

Michael Hanus's avatar
Michael Hanus committed
977
978
979
980
981
982
983
984
--- 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
985
986
-- 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
987
988
packageVersionAsTable :: Config -> [Package] -> ([Int],[[String]])
packageVersionAsTable cfg pkgs = (colsizes, rows)
Michael Hanus's avatar
Michael Hanus committed
989
 where
Michael Hanus's avatar
Michael Hanus committed
990
  namelen = foldl max 4 $ map (length . name) pkgs
Michael Hanus's avatar
Michael Hanus committed
991
  colsizes = [namelen + 2, 68 - namelen, 10]
Michael Hanus's avatar
Michael Hanus committed
992
993
994
  header  = [ ["Name", "Synopsis", "Version"]
            , ["----", "--------", "-------"]]
  rows    = header ++ map formatPkg pkgs
Michael Hanus's avatar
Michael Hanus committed
995
996
997
  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
998
--- current compiler, otherwise shows the version in brackets.
Michael Hanus's avatar
Michael Hanus committed
999
1000
showVersionIfCompatible :: Config -> Package -> String
showVersionIfCompatible cfg p =
Michael Hanus's avatar
Michael Hanus committed
1001
1002
  let s = showVersion (version p)
  in if isCompatibleToCompiler cfg p then s else '(' : s ++ ")"
Michael Hanus's avatar
Michael Hanus committed
1003

Michael Hanus's avatar
Michael Hanus committed
1004
cpmInfo :: String
Michael Hanus's avatar
Michael Hanus committed
1005
cpmInfo = "Use 'cypm info PACKAGE' for more information about a package."
Michael Hanus's avatar
Michael Hanus committed
1006
1007


Michael Hanus's avatar
Michael Hanus committed
1008
--- Search in all (compiler-compatible) packages in the given repository.
Michael Hanus's avatar
Michael Hanus committed
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
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
1026

Michael Hanus's avatar
Michael Hanus committed
1027
1028

--- `upgrade` command.
Michael Hanus's avatar
Michael Hanus committed
1029
1030
upgradeCmd :: UpgradeOptions -> Config -> IO (ErrorLogger ())
upgradeCmd (UpgradeOptions Nothing) cfg =
Michael Hanus's avatar
Michael Hanus committed
1031
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
1032
1033
  cleanCurryPathCache specDir |>
  log Info "Upgrading all packages" |>
Michael Hanus's avatar
Michael Hanus committed
1034
1035
  upgradeAllPackages cfg specDir
upgradeCmd (UpgradeOptions (Just pkg)) cfg =
Michael Hanus's avatar
Michael Hanus committed
1036
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
1037
  log Info ("Upgrade " ++ pkg) |>
Michael Hanus's avatar
Michael Hanus committed
1038
  upgradeSinglePackage cfg specDir pkg
Michael Hanus's avatar
Michael Hanus committed
1039
1040


Michael Hanus's avatar
Michael Hanus committed
1041
--- `link` command.
Michael Hanus's avatar
Michael Hanus committed
1042
linkCmd :: LinkOptions -> Config -> IO (ErrorLogger ())
Michael Hanus's avatar
Michael Hanus committed
1043
1044
linkCmd (LinkOptions src) cfg =
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
1045
  cleanCurryPathCache specDir |>
Michael Hanus's avatar
Michael Hanus committed
1046
  log Info ("Linking '" ++ src ++ "' into local package cache...") |>
Michael Hanus's avatar
Michael Hanus committed
1047
1048
  linkToLocalCache src specDir

Michael Hanus's avatar
Michael Hanus committed
1049
1050
--- `add` command:
--- Option `--package`: copy the given package to the repository index
Michael Hanus's avatar
Michael Hanus committed
1051
1052
--- and package installation directory so that it is available as
--- any other package.
Michael Hanus's avatar
Michael Hanus committed
1053
1054
--- Option `--dependency`: add the package name as a dependency to the
--- current package
Michael Hanus's avatar
Michael Hanus committed
1055
addCmd :: AddOptions -> Config -> IO (ErrorLogger ())
Michael Hanus's avatar
Michael Hanus committed
1056
addCmd (AddOptions addpkg adddep pkg force) config
Michael Hanus's avatar
Michael Hanus committed
1057
  | addpkg    = addPackageToRepository config pkg force True
Michael Hanus's avatar
Michael Hanus committed
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
  | 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
1068
1069
  getAllPackageVersions config pkgname False >>= \allpkgs ->
  case allpkgs of
Michael Hanus's avatar
Michael Hanus committed
1070
1071
    [] -> packageNotFoundFailure pkgname
    ps -> case filter (isCompatibleToCompiler config) ps of
Michael Hanus's avatar
Michael Hanus committed
1072
             []    -> compatPackageNotFoundFailure config pkgname useUpdateHelp
Michael Hanus's avatar
Michael Hanus committed
1073
1074
             (p:_) -> getLocalPackageSpec config "." |>=
                      addDepToLocalPackage (version p)
Michael Hanus's avatar
Michael Hanus committed
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
 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
1085
                        "' added to package '" ++ pkgdir ++ "'")
Michael Hanus's avatar
Michael Hanus committed
1086
1087
1088
1089
1090
1091
1092
         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
1093

Michael Hanus's avatar
Michael Hanus committed
1094
------------------------------------------------------------------------------
1095
1096
1097
1098
--- `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
1099
1100
docCmd :: DocOptions -> Config -> IO (ErrorLogger ())
docCmd opts cfg =
Michael Hanus's avatar
Michael Hanus committed
1101
  getLocalPackageSpec cfg "." |>= \specDir ->
1102
  loadPackageSpec specDir |>= \pkg -> do
Michael Hanus's avatar
Michael Hanus committed
1103
  let docdir = maybe "cdoc" id (docDir opts) </> packageId pkg
Michael Hanus's avatar
Michael Hanus committed
1104
1105
  absdocdir <- getAbsolutePath docdir
  createDirectoryIfMissing True absdocdir
Michael Hanus's avatar
Michael Hanus committed
1106
  (if docManual opts then genPackageManual opts cfg pkg absdocdir
Michael Hanus's avatar
Michael Hanus committed
1107
                     else succeedIO ()) |>
Michael Hanus's avatar
Michael Hanus committed
1108
    (if docPrograms opts then genDocForPrograms opts cfg absdocdir specDir pkg
Michael Hanus's avatar
Michael Hanus committed
1109
1110
1111
                         else succeedIO ())

--- Generate manual according to  documentation specification of package.
Michael Hanus's avatar
Michael Hanus committed
1112
1113
1114
genPackageManual :: DocOptions -> Config -> Package -> String
                 -> IO (ErrorLogger ())
genPackageManual _ _ pkg outputdir = case documentation pkg of
Michael Hanus's avatar
Michael Hanus committed
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
    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
          inDirectory docdir $ system formatcmd
          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
1144
 where
Michael Hanus's avatar
Michael Hanus committed
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
  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
1158
genDocForPrograms :: DocOptions -> Config -> String -> String -> Package
Michael Hanus's avatar
Michael Hanus committed
1159
                  -> IO (ErrorLogger ())
Michael Hanus's avatar
Michael Hanus committed
1160
1161
genDocForPrograms opts cfg docdir specDir pkg = do
  abspkgdir <- getAbsolutePath specDir
Michael Hanus's avatar
Michael Hanus committed
1162
  checkCompiler cfg pkg
Michael Hanus's avatar
Michael Hanus committed
1163
  let exports = exportedModules pkg
Michael Hanus's avatar
Michael Hanus committed
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
      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
1177
    then log Info "No modules to be documented!"
Michael Hanus's avatar
Michael Hanus committed
1178
    else
Michael Hanus's avatar
Michael Hanus committed
1179
      getCurryLoadPath cfg specDir |>= \currypath ->
Michael Hanus's avatar
Michael Hanus committed
1180
      let pkgurls = path2packages abspkgdir currypath in
Michael Hanus's avatar
Michael Hanus committed
1181
      if apidoc
Michael Hanus's avatar
Michael Hanus committed
1182
1183
1184
1185
        then foldEL (\_ -> docModule currypath pkgurls) () docmods |>
             runDocCmd currypath pkgurls
                       (["--title", apititle, "--onlyindexhtml", docdir]
                        ++ docmods) |>
Michael Hanus's avatar
Michael Hanus committed
1186
             log Info ("Documentation generated in '"++docdir++"'")
Michael Hanus's avatar
Michael Hanus committed
1187
        else runDocCmd currypath pkgurls [docdir, head docmods]
Michael Hanus's avatar
Michael Hanus committed
1188
1189
 where
  apititle = "\"API Documentation of Package '" ++ name pkg ++ "'\""
Michael Hanus's avatar
Michael Hanus committed
1190

1191
1192
  currydoc = curryExec cfg ++ " doc"

Michael Hanus's avatar
Michael Hanus committed
1193
1194
  docModule currypath uses mod =
    runDocCmd currypath uses ["--noindexhtml", docdir, mod]
1195

Michael Hanus's avatar
Michael Hanus committed
1196
1197
1198
1199
1200
  runDocCmd currypath uses docparams = do
    let useopts = if docGenImports opts
                    then []
                    else map (\ (d,u) -> "--use "++d++"@"++u) uses
        cmd = unwords (currydoc : useopts ++ docparams)
1201
    infoMessage $ "Running CurryDoc: " ++ cmd
Michael Hanus's avatar
Michael Hanus committed
1202
1203
1204
1205
1206
1207
1208
1209
1210
    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)
Michael Hanus's avatar
Michael Hanus committed
1211
          in docPackageURL opts ++ "/" ++ d
Michael Hanus's avatar
Michael Hanus committed
1212
1213
1214
1215
    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
1216
                docPackageURL opts ++ "/base-" ++ compilerBaseVersion cfg)]
Michael Hanus's avatar
Michael Hanus committed
1217
1218

------------------------------------------------------------------------------
1219
1220
1221
--- `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
1222
1223
testCmd :: TestOptions -> Config -> IO (ErrorLogger ())
testCmd opts cfg =
Michael Hanus's avatar
Michael Hanus committed
1224
  getLocalPackageSpec cfg "." |>= \specDir ->
1225
1226
  loadPackageSpec specDir |>= \pkg -> do
    checkCompiler cfg pkg
Michael Hanus's avatar
Michael Hanus committed
1227
1228
    aspecDir <- getAbsolutePath specDir
    mainprogs <- curryModulesInDir (aspecDir </> "src")
1229
    let tests = testsuites pkg mainprogs
Michael Hanus's avatar
Michael Hanus committed
1230
    if null tests
Michael Hanus's avatar
Michael Hanus committed
1231
      then log Info "No modules to be tested!"
Michael Hanus's avatar
Michael Hanus committed
1232
1233
      else foldEL (\_ -> execTest aspecDir) () tests
 where
Michael Hanus's avatar
Michael Hanus committed
1234
1235
  currycheck = curryExec cfg ++ " check"
  
Michael Hanus's avatar
Michael Hanus committed
1236
  execTest apkgdir (PackageTest dir mods ccopts script) = do
1237
1238
    let scriptcmd = "CURRYBIN=" ++ curryExec cfg ++ " && export CURRYBIN && " ++
                    "." </> script ++ if null ccopts then "" else ' ' : ccopts
Michael Hanus's avatar
Michael Hanus committed
1239
1240
1241
1242
1243
1244
        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 $
1245
      "Executing test script with command:\n" ++ scriptcmd ++ "\n" ++
Michael Hanus's avatar
Michael Hanus committed
1246
      "(in directory '" ++ dir ++ "', showing raw output):\n"
Michael Hanus's avatar
Michael Hanus committed
1247
    let currysubdir = apkgdir </> addCurrySubdir dir
Michael Hanus's avatar
Michael Hanus committed
1248
1249
1250
        testcmd = if not (null mods)
                    then unwords (checkcmd : mods)
                    else scriptcmd
Michael Hanus's avatar
Michael Hanus committed
1251
    debugMessage $ "Removing directory: " ++ currysubdir
Michael Hanus's avatar
Michael Hanus committed
1252
    showExecCmd (unwords ["rm", "-rf", currysubdir])
Michael Hanus's avatar
Michael Hanus committed
1253
    inDirectory (apkgdir </> dir) $
Michael Hanus's avatar
Michael Hanus committed
1254
      execWithPkgDir (ExecOptions testcmd) cfg apkgdir
Michael Hanus's avatar
Michael Hanus committed
1255
1256
1257
1258
1259
1260

  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
1261
1262
                                  else [PackageTest "src" mainprogs "" ""]
                           else [PackageTest "src" exports "" ""])
Michael Hanus's avatar
Michael Hanus committed
1263
                     id
Michael Hanus's avatar
Michael Hanus committed
1264
                     (testSuite spec)
Michael Hanus's avatar
Michael Hanus committed
1265
    Just ms -> [PackageTest "src" ms "" ""]
Michael Hanus's avatar
Michael Hanus committed
1266

1267
--- Get the names of all Curry modules contained in a directory.
Michael Hanus's avatar
Michael Hanus committed
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
--- 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
1283
1284
diffCmd :: DiffOptions -> Config -> IO (ErrorLogger ())
diffCmd opts cfg =
Michael Hanus's avatar
Michael Hanus committed
1285
  getLocalPackageSpec cfg "." |>= \specDir ->
Michael Hanus's avatar
Michael Hanus committed
1286
  loadPackageSpec specDir     |>= \localSpec ->
Michael Hanus's avatar
Michael Hanus committed
1287
  checkCompiler cfg localSpec >>
Michael Hanus's avatar
Michael Hanus committed
1288
1289
1290
1291
  let localname  = name localSpec
      localv     = version localSpec
      showlocalv = showVersion localv
  in
Michael Hanus's avatar
Michael Hanus committed
1292
1293
1294
  getRepoForPackageSpec cfg localSpec >>= \repo ->
  readGlobalCache cfg repo |>= \gc ->
  getDiffVersion repo localname |>= \diffv ->
Michael Hanus's avatar
Michael Hanus committed
1295
1296
1297
1298
  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
1299
1300
         diffAPIIfEnabled      repo gc specDir localSpec diffv |> 
         diffBehaviorIfEnabled repo gc specDir localSpec diffv
Michael Hanus's avatar
Michael Hanus committed
1301
 where
Michael Hanus's avatar
Michael Hanus committed
1302
  getDiffVersion repo localname = case diffVersion opts of
1303
    Nothing -> case findLatestVersion cfg repo localname False of
Michael Hanus's avatar
Michael Hanus committed
1304
1305
1306
1307
1308
      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
1309
1310
    Just v  -> succeedIO v
 
Michael Hanus's avatar
Michael Hanus committed
1311
  diffAPIIfEnabled repo gc specDir localSpec diffversion =
Michael Hanus's avatar
Michael Hanus committed
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
    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
1323
  diffBehaviorIfEnabled repo gc specDir localSpec diffversion =
Michael Hanus's avatar
Michael Hanus committed
1324
1325
1326
1327
1328
1329
1330
1331
    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
1332
-- Implementation of the "curry" command.
Michael Hanus's avatar
Michael Hanus committed
1333
1334
compiler :: ExecOptions -> Config -> IO (ErrorLogger ())
compiler o cfg =
Michael Hanus's avatar
Michael Hanus committed
1335
  getLocalPackageSpec cfg "." |>= \pkgdir ->
Michael Hanus's avatar
Michael Hanus committed
1336
1337
  loadPackageSpec pkgdir |>= \pkg ->
  checkCompiler cfg pkg >>
Michael Hanus's avatar
Michael Hanus committed
1338
1339
  execWithPkgDir
    (ExecOptions $ unwords [curryExec cfg, "--nocypm", exeCommand o])
Michael Hanus's avatar
Michael Hanus committed
1340
    cfg pkgdir
Michael Hanus's avatar
Michael Hanus committed