Skip to content

Can you get the version from package.json? #200

@ysknsid25

Description

@ysknsid25

Describe the feature

Currently, if the version cannot be obtained, an exception is thrown.

https://github.com/ysknsid25/citty/blob/7de2a6c39ec0876e0b0ecf5f07e7d2997591123e/src/main.ts#L23-L27

      const meta =
        typeof cmd.meta === "function" ? await cmd.meta() : await cmd.meta;
      if (!meta?.version) {
        throw new CLIError("No version specified", "E_NO_VERSION");
      }

Users can also define their own functions to obtain the version by using cmd.meta().

However, if we provide an option on the citty side to retrieve package.json and get the version written there, it would reduce the chances of users writing the same function 🤔

The implementation to retrieve package.json has already been implemented by an OSS called Secretlint.

https://github.com/secretlint/secretlint/blob/0bb5cbda7ac920acd4b24e354ec3167eabe6afc3/packages/%40secretlint/resolver/src/index.ts#L128-L167

/**
 * get package.json content from startDir
 * @param cwd
 * @returns package.json content
 */
export const getPackageJson = (cwd: string) => {
    try {
        const startDir = path.dirname(url.fileURLToPath(cwd));
        const packageJsonPath = findPackageJson(startDir);
        if (packageJsonPath) {
            return require(packageJsonPath);
        }
        return undefined;
    } catch (error) {
        // ignore error
        return undefined;
    }
};

/**
 * search package.json from startDir
 * @param startDir
 * @returns
 */
const findPackageJson = (startDir: string): string => {
    let currentDir = startDir;
    while (true) {
        const packageJsonPath = path.join(currentDir, "package.json");
        if (fs.existsSync(packageJsonPath)) {
            return packageJsonPath;
        }

        const parentDir = path.resolve(currentDir, "..");
        if (parentDir === currentDir) {
            return "";
        }

        currentDir = parentDir;
    }
};

(cdw=import.meta.url)

Furthermore, if there is already an implementation to get package.json in another library called Secretlint, might there be a demand for making this process itself a separate module from citty?

Please consider 🙏

Additional information

  • Would you be willing to help implement this feature?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions