Compare commits
	
		
			70 Commits
		
	
	
		
			v4.2.0
			...
			chore-upda
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|  | 567a0586dc | ||
|  | 17dfbbed84 | ||
|  | acdffe0121 | ||
|  | 116133ba32 | ||
|  | 50b2ca6f4a | ||
|  | b46a914756 | ||
|  | bc3e5fbe2f | ||
|  | ea990d6f9d | ||
|  | c60705d5fa | ||
|  | 85cd1e4a46 | ||
|  | 8afbb2f3a9 | ||
|  | 329c24d962 | ||
|  | a30a6f9215 | ||
|  | 2adec54c00 | ||
|  | 619b3c56ea | ||
|  | 5e0da552b0 | ||
|  | 5f2eb2a7a0 | ||
|  | 90b59793a7 | ||
|  | deb6b2373b | ||
|  | 17dec7deb8 | ||
|  | 71f4f42b33 | ||
|  | 73f39d625c | ||
|  | 3bf2aaca4e | ||
|  | 05d1917f9d | ||
|  | e50d52003b | ||
|  | cb8731ee0f | ||
|  | 9908681243 | ||
|  | a83123fb12 | ||
|  | 6b740867d6 | ||
|  | d0e9a8cd85 | ||
|  | f157025f0a | ||
|  | ecf629118a | ||
|  | ce399ee717 | ||
|  | e8bc023ea6 | ||
|  | 33d8c26a28 | ||
|  | b07d929484 | ||
|  | a0f2b69f36 | ||
|  | 13f46a524f | ||
|  | 6ed962fa6e | ||
|  | 8aa2774eca | ||
|  | 37ca29648a | ||
|  | 97d844c3d2 | ||
|  | e7795c5349 | ||
|  | 9da4939f5d | ||
|  | 8fa7b60d2d | ||
|  | d3d6a72d5f | ||
|  | bfd069b755 | ||
|  | 72b4fb0545 | ||
|  | 131713d9db | ||
|  | a17ad9c373 | ||
|  | 56a5ab31bf | ||
|  | d579114dd2 | ||
|  | cc45df9b44 | ||
|  | b813ec0063 | ||
|  | 7b94c9b9a5 | ||
|  | a45039ef17 | ||
|  | 5d0c92871e | ||
|  | 9887f9d6ab | ||
|  | 608c4e8e22 | ||
|  | 0345778aa1 | ||
|  | 77769983d5 | ||
|  | 306622b9a0 | ||
|  | 7d0d52429f | ||
|  | 2fce357306 | ||
|  | 3827789346 | ||
|  | 8c8fe8d131 | ||
|  | 7bf0c138b8 | ||
|  | 16bf5f59e0 | ||
|  | 096fc79a9b | ||
|  | a72dbf0494 | 
							
								
								
									
										2
									
								
								.github/FUNDING.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.github/FUNDING.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,2 +1,2 @@ | |||||||
| github: #biesbjerg | github: biesbjerg | ||||||
| custom: https://donate.biesbjerg.com | custom: https://donate.biesbjerg.com | ||||||
|   | |||||||
							
								
								
									
										2
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							| @@ -8,6 +8,8 @@ npm-debug.log* | |||||||
|  |  | ||||||
| # Compiled files | # Compiled files | ||||||
| dist | dist | ||||||
|  | src/**/*.js | ||||||
|  | tests/**/*.js | ||||||
|  |  | ||||||
| # Extracted strings | # Extracted strings | ||||||
| strings.json | strings.json | ||||||
|   | |||||||
							
								
								
									
										90
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										90
									
								
								README.md
									
									
									
									
									
								
							| @@ -2,13 +2,11 @@ If this tool saves you time, please consider making a donation towards the conti | |||||||
