@@ -80,16 +80,35 @@ def decode_json_header(header):
80
80
81
81
82
82
def tar (path , exclude = None , dockerfile = None , fileobj = None , gzip = False ):
83
- if not fileobj :
84
- fileobj = tempfile .NamedTemporaryFile ()
85
- t = tarfile .open (mode = 'w:gz' if gzip else 'w' , fileobj = fileobj )
86
-
87
83
root = os .path .abspath (path )
88
84
exclude = exclude or []
89
85
90
- for path in sorted (exclude_paths (root , exclude , dockerfile = dockerfile )):
91
- i = t .gettarinfo (os .path .join (root , path ), arcname = path )
86
+ return create_archive (
87
+ files = sorted (exclude_paths (root , exclude , dockerfile = dockerfile )),
88
+ root = root , fileobj = fileobj , gzip = gzip
89
+ )
90
+
91
+
92
+ def build_file_list (root ):
93
+ files = []
94
+ for dirname , dirnames , fnames in os .walk (root ):
95
+ for filename in fnames + dirnames :
96
+ longpath = os .path .join (dirname , filename )
97
+ files .append (
98
+ longpath .replace (root , '' , 1 ).lstrip ('/' )
99
+ )
92
100
101
+ return files
102
+
103
+
104
+ def create_archive (root , files = None , fileobj = None , gzip = False ):
105
+ if not fileobj :
106
+ fileobj = tempfile .NamedTemporaryFile ()
107
+ t = tarfile .open (mode = 'w:gz' if gzip else 'w' , fileobj = fileobj )
108
+ if files is None :
109
+ files = build_file_list (root )
110
+ for path in files :
111
+ i = t .gettarinfo (os .path .join (root , path ), arcname = path )
93
112
if i is None :
94
113
# This happens when we encounter a socket file. We can safely
95
114
# ignore it and proceed.
@@ -102,13 +121,11 @@ def tar(path, exclude=None, dockerfile=None, fileobj=None, gzip=False):
102
121
103
122
try :
104
123
# We open the file object in binary mode for Windows support.
105
- f = open (os .path .join (root , path ), 'rb' )
124
+ with open (os .path .join (root , path ), 'rb' ) as f :
125
+ t .addfile (i , f )
106
126
except IOError :
107
127
# When we encounter a directory the file object is set to None.
108
- f = None
109
-
110
- t .addfile (i , f )
111
-
128
+ t .addfile (i , None )
112
129
t .close ()
113
130
fileobj .seek (0 )
114
131
return fileobj
0 commit comments