Skip to content

Commit

Permalink
fix: support static file copy (#608)
Browse files Browse the repository at this point in the history
  • Loading branch information
echosoar committed Aug 19, 2020
1 parent 96d1cbe commit 941bc5c
Show file tree
Hide file tree
Showing 10 changed files with 124 additions and 28 deletions.
17 changes: 17 additions & 0 deletions packages/faas-cli-plugin-invoke/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
analysisResultToSpec,
compareFileChange,
copyFiles,
copyStaticFiles,
} from '@midwayjs/faas-code-analysis';
import {
CompilerHost,
Expand Down Expand Up @@ -74,6 +75,7 @@ export class FaaSInvokePlugin extends BasePlugin {
'compile', // ts 代码编译
'analysisCode', // Todo: 代码分析,向前兼容
'emit', // ts 代码输出
'copyStaticFile', // 拷贝src中的静态文件到dist目录,例如 html 等
'setFunctionList',
'entry', // 生成执行入口
'getInvoke', // 获取runtime
Expand Down Expand Up @@ -111,6 +113,7 @@ export class FaaSInvokePlugin extends BasePlugin {
'invoke:checkFileChange': this.checkFileChange.bind(this),
'invoke:compile': this.compile.bind(this),
'invoke:emit': this.emit.bind(this),
'invoke:copyStaticFile': this.copyStaticFile.bind(this),
'invoke:setFunctionList': this.setFunctionList.bind(this),
'invoke:entry': this.entry.bind(this),
'invoke:getInvoke': this.getInvoke.bind(this),
Expand Down Expand Up @@ -359,6 +362,20 @@ export class FaaSInvokePlugin extends BasePlugin {
);
}

private async copyStaticFile() {
const isTsMode = checkIsTsMode();
if (isTsMode || this.skipTsBuild) {
return;
}
return copyStaticFiles({
sourceDir: this.analyzedTsCodeRoot,
targetDir: resolve(this.buildDir, 'dist'),
log: filePath => {
this.core.debug('copyStaticFiles', filePath);
},
});
}

async setFunctionList() {
// 这里是必须的,用以其他插件动态修改 functions,比如 hooks
this.setStore('functions', this.core.service.functions);
Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div>a</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
28 changes: 28 additions & 0 deletions packages/faas-cli-plugin-invoke/test/static-files.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { invoke } from '../src/index';
import { join } from 'path';
import * as assert from 'assert';
import { pathExists, remove, existsSync } from 'fs-extra';

describe('/test/static-files.test.ts', () => {
beforeEach(async () => {
const dirs = [join(__dirname, './fixtures/baseApp')];
for (const dir of dirs) {
if (await pathExists(join(dir, '.faas_debug_tmp'))) {
await remove(join(dir, '.faas_debug_tmp'));
}
}
});
it('invoke', async () => {
const dir = join(__dirname, 'fixtures/baseApp');
const dist = join(dir, '.faas_debug_tmp/dist');
const result: any = await (invoke as any)({
functionDir: dir,
functionName: 'http',
clean: false,
});
assert(result.body === 'hello http world');
assert(existsSync(join(dist, 'a.txt')));
assert(existsSync(join(dist, 'view/a.html')));
assert(existsSync(join(dist, 'view/b.json')));
});
});
46 changes: 36 additions & 10 deletions packages/faas-cli-plugin-package/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ import {
} from 'fs-extra';
import * as micromatch from 'micromatch';
import { commonPrefix, formatLayers } from './utils';
import { analysisResultToSpec, copyFiles } from '@midwayjs/faas-code-analysis';
import {
analysisResultToSpec,
copyFiles,
copyStaticFiles,
} from '@midwayjs/faas-code-analysis';
import {
CompilerHost,
Program,
Expand Down Expand Up @@ -56,6 +60,7 @@ export class PackagePlugin extends BasePlugin {
'copyFile', // 拷贝文件: package.include 和 shared content
'compile', // 代码分析
'emit', // 编译函数 'package:after:tscompile'
'copyStaticFile', // 拷贝src中的静态文件到dist目录,例如 html 等
'checkAggregation', // 检测高密度部署
'generateSpec', // 生成对应平台的描述文件,例如 serverless.yml 等
'generateEntry', // 生成对应平台的入口文件
Expand Down Expand Up @@ -111,6 +116,7 @@ export class PackagePlugin extends BasePlugin {
'after:package:generateEntry': this.defaultGenerateEntry.bind(this),
'before:package:finalize': this.finalize.bind(this),
'package:emit': this.emit.bind(this),
'package:copyStaticFile': this.copyStaticFile.bind(this),
};

async cleanup() {
Expand Down Expand Up @@ -316,18 +322,23 @@ export class PackagePlugin extends BasePlugin {
this.core.cli.log(' - Dependencies install complete');
}

async compile() {
// 不存在 tsconfig,跳过编译
if (!existsSync(resolve(this.servicePath, 'tsconfig.json'))) {
return;
}
public getTsCodeRoot(): string {
let tsCodeRoot: string;
const tmpOutDir = resolve(this.defaultTmpFaaSOut, 'src');
if (existsSync(tmpOutDir)) {
tsCodeRoot = tmpOutDir;
} else {
tsCodeRoot = this.codeAnalyzeResult.tsCodeRoot;
}
return tsCodeRoot;
}

async compile() {
// 不存在 tsconfig,跳过编译
if (!existsSync(resolve(this.servicePath, 'tsconfig.json'))) {
return;
}
const tsCodeRoot: string = this.getTsCodeRoot();

const { config } = resolveTsConfigFile(
this.servicePath,
Expand Down Expand Up @@ -371,6 +382,21 @@ export class PackagePlugin extends BasePlugin {
this.core.cli.log(' - Build project complete');
}

private copyStaticFile() {
const isTsDir = existsSync(join(this.servicePath, 'tsconfig.json'));
if (!isTsDir) {
return;
}
const tsCodeRoot: string = this.getTsCodeRoot();
return copyStaticFiles({
sourceDir: tsCodeRoot,
targetDir: join(this.midwayBuildPath, 'dist'),
log: filePath => {
this.core.cli.log(' - copyStaticFiles', filePath);
},
});
}

// 生成默认入口
async defaultGenerateEntry() {
const functions = this.core.service.functions || {};
Expand Down Expand Up @@ -651,7 +677,7 @@ export class PackagePlugin extends BasePlugin {
this.core.cli.log(` - found deployType: ${service?.deployType}`);
// add default function
if (!service.functions || Object.keys(service.functions).length === 0) {
this.core.cli.log(` - create default functions`);
this.core.cli.log(' - create default functions');
service.functions = {
app_index: {
handler: 'index.handler',
Expand All @@ -665,19 +691,19 @@ export class PackagePlugin extends BasePlugin {
}

if (service?.deployType === 'egg') {
this.core.cli.log(` - create default layer: egg`);
this.core.cli.log(' - create default layer: egg');
service.layers['eggLayer'] = { path: 'npm:@midwayjs/egg-layer' };
}

if (service?.deployType === 'express') {
this.core.cli.log(` - create default layer: express`);
this.core.cli.log(' - create default layer: express');
service.layers['expressLayer'] = {
path: 'npm:@midwayjs/express-layer',
};
}

if (service?.deployType === 'koa') {
this.core.cli.log(` - create default layer: koa`);
this.core.cli.log(' - create default layer: koa');
service.layers['koaLayer'] = { path: 'npm:@midwayjs/koa-layer' };
}
}
Expand Down
Empty file.
Empty file.
2 changes: 2 additions & 0 deletions packages/faas-cli-plugin-package/test/package.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ describe('/test/package.test.ts', () => {
await core.invoke(['package']);
const buildPath = join(baseDir, '.serverless');
assert(existsSync(join(buildPath, 'dist/index.js')));
assert(existsSync(join(buildPath, 'dist/a.html')));
assert(existsSync(join(buildPath, 'dist/view/b.json')));
assert(existsSync(join(buildPath, 'node_modules')));
assert(existsSync(join(buildPath, 'src')));
assert(existsSync(join(buildPath, 'package.json')));
Expand Down
57 changes: 39 additions & 18 deletions packages/faas-code-analysis/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,24 +93,7 @@ export const copyFiles = async (options: ICopyOptions) => {
].concat(exclude || []),
}
);
await Promise.all(
paths.map((path: string) => {
const source = join(sourceDir, path);
const target = join(targetDir, path);
if (existsSync(target)) {
const sourceStat = statSync(source);
const targetStat = statSync(target);
// source 修改时间小于目标文件 修改时间,则不拷贝
if (sourceStat.mtimeMs <= targetStat.mtimeMs) {
return;
}
}
if (log) {
log(path);
}
return copy(source, target);
})
);
await docopy(sourceDir, targetDir, paths, log);
};

interface InnerTsConfigOptions {
Expand Down Expand Up @@ -143,3 +126,41 @@ export const innerTsConfigMaker = (options: InnerTsConfigOptions) => {
exclude: options.exclude || [],
};
};

export const copyStaticFiles = async ({ sourceDir, targetDir, log }) => {
const paths = globby.sync(['**/*.*'], {
cwd: sourceDir,
followSymbolicLinks: false,
ignore: [
'**/*.ts',
'**/node_modules/**', // 模块依赖目录
],
});
return docopy(sourceDir, targetDir, paths, log);
};

const docopy = async (
sourceDir: string,
targetDir: string,
paths: string[],
log?
) => {
await Promise.all(
paths.map((path: string) => {
const source = join(sourceDir, path);
const target = join(targetDir, path);
if (existsSync(target)) {
const sourceStat = statSync(source);
const targetStat = statSync(target);
// source 修改时间小于目标文件 修改时间,则不拷贝
if (sourceStat.mtimeMs <= targetStat.mtimeMs) {
return;
}
}
if (log) {
log(path);
}
return copy(source, target);
})
);
};

0 comments on commit 941bc5c

Please sign in to comment.