Skip to content

Commit cf367bf

Browse files
authored
Fix bug with reading package.json from any folder (#10)
* set single quote style * fix reading version from package.json did only work when cwd was specific folder Fixes #8
1 parent a8b06aa commit cf367bf

File tree

9 files changed

+132
-106
lines changed

9 files changed

+132
-106
lines changed

cli.js

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
11
#!/usr/bin/env node
2-
import { existsSync } from "fs";
3-
import { mkdir, writeFile } from "fs/promises";
4-
import minimist from "minimist";
5-
import pc from "picocolors";
6-
import { DATA_DIR, resolvePath, readFile, pkgVersion } from "./src/utils.js";
7-
import { createCertificate } from "./src/index.js";
2+
import { existsSync } from 'fs';
3+
import { mkdir, writeFile } from 'fs/promises';
4+
import minimist from 'minimist';
5+
import pc from 'picocolors';
6+
import { DATA_DIR, resolvePath, readFile, pkgVersion } from './src/utils.js';
7+
import { createCertificate } from './src/index.js';
88

99
/**
1010
* Init, read variables and create folders
1111
*/
1212
const defaults = {
13-
dir: resolvePath("certs", DATA_DIR),
13+
dir: resolvePath('certs', DATA_DIR),
1414
key: 'dev.key',
15-
cert: 'dev.cert'
16-
}
15+
cert: 'dev.cert',
16+
};
1717

