Skip to content

Commit 27bade7

Browse files
authored
move bundle files only on success (#12)
1 parent cf477c8 commit 27bade7

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

pywis_topics/bundle.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@
2222
import io
2323
import logging
2424
import os
25+
from pathlib import Path
2526
import shutil
27+
import tempfile
2628
import zipfile
2729

2830
import click
@@ -34,7 +36,11 @@
3436

3537
USERDIR = get_userdir()
3638

39+
TEMPDIR = tempfile.TemporaryDirectory()
40+
TEMPDIR2 = Path(tempfile.TemporaryDirectory().name)
41+
3742
WIS2_TOPIC_HIERARCHY_DIR = get_userdir() / 'wis2-topic-hierarchy'
43+
WIS2_TOPIC_HIERARCHY_DIR_TEMP = TEMPDIR2 / 'wis2-topic-hierarchy'
3844

3945

4046
@click.group()
@@ -56,7 +62,7 @@ def sync_bundle() -> None:
5662
shutil.rmtree(USERDIR)
5763

5864
LOGGER.debug('Downloading WIS2 topic hierarchy')
59-
WIS2_TOPIC_HIERARCHY_DIR.mkdir(parents=True, exist_ok=True)
65+
WIS2_TOPIC_HIERARCHY_DIR_TEMP.mkdir(parents=True, exist_ok=True)
6066

6167
ZIPFILE_URL = 'https://wmo-im.github.io/wis2-topic-hierarchy/wth-bundle.zip' # noqa
6268
FH = io.BytesIO(urlopen_(ZIPFILE_URL).read())
@@ -66,17 +72,27 @@ def sync_bundle() -> None:
6672
LOGGER.debug(f'Processing entry "{name}"')
6773
filename = os.path.basename(name)
6874

69-
dest_file = WIS2_TOPIC_HIERARCHY_DIR / filename
75+
dest_file = WIS2_TOPIC_HIERARCHY_DIR_TEMP / filename
7076
LOGGER.debug(f'Creating "{dest_file}"')
7177
with z.open(name) as src, dest_file.open('wb') as dest:
7278
shutil.copyfileobj(src, dest)
7379

7480
LOGGER.debug('Downloading IANA TLDs')
7581
IANA_URL = 'https://data.iana.org/TLD/tlds-alpha-by-domain.txt'
76-
iana_file = WIS2_TOPIC_HIERARCHY_DIR / 'tlds-alpha-by-domain.txt'
82+
iana_file = WIS2_TOPIC_HIERARCHY_DIR_TEMP / 'tlds-alpha-by-domain.txt'
7783
with iana_file.open('wb') as fh:
7884
fh.write(urlopen_(f'{IANA_URL}').read())
7985

86+
LOGGER.debug(f'Removing {USERDIR}')
87+
if USERDIR.exists():
88+
shutil.rmtree(USERDIR)
89+
90+
LOGGER.debug(f'Moving files from {TEMPDIR2} to {USERDIR}')
91+
shutil.move(TEMPDIR2, USERDIR)
92+
93+
LOGGER.debug(f'Cleaning up {TEMPDIR}')
94+
TEMPDIR.cleanup()
95+
8096

8197
@click.command()
8298
@get_cli_common_options

0 commit comments

Comments
 (0)