Skip to content

Commit

Permalink
make 'yarn tool preview' more friendly (#2727)
Browse files Browse the repository at this point in the history
  • Loading branch information
peterbe authored Jan 29, 2021
1 parent 3a200d6 commit d3d6d29
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions tool/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,16 +259,47 @@ program
)

.command("preview", "Open a preview of a slug")
.argument("<slug>", "Slug of the document in question")
.option("-p, --port <port>", "Port for your localhost hostname", {
default: PORT,
})
.option("-h, --hostname <hostname>", "Hostname for your local server", {
default: "localhost",
})
.argument("<slug>", "Slug (or path) of the document in question")
.argument("[locale]", "Locale", {
default: DEFAULT_LOCALE,
validator: [...VALID_LOCALES.values()],
})
.action(
tryOrExit(async ({ args }) => {
tryOrExit(async ({ args, options }) => {
const { slug, locale } = args;
const url = `http://localhost:${PORT}${buildURL(locale, slug)}`;
await open(url);
const { hostname, port } = options;
let url;
// Perhaps they typed in a path relative to the content root
if (slug.startsWith("files") && slug.endsWith("index.html")) {
const document = Document.read(
slug.split(path.sep).slice(1, -1).join(path.sep)
);
if (document) {
url = document.url;
}
} else {
try {
const parsed = new URL(slug);
url = parsed.pathname + parsed.hash;
} catch (err) {
// If the `new URL()` constructor fails, it's probably not a URL
}
if (!url) {
url = buildURL(locale, slug);
}
}

if (!url) {
throw new Error(`Unable to turn '${slug}' into an absolute URL`);
}
const absoluteURL = `http://${hostname}:${port}${url}`;
await open(absoluteURL);
})
)

Expand Down

0 comments on commit d3d6d29

Please sign in to comment.