Skip to content

Commit b883526

Browse files
authored
Bugfix to uri_file_path. (#80)
* Allow document fragments in paths with correct quoting * Add test for file_uri and uri_file_path.
1 parent 0c7cc02 commit b883526

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

schema_salad/ref_resolver.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,19 +36,21 @@
3636
DocumentOrStrType = TypeVar(
3737
'DocumentOrStrType', CommentedSeq, CommentedMap, unicode)
3838

39-
def file_uri(path): # type: (unicode) -> unicode
39+
def file_uri(path): # type: (str) -> str
4040
if path.startswith("file://"):
4141
return path
42-
urlpath = urllib.pathname2url(str(path))
42+
pathsp = path.split("#", 2)
43+
frag = "#" + urllib.quote(str(pathsp[1])) if len(pathsp) == 2 else ""
44+
urlpath = urllib.pathname2url(str(pathsp[0]))
4345
if urlpath.startswith("//"):
44-
return "file:%s" % urlpath
46+
return "file:%s%s" % (urlpath, frag)
4547
else:
46-
return "file://%s" % urlpath
48+
return "file://%s%s" % (urlpath, frag)
4749

48-
def uri_file_path(url): # type: (unicode) -> unicode
50+
def uri_file_path(url): # type: (str) -> str
4951
split = urlparse.urlsplit(url)
5052
if split.scheme == "file":
51-
urllib.url2pathname(str(split.path))
53+
return urllib.url2pathname(str(split.path)) + ("#" + urllib.unquote(str(split.fragment)) if split.fragment else "")
5254
else:
5355
raise ValueError("Not a file URI")
5456

schema_salad/tests/test_examples.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,14 @@ def test_fragment(self):
362362
b, _ = ldr.resolve_ref(get_data("tests/frag.yml#foo2"))
363363
self.assertEquals({"id": b["id"], "bar":"b2"}, b)
364364

365+
def test_file_uri(self):
366+
# Note: this test probably won't pass on Windows. Someone with a
367+
# windows box should add an alternate test.
368+
self.assertEquals("file:///foo/bar%20baz/quux", schema_salad.ref_resolver.file_uri("/foo/bar baz/quux"))
369+
self.assertEquals("/foo/bar baz/quux", schema_salad.ref_resolver.uri_file_path("file:///foo/bar%20baz/quux"))
370+
self.assertEquals("file:///foo/bar%20baz/quux#zing%20zong", schema_salad.ref_resolver.file_uri("/foo/bar baz/quux#zing zong"))
371+
self.assertEquals("/foo/bar baz/quux#zing zong", schema_salad.ref_resolver.uri_file_path("file:///foo/bar%20baz/quux#zing%20zong"))
372+
365373

366374
if __name__ == '__main__':
367375
unittest.main()

0 commit comments

Comments
 (0)