Typescriptify main.js

This commit is contained in:
Scott Nonnenberg 2021-10-01 11:49:59 -07:00 committed by GitHub
parent e033fd2cf3
commit 9a1430a460
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 721 additions and 524 deletions

View file

@ -5,19 +5,21 @@
/* eslint-disable more/no-then */
/* eslint-disable no-console */
import * as path from 'path';
import * as fs from 'fs';
import { join } from 'path';
import { readdirSync, readFile, unlinkSync, writeFileSync } from 'fs';
import { BrowserWindow, app, ipcMain as ipc } from 'electron';
import pinoms from 'pino-multi-stream';
import pino from 'pino';
import * as mkdirp from 'mkdirp';
import * as _ from 'lodash';
import { compact, filter, flatten, map, pick, sortBy } from 'lodash';
import readFirstLine from 'firstline';
import { read as readLastLines } from 'read-last-lines';
import rimraf from 'rimraf';
import { createStream } from 'rotating-file-stream';
import { setLogAtLevel } from './log';
import type { LoggerType } from '../types/Logging';
import * as log from './log';
import { Environment, getEnvironment } from '../environment';
import {
@ -39,7 +41,7 @@ declare global {
}
}
let globalLogger: undefined | pinoms.Logger;
let globalLogger: undefined | pino.Logger;
let shouldRestart = false;
const isRunningFromConsole =
@ -49,13 +51,13 @@ const isRunningFromConsole =
export async function initialize(
getMainWindow: () => undefined | BrowserWindow
): Promise<pinoms.Logger> {
): Promise<LoggerType> {
if (globalLogger) {
throw new Error('Already called initialize!');
}
const basePath = app.getPath('userData');
const logPath = path.join(basePath, 'logs');
const logPath = join(basePath, 'logs');
mkdirp.sync(logPath);
try {
@ -73,7 +75,7 @@ export async function initialize(
}, 500);
}
const logFile = path.join(logPath, 'main.log');
const logFile = join(logPath, 'main.log');
const stream = createStream(logFile, {
interval: '1d',
rotate: 3,
@ -160,7 +162,7 @@ export async function initialize(
globalLogger = logger;
return logger;
return log;
}
async function deleteAllLogs(logPath: string): Promise<void> {
@ -189,7 +191,7 @@ async function cleanupLogs(logPath: string) {
try {
const remaining = await eliminateOutOfDateFiles(logPath, earliestDate);
const files = _.filter(remaining, file => !file.start && file.end);
const files = filter(remaining, file => !file.start && file.end);
if (!files.length) {
return;
@ -234,11 +236,11 @@ export function eliminateOutOfDateFiles(
end: boolean;
}>
> {
const files = fs.readdirSync(logPath);
const paths = files.map(file => path.join(logPath, file));
const files = readdirSync(logPath);
const paths = files.map(file => join(logPath, file));
return Promise.all(
_.map(paths, target =>
map(paths, target =>
Promise.all([readFirstLine(target), readLastLines(target, 2)]).then(
results => {
const start = results[0];
@ -253,7 +255,7 @@ export function eliminateOutOfDateFiles(
};
if (!file.start && !file.end) {
fs.unlinkSync(file.path);
unlinkSync(file.path);
}
return file;
@ -269,12 +271,12 @@ export async function eliminateOldEntries(
date: Readonly<Date>
): Promise<void> {
await Promise.all(
_.map(files, file =>
map(files, file =>
fetchLog(file.path).then(lines => {
const recent = _.filter(lines, line => new Date(line.time) >= date);
const text = _.map(recent, line => JSON.stringify(line)).join('\n');
const recent = filter(lines, line => new Date(line.time) >= date);
const text = map(recent, line => JSON.stringify(line)).join('\n');
return fs.writeFileSync(file.path, `${text}\n`);
return writeFileSync(file.path, `${text}\n`);
})
)
);
@ -283,16 +285,16 @@ export async function eliminateOldEntries(
// Exported for testing only.
export function fetchLog(logFile: string): Promise<Array<LogEntryType>> {
return new Promise((resolve, reject) => {
fs.readFile(logFile, { encoding: 'utf8' }, (err, text) => {
readFile(logFile, { encoding: 'utf8' }, (err, text) => {
if (err) {
return reject(err);
}
const lines = _.compact(text.split('\n'));
const data = _.compact(
const lines = compact(text.split('\n'));
const data = compact(
lines.map(line => {
try {
const result = _.pick(JSON.parse(line), ['level', 'time', 'msg']);
const result = pick(JSON.parse(line), ['level', 'time', 'msg']);
return isLogEntry(result) ? result : null;
} catch (e) {
return null;
@ -307,8 +309,8 @@ export function fetchLog(logFile: string): Promise<Array<LogEntryType>> {
// Exported for testing only.
export function fetchLogs(logPath: string): Promise<Array<LogEntryType>> {
const files = fs.readdirSync(logPath);
const paths = files.map(file => path.join(logPath, file));
const files = readdirSync(logPath);
const paths = files.map(file => join(logPath, file));
// creating a manual log entry for the final log result
const fileListEntry: LogEntryType = {
@ -318,11 +320,11 @@ export function fetchLogs(logPath: string): Promise<Array<LogEntryType>> {
};
return Promise.all(paths.map(fetchLog)).then(results => {
const data = _.flatten(results);
const data = flatten(results);
data.push(fileListEntry);
return _.sortBy(data, logEntry => logEntry.time);
return sortBy(data, logEntry => logEntry.time);
});
}
@ -351,12 +353,12 @@ function isProbablyObjectHasBeenDestroyedError(err: unknown): boolean {
// This blows up using mocha --watch, so we ensure it is run just once
if (!console._log) {
setLogAtLevel(logAtLevel);
log.setLogAtLevel(logAtLevel);
console._log = console.log;
console.log = _.partial(logAtLevel, LogLevel.Info);
console.log = log.info;
console._error = console.error;
console.error = _.partial(logAtLevel, LogLevel.Error);
console.error = log.error;
console._warn = console.warn;
console.warn = _.partial(logAtLevel, LogLevel.Warn);
console.warn = log.warn;
}