Compare commits
	
		
			44 Commits
		
	
	
		
			v5.0.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 | 
							
								
								
									
										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 | ||||||
|   | |||||||
							
								
								
									
										24
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										24
									
								
								README.md
									
									
									
									
									
								
							| @@ -15,7 +15,8 @@ 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" | ||||||
| } | } | ||||||
| ... | ... | ||||||
| ``` | ``` | ||||||
| @@ -25,11 +26,11 @@ You can now run `npm run extract-i18n` and it will extract strings from your pro | |||||||
|  |  | ||||||
| **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** | ||||||
| @@ -91,12 +92,17 @@ Options: | |||||||
|                  patterns and multiple paths                                                [array] [required] |                  patterns and multiple paths                                                [array] [required] | ||||||
|  |  | ||||||
| Examples: | Examples: | ||||||
|   cli.js -i ./src-a/ -i ./src-b/ -o strings.json           Extract (ts, html) from multiple paths |   ngx-translate-extract -i ./src-a/ -i ./src-b/ -o strings.json           Extract (ts, html) from multiple paths | ||||||
|   cli.js -i './{src-a,src-b}/' -o strings.json             Extract (ts, html) from multiple paths using brace |   ngx-translate-extract -i './{src-a,src-b}/' -o strings.json             Extract (ts, html) from multiple paths using brace | ||||||
|                                                            expansion |                                                            expansion | ||||||
|   cli.js -i ./src/ -o ./i18n/da.json -o ./i18n/en.json     Extract (ts, html) and save to da.json and en.json |   ngx-translate-extract -i ./src/ -o ./i18n/da.json -o ./i18n/en.json     Extract (ts, html) and save to da.json and en.json | ||||||
|   cli.js -i ./src/ -o './i18n/{en,da}.json'                Extract (ts, html) and save to da.json and en.json |   ngx-translate-extract -i ./src/ -o './i18n/{en,da}.json'                Extract (ts, html) and save to da.json and en.json | ||||||
|                                                            using brace expansion |                                                            using brace expansion | ||||||
|   cli.js -i './src/**/*.{ts,tsx,html}' -o strings.json     Extract from ts, tsx and html |   ngx-translate-extract -i './src/**/*.{ts,tsx,html}' -o strings.json     Extract from ts, tsx and html | ||||||
|   cli.js -i './src/**/!(*.spec).{ts,html}' -o              Extract from ts, html, excluding files with ".spec" |   ngx-translate-extract -i './src/**/!(*.spec).{ts,html}' -o              Extract from ts, html, excluding files with ".spec" | ||||||
|   strings.json |   strings.json | ||||||
|  | ``` | ||||||
|  |  | ||||||
|  | ## 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. | ||||||
|   | |||||||
							
								
								
									
										2085
									
								
								package-lock.json
									
									
									
										generated
									
									
									
								
							
							
						
						
									
										2085
									
								
								package-lock.json
									
									
									
										generated
									
									
									
								
							
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							
							
								
								
									
										60
									
								
								package.json
									
									
									
									
									
								
							
							
						
						
									
										60
									
								
								package.json
									
									
									
									
									
								
							| @@ -1,6 +1,6 @@ | |||||||
| { | { | ||||||
|   "name": "@biesbjerg/ngx-translate-extract", |   "name": "@biesbjerg/ngx-translate-extract", | ||||||
|   "version": "5.0.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,7 +14,7 @@ | |||||||
|   "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" | ||||||
|   }, |   }, | ||||||
| @@ -57,42 +57,48 @@ | |||||||
|   }, |   }, | ||||||
|   "homepage": "https://github.com/biesbjerg/ngx-translate-extract", |   "homepage": "https://github.com/biesbjerg/ngx-translate-extract", | ||||||
|   "engines": { |   "engines": { | ||||||
|     "node": ">=12" |     "node": ">=11.15.0" | ||||||
|   }, |   }, | ||||||
|   "config": {}, |   "config": {}, | ||||||
|   "devDependencies": { |   "devDependencies": { | ||||||
|  |     "@angular/compiler": "^11.2.9", | ||||||
|     "@types/braces": "^3.0.0", |     "@types/braces": "^3.0.0", | ||||||
|     "@types/chai": "^4.2.11", |     "@types/chai": "^4.2.16", | ||||||
|     "@types/flat": "^5.0.0", |     "@types/flat": "^5.0.1", | ||||||
|     "@types/glob": "^7.1.1", |     "@types/gettext-parser": "4.0.0", | ||||||
|     "@types/mkdirp": "^1.0.0", |     "@types/glob": "^7.1.3", | ||||||
|     "@types/mocha": "^7.0.2", |     "@types/mkdirp": "^1.0.1", | ||||||
|     "@types/node": "^12.12.30", |     "@types/mocha": "^8.2.2", | ||||||
|     "@types/yargs": "^15.0.4", |     "@types/node": "^14.14.37", | ||||||
|  |     "@types/yargs": "^16.0.1", | ||||||
|     "braces": "^3.0.2", |     "braces": "^3.0.2", | ||||||
|     "chai": "^4.2.0", |     "chai": "^4.3.4", | ||||||
|     "husky": "^4.2.3", |     "husky": "^6.0.0", | ||||||
|     "lint-staged": "^10.0.8", |     "lint-staged": "^10.5.4", | ||||||
|     "mocha": "^7.1.1", |     "mocha": "^8.3.2", | ||||||
|     "prettier": "^1.19.1", |     "prettier": "^2.2.1", | ||||||
|     "ts-node": "^8.7.0", |     "rimraf": "^3.0.2", | ||||||
|     "tslint": "^6.1.0", |     "ts-node": "^9.1.1", | ||||||
|  |     "tslint": "^6.1.3", | ||||||
|     "tslint-config-prettier": "^1.18.0", |     "tslint-config-prettier": "^1.18.0", | ||||||
|     "tslint-eslint-rules": "^5.4.0", |     "tslint-eslint-rules": "^5.4.0", | ||||||
|     "tslint-etc": "^1.10.1" |     "tslint-etc": "^1.13.9", | ||||||
|  |     "typescript": "^4.2.4" | ||||||
|  |   }, | ||||||
|  |   "peerDependencies": { | ||||||
|  |     "@angular/compiler": ">=8.0.0", | ||||||
|  |     "typescript": ">=3.0.0" | ||||||
|   }, |   }, | ||||||
|   "dependencies": { |   "dependencies": { | ||||||
|     "@angular/compiler": "^9.0.7", |     "@phenomnomnominal/tsquery": "^4.1.1", | ||||||
|     "@phenomnomnominal/tsquery": "^4.0.0", |     "boxen": "^5.0.1", | ||||||
|     "boxen": "^4.2.0", |     "colorette": "^1.2.2", | ||||||
|     "colorette": "^1.1.0", |     "flat": "^5.0.2", | ||||||
|     "flat": "^5.0.0", |     "gettext-parser": "^4.0.4", | ||||||
|     "gettext-parser": "^4.0.3", |  | ||||||
|     "glob": "^7.1.6", |     "glob": "^7.1.6", | ||||||
|     "mkdirp": "^1.0.3", |     "mkdirp": "^1.0.4", | ||||||
|     "path": "^0.12.7", |     "path": "^0.12.7", | ||||||
|     "terminal-link": "^2.1.1", |     "terminal-link": "^2.1.1", | ||||||
|     "typescript": "^3.8.3", |     "yargs": "^16.2.0" | ||||||
|     "yargs": "^15.3.1" |  | ||||||
|   } |   } | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,4 +1,5 @@ | |||||||
| 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'; | ||||||
| @@ -18,8 +19,7 @@ import { normalizePaths } from '../utils/fs-helpers'; | |||||||
| import { donateMessage } from '../utils/donate'; | import { donateMessage } from '../utils/donate'; | ||||||
|  |  | ||||||
| // First parsing pass to be able to access pattern argument for use input/output arguments | // First parsing pass to be able to access pattern argument for use input/output arguments | ||||||
| const y = yargs | const y = yargs.option('patterns', { | ||||||
| 	.option('patterns', { |  | ||||||
| 	alias: 'p', | 	alias: 'p', | ||||||
| 	describe: 'Default patterns', | 	describe: 'Default patterns', | ||||||
| 	type: 'array', | 	type: 'array', | ||||||
| @@ -149,6 +149,13 @@ const compiler: CompilerInterface = CompilerFactory.create(cli.format, { | |||||||
| }); | }); | ||||||
| extractTask.setCompiler(compiler); | extractTask.setCompiler(compiler); | ||||||
|  |  | ||||||
|  | // Run task | ||||||
|  | try { | ||||||
| 	extractTask.execute(); | 	extractTask.execute(); | ||||||
|  | 	console.log(green('\nDone.\n')); | ||||||
| 	console.log(donateMessage); | 	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'; | ||||||
| @@ -24,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 }; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -44,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()) { | ||||||
| @@ -56,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)) { | ||||||
|  | 				try { | ||||||
| 					existing = this.compiler.parse(fs.readFileSync(outputPath, 'utf-8')); | 					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 | ||||||
|  | 			try { | ||||||
|  | 				let event = 'CREATED'; | ||||||
|  | 				if (fs.existsSync(outputPath)) { | ||||||
|  | 					this.options.replace ? (event = 'REPLACED') : (event = 'MERGED'); | ||||||
|  | 				} | ||||||
| 				this.save(outputPath, final); | 				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 { | ||||||
| @@ -98,11 +105,11 @@ export class ExtractTask implements TaskInterface { | |||||||
| 	 */ | 	 */ | ||||||
| 	protected extract(): TranslationCollection { | 	protected extract(): TranslationCollection { | ||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
| 		this.inputs.forEach(pattern => { | 		this.inputs.forEach((pattern) => { | ||||||
| 			this.getFiles(pattern).forEach(filePath => { | 			this.getFiles(pattern).forEach((filePath) => { | ||||||
| 				this.out(dim('- %s'), filePath); | 				this.out(dim('- %s'), filePath); | ||||||
| 				const contents: string = fs.readFileSync(filePath, 'utf-8'); | 				const contents: string = fs.readFileSync(filePath, 'utf-8'); | ||||||
| 				this.parsers.forEach(parser => { | 				this.parsers.forEach((parser) => { | ||||||
| 					const extracted = parser.extract(contents, filePath); | 					const extracted = parser.extract(contents, filePath); | ||||||
| 					if (extracted instanceof TranslationCollection) { | 					if (extracted instanceof TranslationCollection) { | ||||||
| 						collection = collection.union(extracted); | 						collection = collection.union(extracted); | ||||||
| @@ -117,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,9 +146,7 @@ export class ExtractTask implements TaskInterface { | |||||||
| 	 * Get all files matching pattern | 	 * Get all files matching pattern | ||||||
| 	 */ | 	 */ | ||||||
| 	protected getFiles(pattern: string): string[] { | 	protected getFiles(pattern: string): string[] { | ||||||
| 		return glob | 		return glob.sync(pattern).filter((filePath) => fs.statSync(filePath).isFile()); | ||||||
| 			.sync(pattern) |  | ||||||
| 			.filter(filePath => fs.statSync(filePath).isFile()); |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	protected out(...args: any[]): void { | 	protected out(...args: any[]): void { | ||||||
| @@ -151,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)'))); | ||||||
| 		} | 		} | ||||||
| @@ -161,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)'))); | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -28,6 +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'); | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,7 +1,7 @@ | |||||||
| 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'; | ||||||
| @@ -22,8 +22,7 @@ export class PoCompiler implements CompilerInterface { | |||||||
| 				'content-transfer-encoding': '8bit' | 				'content-transfer-encoding': '8bit' | ||||||
| 			}, | 			}, | ||||||
| 			translations: { | 			translations: { | ||||||
| 				[this.domain]: Object.keys(collection.values).reduce( | 				[this.domain]: Object.keys(collection.values).reduce((translations, key) => { | ||||||
| 					(translations, key) => { |  | ||||||
| 					return { | 					return { | ||||||
| 						...translations, | 						...translations, | ||||||
| 						[key]: { | 						[key]: { | ||||||
| @@ -31,34 +30,30 @@ export class PoCompiler implements CompilerInterface { | |||||||
| 							msgstr: collection.get(key) | 							msgstr: collection.get(key) | ||||||
| 						} | 						} | ||||||
| 					}; | 					}; | ||||||
| 					}, | 				}, {} 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( | 			.reduce((result, key) => { | ||||||
| 				(result, key) => { |  | ||||||
| 				return { | 				return { | ||||||
| 					...result, | 					...result, | ||||||
| 						[key]: po.translations[this.domain][key].msgstr.pop() | 					[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,82 +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(source: string, filePath: string): TranslationCollection | null { | ||||||
|  | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
|  |  | ||||||
| 		if (filePath && isPathAngularComponent(filePath)) { | 		if (filePath && isPathAngularComponent(filePath)) { | ||||||
| 			source = extractComponentInlineTemplate(source); | 			source = extractComponentInlineTemplate(source); | ||||||
| 		} | 		} | ||||||
|  | 		const nodes: Node[] = this.parseTemplate(source, filePath); | ||||||
|  | 		const elements: ElementLike[] = this.getElementsWithTranslateAttribute(nodes); | ||||||
|  |  | ||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		elements.forEach((element) => { | ||||||
|  | 			const attribute = this.getAttribute(element, TRANSLATE_ATTR_NAME); | ||||||
|  | 			if (attribute?.value) { | ||||||
|  | 				collection = collection.add(attribute.value); | ||||||
|  | 				return; | ||||||
|  | 			} | ||||||
|  |  | ||||||
| 		const nodes: TmplAstNode[] = this.parseTemplate(source, filePath); | 			const boundAttribute = this.getBoundAttribute(element, TRANSLATE_ATTR_NAME); | ||||||
| 		this.getTranslatableElements(nodes).forEach(element => { | 			if (boundAttribute?.value) { | ||||||
| 			const key = this.getElementTranslateAttrValue(element) || this.getElementContents(element); | 				this.getLiteralPrimitives(boundAttribute.value).forEach((literalPrimitive) => { | ||||||
| 			collection = collection.add(key); | 					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]; | ||||||
|  | 			} | ||||||
|  | 			if (this.hasBoundAttribute(element, TRANSLATE_ATTR_NAME)) { | ||||||
|  | 				elements = [...elements, element]; | ||||||
|  | 			} | ||||||
|  | 			const childElements = this.getElementsWithTranslateAttribute(element.children); | ||||||
|  | 			if (childElements.length) { | ||||||
|  | 				elements = [...elements, ...childElements]; | ||||||
|  | 			} | ||||||
|  | 		}); | ||||||
|  | 		return elements; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	protected findChildrenElements(node: TmplAstNode): TmplAstElement[] { | 	/** | ||||||
| 		if (!this.isElement(node)) { | 	 * Get direct child nodes of type Text | ||||||
| 			return []; | 	 * @param element | ||||||
|  | 	 */ | ||||||
|  | 	protected getTextNodes(element: ElementLike): Text[] { | ||||||
|  | 		return element.children.filter(this.isText); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 		// If element has translate attribute all its contents is translatable | 	/** | ||||||
| 		// so we don't need to traverse any deeper | 	 * Check if attribute is present on element | ||||||
| 		if (this.isTranslatable(node)) { | 	 * @param element | ||||||
| 			return [node]; | 	 */ | ||||||
|  | 	protected hasAttribute(element: ElementLike, name: string): boolean { | ||||||
|  | 		return this.getAttribute(element, name) !== undefined; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 		return node.children.reduce( | 	/** | ||||||
| 			(result: TmplAstElement[], childNode: TmplAstNode) => { | 	 * Get attribute value if present on element | ||||||
| 				if (this.isElement(childNode)) { | 	 * @param element | ||||||
| 					const children = this.findChildrenElements(childNode); | 	 */ | ||||||
| 					return result.concat(children); | 	protected getAttribute(element: ElementLike, name: string): TextAttribute { | ||||||
| 				} | 		return element.attributes.find((attribute) => attribute.name === name); | ||||||
| 				return result; |  | ||||||
| 			}, |  | ||||||
| 			[node] |  | ||||||
| 		); |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	protected parseTemplate(template: string, path: string): TmplAstNode[] { | 	/** | ||||||
|  | 	 * 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?.attributes && node?.children; |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	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?.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(); |  | ||||||
| 	} |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -19,7 +19,7 @@ export class MarkerParser implements ParserInterface { | |||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
|  |  | ||||||
| 		const callExpressions = findFunctionCallExpressions(sourceFile, markerImportName); | 		const callExpressions = findFunctionCallExpressions(sourceFile, markerImportName); | ||||||
| 		callExpressions.forEach(callExpression => { | 		callExpressions.forEach((callExpression) => { | ||||||
| 			const [firstArg] = callExpression.arguments; | 			const [firstArg] = callExpression.arguments; | ||||||
| 			if (!firstArg) { | 			if (!firstArg) { | ||||||
| 				return; | 				return; | ||||||
|   | |||||||
| @@ -1,4 +1,17 @@ | |||||||
| import { TmplAstNode, parseTemplate, BindingPipe, LiteralPrimitive, Conditional, TmplAstTextAttribute } from '@angular/compiler'; | 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'; | ||||||
| @@ -14,8 +27,8 @@ export class PipeParser implements ParserInterface { | |||||||
|  |  | ||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
| 		const nodes: TmplAstNode[] = this.parseTemplate(source, filePath); | 		const nodes: TmplAstNode[] = this.parseTemplate(source, filePath); | ||||||
| 		const pipes: BindingPipe[] = nodes.map(node => this.findPipesInNode(node)).flat(); | 		const pipes: BindingPipe[] = nodes.map((node) => this.findPipesInNode(node)).flat(); | ||||||
| 		pipes.forEach(pipe => { | 		pipes.forEach((pipe) => { | ||||||
| 			this.parseTranslationKeysFromPipe(pipe).forEach((key: string) => { | 			this.parseTranslationKeysFromPipe(pipe).forEach((key: string) => { | ||||||
| 				collection = collection.add(key); | 				collection = collection.add(key); | ||||||
| 			}); | 			}); | ||||||
| @@ -36,9 +49,8 @@ export class PipeParser implements ParserInterface { | |||||||
| 			); | 			); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		if (node?.value?.ast?.expressions) { | 		if (node?.value?.ast) { | ||||||
| 			const translateables = node.value.ast.expressions.filter((exp: any) => this.expressionIsOrHasBindingPipe(exp)); | 			ret.push(...this.getTranslatablesFromAst(node.value.ast)); | ||||||
| 			ret.push(...translateables); |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		if (node?.attributes) { | 		if (node?.attributes) { | ||||||
| @@ -51,17 +63,8 @@ export class PipeParser implements ParserInterface { | |||||||
| 		if (node?.inputs) { | 		if (node?.inputs) { | ||||||
| 			node.inputs.forEach((input: any) => { | 			node.inputs.forEach((input: any) => { | ||||||
| 				// <element [attrib]="'identifier' | translate"> | 				// <element [attrib]="'identifier' | translate"> | ||||||
| 				if (input?.value?.ast && this.expressionIsOrHasBindingPipe(input.value.ast)) { | 				if (input?.value?.ast) { | ||||||
| 					ret.push(input.value.ast); | 					ret.push(...this.getTranslatablesFromAst(input.value.ast)); | ||||||
| 				} |  | ||||||
|  |  | ||||||
| 				// <element attrib="{{'identifier' | translate}}>" |  | ||||||
| 				if (input?.value?.ast?.expressions) { |  | ||||||
| 					input.value.ast.expressions.forEach((exp: BindingPipe) => { |  | ||||||
| 						if (this.expressionIsOrHasBindingPipe(exp)) { |  | ||||||
| 							ret.push(exp); |  | ||||||
| 						} |  | ||||||
| 					}); |  | ||||||
| 				} | 				} | ||||||
| 			}); | 			}); | ||||||
| 		} | 		} | ||||||
| @@ -84,7 +87,67 @@ export class PipeParser implements ParserInterface { | |||||||
| 		return ret; | 		return ret; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	protected expressionIsOrHasBindingPipe(exp: any): boolean { | 	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) { | 		if (exp.name && exp.name === TRANSLATE_PIPE_NAME) { | ||||||
| 			return true; | 			return true; | ||||||
| 		} | 		} | ||||||
|   | |||||||
| @@ -1,8 +1,17 @@ | |||||||
|  | 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 { findClassDeclarations, 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']; | ||||||
| @@ -18,14 +27,13 @@ export class ServiceParser implements ParserInterface { | |||||||
|  |  | ||||||
| 		let collection: TranslationCollection = new TranslationCollection(); | 		let collection: TranslationCollection = new TranslationCollection(); | ||||||
|  |  | ||||||
| 		classDeclarations.forEach(classDeclaration => { | 		classDeclarations.forEach((classDeclaration) => { | ||||||
| 			const propName: string = findClassPropertyByType(classDeclaration, TRANSLATE_SERVICE_TYPE_REFERENCE); | 			const callExpressions = [ | ||||||
| 			if (!propName) { | 				...this.findConstructorParamCallExpressions(classDeclaration), | ||||||
| 				return; | 				...this.findPropertyCallExpressions(classDeclaration) | ||||||
| 			} | 			]; | ||||||
|  |  | ||||||
| 			const callExpressions = findMethodCallExpressions(classDeclaration, propName, TRANSLATE_SERVICE_METHOD_NAMES); | 			callExpressions.forEach((callExpression) => { | ||||||
| 			callExpressions.forEach(callExpression => { |  | ||||||
| 				const [firstArg] = callExpression.arguments; | 				const [firstArg] = callExpression.arguments; | ||||||
| 				if (!firstArg) { | 				if (!firstArg) { | ||||||
| 					return; | 					return; | ||||||
| @@ -36,4 +44,21 @@ export class ServiceParser implements ParserInterface { | |||||||
| 		}); | 		}); | ||||||
| 		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); | ||||||
|  | 	} | ||||||
| } | } | ||||||
|   | |||||||
| @@ -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'; | ||||||
| @@ -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))`; | ||||||
| 	const nodes = tsquery<PropertyAccessExpression>(node, query).map(n => n.parent as CallExpression); | 	const nodes = tsquery<PropertyAccessExpression>(node, query).map((n) => n.parent as CallExpression); | ||||||
| 	return nodes; | 	return nodes; | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -2,6 +2,12 @@ import * as os from 'os'; | |||||||
| import * as fs from 'fs'; | import * as fs from 'fs'; | ||||||
| import * as braces from 'braces'; | 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 { | export function normalizeHomeDir(path: string): string { | ||||||
| 	if (path.substring(0, 1) === '~') { | 	if (path.substring(0, 1) === '~') { | ||||||
| 		return `${os.homedir()}/${path.substring(1)}`; | 		return `${os.homedir()}/${path.substring(1)}`; | ||||||
| @@ -10,17 +16,21 @@ export function normalizeHomeDir(path: string): string { | |||||||
| } | } | ||||||
|  |  | ||||||
| export function expandPattern(pattern: string): string[] { | export function expandPattern(pattern: string): string[] { | ||||||
| 	return braces(pattern, { expand: true }); | 	return braces(pattern, { expand: true, keepEscaping: true }); | ||||||
| } | } | ||||||
|  |  | ||||||
| export function normalizePaths(patterns: string[], defaultPatterns: string[] = []): string[] { | export function normalizePaths(patterns: string[], defaultPatterns: string[] = []): string[] { | ||||||
| 	return patterns.map(pattern => | 	return patterns | ||||||
| 		expandPattern(pattern).map(path => { | 		.map((pattern) => | ||||||
|  | 			expandPattern(pattern) | ||||||
|  | 				.map((path) => { | ||||||
| 					path = normalizeHomeDir(path); | 					path = normalizeHomeDir(path); | ||||||
| 					if (fs.existsSync(path) && fs.statSync(path).isDirectory()) { | 					if (fs.existsSync(path) && fs.statSync(path).isDirectory()) { | ||||||
| 				return defaultPatterns.map(defaultPattern => path + defaultPattern); | 						return defaultPatterns.map((defaultPattern) => path + defaultPattern); | ||||||
| 					} | 					} | ||||||
| 					return path; | 					return path; | ||||||
| 		}).flat() | 				}) | ||||||
| 	).flat(); | 				.flat() | ||||||
|  | 		) | ||||||
|  | 		.flat(); | ||||||
| } | } | ||||||
|   | |||||||
| @@ -14,21 +14,18 @@ export class TranslationCollection { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public addKeys(keys: string[]): TranslationCollection { | 	public addKeys(keys: string[]): TranslationCollection { | ||||||
| 		const values = keys.reduce( | 		const values = keys.reduce((results, key) => { | ||||||
| 			(results, key) => { |  | ||||||
| 			return { ...results, [key]: '' }; | 			return { ...results, [key]: '' }; | ||||||
| 			}, | 		}, {} 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; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -56,7 +53,7 @@ export class TranslationCollection { | |||||||
|  |  | ||||||
| 	public intersect(collection: TranslationCollection): TranslationCollection { | 	public intersect(collection: TranslationCollection): TranslationCollection { | ||||||
| 		const values: TranslationType = {}; | 		const values: TranslationType = {}; | ||||||
| 		this.filter(key => collection.has(key)).forEach((key, val) => { | 		this.filter((key) => collection.has(key)).forEach((key, val) => { | ||||||
| 			values[key] = val; | 			values[key] = val; | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| @@ -87,7 +84,7 @@ export class TranslationCollection { | |||||||
| 		const values: TranslationType = {}; | 		const values: TranslationType = {}; | ||||||
| 		this.keys() | 		this.keys() | ||||||
| 			.sort(compareFn) | 			.sort(compareFn) | ||||||
| 			.forEach(key => { | 			.forEach((key) => { | ||||||
| 				values[key] = this.get(key); | 				values[key] = this.get(key); | ||||||
| 			}); | 			}); | ||||||
|  |  | ||||||
|   | |||||||
							
								
								
									
										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"'); | ||||||
|  | 	}); | ||||||
|  | }); | ||||||
|  |  | ||||||
|  |  | ||||||
|  |  | ||||||
| @@ -12,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', () => { | ||||||
| @@ -66,23 +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']); | ||||||
|  | 	}); | ||||||
|  |  | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -35,4 +35,30 @@ describe('MarkerParser', () => { | |||||||
| 		const keys = parser.extract(contents, componentFilename).keys(); | 		const keys = parser.extract(contents, componentFilename).keys(); | ||||||
| 		expect(keys).to.deep.equal(['Hello world', 'This is a very very very very long line.', 'Mix of different types']); | 		expect(keys).to.deep.equal(['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']); | ||||||
|  | 	}); | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -47,12 +47,48 @@ describe('PipeParser', () => { | |||||||
| 		expect(keys).to.deep.equal(['Hello', 'World']); | 		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', () => { | 	it('should extract strings from ternary operators inside attribute bindings', () => { | ||||||
| 		const contents = `<span [attr]="(condition ? 'Hello' : 'World') | translate"></span>`; | 		const contents = `<span [attr]="(condition ? 'Hello' : 'World') | translate"></span>`; | ||||||
| 		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 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 ', () => { | 	it('should extract strings from nested ternary operators ', () => { | ||||||
| 		const contents = `<h3>{{ (condition ? 'Hello' : anotherCondition ? 'Nested' : 'World' ) | translate }}</h3>`; | 		const contents = `<h3>{{ (condition ? 'Hello' : anotherCondition ? 'Nested' : 'World' ) | translate }}</h3>`; | ||||||
| 		const keys = parser.extract(contents, templateFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| @@ -147,4 +183,22 @@ describe('PipeParser', () => { | |||||||
| 		const keys = parser.extract(contents, templateFilename).keys(); | 		const keys = parser.extract(contents, templateFilename).keys(); | ||||||
| 		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`]); | ||||||
|  | 	}); | ||||||
| }); | }); | ||||||
|   | |||||||
| @@ -11,6 +11,18 @@ describe('ServiceParser', () => { | |||||||
| 		parser = new ServiceParser(); | 		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', () => { | ||||||
| 		const contents = ` | 		const contents = ` | ||||||
| 			@Component({ }) | 			@Component({ }) | ||||||
|   | |||||||
| @@ -1,17 +1,15 @@ | |||||||
| { | { | ||||||
|     "compilerOptions": { |     "compilerOptions": { | ||||||
|         "allowSyntheticDefaultImports": true, |         "allowSyntheticDefaultImports": true, | ||||||
|         "noUnusedLocals": true, |  | ||||||
|         "noImplicitAny": true, |         "noImplicitAny": true, | ||||||
|         "noImplicitReturns": true, |         "noImplicitReturns": true, | ||||||
|         "noImplicitThis": true, |         "noImplicitThis": true, | ||||||
|         "noImplicitUseStrict": true, |         "noImplicitUseStrict": true, | ||||||
|         "removeComments": true, |         "removeComments": true, | ||||||
|         "declaration": true, |         "declaration": true, | ||||||
|         "target": "es2015", |         "target": "es2019", | ||||||
|         "lib": [ |         "lib": [ | ||||||
|             "dom", |             "es2019" | ||||||
|             "esnext.array" |  | ||||||
|         ], |         ], | ||||||
|         "module": "commonjs", |         "module": "commonjs", | ||||||
|         "outDir": "dist", |         "outDir": "dist", | ||||||
|   | |||||||
| @@ -112,6 +112,7 @@ | |||||||
|       "check-operator", |       "check-operator", | ||||||
|       "check-separator", |       "check-separator", | ||||||
|       "check-type" |       "check-type" | ||||||
|     ] |     ], | ||||||
|  |     "quotemark": [true, "single"] | ||||||
|   } |   } | ||||||
| } | } | ||||||
		Reference in New Issue
	
	Block a user