-
Notifications
You must be signed in to change notification settings - Fork 9
/
bootstrap.py
executable file
·1460 lines (1241 loc) · 51.7 KB
/
bootstrap.py
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 python
"""
About
=====
This python script is design to do the bare minimum to compile and link the
Cargo binary for the purposes of bootstrapping itself on a new platform for
which cross-compiling isn't possible. I wrote this specifically to bootstrap
Cargo on [Bitrig](https://bitrig.org). Bitrig is a fork of OpenBSD that uses
clang/clang++ and other BSD licensed tools instead of GNU licensed software.
Cross compiling from another platform is extremely difficult because of the
alternative toolchain Bitrig uses.
With this script, all that should be necessary to run this is a working Rust
toolchain, Python, and Git.
This script will not set up a full cargo cache or anything. It works by
cloning the cargo index and then starting with the cargo dependencies, it
recursively builds the dependency tree. Once it has the dependency tree, it
starts with the leaves of the tree, doing a breadth first traversal and for
each dependency, it clones the repo, sets the repo's head to the correct
revision and then executes the build command specified in the cargo config.
This bootstrap script uses a temporary directory to store the built dependency
libraries and uses that as a link path when linking dependencies and the
cargo binary. The goal is to create a statically linked cargo binary that is
capable of being used as a "local cargo" when running the main cargo Makefiles.
Dependencies
============
* pytoml -- used for parsing toml files.
https://github.com/avakar/pytoml
* dulwich -- used for working with git repos.
https://git.samba.org/?p=jelmer/dulwich.git;a=summary
Both can be installed via the pip tool:
```sh
sudo pip install pytoml dulwich
```
Command Line Options
====================
```
--cargo-root <path> specify the path to the cargo repo root.
--target-dir <path> specify the location to store build results.
--crate-index <path> path to where crates.io index shoudl be cloned
--no-clone don't clone crates.io index, --crate-index must point to existing clone.
--no-clean don't remove the folders created during bootstrapping.
--download only download the crates needed to bootstrap cargo.
--graph output dot format graph of dependencies.
--target <triple> build target: e.g. x86_64-unknown-bitrig
--host <triple> host machine: e.g. x86_64-unknown-linux-gnu
--urls-file <file> file to write crate URLs to
--blacklist <crates> list of blacklisted crates to skip
--include-optional <crates> list of optional crates to include
--patchdir <dir> directory containing patches to apply to crates after fetching them
--save-crate if set, save .crate file when downloading
```
The `--cargo-root` option defaults to the current directory if unspecified. The
target directory defaults to Python equivilent of `mktemp -d` if unspecified.
The `--crate-index` option specifies where the crates.io index will be cloned. Or,
if you already have a clone of the index, the crates index should point there
and you should also specify `--no-clone`. The `--target` option is used to
specify which platform you are bootstrapping for. The `--host` option defaults
to the value of the `--target` option when not specified.
Examples
========
To bootstrap Cargo on (Bitrig)[https://bitrig.org] I followed these steps:
* Cloned this [bootstrap script repo](https://github.com/dhuseby/cargo-bootstra)
to `/tmp/bootstrap`.
* Cloned the [crates.io index](https://github.com/rust-lang/crates.io-index)
to `/tmp/index`.
* Created a target folder, `/tmp/out`, for the output.
* Cloned the (Cargo)[https://github.com/rust-lang/cargo] repo to `/tmp/cargo`.
* Copied the bootstrap.py script to the cargo repo root.
* Ran the bootstrap.py script like so:
```sh
./bootstrap.py --crate-index /tmp/index --target-dir /tmp/out --no-clone --no-clean --target x86_64-unknown-bitrig
```
After the script completed, there is a Cargo executable named `cargo-0_2_0` in
`/tmp/out`. That executable can then be used to bootstrap Cargo from source by
specifying it as the `--local-cargo` option to Cargo's `./configure` script.
"""
import argparse
import cStringIO
import hashlib
import inspect
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import urlparse
import socket
import requests
import pytoml as toml
import dulwich.porcelain as git
from glob import glob
TARGET = None
HOST = None
GRAPH = None
URLS_FILE = None
CRATE_CACHE = None
CRATES_INDEX = 'git://github.com/rust-lang/crates.io-index.git'
CARGO_REPO = 'git://github.com/rust-lang/cargo.git'
CRATE_API_DL = 'https://crates.io/api/v1/crates/%s/%s/download'
SV_RANGE = re.compile(r'^(?P<op>(?:\<=|\>=|=|\<|\>|\^|\~))?\s*'
r'(?P<major>(?:\*|0|[1-9][0-9]*))'
r'(\.(?P<minor>(?:\*|0|[1-9][0-9]*)))?'
r'(\.(?P<patch>(?:\*|0|[1-9][0-9]*)))?'
r'(\-(?P<prerelease>[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?'
r'(\+(?P<build>[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$')
SEMVER = re.compile(r'^\s*(?P<major>(?:0|[1-9][0-9]*))'
r'(\.(?P<minor>(?:0|[1-9][0-9]*)))?'
r'(\.(?P<patch>(?:0|[1-9][0-9]*)))?'
r'(\-(?P<prerelease>[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?'
r'(\+(?P<build>[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$')
BSCRIPT = re.compile(r'^cargo:(?P<key>([^\s=]+))(=(?P<value>.+))?$')
BNAME = re.compile('^(lib)?(?P<name>([^_]+))(_.*)?$')
BUILT = {}
CRATES = {}
CVER = re.compile("-([^-]+)$")
UNRESOLVED = []
PFX = []
BLACKLIST = []
INCLUDE_OPTIONAL = []
def dbgCtx(f):
def do_dbg(self, *cargs):
PFX.append(self.name())
ret = f(self, *cargs)
PFX.pop()
return ret
return do_dbg
def dbg(s):
print '%s: %s' % (':'.join(PFX), s)
class PreRelease(object):
def __init__(self, pr):
self._container = []
if pr is not None:
self._container += str(pr).split('.')
def __str__(self):
return '.'.join(self._container)
def __repr__(self):
return self._container
def __getitem__(self, key):
return self._container[key]
def __len__(self):
return len(self._container)
def __gt__(self, rhs):
return not ((self < rhs) or (self == rhs))
def __ge__(self, rhs):
return not (self < rhs)
def __le__(self, rhs):
return not (self > rhs)
def __eq__(self, rhs):
return self._container == rhs._container
def __ne__(self, rhs):
return not (self == rhs)
def __lt__(self, rhs):
if self == rhs:
return False
# not having a pre-release is higher precedence
if len(self) == 0:
if len(rhs) == 0:
return False
else:
# 1.0.0 > 1.0.0-alpha
return False
else:
if len(rhs) is None:
# 1.0.0-alpha < 1.0.0
return True
# if both have one, then longer pre-releases are higher precedence
if len(self) > len(rhs):
# 1.0.0-alpha.1 > 1.0.0-alpha
return False
elif len(self) < len(rhs):
# 1.0.0-alpha < 1.0.0-alpha.1
return True
# if both have the same length pre-release, must check each piece
# numeric sub-parts have lower precedence than non-numeric sub-parts
# non-numeric sub-parts are compared lexically in ASCII sort order
for l,r in zip(self, rhs):
if l.isdigit():
if r.isdigit():
if int(l) < int(r):
# 2 > 1
return True
elif int(l) > int(r):
# 1 < 2
return False
else:
# 1 == 1
continue
else:
# 1 < 'foo'
return True
else:
if r.isdigit():
# 'foo' > 1
return False
# both are non-numeric
if l < r:
return True
elif l > r:
return False
raise RuntimeError('PreRelease __lt__ failed')
class Semver(dict):
def __init__(self, sv):
match = SEMVER.match(str(sv))
if match is None:
raise ValueError('%s is not a valid semver string' % sv)
self._input = sv
self.update(match.groupdict())
self.prerelease = PreRelease(self['prerelease'])
def __str__(self):
major, minor, patch, prerelease, build = self.parts_raw()
s = ''
if major is None:
s += '0'
else:
s += major
s += '.'
if minor is None:
s += '0'
else:
s += minor
s += '.'
if patch is None:
s += '0'
else:
s += patch
if len(self.prerelease):
s += '-' + str(self.prerelease)
if build is not None:
s += '+' + build
return s
def __hash__(self):
return hash(str(self))
def as_range(self):
return SemverRange('=%s' % self)
def parts(self):
major, minor, patch, prerelease, build = self.parts_raw()
if major is None:
major = '0'
if minor is None:
minor = '0'
if patch is None:
patch = '0'
return (int(major),int(minor),int(patch),prerelease,build)
def parts_raw(self):
return (self['major'],self['minor'],self['patch'],self['prerelease'],self['build'])
def __lt__(self, rhs):
lmaj,lmin,lpat,lpre,_ = self.parts()
rmaj,rmin,rpat,rpre,_ = rhs.parts()
if lmaj < rmaj:
return True
if lmaj > rmaj:
return False
if lmin < rmin:
return True
if lmin > rmin:
return False
if lpat < rpat:
return True
if lpat > rpat:
return False
if lpre is not None and rpre is None:
return True
if lpre is not None and rpre is not None:
if self.prerelease < rhs.prerelease:
return True
return False
def __le__(self, rhs):
return not (self > rhs)
def __gt__(self, rhs):
return not ((self < rhs) or (self == rhs))
def __ge__(self, rhs):
return not (self < rhs)
def __eq__(self, rhs):
# build metadata is only considered for equality
lmaj,lmin,lpat,lpre,lbld = self.parts()
rmaj,rmin,rpat,rpre,rbld = rhs.parts()
return lmaj == rmaj and \
lmin == rmin and \
lpat == rpat and \
lpre == rpre and \
lbld == rbld
def __ne__(self, rhs):
return not (self == rhs)
class SemverRange(object):
def __init__(self, sv):
self._input = sv
self._lower = None
self._upper = None
self._op = None
self._semver = None
sv = str(sv)
svs = [x.strip() for x in sv.split(',')]
if len(svs) > 1:
self._op = '^'
for sr in svs:
rang = SemverRange(sr)
if rang.lower() is not None:
if self._lower is None or rang.lower() < self._lower:
self._lower = rang.lower()
if rang.upper() is not None:
if self._upper is None or rang.upper() > self._upper:
self._upper = rang.upper()
op, semver = rang.op_semver()
if semver is not None:
if op == '>=':
if self._lower is None or semver < self._lower:
self._lower = semver
if op == '<':
if self._upper is None or semver > self._upper:
self._upper = semver
return
match = SV_RANGE.match(sv)
if match is None:
raise ValueError('%s is not a valid semver range string' % sv)
svm = match.groupdict()
op, major, minor, patch, prerelease, build = svm['op'], svm['major'], svm['minor'], svm['patch'], svm['prerelease'], svm['build']
prerelease = PreRelease(prerelease)
# fix up the op
if op is None:
if major == '*' or minor == '*' or patch == '*':
op = '*'
else:
# if no op was specified and there are no wildcards, then op
# defaults to '^'
op = '^'
else:
self._semver = Semver(sv[len(op):])
if op not in ('<=', '>=', '<', '>', '=', '^', '~', '*'):
raise ValueError('%s is not a valid semver operator' % op)
self._op = op
# lower bound
def find_lower():
if op in ('<=', '<', '=', '>', '>='):
return None
if op == '*':
# wildcards specify a range
if major == '*':
return Semver('0.0.0')
elif minor == '*':
return Semver(major + '.0.0')
elif patch == '*':
return Semver(major + '.' + minor + '.0')
elif op == '^':
# caret specifies a range
if patch is None:
if minor is None:
# ^0 means >=0.0.0 and <1.0.0
return Semver(major + '.0.0')
else:
# ^0.0 means >=0.0.0 and <0.1.0
return Semver(major + '.' + minor + '.0')
else:
# ^0.0.1 means >=0.0.1 and <0.0.2
# ^0.1.2 means >=0.1.2 and <0.2.0
# ^1.2.3 means >=1.2.3 and <2.0.0
if int(major) == 0:
if int(minor) == 0:
# ^0.0.1
return Semver('0.0.' + patch)
else:
# ^0.1.2
return Semver('0.' + minor + '.' + patch)
else:
# ^1.2.3
return Semver(major + '.' + minor + '.' + patch)
elif op == '~':
# tilde specifies a minimal range
if patch is None:
if minor is None:
# ~0 means >=0.0.0 and <1.0.0
return Semver(major + '.0.0')
else:
# ~0.0 means >=0.0.0 and <0.1.0
return Semver(major + '.' + minor + '.0')
else:
# ~0.0.1 means >=0.0.1 and <0.1.0
# ~0.1.2 means >=0.1.2 and <0.2.0
# ~1.2.3 means >=1.2.3 and <1.3.0
return Semver(major + '.' + minor + '.' + patch)
raise RuntimeError('No lower bound')
self._lower = find_lower()
def find_upper():
if op in ('<=', '<', '=', '>', '>='):
return None
if op == '*':
# wildcards specify a range
if major == '*':
return None
elif minor == '*':
return Semver(str(int(major) + 1) + '.0.0')
elif patch == '*':
return Semver(major + '.' + str(int(minor) + 1) + '.0')
elif op == '^':
# caret specifies a range
if patch is None:
if minor is None:
# ^0 means >=0.0.0 and <1.0.0
return Semver(str(int(major) + 1) + '.0.0')
else:
# ^0.0 means >=0.0.0 and <0.1.0
return Semver(major + '.' + str(int(minor) + 1) + '.0')
else:
# ^0.0.1 means >=0.0.1 and <0.0.2
# ^0.1.2 means >=0.1.2 and <0.2.0
# ^1.2.3 means >=1.2.3 and <2.0.0
if int(major) == 0:
if int(minor) == 0:
# ^0.0.1
return Semver('0.0.' + str(int(patch) + 1))
else:
# ^0.1.2
return Semver('0.' + str(int(minor) + 1) + '.0')
else:
# ^1.2.3
return Semver(str(int(major) + 1) + '.0.0')
elif op == '~':
# tilde specifies a minimal range
if patch is None:
if minor is None:
# ~0 means >=0.0.0 and <1.0.0
return Semver(str(int(major) + 1) + '.0.0')
else:
# ~0.0 means >=0.0.0 and <0.1.0
return Semver(major + '.' + str(int(minor) + 1) + '.0')
else:
# ~0.0.1 means >=0.0.1 and <0.1.0
# ~0.1.2 means >=0.1.2 and <0.2.0
# ~1.2.3 means >=1.2.3 and <1.3.0
return Semver(major + '.' + str(int(minor) + 1) + '.0')
raise RuntimeError('No upper bound')
self._upper = find_upper()
def __repr__(self):
return "SemverRange(%s, op=%s, semver=%s, lower=%s, upper=%s)" % (repr(self._input), self._op, self._semver, self._lower, self._upper)
def __str__(self):
return self._input
def lower(self):
return self._lower
def upper(self):
return self._upper
def op_semver(self):
return self._op, self._semver
def compare(self, sv):
if not isinstance(sv, Semver):
sv = Semver(sv)
op = self._op
if op == '*':
if self._semver is not None and self._semver['major'] == '*':
return sv >= Semver('0.0.0')
if self._lower is not None and sv < self._lower:
return False
if self._upper is not None and sv >= self._upper:
return False
return True
elif op == '^':
return (sv >= self._lower) and (sv < self._upper)
elif op == '~':
return (sv >= self._lower) and (sv < self._upper)
elif op == '<=':
return sv <= self._semver
elif op == '>=':
return sv >= self._semver
elif op == '<':
return sv < self._semver
elif op == '>':
return sv > self._semver
elif op == '=':
return sv == self._semver
raise RuntimeError('Semver comparison failed to find a matching op')
def test_semver():
"""
Tests for Semver parsing. Run using py.test: py.test bootstrap.py
"""
assert str(Semver("1")) == "1.0.0"
assert str(Semver("1.1")) == "1.1.0"
assert str(Semver("1.1.1")) == "1.1.1"
assert str(Semver("1.1.1-alpha")) == "1.1.1-alpha"
assert str(Semver("1.1.1-alpha.1")) == "1.1.1-alpha.1"
assert str(Semver("1.1.1-alpha+beta")) == "1.1.1-alpha+beta"
assert str(Semver("1.1.1-alpha+beta.1")) == "1.1.1-alpha+beta.1"
def test_semver_eq():
assert Semver("1") == Semver("1.0.0")
assert Semver("1.1") == Semver("1.1.0")
assert Semver("1.1.1") == Semver("1.1.1")
assert Semver("1.1.1-alpha") == Semver("1.1.1-alpha")
assert Semver("1.1.1-alpha.1") == Semver("1.1.1-alpha.1")
assert Semver("1.1.1-alpha+beta") == Semver("1.1.1-alpha+beta")
assert Semver("1.1.1-alpha.1+beta") == Semver("1.1.1-alpha.1+beta")
assert Semver("1.1.1-alpha.1+beta.1") == Semver("1.1.1-alpha.1+beta.1")
def test_semver_comparison():
assert Semver("1") < Semver("2.0.0")
assert Semver("1.1") < Semver("1.2.0")
assert Semver("1.1.1") < Semver("1.1.2")
assert Semver("1.1.1-alpha") < Semver("1.1.1")
assert Semver("1.1.1-alpha") < Semver("1.1.1-beta")
assert Semver("1.1.1-alpha") < Semver("1.1.1-beta")
assert Semver("1.1.1-alpha") < Semver("1.1.1-alpha.1")
assert Semver("1.1.1-alpha.1") < Semver("1.1.1-alpha.2")
assert Semver("1.1.1-alpha+beta") < Semver("1.1.1+beta")
assert Semver("1.1.1-alpha+beta") < Semver("1.1.1-beta+beta")
assert Semver("1.1.1-alpha+beta") < Semver("1.1.1-beta+beta")
assert Semver("1.1.1-alpha+beta") < Semver("1.1.1-alpha.1+beta")
assert Semver("1.1.1-alpha.1+beta") < Semver("1.1.1-alpha.2+beta")
assert Semver("0.5") < Semver("2.0")
assert not (Semver("2.0") < Semver("0.5"))
assert not (Semver("0.5") > Semver("2.0"))
assert not (Semver("0.5") >= Semver("2.0"))
assert Semver("2.0") >= Semver("0.5")
assert Semver("2.0") > Semver("0.5")
assert not (Semver("2.0") > Semver("2.0"))
assert not (Semver("2.0") < Semver("2.0"))
def test_semver_range():
def bounds(spec, lowe, high):
lowe = Semver(lowe) if lowe is not None else lowe
high = Semver(high) if high is not None else high
assert SemverRange(spec).lower() == lowe and SemverRange(spec).upper() == high
bounds('0', '0.0.0', '1.0.0')
bounds('0.0', '0.0.0', '0.1.0')
bounds('0.0.0', '0.0.0', '0.0.1')
bounds('0.0.1', '0.0.1', '0.0.2')
bounds('0.1.1', '0.1.1', '0.2.0')
bounds('1.1.1', '1.1.1', '2.0.0')
bounds('^0', '0.0.0', '1.0.0')
bounds('^0.0', '0.0.0', '0.1.0')
bounds('^0.0.0', '0.0.0', '0.0.1')
bounds('^0.0.1', '0.0.1', '0.0.2')
bounds('^0.1.1', '0.1.1', '0.2.0')
bounds('^1.1.1', '1.1.1', '2.0.0')
bounds('~0', '0.0.0', '1.0.0')
bounds('~0.0', '0.0.0', '0.1.0')
bounds('~0.0.0', '0.0.0', '0.1.0')
bounds('~0.0.1', '0.0.1', '0.1.0')
bounds('~0.1.1', '0.1.1', '0.2.0')
bounds('~1.1.1', '1.1.1', '1.2.0')
bounds('*', '0.0.0', None)
bounds('0.*', '0.0.0', '1.0.0')
bounds('0.0.*', '0.0.0', '0.1.0')
def test_semver_multirange():
assert SemverRange(">= 0.5, < 2.0").compare("1.0.0")
assert SemverRange("*").compare("0.2.7")
class Runner(object):
def __init__(self, c, e, cwd=None):
self._cmd = c
if not isinstance(self._cmd, list):
self._cmd = [self._cmd]
self._env = e
self._stdout = []
self._stderr = []
self._returncode = 0
self._cwd = cwd
def __call__(self, c, e):
cmd = self._cmd + c
env = dict(self._env, **e)
#dbg(' env: %s' % env)
#dbg(' cwd: %s' % self._cwd)
envstr = ''
for k, v in env.iteritems():
envstr += ' %s="%s"' % (k, v)
if self._cwd is not None:
dbg('cd %s && %s %s' % (self._cwd, envstr, ' '.join(cmd)))
else:
dbg('%s %s' % (envstr, ' '.join(cmd)))
proc = subprocess.Popen(cmd, env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=self._cwd)
out, err = proc.communicate()
for lo in out.split('\n'):
if len(lo) > 0:
self._stdout.append(lo)
#dbg('out: %s' % lo)
for le in err.split('\n'):
if len(le) > 0:
self._stderr.append(le)
dbg(le)
"""
while proc.poll() is None:
lo = proc.stdout.readline().rstrip('\n')
le = proc.stderr.readline().rstrip('\n')
if len(lo) > 0:
self._stdout.append(lo)
dbg(lo)
sys.stdout.flush()
if len(le) > 0:
self._stderr.append(le)
dbg('err: %s', le)
sys.stdout.flush()
"""
self._returncode = proc.wait()
#dbg(' ret: %s' % self._returncode)
return self._stdout
def output(self):
return self._stdout
def returncode(self):
return self._returncode
class RustcRunner(Runner):
def __call__(self, c, e):
super(RustcRunner, self).__call__(c, e)
return ([], {}, {})
class BuildScriptRunner(Runner):
def __call__(self, c, e):
#dbg('XXX Running build script:');
#dbg(' env: %s' % e)
#dbg(' '.join(self._cmd + c))
super(BuildScriptRunner, self).__call__(c, e)
# parse the output for cargo: lines
cmd = []
env = {}
denv = {}
for l in self.output():
match = BSCRIPT.match(str(l))
if match is None:
continue
pieces = match.groupdict()
k = pieces['key']
v = pieces['value']
if k == 'rustc-link-lib':
#dbg('YYYYYY: adding -l %s' % v)
cmd += ['-l', v]
elif k == 'rustc-link-search':
#dbg("adding link search path: %s" % v)
cmd += ['-L', v]
elif k == 'rustc-cfg':
cmd += ['--cfg', v]
env['CARGO_FEATURE_%s' % v.upper().replace('-', '_')] = '1'
else:
#dbg("env[%s] = %s" % (k, v));
denv[k] = v
return (cmd, env, denv)
class Crate(object):
def __init__(self, crate, ver, deps, cdir, build):
self._crate = str(crate)
self._version = Semver(ver)
self._dep_info = deps
self._dir = cdir
# put the build scripts first
self._build = [x for x in build if x.get('type') == 'build_script']
# then add the lib/bin builds
self._build += [x for x in build if x.get('type') != 'build_script']
self._resolved = False
self._deps = {}
self._refs = []
self._env = {}
self._dep_env = {}
self._extra_flags = []
def name(self):
return self._crate
def dep_info(self):
return self._dep_info
def version(self):
return self._version
def dir(self):
return self._dir
def __str__(self):
return '%s-%s' % (self.name(), self.version())
def add_dep(self, crate, features):
if str(crate) in self._deps:
return
features = [str(x) for x in features]
self._deps[str(crate)] = { 'features': features }
crate.add_ref(self)
def add_ref(self, crate):
if str(crate) not in self._refs:
self._refs.append(str(crate))
def resolved(self):
return self._resolved
@dbgCtx
def resolve(self, tdir, idir, nodl, graph=None):
if self._resolved:
return
if str(self) in CRATES:
return
if self._dep_info is not None:
print ''
dbg('Resolving dependencies for: %s' % str(self))
for d in self._dep_info:
kind = d.get('kind', 'normal')
if kind not in ('normal', 'build'):
print ''
dbg('Skipping %s dep %s' % (kind, d['name']))
continue
optional = d.get('optional', False)
if optional and d['name'] not in INCLUDE_OPTIONAL:
print ''
dbg('Skipping optional dep %s' % d['name'])
continue
svr = SemverRange(d['req'])
print ''
deps = []
dbg('Looking up info for %s %s' % (d['name'], str(svr)))
if d.get('local', None) is None:
# go through crates first to see if the is satisfied already
dcrate = find_crate_by_name_and_semver(d['name'], svr)
if dcrate is not None:
#import pdb; pdb.set_trace()
svr = dcrate.version().as_range()
name, ver, ideps, ftrs, cksum = crate_info_from_index(idir, d['name'], svr)
if name in BLACKLIST:
dbg('Found in blacklist, skipping %s' % (name))
elif dcrate is None:
if nodl:
cdir = find_downloaded_crate(tdir, name, svr)
else:
cdir = dl_and_check_crate(tdir, name, ver, cksum)
_, tver, tdeps, build = crate_info_from_toml(cdir)
deps += ideps
deps += tdeps
else:
dbg('Found crate already satisfying %s %s' % (d['name'], str(svr)))
deps += dcrate.dep_info()
else:
cdir = d['path']
name, ver, ideps, build = crate_info_from_toml(cdir)
deps += ideps
if name not in BLACKLIST:
try:
if dcrate is None:
dcrate = Crate(name, ver, deps, cdir, build)
if str(dcrate) in CRATES:
dcrate = CRATES[str(dcrate)]
UNRESOLVED.append(dcrate)
if graph is not None:
print >> graph, '"%s" -> "%s";' % (str(self), str(dcrate))
except:
dcrate = None
# clean up the list of features that are enabled
tftrs = d.get('features', [])
if isinstance(tftrs, dict):
tftrs = tftrs.keys()
else:
tftrs = [x for x in tftrs if len(x) > 0]
# add 'default' if default_features is true
if d.get('default_features', True):
tftrs.append('default')
features = []
if isinstance(ftrs, dict):
# add any available features that are activated by the
# dependency entry in the parent's dependency record,
# and any features they depend on recursively
def add_features(f):
if f in ftrs:
for k in ftrs[f]:
# guard against infinite recursion
if not k in features:
features.append(k)
add_features(k)
for k in tftrs:
add_features(k)
else:
features += [x for x in ftrs if (len(x) > 0) and (x in tftrs)]
if dcrate is not None:
self.add_dep(dcrate, features)
self._resolved = True
CRATES[str(self)] = self
@dbgCtx
def build(self, by, out_dir, features=[]):
extra_filename = '-' + str(self.version()).replace('.','_')
output_name = self.name().replace('-','_')
output = os.path.join(out_dir, 'lib%s%s.rlib' % (output_name, extra_filename))
if str(self) in BUILT:
return ({'name':self.name(), 'lib':output}, self._env, self._extra_flags)
externs = []
extra_flags = []
for dep,info in self._deps.iteritems():
if dep in CRATES:
extern, env, extra_flags = CRATES[dep].build(self, out_dir, info['features'])
externs.append(extern)
self._dep_env[CRATES[dep].name()] = env
self._extra_flags += extra_flags
if os.path.isfile(output):
print ''
dbg('Skipping %s, already built (needed by: %s)' % (str(self), str(by)))
BUILT[str(self)] = str(by)
return ({'name':self.name(), 'lib':output}, self._env, self._extra_flags)
# build the environment for subcommands
tenv = dict(os.environ)
env = {}
env['PATH'] = tenv['PATH']
env['OUT_DIR'] = out_dir
env['TARGET'] = TARGET
env['HOST'] = HOST
env['NUM_JOBS'] = '1'
env['OPT_LEVEL'] = '0'
env['DEBUG'] = '0'
env['PROFILE'] = 'release'
env['CARGO_MANIFEST_DIR'] = self.dir()
env['CARGO_PKG_VERSION_MAJOR'] = self.version()['major']
env['CARGO_PKG_VERSION_MINOR'] = self.version()['minor']
env['CARGO_PKG_VERSION_PATCH'] = self.version()['patch']
pre = self.version()['prerelease']
if pre is None:
pre = ''
env['CARGO_PKG_VERSION_PRE'] = pre
env['CARGO_PKG_VERSION'] = str(self.version())
for f in features:
env['CARGO_FEATURE_%s' % f.upper().replace('-','_')] = '1'
for l,e in self._dep_env.iteritems():
for k,v in e.iteritems():
if type(v) is not str and type(v) is not unicode:
v = str(v)
env['DEP_%s_%s' % (l.upper(), v.upper())] = v
# create the builders, build scrips are first
cmds = []
for b in self._build:
v = str(self._version).replace('.','_')
cmd = ['rustc']
cmd.append(os.path.join(self._dir, b['path']))
cmd.append('--crate-name')
if b['type'] == 'lib':
b.setdefault('name', self.name())
cmd.append(b['name'].replace('-','_'))
cmd.append('--crate-type')
cmd.append('lib')
elif b['type'] == 'build_script':
cmd.append('build_script_%s' % b['name'].replace('-','_'))
cmd.append('--crate-type')
cmd.append('bin')
else:
cmd.append(b['name'].replace('-','_'))
cmd.append('--crate-type')
cmd.append('bin')
for f in features:
cmd.append('--cfg')
cmd.append('feature=\"%s\"' % f)
cmd.append('-C')
cmd.append('extra-filename=' + extra_filename)
cmd.append('--out-dir')
cmd.append('%s' % out_dir)
cmd.append('--emit=dep-info,link')
cmd.append('--target')
cmd.append(TARGET)
cmd.append('-L')
cmd.append('%s' % out_dir)
cmd.append('-L')
cmd.append('%s/lib' % out_dir)
# add in the flags from dependencies
cmd += self._extra_flags
for e in externs:
cmd.append('--extern')
cmd.append('%s=%s' % (e['name'].replace('-','_'), e['lib']))
# get the pkg key name
match = BNAME.match(b['name'])
if match is not None:
match = match.groupdict()['name'].replace('-','_')
# queue up the runner
cmds.append({'name':b['name'], 'env_key':match, 'cmd':RustcRunner(cmd, env)})
# queue up the build script runner
if b['type'] == 'build_script':
bcmd = os.path.join(out_dir, 'build_script_%s-%s' % (b['name'], v))
cmds.append({'name':b['name'], 'env_key':match, 'cmd':BuildScriptRunner(bcmd, env, self._dir)})
print ''
dbg('Building %s (needed by: %s)' % (str(self), str(by)))
bcmd = []
benv = {}
for c in cmds:
runner = c['cmd']
(c1, e1, e2) = runner(bcmd, benv)