Skip to content

Commit d268741

Browse files
committed
basename: Add basename.py
1 parent 2528e8f commit d268741

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/basename.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/usr/bin/python3
2+
3+
import os
4+
from optparse import OptionParser
5+
6+
7+
def basename(opts, names: list[str]):
8+
for name in names:
9+
print(
10+
os.path.basename(name.removesuffix(opts.suffix)),
11+
end="\0" if opts.zero else "\n",
12+
)
13+
14+
15+
if __name__ == "__main__":
16+
parser = OptionParser(
17+
usage="Usage: %prog NAME [SUFFIX]\n %prog OPTION... NAME...",
18+
description="Print the last component of each path NAME.",
19+
add_help_option=False,
20+
)
21+
parser.add_option("--help", action="help", help="show usage information and exit")
22+
23+
parser.add_option(
24+
"-a", "--multiple", action="store_true", help="support multiple NAMES"
25+
)
26+
parser.add_option(
27+
"-s",
28+
"--suffix",
29+
metavar="SUFFIX",
30+
help="remove trailing SUFFIX; implies -a",
31+
)
32+
33+
parser.add_option(
34+
"-z",
35+
"--zero",
36+
action="store_true",
37+
help="terminate outputs with NUL instead of newline",
38+
)
39+
40+
opts, args = parser.parse_args()
41+
42+
if not args:
43+
parser.error("missing operand")
44+
45+
if opts.suffix:
46+
opts.multiple = True
47+
elif not opts.multiple and len(args) > 1:
48+
if len(args) > 2:
49+
parser.error(f"extra operand '{args[2]}'")
50+
51+
opts.suffix = args.pop()
52+
else:
53+
opts.suffix = ""
54+
55+
basename(opts, args)

0 commit comments

Comments
 (0)