Coverage for cogapp/whiteutils.py: 88.31%
43 statements
« prev ^ index » next coverage.py v7.5.0a1.dev1, created at 2024-04-15 15:50 -0400
« prev ^ index » next coverage.py v7.5.0a1.dev1, created at 2024-04-15 15:50 -0400
1""" Indentation utilities for Cog.
2"""
4import re
7def whitePrefix(strings):
8 """ Determine the whitespace prefix common to all non-blank lines
9 in the argument list.
10 """
11 # Remove all blank lines from the list
12 strings = [s for s in strings if s.strip() != '']
14 if not strings: return ''
16 # Find initial whitespace chunk in the first line.
17 # This is the best prefix we can hope for.
18 pat = r'\s*'
19 if isinstance(strings[0], bytes): 19 ↛ 20line 19 didn't jump to line 20, because the condition on line 19 was never true
20 pat = pat.encode("utf-8")
21 prefix = re.match(pat, strings[0]).group(0)
23 # Loop over the other strings, keeping only as much of
24 # the prefix as matches each string.
25 for s in strings:
26 for i in range(len(prefix)):
27 if prefix[i] != s[i]: 27 ↛ 28line 27 didn't jump to line 28, because the condition on line 27 was never true
28 prefix = prefix[:i]
29 break
30 return prefix
32def reindentBlock(lines, newIndent=''):
33 """ Take a block of text as a string or list of lines.
34 Remove any common whitespace indentation.
35 Re-indent using newIndent, and return it as a single string.
36 """
37 sep, nothing = '\n', ''
38 if isinstance(lines, bytes): 38 ↛ 39line 38 didn't jump to line 39, because the condition on line 38 was never true
39 sep, nothing = b'\n', b''
40 if isinstance(lines, (bytes, str)):
41 lines = lines.split(sep)
42 oldIndent = whitePrefix(lines)
43 outLines = []
44 for l in lines:
45 if oldIndent:
46 l = l.replace(oldIndent, nothing, 1)
47 if l and newIndent:
48 l = newIndent + l
49 outLines.append(l)
50 return sep.join(outLines)
52def commonPrefix(strings):
53 """ Find the longest string that is a prefix of all the strings.
54 """
55 if not strings: 55 ↛ 56line 55 didn't jump to line 56, because the condition on line 55 was never true
56 return ''
57 prefix = strings[0]
58 for s in strings:
59 if len(s) < len(prefix):
60 prefix = prefix[:len(s)]
61 if not prefix:
62 return ''
63 for i in range(len(prefix)):
64 if prefix[i] != s[i]:
65 prefix = prefix[:i]
66 break
67 return prefix