gh-93096: Make mimetypes CLI tool public (#93097)

Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
This commit is contained in:
Oleg Iarygin 2025-03-13 15:19:22 +04:00 committed by GitHub
parent 119bcfad9c
commit 328f8b8856
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 176 additions and 76 deletions

View file

@ -670,50 +670,38 @@ _default_mime_types()
def _main():
import getopt
"""Run the mimetypes command-line interface."""
import sys
from argparse import ArgumentParser
USAGE = """\
Usage: mimetypes.py [options] type
parser = ArgumentParser(description='map filename extensions to MIME types')
parser.add_argument(
'-e', '--extension',
action='store_true',
help='guess extension instead of type'
)
parser.add_argument(
'-l', '--lenient',
action='store_true',
help='additionally search for common but non-standard types'
)
parser.add_argument('type', nargs='+', help='a type to search')
args = parser.parse_args()
Options:
--help / -h -- print this message and exit
--lenient / -l -- additionally search of some common, but non-standard
types.
--extension / -e -- guess extension instead of type
More than one type argument may be given.
"""
def usage(code, msg=''):
print(USAGE)
if msg: print(msg)
sys.exit(code)
try:
opts, args = getopt.getopt(sys.argv[1:], 'hle',
['help', 'lenient', 'extension'])
except getopt.error as msg:
usage(1, msg)
strict = 1
extension = 0
for opt, arg in opts:
if opt in ('-h', '--help'):
usage(0)
elif opt in ('-l', '--lenient'):
strict = 0
elif opt in ('-e', '--extension'):
extension = 1
for gtype in args:
if extension:
guess = guess_extension(gtype, strict)
if not guess: print("I don't know anything about type", gtype)
else: print(guess)
else:
guess, encoding = guess_type(gtype, strict)
if not guess: print("I don't know anything about type", gtype)
else: print('type:', guess, 'encoding:', encoding)
if args.extension:
for gtype in args.type:
guess = guess_extension(gtype, not args.lenient)
if guess:
print(guess)
else:
sys.exit(f"error: unknown type {gtype}")
else:
for gtype in args.type:
guess, encoding = guess_type(gtype, not args.lenient)
if guess:
print('type:', guess, 'encoding:', encoding)
else:
sys.exit(f"error: media type unknown for {gtype}")
if __name__ == '__main__':