Skip to content

Commit

Permalink
feat: deprecate PathRef in favour of Path
Browse files Browse the repository at this point in the history
  • Loading branch information
dsherret committed Feb 4, 2024
1 parent 1d88634 commit 9ce1260
Show file tree
Hide file tree
Showing 9 changed files with 237 additions and 219 deletions.
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ await $`echo 1 && (echo 2 > ${buffer}) && echo 3`; // 1\n3\n
console.log(buffer); // Uint8Array(2) [ 50, 10 ] (2\n)
```

Supported objects: `Uint8Array`, `PathRef`, `WritableStream`, function that returns a `WritableStream`, any object that implements `[$.symbols.writable](): WritableStream`
Supported objects: `Uint8Array`, `Path`, `WritableStream`, function that returns a `WritableStream`, any object that implements `[$.symbols.writable](): WritableStream`

Or input redirects:

Expand All @@ -208,7 +208,7 @@ const request = $.request("https://plugins.dprint.dev/info.json")
const bytes = await $`sleep 5 && gzip < ${request}`.bytes();
```

Supported objects: `string`, `Uint8Array`, `PathRef`, `RequestBuilder`, `ReadableStream`, function that returns a `ReadableStream`, any object that implements `[$.symbols.readable](): ReadableStream`
Supported objects: `string`, `Uint8Array`, `Path`, `RequestBuilder`, `ReadableStream`, function that returns a `ReadableStream`, any object that implements `[$.symbols.readable](): ReadableStream`

### Providing stdin

