Skip to content
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

[1/] Improvement: Add utility functions for CLI improvements #15

Merged
merged 18 commits into from
Feb 5, 2024
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
5 changes: 5 additions & 0 deletions packages/cli/changelog/@unreleased/pr-15.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
type: improvement
improvement:
description: '[1/] Improvement: Add utility functions for CLI improvements'
links:
- https://github.com/palantir/osdk-ts/pull/15
3 changes: 2 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@osdk/gateway": "workspace:*",
"@osdk/generator": "workspace:*",
"@osdk/shared.net": "workspace:*",
"ajv": "^8.12.0",
"archiver": "^6.0.1",
"conjure-lite": "^0.3.3",
"consola": "^3.2.3",
Expand All @@ -52,7 +53,7 @@
"imports": {
"#net": "./src/net/index.mts"
},
"keywords": [ ],
"keywords": [],
"bin": {
"osdk": "./bin/osdk.mjs"
},
Expand Down
83 changes: 83 additions & 0 deletions packages/cli/src/util/autoVersion.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright 2023 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { execSync } from "node:child_process";
import { describe, expect, it, vi } from "vitest";
import { autoVersion } from "./autoVersion.js";

vi.mock("node:child_process");

describe("autoVersion", () => {
const execSyncMock = vi.mocked(execSync);

it("should return a valid SemVer version from git describe", async () => {
const validGitVersion = "1.2.3";
execSyncMock.mockReturnValue(validGitVersion);

const version = await autoVersion();
expect(version).toBe("1.2.3");

expect(execSyncMock).toHaveBeenCalledWith(
"git describe --tags --first-parent --dirty",
{ encoding: "utf8" },
);
});

it("should replace default prefix v from git describe output", async () => {
const validGitVersion = "v1.2.3";
execSyncMock.mockReturnValue(validGitVersion);
const version = await autoVersion();

expect(version).toBe("1.2.3");
expect(execSyncMock).toHaveBeenCalledWith(
"git describe --tags --first-parent --dirty",
{ encoding: "utf8" },
);
});

it("should replace the prefix from the found git tag", async () => {
const validGitVersion = "@[email protected]";
execSyncMock.mockReturnValue(validGitVersion);

const version = await autoVersion("@package@");

expect(version).toBe("1.2.3");
expect(execSyncMock).toHaveBeenCalledWith(
"git describe --tags --first-parent --dirty --match=\"/^@package@/*\"",
{ encoding: "utf8" },
);
});

it("should only replace the prefix if found at the start of the tag only", async () => {
const validGitVersion = "1.2.3-package";
execSyncMock.mockReturnValue(validGitVersion);

const version = await autoVersion("-package");

expect(version).toBe("1.2.3-package");
expect(execSyncMock).toHaveBeenCalledWith(
"git describe --tags --first-parent --dirty --match=\"/^-package/*\"",
{ encoding: "utf8" },
);
});

it("should throw an error if git describe returns a non-SemVer string", async () => {
const nonSemVerGitVersion = "not-semver";
execSyncMock.mockReturnValue(nonSemVerGitVersion);

await expect(autoVersion()).rejects.toThrow();
});
});
47 changes: 47 additions & 0 deletions packages/cli/src/util/autoVersion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright 2023 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { execSync } from "node:child_process";
import { isValidSemver } from "./isValidSemver.js";

