From b05d8326344a4981b7b1c5b99e133d725c1581ac Mon Sep 17 00:00:00 2001 From: Brian Ward Date: Wed, 4 Dec 2024 14:54:14 +0000 Subject: [PATCH] Normalize newlines before passing to scripts --- gui/src/app/Scripting/ScriptEditor.tsx | 3 ++- gui/src/app/util/normalizeLineEndings.ts | 3 +++ gui/test/app/util/normalizeLineEndings.test.ts | 15 +++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 gui/src/app/util/normalizeLineEndings.ts create mode 100644 gui/test/app/util/normalizeLineEndings.test.ts diff --git a/gui/src/app/Scripting/ScriptEditor.tsx b/gui/src/app/Scripting/ScriptEditor.tsx index 2eb75ab..674817c 100644 --- a/gui/src/app/Scripting/ScriptEditor.tsx +++ b/gui/src/app/Scripting/ScriptEditor.tsx @@ -5,6 +5,7 @@ import { ColorOptions, ToolbarItem } from "@SpComponents/ToolBar"; import { FileNames } from "@SpCore/FileMapping"; import { ProjectContext } from "@SpCore/ProjectContextProvider"; import { ProjectKnownFiles } from "@SpCore/ProjectDataModel"; +import { normalizeLineEndings } from "@SpUtil/normalizeLineEndings"; import { FunctionComponent, RefObject, @@ -67,7 +68,7 @@ const ScriptEditor: FunctionComponent = ({ }, [dataKey, update]); const runCode = useCallback(() => { - onRun(content); + onRun(normalizeLineEndings(content)); }, [content, onRun]); const unsavedChanges = useMemo(() => { diff --git a/gui/src/app/util/normalizeLineEndings.ts b/gui/src/app/util/normalizeLineEndings.ts new file mode 100644 index 0000000..8783e43 --- /dev/null +++ b/gui/src/app/util/normalizeLineEndings.ts @@ -0,0 +1,3 @@ +export const normalizeLineEndings = (str: string) => { + return str.replace(/\r\n/g, "\n"); +}; diff --git a/gui/test/app/util/normalizeLineEndings.test.ts b/gui/test/app/util/normalizeLineEndings.test.ts new file mode 100644 index 0000000..bb17a22 --- /dev/null +++ b/gui/test/app/util/normalizeLineEndings.test.ts @@ -0,0 +1,15 @@ +import { normalizeLineEndings } from "@SpUtil/normalizeLineEndings"; +import { describe, expect, test } from "vitest"; + +describe("normalizeLineEndings", () => { + test("should replace all CRLF with LF", () => { + const actual = normalizeLineEndings("foo\r\nbar\r\nbaz\r\n"); + expect(actual).toBe("foo\nbar\nbaz\n"); + }); + + test("leaves LF alone", () => { + const before = "foo\nbar\nbaz\n"; + const actual = normalizeLineEndings(before); + expect(actual).toBe(before); + }); +});