Skip to content

Commit db0367a

Browse files
committed
Escape % in manifest filenames as required by RFC
1 parent 4bd2713 commit db0367a

2 files changed

Lines changed: 30 additions & 6 deletions

File tree

‎src/bagit/__init__.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1423,18 +1423,19 @@ def generate_manifest_lines(filename, algorithms=DEFAULT_CHECKSUMS):
14231423
for hasher in hashers.values():
14241424
hasher.update(block)
14251425

1426-
decoded_filename = _decode_filename(filename)
1427-
14281426
# We'll generate a list of results in roughly manifest format but prefixed with the algorithm:
14291427
results = [
1430-
(alg, hasher.hexdigest(), decoded_filename, total_bytes)
1428+
(alg, hasher.hexdigest(), filename, total_bytes)
14311429
for alg, hasher in hashers.items()
14321430
]
14331431

14341432
return results
14351433

14361434

14371435
def _encode_filename(s):
1436+
# needs to be first to not escape the % added by escaping \n and \r
1437+
s = s.replace("%", "%25")
1438+
14381439
s = s.replace("\r", "%0D")
14391440
s = s.replace("\n", "%0A")
14401441
return s
@@ -1443,6 +1444,8 @@ def _encode_filename(s):
14431444
def _decode_filename(s):
14441445
s = re.sub(r"%0D", "\r", s, flags=re.IGNORECASE)
14451446
s = re.sub(r"%0A", "\n", s, flags=re.IGNORECASE)
1447+
# needs to be last to not potentially introduce matches for \n / \r
1448+
s = s.replace("%25", "%")
14461449
return s
14471450

14481451

‎test.py‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -827,10 +827,31 @@ def test_missing_tagmanifest_valid(self):
827827
os.remove(j(self.tmpdir, "tagmanifest-md5.txt"))
828828
self.assertTrue(bag.is_valid())
829829

830-
def test_carriage_return_manifest(self):
831-
with open(j(self.tmpdir, "newline\r"), "w") as whatever:
832-
whatever.write("ugh")
830+
def test_special_characters_in_filename(self):
831+
names = [
832+
"carriage-return\r",
833+
"newline\n",
834+
"percent%",
835+
"escapes%0A%0D%25", # has all the escape sequences already in the name
836+
]
837+
838+
for name in names:
839+
with open(j(self.tmpdir, name), "w") as f:
840+
f.write("ugh")
841+
833842
bag = bagit.make_bag(self.tmpdir)
843+
bag_names = slurp_text_file(next(bag.manifest_files()))
844+
845+
escaped_names = [
846+
"carriage-return%0D",
847+
"newline%0A",
848+
"percent%25",
849+
"escapes%250A%250D%2525",
850+
]
851+
852+
for escaped_name in escaped_names:
853+
self.assertIn(f"data/{escaped_name}", bag_names)
854+
834855
self.assertTrue(bag.is_valid())
835856

836857
def test_payload_permissions(self):

0 commit comments

Comments
 (0)