Debian Codegraph @

_transport_rs/src/urlutils.rs

raw
1 use pyo3::exceptions::PyTypeError;
2 use pyo3::exceptions::PyValueError;
3 use pyo3::import_exception;
4 use pyo3::prelude::*;
5 use pyo3::types::PyTuple;
6 use std::collections::HashMap;
7 use std::path::PathBuf;
8
9 import_exception!(dromedary.urlutils, InvalidURLJoin);
10 import_exception!(dromedary.urlutils, InvalidURL);
11 import_exception!(dromedary.errors, PathNotChild);
12
13 #[pyfunction]
14 fn is_url(url: &str) -> bool {
15 dromedary::urlutils::is_url(url)
16 }
17
18 /// On Windows, `file://` URLs without a drive letter are invalid. The
19 /// `split`/`basename`/`dirname`/`strip_trailing_slash` helpers historically
20 /// raised `InvalidURL` for such URLs (matching breezy's behaviour). The
21 /// underlying Rust `split` is platform-agnostic and just splits at the last
22 /// path separator, so do the validation here in the Python boundary.
23 #[cfg(target_os = "windows")]
24 fn validate_win32_file_url(url: &str) -> PyResult<()> {
25 if !is_win32_drive_letter_url(url)
26 && url.starts_with("file:///")
27 && url.len() > "file:///".len()
28 {
29 return Err(InvalidURL::new_err((
30 "Invalid Win32 local URL".to_string(),
31 url.to_string(),
32 )));
33 }
34 Ok(())
35 }
36
37 #[cfg(not(target_os = "windows"))]
38 #[inline]
39 fn validate_win32_file_url(_url: &str) -> PyResult<()> {
40 Ok(())
41 }
42
43 /// Whether `url` is a `file:///<letter>:|...` or `file:///<letter>|...` URL.
44 #[cfg(target_os = "windows")]
45 fn is_win32_drive_letter_url(url: &str) -> bool {
46 let Some(rest) = url.strip_prefix("file:///") else {
47 return false;
48 };
49 let mut chars = rest.chars();
50 matches!(chars.next(), Some(c) if c.is_ascii_alphabetic())
51 && matches!(chars.next(), Some(':') | Some('|'))
52 }
53
54 #[pyfunction]
55 #[pyo3(signature = (url, exclude_trailing_slash = true))]
56 fn split(url: &str, exclude_trailing_slash: Option<bool>) -> PyResult<(String, String)> {
57 validate_win32_file_url(url)?;
58 Ok(split_impl(url, exclude_trailing_slash.unwrap_or(true)))
59 }
60
61 #[cfg(not(target_os = "windows"))]
62 #[inline]
63 fn split_impl(url: &str, exclude_trailing_slash: bool) -> (String, String) {
64 dromedary::urlutils::split(url, exclude_trailing_slash)
65 }
66
67 /// On Windows, drive-letter local URLs split as `file:///C:` + `/path`. The
68 /// generic split treats the URL as `file://` + `/C:/path` and produces the
69 /// wrong head/tail; mirror breezy's `_win32_split` here.
70 #[cfg(target_os = "windows")]
71 fn split_impl(url: &str, exclude_trailing_slash: bool) -> (String, String) {
72 if is_win32_drive_letter_url(url) {
73 let url_base = "file://";
74 // SAFETY: validated above that the URL has shape `file:///<L><:|>...`
75 let path = &url["file://".len()..]; // starts with `/<letter><:|>...`
76 if let Ok((url_base, path)) =
77 dromedary::urlutils::win32::extract_drive_letter(url_base, path)
78 {
79 // `path` is now the part after the drive (e.g. "/foo/bar").
80 return split_after_drive(&url_base, &path, exclude_trailing_slash);
81 }
82 }
83 dromedary::urlutils::split(url, exclude_trailing_slash)
84 }
85
86 #[cfg(target_os = "windows")]
87 fn split_after_drive(url_base: &str, path: &str, exclude_trailing_slash: bool) -> (String, String) {
88 let mut p = path;
89 if exclude_trailing_slash && p.len() > 1 && p.ends_with('/') {
90 p = &p[..p.len() - 1];
91 }
92 match p.rsplit_once('/') {
93 None => (url_base.to_string(), p.to_string()),
94 Some((head, tail)) => {
95 let head = if head.is_empty() { "/" } else { head };
96 (url_base.to_string() + head, tail.to_string())
97 }
98 }
99 }
100
101 #[pyfunction]
102 fn _find_scheme_and_separator(url: &str) -> (Option<usize>, Option<usize>) {
103 dromedary::urlutils::find_scheme_and_separator(url)
104 }
105
106 #[pyfunction]
107 fn strip_trailing_slash(url: &str) -> PyResult<String> {
108 validate_win32_file_url(url)?;
109 #[cfg(target_os = "windows")]
110 {
111 if url.ends_with('/') && is_win32_drive_letter_url(url) {
112 // Drive-letter local URL: preserve `file:///C:/` as-is and
113 // strip exactly one trailing slash from anything longer.
114 return Ok(dromedary::urlutils::win32::strip_local_trailing_slash(url));
115 }
116 }
117 Ok(dromedary::urlutils::strip_trailing_slash(url).to_string())
118 }
119
120 #[pyfunction]
121 #[pyo3(signature = (url, exclude_trailing_slash = true))]
122 fn dirname(url: &str, exclude_trailing_slash: Option<bool>) -> PyResult<String> {
123 validate_win32_file_url(url)?;
124 Ok(split_impl(url, exclude_trailing_slash.unwrap_or(true)).0)
125 }
126
127 #[pyfunction]
128 #[pyo3(signature = (url, exclude_trailing_slash = true))]
129 fn basename(url: &str, exclude_trailing_slash: Option<bool>) -> PyResult<String> {
130 validate_win32_file_url(url)?;
131 Ok(split_impl(url, exclude_trailing_slash.unwrap_or(true)).1)
132 }
133
134 fn map_urlutils_error_to_pyerr(e: dromedary::urlutils::Error) -> PyErr {
135 match e {
136 dromedary::urlutils::Error::AboveRoot(base, path) => {
137 InvalidURLJoin::new_err(("Above root", base, path))
138 }
139 dromedary::urlutils::Error::SubsegmentMissesEquals(segment) => {
140 InvalidURL::new_err(("Subsegment misses equals", segment))
141 }
142 dromedary::urlutils::Error::UnsafeCharacters(c) => {
143 InvalidURL::new_err(("Unsafe characters", c))
144 }
145 dromedary::urlutils::Error::IoError(err) => err.into(),
146 dromedary::urlutils::Error::SegmentParameterKeyContainsEquals(url, segment) => {
147 InvalidURLJoin::new_err(("Segment parameter contains equals (=)", url, segment))
148 }
149 dromedary::urlutils::Error::SegmentParameterContainsComma(url, segments) => {
150 InvalidURLJoin::new_err(("Segment parameter contains comma (,)", url, segments))
151 }
152 dromedary::urlutils::Error::NotLocalUrl(url) => {
153 InvalidURL::new_err(("Not a local url", url))
154 }
155 dromedary::urlutils::Error::UrlNotAscii(url) => InvalidURL::new_err(("URL not ascii", url)),
156 dromedary::urlutils::Error::InvalidUNCUrl(url) => {
157 InvalidURL::new_err(("Invalid UNC URL", url))
158 }
159 dromedary::urlutils::Error::InvalidWin32LocalUrl(url) => {
160 InvalidURL::new_err(("Invalid Win32 local URL", url))
161 }
162 dromedary::urlutils::Error::InvalidWin32Path(path) => {
163 InvalidURL::new_err(("Invalid Win32 path", path))
164 }
165 dromedary::urlutils::Error::PathNotChild(path, start) => {
166 PathNotChild::new_err((path, start))
167 }
168 dromedary::urlutils::Error::UrlTooShort(url) => {
169 PyValueError::new_err(("URL too short", url))
170 }
171 dromedary::urlutils::Error::InvalidUrlPort(url, port_str) => {
172 InvalidURL::new_err((format!("invalid port number {port_str} in url:\n{url}"),))
173 }
174 }
175 }
176
177 #[pyfunction(signature = (url, *args))]
178 fn joinpath(url: &str, args: &Bound<PyTuple>) -> PyResult<String> {
179 let mut path = Vec::new();
180 for arg in args.iter() {
181 if let Ok(arg) = arg.extract::<String>() {
182 path.push(arg);
183 } else {
184 return Err(PyTypeError::new_err(
185 "path must be a string or a list of strings",
186 ));
187 }
188 }
189 let path_ref = path.iter().map(|s| s.as_str()).collect::<Vec<&str>>();
190 dromedary::urlutils::joinpath(url, path_ref.as_slice()).map_err(map_urlutils_error_to_pyerr)
191 }
192
193 #[pyfunction(signature = (url, *args))]
194 fn join(url: &str, args: &Bound<PyTuple>) -> PyResult<String> {
195 let mut path = Vec::new();
196 for arg in args.iter() {
197 if let Ok(arg) = arg.extract::<String>() {
198 path.push(arg);
199 } else {
200 return Err(PyTypeError::new_err(
201 "path must be a string or a list of strings",
202 ));
203 }
204 }
205 let path_ref = path.iter().map(|s| s.as_str()).collect::<Vec<&str>>();
206 dromedary::urlutils::join(url, path_ref.as_slice()).map_err(map_urlutils_error_to_pyerr)
207 }
208
209 #[pyfunction]
210 fn split_segment_parameters(url: &str) -> PyResult<(&str, HashMap<&str, &str>)> {
211 dromedary::urlutils::split_segment_parameters(url).map_err(map_urlutils_error_to_pyerr)
212 }
213
214 #[pyfunction]
215 fn split_segment_parameters_raw(url: &str) -> (&str, Vec<&str>) {
216 dromedary::urlutils::split_segment_parameters_raw(url)
217 }
218
219 #[pyfunction]
220 fn strip_segment_parameters(url: &str) -> &str {
221 dromedary::urlutils::strip_segment_parameters(url)
222 }
223
224 #[pyfunction]
225 fn relative_url(base: &str, url: &str) -> String {
226 dromedary::urlutils::relative_url(base, url)
227 }
228
229 #[pyfunction]
230 fn combine_paths(base_path: &str, relpath: &str) -> String {
231 dromedary::urlutils::combine_paths(base_path, relpath)
232 }
233
234 #[pyfunction]
235 #[pyo3(signature = (text, safe = None))]
236 fn escape(py: Python, text: Py<PyAny>, safe: Option<&str>) -> PyResult<String> {
237 if let Ok(text) = text.extract::<String>(py) {
238 Ok(dromedary::urlutils::escape(text.as_bytes(), safe))
239 } else if let Ok(text) = text.extract::<Vec<u8>>(py) {
240 Ok(dromedary::urlutils::escape(text.as_slice(), safe))
241 } else {
242 Err(PyTypeError::new_err("text must be a string or bytes"))
243 }
244 }
245
246 #[pyfunction]
247 fn normalize_url(url: &str) -> PyResult<String> {
248 dromedary::urlutils::normalize_url(url).map_err(map_urlutils_error_to_pyerr)
249 }
250
251 #[pyfunction]
252 fn local_path_to_url(path: PathBuf) -> PyResult<String> {
253 dromedary::urlutils::local_path_to_url(path.as_path()).map_err(|e| e.into())
254 }
255
256 #[pyfunction(name = "local_path_to_url")]
257 fn win32_local_path_to_url(path: PathBuf) -> PyResult<String> {
258 dromedary::urlutils::win32::local_path_to_url(path).map_err(|e| e.into())
259 }
260
261 #[pyfunction(name = "local_path_to_url")]
262 fn posix_local_path_to_url(path: &str) -> PyResult<String> {
263 dromedary::urlutils::posix::local_path_to_url(path).map_err(|e| e.into())
264 }
265
266 #[pyfunction(signature = (url, *args))]
267 fn join_segment_parameters_raw(url: &str, args: &Bound<PyTuple>) -> PyResult<String> {
268 let mut path = Vec::new();
269 for arg in args.iter() {
270 if let Ok(arg) = arg.extract::<String>() {
271 path.push(arg);
272 } else {
273 return Err(PyTypeError::new_err(
274 "path must be a string or a list of strings",
275 ));
276 }
277 }
278 let path_ref = path.iter().map(|s| s.as_str()).collect::<Vec<&str>>();
279 dromedary::urlutils::join_segment_parameters_raw(url, path_ref.as_slice())
280 .map_err(map_urlutils_error_to_pyerr)
281 }
282
283 #[pyfunction]
284 fn join_segment_parameters(url: &str, parameters: HashMap<String, String>) -> PyResult<String> {
285 let parameters = parameters
286 .iter()
287 .map(|(k, v)| (k.as_str(), v.as_str()))
288 .collect();
289 dromedary::urlutils::join_segment_parameters(url, &parameters)
290 .map_err(map_urlutils_error_to_pyerr)
291 }
292
293 #[pyfunction]
294 fn local_path_from_url(url: &str) -> PyResult<String> {
295 let path =
296 dromedary::urlutils::local_path_from_url(url).map_err(map_urlutils_error_to_pyerr)?;
297
298 match path.to_str() {
299 Some(path) => Ok(path.to_string()),
300 None => Err(PyValueError::new_err("Path is not valid UTF-8")),
301 }
302 }
303
304 #[pyfunction(name = "local_path_from_url")]
305 fn win32_local_path_from_url(url: &str) -> PyResult<String> {
306 let path = dromedary::urlutils::win32::local_path_from_url(url)
307 .map_err(map_urlutils_error_to_pyerr)?;
308
309 match path.to_str() {
310 Some(path) => Ok(path.to_string()),
311 None => Err(PyValueError::new_err("Path is not valid UTF-8")),
312 }
313 }
314
315 /// On win32 the drive letter needs to be added to the url base.
316 #[pyfunction(name = "extract_drive_letter")]
317 fn win32_extract_drive_letter(url_base: &str, path: &str) -> PyResult<(String, String)> {
318 dromedary::urlutils::win32::extract_drive_letter(url_base, path)
319 .map_err(map_urlutils_error_to_pyerr)
320 }
321
322 #[pyfunction(name = "strip_local_trailing_slash")]
323 fn win32_strip_local_trailing_slash(url: &str) -> String {
324 dromedary::urlutils::win32::strip_local_trailing_slash(url)
325 }
326
327 #[pyfunction(name = "local_path_from_url")]
328 fn posix_local_path_from_url(url: &str) -> PyResult<String> {
329 let path = dromedary::urlutils::posix::local_path_from_url(url)
330 .map_err(map_urlutils_error_to_pyerr)?;
331
332 match path.to_str() {
333 Some(path) => Ok(path.to_string()),
334 None => Err(PyValueError::new_err("Path is not valid UTF-8")),
335 }
336 }
337
338 #[pyfunction]
339 fn unescape(text: &str) -> PyResult<String> {
340 dromedary::urlutils::unescape(text).map_err(map_urlutils_error_to_pyerr)
341 }
342
343 #[pyfunction]
344 fn derive_to_location(base: &str) -> String {
345 dromedary::urlutils::derive_to_location(base)
346 }
347
348 #[pyfunction]
349 fn file_relpath(base: &str, path: &str) -> PyResult<String> {
350 dromedary::urlutils::file_relpath(base, path).map_err(map_urlutils_error_to_pyerr)
351 }
352
353 /// Permissive percent-decode mirroring Python's urllib.parse.unquote:
354 /// non-ASCII or undecodable input is returned unchanged.
355 fn unquote_lossy(s: &str) -> String {
356 dromedary::urlutils::unescape(s).unwrap_or_else(|_| s.to_string())
357 }
358
359 /// Rust port of dromedary.urlutils.URL — a parsed URL with both
360 /// quoted and unquoted forms of each component. Attributes are mutable
361 /// to match the historical Python behaviour.
362 #[pyclass(name = "URL", subclass, skip_from_py_object)]
363 #[derive(Clone)]
364 pub(crate) struct UrlObject {
365 #[pyo3(get, set)]
366 scheme: String,
367 #[pyo3(get, set)]
368 quoted_user: Option<String>,
369 #[pyo3(get, set)]
370 user: Option<String>,
371 #[pyo3(get, set)]
372 quoted_password: Option<String>,
373 #[pyo3(get, set)]
374 password: Option<String>,
375 #[pyo3(get, set)]
376 quoted_host: String,
377 #[pyo3(get, set)]
378 host: String,
379 #[pyo3(get, set)]
380 port: Option<u16>,
381 #[pyo3(get, set)]
382 quoted_path: String,
383 #[pyo3(get, set)]
384 path: String,
385 }
386
387 #[pymethods]
388 impl UrlObject {
389 #[new]
390 fn new(
391 scheme: String,
392 quoted_user: Option<String>,
393 quoted_password: Option<String>,
394 quoted_host: String,
395 port: Option<u16>,
396 quoted_path: String,
397 ) -> Self {
398 let host = unquote_lossy(&quoted_host);
399 let user = quoted_user.as_deref().map(unquote_lossy);
400 let password = quoted_password.as_deref().map(unquote_lossy);
401 let normalized_path = dromedary::urlutils::normalize_quoted_path(&quoted_path);
402 let path = unquote_lossy(&normalized_path);
403 UrlObject {
404 scheme,
405 quoted_user,
406 user,
407 quoted_password,
408 password,
409 quoted_host,
410 host,
411 port,
412 quoted_path: normalized_path,
413 path,
414 }
415 }
416
417 #[classmethod]
418 fn from_string(_cls: &Bound<pyo3::types::PyType>, url: &str) -> PyResult<Self> {
419 let parsed = dromedary::urlutils::parse_url(url).map_err(map_urlutils_error_to_pyerr)?;
420 Ok(UrlObject::new(
421 parsed.scheme,
422 parsed.quoted_user,
423 parsed.quoted_password,
424 parsed.quoted_host,
425 parsed.port,
426 parsed.quoted_path,
427 ))
428 }
429
430 fn __eq__(&self, other: &Bound<PyAny>) -> bool {
431 // Match Python: compare scheme/host/user/password/path. Port is
432 // intentionally not compared (preserved from the original impl).
433 match other.extract::<PyRef<UrlObject>>() {
434 Ok(o) => {
435 self.scheme == o.scheme
436 && self.host == o.host
437 && self.user == o.user
438 && self.password == o.password
439 && self.path == o.path
440 }
441 Err(_) => false,
442 }
443 }
444
445 fn __repr__(&self) -> String {
446 // <URL('http', None, None, '1:2:3::40', 80, '/one')>
447 fn opt_repr<T: std::fmt::Display>(v: &Option<T>) -> String {
448 match v {
449 Some(s) => format!("'{}'", s),
450 None => "None".to_string(),
451 }
452 }
453 let port_repr = match self.port {
454 Some(p) => p.to_string(),
455 None => "None".to_string(),
456 };
457 format!(
458 "<URL('{}', {}, {}, '{}', {}, '{}')>",
459 self.scheme,
460 opt_repr(&self.quoted_user),
461 opt_repr(&self.quoted_password),
462 self.quoted_host,
463 port_repr,
464 self.quoted_path,
465 )
466 }
467
468 fn __str__(&self) -> String {
469 // Bracket the host if it looks like an IPv6 literal.
470 let mut netloc = if self.quoted_host.contains(':') {
471 format!("[{}]", self.quoted_host)
472 } else {
473 self.quoted_host.clone()
474 };
475 if let Some(user) = &self.quoted_user {
476 // Password is intentionally omitted to avoid accidental exposure.
477 netloc = format!("{}@{}", user, netloc);
478 }
479 if let Some(port) = self.port {
480 netloc = format!("{}:{}", netloc, port);
481 }
482 let sep = if self.quoted_path.starts_with('/') || self.quoted_path.is_empty() {
483 ""
484 } else {
485 "/"
486 };
487 format!("{}://{}{}{}", self.scheme, netloc, sep, self.quoted_path)
488 }
489
490 #[pyo3(signature = (offset = None))]
491 fn clone(&self, offset: Option<&str>) -> PyResult<Self> {
492 let path = match offset {
493 Some(off) => {
494 // offset must already be url-encoded. Non-ASCII input means
495 // the caller forgot to escape — surface that as InvalidURL
496 // rather than silently passing the raw bytes through.
497 let relative = dromedary::urlutils::unescape(off)
498 .map_err(|_| InvalidURL::new_err((off.to_string(),)))?;
499 let combined = dromedary::urlutils::combine_paths(&self.path, &relative);
500 dromedary::urlutils::escape(combined.as_bytes(), Some("/~"))
501 }
502 None => self.quoted_path.clone(),
503 };
504 Ok(UrlObject::new(
505 self.scheme.clone(),
506 self.quoted_user.clone(),
507 self.quoted_password.clone(),
508 self.quoted_host.clone(),
509 self.port,
510 path,
511 ))
512 }
513 }
514
515 /// (scheme, user, password, host, port, path) — all unquoted.
516 type ParsedUrlTuple = (
517 String,
518 Option<String>,
519 Option<String>,
520 String,
521 Option<u16>,
522 String,
523 );
524
525 #[pyfunction]
526 fn parse_url(url: &str) -> PyResult<ParsedUrlTuple> {
527 let p = dromedary::urlutils::parse_url(url).map_err(map_urlutils_error_to_pyerr)?;
528 Ok((
529 p.scheme,
530 p.quoted_user.as_deref().map(unquote_lossy),
531 p.quoted_password.as_deref().map(unquote_lossy),
532 unquote_lossy(&p.quoted_host),
533 p.port,
534 unquote_lossy(&p.quoted_path),
535 ))
536 }
537
538 #[pymodule]
539 pub fn _urlutils_rs(py: Python, m: &Bound<PyModule>) -> PyResult<()> {
540 m.add_function(wrap_pyfunction!(is_url, m)?)?;
541 m.add_function(wrap_pyfunction!(split, m)?)?;
542 m.add_function(wrap_pyfunction!(_find_scheme_and_separator, m)?)?;
543 m.add_function(wrap_pyfunction!(strip_trailing_slash, m)?)?;
544 m.add_function(wrap_pyfunction!(dirname, m)?)?;
545 m.add_function(wrap_pyfunction!(basename, m)?)?;
546 m.add_function(wrap_pyfunction!(joinpath, m)?)?;
547 m.add_function(wrap_pyfunction!(join, m)?)?;
548 m.add_function(wrap_pyfunction!(split_segment_parameters, m)?)?;
549 m.add_function(wrap_pyfunction!(split_segment_parameters_raw, m)?)?;
550 m.add_function(wrap_pyfunction!(strip_segment_parameters, m)?)?;
551 m.add_function(wrap_pyfunction!(join_segment_parameters_raw, m)?)?;
552 m.add_function(wrap_pyfunction!(join_segment_parameters, m)?)?;
553 m.add_function(wrap_pyfunction!(relative_url, m)?)?;
554 m.add_function(wrap_pyfunction!(combine_paths, m)?)?;
555 m.add_function(wrap_pyfunction!(escape, m)?)?;
556 m.add_function(wrap_pyfunction!(normalize_url, m)?)?;
557 m.add_function(wrap_pyfunction!(local_path_to_url, m)?)?;
558 m.add_function(wrap_pyfunction!(local_path_from_url, m)?)?;
559 m.add_function(wrap_pyfunction!(unescape, m)?)?;
560 m.add_function(wrap_pyfunction!(derive_to_location, m)?)?;
561 m.add_function(wrap_pyfunction!(file_relpath, m)?)?;
562 m.add_function(wrap_pyfunction!(parse_url, m)?)?;
563 m.add_class::<UrlObject>()?;
564 let win32m = PyModule::new(py, "win32")?;
565 win32m.add_function(wrap_pyfunction!(win32_local_path_to_url, &win32m)?)?;
566 win32m.add_function(wrap_pyfunction!(win32_local_path_from_url, &win32m)?)?;
567 win32m.add_function(wrap_pyfunction!(win32_extract_drive_letter, &win32m)?)?;
568 win32m.add_function(wrap_pyfunction!(win32_strip_local_trailing_slash, &win32m)?)?;
569 m.add_submodule(&win32m)?;
570 let posixm = PyModule::new(py, "posix")?;
571 posixm.add_function(wrap_pyfunction!(posix_local_path_to_url, &posixm)?)?;
572 posixm.add_function(wrap_pyfunction!(posix_local_path_from_url, &posixm)?)?;
573 m.add_submodule(&posixm)?;
574
575 // PyO3 submodule hack for proper import support
576 let sys = py.import("sys")?;
577 let modules = sys.getattr("modules")?;
578 let module_name = m.name()?;
579
580 // Register submodules in sys.modules for dotted import support
581 modules.set_item(format!("{}.win32", module_name), &win32m)?;
582 modules.set_item(format!("{}.posix", module_name), &posixm)?;
583
584 Ok(())
585 }