Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
41 changes: 37 additions & 4 deletions src/functions/iac/terraform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,19 @@ describe("terraform iac", () => {
});

it("should serialize arrays of objects with line breaks", () => {
expect(tf.serializeValue([{ a: 1 }])).to.equal("[\n {\n a = 1\n }\n]");
expect(tf.serializeValue([{ a: 1 }])).to.equal(`[
{
a = 1
}
]`);
});

it("should serialize nested objects with proper indentation", () => {
expect(tf.serializeValue({ a: { b: 2 } })).to.equal("{\n a = {\n b = 2\n }\n}");
expect(tf.serializeValue({ a: { b: 2 } })).to.equal(`{
a = {
b = 2
}
}`);
});
});

Expand All @@ -111,7 +119,9 @@ describe("terraform iac", () => {
type: "locals",
attributes: { foo: "bar" },
}),
).to.equal('locals {\n foo = "bar"\n}');
).to.equal(`locals {
foo = "bar"
}`);
});

it("should stringify a block with labels", () => {
Expand All @@ -121,7 +131,30 @@ describe("terraform iac", () => {
labels: ["google_function", "my_func"],
attributes: { name: "test" },
}),
).to.equal('resource "google_function" "my_func" {\n name = "test"\n}');
).to.equal(`resource "google_function" "my_func" {
name = "test"
}`);
});
});

it("should use pretty ordering and spacing for resources", () => {
const block: tf.Block = {
type: "resource",
labels: ["google_cloudfunctions_function", "my_func"],
attributes: {
name: "test",
runtime: "nodejs20",
count: tf.expr("other_resource.count"),
depends_on: [tf.expr("other_resource")],
},
};
expect(tf.blockToString(block)).to.equal(`resource "google_cloudfunctions_function" "my_func" {
count = other_resource.count

name = "test"
runtime = "nodejs20"

depends_on = [other_resource]
}`);
});
});
109 changes: 106 additions & 3 deletions src/functions/iac/terraform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,15 @@
} else if (value === null || value === undefined) {
return "null";
} else if (Array.isArray(value)) {
if (value.some((e) => e !== null && typeof e === "object")) {
// Use multi-line if there is any Object. But we exclude HCL expressions from "objects".
if (
value.some(
(e) =>
e !== null &&
typeof e === "object" &&
(Array.isArray(e) || e["@type"] !== "HCLExpression"),
)
) {
return `[\n${value.map((v) => " ".repeat(indentation + 1) + serializeValue(v, indentation + 1)).join(",\n")}\n${" ".repeat(indentation)}]`;
}
return `[${value.map((v) => serializeValue(v)).join(", ")}]`;
Expand All @@ -121,17 +129,112 @@
return (value as Expression).value;
}
const entries = Object.entries(value).map(
([k, v]) => `${" ".repeat(indentation + 1)}${k} = ${serializeValue(v, indentation + 1)}`,

Check warning on line 132 in src/functions/iac/terraform.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any` assigned to a parameter of type `Value`
);
return `{\n${entries.join("\n")}\n${" ".repeat(indentation)}}`;
}
throw new FirebaseError(`Unsupported terraform value type ${typeof value}`, { exit: 1 });
}

const PREFIX_ARGUMENTS = new Set(["count", "for_each", "provider"]);
const SUFFIX_ARGUMENTS = new Set(["lifecycle", "depends_on"]);

const NON_BLOCK_PARAMETERS: Record<string, Set<string>> = {
google_cloudfunctions_function: new Set([
"name",
"runtime",
"description",
"available_memory_mb",
"timeout",
"entry_point",
"source_archive_bucket",
"source_archive_object",
"trigger_http",
"environment_variables",
"vpc_connector",
"service_account_email",
"max_instances",
"min_instances",
"project",
"region",
]),
google_cloudfunctions2_function: new Set(["name", "location", "description", "project"]),
google_cloud_scheduler_job: new Set([
"name",
"description",
"schedule",
"time_zone",
"paused",
"attempt_deadline",
"region",
"project",
]),
google_cloud_tasks_queue: new Set(["name", "location", "desired_state", "project"]),
google_eventarc_trigger: new Set(["name", "location", "project", "service_account"]),
google_pubsub_topic: new Set([
"name",
"project",
"labels",
"kms_key_name",
"message_retention_duration",
]),
google_pubsub_subscription: new Set([
"name",
"topic",
"project",
"labels",
"ack_deadline_seconds",
"message_retention_duration",
"retain_acked_messages",
"enable_message_ordering",
"filter",
]),
};

function serializeResourceAttributes(
attributes: Record<string, Value>,
resourceType: string,
indentation = 0,
): string {
const nonBlockParams = NON_BLOCK_PARAMETERS[resourceType] || new Set();

const prefixGroup: string[] = [];
const nonBlockGroup: string[] = [];
const blockGroup: string[] = [];
const suffixGroup: string[] = [];

for (const [k, v] of Object.entries(attributes)) {
const serialized = `${" ".repeat(indentation + 1)}${k} = ${serializeValue(v, indentation + 1)}`;
if (PREFIX_ARGUMENTS.has(k)) {
prefixGroup.push(serialized);
} else if (nonBlockParams.has(k)) {
nonBlockGroup.push(serialized);
} else if (SUFFIX_ARGUMENTS.has(k)) {
suffixGroup.push(serialized);
} else {
blockGroup.push(serialized);
}
}

const nonemptyGroups = [prefixGroup, nonBlockGroup, blockGroup, suffixGroup].filter(
(g) => g.length > 0,
);
// Within each group, separate attributes with a newline. Separate different groups with an empty line.
const joinedGroups = nonemptyGroups.map((g) => g.join("\n")).join("\n\n");

return `{\n${joinedGroups}\n${" ".repeat(indentation)}}`;
}

/**
* Converts a block to a string.
*/
export function blockToString(block: Block): string {
export function blockToString(block: Block, indentation: number = 0): string {

Check warning on line 231 in src/functions/iac/terraform.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Type number trivially inferred from a number literal, remove type annotation
const labels = (block.labels || []).map((l) => `"${l}"`).join(" ");
return `${block.type} ${labels ? labels + " " : ""}${serializeValue(block.attributes)}`;

if (block.type === "resource" && block.labels?.length) {
const resourceType = block.labels[0];
return `${" ".repeat(indentation)}${block.type} ${labels ? labels + " " : ""}${serializeResourceAttributes(block.attributes, resourceType, indentation)}`;
}

return `${" ".repeat(indentation)}${block.type} ${labels ? labels + " " : ""}${serializeValue(block.attributes, indentation)}`;
}
Loading