Skip to content

Use @intlify/message-compiler and supports vue-i18n v9 message format #145

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ module.exports = {
ecmaVersion: 2015
},
rules: {
'object-shorthand': 'error'
'object-shorthand': 'error',
'no-debugger': 'error'
},
overrides: [
{
Expand Down
7 changes: 6 additions & 1 deletion docs/started.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ module.export = {
},
settings: {
'vue-i18n': {
localeDir: './path/to/locales/*.{json,json5,yaml,yml}' // extension is glob formatting!
localeDir: './path/to/locales/*.{json,json5,yaml,yml}', // extension is glob formatting!
// or
// localeDir: {
// pattern: './path/to/locales/*.{json,json5,yaml,yml}', // extension is glob formatting!
Expand All @@ -55,6 +55,10 @@ module.export = {
// localeKey: 'file' // or 'key'
// },
// ]

// Specify the version of `vue-i18n` you are using.
// If not specified, the message will be parsed twice.
messageSyntaxVersion: '^9.0.0'
}
}
}
Expand All @@ -72,6 +76,7 @@ See [the rule list](../rules/)
- `'file'` ... Determine the locale name from the filename. The resource file should only contain messages for that locale. Use this option if you use `vue-cli-plugin-i18n`. This option is also used when String option is specified.
- `'key'` ... Determine the locale name from the root key name of the file contents. The value of that key should only contain messages for that locale. Used when the resource file is in the format given to the `messages` option of the `VueI18n` constructor option.
- Array option ... An array of String option and Object option. Useful if you have multiple locale directories.
- `messageSyntaxVersion` (Optional) ... Specify the version of `vue-i18n` you are using. If not specified, the message will be parsed twice.

### Running ESLint from command line

Expand Down
51 changes: 22 additions & 29 deletions lib/rules/no-unused-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import type {
RuleFixer,
Fix,
SourceCode,
Range
Range,
CustomBlockVisitorFactory
} from '../types'
import { joinPath } from '../utils/key-path'
const debug = debugBuilder('eslint-plugin-vue-i18n:no-unused-keys')
Expand Down Expand Up @@ -46,12 +47,13 @@ function isDef<V>(v: V | null | undefined): v is V {
function getUsedKeysMap(
targetLocaleMessage: LocaleMessage,
values: I18nLocaleMessageDictionary,
usedkeys: string[]
usedkeys: string[],
context: RuleContext
): UsedKeys {
/** @type {UsedKeys} */
const usedKeysMap: UsedKeys = {}

for (const key of [...usedkeys, ...collectLinkedKeys(values)]) {
for (const key of [...usedkeys, ...collectLinkedKeys(values, context)]) {
const paths = key.split('.')
let map = usedKeysMap
while (paths.length) {
Expand Down Expand Up @@ -481,29 +483,13 @@ function create(context: RuleContext): RuleListener {
}

if (extname(filename) === '.vue') {
return defineCustomBlocksVisitor(
context,
ctx => {
const localeMessages = getLocaleMessages(context)
const usedLocaleMessageKeys = collectKeysFromAST(
context.getSourceCode().ast as VAST.ESLintProgram,
context.getSourceCode().visitorKeys
)
const targetLocaleMessage = localeMessages.findBlockLocaleMessage(
ctx.parserServices.customBlock
)
if (!targetLocaleMessage) {
return {}
}
const usedKeys = getUsedKeysMap(
targetLocaleMessage,
targetLocaleMessage.messages,
usedLocaleMessageKeys
)

return createVisitorForJson(ctx.getSourceCode(), usedKeys)
},
ctx => {
const createCustomBlockRule = (
createVisitor: (
sourceCode: SourceCode,
usedKeys: UsedKeys
) => RuleListener
): CustomBlockVisitorFactory => {
return ctx => {
const localeMessages = getLocaleMessages(context)
const usedLocaleMessageKeys = collectKeysFromAST(
context.getSourceCode().ast as VAST.ESLintProgram,
Expand All @@ -518,11 +504,17 @@ function create(context: RuleContext): RuleListener {
const usedKeys = getUsedKeysMap(
targetLocaleMessage,
targetLocaleMessage.messages,
usedLocaleMessageKeys
usedLocaleMessageKeys,
context
)

return createVisitorForYaml(ctx.getSourceCode(), usedKeys)
return createVisitor(ctx.getSourceCode(), usedKeys)
}
}
return defineCustomBlocksVisitor(
context,
createCustomBlockRule(createVisitorForJson),
createCustomBlockRule(createVisitorForYaml)
)
} else if (context.parserServices.isJSON || context.parserServices.isYAML) {
const localeMessages = getLocaleMessages(context)
Expand All @@ -543,7 +535,8 @@ function create(context: RuleContext): RuleListener {
const usedKeys = getUsedKeysMap(
targetLocaleMessage,
targetLocaleMessage.messages,
usedLocaleMessageKeys
usedLocaleMessageKeys,
context
)
if (context.parserServices.isJSON) {
return createVisitorForJson(sourceCode, usedKeys)
Expand Down
1 change: 1 addition & 0 deletions lib/types/eslint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export interface RuleContext {
settings: {
'vue-i18n'?: {
localeDir?: SettingsVueI18nLocaleDir
messageSyntaxVersion?: string
}
}
parserPath: string
Expand Down
64 changes: 39 additions & 25 deletions lib/utils/collect-linked-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,36 @@
* @fileoverview Collect the keys used by the linked messages.
* @author Yosuke Ota
*/
// Note: If vue-i18n@next parser is separated from vue plugin, change it to use that.

import type { I18nLocaleMessageDictionary } from '../types'

const linkKeyMatcher = /(?:@(?:\.[a-z]+)?:(?:[\w\-_|.]+|\([\w\-_|.]+\)))/g
const linkKeyPrefixMatcher = /^@(?:\.([a-z]+))?:/
const bracketsMatcher = /[()]/g
import type { ResourceNode } from '@intlify/message-compiler'
import { NodeTypes } from '@intlify/message-compiler'
import { traverseNode } from './message-compiler/traverser'
import type { I18nLocaleMessageDictionary, RuleContext } from '../types'
import { parse } from './message-compiler/parser'
import { parse as parseForV8 } from './message-compiler/parser-v8'
import type { MessageSyntaxVersions } from './message-compiler/utils'
import { getMessageSyntaxVersions } from './message-compiler/utils'

/**
* Extract the keys used by the linked messages.
* @param {any} object
* @returns {IterableIterator<string>}
*/
function* extractUsedKeysFromLinks(
object: I18nLocaleMessageDictionary
object: I18nLocaleMessageDictionary,
messageSyntaxVersions: MessageSyntaxVersions
): IterableIterator<string> {
for (const value of Object.values(object)) {
if (!value) {
continue
}
if (typeof value === 'object') {
yield* extractUsedKeysFromLinks(value)
yield* extractUsedKeysFromLinks(value, messageSyntaxVersions)
} else if (typeof value === 'string') {
if (value.indexOf('@:') >= 0 || value.indexOf('@.') >= 0) {
// see https://github.com/kazupon/vue-i18n/blob/c07d1914dcac186291b658a8b9627732010f6848/src/index.js#L435
const matches = value.match(linkKeyMatcher)!
for (const idx in matches) {
const link = matches[idx]
const linkKeyPrefixMatches = link.match(linkKeyPrefixMatcher)!
const [linkPrefix] = linkKeyPrefixMatches

// Remove the leading @:, @.case: and the brackets
const linkPlaceholder = link
.replace(linkPrefix, '')
.replace(bracketsMatcher, '')
yield linkPlaceholder
}
if (messageSyntaxVersions.v9) {
yield* extractUsedKeysFromAST(parse(value).ast)
}
if (messageSyntaxVersions.v8) {
yield* extractUsedKeysFromAST(parseForV8(value).ast)
}
}
}
Expand All @@ -50,7 +43,28 @@ function* extractUsedKeysFromLinks(
* @returns {string[]}
*/
export function collectLinkedKeys(
object: I18nLocaleMessageDictionary
object: I18nLocaleMessageDictionary,
context: RuleContext
): string[] {
return [...new Set<string>(extractUsedKeysFromLinks(object))]
return [
...new Set<string>(
extractUsedKeysFromLinks(object, getMessageSyntaxVersions(context))
)
].filter(s => !!s)
}

function extractUsedKeysFromAST(ast: ResourceNode): Set<string> {
const keys = new Set<string>()
traverseNode(ast, node => {
if (node.type === NodeTypes.Linked) {
if (node.key.type === NodeTypes.LinkedKey) {
keys.add(node.key.value)
} else if (node.key.type === NodeTypes.Literal) {
keys.add(node.key.value)
} else if (node.key.type === NodeTypes.List) {
keys.add(String(node.key.index))
}
}
})
return keys
}
Loading