diff --git a/synthtool/gcp/snippets.py b/synthtool/gcp/snippets.py
index cafb5724e..5fd8ac8af 100644
--- a/synthtool/gcp/snippets.py
+++ b/synthtool/gcp/snippets.py
@@ -21,6 +21,35 @@
CLOSE_SNIPPET_REGEX = r".*\[END ([a-z0-9_]+)\].*$"
+def _trim_leading_whitespace(lines: List[str]) -> List[str]:
+ """Trims leading, plain spaces from the snippet content. Finds the minimum
+ number of leading spaces, ignoring empty lines, and removes that number of
+ spaces from each line.
+
+ Args:
+ lines (List[str]): Lines of content. These lines are newline terminated.
+
+ Returns:
+ List of trimmed lines.
+ """
+
+ def number_of_leading_spaces(input: str) -> int:
+ 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.
@@ -56,7 +85,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]:
diff --git a/tests/test_snippets.py b/tests/test_snippets.py
index 7194622fa..60c28671f 100644
--- a/tests/test_snippets.py
+++ b/tests/test_snippets.py
@@ -37,24 +37,24 @@ def test_load_snippets():
)
assert (
all_snippets["monitoring_install_with_bom"]
- == """
-
-
- com.google.cloud
- libraries-bom
- 3.5.0
- pom
- import
-
-
-
-
+ == """
com.google.cloud
- google-cloud-monitoring
+ libraries-bom
+ 3.5.0
+ pom
+ import
+
+
+
+
+ com.google.cloud
+ google-cloud-monitoring
+
+
"""
)