-
Notifications
You must be signed in to change notification settings - Fork 479
[jsweep] Clean substitute_placeholders.cjs #19315
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
Merged
pelikhan
merged 6 commits into
main
from
jsweep/clean-substitute-placeholders-b7e9f3579dc8f721
Mar 3, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8999d96
jsweep: clean substitute_placeholders.cjs
invalid-email-address b50208e
ci: trigger checks
github-actions[bot] 2f137de
jsweep: import shim.cjs and simplify logging in substitute_placeholde…
Copilot d43c555
jsweep: add comment explaining shim.cjs import
Copilot d903fc3
Add changeset for substitute placeholder cleanup [skip-ci]
5fc1dcb
ci: trigger checks
github-actions[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,117 +1,56 @@ | ||
| // @ts-check | ||
| /// <reference types="@actions/github-script" /> | ||
|
|
||
| // Ensures global.core is available when running outside github-script context | ||
| require("./shim.cjs"); | ||
| const fs = require("fs"); | ||
| const { getErrorMessage } = require("./error_helpers.cjs"); | ||
| const { ERR_SYSTEM } = require("./error_codes.cjs"); | ||
|
|
||
| /** | ||
| * Substitutes `__KEY__` placeholders in a file with values from the substitutions map. | ||
| * Undefined/null values are treated as empty strings. | ||
| * | ||
| * @param {{ file: string, substitutions: Record<string, string | null | undefined> }} params | ||
| * @returns {Promise<string>} | ||
| */ | ||
| const substitutePlaceholders = async ({ file, substitutions }) => { | ||
| if (typeof core !== "undefined") { | ||
| core.info("========================================"); | ||
| core.info("[substitutePlaceholders] Starting placeholder substitution"); | ||
| core.info("========================================"); | ||
| } | ||
|
|
||
| // Validate parameters | ||
| if (!file) { | ||
| const error = new Error("file parameter is required"); | ||
| if (typeof core !== "undefined") { | ||
| core.info(`[substitutePlaceholders] ERROR: ${error.message}`); | ||
| } | ||
| throw error; | ||
| throw new Error("file parameter is required"); | ||
| } | ||
| if (!substitutions || "object" != typeof substitutions) { | ||
| const error = new Error("substitutions parameter must be an object"); | ||
| if (typeof core !== "undefined") { | ||
| core.info(`[substitutePlaceholders] ERROR: ${error.message}`); | ||
| } | ||
| throw error; | ||
| if (!substitutions || typeof substitutions !== "object") { | ||
| throw new Error("substitutions parameter must be an object"); | ||
| } | ||
|
|
||
| if (typeof core !== "undefined") { | ||
| core.info(`[substitutePlaceholders] File: ${file}`); | ||
| core.info(`[substitutePlaceholders] Substitution count: ${Object.keys(substitutions).length}`); | ||
| } | ||
| core.info(`[substitutePlaceholders] ${file} (${Object.keys(substitutions).length} substitution(s))`); | ||
|
|
||
| // Read the file | ||
| let content; | ||
| try { | ||
| if (typeof core !== "undefined") { | ||
| core.info(`[substitutePlaceholders] Reading file...`); | ||
| } | ||
| content = fs.readFileSync(file, "utf8"); | ||
| if (typeof core !== "undefined") { | ||
| core.info(`[substitutePlaceholders] File read successfully`); | ||
| core.info(`[substitutePlaceholders] Original content length: ${content.length} characters`); | ||
| core.info(`[substitutePlaceholders] First 200 characters: ${content.substring(0, 200).replace(/\n/g, "\\n")}`); | ||
| } | ||
| } catch (error) { | ||
| const errorMessage = getErrorMessage(error); | ||
| if (typeof core !== "undefined") { | ||
| core.info(`[substitutePlaceholders] ERROR reading file: ${errorMessage}`); | ||
| } | ||
| throw new Error(`${ERR_SYSTEM}: Failed to read file ${file}: ${errorMessage}`); | ||
| } | ||
|
|
||
| // Perform substitutions | ||
| if (typeof core !== "undefined") { | ||
| core.info("\n========================================"); | ||
| core.info("[substitutePlaceholders] Processing Substitutions"); | ||
| core.info("========================================"); | ||
| } | ||
|
|
||
| let totalReplacements = 0; | ||
| const beforeLength = content.length; | ||
|
|
||
| for (const [key, value] of Object.entries(substitutions)) { | ||
| const placeholder = `__${key}__`; | ||
| // Convert undefined/null to empty string to avoid leaving "undefined" or "null" in the output | ||
| const safeValue = value === undefined || value === null ? "" : value; | ||
|
|
||
| // Count occurrences before replacement | ||
| const occurrences = (content.match(new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g")) || []).length; | ||
|
|
||
| if (typeof core !== "undefined") { | ||
| if (occurrences > 0) { | ||
| core.info(`[substitutePlaceholders] Replacing ${placeholder} (${occurrences} occurrence(s))`); | ||
| core.info(`[substitutePlaceholders] Value: ${safeValue.substring(0, 100)}${safeValue.length > 100 ? "..." : ""}`); | ||
| } else { | ||
| core.info(`[substitutePlaceholders] Placeholder ${placeholder} not found in content (unused)`); | ||
| } | ||
| } | ||
|
|
||
| const safeValue = value == null ? "" : value; | ||
| content = content.split(placeholder).join(safeValue); | ||
| totalReplacements += occurrences; | ||
| } | ||
|
|
||
| const afterLength = content.length; | ||
|
|
||
| if (typeof core !== "undefined") { | ||
| core.info(`[substitutePlaceholders] Substitution complete: ${totalReplacements} total replacement(s)`); | ||
| core.info(`[substitutePlaceholders] Content length change: ${beforeLength} -> ${afterLength} (${afterLength > beforeLength ? "+" : ""}${afterLength - beforeLength})`); | ||
| } | ||
|
|
||
| // Write back to the file | ||
| try { | ||
| if (typeof core !== "undefined") { | ||
| core.info("\n========================================"); | ||
| core.info("[substitutePlaceholders] Writing Output"); | ||
| core.info("========================================"); | ||
| core.info(`[substitutePlaceholders] Writing processed content back to: ${file}`); | ||
| } | ||
| fs.writeFileSync(file, content, "utf8"); | ||
| if (typeof core !== "undefined") { | ||
| core.info(`[substitutePlaceholders] File written successfully`); | ||
| core.info(`[substitutePlaceholders] Last 200 characters: ${content.substring(Math.max(0, content.length - 200)).replace(/\n/g, "\\n")}`); | ||
| core.info("========================================"); | ||
| core.info("[substitutePlaceholders] Processing complete - SUCCESS"); | ||
| core.info("========================================"); | ||
| } | ||
| } catch (error) { | ||
| const errorMessage = getErrorMessage(error); | ||
| if (typeof core !== "undefined") { | ||
| core.info(`[substitutePlaceholders] ERROR writing file: ${errorMessage}`); | ||
| } | ||
| throw new Error(`${ERR_SYSTEM}: Failed to write file ${file}: ${errorMessage}`); | ||
| } | ||
|
|
||
| return `Successfully substituted ${Object.keys(substitutions).length} placeholder(s) in ${file}`; | ||
| }; | ||
|
|
||
| module.exports = substitutePlaceholders; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,67 +1,100 @@ | ||
| const fs = require("fs"), | ||
| os = require("os"), | ||
| path = require("path"), | ||
| substitutePlaceholders = require("./substitute_placeholders.cjs"); | ||
| import { afterEach, beforeEach, describe, expect, it } from "vitest"; | ||
|
|
||
| const fs = require("fs"); | ||
| const os = require("os"); | ||
| const path = require("path"); | ||
| const substitutePlaceholders = require("./substitute_placeholders.cjs"); | ||
|
|
||
| describe("substitutePlaceholders", () => { | ||
| let tempDir, testFile; | ||
| (beforeEach(() => { | ||
| ((tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "substitute-test-"))), (testFile = path.join(tempDir, "test.txt"))); | ||
| }), | ||
| afterEach(() => { | ||
| (fs.existsSync(testFile) && fs.unlinkSync(testFile), fs.existsSync(tempDir) && fs.rmdirSync(tempDir)); | ||
| }), | ||
| it("should substitute a single placeholder", async () => { | ||
| (fs.writeFileSync(testFile, "Hello __NAME__!", "utf8"), await substitutePlaceholders({ file: testFile, substitutions: { NAME: "World" } })); | ||
| const content = fs.readFileSync(testFile, "utf8"); | ||
| expect(content).toBe("Hello World!"); | ||
| }), | ||
| it("should substitute multiple placeholders", async () => { | ||
| (fs.writeFileSync(testFile, "Repository: __REPO__\nActor: __ACTOR__\nBranch: __BRANCH__", "utf8"), await substitutePlaceholders({ file: testFile, substitutions: { REPO: "test/repo", ACTOR: "testuser", BRANCH: "main" } })); | ||
| const content = fs.readFileSync(testFile, "utf8"); | ||
| expect(content).toBe("Repository: test/repo\nActor: testuser\nBranch: main"); | ||
| }), | ||
| it("should handle special characters safely", async () => { | ||
| (fs.writeFileSync(testFile, "Command: __CMD__", "utf8"), await substitutePlaceholders({ file: testFile, substitutions: { CMD: "$(malicious) `backdoor` ${VAR} | pipe" } })); | ||
| const content = fs.readFileSync(testFile, "utf8"); | ||
| expect(content).toBe("Command: $(malicious) `backdoor` ${VAR} | pipe"); | ||
| }), | ||
| it("should handle placeholders appearing multiple times", async () => { | ||
| (fs.writeFileSync(testFile, "__NAME__ is great. I love __NAME__!", "utf8"), await substitutePlaceholders({ file: testFile, substitutions: { NAME: "Testing" } })); | ||
| const content = fs.readFileSync(testFile, "utf8"); | ||
| expect(content).toBe("Testing is great. I love Testing!"); | ||
| }), | ||
| it("should leave unmatched placeholders unchanged", async () => { | ||
| (fs.writeFileSync(testFile, "__FOO__ and __BAR__", "utf8"), await substitutePlaceholders({ file: testFile, substitutions: { FOO: "foo" } })); | ||
| const content = fs.readFileSync(testFile, "utf8"); | ||
| expect(content).toBe("foo and __BAR__"); | ||
| }), | ||
| it("should handle empty values", async () => { | ||
| (fs.writeFileSync(testFile, "Value: __VAL__", "utf8"), await substitutePlaceholders({ file: testFile, substitutions: { VAL: "" } })); | ||
| const content = fs.readFileSync(testFile, "utf8"); | ||
| expect(content).toBe("Value: "); | ||
| }), | ||
| it("should throw error if file parameter is missing", async () => { | ||
| await expect(substitutePlaceholders({ substitutions: { NAME: "test" } })).rejects.toThrow("file parameter is required"); | ||
| }), | ||
| it("should throw error if substitutions parameter is missing", async () => { | ||
| await expect(substitutePlaceholders({ file: testFile })).rejects.toThrow("substitutions parameter must be an object"); | ||
| }), | ||
| it("should throw error if file does not exist", async () => { | ||
| await expect(substitutePlaceholders({ file: "/nonexistent/file.txt", substitutions: { NAME: "test" } })).rejects.toThrow("Failed to read file"); | ||
| }), | ||
| it("should handle undefined values as empty strings", async () => { | ||
| (fs.writeFileSync(testFile, "Value: __VAL__", "utf8"), await substitutePlaceholders({ file: testFile, substitutions: { VAL: undefined } })); | ||
| const content = fs.readFileSync(testFile, "utf8"); | ||
| expect(content).toBe("Value: "); | ||
| }), | ||
| it("should handle null values as empty strings", async () => { | ||
| (fs.writeFileSync(testFile, "Value: __VAL__", "utf8"), await substitutePlaceholders({ file: testFile, substitutions: { VAL: null } })); | ||
| const content = fs.readFileSync(testFile, "utf8"); | ||
| expect(content).toBe("Value: "); | ||
| }), | ||
| it("should handle mixed undefined and defined values", async () => { | ||
| (fs.writeFileSync(testFile, "Repo: __REPO__\nComment: __COMMENT__\nIssue: __ISSUE__", "utf8"), await substitutePlaceholders({ file: testFile, substitutions: { REPO: "test/repo", COMMENT: undefined, ISSUE: null } })); | ||
| const content = fs.readFileSync(testFile, "utf8"); | ||
| expect(content).toBe("Repo: test/repo\nComment: \nIssue: "); | ||
| })); | ||
| /** @type {string} */ | ||
| let tempDir; | ||
| /** @type {string} */ | ||
| let testFile; | ||
|
|
||
| beforeEach(() => { | ||
| tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "substitute-test-")); | ||
| testFile = path.join(tempDir, "test.txt"); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| if (fs.existsSync(testFile)) fs.unlinkSync(testFile); | ||
| if (fs.existsSync(tempDir)) fs.rmdirSync(tempDir); | ||
| }); | ||
|
|
||
| it("should substitute a single placeholder", async () => { | ||
| fs.writeFileSync(testFile, "Hello __NAME__!", "utf8"); | ||
| await substitutePlaceholders({ file: testFile, substitutions: { NAME: "World" } }); | ||
| expect(fs.readFileSync(testFile, "utf8")).toBe("Hello World!"); | ||
| }); | ||
|
|
||
| it("should substitute multiple placeholders", async () => { | ||
| fs.writeFileSync(testFile, "Repository: __REPO__\nActor: __ACTOR__\nBranch: __BRANCH__", "utf8"); | ||
| await substitutePlaceholders({ | ||
| file: testFile, | ||
| substitutions: { REPO: "test/repo", ACTOR: "testuser", BRANCH: "main" }, | ||
| }); | ||
| expect(fs.readFileSync(testFile, "utf8")).toBe("Repository: test/repo\nActor: testuser\nBranch: main"); | ||
| }); | ||
|
|
||
| it("should handle special characters safely", async () => { | ||
| fs.writeFileSync(testFile, "Command: __CMD__", "utf8"); | ||
| await substitutePlaceholders({ | ||
| file: testFile, | ||
| substitutions: { CMD: "$(malicious) `backdoor` ${VAR} | pipe" }, | ||
| }); | ||
| expect(fs.readFileSync(testFile, "utf8")).toBe("Command: $(malicious) `backdoor` ${VAR} | pipe"); | ||
| }); | ||
|
|
||
| it("should handle placeholders appearing multiple times", async () => { | ||
| fs.writeFileSync(testFile, "__NAME__ is great. I love __NAME__!", "utf8"); | ||
| await substitutePlaceholders({ file: testFile, substitutions: { NAME: "Testing" } }); | ||
| expect(fs.readFileSync(testFile, "utf8")).toBe("Testing is great. I love Testing!"); | ||
| }); | ||
|
|
||
| it("should leave unmatched placeholders unchanged", async () => { | ||
| fs.writeFileSync(testFile, "__FOO__ and __BAR__", "utf8"); | ||
| await substitutePlaceholders({ file: testFile, substitutions: { FOO: "foo" } }); | ||
| expect(fs.readFileSync(testFile, "utf8")).toBe("foo and __BAR__"); | ||
| }); | ||
|
|
||
| it("should handle empty values", async () => { | ||
| fs.writeFileSync(testFile, "Value: __VAL__", "utf8"); | ||
| await substitutePlaceholders({ file: testFile, substitutions: { VAL: "" } }); | ||
| expect(fs.readFileSync(testFile, "utf8")).toBe("Value: "); | ||
| }); | ||
|
|
||
| it("should throw error if file parameter is missing", async () => { | ||
| // @ts-expect-error - testing missing file param | ||
| await expect(substitutePlaceholders({ substitutions: { NAME: "test" } })).rejects.toThrow("file parameter is required"); | ||
| }); | ||
|
|
||
| it("should throw error if substitutions parameter is missing", async () => { | ||
| // @ts-expect-error - testing missing substitutions param | ||
| await expect(substitutePlaceholders({ file: testFile })).rejects.toThrow("substitutions parameter must be an object"); | ||
| }); | ||
|
|
||
| it("should throw error if file does not exist", async () => { | ||
| await expect(substitutePlaceholders({ file: "/nonexistent/file.txt", substitutions: { NAME: "test" } })).rejects.toThrow("Failed to read file"); | ||
| }); | ||
|
|
||
| it("should handle undefined values as empty strings", async () => { | ||
| fs.writeFileSync(testFile, "Value: __VAL__", "utf8"); | ||
| await substitutePlaceholders({ file: testFile, substitutions: { VAL: undefined } }); | ||
| expect(fs.readFileSync(testFile, "utf8")).toBe("Value: "); | ||
| }); | ||
|
|
||
| it("should handle null values as empty strings", async () => { | ||
| fs.writeFileSync(testFile, "Value: __VAL__", "utf8"); | ||
| await substitutePlaceholders({ file: testFile, substitutions: { VAL: null } }); | ||
| expect(fs.readFileSync(testFile, "utf8")).toBe("Value: "); | ||
| }); | ||
|
|
||
| it("should handle mixed undefined and defined values", async () => { | ||
| fs.writeFileSync(testFile, "Repo: __REPO__\nComment: __COMMENT__\nIssue: __ISSUE__", "utf8"); | ||
| await substitutePlaceholders({ | ||
| file: testFile, | ||
| substitutions: { REPO: "test/repo", COMMENT: undefined, ISSUE: null }, | ||
| }); | ||
| expect(fs.readFileSync(testFile, "utf8")).toBe("Repo: test/repo\nComment: \nIssue: "); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.