treewide: Use argparse.FileType in more places

Convert some scripts to use `argparse.FileType` where the change is relatively
easily doable. This allows better error messages as e.g. missing input files
will be detected during argument parsing. And it also makes writing to stdout
in absence of an explicit argument simpler.

Signed-off-by: Barnabás Pőcze <barnabas.pocze@ideasonboard.com>
Reviewed-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
This commit is contained in:
Barnabás Pőcze
2025-09-11 12:00:21 +02:00
parent 901aae13c1
commit b9fd53fbef
6 changed files with 49 additions and 84 deletions

View File

@@ -19,14 +19,12 @@ class DRMFourCC(object):
mod_vendor_regex = re.compile(r"#define DRM_FORMAT_MOD_VENDOR_([A-Z0-9_]+)[ \t]+([0-9a-fA-Fx]+)")
mod_regex = re.compile(r"#define ([A-Za-z0-9_]+)[ \t]+fourcc_mod_code\(([A-Z0-9_]+), ([0-9a-fA-Fx]+)\)")
def __init__(self, filename):
def __init__(self, file):
self.formats = {}
self.vendors = {}
self.mods = {}
for line in open(filename, 'rb').readlines():
line = line.decode('utf-8')
for line in file:
match = DRMFourCC.format_regex.match(line)
if match:
format, fourcc = match.groups()
@@ -80,32 +78,27 @@ def main(argv):
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('-o', dest='output', metavar='file', type=str,
parser.add_argument('-o', dest='output', metavar='file', default=sys.stdout,
type=argparse.FileType('w', encoding='utf-8'),
help='Output file name. Defaults to standard output if not specified.')
parser.add_argument('input', type=str,
parser.add_argument('input', type=argparse.FileType('rb'),
help='Input file name.')
parser.add_argument('template', type=str,
parser.add_argument('template', type=argparse.FileType('r', encoding='utf-8'),
help='Template file name.')
parser.add_argument('drm_fourcc', type=str,
parser.add_argument('drm_fourcc', type=argparse.FileType('r', encoding='utf-8'),
help='Path to drm_fourcc.h.')
args = parser.parse_args(argv[1:])
data = open(args.input, 'rb').read()
formats = yaml.safe_load(data)['formats']
formats = yaml.safe_load(args.input)['formats']
drm_fourcc = DRMFourCC(args.drm_fourcc)
env = jinja2.Environment()
template = env.from_string(open(args.template, 'r', encoding='utf-8').read())
template = env.from_string(args.template.read())
string = template.render({
'formats': generate_formats(formats, drm_fourcc),
})
if args.output:
output = open(args.output, 'wb')
output.write(string.encode('utf-8'))
output.close()
else:
sys.stdout.write(string)
args.output.write(string)
return 0