Skip to content

Commit f48bed8

Browse files
committed
chgrp: Move --from argument parsing logic to core module
This prevents duplication when it has to be used in some other future utilities such as chown. Also added support for numeric UIDs/GIDs instead of only accepting user/group names.
1 parent 86cbe14 commit f48bed8

File tree

3 files changed

+40
-13
lines changed

3 files changed

+40
-13
lines changed

userland/core/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
from .command import *
22
from .io import *
3+
from .users import *

userland/core/users.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import grp
2+
import pwd
3+
4+
from optparse import OptionParser
5+
6+
7+
def parse_onwer_spec(
8+
parser: OptionParser, owner_spec: str
9+
) -> tuple[int | None, int | None]:
10+
"""
11+
Process a string in the form ``[USER][:GROUP]`` and return the UID and GID.
12+
Either or both may be None if omitted from the input string.
13+
An appropriate parser error is thrown if obtaining the UID or GID fails.
14+
"""
15+
tokens = owner_spec.split(":")
16+
17+
uid: int | None = None
18+
gid: int | None = None
19+
20+
if tokens[0]:
21+
if tokens[0].isdecimal():
22+
uid = int(tokens[0])
23+
else:
24+
try:
25+
uid = pwd.getpwnam(tokens[0])
26+
except KeyError:
27+
parser.error(f"invalid user: '{tokens}'")
28+
29+
if len(tokens) > 1 and tokens[1]:
30+
if tokens[1].isdecimal():
31+
gid = int(tokens[1])
32+
else:
33+
try:
34+
gid = grp.getgrnam(tokens[1])
35+
except KeyError:
36+
parser.error(f"invalid group: '{tokens}'")
37+
38+
return uid, gid

userland/utilities/chgrp.py

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -135,19 +135,7 @@ def python_userland_chgrp(opts, args):
135135
from_gid: int | None = None
136136

137137
if opts.from_spec:
138-
from_spec = opts.from_spec.split(":")
139-
140-
if from_spec[0]:
141-
try:
142-
from_uid = pwd.getpwnam(from_spec[0])
143-
except KeyError:
144-
parser.error(f"invalid user: '{opts.from_spec}'")
145-
146-
if len(from_spec) > 1 and from_spec[1]:
147-
try:
148-
from_gid = grp.getgrnam(from_spec[1])
149-
except KeyError:
150-
parser.error(f"invalid group: '{opts.from_spec}'")
138+
from_uid, from_gid = core.parse_onwer_spec(parser, opts.from_spec)
151139

152140
gid: int
153141
gname: str | None = None

0 commit comments

Comments
 (0)