Skip to content

Commit b1f1d4d

Browse files
committed
feat: 设置单测框架
Change-Id: I500393496d965c866c43e3c5258bf1983863fd87
1 parent cf0c836 commit b1f1d4d

File tree

11 files changed

+153
-93
lines changed

11 files changed

+153
-93
lines changed

package.json

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
"description": "",
55
"main": "index.js",
66
"scripts": {
7-
"build": "echo \"Please implement your build script and modify scripts.build section in package.json\" && exit 1",
8-
"sync": "sync-files -w ./typescript.d.ts ./node_modules/typescript/lib/typescript.d.ts"
7+
"build": "tsc",
8+
"sync": "sync-files -w ./typescript.d.ts ./node_modules/typescript/lib/typescript.d.ts",
9+
"test": "npm run build && mocha",
10+
"mocha": "mocha"
911
},
1012
"repository": {
1113
"type": "git",

sample/runner.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import {ts2php} from '../src/index';
2+
import * as path from 'path';
3+
4+
ts2php(path.resolve(__dirname, '../sample/index.ts'), {
5+
modules: {
6+
'./atomWiseUtils': {
7+
path: './path/to/utils.php',
8+
className: 'Atom_Wise_Utils'
9+
},
10+
'./tplData': {
11+
path: '',
12+
className: ''
13+
}
14+
}
15+
});

sample/test.php

Lines changed: 0 additions & 4 deletions
This file was deleted.

src/emitter.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,24 +25,25 @@ import {
2525
} from './utilities/nodeTest';
2626
import * as os from 'os';
2727
import {noop} from './core';
28-
import {options as globalOptions, errors} from './globals';
2928
import {tokenToString} from './scanner';
3029
import {getStartsOnNewLine} from './factory';
30+
import {Ts2phpOptions, ErrorInfo} from './types';
3131

3232
let currentSourceFile: SourceFile;
3333

3434

35-
export function emitFile(sourceFile: SourceFile, typeChecker: ts.TypeChecker) {
35+
export function emitFile(sourceFile: SourceFile, typeChecker: ts.TypeChecker, globalOptions: Ts2phpOptions, errors: ErrorInfo[]) {
3636
const brackets = createBracketsMap();
3737
currentSourceFile = sourceFile;
3838
const writer = createTextWriter(os.EOL);
3939
writer.writeLine();
40+
4041

4142
// 变量与 module 的映射,标记某个变量是从哪个 module 中引入的
4243
// 调用函数的时候,需要转换成类方法
4344
const varModuleMap = {};
4445

45-
46+
writer.write('<?php\n');
4647
ts.forEachChild(sourceFile, (node: ts.Node) => {
4748
emitWithHint(ts.EmitHint.Unspecified, node);
4849
writer.writeLine();
@@ -1744,7 +1745,7 @@ export function emitFile(sourceFile: SourceFile, typeChecker: ts.TypeChecker) {
17441745
}
17451746

17461747
if (allowedModules[importModuleName].path) {
1747-
writer.write(`require_once(${allowedModules[importModuleName].path})`);
1748+
writer.write(`require_once("${allowedModules[importModuleName].path}")`);
17481749
writeSemicolon();
17491750
}
17501751
}

src/index.ts

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,41 +4,34 @@
44
*/
55

66
import * as ts from 'typescript';
7-
import * as path from 'path';
87
import * as emitter from './emitter';
9-
import {Ts2phpOptions} from './types';
8+
import {Ts2phpOptions, ErrorInfo} from './types';
109
import {options as globalOptions} from './globals';
1110
import {assign} from 'lodash';
1211

13-
function ts2php(filePath: string, options?: Ts2phpOptions) {
14-
assign(globalOptions, options);
12+
export function ts2php(filePath: string, options?: Ts2phpOptions) {
13+
const opt = assign({}, globalOptions, options);
14+
const errors: ErrorInfo[] = [];
1515

1616
const program = ts.createProgram([filePath], {
1717
target: ts.ScriptTarget.ES5,
1818
module: ts.ModuleKind.CommonJS
1919
});
2020

2121
const typeChecker = program.getTypeChecker();
22-
22+
2323
for (const sourceFile of program.getSourceFiles()) {
2424
if (!sourceFile.isDeclarationFile) {
25-
const a = emitter.emitFile(sourceFile, typeChecker);
26-
console.log(a);
25+
const res = emitter.emitFile(sourceFile, typeChecker, opt, errors);
26+
return {
27+
phpCode: res,
28+
errors
29+
}
2730
}
2831
}
29-
}
3032

31-
ts2php(path.resolve(__dirname, '../sample/index.ts'), {
32-
modules: {
33-
'./atomWiseUtils': {
34-
path: './path/to/utils.php',
35-
className: 'Atom_Wise_Utils'
36-
},
37-
'./tplData': {
38-
path: '',
39-
className: ''
40-
}
41-
}
42-
});
33+
34+
35+
}
4336

4437

test/features/import.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<?php
2+
require_once("./path/to/utils.php");
3+
$tplData->src = Atom_Wise_Utils::makeTcLink($tplData->src);

test/features/import.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import {makeTcLink} from './atomWiseUtils';
2+
import {tplData} from './tplData';
3+
4+
tplData.src = makeTcLink(tplData.src);

test/features/template.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<?php
2+
$b = "123";
3+
$c = "0" . $b . "45'6'\"789\"";

test/features/template.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
const b = '123';
2+
const c = `0${b}45'6'"789"`;

test/index.js

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,50 @@
44
*/
55

66
const assert = require('assert');
7+
const fs = require('fs');
8+
const path = require('path');
9+
const {ts2php} = require('../dist/index.js');
710

8-
describe('Array', function () {
9-
describe('#indexOf()', function () {
10-
it('should return -1 when the value is not present', function () {
11-
assert.equal([1, 2, 3].indexOf(4), -1);
11+
const files = fs.readdirSync(path.resolve(__dirname, './features'));
12+
const featureNames = files.reduce((res, file) => {
13+
const m = file.match(/(.+)\.ts/);
14+
if (m) {
15+
res.push(m[1]);
16+
}
17+
return res;
18+
}, []);
19+
20+
function readFile(path) {
21+
return new Promise((resolve, reject) => {
22+
fs.readFile(path, {encoding: 'utf-8'}, (err, data) => {
23+
resolve(data);
1224
});
1325
});
26+
}
27+
28+
29+
30+
describe('features', () => {
31+
for (let i = 0; i < featureNames.length; i++) {
32+
it('template', async () => {
33+
const featureName = featureNames[i];
34+
const phpContent = await readFile(path.resolve(__dirname, `./features/${featureName}.php`));
35+
const tsPath = path.resolve(__dirname, `./features/${featureName}.ts`);
36+
const res = ts2php(tsPath, {
37+
modules: {
38+
'./atomWiseUtils': {
39+
path: './path/to/utils.php',
40+
className: 'Atom_Wise_Utils'
41+
},
42+
'./tplData': {
43+
path: '',
44+
className: ''
45+
}
46+
}
47+
});
48+
fs.writeFileSync(path.resolve(__dirname, '../output/' + featureName + '.php'), res.phpCode);
49+
assert.equal(res.phpCode, phpContent);
50+
});
51+
}
1452
});
53+

tsconfig.json

Lines changed: 61 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,64 @@
11
{
2+
"include": [
3+
"src/**/*"
4+
],
25
"compilerOptions": {
3-
/* Basic Options */
4-
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
5-
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
6-
"lib": [
7-
"es2015",
8-
"es6"
9-
], /* Specify library files to be included in the compilation. */
10-
// "allowJs": true, /* Allow javascript files to be compiled. */
11-
// "checkJs": true, /* Report errors in .js files. */
12-
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
13-
// "declaration": true, /* Generates corresponding '.d.ts' file. */
14-
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15-
// "sourceMap": true, /* Generates corresponding '.map' file. */
16-
// "outFile": "./", /* Concatenate and emit output to single file. */
17-
// "outDir": "dist", /* Redirect output structure to the directory. */
18-
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
19-
// "composite": true, /* Enable project compilation */
20-
// "removeComments": true, /* Do not emit comments to output. */
21-
// "noEmit": true, /* Do not emit outputs. */
22-
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
23-
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
24-
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
25-
26-
/* Strict Type-Checking Options */
27-
// "strict": true, /* Enable all strict type-checking options. */
28-
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
29-
// "strictNullChecks": true, /* Enable strict null checks. */
30-
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
31-
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
32-
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
33-
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
34-
35-
/* Additional Checks */
36-
// "noUnusedLocals": true, /* Report errors on unused locals. */
37-
// "noUnusedParameters": true, /* Report errors on unused parameters. */
38-
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
39-
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
40-
41-
/* Module Resolution Options */
42-
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
43-
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
44-
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
45-
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
46-
// "typeRoots": [], /* List of folders to include type definitions from. */
47-
// "types": [], /* Type declaration files to be included in compilation. */
48-
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
49-
// "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
50-
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
51-
52-
/* Source Map Options */
53-
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
54-
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
55-
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
56-
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
57-
58-
/* Experimental Options */
59-
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
60-
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
6+
/* Basic Options */
7+
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
8+
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
9+
"lib": [
10+
"es2015"
11+
], /* Specify library files to be included in the compilation. */
12+
// "allowJs": true, /* Allow javascript files to be compiled. */
13+
// "checkJs": true, /* Report errors in .js files. */
14+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
15+
// "declaration": true, /* Generates corresponding '.d.ts' file. */
16+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
17+
// "sourceMap": true, /* Generates corresponding '.map' file. */
18+
// "outFile": "./", /* Concatenate and emit output to single file. */
19+
"outDir": "dist", /* Redirect output structure to the directory. */
20+
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
21+
// "composite": true, /* Enable project compilation */
22+
// "removeComments": true, /* Do not emit comments to output. */
23+
// "noEmit": true, /* Do not emit outputs. */
24+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
25+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
26+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
27+
28+
/* Strict Type-Checking Options */
29+
// "strict": true, /* Enable all strict type-checking options. */
30+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
31+
// "strictNullChecks": true, /* Enable strict null checks. */
32+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
33+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
34+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
35+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
36+
37+
/* Additional Checks */
38+
// "noUnusedLocals": true, /* Report errors on unused locals. */
39+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
40+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
41+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
42+
43+
/* Module Resolution Options */
44+
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
45+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
46+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
47+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
48+
// "typeRoots": [], /* List of folders to include type definitions from. */
49+
// "types": [], /* Type declaration files to be included in compilation. */
50+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
51+
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
52+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
53+
54+
/* Source Map Options */
55+
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
56+
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
57+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
58+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
59+
60+
/* Experimental Options */
61+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
62+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
6163
}
62-
}
64+
}

0 commit comments

Comments
 (0)