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

Exit code issues #43

Merged
merged 10 commits into from
May 18, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
4,748 changes: 2,303 additions & 2,445 deletions package-lock.json

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zeplin/cli",
"version": "1.0.2",
"version": "1.0.3",
"description": "Zeplin CLI",
"main": "./dist/src/app",
"types": "./dist/types/index",
Expand Down Expand Up @@ -31,28 +31,28 @@
},
"homepage": "https://github.com/zeplin/cli#readme",
"devDependencies": {
"@microsoft/api-documenter": "^7.7.2",
"@microsoft/api-extractor": "^7.7.0",
"@microsoft/api-documenter": "^7.8.0",
"@microsoft/api-extractor": "^7.8.0",
"@types/ci-info": "^2.0.0",
"@types/express": "^4.17.2",
"@types/fs-extra": "^8.0.0",
"@types/hapi__joi": "^16.0.3",
"@types/inquirer": "^6.5.0",
"@types/jest": "^24.0.18",
"@types/jest": "^25.2.1",
"@types/jsonwebtoken": "^8.3.4",
"@types/node": "^12.7.5",
"@types/update-notifier": "^2.5.0",
"@types/update-notifier": "^4.1.0",
"@types/url-join": "^4.0.0",
"@types/winston": "^2.4.4",
"@typescript-eslint/eslint-plugin": "^2.3.0",
"@typescript-eslint/parser": "^2.3.0",
"@zeplin/eslint-config": "^2.2.0",
"eslint": "^6.4.0",
"eslint-import-resolver-typescript": "^1.1.1",
"husky": "^3.0.5",
"jest": "^24.9.0",
"ts-jest": "^24.1.0",
"typescript": "^3.7.3"
"husky": "^4.2.5",
"jest": "^25.5.4",
"ts-jest": "^25.5.1",
"typescript": "^3.9.2"
},
"dependencies": {
"@hapi/joi": "^16.1.7",
Expand Down
4 changes: 3 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ function beforeCommand(): void {
pkg: {
name,
version
}
},
updateCheckInterval: 0,
shouldNotifyInNpmScript: true
});
un.notify();
}
Expand Down
8 changes: 3 additions & 5 deletions src/commands/connect/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,6 @@ const startDevServer = async (

const devServer = new ConnectDevServer(connectedBarrels);

await devServer.start(devModePort);

logger.info(chalk.green(`Development server is started.`));

if (devModeWatch) {
let componentFiles = getComponentFilePaths(connectedBarrels);

Expand Down Expand Up @@ -78,12 +74,14 @@ const startDevServer = async (
watcher.add(componentFiles);
} catch (error) {
logger.error(chalk.red(dedent`
Could not update components.
Could not update connected components.
${error}
`));
}
});
}

await devServer.listen(devModePort);
};

