Skip to content

Commit

Permalink
chore: add eslint lint script (#203)
Browse files Browse the repository at this point in the history
* chore: add lint script

* fix: lint errors

* fix
  • Loading branch information
MaikoTan authored Mar 23, 2024
1 parent 4468630 commit a252e91
Show file tree
Hide file tree
Showing 26 changed files with 130 additions and 95 deletions.
21 changes: 21 additions & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
extends:
- '@hamster-bot/eslint-config/typescript'

ignorePatterns:
- packages/*/lib/**/*

overrides:
- files:
- '**/src/*.ts'
- '**/src/*.tsx'
rules:
'@typescript-eslint/no-namespace': off

- files:
- '**/tests/*.ts'
- '**/tests/*.tsx'
extends:
- '@hamster-bot/eslint-config/node'
- '@hamster-bot/eslint-config/typescript'
rules:
'@typescript-eslint/no-namespace': off
13 changes: 12 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"bump": "yakumo version",
"dep": "yakumo upgrade",
"pub": "yakumo publish",
"lint": "prettier --check .",
"lint": "eslint --ext .ts --ext .tsx . && prettier --check .",
"lint:fix": "eslint --ext .ts --ext .tsx . --fix && prettier --write .",
"format": "prettier --write .",
"test": "yakumo mocha -r esbuild-register -r yml-register",
"test:text": "shx rm -rf coverage && c8 -r text yarn test",
Expand All @@ -24,15 +25,25 @@
},
"prettier": "@hamster-bot/prettier-config",
"devDependencies": {
"@hamster-bot/eslint-config": "^1.0.5",
"@hamster-bot/prettier-config": "^1.0.2",
"@koishijs/vitepress": "^2.1.3",
"@types/chai": "^4.3.4",
"@types/eslint": "^8",
"@types/mocha": "^9.1.1",
"@types/node": "^18.15.11",
"@typescript-eslint/eslint-plugin": "^7.3.1",
"@typescript-eslint/parser": "^7.3.1",
"c8": "^7.13.0",
"chai": "^4.3.7",
"esbuild": "^0.14.54",
"esbuild-register": "^3.4.2",
"eslint": "^8.57.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-mocha": "^10.4.1",
"eslint-plugin-n": "^16.6.2",
"eslint-plugin-promise": "^6.1.1",
"jest-mock": "^28.1.3",
"mocha": "^9.2.2",
"prettier": "^3.2.5",
Expand Down
8 changes: 6 additions & 2 deletions packages/core/src/command.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/* eslint-disable no-fallthrough */
import { Channel, Context, Random, Session, User } from 'koishi'

import { Config, OutputType, SpoilerType, preferSizes } from '.'

export const inject = {
Expand Down Expand Up @@ -108,7 +110,7 @@ export function apply(ctx: Context, config: Config) {
}
switch (config.output) {
case OutputType.All:
if (image.tags)
if (image.tags) {
children.unshift(
<p>
<i18n path='.output.source'>{[source]}</i18n>
Expand All @@ -117,9 +119,10 @@ export function apply(ctx: Context, config: Config) {
<i18n path='.output.tags'>{[image.tags.join(', ')]}</i18n>
</p>,
)
}
case OutputType.ImageAndLink:
case OutputType.ImageAndInfo:
if (image.title || image.author || image.desc)
if (image.title || image.author || image.desc) {
children.unshift(
<p>
{config.output >= OutputType.ImageAndLink && image.pageUrl ? (
Expand All @@ -141,6 +144,7 @@ export function apply(ctx: Context, config: Config) {
<i18n path='.output.desc'>{[image.desc]}</i18n>
</p>,
)
}
case OutputType.ImageOnly:
children.unshift(
/**
Expand Down
13 changes: 10 additions & 3 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Context, Logger, Quester, Schema, Service, remove } from 'koishi'
import LanguageDetect from 'languagedetect'
import { ImageSource } from './source'

import * as Command from './command'
import { ImageSource } from './source'
import {} from '@koishijs/assets'

export * from './source'
Expand All @@ -19,6 +20,7 @@ class ImageService extends Service {
required: [],
optional: ['assets'],
}

private sources: ImageSource[] = []
private languageDetect = new LanguageDetect()

Expand Down Expand Up @@ -66,7 +68,10 @@ class ImageService extends Service {
const images = await source.get({ count: query.count, tags, raw: query.query }).catch((err) => {
if (Quester.Error.is(err)) {
logger.warn(
`source ${source.config.label} request failed ${err.response?.status ? `with code ${err.response?.status} ${JSON.stringify(err.response?.data)}` : ''}`,
[
`source ${source.config.label} request failed`,
err.response?.status ? `with code ${err.response?.status} ${JSON.stringify(err.response?.data)}` : '',
].join(' '),
)
} else {
logger.error(`source ${source.config.label} unknown error: ${err.message}`)
Expand All @@ -75,10 +80,11 @@ class ImageService extends Service {
logger.debug(err)
return []
})
if (images?.length)
if (images?.length) {
return Object.assign(images, {
source: source.source,
})
}
}

return undefined
Expand Down Expand Up @@ -211,5 +217,6 @@ export function apply(ctx: Context, config: Config) {
ctx.plugin(ImageService, config)
ctx.plugin(Command, config)

// eslint-disable-next-line @typescript-eslint/no-var-requires
ctx.i18n.define('zh', require('./locales/zh-CN'))
}
1 change: 1 addition & 0 deletions packages/core/src/source.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Context, Quester, Schema } from 'koishi'

import type {} from '@koishijs/plugin-proxy-agent'
import type { Inject } from 'cordis'

Expand Down
7 changes: 2 additions & 5 deletions packages/danbooru/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import { Context, Schema, trimSlash } from 'koishi'
import { Schema, trimSlash } from 'koishi'
import { ImageSource } from 'koishi-plugin-booru'

import { Danbooru } from './types'

class DanbooruImageSource extends ImageSource<DanbooruImageSource.Config> {
languages = ['en']
source = 'danbooru'

constructor(ctx: Context, config: DanbooruImageSource.Config) {
super(ctx, config)
}

get keyPair() {
if (!this.config.keyPairs.length) return
return this.config.keyPairs[Math.floor(Math.random() * this.config.keyPairs.length)]
Expand Down
10 changes: 5 additions & 5 deletions packages/e621/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Context, Quester, Schema, trimSlash } from 'koishi'
import { ImageSource } from 'koishi-plugin-booru'

import { e621 } from './types'

class e621ImageSource extends ImageSource<e621ImageSource.Config> {
Expand Down Expand Up @@ -77,11 +78,10 @@ namespace e621ImageSource {
)
.default([])
.description('e621/e926 的登录凭据。'),
userAgent: Schema.string()
.description('设置请求的 User Agent。')
.default(
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.37',
),
userAgent: Schema.string().description('设置请求的 User Agent。').default(
// eslint-disable-next-line max-len
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.37',
),
}).description('搜索设置'),
])
}
Expand Down
12 changes: 6 additions & 6 deletions packages/e621/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ export namespace e621 {
sample: Sample
score: Score
tags: Tags
locked_tags: any[]
locked_tags: string[]
change_seq: number
flags: Flags
rating: string
fav_count: number
sources: string[]
pools: any[]
pools: number[]
relationships: Relationships
approver_id: null
uploader_id: number
Expand Down Expand Up @@ -53,7 +53,7 @@ export namespace e621 {
parent_id: null
has_children: boolean
has_active_children: boolean
children: any[]
children: unknown[]
}

export interface Sample {
Expand All @@ -76,10 +76,10 @@ export namespace e621 {
general: string[]
species: string[]
character: string[]
copyright: any[]
copyright: string[]
artist: string[]
invalid: any[]
lore: any[]
invalid: unknown[]
lore: unknown[]
meta: string[]
}
}
7 changes: 2 additions & 5 deletions packages/gelbooru/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import { Context, Schema, trimSlash } from 'koishi'
import { Schema, trimSlash } from 'koishi'
import { ImageSource } from 'koishi-plugin-booru'

import { Gelbooru } from './types'

class GelbooruImageSource extends ImageSource<GelbooruImageSource.Config> {
languages = ['en']
source = 'gelbooru'

constructor(ctx: Context, config: GelbooruImageSource.Config) {
super(ctx, config)
}

get keyPair() {
if (!this.config.keyPairs.length) return
return this.config.keyPairs[Math.floor(Math.random() * this.config.keyPairs.length)]
Expand Down
10 changes: 4 additions & 6 deletions packages/konachan/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { createHash } from 'node:crypto'
import { Context, Dict, Schema, trimSlash } from 'koishi'

import { Dict, Schema, trimSlash } from 'koishi'
import { ImageSource } from 'koishi-plugin-booru'

import { Konachan } from './types'

/**
Expand All @@ -20,10 +22,6 @@ class KonachanImageSource extends ImageSource<KonachanImageSource.Config> {
languages = ['en']
source = 'konachan'

constructor(ctx: Context, config: KonachanImageSource.Config) {
super(ctx, config)
}

get keyPair() {
if (!this.config.keyPairs.length) return
const key = this.config.keyPairs[Math.floor(Math.random() * this.config.keyPairs.length)]
Expand All @@ -39,7 +37,7 @@ class KonachanImageSource extends ImageSource<KonachanImageSource.Config> {
tags: query.tags.join('+') + '+order:random',
limit: `${query.count}`,
}
let url = trimSlash(this.config.endpoint) + '/post.json'
const url = trimSlash(this.config.endpoint) + '/post.json'

const keyPair = this.keyPair
if (keyPair) {
Expand Down
4 changes: 2 additions & 2 deletions packages/konachan/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ export namespace Konachan {
height: number
is_held: boolean
frames_pending_string: string
frames_pending: any[]
frames_pending: unknown[]
frames_string: string
frames: any[]
frames: unknown[]
}
}
25 changes: 16 additions & 9 deletions packages/local/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { Context, Logger, Random, Schema } from 'koishi'
import { ImageSource } from 'koishi-plugin-booru'
import { pathToFileURL } from 'url'
import { readFile, writeFile } from 'fs/promises'
import { existsSync } from 'fs'
import { readFile, writeFile } from 'fs/promises'
import { resolve } from 'path'
import { scraper } from './scraper'
import { pathToFileURL } from 'url'

import { Context, Logger, Random, Schema } from 'koishi'
import { ImageSource } from 'koishi-plugin-booru'

import { Mapping } from './mapping'
import { hash, mkdirs } from './utils'
import { scraper } from './scraper'
import { LocalStorage } from './types'
import { hash, mkdirs } from './utils'

declare module 'koishi' {
interface Tables {
Expand All @@ -20,6 +22,7 @@ class LocalImageSource extends ImageSource<LocalImageSource.Config> {
required: ['booru'],
optional: ['database', 'cache'],
}

languages = []
source = 'local'
private imageMap: LocalStorage.Type[] = []
Expand All @@ -30,7 +33,7 @@ class LocalImageSource extends ImageSource<LocalImageSource.Config> {
this.languages = config.languages
this.logger = ctx.logger('booru-local')

if (config.storage === 'database')
if (config.storage === 'database') {
ctx.using(['database'], async (ctx) => {
ctx.model.extend(
'booru_local',
Expand All @@ -50,14 +53,17 @@ class LocalImageSource extends ImageSource<LocalImageSource.Config> {

this.imageMap = await ctx.database.get('booru_local', {})
})
}

if (config.storage === 'file') {
const absMap = resolve(ctx.root.baseDir, LocalImageSource.DataDir, LocalImageSource.RootMap)
if (!existsSync(resolve(ctx.root.baseDir, LocalImageSource.DataDir)))
if (!existsSync(resolve(ctx.root.baseDir, LocalImageSource.DataDir))) {
mkdirs(resolve(ctx.root.baseDir, LocalImageSource.DataDir))
}

if (existsSync(absMap)) {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
this.imageMap = require(absMap) as LocalStorage.Type[]
} catch (err) {
readFile(absMap, 'utf-8')
Expand Down Expand Up @@ -89,7 +95,7 @@ class LocalImageSource extends ImageSource<LocalImageSource.Config> {
this.config.endpoint = [...new Set(this.config.endpoint)]
if (this.imageMap.length > 0) mapping = mapping.update(this.imageMap)
// mapping the folders to memory by loop
for await (let path of config.endpoint) {
for await (const path of config.endpoint) {
const store = await mapping.create(path, { extnames: config.extension })
const images = store.imagePaths.filter((path) => !store.images.map((img) => img.path).includes(path))
// create image informations
Expand All @@ -108,6 +114,7 @@ class LocalImageSource extends ImageSource<LocalImageSource.Config> {
// save mapping
if (config.storage === 'database') ctx.database.upsert('booru_local', this.imageMap, ['storeId', 'storeName'])
else if (config.storage === 'file') {
// TODO: fill this part
}
writeFile(
resolve(ctx.root.baseDir, LocalImageSource.DataDir, LocalImageSource.RootMap),
Expand Down
6 changes: 4 additions & 2 deletions packages/local/src/mapping.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { PathLike, existsSync, statSync } from 'fs'
import { readdir } from 'fs/promises'
import { extname, isAbsolute, resolve, sep } from 'path'

import { LocalStorage } from './types'
import { hash } from './utils/hash'

Expand Down Expand Up @@ -34,11 +35,12 @@ export class Mapping {
const files = await readdir(folderPath)
await files.forEach((file) => {
file = this.absPath(resolve(folderPath.toString(), file))
if (statSync(file).isFile() && options.extnames.includes(extname(file)) && !imagePaths.includes(file))
if (statSync(file).isFile() && options.extnames.includes(extname(file)) && !imagePaths.includes(file)) {
imagePaths.push(file)
}
})
} catch (error) {
//ignore error task
// ignore error task
}

return {
Expand Down
Loading

0 comments on commit a252e91

Please sign in to comment.