/**
* Gets the version string using git describe. If the @param tagPrefix is empty, git describe will return the
* latest tag (without any filtering) and if the tag starts with "v", it will be removed.
* @param tagPrefix The prefix to use for matching against tags. Defaults to an empty string.
* @returns A promise that resolves to the version string.
* @throws An error if the version string is not SemVer compliant or if the version cannot be determined.
*/
export async function autoVersion(tagPrefix: string = ""): Promise<string> {
const matchRegExp = new RegExp(tagPrefix == "" ? "^v?" : `^${tagPrefix}`);
const matchClause = tagPrefix != "" ? ` --match="${matchRegExp}*"` : "";
try {
const gitVersion = execSync(
`git describe --tags --first-parent --dirty${matchClause}`,
{ encoding: "utf8" },
);
const version = gitVersion.trim().replace(matchRegExp, "");
if (!isValidSemver(version)) {
throw new Error(`The version string ${version} is not SemVer compliant.`);
}

return version;
// TODO(zka): Find out possible error messages from git describe and show specific messages.
} catch (error) {
zeyadkhaled marked this conversation as resolved.
Show resolved Hide resolved
throw new Error(
`Unable to determine the version automatically. Please supply a --version argument. ${error}`,
);
}
}
152 changes: 152 additions & 0 deletions packages/cli/src/util/config.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/*
* Copyright 2023 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { findUp } from "find-up";
import { promises as fsPromises } from "node:fs";
import { describe, expect, it, vi } from "vitest";
import { loadFoundryConfig } from "./config.js";

vi.mock("find-up");
vi.mock("node:fs");

describe("loadFoundryConfig", () => {
vi.mocked(findUp).mockResolvedValue("/path/foundry.config.json");

it("should load and parse the configuration file correctly", async () => {
const correctConfig = {
foundryUrl: "http://localhost",
site: {
application: "test-app",
directory: "/test/directory",
autoVersion: {
type: "git-describe",
},
},
};

vi.mocked(fsPromises.readFile).mockResolvedValue(
JSON.stringify(correctConfig),
);
await expect(loadFoundryConfig()).resolves.toEqual({
configFilePath: "/path/foundry.config.json",
foundryConfig: {
...correctConfig,
},
});
});

it("should throw an error if autoVersion type isn't allowed", async () => {
const inCorrectConfig = {
foundryUrl: "http://localhost",
site: {
application: "test-app",
directory: "/test/directory",
autoVersion: {
type: "invalid",
},
},
};

vi.mocked(fsPromises.readFile).mockResolvedValue(
JSON.stringify(inCorrectConfig),
);

await expect(loadFoundryConfig()).rejects.toThrow(
"Config file schema is invalid.",
);
});

it("should throw an error if autoVersion type is missing", async () => {
const inCorrectConfig = {
foundryUrl: "http://localhost",
site: {
application: "test-app",
directory: "/test/directory",
autoVersion: {},
},
};

vi.mocked(fsPromises.readFile).mockResolvedValue(
JSON.stringify(inCorrectConfig),
);

await expect(loadFoundryConfig()).rejects.toThrow(
"Config file schema is invalid.",
);
});

it("should throw an error if the configuration file cannot be read", async () => {
vi.mocked(fsPromises.readFile).mockRejectedValue(new Error("Read error"));

await expect(loadFoundryConfig()).rejects.toThrow(
"Couldn't read or parse config",
);
});

it("should throw an error if the site key isn't found", async () => {
const fakeConfig = {
foundryUrl: "http://localhost",
};

vi.mocked(fsPromises.readFile).mockResolvedValue(
JSON.stringify(fakeConfig),
);

await expect(loadFoundryConfig()).rejects.toThrow(
"Config file schema is invalid.",
);
});

it("should throw an error if the site configuration is missing required keys", async () => {
const fakeConfig = {
foundryUrl: "http://localhost",
site: {
directory: "/test/directory",
},
};

vi.mocked(fsPromises.readFile).mockResolvedValue(
JSON.stringify(fakeConfig),
);

await expect(loadFoundryConfig()).rejects.toThrow(
"Config file schema is invalid.",
);
});

it("should throw an error if foundryUrl isn't set on top level", async () => {
const fakeConfig = {
site: {
foundryUrl: "http://localhost",
directory: "/test/directory",
application: "test-app",
},
};

vi.mocked(fsPromises.readFile).mockResolvedValue(
JSON.stringify(fakeConfig),
);

await expect(loadFoundryConfig()).rejects.toThrow(
"Config file schema is invalid.",
);
});

it("should return undefined if the configuration file is not found", async () => {
vi.mocked(findUp).mockResolvedValue(undefined);
await expect(loadFoundryConfig()).resolves.toBeUndefined();
});
});
Loading
Loading