Expand Down Expand Up @@ -573,10 +573,10 @@ pb.with(() => {

## Path API

The path API offers an immutable [`PathRef`](https://deno.land/x/dax/src/path.ts?s=PathRef) class, which is a similar concept to Rust's `PathBuf` struct.
The path API offers an immutable [`Path`](https://deno.land/x/dax/src/path.ts?s=Path) class, which is a similar concept to Rust's `PathBuf` struct.

```ts
// create a `PathRef`
// create a `Path`
let srcDir = $.path("src");
// get information about the path
srcDir.isDirSync(); // false
Expand Down Expand Up @@ -610,7 +610,7 @@ const srcDir = $.path("src").resolve();
await $`echo ${srcDir}`;
```

`PathRef`s can be created in the following ways:
`Path`s can be created in the following ways:

```ts
const pathRelative = $.path("./relative");
Expand All @@ -620,7 +620,7 @@ const pathStringFileUrl = $.path("file:///tmp"); // converts to /tmp
const pathImportMeta = $.path(import.meta); // the path for the current module
```

There are a lot of helper methods here, so check the [documentation on PathRef](https://deno.land/x/dax/src/path.ts?s=PathRef) for more details.
There are a lot of helper methods here, so check the [documentation on Path](https://deno.land/x/dax/src/path.ts?s=Path) for more details.

## Helper functions

Expand Down
19 changes: 17 additions & 2 deletions mod.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { readAll, readerFromStreamReader } from "./src/deps.ts";
import $, { build$, CommandBuilder, CommandContext, CommandHandler, KillSignal, KillSignalController } from "./mod.ts";
import $, {
build$,
CommandBuilder,
CommandContext,
CommandHandler,
KillSignal,
KillSignalController,
Path,
PathRef,
} from "./mod.ts";
import {
assert,
assertEquals,
Expand Down Expand Up @@ -810,7 +819,7 @@ Deno.test("piping to stdin", async (t) => {
assertEquals(result, "1\n2");
});

await t.step("PathRef", async () => {
await t.step("Path", async () => {
await using tempDir = usingTempDir();
const tempFile = tempDir.join("temp_file.txt");
const fileText = "1 testing this out\n".repeat(1_000);
Expand Down Expand Up @@ -2099,6 +2108,12 @@ Deno.test("should support empty quoted string", async () => {
assertEquals(output, " test ");
});

Deno.test("esnure deprecated PathRef export still works", () => {
const path = new PathRef("hello");
assert(path instanceof Path);
assert(path instanceof PathRef);
});

function ensurePromiseNotResolved(promise: Promise<unknown>) {
return new Promise<void>((resolve, reject) => {
promise.then(() => reject(new Error("Promise was resolved")));
Expand Down
23 changes: 13 additions & 10 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,14 @@ import {
import { colors, outdent, which, whichSync } from "./src/deps.ts";
import { wasmInstance } from "./src/lib/mod.ts";
import { RequestBuilder, withProgressBarFactorySymbol } from "./src/request.ts";
import { createPathRef, PathRef } from "./src/path.ts";
import { createPath, Path } from "./src/path.ts";

export type { Delay, DelayIterator } from "./src/common.ts";
export { TimeoutError } from "./src/common.ts";
export { FsFileWrapper, PathRef } from "./src/path.ts";
export { FsFileWrapper, Path } from "./src/path.ts";
/** @deprecated Import `Path` instead. */
const PathRef = Path;
export { PathRef };
export type { ExpandGlobOptions, PathSymlinkOptions, SymlinkOptions, WalkEntry, WalkOptions } from "./src/path.ts";
export {
CommandBuilder,
Expand Down Expand Up @@ -201,7 +204,7 @@ export interface $BuiltInProperties<TExtras extends ExtrasObject = {}> {
options?: Create$Options<TNewExtras>,
): $Type<Omit<TExtras, keyof TNewExtras> & TNewExtras>;
/** Changes the directory of the current process. */
cd(path: string | URL | ImportMeta | PathRef): void;
cd(path: string | URL | ImportMeta | Path): void;
/**
* Escapes an argument for the shell when NOT using the template
* literal.
Expand Down Expand Up @@ -259,9 +262,9 @@ export interface $BuiltInProperties<TExtras extends ExtrasObject = {}> {
/** Helper function for creating path references, which provide an easier way for
* working with paths, directories, and files on the file system.
*
* The function creates a new `PathRef` from a path or URL string, file URL, or for the current module.
* The function creates a new `Path` from a path or URL string, file URL, or for the current module.
*/
path: typeof createPathRef;
path: typeof createPath;
/**
* Logs with potential indentation (`$.logIndent`)
* and output of commands or request responses.
Expand Down Expand Up @@ -541,11 +544,11 @@ async function withRetries<TReturn>(
throw new Error(`Failed after ${opts.count} attempts.`);
}

function cd(path: string | URL | ImportMeta | PathRef) {
function cd(path: string | URL | ImportMeta | Path) {
if (typeof path === "string" || path instanceof URL) {
path = new PathRef(path);
} else if (!(path instanceof PathRef)) {
path = new PathRef(path satisfies ImportMeta).parentOrThrow();
path = new Path(path);
} else if (!(path instanceof Path)) {
path = new Path(path satisfies ImportMeta).parentOrThrow();
}
Deno.chdir(path.toString());
}
Expand Down Expand Up @@ -581,7 +584,7 @@ function buildInitial$State<TExtras extends ExtrasObject>(
}

const helperObject = {
path: createPathRef,
path: createPath,
cd,
escapeArg,
stripAnsi(text: string) {
Expand Down
14 changes: 7 additions & 7 deletions src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
} from "./pipes.ts";
import { parseCommand, spawn } from "./shell.ts";
import { isShowingProgressBars } from "./console/progress/interval.ts";
import { PathRef } from "./path.ts";
import { Path } from "./path.ts";
import { RequestBuilder } from "./request.ts";
import { StreamFds } from "./shell.ts";
import { symbols } from "./common.ts";
Expand Down Expand Up @@ -305,7 +305,7 @@ export class CommandBuilder implements PromiseLike<CommandResult> {
state.stdin = reader;
} else if (reader instanceof Uint8Array) {
state.stdin = new Deferred(() => new Buffer(reader));
} else if (reader instanceof PathRef) {
} else if (reader instanceof Path) {
state.stdin = new Deferred(async () => {
const file = await reader.open();
return file.readable;
Expand Down Expand Up @@ -416,11 +416,11 @@ export class CommandBuilder implements PromiseLike<CommandResult> {
}

/** Sets the current working directory to use when executing this command. */
cwd(dirPath: string | URL | PathRef): CommandBuilder {
cwd(dirPath: string | URL | Path): CommandBuilder {
return this.#newWithState((state) => {
state.cwd = dirPath instanceof URL
? path.fromFileUrl(dirPath)
: dirPath instanceof PathRef
: dirPath instanceof Path
? dirPath.resolve().toString()
: path.resolve(dirPath);
});
Expand Down Expand Up @@ -869,7 +869,7 @@ export function parseAndSpawnCommand(state: CommandBuilderState) {

function getOutputBuffer(inheritWriter: WriterSync, { kind, options }: ShellPipeWriterKindWithOptions) {
if (typeof kind === "object") {
if (kind instanceof PathRef) {
if (kind instanceof Path) {
const file = kind.openSync({ write: true, truncate: true, create: true });
disposables.push(file);
return file;
Expand Down Expand Up @@ -1252,7 +1252,7 @@ function templateInner(
const expr = exprs[i];
const inputOrOutputRedirect = detectInputOrOutputRedirect(text);
if (inputOrOutputRedirect === "<") {
if (expr instanceof PathRef) {
if (expr instanceof Path) {
text += templateLiteralExprToString(expr, escape);
} else if (typeof expr === "string") {
handleReadableStream(() =>
Expand Down Expand Up @@ -1312,7 +1312,7 @@ function templateInner(
throw new Error("Unsupported object provided to input redirect.");
}
} else if (inputOrOutputRedirect === ">") {
if (expr instanceof PathRef) {
if (expr instanceof Path) {
text += templateLiteralExprToString(expr, escape);
} else if (expr instanceof WritableStream) {
handleWritableStream(() => expr);
Expand Down
12 changes: 6 additions & 6 deletions src/deps.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createPathRef, PathRef } from "./path.ts";
import { createPath, Path } from "./path.ts";

export {
assert,
Expand All @@ -16,16 +16,16 @@ export { isNode } from "https://deno.land/x/[email protected]/mod.ts";
* Creates a temporary directory, changes the cwd to this directory,
* then cleans up and restores the cwd when complete.
*/
export async function withTempDir(action: (path: PathRef) => Promise<void> | void) {
export async function withTempDir(action: (path: Path) => Promise<void> | void) {
await using dirPath = usingTempDir();
await action(createPathRef(dirPath).resolve());
await action(createPath(dirPath).resolve());
}

export function usingTempDir(): PathRef & AsyncDisposable {
export function usingTempDir(): Path & AsyncDisposable {
const originalDirPath = Deno.cwd();
const dirPath = Deno.makeTempDirSync();
Deno.chdir(dirPath);
const pathRef = createPathRef(dirPath).resolve();
const pathRef = createPath(dirPath).resolve();
(pathRef as any)[Symbol.asyncDispose] = async () => {
try {
await Deno.remove(dirPath, { recursive: true });
Expand All @@ -34,5 +34,5 @@ export function usingTempDir(): PathRef & AsyncDisposable {
}
Deno.chdir(originalDirPath);
};
return pathRef as PathRef & AsyncDisposable;
return pathRef as Path & AsyncDisposable;
}
Loading

0 comments on commit 9ce1260

Please sign in to comment.