misc: fix warning about unclosed resource in import-site (#53577)

This commit is contained in:
Benjamin Dauvergne 2021-04-29 22:56:22 +02:00
parent ea21ad5b00
commit 8855869cf8
1 changed files with 28 additions and 23 deletions

View File

@ -14,6 +14,7 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import contextlib
import json
import sys
import tarfile
@ -35,28 +36,32 @@ class Command(BaseCommand):
parser.add_argument('--overwrite', action='store_true', default=False, help='Overwrite asset files')
def handle(self, filename, *args, **options):
if filename == '-':
format = 'json'
fd = sys.stdin
else:
try:
fd = open(filename, 'rb')
except IOError as e:
raise CommandError(e)
try:
tarfile.open(mode='r', fileobj=fd)
except tarfile.TarError as e:
with contextlib.ExitStack() as stack:
if filename == '-':
format = 'json'
fd = open(filename, 'r')
fd = sys.stdin
else:
format = 'tar'
fd = open(filename, 'rb')
try:
if format == 'json':
import_site(json.load(fd), if_empty=options['if_empty'], clean=options['clean'])
else:
import_site_tar(
fd, if_empty=options['if_empty'], clean=options['clean'], overwrite=options['overwrite']
)
except ImportSiteError as e:
raise CommandError(e)
try:
fd = stack.enter_context(open(filename, 'rb'))
except IOError as e:
raise CommandError(e)
try:
tarfile.open(mode='r', fileobj=fd)
except tarfile.TarError as e:
format = 'json'
fd = open(filename, 'r')
else:
format = 'tar'
fd = open(filename, 'rb')
try:
if format == 'json':
import_site(json.load(fd), if_empty=options['if_empty'], clean=options['clean'])
else:
import_site_tar(
fd,
if_empty=options['if_empty'],
clean=options['clean'],
overwrite=options['overwrite'],
)
except ImportSiteError as e:
raise CommandError(e)