diff --git a/.gitignore b/.gitignore index b8f5bb5..78168c4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/* .DS_store -.idea \ No newline at end of file +.idea +.vscode \ No newline at end of file diff --git a/README.md b/README.md index 8c79057..2b4895e 100644 --- a/README.md +++ b/README.md @@ -2,56 +2,79 @@ ## 简介 -工具可以通过schema文件生成数据库文档,通过路由文件、接口代码、注释等生成接口文档,每次commit自动更新文档,让人专注于代码编写。目前程序初次实现,还有很多功能需要完善,许多地方需要优化。 +工具可以自动化生成数据库文档,API接口文档,并通过修改git hooks,使项目的每次commit都会自动更新文档。 ## 安装 `npm i createDOC -g` +## 配置 + - 在项目根目录使用`createDOC init`命令初始化,该命令会在当前目录创建`doc.json`文件。 + - 生成`doc.json`文件后,需要详细配置数据库schemas存储路径(目前只支持关系型数据库),以及路由控制文件,以及子路由目录。 + - API注释规则,遵循TJ大神dox规范,简化版规则如下 + ```js + /** + * API description + * + * @param {type} name/name=default_value description + * @return {String} description + * @example + * any example + * + * @other description + */ + ``` +*ps: 此工具为内部使用工具,如个人使用可下载源码,做简单修改即可* ## 使用 ```sh -Usage: createDOC [options] [command] - Commands: - - show 显示当前状态 + Usage: createDOC [options] [command] + + Commands: + + init 初始化当前目录doc.json文件 + show 显示配置文件状态 run 启动程序 - modifyhook 修改项目下的hooks文件 - + modifyhook 修改项目下的hook文件 + * + Options: - + -h, --help output usage information -V, --version output the version number -``` -**使用方法:** + Examples: -1. 在开发项目根目录使用该命令工具,在项目根目录新建`doc.json`文件,指定`schema`存储目录,和`markdown`文件输出路径,文件样例如下。 -2. 使用`createDOC -h`或者`createDOC -V(大写)`来确定`createDOC`是否安装成功。 -3. 单独运行程序使用`createDOC run`命令。 -4. 使用`createDOC modifyhook`命令修改本地钩子文件,之后无需任何操作,项目每次`commit`文档会自动更新。 -5. 使用`createDOC show`命令随时查看输入输出路径,确保输入输出路径正确。 + $ createDOC --help + $ createDOC -h + $ createDOC show +``` + +## 示例说明 +doc.json示例 ```json { - "schemas":"/Users/mac/Desktop/testssss/models/", - //schema文件目录,目前所有schema文件都需要存在此目录的根目录,暂时 TODO:不支持子目录 - "markdown": { - "path": "/Users/mac/Desktop/", - "file": "dbDocument.md" + { + "db": { + "schemas":"/Users/mac/Desktop/testssss/schemas", + "markdown": { + "path": "/Users/mac/Desktop/testssss/doc1", + "file": "db.md" + } + }, + "api": { + "controller": "/Users/mac/Desktop/testssss/router.js", + "routes": "/Users/mac/Desktop/testssss/models", + "markdown": { + "path": "/Users/mac/Desktop/testssss/doc", + "file": "api.md" + } } - //markdown文档输出目录和文件名 +} } ``` -## 注意 -1. 尽量全局安装。 -2. schema文件格式, - 1. 如果文件存在`tableName`属性,表名称为`tableName`的值,否则表名称设置为当前文件名。 - 2. 字段属性和值的关系必须严格遵守`key:{}`的格式,`:{`或`: {`是必须存在的标示,用于切割内容。 - 3. 单行注释使用`//这是注释`。 - 4. 多行注释使用`/* 这是注释*/`,切勿出现多行`//`的情况。 - 5. 示例如下(注:只需要上述4条件满足,其他诸如示例前两行的`sequelize`官方格式为非必须,同时字段属性写法也无限制)。 -3. 包版本更新后需要重新使用`createDOC modifyhook`命令设置本地钩子。 -```javascript +schema.js示例 +```js module.exports = function(sequelize, DataTypes) { return sequelize.define('test_zk_absence', { //这是id @@ -87,9 +110,26 @@ module.exports = function(sequelize, DataTypes) { }); }; ``` +api注释示例 +```js +/** + * 获取多个课程 + * @param {Number} examinationId 考试类型 + * @param {Number} subjectId 科目类型 + * @param {Number} statusId=3 状态类型 + * @param {String} startDate 更新开始时间 + * @param {String} endDate 更新结束时间 + * @param {String} keyword 关键词 + * @param {Number} page 页码 + * @return {Array} ok + * @example [1,2,3,3,4] + */ +getCourses(req, params) { + ... ... +} +``` ## TODO 1. 代码逻辑优化,适应力更强。 2. 代码速度、质量优化。 -3. 增加路由、代码、注释文档生成功能。 [github地址](https://github.com/a1511870876/buildDOC) \ No newline at end of file diff --git a/common/asyncfunc.js b/common/asyncfunc.js index b9d7a4a..066ce13 100644 --- a/common/asyncfunc.js +++ b/common/asyncfunc.js @@ -2,10 +2,12 @@ const Promise = require('bluebird'), fs = Promise.promisifyAll(require('fs')), path = require('path'), co = require('co'), - handlebars = require('handlebars'); + handlebars = require('handlebars'), + mkdirp = require('mkdirp'), + dox = require('dox'); -const craeteDb = require('./../src/createDbDOC'), - createRouter = require('./../src/createRouterDOC'), +const craeteDbDoc = require('./../src/createDbDOC'), + createApiDoc = require('./../src/createApiDOC'), func = require('./func'), config = require('./config'); @@ -51,9 +53,9 @@ function* newDoc(inputInfos) { } var content = yield fs.readFileAsync(process.cwd() + '/doc.json', 'utf-8'); console.log(''); - console.log('======= doc.json ========'); + console.log(config.colors.rainbow('======= doc.json ========')); console.log(content); - console.log('==== 请继续配置详细路径 ===='); + console.log(config.colors.rainbow('==== 请继续配置详细路径 ====')); console.log(''); break; default: @@ -61,14 +63,51 @@ function* newDoc(inputInfos) { } } } -//初始化覆盖doc.json,处理函数 +function* mkdirs(str, path) { + var pathname = config.colors.red(path); + if (Array.isArray(path)) { + if (path.length === 2) { + pathname = config.colors.red(path[0]) + ' 和 ' + config.colors.red(path[1]); + } else { + return; + } + } + process.stdout.write(config.colors.red(str) + '输出目录' + pathname + '不存在,是否创建 (y/n):'); + process.stdin.resume(); + process.stdin.setEncoding('utf-8'); + process.stdin.on('data', (chunk) => { + co(function* () { + chunk = chunk.replace(/[\s\n]/, ''); + if (chunk !== 'y' && chunk !== 'Y' && chunk !== 'n' && chunk !== 'N') { + console.log(config.colors.red('您输入的命令是: ' + chunk)); + console.warn(config.colors.red('请输入正确指令:y/n')); + process.exit(); + } + process.stdin.pause(); + if (chunk === 'y' || chunk === 'Y') { + if (Array.isArray(path)) { + yield mkdir(path[0]); + console.log(config.colors.red(path[0]) + '创建成功'); + yield mkdir(path[1]); + console.log(config.colors.red(path[1]) + '创建成功'); + process.exit(); + } + yield mkdir(path) + console.log(config.colors.red(path) + '创建成功'); + process.exit(); + } else if (chunk === 'n' || chunk === 'N') { + process.exit(); + } + }); + }); +} function* modifyHook(file) { try { const inputFile = process.cwd() + '/.git/hooks/prepare-commit-msg'; const content = yield fs.readFileAsync(file); yield fs.writeFileAsync(inputFile, content); - console.log('修改 ' + inputFile + ' 成功。'); + console.log('修改 ' + config.colors.red(inputFile) + ' 成功。'); } catch (err) { console.warn(err); } @@ -76,12 +115,20 @@ function* modifyHook(file) { function exists(file) { return new Promise((resolve, reject) => { - fs.exists(file, function (exists) { + fs.exists(file, (exists) => { if (!exists) resolve(exists); resolve(exists); }); }); } +function mkdir(path) { + return new Promise((resolve, reject) => { + mkdirp(path, (err) => { + if (err) reject(err); + else resolve() + }) + }) +} exports.initAction = function* () { try { var docPath = yield exists(process.cwd() + '/doc.json'); @@ -113,20 +160,28 @@ exports.showAction = function* () { const apiController = yield exists(doc.api.controller); const apiMarkdownPath = yield exists(doc.api.markdown.path); const apiRouters = yield exists(doc.api.routes); - console.log(` -======= √只表示路径存在,不代表路径配置正确 ======= -======= X只表示路径不存在 ======= -${docPath ? '√' : 'X'} doc.json -> ${process.cwd()}/doc.json - - db: -${dbSchemas ? '√' : 'X'} 输入 <- ${doc.db.schemas} -${dbMarkdownPath ? '√' : 'X'} 输出 -> ${doc.db.markdown.path}${doc.db.markdown.file} - - api: -${apiController ? '√' : 'X'} 控制 <- ${doc.api.controller} -${apiMarkdownPath ? '√' : 'X'} 输入 <- ${doc.api.routes} -${apiRouters ? '√' : 'X'} 输出 -> ${doc.api.markdown.path}${doc.api.markdown.file}`) + console.log(config.colors.rainbow(config.showDescription)); + console.log(config.colors.red(` +${docPath ? '√' : 'X'}`) + ` doc.json -> ${process.cwd()}/doc.json +`); + console.log(' db:'); + console.log(config.colors.red(`${dbSchemas ? '√' : 'X'}`) + ` 输入 <- ${doc.db.schemas}`); + console.log(config.colors.red(`${dbMarkdownPath ? '√' : 'X'}`) + ` 输出 -> ${doc.db.markdown.path}${doc.db.markdown.file}`); + console.log(' api:'); + console.log(config.colors.red(`${apiController ? '√' : 'X'}`) + ` 控制 <- ${doc.api.controller}`) + console.log(config.colors.red(`${apiMarkdownPath ? '√' : 'X'}`) + ` 输入 <- ${doc.api.routes}`) + console.log(config.colors.red(`${apiRouters ? '√' : 'X'}`) + ` 输出 -> ${doc.api.markdown.path}${doc.api.markdown.file}`); + console.log(''); + if (!dbMarkdownPath && apiMarkdownPath) { + yield mkdirs('db ', doc.db.markdown.path); + } + if (!apiMarkdownPath && dbMarkdownPath) { + yield mkdirs('api ', doc.api.markdown.path); + } + if (!apiMarkdownPath && !dbMarkdownPath) { + yield mkdirs('db 和 api ', [doc.db.markdown.path, doc.api.markdown.path]); + } return; } else { console.warn(config.nofile); @@ -145,11 +200,11 @@ exports.runAction = function* () { // 处理db文档 doc.db.markdown.path = func.checkPath(doc.db.markdown.path); doc.db.schemas = func.checkPath(doc.db.schemas); - yield craeteDb.createDOC(doc.db.schemas, doc.db.markdown); + //yield craeteDbDoc.createDOC(doc.db.schemas, doc.db.markdown); // 处理api文档 doc.api.markdown.path = func.checkPath(doc.api.markdown.path); doc.api.routes = func.checkPath(doc.api.routes); - yield createRouter.createDOC(doc.api.controller, doc.api.routes, doc.api.markdown); + yield createApiDoc.createDOC(doc.api.controller, doc.api.routes, doc.api.markdown); } else { console.warn(config.nofile); return; @@ -165,7 +220,7 @@ exports.modifyhookAction = function* () { const commitSamplePath = yield exists(process.cwd() + '/.git/hooks/prepare-commit-msg.sample'); const commitPath = yield exists(process.cwd() + '/.git/hooks/prepare-commit-msg'); if (!commitPath && !commitSamplePath) { - console.log(config.nohook) + console.log(config.colors.red(nfig.nohook)); } else if (commitSamplePath) { yield fs.renameAsync(process.cwd() + '/.git/hooks/prepare-commit-msg.sample', process.cwd() + '/.git/hooks/prepare-commit-msg'); @@ -224,5 +279,61 @@ exports.getRoutes = function* (file) { return data; }; +exports.buildDoxObjs = function* (routes, files) { + var doxObjs = []; + var count = 0; + for (var file of files) { + var code = yield fs.readFileAsync(file, 'utf-8'); + doxObjs = doxObjs.concat(dox.parseComments(code)); + count++; + if (count === files.length) { + return filterObj(routes, doxObjs); + } + } +} + +function filterObj(routes, doxObjs) { + var pureObjArr = {}; + doxObjs.map((obj) => { + var key = ''; + var value = {}; + if (obj.ctx) { + var params = []; + key = obj.ctx.name.replace(/[\*]/, ''); + value.type = obj.ctx.type; + value.description = obj.description.full; + if (obj.tags && Array.isArray(obj.tags)) { + for (var tag of obj.tags) { + if (tag.type === 'param') { + var param = {}; + if (/\=/.test(tag.name)) { + var name = tag.name.split('='); + tag.name = name[0]; + tag.defaultValue = name[1]; + } + param.name = tag.name || ''; + param.defaultValue = tag.defaultValue || ''; + param.description = tag.description || ''; + param.type = (tag.types && Array.isArray(tag.types)) ? tag.types.join(' ') : ''; + params.push(param) + value.param = params; + } else if (tag.type === 'example') { + value.example = tag.html || ''; + } else if (tag.type === 'return') { + var returnValue = {}; + returnValue.description = tag.description || ''; + returnValue.type = (tag.types && Array.isArray(tag.types)) ? tag.types.join(' ') : ''; + value.returnValue = returnValue; + } else { + var other = tag.type; + value[other] = tag.string || ''; + } + } + } + pureObjArr[key] = Object.assign(value, routes[key]); + } + }); + return pureObjArr; +} diff --git a/common/config.js b/common/config.js index 1fbe6c9..5f83218 100644 --- a/common/config.js +++ b/common/config.js @@ -1,6 +1,8 @@ /** * Created by mac on 16/8/26. */ +const colors = require('colors/safe'); + module.exports = { newInit: [ @@ -57,6 +59,9 @@ module.exports = { } } }`, + showDescription:` +======= √只表示路径存在,不代表路径配置正确 ======= +======= X只表示路径不存在 =======`, nofile: `找不到doc.json文件,请检查doc.json文件是否存在于项目根目录。`, startModifyhook: @@ -66,4 +71,5 @@ module.exports = { 1、未初始化git,.git目录不存在。 2、prepare-commit-msg文件被修改。 请检查项目文件!`, + colors:colors, } \ No newline at end of file diff --git a/common/func.js b/common/func.js index b5121ae..807b44a 100644 --- a/common/func.js +++ b/common/func.js @@ -1,7 +1,7 @@ /** * Created by mac on 16/8/10.{ */ - +const config = require('./config'); //数组快速排序 exports.quickSort = sort; function sort(array, start, end) { @@ -38,6 +38,65 @@ exports.spaceToFalse = function (str) { return str; } }; +//用于MarkdownBuild,根据对象属性进行赋值 +exports.propertyAssign = function (api) { + var properties = Object.keys(api) + var description = ''; + var path = ''; + var method = ''; + var example = ''; + var other = ''; + var paramTable = ''; + var returnTable = ''; + for (var property of properties) { + switch (property) { + case 'description': + description = api[property]; + break; + case 'path': + path = api[property]; + break; + case 'method': + method = api[property]; + break; + case 'example': + example = api[property]; + break; + case 'other': + other = api[property]; + break; + case 'param': + if (Array.isArray(api[property])) { + for (var param of api[property]) { + paramTable = paramTable + + '|' + param.name + + '|' + param.defaultValue + + '|' + param.type + + '|' + param.description; + paramTable += '|\n' + } + }; + break; + case 'returnValue': + returnTable = returnTable + + '|' + api[property].type + + '|' + api[property].description + '|\n'; + break; + default: + break; + } + } + return { + description: description, + path: path, + method: method, + example: example, + other: other, + paramTable: paramTable, + returnTable: returnTable + } +} + //初始化命令,人机交互控制 exports.initRepl = function (init, func) { var i = 1; @@ -46,17 +105,17 @@ exports.initRepl = function (init, func) { process.stdout.write(init[0].description); process.stdin.resume(); process.stdin.setEncoding('utf-8'); - process.stdin.on('data', function (chunk) { + process.stdin.on('data', (chunk) => { chunk = chunk.replace(/[\s\n]/, ''); - if(chunk !== 'y' && chunk !== 'Y' && chunk !== 'n' && chunk !== 'N'){ - console.log('您输入的命令是: ' + chunk) - console.warn('请输入正确指令:y/n'); + if (chunk !== 'y' && chunk !== 'Y' && chunk !== 'n' && chunk !== 'N') { + console.log(config.colors.red('您输入的命令是: ' + chunk)); + console.warn(config.colors.red('请输入正确指令:y/n')); process.exit(); } - if( - (init[i-1].title === 'modifyConfirm' || init[i-1].title === 'initConfirm') && - (chunk === 'n' || chunk === 'N') - ){ + if ( + (init[i - 1].title === 'modifyConfirm' || init[i - 1].title === 'initConfirm') && + (chunk === 'n' || chunk === 'N') + ) { process.exit(); } var inputJson = { @@ -108,116 +167,6 @@ exports.attributesExists = function (lines) { } return lines; }; -//查看第一个注释出现的地方,用于api文档 -exports.clearUnsignContent = function (lines) { - for (var index in lines) { - if (/^\s?.*\@.*/.test(lines[index])) { - lines.splice(0, index); - break; - } else if (index === lines.length - 1) { - lines.splice(0, lines.length); - break; - } - } - return lines; -}; -//提取信息,用于api文档 -exports.getSignContent = function (line) { - var sign = ['api', 'name', 'group', 'param', 'paramExample', 'success', 'successExample', - 'error', 'errorExample', 'description']; - if (/@api/.test(line)) { - var api = line.split('@api')[1]; - if (/\{.*\}/.test(api)) { - var method = /\{(.*?)\}/.exec(api)[1]; - api.replace(/\{.*\}/, ''); - } - var apiArray = api.split(' '); - console.log(apiArray); - return { - method: method, - path: apiArray[2], - title: apiArray[3] - } - } - if (/@name/.test(line)) { - const name = line.split('@name')[1].split(' '); - return { - name: name[1] - } - } - if (/@group/.test(line)) { - const group = line.split('@group')[1].split(' '); - return { - group: group[1] - } - } - if (/@param/.test(line)) { - const param = line.split('@param')[1]; - if (/\{.*\}/.test(param)) { - var type = /\{(.*?)\}/.exec(param)[1]; - param.replace(/\{.*\}/, ''); - } - if (/\[.*\]/.test(param)) { - var field = /\[(.*?)\]/.exec(param)[1]; - var defaultValue = ''; - if (/\=/.test(field)) { - field = field.split('=')[0]; - defaultValue = field.split('=')[1]; - } - param.replace(/\[.*\]/, ''); - } - if (/required/.test(param)) { - var reqired = true; - param.replace(/required/, ''); - } - var description = param; - return { - paramType: type, - field: field, - defaultValue: defaultValue, - required: required, - paramDescription: description, - } - } - if (/@paramExample/.test(line)) { - return 'paramExample' - }//TODO example处理 - if (/@success/.test(line)) { - if (/@success/.test(line)) { - var success = line.split('@success')[1]; - if (/\{.*\}/.test(success)) { - var type = /\{(.*?)\}/.exec(success)[1]; - success.replace(/\{.*\}/, ''); - } - var successArray = success.split(' '); - console.log(successArray); - return { - successType: type, - status: successArray[1], - text: successArray[3] - } - } - } - if (/@successExample/.test(line)) { - return 'successExample' - } - if (/@error/.test(line)) { - const error = line.split('@name')[1].split(' '); - return { - errorDescription: error[1] - } - } - if (/@errorExample/.test(line)) { - return 'errorExample' - } - if (/@description/.test(line)) { - var description = line.split('@name')[1].split(' '); - return { - description: description[1] - } - } - return; -}; //检查目录路径合法性(末尾时候含有'/'),并修改。 exports.checkPath = function (path) { @@ -233,30 +182,7 @@ exports.removeSymbol = function (code) { return result; } } -//去除杂乱字符,用于api文档 -exports.removeSymbolApi = function (code) { - if (typeof (code) == 'string') { - const result = code.replace(/[\,\']/g, ''); - return result; - } -} -//处理各种example,用于api文档 -exports.buildExample = function (count, lines, example, signObj) { - var start = 0; - var end = 0; - if (/\@/.test(lines[count])) { - start = count; - lines[start] = lines[start].replace('@' + example, ''); - count++; - while (!/\@/.test(lines[count]) && /\*/.test(lines[count])) { - count++; - } - end = count; - signObj[example] = '```' + lines.slice(start, end + 1) + '```'; - } - return signObj; -} //type转换 exports.typeTransform = function (type) { switch (type) { diff --git a/doc.json b/doc.json index 0b50ad6..8b4eba6 100644 --- a/doc.json +++ b/doc.json @@ -2,7 +2,7 @@ "db": { "schemas":"/Users/mac/Desktop/testssss/schemas", "markdown": { - "path": "/Users/mac/Desktop/testssss/doc", + "path": "/Users/mac/Desktop/testssss/doc1", "file": "db.md" } }, diff --git a/example/doc.json b/example/doc.json deleted file mode 100644 index 4beb71f..0000000 --- a/example/doc.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "db": { - "schemas":"", - "markdown": { - "path": "", - "file": "" - } - }, - "api": { - "controller": "", - "routes": "", - "markdown": { - "path": "", - "file": "" - } - } -} \ No newline at end of file diff --git a/package.json b/package.json index 529da9d..a49afd8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "createDOC", - "version": "1.0.13", + "version": "1.0.14", "description": "", "main": "index.js", "scripts": { @@ -27,9 +27,12 @@ "dependencies": { "bluebird": "^3.4.1", "co": "^4.6.0", + "colors": "^1.1.2", "commander": "^2.9.0", + "dox": "^0.9.0", "handlebars": "^4.0.5", - "linebyline": "^1.3.0" + "linebyline": "^1.3.0", + "mkdirp": "^0.5.1" }, "devDependencies": {} } \ No newline at end of file diff --git a/src/MarkdownBuild.js b/src/MarkdownBuild.js index 4c3b732..98562df 100644 --- a/src/MarkdownBuild.js +++ b/src/MarkdownBuild.js @@ -41,7 +41,7 @@ exports.dbbuild = function (tables, markdown) { } //写入文件 - fs.writeFile(markdown.path + markdown.file , text, (err) => { + fs.writeFile(markdown.path + markdown.file, text, (err) => { if (err) throw err; console.log('It\'s saved!'); //文件被保存 return true; @@ -49,6 +49,55 @@ exports.dbbuild = function (tables, markdown) { }; -exports.routerbuild = function (tables, markdown) { +exports.apibuild = function (apis, markdown) { + console.log(apis); + var text = '# API文档\n\n'; + text += ` +` + const paramTableHeader = + '|参数名字|默认值|参数类型|说明|\n' + + '|:---:|:---:|:---:|:---:|\n'; + const returnTableHeader = + '|类型|说明|\n' + + '|:---:|:---:|\n'; + for (var api in apis) { + var properties = func.propertyAssign(apis[api]); + var description = properties.description + '\n'; + var path = '```' + properties.path + '```' + '\n'; + var method = properties.method + '\n'; + var example = properties.example + '\n'; + var other = properties.other + '\n'; + var paramTable = paramTableHeader + + ((properties.paramTable === '') ? '| | | | |' : properties.paramTable) + + '\n'; + var returnTable = returnTableHeader + + ((properties.returnTable === '') ? '| | |' : properties.returnTable) + + '\n'; + text += `## ${api} +#### 简要描述: + - ${description} +#### 请求URL: + - ${path} +#### 请求方式: + - ${method} +#### 参数: +${paramTable} +#### 返回参数说明: +${returnTable} +#### 返回实例: +${example} +#### 其他说明: + - ${other}`; + } + //写入文件 + fs.writeFile(markdown.path + markdown.file, text, (err) => { + if (err) throw err; + console.log('It\'s saved!'); //文件被保存 + return true; + }); }; \ No newline at end of file diff --git a/src/createApiDOC.js b/src/createApiDOC.js new file mode 100644 index 0000000..759671c --- /dev/null +++ b/src/createApiDOC.js @@ -0,0 +1,27 @@ +/** + * API description + * + * @param {type} name/name=default_value description + * @return {String} description + * @example + * any example + * + * @other description + */ + +const markdownBuild = require('./MarkdownBuild'), + asyncfunc = require('./../common/asyncfunc'); + +exports.createDOC = function* (controller, path, markdown) { + try { + const routes = yield asyncfunc.getRoutes(controller); + const files = yield asyncfunc.getAllFiles(path); + + const doxObjs = yield asyncfunc.buildDoxObjs(routes, files); + const mergerObjs = Object.assign(routes, doxObjs); + + markdownBuild.apibuild(mergerObjs, markdown); + } catch (err) { + console.log(err); + } +}; diff --git a/src/createDbDOC.js b/src/createDbDOC.js index 61163f5..ff2484c 100755 --- a/src/createDbDOC.js +++ b/src/createDbDOC.js @@ -3,7 +3,8 @@ const path = require('path'), const markdownBuild = require('./MarkdownBuild'), asyncfunc = require('./../common/asyncfunc'), - func = require('./../common/func'); + func = require('./../common/func'), + config = require('./../common/config'); var fileNumber = 0; //需处理的文件总数 var fileCount = 0; //处理文件计数 @@ -25,16 +26,16 @@ function build(file, markdown) { const lines = []; const read = readline(file); read - .on('line', function (line, lineCount, byteCount) { + .on('line', (line, lineCount, byteCount) => { lines.push(func.removeSymbol(line)); }) - .on('error', function (e) { + .on('error', (e) => { throw e; }) - .on('end', function () { + .on('end', () => { console.log(fileCount + '、 正在处理' + path.basename(file, '.js') + '...'); createObject(lines, file, markdown); - console.log('处理完毕') + console.log(config.colors.blue('处理完毕')); }); } diff --git a/src/createRouterDOC.js b/src/createRouterDOC.js deleted file mode 100644 index 98e9534..0000000 --- a/src/createRouterDOC.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @api {method} path title - * @name name - * @group group - * @param {type} [field=defaultValue] required description - * @paramExample {id:1, name: 'n1'} - * @success 200 {type} ok - * @successExample {type} title - * example - * @error description - * @errorExample - * {code:'xx', msg:'xx'} - * @description description - */ - -const path = require('path'), - readline = require('linebyline'); - -const markdownBuild = require('./MarkdownBuild'), - asyncfunc = require('./../common/asyncfunc'), - func = require('./../common/func'); - -// var fileNumber = 0; //需处理的文件总数 -// var fileCount = 0; //处理文件计数 -// var data = {}; //所有表格整体数据 - -exports.createDOC = function* (controller, path, markdown) { - try { - const files = yield asyncfunc.getAllFiles(path); - const routes = yield asyncfunc.getRoutes(controller); - for (var file of files) { - build(file, markdown); - } - } catch (err) { - console.log(err); - } -}; - -function build(file, markdown) { - const lines = []; - const read = readline(file); - read - .on('line', function (line, lineCount, byteCount) { - lines.push(func.removeSymbolApi(line)); - }) - .on('error', function (e) { - throw e; - }) - .on('end', function () { - //console.log(fileCount + '、 正在处理' + path.basename(file, '.js') + '...'); - createObject(lines, file, markdown); - //console.log('处理完毕') - }); -} - -function createObject(lines, file, markdown) { - func.clearUnsignContent(lines); - const singleRouteData = {}; - var routeName = ''; - var count = 0; - while (count < lines.length) { - //TODO key获取和处理 - var value = {}; - var sign = func.getSignContent(lines[count]); - if (typeof (sign) === 'string') { - var signObj = {}; - switch (sign) { - case 'paramExample': - Object.assgin(value, func.buildExample(count, lines, 'paramExample', signObj)); - break; - case 'successExample': - Object.assgin(func.buildExample(count, lines, 'successExample', signObj)); - break; - case 'errorExample': - Object.assgin(func.buildExample(count, lines, 'errorExample', signObj)); - break; - default: - count++; - break; - } - continue; - } else { - Object.assgin(value, sign); - count++; - continue; - } - } - fileCount++; - if (fileCount === fileNumber) { - return markdownBuild.dbbuild(data, markdown); - } -} diff --git a/src/index.js b/src/index.js index 72a3ae6..dbf1329 100644 --- a/src/index.js +++ b/src/index.js @@ -29,11 +29,11 @@ program program .command('*') - .action(function(env){ + .action((env) => { console.error('不存在命令 "%s"', env); }); -program.on('--help', function(){ +program.on('--help', () => { console.log(' Examples:'); console.log(''); console.log(' $ createDOC --help'); diff --git a/src/index1.js b/src/index1.js deleted file mode 100644 index ee62e09..0000000 --- a/src/index1.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Created by mac on 16/8/25. - */ -const program = require('commander'); - -program - .version('0.0.1') - .description('An application for pizzas ordering') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese ', 'Add the specified type of cheese [marble]') - .option('-C, --no-cheese', 'You do not want any cheese') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program.peppers) console.log(' - peppers'); -if (program.pineapple) console.log(' - pineapple'); -if (program.bbq) console.log(' - bbq'); - -var cheese = true === program.cheese - ? 'marble' - : program.cheese || 'no'; - -console.log(' - %s cheese', cheese); -console.log(program.args); \ No newline at end of file diff --git a/test/test.js b/test/test.js index 9996390..c1ede7d 100644 --- a/test/test.js +++ b/test/test.js @@ -1,29 +1,13 @@ /** * Created by mac on 16/8/22. */ -var co = require('co'); -var asyncFunc = require('./../common/asyncfunc'); -var handlebars = require('handlebars'); -var config = require('./../common/config'); -var fs = require('fs'); -var path = require('path'); +const co = require('co'); +const asyncFunc = require('./../common/asyncfunc'); +const handlebars = require('handlebars'); +const config = require('./../common/config'); +const fs = require('fs'); +const path = require('path'); //co(asyncFunc.initAction) //co(asyncFunc.runAction); //co(asyncFunc.showAction); - -var data = { - schemas: process.cwd(), - dbPath: process.cwd(), - dbFile: 'db.md', - controller: process.cwd(), - routes: process.cwd(), - apiPath: process.cwd(), - apiFile: 'api.md', -} -var template = handlebars.compile(config.docjson); -var result = template(data); -console.log(result); -fs.writeFile(path.resolve(__dirname, '..') + '/doc.json', result, function(err){ - -}) \ No newline at end of file