Main.curry 39.7 KB
Newer Older
Michael Hanus's avatar
Michael Hanus committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
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
596
597
598
599
600
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
--------------------------------------------------------------------------------
--- This is the main module of the Curry Package Manager.
--------------------------------------------------------------------------------

module CPM.Main where

import CSV          ( showCSV )
import Directory    ( doesFileExist, getAbsolutePath, doesDirectoryExist
                    , createDirectory, createDirectoryIfMissing
                    , getDirectoryContents, getModificationTime
                    , renameFile, removeFile, setCurrentDirectory )
import Distribution ( installDir, stripCurrySuffix, addCurrySubdir
                    , curryCompiler )
import Either
import FilePath     ( (</>), splitSearchPath, takeExtension )
import IO           ( hFlush, stdout )
import List         ( intercalate, split, splitOn )
import Sort         ( sortBy )
import System       ( getArgs, getEnviron, setEnviron, system, unsetEnviron
                    , exitWith )

import Boxes (table, render)
import OptParse
import CPM.ErrorLogger
import CPM.FileUtil ( fileInPath, joinSearchPath, safeReadFile, whenFileExists
                    , ifFileExists, inDirectory, removeDirectoryComplete )
import CPM.Config              ( Config ( packageInstallDir, binInstallDir
                                        , binPackageDir )
                               , readConfigurationWithDefault )
import CPM.PackageCache.Global ( GlobalCache, readInstalledPackagesFromDir
                               , installFromZip, checkoutPackage
                               , uninstallPackage )
import CPM.Package
import CPM.Resolution ( showResult )
import CPM.Repository ( Repository, readRepository, findVersion, listPackages
                      , findLatestVersion, updateRepository, searchPackages )
import CPM.PackageCache.Runtime ( dependencyPathsSeparate, writePackageConfig )
import CPM.PackageCopy
import CPM.Diff.API as APIDiff
import qualified CPM.Diff.Behavior as BDiff

-- Banner of this tool:
cpmBanner :: String
cpmBanner = unlines [bannerLine,bannerText,bannerLine]
 where
 bannerText =
  "Curry Package Manager <curry-language.org/tools/cpm> (version of 27/03/2017)"
 bannerLine = take (length bannerText) (repeat '-')

main :: IO ()
main = do
  args <- getArgs
  parseResult <- return $ parse (intercalate " " args) optionParser "cpm"
  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
                       --printUsage "cpm" 80 optionParser
                       putStrLn err
                       exitWith 1
      Right opts -> runWithArgs opts

runWithArgs :: Options -> IO ()
runWithArgs opts = do
  missingExecutables <- checkExecutables
  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
  config <- readConfigurationWithDefault (optDefConfig opts) >>= \c ->
   case c of
    Left err -> do putStrLn $ "Error reading .cpmrc settings: " ++ err
                   exitWith 1
    Right c' -> return c'
  let getGC   = getGlobalCache config
  let getRepo = getRepository config
  setLogLevel $ optLogLevel opts
  (msgs, result) <- case optCommand opts of
    NoCommand   -> failIO "NoCommand"
    Update      -> updateRepository config
    Compiler o  -> compiler o config getRepo getGC
    Exec o      -> exec     o config getRepo getGC
    Test o      -> test     o config getRepo getGC
    Clean       -> cleanPackage Info
    New         -> newPackage
    _ -> do repo <- getRepo
            case optCommand opts of
              List   o -> listCmd o config repo
              Search o -> search  o config repo
              _ -> do globalCache <- getGC
                      case optCommand opts of
                        Deps         -> deps         config repo globalCache
                        PkgInfo o    -> info       o config repo globalCache
                        Checkout o   -> checkout   o config repo globalCache
                        InstallBin o -> installbin o config repo globalCache
                        Install o    -> install    o config repo globalCache
                        Diff o       -> diff       o config repo globalCache
                        Uninstall o  -> uninstall  o config repo globalCache
                        Upgrade o    -> upgrade    o config repo globalCache
                        Link o       -> link       o config repo globalCache
                        _ -> 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)

