Skip to content

Commit

Permalink
feat: add service credential file handling and tests for CredentialsS…
Browse files Browse the repository at this point in the history
…torage
  • Loading branch information
spirulence committed Dec 2, 2024
1 parent b0dae1b commit 346f241
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 3 deletions.
17 changes: 14 additions & 3 deletions apps/cli/src/credentials-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,25 @@ export enum CredentialsStorageType {
ACCOUNT = "user-account",
}

async function findServiceCredentialFiles(service: string): Promise<string[]> {
try {
return await readdir(codemodDirectoryPath).then((dir) =>
dir.filter((file) => file.startsWith(`${service}:`)),
);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
throw error;
}
return [];
}
}

const keytarShim = {
default: {
setPassword: async (service: string, account: string, password: string) =>
writeFile(join(codemodDirectoryPath, `${service}:${account}`), password),
findCredentials: async (service: string) => {
const entries = await readdir(codemodDirectoryPath).then((dir) =>
dir.filter((file) => file.startsWith(`${service}:`)),
);
const entries = await findServiceCredentialFiles(service);

return Promise.all(
entries.map(async (file) => ({
Expand Down
49 changes: 49 additions & 0 deletions apps/cli/test/credentialsStorage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { fs, type DirectoryJSON, vol } from "memfs";
import { beforeEach, describe, expect, it, vi } from "vitest";

// Mock all fs promises functions
vi.mock("node:fs/promises", () => fs.promises);

// Use a mock homedir in order to reliably have a memfs home directory
vi.mock("node:os", () => ({ homedir: () => "/home/codemod-test/" }));

import {
CredentialsStorage,
CredentialsStorageType,
} from "../src/credentials-storage.js";

describe("CredentialsStorage", () => {
const testService = "codemod.com-test";
const testAccount = CredentialsStorageType.ACCOUNT;
const testPassword = "test-password";

describe("when .codemod directory does not exist", () => {
beforeEach(() => {
vol.reset();
});

it("should return null without throwing an error", async () => {
const storage = new CredentialsStorage();
const result = await storage.get(testAccount);

expect(result).toBeNull();
});
});

describe("when .codemod directory exists", () => {
beforeEach(() => {
vol.reset();
const directory: DirectoryJSON = {
[`${testService}:${testAccount}`]: testPassword,
};
vol.fromJSON(directory, "/home/codemod-test/.codemod");
});

it("should retrieve existing credentials", async () => {
const storage = new CredentialsStorage();
const result = await storage.get(testAccount);

expect(result).toBe(testPassword);
});
});
});

0 comments on commit 346f241

Please sign in to comment.