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 ( stripCurrySuffix, addCurrySubdir )
Michael Hanus 's avatar
Michael Hanus committed
14
import Either
Michael Hanus 's avatar
Michael Hanus committed
15
import FilePath     ( (</>), splitSearchPath, replaceExtension, takeExtension )
Michael Hanus 's avatar
Michael Hanus committed
16
import IO           ( hFlush, stdout )
Michael Hanus 's avatar
Michael Hanus committed
17
import List         ( groupBy, intercalate, isSuffixOf, nub, split, splitOn )
Michael Hanus 's avatar
Michael Hanus committed
18
import Sort         ( sortBy )
Michael Hanus 's avatar
Michael Hanus committed
19
20
import System       ( getArgs, getEnviron, setEnviron, unsetEnviron, exitWith
                    , system )
Michael Hanus 's avatar
Michael Hanus committed
21

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

Michael Hanus 's avatar
Michael Hanus committed
26
27
import CPM.ErrorLogger
import CPM.FileUtil ( fileInPath, joinSearchPath, safeReadFile, whenFileExists
Michael Hanus 's avatar
Michael Hanus committed
28
                    , ifFileExists, inDirectory, removeDirectoryComplete
Michael Hanus 's avatar
Michael Hanus committed
29
                    , copyDirectory, quote )
Michael Hanus 's avatar
Michael Hanus committed
30
import CPM.Config   ( Config (..)
Michael Hanus 's avatar
Michael Hanus committed
31
32
                    , readConfigurationWith, showCompilerVersion
                    , showConfiguration )
Michael Hanus 's avatar
Michael Hanus committed
33
34
import CPM.PackageCache.Global ( GlobalCache, readInstalledPackagesFromDir
                               , installFromZip, checkoutPackage
Michael Hanus 's avatar
Michael Hanus committed
35
                               , uninstallPackage, isPackageInstalled )
Michael Hanus 's avatar
Michael Hanus committed
36
import CPM.Package
37
import CPM.Resolution ( isCompatibleToCompiler, showResult )
Michael Hanus 's avatar
Michael Hanus committed
38
import CPM.Repository ( Repository, readRepository, findVersion, listPackages
Michael Hanus 's avatar
Michael Hanus committed
39
                      , findAllVersions, findLatestVersion, updateRepository
Michael Hanus 's avatar
Michael Hanus committed
40
41
                      , searchPackages, updateRepositoryCache
                      , readPackageFromRepository )
Michael Hanus 's avatar
Michael Hanus committed
42
43
44
45
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
46
import CPM.ConfigPackage (packagePath)
Michael Hanus 's avatar
Michael Hanus committed
47
48
49
50
51
52

-- Banner of this tool:
cpmBanner :: String
cpmBanner = unlines [bannerLine,bannerText,bannerLine]
 where
 bannerText =
Michael Hanus 's avatar
Michael Hanus committed
53
  "Curry Package Manager <curry-language.org/tools/cpm> (version of 29/11/2017)"
Michael Hanus 's avatar
Michael Hanus committed
54
55
56
57
58
 bannerLine = take (length bannerText) (repeat '-')

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

runWithArgs :: Options -> IO ()
runWithArgs opts = do
Michael Hanus 's avatar
Michael Hanus committed
74
  setLogLevel $ optLogLevel opts
Michael Hanus 's avatar
Michael Hanus committed
75
  setWithShowTime (optWithTime opts)
Michael Hanus 's avatar
Michael Hanus committed
76
  debugMessage "Reading CPM configuration..."
Michael Hanus 's avatar
Michael Hanus committed
77
  config <- readConfigurationWith (optDefConfig opts) >>= \c ->
Michael Hanus 's avatar
Michael Hanus committed
78
79
80
81
   case c of
    Left err -> do putStrLn $ "Error reading .cpmrc settings: " ++ err
                   exitWith 1
    Right c' -> return c'
Michael Hanus 's avatar
Michael Hanus committed
82
  debugMessage (showConfiguration config)
Michael Hanus 's avatar
Michael Hanus committed
83
  let getRepoGC = readRepository config >>= \repo ->
Michael Hanus 's avatar
Michael Hanus committed
84
                  getGlobalCache config repo >>= \gc -> return (repo,gc)
Michael Hanus 's avatar
Michael Hanus committed
85
86
  (msgs, result) <- case optCommand opts of
    NoCommand   -> failIO "NoCommand"
Michael Hanus 's avatar
Michael Hanus committed
87
    Update      -> checkRequiredExecutables >> updateRepository config
Michael Hanus 's avatar
Michael Hanus committed
88
    Compiler o  -> compiler  o config getRepoGC
Michael Hanus 's avatar
Michael Hanus committed
89
    Exec o      -> execCmd   o config getRepoGC
Michael Hanus 's avatar
Michael Hanus committed
90
91
92
    Doc  o      -> docCmd    o config getRepoGC
    Test o      -> testCmd   o config getRepoGC
    Uninstall o -> uninstall o config getRepoGC
Michael Hanus 's avatar
Michael Hanus committed
93
    Deps o      -> depsCmd   o config getRepoGC
Michael Hanus 's avatar
Michael Hanus committed
94
    PkgInfo   o -> infoCmd   o config getRepoGC
Michael Hanus 's avatar
Michael Hanus committed
95
96
    Link o      -> linkCmd   o config
    Add  o      -> addCmd    o config
Michael Hanus 's avatar
Michael Hanus committed
97
    Clean       -> cleanPackage Info
Michael Hanus 's avatar
Michael Hanus committed
98
    New o       -> newPackage o
Michael Hanus 's avatar
Michael Hanus committed
99
    _ -> do repo <- readRepository config
Michael Hanus 's avatar
Michael Hanus committed
100
            case optCommand opts of
Michael Hanus 's avatar
Michael Hanus committed
101
102
              List   o -> listCmd    o config repo
              Search o -> searchCmd  o config repo
Michael Hanus 's avatar
Michael Hanus committed
103
              _ -> do globalCache <- getGlobalCache config repo
Michael Hanus 's avatar
Michael Hanus committed
104
                      case optCommand opts of
Michael Hanus 's avatar
Michael Hanus committed
105
                        Checkout   o -> checkout   o config repo globalCache
Michael Hanus 's avatar
Michael Hanus committed
106
                        InstallApp o -> installapp o config repo globalCache
Michael Hanus 's avatar
Michael Hanus committed
107
108
109
                        Install    o -> install    o config repo globalCache
                        Diff       o -> diff       o config repo globalCache
                        Upgrade    o -> upgrade    o config repo globalCache
Michael Hanus 's avatar
Michael Hanus committed
110
111
112
113
114
115
116
117
                        _ -> error "Internal command processing error!"
  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)

Michael Hanus 's avatar
Michael Hanus committed
118
119
120
getGlobalCache :: Config -> Repository -> IO GlobalCache
getGlobalCache config repo = do
  maybeGC <- readInstalledPackagesFromDir repo $ packageInstallDir config