getGlobalCache :: Config -> IO GlobalCache
getGlobalCache config = do
  maybeGC <- readInstalledPackagesFromDir $ packageInstallDir config
  case maybeGC of
    Left err -> do putStrLn $ "Error reading global package cache: " ++ err
                   exitWith 1
    Right gc -> return gc

getRepository :: Config -> IO Repository
getRepository config = do
  (repo, repoErrors) <- readRepository config
  if null repoErrors
    then return repo
    else do putStrLn "Problems while reading the package index:"
            mapIO putStrLn repoErrors
            exitWith 1

data Options = Options
  { optLogLevel  :: LogLevel
  , optDefConfig :: [(String,String)]
  , optCommand   :: Command }

data Command 
  = Deps 
  | NoCommand
  | Checkout   CheckoutOptions
  | InstallBin CheckoutOptions
  | Install    InstallOptions
  | Uninstall  UninstallOptions
  | PkgInfo    InfoOptions
  | Compiler   CompilerOptions
  | Update
  | List       ListOptions
  | Search     SearchOptions
  | Upgrade    UpgradeOptions
  | Link       LinkOptions
  | Exec       ExecOptions
  | Test       TestOptions
  | Diff       DiffOptions
  | Clean
  | New

data CheckoutOptions = CheckoutOptions
  { coPackage    :: String
  , coVersion    :: Maybe Version
  , coPrerelease :: Bool }

data InstallOptions = InstallOptions
  { instTarget     :: Maybe String
  , instVersion    :: Maybe Version
  , instPrerelease :: Bool }

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

data InfoOptions = InfoOptions
  { infoPackage :: Maybe String
  , infoVersion :: Maybe Version
  , infoAll     :: Bool }

data ListOptions = ListOptions
  { listAll :: Bool
  , listCSV :: Bool }

data SearchOptions = SearchOptions
  { searchQuery :: String }

data UpgradeOptions = UpgradeOptions
  { upgrTarget :: Maybe String }

data LinkOptions = LinkOptions
  { lnkSource :: String }

data ExecOptions = ExecOptions
  { exeCommand :: String   -- command to be executed
  , exePath    :: [String] -- additional load path
  }

data CompilerOptions = CompilerOptions
  { comCommand :: String }

data TestOptions = TestOptions
  { testModules :: Maybe [String] }

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

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
  _            -> InstallOptions Nothing Nothing False

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
  _            -> InfoOptions Nothing Nothing False

listOpts :: Options -> ListOptions
listOpts s = case optCommand s of
  List opts -> opts
  _         -> ListOptions False False

searchOpts :: Options -> SearchOptions
searchOpts s = case optCommand s of
  Search opts -> opts
  _           -> SearchOptions ""

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 ""

execOpts :: Options -> ExecOptions
execOpts s = case optCommand s of
  Exec opts -> opts
  _         -> ExecOptions "" []

compOpts :: Options -> CompilerOptions
compOpts s = case optCommand s of
  Compiler opts -> opts
  _             -> CompilerOptions ""

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
readLogLevel s = if s == "debug"
  then Right $ Debug
  else Right $ Info

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
  defaultOpts = Options Info [] NoCommand

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

