Skip to content

Commit 1f2374c

Browse files
committed
Port EscapeLeadingWhitespace.
1 parent d40a9f1 commit 1f2374c

File tree

1 file changed

+50
-5
lines changed

1 file changed

+50
-5
lines changed

python/selfie-lib/selfie_lib/EscapeLeadingWhitespace.py

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,56 @@
22

33

44
class EscapeLeadingWhitespace(Enum):
5+
ALWAYS = auto()
56
NEVER = auto()
7+
ONLY_ON_SPACE = auto()
8+
ONLY_ON_TAB = auto()
69

7-
def escape_line(self, line: str, space: str, tab: str) -> str: # noqa: ARG002
8-
return line
10+
def escape_line(self, line: str, space: str, tab: str) -> str:
11+
if line.startswith(" "):
12+
if (
13+
self == EscapeLeadingWhitespace.ALWAYS
14+
or self == EscapeLeadingWhitespace.ONLY_ON_SPACE
15+
):
16+
return f"{space}{line[1:]}"
17+
else:
18+
return line
19+
elif line.startswith("\t"):
20+
if (
21+
self == EscapeLeadingWhitespace.ALWAYS
22+
or self == EscapeLeadingWhitespace.ONLY_ON_TAB
23+
):
24+
return f"{tab}{line[1:]}"
25+
else:
26+
return line
27+
else:
28+
return line
929

10-
@staticmethod
11-
def appropriate_for(file_content: str) -> "EscapeLeadingWhitespace": # noqa: ARG004
12-
return EscapeLeadingWhitespace.NEVER
30+
@classmethod
31+
def appropriate_for(cls, file_content: str) -> "EscapeLeadingWhitespace":
32+
MIXED = "m"
33+
common_whitespace = None
34+
35+
for line in file_content.splitlines():
36+
whitespace = "".join(c for c in line if c.isspace())
37+
if not whitespace:
38+
continue
39+
elif all(c == " " for c in whitespace):
40+
whitespace = " "
41+
elif all(c == "\t" for c in whitespace):
42+
whitespace = "\t"
43+
else:
44+
whitespace = MIXED
45+
46+
if common_whitespace is None:
47+
common_whitespace = whitespace
48+
elif common_whitespace != whitespace:
49+
common_whitespace = MIXED
50+
break
51+
52+
if common_whitespace == " ":
53+
return cls.ONLY_ON_TAB
54+
elif common_whitespace == "\t":
55+
return cls.ONLY_ON_SPACE
56+
else:
57+
return cls.ALWAYS

0 commit comments

Comments
 (0)