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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
|
module CPM.Manage ( main )
where
import Control.Monad ( when, unless )
import Data.List ( (\\), groupBy, isPrefixOf, intercalate, intersect
, isSuffixOf, nub, nubBy, partition, sort, sortBy
, sum, union )
import System.Environment ( getArgs )
import Data.GraphViz
import Data.Time ( CalendarTime, compareCalendarTime, ctDay, ctMonth
, ctYear, getLocalTime, toDayString )
import HTML.Base
import HTML.Styles.Bootstrap4
import Language.Curry.Resources ( curryPackagesDocURL )
import System.CurryPath ( curryModulesInDirectory, stripCurrySuffix )
import System.Directory ( createDirectoryIfMissing, doesDirectoryExist
, doesFileExist, getAbsolutePath, getCurrentDirectory
, getDirectoryContents, getTemporaryDirectory
, setCurrentDirectory )
import System.FilePath ( (</>) )
import System.IOExts ( evalCmd, readCompleteFile )
import System.Process ( getPID, exitWith, system )
import Text.CSV ( readCSV, writeCSVFile )
import CPM.Config ( Config, repositoryDir, packageInstallDir
, readConfigurationWith, showConfiguration )
import CPM.ErrorLogger
import CPM.FileUtil ( cleanTempDir, copyDirectory, inDirectory
, inTempDir, quote, recreateDirectory
, removeDirectoryComplete, tempDir )
import CPM.Package
import CPM.PackageCache.Global ( acquireAndInstallPackageFromSource
, checkoutPackage )
import CPM.Package.Helpers ( renderPackageInfo )
import CPM.Repository ( allPackages, listPackages
, readPackageFromRepository )
import CPM.Repository.Update ( addPackageToRepository, updateRepository )
import CPM.Repository.Select ( getBaseRepository, getPackageVersion )
import CPM.Resolution ( isCompatibleToCompiler )
import CPM.Package.HTML
banner :: String
banner = unlines [bannerLine, bannerText, bannerLine]
where
bannerText = "cpm-manage (Version of 04/10/2024)"
bannerLine = take (length bannerText) (repeat '-')
packageHtmlDir :: String
packageHtmlDir = "pkgs"
currygleDocDir :: String
currygleDocDir = "currygledocs"
main :: IO ()
main = do
allargs <- getArgs
let (rcdefs, args) = readRcOptions allargs
config <- readConfiguration rcdefs
case args of
["genhtml"] -> writePackageIndexAsHTML config "CPM"
["genhtml",d] -> writePackageIndexAsHTML config d
["genhtml",d,p,v] -> writePackageVersionAsHTML config d p v
["genreadme"] -> writeReadmeFiles config "CPM"
["genreadme",d] -> writeReadmeFiles config d
["gendocs"] -> generateDocsOfAllPackages config rcdefs packageDocDir
["gendocs",d] -> getAbsolutePath d >>=
generateDocsOfAllPackages config rcdefs
["gentar"] -> genTarOfAllPackages config packageTarDir
["gentar",d] -> getAbsolutePath d >>= genTarOfAllPackages config
["testall"] -> testAllPackages config rcdefs ""
["testall",d] -> getAbsolutePath d >>= testAllPackages config rcdefs
["sumcsv",d] -> do ad <- getAbsolutePath d
sumCSVStatsOfPkgs ad "SUM.csv"
["add"] -> addNewPackage config rcdefs True
["addnotag"] -> addNewPackage config rcdefs False
["update"] -> updatePackage config rcdefs
["showgraph"] -> visualizePackageDependencies config ""
["showgraph",p] -> visualizePackageDependencies config p
["writeall"] -> writeAllPackages config
["writedeps"] -> writeAllPackageDependencies config
["writemods"] -> writeAllPackageModules config rcdefs
["copydocs"] -> copyPackageDocumentations config packageDocDir
["copydocs",d] -> getAbsolutePath d >>= copyPackageDocumentations config
["config"] -> printConfig config
["--help"] -> putStrLn helpText
["-h"] -> putStrLn helpText
_ -> do putStrLn $ "Illegal arguments: " ++ unwords args
putStrLn helpText
exitWith 1
readRcOptions :: [String] -> ([(String,String)], [String])
readRcOptions [] = ([], [])
readRcOptions (arg:args)
| "--define" `isPrefixOf` arg
= case args of
[] -> error "Illegal argument: '--define' without argument"
(a:as) -> let (remopts, remargs) = readRcOptions as
in (readOpt "--define " a : remopts, remargs)
| "-d" `isPrefixOf` arg
= let (remopts, remargs) = readRcOptions args
in (readOpt "-d" (drop 2 arg) : remopts, remargs)
| otherwise
= let (remopts, remargs) = readRcOptions args
in (remopts, arg : remargs)
where
readOpt p s =
let (option,value) = break (=='=') s
in if null value
then error $ "Illegal option definition: '=' missing in\n" ++ p ++ s
else (option, tail value)
helpText :: String
helpText = banner ++ unlines
[ "Options:", ""
, "-d, --define option=value : Overwrite definition of cpmrc file"
, "-h, --help : show usage information"
, ""
, "Commands:", ""
, "config : show current configuration"
, "genhtml [<d>] : generate HTML pages for all packages into <d>"
, " (default: 'CPM')"
, "genhtml <d> <p> <v>: generate HTML pages for package <p> / version <v>"
, " into directory <d>"
, "genreadme [<d>]: generate README.html files for all packages into <d>"
, " (default: 'CPM') if they are not already present"
, "gendocs [<d>] : generate HTML documentations of all packages into <d>"
, " (default: '" ++ packageDocDir ++ "')"
, "gentar [<d>] : generate tar.gz files of all packages into <d>"
, " (default: '" ++ packageTarDir ++ "')"
, "testall [<d>] : test all packages and write test statistics into"
, " directory <d> if it is provided"
, "sumcsv [<d>] : sum up all CSV package statistic files in <d>"
, "showgraph : visualize all package dependencies as a dot graph"
, "showgraph <p> : visualize dependencies for package <p> as a dot graph"
, "writeall : write all versions of all packages into 'allpkgs.csv'"
, "writedeps : write all package dependencies as CSV file 'pkgdeps.csv'"
, "writemods : write modules exported by package into 'pkgmods.csv'"
, "copydocs [<d> ]: copy latest package documentations"
, " from <d> (default: '" ++ packageDocDir ++ "')"
, " to '" ++ currygleDocDir ++ "'"
]
packageDocDir :: String
packageDocDir = "CPM" </> "DOC"
packageTarDir :: String
packageTarDir = "CPM" </> "PACKAGES"
getAllPackageSpecs :: Config -> Bool -> IO ([[Package]],[Package])
getAllPackageSpecs config compat = do
putStrLn "Reading base repository..."
repo <- fromEL $ getBaseRepository config
let allpkgversions = listPackages repo
allcompatpkgs = sortBy (\ps1 ps2 -> name ps1 <= name ps2)
(concatMap (filterCompatPkgs config)
allpkgversions)
return (allpkgversions, allcompatpkgs)
where
filterCompatPkgs cfg pkgs =
let comppkgs = filter (isCompatibleToCompiler cfg) pkgs
in if null comppkgs
then if compat then [] else take 1 pkgs
else [head comppkgs]
writeReadmeFiles :: Config -> String -> IO ()
writeReadmeFiles cfg cpmindexdir = do
createDirectoryIfMissing True cpmindexdir
inDirectory cpmindexdir $ do
(allpkgversions,_) <- getAllPackageSpecs cfg False
mapM_ genReadmeForPackage
(sortBy (\p1 p2 -> packageId p1 <= packageId p2)
(concat allpkgversions))
genReadmeForPackage :: Package -> IO ()
genReadmeForPackage pkg = do
putStrLn $ "CHECKING PACKAGE: " ++ pkgid
rmfiles <- getReadmeFiles pkgdir
rmexist <- doesFileExist $ docdir </> "README.html"
if null rmfiles || rmexist
then unless rmexist $ putStrLn $ "No README file found"
else do
let readmefile = head rmfiles
formatcmd1 = formatCmd1 (pkgdir </> readmefile)
formatcmd2 = formatCmd2 (pkgdir </> readmefile)
createDirectoryIfMissing True docdir
putStrLn $ "Executing: " ++ formatcmd1
rc1 <- system formatcmd1
putStrLn $ "Executing: " ++ formatcmd2
rc2 <- system formatcmd2
if rc1 == 0 && rc2 == 0
then do
system $ unwords ["chmod -f 644 ", quote outfile1, quote outfile2]
return ()
else error $ "Error during execution of commands:\n" ++
formatcmd1 ++ "\n" ++ formatcmd2
where
pkgid = packageId pkg
pkgdir = "PACKAGES" </> pkgid
docdir = "DOC" </> pkgid
getReadmeFiles dir = do
entries <- getDirectoryContents dir
return $ filter ("README" `isPrefixOf`) entries
outfile1 = docdir </> "README.html"
outfile2 = docdir </> "README_I.html"
formatCmd1 readme = "pandoc -s -t html -o " ++ outfile1 ++ " " ++ readme
formatCmd2 readme = "pandoc -t html -o " ++ outfile2 ++ " " ++ readme
writePackageIndexAsHTML :: Config -> String -> IO ()
writePackageIndexAsHTML config cpmindexdir = do
createDirectoryIfMissing True cpmindexdir
inDirectory cpmindexdir $ do
createDirectoryIfMissing True packageHtmlDir
system $ "chmod 755 " ++ packageHtmlDir
(allpkgversions,newestpkgs) <- getAllPackageSpecs config False
writePackageDependencies config newestpkgs
let stats = pkgStatistics allpkgversions newestpkgs
putStrLn "Reading all package specifications..."
allnpkgs <- fromEL $ mapM (readPackageFromRepository config) newestpkgs
writePackageIndex allnpkgs allnpkgs "index.html" stats 0
allvpkgs <- fromEL $
mapM (readPackageFromRepository config)
(concat
(map reverse
(sortBy (\pg1 pg2 -> name (head pg1) <= name (head pg2))
allpkgversions)))
allvpkgtimes <- mapM (\p -> getUploadTime p >>= \t -> return (p,t)) allvpkgs
let allvpkgsorted = map fst (sortBy comparePkgWithTime allvpkgtimes)
writePackageIndex allvpkgs allvpkgsorted "indexv.html" stats 1
writeCategoryIndexAsHTML allnpkgs
mapM_ (writePackageAsHTML allpkgversions) allvpkgs
return ()
where
comparePkgWithTime (_,mt1) (_,mt2) =
maybe False
(\t1 -> maybe True (\t2 -> compareCalendarTime t1 t2 == GT) mt2)
mt1
writePackageIndex indexpkgs listpkgs indexfile statistics actindex = do
putStrLn $ "Writing '" ++ indexfile ++ "'..."
indextable <- packageInfosAsHtmlTable (actindex/=0) listpkgs
let ptitle = "Curry Packages in the CPM Repository"
refOfPkg = if actindex == 0 then name else packageId
pkglinks = map (\p -> hrefPrimBadge
(packageHtmlDir </> refOfPkg p ++ ".html")
[htxt $ refOfPkg p])
indexpkgs
pindex = if actindex == 0
then [h2 [htxt "Package index:"], par (hitems pkglinks),
h2 [htxt "Packages sorted by name"]]
else [h2 [htxt "All package versions sorted by upload time"]]
pagestring <- cpmIndexPage ptitle (pindex ++ [indextable] ++ statistics)
actindex
writeReadableFile indexfile pagestring
pkgStatistics allpkgversions newestpkgs =
[h4 [htxt "Statistics:"],
par [htxt $ show (length newestpkgs) ++ " packages", breakline,
htxt $ show (length (concat allpkgversions)) ++ " package versions"]]
writeCategoryIndexAsHTML :: [Package] -> IO ()
writeCategoryIndexAsHTML allpkgs = do
let allcats = sortBy (<=) . nub . concatMap category $ allpkgs
catpkgs = map (\c -> (c, sortBy pidLeq . nubBy pidEq .
filter (\p -> c `elem` category p) $ allpkgs))
allcats
cattables <- mapM formatCat catpkgs
let catlinks = map (\ (c,_) -> hrefPrimBadge ('#':c) [htxt c]) catpkgs
hcats = concatMap (\ (c,t) -> [anchor c [htxt ""], hrule, h1 [htxt c], t])
cattables
ptitle = "Curry Packages by Category"
pagestring <- cpmIndexPage ptitle
(h2 [htxt "Category index:"] : par (hitems catlinks) :
hcats) 2
let catindexfile = "indexc.html"
putStrLn $ "Writing '" ++ catindexfile ++ "'..."
writeReadableFile catindexfile pagestring
where
pidEq p1 p2 = packageId p1 == packageId p2
pidLeq p1 p2 = packageId p1 <= packageId p2
formatCat (c,ps) = do
pstable <- packageInfosAsHtmlTable False ps
return (c, pstable)
cpmIndexPage :: String -> [BaseHtml] -> Int -> IO String
cpmIndexPage title maindoc actindex = do
time <- getLocalTime
let dayversion = " (Version: " ++ toDayString time ++ ")"
btbase = "bt4"
return $ showHtmlPage $
bootstrapPage (favIcon btbase) (cssIncludes btbase) (jsIncludes btbase)
title packagesHomeBrand
(leftTopMenu False actindex)
rightTopMenu 0 []
[h1 [htxt title, smallMutedText dayversion]]
maindoc (curryDocFooter time)
writePackageVersionAsHTML :: Config -> String -> String -> String -> IO ()
writePackageVersionAsHTML cfg cpmindexdir pname pversion = do
case readVersion pversion of
Nothing -> error $ "'" ++ pversion ++ "' is not a valid version"
Just v -> do
(allpkgs,_) <- getAllPackageSpecs cfg False
mbpkg <- fromEL $ getPackageVersion cfg pname v
case mbpkg of
Nothing ->
error $ "Package '" ++ pname ++ "-" ++ pversion ++ "' not found!"
Just pkg -> do
fullpkg <- fromEL $ readPackageFromRepository cfg pkg
createDirectoryIfMissing True cpmindexdir
putStrLn $ "Changing to directory '" ++ cpmindexdir ++ "'..."
inDirectory cpmindexdir $ do
createDirectoryIfMissing True packageHtmlDir
system $ "chmod 755 " ++ packageHtmlDir
writePackageAsHTML allpkgs fullpkg
writePackageAsHTML :: [[Package]] -> Package -> IO ()
writePackageAsHTML allpkgversions pkg = do
pagestring <- packageToHTML allpkgversions pkg
inDirectory packageHtmlDir $ do
putStrLn $ "Writing '" ++ htmlfile ++ "'..."
writeReadableFile htmlfile pagestring
putStrLn $ "Writing '" ++ htmlsrcfile ++ "'..."
srcdirstring <- directoryContentsPage
(htmlfile, [htxt $ "Package", nbsp,
code [htxt $ name pkg]])
(".." </> "PACKAGES") pkgid
writeReadableFile htmlsrcfile srcdirstring
writeReadableFile metafile (renderPackageInfo True True True pkg)
system $ unwords
["/bin/rm", "-f", htmllink, "&&", "ln", "-s", htmlfile, htmllink]
return ()
where
pkgid = packageId pkg
htmlfile = pkgid ++ ".html"
htmlsrcfile = pkgid ++ "-src.html"
htmllink = name pkg ++ ".html"
metafile = pkgid ++ ".txt"
writeReadableFile :: String -> String -> IO ()
writeReadableFile f s = writeFile f s >> system ("chmod 644 " ++ f) >> return ()
packageInfosAsHtmlTable :: Bool -> [Package] -> IO BaseHtml
packageInfosAsHtmlTable withversion pkgs = do
rows <- mapM formatPkgAsRow pkgs
return $ borderedHeadedTable
(map ((:[]) . htxt)
["Name","Executable","Synopsis", "Version", "Upload date"])
rows
where
formatPkgAsRow :: Package -> IO [[BaseHtml]]
formatPkgAsRow pkg = do
ptime <- getUploadTime pkg
return
[ [hrefPrimSmBlock (packageHtmlDir </> pkgref ++ ".html")
[htxt $ name pkg]]
, intercalate [nbsp]
(map (\ (PackageExecutable n _ _) -> [kbdInput [htxt n]])
(executableSpec pkg))
, [htxt $ synopsis pkg]
, [htxt $ showVersion (version pkg)]
, maybe [nbsp] (\t -> [htxt $ toDate t]) ptime
]
where
pkgref = if withversion then packageId pkg else name pkg
toDate ct = show (ctYear ct) ++ show2 (ctMonth ct) ++ show2 (ctDay ct)
where show2 i = '-' : if i < 10 then '0' : show i else show i
generateDocsOfAllPackages :: Config -> [(String,String)] -> String -> IO ()
generateDocsOfAllPackages cfg rcdefs packagedocdir = do
(_,allpkgs) <- getAllPackageSpecs cfg True
mapM_ genDocOfPackage allpkgs
where
genDocOfPackage pkg = inEmptyTempDir $ do
let pname = name pkg
pversion = showVersion (version pkg)
putStrLn $ unlines [dline, "Documenting: " ++ pname, dline]
let cpmcall = cpmCall rcdefs
cmd = unwords [ "rm -rf", pname, "&&"
, cpmcall, "checkout", pname, pversion, "&&"
, "cd", pname, "&&"
, cpmcall, "install", "--noexec", "&&"
, cpmcall, "doc", "--docdir", packagedocdir
, "--url", curryPackagesDocURL, "&&"
, "cd ..", "&&"
, "rm -rf", pname
]
putStrLn $ "CMD: " ++ cmd
system cmd
testAllPackages :: Config -> [(String,String)] -> String -> IO ()
testAllPackages cfg rcdefs statdir = do
(_,allpkgs) <- getAllPackageSpecs cfg True
results <- mapM (checkoutAndTestPackage rcdefs statdir) allpkgs
putStrLn dline
let (incmpt,cmptres) = partition ((<0) . fst) results
unless (null incmpt) $ putStrLn $
"INCOMPATIBLE PACKAGES (NOT TESTED): " ++ unwords (map snd incmpt)
if sum (map fst cmptres) == 0
then putStrLn $ show (length cmptres) ++ " PACKAGES SUCCESSFULLY TESTED!"
else do putStrLn $ "ERRORS OCCURRED IN PACKAGES: " ++
unwords (map snd (filter ((> 0) . fst) cmptres))
exitWith 1
dline :: String
dline = take 78 (repeat '=')
genTarOfAllPackages :: Config -> String -> IO ()
genTarOfAllPackages cfg tardir = do
createDirectoryIfMissing True tardir
putStrLn $ "Generating tar.gz of all package versions in '" ++ tardir ++
"'..."
(allpkgversions,_) <- getAllPackageSpecs cfg False
allpkgs <- fromEL $ mapM (readPackageFromRepository cfg)
(sortBy (\ps1 ps2 -> packageId ps1 <= packageId ps2)
(concat allpkgversions))
mapM_ writePackageAsTar allpkgs
where
writePackageAsTar pkg = do
let pkgname = name pkg
pkgid = packageId pkg
pkgdir = tardir </> pkgid
tarfile = pkgdir ++ ".tar.gz"
putStrLn $ "Checking out '" ++ pkgid ++ "'..."
let checkoutdir = pkgname
system $ unwords [ "rm -rf", checkoutdir, pkgdir ]
fromEL $ do
acquireAndInstallPackageFromSource cfg pkg
checkoutPackage cfg pkg ""
let cmd = unwords [ "cd", checkoutdir, "&&"
, "tar", "cvzf", tarfile, ".", "&&"
, "chmod", "644", tarfile, "&&"
, "cd", "..", "&&", "mv", checkoutdir, pkgdir, "&&"
, "chmod", "-R", "go+rX", pkgdir
]
putStrLn $ "...with command:\n" ++ cmd
ecode <- system cmd
when (ecode>0) $ error $ "ERROR OCCURED IN PACKAGE '" ++ pkgid ++ "'!"
addNewPackage :: Config -> [(String,String)] -> Bool -> IO ()
addNewPackage config rcdefs withtag = do
pkg <- fromEL (loadPackageSpec ".")
when withtag $ setTagInGit pkg
let pkgIndexDir = name pkg </> showVersion (version pkg)
pkgRepositoryDir = repositoryDir config </> pkgIndexDir
pkgInstallDir = packageInstallDir config </> packageId pkg
fromEL $ addPackageToRepository config "." False False
putStrLn $ "Package repository directory '" ++ pkgRepositoryDir ++ "' added."
(ecode,_) <- checkoutAndTestPackage rcdefs "" pkg
when (ecode > 0) $ do
removeDirectoryComplete pkgRepositoryDir
removeDirectoryComplete pkgInstallDir
putStrLn "Checkout/test failure, package deleted in repository directory!"
fromEL $ updateRepository config True True True False
exitWith 1
putStrLn $ "\nEverything looks fine..."
putStrLn $ "\nTo publish the new repository directory, run command:\n"
putStrLn $ "pushd " ++ repositoryDir config ++
" && git add " ++ pkgIndexDir </> packageSpecFile ++
" && git commit -m\"" ++ pkgIndexDir ++ " added\" " ++
" && git push origin master && popd"
setTagInGit :: Package -> IO ()
setTagInGit pkg = do
let ts = 'v' : showVersion (version pkg)
(_,gittag,_) <- evalCmd "git" ["tag","-l",ts] ""
let deltag = if null gittag then [] else ["git tag -d",ts,"&&"]
cmd = unwords $ deltag ++ ["git tag -a",ts,"-m",ts,"&&",
"git push --tags -f"]
putStrLn $ "Execute: " ++ cmd
ecode <- system cmd
when (ecode > 0) $ error "ERROR in setting the git tag"
checkoutAndTestPackage :: [(String,String)] -> String -> Package
-> IO (Int,String)
checkoutAndTestPackage rcdefs statdir pkg = inEmptyTempDir $ do
putStrLn $ unlines [dline, "Testing package: " ++ pkgid, dline]
curdir <- getCurrentDirectory
let bindir = curdir </> "pkgbin"
recreateDirectory bindir
let statfile = if null statdir then "" else statdir </> pkgid ++ ".csv"
unless (null statdir) $ createDirectoryIfMissing True statdir
let checkoutdir = pkgname
cpmcall = cpmCall (rcdefs ++ [("bin_install_path",bindir)])
icmd = unwords $
[ "rm -rf", checkoutdir, "&&"
, cpmcall, "checkout", pkgname, showVersion pkgversion, "&&"
, "cd", checkoutdir, "&&"
, cpmcall, "install", "&&"
, "echo PACKAGE LOAD PATH:", "&&"
, cpmcall, "deps --path" ]
tcmd = unwords $
[ "cd", checkoutdir, "&&"
, "export PATH=" ++ bindir ++ ":$PATH", "&&"
, cpmcall, "test"] ++
(if null statfile then [] else ["-f", statfile]) ++
[ "&&", cpmcall, "uninstall" ]
putStrLn $ "CHECKOUT AND INSTALL WITH COMMAND:\n" ++ icmd
ecode1 <- system icmd
if ecode1 > 0
then do
putStrLn $ "INCOMPATIBLE PACKAGE '" ++ pkgid ++ "'!"
return (-1,pkgid)
else do
putStrLn $ "TEST WITH COMMAND:\n" ++ tcmd
ecode2 <- system tcmd
when (ecode2 > 0) $ putStrLn $
"ERROR OCCURED IN PACKAGE '" ++ pkgid ++ "'!"
return (ecode2,pkgid)
where
pkgname = name pkg
pkgversion = version pkg
pkgid = packageId pkg
sumCSVStatsOfPkgs :: String -> String -> IO ()
sumCSVStatsOfPkgs dir outfile = do
combineCSVFilesInDir readStats showResult addStats ([],[]) dir outfile
putStrLn $ "All results written to file '" ++ outfile ++ "'."
where
readStats rows =
let [pkgid,ct,rc,total,unit,prop,eqv,io,mods] = rows !! 1
in (rows !! 0,
[ (pkgid, ct,
map (\s -> read s :: Int) [rc,total,unit,prop,eqv,io], mods) ])
showResult (header,rows) =
header :
sortBy (<=)
(map (\(pkgid,ct,nums,mods) -> pkgid : ct : map show nums ++ [mods])
rows) ++
["TOTAL:" : "" :
map show
(foldr1 (\nums1 nums2 -> map (uncurry (+)) (zip nums1 nums2))
(map (\ (_,_,ns,_) -> ns) rows))]
addStats (header,rows1) (_,rows2) = (header, rows1 ++ rows2)
combineCSVFilesInDir :: ([[String]] -> a) -> (a -> [[String]]) -> (a -> a -> a)
-> a -> String -> String -> IO ()
combineCSVFilesInDir fromcsv tocsv combine emptycsv statdir outfile = do
dcnts <- getDirectoryContents statdir
let csvfiles = map (statdir </>) (filter (".csv" `isSuffixOf`) dcnts)
stats <- mapM (\f -> readCompleteFile f >>= return . fromcsv . readCSV)
csvfiles
let results = foldr combine emptycsv stats
writeCSVFile outfile (tocsv results)
updatePackage :: Config -> [(String,String)] -> IO ()
updatePackage config rcdefs = do
pkg <- fromEL (loadPackageSpec ".")
let pkgInstallDir = packageInstallDir config </> packageId pkg
setTagInGit pkg
putStrLn $ "Deleting old repo copy '" ++ pkgInstallDir ++ "'..."
removeDirectoryComplete pkgInstallDir
(ecode,_) <- checkoutAndTestPackage rcdefs "" pkg
when (ecode > 0) $ do removeDirectoryComplete pkgInstallDir
putStrLn $ "ERROR in package, CPM index not updated!"
exitWith 1
fromEL $ addPackageToRepository config "." True False
writePackageDependencies :: Config -> [Package] -> IO ()
writePackageDependencies _ pkgs = do
putStrLn $ "Generating package dependency files in directory '" ++
packageHtmlDir ++ "'..."
inDirectory packageHtmlDir $ mapM_ writeDepsOfPackage (map name pkgs)
where
writeDepsOfPackage pname = do
let dotgraph = packageDependenciesAsGraph pkgs pname
htmldepsfile = pname ++ "-deps.html"
putStrLn $ "Writing '" ++ htmldepsfile ++ "'..."
(_,svgtxt,_) <- evalCmd "/usr/bin/dot" ["-Tsvg"] (showDotGraph dotgraph)
depspage <- subdirHtmlPage ("Dependencies of " ++ pname)
(pname ++ ".html",
[htxt $ "Package", nbsp, code [htxt $ pname]])
[h1 [smallMutedText "Dependencies of ", htxt pname]]
[block [htmlText svgtxt]]
writeReadableFile htmldepsfile depspage
visualizePackageDependencies :: Config -> String -> IO ()
visualizePackageDependencies cfg pname = do
(_,pkgs) <- getAllPackageSpecs cfg False
putStrLn "Show dot graph..."
viewDotGraph (packageDependenciesAsGraph pkgs pname)
packageDependenciesAsGraph :: [Package] -> String -> DotGraph
packageDependenciesAsGraph pkgs pname =
let alldeps = map (\p -> (name p, map (\ (Dependency p' _) -> p')
(dependencies p))) pkgs
deps = if null pname then alldeps
else depsOnPkgs alldeps [pname] [] [] `union`
depsOfPkgs alldeps [pname] [] []
in depsToGraph pname deps
type PkgDeps = [(String, [String])]
depsOnPkgs :: PkgDeps -> [String] -> [String] -> PkgDeps -> PkgDeps
depsOnPkgs _ [] seenps deps =
map (\ (pn,ds) -> (pn, ds `intersect` seenps)) deps
depsOnPkgs alldeps (p:ps) seenps deps =
let pdeps = filter ((p `elem`) . snd) alldeps
in depsOnPkgs alldeps (ps `union` nub (map fst pdeps \\ seenps))
(p:seenps) (pdeps `union` deps)
depsOfPkgs :: PkgDeps -> [String] -> [String] -> PkgDeps -> PkgDeps
depsOfPkgs _ [] _ deps = deps
depsOfPkgs alldeps (p:ps) seenps deps =
let pdeps = filter ((==p) . fst) alldeps
in depsOfPkgs alldeps (ps `union` nub (concatMap snd pdeps \\ seenps))
(p:seenps) (pdeps `union` deps)
depsToGraph :: String -> PkgDeps -> DotGraph
depsToGraph pname cpmdeps =
dgraph "Package Dependencies"
(map (\s -> Node s (("URL", s ++ ".html") :
if pname==s then currentPackageStyle else []))
(nub (map fst cpmdeps ++ concatMap snd cpmdeps)))
(map (\ (s,t) -> Edge s t [])
(nub (concatMap (\ (p,ds) -> map (\d -> (p,d)) ds) cpmdeps)))
where
currentPackageStyle = [("style","filled"), ("fillcolor","red")]
writeAllPackages :: Config -> IO ()
writeAllPackages cfg = do
(allpkgs,_) <- getAllPackageSpecs cfg True
putStr "Reading all packages.."
pkginfos <- mapM pkg2csv (sortBy leqP (concat allpkgs))
let outfile = "allpkgs.csv"
writeCSVFile outfile (headline : pkginfos)
putStrLn $ "Infos about all packages written to '" ++ outfile ++ "'"
where
headline = [ "Package name", "Version", "Description", "Upload time"
, "Dependencies", "Exported modules", "Categories"]
leqP p1 p2 = name p1 < name p2 ||
(name p1 == name p2 &&
showVersion (version p1) <= showVersion (version p2))
pkg2csv p = do
putChar '.'
pkg <- fromEL $ readPackageFromRepository cfg p
mbtime <- getUploadTime pkg
return
[ name pkg
, showVersion $ version pkg
, pkg2desc pkg
, show mbtime
, show $ sort $ map (\ (Dependency p' _) -> p') (dependencies pkg)
, show $ sort $ exportedModules pkg
, show $ sort $ category pkg
]
pkg2desc pkg = unwords $ words $
maybe (synopsis pkg)
id
(description pkg)
writeAllPackageDependencies :: Config -> IO ()
writeAllPackageDependencies cfg = do
(_,pkgs) <- getAllPackageSpecs cfg True
let alldeps = map (\p -> name p : showVersion (version p) :
map (\ (Dependency p' _) -> p') (dependencies p))
pkgs
let outfile = "pkgdeps.csv"
writeCSVFile outfile alldeps
putStrLn $ "Package dependencies written to '" ++ outfile ++ "'"
writeAllPackageModules :: Config -> [(String,String)] -> IO ()
writeAllPackageModules cfg rcdefs = do
(allpkgversions,allcompatpkgs) <- getAllPackageSpecs cfg True
putStr "Reading packages:"
allmods <- mapM (\p -> expMods p >>= return . showPkgLine p True)
allcompatpkgs
let allpkgs = concatMap (take 1) allpkgversions
incnames = map name allpkgs \\ map name allcompatpkgs
incpkgs = filter (\p -> name p `elem` incnames) allpkgs
incpmods <- mapM (\p -> expMods p >>= return . showPkgLine p False)
(sortBy (\p1 p2 -> name p1 <= name p2) incpkgs)
let headline = ["Package name", "Version", "#modules", "Module", "..."]
writeCSVFile outFile (headline : allmods ++ incpmods)
putStrLn $ "\nPackage dependencies written to '" ++ outFile ++ "'"
cleanTempDir
where
outFile = "pkgmods.csv"
showPkgLine p cmpt mods =
name p : withBrackets (showVersion (version p))
: show (length mods) : mods
where
withBrackets s = if cmpt then s else '(' : s ++ ")"
expMods p = do
putStr $ " " ++ name p
pkg <- fromEL $ readPackageFromRepository cfg p
let expmods = exportedModules pkg
if null expmods
then do pkgdir <- checkOutPkgInDir rcdefs (name p) (version p)
dirmods <- mapM curryModulesInDirectory
(map (pkgdir </>) (sourceDirsOf pkg))
return (concat dirmods)
else return expmods
checkOutPkgInDir :: [(String,String)] -> String -> Version -> IO String
checkOutPkgInDir rcdefs pname pvers = inTempDir $ do
cdir <- getCurrentDirectory
let cpmcall = cpmCall rcdefs
codir = cdir </> pname
cmd = unwords $
[ "rm -rf", codir, "&&"
, cpmcall, "-v quiet", "checkout", pname, showVersion pvers ]
putStr "*"
ecode <- system cmd
when (ecode>0) $
error $ "COULD NOT CHECKOUT PACKAGE '" ++ pname ++ "'!"
return codir
copyPackageDocumentations :: Config -> String -> IO ()
copyPackageDocumentations cfg packagedocdir = do
allpkgs <- getAllPackages cfg
let pkgs = map sortVersions (groupBy (\a b -> name a == name b) allpkgs)
pkgids = sortBy (\xs ys -> head xs <= head ys) (map (map packageId) pkgs)
putStrLn $ "Number of package documentations: " ++ show (length pkgs)
recreateDirectory currygleDocDir
mapM_ copyPackageDoc pkgids
where
sortVersions ps = sortBy (\a b -> version a `vgt` version b) ps
copyPackageDoc [] = return ()
copyPackageDoc (pid:pids) = do
let pdir = packagedocdir </> pid
exdoc <- doesDirectoryExist pdir
if exdoc
then do putStrLn $ "Copying documentation of " ++ pid ++ "..."
copyDirectory pdir (currygleDocDir </> pid)
else
if null pids
then putStrLn $ "Documentation " ++ pid ++ " does not exist!"
else copyPackageDoc pids
getAllPackages :: Config -> IO [Package]
getAllPackages config = do
fromEL (getBaseRepository config >>= return . allPackages)
readConfiguration :: [(String,String)] -> IO Config
readConfiguration rcdefs = do
c <- fromEL $ readConfigurationWith rcdefs
case c of
Left err -> do putStrLn $ "Error reading .cpmrc file: " ++ err
exitWith 1
Right c' -> return c'
printConfig :: Config -> IO ()
printConfig cfg = do
putStr $ unlines [banner, "Current configuration:", "", showConfiguration cfg]
(allpkgversions,allcompatpkgs) <- getAllPackageSpecs cfg True
putStrLn $ "\nNewest packages compatible to compiler version:\n" ++
unwords (map packageId allcompatpkgs)
let allpkgs = concatMap (take 1) allpkgversions
incnames = map name allpkgs \\ map name allcompatpkgs
putStrLn $ "\nPackages with incompatible compiler dependency:\n" ++
unwords (sort incnames)
inEmptyTempDir :: IO a -> IO a
inEmptyTempDir a = do
tmp <- newTempDir
createDirectoryIfMissing True tmp
r <- inDirectory tmp a
removeDirectoryComplete tmp
return r
newTempDir :: IO String
newTempDir = do
t <- getTemporaryDirectory
pid <- getPID
getNewDir (t </> "cpm" ++ show pid) 0
where
getNewDir base i = do
let tmpdir = base ++ show i
exdir <- doesDirectoryExist tmpdir
if exdir then getNewDir base (i+1)
else return tmpdir
directoryContentsPage :: (String,[BaseHtml]) -> String -> String -> IO String
directoryContentsPage homebrand base dir = do
maindoc <- directoryContentsAsHTML 1 base dir
subdirHtmlPage ("Browse " ++ dir) homebrand
[h1 [smallMutedText "Contents of ", htxt dir]] maindoc
subdirHtmlPage :: String -> (String,[BaseHtml]) -> [BaseHtml] -> [BaseHtml]
-> IO String
subdirHtmlPage pagetitle homebrand header maindoc = do
time <- getLocalTime
let btbase = "../bt4"
return $ showHtmlPage $
bootstrapPage (favIcon btbase) (cssIncludes btbase) (jsIncludes btbase)
pagetitle homebrand
(leftTopMenu True (-1)) rightTopMenu 0 []
header
maindoc (curryDocFooter time)
directoryContentsAsHTML :: Int -> String -> String -> IO [BaseHtml]
directoryContentsAsHTML d base dir = do
exdir <- doesDirectoryExist basedir
if exdir
then do
dirfiles <- getDirectoryContents basedir >>= return . filter isReal
if null dirfiles
then return []
else do
ls <- mapM dirElemAsHTML (sortBy (<=) dirfiles)
let (files,dirs) = partition (\hes -> length hes == 1) ls
return [ulist (files ++ dirs) `addAttr` ("style","list-style: none")]
else return []
where
basedir = base </> dir
dirElemAsHTML df = do
isdir <- doesDirectoryExist (basedir </> df)
if isdir && (d < 10)
then do subdir <- directoryContentsAsHTML (d+1) basedir df
return [code [htxt (df ++ "/")], block subdir]
else return [code [href (basedir </> df)
[htxt $ df ++ if isdir then "/" else ""]]]
isReal fn = not ("." `isPrefixOf` fn)
cpmCall :: [(String,String)] -> String
cpmCall rcdefs =
"cypm" ++ concatMap (\ (k,v) -> " --define " ++ k ++ "=" ++ v) rcdefs
fromEL :: ErrorLogger a -> IO a
fromEL = fromErrorLogger Info False
|