Michael Hanus 's avatar
Michael Hanus committed
121
122
123
124
125
126
127
128
  case maybeGC of
    Left err -> do putStrLn $ "Error reading global package cache: " ++ err
                   exitWith 1
    Right gc -> return gc

data Options = Options
  { optLogLevel  :: LogLevel
  , optDefConfig :: [(String,String)]
Michael Hanus 's avatar
Michael Hanus committed
129
  , optWithTime  :: Bool
Michael Hanus 's avatar
Michael Hanus committed
130
131
132
  , optCommand   :: Command }

data Command 
Michael Hanus 's avatar
Michael Hanus committed
133
134
  = NoCommand
  | Deps       DepsOptions
Michael Hanus 's avatar
Michael Hanus committed
135
  | Checkout   CheckoutOptions
Michael Hanus 's avatar
Michael Hanus committed
136
  | InstallApp CheckoutOptions
Michael Hanus 's avatar
Michael Hanus committed
137
138
139
  | Install    InstallOptions
  | Uninstall  UninstallOptions
  | PkgInfo    InfoOptions
Michael Hanus 's avatar
Michael Hanus committed
140
  | Compiler   ExecOptions
Michael Hanus 's avatar
Michael Hanus committed
141
142
143
144
145
  | Update
  | List       ListOptions
  | Search     SearchOptions
  | Upgrade    UpgradeOptions
  | Link       LinkOptions
Michael Hanus 's avatar
Michael Hanus committed
146
  | Add        AddOptions
Michael Hanus 's avatar
Michael Hanus committed
147
  | Exec       ExecOptions
148
  | Doc        DocOptions
Michael Hanus 's avatar
Michael Hanus committed
149
150
  | Test       TestOptions
  | Diff       DiffOptions
Michael Hanus 's avatar
Michael Hanus committed
151
  | New        NewOptions
Michael Hanus 's avatar
Michael Hanus committed
152
  | Clean
Michael Hanus 's avatar
Michael Hanus committed
153

Michael Hanus 's avatar
Michael Hanus committed
154
155
156
157
data DepsOptions = DepsOptions
  { depsPath :: Bool  -- show CURRYPATH only?
  }

Michael Hanus 's avatar
Michael Hanus committed
158
159
160
161
162
163
164
165
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
166
  , instPrerelease :: Bool
Michael Hanus 's avatar
Michael Hanus committed
167
168
  , instExecutable :: Bool
  , instExecOnly   :: Bool }
Michael Hanus 's avatar
Michael Hanus committed
169
170
171
172
173
174
175
176

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
177
178
179
  , infoAll     :: Bool
  , infoPlain   :: Bool  -- plain output, no bold/color
  }
Michael Hanus 's avatar
Michael Hanus committed
180
181

data ListOptions = ListOptions
Michael Hanus 's avatar
Michael Hanus committed
182
  { listVers :: Bool   -- list all versions of each package
Michael Hanus 's avatar
Michael Hanus committed
183
184
  , listCSV  :: Bool   -- list in CSV format
  , listCat  :: Bool   -- list all categories
185
  }
Michael Hanus 's avatar
Michael Hanus committed
186
187

data SearchOptions = SearchOptions
Michael Hanus 's avatar
Michael Hanus committed
188
189
190
  { 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
191
  }
Michael Hanus 's avatar
Michael Hanus committed
192
193
194
195
196
197
198

data UpgradeOptions = UpgradeOptions
  { upgrTarget :: Maybe String }

data LinkOptions = LinkOptions
  { lnkSource :: String }

Michael Hanus 's avatar
Michael Hanus committed
199
data AddOptions = AddOptions
Michael Hanus 's avatar
Michael Hanus committed
200
201
202
203
  { addPackage    :: Bool
  , addDependency :: Bool
  , addSource     :: String
  , forceAdd      :: Bool
Michael Hanus 's avatar
Michael Hanus committed
204
205
  }

Michael Hanus 's avatar
Michael Hanus committed
206
207
208
data NewOptions = NewOptions
  { projectName :: String }

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

213
data DocOptions = DocOptions
Michael Hanus 's avatar
Michael Hanus committed
214
215
216
217
  { docDir      :: Maybe String    -- documentation directory
  , docModules  :: Maybe [String]  -- modules to be documented
  , docPrograms :: Bool            -- generate documentation for programs
  , docManual   :: Bool            -- generate manual (if specified)
218
219
  }

Michael Hanus 's avatar
Michael Hanus committed
220
221
222
223
224
225
226
227
228
229
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
230
231
232
233
234
depsOpts :: Options -> DepsOptions
depsOpts s = case optCommand s of
  Deps opts -> opts
  _         -> DepsOptions False

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

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

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

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

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

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

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

290
291
292
docOpts :: Options -> DocOptions
docOpts s = case optCommand s of
  Doc opts -> opts
Michael Hanus 's avatar
Michael Hanus committed
293
  _        -> DocOptions Nothing Nothing True True
294

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

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

applyEither :: [Options -> Either String Options] -> Options -> Either String Options
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
332
  defaultOpts = Options Info [] False NoCommand
Michael Hanus 's avatar
Michael Hanus committed
333
334
335
336
337
338

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

  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
486
487
    rest (\_ a -> Right $ a { optCommand = Compiler (execOpts a)
                                            { exeCommand = unwords remargs } })
Michael Hanus 's avatar
Michael Hanus committed
488
489
490
         (  metavar "ARGS"
         <> help "The options to pass to the compiler"
         <> optional )
Michael Hanus 's avatar
Michael Hanus committed
491
492
    where
     remargs = tail (snd (break (=="curry") allargs))
Michael Hanus 's avatar
Michael Hanus committed
493
494

  execArgs =
Michael Hanus 's avatar
Michael Hanus committed
495
496
    rest (\_ a -> Right $ a { optCommand = Exec (execOpts a)
                                            { exeCommand = unwords remargs } })
Michael Hanus 's avatar
Michael Hanus committed
497
         (  metavar "CMD"
Michael Hanus 's avatar
Michael Hanus committed
498
         <> help "The command to be executed."
Michael Hanus 's avatar
Michael Hanus committed
499
         <> optional )
Michael Hanus 's avatar
Michael Hanus committed
500
501
    where
     remargs = tail (snd (break (=="exec") allargs))
Michael Hanus 's avatar
Michael Hanus committed
502
503
504
505
506

  infoArgs =
        arg (\s a -> Right $ a { optCommand = PkgInfo (infoOpts a)
                                                { infoPackage = Just s } })
          (  metavar "PACKAGE"
Michael Hanus 's avatar
Michael Hanus committed
507
          <> help ("The package name. If no name is specified, CPM tries " ++
Michael Hanus 's avatar
Michael Hanus committed
508
509
510
511
512
513
514
                   "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
515
                   "CPM uses the latest version of the specified package.")
Michael Hanus 's avatar
Michael Hanus committed
516
517
518
519
520
          <> optional )
    <.> flag (\a -> Right $ a { optCommand = PkgInfo (infoOpts a)
                                               { infoAll = True } })
          (  short "a"
          <> long "all"
Michael Hanus 's avatar
Michael Hanus committed
521
522
523
524
525
526
          <> 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
527
528
          <> optional )