const upload = async (connectedBarrels: ConnectedBarrelComponents[]): Promise<void> => {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/connect/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const createPluginInstance = async (plugin: Plugin): Promise<ConnectPluginInstan
pluginInstance.name = plugin.name;

if (typeof pluginInstance.init === "function") {
logger.debug(`${plugin.name} has init method. Initializing with ${plugin.config}`);
logger.debug(`${plugin.name} has init method. Initializing with ${JSON.stringify(plugin.config)}`);
await pluginInstance.init({ config: plugin.config });
}

Expand Down
15 changes: 14 additions & 1 deletion src/commands/connect/server/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import chalk from "chalk";
import express from "express";
import { Server } from "http";
import { OK } from "http-status-codes";
Expand Down Expand Up @@ -29,7 +30,7 @@ export class ConnectDevServer {
}

start(port: number): Promise<Server> {
if (this.server && this.server.listening) {
if (this.server?.listening) {
return Promise.resolve(this.server);
}

Expand All @@ -55,6 +56,9 @@ export class ConnectDevServer {
this.server = app.listen(port)
.on("listening", () => {
logger.debug(`Started dev server on port ${port}`);

logger.info(chalk.green(`Development server is started.`));

resolve(this.server);
})
.on("error", (err: NodeJS.ErrnoException) => {
Expand Down Expand Up @@ -84,4 +88,13 @@ export class ConnectDevServer {
});
});
}
async listen(port: number): Promise<void> {
await this.start(port);
return new Promise((resolve): void => {
process.on("SIGINT", async () => {
await this.stop();
resolve();
});
});
}
}
31 changes: 13 additions & 18 deletions src/util/command.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import chalk from "chalk";
import dedent from "ts-dedent";
import os from "os";
import path from "path";
import { isVerbose } from "../util/env";
import { CLIError } from "../errors";
import logger from "../util/logger";
import logger, { loggerFinishAndExit } from "../util/logger";

const waitForLoggerAndExit = (exitCode = 0): Promise<void> =>
new Promise((resolve): void => {
logger.on("finish", () => {
resolve();
process.exit(exitCode);
});
});

const errorHandler = (error: Error): void => {
const errorHandler = (error: Error): Promise<never> => {
if (isVerbose()) {
logger.error(`\n${chalk.redBright(error.stack)}`);
} else {
Expand All @@ -24,25 +18,26 @@ const errorHandler = (error: Error): void => {
const errorDetails = JSON.stringify(error.details);
if (isVerbose()) {
logger.error(chalk.redBright(dedent`
Details:
${errorDetails}`));
Details:
${errorDetails}`));
} else {
logger.debug(`${errorDetails}`);
}
}
logger.info(`\nPlease check ${chalk.dim("~/.zeplin/cli.log")} for details.\n`);

waitForLoggerAndExit(1);
const logFile = path.join(os.homedir(), ".zeplin", "cli.log");
logger.info(`\nPlease check ${chalk.dim(logFile)} for details.\n`);

return loggerFinishAndExit(1);
};

type FunctionReturnsPromise = (...args: Array<any>) => Promise<void>;

function commandRunner(fn: FunctionReturnsPromise): FunctionReturnsPromise {
return async (...args: Array<any>): Promise<void> => {
await fn(...args)
.then(() => waitForLoggerAndExit())
return (...args: Array<any>): Promise<void> =>
fn(...args)
yuqu marked this conversation as resolved.
Show resolved Hide resolved
.then(() => loggerFinishAndExit())
.catch(errorHandler);
};
}

export { commandRunner };
80 changes: 53 additions & 27 deletions src/util/logger.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,63 @@
import winston, { format } from "winston";
import os from "os";
import stripAnsi from "strip-ansi";
import { EventEmitter } from "events";

const fileTransport = new winston.transports.File({
level: "silly",
filename: "cli.log",
maxsize: 1048576, // 1 MB
maxFiles: 2,
dirname: `${os.homedir()}/.zeplin`,
tailable: true,
format: format.combine(
format.timestamp({
format: "YYYY-MM-DD HH:mm:ss"
}),
format.errors({ stack: true }),
format.splat(),
format.printf(m =>
stripAnsi(`${m.timestamp} - ${m.level} - ${m.message}${m.stack ? `\n${m.stack}` : ""}`)
.replace(/\r?\n/g, "")
)
)
});

const consoleTransport = new winston.transports.Console({
level: "info",
stderrLevels: ["error"],
format: format.combine(
format.splat(),
format.printf(m => `${m.message}`)
)
});

const logger = winston.createLogger({
transports: [
new winston.transports.File({
level: "silly",
filename: "cli.log",
maxsize: 1048576, // 1 MB
maxFiles: 2,
dirname: `${os.homedir()}/.zeplin`,
tailable: true,
format: format.combine(
format.timestamp({
format: "YYYY-MM-DD HH:mm:ss"
}),
format.errors({ stack: true }),
format.splat(),
format.printf(m =>
stripAnsi(`${m.timestamp} - ${m.level} - ${m.message}${m.stack ? `\n${m.stack}` : ""}`)
.replace(/\r?\n/g, "")
)
)
}),
new winston.transports.Console({
level: "info",
stderrLevels: ["error"],
format: format.combine(
format.splat(),
format.printf(m => `${m.message}`)
)
})
fileTransport,
consoleTransport
]
});

// Workaround to ensure all logs are written into the file before process exit
const fileLogWatcher = new EventEmitter();
fileTransport.on("open", () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
// eslint-disable-next-line no-underscore-dangle
fileTransport._dest.on("finish", () => {
fileLogWatcher.emit("finish");
});
});

const loggerFinishAndExit = (exitCode = 0): Promise<never> => new Promise((): void => {
fileLogWatcher.on("finish", (): void => {
process.exit(exitCode);
yuqu marked this conversation as resolved.
Show resolved Hide resolved
});
logger.end();
});

export default logger;
export {
loggerFinishAndExit
};