Skip to content

Commit

Permalink
feat: 设置单测框架
Browse files Browse the repository at this point in the history
Change-Id: I500393496d965c866c43e3c5258bf1983863fd87
  • Loading branch information
meixg committed Dec 5, 2018
1 parent cf0c836 commit b1f1d4d
Show file tree
Hide file tree
Showing 11 changed files with 153 additions and 93 deletions.
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
"description": "",
"main": "index.js",
"scripts": {
"build": "echo \"Please implement your build script and modify scripts.build section in package.json\" && exit 1",
"sync": "sync-files -w ./typescript.d.ts ./node_modules/typescript/lib/typescript.d.ts"
"build": "tsc",
"sync": "sync-files -w ./typescript.d.ts ./node_modules/typescript/lib/typescript.d.ts",
"test": "npm run build && mocha",
"mocha": "mocha"
},
"repository": {
"type": "git",
Expand Down
15 changes: 15 additions & 0 deletions sample/runner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {ts2php} from '../src/index';
import * as path from 'path';

ts2php(path.resolve(__dirname, '../sample/index.ts'), {
modules: {
'./atomWiseUtils': {
path: './path/to/utils.php',
className: 'Atom_Wise_Utils'
},
'./tplData': {
path: '',
className: ''
}
}
});
4 changes: 0 additions & 4 deletions sample/test.php

This file was deleted.

9 changes: 5 additions & 4 deletions src/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,24 +25,25 @@ import {
} from './utilities/nodeTest';
import * as os from 'os';
import {noop} from './core';
import {options as globalOptions, errors} from './globals';
import {tokenToString} from './scanner';
import {getStartsOnNewLine} from './factory';
import {Ts2phpOptions, ErrorInfo} from './types';

let currentSourceFile: SourceFile;


export function emitFile(sourceFile: SourceFile, typeChecker: ts.TypeChecker) {
export function emitFile(sourceFile: SourceFile, typeChecker: ts.TypeChecker, globalOptions: Ts2phpOptions, errors: ErrorInfo[]) {
const brackets = createBracketsMap();
currentSourceFile = sourceFile;
const writer = createTextWriter(os.EOL);
writer.writeLine();


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


writer.write('<?php\n');
ts.forEachChild(sourceFile, (node: ts.Node) => {
emitWithHint(ts.EmitHint.Unspecified, node);
writer.writeLine();
Expand Down Expand Up @@ -1744,7 +1745,7 @@ export function emitFile(sourceFile: SourceFile, typeChecker: ts.TypeChecker) {
}

if (allowedModules[importModuleName].path) {
writer.write(`require_once(${allowedModules[importModuleName].path})`);
writer.write(`require_once("${allowedModules[importModuleName].path}")`);
writeSemicolon();
}
}
Expand Down
33 changes: 13 additions & 20 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,34 @@
*/

import * as ts from 'typescript';
import * as path from 'path';
import * as emitter from './emitter';
import {Ts2phpOptions} from './types';
import {Ts2phpOptions, ErrorInfo} from './types';
import {options as globalOptions} from './globals';
import {assign} from 'lodash';

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

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

const typeChecker = program.getTypeChecker();

for (const sourceFile of program.getSourceFiles()) {
if (!sourceFile.isDeclarationFile) {
const a = emitter.emitFile(sourceFile, typeChecker);
console.log(a);
const res = emitter.emitFile(sourceFile, typeChecker, opt, errors);
return {
phpCode: res,
errors
}
}
}
}

ts2php(path.resolve(__dirname, '../sample/index.ts'), {
modules: {
'./atomWiseUtils': {
path: './path/to/utils.php',
className: 'Atom_Wise_Utils'
},
'./tplData': {
path: '',
className: ''
}
}
});


}


3 changes: 3 additions & 0 deletions test/features/import.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php
require_once("./path/to/utils.php");
$tplData->src = Atom_Wise_Utils::makeTcLink($tplData->src);
4 changes: 4 additions & 0 deletions test/features/import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import {makeTcLink} from './atomWiseUtils';
import {tplData} from './tplData';

tplData.src = makeTcLink(tplData.src);
3 changes: 3 additions & 0 deletions test/features/template.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php
$b = "123";
$c = "0" . $b . "45'6'\"789\"";
2 changes: 2 additions & 0 deletions test/features/template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const b = '123';
const c = `0${b}45'6'"789"`;
47 changes: 43 additions & 4 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,50 @@
*/

const assert = require('assert');
const fs = require('fs');
const path = require('path');
const {ts2php} = require('../dist/index.js');

describe('Array', function () {
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal([1, 2, 3].indexOf(4), -1);
const files = fs.readdirSync(path.resolve(__dirname, './features'));
const featureNames = files.reduce((res, file) => {
const m = file.match(/(.+)\.ts/);
if (m) {
res.push(m[1]);
}
return res;
}, []);

function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, {encoding: 'utf-8'}, (err, data) => {
resolve(data);
});
});
}



describe('features', () => {
for (let i = 0; i < featureNames.length; i++) {
it('template', async () => {
const featureName = featureNames[i];
const phpContent = await readFile(path.resolve(__dirname, `./features/${featureName}.php`));
const tsPath = path.resolve(__dirname, `./features/${featureName}.ts`);
const res = ts2php(tsPath, {
modules: {
'./atomWiseUtils': {
path: './path/to/utils.php',
className: 'Atom_Wise_Utils'
},
'./tplData': {
path: '',
className: ''
}
}
});
fs.writeFileSync(path.resolve(__dirname, '../output/' + featureName + '.php'), res.phpCode);
assert.equal(res.phpCode, phpContent);
});
}
});

120 changes: 61 additions & 59 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,62 +1,64 @@
{
"include": [
"src/**/*"
],
"compilerOptions": {
/* Basic Options */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"lib": [
"es2015",
"es6"
], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
// "strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
// "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */

/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Basic Options */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"lib": [
"es2015"
], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
// "strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */

/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
}

0 comments on commit b1f1d4d

Please sign in to comment.