1
+ import os
1
2
import io
2
3
import mimetypes
3
4
import json
@@ -261,7 +262,9 @@ def SetContentString(self, content, encoding="utf-8"):
261
262
:param content: content of the file in string.
262
263
:type content: str
263
264
"""
264
- self .content = io .BytesIO (content .encode (encoding ))
265
+ if content :
266
+ self .content = io .BytesIO (content .encode (encoding ))
267
+
265
268
if self .get ("mimeType" ) is None :
266
269
self ["mimeType" ] = "text/plain"
267
270
@@ -275,7 +278,9 @@ def SetContentFile(self, filename):
275
278
:param filename: name of the file to be uploaded.
276
279
:type filename: str.
277
280
"""
278
- self .content = open (filename , "rb" )
281
+ if os .path .getsize (filename ):
282
+ self .content = open (filename , "rb" )
283
+
279
284
if self .get ("title" ) is None :
280
285
self ["title" ] = filename
281
286
if self .get ("mimeType" ) is None :
@@ -353,20 +358,32 @@ def download(fd, request):
353
358
download (fd , files .get_media (fileId = file_id ))
354
359
except errors .HttpError as error :
355
360
exc = ApiRequestError (error )
356
- if (
357
- exc .error ["code" ] != 403
358
- or exc .GetField ("reason" ) != "fileNotDownloadable"
359
- ):
361
+ code = exc .error ["code" ]
362
+ reason = exc .GetField ("reason" )
363
+ if code == 403 and reason == "fileNotDownloadable" :
364
+ mimetype = mimetype or "text/plain"
365
+ fd .seek (0 ) # just in case `download()` modified `fd`
366
+ try :
367
+ download (
368
+ fd ,
369
+ files .export_media (
370
+ fileId = file_id , mimeType = mimetype
371
+ ),
372
+ )
373
+ except errors .HttpError as error :
374
+ raise ApiRequestError (error )
375
+ elif code == 416 and reason == "requestedRangeNotSatisfiable" :
376
+ # NOTE: An empty file case. Wasting one API call to make
377
+ # absolutely sure. See
378
+ # https://github.com/iterative/dvc/issues/4507
379
+ try :
380
+ self .FetchMetadata (fields = "fileSize" )
381
+ if int (self ["fileSize" ]) != 0 :
382
+ raise exc
383
+ except errors .HttpError :
384
+ raise exc
385
+ else :
360
386
raise exc
361
- mimetype = mimetype or "text/plain"
362
- fd .seek (0 ) # just in case `download()` modified `fd`
363
- try :
364
- download (
365
- fd ,
366
- files .export_media (fileId = file_id , mimeType = mimetype ),
367
- )
368
- except errors .HttpError as error :
369
- raise ApiRequestError (error )
370
387
371
388
if mimetype == "text/plain" and remove_bom :
372
389
fd .seek (0 )
0 commit comments