Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/yarl/_path.py: 95%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

21 statements  

1"""Utilities for working with paths.""" 

2 

3from collections.abc import Sequence 

4from contextlib import suppress 

5 

6 

7def normalize_path_segments(segments: Sequence[str]) -> list[str]: 

8 """Drop '.' and '..' from a sequence of str segments""" 

9 

10 resolved_path: list[str] = [] 

11 

12 for seg in segments: 

13 if seg == "..": 

14 # ignore any .. segments that would otherwise cause an 

15 # IndexError when popped from resolved_path if 

16 # resolving for rfc3986 

17 with suppress(IndexError): 

18 resolved_path.pop() 

19 elif seg != ".": 

20 resolved_path.append(seg) 

21 

22 if segments and segments[-1] in (".", ".."): 

23 # do some post-processing here. 

24 # if the last segment was a relative dir, 

25 # then we need to append the trailing '/' 

26 resolved_path.append("") 

27 

28 return resolved_path 

29 

30 

31def normalize_path(path: str) -> str: 

32 # Drop '.' and '..' from str path 

33 prefix = "" 

34 if path and path[0] == "/": 

35 # preserve the "/" root element of absolute paths, copying it to the 

36 # normalised output as per sections 5.2.4 and 6.2.2.3 of rfc3986. 

37 prefix = "/" 

38 path = path[1:] 

39 

40 segments = path.split("/") 

41 return prefix + "/".join(normalize_path_segments(segments))