|  |  | ||||||
| [](https://donate.biesbjerg.com) | [](https://donate.biesbjerg.com) | ||||||
|  |  | ||||||
| # Usage | # ngx-translate-extract | ||||||
|  |  | ||||||
| ## ngx-translate-extract |  | ||||||
| Extract translatable (ngx-translate) strings and save as a JSON or Gettext pot file. | Extract translatable (ngx-translate) strings and save as a JSON or Gettext pot file. | ||||||
| Merges with existing strings if the output file already exists. | Merges with existing strings if the output file already exists. | ||||||
|  |  | ||||||
| ### Usage | ## Install | ||||||
| Install the package in your project: | Install the package in your project: | ||||||
|  |  | ||||||
| `npm install @biesbjerg/ngx-translate-extract --save-dev` | `npm install @biesbjerg/ngx-translate-extract --save-dev` | ||||||
| @@ -17,33 +15,28 @@ Add a script to your project's `package.json`: | |||||||
| ```json | ```json | ||||||
| ... | ... | ||||||
| "scripts": { | "scripts": { | ||||||
|   "extract-i18n": "ngx-translate-extract --input ./src --output ./src/assets/i18n/ --clean --sort --format namespaced-json" |   "i18n:init": "ngx-translate-extract --input ./src --output ./src/assets/i18n/template.json --key-as-default-value --replace --format json", | ||||||
|  |   "i18n:extract": "ngx-translate-extract --input ./src --output ./src/assets/i18n/{en,da,de,fi,nb,nl,sv}.json --clean --format json" | ||||||
| } | } | ||||||
| ... | ... | ||||||
| ``` | ``` | ||||||
| You can now run `npm run extract-i18n` and it will extract strings from your project. | You can now run `npm run extract-i18n` and it will extract strings from your project. | ||||||
|  |  | ||||||
| ### Examples | ## Usage | ||||||
|  |  | ||||||
| **Extract from dir and save to file** | **Extract from dir and save to file** | ||||||
|  |  | ||||||
| `ngx-translate-extract --input ./src --output ./src/assets/i18n/template.json` | `ngx-translate-extract --input ./src --output ./src/assets/i18n/strings.json` | ||||||
|  |  | ||||||
| **Extract from multiple dirs** | **Extract from multiple dirs** | ||||||
|  |  | ||||||
| `ngx-translate-extract --input ./src-a ./src-b --output ./src/assets/i18n/template.json` | `ngx-translate-extract --input ./src-a ./src-b --output ./src/assets/i18n/strings.json` | ||||||
|  |  | ||||||
|  |  | ||||||
| **Extract and save to multiple files using path expansion** | **Extract and save to multiple files using path expansion** | ||||||
|  |  | ||||||
| _Note: This method does not work on Windows!_ |  | ||||||
|  |  | ||||||
| `ngx-translate-extract --input ./src --output ./src/i18n/{da,en}.json` | `ngx-translate-extract --input ./src --output ./src/i18n/{da,en}.json` | ||||||
|  |  | ||||||
| On Windows you must specify each output destination individually: |  | ||||||
|  |  | ||||||
| `ngx-translate-extract --input ./src --output ./src/i18n/da.json ./src/i18n/en.json` |  | ||||||
|  |  | ||||||
| ### JSON indentation | ### JSON indentation | ||||||
| Tabs are used by default for indentation when saving extracted strings in json formats: | Tabs are used by default for indentation when saving extracted strings in json formats: | ||||||
|  |  | ||||||
| @@ -51,8 +44,8 @@ If you want to use spaces instead, you can do the following: | |||||||
|  |  | ||||||
| `ngx-translate-extract --input ./src --output ./src/i18n/en.json --format-indentation '  '` | `ngx-translate-extract --input ./src --output ./src/i18n/en.json --format-indentation '  '` | ||||||
|  |  | ||||||
| ## Mark strings for extraction using a marker function | ### Marker function | ||||||
| If, for some reason, you want to extract strings not passed directly to `TranslateService`'s `get()` or `instant()` methods, you can wrap them in a marker function to let `ngx-translate-extract` know you want to extract them. | If you want to extract strings that are not passed directly to `TranslateService`'s `get()`/`instant()`/`stream()` methods, you can wrap them in a marker function to let `ngx-translate-extract` know you want to extract them. | ||||||
|  |  | ||||||
| Install marker function: | Install marker function: | ||||||
| `npm install @biesbjerg/ngx-translate-extract-marker` | `npm install @biesbjerg/ngx-translate-extract-marker` | ||||||
| @@ -63,10 +56,6 @@ import { marker } from '@biesbjerg/ngx-translate-extract-marker'; | |||||||
| marker('Extract me'); | marker('Extract me'); | ||||||
| ``` | ``` | ||||||
|  |  | ||||||
| Add the `marker` argument when running the extract script: |  | ||||||
|  |  | ||||||
| `ngx-translate-extract ... -m extract` |  | ||||||
|  |  | ||||||
| You can alias the marker function if needed: | You can alias the marker function if needed: | ||||||
|  |  | ||||||
| ```ts | ```ts | ||||||
| @@ -75,36 +64,45 @@ import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; | |||||||
| _('Extract me'); | _('Extract me'); | ||||||
| ``` | ``` | ||||||
|  |  | ||||||
| `ngx-translate-extract ... -m _` | _Note: `ngx-translate-extract` will automatically detect the import name_ | ||||||
|  |  | ||||||
| ## Commandline arguments | ### Commandline arguments | ||||||
| ``` | ``` | ||||||
| Usage: | Usage: | ||||||
| ngx-translate-extract [options] | ngx-translate-extract [options] | ||||||
|  |  | ||||||
|  | Output | ||||||
|  |   --format, -f                Format    [string] [choices: "json", "namespaced-json", "pot"] [default: "json"] | ||||||
|  |   --format-indentation, --fi  Format indentation (JSON/Namedspaced JSON)                [string] [default: "	"] | ||||||
|  |   --sort, -s                  Sort strings in alphabetical order                                     [boolean] | ||||||
|  |   --clean, -c                 Remove obsolete strings after merge                                    [boolean] | ||||||
|  |   --replace, -r               Replace the contents of output file if it exists (Merges by default)   [boolean] | ||||||
|  |  | ||||||
|  | Extracted key value (defaults to empty string) | ||||||
|  |   --key-as-default-value, -k     Use key as default value                                            [boolean] | ||||||
|  |   --null-as-default-value, -n    Use null as default value                                           [boolean] | ||||||
|  |   --string-as-default-value, -d  Use string as default value                                          [string] | ||||||
|  |  | ||||||
| Options: | Options: | ||||||
|   --version, -v               Show version number                      [boolean] |   --version, -v  Show version number                                                                 [boolean] | ||||||
|   --help, -h                  Show help                                [boolean] |   --help, -h     Show help                                                                           [boolean] | ||||||
|   --input, -i                 Paths you would like to extract strings from. You |   --input, -i    Paths you would like to extract strings from. You can use path expansion, glob patterns and | ||||||
|                               can use path expansion, glob patterns and multiple |                  multiple paths        [array] [required] [default: ["/Users/kim/apps/ngx-translate-extract"]] | ||||||
|                               paths |   --output, -o   Paths where you would like to save extracted strings. You can use path expansion, glob | ||||||
|                       [array] [default: current working path] |                  patterns and multiple paths                                                [array] [required] | ||||||
|      [array] [required] [default: current working path] |  | ||||||
|   --patterns, -p               Extract strings from the following file patterns | Examples: | ||||||
|                                     [array] [default: ["/**/*.html","/**/*.ts"]] |   ngx-translate-extract -i ./src-a/ -i ./src-b/ -o strings.json           Extract (ts, html) from multiple paths | ||||||
|   --output, -o                 Paths where you would like to save extracted |   ngx-translate-extract -i './{src-a,src-b}/' -o strings.json             Extract (ts, html) from multiple paths using brace | ||||||
|                                strings. You can use path expansion, glob |                                                            expansion | ||||||
|                                patterns and multiple paths    [array] [required] |   ngx-translate-extract -i ./src/ -o ./i18n/da.json -o ./i18n/en.json     Extract (ts, html) and save to da.json and en.json | ||||||
|   --format, -f                 Output format |   ngx-translate-extract -i ./src/ -o './i18n/{en,da}.json'                Extract (ts, html) and save to da.json and en.json | ||||||
|           [string] [choices: "json", "namespaced-json", "pot"] [default: "json"] |                                                            using brace expansion | ||||||
|   --format-indentation, --fi   Output format indentation  [string] [default: "	"] |   ngx-translate-extract -i './src/**/*.{ts,tsx,html}' -o strings.json     Extract from ts, tsx and html | ||||||
|   --replace, -r                Replace the contents of output file if it exists |   ngx-translate-extract -i './src/**/!(*.spec).{ts,html}' -o              Extract from ts, html, excluding files with ".spec" | ||||||
|                                (Merges by default)                     [boolean] |   strings.json | ||||||
|   --sort, -s                   Sort strings in alphabetical order when saving |  | ||||||
|                                                                        [boolean] |  | ||||||
|   --clean, -c                  Remove obsolete strings when merging    [boolean] |  | ||||||
|   --key-as-default-value, -k   Use key as default value for translations |  | ||||||
|                                                                        [boolean] |  | ||||||
|   --null-as-default-value, -n  Use null as default value for translations |  | ||||||
|                                                                        [boolean] |  | ||||||
| ``` | ``` | ||||||
|  |  | ||||||
|  | ## Note for GetText users | ||||||
|  |  | ||||||
|  | Please pay attention of which version of `gettext-parser` you actually use in your project. For instance, `gettext-parser:1.2.2` does not support HTML tags in translation keys. | ||||||
|   | |||||||
							
								
								
									
										2351
									
								
								package-lock.json
									
									
									
										generated
									
									
									
								
							
							
						
						
									
										2351
									
								
								package-lock.json
									
									
									
										generated
									
									
									
								
							
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							
							
								
								
									
										85
									
								
								package.json
									
									
									
									
									
								
							
							
						
						
									
										85
									
								
								package.json
									
									
									
									
									
								
							| @@ -1,6 +1,6 @@ | |||||||
| { | { | ||||||
|   "name": "@biesbjerg/ngx-translate-extract", |   "name": "@biesbjerg/ngx-translate-extract", | ||||||
|   "version": "4.2.0", |   "version": "7.0.3", | ||||||
|   "description": "Extract strings from projects using ngx-translate", |   "description": "Extract strings from projects using ngx-translate", | ||||||
|   "main": "dist/index.js", |   "main": "dist/index.js", | ||||||
|   "typings": "dist/index.d.ts", |   "typings": "dist/index.d.ts", | ||||||
| @@ -14,10 +14,27 @@ | |||||||
|   "scripts": { |   "scripts": { | ||||||
|     "build": "npm run clean && tsc", |     "build": "npm run clean && tsc", | ||||||
|     "watch": "npm run clean && tsc --watch", |     "watch": "npm run clean && tsc --watch", | ||||||
|     "clean": "rm -rf ./dist", |     "clean": "rimraf ./dist", | ||||||
|     "lint": "tslint --force './src/**/*.ts'", |     "lint": "tslint --force './src/**/*.ts'", | ||||||
|     "test": "mocha -r ts-node/register tests/**/*.spec.ts" |     "test": "mocha -r ts-node/register tests/**/*.spec.ts" | ||||||
|   }, |   }, | ||||||
|  |   "husky": { | ||||||
|  |     "hooks": { | ||||||
|  |       "pre-commit": "lint-staged && npm test" | ||||||
|  |     } | ||||||
|  |   }, | ||||||
|  |   "prettier": { | ||||||
|  |     "trailingComma": "none", | ||||||
|  |     "printWidth": 145, | ||||||
|  |     "useTabs": true, | ||||||
|  |     "singleQuote": true | ||||||
|  |   }, | ||||||
|  |   "lint-staged": { | ||||||
|  |     "{src,tests}/**/*.{ts}": [ | ||||||
|  |       "tslint --project tsconfig.json -c tslint.commit.json --fix", | ||||||
|  |       "prettier --write" | ||||||
|  |     ] | ||||||
|  |   }, | ||||||
|   "repository": { |   "repository": { | ||||||
|     "type": "git", |     "type": "git", | ||||||
|     "url": "https://github.com/biesbjerg/ngx-translate-extract.git" |     "url": "https://github.com/biesbjerg/ngx-translate-extract.git" | ||||||
| @@ -40,38 +57,48 @@ | |||||||
|   }, |   }, | ||||||
|   "homepage": "https://github.com/biesbjerg/ngx-translate-extract", |   "homepage": "https://github.com/biesbjerg/ngx-translate-extract", | ||||||
|   "engines": { |   "engines": { | ||||||
|     "node": ">=8" |     "node": ">=11.15.0" | ||||||
|   }, |   }, | ||||||
|   "config": {}, |   "config": {}, | ||||||
|   "devDependencies": { |   "devDependencies": { | ||||||
|     "@types/chai": "^4.2.2", |     "@angular/compiler": "^11.2.9", | ||||||
|     "@types/flat": "^0.0.28", |     "@types/braces": "^3.0.0", | ||||||
|     "@types/glob": "^7.1.1", |     "@types/chai": "^4.2.16", | ||||||
|     "@types/mkdirp": "^0.5.2", |     "@types/flat": "^5.0.1", | ||||||
|     "@types/mocha": "^5.2.7", |     "@types/gettext-parser": "4.0.0", | ||||||
|     "@types/node": "^12.7.5", |     "@types/glob": "^7.1.3", | ||||||
|     "@types/yargs": "^13.0.2", |     "@types/mkdirp": "^1.0.1", | ||||||
|     "chai": "^4.2.0", |     "@types/mocha": "^8.2.2", | ||||||
|     "mocha": "^6.2.0", |     "@types/node": "^14.14.37", | ||||||
|     "ts-node": "^8.4.1", |     "@types/yargs": "^16.0.1", | ||||||
|     "tslint": "^5.20.0", |     "braces": "^3.0.2", | ||||||
|     "tslint-eslint-rules": "^5.4.0" |     "chai": "^4.3.4", | ||||||
|  |     "husky": "^6.0.0", | ||||||
|  |     "lint-staged": "^10.5.4", | ||||||
|  |     "mocha": "^8.3.2", | ||||||
|  |     "prettier": "^2.2.1", | ||||||
|  |     "rimraf": "^3.0.2", | ||||||
|  |     "ts-node": "^9.1.1", | ||||||
|  |     "tslint": "^6.1.3", | ||||||
|  |     "tslint-config-prettier": "^1.18.0", | ||||||
|  |     "tslint-eslint-rules": "^5.4.0", | ||||||
|  |     "tslint-etc": "^1.13.9", | ||||||
|  |     "typescript": "^4.2.4" | ||||||
|  |   }, | ||||||
|  |   "peerDependencies": { | ||||||
|  |     "@angular/compiler": ">=8.0.0", | ||||||
|  |     "typescript": ">=3.0.0" | ||||||
|   }, |   }, | ||||||
|   "bundledDependencies": [ |  | ||||||
|     "flat" |  | ||||||
|   ], |  | ||||||
|   "dependencies": { |   "dependencies": { | ||||||
|     "@angular/compiler": "^8.2.6", |     "@phenomnomnominal/tsquery": "^4.1.1", | ||||||
|     "@phenomnomnominal/tsquery": "^3.0.0", |     "boxen": "^5.0.1", | ||||||
|     "boxen": "^4.1.0", |     "colorette": "^1.2.2", | ||||||
|     "colorette": "^1.1.0", |     "flat": "^5.0.2", | ||||||
|     "flat": "github:lenchvolodymyr/flat#ffe77ef", |     "gettext-parser": "^4.0.4", | ||||||
|     "gettext-parser": "^4.0.2", |     "glob": "^7.1.6", | ||||||
|     "glob": "^7.1.4", |     "mkdirp": "^1.0.4", | ||||||
|     "mkdirp": "^0.5.1", |  | ||||||
|     "path": "^0.12.7", |     "path": "^0.12.7", | ||||||
|     "terminal-link": "^2.0.0", |     "terminal-link": "^2.1.1", | ||||||
|     "typescript": "^3.6.3", |     "yargs": "^16.2.0" | ||||||
|     "yargs": "^14.0.0" |  | ||||||
|   } |   } | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,5 +1,5 @@ | |||||||
| import * as fs from 'fs'; |  | ||||||
| import * as yargs from 'yargs'; | import * as yargs from 'yargs'; | ||||||
|  | import { red, green } from 'colorette'; | ||||||
|  |  | ||||||
| import { ExtractTask } from './tasks/extract.task'; | import { ExtractTask } from './tasks/extract.task'; | ||||||
| import { ParserInterface } from '../parsers/parser.interface'; | import { ParserInterface } from '../parsers/parser.interface'; | ||||||
| @@ -11,12 +11,25 @@ import { PostProcessorInterface } from '../post-processors/post-processor.interf | |||||||
| import { SortByKeyPostProcessor } from '../post-processors/sort-by-key.post-processor'; | import { SortByKeyPostProcessor } from '../post-processors/sort-by-key.post-processor'; | ||||||
| import { KeyAsDefaultValuePostProcessor } from '../post-processors/key-as-default-value.post-processor'; | import { KeyAsDefaultValuePostProcessor } from '../post-processors/key-as-default-value.post-processor'; | ||||||
| import { NullAsDefaultValuePostProcessor } from '../post-processors/null-as-default-value.post-processor'; | import { NullAsDefaultValuePostProcessor } from '../post-processors/null-as-default-value.post-processor'; | ||||||
|  | import { StringAsDefaultValuePostProcessor } from '../post-processors/string-as-default-value.post-processor'; | ||||||
| import { PurgeObsoleteKeysPostProcessor } from '../post-processors/purge-obsolete-keys.post-processor'; | import { PurgeObsoleteKeysPostProcessor } from '../post-processors/purge-obsolete-keys.post-processor'; | ||||||
| import { CompilerInterface } from '../compilers/compiler.interface'; | import { CompilerInterface } from '../compilers/compiler.interface'; | ||||||
| import { CompilerFactory } from '../compilers/compiler.factory'; | import { CompilerFactory } from '../compilers/compiler.factory'; | ||||||
|  | import { normalizePaths } from '../utils/fs-helpers'; | ||||||
| import { donateMessage } from '../utils/donate'; | import { donateMessage } from '../utils/donate'; | ||||||
|  |  | ||||||
| export const cli = yargs | // First parsing pass to be able to access pattern argument for use input/output arguments | ||||||
|  | const y = yargs.option('patterns', { | ||||||
|  | 	alias: 'p', | ||||||
|  | 	describe: 'Default patterns', | ||||||
|  | 	type: 'array', | ||||||
|  | 	default: ['/**/*.html', '/**/*.ts'], | ||||||
|  | 	hidden: true | ||||||
|  | }); | ||||||
|  |  | ||||||
|  | const parsed = y.parse(); | ||||||
|  |  | ||||||
|  | export const cli = y | ||||||
| 	.usage('Extract strings from files for translation.\nUsage: $0 [options]') | 	.usage('Extract strings from files for translation.\nUsage: $0 [options]') | ||||||
| 	.version(require(__dirname + '/../../package.json').version) | 	.version(require(__dirname + '/../../package.json').version) | ||||||
| 	.alias('version', 'v') | 	.alias('version', 'v') | ||||||
| @@ -30,20 +43,9 @@ export const cli = yargs | |||||||
| 		normalize: true, | 		normalize: true, | ||||||
| 		required: true | 		required: true | ||||||
| 	}) | 	}) | ||||||
| 	.check(options => { | 	.coerce('input', (input: string[]) => { | ||||||
| 		options.input.forEach((dir: string) => { | 		const paths = normalizePaths(input, parsed.patterns); | ||||||
| 			if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) { | 		return paths; | ||||||
| 				throw new Error(`The path you supplied was not found: '${dir}'`); |  | ||||||
| 			} |  | ||||||
|  |  | ||||||
| 		}); |  | ||||||
| 		return true; |  | ||||||
| 	}) |  | ||||||
| 	.option('patterns', { |  | ||||||
| 		alias: 'p', |  | ||||||
| 		describe: 'Extract strings from the following file patterns', |  | ||||||
| 		type: 'array', |  | ||||||
| 		default: ['/**/*.html', '/**/*.ts'] |  | ||||||
| 	}) | 	}) | ||||||
| 	.option('output', { | 	.option('output', { | ||||||
| 		alias: 'o', | 		alias: 'o', | ||||||
| @@ -52,16 +54,20 @@ export const cli = yargs | |||||||
| 		normalize: true, | 		normalize: true, | ||||||
| 		required: true | 		required: true | ||||||
| 	}) | 	}) | ||||||
|  | 	.coerce('output', (output: string[]) => { | ||||||
|  | 		const paths = normalizePaths(output, parsed.patterns); | ||||||
|  | 		return paths; | ||||||
|  | 	}) | ||||||
| 	.option('format', { | 	.option('format', { | ||||||
| 		alias: 'f', | 		alias: 'f', | ||||||
| 		describe: 'Output format', | 		describe: 'Format', | ||||||
| 		default: 'json', | 		default: 'json', | ||||||
| 		type: 'string', | 		type: 'string', | ||||||
| 		choices: ['json', 'namespaced-json', 'pot'] | 		choices: ['json', 'namespaced-json', 'pot'] | ||||||
| 	}) | 	}) | ||||||
| 	.option('format-indentation', { | 	.option('format-indentation', { | ||||||
| 		alias: 'fi', | 		alias: 'fi', | ||||||
| 		describe: 'Output format indentation', | 		describe: 'Format indentation (JSON/Namedspaced JSON)', | ||||||
| 		default: '\t', | 		default: '\t', | ||||||
| 		type: 'string' | 		type: 'string' | ||||||
| 	}) | 	}) | ||||||
| @@ -72,40 +78,51 @@ export const cli = yargs | |||||||
| 	}) | 	}) | ||||||
| 	.option('sort', { | 	.option('sort', { | ||||||
| 		alias: 's', | 		alias: 's', | ||||||
| 		describe: 'Sort strings in alphabetical order when saving', | 		describe: 'Sort strings in alphabetical order', | ||||||
| 		type: 'boolean' | 		type: 'boolean' | ||||||
| 	}) | 	}) | ||||||
| 	.option('clean', { | 	.option('clean', { | ||||||
| 		alias: 'c', | 		alias: 'c', | ||||||
| 		describe: 'Remove obsolete strings when merging', | 		describe: 'Remove obsolete strings after merge', | ||||||
| 		type: 'boolean' | 		type: 'boolean' | ||||||
| 	}) | 	}) | ||||||
| 	.option('key-as-default-value', { | 	.option('key-as-default-value', { | ||||||
| 		alias: 'k', | 		alias: 'k', | ||||||
| 		describe: 'Use key as default value for translations', | 		describe: 'Use key as default value', | ||||||
| 		type: 'boolean' | 		type: 'boolean', | ||||||
|  | 		conflicts: ['null-as-default-value', 'string-as-default-value'] | ||||||
| 	}) | 	}) | ||||||
| 	.option('null-as-default-value', { | 	.option('null-as-default-value', { | ||||||
| 		alias: 'n', | 		alias: 'n', | ||||||
| 		describe: 'Use null as default value for translations', | 		describe: 'Use null as default value', | ||||||
| 		type: 'boolean' | 		type: 'boolean', | ||||||
|  | 		conflicts: ['key-as-default-value', 'string-as-default-value'] | ||||||
| 	}) | 	}) | ||||||
|  | 	.option('string-as-default-value', { | ||||||
|  | 		alias: 'd', | ||||||
|  | 		describe: 'Use string as default value', | ||||||
|  | 		type: 'string', | ||||||
|  | 		conflicts: ['null-as-default-value', 'key-as-default-value'] | ||||||
|  | 	}) | ||||||
|  | 	.group(['format', 'format-indentation', 'sort', 'clean', 'replace'], 'Output') | ||||||
|  | 	.group(['key-as-default-value', 'null-as-default-value', 'string-as-default-value'], 'Extracted key value (defaults to empty string)') | ||||||
| 	.conflicts('key-as-default-value', 'null-as-default-value') | 	.conflicts('key-as-default-value', 'null-as-default-value') | ||||||
|  | 	.example(`$0 -i ./src-a/ -i ./src-b/ -o strings.json`, 'Extract (ts, html) from multiple paths') | ||||||
|  | 	.example(`$0 -i './{src-a,src-b}/' -o strings.json`, 'Extract (ts, html) from multiple paths using brace expansion') | ||||||
|  | 	.example(`$0 -i ./src/ -o ./i18n/da.json -o ./i18n/en.json`, 'Extract (ts, html) and save to da.json and en.json') | ||||||
|  | 	.example(`$0 -i ./src/ -o './i18n/{en,da}.json'`, 'Extract (ts, html) and save to da.json and en.json using brace expansion') | ||||||
|  | 	.example(`$0 -i './src/**/*.{ts,tsx,html}' -o strings.json`, 'Extract from ts, tsx and html') | ||||||
|  | 	.example(`$0 -i './src/**/!(*.spec).{ts,html}' -o strings.json`, 'Extract from ts, html, excluding files with ".spec" in filename') | ||||||
|  | 	.wrap(110) | ||||||
| 	.exitProcess(true) | 	.exitProcess(true) | ||||||
| 	.parse(process.argv); | 	.parse(process.argv); | ||||||
|  |  | ||||||
| const extractTask = new ExtractTask(cli.input, cli.output, { | const extractTask = new ExtractTask(cli.input, cli.output, { | ||||||
| 	replace: cli.replace, | 	replace: cli.replace | ||||||
| 	patterns: cli.patterns |  | ||||||
| }); | }); | ||||||
|  |  | ||||||
| // Parsers | // Parsers | ||||||
| const parsers: ParserInterface[] = [ | const parsers: ParserInterface[] = [new PipeParser(), new DirectiveParser(), new ServiceParser(), new MarkerParser()]; | ||||||
| 	new PipeParser(), |  | ||||||
| 	new DirectiveParser(), |  | ||||||
| 	new ServiceParser(), |  | ||||||
| 	new MarkerParser() |  | ||||||
| ]; |  | ||||||
| extractTask.setParsers(parsers); | extractTask.setParsers(parsers); | ||||||
|  |  | ||||||
| // Post processors | // Post processors | ||||||
| @@ -117,7 +134,10 @@ if (cli.keyAsDefaultValue) { | |||||||
| 	postProcessors.push(new KeyAsDefaultValuePostProcessor()); | 	postProcessors.push(new KeyAsDefaultValuePostProcessor()); | ||||||
| } else if (cli.nullAsDefaultValue) { | } else if (cli.nullAsDefaultValue) { | ||||||
| 	postProcessors.push(new NullAsDefaultValuePostProcessor()); | 	postProcessors.push(new NullAsDefaultValuePostProcessor()); | ||||||
|  | } else if (cli.stringAsDefaultValue) { | ||||||
|  | 	postProcessors.push(new StringAsDefaultValuePostProcessor({ defaultValue: cli.stringAsDefaultValue as string })); | ||||||
| } | } | ||||||
|  |  | ||||||
| if (cli.sort) { | if (cli.sort) { | ||||||
| 	postProcessors.push(new SortByKeyPostProcessor()); | 	postProcessors.push(new SortByKeyPostProcessor()); | ||||||
| } | } | ||||||
| @@ -129,6 +149,13 @@ const compiler: CompilerInterface = CompilerFactory.create(cli.format, { | |||||||
| }); | }); | ||||||
| extractTask.setCompiler(compiler); | extractTask.setCompiler(compiler); | ||||||
|  |  | ||||||
| extractTask.execute(); | // Run task | ||||||
|  | try { | ||||||
| console.log(donateMessage); | 	extractTask.execute(); | ||||||
|  | 	console.log(green('\nDone.\n')); | ||||||
|  | 	console.log(donateMessage); | ||||||
|  | 	process.exit(0); | ||||||
|  | } catch (e) { | ||||||
|  | 	console.log(red(`\nAn error occurred: ${e}\n`)); | ||||||
|  | 	process.exit(1); | ||||||
|  | } | ||||||
|   | |||||||
| @@ -4,7 +4,7 @@ import { ParserInterface } from '../../parsers/parser.interface'; | |||||||
| import { PostProcessorInterface } from '../../post-processors/post-processor.interface'; | import { PostProcessorInterface } from '../../post-processors/post-processor.interface'; | ||||||
| import { CompilerInterface } from '../../compilers/compiler.interface'; | import { CompilerInterface } from '../../compilers/compiler.interface'; | ||||||
|  |  | ||||||
| import { cyan, green, bold, dim } from 'colorette'; | import { cyan, green, bold, dim, red } from 'colorette'; | ||||||
| import * as glob from 'glob'; | import * as glob from 'glob'; | ||||||
| import * as fs from 'fs'; | import * as fs from 'fs'; | ||||||
| import * as path from 'path'; | import * as path from 'path'; | ||||||
| @@ -12,14 +12,11 @@ import * as mkdirp from 'mkdirp'; | |||||||
|  |  | ||||||
| export interface ExtractTaskOptionsInterface { | export interface ExtractTaskOptionsInterface { | ||||||
| 	replace?: boolean; | 	replace?: boolean; | ||||||
| 	patterns?: string[]; |  | ||||||
| } | } | ||||||
|  |  | ||||||
| export class ExtractTask implements TaskInterface { | export class ExtractTask implements TaskInterface { | ||||||
|  |  | ||||||
| 	protected options: ExtractTaskOptionsInterface = { | 	protected options: ExtractTaskOptionsInterface = { | ||||||
| 		replace: false, | 		replace: false | ||||||
| 		patterns: [] |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	protected parsers: ParserInterface[] = []; | 	protected parsers: ParserInterface[] = []; | ||||||
| @@ -27,8 +24,8 @@ export class ExtractTask implements TaskInterface { | |||||||
| 	protected compiler: CompilerInterface; | 	protected compiler: CompilerInterface; | ||||||
|  |  | ||||||
| 	public constructor(protected inputs: string[], protected outputs: string[], options?: ExtractTaskOptionsInterface) { | 	public constructor(protected inputs: string[], protected outputs: string[], options?: ExtractTaskOptionsInterface) { | ||||||
| 		this.inputs = inputs.map(input => path.resolve(input)); | 		this.inputs = inputs.map((input) => path.resolve(input)); | ||||||
| 		this.outputs = outputs.map(output => path.resolve(output)); | 		this.outputs = outputs.map((output) => path.resolve(output)); | ||||||
| 		this.options = { ...this.options, ...options }; | 		this.options = { ...this.options, ...options }; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -47,7 +44,7 @@ export class ExtractTask implements TaskInterface { | |||||||
|  |  | ||||||
| 		this.out(bold('Saving:')); | 		this.out(bold('Saving:')); | ||||||
|  |  | ||||||
| 		this.outputs.forEach(output => { | 		this.outputs.forEach((output) => { | ||||||
| 			let dir: string = output; | 			let dir: string = output; | ||||||
| 			let filename: string = `strings.${this.compiler.extension}`; | 			let filename: string = `strings.${this.compiler.extension}`; | ||||||
| 			if (!fs.existsSync(output) || !fs.statSync(output).isDirectory()) { | 			if (!fs.existsSync(output) || !fs.statSync(output).isDirectory()) { | ||||||
| @@ -59,26 +56,33 @@ export class ExtractTask implements TaskInterface { | |||||||
|  |  | ||||||
| 			let existing: TranslationCollection = new TranslationCollection(); | 			let existing: TranslationCollection = new TranslationCollection(); | ||||||
| 			if (!this.options.replace && fs.existsSync(outputPath)) { | 			if (!this.options.replace && fs.existsSync(outputPath)) { | ||||||
| 				existing = this.compiler.parse(fs.readFileSync(outputPath, 'utf-8')); | 				try { | ||||||
|  | 					existing = this.compiler.parse(fs.readFileSync(outputPath, 'utf-8')); | ||||||
|  | 				} catch (e) { | ||||||
|  | 					this.out(`%s %s`, dim(`- ${outputPath}`), red(`[ERROR]`)); | ||||||
|  | 					throw e; | ||||||
|  | 				} | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			// merge extracted strings with existing | 			// merge extracted strings with existing | ||||||
| 			const draft = extracted.union(existing); | 			const draft = extracted.union(existing); | ||||||
|  |  | ||||||
| 			if (existing.isEmpty()) { |  | ||||||
| 				this.out(dim(`- ${outputPath}`)); |  | ||||||
| 			} else { |  | ||||||
| 				this.out(dim(`- ${outputPath} (merged)`)); |  | ||||||
| 			} |  | ||||||
|  |  | ||||||
| 			// Run collection through post processors | 			// Run collection through post processors | ||||||
| 			const final = this.process(draft, extracted, existing); | 			const final = this.process(draft, extracted, existing); | ||||||
|  |  | ||||||
| 			// Save to file | 			// Save | ||||||
| 			this.save(outputPath, final); | 			try { | ||||||
|  | 				let event = 'CREATED'; | ||||||
|  | 				if (fs.existsSync(outputPath)) { | ||||||
|  | 					this.options.replace ? (event = 'REPLACED') : (event = 'MERGED'); | ||||||
|  | 				} | ||||||
|  | 				this.save(outputPath, final); | ||||||
|  | 				this.out(`%s %s`, dim(`- ${outputPath}`), green(`[${event}]`)); | ||||||
|  | 			} catch (e) { | ||||||
|  | 				this.out(`%s %s`, dim(`- ${outputPath}`), red(`[ERROR]`)); | ||||||
|  | 				throw e; | ||||||
|  | 			} | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		this.out(green('\nDone.\n')); |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public setParsers(parsers: ParserInterface[]): this { | 	public setParsers(parsers: ParserInterface[]): this { | ||||||
| @@ -101,13 +105,13 @@ export class ExtractTask implements TaskInterface { | |||||||
| 	 */ | 	 */ | ||||||
| 	protected extract(): TranslationCollection { | 	protected extract(): TranslationCollection { | ||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
| 		this.inputs.forEach(dir => { | 		this.inputs.forEach((pattern) => { | ||||||
| 			this.readDir(dir, this.options.patterns).forEach(path => { | 			this.getFiles(pattern).forEach((filePath) => { | ||||||
| 				this.out(dim('- %s'), path); | 				this.out(dim('- %s'), filePath); | ||||||
| 				const contents: string = fs.readFileSync(path, 'utf-8'); | 				const contents: string = fs.readFileSync(filePath, 'utf-8'); | ||||||
| 				this.parsers.forEach(parser => { | 				this.parsers.forEach((parser) => { | ||||||
| 					const extracted = parser.extract(contents, path); | 					const extracted = parser.extract(contents, filePath); | ||||||
| 					if (extracted) { | 					if (extracted instanceof TranslationCollection) { | ||||||
| 						collection = collection.union(extracted); | 						collection = collection.union(extracted); | ||||||
| 					} | 					} | ||||||
| 				}); | 				}); | ||||||
| @@ -120,7 +124,7 @@ export class ExtractTask implements TaskInterface { | |||||||
| 	 * Run strings through configured post processors | 	 * Run strings through configured post processors | ||||||
| 	 */ | 	 */ | ||||||
| 	protected process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | 	protected process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | ||||||
| 		this.postProcessors.forEach(postProcessor => { | 		this.postProcessors.forEach((postProcessor) => { | ||||||
| 			draft = postProcessor.process(draft, extracted, existing); | 			draft = postProcessor.process(draft, extracted, existing); | ||||||
| 		}); | 		}); | ||||||
| 		return draft; | 		return draft; | ||||||
| @@ -139,14 +143,10 @@ export class ExtractTask implements TaskInterface { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
| 	 * Get all files in dir matching patterns | 	 * Get all files matching pattern | ||||||
| 	 */ | 	 */ | ||||||
| 	protected readDir(dir: string, patterns: string[]): string[] { | 	protected getFiles(pattern: string): string[] { | ||||||
| 		return patterns.reduce((results, pattern) => { | 		return glob.sync(pattern).filter((filePath) => fs.statSync(filePath).isFile()); | ||||||
| 			return glob.sync(dir + pattern) |  | ||||||
| 				.filter(path => fs.statSync(path).isFile()) |  | ||||||
| 				.concat(results); |  | ||||||
| 		}, []); |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	protected out(...args: any[]): void { | 	protected out(...args: any[]): void { | ||||||
| @@ -156,7 +156,7 @@ export class ExtractTask implements TaskInterface { | |||||||
| 	protected printEnabledParsers(): void { | 	protected printEnabledParsers(): void { | ||||||
| 		this.out(cyan('Enabled parsers:')); | 		this.out(cyan('Enabled parsers:')); | ||||||
| 		if (this.parsers.length) { | 		if (this.parsers.length) { | ||||||
| 			this.out(cyan(dim(this.parsers.map(parser => `- ${parser.constructor.name}`).join('\n')))); | 			this.out(cyan(dim(this.parsers.map((parser) => `- ${parser.constructor.name}`).join('\n')))); | ||||||
| 		} else { | 		} else { | ||||||
| 			this.out(cyan(dim('(none)'))); | 			this.out(cyan(dim('(none)'))); | ||||||
| 		} | 		} | ||||||
| @@ -166,7 +166,7 @@ export class ExtractTask implements TaskInterface { | |||||||
| 	protected printEnabledPostProcessors(): void { | 	protected printEnabledPostProcessors(): void { | ||||||
| 		this.out(cyan('Enabled post processors:')); | 		this.out(cyan('Enabled post processors:')); | ||||||
| 		if (this.postProcessors.length) { | 		if (this.postProcessors.length) { | ||||||
| 			this.out(cyan(dim(this.postProcessors.map(postProcessor => `- ${postProcessor.constructor.name}`).join('\n')))); | 			this.out(cyan(dim(this.postProcessors.map((postProcessor) => `- ${postProcessor.constructor.name}`).join('\n')))); | ||||||
| 		} else { | 		} else { | ||||||
| 			this.out(cyan(dim('(none)'))); | 			this.out(cyan(dim('(none)'))); | ||||||
| 		} | 		} | ||||||
| @@ -178,5 +178,4 @@ export class ExtractTask implements TaskInterface { | |||||||
| 		this.out(cyan(dim(`- ${this.compiler.constructor.name}`))); | 		this.out(cyan(dim(`- ${this.compiler.constructor.name}`))); | ||||||
| 		this.out(); | 		this.out(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -4,14 +4,16 @@ import { NamespacedJsonCompiler } from '../compilers/namespaced-json.compiler'; | |||||||
| import { PoCompiler } from '../compilers/po.compiler'; | import { PoCompiler } from '../compilers/po.compiler'; | ||||||
|  |  | ||||||
| export class CompilerFactory { | export class CompilerFactory { | ||||||
|  |  | ||||||
| 	public static create(format: string, options?: {}): CompilerInterface { | 	public static create(format: string, options?: {}): CompilerInterface { | ||||||
| 		switch (format) { | 		switch (format) { | ||||||
| 			case 'pot': return new PoCompiler(options); | 			case 'pot': | ||||||
| 			case 'json': return new JsonCompiler(options); | 				return new PoCompiler(options); | ||||||
| 			case 'namespaced-json': return new NamespacedJsonCompiler(options); | 			case 'json': | ||||||
| 			default: throw new Error(`Unknown format: ${format}`); | 				return new JsonCompiler(options); | ||||||
|  | 			case 'namespaced-json': | ||||||
|  | 				return new NamespacedJsonCompiler(options); | ||||||
|  | 			default: | ||||||
|  | 				throw new Error(`Unknown format: ${format}`); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,11 +1,9 @@ | |||||||
| import { TranslationCollection } from '../utils/translation.collection'; | import { TranslationCollection } from '../utils/translation.collection'; | ||||||
|  |  | ||||||
| export interface CompilerInterface { | export interface CompilerInterface { | ||||||
|  |  | ||||||
| 	extension: string; | 	extension: string; | ||||||
|  |  | ||||||
| 	compile(collection: TranslationCollection): string; | 	compile(collection: TranslationCollection): string; | ||||||
|  |  | ||||||
| 	parse(contents: string): TranslationCollection; | 	parse(contents: string): TranslationCollection; | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -5,7 +5,6 @@ import { stripBOM } from '../utils/utils'; | |||||||
| import { flatten } from 'flat'; | import { flatten } from 'flat'; | ||||||
|  |  | ||||||
| export class JsonCompiler implements CompilerInterface { | export class JsonCompiler implements CompilerInterface { | ||||||
|  |  | ||||||
| 	public indentation: string = '\t'; | 	public indentation: string = '\t'; | ||||||
|  |  | ||||||
| 	public extension: string = 'json'; | 	public extension: string = 'json'; | ||||||
| @@ -29,7 +28,6 @@ export class JsonCompiler implements CompilerInterface { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	protected isNamespacedJsonFormat(values: any): boolean { | 	protected isNamespacedJsonFormat(values: any): boolean { | ||||||
| 		return Object.keys(values).some(key => typeof values[key] === 'object'); | 		return Object.keys(values).some((key) => typeof values[key] === 'object'); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -5,7 +5,6 @@ import { stripBOM } from '../utils/utils'; | |||||||
| import { flatten, unflatten } from 'flat'; | import { flatten, unflatten } from 'flat'; | ||||||
|  |  | ||||||
| export class NamespacedJsonCompiler implements CompilerInterface { | export class NamespacedJsonCompiler implements CompilerInterface { | ||||||
|  |  | ||||||
| 	public indentation: string = '\t'; | 	public indentation: string = '\t'; | ||||||
|  |  | ||||||
| 	public extension = 'json'; | 	public extension = 'json'; | ||||||
| @@ -27,5 +26,4 @@ export class NamespacedJsonCompiler implements CompilerInterface { | |||||||
| 		const values: {} = flatten(JSON.parse(stripBOM(contents))); | 		const values: {} = flatten(JSON.parse(stripBOM(contents))); | ||||||
| 		return new TranslationCollection(values); | 		return new TranslationCollection(values); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,10 +1,9 @@ | |||||||
| import { CompilerInterface } from './compiler.interface'; | import { CompilerInterface } from './compiler.interface'; | ||||||
| import { TranslationCollection, TranslationType } from '../utils/translation.collection'; | import { TranslationCollection, TranslationType } from '../utils/translation.collection'; | ||||||
|  |  | ||||||
| import * as gettext from 'gettext-parser'; | import { po } from 'gettext-parser'; | ||||||
|  |  | ||||||
| export class PoCompiler implements CompilerInterface { | export class PoCompiler implements CompilerInterface { | ||||||
|  |  | ||||||
| 	public extension: string = 'po'; | 	public extension: string = 'po'; | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
| @@ -24,34 +23,38 @@ export class PoCompiler implements CompilerInterface { | |||||||
| 			}, | 			}, | ||||||
| 			translations: { | 			translations: { | ||||||
| 				[this.domain]: Object.keys(collection.values).reduce((translations, key) => { | 				[this.domain]: Object.keys(collection.values).reduce((translations, key) => { | ||||||
| 					translations[key] = { | 					return { | ||||||
| 						msgid: key, | 						...translations, | ||||||
| 						msgstr: collection.get(key) | 						[key]: { | ||||||
|  | 							msgid: key, | ||||||
|  | 							msgstr: collection.get(key) | ||||||
|  | 						} | ||||||
| 					}; | 					}; | ||||||
| 					return translations; |  | ||||||
| 				}, {} as any) | 				}, {} as any) | ||||||
| 			} | 			} | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
| 		return gettext.po.compile(data); | 		return po.compile(data).toString('utf8'); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public parse(contents: string): TranslationCollection { | 	public parse(contents: string): TranslationCollection { | ||||||
| 		const collection = new TranslationCollection(); | 		const collection = new TranslationCollection(); | ||||||
|  |  | ||||||
| 		const po = gettext.po.parse(contents, 'utf8'); | 		const parsedPo = po.parse(contents, 'utf8'); | ||||||
| 		if (!po.translations.hasOwnProperty(this.domain)) { |  | ||||||
|  | 		if (!parsedPo.translations.hasOwnProperty(this.domain)) { | ||||||
| 			return collection; | 			return collection; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		const values = Object.keys(po.translations[this.domain]) | 		const values = Object.keys(parsedPo.translations[this.domain]) | ||||||
| 			.filter(key => key.length > 0) | 			.filter((key) => key.length > 0) | ||||||
| 			.reduce((values, key) => { | 			.reduce((result, key) => { | ||||||
| 				values[key] = po.translations[this.domain][key].msgstr.pop(); | 				return { | ||||||
| 				return values; | 					...result, | ||||||
|  | 					[key]: parsedPo.translations[this.domain][key].msgstr.pop() | ||||||
|  | 				}; | ||||||
| 			}, {} as TranslationType); | 			}, {} as TranslationType); | ||||||
|  |  | ||||||
| 		return new TranslationCollection(values); | 		return new TranslationCollection(values); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
							
								
								
									
										1
									
								
								src/declarations.d.ts
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										1
									
								
								src/declarations.d.ts
									
									
									
									
										vendored
									
									
								
							| @@ -1 +0,0 @@ | |||||||
| declare module 'gettext-parser'; |  | ||||||
| @@ -1,83 +1,180 @@ | |||||||
|  | import { | ||||||
|  | 	parseTemplate, | ||||||
|  | 	TmplAstNode as Node, | ||||||
|  | 	TmplAstElement as Element, | ||||||
|  | 	TmplAstText as Text, | ||||||
|  | 	TmplAstTemplate as Template, | ||||||
|  | 	TmplAstTextAttribute as TextAttribute, | ||||||
|  | 	TmplAstBoundAttribute as BoundAttribute, | ||||||
|  | 	AST, | ||||||
|  | 	ASTWithSource, | ||||||
|  | 	LiteralPrimitive, | ||||||
|  | 	Conditional, | ||||||
|  | 	Binary, | ||||||
|  | 	BindingPipe, | ||||||
|  | 	Interpolation, | ||||||
|  | 	LiteralArray, | ||||||
|  | 	LiteralMap | ||||||
|  | } from '@angular/compiler'; | ||||||
|  |  | ||||||
| import { ParserInterface } from './parser.interface'; | import { ParserInterface } from './parser.interface'; | ||||||
| import { TranslationCollection } from '../utils/translation.collection'; | import { TranslationCollection } from '../utils/translation.collection'; | ||||||
| import { isPathAngularComponent, extractComponentInlineTemplate } from '../utils/utils'; | import { isPathAngularComponent, extractComponentInlineTemplate } from '../utils/utils'; | ||||||
|  |  | ||||||
| import { parseTemplate, TmplAstNode, TmplAstElement, TmplAstTextAttribute } from '@angular/compiler'; | const TRANSLATE_ATTR_NAME = 'translate'; | ||||||
|  | type ElementLike = Element | Template; | ||||||
|  |  | ||||||
| export class DirectiveParser implements ParserInterface { | export class DirectiveParser implements ParserInterface { | ||||||
|  | 	public extract(source: string, filePath: string): TranslationCollection | null { | ||||||
| 	public extract(template: string, path: string): TranslationCollection { |  | ||||||
| 		if (path && isPathAngularComponent(path)) { |  | ||||||
| 			template = extractComponentInlineTemplate(template); |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
|  |  | ||||||
| 		const nodes: TmplAstNode[] = this.parseTemplate(template, path); | 		if (filePath && isPathAngularComponent(filePath)) { | ||||||
| 		this.getTranslatableElements(nodes).forEach(element => { | 			source = extractComponentInlineTemplate(source); | ||||||
| 			const key = this.getElementTranslateAttrValue(element) || this.getElementContents(element); | 		} | ||||||
| 			collection = collection.add(key); | 		const nodes: Node[] = this.parseTemplate(source, filePath); | ||||||
| 		}); | 		const elements: ElementLike[] = this.getElementsWithTranslateAttribute(nodes); | ||||||
|  |  | ||||||
|  | 		elements.forEach((element) => { | ||||||
|  | 			const attribute = this.getAttribute(element, TRANSLATE_ATTR_NAME); | ||||||
|  | 			if (attribute?.value) { | ||||||
|  | 				collection = collection.add(attribute.value); | ||||||
|  | 				return; | ||||||
|  | 			} | ||||||
|  |  | ||||||
|  | 			const boundAttribute = this.getBoundAttribute(element, TRANSLATE_ATTR_NAME); | ||||||
|  | 			if (boundAttribute?.value) { | ||||||
|  | 				this.getLiteralPrimitives(boundAttribute.value).forEach((literalPrimitive) => { | ||||||
|  | 					collection = collection.add(literalPrimitive.value); | ||||||
|  | 				}); | ||||||
|  | 				return; | ||||||
|  | 			} | ||||||
|  |  | ||||||
|  | 			const textNodes = this.getTextNodes(element); | ||||||
|  | 			textNodes.forEach((textNode) => { | ||||||
|  | 				collection = collection.add(textNode.value.trim()); | ||||||
|  | 			}); | ||||||
|  | 		}); | ||||||
| 		return collection; | 		return collection; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	protected getTranslatableElements(nodes: TmplAstNode[]): TmplAstElement[] { | 	/** | ||||||
| 		return nodes | 	 * Find all ElementLike nodes with a translate attribute | ||||||
| 			.filter(element => this.isElement(element)) | 	 * @param nodes | ||||||
| 			.reduce((result: TmplAstElement[], element: TmplAstElement) => { | 	 */ | ||||||
| 				return result.concat(this.findChildrenElements(element)); | 	protected getElementsWithTranslateAttribute(nodes: Node[]): ElementLike[] { | ||||||
| 			}, []) | 		let elements: ElementLike[] = []; | ||||||
| 			.filter(element => this.isTranslatable(element)); | 		nodes.filter(this.isElementLike).forEach((element) => { | ||||||
| 	} | 			if (this.hasAttribute(element, TRANSLATE_ATTR_NAME)) { | ||||||
|  | 				elements = [...elements, element]; | ||||||
| 	protected findChildrenElements(node: TmplAstNode): TmplAstElement[] { |  | ||||||
| 		if (!this.isElement(node)) { |  | ||||||
| 			return []; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		// If element has translate attribute all its contents is translatable |  | ||||||
| 		// so we don't need to traverse any deeper |  | ||||||
| 		if (this.isTranslatable(node)) { |  | ||||||
| 			return [node]; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		return node.children.reduce((result: TmplAstElement[], childNode: TmplAstNode) => { |  | ||||||
| 			if (this.isElement(childNode)) { |  | ||||||
| 				const children = this.findChildrenElements(childNode); |  | ||||||
| 				return result.concat(children); |  | ||||||
| 			} | 			} | ||||||
| 			return result; | 			if (this.hasBoundAttribute(element, TRANSLATE_ATTR_NAME)) { | ||||||
| 		}, [node]); | 				elements = [...elements, element]; | ||||||
|  | 			} | ||||||
|  | 			const childElements = this.getElementsWithTranslateAttribute(element.children); | ||||||
|  | 			if (childElements.length) { | ||||||
|  | 				elements = [...elements, ...childElements]; | ||||||
|  | 			} | ||||||
|  | 		}); | ||||||
|  | 		return elements; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	protected parseTemplate(template: string, path: string): TmplAstNode[] { | 	/** | ||||||
|  | 	 * Get direct child nodes of type Text | ||||||
|  | 	 * @param element | ||||||
|  | 	 */ | ||||||
|  | 	protected getTextNodes(element: ElementLike): Text[] { | ||||||
|  | 		return element.children.filter(this.isText); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	/** | ||||||
|  | 	 * Check if attribute is present on element | ||||||
|  | 	 * @param element | ||||||
|  | 	 */ | ||||||
|  | 	protected hasAttribute(element: ElementLike, name: string): boolean { | ||||||
|  | 		return this.getAttribute(element, name) !== undefined; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	/** | ||||||
|  | 	 * Get attribute value if present on element | ||||||
|  | 	 * @param element | ||||||
|  | 	 */ | ||||||
|  | 	protected getAttribute(element: ElementLike, name: string): TextAttribute { | ||||||
|  | 		return element.attributes.find((attribute) => attribute.name === name); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	/** | ||||||
|  | 	 * Check if bound attribute is present on element | ||||||
|  | 	 * @param element | ||||||
|  | 	 * @param name | ||||||
|  | 	 */ | ||||||
|  | 	protected hasBoundAttribute(element: ElementLike, name: string): boolean { | ||||||
|  | 		return this.getBoundAttribute(element, name) !== undefined; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	/** | ||||||
|  | 	 * Get bound attribute if present on element | ||||||
|  | 	 * @param element | ||||||
|  | 	 * @param name | ||||||
|  | 	 */ | ||||||
|  | 	protected getBoundAttribute(element: ElementLike, name: string): BoundAttribute { | ||||||
|  | 		return element.inputs.find((input) => input.name === name); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	/** | ||||||
|  | 	 * Get literal primitives from expression | ||||||
|  | 	 * @param exp | ||||||
|  | 	 */ | ||||||
|  | 	protected getLiteralPrimitives(exp: AST): LiteralPrimitive[] { | ||||||
|  | 		if (exp instanceof LiteralPrimitive) { | ||||||
|  | 			return [exp]; | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		let visit: AST[] = []; | ||||||
|  | 		if (exp instanceof Interpolation) { | ||||||
|  | 			visit = exp.expressions; | ||||||
|  | 		} else if (exp instanceof LiteralArray) { | ||||||
|  | 			visit = exp.expressions; | ||||||
|  | 		} else if (exp instanceof LiteralMap) { | ||||||
|  | 			visit = exp.values; | ||||||
|  | 		} else if (exp instanceof BindingPipe) { | ||||||
|  | 			visit = [exp.exp]; | ||||||
|  | 		} else if (exp instanceof Conditional) { | ||||||
|  | 			visit = [exp.trueExp, exp.falseExp]; | ||||||
|  | 		} else if (exp instanceof Binary) { | ||||||
|  | 			visit = [exp.left, exp.right]; | ||||||
|  | 		} else if (exp instanceof ASTWithSource) { | ||||||
|  | 			visit = [exp.ast]; | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		let results: LiteralPrimitive[] = []; | ||||||
|  | 		visit.forEach((child) => { | ||||||
|  | 			results = [...results, ...this.getLiteralPrimitives(child)]; | ||||||
|  | 		}); | ||||||
|  | 		return results; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	/** | ||||||
|  | 	 * Check if node type is ElementLike | ||||||
|  | 	 * @param node | ||||||
|  | 	 */ | ||||||
|  | 	protected isElementLike(node: Node): node is ElementLike { | ||||||
|  | 		return node instanceof Element || node instanceof Template; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	/** | ||||||
|  | 	 * Check if node type is Text | ||||||
|  | 	 * @param node | ||||||
|  | 	 */ | ||||||
|  | 	protected isText(node: Node): node is Text { | ||||||
|  | 		return node instanceof Text; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	/** | ||||||
|  | 	 * Parse a template into nodes | ||||||
|  | 	 * @param template | ||||||
|  | 	 * @param path | ||||||
|  | 	 */ | ||||||
|  | 	protected parseTemplate(template: string, path: string): Node[] { | ||||||
| 		return parseTemplate(template, path).nodes; | 		return parseTemplate(template, path).nodes; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	protected isElement(node: any): node is TmplAstElement { |  | ||||||
| 		return node |  | ||||||
| 			&& node.attributes !== undefined |  | ||||||
| 			&& node.children !== undefined; |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	protected isTranslatable(node: TmplAstNode): boolean { |  | ||||||
| 		if (this.isElement(node) && node.attributes.some(attribute => attribute.name === 'translate')) { |  | ||||||
| 			return true; |  | ||||||
| 		} |  | ||||||
| 		return false; |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	protected getElementTranslateAttrValue(element: TmplAstElement): string { |  | ||||||
| 		const attr: TmplAstTextAttribute = element.attributes.find(attribute => attribute.name === 'translate'); |  | ||||||
| 		return attr && attr.value || ''; |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	protected getElementContents(element: TmplAstElement): string { |  | ||||||
| 		const contents = element.sourceSpan.start.file.content; |  | ||||||
| 		const start = element.startSourceSpan.end.offset; |  | ||||||
| 		const end = element.endSourceSpan.start.offset; |  | ||||||
| 		return contents.substring(start, end).trim(); |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -4,31 +4,29 @@ import { ParserInterface } from './parser.interface'; | |||||||
| import { TranslationCollection } from '../utils/translation.collection'; | import { TranslationCollection } from '../utils/translation.collection'; | ||||||
| import { getNamedImportAlias, findFunctionCallExpressions, getStringsFromExpression } from '../utils/ast-helpers'; | import { getNamedImportAlias, findFunctionCallExpressions, getStringsFromExpression } from '../utils/ast-helpers'; | ||||||
|  |  | ||||||
| const MARKER_PACKAGE_MODULE_NAME = '@biesbjerg/ngx-translate-extract-marker'; | const MARKER_MODULE_NAME = '@biesbjerg/ngx-translate-extract-marker'; | ||||||
| const MARKER_PACKAGE_IMPORT_NAME = 'marker'; | const MARKER_IMPORT_NAME = 'marker'; | ||||||
|  |  | ||||||
| export class MarkerParser implements ParserInterface { | export class MarkerParser implements ParserInterface { | ||||||
|  | 	public extract(source: string, filePath: string): TranslationCollection | null { | ||||||
|  | 		const sourceFile = tsquery.ast(source, filePath); | ||||||
|  |  | ||||||
| 	public extract(contents: string, filePath: string): TranslationCollection | null { | 		const markerImportName = getNamedImportAlias(sourceFile, MARKER_MODULE_NAME, MARKER_IMPORT_NAME); | ||||||
| 		const sourceFile = tsquery.ast(contents, filePath); | 		if (!markerImportName) { | ||||||
|  | 			return null; | ||||||
| 		const markerFnName = getNamedImportAlias(sourceFile, MARKER_PACKAGE_MODULE_NAME, MARKER_PACKAGE_IMPORT_NAME); |  | ||||||
| 		if (!markerFnName) { |  | ||||||
| 			return; |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
|  |  | ||||||
| 		const callNodes = findFunctionCallExpressions(sourceFile, markerFnName); | 		const callExpressions = findFunctionCallExpressions(sourceFile, markerImportName); | ||||||
| 		callNodes.forEach(callNode => { | 		callExpressions.forEach((callExpression) => { | ||||||
| 			const [firstArgNode] = callNode.arguments; | 			const [firstArg] = callExpression.arguments; | ||||||
| 			if (!firstArgNode) { | 			if (!firstArg) { | ||||||
| 				return; | 				return; | ||||||
| 			} | 			} | ||||||
| 			const strings = getStringsFromExpression(firstArgNode); | 			const strings = getStringsFromExpression(firstArg); | ||||||
| 			collection = collection.addKeys(strings); | 			collection = collection.addKeys(strings); | ||||||
| 		}); | 		}); | ||||||
| 		return collection; | 		return collection; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,7 +1,5 @@ | |||||||
| import { TranslationCollection } from '../utils/translation.collection'; | import { TranslationCollection } from '../utils/translation.collection'; | ||||||
|  |  | ||||||
| export interface ParserInterface { | export interface ParserInterface { | ||||||
|  |  | ||||||
| 	extract(source: string, filePath: string): TranslationCollection | null; | 	extract(source: string, filePath: string): TranslationCollection | null; | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,27 +1,163 @@ | |||||||
|  | import { | ||||||
|  | 	AST, | ||||||
|  | 	TmplAstNode, | ||||||
|  | 	parseTemplate, | ||||||
|  | 	BindingPipe, | ||||||
|  | 	LiteralPrimitive, | ||||||
|  | 	Conditional, | ||||||
|  | 	TmplAstTextAttribute, | ||||||
|  | 	Binary, | ||||||
|  | 	LiteralMap, | ||||||
|  | 	LiteralArray, | ||||||
|  | 	Interpolation, | ||||||
|  | 	MethodCall | ||||||
|  | } from '@angular/compiler'; | ||||||
|  |  | ||||||
| import { ParserInterface } from './parser.interface'; | import { ParserInterface } from './parser.interface'; | ||||||
| import { TranslationCollection } from '../utils/translation.collection'; | import { TranslationCollection } from '../utils/translation.collection'; | ||||||
| import { isPathAngularComponent, extractComponentInlineTemplate } from '../utils/utils'; | import { isPathAngularComponent, extractComponentInlineTemplate } from '../utils/utils'; | ||||||
|  |  | ||||||
|  | const TRANSLATE_PIPE_NAME = 'translate'; | ||||||
|  |  | ||||||
| export class PipeParser implements ParserInterface { | export class PipeParser implements ParserInterface { | ||||||
|  | 	public extract(source: string, filePath: string): TranslationCollection | null { | ||||||
| 	public extract(template: string, path: string): TranslationCollection { | 		if (filePath && isPathAngularComponent(filePath)) { | ||||||
| 		if (path && isPathAngularComponent(path)) { | 			source = extractComponentInlineTemplate(source); | ||||||
| 			template = extractComponentInlineTemplate(template); |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return this.parseTemplate(template); |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	protected parseTemplate(template: string): TranslationCollection { |  | ||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
|  | 		const nodes: TmplAstNode[] = this.parseTemplate(source, filePath); | ||||||
| 		const regExp: RegExp = /(['"`])((?:(?!\1).|\\\1)+)\1\s*\|\s*translate/g; | 		const pipes: BindingPipe[] = nodes.map((node) => this.findPipesInNode(node)).flat(); | ||||||
| 		let matches: RegExpExecArray; | 		pipes.forEach((pipe) => { | ||||||
| 		while (matches = regExp.exec(template)) { | 			this.parseTranslationKeysFromPipe(pipe).forEach((key: string) => { | ||||||
| 			collection = collection.add(matches[2].split('\\\'').join('\'')); | 				collection = collection.add(key); | ||||||
| 		} | 			}); | ||||||
|  | 		}); | ||||||
| 		return collection; | 		return collection; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	protected findPipesInNode(node: any): BindingPipe[] { | ||||||
|  | 		let ret: BindingPipe[] = []; | ||||||
|  |  | ||||||
|  | 		if (node?.children) { | ||||||
|  | 			ret = node.children.reduce( | ||||||
|  | 				(result: BindingPipe[], childNode: TmplAstNode) => { | ||||||
|  | 					const children = this.findPipesInNode(childNode); | ||||||
|  | 					return result.concat(children); | ||||||
|  | 				}, | ||||||
|  | 				[ret] | ||||||
|  | 			); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		if (node?.value?.ast) { | ||||||
|  | 			ret.push(...this.getTranslatablesFromAst(node.value.ast)); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		if (node?.attributes) { | ||||||
|  | 			const translateableAttributes = node.attributes.filter((attr: TmplAstTextAttribute) => { | ||||||
|  | 				return attr.name === TRANSLATE_PIPE_NAME; | ||||||
|  | 			}); | ||||||
|  | 			ret = [...ret, ...translateableAttributes]; | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		if (node?.inputs) { | ||||||
|  | 			node.inputs.forEach((input: any) => { | ||||||
|  | 				// <element [attrib]="'identifier' | translate"> | ||||||
|  | 				if (input?.value?.ast) { | ||||||
|  | 					ret.push(...this.getTranslatablesFromAst(input.value.ast)); | ||||||
|  | 				} | ||||||
|  | 			}); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		return ret; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	protected parseTranslationKeysFromPipe(pipeContent: BindingPipe | LiteralPrimitive | Conditional): string[] { | ||||||
|  | 		const ret: string[] = []; | ||||||
|  | 		if (pipeContent instanceof LiteralPrimitive) { | ||||||
|  | 			ret.push(pipeContent.value); | ||||||
|  | 		} else if (pipeContent instanceof Conditional) { | ||||||
|  | 			const trueExp: LiteralPrimitive | Conditional = pipeContent.trueExp as any; | ||||||
|  | 			ret.push(...this.parseTranslationKeysFromPipe(trueExp)); | ||||||
|  | 			const falseExp: LiteralPrimitive | Conditional = pipeContent.falseExp as any; | ||||||
|  | 			ret.push(...this.parseTranslationKeysFromPipe(falseExp)); | ||||||
|  | 		} else if (pipeContent instanceof BindingPipe) { | ||||||
|  | 			ret.push(...this.parseTranslationKeysFromPipe(pipeContent.exp as any)); | ||||||
|  | 		} | ||||||
|  | 		return ret; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	protected getTranslatablesFromAst(ast: AST): BindingPipe[] { | ||||||
|  | 		// the entire expression is the translate pipe, e.g.: | ||||||
|  | 		// - 'foo' | translate | ||||||
|  | 		// - (condition ? 'foo' : 'bar') | translate | ||||||
|  | 		if (this.expressionIsOrHasBindingPipe(ast)) { | ||||||
|  | 			return [ast]; | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		// angular double curly bracket interpolation, e.g.: | ||||||
|  | 		// - {{ expressions }} | ||||||
|  | 		if (ast instanceof Interpolation) { | ||||||
|  | 			return this.getTranslatablesFromAsts(ast.expressions); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		// ternary operator, e.g.: | ||||||
|  | 		// - condition ? null : ('foo' | translate) | ||||||
|  | 		// - condition ? ('foo' | translate) : null | ||||||
|  | 		if (ast instanceof Conditional) { | ||||||
|  | 			return this.getTranslatablesFromAsts([ast.trueExp, ast.falseExp]); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		// string concatenation, e.g.: | ||||||
|  | 		// - 'foo' + 'bar' + ('baz' | translate) | ||||||
|  | 		if (ast instanceof Binary) { | ||||||
|  | 			return this.getTranslatablesFromAsts([ast.left, ast.right]); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		// a pipe on the outer expression, but not the translate pipe - ignore the pipe, visit the expression, e.g.: | ||||||
|  | 		// - { foo: 'Hello' | translate } | json | ||||||
|  | 		if (ast instanceof BindingPipe) { | ||||||
|  | 			return this.getTranslatablesFromAst(ast.exp); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		// object - ignore the keys, visit all values, e.g.: | ||||||
|  | 		// - { key1: 'value1' | translate, key2: 'value2' | translate } | ||||||
|  | 		if (ast instanceof LiteralMap) { | ||||||
|  | 			return this.getTranslatablesFromAsts(ast.values); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		// array - visit all its values, e.g.: | ||||||
|  | 		// - [ 'value1' | translate, 'value2' | translate ] | ||||||
|  | 		if (ast instanceof LiteralArray) { | ||||||
|  | 			return this.getTranslatablesFromAsts(ast.expressions); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		if (ast instanceof MethodCall) { | ||||||
|  | 			return this.getTranslatablesFromAsts(ast.args); | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		return []; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	protected getTranslatablesFromAsts(asts: AST[]): BindingPipe[] { | ||||||
|  | 		return this.flatten(asts.map((ast) => this.getTranslatablesFromAst(ast))); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	protected flatten<T extends AST>(array: T[][]): T[] { | ||||||
|  | 		return [].concat(...array); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	protected expressionIsOrHasBindingPipe(exp: any): exp is BindingPipe { | ||||||
|  | 		if (exp.name && exp.name === TRANSLATE_PIPE_NAME) { | ||||||
|  | 			return true; | ||||||
|  | 		} | ||||||
|  | 		if (exp.exp && exp.exp instanceof BindingPipe) { | ||||||
|  | 			return this.expressionIsOrHasBindingPipe(exp.exp); | ||||||
|  | 		} | ||||||
|  | 		return false; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	protected parseTemplate(template: string, path: string): TmplAstNode[] { | ||||||
|  | 		return parseTemplate(template, path).nodes; | ||||||
|  | 	} | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,41 +1,64 @@ | |||||||
|  | import { ClassDeclaration, CallExpression } from 'typescript'; | ||||||
| import { tsquery } from '@phenomnomnominal/tsquery'; | import { tsquery } from '@phenomnomnominal/tsquery'; | ||||||
|  |  | ||||||
| import { ParserInterface } from './parser.interface'; | import { ParserInterface } from './parser.interface'; | ||||||
| import { TranslationCollection } from '../utils/translation.collection'; | import { TranslationCollection } from '../utils/translation.collection'; | ||||||
| import { findClasses, findClassPropertyByType, findMethodCallExpressions, getStringsFromExpression } from '../utils/ast-helpers'; | import { | ||||||
|  | 	findClassDeclarations, | ||||||
|  | 	findClassPropertyByType, | ||||||
|  | 	findPropertyCallExpressions, | ||||||
|  | 	findMethodCallExpressions, | ||||||
|  | 	getStringsFromExpression, | ||||||
|  | 	findMethodParameterByType, | ||||||
|  | 	findConstructorDeclaration | ||||||
|  | } from '../utils/ast-helpers'; | ||||||
|  |  | ||||||
| const TRANSLATE_SERVICE_TYPE_REFERENCE = 'TranslateService'; | const TRANSLATE_SERVICE_TYPE_REFERENCE = 'TranslateService'; | ||||||
| const TRANSLATE_SERVICE_METHOD_NAMES = ['get', 'instant', 'stream']; | const TRANSLATE_SERVICE_METHOD_NAMES = ['get', 'instant', 'stream']; | ||||||
|  |  | ||||||
| export class ServiceParser implements ParserInterface { | export class ServiceParser implements ParserInterface { | ||||||
|  |  | ||||||
| 	public extract(source: string, filePath: string): TranslationCollection | null { | 	public extract(source: string, filePath: string): TranslationCollection | null { | ||||||
| 		const sourceFile = tsquery.ast(source, filePath); | 		const sourceFile = tsquery.ast(source, filePath); | ||||||
|  |  | ||||||
| 		const classNodes = findClasses(sourceFile); | 		const classDeclarations = findClassDeclarations(sourceFile); | ||||||
| 		if (!classNodes) { | 		if (!classDeclarations) { | ||||||
| 			return; | 			return null; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
|  |  | ||||||
| 		classNodes.forEach(classNode => { | 		classDeclarations.forEach((classDeclaration) => { | ||||||
| 			const propName: string = findClassPropertyByType(classNode, TRANSLATE_SERVICE_TYPE_REFERENCE); | 			const callExpressions = [ | ||||||
| 			if (!propName) { | 				...this.findConstructorParamCallExpressions(classDeclaration), | ||||||
| 				return; | 				...this.findPropertyCallExpressions(classDeclaration) | ||||||
| 			} | 			]; | ||||||
|  |  | ||||||
| 			const callNodes = findMethodCallExpressions(classNode, propName, TRANSLATE_SERVICE_METHOD_NAMES); | 			callExpressions.forEach((callExpression) => { | ||||||
| 			callNodes.forEach(callNode => { | 				const [firstArg] = callExpression.arguments; | ||||||
| 				const [firstArgNode] = callNode.arguments; | 				if (!firstArg) { | ||||||
| 				if (!firstArgNode) { |  | ||||||
| 					return; | 					return; | ||||||
| 				} | 				} | ||||||
| 				const strings = getStringsFromExpression(firstArgNode); | 				const strings = getStringsFromExpression(firstArg); | ||||||
| 				collection = collection.addKeys(strings); | 				collection = collection.addKeys(strings); | ||||||
| 			}); | 			}); | ||||||
| 		}); | 		}); | ||||||
| 		return collection; | 		return collection; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	protected findConstructorParamCallExpressions(classDeclaration: ClassDeclaration): CallExpression[] { | ||||||
|  | 		const constructorDeclaration = findConstructorDeclaration(classDeclaration); | ||||||
|  | 		if (!constructorDeclaration) { | ||||||
|  | 			return []; | ||||||
|  | 		} | ||||||
|  | 		const paramName = findMethodParameterByType(constructorDeclaration, TRANSLATE_SERVICE_TYPE_REFERENCE); | ||||||
|  | 		return findMethodCallExpressions(constructorDeclaration, paramName, TRANSLATE_SERVICE_METHOD_NAMES); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	protected findPropertyCallExpressions(classDeclaration: ClassDeclaration): CallExpression[] { | ||||||
|  | 		const propName: string = findClassPropertyByType(classDeclaration, TRANSLATE_SERVICE_TYPE_REFERENCE); | ||||||
|  | 		if (!propName) { | ||||||
|  | 			return []; | ||||||
|  | 		} | ||||||
|  | 		return findPropertyCallExpressions(classDeclaration, propName, TRANSLATE_SERVICE_METHOD_NAMES); | ||||||
|  | 	} | ||||||
| } | } | ||||||
|   | |||||||
| @@ -2,11 +2,9 @@ import { TranslationCollection } from '../utils/translation.collection'; | |||||||
| import { PostProcessorInterface } from './post-processor.interface'; | import { PostProcessorInterface } from './post-processor.interface'; | ||||||
|  |  | ||||||
| export class KeyAsDefaultValuePostProcessor implements PostProcessorInterface { | export class KeyAsDefaultValuePostProcessor implements PostProcessorInterface { | ||||||
|  |  | ||||||
| 	public name: string = 'KeyAsDefaultValue'; | 	public name: string = 'KeyAsDefaultValue'; | ||||||
|  |  | ||||||
| 	public process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | 	public process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | ||||||
| 		return draft.map((key, val) => val === '' ? key : val); | 		return draft.map((key, val) => (val === '' ? key : val)); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -2,11 +2,9 @@ import { TranslationCollection } from '../utils/translation.collection'; | |||||||
| import { PostProcessorInterface } from './post-processor.interface'; | import { PostProcessorInterface } from './post-processor.interface'; | ||||||
|  |  | ||||||
| export class NullAsDefaultValuePostProcessor implements PostProcessorInterface { | export class NullAsDefaultValuePostProcessor implements PostProcessorInterface { | ||||||
|  |  | ||||||
| 	public name: string = 'NullAsDefaultValue'; | 	public name: string = 'NullAsDefaultValue'; | ||||||
|  |  | ||||||
| 	public process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | 	public process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | ||||||
| 		return draft.map((key, val) => existing.get(key) === undefined ? null : val); | 		return draft.map((key, val) => (existing.get(key) === undefined ? null : val)); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,9 +1,7 @@ | |||||||
| import { TranslationCollection } from '../utils/translation.collection'; | import { TranslationCollection } from '../utils/translation.collection'; | ||||||
|  |  | ||||||
| export interface PostProcessorInterface { | export interface PostProcessorInterface { | ||||||
|  |  | ||||||
| 	name: string; | 	name: string; | ||||||
|  |  | ||||||
| 	process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection; | 	process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection; | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -2,11 +2,9 @@ import { TranslationCollection } from '../utils/translation.collection'; | |||||||
| import { PostProcessorInterface } from './post-processor.interface'; | import { PostProcessorInterface } from './post-processor.interface'; | ||||||
|  |  | ||||||
| export class PurgeObsoleteKeysPostProcessor implements PostProcessorInterface { | export class PurgeObsoleteKeysPostProcessor implements PostProcessorInterface { | ||||||
|  |  | ||||||
| 	public name: string = 'PurgeObsoleteKeys'; | 	public name: string = 'PurgeObsoleteKeys'; | ||||||
|  |  | ||||||
| 	public process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | 	public process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | ||||||
| 		return draft.intersect(extracted); | 		return draft.intersect(extracted); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -2,11 +2,9 @@ import { TranslationCollection } from '../utils/translation.collection'; | |||||||
| import { PostProcessorInterface } from './post-processor.interface'; | import { PostProcessorInterface } from './post-processor.interface'; | ||||||
|  |  | ||||||
| export class SortByKeyPostProcessor implements PostProcessorInterface { | export class SortByKeyPostProcessor implements PostProcessorInterface { | ||||||
|  |  | ||||||
| 	public name: string = 'SortByKey'; | 	public name: string = 'SortByKey'; | ||||||
|  |  | ||||||
| 	public process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | 	public process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | ||||||
| 		return draft.sort(); | 		return draft.sort(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -0,0 +1,16 @@ | |||||||
|  | import { TranslationCollection } from '../utils/translation.collection'; | ||||||
|  | import { PostProcessorInterface } from './post-processor.interface'; | ||||||
|  |  | ||||||
|  | interface Options { | ||||||
|  | 	defaultValue: string; | ||||||
|  | } | ||||||
|  |  | ||||||
|  | export class StringAsDefaultValuePostProcessor implements PostProcessorInterface { | ||||||
|  | 	public name: string = 'StringAsDefaultValue'; | ||||||
|  |  | ||||||
|  | 	public constructor(protected options: Options) {} | ||||||
|  |  | ||||||
|  | 	public process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { | ||||||
|  | 		return draft.map((key, val) => (existing.get(key) === undefined ? this.options.defaultValue : val)); | ||||||
|  | 	} | ||||||
|  | } | ||||||
| @@ -1,15 +1,16 @@ | |||||||
| import { tsquery } from '@phenomnomnominal/tsquery'; | import { tsquery } from '@phenomnomnominal/tsquery'; | ||||||
| import { | import { | ||||||
|  | 	SyntaxKind, | ||||||
| 	Node, | 	Node, | ||||||
| 	NamedImports, | 	NamedImports, | ||||||
| 	Identifier, | 	Identifier, | ||||||
| 	ClassDeclaration, | 	ClassDeclaration, | ||||||
| 	CallExpression, | 	ConstructorDeclaration, | ||||||
| 	isStringLiteralLike, | 	isStringLiteralLike, | ||||||
| 	isArrayLiteralExpression, | 	isArrayLiteralExpression, | ||||||
|  | 	CallExpression, | ||||||
| 	Expression, | 	Expression, | ||||||
| 	isBinaryExpression, | 	isBinaryExpression, | ||||||
| 	SyntaxKind, |  | ||||||
| 	isConditionalExpression, | 	isConditionalExpression, | ||||||
| 	PropertyAccessExpression | 	PropertyAccessExpression | ||||||
| } from 'typescript'; | } from 'typescript'; | ||||||
| @@ -22,7 +23,7 @@ export function getNamedImports(node: Node, moduleName: string): NamedImports[] | |||||||
| export function getNamedImportAlias(node: Node, moduleName: string, importName: string): string | null { | export function getNamedImportAlias(node: Node, moduleName: string, importName: string): string | null { | ||||||
| 	const [namedImportNode] = getNamedImports(node, moduleName); | 	const [namedImportNode] = getNamedImports(node, moduleName); | ||||||
| 	if (!namedImportNode) { | 	if (!namedImportNode) { | ||||||
| 		return; | 		return null; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	const query = `ImportSpecifier:has(Identifier[name="${importName}"]) > Identifier`; | 	const query = `ImportSpecifier:has(Identifier[name="${importName}"]) > Identifier`; | ||||||
| @@ -36,7 +37,7 @@ export function getNamedImportAlias(node: Node, moduleName: string, importName: | |||||||
| 	return null; | 	return null; | ||||||
| } | } | ||||||
|  |  | ||||||
| export function findClasses(node: Node): ClassDeclaration[] { | export function findClassDeclarations(node: Node): ClassDeclaration[] { | ||||||
| 	const query = 'ClassDeclaration'; | 	const query = 'ClassDeclaration'; | ||||||
| 	return tsquery<ClassDeclaration>(node, query); | 	return tsquery<ClassDeclaration>(node, query); | ||||||
| } | } | ||||||
| @@ -45,6 +46,30 @@ export function findClassPropertyByType(node: ClassDeclaration, type: string): s | |||||||
| 	return findClassPropertyConstructorParameterByType(node, type) || findClassPropertyDeclarationByType(node, type); | 	return findClassPropertyConstructorParameterByType(node, type) || findClassPropertyDeclarationByType(node, type); | ||||||
| } | } | ||||||
|  |  | ||||||
|  | export function findConstructorDeclaration(node: ClassDeclaration): ConstructorDeclaration { | ||||||
|  | 	const query = `Constructor`; | ||||||
|  | 	const [result] = tsquery<ConstructorDeclaration>(node, query); | ||||||
|  | 	return result; | ||||||
|  | } | ||||||
|  |  | ||||||
|  | export function findMethodParameterByType(node: Node, type: string): string | null { | ||||||
|  | 	const query = `Parameter:has(TypeReference > Identifier[name="${type}"]) > Identifier`; | ||||||
|  | 	const [result] = tsquery<Identifier>(node, query); | ||||||
|  | 	if (result) { | ||||||
|  | 		return result.text; | ||||||
|  | 	} | ||||||
|  | 	return null; | ||||||
|  | } | ||||||
|  |  | ||||||
|  | export function findMethodCallExpressions(node: Node, propName: string, fnName: string | string[]): CallExpression[] { | ||||||
|  | 	if (Array.isArray(fnName)) { | ||||||
|  | 		fnName = fnName.join('|'); | ||||||
|  | 	} | ||||||
|  | 	const query = `CallExpression > PropertyAccessExpression:has(Identifier[name=/^(${fnName})$/]):has(PropertyAccessExpression:has(Identifier[name="${propName}"]):not(:has(ThisKeyword)))`; | ||||||
|  | 	const nodes = tsquery<PropertyAccessExpression>(node, query).map((n) => n.parent as CallExpression); | ||||||
|  | 	return nodes; | ||||||
|  | } | ||||||
|  |  | ||||||
| export function findClassPropertyConstructorParameterByType(node: ClassDeclaration, type: string): string | null { | export function findClassPropertyConstructorParameterByType(node: ClassDeclaration, type: string): string | null { | ||||||
| 	const query = `Constructor Parameter:has(TypeReference > Identifier[name="${type}"]):has(PublicKeyword,ProtectedKeyword,PrivateKeyword) > Identifier`; | 	const query = `Constructor Parameter:has(TypeReference > Identifier[name="${type}"]):has(PublicKeyword,ProtectedKeyword,PrivateKeyword) > Identifier`; | ||||||
| 	const [result] = tsquery<Identifier>(node, query); | 	const [result] = tsquery<Identifier>(node, query); | ||||||
| @@ -72,12 +97,12 @@ export function findFunctionCallExpressions(node: Node, fnName: string | string[ | |||||||
| 	return nodes; | 	return nodes; | ||||||
| } | } | ||||||
|  |  | ||||||
| export function findMethodCallExpressions(node: Node, prop: string, fnName: string | string[]): CallExpression[] { | export function findPropertyCallExpressions(node: Node, prop: string, fnName: string | string[]): CallExpression[] { | ||||||
| 	if (Array.isArray(fnName)) { | 	if (Array.isArray(fnName)) { | ||||||
| 		fnName = fnName.join('|'); | 		fnName = fnName.join('|'); | ||||||
| 	} | 	} | ||||||
| 	const query = `CallExpression > PropertyAccessExpression:has(Identifier[name=/^(${fnName})$/]):has(PropertyAccessExpression:has(Identifier[name="${prop}"]):has(ThisKeyword))`; | 	const query = `CallExpression > PropertyAccessExpression:has(Identifier[name=/^(${fnName})$/]):has(PropertyAccessExpression:has(Identifier[name="${prop}"]):has(ThisKeyword))`; | ||||||
| 	let nodes = tsquery<PropertyAccessExpression>(node, query).map(node => node.parent as CallExpression); | 	const nodes = tsquery<PropertyAccessExpression>(node, query).map((n) => n.parent as CallExpression); | ||||||
| 	return nodes; | 	return nodes; | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -88,17 +113,14 @@ export function getStringsFromExpression(expression: Expression): string[] { | |||||||
|  |  | ||||||
| 	if (isArrayLiteralExpression(expression)) { | 	if (isArrayLiteralExpression(expression)) { | ||||||
| 		return expression.elements.reduce((result: string[], element: Expression) => { | 		return expression.elements.reduce((result: string[], element: Expression) => { | ||||||
| 			const strings = this.getStringsFromExpression(element); | 			const strings = getStringsFromExpression(element); | ||||||
| 			return [ | 			return [...result, ...strings]; | ||||||
| 				...result, |  | ||||||
| 				...strings |  | ||||||
| 			]; |  | ||||||
| 		}, []); | 		}, []); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	if (isBinaryExpression(expression)) { | 	if (isBinaryExpression(expression)) { | ||||||
| 		const [left] = this.getStringsFromExpression(expression.left); | 		const [left] = getStringsFromExpression(expression.left); | ||||||
| 		const [right] = this.getStringsFromExpression(expression.right); | 		const [right] = getStringsFromExpression(expression.right); | ||||||
|  |  | ||||||
| 		if (expression.operatorToken.kind === SyntaxKind.PlusToken) { | 		if (expression.operatorToken.kind === SyntaxKind.PlusToken) { | ||||||
| 			if (typeof left === 'string' && typeof right === 'string') { | 			if (typeof left === 'string' && typeof right === 'string') { | ||||||
| @@ -119,8 +141,8 @@ export function getStringsFromExpression(expression: Expression): string[] { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	if (isConditionalExpression(expression)) { | 	if (isConditionalExpression(expression)) { | ||||||
| 		const [whenTrue] = this.getStringsFromExpression(expression.whenTrue); | 		const [whenTrue] = getStringsFromExpression(expression.whenTrue); | ||||||
| 		const [whenFalse] = this.getStringsFromExpression(expression.whenFalse); | 		const [whenFalse] = getStringsFromExpression(expression.whenFalse); | ||||||
|  |  | ||||||
| 		const result = []; | 		const result = []; | ||||||
| 		if (typeof whenTrue === 'string') { | 		if (typeof whenTrue === 'string') { | ||||||
|   | |||||||
							
								
								
									
										36
									
								
								src/utils/fs-helpers.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										36
									
								
								src/utils/fs-helpers.ts
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,36 @@ | |||||||
|  | import * as os from 'os'; | ||||||
|  | import * as fs from 'fs'; | ||||||
|  | import * as braces from 'braces'; | ||||||
|  |  | ||||||
|  | declare module 'braces' { | ||||||
|  | 	interface Options { | ||||||
|  | 		keepEscaping?: boolean; // Workaround for option not present in @types/braces 3.0.0 | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | export function normalizeHomeDir(path: string): string { | ||||||
|  | 	if (path.substring(0, 1) === '~') { | ||||||
|  | 		return `${os.homedir()}/${path.substring(1)}`; | ||||||
|  | 	} | ||||||
|  | 	return path; | ||||||
|  | } | ||||||
|  |  | ||||||
|  | export function expandPattern(pattern: string): string[] { | ||||||
|  | 	return braces(pattern, { expand: true, keepEscaping: true }); | ||||||
|  | } | ||||||
|  |  | ||||||
|  | export function normalizePaths(patterns: string[], defaultPatterns: string[] = []): string[] { | ||||||
|  | 	return patterns | ||||||
|  | 		.map((pattern) => | ||||||
|  | 			expandPattern(pattern) | ||||||
|  | 				.map((path) => { | ||||||
|  | 					path = normalizeHomeDir(path); | ||||||
|  | 					if (fs.existsSync(path) && fs.statSync(path).isDirectory()) { | ||||||
|  | 						return defaultPatterns.map((defaultPattern) => path + defaultPattern); | ||||||
|  | 					} | ||||||
|  | 					return path; | ||||||
|  | 				}) | ||||||
|  | 				.flat() | ||||||
|  | 		) | ||||||
|  | 		.flat(); | ||||||
|  | } | ||||||
| @@ -3,7 +3,6 @@ export interface TranslationType { | |||||||
| } | } | ||||||
|  |  | ||||||
| export class TranslationCollection { | export class TranslationCollection { | ||||||
|  |  | ||||||
| 	public values: TranslationType = {}; | 	public values: TranslationType = {}; | ||||||
|  |  | ||||||
| 	public constructor(values: TranslationType = {}) { | 	public constructor(values: TranslationType = {}) { | ||||||
| @@ -16,24 +15,23 @@ export class TranslationCollection { | |||||||
|  |  | ||||||
| 	public addKeys(keys: string[]): TranslationCollection { | 	public addKeys(keys: string[]): TranslationCollection { | ||||||
| 		const values = keys.reduce((results, key) => { | 		const values = keys.reduce((results, key) => { | ||||||
| 			results[key] = ''; | 			return { ...results, [key]: '' }; | ||||||
| 			return results; |  | ||||||
| 		}, {} as TranslationType); | 		}, {} as TranslationType); | ||||||
| 		return new TranslationCollection({ ...this.values, ...values }); | 		return new TranslationCollection({ ...this.values, ...values }); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public remove(key: string): TranslationCollection { | 	public remove(key: string): TranslationCollection { | ||||||
| 		return this.filter(k => key !== k); | 		return this.filter((k) => key !== k); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public forEach(callback: (key?: string, val?: string) => void): TranslationCollection { | 	public forEach(callback: (key?: string, val?: string) => void): TranslationCollection { | ||||||
| 		Object.keys(this.values).forEach(key => callback.call(this, key, this.values[key])); | 		Object.keys(this.values).forEach((key) => callback.call(this, key, this.values[key])); | ||||||
| 		return this; | 		return this; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public filter(callback: (key?: string, val?: string) => boolean): TranslationCollection { | 	public filter(callback: (key?: string, val?: string) => boolean): TranslationCollection { | ||||||
| 		let values: TranslationType = {}; | 		const values: TranslationType = {}; | ||||||
| 		this.forEach((key: string, val: string) => { | 		this.forEach((key, val) => { | ||||||
| 			if (callback.call(this, key, val)) { | 			if (callback.call(this, key, val)) { | ||||||
| 				values[key] = val; | 				values[key] = val; | ||||||
| 			} | 			} | ||||||
| @@ -42,8 +40,8 @@ export class TranslationCollection { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public map(callback: (key?: string, val?: string) => string): TranslationCollection { | 	public map(callback: (key?: string, val?: string) => string): TranslationCollection { | ||||||
| 		let values: TranslationType = {}; | 		const values: TranslationType = {}; | ||||||
| 		this.forEach((key: string, val: string) => { | 		this.forEach((key, val) => { | ||||||
| 			values[key] = callback.call(this, key, val); | 			values[key] = callback.call(this, key, val); | ||||||
| 		}); | 		}); | ||||||
| 		return new TranslationCollection(values); | 		return new TranslationCollection(values); | ||||||
| @@ -54,11 +52,10 @@ export class TranslationCollection { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public intersect(collection: TranslationCollection): TranslationCollection { | 	public intersect(collection: TranslationCollection): TranslationCollection { | ||||||
| 		let values: TranslationType = {}; | 		const values: TranslationType = {}; | ||||||
| 		this.filter(key => collection.has(key)) | 		this.filter((key) => collection.has(key)).forEach((key, val) => { | ||||||
| 			.forEach((key: string, val: string) => { | 			values[key] = val; | ||||||
| 				values[key] = val; | 		}); | ||||||
| 			}); |  | ||||||
|  |  | ||||||
| 		return new TranslationCollection(values); | 		return new TranslationCollection(values); | ||||||
| 	} | 	} | ||||||
| @@ -84,10 +81,12 @@ export class TranslationCollection { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public sort(compareFn?: (a: string, b: string) => number): TranslationCollection { | 	public sort(compareFn?: (a: string, b: string) => number): TranslationCollection { | ||||||
| 		let values: TranslationType = {}; | 		const values: TranslationType = {}; | ||||||
| 		this.keys().sort(compareFn).forEach((key) => { | 		this.keys() | ||||||
| 			values[key] = this.get(key); | 			.sort(compareFn) | ||||||
| 		}); | 			.forEach((key) => { | ||||||
|  | 				values[key] = this.get(key); | ||||||
|  | 			}); | ||||||
|  |  | ||||||
| 		return new TranslationCollection(values); | 		return new TranslationCollection(values); | ||||||
| 	} | 	} | ||||||
|   | |||||||
| @@ -2,7 +2,7 @@ | |||||||
|  * Assumes file is an Angular component if type is javascript/typescript |  * Assumes file is an Angular component if type is javascript/typescript | ||||||
|  */ |  */ | ||||||
| export function isPathAngularComponent(path: string): boolean { | export function isPathAngularComponent(path: string): boolean { | ||||||
| 	return (/\.ts|js$/i).test(path); | 	return /\.ts|js$/i.test(path); | ||||||
| } | } | ||||||
|  |  | ||||||
| /** | /** | ||||||
|   | |||||||
| @@ -4,7 +4,6 @@ import { TranslationCollection } from '../../src/utils/translation.collection'; | |||||||
| import { NamespacedJsonCompiler } from '../../src/compilers/namespaced-json.compiler'; | import { NamespacedJsonCompiler } from '../../src/compilers/namespaced-json.compiler'; | ||||||
|  |  | ||||||
| describe('NamespacedJsonCompiler', () => { | describe('NamespacedJsonCompiler', () => { | ||||||
|  |  | ||||||
| 	let compiler: NamespacedJsonCompiler; | 	let compiler: NamespacedJsonCompiler; | ||||||
|  |  | ||||||
| 	beforeEach(() => { | 	beforeEach(() => { | ||||||
| @@ -23,7 +22,10 @@ describe('NamespacedJsonCompiler', () => { | |||||||
| 			} | 			} | ||||||
| 		`; | 		`; | ||||||
| 		const collection: TranslationCollection = compiler.parse(contents); | 		const collection: TranslationCollection = compiler.parse(contents); | ||||||
| 		expect(collection.values).to.deep.equal({'NAMESPACE.KEY.FIRST_KEY': '', 'NAMESPACE.KEY.SECOND_KEY': 'VALUE' }); | 		expect(collection.values).to.deep.equal({ | ||||||
|  | 			'NAMESPACE.KEY.FIRST_KEY': '', | ||||||
|  | 			'NAMESPACE.KEY.SECOND_KEY': 'VALUE' | ||||||
|  | 		}); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should unflatten keys on compile', () => { | 	it('should unflatten keys on compile', () => { | ||||||
| @@ -59,11 +61,10 @@ describe('NamespacedJsonCompiler', () => { | |||||||
|  |  | ||||||
| 	it('should not reorder keys when compiled', () => { | 	it('should not reorder keys when compiled', () => { | ||||||
| 		const collection = new TranslationCollection({ | 		const collection = new TranslationCollection({ | ||||||
| 			'BROWSE': '', | 			BROWSE: '', | ||||||
| 			'LOGIN': '' | 			LOGIN: '' | ||||||
| 		}); | 		}); | ||||||
| 		const result: string = compiler.compile(collection); | 		const result: string = compiler.compile(collection); | ||||||
| 		expect(result).to.equal('{\n\t"BROWSE": "",\n\t"LOGIN": ""\n}'); | 		expect(result).to.equal('{\n\t"BROWSE": "",\n\t"LOGIN": ""\n}'); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
							
								
								
									
										24
									
								
								tests/compilers/po.compiler.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										24
									
								
								tests/compilers/po.compiler.spec.ts
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,24 @@ | |||||||
|  | import { expect } from 'chai'; | ||||||
|  |  | ||||||
|  | import { TranslationCollection } from '../../src/utils/translation.collection'; | ||||||
|  | import { PoCompiler } from '../../src/compilers/po.compiler'; | ||||||
|  |  | ||||||
|  | describe('PoCompiler', () => { | ||||||
|  | 	let compiler: PoCompiler; | ||||||
|  |  | ||||||
|  | 	beforeEach(() => { | ||||||
|  | 		compiler = new PoCompiler(); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should still include html ', () => { | ||||||
|  | 		const collection = new TranslationCollection({ | ||||||
|  | 			'A <strong>test</strong>': 'Un <strong>test</strong>', | ||||||
|  | 			'With a lot of <em>html</em> included': 'Avec beaucoup d\'<em>html</em> inclus' | ||||||
|  | 		}); | ||||||
|  | 		const result: Buffer = Buffer.from(compiler.compile(collection)); | ||||||
|  | 		expect(result.toString('utf8')).to.equal('msgid ""\nmsgstr ""\n"mime-version: 1.0\\n"\n"Content-Type: text/plain; charset=utf-8\\n"\n"Content-Transfer-Encoding: 8bit\\n"\n\nmsgid "A <strong>test</strong>"\nmsgstr "Un <strong>test</strong>"\n\nmsgid "With a lot of <em>html</em> included"\nmsgstr "Avec beaucoup d\'<em>html</em> inclus"'); | ||||||
|  | 	}); | ||||||
|  | }); | ||||||
|  |  | ||||||
|  |  | ||||||
|  |  | ||||||
| @@ -3,7 +3,6 @@ import { expect } from 'chai'; | |||||||
| import { DirectiveParser } from '../../src/parsers/directive.parser'; | import { DirectiveParser } from '../../src/parsers/directive.parser'; | ||||||
|  |  | ||||||
| describe('DirectiveParser', () => { | describe('DirectiveParser', () => { | ||||||
|  |  | ||||||
| 	const templateFilename: string = 'test.template.html'; | 	const templateFilename: string = 'test.template.html'; | ||||||
| 	const componentFilename: string = 'test.component.ts'; | 	const componentFilename: string = 'test.component.ts'; | ||||||
|  |  | ||||||
| @@ -13,28 +12,89 @@ describe('DirectiveParser', () => { | |||||||
| 		parser = new DirectiveParser(); | 		parser = new DirectiveParser(); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should not choke when no html is present in template', () => { |  | ||||||
| 		const contents = 'Hello World'; | 	it('should extract keys when using literal map in bound attribute', () => { | ||||||
|  | 		const contents = `<div [translate]="{ key1: 'value1' | translate, key2: 'value2' | translate }"></div>`; | ||||||
| 		const keys = parser.extract(contents, templateFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal([]); | 		expect(keys).to.deep.equal(['value1', 'value2']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should use contents as key when there is no translate attribute value provided', () => { | 	it('should extract keys when using literal arrays in bound attribute', () => { | ||||||
|  | 		const contents = `<div [translate]="[ 'value1' | translate, 'value2' | translate ]"></div>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['value1', 'value2']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract keys when using binding pipe in bound attribute', () => { | ||||||
|  | 		const contents = `<div [translate]="'KEY1' | withPipe"></div>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['KEY1']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract keys when using binary expression in bound attribute', () => { | ||||||
|  | 		const contents = `<div [translate]="keyVar || 'KEY1'"></div>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['KEY1']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract keys when using literal primitive in bound attribute', () => { | ||||||
|  | 		const contents = `<div [translate]="'KEY1'"></div>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['KEY1']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract keys when using conditional in bound attribute', () => { | ||||||
|  | 		const contents = `<div [translate]="condition ? 'KEY1' : 'KEY2'"></div>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['KEY1', 'KEY2']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract keys when using nested conditionals in bound attribute', () => { | ||||||
|  | 		const contents = `<div [translate]="isSunny ? (isWarm ? 'Sunny and warm' : 'Sunny but cold') : 'Not sunny'"></div>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Sunny and warm', 'Sunny but cold', 'Not sunny']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract keys when using interpolation', () => { | ||||||
|  | 		const contents = `<div translate="{{ 'KEY1' + key2 + 'KEY3' }}"></div>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['KEY1', 'KEY3']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract keys keeping proper whitespace', () => { | ||||||
|  | 		const contents = ` | ||||||
|  | 			<div translate> | ||||||
|  | 				Wubba | ||||||
|  | 				Lubba | ||||||
|  | 				Dub Dub | ||||||
|  | 			</div> | ||||||
|  | 		`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Wubba Lubba Dub Dub']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should use element contents as key when no translate attribute value is present', () => { | ||||||
| 		const contents = '<div translate>Hello World</div>'; | 		const contents = '<div translate>Hello World</div>'; | ||||||
| 		const keys = parser.extract(contents, templateFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal(['Hello World']); | 		expect(keys).to.deep.equal(['Hello World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should use translate attribute value as key when provided', () => { | 	it('should use translate attribute value as key when present', () => { | ||||||
| 		const contents = '<div translate="MY_KEY">Hello World<div>'; | 		const contents = '<div translate="MY_KEY">Hello World<div>'; | ||||||
| 		const keys = parser.extract(contents, templateFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal(['MY_KEY']); | 		expect(keys).to.deep.equal(['MY_KEY']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should not process children when translate attribute is present', () => { | 	it('should extract keys from child elements when translate attribute is present', () => { | ||||||
| 		const contents = `<div translate>Hello <strong translate>World</strong></div>`; | 		const contents = `<div translate>Hello <strong translate>World</strong></div>`; | ||||||
| 		const keys = parser.extract(contents, templateFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal(['Hello <strong translate>World</strong>']); | 		expect(keys).to.deep.equal(['Hello', 'World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should not extract keys from child elements when translate attribute is not present', () => { | ||||||
|  | 		const contents = `<div translate>Hello <strong>World</strong></div>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Hello']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should extract and parse inline template', () => { | 	it('should extract and parse inline template', () => { | ||||||
| @@ -67,24 +127,47 @@ describe('DirectiveParser', () => { | |||||||
| 		expect(collection.values).to.deep.equal({}); | 		expect(collection.values).to.deep.equal({}); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should extract contents from within custom tags', () => { | 	it('should extract contents from custom elements', () => { | ||||||
| 		const contents = `<custom-table><tbody><tr><td translate>Hello World</td></tr></tbody></custom-table>`; | 		const contents = `<custom-table><tbody><tr><td translate>Hello World</td></tr></tbody></custom-table>`; | ||||||
| 		const keys = parser.extract(contents, templateFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal(['Hello World']); | 		expect(keys).to.deep.equal(['Hello World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should not cause error when no html is present in template', () => { | 	it('should extract from template without leading/trailing whitespace', () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			import { Component } from '@angular/core'; | 			<div *ngIf="!isLoading && studentsToGrid && studentsToGrid.length == 0" class="no-students" mt-rtl translate>There | ||||||
| 			@Component({ | 				are currently no students in this class. The good news is, adding students is really easy! Just use the options | ||||||
| 				template: '{{ variable }}' | 				at the top. | ||||||
| 			}) | 			</div> | ||||||
| 			export class MyComponent { |  | ||||||
| 				variable: string |  | ||||||
| 			} |  | ||||||
| 		`; | 		`; | ||||||
| 		const keys = parser.extract(contents, componentFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal([]); | 		expect(keys).to.deep.equal([ | ||||||
|  | 			'There are currently no students in this class. The good news is, adding students is really easy! Just use the options at the top.' | ||||||
|  | 		]); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract keys from element without leading/trailing whitespace', () => { | ||||||
|  | 		const contents = ` | ||||||
|  | 			<div translate> | ||||||
|  | 				this is an example | ||||||
|  | 				of a long label | ||||||
|  | 			</div> | ||||||
|  |  | ||||||
|  | 			<div> | ||||||
|  | 				<p translate> | ||||||
|  | 					this is an example | ||||||
|  | 					of another a long label | ||||||
|  | 				</p> | ||||||
|  | 			</div> | ||||||
|  | 		`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['this is an example of a long label', 'this is an example of another a long label']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should collapse excessive whitespace', () => { | ||||||
|  | 		const contents = '<p translate>this      is an example</p>'; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['this is an example']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -3,7 +3,6 @@ import { expect } from 'chai'; | |||||||
| import { MarkerParser } from '../../src/parsers/marker.parser'; | import { MarkerParser } from '../../src/parsers/marker.parser'; | ||||||
|  |  | ||||||
| describe('MarkerParser', () => { | describe('MarkerParser', () => { | ||||||
|  |  | ||||||
| 	const componentFilename: string = 'test.component.ts'; | 	const componentFilename: string = 'test.component.ts'; | ||||||
|  |  | ||||||
| 	let parser: MarkerParser; | 	let parser: MarkerParser; | ||||||
| @@ -12,7 +11,6 @@ describe('MarkerParser', () => { | |||||||
| 		parser = new MarkerParser(); | 		parser = new MarkerParser(); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
|  |  | ||||||
| 	it('should extract strings using marker function', () => { | 	it('should extract strings using marker function', () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			import { marker } from '@biesbjerg/ngx-translate-extract-marker'; | 			import { marker } from '@biesbjerg/ngx-translate-extract-marker'; | ||||||
| @@ -35,11 +33,32 @@ describe('MarkerParser', () => { | |||||||
| 			_('Mix ' + \`of \` + 'different ' + \`types\`); | 			_('Mix ' + \`of \` + 'different ' + \`types\`); | ||||||
| 		`; | 		`; | ||||||
| 		const keys = parser.extract(contents, componentFilename).keys(); | 		const keys = parser.extract(contents, componentFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal([ | 		expect(keys).to.deep.equal(['Hello world', 'This is a very very very very long line.', 'Mix of different types']); | ||||||
| 			'Hello world', |  | ||||||
| 			'This is a very very very very long line.', |  | ||||||
| 			'Mix of different types' |  | ||||||
| 		]); |  | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract split strings while keeping html tags', () => { | ||||||
|  | 		const contents = ` | ||||||
|  | 			import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; | ||||||
|  | 			_('Hello ' + 'world'); | ||||||
|  | 			_('This <em>is</em> a ' + 'very ' + 'very ' + 'very ' + 'very ' + 'long line.'); | ||||||
|  | 			_('Mix ' + \`of \` + 'different ' + \`types\`); | ||||||
|  | 		`; | ||||||
|  | 		const keys = parser.extract(contents, componentFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Hello world', 'This <em>is</em> a very very very very long line.', 'Mix of different types']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract the strings', () => { | ||||||
|  | 		const contents = ` | ||||||
|  | 		import { marker } from '@biesbjerg/ngx-translate-extract-marker'; | ||||||
|  |  | ||||||
|  | 		export class AppModule { | ||||||
|  | 			constructor() { | ||||||
|  | 				marker('DYNAMIC_TRAD.val1'); | ||||||
|  | 				marker('DYNAMIC_TRAD.val2'); | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  | 		`; | ||||||
|  | 		const keys = parser.extract(contents, componentFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['DYNAMIC_TRAD.val1', 'DYNAMIC_TRAD.val2']); | ||||||
|  | 	}); | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -3,7 +3,6 @@ import { expect } from 'chai'; | |||||||
| import { PipeParser } from '../../src/parsers/pipe.parser'; | import { PipeParser } from '../../src/parsers/pipe.parser'; | ||||||
|  |  | ||||||
| describe('PipeParser', () => { | describe('PipeParser', () => { | ||||||
|  |  | ||||||
| 	const templateFilename: string = 'test.template.html'; | 	const templateFilename: string = 'test.template.html'; | ||||||
|  |  | ||||||
| 	let parser: PipeParser; | 	let parser: PipeParser; | ||||||
| @@ -30,12 +29,78 @@ describe('PipeParser', () => { | |||||||
| 		expect(keys).to.deep.equal(['World']); | 		expect(keys).to.deep.equal(['World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should extract interpolated strings when translate pipe is used in conjunction with other pipes', () => { | 	it('should extract interpolated strings when translate pipe is used before other pipes', () => { | ||||||
| 		const contents = `Hello {{ 'World' | translate | upper }}`; | 		const contents = `Hello {{ 'World' | translate | upper }}`; | ||||||
| 		const keys = parser.extract(contents, templateFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal(['World']); | 		expect(keys).to.deep.equal(['World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract interpolated strings when translate pipe is used after other pipes', () => { | ||||||
|  | 		const contents = `Hello {{ 'World'  | upper | translate }}`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from ternary operators inside interpolations', () => { | ||||||
|  | 		const contents = `{{ (condition ? 'Hello' : 'World') | translate }}`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Hello', 'World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from ternary operators right expression', () => { | ||||||
|  | 		const contents = `{{ condition ? null : ('World' | translate) }}`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from ternary operators inside attribute bindings', () => { | ||||||
|  | 		const contents = `<span [attr]="condition ? null : ('World' | translate)"></span>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from ternary operators left expression', () => { | ||||||
|  | 		const contents = `{{ condition ? ('World' | translate) : null }}`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings inside string concatenation', () => { | ||||||
|  | 		const contents = `{{ 'a' + ('Hello' | translate) + 'b' + 'c' + ('World' | translate) + 'd' }}`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Hello', 'World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from object', () => { | ||||||
|  | 		const contents = `{{ { foo: 'Hello' | translate, bar: ['World' | translate], deep: { nested: { baz: 'Yes' | translate } } } | json }}`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Hello', 'World', 'Yes']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from ternary operators inside attribute bindings', () => { | ||||||
|  | 		const contents = `<span [attr]="(condition ? 'Hello' : 'World') | translate"></span>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Hello', 'World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from nested expressions', () => { | ||||||
|  | 		const contents = `<span [attr]="{ foo: ['a' + ((condition ? 'Hello' : 'World') | translate) + 'b'] }"></span>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Hello', 'World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from nested ternary operators ', () => { | ||||||
|  | 		const contents = `<h3>{{ (condition ? 'Hello' : anotherCondition ? 'Nested' : 'World' ) | translate }}</h3>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Hello', 'Nested', 'World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from ternary operators inside attribute interpolations', () => { | ||||||
|  | 		const contents = `<span attr="{{(condition ? 'Hello' : 'World') | translate}}"></span>`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['Hello', 'World']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
| 	it('should extract strings with escaped quotes', () => { | 	it('should extract strings with escaped quotes', () => { | ||||||
| 		const contents = `Hello {{ 'World\\'s largest potato' | translate }}`; | 		const contents = `Hello {{ 'World\\'s largest potato' | translate }}`; | ||||||
| 		const keys = parser.extract(contents, templateFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| @@ -60,7 +125,7 @@ describe('PipeParser', () => { | |||||||
| 		expect(keys).to.deep.equal(['Hello World']); | 		expect(keys).to.deep.equal(['Hello World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should not use a greedy regular expression', () => { | 	it('should extract multiple entries from nodes', () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			<ion-header> | 			<ion-header> | ||||||
| 				<ion-navbar color="brand"> | 				<ion-navbar color="brand"> | ||||||
| @@ -119,4 +184,21 @@ describe('PipeParser', () => { | |||||||
| 		expect(keys).to.deep.equal(['message']); | 		expect(keys).to.deep.equal(['message']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
|  | 	it('should ignore calculated values', () => { | ||||||
|  | 		const contents = `{{ 'SOURCES.' + source.name + '.NAME_PLURAL' | translate }}`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal([]); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should not extract pipe argument', () => { | ||||||
|  | 		const contents = `{{ value | valueToTranslationKey: 'argument' | translate }}`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal([]); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings from piped arguments inside a function calls on templates', () => { | ||||||
|  | 		const contents = `{{ callMe('Hello' | translate, 'World' | translate ) }}`; | ||||||
|  | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal([`Hello`, `World`]); | ||||||
|  | 	}); | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -2,18 +2,25 @@ import { expect } from 'chai'; | |||||||
|  |  | ||||||
| import { ServiceParser } from '../../src/parsers/service.parser'; | import { ServiceParser } from '../../src/parsers/service.parser'; | ||||||
|  |  | ||||||
| class TestServiceParser extends ServiceParser { |  | ||||||
|  |  | ||||||
| } |  | ||||||
|  |  | ||||||
| describe('ServiceParser', () => { | describe('ServiceParser', () => { | ||||||
|  |  | ||||||
| 	const componentFilename: string = 'test.component.ts'; | 	const componentFilename: string = 'test.component.ts'; | ||||||
|  |  | ||||||
| 	let parser: TestServiceParser; | 	let parser: ServiceParser; | ||||||
|  |  | ||||||
| 	beforeEach(() => { | 	beforeEach(() => { | ||||||
| 		parser = new TestServiceParser(); | 		parser = new ServiceParser(); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should extract strings when TranslateService is accessed directly via constructor parameter', () => { | ||||||
|  | 		const contents = ` | ||||||
|  | 			@Component({ }) | ||||||
|  | 			export class MyComponent { | ||||||
|  | 				public constructor(protected translateService: TranslateService) { | ||||||
|  | 					translateService.get('It works!'); | ||||||
|  | 				} | ||||||
|  | 		`; | ||||||
|  | 		const keys = parser.extract(contents, componentFilename).keys(); | ||||||
|  | 		expect(keys).to.deep.equal(['It works!']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should support extracting binary expressions', () => { | 	it('should support extracting binary expressions', () => { | ||||||
| @@ -44,7 +51,7 @@ describe('ServiceParser', () => { | |||||||
| 		expect(keys).to.deep.equal(['Fallback message']); | 		expect(keys).to.deep.equal(['Fallback message']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should extract strings in TranslateService\'s get() method', () => { | 	it("should extract strings in TranslateService's get() method", () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			@Component({ }) | 			@Component({ }) | ||||||
| 			export class AppComponent { | 			export class AppComponent { | ||||||
| @@ -57,7 +64,7 @@ describe('ServiceParser', () => { | |||||||
| 		expect(keys).to.deep.equal(['Hello World']); | 		expect(keys).to.deep.equal(['Hello World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should extract strings in TranslateService\'s instant() method', () => { | 	it("should extract strings in TranslateService's instant() method", () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			@Component({ }) | 			@Component({ }) | ||||||
| 			export class AppComponent { | 			export class AppComponent { | ||||||
| @@ -70,7 +77,7 @@ describe('ServiceParser', () => { | |||||||
| 		expect(keys).to.deep.equal(['Hello World']); | 		expect(keys).to.deep.equal(['Hello World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should extract strings in TranslateService\'s stream() method', () => { | 	it("should extract strings in TranslateService's stream() method", () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			@Component({ }) | 			@Component({ }) | ||||||
| 			export class AppComponent { | 			export class AppComponent { | ||||||
| @@ -83,7 +90,7 @@ describe('ServiceParser', () => { | |||||||
| 		expect(keys).to.deep.equal(['Hello World']); | 		expect(keys).to.deep.equal(['Hello World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should extract array of strings in TranslateService\'s get() method', () => { | 	it("should extract array of strings in TranslateService's get() method", () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			@Component({ }) | 			@Component({ }) | ||||||
| 			export class AppComponent { | 			export class AppComponent { | ||||||
| @@ -96,7 +103,7 @@ describe('ServiceParser', () => { | |||||||
| 		expect(keys).to.deep.equal(['Hello', 'World']); | 		expect(keys).to.deep.equal(['Hello', 'World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should extract array of strings in TranslateService\'s instant() method', () => { | 	it("should extract array of strings in TranslateService's instant() method", () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			@Component({ }) | 			@Component({ }) | ||||||
| 			export class AppComponent { | 			export class AppComponent { | ||||||
| @@ -109,7 +116,7 @@ describe('ServiceParser', () => { | |||||||
| 		expect(key).to.deep.equal(['Hello', 'World']); | 		expect(key).to.deep.equal(['Hello', 'World']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should extract array of strings in TranslateService\'s stream() method', () => { | 	it("should extract array of strings in TranslateService's stream() method", () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			@Component({ }) | 			@Component({ }) | ||||||
| 			export class AppComponent { | 			export class AppComponent { | ||||||
| @@ -298,5 +305,4 @@ describe('ServiceParser', () => { | |||||||
| 		const keys = parser.extract(contents, componentFilename).keys(); | 		const keys = parser.extract(contents, componentFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal(['Back']); | 		expect(keys).to.deep.equal(['Back']); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -3,7 +3,6 @@ import { expect } from 'chai'; | |||||||
| import { isPathAngularComponent, extractComponentInlineTemplate } from '../../src/utils/utils'; | import { isPathAngularComponent, extractComponentInlineTemplate } from '../../src/utils/utils'; | ||||||
|  |  | ||||||
| describe('Utils', () => { | describe('Utils', () => { | ||||||
|  |  | ||||||
| 	it('should recognize js extension as angular component', () => { | 	it('should recognize js extension as angular component', () => { | ||||||
| 		const result = isPathAngularComponent('test.js'); | 		const result = isPathAngularComponent('test.js'); | ||||||
| 		expect(result).to.equal(true); | 		expect(result).to.equal(true); | ||||||
| @@ -63,5 +62,4 @@ describe('Utils', () => { | |||||||
| 		const template = extractComponentInlineTemplate(contents); | 		const template = extractComponentInlineTemplate(contents); | ||||||
| 		expect(template).to.equal('\n\t\t\t\t\t<p>\n\t\t\t\t\t\tHello World\n\t\t\t\t\t</p>\n\t\t\t\t'); | 		expect(template).to.equal('\n\t\t\t\t\t<p>\n\t\t\t\t\t\tHello World\n\t\t\t\t\t</p>\n\t\t\t\t'); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -5,7 +5,6 @@ import { KeyAsDefaultValuePostProcessor } from '../../src/post-processors/key-as | |||||||
| import { TranslationCollection } from '../../src/utils/translation.collection'; | import { TranslationCollection } from '../../src/utils/translation.collection'; | ||||||
|  |  | ||||||
| describe('KeyAsDefaultValuePostProcessor', () => { | describe('KeyAsDefaultValuePostProcessor', () => { | ||||||
|  |  | ||||||
| 	let processor: PostProcessorInterface; | 	let processor: PostProcessorInterface; | ||||||
|  |  | ||||||
| 	beforeEach(() => { | 	beforeEach(() => { | ||||||
| @@ -27,5 +26,4 @@ describe('KeyAsDefaultValuePostProcessor', () => { | |||||||
| 			'Use this key as value as well': 'Use this key as value as well' | 			'Use this key as value as well': 'Use this key as value as well' | ||||||
| 		}); | 		}); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -5,7 +5,6 @@ import { NullAsDefaultValuePostProcessor } from '../../src/post-processors/null- | |||||||
| import { TranslationCollection } from '../../src/utils/translation.collection'; | import { TranslationCollection } from '../../src/utils/translation.collection'; | ||||||
|  |  | ||||||
| describe('NullAsDefaultValuePostProcessor', () => { | describe('NullAsDefaultValuePostProcessor', () => { | ||||||
|  |  | ||||||
| 	let processor: PostProcessorInterface; | 	let processor: PostProcessorInterface; | ||||||
|  |  | ||||||
| 	beforeEach(() => { | 	beforeEach(() => { | ||||||
| @@ -38,5 +37,4 @@ describe('NullAsDefaultValuePostProcessor', () => { | |||||||
| 			'String A': 'Streng A' | 			'String A': 'Streng A' | ||||||
| 		}); | 		}); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -5,15 +5,14 @@ import { PurgeObsoleteKeysPostProcessor } from '../../src/post-processors/purge- | |||||||
| import { TranslationCollection } from '../../src/utils/translation.collection'; | import { TranslationCollection } from '../../src/utils/translation.collection'; | ||||||
|  |  | ||||||
| describe('PurgeObsoleteKeysPostProcessor', () => { | describe('PurgeObsoleteKeysPostProcessor', () => { | ||||||
|  | 	let postProcessor: PostProcessorInterface; | ||||||
| 	let processor: PostProcessorInterface; |  | ||||||
|  |  | ||||||
| 	beforeEach(() => { | 	beforeEach(() => { | ||||||
| 		processor = new PurgeObsoleteKeysPostProcessor(); | 		postProcessor = new PurgeObsoleteKeysPostProcessor(); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should purge obsolete keys', () => { | 	it('should purge obsolete keys', () => { | ||||||
| 		const collection = new TranslationCollection({ | 		const draft = new TranslationCollection({ | ||||||
| 			'I am completely new': '', | 			'I am completely new': '', | ||||||
| 			'I already exist': '', | 			'I already exist': '', | ||||||
| 			'I already exist but was not present in extract': '' | 			'I already exist but was not present in extract': '' | ||||||
| @@ -27,10 +26,9 @@ describe('PurgeObsoleteKeysPostProcessor', () => { | |||||||
| 			'I already exist but was not present in extract': '' | 			'I already exist but was not present in extract': '' | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		expect(processor.process(collection, extracted, existing).values).to.deep.equal({ | 		expect(postProcessor.process(draft, extracted, existing).values).to.deep.equal({ | ||||||
| 			'I am completely new': '', | 			'I am completely new': '', | ||||||
| 			'I already exist': '' | 			'I already exist': '' | ||||||
| 		}); | 		}); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -5,7 +5,6 @@ import { SortByKeyPostProcessor } from '../../src/post-processors/sort-by-key.po | |||||||
| import { TranslationCollection } from '../../src/utils/translation.collection'; | import { TranslationCollection } from '../../src/utils/translation.collection'; | ||||||
|  |  | ||||||
| describe('SortByKeyPostProcessor', () => { | describe('SortByKeyPostProcessor', () => { | ||||||
|  |  | ||||||
| 	let processor: PostProcessorInterface; | 	let processor: PostProcessorInterface; | ||||||
|  |  | ||||||
| 	beforeEach(() => { | 	beforeEach(() => { | ||||||
| @@ -14,20 +13,19 @@ describe('SortByKeyPostProcessor', () => { | |||||||
|  |  | ||||||
| 	it('should sort keys alphanumerically', () => { | 	it('should sort keys alphanumerically', () => { | ||||||
| 		const collection = new TranslationCollection({ | 		const collection = new TranslationCollection({ | ||||||
| 			'z': 'last value', | 			z: 'last value', | ||||||
| 			'a': 'a value', | 			a: 'a value', | ||||||
| 			'9': 'a numeric key', | 			'9': 'a numeric key', | ||||||
| 			'b': 'another value' | 			b: 'another value' | ||||||
| 		}); | 		}); | ||||||
| 		const extracted = new TranslationCollection(); | 		const extracted = new TranslationCollection(); | ||||||
| 		const existing = new TranslationCollection(); | 		const existing = new TranslationCollection(); | ||||||
|  |  | ||||||
| 		expect(processor.process(collection, extracted, existing).values).to.deep.equal({ | 		expect(processor.process(collection, extracted, existing).values).to.deep.equal({ | ||||||
| 			'9': 'a numeric key', | 			'9': 'a numeric key', | ||||||
| 			'a': 'a value', | 			a: 'a value', | ||||||
| 			'b': 'another value', | 			b: 'another value', | ||||||
| 			'z': 'last value' | 			z: 'last value' | ||||||
| 		}); | 		}); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -0,0 +1,40 @@ | |||||||
|  | import { expect } from 'chai'; | ||||||
|  |  | ||||||
|  | import { PostProcessorInterface } from '../../src/post-processors/post-processor.interface'; | ||||||
|  | import { StringAsDefaultValuePostProcessor } from '../../src/post-processors/string-as-default-value.post-processor'; | ||||||
|  | import { TranslationCollection } from '../../src/utils/translation.collection'; | ||||||
|  |  | ||||||
|  | describe('StringAsDefaultValuePostProcessor', () => { | ||||||
|  | 	let processor: PostProcessorInterface; | ||||||
|  |  | ||||||
|  | 	beforeEach(() => { | ||||||
|  | 		processor = new StringAsDefaultValuePostProcessor({ defaultValue: 'default' }); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should use string as default value', () => { | ||||||
|  | 		const draft = new TranslationCollection({ 'String A': '' }); | ||||||
|  | 		const extracted = new TranslationCollection({ 'String A': '' }); | ||||||
|  | 		const existing = new TranslationCollection(); | ||||||
|  | 		expect(processor.process(draft, extracted, existing).values).to.deep.equal({ | ||||||
|  | 			'String A': 'default' | ||||||
|  | 		}); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should keep existing value even if it is an empty string', () => { | ||||||
|  | 		const draft = new TranslationCollection({ 'String A': '' }); | ||||||
|  | 		const extracted = new TranslationCollection({ 'String A': '' }); | ||||||
|  | 		const existing = new TranslationCollection({ 'String A': '' }); | ||||||
|  | 		expect(processor.process(draft, extracted, existing).values).to.deep.equal({ | ||||||
|  | 			'String A': '' | ||||||
|  | 		}); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
|  | 	it('should keep existing value', () => { | ||||||
|  | 		const draft = new TranslationCollection({ 'String A': 'Streng A' }); | ||||||
|  | 		const extracted = new TranslationCollection({ 'String A': 'Streng A' }); | ||||||
|  | 		const existing = new TranslationCollection({ 'String A': 'Streng A' }); | ||||||
|  | 		expect(processor.process(draft, extracted, existing).values).to.deep.equal({ | ||||||
|  | 			'String A': 'Streng A' | ||||||
|  | 		}); | ||||||
|  | 	}); | ||||||
|  | }); | ||||||
| @@ -3,7 +3,6 @@ import { expect } from 'chai'; | |||||||
| import { TranslationCollection } from '../../src/utils/translation.collection'; | import { TranslationCollection } from '../../src/utils/translation.collection'; | ||||||
|  |  | ||||||
| describe('StringCollection', () => { | describe('StringCollection', () => { | ||||||
|  |  | ||||||
| 	let collection: TranslationCollection; | 	let collection: TranslationCollection; | ||||||
|  |  | ||||||
| 	beforeEach(() => { | 	beforeEach(() => { | ||||||
| @@ -64,12 +63,15 @@ describe('StringCollection', () => { | |||||||
| 	it('should merge with other collection', () => { | 	it('should merge with other collection', () => { | ||||||
| 		collection = collection.add('oldKey', 'oldVal'); | 		collection = collection.add('oldKey', 'oldVal'); | ||||||
| 		const newCollection = new TranslationCollection({ newKey: 'newVal' }); | 		const newCollection = new TranslationCollection({ newKey: 'newVal' }); | ||||||
| 		expect(collection.union(newCollection).values).to.deep.equal({ oldKey: 'oldVal', newKey: 'newVal' }); | 		expect(collection.union(newCollection).values).to.deep.equal({ | ||||||
|  | 			oldKey: 'oldVal', | ||||||
|  | 			newKey: 'newVal' | ||||||
|  | 		}); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| 	it('should intersect with passed collection', () => { | 	it('should intersect with passed collection', () => { | ||||||
| 		collection = collection.addKeys(['red', 'green', 'blue']); | 		collection = collection.addKeys(['red', 'green', 'blue']); | ||||||
| 		const newCollection = new TranslationCollection( { red: '', blue: '' }); | 		const newCollection = new TranslationCollection({ red: '', blue: '' }); | ||||||
| 		expect(collection.intersect(newCollection).values).to.deep.equal({ red: '', blue: '' }); | 		expect(collection.intersect(newCollection).values).to.deep.equal({ red: '', blue: '' }); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| @@ -88,7 +90,10 @@ describe('StringCollection', () => { | |||||||
| 	it('should map values', () => { | 	it('should map values', () => { | ||||||
| 		collection = new TranslationCollection({ red: 'rød', green: 'grøn', blue: 'blå' }); | 		collection = new TranslationCollection({ red: 'rød', green: 'grøn', blue: 'blå' }); | ||||||
| 		collection = collection.map((key, val) => 'mapped value'); | 		collection = collection.map((key, val) => 'mapped value'); | ||||||
| 		expect(collection.values).to.deep.equal({ red: 'mapped value', green: 'mapped value', blue: 'mapped value' }); | 		expect(collection.values).to.deep.equal({ | ||||||
|  | 			red: 'mapped value', | ||||||
|  | 			green: 'mapped value', | ||||||
|  | 			blue: 'mapped value' | ||||||
|  | 		}); | ||||||
| 	}); | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -1,26 +1,25 @@ | |||||||
| { | { | ||||||
|     "compilerOptions": { |     "compilerOptions": { | ||||||
|         "allowSyntheticDefaultImports": true, |         "allowSyntheticDefaultImports": true, | ||||||
|         "noUnusedLocals": true, |  | ||||||
|         "noImplicitAny": true, |         "noImplicitAny": true, | ||||||
|  |         "noImplicitReturns": true, | ||||||
|  |         "noImplicitThis": true, | ||||||
|  |         "noImplicitUseStrict": true, | ||||||
|         "removeComments": true, |         "removeComments": true, | ||||||
|         "declaration": true, |         "declaration": true, | ||||||
|         "target": "es2015", |         "target": "es2019", | ||||||
|         "lib": [ |         "lib": [ | ||||||
|             "dom", |             "es2019" | ||||||
|             "es2018" |  | ||||||
|         ], |         ], | ||||||
|         "module": "commonjs", |         "module": "commonjs", | ||||||
|         "outDir": "./dist/", |         "outDir": "dist", | ||||||
|         "sourceMap": true, |         "sourceMap": true, | ||||||
|         "typeRoots" : [ |         "typeRoots" : [ | ||||||
|             "./node_modules/@types" |             "node_modules/@types" | ||||||
|         ], |         ] | ||||||
|     }, |     }, | ||||||
|     "include": [ |     "include": [ | ||||||
|         "src/**/*.ts" |         "src/**/*.ts" | ||||||
|     ], |     ], | ||||||
|     "exclude": [ |     "exclude": [] | ||||||
|         "node_modules" |  | ||||||
|     ] |  | ||||||
| } | } | ||||||
|   | |||||||
							
								
								
									
										8
									
								
								tslint.commit.json
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										8
									
								
								tslint.commit.json
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,8 @@ | |||||||
|  | { | ||||||
|  |   "extends": ["./tslint.json", "tslint-etc"], | ||||||
|  |   "jsRules": {}, | ||||||
|  |   "rules": { | ||||||
|  |     "ordered-imports": false, | ||||||
|  |     "no-unused-declaration": true | ||||||
|  |   } | ||||||
|  | } | ||||||
							
								
								
									
										169
									
								
								tslint.json
									
									
									
									
									
								
							
							
						
						
									
										169
									
								
								tslint.json
									
									
									
									
									
								
							| @@ -1,53 +1,118 @@ | |||||||
| { | { | ||||||
| 	"rulesDirectory": [ |   "defaultSeverity": "error", | ||||||
| 		"node_modules/tslint-eslint-rules/dist/rules" |   "extends": [ | ||||||
| 	], |     "tslint-config-prettier" | ||||||
| 	"rules": { |   ], | ||||||
| 		"indent": [true, "tabs"], |   "rules": { | ||||||
| 		"semicolon": [true, "always", "ignore-interfaces"], |     "arrow-return-shorthand": true, | ||||||
| 		"quotemark": [true, "single", "avoid-escape"], |     "callable-types": true, | ||||||
| 		"only-arrow-functions": false, |     "class-name": true, | ||||||
| 		"no-duplicate-variable": true, |     "comment-format": [ | ||||||
| 		"member-access": true, |       true, | ||||||
| 		"member-ordering": [ |       "check-space" | ||||||
| 			true, |     ], | ||||||
| 			{ |     "curly": true, | ||||||
| 				"order": [ |     "deprecation": { | ||||||
| 					"public-static-field", |       "severity": "warn" | ||||||
| 					"public-static-method", |     }, | ||||||
| 					"protected-static-field", |     "eofline": true, | ||||||
| 					"protected-static-method", |     "forin": true, | ||||||
| 					"private-static-field", |     "import-spacing": true, | ||||||
| 					"private-static-method", |     "indent": [ | ||||||
| 					"public-instance-field", |       true, | ||||||
| 					"protected-instance-field", |       "tabs" | ||||||
| 					"private-instance-field", |     ], | ||||||
| 					"constructor", |     "interface-over-type-literal": true, | ||||||
| 					"public-instance-method", |     "label-position": true, | ||||||
| 					"protected-instance-method", |     "max-line-length": [ | ||||||
| 					"private-instance-method" |       true, | ||||||
| 				] |       220 | ||||||
| 			} |     ], | ||||||
| 		], |     "member-access": false, | ||||||
| 		"curly": true, |     "member-ordering": [ | ||||||
| 		"eofline": true, |       true, | ||||||
| 		"no-trailing-whitespace": true, |       { | ||||||
| 		"trailing-comma": [ |         "order": [ | ||||||
| 			true, |           "static-field", | ||||||
| 			{ |           "instance-field", | ||||||
| 				"multiline": "never", |           "static-method", | ||||||
| 				"singleline": "never" |           "instance-method" | ||||||
| 			} |         ] | ||||||
| 		], |       } | ||||||
| 		"whitespace": [ |     ], | ||||||
| 			true, |     "no-arg": true, | ||||||
| 			"check-branch", |     "no-bitwise": true, | ||||||
| 			"check-decl", |     "no-console": [ | ||||||
| 			"check-operator", |       true, | ||||||
| 			"check-module", |       "debug", | ||||||
| 			"check-separator", |       "info", | ||||||
| 			"check-type", |       "time", | ||||||
| 			"check-typecast" |       "timeEnd", | ||||||
| 		] |       "trace" | ||||||
| 	} |     ], | ||||||
| } |     "no-construct": true, | ||||||
|  |     "no-debugger": true, | ||||||
|  |     "no-duplicate-super": true, | ||||||
|  |     "no-empty": false, | ||||||
|  |     "no-empty-interface": true, | ||||||
|  |     "no-eval": true, | ||||||
|  |     "no-inferrable-types": [ | ||||||
|  |       false, | ||||||
|  |       "ignore-params" | ||||||
|  |     ], | ||||||
|  |     "no-misused-new": true, | ||||||
|  |     "no-non-null-assertion": true, | ||||||
|  |     "no-shadowed-variable": true, | ||||||
|  |     "no-string-literal": false, | ||||||
|  |     "no-string-throw": true, | ||||||
|  |     "no-switch-case-fall-through": true, | ||||||
|  |     "no-trailing-whitespace": true, | ||||||
|  |     "no-unnecessary-initializer": true, | ||||||
|  |     "no-unused-expression": true, | ||||||
|  |     "no-var-keyword": true, | ||||||
|  |     "object-literal-sort-keys": false, | ||||||
|  |     "one-line": [ | ||||||
|  |       true, | ||||||
|  |       "check-open-brace", | ||||||
|  |       "check-catch", | ||||||
|  |       "check-else", | ||||||
|  |       "check-whitespace" | ||||||
|  |     ], | ||||||
|  |     "prefer-const": true, | ||||||
|  |     "radix": true, | ||||||
|  |     "semicolon": [ | ||||||
|  |       true, | ||||||
|  |       "always" | ||||||
|  |     ], | ||||||
|  |     "triple-equals": [ | ||||||
|  |       true, | ||||||
|  |       "allow-null-check" | ||||||
|  |     ], | ||||||
|  |     "typedef-whitespace": [ | ||||||
|  |       true, | ||||||
|  |       { | ||||||
|  |         "call-signature": "nospace", | ||||||
|  |         "index-signature": "nospace", | ||||||
|  |         "parameter": "nospace", | ||||||
|  |         "property-declaration": "nospace", | ||||||
|  |         "variable-declaration": "nospace" | ||||||
|  |       } | ||||||
|  |     ], | ||||||
|  |     "unified-signatures": true, | ||||||
|  |     "variable-name": [ | ||||||
|  |       true, | ||||||
|  |       "ban-keywords", | ||||||
|  |       "allow-pascal-case", | ||||||
|  |       "check-format" | ||||||
|  |     ], | ||||||
|  |     "whitespace": [ | ||||||
|  |       true, | ||||||
|  |       "check-branch", | ||||||
|  |       "check-decl", | ||||||
|  |       "check-operator", | ||||||
|  |       "check-separator", | ||||||
|  |       "check-type" | ||||||
|  |     ], | ||||||
|  |     "quotemark": [true, "single"] | ||||||
|  |   } | ||||||
|  | } | ||||||
		Reference in New Issue
	
	Block a user