forked from mefyl/drake
/
__init__.py
4538 lines (3906 loc) · 131 KB
/
__init__.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
# Copyright (C) 2009-2017, Quentin "mefyl" Hocquet
#
# This software is provided "as is" without warranty of any kind,
# either expressed or implied, including but not limited to the
# implied warranties of fitness for a particular purpose.
#
# See the LICENSE file for more information.
import os as _OS
import atexit
import contextlib
import drake.debug
import hashlib
import inspect
import itertools
import os.path
import pickle
import pipes
import platform
import re
import shutil
import stat
import string
import subprocess
import sys
import threading
import time
import types
from drake.sched import Coroutine, Scheduler
from drake.enumeration import Enumerated
from itertools import chain
from drake.sched import logger
from drake.utils import property_memoize
# The default timeout value for shell commands, in seconds.
TIMEOUT = int(_OS.getenv('DRAKE_TIMEOUT', '3600'))
PRETTY = 'DRAKE_PRETTY' in _OS.environ
PROFILE = 'DRAKE_PROFILE' in _OS.environ
def _scheduled():
return Coroutine.current and \
Coroutine.current._Coroutine__scheduler
def path_source(path = None):
if path is None:
return Drake.current.path_source
path = Path(path)
if path.absolute():
return path
else:
return Drake.current.path_source / Drake.current.prefix / path
def duration(start, stop = None):
'''The duration from start to stop, with nice conversion to string.'''
if not stop:
stop = time.time()
import datetime
return datetime.timedelta(seconds=round(stop - start))
class Drake:
current = None
@property
def jobs(self):
return self.__jobs
def jobs_set(self, n):
n = int(n)
if n == 1:
self.__jobs_lock = None
else:
self.__jobs_lock = sched.Semaphore(n)
jobs.setter(jobs_set)
@property
def path_source(self):
"""The path to the source directory relative to the build directory."""
return self.__source
@property
def configure(self):
return self.__configure
@configure.setter
def configure(self, value):
assert self.__configure is None
self.__configure = value
@property
def scheduler(self):
return self.__scheduler
@property
def jobs_lock(self):
return self.__jobs_lock
__previous = []
def __enter__(self):
Drake.__previous.append(Drake.current)
Drake.current = self
return self
def __exit__(self, *args):
Drake.current = Drake.__previous[-1]
del Drake.__previous[-1]
@property
def prefix(self):
"""The current prefix.
The prefix is the path from the root of the build tree to the
current drakefile build tree. This is '.' for the root drakefile.
"""
return self.__prefix
@property
def nodes(self):
return self.__nodes
def recurse(self, path):
class Recurser:
def __init__(self, drake):
self.__drake = drake
self.__previous = None
def __enter__(self):
self.__previous = self.__drake.prefix
self.__drake._Drake__prefix = self.__previous / path
def __exit__(self, *args, **kwargs):
self.__drake._Drake__prefix = self.__previous
return Recurser(self)
def __option(self, name, default, override = None):
if override is not None:
return override
v = _OS.environ.get('DRAKE_%s' % name)
if v is None:
return default
else:
return bool(int(v))
def __init__(self,
root = None,
jobs = None,
kill_builders_on_failure = False,
use_mtime = None,
adjust_mtime = None,
adjust_mtime_future = None,
adjust_mtime_second = None,
):
if root is None:
root = drake.Path('.')
self.__jobs = 1
self.__jobs_lock = None
self.__kill_builders_on_failure = kill_builders_on_failure
self.__nodes = {}
self.__prefix = drake.Path('.')
self.__scheduler = Scheduler(policy = sched.DepthFirst())
self.__source = drake.Path(root)
self.__use_mtime = self.__option(
'MTIME', True, use_mtime)
self.__adjust_mtime = self.__option(
'ADJUST_MTIME', True, adjust_mtime)
self.__adjust_mtime_future = self.__option(
'ADJUST_MTIME_FUTURE', False, adjust_mtime_future)
self.__adjust_mtime_second = self.__option(
'ADJUST_MTIME_SECOND', False, adjust_mtime_second)
# Load the root drakefile
self.__globals = {}
path = str(self.path_source / 'drakefile')
if _OS.path.exists(path):
with open(path, 'r') as drakefile:
with self:
exec(compile(drakefile.read(), path, 'exec'),
self.__globals)
self.__module = _Module(self.__globals)
self.__configure = self.__module.configure
else:
self.__module = _Module({})
self.__configure = None
if jobs is not None:
self.jobs_set(jobs)
@property
def kill_builders_on_failure(self):
return self.__kill_builders_on_failure
@property
def use_mtime(self):
return self.__use_mtime
@property
def adjust_mtime(self):
return self.__adjust_mtime
@property
def adjust_mtime_future(self):
return self.__adjust_mtime_future
@property
def adjust_mtime_second(self):
return self.__adjust_mtime_second
def notify(self, status, message, start, stop=None):
'''Notify the user that a run was finished.'''
icon = str(self.path_source / 'logo.png')
args = {
'title': '{} ({})'.format('failed' if status else 'done',
duration(start, stop)),
'icon': icon if _OS.path.exists(icon) else None,
'message': message,
}
# For some reason, the some first characters (such as open paren
# or bracket) must be escaped. Fortunately, a leading backlash
# suffices.
if sys.platform == 'darwin':
args['sound'] = 'Basso' if status else 'Glass'
cmd = ('(terminal-notifier -title "\\{title}" -message "\\{message}"'
+ (' -sound "{sound}"')
+ (' -appIcon "{icon}"' if 'icon' in args else '')
+ ') 2>/dev/null').format_map(args)
_OS.system(cmd)
def run(self, *cfg, **kwcfg):
start = time.time()
try:
g = self.__globals
module = self.__module
configure = self.__configure
# Parse arguments
options = {
'--jobs': lambda j: self.jobs_set(j),
'-j' : lambda j : self.jobs_set(j),
'--help': help,
'-h' : help,
'--complete-modes': complete_modes,
'--complete-options': complete_options,
'--complete-nodes': complete_nodes,
}
arguments_re = re.compile('--(\\w+)=(.*)')
specs = inspect.getfullargspec(configure)
callbacks = []
i = 0
args = sys.argv[1:]
while i < len(args):
match = arguments_re.match(args[i])
if match:
name = match.group(1)
value = match.group(2)
if name in specs.args:
if name in specs.annotations:
t = specs.annotations[name]
if t is bool:
if value.lower() in ['true', 'yes']:
value = True
elif value.lower() in ['false', 'no']:
value = False
else:
raise Exception('invalid value for '
'boolean option %s: %s' % (name, value))
kwcfg[name] = value
del args[i]
continue
elif args[i] in options:
opt = args[i]
del args[i]
opt_args = []
for a in inspect.getfullargspec(options[opt]).args:
opt_args.append(args[i])
del args[i]
cb = options[opt](*opt_args)
if cb is not None:
callbacks.append(cb)
continue
i += 1
# Configure
with self:
configure(*cfg, **kwcfg)
# Run callbacks.
for cb in callbacks:
cb()
mode = _MODES['build']
i = 0
with self:
while True:
if i < len(args):
arg = args[i]
if arg[0:2] == '--':
arg = arg[2:]
if arg in _MODES:
mode = _MODES[arg]
else:
raise Exception('Unknown option: %s.' % arg)
i += 1
nodes = []
while i < len(args) and args[i][0:2] != '--':
nodes.append(node(args[i]))
i += 1
if not nodes:
nodes = _DEFAULTS
mode(nodes)
if i == len(args):
break
except Exception as e:
self.notify(1, str(e), start)
print('%s: %s' % (sys.argv[0], e))
if 'DRAKE_DEBUG_BACKTRACE' in _OS.environ:
import traceback
traceback.print_exc()
sys.exit(1)
except KeyboardInterrupt:
print('%s: interrupted.' % sys.argv[0])
sys.exit(1)
self.notify(0, ' '.join(args), start)
EXPLAIN = 'DRAKE_EXPLAIN' in _OS.environ
def explain(node, reason):
if EXPLAIN:
print('Execute %s because %s' % (node, reason))
def warn(msg):
print('Warning: %s.' % msg, file = sys.stderr)
class Profile:
def __init__(self, name):
self.__calls = 0
self.__name = name
self.__time = 0
if PROFILE:
atexit.register(self.show)
def __call__(self):
if PROFILE:
return ProfileInstance(self)
else:
return drake.log.NOOP
def show(self):
print(self)
def __str__(self):
return '%s: called %s time, %s seconds.' % (
self.__name, self.__calls, self.__time)
class ProfileInstance:
def __init__(self, parent):
self.__parent = parent
self.__time = 0
self.__time = None
def __enter__(self):
self.__time = time.time()
def __exit__(self, *args):
self.__parent._Profile__calls += 1
t = time.time() - self.__time
self.__parent._Profile__time += t
profile_hashing = Profile('files hashing')
profile_unpickling = Profile('dependencies files reading')
profile_pickling = Profile('dependencies files writing')
class NodeRedefinition(Exception):
"""Thrown when a node is redefined.
In most cases, this exception will not be seen by the user
since all primitives (even node constructors) will return the
existing node if it exists."""
def __init__(self, name_absolute):
"""Build a redefinition exception.
name_absolute -- the absolute name of the redefined node."""
Exception.__init__(self)
self.__name = name_absolute
def __str__(self):
"""Description, with the redefined node name."""
return 'node redefinition: %s' % self.__name
def name(self):
"""The absolute name of the redefined node.
See Node.name_absolute."""
return self.__name
class NoBuilder(Exception):
"""Node raised when a Node builder is missing.
Raised when a Nodehas no builder and its associated file does not
exist.
"""
def __init__(self, node):
"""Build a NoBuilder exception.
node -- the node whose builder is missing.
"""
self.__node = node
Exception.__init__(self,
'no builder to make %s' % self.__node)
class BuilderRedefinition(Exception):
"""Exception raised when two builders are defined for a node."""
def __init__(self, node, previous, new):
self.__node = node
self.__previous = previous
self.__new = new
super().__init__('builder redefinition for %s' % self.__node)
@property
def node(self):
return self.__node
@property
def previous_builder(self):
return self.__previous
@property
def new_builder(self):
return self.__new
_RAW = 'DRAKE_RAW' in _OS.environ
_SILENT = 'DRAKE_SILENT' in _OS.environ
class Path:
"""Node names, similar to a filesystem path."""
cache = {}
def __new__(self,
path,
absolute = None,
virtual = None,
volume = None,
string = None):
if path.__class__ is Path:
return path
elif path.__class__ is str:
strkey = path
res = Path.cache.get(path, None)
if res is not None:
return res
else:
path, absolute, virtual, volume = Path.__parse(path)
else:
strkey = string
if Path.windows:
key = (path, absolute, virtual, volume)
else:
key = (path, absolute, virtual)
res = Path.cache.get(key, None)
if res is None:
res = object.__new__(self)
res.__init(path, absolute, virtual, volume)
Path.cache[key] = res
if strkey is not None:
Path.cache[strkey] = res
return res
def unfold(self):
p = self
while p != drake.Path.dot:
yield p
p = p.dirname()
@classmethod
def rootify(self, paths):
res = set()
for p in paths:
insert = True
for e in set(res):
if e.prefix_of(p):
insert = False
break
elif p.prefix_of(e):
res.remove(e)
if insert:
res.add(p)
return res
def __parse(path):
if Path.windows:
volume = re.compile('^([a-zA-Z]):').match(path)
if volume:
volume = volume.group(1)
path = path[2:]
else:
volume = ''
if path[:2] == '//' or path[:2] == '\\\\':
path = path[2:]
absolute = False
virtual = True
elif path[:1] == '/' or path[:1] == '\\':
path = path[1:]
absolute = True
virtual = False
else:
absolute = False
virtual = False
path = path = tuple(re.split(r'/|\\', path))
else:
volume = None
if path[:2] == '//':
path = path[2:]
absolute = False
virtual = True
elif path[:1] == '/':
path = path[1:]
absolute = True
virtual = False
else:
absolute = False
virtual = False
path = tuple(path.split('/'))
return path, absolute, virtual, volume
separator = '/'
windows = platform.system() == 'Windows'
if windows:
separator = '\\'
def __init(self, path, absolute, virtual, volume):
"""Build a path.
path -- The path, as a string or an other Path.
"""
self.__absolute = absolute
self.__canonized = None
self.__path = path
self.__str = None
self.__virtual = virtual
self.__volume = volume
def canonize(self):
if self.__canonized is None:
res = ()
path = self.__path
for i in range(len(path)):
if path[i] == '..' and len(res) > 0 and res[-1] != '..':
res = res[:-1]
elif path[i] == '.':
pass
else:
res += (path[i],)
if res == self.__path:
self.__canonized = self
else:
self.__canonized = drake.Path(res,
absolute = self.__absolute,
virtual = self.__virtual,
volume = self.__volume)
return self.__canonized
def absolute(self):
"""Whether this path is absolute.
>>> Path('.').absolute()
False
>>> Path('foo/bar').absolute()
False
>>> Path('/').absolute()
True
>>> Path('/foo').absolute()
True
"""
return self.__absolute
@property
def name_relative(self):
"""Path relative to the current drakefile."""
if self.absolute():
return self
else:
return self.without_prefix(drake.Drake.current.prefix)
@property
def relative(self):
return not self.__absolute
@property
def virtual(self):
"""Whether this path is virtual.
>>> Path('.').virtual
False
>>> Path('foo/bar').virtual
False
>>> Path('//').virtual
True
>>> Path('//foo').virtual
True
"""
return self.__virtual
@property
def volume(self):
return self.__volume
def remove(self, err = False):
"""Remove the target file.
err -- Whether this is an error for non-existent file.
No-op if the file does not exist, unless err is true.
>>> p = Path('/tmp/.drake.foo')
>>> p.touch()
>>> p.exists()
True
>>> p.remove()
>>> p.exists()
False
>>> p.touch()
>>> p.remove(True)
>>> p.remove(True)
Traceback (most recent call last):
...
Exception: Path does not exist: /tmp/.drake.foo
"""
try:
_OS.remove(str(self))
except OSError as e:
import sys
if e.errno == 2:
if err:
raise Exception('Path does not exist: %s' % str(self))
# OS X throws an errno 1 when trying to remove a directory.
elif e.errno == 21 or (sys.platform == 'darwin' and e.errno == 1):
shutil.rmtree(str(self))
else:
raise
def __extension_get(self):
parts = self.__path[-1].split('.')
if len(parts) > 1:
return '.'.join(parts[1:])
else:
return ''
def with_extension(self, value):
'''The path with a different extension.
>>> p = Path('foo')
>>> p
Path("foo")
>>> p = p.with_extension('tar.bz2')
>>> p
Path("foo.tar.bz2")
>>> p.with_extension('txt')
Path("foo.txt")
'''
parts = self.__path[-1].split('.')
if len(parts) > 1:
if value == '':
parts = [parts[0]]
else:
parts = [parts[0], value]
return Path(self.__path[:-1] + ('.'.join(parts),),
absolute = self.__absolute,
virtual = self.__virtual,
volume = self.__volume)
else:
if value != '':
return Path(self.__path[:-1] + ('%s.%s' % (parts[0], value),),
absolute = self.__absolute,
virtual = self.__virtual,
volume = self.__volume)
else:
return self
extension = property(
fget = __extension_get,
doc = """Extension of the file name.
The extension is the part after the first dot of the basename,
or the empty string if there are no dot.
>>> Path('foo.txt').extension
'txt'
>>> Path('foo.tar.bz2').extension
'tar.bz2'
>>> Path('foo').extension
''
""")
def without_last_extension(self):
"""Remove the last dot and what follows from the basename.
Does nothing if there is no dot.
>>> p = Path('foo.tar.bz2')
>>> p
Path("foo.tar.bz2")
>>> p = p.without_last_extension()
>>> p
Path("foo.tar")
>>> p = p.without_last_extension()
>>> p
Path("foo")
>>> p.without_last_extension()
Path("foo")
"""
ext = '.'.join(self.extension.split('.')[:-1])
return self.with_extension(ext)
def __str__(self):
"""The path as a string, adapted to the underlying OS."""
if self.__str is None:
if self.__absolute:
if self.__volume is None or self.__volume == '':
prefix = drake.Path.separator
else:
prefix = self.__volume + ':' + drake.Path.separator
elif self.__virtual:
prefix = drake.Path.separator * 2
else:
prefix = ''
if not self.__path:
body = '.'
else:
body = self.separator.join(self.__path)
self.__str = prefix + body
return self.__str
def __repr__(self):
"""Python representation."""
return 'Path(\"%s\")' % str(self)
def __lt__(self, rhs):
"""Arbitrary comparison.
>>> Path('foo') < Path('foo')
False
>>> (Path('foo') < Path('bar')) ^ (Path('bar') < Path('foo'))
True
"""
return str(self) < str(rhs)
def __hash__(self):
"""Hash value.
>>> hash(Path('foo')) == hash(Path('foo'))
True
"""
return id(self)
def exists(self):
"""Whether the designated file or directory exists.
>>> p = Path('/tmp/.drake.foo')
>>> p.touch()
>>> p.exists()
True
>>> p.remove()
>>> p.exists()
False
"""
if _OS.path.islink(str(self)):
return True
return _OS.path.exists(str(self))
@property
def executable(self):
"""Whether the designated file is executable by the user."""
return _OS.access(str(self), _OS.X_OK)
def is_file(self):
"""Whether the designated file exists and is a regular file.
>>> p = Path('/tmp/.drake.foo')
>>> p.touch()
>>> p.is_file()
True
>>> p.remove()
>>> p.is_file()
False
>>> p.mkpath()
>>> p.exists()
True
>>> p.is_file()
False
>>> p.remove()
"""
return _OS.path.isfile(str(self))
def basename(self):
"""The filename part of the path.
This is the path without the dirname. Throws if the path has
no components.
>>> Path('foo/bar/baz').basename()
Path("baz")
"""
if not self.__path:
raise Exception('Cannot take the basename of an empty path.')
return Path(self.__path[-1:],
absolute = False,
virtual = False,
volume = '')
def dirname(self):
"""The directory part of the path.
This is the path without the basename. Throws if the path has
no components.
>>> Path('foo/bar/baz').dirname()
Path("foo/bar")
>>> Path('foo').dirname()
Path(".")
"""
if len(self.__path) == 1:
return Path.dot
else:
return Path(self.__path[0:-1],
absolute = self.__absolute,
virtual = self.__virtual,
volume = self.__volume)
def touch(self):
"""Create the designated file if it does not exists.
Creates the parent directories if needed first.
>>> Path('/tmp/.drake').remove()
>>> p = Path('/tmp/.drake/.sub/.foo')
>>> p.touch()
>>> p.exists()
True
If the file does exist, this is a no-op.
>>> path = Path('/tmp/.drake.touch.exists')
>>> with open(str(path), 'w') as f:
... print('foobar', file = f)
>>> path.touch()
>>> with open(str(path), 'r') as f:
... print(f.read(), end = '')
foobar
"""
parent = self.dirname()
if parent is not Path.dot:
parent.mkpath()
if not _OS.path.exists(str(self)):
with open(str(self), 'w') as f:
pass
def mkpath(self):
"""Create the designated directory.
Creates the parent directories if needed first.
>>> Path('/tmp/.drake').remove()
>>> p = Path('/tmp/.drake/.sub/')
>>> p.mkpath()
>>> p.exists()
True
"""
if not _OS.path.exists(str(self)):
_OS.makedirs(str(self))
def __eq__(self, rhs):
"""Whether self equals rhs.
Pathes are equals if they have the same components and
absoluteness.
>>> Path('foo/bar') == Path('foo/bar')
True
>>> Path('foo/bar') == Path('foo')
False
>>> Path('foo/bar') == Path('bar/foo')
False
>>> Path('foo/bar') == Path('/foo/bar')
False
>>> Path('/foo/bar') == Path('/foo/bar')
True
"""
return self is drake.Path(rhs)
def __truediv__(self, rhs):
"""The concatenation of self and rhs.
rhs -- the end of the new path, as a Path or a string.
>>> Path('foo/bar') / Path('bar/baz')
Path("foo/bar/bar/baz")
>>> Path('foo/bar') / 'baz'
Path("foo/bar/baz")
>>> Path('.') / 'baz'
Path("baz")
Contatenating an absolute path yields the path itself.
>>> Path('foo') / Path('/absolute')
Path("/absolute")
"""
rhs = Path(rhs)
if self is Path.dot:
return rhs
if rhs is Path.dot:
return self
if rhs.__absolute:
return rhs
return drake.Path(self.__path + rhs.__path,
absolute = self.__absolute,
virtual = self.__virtual,
volume = self.__volume)
def prefix_of(self, rhs):
"""Whether self is a prefix of rhs.
>>> p = Path('foo/bar')
>>> p.prefix_of('foo/bar/baz/quux')
True
>>> p.prefix_of('foo/baz/bar/quux')
False
>>> p.prefix_of('nope')
False
"""
rhs = drake.Path(rhs).canonize().__path
path = self.__path
while len(rhs) and len(path) and path[0] == rhs[0]:
rhs = rhs[1:]
path = path[1:]
return len(path) == 0
def without_prefix(self, rhs, force = True):
"""Remove rhs prefix from self.
rhs -- the prefix to strip, as a Path or a string.
>>> p = Path('foo/bar/baz/quux')
>>> p
Path("foo/bar/baz/quux")
>>> p.without_prefix("foo/bar")
Path("baz/quux")
>>> p = Path('/foo/bar/baz')
>>> p.absolute()
True
>>> p = p.without_prefix('/foo')
>>> p
Path("bar/baz")
>>> p.absolute()
False
Rewinds if rhs is not a prefix of self.
>>> p.without_prefix("quux")
Path("../bar/baz")
Rewinding a path entirerly yields the current directory.
>>> Path('foo/bar').without_prefix('foo/bar')
Path(".")
"""
rhs = drake.Path(rhs).canonize().__path
path = self.__path
while len(rhs) and len(path) and path[0] == rhs[0]:
rhs = rhs[1:]
path = path[1:]
if not force and len(rhs) > 0:
return self
# FIXME: naive if rhs contains some '..'
assert '..' not in rhs
path = ('..',) * len(rhs) + path
if not path:
path = ('.',)
return drake.Path(path,
absolute = False,
virtual = False,
volume = '')
def __len__(self):
return len(self.__path)
def without_suffix(self, rhs):
"""Remove rhs suffix from self.
rhs -- the suffix to strip, as a Path or a string.