optionParser :: ParseSpec (Options -> Either String Options)
optionParser = optParser 
  (   option (\s a -> readLogLevel s >.> \ll -> a { optLogLevel = ll })
        (  long "verbosity"
        <> short "v"
        <> metavar "LEVEL"
        <> help "Log level for the application. Valid values are 'info' and 'debug'." )
  <.> 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'." )
  <.> commands (metavar "COMMAND")
        (   command "checkout" (help "Checkout a package.") Right
              (   arg (\s a -> Right $ a { optCommand = Checkout
                                           (checkoutOpts a) { coPackage = s } })
                    (  metavar "PACKAGE"
                    <> help "The package name" )
              <.> arg (\s a -> readVersion' s >.> \v -> a { optCommand = Checkout (checkoutOpts a) { coVersion = Just v } })
                    (  metavar "VERSION"
                    <> help "The package version"
                    <> optional )
              <.> flag (\a -> Right $ a { optCommand = Checkout (checkoutOpts a) { coPrerelease = True } })
                    (  short "p"
                    <> long "pre"
                    <> help "Try pre-release versions when searching for newest version.") )
        <|> command "installbin" (help "Install the binary provided by a package.") 
                     Right
              (   arg (\s a -> Right $ a { optCommand = InstallBin
                                           (checkoutOpts a) { coPackage = s } })
                    (  metavar "PACKAGE"
                    <> help "The package name" )
              <.> arg (\s a -> readVersion' s >.> \v -> a { optCommand = InstallBin (checkoutOpts a) { coVersion = Just v } })
                    (  metavar "VERSION"
                    <> help "The package version"
                    <> optional)
              <.> flag (\a -> Right $ a { optCommand = InstallBin (checkoutOpts a) { coPrerelease = True } })
                    (  short "p"
                    <> long "pre"
                    <> help "Try pre-release versions when searching for newest version.") )
        <|> command "install" (help "Install a package.")
                     (\a -> Right $ a { optCommand = Install (installOpts a) })
              (   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.") )
        <|> command "uninstall" (help "Uninstall package")
                    (\a -> Right $ a { optCommand = Uninstall (uninstallOpts a) })
              (   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) )
        <|> command "deps" (help "Calculate dependencies")
                           (\a -> Right $ a { optCommand = Deps }) [] 
        <|> command "clean" (help "Clean the current package")
                          (\a -> Right $ a { optCommand = Clean }) []
        <|> command "new" (help "Create a new package")
                          (\a -> Right $ a { optCommand = New }) []
        <|> command "update" (help "Update the package index")
                             (\a -> Right $ a { optCommand = Update }) []
        <|> command "curry" (help "Load package spec from current directory and start Curry with correct dependencies.")
                            (\a -> Right $ a { optCommand = Compiler (compOpts a) })
              (   rest (\s a -> Right $ a { optCommand = Compiler (compOpts a) { comCommand = s } })
                    (  metavar "ARGS"
                    <> help "The options to pass to the compiler"
                    <> optional) )
        <|> command "exec" (help "Execute a command with the CURRYPATH set") (\a -> Right $ a { optCommand = Exec (execOpts a) })
              (   rest (\s a -> Right $ a { optCommand = Exec (execOpts a) { exeCommand = s } })
                    (  metavar "CMD"
                    <> help "The command to execute. Don't forget the quotes!"
                    <> optional) ) 
        <|> command "info" (help "Print package information")
                       (\a -> Right $ a { optCommand = PkgInfo (infoOpts a) })
              (   arg (\s a -> Right $ a { optCommand = PkgInfo (infoOpts a)
                                                    { infoPackage = Just s } })
                    (  metavar "PACKAGE"
                    <> help "The package name. If no name is specified, cpm tries 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, cpm uses the latest version of the specified package."
                    <> optional )
              <.> flag (\a -> Right $ a { optCommand = PkgInfo (infoOpts a)
                                                         { infoAll = True } })
                    (  short "a"
                    <> long "all"
                    <> help "Show all infos"
                    <> optional ) )
        <|> command "test" (help "Test the current package (with CurryCheck)")
                    (\a -> Right $ a { optCommand = Test (testOpts a) })
              (   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 ) )
        <|> command "diff"
                    (help "Diff the current package against another version")
                    (\a -> Right $ a { optCommand = Diff (diffOpts a) })
              (   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, cpm diffs against the latest repository version."
                    <> 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") )
        <|> command "list" (help "List all packages of the repository")
                           (\a -> Right $ a { optCommand = List (listOpts a) })
              (   flag (\a -> Right $ a { optCommand = List (listOpts a)
                                                         { listAll = True } })
                    (  short "a"
                    <> long "all"
                    <> help "Show all versions"
                    <> optional ) 
              <.> flag (\a -> Right $ a { optCommand = List (listOpts a)
                                                      { listCSV = True } })
                    (  short "c"
                    <> long "csv"
                    <> help "Show in CSV format"
                    <> optional ) )
        <|> command "search" (help "Search the package repository") Right
              (   arg (\s a -> Right $ a { optCommand = Search (searchOpts a) { searchQuery = s } }) 
                    (  metavar "QUERY"
                    <> help "The search term" ) ) 
        <|> command "upgrade" (help "Upgrade one or more packages") (\a -> Right $ a { optCommand = Upgrade (upgradeOpts a) })
              (   arg (\s a -> Right $ a { optCommand = Upgrade (upgradeOpts a) { upgrTarget = Just s } })
                    (  metavar "PACKAGE"
                    <> help "The package to upgrade" 
                    <> optional) )
        <|> command "link" (help "Link a package to the local cache") Right
              (   arg (\s a -> Right $ a { optCommand = Link (linkOpts a) { lnkSource = s } })
                    (  metavar "SOURCE"
                    <> help "The directory to link" ) ) ) )

-- Check if operating system executables we depend on are present on the current
-- system.
checkExecutables :: IO [String]
checkExecutables = do
  present <- mapIO fileInPath listOfExecutables
  return $ map fst $ filter (not . snd) (zip listOfExecutables present)
 where
  listOfExecutables = 
    [ "curl"  
    , "git"   
    , "unzip" 
    , "cp"
    , "rm"
    , "ln"
    , "readlink" ]

deps :: Config -> Repository -> GlobalCache -> IO (ErrorLogger ())
deps cfg repo gc =
  tryFindLocalPackageSpec "." |>= \specDir ->
  resolveDependencies cfg repo gc specDir |>= \result ->
  putStrLn (showResult result) >> succeedIO ()

info :: InfoOptions -> Config -> Repository -> GlobalCache
     -> IO (ErrorLogger ())
info (InfoOptions Nothing Nothing allinfos) _ repo gc =
  tryFindLocalPackageSpec "." |>= \specDir ->
  loadPackageSpec specDir |>= printInfo allinfos repo gc
info (InfoOptions (Just pkg) Nothing allinfos) _ repo gc =
  case findLatestVersion repo pkg False of
   Nothing -> failIO $
                "Package '" ++ pkg ++ "' not found in package repository."
   Just p  -> printInfo allinfos repo gc p
info (InfoOptions (Just pkg) (Just v) allinfos) _ repo gc =
 case findVersion repo pkg v of
   Nothing -> failIO $ "Package '" ++ pkg ++ "-" ++ (showVersion v) ++
                       "' not found in package repository."
   Just p  -> printInfo allinfos repo gc p
info (InfoOptions Nothing (Just _) _) _ _ _ = failIO "Must specify package name"

printInfo :: Bool -> Repository -> GlobalCache -> Package -> IO (ErrorLogger ())
printInfo allinfos repo gc pkg =
  putStrLn (renderPackageInfo allinfos repo gc pkg) >> succeedIO ()


compiler :: CompilerOptions -> Config -> IO Repository -> IO GlobalCache
         -> IO (ErrorLogger ())
compiler o cfg getRepo getGC =
  tryFindLocalPackageSpec "." |>= \specDir ->
  loadCurryPathFromCache specDir |>=
  maybe (computePackageLoadPath specDir) succeedIO |>= \currypath ->
  log Info ("Starting Curry with CURRYPATH " ++ currypath) |>
  do setEnviron "CURRYPATH" $ currypath
     ecode <- system $ "curry " ++ comCommand o
     unsetEnviron "CURRYPATH"
     unless (ecode==0) (exitWith ecode)
     succeedIO ()
 where
  computePackageLoadPath pkgdir =
    getRepo >>= \repo -> getGC >>= \gc ->
    resolveAndCopyDependencies cfg repo gc pkgdir |>= \pkgs ->
    getAbsolutePath pkgdir >>= \abs -> succeedIO () |>
    succeedIO (abs </> "src") |>= \srcDir ->
    let currypath = joinSearchPath (srcDir : dependencyPathsSeparate pkgs abs)
    in saveCurryPathToCache pkgdir currypath >> succeedIO currypath


checkout :: CheckoutOptions -> Config -> Repository -> GlobalCache
         -> IO (ErrorLogger ())
checkout (CheckoutOptions pkg Nothing pre) cfg repo gc =
 case findLatestVersion repo pkg pre of
  Nothing -> failIO $ "Package '" ++ pkg ++
                      "' not found in package repository."
  Just  p -> acquireAndInstallPackageWithDependencies cfg repo gc p |>
             checkoutPackage cfg repo gc p
checkout (CheckoutOptions pkg (Just ver) _) cfg repo gc =
 case findVersion repo pkg ver of
  Nothing -> failIO $ "Package '" ++ pkg ++ "-" ++ showVersion ver ++
                      "' not found in package repository."
  Just  p -> acquireAndInstallPackageWithDependencies cfg repo gc p |>
             checkoutPackage cfg repo gc p

-- Installs the binary provided by a package.
-- This is done by checking out the package into CPM's bin_packages
-- cache (default: $HOME/.cpm/bin_packages, see bin_package_path
-- in .cpmrc configuration file) and then install this package.
installbin :: CheckoutOptions -> Config -> Repository -> GlobalCache
           -> IO (ErrorLogger ())
installbin opts cfg repo gc = do
  removeDirectoryComplete copkgdir
  debugMessage ("Change into directory " ++ binpkgdir)
  inDirectory binpkgdir
    (checkout opts cfg repo gc |>
     log Debug ("Change into directory " ++ copkgdir) |>
     (setCurrentDirectory copkgdir >> succeedIO ()) |>
     install (InstallOptions Nothing Nothing False) cfg repo gc |>
     cleanPackage Debug)
 where
  binpkgdir = binPackageDir cfg
  copkgdir  = binpkgdir </> coPackage opts

install :: InstallOptions -> Config -> Repository -> GlobalCache
        -> IO (ErrorLogger ())
install (InstallOptions Nothing Nothing _) cfg repo gc =
  tryFindLocalPackageSpec "." |>= \specDir ->
  installLocalDependencies cfg repo gc specDir |>= \ (pkg,_) ->
  installExecutable cfg repo pkg specDir
install (InstallOptions (Just pkg) Nothing pre) cfg repo gc = do
  fileExists <- doesFileExist pkg
  if fileExists
    then installFromZip cfg pkg
    else case findLatestVersion repo pkg pre of
      Nothing -> failIO $ "Package '" ++ pkg ++
                          "' not found in package repository."
      Just  p -> acquireAndInstallPackageWithDependencies cfg repo gc p
install (InstallOptions (Just pkg) (Just ver) _) cfg repo gc =
 case findVersion repo pkg ver of
  Nothing -> failIO $ "Package '" ++ pkg ++ "-" ++ (showVersion ver) ++
                      "' not found in package repository."
  Just  p -> acquireAndInstallPackageWithDependencies cfg repo gc p
install (InstallOptions Nothing (Just _) _) _ _ _ =
  failIO "Must specify package name"

--- Installs the executable specified in the package in the
--- bin directory of CPM (compare .cpmrc).
installExecutable :: Config -> Repository -> Package -> String
                  -> IO (ErrorLogger ())
installExecutable cfg repo pkg pkgdir =
  -- we read the global cache again since it might be modified by
  -- the installation of the package:
  getGlobalCache cfg >>= \gc ->
  maybe (succeedIO ())
        (\ (PackageExecutable name mainmod) ->
           getLogLevel >>= \lvl ->
           getEnviron "PATH" >>= \path ->
           log Info ("Compiling main module: " ++ mainmod) |>
           let cmd = unwords $
                       [":set", if levelGte Debug lvl then "v1" else "v0"] ++
                       (if curryCompiler == "pakcs" && not (levelGte Debug lvl)
                          then [":set","-warn"] else []) ++
                       [":load", mainmod, ":save", ":quit"]
               bindir     = binInstallDir cfg
               binexec    = bindir </> name
           in writePackageConfig cfg pkgdir pkg |>
              compiler CompilerOptions { comCommand = cmd }
                       cfg (return repo) (return gc) |>
              log Info ("Installing executable '" ++ name ++ "' into '" ++
                        bindir ++ "'") |>
              (whenFileExists binexec (backupExistingBin binexec) >>
               -- renaming might not work across file systems:
               system (unwords ["mv", mainmod, binexec]) >>
               checkPath path bindir))
        (executableSpec pkg)
 where
  backupExistingBin binexec = do
    let binexecbak = binexec ++ ".bak"
    system $ "rm -f " ++ binexecbak
    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!"


uninstall :: UninstallOptions -> Config -> Repository -> GlobalCache
          -> IO (ErrorLogger ())
uninstall (UninstallOptions (Just pkg) (Just ver)) cfg repo gc =
  uninstallPackage cfg repo gc pkg ver
uninstall (UninstallOptions (Just _) Nothing) _ _ _ =
  log Error "Please provide a package and version number!"
uninstall (UninstallOptions Nothing (Just _)) _ _ _ =
  log Error "Please provide a package and version number!"
uninstall (UninstallOptions Nothing Nothing) cfg _ _ =
  tryFindLocalPackageSpec "." |>= \specDir ->
  loadPackageSpec specDir |>= \pkg ->
  maybe (succeedIO ())
        (\ (PackageExecutable name _) ->
           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
  Nothing -> failIO $ "Package '" ++ pkg ++ "-" ++ (showVersion ver) ++
                      "' not found in package repository."
  Just  p -> succeedIO $ p

--- Lists all packages in the given repository.
listCmd :: ListOptions -> Config -> Repository -> IO (ErrorLogger ())
listCmd (ListOptions lv csv) _ repo = putStr rendered >> succeedIO ()
 where
  results = concatMap (if lv then id else ((:[]) . head))
                      (sortBy (\ps1 ps2 -> name (head ps1) <= name (head ps2))
                              (listPackages repo))

  rendered =
    if csv
      then showCSV (head columns : drop 2 columns)
      else render (table columns [nameLen + 4, 66 - nameLen, 10]) ++
             "\nUse 'cpm info PACKAGE' for more information about a package." ++
             "\nUse 'cpm update' to download the newest package index.\n"

  header = [ ["Name", "Synopsis", "Version"]
           , ["----", "--------", "-------"]]

  formatPkg p = [name p, synopsis p, showVersion (version p)]
  columns = header ++ map formatPkg results
  nameLen = foldl max 0 $ map (length . name) results

search :: SearchOptions -> Config -> Repository -> IO (ErrorLogger ())
search (SearchOptions q) _ repo = putStr rendered >> succeedIO ()
 where
  results = sortBy (\p1 p2 -> name p1 <= name p2) (searchPackages repo q)
  rendered = if length results == 0
    then "No packages found for '" ++ q ++ "'\n"
    else render $ table columns [nameLen + 4, 76 - nameLen]
  header = [["Name", "Synopsis"], ["----", "--------"], [" ", " "]]
  columns = header ++ map (\p -> [name p, synopsis p]) results
  nameLen = foldl max 0 $ map (length . name) results

upgrade :: UpgradeOptions -> Config -> Repository -> GlobalCache
        -> IO (ErrorLogger ())
upgrade (UpgradeOptions Nothing) cfg repo gc = tryFindLocalPackageSpec "." |>=
  \specDir -> log Info "Upgrading all packages" |>
  upgradeAllPackages cfg repo gc specDir
upgrade (UpgradeOptions (Just pkg)) cfg repo gc =
  tryFindLocalPackageSpec "." |>=
  \specDir -> log Info ("Upgrade " ++ pkg) |>
  upgradeSinglePackage cfg repo gc specDir pkg


link :: LinkOptions -> Config -> Repository -> GlobalCache
     -> IO (ErrorLogger ())
link (LinkOptions src) _ _ _ = tryFindLocalPackageSpec "." |>=
  \specDir -> log Info ("Linking '" ++ src ++ "' into local package cache") |>
  linkToLocalCache src specDir

--- `test` command: run `curry check` on exported or top-level modules
--- of the package, or on the modules provided as an argument.
test :: TestOptions -> Config -> IO Repository -> IO GlobalCache
     -> IO (ErrorLogger ())
test opts cfg getRepo getGC =
  tryFindLocalPackageSpec "." |>= \specDir ->
  loadPackageSpec specDir |>= \localSpec -> do
    aspecDir <- getAbsolutePath specDir
    mainprogs <- curryModulesInDir (aspecDir </> "src")
    let tests = testsuites localSpec mainprogs
    if null tests
      then putStrLn "No modules to be tested!" >> succeedIO ()
      else foldEL (\_ -> execTest aspecDir) () tests
 where
  execTest apkgdir (dir,mods) = do
    putStrLn $ "Testing modules (in directory '" ++ dir ++ "', " ++
               "with CurryCheck, showing raw output):\n" ++
               unwords mods ++ "\n"
    inDirectory dir $
     execWithPkgDir
      (ExecOptions (installDir </> "bin" </> "curry check " ++ unwords mods) [])
      cfg getRepo getGC apkgdir

  testsuites spec mainprogs = case testModules opts of
    Nothing -> maybe (let exports = exportedModules spec
                      in if null exports
                           then if null mainprogs
                                  then []
                                  else [("src",mainprogs)]
                           else [("src",exports)])
                     (\ (PackageTests tests) -> tests)
                     (testSuite spec)
    Just ms -> [("src",ms)]

--- Get the names of all Curry modules containing in a directory.
--- 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 =
  tryFindLocalPackageSpec "." |>= \specDir ->
  loadPackageSpec specDir     |>= \localSpec ->
  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
    Nothing -> case findLatestVersion repo localname False of
                 Nothing -> failIO $ "No other version of local package '" ++
                                 localname ++ "' found in package repository."
                 Just p  -> succeedIO (version p)
    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 ()


exec :: ExecOptions -> Config -> IO Repository -> IO GlobalCache
     -> IO (ErrorLogger ())
exec o cfg getRepo getGC =
  tryFindLocalPackageSpec "." |>= execWithPkgDir o cfg getRepo getGC

execWithPkgDir :: ExecOptions -> Config -> IO Repository -> IO GlobalCache
               -> String -> IO (ErrorLogger ())
execWithPkgDir o cfg getRepo getGC specDir =
  loadCurryPathFromCache specDir |>=
  maybe (computePackageLoadPath specDir) succeedIO |>= \currypath ->
  let execpath = joinSearchPath (exePath o ++ splitSearchPath currypath)
  in log Debug ("Setting CURRYPATH to " ++ execpath) |>
  do setEnviron "CURRYPATH" execpath
     ecode <- system (exeCommand o)
     unsetEnviron "CURRYPATH"
     unless (ecode==0) (exitWith ecode)
     succeedIO ()
 where
  computePackageLoadPath pkgdir =
    getRepo >>= \repo -> getGC >>= \gc ->
    resolveAndCopyDependencies cfg repo gc pkgdir |>= \pkgs ->
    getAbsolutePath pkgdir >>= \abs -> succeedIO () |>
    succeedIO (abs </> "src") |>= \srcDir ->
    let currypath = joinSearchPath (srcDir : dependencyPathsSeparate pkgs abs)
    in saveCurryPathToCache pkgdir currypath >> succeedIO currypath


-- Clean auxiliary files in the current package
cleanPackage :: LogLevel -> IO (ErrorLogger ())
cleanPackage ll =
  tryFindLocalPackageSpec "." |>= \specDir ->
  loadPackageSpec specDir     |>= \pkg ->
  let dotcpm   = specDir </> ".cpm"
      srcdirs  = [specDir </> "src"]
      testdirs = maybe [] (\ (PackageTests tests) -> map fst tests)
                       (testSuite pkg)
      rmdirs   = dotcpm : map addCurrySubdir (srcdirs ++ testdirs)
  in log ll ("Removing directories: " ++ unwords rmdirs) |>
     (system (unwords (["rm", "-rf"] ++ rmdirs)) >> succeedIO ())

--- Creates a new package by asking some questions.
newPackage :: IO (ErrorLogger ())
newPackage = do
  putStrLn "Create a new package"
  putStrLn "--------------------"
  inpName <- askMandatory "What is the name of the new package?"
  exists <- doesDirectoryExist inpName
  if exists
    then do putStrLn $ "There is already a directory with that name. " ++
                       "I can't overwrite directories!"
            exitWith 1
    else return ()
  inpVersionS <- askDefault "What is the first version of the package?" "0.0.1"
  inpVersion <- case readVersion inpVersionS of
    Nothing -> putStrLn "Not a valid version!" >> exitWith 1
    Just  v -> return v
  inpAuthor <- askMandatory "Who is the author of the package?"
  inpSynopsis <- askMandatory
     "Please provide a short (one line) summary of what the package does:\n>"
  createDirectory inpName
  let pkgSpec = emptyPackage { name         = inpName
                             , version      = inpVersion
                             , author       = inpAuthor
                             , synopsis     = inpSynopsis
                             , category     = []
                             , dependencies = [] 
                             , exportedModules = []
                             }
  writePackageSpec pkgSpec (inpName </> "package.json") 
  createDirectory (inpName </> "src")
  putStrLn $
    "A new package in the directory '" ++ inpName ++ "' has been created.\n" ++
    "Please go into this directory, add dependencies in 'package.json',\n" ++
    "and run 'cpm install' to install all dependencies."
  succeedIO ()
 where
  askMandatory question = do
    putStr $ question ++ " "
    hFlush stdout
    val <- getLine
    if val == ""
      then askMandatory question
      else return val
  askDefault question def = do
    putStr $ question ++ " [" ++ def ++ "] "
    hFlush stdout
    val <- getLine
    if val == ""
      then return def
      else return val

---------------------------------------------------------------------------
-- Caching the current CURRYPATH of a package for faster startup.

--- The name of the cache file in a package directory.
curryPathCachFile :: String -> String
curryPathCachFile pkgdir = pkgdir </> ".cpm" </> "currypath_cache"

--- Saves package CURRYPATH in local cache file in the given package dir.
saveCurryPathToCache :: String -> String -> IO ()
saveCurryPathToCache pkgdir path = do
  let cpmdir = pkgdir </> ".cpm"
  createDirectoryIfMissing False cpmdir
  writeFile (curryPathCachFile pkgdir) (path ++ "\n")

--- Restores package CURRYPATH from local cache file in the given package dir,
--- if it is still up-to-date.
loadCurryPathFromCache :: String -> IO (ErrorLogger (Maybe String))
loadCurryPathFromCache pkgdir = do
  let cachefile = curryPathCachFile pkgdir
  excache <- doesFileExist cachefile
  if excache
    then do
      cftime <- getModificationTime cachefile
      pftime <- getModificationTime (pkgdir </> "package.json")
      if cftime > pftime
        then do cnt <- safeReadFile cachefile
                let ls = either (const []) lines cnt
                succeedIO $ if null ls then Nothing
                                       else Just (head ls)
        else succeedIO Nothing
    else succeedIO Nothing

---------------------------------------------------------------------------