diff --git a/src/sshConfig.test.ts b/src/sshConfig.test.ts index 03b73fab..d4a8e41d 100644 --- a/src/sshConfig.test.ts +++ b/src/sshConfig.test.ts @@ -2,11 +2,17 @@ import { it, afterEach, vi, expect } from "vitest" import { SSHConfig } from "./sshConfig" -const sshFilePath = "~/.config/ssh" +// This is not the usual path to ~/.ssh/config, but +// setting it to a different path makes it easier to test +// and makes mistakes abundantly clear. +const sshFilePath = "/Path/To/UserHomeDir/.sshConfigDir/sshConfigFile" +const sshTempFilePathExpr = `^/Path/To/UserHomeDir/\\.sshConfigDir/\\.sshConfigFile\\.vscode-coder-tmp\\.[a-z0-9]+$` const mockFileSystem = { - readFile: vi.fn(), mkdir: vi.fn(), + readFile: vi.fn(), + rename: vi.fn(), + stat: vi.fn(), writeFile: vi.fn(), } @@ -16,6 +22,7 @@ afterEach(() => { it("creates a new file and adds config with empty label", async () => { mockFileSystem.readFile.mockRejectedValueOnce("No file found") + mockFileSystem.stat.mockRejectedValueOnce({ code: "ENOENT" }) const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) await sshConfig.load() @@ -38,11 +45,20 @@ Host coder-vscode--* # --- END CODER VSCODE ---` expect(mockFileSystem.readFile).toBeCalledWith(sshFilePath, expect.anything()) - expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, expect.anything()) + expect(mockFileSystem.writeFile).toBeCalledWith( + expect.stringMatching(sshTempFilePathExpr), + expectedOutput, + expect.objectContaining({ + encoding: "utf-8", + mode: 0o600, // Default mode for new files. + }), + ) + expect(mockFileSystem.rename).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), sshFilePath) }) it("creates a new file and adds the config", async () => { mockFileSystem.readFile.mockRejectedValueOnce("No file found") + mockFileSystem.stat.mockRejectedValueOnce({ code: "ENOENT" }) const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) await sshConfig.load() @@ -65,7 +81,15 @@ Host coder-vscode.dev.coder.com--* # --- END CODER VSCODE dev.coder.com ---` expect(mockFileSystem.readFile).toBeCalledWith(sshFilePath, expect.anything()) - expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, expect.anything()) + expect(mockFileSystem.writeFile).toBeCalledWith( + expect.stringMatching(sshTempFilePathExpr), + expectedOutput, + expect.objectContaining({ + encoding: "utf-8", + mode: 0o600, // Default mode for new files. + }), + ) + expect(mockFileSystem.rename).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), sshFilePath) }) it("adds a new coder config in an existent SSH configuration", async () => { @@ -77,6 +101,7 @@ it("adds a new coder config in an existent SSH configuration", async () => { StrictHostKeyChecking=no UserKnownHostsFile=/dev/null` mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + mockFileSystem.stat.mockResolvedValueOnce({ mode: 0o644 }) const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) await sshConfig.load() @@ -100,10 +125,11 @@ Host coder-vscode.dev.coder.com--* UserKnownHostsFile /dev/null # --- END CODER VSCODE dev.coder.com ---` - expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, { + expect(mockFileSystem.writeFile).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), expectedOutput, { encoding: "utf-8", - mode: 384, + mode: 0o644, }) + expect(mockFileSystem.rename).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), sshFilePath) }) it("updates an existent coder config", async () => { @@ -138,6 +164,7 @@ Host coder-vscode.dev.coder.com--* Host * SetEnv TEST=1` mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + mockFileSystem.stat.mockResolvedValueOnce({ mode: 0o644 }) const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) await sshConfig.load() @@ -164,10 +191,11 @@ Host coder-vscode.dev-updated.coder.com--* Host * SetEnv TEST=1` - expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, { + expect(mockFileSystem.writeFile).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), expectedOutput, { encoding: "utf-8", - mode: 384, + mode: 0o644, }) + expect(mockFileSystem.rename).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), sshFilePath) }) it("does not remove deployment-unaware SSH config and adds the new one", async () => { @@ -186,6 +214,7 @@ Host coder-vscode--* UserKnownHostsFile=/dev/null # --- END CODER VSCODE ---` mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + mockFileSystem.stat.mockResolvedValueOnce({ mode: 0o644 }) const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) await sshConfig.load() @@ -209,16 +238,18 @@ Host coder-vscode.dev.coder.com--* UserKnownHostsFile /dev/null # --- END CODER VSCODE dev.coder.com ---` - expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, { + expect(mockFileSystem.writeFile).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), expectedOutput, { encoding: "utf-8", - mode: 384, + mode: 0o644, }) + expect(mockFileSystem.rename).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), sshFilePath) }) it("it does not remove a user-added block that only matches the host of an old coder SSH config", async () => { const existentSSHConfig = `Host coder-vscode--* ForwardAgent=yes` mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + mockFileSystem.stat.mockResolvedValueOnce({ mode: 0o644 }) const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) await sshConfig.load() @@ -243,14 +274,293 @@ Host coder-vscode.dev.coder.com--* UserKnownHostsFile /dev/null # --- END CODER VSCODE dev.coder.com ---` - expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, { + expect(mockFileSystem.writeFile).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), expectedOutput, { encoding: "utf-8", - mode: 384, + mode: 0o644, }) + expect(mockFileSystem.rename).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), sshFilePath) +}) + +it("throws an error if there is a missing end block", async () => { + // The below config is missing an end block. + // This is a malformed config and should throw an error. + const existentSSHConfig = `Host beforeconfig + HostName before.config.tld + User before + +# --- START CODER VSCODE dev.coder.com --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null + +Host afterconfig + HostName after.config.tld + User after` + + const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) + mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + await sshConfig.load() + + // When we try to update the config, it should throw an error. + await expect( + sshConfig.update("dev.coder.com", { + Host: "coder-vscode.dev.coder.com--*", + ProxyCommand: "some-command-here", + ConnectTimeout: "0", + StrictHostKeyChecking: "no", + UserKnownHostsFile: "/dev/null", + LogLevel: "ERROR", + }), + ).rejects.toThrow( + `Malformed config: ${sshFilePath} has an unterminated START CODER VSCODE dev.coder.com block. Each START block must have an END block.`, + ) +}) + +it("throws an error if there is a mismatched start and end block count", async () => { + // The below config contains two start blocks and one end block. + // This is a malformed config and should throw an error. + // Previously were were simply taking the first occurrences of the start and + // end blocks, which would potentially lead to loss of any content between the + // missing end block and the next start block. + const existentSSHConfig = `Host beforeconfig + HostName before.config.tld + User before + +# --- START CODER VSCODE dev.coder.com --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# missing END CODER VSCODE dev.coder.com --- + +Host donotdelete + HostName dont.delete.me + User please + +# --- START CODER VSCODE dev.coder.com --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# --- END CODER VSCODE dev.coder.com --- + +Host afterconfig + HostName after.config.tld + User after` + + const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) + mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + await sshConfig.load() + + // When we try to update the config, it should throw an error. + await expect( + sshConfig.update("dev.coder.com", { + Host: "coder-vscode.dev.coder.com--*", + ProxyCommand: "some-command-here", + ConnectTimeout: "0", + StrictHostKeyChecking: "no", + UserKnownHostsFile: "/dev/null", + LogLevel: "ERROR", + }), + ).rejects.toThrow( + `Malformed config: ${sshFilePath} has an unterminated START CODER VSCODE dev.coder.com block. Each START block must have an END block.`, + ) +}) + +it("throws an error if there is a mismatched start and end block count (without label)", async () => { + // As above, but without a label. + const existentSSHConfig = `Host beforeconfig + HostName before.config.tld + User before + +# --- START CODER VSCODE --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# missing END CODER VSCODE --- + +Host donotdelete + HostName dont.delete.me + User please + +# --- START CODER VSCODE --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# --- END CODER VSCODE --- + +Host afterconfig + HostName after.config.tld + User after` + + const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) + mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + await sshConfig.load() + + // When we try to update the config, it should throw an error. + await expect( + sshConfig.update("", { + Host: "coder-vscode.dev.coder.com--*", + ProxyCommand: "some-command-here", + ConnectTimeout: "0", + StrictHostKeyChecking: "no", + UserKnownHostsFile: "/dev/null", + LogLevel: "ERROR", + }), + ).rejects.toThrow( + `Malformed config: ${sshFilePath} has an unterminated START CODER VSCODE block. Each START block must have an END block.`, + ) +}) + +it("throws an error if there are more than one sections with the same label", async () => { + const existentSSHConfig = `Host beforeconfig + HostName before.config.tld + User before + +# --- START CODER VSCODE dev.coder.com --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# --- END CODER VSCODE dev.coder.com --- + +Host donotdelete + HostName dont.delete.me + User please + +# --- START CODER VSCODE dev.coder.com --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# --- END CODER VSCODE dev.coder.com --- + +Host afterconfig + HostName after.config.tld + User after` + + const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) + mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + await sshConfig.load() + + // When we try to update the config, it should throw an error. + await expect( + sshConfig.update("dev.coder.com", { + Host: "coder-vscode.dev.coder.com--*", + ProxyCommand: "some-command-here", + ConnectTimeout: "0", + StrictHostKeyChecking: "no", + UserKnownHostsFile: "/dev/null", + LogLevel: "ERROR", + }), + ).rejects.toThrow( + `Malformed config: ${sshFilePath} has 2 START CODER VSCODE dev.coder.com sections. Please remove all but one.`, + ) +}) + +it("correctly handles interspersed blocks with and without label", async () => { + const existentSSHConfig = `Host beforeconfig + HostName before.config.tld + User before + +# --- START CODER VSCODE --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# --- END CODER VSCODE --- + +Host donotdelete + HostName dont.delete.me + User please + +# --- START CODER VSCODE dev.coder.com --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# --- END CODER VSCODE dev.coder.com --- + +Host afterconfig + HostName after.config.tld + User after` + + const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) + mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + mockFileSystem.stat.mockResolvedValueOnce({ mode: 0o644 }) + await sshConfig.load() + + const expectedOutput = `Host beforeconfig + HostName before.config.tld + User before + +# --- START CODER VSCODE --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# --- END CODER VSCODE --- + +Host donotdelete + HostName dont.delete.me + User please + +# --- START CODER VSCODE dev.coder.com --- +Host coder-vscode.dev.coder.com--* + ConnectTimeout 0 + LogLevel ERROR + ProxyCommand some-command-here + StrictHostKeyChecking no + UserKnownHostsFile /dev/null +# --- END CODER VSCODE dev.coder.com --- + +Host afterconfig + HostName after.config.tld + User after` + + await sshConfig.update("dev.coder.com", { + Host: "coder-vscode.dev.coder.com--*", + ProxyCommand: "some-command-here", + ConnectTimeout: "0", + StrictHostKeyChecking: "no", + UserKnownHostsFile: "/dev/null", + LogLevel: "ERROR", + }) + + expect(mockFileSystem.writeFile).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), expectedOutput, { + encoding: "utf-8", + mode: 0o644, + }) + expect(mockFileSystem.rename).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), sshFilePath) }) it("override values", async () => { mockFileSystem.readFile.mockRejectedValueOnce("No file found") + mockFileSystem.stat.mockRejectedValueOnce({ code: "ENOENT" }) + const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) await sshConfig.load() await sshConfig.update( @@ -287,5 +597,62 @@ Host coder-vscode.dev.coder.com--* # --- END CODER VSCODE dev.coder.com ---` expect(mockFileSystem.readFile).toBeCalledWith(sshFilePath, expect.anything()) - expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, expect.anything()) + expect(mockFileSystem.writeFile).toBeCalledWith( + expect.stringMatching(sshTempFilePathExpr), + expectedOutput, + expect.objectContaining({ + encoding: "utf-8", + mode: 0o600, // Default mode for new files. + }), + ) + expect(mockFileSystem.rename).toBeCalledWith(expect.stringMatching(sshTempFilePathExpr), sshFilePath) +}) + +it("fails if we are unable to write the temporary file", async () => { + const existentSSHConfig = `Host beforeconfig + HostName before.config.tld + User before` + + const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) + mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + mockFileSystem.stat.mockResolvedValueOnce({ mode: 0o600 }) + mockFileSystem.writeFile.mockRejectedValueOnce(new Error("EACCES")) + + await sshConfig.load() + + expect(mockFileSystem.readFile).toBeCalledWith(sshFilePath, expect.anything()) + await expect( + sshConfig.update("dev.coder.com", { + Host: "coder-vscode.dev.coder.com--*", + ProxyCommand: "some-command-here", + ConnectTimeout: "0", + StrictHostKeyChecking: "no", + UserKnownHostsFile: "/dev/null", + LogLevel: "ERROR", + }), + ).rejects.toThrow(/Failed to write temporary SSH config file.*EACCES/) +}) + +it("fails if we are unable to rename the temporary file", async () => { + const existentSSHConfig = `Host beforeconfig + HostName before.config.tld + User before` + + const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) + mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) + mockFileSystem.stat.mockResolvedValueOnce({ mode: 0o600 }) + mockFileSystem.writeFile.mockResolvedValueOnce("") + mockFileSystem.rename.mockRejectedValueOnce(new Error("EACCES")) + + await sshConfig.load() + await expect( + sshConfig.update("dev.coder.com", { + Host: "coder-vscode.dev.coder.com--*", + ProxyCommand: "some-command-here", + ConnectTimeout: "0", + StrictHostKeyChecking: "no", + UserKnownHostsFile: "/dev/null", + LogLevel: "ERROR", + }), + ).rejects.toThrow(/Failed to rename temporary SSH config file.*EACCES/) }) diff --git a/src/sshConfig.ts b/src/sshConfig.ts index 133ed6a4..4a75b209 100644 --- a/src/sshConfig.ts +++ b/src/sshConfig.ts @@ -1,5 +1,6 @@ -import { mkdir, readFile, writeFile } from "fs/promises" +import { mkdir, readFile, rename, stat, writeFile } from "fs/promises" import path from "path" +import { countSubstring } from "./util" class SSHConfigBadFormat extends Error {} @@ -19,14 +20,18 @@ export interface SSHValues { // Interface for the file system to make it easier to test export interface FileSystem { - readFile: typeof readFile mkdir: typeof mkdir + readFile: typeof readFile + rename: typeof rename + stat: typeof stat writeFile: typeof writeFile } const defaultFileSystem: FileSystem = { - readFile, mkdir, + readFile, + rename, + stat, writeFile, } @@ -123,10 +128,26 @@ export class SSHConfig { */ private getBlock(label: string): Block | undefined { const raw = this.getRaw() - const startBlockIndex = raw.indexOf(this.startBlockComment(label)) - const endBlockIndex = raw.indexOf(this.endBlockComment(label)) - const hasBlock = startBlockIndex > -1 && endBlockIndex > -1 + const startBlock = this.startBlockComment(label) + const endBlock = this.endBlockComment(label) + + const startBlockCount = countSubstring(startBlock, raw) + const endBlockCount = countSubstring(endBlock, raw) + if (startBlockCount !== endBlockCount) { + throw new SSHConfigBadFormat( + `Malformed config: ${this.filePath} has an unterminated START CODER VSCODE ${label ? label + " " : ""}block. Each START block must have an END block.`, + ) + } + + if (startBlockCount > 1 || endBlockCount > 1) { + throw new SSHConfigBadFormat( + `Malformed config: ${this.filePath} has ${startBlockCount} START CODER VSCODE ${label ? label + " " : ""}sections. Please remove all but one.`, + ) + } + const startBlockIndex = raw.indexOf(startBlock) + const endBlockIndex = raw.indexOf(endBlock) + const hasBlock = startBlockIndex > -1 && endBlockIndex > -1 if (!hasBlock) { return } @@ -144,7 +165,7 @@ export class SSHConfig { } return { - raw: raw.substring(startBlockIndex, endBlockIndex + this.endBlockComment(label).length), + raw: raw.substring(startBlockIndex, endBlockIndex + endBlock.length), } } @@ -203,14 +224,45 @@ export class SSHConfig { } private async save() { + // We want to preserve the original file mode. + const existingMode = await this.fileSystem + .stat(this.filePath) + .then((stat) => stat.mode) + .catch((ex) => { + if (ex.code && ex.code === "ENOENT") { + return 0o600 // default to 0600 if file does not exist + } + throw ex // Any other error is unexpected + }) await this.fileSystem.mkdir(path.dirname(this.filePath), { mode: 0o700, // only owner has rwx permission, not group or everyone. recursive: true, }) - return this.fileSystem.writeFile(this.filePath, this.getRaw(), { - mode: 0o600, // owner rw - encoding: "utf-8", - }) + const randSuffix = Math.random().toString(36).substring(8) + const fileName = path.basename(this.filePath) + const dirName = path.dirname(this.filePath) + const tempFilePath = `${dirName}/.${fileName}.vscode-coder-tmp.${randSuffix}` + try { + await this.fileSystem.writeFile(tempFilePath, this.getRaw(), { + mode: existingMode, + encoding: "utf-8", + }) + } catch (err) { + throw new Error( + `Failed to write temporary SSH config file at ${tempFilePath}: ${err instanceof Error ? err.message : String(err)}. ` + + `Please check your disk space, permissions, and that the directory exists.`, + ) + } + + try { + await this.fileSystem.rename(tempFilePath, this.filePath) + } catch (err) { + throw new Error( + `Failed to rename temporary SSH config file at ${tempFilePath} to ${this.filePath}: ${ + err instanceof Error ? err.message : String(err) + }. Please check your disk space, permissions, and that the directory exists.`, + ) + } } public getRaw() { diff --git a/src/util.test.ts b/src/util.test.ts index 4fffcc75..0c5da63a 100644 --- a/src/util.test.ts +++ b/src/util.test.ts @@ -1,5 +1,5 @@ -import { it, expect } from "vitest" -import { parseRemoteAuthority, toSafeHost } from "./util" +import { describe, it, expect } from "vitest" +import { countSubstring, parseRemoteAuthority, toSafeHost } from "./util" it("ignore unrelated authorities", async () => { const tests = [ @@ -73,3 +73,35 @@ it("escapes url host", async () => { expect(() => toSafeHost("invalid url")).toThrow("Invalid URL") expect(toSafeHost("http://ignore-port.com:8080/")).toBe("ignore-port.com") }) + +describe("countSubstring", () => { + it("handles empty strings", () => { + expect(countSubstring("", "")).toBe(0) + expect(countSubstring("foo", "")).toBe(0) + expect(countSubstring("", "foo")).toBe(0) + }) + + it("handles single character", () => { + expect(countSubstring("a", "a")).toBe(1) + expect(countSubstring("a", "b")).toBe(0) + expect(countSubstring("a", "aa")).toBe(2) + expect(countSubstring("a", "aaa")).toBe(3) + expect(countSubstring("a", "baaa")).toBe(3) + }) + + it("handles multiple characters", () => { + expect(countSubstring("foo", "foo")).toBe(1) + expect(countSubstring("foo", "bar")).toBe(0) + expect(countSubstring("foo", "foobar")).toBe(1) + expect(countSubstring("foo", "foobarbaz")).toBe(1) + expect(countSubstring("foo", "foobarbazfoo")).toBe(2) + expect(countSubstring("foo", "foobarbazfoof")).toBe(2) + }) + + it("does not handle overlapping substrings", () => { + expect(countSubstring("aa", "aaa")).toBe(1) + expect(countSubstring("aa", "aaaa")).toBe(2) + expect(countSubstring("aa", "aaaaa")).toBe(2) + expect(countSubstring("aa", "aaaaaa")).toBe(3) + }) +}) diff --git a/src/util.ts b/src/util.ts index 87707210..edcf56ec 100644 --- a/src/util.ts +++ b/src/util.ts @@ -120,3 +120,19 @@ export function expandPath(input: string): string { const userHome = os.homedir() return input.replace(/\${userHome}/g, userHome) } + +/** + * Return the number of times a substring appears in a string. + */ +export function countSubstring(needle: string, haystack: string): number { + if (needle.length < 1 || haystack.length < 1) { + return 0 + } + let count = 0 + let pos = haystack.indexOf(needle) + while (pos !== -1) { + count++ + pos = haystack.indexOf(needle, pos + needle.length) + } + return count +}