Skip to content

Commit

Permalink
Refactor test cases (#222)
Browse files Browse the repository at this point in the history
* Refactor test cases

* sort messages

* combine the messages that are output twice.

* refactor for no-html-messages test

* update

* refactor test

* remove unused source code
  • Loading branch information
ota-meshi authored Aug 22, 2021
1 parent 8d094f9 commit df4fffd
Show file tree
Hide file tree
Showing 13 changed files with 1,180 additions and 1,538 deletions.
32 changes: 21 additions & 11 deletions lib/rules/no-duplicate-keys-in-locale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
SourceCode
} from '../types'
import { joinPath } from '../utils/key-path'
import { getCwd } from '../utils/get-cwd'
const debug = debugBuilder('eslint-plugin-vue-i18n:no-duplicate-keys-in-locale')

interface DictData {
Expand All @@ -29,9 +30,10 @@ interface PathStack {
upper?: PathStack
}

function getMessageFilepath(fullPath: string) {
if (fullPath.startsWith(process.cwd())) {
return fullPath.replace(process.cwd() + '/', './')
function getMessageFilepath(fullPath: string, context: RuleContext) {
const cwd = getCwd(context)
if (fullPath.startsWith(cwd)) {
return fullPath.replace(cwd + '/', './')
}
return fullPath
}
Expand Down Expand Up @@ -121,23 +123,31 @@ function create(context: RuleContext): RuleListener {
const keyPath = [...pathStack.keyPath, key]
const keyPathStr = joinPath(...keyPath)
const nextOtherDictionaries: DictData[] = []
const reportFiles = []
for (const value of keyOtherValues) {
if (typeof value.value === 'string') {
context.report({
message: `duplicate key '${keyPathStr}' in '${
pathStack.locale
}'. "${getMessageFilepath(
value.source.fullpath
)}" has the same key`,
loc: reportNode.loc
})
reportFiles.push(
'"' + getMessageFilepath(value.source.fullpath, context) + '"'
)
} else {
nextOtherDictionaries.push({
dict: value.value,
source: value.source
})
}
}
if (reportFiles.length) {
reportFiles.sort()
const last = reportFiles.pop()
context.report({
message: `duplicate key '${keyPathStr}' in '${pathStack.locale}'. ${
reportFiles.length === 0
? last
: reportFiles.join(', ') + ', and ' + last
} has the same key`,
loc: reportNode.loc
})
}

pushKey(
existsKeyNodes[pathStack.locale] ||
Expand Down
6 changes: 4 additions & 2 deletions lib/rules/no-unused-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type {
CustomBlockVisitorFactory
} from '../types'
import { joinPath, parsePath } from '../utils/key-path'
import { getCwd } from '../utils/get-cwd'
const debug = debugBuilder('eslint-plugin-vue-i18n:no-unused-keys')

type UsedKeys = {
Expand Down Expand Up @@ -524,12 +525,13 @@ function create(context: RuleContext): RuleListener {
debug(`ignore ${filename} in no-unused-keys`)
return {}
}
const src = options.src || process.cwd()
const src = options.src || getCwd(context)
const extensions = options.extensions || ['.js', '.vue']

const usedLocaleMessageKeys = usedKeysCache.collectKeysFromFiles(
[src],
extensions
extensions,
context
)
const sourceCode = context.getSourceCode()

Expand Down
2 changes: 2 additions & 0 deletions lib/types/eslint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export interface RuleContext {
'vue-i18n'?: {
localeDir?: SettingsVueI18nLocaleDir
messageSyntaxVersion?: string
cwd?: string // for test
}
}
parserPath: string
Expand All @@ -44,6 +45,7 @@ export interface RuleContext {
getSourceCode(): SourceCode
getScope(): Scope
report(descriptor: ReportDescriptor): void
getCwd?: () => string
}

interface ReportDescriptorOptionsBase {
Expand Down
27 changes: 18 additions & 9 deletions lib/utils/collect-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ import { ResourceLoader } from './resource-loader'
import { CacheLoader } from './cache-loader'
import { defineCacheFunction } from './cache-function'
import debugBuilder from 'debug'
import type { VisitorKeys } from '../types'
import type { RuleContext, VisitorKeys } from '../types'
// @ts-expect-error -- ignore
import { Legacy } from '@eslint/eslintrc'
import { getCwd } from './get-cwd'
const debug = debugBuilder('eslint-plugin-vue-i18n:collect-keys')
const { CascadingConfigArrayFactory } = Legacy

Expand Down Expand Up @@ -246,16 +247,16 @@ export function collectKeysFromAST(

class UsedKeysCache {
private _targetFilesLoader: CacheLoader<
[string[], string[], string],
[string, string[], string[], string],
string[]
>
private _collectKeyResourcesFromFiles: (
fileNames: string[],
cwd: string
) => ResourceLoader<string[]>[]
constructor() {
this._targetFilesLoader = new CacheLoader((files, extensions) => {
return listFilesToProcess(files, { extensions })
this._targetFilesLoader = new CacheLoader((cwd, files, extensions) => {
return listFilesToProcess(files, { cwd, extensions })
.filter(f => !f.ignored && extensions.includes(extname(f.filename)))
.map(f => f.filename)
})
Expand All @@ -271,9 +272,13 @@ class UsedKeysCache {
* @param {string[]} extensions
* @returns {string[]}
*/
collectKeysFromFiles(files: string[], extensions: string[]) {
collectKeysFromFiles(
files: string[],
extensions: string[],
context: RuleContext
) {
const result = new Set<string>()
for (const resource of this._getKeyResources(files, extensions)) {
for (const resource of this._getKeyResources(context, files, extensions)) {
for (const key of resource.getResource()) {
result.add(key)
}
Expand All @@ -284,9 +289,13 @@ class UsedKeysCache {
/**
* @returns {ResourceLoader[]}
*/
_getKeyResources(files: string[], extensions: string[]) {
const cwd = process.cwd()
const fileNames = this._targetFilesLoader.get(files, extensions, cwd)
_getKeyResources(
context: RuleContext,
files: string[],
extensions: string[]
) {
const cwd = getCwd(context)
const fileNames = this._targetFilesLoader.get(cwd, files, extensions, cwd)
return this._collectKeyResourcesFromFiles(fileNames, cwd)
}
}
Expand Down
7 changes: 7 additions & 0 deletions lib/utils/get-cwd.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { RuleContext } from '../types'

export function getCwd(context: RuleContext): string {
return (
context.settings?.['vue-i18n']?.cwd ?? context.getCwd?.() ?? process.cwd()
)
}
17 changes: 13 additions & 4 deletions lib/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type {
} from '../types'
import * as jsoncESLintParser from 'jsonc-eslint-parser'
import * as yamlESLintParser from 'yaml-eslint-parser'
import { getCwd } from './get-cwd'

interface LocaleFiles {
files: string[]
Expand Down Expand Up @@ -162,7 +163,10 @@ export function getLocaleMessages(context: RuleContext): LocaleMessages {
return new LocaleMessages([
...(getLocaleMessagesFromI18nBlocks(context, i18nBlocks) || []),
...((localeDir &&
localeDirLocaleMessagesCache.getLocaleMessagesFromLocaleDir(localeDir)) ||
localeDirLocaleMessagesCache.getLocaleMessagesFromLocaleDir(
context,
localeDir
)) ||
[])
])
}
Expand All @@ -174,7 +178,9 @@ class LocaleDirLocaleMessagesCache {
cwd: string
) => FileLocaleMessage[]
constructor() {
this._targetFilesLoader = new CacheLoader(pattern => glob.sync(pattern))
this._targetFilesLoader = new CacheLoader((pattern, cwd) =>
glob.sync(pattern, { cwd })
)

this._loadLocaleMessages = defineCacheFunction(
(localeFilesList: LocaleFiles[], cwd) => {
Expand All @@ -186,8 +192,11 @@ class LocaleDirLocaleMessagesCache {
* @param {SettingsVueI18nLocaleDir} localeDir
* @returns {LocaleMessage[]}
*/
getLocaleMessagesFromLocaleDir(localeDir: SettingsVueI18nLocaleDir) {
const cwd = process.cwd()
getLocaleMessagesFromLocaleDir(
context: RuleContext,
localeDir: SettingsVueI18nLocaleDir
) {
const cwd = getCwd(context)
let localeFilesList: LocaleFiles[]
if (Array.isArray(localeDir)) {
localeFilesList = localeDir.map(dir => this._toLocaleFiles(dir, cwd))
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@
"release:prepare": "shipjs prepare",
"release:trigger": "shipjs trigger",
"test": "mocha --require ts-node/register \"./tests/**/*.ts\"",
"test:debug": "mocha --require ts-node/register/transpile-only --inspect \"./tests/**/*.ts\"",
"test:debug": "mocha --require ts-node/register/transpile-only \"./tests/**/*.ts\"",
"test:coverage": "nyc mocha --require ts-node/register \"./tests/**/*.ts\" --timeout 60000",
"test:integrations": "mocha ./tests-integrations/*.js --timeout 60000"
}
Expand Down
Loading

0 comments on commit df4fffd

Please sign in to comment.