This repository has been archived by the owner on Jun 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cabbage
executable file
·1300 lines (1189 loc) · 37.7 KB
/
cabbage
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
cabalFileExists() {
local NUMCABALS=$(find . -maxdepth 1 -name '?*.cabal' | wc -l)
if [ "$NUMCABALS" -gt 1 ]; then
return 2
elif [ "$NUMCABALS" -eq 1 ]; then
return 0
else
return 1
fi
}
# Print only the library target portion of a .cabal file and filter
# out line comments.
isolateLibraryTarget() {
sed -n '/^[Ll]ibrary/,/^[^[:space:]]/ { /^[Ll]ibrary/p; /^[[:space:]]/p; }'
}
# Print only the executable target portions of a .cabal file.
isolateExecutableTarget() {
sed -n '/^[Ee]xecutable/,/^[^[:space:]]/ { /^[Ee]xecutable/p; /^[[:space:]]/p; }'
}
isolateLibraryAndExecutableTargets() {
local TMP=$(cat *.cabal | sed 's/--.*$//')
echo "$TMP" | isolateLibraryTarget
echo "$TMP" | isolateExecutableTarget
}
# Remove any Cabal block guarded by an "if os(windows)" or "if
# os(solaris)" or "if os(ios)" conditional. This is a very fragile
# test!
removeWindowsBlocks() {
local AWK
read -r -d '' AWK<<'EOF'
BEGIN { windowsIndent = 0; }
{
if(match($0, /if os\(windows\)/)) {
windowsIndent = RSTART;
} else if(match($0, /if os\(solaris\)/)) {
windowsIndent = RSTART;
} else if(match($0, /if os\(ios\)/)) {
windowsIndent = RSTART;
} else if(windowsIndent > 0) {
match($0, /^[[:space:]]*/);
if(RLENGTH <= windowsIndent) {
windowsIndent = 0;
print($0);
}
} else {
print($0);
}
}
EOF
awk "$AWK"
}
# Print the library target of any .cabal file in the current directory
# while removing any blocks guarded by a windows or solaris check.
cabalLibraryTarget() {
if cabalFileExists ; then
cat ./*.cabal | sed 's/--.*$//' | isolateLibraryTarget | removeWindowsBlocks
fi
}
# Take all lines until the next Cabal file stanza begins. The
# assumption is that the first line is the beginning of a stanza, so
# its indentation level determines where the next stanza begins.
stanzaHead() {
local AWK
read -r -d '' AWK<<'EOF'
BEGIN { firstLine = 1; }
{
if(firstLine) {
match($0, /^[[:space:]]*/);
stanzaIndent = RLENGTH;
print $0;
firstLine = 0;
} else {
match($0, /^[[:space:]]*/);
if(RLENGTH <= stanzaIndent) {
exit;
} else {
print $0;
}
}
}
EOF
awk "$AWK"
}
# Print out a .cabal file starting with a pkgconfig-depends line.
pkgconfigDependsStarts() {
cat ./*.cabal | sed 's/--.*$//' | sed -n '/[[:space:]]*[Pp]kg[Cc]onfig-[Dd]epends:/,$ p'
}
# Pull all pkgconfig dependencies from a .cabal file
pkgconfigDepends() {
if cabalFileExists ; then
grep -q -i "[[:space:]]*pkgconfig\-depends:" *.cabal
if [ $? -eq 0 ]; then
pkgconfigDependsStarts | stanzaHead \
| sed -e 's/[Pp]kg[Cc]onfig-[Dd]epends:[[:space:]]*//' -e 's/,/\
/g' | sed 's/^[[:space:]]*//' | sed '/^$/d'
else
echo
fi
fi
}
# Print each build-tool without any version constraint.
cabalBuildTools() {
if cabalFileExists ; then
grep -q -i "[[:space:]]*build-tools:" ./*.cabal
if [ $? -eq 0 ]; then
isolateLibraryAndExecutableTargets | removeWindowsBlocks \
| grep -i "build-tools" | awk 'BEGIN { FS=":"; } { print($2); }' | sed 's/,/\
/g' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]].*$//'
else
echo
fi
fi
}
# GTK's build tools package actually defines multiple build-tool
# executables. If a Cabal package refers to the executable name, we
# need to map that back to the Cabal package that provides that
# executable.
resolveBuildToolPackages() {
sed -e 's/gtk2hsC2hs/gtk2hs-buildtools/' \
-e 's/gtk2hsTypeGen/gtk2hs-buildtools/' \
-e 's/gtk2hsHookGenerator/gtk2hs-buildtools/'
}
allBuildToolsAux() {
cabalBuildTools | resolveBuildToolPackages
if [ -d .cabbages ]; then
local DEPS=($(buildplanDependencies))
local d
(cd .cabbages && \
for d in "${DEPS[@]}"; do
(cd "$d" && cabalBuildTools | resolveBuildToolPackages)
done)
fi
}
# Print the array of all build-tools used to build this package and
# all its dependencies.
allBuildTools1() {
local TOOLS=($(allBuildToolsAux | sort -u))
# hsc2hs comes with GHC
local special
for special in hsc2hs ghc; do
local i=$(findIndex "$special" TOOLS[@])
if [ "$i" -gt -1 ]; then
unset TOOLS[$i]
fi
done
echo "${TOOLS[@]}"
}
# Print the array of all build-tools used to build this package, all
# its dependencies, and the build-tools needed to build those
# build-tools.
allBuildTools() {
local TOOLS=($(allBuildTools1))
local t
local TOOLS2=()
if [ -d .cabbages ]; then
for t in "${TOOLS[@]}"; do
local latest=$(find .cabbages -name "$t-[[:digit:].]*" -depth 1 | tail -n 1)
TOOLS2+=($(cd "$latest" && allBuildTools1))
done
fi
((for t in "${TOOLS[@]}"; do
printf "%s\n" "$t"
done;
for t in "${TOOLS2[@]}"; do
printf "%s\n" "$t"
done) | sort -u)
}
cabalFrameworks() {
if cabalFileExists ; then
grep -q -i "[[:space:]]*frameworks:" ./*.cabal
if [ $? -eq 0 ]; then
cabalLibraryTarget \
| grep -i "frameworks" | awk 'BEGIN { FS=":"; } { print($2); }' | sed 's/,/\
/' | sort -u
fi
fi
}
# Prints out lines of the form "pkgName X.Y.Z" (where X, Y, and Z are
# numbers). One line for each package that will have to be installed
# in a sandbox given the current version of GHC and the contents of
# its global package database.
dryDependencies() {
local EXTRAS=""
if [ "$#" -gt 0 ]; then
if [ $1 -eq 2 ]; then
EXTRAS="--enable-tests --enable-benchmarks"
fi
fi
if [ -f cabbage.config ]; then
local MYNAME=$(cat ./*.cabal | grep -i "name:" | awk 'BEGIN { FS=":"; } {print($2);}' | sed 's/^[[:space:]]*//')
local FLAGS=$(cat cabbage.config | flagsFor "$MYNAME")
if ! [ "$FLAGS" = "" ]; then
EXTRAS="$EXTRAS --flags=\"$FLAGS\""
fi
fi
local CMD="cabal install --dependencies-only --dry-run"
if ! [ "$EXTRAS" = "" ]; then
CMD="$CMD $EXTRAS"
fi
eval $CMD \
| sed -n '3,$ p' | sed '/Warning: /,$ d' \
| sed -e 's/ .*$//' -e 's/\([-_[:alnum:]]*\)-\([[:digit:].]*\)$/\1 \2/' \
| sed '/^[-_[:alnum:]]* [[:digit:]]/ !d'
}
# Reads the buildplan file in the current directory and prints one
# package per line in the form "pkgname-X.Y.Z".
buildplanDependencies() {
if [ -f buildplan ]; then
cat buildplan | sed 's/\([^ ]*\) \(.*\)$/\1-\2/'
else
echo "No buildplan found in $(pwd)"
exit 1
fi
}
# Generate cabal.config contents from a buildplan. This removes
# cabbage-patched version numbers so that "cabal install" can work
# properly.
buildplanConstraints() {
echo "constraints:"; (cat buildplan | sed 's/^\([^ ]*\) \(.*\)$/ \1 ==\2,/' | sed 's/\.4552,$/,/' | sed '$ s/,//')
}
unconstrainCabal() {
local UNCONSTRAIN
read -r -d '' UNCONSTRAIN<<'EOF'
BEGIN {
buildDep = 0;
FS = ",";
}
{
lineSkip = 0;
if(match($0, /^[[:space:]]*[Bb][Uu][Ii][Ll][Dd]-[Dd][Ee][Pp][Ee][Nn][Dd][Ss]:/)) {
buildDep = 1;
match($0, /^[[:space:]]*/);
indentation = RLENGTH;
for(i = 0; i < RLENGTH; ++i) printf(" ");
printf("build-depends:");
sub(/^[[:space:]]*[Bb][Uu][Ii][Ll][Dd]-[Dd][Ee][Pp][Ee][Nn][Dd][Ss]:/,"",$0);
match($0, /^[[:space:]]*/);
for(i = 0; i < RLENGTH; ++i) printf(" ");
sub(/^[[:space:]]*/,"",$0);
} else if(buildDep) {
if(match($0,/^[[:space:]]*$/)) {
lineSkip = 1;
} else {
match($0, /^[[:space:]]*/);
if(RLENGTH <= indentation) {
buildDep = 0;
} else {
for(i = 0; i < RLENGTH; ++i) printf(" ");
sub(/^[[:space:]]*/,"",$0);
}
}
}
if(buildDep && !lineSkip) {
# Update a line of a build-depend
for(i = 1; i <= NF; ++i) {
sub(/^[[:space:]]*/,"",$(i));
sub(/[[:space:]]*$/,"",$(i));
if(match($(i), "[ ><=]")) {
pkgName = substr($(i), 1, RSTART - 1);
printf("%s", pkgName);
} else {
printf("%s", $(i));
}
if(i < NF) printf(", ");
}
printf("\n");
} else {
# Everything else gets printed
print $0
}
}
EOF
awk "$UNCONSTRAIN"
}
# Try freezing after removing all version constraints.
freezeUnconstrained() {
local NUMCABALS=$(find . -maxdepth 1 -name '?*.cabal' | wc -l)
if [ "$NUMCABALS" -gt 1 ]; then
echo "Error: Found multiple cabal files in $(pwd)"
exit 1
fi
local REALCABAL=$(basename "$(ls ./*.cabal)")
(cat "$REALCABAL" | sed 's/--.*$//' | unconstrainCabal) > cabbageDummy.cabal
mv "$REALCABAL" cabbageBackup.bak
mv cabbageDummy.cabal "$REALCABAL"
freezeCabbagePatch 1
local OK=$?
return $OK
}
# List directories of added sources
getAddedSources() {
sed '1,/^$/ d' | sed '/^$/,$ d'
}
# The start of a Cabal library specification, ready for a
# build-depends stanza.
dummyCabalLibrary() {
echo "name: Dummy"
echo "version: 0.1.0.0"
echo "build-type: Simple"
echo "cabal-version: >=1.10"
echo ""
echo "library"
echo " exposed-modules:"
}
# Builds a .cabal file that depends on every package listed in a
# cabal.config file consisting solely of a single "constraints"
# stanza. This is intended to work with Stackage releases.
dummyFromConstraints() {
dummyCabalLibrary; sed -e 's/^constraints:/ build-depends:/' -e 's/^\( [[:space:]]*\)\(.*\)$/\1 \2/' -e 's/^.* installed,$//' cabal.config
}
# Prints the extra-libraires from a cabal file iff they occur in a
# library target.
cabalExtraLibraries() {
if cabalFileExists ; then
grep -q -i "[[:space:]]*extra\-libraries:" ./*.cabal
if [ $? -eq 0 ]; then
cat ./*.cabal | sed 's/--.*$//' | isolateLibraryTarget | removeWindowsBlocks | \
grep -i "extra-libraries" | awk 'BEGIN { FS=":"; } { print($2); }'
fi
fi
}
# Looks in a cabal.config file to identify all dependencies, then
# visits each of them in the .cabbages directory and prints out all
# extra-libraries.
allExtraLibrariesAux() {
local DEPS=($(buildplanDependencies))
local d
cabalExtraLibraries
(cd .cabbages && \
for d in "${DEPS[@]}"; do
(cd "$d" && cabalExtraLibraries)
done)
}
# Print out an array of possibly-needed extra-libraries.
allExtraLibraries() {
local LIBS=($(allExtraLibrariesAux | sed 's/,/\
/'))
if [ "${#LIBS[@]}" -gt 0 ]; then
printf '%s\n' "${LIBS[@]}" | sort -u | tr '\n' ' '
else
echo "${LIBS[@]}"
fi
}
# Let the user know they might need to prepare system dependencies.
warnExtraLibraries() {
local LIBS=($(allExtraLibraries))
if [ "${#LIBS[@]}" -gt 0 ]; then
echo
echo "You may need to supply system dependencies!"
echo
echo "See the cabbage documentation for how to do this with a 'systemDeps'"
echo "section in a cabbage.config file."
echo
echo "Potentially necessary extra-libraries: ${LIBS[@]}"
# read -p "Press any key to continue..." -n 1 -t 5
echo
fi
}
# Unversion package name. Remove the version number from a versioned
# package name.
unversionPackageName() {
sed 's/\(.*\)-[-[:digit:].]*$/\1/' <<< "$1"
}
# Returns any flags set for the given package name in a cabbage.config
# file
flagsFor() {
local FINDFLAGS
read -r -d '' FINDFLAGS<<EOF
BEGIN { inFlags = 0; }
/^flags:/ { inFlags = 1; }
/^[^[:space:]]/ { if(inFlags == 2) { exit 0; } }
{
if(inFlags == 1) {
inFlags = 2;
} else if(inFlags == 2) {
gsub(/^[[:space:]]*/,"",\$1);
if(\$1 == "$1:") {
for(i = 2; i <= NR; ++i) {
printf("%s", \$(i));
if(i != NR) { printf(" "); }
}
}
}
}
EOF
awk "$FINDFLAGS"
}
# Find any systemDeps (system dependencies) specified for the named
# package in a cabbage.config file. The package name should be
# unversioned.
systemDepsFor() {
local FINDDEPS
read -r -d '' FINDDEPS<<EOF
BEGIN { inDeps = 0; }
/^systemDeps:/ { inDeps = 1; }
/^[^[:space:]]/ { if(inDeps == 2) { exit 0; } }
{
if(inDeps == 1) {
inDeps = 2;
} else if(inDeps == 2) {
gsub(/^[[:space:]]*/,"",\$1);
if(\$1 == "$1:") {
for(i = 2; i <= NR; ++i) {
printf("%s", \$(i));
if(i != NR) { printf(" "); }
}
}
}
}
EOF
awk "$FINDDEPS"
}
# Takes a cabbage.config file and distributes subset cabbage.config
# files to directories in the .cabbages directory on an as-needed
# basis. Specifically, the flags for a named package will be copied
# into a cabbage.config file in that package's directory.
sowFlags() {
local AWK
read -r -d '' AWK<<'EOF'
BEGIN { FS = ":"; inFlags = 0;}
/flags:/ { inFlags = 1; }
/^[^[:space:]]/ { if(inFlags == 2) { exit 0; } }
{
if(inFlags == 1) {
inFlags = 2;
} else if(inFlags == 2) {
gsub(/^[[:space:]]*/,"",$1);
cmd = sprintf("find .cabbages -maxdepth 1 -name '%s-[[:digit:].]*'", $1);
if( (cmd | getline versionedName) ) {
flags = sprintf("flags:\n %s:%s\n", $1, $2);
cmd = sprintf("echo '%s' > .cabbages/$(basename \"%s\")/cabbage.config", flags, versionedName);
system(cmd);
} else {
# print "Ignoring flag for unknown dependency:", $1
}
}
}
EOF
awk "$AWK"
}
# Get the package in this directory's full versioned name. E.g. name-x.y.z
getMyFullName() {
local CABAL=$(ls ./*.cabal)
{ (cat "$CABAL" | tr -d '\r' | grep -i "^name:" | sed 's/^[Nn]ame:[[:space:]]*\(.*\)$/\1/');
(cat "$CABAL" | tr -d '\r' | grep -i "^version:" | sed 's/^[Vv]ersion:[[:space:]]*\(.*\)$/\1/'); } \
| tr '\n' '-' | sed 's/-$//'
}
# Takes a directory name, and returns the package that can be built
# from that directory.
getAddedPackageName() {
(cd "$1" && getMyFullName)
}
# Get a source distribution of an added-source package
getAddSource() {
local CWD=$(pwd)
(cd "$1" && cabal sdist -v0 --output-directory="$CWD"/.cabbages/"$(getMyFullName)")
}
# Takes an element and an array, returns -1 if the element is /not/ in
# the array; or its index if it is.
findIndex() {
local i
local -a arr=("${!2}")
for i in "${!arr[@]}"; do
[[ "${arr[$i]}" == "$1" ]] && echo "$i" && return 0; done
echo "-1"
return 1
# for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
# return 1
}
# Get all dependency sources for the package in the current
# directory. This handles add-sourced dependencies, or those that
# "cabal get" can get (i.e. from hackage).
getDependencySources() {
local ADDEDSOURCEDIRS=($(cabal sandbox list-sources | getAddedSources))
local ADDEDSOURCEPACKAGES
local i
for i in "${!ADDEDSOURCEDIRS[@]}"; do
ADDEDSOURCEPACKAGES[$i]=$(getAddedPackageName "${ADDEDSOURCEDIRS[$i]}")
done
local DEPS=($(buildplanDependencies))
mkdir -p .cabbages
local d
for d in "${DEPS[@]}"; do
i=$(findIndex "$d" ADDEDSOURCEPACKAGES[@])
if [ "$i" -gt "-1" ]; then
echo "Getting add-source dependency: $d"
getAddSource "${ADDEDSOURCEDIRS[$i]}"
elif [ -d .cabbages/"$d" ]; then
echo "Using existing source dist of $d"
elif [ "${d: -5}" == ".4552" ]; then
echo "Cabbage patching globally installed package: $d"
cabbagePatch "$d"
else
echo "Getting dependency: $d"
cabal get "$d" -d .cabbages
fi
done
# add-sourced build-tools are handled carefully We first strip off
# the version numbers of the add-sourced packages because
# build-tools are not usually specified with versions. We then
# perform similar logic to how we get library dependencies.
local BUILDTOOLS=($(allBuildTools))
for i in "${!ADDEDSOURCEPACKAGES[@]}"; do
ADDEDSOURCEPACKAGES[$i]=$(unversionPackageName "${ADDEDSOURCEPACKAGES[$i]}")
done
for d in "${BUILDTOOLS[@]}"; do
i=$(findIndex "$d" ADDEDSOURCEPACKAGES[@])
if [ "$i" -gt "-1" ]; then
echo "Getting add-source build-tool: $d"
getAddSource "${ADDEDSOURCEDIRS[$i]}"
elif [ -d .cabbages/"$d" ]; then
echo "Using existing source dist of $d"
else
echo "Getting build-tool: $d"
cabal get "$d" -d .cabbages
fi
done
}
getPackageDBPath() {
if [ -f cabal.sandbox.config ]; then
cabal sandbox hc-pkg list | grep ".conf.d" | tail -n 1 | sed 's/.*\/\(.*\)-packages.conf.d.*/\1/'
return 0
else
return 1
fi
}
getSynopsis() {
local CABAL=$(ls ./*.cabal)
cat "$CABAL" | sed -n '/^[Ss]ynopsis/,/^[^[:space:]]/ p' | sed '$d' \
| sed -e 's/^[Ss]ynopsis:[[:space:]]*//' -e 's/^[[:space:]]*//' -e 's/"/\\"/g' \
| tr '\n' ' '
}
# Define an attribute for each package. Takes an array of attribute
# names, and an array of corresponding directory names that are home
# to Nix package definitions (these are all in the .cabbages
# directory).
callCabbages() {
local -a NAMES=("${!1}")
local -a PKGS=("${!2}")
local i
for ((i = 0; i < ${#NAMES[@]}; ++i)); do
local TOOLSARR=($(cd .cabbages/${PKGS[$i]} && allBuildTools))
local TOOLS=""
if [ ${#TOOLSARR[@]} -gt 0 ]; then
TOOLS=" $(echo ${TOOLSARR[@]})"
fi
echo " ${NAMES[$i]} = callPackage .cabbages/${PKGS[$i]} {"
echo " inherit frozenCabbages haskellBuildTools pkgs$TOOLS;"
echo " };"
done
}
# Build a .nix file from a .cabal file in the current directory Takes
# the ghcPlatform string, this package's name, and whether or not this
# package should define frozenCabbages: 0 = this is an upstream
# package, 1 = this is a downstream package, 2 = this is a build-tool.
mkCabbage() {
local NIX
local FROZENUPSTREAM
local FROZENDEF
local LINKSANDBOX
local DEPS=($(buildplanDependencies))
local DEPNAMES=($(cat buildplan | sed 's/ .*$//'))
if [ $3 -gt 0 ]; then
# This is /the/ downstream package or a build-tool
# We will need the standard callPackage function
FROZENUPSTREAM="callPackage, frozenCabbages ? {}"
# We will define the frozenCabbages attribute
IFS=$'\n' read -r -d '' FROZENDEF <<EOF
myCabbages = lib.fix (frozenCabbages: {
$(callCabbages DEPNAMES[@] DEPS[@])
});
EOF
# We will seed the sandbox /in this directory/ with our
# dependencies in the nix store so the user can continue using a
# standard cabal workflow (e.g. tools like ghc-mod).
mkdir -p .cabal-sandbox/lib/"$1"
LINKSANDBOX="ln -sFf \${pkg.outPath}/.cabal-sandbox/$1-packages.conf.d/*.conf "$(pwd)"/.cabal-sandbox/$1-packages.conf.d/\n";
# We create a dummy sdist file so that the src attribute on the
# downstream package's nix expression is a file, even if its
# contents are currently bogus. This is done so that Nix can
# evaluate the expression and install dependencies, without which
# the configure phase (run in order to produce the sdist) of the
# downstream package can fail due to missing dependencies.
if ! [ -d "./dist" ]; then
mkdir dist
fi
if ! [ -f "./dist/$2.tar.gz" ]; then
touch "./dist/$2.tar.gz"
fi
else
# This is an upstream package (dependency)
FROZENUPSTREAM="frozenCabbages"
fi
local SYNOPSIS=$(getSynopsis)
local SYSTEMDEPS=""
if [ -f ../../cabbage.config ]; then
local MYNAME=$(unversionPackageName "$2")
SYSTEMDEPS=$(cat ../../cabbage.config | systemDepsFor "$MYNAME")
fi
if [ -f cabbage.config ]; then
local MYNAME=$(unversionPackageName "$2")
SYSTEMDEPS=$(cat cabbage.config | systemDepsFor "$MYNAME")
fi
local PKGS=($(pkgconfigDepends))
if [ "${#PKGS[@]}" -gt 0 ]; then
SYSTEMDEPS="$SYSTEMDEPS pkgconfig"
fi
local TOOLS=($(allBuildTools))
local TOOLSDEPS=""
if [ "${#TOOLS[@]}" -gt 0 ]; then
TOOLSDEPS=$(echo "${TOOLS[@]}" | awk '{for(i=1;i<=NF;i++) printf(", %s",$(i));}')
fi
local FRAMEWORKS=($(cabalFrameworks))
local NIXFW=""
SYSTEMDEPS="[ $SYSTEMDEPS ]"
if [ "${#FRAMEWORKS[@]}" -gt 0 ]; then
# We need to replace uses of CoreFoundation with darwin.cf-private
# and ensure that it is at the start of the framework search path
# since it overlaps with another nixpkgs CoreFoundation framework.
echo "${FRAMEWORKS[@]}" | grep -q CoreFoundation
if [ $? -eq 0 ]; then
FRAMEWORKS=($(echo "${FRAMEWORKS[@]}" | sed 's/CoreFoundation[[:space:]]*//'))
FRAMEWORKS=("darwin.cf-private ${FRAMEWORKS[@]}")
fi
# Hack to pull in the Kernel framework.
# Needed by some uses of IOKit, for example.
FRAMEWORKS=("${FRAMEWORKS[@]} Kernel")
SYSTEMDEPS="($SYSTEMDEPS ++ lib.optionals stdenv.isDarwin (with darwin.apple_sdk.frameworks; [ ${FRAMEWORKS[@]} ]))"
local fw
for fw in "${FRAMEWORKS[@]}"; do
NIXFW="$NIXFW -framework $fw"
done
fi
# Now we build up the Nix expression
IFS=$'\n' read -r -d '' NIX <<EOF
{ stdenv, lib, haskellBuildTools, pkgs$TOOLSDEPS, $FROZENUPSTREAM }:
let cabalTmp = "cabal --config-file=./.cabal/config";
$FROZENDEF
mkCmd = pkg: let nm = lib.strings.removePrefix "haskell-" pkg.name;
p = pkg.outPath;
pkgPath = ".cabal-sandbox/$1-packages.conf.d";
in ''ln -sFf \${p}/\${pkgPath}/*.conf \$out/\${pkgPath}/
'';
$(if [ $3 -eq 1 ]; then
echo " mkSetupCmd = pkg: let nm = lib.strings.removePrefix \"haskell-\" pkg.name;"
echo " p = pkg.outPath;"
echo " in \"$LINKSANDBOX\";"
elif [ $3 -eq 2 ]; then
echo " mkSetupCmd = pkg: \"\";"
fi)
in
stdenv.mkDerivation rec {
name = "haskell-$2";
src = $(if [ $3 -eq 1 ]; then
echo "./dist/$2.tar.gz"
else
echo "./."
fi);
$(if [ $3 -gt 0 ]; then
echo -n " cabbageDeps = with myCabbages; [ "
else
echo -n " cabbageDeps = with frozenCabbages; [ "
fi)
$(echo "${DEPNAMES[@]}") ];
systemDeps = (with pkgs; $SYSTEMDEPS) ++
lib.lists.unique (lib.concatMap (lib.attrByPath ["systemDeps"] []) cabbageDeps);
propagatedBuildInputs = systemDeps;
buildInputs = [ stdenv.cc $(echo "${TOOLS[@]}")] ++ haskellBuildTools ++ cabbageDeps ++ systemDeps;
# Build the commands to merge package databases
cmds = lib.strings.concatStrings (map mkCmd cabbageDeps);
$(if [ $3 -gt 0 ]; then
cat << SETUPEOF
setupCmds = lib.strings.concatStrings (map mkSetupCmd cabbageDeps);
setup = builtins.toFile "setup.sh" ''
# Takes a GHC platform string, an array of add-source dependency
# directories, and a string of old timestamps. Produces a new
# timestamp string.
updateTimeStamps() {
local -a DEPS=("''\${!2}")
local CUR_TIME=\$(date +%s)
local i
local STAMPED
for ((i = 0; i < "''\${#DEPS[@]}"; ++i)); do
STAMPED[\$i]="(\"''\${DEPS[\$i]}\",\$CUR_TIME)"
done
local LIST=\$(printf ",%s" "''\${STAMPED[@]}")
LIST=''\${LIST:1}
local NEWSTAMP="(\"\$1\",[\$LIST])"
if echo "\$3" | grep -q "\$1"; then
echo "\$3" | sed "s:(\"\$1\",[^]]*\]):\$NEWSTAMP:"
elif echo "\$3" | grep -q "]\\\\$"; then
echo "\$3" | sed "s:\]\\\$:,\$NEWSTAMP]:"
else
echo "[\$NEWSTAMP]"
fi
}
eval "\$setupCmds"
\${cabalTmp} sandbox hc-pkg recache
SRCS=(\$(cabal sandbox list-sources | sed '1,/^\$/ d' | sed '/^\$/,\$ d'))
OLDTIMESTAMPS=\$(cat .cabal-sandbox/add-source-timestamps)
updateTimeStamps "$1" SRCS[@] "\$OLDTIMESTAMPS" > .cabal-sandbox/add-source-timestamps
'';
SETUPEOF
fi)
builder = builtins.toFile "builder.sh" ''
source \$stdenv/setup
mkdir \$out
if [ -d "\$src" ]; then
cp -R "\$src"/* .
#*/
if [ -f \$src/buildplan ]; then
mkdir \$out/.cabbageCache
cp "\$src/buildplan" "\$out/.cabbageCache/buildplan"
fi
else
tar xf "\$src" --strip=1
fi
chmod -R u+w .
if [ -d dist ]; then
# Copy pre-generated dist files to store
cp -R dist \$out
fi
\${cabalTmp} sandbox --sandbox=\$out/.cabal-sandbox init -v0
mkdir -p \$out/.cabal-sandbox/lib/$1
eval "\$cmds"
\${cabalTmp} sandbox hc-pkg recache
\${cabalTmp} --builddir=\$out/dist --bindir=\$out/bin --libexecdir=\$out/libexec --libdir=\$out/.cabal-sandbox/lib --with-gcc=\$CC configure -p \$(echo \$NIX_LDFLAGS | awk -e '{ for(i=1;i <= NF; i++) { if(match(\$(i), /^-L/)) printf("--extra-lib-dirs=%s ", substr(\$(i),3)); } }')
echo "Building..."
# Ensure framework dependencies are used by GHC as they are needed
# when GHC invokes a C compiler.
COPTS=\$(echo "\$NIX_CFLAGS_COMPILE" | awk -e '{ for(i=1; i<=NF; i++) { if (match(\$(i), /^-F/)) printf("-optc %s ", \$(i)); }}')
\${cabalTmp} --builddir=\$out/dist build -v0 --ghc-options="\$COPTS"
\${cabalTmp} --builddir=\$out/dist haddock -v0 || true
\${cabalTmp} --builddir=\$out/dist copy
\${cabalTmp} --builddir=\$out/dist register
\${cabalTmp} --builddir=\$out/dist clean || true
'';
meta = {
description = "$SYNOPSIS";
};
}
EOF
echo "$NIX" > default.nix
}
# Freezes the cabal file in the current directory. Takes the versioned
# name of the package to prepare, and the dbPath for the current
# platform (e.g. x86_64-osx-ghc-7.8.4).
prepCabbage() {
local d="$1"
local dbPath="$2"
local FLAGS
cabal sandbox init --sandbox=../../.cabal-sandbox > /dev/null
if [ -f cabal.config ]; then
mv cabal.config cabal.config.bak
fi
ln -s ../../bpconstraints cabal.config
if [ -n "$FLAGS" ]; then
freezeCabbagePatch 0 > /dev/null
else
freezeCabbagePatch > /dev/null
fi
rm cabal.config
if [ -f cabal.config.bak ]; then
mv cabal.config.bak cabal.config
fi
rm cabal.sandbox.config
mkCabbage "$dbPath" "$d" 0
}
# Takes a flag to determine if the dependencies of all targets should
# be built. If the flag is true, then the build-depends of all targets
# are consolidated and considered when determining a build plan. The
# second argument is another flag for which true indicates this is a
# downstream package, and false indicates this is a build-tool.
mkCabbages() {
local NUMCABALS=$(find . -maxdepth 1 -name '?*.cabal' | wc -l)
if [ "$NUMCABALS" -gt 1 ]; then
echo "Error: Found multiple cabal files in $(pwd)!"
exit 1
fi
if [ "$1" = true ]; then
freezeCabbagePatch 2
else
freezeCabbagePatch 1
if ! [ $? -eq 0 ]; then
if [ "$2" = false ]; then
echo "Trying emergency constraint patch..."
freezeUnconstrained
fi
fi
fi
if [ -f "$CABAL.cabbage.bak" ]; then
mv "$CABAL.cabbage.bak" "$CABAL"
fi
local RES=$?
if [ $RES -ne 0 ]; then
echo "Freezing the downstream package $(pwd) failed ($RES)" && false
else
echo "Froze downstream package at $(pwd)"
fi
local dbPath=$(getPackageDBPath)
local deps=($(buildplanDependencies))
getDependencySources
if [ -f cabbage.config ]; then
cat cabbage.config | sowFlags
fi
# Print a message if there are extra-libraries sepecified in any
# .cabal file used to build the downstream package that is not
# obviously guarded by an os(windows) or os(solaris) check.
warnExtraLibraries
# Build a constraints file the upstream packages can use when
# computing their own build plans.
buildplanConstraints > bpconstraints
pushd .cabbages > /dev/null
local d
# We execute several calls to prepCabbage in parallel
#local numPar=$(getconf _NPROCESSORS_ONLN)
local numPar=1
local pids=()
local numJobs=0
for d in "${deps[@]}"; do
echo "Making cabbage: $d"
if [ -f "$d"/default.nix ]; then
echo "Using existing default.nix"
else
(cd "$d" && prepCabbage "$d" "$dbPath") &
pids+=($!)
numJobs=$((numJobs + 1))
if [ "$numJobs" -eq "$numPar" ]; then
for p in ${pids[@]}; do
wait $p
done
pids=()
numJobs=0
fi
fi
done
for p in ${pids[@]}; do
wait $p
done
popd > /dev/null
rm bpconstraints
local BUILDTOOLS=($(allBuildTools))
if [ "${#BUILDTOOLS}" -gt 0 ]; then
echo "Making cabbages for build-tools"
pushd .cabbages > /dev/null
local bt
for bt in "${BUILDTOOLS[@]}"; do
# cabal get "$bt"
# if ! [ "$?" -eq 0 ]; then
# local ANS
# echo
# echo "WARNING: cabal get did not unpack $bt"
# read -p "Should we continue? [Y/n] " -n 1 -t 5 ANS
# echo
# if [ "$ANS" = "n" ]; then
# exit 1
# fi
# fi
local d=$(find . -name "$bt-[[:digit:].]*" -depth 1)
local dresult=$?
if [ "$d" = "" ]; then
echo "WARNING: Couldn't find build tool: $bt"
else
d=$(basename "$d")
echo "Making build-tool cabbage: $d"
(cd "$d" && cabal sandbox init && mkCabbages false false && cabal sandbox delete)
fi
done
popd > /dev/null
fi
if [ "$2" = true ]; then
mkCabbage "$dbPath" "$(getMyFullName)" 1
else
mkCabbage "$dbPath" "$(getMyFullName)" 2
fi
}
# Takes a cabbage-patched versioned package name; prepares an sdist.
cabbagePatch() {
if ! [ ${1: -5} = ".4552" ]; then
echo "Bad call to cabbagePatch with $1"
exit 1
fi
local NAME=${1%".4552"}
cabal get "$NAME" -d .cabbages
(cd .cabbages && \
mv "$NAME" "$1" && \
(cd "$1" && \
local CABAL=$(basename "$(ls ./*.cabal)") && \
mv "$CABAL" "$CABAL".bak && \
sed 's/\([Vv]ersion:[[:space:]]*\)\([[:digit:].]*\)$/\1\2.4552/' "$CABAL".bak > "$CABAL" && \
rm "$CABAL".bak))
}
# Determines if a newer version of a globally installed package is
# required. If so, the exit code is 1. If no globally-installed
# package is to be upgraded, the exit code is 0.
upgradesGlobal() {
local AWK
read -r -d '' AWK<<'EOF'
BEGIN {
firstLine = 1;
}
{
if(firstLine) {
split($0,arr," ");
for(i in arr) {
match(arr[i], /-[[:digit:].]*$/);
pkg = substr(arr[i], 1, RSTART-1);