Giter Club home page Giter Club logo

ngx-translate-lint's Introduction

ngx-translate-lint

Simple tools for check ngx-translate keys in Angular applications in whole app which use regexp.

Build Master semantic npm download npm

for react-intl use react-intl-lint

for react-i18next use react-i18next-lint

Table of Contents

Background

There are a lot of translation ngx-translate keys in the whole app. This repository contains a proposal to check all translation keys in the whole app which should exist in all languages files.

Installation

NPM

npm install ngx-translate-lint -g

GitHub

The source code are available for download at GitHub Releases and GitHub pages as well.

Usage

CLI


Usage: ngx-translate-lint [options]

Simple CLI tools for check `ngx-translate` keys in app

Options:
  -p,  --project [glob] (required)
          The path to project folder
          Possible Values: <relative path|absolute path>
          (default: "./src/app/**/*.{html,ts}")
  -l,  --languages [glob] (required)
          The path to languages folder
          Possible Values: <relative path|absolute path>
          (default: "./src/assets/i18n/*.json")
  -kv,  --keysOnViews [enum]
          Described how to handle the error of missing keys on view
          Possible Values: <disable|warning|error>
          (default: "error")
  -zk,  --zombieKeys [enum]
          Described how to handle the error of zombies keys
          Possible Values: <disable|warning|error>
          (default: "warning")
  -ek, --emptyKeys [enum]
          Described how to handle empty value on translate keys
          Possible Values: <disable|warning|error>
           (default: "warning")
  -i,  --ignore [glob]
          Ignore projects and languages files
          Possible Values: <relative path|absolute path>
  --maxWarning [glob]
          Max count of warnings in all files. If this value more that count of warnings, then an error is return
          Possible Values: <number>
           (default: "0")
  -mk,  --misprintKeys [enum]
          Try to find matches with misprint keys on views and languages keys. CCan be longer process!!
          Possible Values: <disable|warning|error>
           (default: "disable")
  -ds,  --deepSearch [enum]
          Add each translate key to global regexp end try to find them on project. Can be longer process!!
          Possible Values: <disable|enable>
           (default: "disable")
  -mc, --misprintCoefficient [number]
          Coefficient for misprint option can be from 0 to 1.0.
          (default: "0.9")
  -c, --config [path]
          Path to the config file.


  -V, --version   output the version number
  -h, --help      output usage information


Examples:

    $ npx ngx-translate-lint  -p ./src/app/**/*.{html,ts} -l ./src/assets/i18n/*.json
    $ ngx-translate-lint -p ./src/app/**/*.{html,ts} -l ./src/assets/i18n/*.json
    $ ngx-translate-lint -p ./src/app/**/*.{html,ts} -z disable -v error

NOTE: For project and languages options need to include file types like on the example. WARNING!: BETA flag working only with angular 11 and higher!

Default Config is:

{
    "rules": {
        "keysOnViews": "error",
        "zombieKeys": "warning",
        "misprintKeys": "disable",
        "deepSearch": "disable",
        "emptyKeys": "warning",
        "maxWarning": "0",
        "misprintCoefficient": "0.9",
        "ignoredKeys": [ "IGNORED.KEY.(.*)" ], // can be string or RegExp
        "ignoredMisprintKeys": [],
        "customRegExpToFindKeys": [ "(?<=marker\\(['\"])([A-Za-z0-9_\\-.]+)(?=['\"]\\))"], // to find: marker('TRSNLATE.KEY');
    },
    "project": "./src/app/**/*.{html,ts}",
    "languages": "./src/assets/i18n/*.json"
}

How to write Custom RegExp

