Skip to content

Instantly share code, notes, and snippets.

@piyueh
Created May 31, 2022 20:34
Show Gist options
  • Save piyueh/3bafccf9d1d8435ac49454fa6ff1dc6e to your computer and use it in GitHub Desktop.
Save piyueh/3bafccf9d1d8435ac49454fa6ff1dc6e to your computer and use it in GitHub Desktop.
List files in each layer of an image tarball created through `docker save`.
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2022 Pi-Yueh Chuang <pychuang@pm.me>
#
# Distributed under terms of the BSD 3-Clause license.
"""List files in each layer of an image tarball created through `docker save`.
"""
import argparse
import logging
import pathlib
import tarfile
import tempfile
def main(image, logger):
"""Main function.
"""
with tarfile.open(image, "r") as fobj:
member = fobj.next()
while member is not None:
if "layer.tar" not in member.name:
member = fobj.next()
continue
logger.info(f"{member.name}")
with tempfile.TemporaryDirectory() as tempdir:
fobj.extract(member, tempdir)
with tarfile.open(f"{tempdir}/{member.name}", "r") as subfobj:
submember = subfobj.next()
while submember is not None:
logger.info(f"\t{submember.name}")
submember = subfobj.next()
logger.info("")
member = fobj.next()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="List files in each layer of a Docker image (in *.tar.gz format)")
parser.add_argument("image", metavar="IMAGE", action="store", type=pathlib.Path)
parser.add_argument("logfile", metavar="LOGFILE", action="store", type=pathlib.Path)
args = parser.parse_args()
logger = logging.getLogger(__name__)
logging.basicConfig(handlers=[logging.NullHandler()], format="%(message)s", level=logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger.addHandler(logging.FileHandler(args.logfile, "w", "utf-8"))
main(args.image, logger)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment