Coverage for cogapp/whiteutils.py: 88.16%

44 statements  

« prev     ^ index     » next       coverage.py v7.6.9, created at 2024-12-06 06:21 -0500

1"""Indentation utilities for Cog.""" 

2 

3import re 

4 

5 

6def white_prefix(strings): 

7 """Find the whitespace prefix common to non-blank lines in `strings`.""" 

8 # Remove all blank lines from the list 

9 strings = [s for s in strings if s.strip() != ""] 

10 

11 if not strings: 

12 return "" 

13 

14 # Find initial whitespace chunk in the first line. 

15 # This is the best prefix we can hope for. 

16 pat = r"\s*" 

17 if isinstance(strings[0], bytes): 17 ↛ 18line 17 didn't jump to line 18 because the condition on line 17 was never true

18 pat = pat.encode("utf-8") 

19 prefix = re.match(pat, strings[0]).group(0) 

20 

21 # Loop over the other strings, keeping only as much of 

22 # the prefix as matches each string. 

23 for s in strings: 

24 for i in range(len(prefix)): 

25 if prefix[i] != s[i]: 25 ↛ 26line 25 didn't jump to line 26 because the condition on line 25 was never true

26 prefix = prefix[:i] 

27 break 

28 return prefix 

29 

30 

31def reindent_block(lines, new_indent=""): 

32 """Re-indent a block of text. 

33 

34 Take a block of text as a string or list of lines. 

35 Remove any common whitespace indentation. 

36 Re-indent using `newIndent`, and return it as a single string. 

37 

38 """ 

39 sep, nothing = "\n", "" 

40 if isinstance(lines, bytes): 40 ↛ 41line 40 didn't jump to line 41 because the condition on line 40 was never true

41 sep, nothing = b"\n", b"" 

42 if isinstance(lines, (bytes, str)): 

43 lines = lines.split(sep) 

44 old_indent = white_prefix(lines) 

45 out_lines = [] 

46 for line in lines: 

47 if old_indent: 

48 line = line.replace(old_indent, nothing, 1) 

49 if line and new_indent: 

50 line = new_indent + line 

51 out_lines.append(line) 

52 return sep.join(out_lines) 

53 

54 

55def common_prefix(strings): 

56 """Find the longest string that is a prefix of all the strings.""" 

57 if not strings: 57 ↛ 58line 57 didn't jump to line 58 because the condition on line 57 was never true

58 return "" 

59 prefix = strings[0] 

60 for s in strings: 

61 if len(s) < len(prefix): 

62 prefix = prefix[: len(s)] 

63 if not prefix: 

64 return "" 

65 for i in range(len(prefix)): 

66 if prefix[i] != s[i]: 

67 prefix = prefix[:i] 

68 break 

69 return prefix