Skip to content

Commit ca17146

Browse files
committed
Ruff robo-fixes
1 parent d639784 commit ca17146

File tree

4 files changed

+77
-84
lines changed

4 files changed

+77
-84
lines changed

src/bagit/__init__.py

Lines changed: 66 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
32

43
import argparse
54
import codecs
@@ -208,74 +207,73 @@ def make_bag(
208207
raise BagError(
209208
_("Read permissions are required to calculate file fixities")
210209
)
211-
else:
212-
LOGGER.info(_("Creating data directory"))
213-
214-
# FIXME: if we calculate full paths we won't need to deal with changing directories
215-
os.chdir(bag_dir)
216-
cwd = os.getcwd()
217-
temp_data = tempfile.mkdtemp(dir=cwd)
218-
219-
for f in os.listdir("."):
220-
if os.path.abspath(f) == temp_data:
221-
continue
222-
new_f = os.path.join(temp_data, f)
223-
LOGGER.info(
224-
_("Moving %(source)s to %(destination)s"),
225-
{"source": f, "destination": new_f},
226-
)
227-
os.rename(f, new_f)
210+
LOGGER.info(_("Creating data directory"))
211+
212+
# FIXME: if we calculate full paths we won't need to deal with changing directories
213+
os.chdir(bag_dir)
214+
cwd = os.getcwd()
215+
temp_data = tempfile.mkdtemp(dir=cwd)
228216

217+
for f in os.listdir("."):
218+
if os.path.abspath(f) == temp_data:
219+
continue
220+
new_f = os.path.join(temp_data, f)
229221
LOGGER.info(
230222
_("Moving %(source)s to %(destination)s"),
231-
{"source": temp_data, "destination": "data"},
223+
{"source": f, "destination": new_f},
232224
)
233-
while True:
234-
try:
235-
os.rename(temp_data, "data")
236-
break
237-
except PermissionError as e:
238-
if hasattr(e, "winerror") and e.winerror == 5:
239-
LOGGER.warning(
240-
_(
241-
"PermissionError [WinError 5] when renaming temp folder. Retrying in 10 seconds..."
242-
)
225+
os.rename(f, new_f)
226+
227+
LOGGER.info(
228+
_("Moving %(source)s to %(destination)s"),
229+
{"source": temp_data, "destination": "data"},
230+
)
231+
while True:
232+
try:
233+
os.rename(temp_data, "data")
234+
break
235+
except PermissionError as e:
236+
if hasattr(e, "winerror") and e.winerror == 5:
237+
LOGGER.warning(
238+
_(
239+
"PermissionError [WinError 5] when renaming temp folder. Retrying in 10 seconds..."
243240
)
244-
time.sleep(10)
245-
else:
246-
raise
241+
)
242+
time.sleep(10)
243+
else:
244+
raise
247245

248-
# permissions for the payload directory should match those of the
249-
# original directory
250-
os.chmod("data", os.stat(cwd).st_mode)
246+
# permissions for the payload directory should match those of the
247+
# original directory
248+
os.chmod("data", os.stat(cwd).st_mode)
251249

252-
total_bytes, total_files = make_manifests(
253-
"data", processes, algorithms=checksums, encoding=encoding
254-
)
250+
total_bytes, total_files = make_manifests(
251+
"data", processes, algorithms=checksums, encoding=encoding
252+
)
255253

256-
LOGGER.info(_("Creating bagit.txt"))
257-
txt = """BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n"""
258-
with open_text_file("bagit.txt", "w") as bagit_file:
259-
bagit_file.write(txt)
260-
261-
LOGGER.info(_("Creating bag-info.txt"))
262-
if bag_info is None:
263-
bag_info = {}
264-
265-
# allow 'Bagging-Date' and 'Bag-Software-Agent' to be overidden
266-
if "Bagging-Date" not in bag_info:
267-
bag_info["Bagging-Date"] = date.strftime(date.today(), "%Y-%m-%d")
268-
if "Bag-Software-Agent" not in bag_info:
269-
bag_info["Bag-Software-Agent"] = "bagit.py v%s <%s>" % (
270-
VERSION,
271-
PROJECT_URL,
272-
)
254+
LOGGER.info(_("Creating bagit.txt"))
255+
txt = """BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n"""
256+
with open_text_file("bagit.txt", "w") as bagit_file:
257+
bagit_file.write(txt)
258+
259+
LOGGER.info(_("Creating bag-info.txt"))
260+
if bag_info is None:
261+
bag_info = {}
262+
263+
# allow 'Bagging-Date' and 'Bag-Software-Agent' to be overidden
264+
if "Bagging-Date" not in bag_info:
265+
bag_info["Bagging-Date"] = date.strftime(date.today(), "%Y-%m-%d")
266+
if "Bag-Software-Agent" not in bag_info:
267+
bag_info["Bag-Software-Agent"] = "bagit.py v%s <%s>" % (
268+
VERSION,
269+
PROJECT_URL,
270+
)
273271

274-
bag_info["Payload-Oxum"] = "%s.%s" % (total_bytes, total_files)
275-
_make_tag_file("bag-info.txt", bag_info)
272+
bag_info["Payload-Oxum"] = "%s.%s" % (total_bytes, total_files)
273+
_make_tag_file("bag-info.txt", bag_info)
276274

277-
for c in checksums:
278-
_make_tagmanifest_file(c, bag_dir, encoding="utf-8")
275+
for c in checksums:
276+
_make_tagmanifest_file(c, bag_dir, encoding="utf-8")
279277
except Exception:
280278
LOGGER.exception(_("An error occurred creating a bag in %s"), bag_dir)
281279
raise
@@ -285,14 +283,14 @@ def make_bag(
285283
return Bag(bag_dir)
286284

287285

288-
class Bag(object):
286+
class Bag:
289287
"""A representation of a bag."""
290288

291289
valid_files = ["bagit.txt", "fetch.txt"]
292290
valid_directories = ["data"]
293291

294292
def __init__(self, path):
295-
super(Bag, self).__init__()
293+
super().__init__()
296294
self.tags = {}
297295
self.info = {}
298296
#: Dictionary of manifest entries and the checksum values for each
@@ -723,8 +721,7 @@ def _load_manifests(self):
723721
)
724722
if self.version_info >= (1,):
725723
raise BagError(msg % warning_ctx)
726-
else:
727-
LOGGER.warning(msg, warning_ctx)
724+
LOGGER.warning(msg, warning_ctx)
728725
else:
729726
raise BagError(
730727
_(
@@ -960,7 +957,7 @@ class BagError(Exception):
960957

961958
class BagValidationError(BagError):
962959
def __init__(self, message, details=None):
963-
super(BagValidationError, self).__init__()
960+
super().__init__()
964961

965962
if details is None:
966963
details = []
@@ -977,14 +974,14 @@ def __str__(self):
977974

978975
class ManifestErrorDetail(BagError):
979976
def __init__(self, path):
980-
super(ManifestErrorDetail, self).__init__()
977+
super().__init__()
981978

982979
self.path = path
983980

984981

985982
class ChecksumMismatch(ManifestErrorDetail):
986983
def __init__(self, path, algorithm=None, expected=None, found=None):
987-
super(ChecksumMismatch, self).__init__(path)
984+
super().__init__(path)
988985

989986
self.path = path
990987
self.algorithm = algorithm
@@ -1021,7 +1018,7 @@ class FileNormalizationConflict(BagError):
10211018
"""
10221019

10231020
def __init__(self, file_a, file_b):
1024-
super(FileNormalizationConflict, self).__init__()
1021+
super().__init__()
10251022

10261023
self.file_a = file_a
10271024
self.file_b = file_b
@@ -1079,8 +1076,7 @@ def build_unicode_normalized_lookup_dict(filenames):
10791076
normalized_filename = normalize_unicode(filename)
10801077
if normalized_filename in output:
10811078
raise FileNormalizationConflict(filename, output[normalized_filename])
1082-
else:
1083-
output[normalized_filename] = filename
1079+
output[normalized_filename] = filename
10841080

10851081
return output
10861082

@@ -1153,7 +1149,7 @@ def _calculate_file_hashes(full_path, f_hashers):
11531149
break
11541150
for i in f_hashers.values():
11551151
i.update(block)
1156-
except (OSError, IOError) as e:
1152+
except OSError as e:
11571153
raise BagValidationError(
11581154
_("Could not read %(filename)s: %(error)s")
11591155
% {"filename": full_path, "error": str(e)}

test.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
# encoding: utf-8
21

3-
from __future__ import absolute_import, division, print_function, unicode_literals
42

53
import codecs
64
import datetime
@@ -38,7 +36,7 @@ class SelfCleaningTestCase(unittest.TestCase):
3836
"""TestCase subclass which cleans up self.tmpdir after each test"""
3937

4038
def setUp(self):
41-
super(SelfCleaningTestCase, self).setUp()
39+
super().setUp()
4240

4341
self.starting_directory = (
4442
os.getcwd()
@@ -62,7 +60,7 @@ def tearDown(self):
6260

6361
shutil.rmtree(self.tmpdir)
6462

65-
super(SelfCleaningTestCase, self).tearDown()
63+
super().tearDown()
6664

6765

6866
@mock.patch(
@@ -267,7 +265,7 @@ def test_validation_completeness_error_details(self):
267265
def test_bom_in_bagit_txt(self):
268266
bag = bagit.make_bag(self.tmpdir)
269267
BOM = codecs.BOM_UTF8.decode("utf-8")
270-
with open(j(self.tmpdir, "bagit.txt"), "r") as bf:
268+
with open(j(self.tmpdir, "bagit.txt")) as bf:
271269
bagfile = BOM + bf.read()
272270
with open(j(self.tmpdir, "bagit.txt"), "w") as bf:
273271
bf.write(bagfile)
@@ -332,7 +330,7 @@ def test_mixed_case_checksums(self):
332330
hasher = hashlib.new("md5")
333331
contents = slurp_text_file(j(self.tmpdir, "manifest-md5.txt")).encode("utf-8")
334332
hasher.update(contents)
335-
with open(j(self.tmpdir, "tagmanifest-md5.txt"), "r") as tagmanifest:
333+
with open(j(self.tmpdir, "tagmanifest-md5.txt")) as tagmanifest:
336334
tagman_contents = tagmanifest.read()
337335
tagman_contents = tagman_contents.replace(
338336
bag.entries["manifest-md5.txt"]["md5"], hasher.hexdigest()
@@ -424,7 +422,7 @@ def test_validate_optional_tagfile_in_directory(self):
424422
self.assertRaises(bagit.BagValidationError, self.validate, bag)
425423

426424
hasher = hashlib.new("md5")
427-
with open(j(tagdir, "tagfolder", "tagfile"), "r") as tf:
425+
with open(j(tagdir, "tagfolder", "tagfile")) as tf:
428426
contents = tf.read().encode("utf-8")
429427
hasher.update(contents)
430428
with open(j(self.tmpdir, "tagmanifest-md5.txt"), "w") as tagman:
@@ -454,7 +452,7 @@ def test_validate_unreadable_file(self):
454452

455453
class TestMultiprocessValidation(TestSingleProcessValidation):
456454
def validate(self, bag, *args, **kwargs):
457-
return super(TestMultiprocessValidation, self).validate(
455+
return super().validate(
458456
bag, *args, processes=2, **kwargs
459457
)
460458

@@ -1014,7 +1012,7 @@ def test_open_bag_with_unknown_encoding(self):
10141012

10151013
class TestFetch(SelfCleaningTestCase):
10161014
def setUp(self):
1017-
super(TestFetch, self).setUp()
1015+
super().setUp()
10181016

10191017
# All of these tests will involve fetch.txt usage with an existing bag
10201018
# so we'll simply create one:

utils/bench.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
ftp.retrlines("NLST", files.append)
2727

2828
for file in files:
29-
print(("fetching %s" % file))
29+
print("fetching %s" % file)
3030
fh = open(os.path.join("bench-data", file), "wb")
3131
ftp.retrbinary("RETR %s" % file, fh.write)
3232
fh.close()
@@ -49,7 +49,7 @@
4949
for p in range(1, 9):
5050
t = timeit.Timer(statement % p)
5151
print(
52-
("create w/ %s processes: %.2f seconds " % (p, (10 * t.timeit(number=10) / 10)))
52+
"create w/ %s processes: %.2f seconds " % (p, (10 * t.timeit(number=10) / 10))
5353
)
5454

5555

@@ -71,10 +71,10 @@
7171
for p in range(1, 9):
7272
t = timeit.Timer(statement % p)
7373
print(
74-
(
74+
7575
"validate w/ %s processes: %.2f seconds "
7676
% (p, (10 * t.timeit(number=10) / 10))
77-
)
77+
7878
)
7979

8080
shutil.rmtree("bench-data-bag")

utils/locales.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python
2-
# encoding: utf-8
32

43
import sys
54
import subprocess

0 commit comments

Comments
 (0)