/
io.py
executable file
·1745 lines (1448 loc) · 54.9 KB
/
io.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
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2022, Johannes Köster"
__email__ = "johannes.koester@uni-due.de"
__license__ = "MIT"
import collections
from hashlib import sha256
import os
import shutil
from pathlib import Path
import re
import stat
import time
import datetime
import json
import copy
import functools
import subprocess as sp
from itertools import product, chain
from contextlib import contextmanager
import string
import collections
import asyncio
from snakemake.exceptions import (
MissingOutputException,
WorkflowError,
WildcardError,
RemoteFileException,
)
from snakemake.logging import logger
from inspect import isfunction, ismethod
from snakemake.common import DYNAMIC_FILL, ON_WINDOWS, async_run
class Mtime:
__slots__ = ["_local", "_local_target", "_remote"]
def __init__(self, local=None, local_target=None, remote=None):
self._local = local
self._local_target = local_target
self._remote = remote
def local_or_remote(self, follow_symlinks=False):
if self._remote is not None:
return self._remote
if follow_symlinks and self._local_target is not None:
return self._local_target
return self._local
def remote(
self,
):
return self._remote
def local(self, follow_symlinks=False):
if follow_symlinks and self._local_target is not None:
return self._local_target
return self._local
def lutime(f, times):
# In some cases, we have a platform where os.supports_follow_symlink includes stat()
# but not utime(). This leads to an anomaly. In any case we never want to touch the
# target of a link.
if os.utime in os.supports_follow_symlinks:
# ...utime is well behaved
os.utime(f, times, follow_symlinks=False)
elif not os.path.islink(f):
# ...symlinks not an issue here
os.utime(f, times)
else:
try:
# try the system command
if times:
fmt_time = lambda sec: datetime.fromtimestamp(sec).strftime(
"%Y%m%d%H%M.%S"
)
atime, mtime = times
sp.check_call(["touch", "-h", f, "-a", "-t", fmt_time(atime)])
sp.check_call(["touch", "-h", f, "-m", "-t", fmt_time(mtime)])
else:
sp.check_call(["touch", "-h", f])
except sp.CalledProcessError:
pass
# ...problem system. Do nothing.
logger.warning(
"Unable to set utime on symlink {}. Your Python build does not support it.".format(
f
)
)
return None
if os.chmod in os.supports_follow_symlinks:
def lchmod(f, mode):
os.chmod(f, mode, follow_symlinks=False)
else:
def lchmod(f, mode):
os.chmod(f, mode)
class ExistsDict(dict):
def __init__(self, cache):
super().__init__()
self.cache = cache
self.has_inventory = set()
def __getitem__(self, path):
# Always return False if not in dict.
# The reason is that this is only called if the method contains below has returned True.
# Hence, we already know that either path is in dict, or inventory has never
# seen it, and hence it does not exist.
return self.get(path, False)
def __contains__(self, path):
# if already in inventory, always return True.
parent = path.get_inventory_parent()
return parent in self.has_inventory or super().__contains__(path)
class IOCache:
def __init__(self, max_wait_time):
self.mtime = dict()
self.exists_local = ExistsDict(self)
self.exists_remote = ExistsDict(self)
self.size = dict()
self.active = True
self.remaining_wait_time = max_wait_time
self.max_wait_time = max_wait_time
def mtime_inventory(self, jobs):
async_run(self._mtime_inventory(jobs))
async def _mtime_inventory(self, jobs, n_workers=8):
queue = asyncio.Queue()
stop_item = object()
async def worker(queue):
while True:
item = await queue.get()
if item is stop_item:
queue.task_done()
return
try:
self.mtime[item] = await self.collect_mtime(item)
except Exception as e:
queue.task_done()
raise e
queue.task_done()
tasks = [
asyncio.get_event_loop().create_task(worker(queue))
for _ in range(n_workers)
]
for job in jobs:
for f in chain(job.input, job.expanded_output):
if f.exists:
queue.put_nowait(f)
if job.benchmark and job.benchmark.exists:
queue.put_nowait(job.benchmark)
# Send a stop item to each worker.
for _ in range(n_workers):
queue.put_nowait(stop_item)
await asyncio.gather(*tasks)
async def collect_mtime(self, path):
return path.mtime_uncached
def clear(self):
self.mtime.clear()
self.size.clear()
self.exists_local.clear()
self.exists_remote.clear()
self.remaining_wait_time = self.max_wait_time
def deactivate(self):
self.clear()
self.active = False
def IOFile(file, rule=None):
assert rule is not None
f = _IOFile(file)
f.rule = rule
return f
class _IOFile(str):
"""
A file that is either input or output of a rule.
"""
__slots__ = [
"_is_function",
"_file",
"rule",
"_regex",
]
def __new__(cls, file):
is_annotated = isinstance(file, AnnotatedString)
is_callable = (
isfunction(file) or ismethod(file) or (is_annotated and bool(file.callable))
)
if not is_callable and file.endswith("/"):
# remove trailing slashes
stripped = file.rstrip("/")
if is_annotated:
stripped = AnnotatedString(stripped)
stripped.flags = file.flags
file = stripped
obj = str.__new__(cls, file)
obj._is_function = is_callable
obj._file = file
obj.rule = None
obj._regex = None
if obj.is_remote:
obj.remote_object._iofile = obj
return obj
def new_from(self, new_value):
new = str.__new__(self.__class__, new_value)
new._is_function = self._is_function
new._file = self._file
new.rule = self.rule
if new.is_remote:
new.remote_object._iofile = new
return new
def iocache(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if self.rule.workflow.iocache.active:
cache = getattr(self.rule.workflow.iocache, func.__name__)
if self in cache:
return cache[self]
v = func(self, *args, **kwargs)
cache[self] = v
return v
else:
return func(self, *args, **kwargs)
return wrapper
def _refer_to_remote(func):
"""
A decorator so that if the file is remote and has a version
of the same file-related function, call that version instead.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if self.is_remote:
if hasattr(self.remote_object, func.__name__):
return getattr(self.remote_object, func.__name__)(*args, **kwargs)
return func(self, *args, **kwargs)
return wrapper
def inventory(self):
async_run(self._inventory())
async def _inventory(self):
"""Starting from the given file, try to cache as much existence and
modification date information of this and other files as possible.
"""
cache = self.rule.workflow.iocache
if cache.active:
tasks = []
if self.is_remote and self not in cache.exists_remote:
# info not yet in inventory, let's discover as much as we can
tasks.append(self.remote_object.inventory(cache))
if not ON_WINDOWS and self not in cache.exists_local:
# we don't want to mess with different path representations on windows
tasks.append(self._local_inventory(cache))
await asyncio.gather(*tasks)
async def _local_inventory(self, cache):
# for local files, perform BFS via os.scandir to determine existence of files
if cache.remaining_wait_time <= 0:
# No more time to create inventory.
return
start_time = time.time()
folders = self.split("/")[:-1]
if not folders:
return
if os.path.isabs(self):
# For absolute paths, only use scan the immediate parent
ancestors = [os.path.dirname(self)]
else:
ancestors = ["/".join(folders[:i]) for i in range(1, len(folders) + 1)]
for (i, path) in enumerate(ancestors):
if path in cache.exists_local.has_inventory:
# This path was already scanned before, hence we can stop.
break
try:
with os.scandir(path) as scan:
for entry in scan:
cache.exists_local[entry.path] = True
cache.exists_local[path] = True
cache.exists_local.has_inventory.add(path)
except FileNotFoundError:
# Not found, hence, all subfolders cannot be present as well
for path in ancestors[i:]:
cache.exists_local[path] = False
cache.exists_local.has_inventory.add(path)
break
except PermissionError:
raise WorkflowError(
"Insufficient permissions to access {}. "
"Please make sure that all accessed files and directories "
"are readable and writable for you.".format(self)
)
cache.remaining_wait_time -= time.time() - start_time
@_refer_to_remote
def get_inventory_parent(self):
"""If eligible for inventory, get the parent of a given path.
This code does not work on local Windows paths,
but inventory is disabled on Windows.
"""
parent = os.path.dirname(self)
if parent and parent != "..":
return parent
@contextmanager
def open(self, mode="r", buffering=-1, encoding=None, errors=None, newline=None):
"""Open this file. If necessary, download it from remote first.
This can (and should) be used in a `with`-statement.
"""
if not self.exists:
raise WorkflowError(
"File {} cannot be opened, since it does not exist.".format(self)
)
if not self.exists_local and self.is_remote:
self.download_from_remote()
f = open(self)
try:
yield f
finally:
f.close()
def contains_wildcard(self):
return contains_wildcard(self.file)
@property
def is_remote(self):
return is_flagged(self._file, "remote_object")
@property
def is_ancient(self):
return is_flagged(self._file, "ancient")
@property
def is_directory(self):
return is_flagged(self._file, "directory")
@property
def is_temp(self):
return is_flagged(self._file, "temp")
@property
def is_multiext(self):
return is_flagged(self._file, "multiext")
@property
def multiext_prefix(self):
return get_flag_value(self._file, "multiext")
def update_remote_filepath(self):
# if the file string is different in the iofile, update the remote object
# (as in the case of wildcard expansion)
remote_object = self.remote_object
if remote_object._file != self._file:
remote_object._iofile = self
@property
def should_keep_local(self):
return self.remote_object.keep_local
@property
def should_stay_on_remote(self):
return self.remote_object.stay_on_remote
@property
def remote_object(self):
return get_flag_value(self._file, "remote_object")
@property
@_refer_to_remote
def file(self):
if not self._is_function:
return self._file
else:
raise ValueError(
"This IOFile is specified as a function and "
"may not be used directly."
)
def check(self):
hint = (
"It can also lead to inconsistent results of the file-matching "
"approach used by Snakemake."
)
if self._file.startswith("./"):
logger.warning(
"Relative file path '{}' starts with './'. This is redundant "
"and strongly discouraged. {} You can simply omit the './' "
"for relative file paths.".format(self._file, hint)
)
if self._file.startswith(" "):
logger.warning(
"File path '{}' starts with whitespace. "
"This is likely unintended. {}".format(self._file, hint)
)
if self._file.endswith(" "):
logger.warning(
"File path '{}' ends with whitespace. "
"This is likely unintended. {}".format(self._file, hint)
)
if "\n" in self._file:
logger.warning(
"File path '{}' contains line break. "
"This is likely unintended. {}".format(self._file, hint)
)
if _double_slash_regex.search(self._file) is not None and not self.is_remote:
logger.warning(
"File path {} contains double '{}'. "
"This is likely unintended. {}".format(self._file, os.path.sep, hint)
)
@property
def exists(self):
if self.is_remote:
return self.exists_remote
else:
return self.exists_local
def parents(self, omit=0):
"""Yield all parent paths, omitting the given number of ancestors."""
for p in list(Path(self.file).parents)[::-1][omit:]:
p = IOFile(str(p), rule=self.rule)
p.clone_flags(self)
yield p
@property
@iocache
def exists_local(self):
return os.path.exists(self.file)
@property
@iocache
def exists_remote(self):
if not self.is_remote:
return False
return self.remote_object.exists()
@property
def protected(self):
"""Returns True if the file is protected. Always False for symlinks."""
# symlinks are never regarded as protected
return (
self.exists_local
and not os.access(self.file, os.W_OK)
and not os.path.islink(self.file)
)
@property
@iocache
def mtime(self):
return self.mtime_uncached
@property
def mtime_uncached(self):
"""Obtain mtime.
Usually, this will be one stat call only. For symlinks and directories
it will be two, for symlinked directories it will be three,
for remote files it will additionally query the remote
location.
"""
mtime_remote = self.remote_object.mtime() if self.is_remote else None
# We first do a normal stat.
try:
_stat = os.stat(self.file, follow_symlinks=False)
is_symlink = stat.S_ISLNK(_stat.st_mode)
is_dir = stat.S_ISDIR(_stat.st_mode)
mtime = _stat.st_mtime
def get_dir_mtime():
# Try whether we have a timestamp file for it.
return os.stat(
os.path.join(self.file, ".snakemake_timestamp"),
follow_symlinks=True,
).st_mtime
if not is_symlink:
if is_dir:
try:
mtime = get_dir_mtime()
except FileNotFoundError:
# No timestamp, hence go on as if it is a file.
pass
# In the usual case, not a dir, not a symlink.
# We need just a single stat call.
return Mtime(local=mtime, remote=mtime_remote)
else:
# In case of a symlink, we need the stats for the target file/dir.
target_stat = os.stat(self.file, follow_symlinks=True)
# Further, we need to check again if this is a directory.
is_dir = stat.S_ISDIR(target_stat.st_mode)
mtime_target = target_stat.st_mtime
if is_dir:
try:
mtime_target = get_dir_mtime()
except FileNotFoundError:
# No timestamp, hence go on as if it is a file.
pass
return Mtime(
local=mtime, local_target=mtime_target, remote=mtime_remote
)
except FileNotFoundError:
if self.is_remote:
return Mtime(remote=mtime_remote)
raise WorkflowError(
"Unable to obtain modification time of file {} although it existed before. "
"It could be that a concurrent process has deleted it while Snakemake "
"was running.".format(self.file)
)
except PermissionError:
raise WorkflowError(
"Unable to obtain modification time of file {} because of missing "
"read permissions.".format(self.file)
)
@property
def flags(self):
return getattr(self._file, "flags", {})
def is_fifo(self):
"""Return True if file is a FIFO according to the filesystem."""
return stat.S_ISFIFO(os.stat(self).st_mode)
@property
@iocache
@_refer_to_remote
def size(self):
return self.size_local
@property
def size_local(self):
# follow symlinks but throw error if invalid
self.check_broken_symlink()
return os.path.getsize(self.file)
def is_checksum_eligible(self):
return (
self.exists_local
and not os.path.isdir(self.file)
and self.size < 100000
and not self.is_fifo()
)
def checksum(self, force=False):
"""Return checksum if file is small enough, else None.
Returns None if file does not exist. If force is True,
omit eligibility check."""
if force or self.is_checksum_eligible(): # less than 100000 bytes
checksum = sha256()
if self.size > 0:
# only read if file is bigger than zero
# otherwise the checksum is the same as taking hexdigest
# from the empty sha256 as initialized above
# This helps endless reading in case the input
# is a named pipe or a socket or a symlink to a device like
# /dev/random.
with open(self.file, "rb") as f:
checksum.update(f.read())
return checksum.hexdigest()
else:
return None
def is_same_checksum(self, other_checksum, force=False):
checksum = self.checksum(force=force)
if checksum is None or other_checksum is None:
# if no checksum available or files too large, not the same
return False
else:
return checksum == other_checksum
def check_broken_symlink(self):
"""Raise WorkflowError if file is a broken symlink."""
if not self.exists_local:
try:
if os.lstat(self.file):
raise WorkflowError(
"File {} seems to be a broken symlink.".format(self.file)
)
except FileNotFoundError as e:
# there is no broken symlink present, hence all fine
return
@_refer_to_remote
def is_newer(self, time):
"""Returns true of the file (which is an input file) is newer than time, or if it is
a symlink that points to a file newer than time."""
if self.is_ancient:
return False
return self.mtime.local_or_remote(follow_symlinks=True) > time
def download_from_remote(self):
if self.is_remote and self.remote_object.exists():
if not self.should_stay_on_remote:
logger.info("Downloading from remote: {}".format(self.file))
self.remote_object.download()
logger.info("Finished download.")
else:
raise RemoteFileException(
"The file to be downloaded does not seem to exist remotely."
)
def upload_to_remote(self):
if self.is_remote:
logger.info("Uploading to remote: {}".format(self.file))
self.remote_object.upload()
logger.info("Finished upload.")
def prepare(self):
path_until_wildcard = re.split(DYNAMIC_FILL, self.file)[0]
dir = os.path.dirname(path_until_wildcard)
if len(dir) > 0:
try:
os.makedirs(dir, exist_ok=True)
except OSError as e:
# ignore Errno 17 "File exists" (reason: multiprocessing)
if e.errno != 17:
raise e
if is_flagged(self._file, "pipe"):
os.mkfifo(self._file)
def protect(self):
mode = (
os.lstat(self.file).st_mode & ~stat.S_IWUSR & ~stat.S_IWGRP & ~stat.S_IWOTH
)
if os.path.isdir(self.file):
for root, dirs, files in os.walk(self.file):
for d in dirs:
lchmod(os.path.join(self.file, d), mode)
for f in files:
lchmod(os.path.join(self.file, f), mode)
lchmod(self.file, mode)
def remove(self, remove_non_empty_dir=False):
if self.is_directory:
remove(self, remove_non_empty_dir=True)
else:
remove(self, remove_non_empty_dir=remove_non_empty_dir)
def touch(self, times=None):
"""times must be 2-tuple: (atime, mtime)"""
try:
if self.is_directory:
file = os.path.join(self.file, ".snakemake_timestamp")
# Create the flag file if it doesn't exist
if not os.path.exists(file):
with open(file, "w"):
pass
lutime(file, times)
else:
lutime(self.file, times)
except OSError as e:
if e.errno == 2:
raise MissingOutputException(
"Output file {} of rule {} shall be touched but "
"does not exist.".format(self.file, self.rule.name),
lineno=self.rule.lineno,
snakefile=self.rule.snakefile,
)
else:
raise e
def touch_or_create(self):
try:
self.touch()
except MissingOutputException:
# first create directory if it does not yet exist
dir = self.file if self.is_directory else os.path.dirname(self.file)
if dir:
os.makedirs(dir, exist_ok=True)
# create empty file
file = (
os.path.join(self.file, ".snakemake_timestamp")
if self.is_directory
else self.file
)
with open(file, "w") as f:
pass
def apply_wildcards(self, wildcards, fill_missing=False, fail_dynamic=False):
f = self._file
if self._is_function:
f = self._file(Namedlist(fromdict=wildcards))
# this bit ensures flags are transferred over to files after
# wildcards are applied
file_with_wildcards_applied = IOFile(
apply_wildcards(
f,
wildcards,
fill_missing=fill_missing,
fail_dynamic=fail_dynamic,
dynamic_fill=DYNAMIC_FILL,
),
rule=self.rule,
)
file_with_wildcards_applied.clone_flags(self)
return file_with_wildcards_applied
def get_wildcard_names(self):
return get_wildcard_names(self.file)
def regex(self):
if self._regex is None:
# compile a regular expression
self._regex = re.compile(regex(self.file))
return self._regex
def constant_prefix(self):
first_wildcard = _wildcard_regex.search(self.file)
if first_wildcard:
return self.file[: first_wildcard.start()]
return self.file
def constant_suffix(self):
m = None
for m in _wildcard_regex.finditer(self.file):
pass
last_wildcard = m
if last_wildcard:
return self.file[last_wildcard.end() :]
return self.file
def match(self, target):
return self.regex().match(target) or None
def format_dynamic(self):
return self.replace(DYNAMIC_FILL, "{*}")
def clone_flags(self, other):
if isinstance(self._file, str):
self._file = AnnotatedString(self._file)
if isinstance(other._file, AnnotatedString) or isinstance(other._file, _IOFile):
self._file.flags = getattr(other._file, "flags", {}).copy()
if "remote_object" in self._file.flags:
self._file.flags["remote_object"] = copy.copy(
self._file.flags["remote_object"]
)
self.update_remote_filepath()
def clone_remote_object(self, other):
if (
isinstance(other._file, AnnotatedString)
and "remote_object" in other._file.flags
):
self._file.flags["remote_object"] = copy.copy(
other._file.flags["remote_object"]
)
self.update_remote_filepath()
def set_flags(self, flags):
if isinstance(self._file, str):
self._file = AnnotatedString(self._file)
self._file.flags = flags
def __eq__(self, other):
f = other._file if isinstance(other, _IOFile) else other
return self._file == f
def __hash__(self):
return self._file.__hash__()
_double_slash_regex = (
re.compile(r"([^:]//|^//)") if os.path.sep == "/" else re.compile(r"\\\\")
)
_wildcard_regex = re.compile(
r"""
\{
(?=( # This lookahead assertion emulates an 'atomic group'
# which is required for performance
\s*(?P<name>\w+) # wildcard name
(\s*,\s*
(?P<constraint> # an optional constraint
([^{}]+ | \{\d+(,\d+)?\})* # allow curly braces to nest one level
) # ... as in '{w,a{3,5}}'
)?\s*
))\1
\}
""",
re.VERBOSE,
)
def wait_for_files(
files, latency_wait=3, force_stay_on_remote=False, ignore_pipe_or_service=False
):
"""Wait for given files to be present in the filesystem."""
files = list(files)
def get_missing():
return [
f
for f in files
if not (
f.exists_remote
if (
isinstance(f, _IOFile)
and f.is_remote
and (force_stay_on_remote or f.should_stay_on_remote)
)
else os.path.exists(f)
if not (
(is_flagged(f, "pipe") or is_flagged(f, "service"))
and ignore_pipe_or_service
)
else True
)
]
missing = get_missing()
if missing:
logger.info(
"Waiting at most {} seconds for missing files.".format(latency_wait)
)
for _ in range(latency_wait):
missing = get_missing()
if not missing:
return
time.sleep(1)
missing = "\n".join(get_missing())
raise IOError(
f"Missing files after {latency_wait} seconds. This might be due to "
"filesystem latency. If that is the case, consider to increase the "
"wait time with --latency-wait:\n"
f"{missing}"
)
def get_wildcard_names(pattern):
return set(match.group("name") for match in _wildcard_regex.finditer(pattern))
def contains_wildcard(path):
return _wildcard_regex.search(path) is not None
def contains_wildcard_constraints(pattern):
return any(match.group("constraint") for match in _wildcard_regex.finditer(pattern))
def remove(file, remove_non_empty_dir=False):
if file.is_remote and file.should_stay_on_remote:
if file.exists_remote:
file.remote_object.remove()
elif os.path.isdir(file) and not os.path.islink(file):
if remove_non_empty_dir:
shutil.rmtree(file)
else:
try:
os.removedirs(file)
except OSError as e:
# skip non empty directories
if e.errno == 39:
logger.info(
"Skipped removing non-empty directory {}".format(e.filename)
)
else:
logger.warning(str(e))
# Remember that dangling symlinks fail the os.path.exists() test, but
# we definitely still want to zap them. try/except is the safest way.
# Also, we don't want to remove the null device if it is an output.
elif os.devnull != str(file):
try:
os.remove(file)
except FileNotFoundError:
pass
def regex(filepattern):
f = []
last = 0
wildcards = set()
for match in _wildcard_regex.finditer(filepattern):
f.append(re.escape(filepattern[last : match.start()]))
wildcard = match.group("name")
if wildcard in wildcards:
if match.group("constraint"):
raise ValueError(
"Constraint regex must be defined only in the first "
"occurence of the wildcard in a string."
)
f.append("(?P={})".format(wildcard))
else:
wildcards.add(wildcard)
f.append(
"(?P<{}>{})".format(
wildcard,
match.group("constraint") if match.group("constraint") else ".+",
)
)
last = match.end()
f.append(re.escape(filepattern[last:]))
f.append("$") # ensure that the match spans the whole file
return "".join(f)
def apply_wildcards(
pattern,
wildcards,
fill_missing=False,
fail_dynamic=False,
dynamic_fill=None,
keep_dynamic=False,
):
def format_match(match):
name = match.group("name")
try:
value = wildcards[name]
if fail_dynamic and value == dynamic_fill:
raise WildcardError(name)
return str(value) # convert anything into a str
except KeyError as ex:
if keep_dynamic:
return "{{{}}}".format(name)
elif fill_missing:
return dynamic_fill
else:
raise WildcardError(str(ex))
return _wildcard_regex.sub(format_match, pattern)
def not_iterable(value):
return (
isinstance(value, str)
or isinstance(value, dict)
or not isinstance(value, collections.abc.Iterable)
)
def is_callable(value):
return (
callable(value)
or (isinstance(value, _IOFile) and value._is_function)
or (isinstance(value, AnnotatedString) and value.callable is not None)
)
class AnnotatedString(str):
def __init__(self, value):
self.flags = dict()
self.callable = value if is_callable(value) else None
def new_from(self, new_value):
new = str.__new__(self.__class__, new_value)
new.flags = self.flags
new.callable = self.callable