Skip to content

Commit 1211c3d

Browse files
committed
env: Add env.py
1 parent 4ea011d commit 1211c3d

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

userland/utilities/env.py

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import os
2+
import shlex
3+
import sys
4+
5+
from .. import core
6+
7+
8+
parser = core.create_parser(
9+
usage=("%prog [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]",),
10+
)
11+
parser.disable_interspersed_args()
12+
13+
parser.add_option(
14+
"-a",
15+
"--argv0",
16+
metavar="ARG",
17+
help="pass ARG as zeroth argument instead of COMMAND",
18+
)
19+
parser.add_option(
20+
"-i",
21+
"--ignore-environment",
22+
action="store_true",
23+
help="start with empty environment",
24+
)
25+
parser.add_option(
26+
"-u",
27+
"--unset",
28+
action="append",
29+
metavar="NAME",
30+
help="remove variable NAME from the environment",
31+
)
32+
parser.add_option(
33+
"-0",
34+
"--null",
35+
action="store_true",
36+
help="terminate outputs with NUL instead of newline",
37+
)
38+
parser.add_option(
39+
"-C",
40+
"--chdir",
41+
metavar="DIR",
42+
help="change working directory to DIR",
43+
)
44+
parser.add_option(
45+
"-S",
46+
"--split-string",
47+
metavar="STRING",
48+
help="split STRING into separate arguments",
49+
)
50+
51+
52+
@core.command(parser)
53+
def python_userland_env(opts, args):
54+
if args and args[0] == "-":
55+
opts.ignore_environment = True
56+
del args[0]
57+
58+
if opts.ignore_environment:
59+
env = {}
60+
elif opts.unset:
61+
env = {
62+
name: value for name, value in os.environ.items() if name not in opts.unset
63+
}
64+
else:
65+
env = os.environ.copy()
66+
67+
prog_args = []
68+
69+
parsing_decls = True
70+
for arg in args:
71+
if parsing_decls and (eq_pos := arg.find("=")) >= 0:
72+
env[arg[:eq_pos]] = arg[eq_pos + 1 :]
73+
else:
74+
prog_args.append(arg)
75+
parsing_decls = False
76+
77+
if opts.split_string:
78+
prog_args = shlex.split(opts.split_string) + prog_args
79+
80+
if not prog_args:
81+
for name, value in env.items():
82+
print(f"{name}={value}", end="\0" if opts.null else "\n")
83+
return
84+
85+
if opts.chdir:
86+
try:
87+
os.chdir(opts.chdir)
88+
except OSError as e:
89+
print(e, file=sys.stderr)
90+
return 125
91+
92+
prog_args.insert(1, opts.argv0 if opts.argv0 else prog_args[0])
93+
94+
try:
95+
os.execvpe(prog_args[0], prog_args[1:], env)
96+
except OSError as e:
97+
print(e, file=sys.stderr)
98+
return 126 if isinstance(e, FileNotFoundError) else 127

0 commit comments

Comments
 (0)