diff --git a/src/openUrl.ts b/src/openUrl.ts new file mode 100644 index 0000000..99cb5b7 --- /dev/null +++ b/src/openUrl.ts @@ -0,0 +1,41 @@ +import { spawn } from "child_process"; + +function getCommandForPlatform(): string { + switch (process.platform) { + case "darwin": + return "open"; + case "win32": + return "explorer.exe"; + case "linux": + return "xdg-open"; + default: + return "open"; + } +} + +export async function openUrl(url: string): Promise { + return new Promise((resolve, reject) => { + const command = getCommandForPlatform(); + const child = spawn(command, [url]); + let errorText = ""; + + child.stderr.setEncoding("utf8"); + + child.stderr.on("data", function (data) { + errorText += data; + }); + + child.stderr.on("end", function () { + if (errorText.length > 0) { + const error = new Error(errorText); + reject(error); + } else { + resolve(); + } + }); + + child.on("error", (error) => { + reject(error); + }); + }); +} diff --git a/src/subcommands/login.ts b/src/subcommands/login.ts index f58eedf..469e2af 100644 --- a/src/subcommands/login.ts +++ b/src/subcommands/login.ts @@ -3,6 +3,7 @@ import chalk from "chalk"; import { boolean, command, flag, option, optional, string } from "cmd-ts"; import { createClient, createClientArgs } from "../createClient.js"; import { createLogger, logLevelArgs } from "../logLevel.js"; +import { openUrl } from "../openUrl.js"; export const login = command({ name: "login", @@ -69,9 +70,20 @@ export const login = command({ } let askedToAuthenticate = false; await client.repository.ensureAuthenticated({ - onAuthenticationUrl: url => { + onAuthenticationUrl: async url => { askedToAuthenticate = true; - logger.info("Please visit the following URL to authenticate:"); + + try { + await openUrl(url); + logger.infoText` + Opening browser for authentication... + If a browser window does not open automatically, visit the following URL directly: + ` + ; + } catch { + logger.info("Please visit the following URL to authenticate:"); + } + logger.info(); logger.info(chalk.greenBright(` ${url}`)); logger.info();