We have (?<=marker\\(['\"])([A-Za-z0-9_\\-.]+)(?=['\"]\\)) RegExp witch contains of 3 parts:

  • Prefix - (?<=marker\\(['\"])

    • This construction tells that what we need matching before translate key
    • start with (?<= and end ).
    • marker\\(['\"] - tells that we try to find word market witch have on the second character 'or "
    • To summarize, we are trying to find keys before each word to be market and commas ' or "
  • Matching for key: ([A-Za-z0-9_\\-.]+)

    • This construction tells that we find and save all words which contain alphabet, numbers, and _ or -.
    • We recommend using this part of RegExp to find and save translated keys
    • But you can also use (.*) If it's enough for your project
  • Postfix - (?=['\"]\\)) (the same as prefix, but need to be ended)

    • This construction tells that what we need matching after translate key
    • start with (?= and end )
    • ['\"]\\) - tells that we try to find word comas ' or " and ended with )
    • To summarize, we are trying to find keys ended each word to be commas ' or " and )

Example RegExp will find following keys

  • marker('TRSNLATE.KEY')
  • marker("TRSNLATE.KEY-2")

Exit Codes

The CLI process may exit with the following codes:

  • 0: Linting succeeded without errors (warnings may have occurred)
  • 1: Linting failed with one or more rule violations with severity error
  • 2: An invalid command line argument or combination thereof was used

TypeScript

import { ToggleRule, NgxTranslateLint, IRulesConfig, ResultCliModel, ErrorTypes, LanguagesModel } from 'ngx-translate-lint';

const viewsPath: string = './src/app/**/*.{html,ts}';
const languagesPath: string = './src/assets/i18n/*.json';
const ignoredLanguagesPath: string = "./src/assets/i18n/ru.json, ./src/assets/i18n/ru-RU.json";
const ruleConfig: IRulesConfig = {
        keysOnViews: ErrorTypes.error,
        zombieKeys: ErrorTypes.warning,
        misprintKeys: ErrorTypes.disable,
        deepSearch: ToggleRule.disable,
        emptyKeys: ErrorTypes.warning,
        maxWarning: 0,
        misprintCoefficient: 0.9,
        ignoredKeys: [ 'EXAMPLE.KEY', 'IGNORED.KEY.(.*)' ], // can be string or RegExp
        ignoredMisprintKeys: [],
        customRegExpToFindKeys: [ "(?<=marker\\(['\"])([A-Za-z0-9_\\-.]+)(?=['\"]\\))" ] // to find: marker('TRSNLATE.KEY');
};

const ngxTranslateLint = new NgxTranslateLint(viewsPath, languagesPath, ignoredLanguagesPath, ruleConfig)
const resultLint: ResultCliModel = ngxTranslateLint.lint(); // Run Lint
const languages: LanguagesModel[] = ngxTranslateLint.getLanguages()  // Get Languages with all keys and views

NOTE!

If you have error Can't resolve 'fs' in .... Please add next setting to you project:

  • webpack.js: (angular.webpack.json)
config.externals = {
    ...config.externals,
    "fs": 'require("fs")',
    "path": 'require("path")'
};
  • tsconfig.json
{
   "skipLibCheck": true
}

Contribute

You may contribute in several ways like requesting new features, adding tests, fixing bugs, improving documentation or examples. Please check our contributing guidelines.

Used By

Here can be your extensions:

  • ngx-translate-editor - Simple GUI for CRUD translate keys of ngx-translate, which included ngx-translate-lint
  • 121 Platform - 121 is an open source platform for Cash based Aid built with Digital Identity & Local/Global Financial service partners.

License

MIT

ngx-translate-lint's People

Contributors

fvilers avatar itekaf avatar sebd71 avatar semantic-release-bot avatar wlucha avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

ngx-translate-lint's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Incorrect behaviour with component mat-icon

Bug report

Describe the bug

When I am using <mat-icon>keyboard_arrow_down</mat-icon> on the view , I am getting
Key: 'keyboard_arrow_down' doesn't exist in 'en.json' in console log

To Reproduce

  1. Use <mat-icon>keyboard_arrow_down</mat-icon> on the view
  2. npx ngx-translate-lint --zombies 'error'

Expected behavior

Ignore component mat-icon for translation, because name icon one for all languages.

Confusing option zombieKeys versus zombies (same for keysOnViews vs views)

Bug report

Describe the bug

The documentation and readme mention that zombieKeys in rules must be set to error|warning|disable in config file to define how zombie errors are handled.
But regarding the source code (file cli.js line 93 and 103), the key to set seems to be zombies

Same "problem" exists with keysOnViews => views.

To Reproduce

Steps to reproduce the behavior:

  • Create a config file myConfig.json with zombieKeys set to error:
{
    "rules": {
        "keysOnViews": "error",
        "zombieKeys": "error",
        "misprint": "warning",
        "maxWarning": "0",
        "misprintCoefficient": "0.9",
        "ignoredKeys": [],
        "ignoredMisprintKeys": [],
        "ast": {
          "isNgsTranslateImported": "error"
        }
    },
    "tsconfig": "./",
    "project": "./src/app/**/*.{html,ts}",
    "languages": "./src/assets/i18n/*.json"
}
  • Run with : npx ngx-translate-lint --config myConfig.json

  • See error
    zombie errors will be not handled as an error

Expected behavior

Now add "zombies" : "error" statement in myConfig.json :

{
    "rules": {
        "keysOnViews": "error",
        "zombies": "error",
        "misprint": "warning",
        "maxWarning": "0",
        "misprintCoefficient": "0.9",
        "ignoredKeys": [],
        "ignoredMisprintKeys": [],
        "ast": {
          "isNgsTranslateImported": "error"
        }
    },
    "tsconfig": "./",
    "project": "./src/app/**/*.{html,ts}",
    "languages": "./src/assets/i18n/*.json"
}

So I'm not sure of what is the right fix:
1- update the readme + doc and mention `zombies` and `views` names
2- or update code (line 91 - 103) to process `zombieKeys` and `keysOnViews` 

I would says solution 1 to have same naming as command line `--zombies` and  `--views`.

Create CLI tools for check `ngx-translat` keys

There are a lot of translation ngx-translate keys in the whole app.

This issue contains a proposal to check all translation keys in the whole app which should exist in all languages files.

I think a better solution for that case is CLI tools

This CLI must have arguments:

  • the path to a views folder, example ./src/app/
  • the path to languages file folder, example ./src/assets/i18n

If keys don't exist on language file, CLI should be print errors for each view and exit with status code 1 else nothing to print and the exit status is 0

Option: `max-warnings`

Feature request

Default config included warning error type for zombies keys, but for supports pure files we need to have a max-warnings count

Describe the solution you'd like

Create option max-warnings which should print errors if the count of warnings more then value.

Incorrect behaviour with --zombies 'error'

Bug report

Describe the bug

npx ngx-translate-lint --zombies 'error' exits with 0

according to the doc it should exit with 1 when some missed keys are present

To Reproduce

npx ngx-translate-lint --zombies 'error'

Expected behavior

returns 1 when some missed keys are found

Create config property and default config

Bug report

Describe the feature

  • Options for projects and languages path doesn't get an array
  • Includes files and extensions
  • Excludes files and extensions
  • all flags from CLI

Expected behavior

ngx-translate-lint -c './src/.ngxtling.json'

Documentation and code of `max-warning` flag is mismatch both of them

Bug report

According to the docs, an error status will be reported if the number of warnings are greater than the defined 'max-warning'. It looks to me like the code is still checking for ">=" when it should just be ">". So if I define 'max-warning' as 2, I would expect an OK result if 2 warnings occur...I wouldn't expect an error result until 3 or more warnings occur.

Treat empty value as missing

Feature request

Since translations should contain a text, it should be something in every language (I at least haven't discovered a case yet where it's not). Therefore I would like an option to treat an empty value of a key as a missing key.

parser take enums as keys for ngx-translate

Hi guys,

I have some issue because I use in projects a classic enums

export enum CreatorState {
  NEW,
  DRAFT,
  VERSION,
}

html

<h1 *ngIf="creatorState === CreatorState.NEW">{{'carousel.details.title-new' | translate}}</h1>

and when I run ngx-translate-lint I have a lot of error like this:

                Key: 'CreatorState.NEW' doesn't exist in 'en.json'
                Key: 'CreatorState.NEW' doesn't exist in 'es.json'

I tried to ignore this file, but for parameter ignore I can use only one path, but I have a lot of situations like this.
I think It was very helpful to make some annotation to ignore line like this

No report of missing translation when using `marker("key")`

Bug report

Describe the bug

The command does not report an error if a translation key is required using the following typescript:

import { marker } from "@biesbjerg/ngx-translate-extract-marker";

marker("some-random-translation-key");

To Reproduce

Steps to reproduce the behavior:

  • Add the package @biesbjerg/ngx-translate-extract-marker
  • Define a key in your translation files which you do not use.
  • Define a marker for it.
  • Running the linter you should see no warning anymore.
  • Define a marker for a translation key which is not translated.
  • Running the linter you do not see an error, as you would if you define a non-translated key in your HTML template.

Expected behavior

The command should fail when defining a marker for a translation key that does not exist.

Screenshots

Not applicable.

Additional context

I can verify that those keys are used in some way, because I can use them to suppress a notification of Key: 'some-other-random-translation-key' doesn't exist in project'

Rule: Try to match absent and error keys

Feature request

Some keys have misprint on views and languages.

For example:

{{ EXAMPLE.Key }}

and

{
   "EXAMPLE.KEY": "Value"
}

In current implementation it was error and warning, but it's wrong.

Describe the solution you'd like

I suggest add string-similarity to the project and try to match that case.

We can create some boolean option for it, like this: misprint

The `translate` directive inside html tags is sometimes not detected by the tool

Bug report

Describe the bug

The translate directive inside html tags is not detected by the tool for somewhat complex tags.

To Reproduce

Steps to reproduce the behavior:

Create a html file with the following content:

<mat-label fxLayoutAlign.xs="center center" [value]="test" translate anotherDirective>translation.key</mat-label>

Launch the linter on the project.

Expected behavior

The missing translation translation.key should be detected.

Cannot read property 'ignore' of undefined

Bug report

Describe the bug

When I am using: npx ngx-translate-lint --zombies 'error'
I am getting error: TypeError: Cannot read property 'ignore' of undefined
at Cli.runCli (..\node_modules\ngx-translate-lint\dist\src\cli\cli.js:65:66)
at Function.run (..\node_modules\ngx-translate-lint\dist\src\cli\cli.js:40:13)
at Object. (..\node_modules\ngx-translate-lint\dist\src\cli\bin.js:6:11)

My current ngx-translate-lint version "1.14.0".

To Reproduce

  1. npx ngx-translate-lint --zombies 'error'

Expected behavior

All work fine

ignoredKeys is not working

Bug report

Describe the bug

I used configuration:

{
  "rules": {
    "keysOnViews": "error",
    "zombieKeys": "warning",
    "misprint": "warning",
    "maxWarning": "0",
    "misprintCoefficient": "0.9",
    "ignoredKeys": [
      "projects.edit.paths_to_styles.no_items_edit",
      "projects.modal.domain.title",
      "projects.modal.domain.label",
      "projects.modal.path.title",
      "projects.modal.path.label"
    ]
  },
  "ast": "./",
  "project": "./apps/admin/src/app/**/*.{html,ts}",
  "languages": "./apps/admin/src/assets/i18n/*.json",
  "tsconfig": "./tsconfig.json"
}

and I run ng-translate-lint and after that, I had these keys which should be ignored


 Following file /admin/src/assets/i18n/en.json have errors:

                Key: 'projects.edit.paths_to_styles.no_items_edit' doesn't exist in project'

                Key: 'projects.modal.domain.title' doesn't exist in project'

                Key: 'projects.modal.domain.label' doesn't exist in project'

                Key: 'projects.modal.path.title' doesn't exist in project'

                Key: 'projects.modal.path.label' doesn't exist in project'


        Following file /admin/src/assets/i18n/es.json have errors:

                Key: 'projects.edit.paths_to_styles.no_items_edit' doesn't exist in project'

                Key: 'projects.modal.domain.title' doesn't exist in project'

                Key: 'projects.modal.domain.label' doesn't exist in project'

                Key: 'projects.modal.path.title' doesn't exist in project'

                Key: 'projects.modal.path.label' doesn't exist in project'

I used version 1.13.0

Refactor tests

Current tests are difficult for understanding.

Proposal is refactor them and create separate tests for features and bugs.

Use AOT compilation to detect translation field

Feature request

Is your feature request related to a problem? Please describe

Currently, I'm using some smaller components for the inputs. These components are using values passed as input to be rendered.

Describe the solution you'd like

Maybe by using angular AOT compiler, it will be possible to fetch the HTML outputted files to find the real used key.

Rule: Check if `i18n` exist on project

Feature request

Check if one of the translation exists on a project (i18n or ngx-translate). If exist both print error

Also, we can create rules wich separate:

  • Only one of translation
  • Print error if i18n exists on templates

Describe alternatives you've considered [optional]

Rules for i18n work on codelyzer

Create API

Create following methods:

  • getKeys
  • getLanguages
  • getViews

Error code is returned when number of warnings is equal to `max-warning` value

Bug report

Describe the bug

Running ngx-translate-lint always results in an error return code, due to the fact that the check for 'max-warning' checks whether the warning count is greater than or equal to 'max-warning'.

To Reproduce

Run ngx-translate-lint (without setting an explicit value for 'max-warning') on a project that has no errors and no warnings.

Expected behavior

I would expect the linter to return an "OK" code (0) if no errors and no warnings occur.

Screenshots

N/A

Additional context

Current workaround is to configure 'max-warning' with a value of '1', as opposed to using the default value of '0'.

AST option doesn't work

Bug report

Describe the bug

I don't have any import TranslateModule on my project (default), but when I run ngx-translate-lint with the flag ast linter doesn't write any errors about that case

To Reproduce

  1. Create simple project
  2. Run npx ngx-translate-lint --ast ./

Update README.md file

The current description of usage CLI isn't actual for develop branch. Please, update it.

Flag: skip keys

Suggestion create separate flag on config file which should be skip translations keys.

For more details look bug #61

Option: `ignore-files`

Feature request

When I have some a lot of languages but one of them used as a default for all, I don't need to check all

Describe the solution you'd like

Add ignore-files flag to languages and project options.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.