-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
resholve
executable file
·4660 lines (4023 loc) · 160 KB
/
resholve
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 python2
from __future__ import print_function
from _resholve import strings
from _resholve.version import __version__
DIRECTIVE_FORMAT = "3"
import sys
import os
import StringIO
import io
import copy
import re
import csv
import shlex
from threading import Timer
from subprocess import Popen, PIPE
from contextlib import contextmanager
import argparse as theirparse # external command parsers
import configargparse as ourparse # resholve's own parser
import logging
from collections import defaultdict, Iterable
logger = logging.getLogger(__name__)
logging.basicConfig(level=os.environ.get("LOGLEVEL", logging.WARNING))
# logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
"""
NOTE:
All of the below are imports from/for oil. Try to keep careful notes
on what is used from each Oil module. Oil is still young.
It's easier to track upstream reorg w/ succinct notes.
"""
from oil.asdl import pybase # CompoundObj
from oil.core import (
alloc, # Arena
error, # Parse, _ErrorWithLocation
main_loop, # ParseWholeFile
optview, # Parse
state, # InitOpts
ui, # PrettyPrintError
)
from oil.osh import (
word_, # StaticEval
split, # SplitContext
word_eval, # CompletionWordEvaluator, StringWordEvaluator
sh_expr_eval, # ArithEvaluator
)
from oil.frontend import (
parse_lib, # ParseContext
reader, # FileLineReader
)
from oil._devbuild.gen.id_kind_asdl import (
Id, # Left_Backtick, Left_DollarParen, Lit_TildeLike, VSub_At, VSub_DollarName, VSub_Number, VSub_Name, VSub_Star
)
from oil._devbuild.gen.syntax_asdl import (
source, # MainFile, Stdin
command, # ShFunction, Simple
simple_var_sub,
braced_var_sub,
)
from oil.tools import osh2oil # Cursor
def jeepers_peepers(self, *args, **kwargs):
self._old_init(*args, **kwargs)
self.members.append(self)
def consume_members(cls):
members = cls.members
cls.members = list()
yield members
PEEPS = (simple_var_sub, braced_var_sub, command.Simple, command.ShFunction)
for peep in PEEPS:
peep.members = list()
peep._old_init = peep.__init__
peep.__init__ = jeepers_peepers
peep.consume_members = classmethod(contextmanager(consume_members))
def blink():
"""clear global state that interferes w/ multi-step parse"""
for peep in PEEPS:
peep.members = list()
class ResolutionDirectives(object):
fake = fix = keep = None
@property
def varsubs(self):
"""
It's a little wasteful if we end up needing these
more than once, but at the moment we don't, and it
takes more logic to "ingest" them into their own var
in even a hackish way, let alone a principled/safe
one...
"""
return {
k[1:]: v
for k, v in filter(lambda x: isinstance(x, tuple) and len(x) == 2, self.fix)
if k.startswith("$")
}
def __init__(self, fake=None, fix=None, keep=None):
self.fake = fake or set()
self.fix = fix or set()
self.keep = keep or set()
def __len__(self):
return len(self.fake) + len(self.fix) + len(self.keep)
def update(self, *peers):
for peer in peers:
assert isinstance(peer, ResolutionDirectives)
self.fake.update(peer.fake)
self.fix.update(peer.fix)
self.keep.update(peer.keep)
@staticmethod
def _type_tuple(type, entry):
if len(entry) == 1:
return (type, entry[0])
if len(entry) == 2:
return (type, entry[0], entry[1])
def difference(self, *peers):
out = set()
for peer in peers:
assert isinstance(peer, ResolutionDirectives)
for fake in self.fake.difference(peer.fake):
out.add((self._type_tuple("fake", fake)))
for fix in self.fix.difference(peer.fix):
out.add((self._type_tuple("fix", fix)))
for keep in self.keep.difference(peer.keep):
out.add((self._type_tuple("keep", keep)))
return out
def relevant(self, name):
def rel_filt(val):
if len(val) == 1:
return name == val[0]
if len(val) == 2:
return name == val[1]
return self.__class__(
fake=filter(rel_filt, self.fake),
fix=filter(rel_filt, self.fix),
keep=filter(rel_filt, self.keep),
)
directives = ResolutionDirectives()
def parse_directive(value, scope_map=None):
if not len(value):
return set()
out = set()
try:
"""
TODO:
this used to use simple string split. I changed to shlex
to work around cases where someone needs to shell-quote
a directive to support spacing. Example case reported in
https://github.com/abathur/resholve/issues/32
Unfortunately, shlex.split is about an oom slower...
very high fruit, but there's probably a better way to
split this particular baby.
"""
directives = shlex.split(value)
logger.debug("directives: %r", directives)
for directive in directives:
rules = directive.split(":", 1)
if len(rules) == 1:
out.add((rules[0],))
continue
elif len(rules) == 2:
scope = rules[0] if not scope_map else scope_map(rules[0])
rules = rules[1]
rules = rules.split(";")
for rule in rules:
out.add((scope, rule))
else:
raise ourparse.ArgumentTypeError(
"Directives may not have more than one colon: %r" % directive
)
except ValueError as e:
raise ourparse.ArgumentTypeError(
"I don't recognize %r as a known directive. See 'man resholve'." % value
)
return out
FAKE_DIRECTIVE_MAP = {
"a": "alias",
"b": "builtin",
"e": "external",
"f": "function",
"k": "keyword",
"s": "source",
}
FAKE_DIRECTIVE_TYPES = set(FAKE_DIRECTIVE_MAP.keys()) | set(FAKE_DIRECTIVE_MAP.values())
def remap_fake_scope(scope):
global FAKE_DIRECTIVE_MAP
if scope in FAKE_DIRECTIVE_MAP:
return FAKE_DIRECTIVE_MAP[scope]
else:
return scope
def directive_fake(value):
global FAKE_DIRECTIVE_TYPES
directives = parse_directive(value, remap_fake_scope)
for directive in directives:
if len(directive) == 1:
raise ourparse.ArgumentTypeError(
"valid fake directives must have at least two parts"
)
elif directive[0] not in FAKE_DIRECTIVE_TYPES:
raise ourparse.ArgumentTypeError(
"fake directive type (%r) is not one of %r"
% (directive[0], FAKE_DIRECTIVE_TYPES)
)
return directives
def directive_fix(value):
directives = parse_directive(value)
logger.debug("validating fix directives %r", directives)
for directive in directives:
if len(directive) == 1:
logger.debug("%r %r", directive[0], directive[0] == "aliases")
if directive[0] == "aliases":
pass # ok literal
elif os.path.isabs(directive[0]):
pass # ok absolute path
else:
raise ourparse.ArgumentTypeError(
"valid single-part fix directives: 'aliases', absolute path"
)
elif len(directive) == 2:
# we can't validate $variable or outer_command before parse
# we could pre-validate command lookup for a target, but we
# have to wait for the lookup() object... but it isn't a
# given that this will only be used to substitute commands.
# So, we'll just let it fail naturally during the regular
# parse.
pass
return directives
def directive_keep(value):
directives = parse_directive(value)
logger.debug("validating keep directives %r", directives)
for directive in directives:
if len(directive) == 1:
if directive[0][0] == "$":
pass # ok literal
elif directive[0][0:2] == "~/" and os.path.isabs(
os.path.expanduser(directive[0])
):
pass
elif directive[0][0:2] == "./":
pass
elif os.path.isabs(directive[0]):
pass # ok absolute path
else:
raise ourparse.ArgumentTypeError(
"valid single-part keep directives: $variable, absolute path, ~/path, ./path"
)
elif len(directive) == 2:
pass
# can't do much to pre-validate these
return directives
# TODO: action unused for now; delete if still here
# in 2022
# class InvocationAction(theirparse.Action):
# def __call__(self, parser, namespace, values, option_string=None):
# setattr(namespace, self.dest, Invocation(words=values))
class InvocationsAction(theirparse._AppendAction):
"""
Collect arg as a list of invocations.
Use kwarg split=True when the subexec arg is a single
shell word (usually quoted) that will be split on exec.
In this case, the arg will be split with shlex.split.
1-word behavior is more common with --options, while
using a collection of loose shell words is more common
at the end of an invocation--though exceptions, such as
the +/;-terminated -exec/-execdir/-ok/-okdir flags in
find, do exist.
I think (but am not certain; I forgot to doc this earlier)
that this should always be used with nargs (whether a
specific number, or the remainder constant).
TODO: there's a gremlin in here wrt the above; if it isn't
done you can get obtuse failures like in #70. This likely
needs fixing or a backstop or better error-handing--
something to sand down that sharp corner.
"""
split = False
def __init__(self, *args, **kwargs):
kwargs["default"] = list()
self.split = kwargs.pop("split", self.split)
return super(InvocationsAction, self).__init__(*args, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
if not values:
# bail; see https://github.com/abathur/resholve/issues/34
# for more context/motive
return None
if self.split:
words = []
for val in values:
words.extend([Word(val.ast, x) for x in shlex.split(val)])
values = words
return super(InvocationsAction, self).__call__(
parser,
namespace,
Invocation(words=values),
option_string,
)
def interpreter_to_shebang(interp):
if interp == "none":
return None
if not os.path.exists(interp):
raise ourparse.ArgumentTypeError(
"Interpreter must exist or be the string 'none'"
)
if not os.path.isabs(interp):
raise ourparse.ArgumentTypeError("Interpreter path must be absolute")
if not os.access(interp, os.X_OK):
raise ourparse.ArgumentTypeError("Interpreter must be executable")
return "#!{:}\n".format(interp)
class SuperSerial(csv.Dialect):
"""
I'm using : for field separating and \n
for row/record separation for now.
I've intertained using unit separator as
the delimiter, but : is more humane (if
it doesn't cause all kinds of trouble)
"""
delimiter = ":"
escapechar = str("\x1f") # https://en.wikipedia.org/wiki/Unit_separator
quotechar = None
doublequote = False
skipinitialspace = False
lineterminator = "\n"
quoting = csv.QUOTE_NONE
csv.register_dialect("superserial", SuperSerial)
class LoreType(object):
"""
Type for working with a "lore" directory.
"""
lore_kinds = None
@staticmethod
def reader(f, fields):
return csv.DictReader(
f,
fields,
dialect="superserial",
)
@staticmethod
def execers(f):
return LoreType.reader(
f,
[
"verdict", # can|cannot|might
"executable", # abspath
],
)
@staticmethod
def wrappers(f):
return LoreType.reader(
f,
[
"wrapper", # abspath
"wrapped", # abspath
],
)
def __init__(self, lore_kinds):
""" """
self.lore_kinds = lore_kinds
# TODO: see if you can fold ingest_lore in for better
# invocation-time ourparse errors
def __call__(self, value):
if len(self.lore_kinds) == 1:
return self._call_str(value)
else:
return self._call_dir(value)
def _call_str(self, value):
try:
for kind in self.lore_kinds:
reader = getattr(self, kind)
return list(reader(value.split()))
except Exception as e:
raise ourparse.ArgumentTypeError(
"%s must be a colon-delimited string. Got: %r"
% (self.lore_kinds[0], value)
)
def _call_file(self, path):
try:
if os.path.exists(path) and not os.path.isdir(path):
for kind in self.lore_kinds:
f = open(path)
reader = getattr(self, kind)
return reader(f)
else:
raise Exception("%s is not a file" % path)
except Exception as e:
raise ourparse.ArgumentTypeError(
"%s\n lore must be a single file. %s" % (self.lore_kinds[0], e)
)
def _call_dir(self, path):
try:
if os.path.isdir(path):
files = dict()
for kind in self.lore_kinds:
f = open("{:}/{:}".format(path, kind))
reader = getattr(self, kind)
files[kind] = reader(f)
return files
else:
raise Exception("%s is not a directory" % path)
except Exception as e:
raise ourparse.ArgumentTypeError(
"%s\nLore must be a "
"directory with a file named "
"'execers' (and optionally one named "
"'wrappers')." % e
)
class Accumulate(ourparse.Action):
def __call__(self, _parser, ns, vals, *args):
setattr(ns, self.dest, (getattr(ns, self.dest) or []) + vals)
lookup = None
class LookSee(dict):
"""
A dictionary for input (~PATH) lookups.
Broad strokes:
- Take ownership of lookup from distutils.spawn.find_executable to
stop matching files in the current PWD (explicit > implicit) and
avoid having to set PATH.
- Support both directories and individual files in the ~PATH.
- Pre-cache files and rm from search path
- Lazily lookup and cache others
"""
pwd = os.getcwd()
paths = None
__call__ = dict.__getitem__
def __init__(self, path):
"""
init from path-fmt string
- comes via --path/--inputs or RESHOLVE_(PATH|INPUTS)
- each element may be a dir or file
"""
dict.__init__(self)
paths = set()
for path in set(path.split(os.pathsep)):
if os.path.isabs(path):
if os.path.isfile(path):
self[os.path.basename(path)] = path
else:
paths.add(path)
else:
x = os.path.join(self.pwd, path)
if os.path.isfile(x):
self[path] = x
elif os.path.exists(x):
paths.add(x)
else:
paths.add(path)
self.paths = paths
def __missing__(self, basename):
"""
Return abspath or None
"""
for path in self.paths:
abspath = os.path.join(path, basename)
if os.path.isfile(abspath):
return abspath
return None
def make_arg_parser(module):
parser = module.ArgumentParser(
description=strings.description,
usage=strings.synopsis,
auto_env_var_prefix="RESHOLVE_",
add_env_var_help=False,
add_help=False,
)
parser.register("action", "accumulate", Accumulate)
req = parser.add_argument_group(
title="Required",
)
req_path = req.add_mutually_exclusive_group(required=True)
req.add_argument(
"scripts",
metavar="script",
type=str,
nargs="*",
help=strings.scripts,
)
req_path.add_argument(
"--path",
metavar="str",
dest="path",
type=LookSee,
help=strings.path,
)
req_path.add_argument(
"--inputs",
metavar="str",
dest="path",
type=LookSee,
help=strings.inputs,
)
req.add_argument(
"--interpreter",
dest="shebang",
type=interpreter_to_shebang,
metavar="p",
help=strings.interpreter,
required=True,
)
res = parser.add_argument_group(
title="Controlling resolution",
)
res.add_argument(
"--fake",
metavar="str",
action="append",
type=directive_fake,
help=strings.fake,
)
res.add_argument(
"--fix",
metavar="str",
action="append",
type=directive_fix,
help=strings.fix,
)
res.add_argument(
"--keep",
metavar="str",
action="append",
type=directive_keep,
help=strings.keep,
)
"""
TODO: disabling some options that I sketched out but that
do not square with the current implementation and may not
be necessary. Can probably dump if still here in 2022.
res.add_argument(
"--oracle",
dest="oracle",
metavar="str",
action="append",
type=str,
help="executable...",
)
res.add_argument(
"--assayer",
dest="assayer",
metavar="str",
action="append",
type=str,
help="executable...",
)
"""
res.add_argument(
"--lore",
type=LoreType(("execers", "wrappers")),
metavar="d",
help=strings.lore,
)
res.add_argument(
"--execer",
type=LoreType(("execers",)),
metavar="str",
action="accumulate",
help=strings.execer,
)
res.add_argument(
"--wrapper",
type=LoreType(("wrappers",)),
metavar="str",
action="accumulate",
help=strings.wrapper,
)
res.add_argument(
"--assay",
type=ourparse.FileType("r"),
metavar="f",
# see tests for usage; not "supported; unsure.
help=ourparse.SUPPRESS,
)
other = parser.add_argument_group(title="Other")
other.add_argument(
"--prologue",
type=ourparse.FileType("r"),
metavar="f",
help=strings.prologue,
)
other.add_argument(
"--epilogue",
type=ourparse.FileType("r"),
metavar="f",
help=strings.epilogue,
)
other.add_argument(
"--overwrite",
action="store_true",
dest="overwrite",
help=strings.overwrite,
)
# other.add_argument(
# "--faff", type=int, metavar="int", help="fuzz n times for missed commands",
# )
meta = parser.add_argument_group(title="Meta")
meta.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
meta.add_argument(
"--version",
action="version",
version="%(prog)s {:}".format(__version__),
)
return parser
parser = make_arg_parser(ourparse)
resolved_scripts = dict()
def resolve_script(script_path, shebang="", prologue=None, epilogue=None):
if script_path in resolved_scripts:
return resolved_scripts[script_path]
resolved = resolved_scripts[script_path] = ResolvedScript(
script_path, shebang=shebang, prologue=prologue, epilogue=epilogue
)
return resolved
def write_resolved_script(script_path, resolved, overwrite=False):
if not script_path:
resolved.write_to()
elif overwrite:
logger.info("attempting to overwrite script %r", script_path)
resolved.write_to(script_path)
sys.stderr.write("Overwrote %r\n" % (script_path))
else:
logger.info(
"overwrite not set; will attempt to write to: %s%s",
script_path,
".resolved",
)
resolved.write_to(script_path + ".resolved")
sys.stderr.write(
"Rewrote %r to %r\n" % (script_path, script_path + ".resolved")
)
def lookup_source(word):
"""
wrap lookup(word) to special-case source lookups
lookup can't resolve something like `source submodule/helper.sh`
unless we add subdirs to PATH, but that could let all kinds of
stuff into the resolution scope.
Instead, we'll try to resolve source calls from the list of
input scripts before giving lookup a chance.
This is a little weird, but this is a not-implemented stub for
documentation. The business-end of this function is temporarily
published the sourcePATH() context manager during punshow()
"""
raise NotImplementedError("lookup_source called outside of sourcePATH context")
@contextmanager
def sourcePATH(script_map):
global lookup_source
def contextual_lookup_source(word):
if word in script_map:
logger.debug("source in script map %r -> %r", word, script_map)
return script_map[word]
logger.debug("source not in script map %r", word)
return lookup(word)
prev = lookup_source
lookup_source = contextual_lookup_source
yield
lookup_source = prev
lore = dict()
decided_execers = defaultdict(dict)
def ingest_lore(lorefiles):
global lore
logger.debug("ingesting lore %r", lorefiles)
logger.debug("ingesting lore:execers %r", lorefiles["execers"])
for row in lorefiles["execers"]:
logger.debug("ingesting lore:execers:row %r", row)
try:
lore[row["executable"]] = row["verdict"]
except Exception as e:
raise Exception(row, lore, e)
if "wrappers" not in lorefiles:
return
for row in lorefiles["wrappers"]:
if row["wrapped"] in lore:
# overwrite the wrapper's verdict with the wrapped executable's
lore[row["wrapper"]] = lore[row["wrapped"]]
def ingest_assay(assayfile):
reader = csv.DictReader(
# TODO: If the general practice sticks, I may move cmd to end because
# the separator is now ":", and it'll be easier to adapt to colons in
# invocations if we can eat 3 colons and call the rest the command.
assayfile,
[
"executable", # abspath
"command", # ~basename $@
"verdict", # yes|no|unknown
# positions 0-indexed
# let's try to work at the word level first?
"wordnum",
],
dialect="superserial",
)
for row in reader:
logger.debug("assay ingest %r", row)
if row["wordnum"] == "0":
# TODO this needs to be fixed somehow; argparse
# won't catch so it'll throw a stack AND exit 1
raise ourparse.ArgumentTypeError(
"assay wordnum should be 1+ (0 is the same as the invoking command itself)"
)
decided_execers[row["command"].split()[0]] = {k: v for k, v in row.items()}
def punshow():
global lookup
args = parser.parse_args()
# if it makes sense at some point, vars(args) yields a dict of these
# that can be passed as kwargs or something...
logger.info("argparsed: %r", args)
logger.debug("argument sources: \n%s", parser.format_values())
# adopt the runtime dependency path for resolving external executables
if args.path is None:
# made this not-required in order to support both "path" and
# "inputs" terminology (inputs is more nix-idiomatic) but
# store in a single dest; fake our own error
parser.error(
"argument --path/--inputs (or RESHOLVE_PATH/RESHOLVE_INPUTS) is required"
)
lookup = args.path
if args.fake:
for group in args.fake:
directives.fake.update(group)
if args.fix:
for group in args.fix:
directives.fix.update(group)
if args.keep:
for group in args.keep:
directives.keep.update(group)
if args.lore:
ingest_lore(args.lore)
global lore
logger.debug("lore: %r", lore)
if args.execer or args.wrapper:
ingest_lore(
{
"execers": args.execer if args.execer else tuple(),
"wrappers": args.wrapper if args.wrapper else tuple(),
}
)
if args.assay:
ingest_assay(args.assay)
if ("aliases",) not in directives.fix:
RecordCommandlike.disable_alias_replacement()
try:
to_write = set()
checked_scripts = list()
script_map = dict()
for in_script in args.scripts:
abs_script = os.path.abspath(in_script)
if os.path.exists(abs_script):
checked_scripts.append(abs_script)
script_map[in_script] = abs_script
else:
sys.stderr.write("Aborting due to missing file: %r\n" % abs_script)
return 2
if len(set(checked_scripts)) != len(checked_scripts):
sys.stderr.write(
"Aborting due to duplicate script targets.\n"
"Verify your inputs and try again.\n"
)
sys.stderr.write(" Original: %r\n" % args.scripts)
sys.stderr.write(" Distinct: %r\n" % set(checked_scripts))
return 2
if len(args.scripts) == 0:
# None == <stdin>
with sourcePATH(dict()):
resolved_scripts[None] = ResolvedScript(
shebang=args.shebang,
prologue=args.prologue,
epilogue=args.epilogue,
)
to_write.add(None)
resolve_cmdlikes()
else:
with sourcePATH(script_map):
for script in checked_scripts:
resolve_script(
script,
shebang=args.shebang,
prologue=args.prologue,
epilogue=args.epilogue,
)
to_write.add(script)
resolve_cmdlikes()
for script_path in to_write:
write_resolved_script(
script_path, resolved_scripts[script_path], args.overwrite
)
except IOError as e:
sys.stderr.write("Whoooo buddy: " + str(e))
return 2
except Forbid as e:
e.print_if_needed()
return e.exit_status
except error._ErrorWithLocation as e:
if hasattr(e, "print_if_needed"):
e.print_if_needed()
elif hasattr(e, "arena"):
ui.PrettyPrintError(e, e.arena, getattr(e, "label", "error: "))
else:
print(
"This error has location context I couldn't "
"figure out how to print. Please report this "
"@ https://github.com/abathur/resholve/issues",
repr(e),
)
if hasattr(e, "exit_status") and e.exit_status is not None:
return e.exit_status
else:
return 2
except InFileDirectiveError as e:
sys.stderr.write(str(e))
return 2
except ourparse.ArgumentTypeError as e:
sys.stderr.write("Hold up there, cowpoke: " + str(e))
return 2
def find_earliest_spid(node):
"""
I'll focus on the goal rather than mislead you with assertions about
what this does (I'm not confident I understand all of the underlying
variation within oil on this point).
The old assumption was that, when a node has an spids list, the first
item in the list is the earliest spid under the umbrella. That is
usually true, and has held water for many months, but I've found at
least one case with command.AndOr nodes where the leftmost spid in
this array is actually for the && or || token.
We really do want the earliest spid, because we want to be able to
inject a prologue at that point. So, we'll try to descend the ~edge
of the AST, keeping the lowest spid we find.
"""
node_spid = sub_spid = None
if hasattr(node, "spids") and node.spids and len(node.spids):
node_spid = node.spids[0]
elif hasattr(node, "span_id"):
node_spid = node.span_id
elif hasattr(node, "token"):
node_spid = node.token.span_id
if hasattr(node, "children"):
sub_spid = find_earliest_spid(node.children[0])
elif hasattr(node, "words"):
sub_spid = find_earliest_spid(node.words[0])
elif hasattr(node, "parts"):
sub_spid = find_earliest_spid(node.parts[0])
# min will return a None, so fail down the list just in case
return min(node_spid, sub_spid) or node_spid or sub_spid
def get_original_text(arena, location, positions):
text = list()
for loc in range(location, location + positions):
span = arena.GetLineSpan(loc)
line = arena.GetLine(span.line_id)
text.append(line[span.col : span.col + span.length])