529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
  docArgs =
    option (\s a -> Right $ a { optCommand =
                                  Doc (docOpts a) { docDir = Just $ s } })
          (  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
544
545
546
547
548
549
550
551
552
553
554
555
    <.> 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 )
556

Michael Hanus 's avatar
Michael Hanus committed
557
558
559
560
561
562
563
564
565
566
567
568
569
  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
570
                    "CPM diffs against the latest repository version.")
Michael Hanus 's avatar
Michael Hanus committed
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
           <> 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
596
        flag (\a -> Right $ a { optCommand =
Michael Hanus 's avatar
Michael Hanus committed
597
598
599
                                  List (listOpts a) { listVers = True } })
          (  short "v"
          <> long "versions"
Michael Hanus 's avatar
Michael Hanus committed
600
          <> help "Show all versions" ) 
Michael Hanus 's avatar
Michael Hanus committed
601
602
    <.> flag (\a -> Right $ a { optCommand =
                                  List (listOpts a) { listCSV = True } })
Michael Hanus 's avatar
Michael Hanus committed
603
604
605
          (  short "t"
          <> long "csv"
          <> help "Show in CSV table format" )
Michael Hanus 's avatar
Michael Hanus committed
606
607
    <.> flag (\a -> Right $ a { optCommand =
                                  List (listOpts a) { listCat = True } })
Michael Hanus 's avatar
Michael Hanus committed
608
609
610
611
612
          (  short "c"
          <> long "category"
          <> help "Show all categories" )

  searchArgs =
