/
environ.py
2513 lines (2282 loc) · 87.9 KB
/
environ.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
"""Environment for the xonsh shell."""
import inspect
import os
import re
import sys
import pprint
import textwrap
import locale
import threading
import warnings
import contextlib
import collections.abc as cabc
import subprocess
import platform
import typing as tp
from collections import ChainMap
from xonsh import __version__ as XONSH_VERSION
from xonsh.lazyasd import lazyobject, LazyBool
from xonsh.codecache import run_script_with_cache
from xonsh.dirstack import _get_cwd
from xonsh.events import events
from xonsh.platform import (
BASH_COMPLETIONS_DEFAULT,
DEFAULT_ENCODING,
PATH_DEFAULT,
ON_WINDOWS,
ON_LINUX,
ON_CYGWIN,
os_environ,
)
from xonsh.built_ins import XSH
from xonsh.tools import (
always_true,
always_false,
detype,
ensure_string,
is_path,
str_to_path,
path_to_str,
is_env_path,
str_to_env_path,
env_path_to_str,
is_bool,
to_bool,
bool_to_str,
is_bool_or_none,
to_bool_or_none,
bool_or_none_to_str,
is_history_tuple,
to_history_tuple,
history_tuple_to_str,
is_float,
is_string,
is_string_or_callable,
is_completions_display_value,
to_completions_display_value,
is_completion_mode,
to_completion_mode,
is_string_set,
csv_to_set,
set_to_csv,
is_int,
to_bool_or_int,
bool_or_int_to_str,
DefaultNotGiven,
print_exception,
intensify_colors_on_win_setter,
is_dynamic_cwd_width,
to_dynamic_cwd_tuple,
dynamic_cwd_tuple_to_str,
is_logfile_opt,
to_logfile_opt,
logfile_opt_to_str,
executables_in,
is_nonstring_seq_of_strings,
pathsep_to_upper_seq,
seq_to_upper_pathsep,
print_color,
is_history_backend,
to_itself,
swap_values,
ptk2_color_depth_setter,
is_str_str_dict,
to_str_str_dict,
dict_to_str,
to_int_or_none,
DefaultNotGivenType,
to_repr_pretty_,
)
from xonsh.ansi_colors import (
ansi_color_escape_code_to_name,
ansi_color_name_to_escape_code,
ansi_reverse_style,
ansi_style_by_name,
)
import xonsh.prompt.base as prompt
from xonsh.prompt.gitstatus import _DEFS as GITSTATUS_FIELD_DEFS
events.doc(
"on_envvar_new",
"""
on_envvar_new(name: str, value: Any) -> None
Fires after a new environment variable is created.
Note: Setting envvars inside the handler might
cause a recursion until the limit.
""",
)
events.doc(
"on_envvar_change",
"""
on_envvar_change(name: str, oldvalue: Any, newvalue: Any) -> None
Fires after an environment variable is changed.
Note: Setting envvars inside the handler might
cause a recursion until the limit.
""",
)
events.doc(
"on_pre_spec_run_ls",
"""
on_pre_spec_run_ls(spec: xonsh.built_ins.SubprocSpec) -> None
Fires right before a SubprocSpec.run() is called for the ls
command.
""",
)
events.doc(
"on_lscolors_change",
"""
on_lscolors_change(key: str, oldvalue: Any, newvalue: Any) -> None
Fires after a value in LS_COLORS changes, when a new key is added (oldvalue is None)
or when an existing key is deleted (newvalue is None).
LS_COLORS values must be (ANSI color) strings, None is unambiguous.
Does not fire when the whole environment variable changes (see on_envvar_change).
Does not fire for each value when LS_COLORS is first instantiated.
Normal usage is to arm the event handler, then read (not modify) all existing values.
""",
)
@lazyobject
def HELP_TEMPLATE():
return (
"{{INTENSE_RED}}{envvar}{{RESET}}:\n\n"
"{{INTENSE_YELLOW}}{docstr}{{RESET}}\n\n"
"default: {{CYAN}}{default}{{RESET}}\n"
"configurable: {{CYAN}}{configurable}{{RESET}}"
)
@lazyobject
def LOCALE_CATS():
lc = {
"LC_CTYPE": locale.LC_CTYPE,
"LC_COLLATE": locale.LC_COLLATE,
"LC_NUMERIC": locale.LC_NUMERIC,
"LC_MONETARY": locale.LC_MONETARY,
"LC_TIME": locale.LC_TIME,
}
if hasattr(locale, "LC_MESSAGES"):
lc["LC_MESSAGES"] = locale.LC_MESSAGES
return lc
def locale_convert(key):
"""Creates a converter for a locale key."""
def lc_converter(val):
try:
locale.setlocale(LOCALE_CATS[key], val)
val = locale.setlocale(LOCALE_CATS[key])
except (locale.Error, KeyError):
msg = f"Failed to set locale {key!r} to {val!r}"
warnings.warn(msg, RuntimeWarning)
return val
return lc_converter
def to_debug(x):
"""Converts value using to_bool_or_int() and sets this value on as the
execer's debug level.
"""
val = to_bool_or_int(x)
if XSH.execer is not None:
XSH.execer.debug_level = val
return val
#
# $LS_COLORS tools
#
class LsColors(cabc.MutableMapping):
"""Helps convert to/from $LS_COLORS format, respecting the xonsh color style.
This accepts the same inputs as dict(). The special value ``target`` is
replaced by no color, but sets a flag for cognizant application (see is_target()).
"""
default_settings = {
"*.7z": ("BOLD_RED",),
"*.Z": ("BOLD_RED",),
"*.aac": ("CYAN",),
"*.ace": ("BOLD_RED",),
"*.alz": ("BOLD_RED",),
"*.arc": ("BOLD_RED",),
"*.arj": ("BOLD_RED",),
"*.asf": ("BOLD_PURPLE",),
"*.au": ("CYAN",),
"*.avi": ("BOLD_PURPLE",),
"*.bmp": ("BOLD_PURPLE",),
"*.bz": ("BOLD_RED",),
"*.bz2": ("BOLD_RED",),
"*.cab": ("BOLD_RED",),
"*.cgm": ("BOLD_PURPLE",),
"*.cpio": ("BOLD_RED",),
"*.deb": ("BOLD_RED",),
"*.dl": ("BOLD_PURPLE",),
"*.dwm": ("BOLD_RED",),
"*.dz": ("BOLD_RED",),
"*.ear": ("BOLD_RED",),
"*.emf": ("BOLD_PURPLE",),
"*.esd": ("BOLD_RED",),
"*.flac": ("CYAN",),
"*.flc": ("BOLD_PURPLE",),
"*.fli": ("BOLD_PURPLE",),
"*.flv": ("BOLD_PURPLE",),
"*.gif": ("BOLD_PURPLE",),
"*.gl": ("BOLD_PURPLE",),
"*.gz": ("BOLD_RED",),
"*.jar": ("BOLD_RED",),
"*.jpeg": ("BOLD_PURPLE",),
"*.jpg": ("BOLD_PURPLE",),
"*.lha": ("BOLD_RED",),
"*.lrz": ("BOLD_RED",),
"*.lz": ("BOLD_RED",),
"*.lz4": ("BOLD_RED",),
"*.lzh": ("BOLD_RED",),
"*.lzma": ("BOLD_RED",),
"*.lzo": ("BOLD_RED",),
"*.m2v": ("BOLD_PURPLE",),
"*.m4a": ("CYAN",),
"*.m4v": ("BOLD_PURPLE",),
"*.mid": ("CYAN",),
"*.midi": ("CYAN",),
"*.mjpeg": ("BOLD_PURPLE",),
"*.mjpg": ("BOLD_PURPLE",),
"*.mka": ("CYAN",),
"*.mkv": ("BOLD_PURPLE",),
"*.mng": ("BOLD_PURPLE",),
"*.mov": ("BOLD_PURPLE",),
"*.mp3": ("CYAN",),
"*.mp4": ("BOLD_PURPLE",),
"*.mp4v": ("BOLD_PURPLE",),
"*.mpc": ("CYAN",),
"*.mpeg": ("BOLD_PURPLE",),
"*.mpg": ("BOLD_PURPLE",),
"*.nuv": ("BOLD_PURPLE",),
"*.oga": ("CYAN",),
"*.ogg": ("CYAN",),
"*.ogm": ("BOLD_PURPLE",),
"*.ogv": ("BOLD_PURPLE",),
"*.ogx": ("BOLD_PURPLE",),
"*.opus": ("CYAN",),
"*.pbm": ("BOLD_PURPLE",),
"*.pcx": ("BOLD_PURPLE",),
"*.pgm": ("BOLD_PURPLE",),
"*.png": ("BOLD_PURPLE",),
"*.ppm": ("BOLD_PURPLE",),
"*.qt": ("BOLD_PURPLE",),
"*.ra": ("CYAN",),
"*.rar": ("BOLD_RED",),
"*.rm": ("BOLD_PURPLE",),
"*.rmvb": ("BOLD_PURPLE",),
"*.rpm": ("BOLD_RED",),
"*.rz": ("BOLD_RED",),
"*.sar": ("BOLD_RED",),
"*.spx": ("CYAN",),
"*.svg": ("BOLD_PURPLE",),
"*.svgz": ("BOLD_PURPLE",),
"*.swm": ("BOLD_RED",),
"*.t7z": ("BOLD_RED",),
"*.tar": ("BOLD_RED",),
"*.taz": ("BOLD_RED",),
"*.tbz": ("BOLD_RED",),
"*.tbz2": ("BOLD_RED",),
"*.tga": ("BOLD_PURPLE",),
"*.tgz": ("BOLD_RED",),
"*.tif": ("BOLD_PURPLE",),
"*.tiff": ("BOLD_PURPLE",),
"*.tlz": ("BOLD_RED",),
"*.txz": ("BOLD_RED",),
"*.tz": ("BOLD_RED",),
"*.tzo": ("BOLD_RED",),
"*.tzst": ("BOLD_RED",),
"*.vob": ("BOLD_PURPLE",),
"*.war": ("BOLD_RED",),
"*.wav": ("CYAN",),
"*.webm": ("BOLD_PURPLE",),
"*.wim": ("BOLD_RED",),
"*.wmv": ("BOLD_PURPLE",),
"*.xbm": ("BOLD_PURPLE",),
"*.xcf": ("BOLD_PURPLE",),
"*.xpm": ("BOLD_PURPLE",),
"*.xspf": ("CYAN",),
"*.xwd": ("BOLD_PURPLE",),
"*.xz": ("BOLD_RED",),
"*.yuv": ("BOLD_PURPLE",),
"*.z": ("BOLD_RED",),
"*.zip": ("BOLD_RED",),
"*.zoo": ("BOLD_RED",),
"*.zst": ("BOLD_RED",),
"bd": ("BACKGROUND_BLACK", "YELLOW"),
"ca": ("BLACK", "BACKGROUND_RED"),
"cd": ("BACKGROUND_BLACK", "YELLOW"),
"di": ("BOLD_BLUE",),
"do": ("BOLD_PURPLE",),
"ex": ("BOLD_GREEN",),
"fi": ("RESET",),
"ln": ("BOLD_CYAN",),
"mh": ("RESET",),
"mi": ("RESET",),
"or": ("BACKGROUND_BLACK", "RED"),
"ow": ("BLUE", "BACKGROUND_GREEN"),
"pi": ("BACKGROUND_BLACK", "YELLOW"),
"rs": ("RESET",),
"sg": ("BLACK", "BACKGROUND_YELLOW"),
"so": ("BOLD_PURPLE",),
"st": ("WHITE", "BACKGROUND_BLUE"),
"su": ("WHITE", "BACKGROUND_RED"),
"tw": ("BLACK", "BACKGROUND_GREEN"),
}
target_value = "target" # special value to set for ln=target
target_color = ("RESET",) # repres in color space
def __init__(self, ini_dict: dict = None):
self._style = self._style_name = None
self._detyped = None
self._d = dict()
self._targets = set()
if ini_dict:
for key, value in ini_dict.items():
if value == LsColors.target_value:
self._targets.add(key)
value = LsColors.target_color
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __setitem__(self, key, value):
self._detyped = None
old_value = self._d.get(key, None)
self._targets.discard(key)
if value == LsColors.target_value:
value = LsColors.target_color
self._targets.add(key)
self._d[key] = value
if (
old_value != value
): # bug won't fire if new value is 'target' and old value happened to be no color.
events.on_lscolors_change.fire(key=key, oldvalue=old_value, newvalue=value)
def __delitem__(self, key):
self._detyped = None
old_value = self._d.get(key, None)
self._targets.discard(key)
del self._d[key]
events.on_lscolors_change.fire(key=key, oldvalue=old_value, newvalue=None)
def __len__(self):
return len(self._d)
def __iter__(self):
yield from self._d
def __str__(self):
return str(self._d)
def __repr__(self):
return f"{self.__class__.__module__}.{self.__class__.__name__}(...)"
_repr_pretty_ = to_repr_pretty_
def is_target(self, key) -> bool:
"""Return True if key is 'target'"""
return key in self._targets
def detype(self):
"""De-types the instance, allowing it to be exported to the environment."""
style = self.style
if self._detyped is None:
self._detyped = ":".join(
[
key
+ "="
+ ";".join(
[
LsColors.target_value
if key in self._targets
else ansi_color_name_to_escape_code(v, cmap=style)
for v in val
]
)
for key, val in sorted(self._d.items())
]
)
return self._detyped
@property
def style_name(self):
"""Current XONSH_COLOR_STYLE value"""
env = getattr(XSH, "env", {}) or {}
env_style_name = env.get("XONSH_COLOR_STYLE", "default")
if self._style_name is None or self._style_name != env_style_name:
self._style_name = env_style_name
self._style = self._detyped = None
return self._style_name
@property
def style(self):
"""The ANSI color style for the current XONSH_COLOR_STYLE"""
style_name = self.style_name
if self._style is None:
self._style = ansi_style_by_name(style_name)
self._detyped = None
return self._style
@classmethod
def fromstring(cls, s):
"""Creates a new instance of the LsColors class from a colon-separated
string of dircolor-valid keys to ANSI color escape sequences.
"""
ini_dict = dict()
# string inputs always use default codes, so translating into
# xonsh names should be done from defaults
reversed_default = ansi_reverse_style(style="default")
for item in s.split(":"):
key, eq, esc = item.partition("=")
if not eq:
# not a valid item
pass
elif esc == LsColors.target_value: # really only for 'ln'
ini_dict[key] = esc
else:
try:
ini_dict[key] = ansi_color_escape_code_to_name(
esc, "default", reversed_style=reversed_default
)
except Exception as e:
print("xonsh:warning:" + str(e), file=sys.stderr)
ini_dict[key] = ("RESET",)
return cls(ini_dict)
@classmethod
def fromdircolors(cls, filename=None):
"""Constructs an LsColors instance by running dircolors.
If a filename is provided, it is passed down to the dircolors command.
"""
# assemble command
cmd = ["dircolors", "-b"]
if filename is not None:
cmd.append(filename)
# get env
if XSH.env:
denv = XSH.env.detype()
else:
denv = None
# run dircolors
try:
out = subprocess.check_output(
cmd, env=denv, universal_newlines=True, stderr=subprocess.DEVNULL
)
except (subprocess.CalledProcessError, FileNotFoundError):
return cls(cls.default_settings)
except OSError:
# necessary to catch OSError: [WinError 740] The requested operation requires elevation
if ON_WINDOWS:
return cls(cls.default_settings)
raise
if not out:
return cls(cls.default_settings)
s = out.splitlines()[0]
_, _, s = s.partition("'")
s, _, _ = s.rpartition("'")
return cls.fromstring(s)
@classmethod
def convert(cls, x):
"""Converts an object to LsColors, if needed."""
if isinstance(x, cls):
return x
elif isinstance(x, str):
return cls.fromstring(x)
elif isinstance(x, bytes):
return cls.fromstring(x.decode())
else:
return cls(x)
def is_lscolors(x):
"""Checks if an object is an instance of LsColors"""
return isinstance(x, LsColors)
@events.on_pre_spec_run_ls
def ensure_ls_colors_in_env(spec=None, **kwargs):
"""This ensures that the $LS_COLORS environment variable is in the
environment. This fires exactly once upon the first time the
ls command is called.
"""
env = XSH.env
if "LS_COLORS" not in env._d:
# this adds it to the env too
default_lscolors(env)
events.on_pre_spec_run_ls.discard(ensure_ls_colors_in_env)
#
# Ensurers
#
# we use this as a registry of common ensurers; valuable for user interface
ENSURERS = {
"bool": (is_bool, to_bool, bool_to_str),
"str": (is_string, ensure_string, ensure_string),
"path": (is_path, str_to_path, path_to_str),
"env_path": (is_env_path, str_to_env_path, env_path_to_str),
"float": (is_float, float, str),
"int": (is_int, int, str),
}
#
# Defaults
#
def default_value(f):
"""Decorator for making callable default values."""
f._xonsh_callable_default = True
return f
def is_callable_default(x):
"""Checks if a value is a callable default."""
return callable(x) and getattr(x, "_xonsh_callable_default", False)
DEFAULT_TITLE = "{current_job:{} | }{user}@{hostname}: {cwd} | xonsh"
@default_value
def xonsh_data_dir(env):
"""Ensures and returns the $XONSH_DATA_DIR"""
xdd = os.path.expanduser(os.path.join(env.get("XDG_DATA_HOME"), "xonsh"))
os.makedirs(xdd, exist_ok=True)
return xdd
@default_value
def xonsh_config_dir(env):
"""``$XDG_CONFIG_HOME/xonsh``"""
xcd = os.path.expanduser(os.path.join(env.get("XDG_CONFIG_HOME"), "xonsh"))
os.makedirs(xcd, exist_ok=True)
return xcd
@default_value
def xdg_data_dirs(env):
r"""
On Windows: ``[%ProgramData%]`` (normally C:\ProgramData)
- More Info: https://docs.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/microsoft-windows-shell-setup-folderlocations-programdata
On Linux and Unix based systemd it is the same as in open-desktop standard: ``['/usr/share', '/usr/local/share']``
"""
if ON_WINDOWS:
return [os_environ["ProgramData"]]
return [
os.path.join("/usr", "share"),
os.path.join("/usr", "local", "share"),
]
@default_value
def xonsh_sys_config_dir(env):
"""
On Linux & Mac OSX: ``'/etc/xonsh'``
On Windows: ``'%ALLUSERSPROFILE%\\\\xonsh'``
"""
if ON_WINDOWS:
etc_path = os_environ["ALLUSERSPROFILE"]
else:
etc_path = "/etc"
return os.path.join(etc_path, "xonsh")
def xonshconfig(env):
"""Ensures and returns the $XONSHCONFIG"""
xcd = env.get("XONSH_CONFIG_DIR")
xc = os.path.join(xcd, "config.json")
return xc
@default_value
def default_xonshrc(env) -> "tuple[str, ...]":
"""
``['$XONSH_SYS_CONFIG_DIR/xonshrc', '$XONSH_CONFIG_DIR/xonsh/rc.xsh', '~/.xonshrc']``
"""
dxrc = (
os.path.join(xonsh_sys_config_dir(env), "xonshrc"),
os.path.join(xonsh_config_dir(env), "rc.xsh"),
os.path.expanduser("~/.xonshrc"),
)
# Check if old config file exists and issue warning
old_config_filename = xonshconfig(env)
if os.path.isfile(old_config_filename):
print(
"WARNING! old style configuration ("
+ old_config_filename
+ ") is no longer supported. "
+ "Please migrate to xonshrc."
)
return dxrc
def get_config_paths(env: "Env", name: str):
return (
os.path.join(xonsh_sys_config_dir(env), name),
os.path.join(xonsh_config_dir(env), name),
)
@default_value
def default_xonshrcdir(env):
"""``['$XONSH_SYS_CONFIG_DIR/rc.d', '$XONSH_CONFIG_DIR/rc.d']``\n"""
return get_config_paths(env, "rc.d")
@default_value
def default_completer_dirs(env):
"""By default, the following paths are searched.
1. ``$XONSH_CONFIG_DIR/completions`` - user level completions
2. ``$XONSH_SYS_CONFIG_DIR/completions`` - system level completions
3. ``$XONSH_DATA_DIR/generated_completions`` - auto generated completers from man pages
4. ``$XDG_DATA_DIRS/xonsh/vendor_completions`` - completers from other programs can be placed here.
Other than this, Python package namespace ``xompletions`` can be used to put completer modules as well.
"""
# inspired from - https://fishshell.com/docs/current/completions.html#where-to-put-completions
return [
os.path.join(env["XONSH_CONFIG_DIR"], "completions"),
os.path.join(env["XONSH_SYS_CONFIG_DIR"], "completions"),
os.path.join(env["XONSH_DATA_DIR"], "generated_completions"),
] + [
os.path.join(parent, "xonsh", "vendor_completions")
for parent in env["XDG_DATA_DIRS"]
]
@default_value
def xonsh_append_newline(env):
"""Appends a newline if we are in interactive mode"""
return env.get("XONSH_INTERACTIVE", False)
@default_value
def default_lscolors(env):
"""Gets a default instanse of LsColors"""
inherited_lscolors = os_environ.get("LS_COLORS", None)
if inherited_lscolors is None:
lsc = LsColors.fromdircolors()
else:
lsc = LsColors.fromstring(inherited_lscolors)
# have to place this in the env, so it is applied
env["LS_COLORS"] = lsc
return lsc
VarKeyType = tp.Union[str, tp.Pattern]
class Var(tp.NamedTuple):
"""Named tuples whose elements represent environment variable
validation, conversion, detyping; default values; and documentation.
Attributes
----------
validate : func
Validator function returning a bool; checks that the variable is of the
expected type.
convert : func
Function to convert variable from a string representation to its type.
detype : func
Function to convert variable from its type to a string representation.
default
Default value for variable. If set to DefaultNotGiven, raise KeyError
instead of returning this default value. Used for env vars defined
outside of Xonsh.
doc : str, optional
The environment variable docstring.
doc_default : str, optional
Custom docstring for the default value for complex defaults.
is_configurable : bool, optional
Flag for whether the environment variable is configurable or not.
can_store_as_str : bool, optional
Flag for whether the environment variable should be stored as a
string. This is used when persisting a variable that is not JSON
serializable to the config file. For example, sets, frozensets, and
potentially other non-trivial data types. default, False.
pattern
a regex pattern to match for the given variable
"""
validate: tp.Optional[tp.Callable] = always_true
convert: tp.Optional[tp.Callable] = None
detype: tp.Optional[tp.Callable] = ensure_string
default: tp.Any = DefaultNotGiven
doc: str = ""
is_configurable: tp.Union[bool, LazyBool] = True
doc_default: tp.Union[str, DefaultNotGivenType] = DefaultNotGiven
can_store_as_str: bool = False
pattern: tp.Optional[VarKeyType] = None
@classmethod
def with_default(
cls,
default: object,
doc: str = "",
doc_default: tp.Union[str, DefaultNotGivenType] = DefaultNotGiven,
type_str: str = "",
**kwargs,
):
"""fill arguments from the value of default"""
if not type_str:
cls_name = type(default).__name__
type_str = {"LazyBool": "bool"}.get(cls_name, cls_name)
if type_str in ENSURERS and "validate" not in kwargs:
validator, convertor, detyper = ENSURERS[type_str]
kwargs.update(
{"validate": validator, "convert": convertor, "detype": detyper}
)
if doc_default == DefaultNotGiven and is_callable_default(default):
doc_default = inspect.getdoc(default) or DefaultNotGiven
return Var(default=default, doc=doc, doc_default=doc_default, **kwargs)
@classmethod
def no_default(cls, type_str: str, doc: str = "", **kwargs):
return cls.with_default(
default=DefaultNotGiven, doc=doc, type_str=type_str, **kwargs
)
@classmethod
def for_locale(cls, lcle: str):
return cls(
validate=always_false,
convert=locale_convert(lcle),
detype=ensure_string,
default=locale.setlocale(getattr(locale, lcle)),
)
def get_key(self, var_name: str) -> VarKeyType:
return self.pattern or var_name
class Xettings:
"""Parent class - All setting classes will be inheriting from this.
The first line of those class's docstring will become the group's title.
Rest of the docstring will become the description of that Group of settings.
"""
@classmethod
def get_settings(cls) -> tp.Iterator[tp.Tuple[VarKeyType, Var]]:
for var_name, var in vars(cls).items():
if not var_name.startswith("__") and var_name.isupper():
yield var.get_key(var_name), var
@staticmethod
def _get_groups(
cls, _seen: tp.Optional[tp.Set["Xettings"]] = None, *bases: "Xettings"
):
if _seen is None:
_seen = set()
subs = cls.__subclasses__()
for sub in subs:
if sub not in _seen:
_seen.add(sub)
yield (*bases, sub), tuple(sub.get_settings())
yield from Xettings._get_groups(sub, _seen, *bases, sub)
@classmethod
def get_groups(
cls,
) -> tp.Iterator[
tp.Tuple[tp.Tuple["Xettings", ...], tp.Tuple[tp.Tuple[VarKeyType, Var], ...]]
]:
yield from Xettings._get_groups(cls)
@classmethod
def get_doc(cls):
import inspect
return inspect.getdoc(cls)
@classmethod
def get_group_title(cls) -> str:
doc = cls.get_doc()
if doc:
return doc.splitlines()[0]
return cls.__name__
@classmethod
def get_group_description(cls) -> str:
doc = cls.get_doc()
if doc:
lines = doc.splitlines()
if len(lines) > 1:
return "\n".join(lines[1:])
return ""
class GeneralSetting(Xettings):
"""General"""
AUTO_CONTINUE = Var.with_default(
False,
"If ``True``, automatically resume stopped jobs when they are disowned. "
"When stopped jobs are disowned and this option is ``False``, a warning "
"will print information about how to continue the stopped process.",
)
COMMANDS_CACHE_SIZE_WARNING = Var.with_default(
6000,
"Number of files on the PATH above which a warning is shown.",
)
COMMANDS_CACHE_SAVE_INTERMEDIATE = Var.with_default(
False,
"If enabled, the CommandsCache saved between runs and can reduce the startup time.",
)
HOSTNAME = Var.with_default(
default=default_value(lambda env: platform.node()),
doc="Automatically set to the name of the current host.",
type_str="str",
)
HOSTTYPE = Var.with_default(
default=default_value(lambda env: platform.machine()),
doc="Automatically set to a string that fully describes the system type on which xonsh is executing.",
type_str="str",
)
LANG = Var.with_default(
default="C.UTF-8",
doc="Fallback locale setting for systems where it matters",
type_str="str",
)
LC_COLLATE = Var.for_locale("LC_COLLATE")
LC_CTYPE = Var.for_locale("LC_CTYPE")
LC_MONETARY = Var.for_locale("LC_MONETARY")
LC_NUMERIC = Var.for_locale("LC_NUMERIC")
LC_TIME = Var.for_locale("LC_TIME")
if hasattr(locale, "LC_MESSAGES"):
LC_MESSAGES = Var.for_locale("LC_MESSAGES")
OLDPWD = Var.with_default(
".",
"Used to represent a previous present working directory.",
is_configurable=False,
)
PATH = Var.with_default(
PATH_DEFAULT,
"List of strings representing where to look for executables.",
type_str="env_path",
doc_default="On Windows: it is ``Path`` value of register's "
"``HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment``. "
"On Mac OSX: ``('/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin')`` "
"On Linux & on Cygwin & on MSYS, when detected that the distro "
"is like arch, the default PATH is "
"``('/usr/local/sbin', '/usr/local/bin', '/usr/bin', "
"'/usr/bin/site_perl', '/usr/bin/vendor_perl', '/usr/bin/core_perl')``"
" and otherwise is "
"``('~/bin', '/usr/local/sbin', '/usr/local/bin', '/usr/sbin',"
"'/usr/bin', '/sbin', '/bin', '/usr/games', '/usr/local/games')``",
)
PATHEXT = Var(
is_nonstring_seq_of_strings,
pathsep_to_upper_seq,
seq_to_upper_pathsep,
[".COM", ".EXE", ".BAT", ".CMD"] if ON_WINDOWS else [],
"Sequence of extension strings (eg, ``.EXE``) for "
"filtering valid executables by. Each element must be "
"uppercase.",
)
RAISE_SUBPROC_ERROR = Var.with_default(
False,
"Whether or not to raise an error if a subprocess (captured or "
"uncaptured) returns a non-zero exit status, which indicates failure. "
"This is most useful in xonsh scripts or modules where failures "
"should cause an end to execution. This is less useful at a terminal. "
"The error that is raised is a ``subprocess.CalledProcessError``.",
)
XONSH_SUBPROC_CAPTURED_PRINT_STDERR = Var.with_default(
False,
"If ``True`` the stderr from captured subproc will be printed automatically.",
)
TERM = Var.no_default(
"str",
"TERM is sometimes set by the terminal emulator. This is used (when "
"valid) to determine whether the terminal emulator can support "
"the selected shell, or whether or not to set the title. Users shouldn't "
"need to set this themselves. Note that this variable should be set as "
"early as possible in order to ensure it is effective. Here are a few "
"options:\n\n"
"* Set this from the program that launches xonsh. On POSIX systems, \n"
" this can be performed by using env, e.g. \n"
" ``/usr/bin/env TERM=xterm-color xonsh`` or similar.\n"
"* From the xonsh command line, namely ``xonsh -DTERM=xterm-color``.\n"
'* In the config file with ``{"env": {"TERM": "xterm-color"}}``.\n'
"* Lastly, in xonshrc with ``$TERM``\n\n"
"Ideally, your terminal emulator will set this correctly but that does "
"not always happen.",
is_configurable=False,
)
XONSH_CAPTURE_ALWAYS = Var.with_default(
False,
"Try to capture output of commands run without explicit capturing.\n"
"If True, xonsh will capture the output of commands run directly or in ``![]``"
"to the session history.\n"
"Setting to True has the following disadvantages:\n"
"* Some interactive commands won't work properly (like when ``git`` invokes an interactive editor).\n"
" For more information see discussion at https://github.com/xonsh/xonsh/issues/3672.\n"
"* Stopping these commands with ^Z (i.e. ``SIGTSTP``)\n"
" is disabled as it causes deadlocked terminals.\n"
" ``SIGTSTP`` may still be issued and only the physical pressing\n"
" of ``Ctrl+Z`` is ignored.\n\n"
"Regardless of this value, commands run in ``$()``, ``!()`` or with an IO redirection (``>`` or ``|``) "
"will always be captured.\n"
"Setting this to True depends on ``$THREAD_SUBPROCS`` being True.",
)
THREAD_SUBPROCS = Var(
is_bool_or_none,
to_bool_or_none,
bool_or_none_to_str,
not ON_CYGWIN,
"Note: The ``$XONSH_CAPTURE_ALWAYS`` variable introduces finer control "
"and you should probably use that instead.\n\n"
"Whether or not to try to run subrocess mode in a Python thread, "
"when trying to capture its output. There are various trade-offs.\n\n"
"If True, xonsh is able capture & store the stdin, stdout, and stderr \n"
" of threadable subprocesses.\n"
"The disadvantages are listed in ``$XONSH_CAPTURE_ALWAYS``.\n"
"The desired effect is often up to the command, user, or use case.\n\n"
"None values are for internal use only and are used to turn off "
"threading when loading xonshrc files. This is done because Bash "
"was automatically placing new xonsh instances in the background "
"at startup when threadable subprocs were used. Please see "
"https://github.com/xonsh/xonsh/pull/3705 for more information.\n",
)
UPDATE_OS_ENVIRON = Var.with_default(
False,
"If True ``os_environ`` will always be updated "
"when the xonsh environment changes. The environment can be reset to "
"the default value by calling ``__xonsh__.env.undo_replace_env()``",
)
XDG_CONFIG_HOME = Var.with_default(
os.path.expanduser(os.path.join("~", ".config")),
"Open desktop standard configuration home dir. This is the same "
"default as used in the standard.",
is_configurable=False,
doc_default="``~/.config``",
type_str="str",
)
XDG_DATA_HOME = Var.with_default(
os.path.expanduser(os.path.join("~", ".local", "share")),
"Open desktop standard data home dir. This is the same default as "
"used in the standard.",
doc_default="``~/.local/share``",
type_str="str",
)
XDG_DATA_DIRS = Var.with_default(
xdg_data_dirs,
"A list of directories where system level data files are stored.",
type_str="env_path",
)
XONSHRC = Var.with_default(
default_xonshrc,
"A list of the locations of run control files, if they exist. User "
"defined run control file will supersede values set in system-wide "
"control file if there is a naming collision. $THREAD_SUBPROCS=None "