Skip to content

Commit 6b8b233

Browse files
committed
feat: implement support for dockerignore and containerignore
Currently repo2docker creates a context object that includes the whole content of the repository it builds an image for. Thus it includes folders like .git which is usually something that has no interest in the final image, can take quite a lot of space and most importantly, kills the caching of that layer. This patch adds support for reading dockerignore and containerignore files that are used to ensure only the relevant data are used to build the image. By default it also excludes the .git folder if neither of these files are provided.
1 parent 0e02889 commit 6b8b233

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

repo2docker/buildpacks/base.py

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
import escapism
1313
import jinja2
1414

15+
from docker.utils.build import exclude_paths
16+
1517
# Only use syntax features supported by Docker 17.09
1618
TEMPLATE = r"""
1719
FROM {{base_image}}
@@ -590,16 +592,16 @@ def build(
590592

591593
tar.addfile(dockerfile_tarinfo, io.BytesIO(dockerfile))
592594

593-
def _filter_tar(tar):
595+
def _filter_tar(tarinfo):
594596
# We need to unset these for build_script_files we copy into tar
595597
# Otherwise they seem to vary each time, preventing effective use
596598
# of the cache!
597599
# https://github.com/docker/docker-py/pull/1582 is related
598-
tar.uname = ""
599-
tar.gname = ""
600-
tar.uid = int(build_args.get("NB_UID", DEFAULT_NB_UID))
601-
tar.gid = int(build_args.get("NB_UID", DEFAULT_NB_UID))
602-
return tar
600+
tarinfo.uname = ""
601+
tarinfo.gname = ""
602+
tarinfo.uid = int(build_args.get("NB_UID", DEFAULT_NB_UID))
603+
tarinfo.gid = int(build_args.get("NB_UID", DEFAULT_NB_UID))
604+
return tarinfo
603605

604606
for src in sorted(self.get_build_script_files()):
605607
dest_path, src_path = self.generate_build_context_filename(src)
@@ -608,7 +610,25 @@ def _filter_tar(tar):
608610
for fname in ("repo2docker-entrypoint", "python3-login"):
609611
tar.add(os.path.join(HERE, fname), fname, filter=_filter_tar)
610612

611-
tar.add(".", "src/", filter=_filter_tar)
613+
exclude = []
614+
615+
for ignore_file in [".dockerignore", ".containerignore"]:
616+
if os.path.exists(ignore_file):
617+
with open(ignore_file, "r") as f:
618+
exclude.extend(
619+
list(
620+
filter(
621+
lambda x: x != "" and x[0] != "#",
622+
[l.strip() for l in f.read().splitlines()],
623+
)
624+
)
625+
)
626+
627+
if not exclude:
628+
exclude = ["**/.git"]
629+
630+
for item in exclude_paths(".", exclude):
631+
tar.add(item, f"src/{item}", filter=_filter_tar)
612632

613633
tar.close()
614634
tarf.seek(0)

0 commit comments

Comments
 (0)