Skip to content

Commit

Permalink
Lots of manual edits to appease linting
Browse files Browse the repository at this point in the history
  • Loading branch information
benjie committed Jan 18, 2024
1 parent 6890357 commit 3537613
Show file tree
Hide file tree
Showing 15 changed files with 140 additions and 70 deletions.
26 changes: 14 additions & 12 deletions src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Logger } from "@graphile/logger";
import { exec as rawExec } from "child_process";
import { promises as fsp } from "fs";
import { parse } from "pg-connection-string";
import { promisify } from "util";
import { inspect, promisify } from "util";

import { mergeWithoutClobbering } from "./lib";
import { generatePlaceholderReplacement } from "./migration";
Expand Down Expand Up @@ -127,13 +127,14 @@ export async function executeActions(
if (stderr) {
parsedSettings.logger.error(stderr);
}
} catch (e: any) {
const { stdout, stderr } = e;
if (stdout) {
parsedSettings.logger.info(stdout);
}
if (stderr) {
parsedSettings.logger.error(stderr);
} catch (e) {
if (typeof e === "object" && e !== null) {
if ("stdout" in e && typeof e.stdout === "string" && e.stdout) {
parsedSettings.logger.info(e.stdout);
}
if ("stderr" in e && typeof e.stderr === "string" && e.stderr) {
parsedSettings.logger.error(e.stderr);
}
}
throw e;
}
Expand All @@ -146,14 +147,15 @@ export function makeValidateActionCallback(logger: Logger, allowRoot = false) {
const specs: ActionSpec[] = [];
if (inputValue) {
const rawSpecArray = Array.isArray(inputValue)
? inputValue
? (inputValue as unknown[])
: [inputValue];
for (const trueRawSpec of rawSpecArray) {
// This fudge is for backwards compatibility with v0.0.3
const isV003OrBelowCommand =
typeof trueRawSpec === "object" &&
trueRawSpec &&
!trueRawSpec["_"] &&
trueRawSpec !== null &&
!("_" in trueRawSpec && trueRawSpec._) &&
"command" in trueRawSpec &&
typeof trueRawSpec["command"] === "string";
if (isV003OrBelowCommand) {
logger.warn(
Expand Down Expand Up @@ -181,7 +183,7 @@ export function makeValidateActionCallback(logger: Logger, allowRoot = false) {
specs.push(rawSpec);
} else {
throw new Error(
`Action spec of type '${rawSpec["_"]}' not supported; perhaps you need to upgrade?`,
`Action spec '${inspect(rawSpec)}' not supported; perhaps you need to upgrade?`,
);
}
} else {
Expand Down
14 changes: 11 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { runCommand } from "./commands/run";
import { statusCommand } from "./commands/status";
import { uncommitCommand } from "./commands/uncommit";
import { watchCommand } from "./commands/watch";
import { isLoggedError } from "./lib";
import { version } from "./version";

function wrapHandler<T1, T2>(
Expand All @@ -20,8 +21,8 @@ function wrapHandler<T1, T2>(
const newHandler: yargs.CommandModule<T1, T2>["handler"] = async (argv) => {
try {
return await Promise.resolve(handler(argv));
} catch (e: any) {
if (!e["_gmlogged"]) {
} catch (e) {
if (!isLoggedError(e)) {
// eslint-disable-next-line no-console
console.error(e);
}
Expand All @@ -35,7 +36,7 @@ function wrapHandler<T1, T2>(
};
}

yargs
const f = yargs
.parserConfiguration({
"boolean-negation": true,
"camel-case-expansion": false,
Expand Down Expand Up @@ -99,3 +100,10 @@ You are running graphile-migrate v${version}.
╚═══════════════════════════════════╝
`,
).argv;

if ("then" in f && typeof f.then === "function") {
f.then(null, (e: Error) => {
// eslint-disable-next-line no-console
console.error(e);
});
}
32 changes: 19 additions & 13 deletions src/commands/_common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { constants, promises as fsp } from "fs";
import * as JSON5 from "json5";
import { resolve } from "path";
import { parse } from "pg-connection-string";
import { pathToFileURL } from "url";

import { Settings } from "../settings";

Expand Down Expand Up @@ -33,13 +34,17 @@ export async function getSettingsFromJSON(path: string): Promise<Settings> {
let data;
try {
data = await fsp.readFile(path, "utf8");
} catch (e: any) {
throw new Error(`Failed to read '${path}': ${e.message}`);
} catch (e) {
throw new Error(
`Failed to read '${path}': ${e instanceof Error ? e.message : String(e)}`,
);
}
try {
return JSON5.parse(data);
} catch (e: any) {
throw new Error(`Failed to parse '${path}': ${e.message}`);
} catch (e) {
throw new Error(
`Failed to parse '${path}': ${e instanceof Error ? e.message : String(e)}`,
);
}
}

Expand All @@ -64,20 +69,21 @@ interface Options {
*/
export async function getSettings(options: Options = {}): Promise<Settings> {
const { configFile } = options;
const tryRequire = (path: string): Settings => {
const tryRequire = async (path: string): Promise<Settings> => {
// If the file is e.g. `foo.js` then Node `require('foo.js')` would look in
// `node_modules`; we don't want this - instead force it to be a relative
// path.
const relativePath = resolve(process.cwd(), path);
const relativePath = pathToFileURL(resolve(process.cwd(), path)).href;

try {
return require(relativePath);
} catch (e: any) {
return (await import(relativePath)) as Settings;
} catch (e) {
throw new Error(
`Failed to import '${relativePath}'; error:\n ${e.stack.replace(
/\n/g,
"\n ",
)}`,
`Failed to import '${relativePath}'; error:\n ${
e instanceof Error && e.stack
? e.stack.replace(/\n/g, "\n ")
: String(e)
}`,
);
}
};
Expand Down Expand Up @@ -120,7 +126,7 @@ export function readStdin(): Promise<string> {
process.stdin.on("readable", () => {
let chunk;
// Use a loop to make sure we read all available data.
while ((chunk = process.stdin.read()) !== null) {
while ((chunk = process.stdin.read() as string | null) !== null) {
data += chunk;
}
});
Expand Down
4 changes: 3 additions & 1 deletion src/commands/commit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ export async function _commit(
currentLocation,
parsedSettings.blankMigrationContent.trim() + "\n",
);
} catch (e: any) {
} catch (err) {
const e = err instanceof Error ? err : new Error(String(err));

logDbError(parsedSettings, e);

parsedSettings.logger.error("ABORTING...");
Expand Down
4 changes: 2 additions & 2 deletions src/commands/reset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ export async function _reset(
databaseName,
)} OWNER ${escapeIdentifier(databaseOwner)};`,
);
} catch (e: any) {
} catch (e) {
throw new Error(
`Failed to create database '${databaseName}' with owner '${databaseOwner}': ${e.message}`,
`Failed to create database '${databaseName}' with owner '${databaseOwner}': ${e instanceof Error ? e.message : String(e)}`,
);
}
await pgClient.query(
Expand Down
3 changes: 2 additions & 1 deletion src/commands/run.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { promises as fsp } from "fs";
import { QueryResultRow } from "pg";
import { CommandModule } from "yargs";

import { DO_NOT_USE_DATABASE_URL } from "../actions";
Expand All @@ -19,7 +20,7 @@ interface RunArgv extends CommonArgv {
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function run<T = any>(
export async function run<T extends QueryResultRow = QueryResultRow>(
settings: Settings,
content: string,
filename: string,
Expand Down
13 changes: 8 additions & 5 deletions src/commands/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
readCurrentMigration,
writeCurrentMigration,
} from "../current";
import { DbCurrent } from "../interfaces";
import { isLoggedError } from "../lib";
import { CommonArgv, getSettings } from "./_common";

interface WatchArgv extends CommonArgv {
Expand Down Expand Up @@ -57,7 +59,7 @@ export function _makeCurrentMigrationRunner(
// 2: Get last current.sql from graphile_migrate.current
const {
rows: [previousCurrent],
} = await lockingPgClient.query(
} = await lockingPgClient.query<DbCurrent>(
`
select *
from graphile_migrate.current
Expand Down Expand Up @@ -161,7 +163,8 @@ export function _makeCurrentMigrationRunner(
: ""
})`,
);
} catch (e: any) {
} catch (err) {
const e = err instanceof Error ? err : new Error(String(err));
logDbError(parsedSettings, e);
throw e;
}
Expand Down Expand Up @@ -198,10 +201,10 @@ export async function _watch(
running = true;

run()
.catch((error) => {
if (!error["_gmlogged"]) {
.catch((error: unknown) => {
if (!isLoggedError(error)) {
parsedSettings.logger.error(
`Error occurred whilst processing migration: ${error.message}`,
`Error occurred whilst processing migration: ${error instanceof Error ? error.message : String(error)}`,
{ error },
);
}
Expand Down
15 changes: 9 additions & 6 deletions src/current.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as assert from "assert";
import { promises as fsp, Stats } from "fs";

import { isNoTransactionDefined } from "./header";
import { errorCode } from "./lib";
import { parseMigrationText, serializeHeader } from "./migration";
import { ParsedSettings } from "./settings";

Expand All @@ -10,8 +11,8 @@ export const VALID_FILE_REGEX = /^([0-9]+)(-[-_a-zA-Z0-9]*)?\.sql$/;
async function statOrNull(path: string): Promise<Stats | null> {
try {
return await fsp.stat(path);
} catch (e: any) {
if (e.code === "ENOENT") {
} catch (e) {
if (errorCode(e) === "ENOENT") {
return null;
}
throw e;
Expand All @@ -21,8 +22,8 @@ async function statOrNull(path: string): Promise<Stats | null> {
async function readFileOrNull(path: string): Promise<string | null> {
try {
return await fsp.readFile(path, "utf8");
} catch (e: any) {
if (e.code === "ENOENT") {
} catch (e) {
if (errorCode(e) === "ENOENT") {
return null;
}
throw e;
Expand All @@ -31,8 +32,10 @@ async function readFileOrNull(path: string): Promise<string | null> {
async function readFileOrError(path: string): Promise<string> {
try {
return await fsp.readFile(path, "utf8");
} catch (e: any) {
throw new Error(`Failed to read file at '${path}': ${e.message}`);
} catch (e) {
throw new Error(
`Failed to read file at '${path}': ${e instanceof Error ? e.message : String(e)}`,
);
}
}

Expand Down
29 changes: 17 additions & 12 deletions src/instrumentation.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import * as chalk from "chalk";
import { QueryResultRow } from "pg";

import indent from "./indent";
import { Client } from "./pg";
import { ParsedSettings } from "./settings";

interface InstrumentationError extends Error {
export interface InstrumentationError extends Error {
severity?: string;
code?: string;
detail?: string;
Expand All @@ -14,19 +15,21 @@ interface InstrumentationError extends Error {
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function runQueryWithErrorInstrumentation<T = any>(
pgClient: Client,
body: string,
filename: string,
): Promise<T[] | undefined> {
export async function runQueryWithErrorInstrumentation<
T extends QueryResultRow = QueryResultRow,
>(pgClient: Client, body: string, filename: string): Promise<T[] | undefined> {
try {
const { rows } = await pgClient.query({
const { rows } = await pgClient.query<T>({
text: body,
});
return rows;
} catch (e: any) {
if (e.position) {
const p = parseInt(e.position, 10);
} catch (e) {
if (
e instanceof Error &&
"position" in e &&
(typeof e.position === "string" || typeof e.position === "number")
) {
const p = parseInt(String(e.position), 10);
let line = 1;
let column = 0;
let idx = 0;
Expand Down Expand Up @@ -61,9 +64,11 @@ export async function runQueryWithErrorInstrumentation<T = any>(
chalk.reset(indent(indent(snippet, codeIndent), indentString)),
indentString +
chalk.red("-".repeat(positionWithinLine - 1 + codeIndent) + "^"),
indentString + chalk.red.bold(e.code) + chalk.red(": " + e.message),
indentString +
chalk.red.bold((e as InstrumentationError).code) +
chalk.red(": " + e.message),
];
e["_gmMessageOverride"] = lines.join("\n");
(e as InstrumentationError)["_gmMessageOverride"] = lines.join("\n");
}
throw e;
}
Expand Down
6 changes: 6 additions & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** Represents the graphile_migrate.current type in the DB */
export interface DbCurrent {
filename: string;
content: string;
date: Date;
}
18 changes: 18 additions & 0 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,21 @@ export function mergeWithoutClobbering(

return result;
}

export function isLoggedError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"_gmlogged" in error &&
error._gmlogged === true
);
}

export function errorCode(e: unknown): string | null {
return typeof e === "object" &&
e !== null &&
"code" in e &&
typeof e.code === "string"
? e.code
: null;
}
8 changes: 4 additions & 4 deletions src/memoize.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-assignment */
export default function memoize<T extends (...args: Array<any>) => any>(
fn: T,
): (...funcArgs: Parameters<T>) => ReturnType<T> {
let lastArgs: Array<any>;
let lastResult: any;
return (...args: Array<any>): any => {
let lastArgs: Parameters<T>;
let lastResult: ReturnType<T>;
return (...args: Parameters<T>): ReturnType<T> => {
if (
lastArgs &&
args.length === lastArgs.length &&
Expand Down
Loading

0 comments on commit 3537613

Please sign in to comment.