use findFile() api

This commit is contained in:
masnn committed 2021-04-13 17:49:58 +00:00
1 parent 8a8e312ca4
commit 9a538130ee
10 files changed
+105 -52

No files matched your search

+35 -32
View File
@@ -7,52 +7,55 @@ globals:
Atomics: readonly Atomics: readonly
SharedArrayBuffer: readonly SharedArrayBuffer: readonly
BigInt: readonly BigInt: readonly
parser: '@typescript-eslint/parser' parser: "@typescript-eslint/parser"
plugins: plugins:
- '@typescript-eslint' - "@typescript-eslint"
rules: rules:
'@typescript-eslint/dot-notation': off "@typescript-eslint/dot-notation": 0
'@typescript-eslint/no-implied-eval': off "@typescript-eslint/no-implied-eval": 0
'@typescript-eslint/no-throw-literal': off "@typescript-eslint/no-throw-literal": 0
'@typescript-eslint/return-await': off "@typescript-eslint/return-await": 0
'@typescript-eslint/indent': "@typescript-eslint/indent":
- warn - warn
- 4 - 4
'@typescript-eslint/lines-between-class-members': "@typescript-eslint/lines-between-class-members":
- error - error
- always - always
- exceptAfterSingleLine: true - exceptAfterSingleLine: true
'@typescript-eslint/naming-convention': off "@typescript-eslint/naming-convention": 0
'@typescript-eslint/no-redeclare': off "@typescript-eslint/no-redeclare": 0
class-methods-use-this: off class-methods-use-this: 0
global-require: off global-require: 0
guard-for-in: off guard-for-in: 0
implicit-arrow-linebreak: off implicit-arrow-linebreak: 0
import/no-cycle: off import/no-cycle: 0
import/no-extraneous-dependencies: off import/no-extraneous-dependencies: 0
import/no-named-as-default: off import/no-named-as-default: 0
import/prefer-default-export: off import/prefer-default-export: 0
max-classes-per-file: off max-classes-per-file: 0
max-len: max-len:
- warn - warn
- 150 - 150
no-bitwise: off no-bitwise: 0
no-console: off no-console: 0
no-continue: off no-continue: 0
no-extend-native: off no-extend-native: 0
no-multi-assign: off no-empty:
no-nested-ternary: off - warn
no-param-reassign: off - allowEmptyCatch: true
no-plusplus: off no-multi-assign: 0
no-restricted-syntax: off no-nested-ternary: 0
no-return-await: off no-param-reassign: 0
no-underscore-dangle: off no-plusplus: 0
prefer-destructuring: off no-restricted-syntax: 0
no-return-await: 0
no-underscore-dangle: 0
prefer-destructuring: 0
settings: settings:
import/parsers: import/parsers:
'@typescript-eslint/parser': "@typescript-eslint/parser":
- .ts - .ts
- .js - .js
- .jsx - .jsx
+1 -1
View File
@@ -19,7 +19,7 @@ if (!cluster.isMaster) {
fs.ensureDirSync(path.resolve(os.homedir(), '.hydro')); fs.ensureDirSync(path.resolve(os.homedir(), '.hydro'));
const addonPath = path.resolve(os.homedir(), '.hydro', 'addon.json'); const addonPath = path.resolve(os.homedir(), '.hydro', 'addon.json');
let addons = filter( let addons = filter(
fs.readdirSync(path.resolve(__dirname, '../packages')), fs.readdirSync(path.resolve(process.cwd(), 'packages')),
(i) => i !== 'hydrooj', (i) => i !== 'hydrooj',
).map((i) => `@hydrooj/${i}`); ).map((i) => `@hydrooj/${i}`);
fs.writeFileSync(addonPath, JSON.stringify(addons, null, 2)); fs.writeFileSync(addonPath, JSON.stringify(addons, null, 2));
+1 -2
View File
@@ -1,10 +1,9 @@
/* eslint-disable no-console */ /* eslint-disable no-console */
/* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable import/no-extraneous-dependencies */
import path from 'path';
import globby from 'globby'; import globby from 'globby';
import spawn from 'cross-spawn'; import spawn from 'cross-spawn';
export const cwd = path.resolve(__dirname, '..'); export const cwd = process.cwd();
export function getWorkspaces() { export function getWorkspaces() {
return globby(require('../package').workspaces, { return globby(require('../package').workspaces, {
+2 -2
View File
@@ -1,9 +1,9 @@
import 'hydrooj'; import 'hydrooj';
import fs from 'fs'; import fs from 'fs';
import path from 'path';
import { Reader } from 'maxmind'; import { Reader } from 'maxmind';
import { findFileSync } from '@hydrooj/utils/lib/utils';
const buffer = fs.readFileSync(path.resolve(__dirname, 'GeoLite2-City.mmdb')); const buffer = fs.readFileSync(findFileSync('@hydrooj/geoip/GeoLite2-City.mmdb'));
const reader = new Reader(buffer); const reader = new Reader(buffer);
export interface Result { export interface Result {
+4 -2
View File
@@ -1,10 +1,12 @@
import fs from 'fs-extra'; import fs from 'fs-extra';
import { resolve } from 'path'; import { findFileSync } from '@hydrooj/utils/lib/utils';
import checkers from './checkers'; import checkers from './checkers';
import compile from './compile'; import compile from './compile';
import { SystemError } from './error'; import { SystemError } from './error';
import { parseFilename } from './utils'; import { parseFilename } from './utils';
const testlibSrc = findFileSync('@hydrooj/hydrojudge/vendor/testlib/testlib.h');
export async function check(config): Promise<[number, number, string]> { export async function check(config): Promise<[number, number, string]> {
if (!checkers[config.checker_type]) throw new SystemError(`未知比较器类型:${config.checker_type}`); if (!checkers[config.checker_type]) throw new SystemError(`未知比较器类型:${config.checker_type}`);
const { const {
@@ -24,7 +26,7 @@ export async function check(config): Promise<[number, number, string]> {
export async function compileChecker(checkerType: string, checker: string, copyIn: any) { export async function compileChecker(checkerType: string, checker: string, copyIn: any) {
if (!checkers[checkerType]) throw new SystemError('Unknown checker type {0}.', [checkerType]); if (!checkers[checkerType]) throw new SystemError('Unknown checker type {0}.', [checkerType]);
if (checkerType === 'testlib') copyIn['testlib.h'] = { src: resolve(__dirname, '../vendor/testlib/testlib.h') }; if (checkerType === 'testlib') copyIn['testlib.h'] = { src: testlibSrc };
const file = await fs.readFile(checker); const file = await fs.readFile(checker);
// TODO cache compiled checker // TODO cache compiled checker
return await compile(parseFilename(checker).split('.')[1], file.toString(), 'checker', copyIn); return await compile(parseFilename(checker).split('.')[1], file.toString(), 'checker', copyIn);
+3 -3
View File
@@ -1,14 +1,14 @@
import Queue from 'p-queue'; import Queue from 'p-queue';
import fs from 'fs-extra'; import fs from 'fs-extra';
import { resolve } from 'path';
import * as STATUS from '../status'; import * as STATUS from '../status';
import { parse } from '../testlib'; import { parse } from '../testlib';
import { parseFilename } from '../utils'; import { findFileSync, parseFilename } from '../utils';
import { run } from '../sandbox'; import { run } from '../sandbox';
import compile from '../compile'; import compile from '../compile';
import signals from '../signals'; import signals from '../signals';
import { getConfig } from '../config'; import { getConfig } from '../config';
const testlibSrc = findFileSync('@hydrooj/hydrojudge/vendor/testlib/testlib.h');
const Score = { const Score = {
sum: (a, b) => (a + b), sum: (a, b) => (a + b),
max: Math.max, max: Math.max,
@@ -19,7 +19,7 @@ function judgeCase(c) {
return async (ctx, ctxSubtask) => { return async (ctx, ctxSubtask) => {
ctx.executeInteractor.copyIn.in = c.input ? { src: c.input } : { content: '' }; ctx.executeInteractor.copyIn.in = c.input ? { src: c.input } : { content: '' };
ctx.executeInteractor.copyIn.out = c.output ? { src: c.output } : { content: '' }; ctx.executeInteractor.copyIn.out = c.output ? { src: c.output } : { content: '' };
ctx.executeInteractor.copyIn['testlib.h'] = { src: resolve(__dirname, '../../vendor/testlib/testlib.h') }; ctx.executeInteractor.copyIn['testlib.h'] = { src: testlibSrc };
const [{ code, time_usage_ms, memory_usage_kb }, resInteractor] = await run([ const [{ code, time_usage_ms, memory_usage_kb }, resInteractor] = await run([
{ {
execute: ctx.executeUser.execute.replace(/\$\{name\}/g, 'code'), execute: ctx.executeUser.execute.replace(/\$\{name\}/g, 'code'),
+1
View File
@@ -43,6 +43,7 @@
"@types/inquirer": "^7.3.1", "@types/inquirer": "^7.3.1",
"@types/js-yaml": "^4.0.0", "@types/js-yaml": "^4.0.0",
"@types/koa": "^2.13.1", "@types/koa": "^2.13.1",
"@types/koa-compress": "^4.0.1",
"@types/koa-router": "^7.4.1", "@types/koa-router": "^7.4.1",
"@types/koa-static-cache": "^5.1.0", "@types/koa-static-cache": "^5.1.0",
"@types/lodash": "^4.14.168", "@types/lodash": "^4.14.168",
+3 -7
View File
@@ -1,6 +1,7 @@
import fs from 'fs'; import fs from 'fs';
import os from 'os'; import os from 'os';
import path from 'path'; import path from 'path';
import { findFileSync } from '@hydrooj/utils/lib/utils';
import { Logger } from './logger'; import { Logger } from './logger';
const logger = new Logger('options'); const logger = new Logger('options');
@@ -13,13 +14,8 @@ export = function load() {
process.env[line.split('=')[0]] = line.split('=')[1]; process.env[line.split('=')[0]] = line.split('=')[1];
} }
} }
const f = findFileSync('config.json', false);
let f = path.resolve(process.cwd(), 'config.json'); if (!f) return null;
if (!fs.existsSync(f)) f = path.resolve(__dirname, 'config.json');
if (!fs.existsSync(f)) f = path.resolve(os.homedir(), '.config', 'hydro', 'config.json');
if (!fs.existsSync(f)) f = path.resolve(os.homedir(), '.hydro', 'config.json');
if (!fs.existsSync(f)) f = path.resolve('/config/config.json');
if (!fs.existsSync(f)) return null;
let result: any = {}; let result: any = {};
try { try {
result = JSON.parse(fs.readFileSync(f).toString()); result = JSON.parse(fs.readFileSync(f).toString());
+5 -2
View File
@@ -6,6 +6,7 @@ const nunjucks = require('nunjucks');
const { filter } = require('lodash'); const { filter } = require('lodash');
const { argv } = require('yargs'); const { argv } = require('yargs');
const Xss = require('xss'); const Xss = require('xss');
const { findFileSync } = require('@hydrooj/utils/lib/utils');
const markdown = require('./markdown'); const markdown = require('./markdown');
const { misc, buildContent } = global.Hydro.lib; const { misc, buildContent } = global.Hydro.lib;
@@ -76,6 +77,9 @@ const xss = new Xss.FilterXSS({
}, },
}); });
if (argv.template && argv.template !== 'string') argv.template = findFileSync('@hydrooj/ui-default/templates');
else argv.template = findFileSync(argv.template);
class Loader extends nunjucks.Loader { class Loader extends nunjucks.Loader {
// eslint-disable-next-line class-methods-use-this // eslint-disable-next-line class-methods-use-this
getSource(name) { getSource(name) {
@@ -88,8 +92,7 @@ class Loader extends nunjucks.Loader {
}; };
} }
let fullpath = null; let fullpath = null;
if (typeof argv.template !== 'string') argv.template = path.resolve(__dirname, '..', 'templates'); const p = path.resolve(argv.template, name);
const p = path.resolve(process.cwd(), argv.template, name);
if (fs.existsSync(p)) fullpath = p; if (fs.existsSync(p)) fullpath = p;
if (!fullpath) { if (!fullpath) {
if (global.Hydro.ui.template[name]) { if (global.Hydro.ui.template[name]) {
+50 -1
View File
@@ -1,5 +1,6 @@
import path, { sep } from 'path'; import path, { sep } from 'path';
import fs from 'fs'; import fs from 'fs-extra';
import os from 'os';
import { Duplex } from 'stream'; import { Duplex } from 'stream';
import { ObjectID } from 'bson'; import { ObjectID } from 'bson';
import { isMoment } from 'moment'; import { isMoment } from 'moment';
@@ -305,6 +306,54 @@ export function changeErrorType(err: Error, Err: any) {
return e; return e;
} }
export async function findFile(pathname: string, doThrow = true) {
if (await fs.pathExists(path.resolve(pathname))) return path.resolve(pathname);
if (await fs.pathExists(path.resolve(process.cwd(), pathname))) return path.resolve(process.cwd(), pathname);
if (await fs.pathExists(path.resolve(__dirname, pathname))) return path.resolve(__dirname, pathname);
try {
return require.resolve(pathname);
} catch (e) { }
if (pathname.includes('/')) {
const eles = pathname.split('/');
let pkg = eles.shift();
if (pkg.startsWith('@')) pkg = `${pkg}/${eles.shift()}`;
const rest = eles.join('/');
try {
const p = require.resolve(pkg);
if (await fs.pathExists(path.resolve(p, rest))) return path.resolve(p, rest);
} catch (e) { }
}
if (await fs.pathExists(path.resolve(os.homedir(), pathname))) return path.resolve(__dirname, pathname);
if (await fs.pathExists(path.resolve(os.homedir(), '.hydro', pathname))) return path.resolve(__dirname, pathname);
if (await fs.pathExists(path.resolve(os.homedir(), '.config', 'hydro', pathname))) return path.resolve(__dirname, pathname);
if (doThrow) throw new Error(`File ${pathname} not found`);
return null;
}
export function findFileSync(pathname: string, doThrow = true) {
if (fs.pathExistsSync(path.resolve(pathname))) return path.resolve(pathname);
if (fs.pathExistsSync(path.resolve(process.cwd(), pathname))) return path.resolve(process.cwd(), pathname);
if (fs.pathExistsSync(path.resolve(__dirname, pathname))) return path.resolve(__dirname, pathname);
try {
return require.resolve(pathname);
} catch (e) { }
if (pathname.includes('/')) {
const eles = pathname.split('/');
let pkg = eles.shift();
if (pkg.startsWith('@')) pkg = `${pkg}/${eles.shift()}`;
const rest = eles.join('/');
try {
const p = require.resolve(pkg);
if (fs.pathExistsSync(path.resolve(p, rest))) return path.resolve(p, rest);
} catch (e) { }
}
if (fs.pathExistsSync(path.resolve(os.homedir(), pathname))) return path.resolve(__dirname, pathname);
if (fs.pathExistsSync(path.resolve(os.homedir(), '.hydro', pathname))) return path.resolve(__dirname, pathname);
if (fs.pathExistsSync(path.resolve(os.homedir(), '.config', 'hydro', pathname))) return path.resolve(__dirname, pathname);
if (doThrow) throw new Error(`File ${pathname} not found`);
return null;
}
export async function retry(func: Function, ...args: any[]): Promise<any>; export async function retry(func: Function, ...args: any[]): Promise<any>;
export async function retry(times: number, func: Function, ...args: any[]): Promise<any>; export async function retry(times: number, func: Function, ...args: any[]): Promise<any>;
// eslint-disable-next-line consistent-return // eslint-disable-next-line consistent-return