Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(snippets): trim leading whitespace when extracting snippets #449

Merged
merged 3 commits into from
Mar 19, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion synthtool/gcp/snippets.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,24 @@
CLOSE_SNIPPET_REGEX = r".*\[END ([a-z0-9_]+)\].*$"


def _trim_leading_whitespace(lines: List[str]) -> List[str]:
def number_of_leading_spaces(input: str) -> int:
chingor13 marked this conversation as resolved.
Show resolved Hide resolved
return len(input) - len(input.lstrip(" "))

def is_empty_line(input: str) -> bool:
if re.match(r"^\s*$", input):
return True
return False

leading_spaces = [
number_of_leading_spaces(line) for line in lines if not is_empty_line(line)
]
max_leading_spaces = min(leading_spaces)
return [
"\n" if is_empty_line(line) else line[max_leading_spaces:] for line in lines
]


def all_snippets_from_file(sample_file: str) -> Dict[str, str]:
"""Reads in a sample file and parse out all contained snippets.

Expand Down Expand Up @@ -56,7 +74,10 @@ def all_snippets_from_file(sample_file: str) -> Dict[str, str]:
for snippet in open_snippets:
snippet_lines[snippet].append(line)

return {snippet: "".join(lines) for snippet, lines in snippet_lines.items()}
return {
snippet: "".join(_trim_leading_whitespace(lines))
for snippet, lines in snippet_lines.items()
}


def all_snippets(snippet_globs: List[str]) -> Dict[str, str]:
Expand Down
26 changes: 13 additions & 13 deletions tests/test_snippets.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,24 +37,24 @@ def test_load_snippets():
)
assert (
all_snippets["monitoring_install_with_bom"]
== """ <dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>3.5.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

== """<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-monitoring</artifactId>
<artifactId>libraries-bom</artifactId>
<version>3.5.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-monitoring</artifactId>
</dependency>
</dependencies>
"""
)

Expand Down