Bug fix
authorJakob <jakob@jcornell.net>
Sun, 1 Dec 2019 23:39:31 +0000 (17:39 -0600)
committerJakob <jakob@jcornell.net>
Sun, 1 Dec 2019 23:39:31 +0000 (17:39 -0600)
main.py

diff --git a/main.py b/main.py
index 02edeb07e719f439d3a5be3e1d55b6fb8bfd53a5..5ea39fb5ad8342ff6c4bf20ab36d788fe205334d 100644 (file)
--- a/main.py
+++ b/main.py
@@ -14,6 +14,7 @@
 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
 
 import configparser
+from contextlib import contextmanager
 import filecmp
 import functools
 import json
@@ -48,6 +49,12 @@ class Cli:
                return getpass("Blackboard password: ")
 
 
+@contextmanager
+def deleting(path):
+       yield
+       path.unlink()
+
+
 cfg_parser = configparser.ConfigParser()
 with open('config.ini') as f:
        cfg_parser.read_file(f)
@@ -112,12 +119,14 @@ with StorageManager(Path('auth_cache')) as storage_mgr:
 
                        log('info', "Checking attachment {id}: \"{fileName}\"".format(**attachment_doc), indent = 1)
 
-                       with tempfile.NamedTemporaryFile() as tmp:
+                       # On Windows, can't reopen the temp file while it's open.
+                       # This is needed by `filecmp', so we can't use `tempfile''s auto deletion.
+                       with tempfile.NamedTemporaryFile(delete = False) as tmp:
                                tmp_path = Path(tmp.name)
                                with api_iface.download_attachment(course_id, child_doc['id'], att_id) as resp:
                                        shutil.copyfileobj(resp, tmp)
-                               tmp.seek(0)
 
+                       with deleting(tmp_path):
                                class Result:
                                        NoVersions = namedtuple('NoVersions', [])
                                        MultipleLatest = namedtuple('MultipleLatest', ['paths'])
@@ -152,9 +161,7 @@ with StorageManager(Path('auth_cache')) as storage_mgr:
                                                log('info', "Storing initial revision", indent = 2)
                                        dest = fs.get_new_path(local_path, attachment_doc['fileName'])
                                        log('info', "Destination: {}".format(dest), indent = 2)
-                                       tmp.seek(0)
-                                       with dest.open('wb') as f:
-                                               shutil.copyfileobj(tmp, f)
+                                       shutil.copy2(str(tmp_path), str(dest))
                                        fs.write_metadata(dest, new_version)
                                elif isinstance(result, Result.SingleLatest):
                                        # versions match