git-p4: auto-delete named temporary file

Avoid double-open exceptions on Windows platform when calculating for lfs compressed size threshold (git-p4.largeFileCompressedThreshold) comparisons. Take new approach using the NamedTemporaryFile() file-like object as input to the ZipFile() which auto-deletes after implicit close leaving with scope. Original code had double-open exception on Windows platform because file still open from NamedTemporaryFile() using generated filename instead of object. Thanks to Andrey for patiently suggesting several iterations on this change for avoiding exceptions! Also print error details after resulting IOError to make debugging cause of exception less mysterious when it has nothing to do with "git version recent enough." Signed-off-by: Philip.McGraw <Philip.McGraw@bentley.com> Reviewed-by: Andrey Mazo <ahippo@yandex.com> Acked-by: Luke Diamand <luke@diamand.org> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Philip.McGraw committed Aug 27, 2019 at 06:43 UTC de5abb5f7a22fbb595fbc6ccb4a75bfad14396d3
1 file changed +6 -7
git-p4.py
+6 -7
@@ -1160,13 +1160,11 @@ class LargeFileSystem(object):
1160 if contentsSize <= gitConfigInt('git-p4.largeFileCompressedThreshold'):
1161 return False
1162 contentTempFile = self.generateTempFile(contents)
1163 - compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False)
1164 - zf = zipfile.ZipFile(compressedContentFile.name, mode='w')
1165 - zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED)
1166 - zf.close()
1167 - compressedContentsSize = zf.infolist()[0].compress_size
1163 + compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=True)
1164 + with zipfile.ZipFile(compressedContentFile, mode='w') as zf:
1165 + zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED)
1166 + compressedContentsSize = zf.infolist()[0].compress_size
1167 os.remove(contentTempFile)
1169 - os.remove(compressedContentFile.name)
1168 if compressedContentsSize > gitConfigInt('git-p4.largeFileCompressedThreshold'):
1169 return True
1170 return False
@@ -3525,8 +3523,9 @@ class P4Sync(Command, P4UserMap):
3523 self.updateOptionDict(details)
3524 try:
3525 self.commit(details, self.extractFilesFromCommit(details), self.branch)
3528 - except IOError:
3526 + except IOError as err:
3527 print("IO error with git fast-import. Is your git version recent enough?")
3528 + print("IO error details: {}".format(err))
3529 print(self.gitError.read())
3530
3531 def openStreams(self):