Skip to content

Commit

Permalink
pythonGH-126601: pathname2url(): handle NTFS alternate data streams
Browse files Browse the repository at this point in the history
Adjust `pathname2url()` to encode embedded colon characters in Windows
paths, rather than bailing out with an `OSError`.
  • Loading branch information
barneygale committed Nov 12, 2024
1 parent bf224bd commit 0ed23a5
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 12 deletions.
15 changes: 5 additions & 10 deletions Lib/nturl2path.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def pathname2url(p):
# C:\foo\bar\spam.foo
# becomes
# ///C:/foo/bar/spam.foo
import ntpath
import urllib.parse
# First, clean up some special forms. We are going to sacrifice
# the additional information anyway
Expand All @@ -49,16 +50,10 @@ def pathname2url(p):
p = p[4:]
if p[:4].upper() == 'UNC/':
p = '//' + p[4:]
elif p[1:2] != ':':
raise OSError('Bad path: ' + p)
if not ':' in p:
drive, tail = ntpath.splitdrive(p)
if drive[1:2] != ':':
# No DOS drive specified, just quote the pathname
return urllib.parse.quote(p)
comp = p.split(':', maxsplit=2)
if len(comp) != 2 or len(comp[0]) > 1:
error = 'Bad path: ' + p
raise OSError(error)

drive = urllib.parse.quote(comp[0].upper())
tail = urllib.parse.quote(comp[1])
drive = urllib.parse.quote(drive[0].upper())
tail = urllib.parse.quote(tail)
return '///' + drive + ':' + tail
5 changes: 3 additions & 2 deletions Lib/test/test_urllib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1533,8 +1533,9 @@ def test_pathname2url_win(self):
self.assertEqual(fn('C:\\a\\b%#c'), '///C:/a/b%25%23c')
self.assertEqual(fn('C:\\a\\b\xe9'), '///C:/a/b%C3%A9')
self.assertEqual(fn('C:\\foo\\bar\\spam.foo'), "///C:/foo/bar/spam.foo")
# Long drive letter
self.assertRaises(IOError, fn, "XX:\\")
# NTFS alternate data streams
self.assertEqual(fn('C:\\foo:bar'), '///C:/foo%3Abar')
self.assertEqual(fn('foo:bar'), 'foo%3Abar')
# No drive letter
self.assertEqual(fn("\\folder\\test\\"), '/folder/test/')
self.assertEqual(fn("\\\\folder\\test\\"), '//folder/test/')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix issue where :func:`urllib.request.pathname2url` raised :exc:`OSError`
when given a Windows path containing a colon character not following a
drive letter, such as before an NTFS alternate data stream.

0 comments on commit 0ed23a5

Please sign in to comment.