From e582d9cca080d8c33c3665cc7bace323cd3f88b7 Mon Sep 17 00:00:00 2001 From: Pieter De Gendt Date: Wed, 13 Sep 2023 16:22:42 +0200 Subject: [PATCH] scripts: build: file2hex: Add optional offset and length parameters Add optional offset and length parameters to generate partial hex files. Signed-off-by: Pieter De Gendt --- scripts/build/file2hex.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/scripts/build/file2hex.py b/scripts/build/file2hex.py index 34857d4159bdf83..2bb967cf29da025 100755 --- a/scripts/build/file2hex.py +++ b/scripts/build/file2hex.py @@ -26,6 +26,11 @@ def parse_args(): formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False) parser.add_argument("-f", "--file", required=True, help="Input file") + parser.add_argument("-o", "--offset", type=lambda x: int(x, 0), default=0, + help="Byte offset in the input file") + parser.add_argument("-l", "--length", type=lambda x: int(x, 0), default=-1, + help="""Length in bytes to read from the input file. + Defaults to reading till the end of the input file.""") parser.add_argument("-g", "--gzip", action="store_true", help="Compress the file using gzip before output") parser.add_argument("-t", "--gzip-mtime", type=int, default=0, @@ -53,18 +58,26 @@ def main(): if args.gzip: with io.BytesIO() as content: with open(args.file, 'rb') as fg: + fg.seek(args.offset) with gzip.GzipFile(fileobj=content, mode='w', mtime=args.gzip_mtime, compresslevel=9) as gz_obj: - gz_obj.write(fg.read()) + gz_obj.write(fg.read(args.length)) content.seek(0) for chunk in iter(lambda: content.read(8), b''): make_hex(chunk) else: with open(args.file, "rb") as fp: - for chunk in iter(lambda: fp.read(8), b''): - make_hex(chunk) + fp.seek(args.offset) + if args.length < 0: + for chunk in iter(lambda: fp.read(8), b''): + make_hex(chunk) + else: + remainder = args.length + for chunk in iter(lambda: fp.read(min(8, remainder)), b''): + make_hex(chunk) + remainder = remainder - len(chunk) if __name__ == "__main__":