Skip to content
This repository has been archived by the owner on Aug 22, 2023. It is now read-only.

Commit

Permalink
chore: eslint -> tslint (#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
RasPhilCo authored Nov 21, 2019
1 parent ad7d96b commit 99238a7
Show file tree
Hide file tree
Showing 12 changed files with 1,030 additions and 442 deletions.
6 changes: 5 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
{
"extends": "oclif"
"extends": [
"oclif",
"oclif-typescript"
],
"rules": {}
}
6 changes: 3 additions & 3 deletions example/ls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ class LS extends Command {

async run() {
const {flags} = this.parse(LS)
let files = fs.readdirSync(flags.dir)
for (let f of files) {
const files = fs.readdirSync(flags.dir)
for (const f of files) {
this.log(f)
}
}
}

LS.run()
.then(() => {}, require('@oclif/errors/handle'))
.then(() => {}, require('@oclif/errors/handle'))
12 changes: 7 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,20 @@
},
"devDependencies": {
"@oclif/plugin-plugins": "^1.7.7",
"@oclif/tslint": "^3.1.1",
"@types/chai": "^4.1.7",
"@types/mocha": "^5.2.6",
"@types/node": "^10.12.24",
"@types/semver": "^5.5.0",
"chai": "^4.2.0",
"cli-ux": "^5.1.0",
"conventional-changelog-cli": "^2.0.12",
"eslint": "^6.6.0",
"eslint-config-oclif": "^3.1.0",
"eslint-config-oclif-typescript": "^0.1.0",
"fancy-test": "^1.4.3",
"globby": "^9.0.0",
"mocha": "^6.0.2",
"ts-node": "^8.0.3",
"tslint": "^5.14.0",
"typescript": "^3.3.3333"
},
"peerDependencies": {
Expand Down Expand Up @@ -55,11 +56,12 @@
"repository": "oclif/command",
"scripts": {
"build": "rm -rf lib && tsc",
"lint": "tsc -p test --noEmit && tslint -p test -t stylish",
"posttest": "yarn run lint",
"lint": "eslint . --ext .ts --config .eslintrc",
"posttest": "yarn lint",
"prepublishOnly": "yarn run build",
"test": "mocha --forbid-only \"test/**/*.test.ts\"",
"version": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md"
"version": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md",
"pretest": "tsc -p test --noEmit"
},
"types": "lib/index.d.ts"
}
81 changes: 56 additions & 25 deletions src/command.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// tslint:disable no-implicit-dependencies
// tslint:disable no-single-line-block-comment
const pjson = require('../package.json')
import * as Config from '@oclif/config'
import * as Errors from '@oclif/errors'
Expand Down Expand Up @@ -27,52 +25,72 @@ process.stdout.on('error', err => {

export default abstract class Command {
static _base = `${pjson.name}@${pjson.version}`

/** A command ID, used mostly in error or verbose reporting */
static id: string
// TODO: Confirm unused?

// to-do: Confirm unused?
static title: string | undefined

/**
* The tweet-sized description for your class, used in a parent-commands
* sub-command listing and as the header for the command help
*/
static description: string | undefined

/** hide the command from help? */
static hidden: boolean

/** An override string (or strings) for the default usage documentation */
static usage: string | string[] | undefined

static help: string | undefined

/** An array of aliases for this command */
static aliases: string[] = []

/** When set to false, allows a variable amount of arguments */
static strict = true

static parse = true

/** A hash of flags for the command */
static flags?: flags.Input<any>

/** An order-dependent array of arguments for the command */
static args?: Parser.args.IArg[]

static plugin: Config.IPlugin | undefined

/** An array of example strings to show at the end of the command's help */
static examples: string[] | undefined

static parserOptions = {}

/**
* instantiate and run the command
* @param {Config.Command.Class} this Class
* @param {string[]} argv argv
* @param {Config.LoadOptions} opts options
*/
static run: Config.Command.Class['run'] = async function (this: Config.Command.Class, argv?: string[], opts?) {
if (!argv) argv = process.argv.slice(2)
const config = await Config.load(opts || module.parent && module.parent.parent && module.parent.parent.filename || __dirname)
let cmd = new this(argv, config)
const config = await Config.load(opts || (module.parent && module.parent.parent && module.parent.parent.filename) || __dirname)
const cmd = new this(argv, config)
return cmd._run(argv)
}

id: string | undefined

protected debug: (...args: any[]) => void

constructor(public argv: string[], public config: Config.IConfig) {
this.id = this.ctor.id
try {
this.debug = require('debug')(this.id ? `${this.config.bin}:${this.id}` : this.config.bin)
} catch { this.debug = () => {} }
} catch {
this.debug = () => {}
}
}

get ctor(): typeof Command {
Expand All @@ -87,21 +105,30 @@ export default abstract class Command {

await this.init()
return await this.run()
} catch (e) {
err = e
await this.catch(e)
} catch (error) {
err = error
await this.catch(error)
} finally {
await this.finally(err)
}
}

exit(code = 0) { return Errors.exit(code) }
warn(input: string | Error) { Errors.warn(input) }
error(input: string | Error, options: {code?: string, exit: false}): void
error(input: string | Error, options?: {code?: string, exit?: number}): never
error(input: string | Error, options: {code?: string, exit?: number | false} = {}) {
exit(code = 0) {
return Errors.exit(code)
}

warn(input: string | Error) {
Errors.warn(input)
}

error(input: string | Error, options: {code?: string; exit: false}): void

error(input: string | Error, options?: {code?: string; exit?: number}): never

error(input: string | Error, options: {code?: string; exit?: number | false} = {}) {
return Errors.error(input, options as any)
}

log(message = '', ...args: any[]) {
// tslint:disable-next-line strict-type-predicates
message = typeof message === 'string' ? message : inspect(message)
Expand All @@ -112,6 +139,7 @@ export default abstract class Command {
* actual command run code goes here
*/
abstract run(): PromiseLike<any>

protected async init(): Promise<any> {
this.debug('init version: %s argv: %o', this.ctor._base, this.argv)
if (this.config.debug) Errors.config.debug = true
Expand All @@ -135,23 +163,26 @@ export default abstract class Command {
if (!err.message) throw err
if (err.message.match(/Unexpected arguments?: (-h|--help|help)(,|\n)/)) {
return this._help()
} else if (err.message.match(/Unexpected arguments?: (-v|--version|version)(,|\n)/)) {
}
if (err.message.match(/Unexpected arguments?: (-v|--version|version)(,|\n)/)) {
return this._version()
} else {
try {
const {cli} = require('cli-ux')
const chalk = require('chalk')
cli.action.stop(chalk.bold.red('!'))
} catch {}
throw err
}
try {
const {cli} = require('cli-ux')
const chalk = require('chalk') // eslint-disable-line node/no-extraneous-require
cli.action.stop(chalk.bold.red('!'))
} catch {}
throw err
}

protected async finally(_: Error | undefined): Promise<any> {
try {
const config = require('@oclif/errors').config
if (config.errorLogger) await config.errorLogger.flush()
// tslint:disable-next-line no-console
} catch (err) { console.error(err) }
} catch (error) {
console.error(error)
}
}

protected _help() {
Expand All @@ -163,12 +194,12 @@ export default abstract class Command {
topics = topics.filter((t: any) => !t.hidden)
topics = sortBy(topics, (t: any) => t.name)
topics = uniqBy(topics, (t: any) => t.name)
help.showCommandHelp(cmd, this.config.topics)
help.showCommandHelp(cmd, topics)
return this.exit(0)
}

protected _helpOverride(): boolean {
for (let arg of this.argv) {
for (const arg of this.argv) {
if (arg === '--help') return true
if (arg === '--') return false
}
Expand Down
24 changes: 12 additions & 12 deletions src/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@ import * as Parser from '@oclif/parser'
import {Command} from '.'

export type ICompletionContext = {
args?: { [name: string]: string }
flags?: { [name: string]: string }
argv?: string[]
config: IConfig
args?: { [name: string]: string };
flags?: { [name: string]: string };
argv?: string[];
config: IConfig;
}

export type ICompletion = {
skipCache?: boolean
cacheDuration?: number
cacheKey?(ctx: ICompletionContext): Promise<string>
options(ctx: ICompletionContext): Promise<string[]>
skipCache?: boolean;
cacheDuration?: number;
cacheKey?(ctx: ICompletionContext): Promise<string>;
options(ctx: ICompletionContext): Promise<string[]>;
}

export type IOptionFlag<T> = Parser.flags.IOptionFlag<T> & {
completion?: ICompletion
completion?: ICompletion;
}

export type IFlag<T> = Parser.flags.IBooleanFlag<T> | IOptionFlag<T>
Expand All @@ -27,9 +27,9 @@ export type Output = Parser.flags.Output
export type Input<T extends Parser.flags.Output> = { [P in keyof T]: IFlag<T[P]> }

export type Definition<T> = {
(options: {multiple: true} & Partial<IOptionFlag<T[]>>): IOptionFlag<T[]>
(options: ({required: true} | {default: Parser.flags.Default<T>}) & Partial<IOptionFlag<T>>): IOptionFlag<T>
(options?: Partial<IOptionFlag<T>>): IOptionFlag<T | undefined>
(options: {multiple: true} & Partial<IOptionFlag<T[]>>): IOptionFlag<T[]>;
(options: ({required: true} | {default: Parser.flags.Default<T>}) & Partial<IOptionFlag<T>>): IOptionFlag<T>;
(options?: Partial<IOptionFlag<T>>): IOptionFlag<T | undefined>;
}

export function build<T>(defaults: {parse: IOptionFlag<T>['parse']} & Partial<IOptionFlag<T>>): Definition<T>
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import * as semver from 'semver'
function checkCWD() {
try {
process.cwd()
} catch (err) {
if (err.code === 'ENOENT') {
} catch (error) {
if (error.code === 'ENOENT') {
process.stderr.write('WARNING: current directory does not exist\n')
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@ import {Command} from '.'

export class Main extends Command {
static run(argv = process.argv.slice(2), options?: Config.LoadOptions) {
return super.run(argv, options || module.parent && module.parent.parent && module.parent.parent.filename || __dirname)
return super.run(argv, options || (module.parent && module.parent.parent && module.parent.parent.filename) || __dirname)
}

async init() {
let [id, ...argv] = this.argv
const [id, ...argv] = this.argv
await this.config.runHook('init', {id, argv})
return super.init()
}

async run() {
let [id, ...argv] = this.argv
const [id, ...argv] = this.argv
this.parse({strict: false, '--': false, ...this.ctor as any})
if (!this.config.findCommand(id)) {
let topic = this.config.findTopic(id)
const topic = this.config.findTopic(id)
if (topic) return this._help()
}
await this.config.runCommand(id, argv)
Expand All @@ -28,7 +28,7 @@ export class Main extends Command {
if (['-v', '--version', 'version'].includes(this.argv[0])) return this._version() as any
if (['-h', 'help'].includes(this.argv[0])) return true
if (this.argv.length === 0) return true
for (let arg of this.argv) {
for (const arg of this.argv) {
if (arg === '--help') return true
if (arg === '--') return false
}
Expand Down
6 changes: 3 additions & 3 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
export function compact<T>(a: (T | undefined)[]): T[] {
return a.filter((a): a is T => !!a)
return a.filter((a): a is T => Boolean(a))
}

export function uniqBy<T>(arr: T[], fn: (cur: T) => any): T[] {
return arr.filter((a, i) => {
let aVal = fn(a)
const aVal = fn(a)
return !arr.find((b, j) => j > i && fn(b) === aVal)
})
}
Expand All @@ -19,7 +19,7 @@ export function sortBy<T>(arr: T[], fn: (i: T) => sort.Types | sort.Types[]): T[

if (Array.isArray(a) && Array.isArray(b)) {
if (a.length === 0 && b.length === 0) return 0
let diff = compare(a[0], b[0])
const diff = compare(a[0], b[0])
if (diff !== 0) return diff
return compare(a.slice(1), b.slice(1))
}
Expand Down
Loading

0 comments on commit 99238a7

Please sign in to comment.