1818
const argv = minimist(process.argv.slice(2));
1919
const cwd = process.cwd();
@@ -26,7 +26,6 @@ if (argv.version) {
2626

2727
// Display help and exit
2828
if (argv.h || argv.help) {
29-
3029
console.log(`
3130
${pc.bold('Usage')}
3231
$ npx mkcert-cli <options>
@@ -54,31 +53,29 @@ const verbose = argv.v ?? false;
5453
const host = argv.host;
5554
const force = (argv.force || argv.f) ?? false;
5655
const autoUpgrade = (argv.upgrade || argv.u) ?? false;
57-
const outDir = (argv.outDir || argv.o) ? resolvePath(argv.outDir || argv.o, cwd) : defaults.dir;
58-
const hosts = host
59-
? Array.isArray(host)
60-
? host
61-
: [host]
62-
: [];
56+
const outDir = argv.outDir || argv.o ? resolvePath(argv.outDir || argv.o, cwd) : defaults.dir;
57+
const hosts = host ? (Array.isArray(host) ? host : [host]) : [];
6358
const certFile = (argv.c || argv.cert) ?? defaults.cert;
6459
const keyFile = (argv.k || argv.key) ?? defaults.key;
6560
const certFilePath = resolvePath(certFile, outDir);
6661
const keyFilePath = resolvePath(keyFile, outDir);
6762
const dryRun = (argv.d || argv.dryRun) ?? false;
6863

69-
console.log(`\nRunning ${pc.green(`${pc.bold("mkcert-cli")}`)} (${pkgVersion})\n`);
64+
console.log(`\nRunning ${pc.green(`${pc.bold('mkcert-cli')}`)} (${pkgVersion})\n`);
7065

7166
(dryRun || verbose) &&
72-
console.log(`${pc.bold("With options:")}
73-
- ${pc.blue("cwd")}: ${pc.yellow(cwd)}
74-
- ${pc.blue("outDir")}: ${pc.yellow(outDir)}
75-
- ${pc.blue("hosts")}: ${JSON.stringify(hosts)}
76-
- ${pc.blue("cert")}: ${certFile}
77-
- ${pc.blue("key")}: ${keyFile}
78-
- ${pc.blue("force")}: ${force}
79-
- ${pc.blue("autoUpgrade")}: ${autoUpgrade}
67+
console.log(`${pc.bold('With options:')}
68+
- ${pc.blue('cwd')}: ${pc.yellow(cwd)}
69+
- ${pc.blue('outDir')}: ${pc.yellow(outDir)}
70+
- ${pc.blue('hosts')}: ${JSON.stringify(hosts)}
71+
- ${pc.blue('cert')}: ${certFile}
72+
- ${pc.blue('key')}: ${keyFile}
73+
- ${pc.blue('force')}: ${force}
74+
- ${pc.blue('autoUpgrade')}: ${autoUpgrade}
8075
`);
81-
if (dryRun) { process.exit() }
76+
if (dryRun) {
77+
process.exit();
78+
}
8279

8380
if (!existsSync(outDir)) {
8481
await mkdir(outDir, { recursive: true });
@@ -90,9 +87,7 @@ if (!existsSync(outDir)) {
9087
const filesExist = existsSync(certFilePath) && existsSync(keyFilePath);
9188
const writeFiles = force || !filesExist;
9289
if (!writeFiles) {
93-
console.log(`🎉 Files "${pc.magenta(certFile)}" and "${pc.magenta(
94-
keyFile
95-
)}" already exist
90+
console.log(`🎉 Files "${pc.magenta(certFile)}" and "${pc.magenta(keyFile)}" already exist
9691
in ${pc.yellow(outDir)}`);
9792
process.exit(0);
9893
}
@@ -104,8 +99,8 @@ try {
10499
keyFilePath,
105100
certFilePath,
106101
});
107-
await writeFile(keyFilePath, key, { encoding: "utf-8" });
108-
await writeFile(certFilePath, cert, { encoding: "utf-8" });
102+
await writeFile(keyFilePath, key, { encoding: 'utf-8' });
103+
await writeFile(certFilePath, cert, { encoding: 'utf-8' });
109104
} catch (/** @type {any}*/ writeErr) {
110105
console.error(writeErr.toString());
111106
process.exit(1);

rome.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44
"indentStyle": "space",
55
"lineWidth": 120
66
},
7+
"javascript": {
8+
"formatter": {
9+
"quoteStyle": "single"
10+
}
11+
},
712
"linter": {
813
"enabled": true,
914
"rules": {

src/index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { Mkcert } from "./mkcert/mkcert.js";
2-
import { getDefaultHosts } from "./utils.js";
1+
import { Mkcert } from './mkcert/mkcert.js';
2+
import { getDefaultHosts } from './utils.js';
33

44
/**
55
* @param {string[]=} hosts

src/mkcert/downloader.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { writeFile } from "../utils.js";
2-
import { request } from "../request.js";
1+
import { writeFile } from '../utils.js';
2+
import { request } from '../request.js';
33

44
export class Downloader {
55
constructor() {}
@@ -9,12 +9,12 @@ export class Downloader {
99
* @param {string} savedPath
1010
*/
1111
async download(downloadUrl, savedPath) {
12-
console.log("Downloading the mkcert executable from %s", downloadUrl);
12+
console.log('Downloading the mkcert executable from %s', downloadUrl);
1313

14-
const data = await request(downloadUrl, {}, "arrayBuffer");
14+
const data = await request(downloadUrl, {}, 'arrayBuffer');
1515

1616
await writeFile(savedPath, data);
1717

18-
console.log("The mkcert has been saved to %s", savedPath);
18+
console.log('The mkcert has been saved to %s', savedPath);
1919
}
2020
}

src/mkcert/mkcert.js

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { exec, existsSync, readFile, resolvePath, wrapInQuotes, semverGreaterThan, ensureDirExist } from "../utils.js";
1+
import { exec, existsSync, readFile, resolvePath, wrapInQuotes, semverGreaterThan, ensureDirExist } from '../utils.js';
22

3-
import { Downloader } from "./downloader.js";
4-
import { GithubSource } from "./source.js";
3+
import { Downloader } from './downloader.js';
4+
import { GithubSource } from './source.js';
55

66
export class Mkcert {
77
force;
@@ -28,7 +28,7 @@ export class Mkcert {
2828

2929
this.source = new GithubSource();
3030

31-
this.mkcertSavedPath = resolvePath(process.platform === "win32" ? "mkcert.exe" : "mkcert");
31+
this.mkcertSavedPath = resolvePath(process.platform === 'win32' ? 'mkcert.exe' : 'mkcert');
3232
}
3333

3434
async getMkcertBinary() {
@@ -56,7 +56,7 @@ export class Mkcert {
5656
* @param {string[]} hosts
5757
*/
5858
async createCertificate(hosts) {
59-
const names = hosts.join(" ");
59+
const names = hosts.join(' ');
6060

6161
const mkcertBinary = await this.getMkcertBinary();
6262

@@ -83,7 +83,7 @@ export class Mkcert {
8383
const mkcertBinary = await this.getMkcertBinary();
8484

8585
if (!mkcertBinary) {
86-
console.error("Mkcert does not exist, unable to get current version...");
86+
console.error('Mkcert does not exist, unable to get current version...');
8787
return null;
8888
}
8989

@@ -119,32 +119,32 @@ export class Mkcert {
119119
const sourceInfo = await this.source.getSourceInfo();
120120

121121
if (!sourceInfo) {
122-
console.error("Failed to request mkcert information, please check your network");
122+
console.error('Failed to request mkcert information, please check your network');
123123
return undefined;
124124
}
125125

126-
console.log("getSourceInfo", sourceInfo);
126+
console.log('getSourceInfo', sourceInfo);
127127
return sourceInfo;
128128
}
129129
async initMkcert() {
130130
const sourceInfo = await this.getSourceInfo();
131131

132-
console.log("The mkcert does not exist, download it now");
132+
console.log('The mkcert does not exist, download it now');
133133

134134
if (!sourceInfo) {
135-
console.error("Can not obtain download information of mkcert, init skipped");
135+
console.error('Can not obtain download information of mkcert, init skipped');
136136
return;
137137
}
138138

139139
await this.downloadMkcert(sourceInfo.downloadUrl, this.mkcertSavedPath);
140140
}
141141

142142
async upgradeMkcert() {
143-
console.log("Upgrade mkcert...");
143+
console.log('Upgrade mkcert...');
144144
const sourceInfo = await this.getSourceInfo();
145145

146146
if (!sourceInfo) {
147-
console.error("Can not obtain download information of mkcert, update skipped");
147+
console.error('Can not obtain download information of mkcert, update skipped');
148148
return;
149149
}
150150

@@ -153,7 +153,7 @@ export class Mkcert {
153153
if (shouldUpgrade) {
154154
await this.downloadMkcert(sourceInfo.downloadUrl, this.mkcertSavedPath);
155155
} else {
156-
console.log("Already at latest version: ", current);
156+
console.log('Already at latest version: ', current);
157157
}
158158
}
159159

@@ -172,7 +172,7 @@ export class Mkcert {
172172
*/
173173
async renew(hosts) {
174174
if (this.force || !(existsSync(this.CERT_FILE_PATH) && existsSync(this.KEY_FILE_PATH))) {
175-
console.log("Certificate is forced to regenerate");
175+
console.log('Certificate is forced to regenerate');
176176

177177
await this.regenerate(hosts);
178178
}

src/mkcert/source.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
1-
import { request } from "../request.js";
1+
import { request } from '../request.js';
22

33
const getPlatformIdentifier = () => {
44
switch (process.platform) {
5-
case "win32":
6-
return "windows-amd64.exe";
7-
case "linux":
8-
return process.arch === "arm64" ? "linux-arm64" : process.arch === "arm" ? "linux-arm" : "linux-amd64";
9-
case "darwin":
10-
return "darwin-amd64";
5+
case 'win32':
6+
return 'windows-amd64.exe';
7+
case 'linux':
8+
return process.arch === 'arm64' ? 'linux-arm64' : process.arch === 'arm' ? 'linux-arm' : 'linux-amd64';
9+
case 'darwin':
10+
return 'darwin-amd64';
1111
default:
12-
throw new Error("Unsupported platform");
12+
throw new Error('Unsupported platform');
1313
}
1414
};
1515

16-
const owner = "FiloSottile";
17-
const repo = "mkcert";
16+
const owner = 'FiloSottile';
17+
const repo = 'mkcert';
1818
const fetchLatestRelease = async () => {
1919
// -H "Authorization: Bearer <YOUR-TOKEN>" \
2020
/** @type {Promise<{ assets: Array<{name: string, browser_download_url: string}>, tag_name?: string }>} */
2121
const res = await request(
2222
`https://api.github.com/repos/${owner}/${repo}/releases/latest`,
23-
{ Accept: "application/vnd.github+json" },
24-
"json",
23+
{ Accept: 'application/vnd.github+json' },
24+
'json',
2525
);
2626
return res;
2727
};

src/request.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import https from "https";
2-
import { pkgVersion } from "./utils.js";
1+
import https from 'https';
2+
import { pkgVersion } from './utils.js';
33

44
const defaultHeaders = {
5-
Accept: "application/json, text/plain, */*",
6-
["User-Agent"]: `mkcert-cli/${pkgVersion}`,
5+
Accept: 'application/json, text/plain, */*',
6+
['User-Agent']: `mkcert-cli/${pkgVersion}`,
77
};
88
const MAX_REDIRECTS = 4;
99

@@ -14,7 +14,7 @@ const MAX_REDIRECTS = 4;
1414
* @param {'json' | 'arrayBuffer'} responseType
1515
* @returns {Promise<any>}
1616
*/
17-
export const request = async (url, customHeaders = {}, responseType = "json", _redirect = 0) => {
17+
export const request = async (url, customHeaders = {}, responseType = 'json', _redirect = 0) => {
1818
const headers = { ...defaultHeaders, ...customHeaders };
1919
return new Promise((resolve) => {
2020
/** @type {Uint8Array[]} */
@@ -31,19 +31,19 @@ export const request = async (url, customHeaders = {}, responseType = "json", _r
3131
resolve(response);
3232
}
3333

34-
res.on("data", (chunk) => {
34+
res.on('data', (chunk) => {
3535
responseBuffer.push(chunk);
36-
if (url.includes("/download/")) {
37-
console.log("on(data): ", chunk);
36+
if (url.includes('/download/')) {
37+
console.log('on(data): ', chunk);
3838
}
3939
});
40-
res.on("end", () => {
40+
res.on('end', () => {
4141
const arrayBuffer = Buffer.concat(responseBuffer);
4242
switch (responseType) {
43-
case "json": {
43+
case 'json': {
4444
return resolve(JSON.parse(arrayBuffer.toString()));
4545
}
46-
case "arrayBuffer": {
46+
case 'arrayBuffer': {
4747
return resolve(arrayBuffer);
4848
}
4949
}

0 commit comments

Comments
 (0)