Michael Hanus 's avatar
Michael Hanus committed
613
614
615
616
        flag (\a -> Right $ a { optCommand = Search (searchOpts a)
                                               { searchModule = True } })
             (  short "m"
             <> long "module"
Michael Hanus 's avatar
Michael Hanus committed
617
618
619
620
621
622
             <> 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
623
624
625
626
    <.> arg (\s a -> Right $ a { optCommand = Search (searchOpts a)
                                                { searchQuery = s } }) 
            (  metavar "QUERY"
            <> help "The search term" )
Michael Hanus 's avatar
Michael Hanus committed
627
628
629
630
631
632
633
634
635
636
637
638

  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
639

Michael Hanus 's avatar
Michael Hanus committed
640
641
  addArgs =
       flag (\a -> Right $ a { optCommand =
Michael Hanus 's avatar
Michael Hanus committed
642
643
644
645
646
647
648
649
650
651
                                 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
652
653
654
655
656
657
                                 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
658
659
           (  metavar "PACKAGE"
           <> help "The package directory or name to be added" )
Michael Hanus 's avatar
Michael Hanus committed
660

Michael Hanus 's avatar
Michael Hanus committed
661
-- Check if operating system executables we depend on are present on the
Michael Hanus 's avatar
Michael Hanus committed
662
663
664
665
666
667
668
669
670
671
672
673
-- 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
      putStrLn $ "The following programs could not be found on the PATH " ++
                 "(they are required for CPM to work):\n" ++
                 intercalate ", " missingExecutables
      exitWith 1
  debugMessage "All required executables found."
Michael Hanus 's avatar
Michael Hanus committed
674
675
676
677
678
679
680
681
682
683
 where
  listOfExecutables = 
    [ "curl"  
    , "git"   
    , "unzip" 
    , "cp"
    , "rm"
    , "ln"
    , "readlink" ]

Michael Hanus 's avatar
Michael Hanus committed
684
685
686
687
688
689
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
690
691
692
depsCmd :: DepsOptions -> Config -> IO (Repository,GlobalCache)
        -> IO (ErrorLogger ())
depsCmd opts cfg getRepoGC =
Michael Hanus 's avatar
Michael Hanus committed
693
  getLocalPackageSpec "." |>= \specDir ->
Michael Hanus 's avatar
Michael Hanus committed
694
695
696
  loadPackageSpec specDir |>= \pkg ->
  checkCompiler cfg pkg >>
  if depsPath opts -- show CURRYPATH only?
Michael Hanus 's avatar
Michael Hanus committed
697
    then loadCurryPathFromCache cfg specDir |>=
Michael Hanus 's avatar
Michael Hanus committed
698
699
700
701
702
703
         maybe (computePackageLoadPath cfg specDir getRepoGC)
               succeedIO |>= \currypath ->
         putStrLn currypath >> succeedIO ()
    else getRepoGC >>= \ (repo,gc) ->
         resolveDependencies cfg repo gc specDir |>= \result ->
         putStrLn (showResult result) >> succeedIO ()
Michael Hanus 's avatar
Michael Hanus committed
704

Michael Hanus 's avatar
Michael Hanus committed
705
706
707
------------------------------------------------------------------------------
-- `info` command:
infoCmd :: InfoOptions -> Config -> IO (Repository,GlobalCache)
Michael Hanus 's avatar
Michael Hanus committed
708
        -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
infoCmd opts cfg getRepoGC = case (infoPackage opts, infoVersion opts) of
  (Nothing, Just _) -> failIO "Must specify package name"
  (Nothing, Nothing) ->
     getLocalPackageSpec "." |>= \specDir ->
     loadPackageSpec specDir |>= \p -> 
     let allinfos = infoAll opts
     in if allinfos
          then getRepoGC >>= \ (_,gc) ->
               printInfo (infoAll opts) (infoPlain opts)
                         (Just (isPackageInstalled gc p)) p
          else printInfo (infoAll opts) (infoPlain opts) Nothing p
  (Just pkg, mbvers) ->
    getRepoGC >>= \ (repo,gc) ->
    infoCmdRepoGC pkg mbvers (infoAll opts) (infoPlain opts) cfg repo gc

infoCmdRepoGC :: String -> Maybe Version -> Bool -> Bool -> Config
              -> Repository -> GlobalCache -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
726
727
728
729
infoCmdRepoGC pkgname Nothing allinfos plain cfg repo gc =
  case findAllVersions repo pkgname False of
    [] -> packageNotFoundFailure pkgname
    ps -> case filter (isCompatibleToCompiler cfg) ps of
Michael Hanus 's avatar
Michael Hanus committed
730
731
732
733
734
735
736
           [] -> 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 allinfos plain (Just (isPackageInstalled gc p)) p
infoCmdRepoGC pkg (Just v) allinfos plain cfg repo gc =
Michael Hanus 's avatar
Michael Hanus committed
737
  case findVersion repo pkg v of
Michael Hanus 's avatar
Michael Hanus committed
738
    Nothing -> packageNotFoundFailure $ pkg ++ "-" ++ showVersion v
Michael Hanus 's avatar
Michael Hanus committed
739
740
    Just rp -> readPackageFromRepository cfg rp |>=  \p ->
               printInfo allinfos plain (Just (isPackageInstalled gc p)) p
Michael Hanus 's avatar
Michael Hanus committed
741
742

printInfo :: Bool -> Bool -> Maybe Bool -> Package
Michael Hanus 's avatar
Michael Hanus committed
743
          -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
744
745
printInfo allinfos plain mbinstalled pkg =
  putStrLn (renderPackageInfo allinfos plain mbinstalled pkg) >> succeedIO ()
Michael Hanus 's avatar
Michael Hanus committed
746
747


Michael Hanus 's avatar
Michael Hanus committed
748
749
------------------------------------------------------------------------------
-- `checkout` command:
Michael Hanus 's avatar
Michael Hanus committed
750
751
checkout :: CheckoutOptions -> Config -> Repository -> GlobalCache
         -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
752
753
754
755
756
757
checkout (CheckoutOptions pkgname Nothing pre) cfg repo gc =
 case findAllVersions repo pkgname pre of
  [] -> packageNotFoundFailure pkgname
  ps -> case filter (isCompatibleToCompiler cfg) ps of
    []    -> compatPackageNotFoundFailure cfg pkgname cpmUpdate
    (p:_) -> acquireAndInstallPackageWithDependencies cfg repo gc p |>
Michael Hanus 's avatar
Michael Hanus committed
758
759
760
             checkoutPackage cfg repo gc p
checkout (CheckoutOptions pkg (Just ver) _) cfg repo gc =
 case findVersion repo pkg ver of
Michael Hanus 's avatar
Michael Hanus committed
761
  Nothing -> packageNotFoundFailure $ pkg ++ "-" ++ showVersion ver
Michael Hanus 's avatar
Michael Hanus committed
762
763
764
  Just  p -> acquireAndInstallPackageWithDependencies cfg repo gc p |>
             checkoutPackage cfg repo gc p

Michael Hanus 's avatar
Michael Hanus committed
765
766
767
install :: InstallOptions -> Config -> Repository -> GlobalCache
        -> IO (ErrorLogger ())
install (InstallOptions Nothing Nothing _ instexec False) cfg repo gc =
Michael Hanus 's avatar
Michael Hanus committed
768
  getLocalPackageSpec "." |>= \pkgdir ->
Michael Hanus 's avatar
Michael Hanus committed
769
770
  cleanCurryPathCache pkgdir |>
  installLocalDependencies cfg repo gc pkgdir |>= \ (pkg,_) ->
Michael Hanus 's avatar
Michael Hanus committed
771
  saveBaseVersionToCache cfg pkgdir >>
Michael Hanus 's avatar
Michael Hanus committed
772
773
774
775
  writePackageConfig cfg pkgdir pkg |>
  if instexec then installExecutable cfg repo pkg else succeedIO ()
-- Install executable only:
install (InstallOptions Nothing Nothing _ _ True) cfg repo _ =
Michael Hanus 's avatar
Michael Hanus committed
776
  getLocalPackageSpec "." |>= \pkgdir ->
Michael Hanus 's avatar
Michael Hanus committed
777
778
779
780
781
782
783
784
785
786
  loadPackageSpec pkgdir |>= \pkg ->
  installExecutable cfg repo pkg
install (InstallOptions (Just pkg) vers pre _ _) cfg repo gc = do
  fileExists <- doesFileExist pkg
  if fileExists
    then installFromZip cfg pkg
    else installapp (CheckoutOptions pkg vers pre) cfg repo gc
install (InstallOptions Nothing (Just _) _ _ _) _ _ _ =
  failIO "Must specify package name"

Michael Hanus 's avatar
Michael Hanus committed
787
--- Installs the application (i.e., binary) provided by a package.
Michael Hanus 's avatar
Michael Hanus committed
788
789
--- This is done by checking out the package into CPM's application packages
--- cache (default: $HOME/.cpm/app_packages, see APP_PACKAGE_PATH
790
791
--- in .cpmrc configuration file) and then install this package.
---
Michael Hanus 's avatar
Michael Hanus committed
792
--- Internal note: the installed package should not be cleaned or removed
793
794
--- 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
795
installapp :: CheckoutOptions -> Config -> Repository -> GlobalCache
Michael Hanus 's avatar
Michael Hanus committed
796
           -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
797
installapp opts cfg repo gc = do
Michael Hanus 's avatar
Michael Hanus committed
798
799
800
  let apppkgdir = appPackageDir cfg
      copkgdir  = apppkgdir </> coPackage opts
  curdir <- getCurrentDirectory
Michael Hanus 's avatar
Michael Hanus committed
801
  removeDirectoryComplete copkgdir
Michael Hanus 's avatar
Michael Hanus committed
802
803
  debugMessage ("Change into directory " ++ apppkgdir)
  inDirectory apppkgdir
Michael Hanus 's avatar
Michael Hanus committed
804
805
806
807
808
809
810
811
812
813
814
815
    ( checkout opts cfg repo gc |>
      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."))
            (\_ -> install (InstallOptions Nothing Nothing False True False)
                           cfg repo gc)
            (executableSpec pkg)
    )
Michael Hanus 's avatar
Michael Hanus committed
816

817
818
819
820
--- Checks the compiler compatibility.
checkCompiler :: Config -> Package -> IO ()
checkCompiler cfg pkg =
  unless (isCompatibleToCompiler cfg pkg)
Michael Hanus 's avatar
Michael Hanus committed
821
822
    (error $ "Current compiler '" ++ showCompilerVersion cfg ++
             "' incompatible to package specification!")
823

Michael Hanus 's avatar
Michael Hanus committed
824
825
--- Installs the executable specified in the package in the
--- bin directory of CPM (compare .cpmrc).
Michael Hanus 's avatar
Michael Hanus committed
826
827
installExecutable :: Config -> Repository -> Package -> IO (ErrorLogger ())
installExecutable cfg repo pkg =
828
  checkCompiler cfg pkg >>
Michael Hanus 's avatar
Michael Hanus committed
829
830
  -- we read the global cache again since it might be modified by
  -- the installation of the package:
Michael Hanus 's avatar
Michael Hanus committed
831
  getGlobalCache cfg repo >>= \gc ->
Michael Hanus 's avatar
Michael Hanus committed
832
  maybe (succeedIO ())
Michael Hanus 's avatar
Michael Hanus committed
833
        (\ (PackageExecutable name mainmod eopts) ->
Michael Hanus 's avatar
Michael Hanus committed
834
835
836
           getLogLevel >>= \lvl ->
           getEnviron "PATH" >>= \path ->
           log Info ("Compiling main module: " ++ mainmod) |>
Michael Hanus 's avatar
Michael Hanus committed
837
838
839
840
841
           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
842
843
               bindir     = binInstallDir cfg
               binexec    = bindir </> name
Michael Hanus 's avatar
Michael Hanus committed
844
           in compiler (ExecOptions cmd)
Michael Hanus 's avatar
Michael Hanus committed
845
                       cfg (return (repo,gc)) |>
Michael Hanus 's avatar
Michael Hanus committed
846
847
848
              log Info ("Installing executable '" ++ name ++ "' into '" ++
                        bindir ++ "'") |>
              (whenFileExists binexec (backupExistingBin binexec) >>
Michael Hanus 's avatar
Michael Hanus committed
849
               -- renaming might not work across file systems, hence we move:
Michael Hanus 's avatar
Michael Hanus committed
850
               showExecCmd (unwords ["mv", mainmod, binexec]) >>
Michael Hanus 's avatar
Michael Hanus committed
851
852
853
854
855
               checkPath path bindir))
        (executableSpec pkg)
 where
  backupExistingBin binexec = do
    let binexecbak = binexec ++ ".bak"
Michael Hanus 's avatar
Michael Hanus committed
856
    showExecCmd $ "rm -f " ++ binexecbak
Michael Hanus 's avatar
Michael Hanus committed
857
858
859
860
861
862
863
864
865
866
    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
867
uninstall :: UninstallOptions -> Config -> IO (Repository,GlobalCache)
Michael Hanus 's avatar
Michael Hanus committed
868
          -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
869
870
871
872
873
874
875
876
877
878
879
880
881
uninstall (UninstallOptions (Just pkgname) (Just ver)) cfg getRepoGC =
  getRepoGC >>= \ (repo,gc) -> uninstallPackage cfg repo gc pkgname ver
--- uninstalls an application (i.e., binary) provided by a package:
uninstall (UninstallOptions (Just pkgname) Nothing) cfg _ = do
  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."
uninstall (UninstallOptions Nothing (Just _)) _ _ =
Michael Hanus 's avatar
Michael Hanus committed
882
  log Error "Please provide a package and version number!"
Michael Hanus 's avatar
Michael Hanus committed
883
uninstall (UninstallOptions Nothing Nothing) cfg _ =
Michael Hanus 's avatar
Michael Hanus committed
884
  getLocalPackageSpec "." |>= \pkgdir ->
Michael Hanus 's avatar
Michael Hanus committed
885
886
887
888
  loadPackageSpec pkgdir |>= uninstallPackageExecutable cfg

uninstallPackageExecutable :: Config -> Package -> IO (ErrorLogger ())
uninstallPackageExecutable cfg pkg =
Michael Hanus 's avatar
Michael Hanus committed
889
  maybe (succeedIO ())
Michael Hanus 's avatar
Michael Hanus committed
890
        (\ (PackageExecutable name _ _) ->
Michael Hanus 's avatar
Michael Hanus committed
891
892
893
894
895
896
897
898
899
           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
900
  Nothing -> packageNotFoundFailure $ pkg ++ "-" ++ showVersion ver
Michael Hanus 's avatar
Michael Hanus committed
901
902
  Just  p -> succeedIO $ p

Michael Hanus 's avatar
Michael Hanus committed
903
904
--- Lists all (compiler-compatible if `lall` is false) packages
--- in the given repository.
Michael Hanus 's avatar
Michael Hanus committed
905
listCmd :: ListOptions -> Config -> Repository -> IO (ErrorLogger ())
906
listCmd (ListOptions lv csv cat) cfg repo =
Michael Hanus 's avatar
Michael Hanus committed
907
  let listresult = if cat then renderCats catgroups
908
                          else renderPkgs allpkgs
Michael Hanus 's avatar
Michael Hanus committed
909
  in putStr listresult >> succeedIO ()
Michael Hanus 's avatar
Michael Hanus committed
910
 where
911
  -- all packages (and versions if `lv`)
Michael Hanus 's avatar
Michael Hanus committed
912
  allpkgs = concatMap (if lv then id else ((:[]) . filterCompatPkgs cfg))
Michael Hanus 's avatar
Michael Hanus committed
913
                      (sortBy (\ps1 ps2 -> name (head ps1) <= name (head ps2))
Michael Hanus 's avatar
Michael Hanus committed
914
                              (listPackages repo))
Michael Hanus 's avatar
Michael Hanus committed
915

916
917
  -- all categories together with their package names:
  catgroups =
Michael Hanus 's avatar
Michael Hanus committed
918
    let pkgid p = name p ++ '-' : showVersionIfCompatible cfg p
Michael Hanus 's avatar
Michael Hanus committed
919
        newpkgs = map (filterCompatPkgs cfg) (listPackages repo)
Michael Hanus 's avatar
Michael Hanus committed
920
921
922
        catpkgs = concatMap (\p -> map (\c -> (c, pkgid p)) (category p))
                            newpkgs
        nocatps = map pkgid (filter (null . category) newpkgs)
923
924
925
926
927
928
    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
929
    let (colsizes,rows) = packageVersionAsTable cfg pkgs
Michael Hanus 's avatar
Michael Hanus committed
930
    in renderTable colsizes rows
931
932

  renderCats catgrps =
Michael Hanus 's avatar
Michael Hanus committed
933
    let namelen = foldl max 8 $ map (length . fst) catgrps
934
935
        header = [ ["Category", "Packages"]
                 , ["--------", "--------"]]
Michael Hanus 's avatar
Michael Hanus committed
936
        rows   = header ++ map (\ (c,ns) -> [c, unwords ns]) catgrps
Michael Hanus 's avatar
Michael Hanus committed
937
    in renderTable [namelen + 2, 78 - namelen] rows
938
  
Michael Hanus 's avatar
Michael Hanus committed
939
940
941
942
  renderTable colsizes rows =
    if csv then showCSV (head rows : drop 2 rows)
           else unlines [render (table rows colsizes), cpmInfo, cpmUpdate]

Michael Hanus 's avatar
Michael Hanus committed
943
944
945
946
947
948
949
950
--- 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
951
952
-- 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
953
954
packageVersionAsTable :: Config -> [Package] -> ([Int],[[String]])
packageVersionAsTable cfg pkgs = (colsizes, rows)
Michael Hanus 's avatar
Michael Hanus committed
955
 where
Michael Hanus 's avatar
Michael Hanus committed
956
  namelen = foldl max 4 $ map (length . name) pkgs
Michael Hanus 's avatar
Michael Hanus committed
957
  colsizes = [namelen + 2, 68 - namelen, 10]
Michael Hanus 's avatar
Michael Hanus committed
958
959
960
  header  = [ ["Name", "Synopsis", "Version"]
            , ["----", "--------", "-------"]]
  rows    = header ++ map formatPkg pkgs
Michael Hanus 's avatar
Michael Hanus committed
961
962
963
  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
964
--- current compiler, otherwise shows the version in brackets.
Michael Hanus 's avatar
Michael Hanus committed
965
966
showVersionIfCompatible :: Config -> Package -> String
showVersionIfCompatible cfg p =
Michael Hanus 's avatar
Michael Hanus committed
967
968
  let s = showVersion (version p)
  in if isCompatibleToCompiler cfg p then s else '(' : s ++ ")"
Michael Hanus 's avatar
Michael Hanus committed
969

Michael Hanus 's avatar
Michael Hanus committed
970
cpmInfo :: String
Michael Hanus 's avatar
Michael Hanus committed
971
cpmInfo = "Use 'cypm info PACKAGE' for more information about a package."
Michael Hanus 's avatar
Michael Hanus committed
972

Michael Hanus 's avatar
Michael Hanus committed
973
cpmUpdate :: String
Michael Hanus 's avatar
Michael Hanus committed
974
cpmUpdate = "Use 'cypm update' to download the newest package index."
Michael Hanus 's avatar
Michael Hanus committed
975
976


Michael Hanus 's avatar
Michael Hanus committed
977
--- Search in all (compiler-compatible) packages in the given repository.
Michael Hanus 's avatar
Michael Hanus committed
978
979
980
searchCmd :: SearchOptions -> Config -> Repository -> IO (ErrorLogger ())
searchCmd (SearchOptions q smod sexec) cfg repo =
  putStr rendered >> succeedIO ()
Michael Hanus 's avatar
Michael Hanus committed
981
 where
Michael Hanus 's avatar
Michael Hanus committed
982
983
984
  results = sortBy (\p1 p2 -> name p1 <= name p2)
                   (map (filterCompatPkgs cfg)
                        (searchPackages repo smod sexec q))
Michael Hanus 's avatar
Michael Hanus committed
985
  (colsizes,rows) = packageVersionAsTable cfg results
Michael Hanus 's avatar
Michael Hanus committed
986
987
  rendered = unlines $
               if null results
Michael Hanus 's avatar
Michael Hanus committed
988
                 then ["No packages found for '" ++ q ++ "'", cpmUpdate]
Michael Hanus 's avatar
Michael Hanus committed
989
                 else [ render (table rows colsizes), cpmInfo, cpmUpdate ]
Michael Hanus 's avatar
Michael Hanus committed
990

Michael Hanus 's avatar
Michael Hanus committed
991
992

--- `upgrade` command.
Michael Hanus 's avatar
Michael Hanus committed
993
994
upgrade :: UpgradeOptions -> Config -> Repository -> GlobalCache
        -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
995
upgrade (UpgradeOptions Nothing) cfg repo gc =
Michael Hanus 's avatar
Michael Hanus committed
996
  getLocalPackageSpec "." |>= \specDir ->
Michael Hanus 's avatar
Michael Hanus committed
997
998
  cleanCurryPathCache specDir |>
  log Info "Upgrading all packages" |>
Michael Hanus 's avatar
Michael Hanus committed
999
1000
  upgradeAllPackages cfg repo gc specDir
upgrade (UpgradeOptions (Just pkg)) cfg repo gc =
Michael Hanus 's avatar
Michael Hanus committed
1001
  getLocalPackageSpec "." |>= \specDir ->
Michael Hanus 's avatar
Michael Hanus committed
1002
  log Info ("Upgrade " ++ pkg) |>
Michael Hanus 's avatar
Michael Hanus committed
1003
1004
1005
  upgradeSinglePackage cfg repo gc specDir pkg


Michael Hanus 's avatar
Michael Hanus committed
1006
--- `link` command.
Michael Hanus 's avatar
Michael Hanus committed
1007
1008
linkCmd :: LinkOptions -> Config -> IO (ErrorLogger ())
linkCmd (LinkOptions src) _ =
Michael Hanus 's avatar
Michael Hanus committed
1009
  getLocalPackageSpec "." |>= \specDir ->
Michael Hanus 's avatar
Michael Hanus committed
1010
  cleanCurryPathCache specDir |>
Michael Hanus 's avatar
Michael Hanus committed
1011
  log Info ("Linking '" ++ src ++ "' into local package cache...") |>
Michael Hanus 's avatar
Michael Hanus committed
1012
1013
  linkToLocalCache src specDir

Michael Hanus 's avatar
Michael Hanus committed
1014
1015
1016
1017
--- `add` command: copy the given package to the repository index
--- and package installation directory so that it is available as
--- any other package.
addCmd :: AddOptions -> Config -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
addCmd (AddOptions addpkg adddep pkg force) config
  | addpkg    = addPackageCmd    pkg force config
  | adddep    = addDependencyCmd pkg force config
  | otherwise = log Critical "Option --package or --dependency missing!"

--- `add --package` command: copy the given package to the repository index
--- and package installation directory so that it is available as
--- any other package.
addPackageCmd :: String -> Bool -> Config -> IO (ErrorLogger ())
addPackageCmd pkgdir force config = do
Michael Hanus 's avatar
Michael Hanus committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
  dirExists <- doesDirectoryExist pkgdir
  if dirExists
    then loadPackageSpec pkgdir |>= \pkgSpec ->
         (copyPackage pkgSpec >> succeedIO ()) |>
         log Info ("Package in directory '" ++ pkgdir ++
                   "' installed into local repository")
    else log Critical ("Directory '" ++ pkgdir ++ "' does not exist.") |>
         succeedIO ()
 where
  copyPackage pkg = do
    let pkgName          = name pkg
        pkgVersion       = version pkg
        pkgIndexDir      = pkgName </> showVersion pkgVersion
        pkgRepositoryDir = repositoryDir config </> pkgIndexDir
        pkgInstallDir    = packageInstallDir config </> packageId pkg
    exrepodir <- doesDirectoryExist pkgRepositoryDir
    when (exrepodir && not force) $ error $
      "Package repository directory '" ++
      pkgRepositoryDir ++ "' already exists!\n" ++ useForce
    expkgdir <- doesDirectoryExist pkgInstallDir
    when expkgdir $
      if force then removeDirectoryComplete pkgInstallDir
               else error $ "Package installation directory '" ++
                            pkgInstallDir ++ "' already exists!\n" ++ useForce
    infoMessage $ "Create directory: " ++ pkgRepositoryDir
    createDirectoryIfMissing True pkgRepositoryDir
    copyFile (pkgdir </> "package.json") (pkgRepositoryDir </> "package.json")
    copyDirectory pkgdir pkgInstallDir
    updateRepositoryCache config

Michael Hanus 's avatar
Michael Hanus committed
1058
1059
1060
1061
1062
1063
1064
1065
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 =
  readRepository config >>= \repo ->
Michael Hanus 's avatar
Michael Hanus committed
1066
1067
1068
1069
1070
1071
1072
  case findAllVersions repo pkgname False of
    [] -> packageNotFoundFailure pkgname
    ps -> case filter (isCompatibleToCompiler config) ps of
             []    -> compatPackageNotFoundFailure config pkgname cpmUpdate
             (p:_) -> searchLocalPackageSpec "." |>=
                      maybe (genNewLocalPackage (version p))
                            (addDepToLocalPackage (version p))
Michael Hanus 's avatar
Michael Hanus committed
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
 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 ++
                        "' added to current package specification")
         else log Critical ("Dependency '" ++ pkgname ++
                            "' already exists!\n" ++ useForce)

  genNewLocalPackage vers =
    let newpkg  = emptyPackage { name            = "PSEUDO_PACKAGE"
                               , version         = initialVersion
                               , author          = "NN"
                               , synopsis        = "UNKNOWN"
                               , dependencies    = addDep [[VGte vers]] []
                               }
    in writePackageSpec newpkg "package.json" |>>
       log Info ("New package specification 'package.json' with dependency '" ++
                 pkgname ++ " >= " ++ showVersion vers ++ "' generated")

  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
1102

Michael Hanus 's avatar
Michael Hanus committed
1103
------------------------------------------------------------------------------
1104
1105
1106
1107
--- `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
1108
docCmd :: DocOptions -> Config -> IO (Repository,GlobalCache)
1109
       -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
1110
docCmd opts cfg getRepoGC =
Michael Hanus 's avatar
Michael Hanus committed
1111
  getLocalPackageSpec "." |>= \specDir ->
1112
  loadPackageSpec specDir |>= \pkg -> do
Michael Hanus 's avatar
Michael Hanus committed
1113
1114
1115
  let docdir = maybe "cdoc" id (docDir opts)
  absdocdir <- getAbsolutePath docdir
  createDirectoryIfMissing True absdocdir
Michael Hanus 's avatar
Michael Hanus committed
1116
  (if docManual opts then genPackageManual opts cfg pkg absdocdir
Michael Hanus 's avatar
Michael Hanus committed
1117
1118
1119
1120
1121
                     else succeedIO ()) |>
    (if docPrograms opts then genDocForPrograms opts cfg getRepoGC specDir pkg
                         else succeedIO ())

--- Generate manual according to  documentation specification of package.
Michael Hanus 's avatar
Michael Hanus committed
1122
1123
1124
genPackageManual :: DocOptions -> Config -> Package -> String
                 -> IO (ErrorLogger ())
genPackageManual _ _ pkg outputdir = case documentation pkg of
Michael Hanus 's avatar
Michael Hanus committed
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
    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
1154
 where
Michael Hanus 's avatar
Michael Hanus committed
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
  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.
genDocForPrograms :: DocOptions -> Config -> IO (Repository,GlobalCache)
                  -> String -> Package -> IO (ErrorLogger ())
genDocForPrograms opts cfg getRepoGC specDir pkg = do
  checkCompiler cfg pkg
  let docdir  = maybe "cdoc" id (docDir opts)
      exports = exportedModules pkg
      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
    then putStrLn "No modules to be documented!" >> succeedIO ()
    else
      if apidoc
        then foldEL (\_ -> docModule specDir docdir) () docmods |>
             runDocCmd specDir
                       ([currydoc, "--title", apititle, "--onlyindexhtml",
                         docdir] ++ docmods) |>
             log Info ("Documentation generated in '"++docdir++"'")
        else runDocCmd specDir [currydoc, docdir, head docmods]
 where
  apititle = "\"API Documentation of Package '" ++ name pkg ++ "'\""
Michael Hanus 's avatar
Michael Hanus committed
1198

1199
1200
1201
1202
1203
1204
1205
1206
  currydoc = curryExec cfg ++ " doc"

  docModule pkgdir docdir mod =
    runDocCmd pkgdir [currydoc, "--noindexhtml", docdir, mod]

  runDocCmd pkgdir doccmd = do
    let cmd = unwords doccmd
    infoMessage $ "Running CurryDoc: " ++ cmd
Michael Hanus 's avatar
Michael Hanus committed
1207
    execWithPkgDir (ExecOptions cmd) cfg getRepoGC pkgdir
1208

Michael Hanus 's avatar
Michael Hanus committed
1209
1210

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

  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
1254
1255
                                  else [PackageTest "src" mainprogs "" ""]
                           else [PackageTest "src" exports "" ""])
Michael Hanus 's avatar
Michael Hanus committed
1256
                     id
Michael Hanus 's avatar
Michael Hanus committed
1257
                     (testSuite spec)
Michael Hanus 's avatar
Michael Hanus committed
1258
    Just ms -> [PackageTest "src" ms "" ""]
Michael Hanus 's avatar
Michael Hanus committed
1259

1260
--- Get the names of all Curry modules contained in a directory.
Michael Hanus 's avatar
Michael Hanus committed
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
--- 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


diff :: DiffOptions -> Config -> Repository -> GlobalCache
     -> IO (ErrorLogger ())
diff opts cfg repo gc =
Michael Hanus 's avatar
Michael Hanus committed
1279
  getLocalPackageSpec "." |>= \specDir ->
Michael Hanus 's avatar
Michael Hanus committed
1280
  loadPackageSpec specDir     |>= \localSpec ->
Michael Hanus 's avatar
Michael Hanus committed
1281
  checkCompiler cfg localSpec >>
Michael Hanus 's avatar
Michael Hanus committed
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
  let localname  = name localSpec
      localv     = version localSpec
      showlocalv = showVersion localv
  in
  getDiffVersion localname |>= \diffv ->
  if diffv == localv
    then failIO $ "Cannot diff identical package versions " ++ showlocalv
    else putStrLn ("Comparing local version " ++ showlocalv ++
                   " and repository version " ++ showVersion diffv ++ ":\n") >>
         diffAPIIfEnabled      specDir localSpec diffv |> 
         diffBehaviorIfEnabled specDir localSpec diffv
 where
  getDiffVersion localname = case diffVersion opts of
1295
    Nothing -> case findLatestVersion cfg repo localname False of
Michael Hanus 's avatar
Michael Hanus committed
1296
1297
1298
1299
1300
      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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
    Just v  -> succeedIO v
 
  diffAPIIfEnabled specDir localSpec diffversion =
    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 () 

  diffBehaviorIfEnabled specDir localSpec diffversion =
    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
1324
1325
1326
1327
1328
1329
1330
-- Implementation of the "curry" command.
compiler :: ExecOptions -> Config -> IO (Repository,GlobalCache)
         -> IO (ErrorLogger ())
compiler o cfg getRepoGC =
  getLocalPackageSpec "." |>= \pkgdir ->
  loadPackageSpec pkgdir |>= \pkg ->
  checkCompiler cfg pkg >>
Michael Hanus 's avatar
Michael Hanus committed
1331
1332
1333
  execWithPkgDir
    (ExecOptions $ unwords [curryExec cfg, "--nocypm", exeCommand o])
    cfg getRepoGC pkgdir
Michael Hanus 's avatar
Michael Hanus committed
1334

Michael Hanus 's avatar
Michael Hanus committed
1335
1336
1337
execCmd :: ExecOptions -> Config -> IO (Repository,GlobalCache)
        -> IO (ErrorLogger ())
execCmd o cfg getRepoGC =
Michael Hanus 's avatar
Michael Hanus committed
1338
  getLocalPackageSpec "." |>= execWithPkgDir o cfg getRepoGC
Michael Hanus 's avatar
Michael Hanus committed
1339

Michael Hanus 's avatar
Michael Hanus committed
1340
execWithPkgDir :: ExecOptions -> Config -> IO (Repository,GlobalCache)
Michael Hanus 's avatar
Michael Hanus committed
1341
               -> String -> IO (ErrorLogger ())
Michael Hanus 's avatar
Michael Hanus committed
1342
execWithPkgDir o cfg getRepoGC specDir =
Michael Hanus 's avatar
Michael Hanus committed
1343
  loadCurryPathFromCache cfg specDir |>=
Michael Hanus 's avatar
Michael Hanus committed
1344
1345
1346
1347
  maybe (computePackageLoadPath cfg specDir getRepoGC)
        succeedIO |>= \currypath ->
  log Debug ("Setting CURRYPATH to " ++ currypath) |>
  do setEnviron "CURRYPATH" currypath
Michael Hanus 's avatar
Michael Hanus committed
1348
     ecode <- showExecCmd (exeCommand o)
Michael Hanus 's avatar
Michael Hanus committed
1349
1350
1351
     unsetEnviron "CURRYPATH"
     unless (ecode==0) (exitWith ecode)
     succeedIO ()
Michael Hanus 's avatar
Michael Hanus committed
1352
1353
1354
1355

computePackageLoadPath :: Config -> String -> IO (Repository,GlobalCache)
                       -> IO (ErrorLogger String)
computePackageLoadPath cfg pkgdir getRepoGC =
Michael Hanus 's avatar
Michael Hanus committed
1356
  debugMessage "Computing load path for package..." >>
Michael Hanus 's avatar
Michael Hanus committed
1357
1358
  getRepoGC >>= \ (repo,gc) ->
  loadPackageSpec pkgdir |>= \pkg ->
Michael Hanus 's avatar
Michael Hanus committed
1359
1360
1361
  loadBaseVersionFromCache pkgdir >>= \cbv ->
  let cfg' = if null cbv then cfg else cfg { baseVersion = cbv } in
  resolveAndCopyDependenciesForPackage cfg' repo gc pkgdir pkg |>= \allpkgs ->
Michael Hanus 's avatar
Michael Hanus committed
1362
1363
  getAbsolutePath pkgdir >>= \abs -> succeedIO () |>
  let srcdirs = map (abs </>) (sourceDirsOf pkg)
Michael Hanus 's avatar
Michael Hanus committed
1364
1365
      -- remove 'base' package if it is the same as in current config:
      pkgs = filter notCurrentBase allpkgs
Michael Hanus 's avatar
Michael Hanus committed
1366
      currypath = joinSearchPath (srcdirs ++ dependencyPathsSeparate pkgs abs)
Michael Hanus 's avatar
Michael Hanus committed
1367
  in saveCurryPathToCache cfg' pkgdir currypath >> succeedIO currypath
Michael Hanus 's avatar
Michael Hanus committed
1368
1369
1370
 where
  notCurrentBase pkg = name pkg /= "base" ||
                       showVersion (version pkg) /= compilerBaseVersion cfg
Michael Hanus 's avatar
Michael Hanus committed
1371
1372
1373
1374

-- Clean auxiliary files in the current package
cleanPackage :: LogLevel -> IO (ErrorLogger ())
cleanPackage ll =
Michael Hanus 's avatar
Michael Hanus committed
1375
  getLocalPackageSpec "." |>= \specDir ->
Michael Hanus 's avatar
Michael Hanus committed
1376
1377
  loadPackageSpec specDir     |>= \pkg ->
  let dotcpm   = specDir </> ".cpm"
Michael Hanus 's avatar
Michael Hanus committed
1378
1379
1380
      srcdirs  = map (specDir </>) (sourceDirsOf pkg)
      testdirs = map (specDir </>)
                     (maybe []
Michael Hanus 's avatar
Michael Hanus committed
1381
                            (map (\ (PackageTest m _ _ _) -> m))
Michael Hanus 's avatar
Michael Hanus committed
1382
                            (testSuite pkg))
Michael Hanus 's avatar
Michael Hanus committed
1383
      rmdirs   = nub (dotcpm : map addCurrySubdir (srcdirs ++ testdirs))
Michael Hanus 's avatar
Michael Hanus committed
1384
  in log ll ("Removing directories: " ++ unwords rmdirs) |>
Michael Hanus 's avatar
Michael Hanus committed
1385
     (showExecCmd (unwords $ ["rm", "-rf"] ++ rmdirs) >> succeedIO ())
Michael Hanus 's avatar
Michael Hanus committed
1386

Michael Hanus 's avatar
Michael Hanus committed
1387
1388

--- Creates a new package.
Michael Hanus 's avatar
Michael Hanus committed
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
newPackage :: NewOptions -> IO (ErrorLogger ())
newPackage (NewOptions pname) = do
  exists <- doesDirectoryExist pname
  when exists $ do
    putStrLn $ "There is already a directory with the new project name. " ++
               "I cannot create new project!"
    exitWith 1
  let emptyAuthor   = "YOUR NAME <YOUR EMAIL ADDRESS>"
      emptySynopsis = "PLEASE PROVIDE A ONE-LINE SUMMARY ABOUT THE PACKAGE"
  createDirectory pname
  let pkgSpec = emptyPackage { name            = pname
                             , version         = initialVersion
                             , author          = emptyAuthor
                             , synopsis        = emptySynopsis
                             , category        = ["Programming"]
                             , dependencies    = [] 
Michael Hanus 's avatar
Michael Hanus committed
1405
                             , exportedModules = []
Michael Hanus 's avatar
Michael Hanus committed
1406
1407
                             , license         = Just "BSD-3-Clause"
                             , licenseFile     = Just "LICENSE"
Michael Hanus 's avatar
Michael Hanus committed
1408
                             }
Michael Hanus 's avatar
Michael Hanus committed
1409
1410
1411
1412
1413
1414
1415
  writePackageSpec pkgSpec (pname </> "package.json")
  copyFile (packagePath </> "templates" </> "LICENSE") (pname </> "LICENSE")
  createDirectory (pname </> "src")
  let cmain = "Main.curry"
  copyFile (packagePath </> "templates" </> cmain) (pname </> "src" </> cmain)
  writeFile (pname </> "README.md") readme
  putStr $ unlines todo
Michael Hanus 's avatar
Michael Hanus committed
1416
1417
  succeedIO ()
 where
Michael Hanus 's avatar
Michael Hanus committed
1418
1419
1420