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

fix(cli-utils): Create directories in CLI when writing to non-existent paths #401

Merged
merged 3 commits into from
Sep 24, 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 .changeset/rotten-balloons-bow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gql.tada/cli-utils': patch
---

Create target directories if they don't exist and the CLI is trying to write to them.
28 changes: 26 additions & 2 deletions packages/cli-utils/src/commands/shared/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
import type { WriteStream } from 'node:tty';
import type { PathLike } from 'node:fs';
import { dirname } from 'node:path';
import * as fs from 'node:fs/promises';

/** Checks whether a directory exists on disk */
const directoryExists = async (file: PathLike): Promise<boolean> => {
try {
const stat = await fs.stat(file);
if (stat.isDirectory()) {
return true;
} else if (stat.isSymbolicLink()) {
return directoryExists(await fs.realpath(file));
} else {
return false;
}
} catch {
return false;
}
};

/** Checks whether a file exists on disk */
export const fileExists = (file: PathLike): Promise<boolean> =>
const fileExists = (file: PathLike): Promise<boolean> =>
fs
.stat(file)
.then((stat) => stat.isFile())
Expand Down Expand Up @@ -32,7 +49,14 @@ export const writeOutput = async (target: WriteTarget, contents: string): Promis
}
});
});
} else if (!(await fileExists(target))) {
}

const targetDirectory = dirname(typeof target !== 'string' ? await fs.realpath(target) : target);
if (!(await directoryExists(targetDirectory))) {
await fs.mkdir(targetDirectory, { recursive: true });
}

if (!(await fileExists(target))) {
// If the file doesn't exist, we can write directly, and not
// try-catch so the error falls through
await fs.writeFile(target, contents);
Expand Down
Loading