1111
1212import escapism
1313import jinja2
14+ from docker .utils .build import exclude_paths
1415
1516# Only use syntax features supported by Docker 17.09
1617TEMPLATE = r"""
@@ -590,16 +591,16 @@ def build(
590591
591592 tar .addfile (dockerfile_tarinfo , io .BytesIO (dockerfile ))
592593
593- def _filter_tar (tar ):
594+ def _filter_tar (tarinfo ):
594595 # We need to unset these for build_script_files we copy into tar
595596 # Otherwise they seem to vary each time, preventing effective use
596597 # of the cache!
597598 # 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
599+ tarinfo .uname = ""
600+ tarinfo .gname = ""
601+ tarinfo .uid = int (build_args .get ("NB_UID" , DEFAULT_NB_UID ))
602+ tarinfo .gid = int (build_args .get ("NB_UID" , DEFAULT_NB_UID ))
603+ return tarinfo
603604
604605 for src in sorted (self .get_build_script_files ()):
605606 dest_path , src_path = self .generate_build_context_filename (src )
@@ -608,7 +609,34 @@ def _filter_tar(tar):
608609 for fname in ("repo2docker-entrypoint" , "python3-login" ):
609610 tar .add (os .path .join (HERE , fname ), fname , filter = _filter_tar )
610611
611- tar .add ("." , "src/" , filter = _filter_tar )
612+ exclude = []
613+
614+ for ignore_file_name in [".dockerignore" , ".containerignore" ]:
615+ ignore_file_name = self .binder_path (ignore_file_name )
616+ if os .path .exists (ignore_file_name ):
617+ with open (ignore_file_name ) as ignore_file :
618+ cleaned_lines = [
619+ line .strip () for line in ignore_file .read ().splitlines ()
620+ ]
621+ exclude .extend (
622+ [
623+ line
624+ for line in cleaned_lines
625+ if line != "" and line [0 ] != "#"
626+ ]
627+ )
628+
629+ files_to_add = exclude_paths ("." , exclude )
630+
631+ if files_to_add :
632+ for item in files_to_add :
633+ tar .add (item , f"src/{ item } " , filter = _filter_tar )
634+ else :
635+ # Either the source was empty or everything was filtered out.
636+ # In any case, create an src dir so the build can proceed.
637+ src = tarfile .TarInfo ("src" )
638+ src .type = tarfile .DIRTYPE
639+ tar .addfile (src )
612640
613641 tar .close ()
614642 tarf .seek (0 )
0 commit comments