├── .npmrc
├── .npmignore
├── test
├── translate-file
│ ├── translate.md
│ ├── source.md
│ ├── source.zh.md
│ ├── translate-values.md
│ └── values.test.js
├── feature
│ ├── testWrite3.zh.md
│ ├── testWrite1.md
│ ├── testWrite1.zh.md
│ ├── testWrite3.en.md
│ ├── testWrite3.md
│ ├── testWrite.md
│ └── testWrite.zh.md
├── readmd.test.js
├── mergeConfig.js
├── Fix
│ ├── testWithSymbal.zh.md
│ ├── testWithSymbal.md
│ ├── fixFileTooBig.test.js
│ └── lengthEqual.test.js
├── disk-cache
│ └── disk.js
├── writeDataToFile.test.js
├── cli.test.js
├── logger
│ ├── debugMgs.test.js
│ └── logger.test.js
├── translateExports.test.js
├── setObjectKey.test.js
├── optionsTodo.test.js
├── setObjectKey.Object.js
└── cutMdhead.test.js
├── src
├── util
│ ├── readmd.js
│ ├── cutMdhead.js
│ ├── diskCache.js
│ ├── writeDataToFile.js
│ ├── debugMsg.js
│ └── util.js
├── Fix
│ ├── fixZhtoEn.js
│ ├── fixFileTooBig.js
│ └── lengthEqual.js
├── config
│ ├── work-options.js
│ ├── defaultConfig.json
│ ├── loggerConfig.js
│ ├── optionsTodo.js
│ └── mergeConfig.js
├── typeSetAndGet.js
├── translateMds.js
└── setObjectKey.js
├── imgs
└── demo.gif
├── .editorconfig
├── md
├── 2.zh.md
├── about
│ ├── 3.zh.md
│ ├── 3.md
│ └── aboutme
│ │ ├── me.zh.md
│ │ └── me.md
├── start
│ ├── index.zh.md
│ └── index.md
├── 2.md
├── 1.zh.md
└── 1.md
├── .travis.yml
├── .gitignore
├── .vscode
└── launch.json
├── package.json
├── NodePathdata.json
├── README.md
├── README.en.md
├── cli.js
├── License
└── CHANGELOG.md
/.npmrc:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | test
2 | md
3 | imgs
4 |
--------------------------------------------------------------------------------
/test/translate-file/translate.md:
--------------------------------------------------------------------------------
1 | 你好 世界
2 |
--------------------------------------------------------------------------------
/test/feature/testWrite3.zh.md:
--------------------------------------------------------------------------------
1 | hello!
2 | world
--------------------------------------------------------------------------------
/test/translate-file/source.md:
--------------------------------------------------------------------------------
1 | hello world
2 |
--------------------------------------------------------------------------------
/test/translate-file/source.zh.md:
--------------------------------------------------------------------------------
1 | 你好 世界
2 |
3 |
--------------------------------------------------------------------------------
/test/translate-file/translate-values.md:
--------------------------------------------------------------------------------
1 | hello world
--------------------------------------------------------------------------------
/src/util/readmd.js:
--------------------------------------------------------------------------------
1 | module.exports = require('files-list')
2 |
--------------------------------------------------------------------------------
/src/Fix/fixZhtoEn.js:
--------------------------------------------------------------------------------
1 | module.exports = require('zh-to-en-symbol')
2 |
--------------------------------------------------------------------------------
/imgs/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chinanf-boy/translate-mds/HEAD/imgs/demo.gif
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = space
5 | end_of_line = lf
6 | charset = utf-8
7 | trim_trailing_whitespace = true
8 | insert_final_newline = true
9 |
10 | [*.yml]
11 | indent_style = space
12 | indent_size = 2
13 |
--------------------------------------------------------------------------------
/src/config/work-options.js:
--------------------------------------------------------------------------------
1 | const Dconfig = require('./defaultConfig.json')
2 |
3 | let Options = Dconfig
4 |
5 | function setOptions(options){
6 | Options = options
7 | }
8 |
9 | function getOptions(){
10 | return Options
11 | }
12 |
13 | module.exports = {
14 | setOptions,
15 | getOptions
16 | }
17 |
--------------------------------------------------------------------------------
/src/util/cutMdhead.js:
--------------------------------------------------------------------------------
1 | module.exports = cutMdhead = (data) =>{
2 | let headlike = ['---','+++']
3 | for(let i in headlike)
4 | if(data.startsWith( headlike[i] )){
5 | let index = data.slice(3).indexOf( headlike[i] ) + 6
6 | return [data.slice(index), data.slice(0,index)+'\n\n']
7 |
8 | }
9 | return [data, ""]
10 | }
11 |
--------------------------------------------------------------------------------
/test/readmd.test.js:
--------------------------------------------------------------------------------
1 | const { test } = require('ava')
2 |
3 | const Listmd = require('../src/util/readmd.js')
4 |
5 | test("read zh md folder", async t =>{
6 | const len = await Listmd(__dirname+"/../md/",{ deep: 'all' })
7 | t.is(len.length, 10)
8 | })
9 |
10 | test("read md file", async t =>{
11 | const len = await Listmd(__dirname+"/feature/testWrite.md")
12 | t.is(len.length, 1)
13 | })
14 |
--------------------------------------------------------------------------------
/test/mergeConfig.js:
--------------------------------------------------------------------------------
1 | import test from 'ava'
2 | import mergeConfig from '../src/config/mergeConfig'
3 |
4 | test('cli config',t =>{
5 | let cli = {
6 | flags:{
7 | F:true,
8 | G:true,
9 | values:true,
10 | translate: 'hello',
11 | timewait: '1000'
12 | }
13 | }
14 |
15 | let config = mergeConfig(cli)
16 |
17 | t.is(Object.keys(config).length,10)
18 | })
19 |
--------------------------------------------------------------------------------
/src/config/defaultConfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "logger": {
3 | "level": "info"
4 | },
5 | "api": "google",
6 | "from": false,
7 | "to": "zh",
8 | "num": 1,
9 | "rewrite": false,
10 | "com": false,
11 | "force": false,
12 | "timewait": "80",
13 | "getvalues": false,
14 | "translate": false,
15 | "apis": ["baidu", "google", "youdao"],
16 | "ignore": false,
17 | "matchs": [],
18 | "types": [],
19 | "skips": [],
20 | "textGlob": false,
21 | "disk": true,
22 | "zh":true,
23 | "cache": false,
24 | "cacheName": "translateMds"
25 | }
26 |
--------------------------------------------------------------------------------
/test/Fix/testWithSymbal.zh.md:
--------------------------------------------------------------------------------
1 | # 真棒冷阵雨
2 |
3 | 当人们对事物感到兴奋时,这很好,但有时他们会有一点点兴奋_太_兴奋. 这是一个真棒(严谨和尊重),并策划(我阅读每一个建议,并作出判断呼吁)冷水淋浴名单上overhyped topics.this做**不**意味着热情是不好的或错误的: 我们只是提醒人们保持接地. 随时提交你的最爱!
4 |
5 | #### [验证技术](http://www.cypherpunks.to/~peter/04_verif_techniques.pdf)(PDF)
6 |
7 | - **炒作: **"正式验证是写软件的好方法,我们应该证明我们所有的代码都是正确的. "淋浴:
8 |
9 | - **大量的文献回顾显示,正式的方法很难学,应用的代价极其昂贵,并且经常错过重要的错误. **注意事项:
10 |
11 | - **写于2000年,并不包括现代工具/技术,如Tla +或从属打字. **笔记:
12 |
13 | - **部分**彼得古特曼[的论文,"密码安全体系结构的设计和验证". ](https://www.cs.auckland.ac.nz/~pgut001/)的论文,"密码安全体系结构的设计和验证".
--------------------------------------------------------------------------------
/md/2.zh.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | 雨果是**世界上最快的静态网站引擎. **它是用去(aka Golang)开发的[BEP](https://github.com/bep),[spf13](https://github.com/spf13)和[朋友](https://github.com/gohugoio/hugo/graphs/contributors). 下面您将从我们的文档中找到一些最常见和最有用的页面.
20 |
21 | 你好
22 |
--------------------------------------------------------------------------------
/md/about/3.zh.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | 雨果是**世界上最快的静态网站引擎. **它是用去(aka Golang)开发的[BEP](https://github.com/bep),[spf13](https://github.com/spf13)和[朋友](https://github.com/gohugoio/hugo/graphs/contributors). 下面您将从我们的文档中找到一些最常见和最有用的页面.
20 |
21 | 你好
22 |
--------------------------------------------------------------------------------
/md/start/index.zh.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | 雨果是**世界上最快的静态网站引擎. **它是用去(aka Golang)开发的[BEP](https://github.com/bep),[spf13](https://github.com/spf13)和[朋友](https://github.com/gohugoio/hugo/graphs/contributors). 下面您将从我们的文档中找到一些最常见和最有用的页面.
20 |
21 | 你好
22 |
--------------------------------------------------------------------------------
/test/translate-file/values.test.js:
--------------------------------------------------------------------------------
1 | import test from 'ava';
2 | process.chdir(__dirname + '/../../');
3 |
4 | const path = require('path');
5 | const execa = require('execa');
6 |
7 | test('use --values [path]', async t => {
8 | let err = await t.throws(
9 | execa.shell(
10 | 'node cli.js ./test/translate-file/source.md --values ./test/translate-file/translate-values.md -R'
11 | )
12 | );
13 | t.regex(err.message, /values save/);
14 | });
15 |
16 | test('use --translate [path]', async t => {
17 | let err = await execa.shell(
18 | 'node cli.js ./test/translate-file/source.md --translate ./test/translate-file/translate.md -R'
19 | );
20 | t.regex(err.stderr, /be The translation/);
21 | });
22 |
--------------------------------------------------------------------------------
/test/disk-cache/disk.js:
--------------------------------------------------------------------------------
1 | const {test} = require('ava');
2 | const dbFunc = require('../../src/util/diskCache');
3 |
4 | const DBname = 'test-disk';
5 | let dbFace = dbFunc(DBname);
6 | const OBJ = {author: 'name'};
7 |
8 | test.serial('get obj', async t => {
9 | let res = await dbFace.getDisk(DBname, {nothing:1});
10 | t.deepEqual(res, undefined);
11 | });
12 | test.serial('set obj', async t => {
13 | let res = await dbFace.setDisk(DBname, OBJ, OBJ);
14 | console.log(res);
15 | t.true(Object.keys(res).some(x => res[x] > 0));
16 | });
17 |
18 | test.serial('get obj', async t => {
19 | let res = await dbFace.getDisk(DBname);
20 | t.deepEqual(res.author, OBJ.author);
21 | });
22 | test.serial('db path', t => {
23 | t.true(dbFace.path.includes('disks'));
24 | });
25 |
--------------------------------------------------------------------------------
/md/2.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors). Below you will find some of the most common and helpful pages from our documentation.
20 |
21 | 你好
--------------------------------------------------------------------------------
/md/about/3.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors). Below you will find some of the most common and helpful pages from our documentation.
20 |
21 | 你好
--------------------------------------------------------------------------------
/test/feature/testWrite1.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors). Below you will find some of the most common and helpful pages from our documentation.
--------------------------------------------------------------------------------
/test/feature/testWrite1.zh.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors). Below you will find some of the most common and helpful pages from our documentation.
--------------------------------------------------------------------------------
/test/feature/testWrite3.en.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors). Below you will find some of the most common and helpful pages from our documentation.
--------------------------------------------------------------------------------
/test/feature/testWrite3.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors). Below you will find some of the most common and helpful pages from our documentation.
--------------------------------------------------------------------------------
/md/start/index.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors). Below you will find some of the most common and helpful pages from our documentation.
20 |
21 | 你好
--------------------------------------------------------------------------------
/test/feature/testWrite.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors). Below you will find some of the most common and helpful pages from our documentation.
20 | ➜ /Users/lizhenyong/Desk
--------------------------------------------------------------------------------
/test/feature/testWrite.zh.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hugo Documentation
3 | linktitle: Hugo
4 | description: Hugo is the world's fastest static website engine. It's written in Go (aka Golang) and developed by bep, spf13 and friends.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | menu:
9 | main:
10 | parent: "section name"
11 | weight: 01
12 | weight: 01 #rem
13 | draft: false
14 | slug:
15 | aliases: []
16 | toc: false
17 | layout: documentation-home
18 | ---
19 | Hugo is the **world's fastest static website engine.** It's written in Go (aka Golang) and developed by [bep](https://github.com/bep), [spf13](https://github.com/spf13) and [friends](https://github.com/gohugoio/hugo/graphs/contributors). Below you will find some of the most common and helpful pages from our documentation.
20 | ➜ /Users/lizhenyong/Desk
--------------------------------------------------------------------------------
/src/util/diskCache.js:
--------------------------------------------------------------------------------
1 | var dbS = require("diskdb");
2 | const path = require("path");
3 | const fs = require("fs");
4 |
5 | const localPath = () => path.join(__dirname, "../../disks");
6 |
7 | function loadDisk(...filename) {
8 | // fixed: missing path
9 | let lP = localPath();
10 | if (!fs.existsSync(lP)) {
11 | fs.mkdirSync(lP);
12 | }
13 | let db = dbS.connect(lP, [...filename]);
14 |
15 | let options = {
16 | multi: false, // update multiple - default false
17 | upsert: true, // if object is not found, add it (update-insert) - default false
18 | };
19 |
20 | function setDisk(key, q, obj) {
21 | return db[key].update(q, obj, options);
22 | }
23 |
24 | function getDisk(key, obj) {
25 | return db[key].findOne(obj);
26 | }
27 |
28 | return { setDisk, getDisk, db, path: db._db.path };
29 | }
30 |
31 | module.exports = loadDisk;
32 |
--------------------------------------------------------------------------------
/test/writeDataToFile.test.js:
--------------------------------------------------------------------------------
1 | const { test } = require('ava')
2 | const fs = require('fs')
3 |
4 | const { writeDataToFile } = require('../src/util/writeDataToFile.js')
5 | const { insert_flg } = require('../src/util/util.js')
6 |
7 | test("get new filename ",t =>{
8 | let result = insert_flg('aaaa.md', '.zh', 3)
9 | t.is(result, 'aaaa.zh.md')
10 | })
11 |
12 | test.failing("get bad filename ",t =>{
13 | insert_flg('', '.zh', 3)
14 | t.fail('这里是传入不正确的文件名')
15 | })
16 |
17 | test.failing("filename no .md", async t =>{
18 | await writeDataToFile('data', __dirname + '')
19 |
20 | })
21 |
22 | test.serial("writeData with Array ", async t =>{
23 | let result = await writeDataToFile(["hello!", "world"], __dirname + '/feature/testWrite3.md')
24 | t.true(result.includes('file saved'))
25 | })
26 |
27 | test.failing("filename Array ", async t =>{
28 | await writeDataToFile(['data','data'], __dirname + '')
29 | })
30 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - 8
4 | - 9
5 | - 10
6 | script:
7 | - npm test
8 | after_success:
9 | - bash <(curl -s https://codecov.io/bash)
10 | deploy:
11 | provider: npm
12 | email: yobrave@outlook.com
13 | api_key:
14 | secure: ZBbhBBFZ0mOvIhuXZwmK87h7JnwPAkEP88qaBx7jELHdos0r7O7G0F6Tb+Zfw7UWM2aJPXrMthH28rsbpr3zGX0Y3qD5VmfyeGWSZd+UimEmEYpQpJ1rilpynkMLpbBeultapN1bN4ZWGwDYsyoXNC4Y/lfleq+ZKE0O80oBqu8M1EXN1QJrCnV7lIz7R+FRk/EP3jo0LZ0ZBAWuhSbJ4JWzliD41NCJVanoT1qj//3+NXEgKCOPc2lvG31AhYDCj0C0/34MY1woS8laVEY5qA3fGUljktob2edcv1+VThZ8rP7yYKiKVmdd6mJpkDEBxAm8zR1FKg19Il1wo/20F2e/41wcaHch8WNXJWHXSaduXzK2VE5obsRTkwWL5WRddmdSsRuL3yu8W79wrMEh48oJXWHEP05dDAPxr7tmjEJke68fIOjdeAERU3V7hgSohjEgHLDRG1O7OskFX+FuUC5tDh+fYjVF0LgduR8OyLspXZgBwy2+Z0GyGaIhgVMGPsxZJkenXC0G8YMqzbqdakfBtEQrW8zXMSfa+FcsdbxnU6DW/BWNUFVCRfiabE453YuWh2/KzVSGKXmtIqqNkZpicDeZwsA691Ci6QwOIEx1ISo+aN8gCYO/U4PoSLDYfKxZvoBLNtvi/RNQxfAN9j0kIL3MRmKU3Fok0MsRNDI=
15 | on:
16 | branch: master
17 | tags: true
18 | repo: chinanf-boy/translate-mds
19 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *DS
2 | node_modules/
3 | .nyc_ou*
4 | *.log
5 | npm-debug.log*
6 |
7 | # vscode debug
8 | try.js
9 |
10 | # Runtime data
11 | pids
12 | *.pid
13 | *.seed
14 |
15 | # Directory for instrumented libs generated by jscoverage/JSCover
16 | lib-cov
17 |
18 | # Coverage directory used by tools like istanbul
19 | coverage
20 |
21 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
22 | .grunt
23 |
24 | # node-waf configuration
25 | .lock-wscript
26 |
27 | # Compiled binary addons (http://nodejs.org/api/addons.html)
28 | build/*
29 |
30 | # Dependency directory
31 | # https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
32 | node_modules
33 |
34 | # Static file
35 | public
36 |
37 | # Bower
38 | bower_components
39 |
40 | # Optional npm cache directory
41 | .npm
42 |
43 | # Optional REPL history
44 | .node_repl_history
45 |
46 | .idea/*
47 | /coverage
48 | .DS_Store
49 | src/config/config.local*
50 | src/config/sequelize.json
51 | lib/*
52 | .nyc_output
53 | ./config.json
54 | disks
55 |
--------------------------------------------------------------------------------
/src/util/writeDataToFile.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 | const { m,insert_flg,relaPath,g } = require('./util')
3 | const {
4 | logger
5 | } = require('../config/loggerConfig.js');
6 | const {
7 | getOptions
8 | } = require('../config/work-options.js');
9 | let configs = getOptions()
10 | const tranT = configs.to
11 |
12 |
13 | const writeDataToFile = async (data, file_dir) => {
14 | return new Promise((ok, Err) => {
15 | try{
16 |
17 | let zhfile
18 | if (!file_dir.endsWith('.md')) {
19 | Err("no md file,just go away")
20 | }
21 | require.resolve(file_dir)
22 |
23 | zhfile = insert_flg(file_dir, `.${tranT}`, 3)
24 |
25 | // data is Array
26 | if (data instanceof Array) {
27 | data = data.join("\n")
28 | }
29 |
30 |
31 | fs.writeFile(zhfile + '', data, (err) => {
32 | if (err)
33 | Err(err);
34 | ok(`4. ${m(tranT)} file saved! -->> ${g(relaPath(zhfile))}`)
35 | });
36 |
37 | }catch(err){
38 | Err(err)
39 | }
40 | })
41 | }
42 |
43 |
44 | module.exports = {
45 | writeDataToFile,
46 | insert_flg
47 | }
48 |
--------------------------------------------------------------------------------
/test/Fix/testWithSymbal.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # Awesome Cold Showers
4 |
5 | It's great when people get excited about things, but sometimes they get a little _too_ excited. This an awesome (rigorous and respectful) and curated (I read every suggestion and make judgement calls) list of cold showers on overhyped topics.This does **not** mean the enthusiasm is bad or wrong: we're just reminding people to stay grounded. Feel free to submit your favorites!
6 |
7 | #### [Verification Techniques](http://www.cypherpunks.to/~peter/04_verif_techniques.pdf) (PDF)
8 |
9 | * **Hype:** "Formal Verification is a great way to write software. We should prove all of our code correct."
10 |
11 | * **Shower:** Extensive literature review showing that formal methods are hard to learn, extremely expensive to apply, and often miss critical bugs.
12 |
13 | * **Caveats:** Written in 2000 and doesn't cover modern tools/techniques, such as TLA+ or dependent typing.
14 |
15 | * **Notes:** Part of [Peter Gutmann](https://www.cs.auckland.ac.nz/~pgut001/)'s thesis, "The Design and Verification of a Cryptographic Security Architecture".
16 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // 使用 IntelliSense 了解相关属性。
3 | // 悬停以查看现有属性的描述。
4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "type": "node",
9 | "request": "launch",
10 | "name": "Launch try export",
11 | "program": "${workspaceFolder}/try.js"
12 | },
13 | {
14 | "type": "node",
15 | "request": "launch",
16 | "name": "Launch src/write",
17 | "program": "${workspaceFolder}/src/writeDataToFile.js"
18 | },
19 | {
20 | "type": "node",
21 | "request": "launch",
22 | "name": "Launch src/readmd",
23 | "program": "${workspaceFolder}/src/readmd.js"
24 | },
25 | {
26 | "type": "node",
27 | "request": "launch",
28 | "name": "Launch index",
29 | "program": "${workspaceFolder}/cli.js",
30 | "args": [
31 | "test/feature/testWrite.md"
32 | ]
33 | }
34 | ]
35 | }
36 |
--------------------------------------------------------------------------------
/test/cli.test.js:
--------------------------------------------------------------------------------
1 | const { test } = require('ava')
2 | const path = require('path')
3 | const execa = require('execa')
4 | process.chdir(path.resolve(__dirname+'/..'));
5 |
6 | let a = `./test/feature/testWrite3.en.md`
7 | let b = `./test/translate-file/translate-values.md`
8 |
9 |
10 | test('show help screen', async t => {
11 | t.regex(await execa.shell('node cli.js').then(x=>x.stderr).catch(x =>x.stderr), /translate/)
12 | });
13 |
14 | test('--glob', async t => {
15 | t.regex(await execa.shell(`node cli.js ${b} --glob *.js -D`).then(x=>x.stderr), /glob/)
16 | });
17 |
18 | test('--ignore', async t => {
19 | t.regex(await execa.shell(`node cli.js ${b} --ignore ${b} -D`).then(x=>x.stderr), /ignore/)
20 | });
21 |
22 | test('已翻译', async t => {
23 | t.regex(await execa.shell(`node cli.js ./md -D`).then(x=>x.stderr), /已翻译/)
24 | });
25 |
26 | test('国家后缀', async t => {
27 | t.regex(await execa.shell(`node cli.js ${a} -D`).then(x=>x.stderr), /国家/)
28 | });
29 |
30 | test('show version', async t => {
31 | t.is(await execa.shell('node cli.js --version').then(x=>x.stdout), require('../package').version);
32 | });
33 |
--------------------------------------------------------------------------------
/test/logger/debugMgs.test.js:
--------------------------------------------------------------------------------
1 | import test from 'ava';
2 | const debugMsg = require('../../src/util/debugMsg');
3 | const debug = require('debug')('mds:tran');
4 | const {
5 | logger,
6 | loggerStart,
7 | loggerText,
8 | oneOra,
9 | _SETDEBUG
10 | } = require('../../src/config/loggerConfig.js');
11 |
12 | const source1 = ['Hello', 'World'];
13 | const result1 = ['你好', '世界', '. '];
14 | const matstr = '2. set-';
15 |
16 | test('debug msg step 1', t => {
17 | loggerStart('debug 1 running ...');
18 |
19 | debugMsg(1, source1, result1);
20 | t.pass('debug 1');
21 | });
22 |
23 | test('debug msg step 2', t => {
24 | loggerStart('debug 2 running ...');
25 |
26 | debugMsg(2, source1, result1);
27 | t.pass('debug 2');
28 | });
29 |
30 | test('debug msg step 1:debug', t => {
31 | process.env.DEBUG = '*';
32 |
33 | _SETDEBUG(true);
34 |
35 | loggerStart('debug 1 running ...');
36 |
37 | debugMsg(1, source1, result1);
38 | t.pass('debug 1');
39 | });
40 |
41 | test('debug msg step 2:debug', t => {
42 | process.env.DEBUG = '*';
43 |
44 | _SETDEBUG(true);
45 | loggerStart('debug 2 running ...');
46 |
47 | debugMsg(2, source1, result1);
48 | t.pass('debug 2');
49 | });
50 |
--------------------------------------------------------------------------------
/test/logger/logger.test.js:
--------------------------------------------------------------------------------
1 | import test from 'ava';
2 | const { logger,
3 | loggerStart,
4 | loggerText,
5 | loggerStop,
6 | getLogger,
7 | _SETDEBUG } = require('../../src/config/loggerConfig')
8 |
9 | const H = "hello world"
10 |
11 | test.todo("logger")
12 |
13 | test.serial('start', t => {
14 | loggerStart(H)
15 | let L = getLogger()
16 | t.true(L !== undefined)
17 | });
18 |
19 | test.serial('text', t => {
20 | loggerText(H)
21 | t.is(getLogger().text, H)
22 | });
23 |
24 | test.serial(' stop', t => {
25 | loggerStop()
26 | t.true(!getLogger())
27 | });
28 |
29 | test.serial(' stop with succeed', t => {
30 | loggerStart(H)
31 | loggerStop('ok',{ora:'succeed'})
32 | t.true(!getLogger())
33 | });
34 |
35 | test.serial('stop with no start ', t => {
36 |
37 | t.true(!loggerStop("ok done"))
38 | });
39 |
40 | test.todo("logger DEBUG")
41 |
42 | test('start DEBUG', t => {
43 | _SETDEBUG(true)
44 | loggerStart(H)
45 | let L = getLogger()
46 | t.true(L !== undefined)
47 | });
48 |
49 | test('text DEBUG', t => {
50 | loggerText(H)
51 | t.is(!!getLogger().debug, true)
52 | });
53 |
54 | test(' stop DEBUG', t => {
55 | loggerStop(H)
56 | t.true(!getLogger())
57 | });
58 |
59 | test('stop with no start DEBUG', t => {
60 |
61 | t.true(!loggerStop("ok done"))
62 | });
63 |
--------------------------------------------------------------------------------
/test/Fix/fixFileTooBig.test.js:
--------------------------------------------------------------------------------
1 | const { test } = require('ava')
2 | const fs = require('fs')
3 |
4 | const { fixFileTooBig, indexMergeArr, thirdArray } = require('../../src/Fix/fixFileTooBig.js')
5 |
6 | test("fixFileTooBig 1 <= length <= 30 & 1<= string<=300", t =>{
7 | let a = []
8 | let n = 30;
9 | let n1 = n
10 |
11 | while(n--){
12 | a.push(`${n}+hello`)
13 | }
14 | t.is(a.length, n1)
15 | let b = fixFileTooBig(a)
16 | t.is(b.length, 1)
17 | })
18 |
19 | test("fixFileTooBig length > 30 & 1<= string<=300 ", t =>{
20 | let a = []
21 | let n = 31
22 | let n1 = n
23 | while(n--){
24 | a.push(`${n}+hello`)
25 | }
26 | t.is(a.length, n1)
27 | let b = fixFileTooBig(a)
28 | t.is(b.length, 2)
29 | })
30 |
31 | test("indexMergeArr Arr ", t =>{
32 | let a = [1,2,3,4]
33 | let b = indexMergeArr(a, 1, 1)
34 | t.is(b.length, 1)
35 | t.is(b[0], 2)
36 | })
37 |
38 | test.failing("indexMergeArr B fail", t =>{
39 | let a = [1,2,3,4]
40 | t.throws(indexMergeArr(a, -1, 7))
41 | })
42 |
43 | test("indexMergeArr Arr >[0] + [1]", t =>{
44 | let a = [1,2,2.5,3,4,]
45 | let b = []
46 | b[0] = indexMergeArr(a, 0, 3)
47 | b[1] = indexMergeArr(a, 3, (5-3))
48 | t.deepEqual(b, [[1,2,2.5],[3,4]])
49 | })
50 |
--------------------------------------------------------------------------------
/src/util/debugMsg.js:
--------------------------------------------------------------------------------
1 | const debug = require('debug')('mds:tran');
2 | const {tc, g, y, yow, m, b, r} = require('./util.js');
3 | const {
4 | logger,
5 | loggerStart,
6 | loggerText,
7 | oneOra
8 | } = require('../config/loggerConfig.js');
9 |
10 | module.exports = debugMsg = (step, valueArr, resArr) => {
11 | let BigOne = valueArr.length > resArr.length ? valueArr : resArr;
12 | let debugInfo = `-- source: ${valueArr.length}/${
13 | resArr.length
14 | }: translte ---`;
15 | if (resArr.length == 0) return;
16 |
17 | function tranSourceShow(debug) {
18 | for (let i in BigOne) {
19 | // Debug
20 | if (!valueArr[i] || !resArr[i]) {
21 | debug(
22 | `2. set- ${i} : ${g(valueArr[i])} ${tc.bgMagenta(
23 | 'to->'
24 | )} ${i} : ${yow(resArr[i])}`
25 | );
26 | } else {
27 | debug(
28 | `2. set- ${i} : ${g(valueArr[i])} to-> ${i} : ${yow(resArr[i])}`
29 | );
30 | }
31 | }
32 | }
33 |
34 | if (step == 1) {
35 | if (debug.enabled) {
36 | // debug all
37 | debug(debugInfo);
38 |
39 | tranSourceShow(debug);
40 | } else {
41 | loggerText(debugInfo);
42 | }
43 | } else {
44 | loggerText(debugInfo);
45 |
46 | tranSourceShow(logger.debug);
47 | }
48 | };
49 |
--------------------------------------------------------------------------------
/src/util/util.js:
--------------------------------------------------------------------------------
1 | const tc = require('turbocolor');
2 | const relative = require('path').relative
3 | let g = tc.green
4 | let y = tc.cyan
5 | let yow = tc.yellow
6 | let m = tc.magenta
7 | let b = tc.blue
8 | let r = tc.red
9 |
10 |
11 | function relaPath(p){
12 | return relative(process.cwd(),p)
13 | }
14 |
15 | const newObject = (obj) => JSON.parse(JSON.stringify(obj))
16 |
17 | function time(ms) {
18 | return new Promise((resolve, reject) => {
19 | setTimeout(resolve, ms);
20 | });
21 | }
22 |
23 | function insert_flg(str, flg, Uindex) {
24 | let newstr = "";
25 | if (!str || !flg) {
26 | throw TypeError('filename<' + str + '> can not add' + flg)
27 | }
28 | let len = str.length
29 | let tmp = str.substring(0, len - Uindex);
30 | newstr = tmp + flg + str.substring(len - Uindex, len)
31 | return newstr;
32 | }
33 |
34 | function O2A(options) {
35 | let {
36 | aFile,
37 | api,
38 | tF,
39 | tT
40 | } = options
41 | return [aFile, api, tF, tT]
42 | }
43 |
44 | const fs = require('mz/fs')
45 | const EOL = `\n`
46 |
47 | async function asyncWrite(p, arry){
48 | return await fs.writeFile(p,arry.join(EOL+EOL))
49 | }
50 | async function asyncRead(p){
51 | return await fs.readFileSync(p,"utf8").split(EOL+EOL).filter(ok => ok)
52 | }
53 | module.exports = {
54 | time,
55 | g,
56 | y,
57 | yow,
58 | m,
59 | b,
60 | r,
61 | relaPath,
62 | newObject,
63 | insert_flg,
64 | O2A,
65 | asyncWrite,
66 | asyncRead,
67 | tc
68 | }
69 |
--------------------------------------------------------------------------------
/src/Fix/fixFileTooBig.js:
--------------------------------------------------------------------------------
1 | const MAXLENGTH = 30;
2 |
3 | /**
4 | * @description fix file-value Too big
5 | * @param {Array} bigArr
6 | */
7 | function fixFileTooBig(bigArr){
8 | let chunkArr = []
9 | let bigL = bigArr.length
10 | let bigl_2 = Math.ceil(bigL/2)
11 | // length > 30
12 | if(bigL > MAXLENGTH){
13 |
14 | let n = Math.ceil(bigL / MAXLENGTH) // how many chunk
15 | let chunkLength = Math.ceil(bigL/n) // single chunk:Array almost length
16 |
17 | for(let numChunk = 0; numChunk < n ; numChunk ++){ // for chunk length
18 |
19 | // while index+length > bigArr.length ,
20 | // we most shrot length in indexMergeArr
21 | chunkArr.push( indexMergeArr(bigArr, (numChunk*chunkLength), chunkLength) )
22 | }
23 | return chunkArr
24 | }else { // string <= 100
25 | chunkArr.push(bigArr)
26 | return chunkArr
27 | }
28 | }
29 |
30 | /**
31 | * @description
32 | * @param {Array} Arr
33 | * @param {number} B begin
34 | * @param {number} L length
35 | * @returns
36 | */
37 | function indexMergeArr(Arr, B, L){
38 | if(B < 0){
39 | throw new Error("indexMergeArr Arr.length < index -- Error")
40 | }
41 | if(Arr.length < (B+L)){
42 | //shrot length in indexMergeArr
43 | L = Arr.length - B
44 | }
45 | let backArr = []
46 | for(let index in Arr){
47 | if((B <= +index) && (+index < (B+L))){
48 | backArr.push(Arr[index])
49 | }
50 | }
51 | return backArr
52 | }
53 |
54 | module.exports = { fixFileTooBig, indexMergeArr }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "translate-mds",
3 | "version": "4.0.5",
4 | "description": "translate [folder/single] md file language to you want",
5 | "main": "./src/translateMds.js",
6 | "engines": {
7 | "node": ">=8.0.0"
8 | },
9 | "scripts": {
10 | "demo": "node cli.js md/",
11 | "ava": "ava",
12 | "test": "nyc --reporter=lcov --reporter=text --reporter=html npm run ava",
13 | "pub": "npm run test && npm version patch && git push origin master && git push --tags",
14 | "changelog": "github_changelog_generator"
15 | },
16 | "husky": {
17 | "hooks": {}
18 | },
19 | "files": [
20 | "src",
21 | "cli.js"
22 | ],
23 | "ava": {
24 | "files": [
25 | "test/**/*",
26 | "!test/*.Object.js",
27 | "!config/**",
28 | "!cli.js"
29 | ]
30 | },
31 | "bin": {
32 | "translateMds": "./cli.js"
33 | },
34 | "author": "yobrave",
35 | "license": "ISC",
36 | "dependencies": {
37 | "async": "^2.6.0",
38 | "debug": "^3.1.0",
39 | "diskdb": "^0.1.17",
40 | "files-list": "^1.4.1",
41 | "meow": "^3.7.0",
42 | "minimatch": "^3.0.4",
43 | "mz": "^2.7.0",
44 | "ora-min": "^1.0.0",
45 | "remark": "^9.0.0",
46 | "translation.js-fix": "^0.7.8",
47 | "turbocolor": "^2.6.1",
48 | "update-notifier": "^2.5.0",
49 | "what-time": "^0.0.2",
50 | "winston": "^2.4.0",
51 | "zh-to-en-symbol": "^3.0.0"
52 | },
53 | "keywords": [
54 | "md",
55 | "translate",
56 | "languages"
57 | ],
58 | "devDependencies": {
59 | "ava": "^0.24.0",
60 | "husky": "1.0.0-rc.13",
61 | "nyc": "^11.3.0"
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/test/translateExports.test.js:
--------------------------------------------------------------------------------
1 | const { test } = require('ava')
2 | const path = require('path')
3 | const translate = require('../src/translateMds.js')
4 |
5 | let trueResult = `---\ntitle: Hugo Documentation\nlinktitle: Hugo\ndescription: Hugo is the world\'s fastest static website engine. It\'s written in Go (aka Golang) and developed by bep, spf13 and friends.\ndate: 2017-02-01\npublishdate: 2017-02-01\nlastmod: 2017-02-01\nmenu:\n main:\n parent: \"section name\"\n weight: 01\nweight: 01\t#rem\ndraft: false\nslug:\naliases: []\ntoc: false\nlayout: documentation-home\n---\n雨果是**世界上最快的静态网站引擎。**它是用去(aka Golang)开发的[BEP](https://github.com/bep),[spf13](https://github.com/spf13)和[朋友](https://github.com/gohugoio/hugo/graphs/contributors)。下面您将从我们的文档中找到一些最常见和最有用的页面。\n`
6 |
7 | test.failing('translate no absolute file fail', async t =>{
8 | let results = await translate(['./feature/testWrite1.md'])
9 | t.fail()
10 | })
11 |
12 | test.failing('translate nothing', async t =>{
13 | let results = await translate("")
14 | t.fail()
15 | })
16 | test.failing('translate input Object fail', async t =>{
17 | let results = await translate({})
18 | t.fail()
19 | })
20 | test.serial('translate absolute file ', async t =>{
21 | let results = await translate({aFile:__dirname+'/feature/testWrite1.md', api:'google'})
22 | results = results.map(x =>x.text)
23 | t.is(results.length, 0)
24 | })
25 |
26 | test.serial('translate absolute file from zh to en', async t =>{
27 | let results = await translate({'aFile':__dirname+'/feature/testWrite1.md',tF:'en',tT:'zh'})
28 | results = results.map(x =>x.text)
29 | t.is(results.length, 0)
30 | })
31 |
32 | test.serial('translate absolute folder auto', async t =>{
33 | let results = await translate([path.resolve(__dirname,'../md/'),'google','en','zh'], 'info')
34 | results = results.map(x =>x.text)
35 | t.is(results.length,0)
36 | })
37 |
38 | // test.serial('translate absolute big folder auto', async t =>{
39 | // let results = await translate([`*******/You_Don\'t\ _Know_JS/You-Dont-Know-JS`,'baidu'], 'verbose')
40 | // t.is(results.length,5)
41 | // })
42 |
--------------------------------------------------------------------------------
/test/setObjectKey.test.js:
--------------------------------------------------------------------------------
1 | const { test } = require('ava')
2 | const fs = require('fs')
3 | const [tree, truetree ] = require('./setObjectKey.Object.js')
4 | const {setObjectKey, translateValue} = require('../src/setObjectKey.js')
5 | var newObject = (oldObject) =>JSON.parse(JSON.stringify(oldObject));
6 |
7 | let opts = (api) =>newObject({api,name:'test.md'})
8 |
9 | test(' test baidu',async t =>{
10 | let newTree = await setObjectKey(newObject(tree), opts('baidu'))
11 | delete newTree.Error
12 | t.true(!!newTree)
13 | })
14 |
15 | test(' test youdao',async t =>{
16 | let newTree = await setObjectKey(newObject(tree), opts('youdao'))
17 | delete newTree.Error
18 | t.true(!!newTree)
19 | })
20 |
21 | test(' test google',async t =>{
22 | let newTree = await setObjectKey(newObject(tree), opts('google'))
23 | delete newTree.Error
24 | t.true(!!newTree)
25 | })
26 |
27 | test(' test translate type:asdf + html',async t =>{
28 | let source = {type:'asdf',"value":"hello","child":{
29 | "type": "html",
30 | "value": ""
31 | }}
32 | let value = {type:'asdf',"value":"你好","child":{
33 | "type": "html",
34 | "value": ""
35 | }}
36 | let v = await setObjectKey(newObject(source), opts('baidu'))
37 | t.deepEqual(v,value)
38 | })
39 |
40 | test(' test translate no key == value ',async t =>{
41 | let noValue = await setObjectKey(newObject({type:'asdf'}), opts('baidu'))
42 | t.is(noValue,'no value')
43 | })
44 |
45 | test(' test translate code or html false',async t =>{
46 | let noValue = await setObjectKey(newObject({
47 | "type": "html",
48 | "value": ""
49 | }), opts('baidu'))
50 | t.is(noValue,'no value')
51 | })
52 |
53 | test.serial(' test translateValue ',async t =>{
54 | let value = ['hello world']
55 | let result = await translateValue(value, 'google').catch(e =>{
56 | return [e]
57 | })
58 | t.is(result.length,1)
59 | })
60 |
--------------------------------------------------------------------------------
/test/Fix/lengthEqual.test.js:
--------------------------------------------------------------------------------
1 | const { test } = require('ava')
2 | const fs = require('fs')
3 |
4 | const { translateLengthEquals, mergeAndCut } = require('../../src/Fix/lengthEqual.js')
5 |
6 | test("mergeAndCut String asdf", t =>{
7 | let a =["a","b","c","d","e","f","g"]
8 | mergeAndCut(a, 2, 2, 5)
9 | t.deepEqual(a, ["a", "b", "cde", "f", "g"])
10 | })
11 |
12 | test("mergeAndCut String single", t =>{
13 | let a =["asdf. ", "asdf. "]
14 | mergeAndCut(a, 0, 2, 1)
15 | t.deepEqual(a, ["asdf. asdf. "])
16 | })
17 |
18 | test("translateLengthEquals String long", t =>{
19 | let a =[`excited. This an awesome (rigorous and respectful) and curated (I read every suggestion and make judgement calls) list of cold showers on overhyped topics. This does `]
20 | let b = ["1","2","4"]
21 | translateLengthEquals(a, b)
22 | t.is(b.length, 1)
23 | })
24 |
25 | test("translateLengthEquals String with \' or \" ", t =>{
26 | let a =[`"excited. This an awesome (rigorous and respectful) and curated (I read every suggestion and make judgement calls) list of cold showers on overhyped topics. This does "`]
27 | let b = ["1","2","3","4"]
28 | translateLengthEquals(a, b)
29 | t.is(b.length, 4)
30 | })
31 |
32 | test("translateLengthEquals String with \' or \" has space", t =>{
33 | let a =[` "excited. This an awesome (rigorous and respectful) and curated (I read every suggestion and make judgement calls) list of cold showers on overhyped topics. This does "`]
34 | let b = ["1","2","3","4"]
35 | translateLengthEquals(a, b)
36 | t.is(b.length, 4)
37 | })
38 |
39 | test("translateLengthEquals with '. '", t =>{
40 | let b =["asdf. asdf. . "]
41 | let c =["asdf. ", "asdf. ", ". "]
42 | translateLengthEquals(b, c)
43 | t.deepEqual(c, ["asdf. asdf. . "])
44 | })
45 |
46 | test("translateLengthEquals with '. ' and '!' ", t =>{
47 | let b =["a,etc. sdf!. asdf. !"]
48 | let c =["asdf!", ". ", "asdf. ", "!"]
49 | translateLengthEquals(b, c)
50 | t.deepEqual(c, ["asdf!. asdf. !"])
51 | })
52 |
53 | test(`translateLengthEquals with '. ' and '。' `, t =>{
54 | let b =[`asdf。. asdf. 。`,`asdf`]
55 | let c =[`asdf。`, `. `, `asdf. `, `。`, `asdf`]
56 | translateLengthEquals(b, c)
57 | t.deepEqual(c, b)
58 | })
59 |
60 |
--------------------------------------------------------------------------------
/src/typeSetAndGet.js:
--------------------------------------------------------------------------------
1 | const minimatch = require('minimatch');
2 |
3 | const {getOptions} = require('./config/work-options.js')
4 | const configs = getOptions()
5 | const TYPES = configs['types']
6 | const textGlob = configs['textGlob'];
7 |
8 | let types = ['html', 'code'].concat(TYPES)
9 | let sum = 0;
10 |
11 | function getTypeValue(obj,tranArray){
12 | sum = 0;
13 | /**
14 | * @description Find ``obj['type'] === 'value'`` ,and``tranArray.push(obj[key])``
15 | * @param {Object} obj
16 | * @param {String[]} tranArray
17 | * @returns {number} - find value number
18 | */
19 | function deep(obj, tranArray) {
20 | Object.keys(obj).forEach(function (key) {
21 |
22 | // no translate code content
23 | if (obj['type'] && (types.some(t => obj['type'] == t))) {
24 | return sum
25 | }
26 | (obj[key] && typeof obj[key] === 'object') && deep(obj[key], tranArray)
27 |
28 |
29 | if (key === 'value' && obj[key].trim()) {
30 | // --text-glob {cli options}
31 | if(!textGlob || textGlob.every(g =>minimatch(obj[key],g))){
32 | tranArray.push(obj[key])
33 | sum++
34 | }
35 | }
36 | });
37 | return sum
38 | };
39 |
40 | return deep(obj,tranArray)
41 | }
42 | function setTypeValue(obj, tranArrayZh){
43 | /**
44 | * @description Find ``obj['type'] === 'value'``, and use ``tranArrayZh.shift`` set ``obj['value']``
45 | * @param {any} obj - AST
46 | * @param {String[]} tranArrayZh
47 | * @returns
48 | */
49 | function setdeep(obj, tranArrayZh) {
50 | Object.keys(obj).forEach(function (key) {
51 |
52 | if (obj['type'] && (types.some(t => obj['type'] == t))) {
53 | return sum
54 | }
55 |
56 | (obj[key] && typeof obj[key] === 'object') && setdeep(obj[key], tranArrayZh)
57 |
58 | if (key === 'value' && obj[key].trim()) {
59 | if (tranArrayZh.length) {
60 | if(!textGlob || textGlob.every(g =>minimatch(obj[key],g))){
61 | obj[key] = tranArrayZh.shift()
62 | sum--
63 | }
64 | }
65 | }
66 | });
67 | return sum
68 | };
69 |
70 | return setdeep(obj, tranArrayZh)
71 | }
72 | module.exports = {
73 | getTypeValue,
74 | setTypeValue
75 | }
76 |
--------------------------------------------------------------------------------
/test/optionsTodo.test.js:
--------------------------------------------------------------------------------
1 | const { test } = require('ava')
2 | const fs = require('fs')
3 | let p = '../src/config/optionsTodo.js'
4 | const defaultArgs = {
5 | "logger": {
6 | "level": "verbose"
7 | },
8 | "api":"baidu",
9 | "from":"en",
10 | "to":"zh",
11 | "num": 5,
12 | "rewrite": false
13 | }
14 | const {setDefault} = require(p)
15 |
16 | const rNobj =(obj) =>JSON.parse(JSON.stringify(obj))
17 |
18 | test("setDefault",t=>{
19 | function sum(a,b){return a+b}
20 | const s = setDefault(1, sum, 1)
21 | t.is(s,2)
22 | })
23 |
24 | const {debugTodo} = require(p)
25 |
26 | test("debugTodo",t=>{
27 | const s = debugTodo(true,rNobj(defaultArgs))
28 | t.is(s, 'debug')
29 | const s2 = debugTodo('info',rNobj(defaultArgs))
30 | t.is(s2,'info')
31 | })
32 |
33 | const {matchAndSkip} = require(p)
34 |
35 | test("matchAndSkip",t=>{
36 | const s = matchAndSkip({n:"info,nihao",type:'M'},rNobj(defaultArgs))
37 | t.is(s.length, 2)
38 | const s2 = matchAndSkip({n:"info",type:'M'},rNobj(defaultArgs))
39 | t.is(s2.length, 1)
40 | const s3 = matchAndSkip("",rNobj(defaultArgs))
41 | t.is(s3.length, 0)
42 | })
43 |
44 | const {typesTodo} = require(p)
45 |
46 | test("typesTodo",t=>{
47 | const s = typesTodo({n:"info,nihao",type:'T'},rNobj(defaultArgs))
48 | t.is(s.length, 2)
49 | })
50 |
51 | const {fromTodo} = require(p)
52 |
53 | test("fromTodo",t=>{
54 | const s = fromTodo('zh',rNobj(defaultArgs))
55 | t.is(s,'zh')
56 | const s2 = fromTodo('',rNobj(defaultArgs))
57 | t.is(s2,'en')
58 | })
59 | const {toTodo} = require(p)
60 |
61 | test("toTodo",t=>{
62 | const s = toTodo('ja',rNobj(defaultArgs))
63 | t.is(s,'ja')
64 | const s2 = toTodo('',rNobj(defaultArgs))
65 | t.is(s2,'zh')
66 | })
67 | const {apiTodo} = require(p)
68 |
69 | test("apiTodo",t=>{
70 | const s = apiTodo('',rNobj(defaultArgs))
71 | t.is(s,'baidu')
72 | const s2 = apiTodo('google',rNobj(defaultArgs))
73 | t.is(s2,'google')
74 | })
75 | const {rewriteTodo} = require(p)
76 |
77 | test("rewriteTodo",t=>{
78 | const one = rewriteTodo(true,rNobj(defaultArgs))
79 | t.is(one,true)
80 |
81 | const two = rewriteTodo('google',rNobj(defaultArgs))
82 | t.is(two,true)
83 |
84 | const three = rewriteTodo('',rNobj(defaultArgs))
85 | t.is(three,false)
86 | })
87 | const {numTodo} = require(p)
88 |
89 | test("numTodo",t=>{
90 | const s = numTodo(10,rNobj(defaultArgs))
91 | t.is(s,10)
92 |
93 | const s2 = numTodo('google',rNobj(defaultArgs))
94 | t.is(s2,5)
95 | })
96 |
--------------------------------------------------------------------------------
/src/Fix/lengthEqual.js:
--------------------------------------------------------------------------------
1 | const {getOptions} = require('../config/work-options.js');
2 | let configs = getOptions();
3 | const {matchs, skips} = configs;
4 | const {tc} = require('../util/util.js');
5 |
6 | let Equal;
7 | function translateLengthEquals(source, tranTxt) {
8 | let skipArr = ['... ', 'etc. ', 'i.e. ', 'e.g. '].concat(skips);
9 | let matchArr = ['. ', '! ', '; ', '!', '? ', '。'].concat(matchs);
10 | let trim = ["'", '"'];
11 | Equal = source.length;
12 | let newSource = [].concat(source);
13 | for (let i in source) {
14 | // typeof i == string
15 | // if(Equal == tranTxt.length) return
16 |
17 | source[i] = source[i].trim();
18 | let idxStr = source[i];
19 | if (trim.some(x => idxStr.startsWith(x) && idxStr.endsWith(x))) {
20 | // ' ** ' /" ** "
21 | } else {
22 | let howMany = 0;
23 | // let s = source[i]
24 |
25 | let thisMatch = matchArr.filter(m => idxStr.includes(m)); // just filter match string
26 |
27 | thisMatch.forEach(function(val) {
28 | while (idxStr.includes(val)) {
29 | let skipIndexs = [];
30 |
31 | skipArr.forEach(function(skip) {
32 | if (idxStr.includes(skip)) {
33 | skipIndexs.push(skip);
34 | }
35 | });
36 |
37 | if (skipIndexs.length) {
38 |
39 | skipIndexs.forEach(skip => {
40 | idxStr = idxStr.replace(skip, tc.bgMagenta(`👌 `)); // over val
41 | });
42 |
43 | continue;
44 | } else {
45 | if (idxStr.indexOf(val) + val.length == idxStr.length) {
46 | break;
47 | }
48 |
49 | idxStr = idxStr.replace(val, tc.bgRed(`🥄 `)); // over val
50 | howMany++; // how many ". "/ etc
51 | }
52 | }
53 | });
54 | !!howMany && mergeAndCut(tranTxt, +i, howMany); // pay attion two + , string/number
55 | newSource[i] = idxStr;
56 | }
57 | }
58 |
59 | return newSource;
60 | }
61 |
62 | function mergeAndCut(Arr, index, howMany, TestLen) {
63 | let E = Equal || TestLen;
64 | let num = 0;
65 | // Merge howMany items to Index item
66 | for (let i = index; i < index + howMany; i++) {
67 | if (1 || Arr.length - num !== E) {
68 | Arr[i + 1] && (Arr[index] = Arr[index] + Arr[i + 1]);
69 | num++;
70 | }
71 | // else{
72 | // break;
73 | // }
74 | }
75 | // splice Items : From the Index + 1 to ` i `
76 | Arr.splice(index + 1, num);
77 | }
78 |
79 | module.exports = {translateLengthEquals, mergeAndCut};
80 |
--------------------------------------------------------------------------------
/md/1.zh.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Accented Characters in URLs
3 | linktitle: Accented Characters in URLs
4 | description: If you're having trouble with special characters in your taxonomies or titles adding odd characters to your URLs.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | keywords: [urls,multilingual,special characters]
9 | categories: [troubleshooting]
10 | menu:
11 | docs:
12 | parent: "troubleshooting"
13 | weight:
14 | draft: false
15 | slug:
16 | aliases: [/troubleshooting/categories-with-accented-characters/]
17 | toc: true
18 | ---
19 | ## 问题: 带有重音字符的类别
20 |
21 | > 我的一个类别被命名为"乐卡尔",但链接最终是这样生成的:
22 | >
23 | > categories/le-carr%C3%A9
24 | >
25 | > 不工作. 我能忽略这个问题吗?
26 |
27 | ## 解决方案
28 |
29 | 你是一个MacOS的用户吗?如果是这样的话,你可能是一个受害者,HFS +文件系统的坚持来存储"é"(U + 00e9)字符正常形式分解(NFD)模式,即为"E"+"́"(U + 0065 + 0301).
30 |
31 | `勒% %`实际上是正确的,`% %`在U+ UTF-8版本00e9预期由Web服务器. 问题是OS X转了. [u + 00e9]进入之内[0065+0301+],从而`勒% %`不再工作. 相反,只有`勒卡雷连铸% 81`结束`81 %`将匹配[0065+0301+]最后.
32 |
33 | 这是OS X独有的. 世界上其他地方没有这样做,当然也不是你最可能运行Linux的Web服务器. 这也不是雨果特有的问题. 其他人在他们的HTML文件中有重音字符时就被这个咬了.
34 |
35 | 注意,这个问题并不具体于拉丁语脚本. 日本的Mac用户经常遇到相同的问题,例如`だ`分解成`た`和`与# x3099;`. (读[日本perl用户文章][]).
36 |
37 | rsync 3. x的救援!从[服务器故障的答案][]:
38 |
39 | > 你可以使用rsync的`ℴℴiconv`选择UTF-8 NFC与NFD之间转换,至少如果你的Mac. 有一个特别的`utf-8-mac`字符集是UTF-8 NFD. 因此,为了将文件从Mac复制到Web服务器,您需要运行类似于:
40 | >
41 | > `rsync -ℴℴiconv = utf-8-mac,UTF-8 localdir / mywebserver: remotedir /`
42 | >
43 | > 这会将所有本地文件名由UTF-8 NFD为NFC在远程服务器. 文件的内容不会受到影响. ℴ[服务器故障][]
44 |
45 | 请确保你有rsync 3的最新版本. 装X. rsync,OS X的船只已经过时. 即使是包装版本10.10(优诗美地国家公园)是版本2.6.9协议版本29. 这个`ℴℴiconv`国旗是新的rsync 3. X.
46 |
47 | ### 论坛参考
48 |
49 | -
50 | - [http://wiki.apache.org/subversion/nonnormalizingunicodecompositionawareness](http://wiki.apache.org/subversion/NonNormalizingUnicodeCompositionAwareness)
51 | - [http: / /恩. 维基百科. org /维基/ unicode_equivalence #例子](https://en.wikipedia.org/wiki/Unicode_equivalence#Example)
52 | -
53 | -
54 |
55 | [an answer posted on server fault]: http://serverfault.com/questions/397420/converting-utf-8-nfd-filenames-to-utf-8-nfc-in-either-rsync-or-afpd "Converting UTF-8 NFD filenames to UTF-8 NFC in either rsync or afpd, Server Fault Discussion"
56 |
57 | [japanese perl users article]: http://perl-users.jp/articles/advent-calendar/2010/english/24 "Encode::UTF8Mac makes you happy while handling file names on MacOSX"
58 |
59 | [server fault]: http://serverfault.com/questions/397420/converting-utf-8-nfd-filenames-to-utf-8-nfc-in-either-rsync-or-afpd "Converting UTF-8 NFD filenames to UTF-8 NFC in either rsync or afpd, Server Fault Discussion"
60 |
--------------------------------------------------------------------------------
/md/about/aboutme/me.zh.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Accented Characters in URLs
3 | linktitle: Accented Characters in URLs
4 | description: If you're having trouble with special characters in your taxonomies or titles adding odd characters to your URLs.
5 | date: 2017-02-01
6 | publishdate: 2017-02-01
7 | lastmod: 2017-02-01
8 | keywords: [urls,multilingual,special characters]
9 | categories: [troubleshooting]
10 | menu:
11 | docs:
12 | parent: "troubleshooting"
13 | weight:
14 | draft: false
15 | slug:
16 | aliases: [/troubleshooting/categories-with-accented-characters/]
17 | toc: true
18 | ---
19 | ## 问题: 带有重音字符的类别
20 |
21 | > 我的一个类别被命名为"乐卡尔",但链接最终是这样生成的:
22 | >
23 | > categories/le-carr%C3%A9
24 | >
25 | > 不工作. 我能忽略这个问题吗?
26 |
27 | ## 解决方案
28 |
29 | 你是一个MacOS的用户吗?如果是这样的话,你可能是一个受害者,HFS +文件系统的坚持来存储"é"(U + 00e9)字符正常形式分解(NFD)模式,即为"E"+"́"(U + 0065 + 0301).
30 |
31 | `勒% %`实际上是正确的,`% %`在U+ UTF-8版本00e9预期由Web服务器. 问题是OS X转了. [u + 00e9]进入之内[0065+0301+],从而`勒% %`不再工作. 相反,只有`勒卡雷连铸% 81`结束`81 %`将匹配[0065+0301+]最后.
32 |
33 | 这是OS X独有的. 世界上其他地方没有这样做,当然也不是你最可能运行Linux的Web服务器. 这也不是雨果特有的问题. 其他人在他们的HTML文件中有重音字符时就被这个咬了.
34 |
35 | 注意,这个问题并不具体于拉丁语脚本. 日本的Mac用户经常遇到相同的问题,例如`だ`分解成`た`和`与# x3099;`. (读[日本perl用户文章][]).
36 |
37 | rsync 3. x的救援!从[服务器故障的答案][]:
38 |
39 | > 你可以使用rsync的`ℴℴiconv`选择UTF-8 NFC与NFD之间转换,至少如果你的Mac. 有一个特别的`utf-8-mac`字符集是UTF-8 NFD. 因此,为了将文件从Mac复制到Web服务器,您需要运行类似于:
40 | >
41 | > `rsync -ℴℴiconv = utf-8-mac,UTF-8 localdir / mywebserver: remotedir /`
42 | >
43 | > 这会将所有本地文件名由UTF-8 NFD为NFC在远程服务器. 文件的内容不会受到影响. ℴ[服务器故障][]
44 |
45 | 请确保你有rsync 3的最新版本. 装X. rsync,OS X的船只已经过时. 即使是包装版本10.10(优诗美地国家公园)是版本2.6.9协议版本29. 这个`ℴℴiconv`国旗是新的rsync 3. X.
46 |
47 | ### 论坛参考
48 |
49 | -
50 | - [http://wiki.apache.org/subversion/nonnormalizingunicodecompositionawareness](http://wiki.apache.org/subversion/NonNormalizingUnicodeCompositionAwareness)
51 | - [http: / /恩. 维基百科. org /维基/ unicode_equivalence #例子](https://en.wikipedia.org/wiki/Unicode_equivalence#Example)
52 | -
53 | -
54 |
55 | [an answer posted on server fault]: http://serverfault.com/questions/397420/converting-utf-8-nfd-filenames-to-utf-8-nfc-in-either-rsync-or-afpd "Converting UTF-8 NFD filenames to UTF-8 NFC in either rsync or afpd, Server Fault Discussion"
56 |
57 | [japanese perl users article]: http://perl-users.jp/articles/advent-calendar/2010/english/24 "Encode::UTF8Mac makes you happy while handling file names on MacOSX"
58 |
59 | [server fault]: http://serverfault.com/questions/397420/converting-utf-8-nfd-filenames-to-utf-8-nfc-in-either-rsync-or-afpd "Converting UTF-8 NFD filenames to UTF-8 NFC in either rsync or afpd, Server Fault Discussion"
60 |
--------------------------------------------------------------------------------
/src/config/loggerConfig.js:
--------------------------------------------------------------------------------
1 | const winston = require('winston');
2 | const ora = require("ora-min")
3 |
4 | // 获得日志等级
5 | const {
6 | getOptions
7 | } = require('./work-options.js')
8 | const configs = getOptions()
9 |
10 | var logger = new(winston.Logger)({
11 | level: 'info',
12 | transports: [
13 | new(winston.transports.Console)({
14 | datePattern: '.yyyy-MM-ddTHH-mm',
15 | colorize: true
16 | }),
17 | new(winston.transports.File)({
18 | filename: 'translate-info.log',
19 | handleExceptions: true,
20 | maxsize: 52000,
21 | maxFiles: 1,
22 | level: 'info',
23 | colorize: true
24 | })
25 | ]
26 | });
27 |
28 | logger.level = configs.logger.level
29 |
30 | let D = configs.logger.level === 'debug'
31 |
32 | // 日志接口
33 |
34 | let LOGGER;
35 |
36 | /**
37 | * @description start logger
38 | * @param {any} str
39 | * @param {string} level
40 | */
41 | function loggerStart(str, level = 'debug'){
42 |
43 | if (!D) {
44 | LOGGER = ora(str).start()
45 | } else {
46 | LOGGER = logger
47 | LOGGER[level](str)
48 | }
49 | }
50 |
51 | /**
52 | * @description set logger text
53 | * @param {String} str
54 | * @param {string} options.level
55 | * @param {string} options.color *
56 | */
57 | function loggerText(str, options = {level:"debug",color:"green"}){
58 | if(!LOGGER) return
59 |
60 | if (!D) {
61 | LOGGER.text = str
62 | if (options.color) {
63 | LOGGER.color = options.color
64 | }
65 | } else {
66 | str += '\n'
67 | if (options.level) {
68 | let level = options.level
69 | LOGGER[level](str)
70 | }
71 | }
72 | }
73 |
74 | /**
75 | * @description logger stop
76 | * @param {string} str
77 | * @param {string} options.ora
78 | * @param {string} options.level
79 | */
80 | function loggerStop(str, options = {level:"debug"}){
81 | if(!LOGGER){
82 | return false
83 | }
84 | if (!D) {
85 | if (options.ora && str) {
86 | let ora = options.ora
87 | LOGGER[ora](str)
88 | } else {
89 | LOGGER.stop()
90 | }
91 | } else {
92 | if (str) {
93 | LOGGER[options.level](str)
94 | }
95 | }
96 |
97 | LOGGER = null
98 |
99 | }
100 |
101 | const getLogger = () =>{
102 | return LOGGER
103 | }
104 |
105 | const _SETDEBUG = (d) =>{
106 | D = d
107 | }
108 |
109 | function oneOra(str,end = 'succeed') {
110 | let l = getLogger()
111 | let oT;
112 | if(l && !D){
113 | oT = l.text
114 | l.stop()
115 | }
116 | const s = ora(str).start()
117 | s.color = 'red'
118 | s[end]()
119 |
120 | if(l && !D){
121 | loggerStart(oT)
122 | }
123 | }
124 |
125 | module.exports = {
126 | logger,
127 | loggerStart,
128 | loggerText,
129 | loggerStop,
130 | getLogger,
131 | _SETDEBUG,
132 | oneOra
133 | }
134 |
--------------------------------------------------------------------------------
/test/setObjectKey.Object.js:
--------------------------------------------------------------------------------
1 |
2 | const { test } = require('ava')
3 |
4 | const tree = {
5 | "type": "root",
6 | "children": [
7 | {
8 | "type": "heading",
9 | "depth": 2,
10 | "children": [
11 | {
12 | "type": "text",
13 | "value": "1. InPath",
14 | "position": {
15 | "start": {
16 | "line": 1,
17 | "column": 4,
18 | "value": "Hello",
19 | "offset": 3
20 | },
21 | "end": {
22 | "line": 1,
23 | "column": 9,
24 | "offset": 8
25 | },
26 | "indent": []
27 | }
28 | }
29 | ],
30 | "position": {
31 | "start": {
32 | "line": 1,
33 | "column": 1,
34 | "offset": 0
35 | },
36 | "end": {
37 | "line": 1,
38 | "column": 9,
39 | "offset": 8
40 | },
41 | "indent": [],
42 | "value": "2. OutPath"
43 | }
44 | }
45 | ],
46 | "position": {
47 | "start": {
48 | "line": 1,
49 | "column": 1,
50 | "offset": 0
51 | },
52 | "end": {
53 | "line": 2,
54 | "column": 1,
55 | "offset": 9
56 | }
57 | }
58 | }
59 |
60 |
61 |
62 | const truetree = {
63 | "type": "root",
64 | "children": [
65 | {
66 | "type": "heading",
67 | "depth": 2,
68 | "children": [
69 | {
70 | "type": "text",
71 | "value": "1. InPath",
72 | "position": {
73 | "start": {
74 | "line": 1,
75 | "column": 4,
76 | "value": "你好",
77 | "offset": 3
78 | },
79 | "end": {
80 | "line": 1,
81 | "column": 9,
82 | "offset": 8
83 | },
84 | "indent": []
85 | }
86 | }
87 | ],
88 | "position": {
89 | "start": {
90 | "line": 1,
91 | "column": 1,
92 | "offset": 0
93 | },
94 | "end": {
95 | "line": 1,
96 | "column": 9,
97 | "offset": 8
98 | },
99 | "indent": [],
100 | "value": "2. OutPath"
101 | }
102 | }
103 | ],
104 | "position": {
105 | "start": {
106 | "line": 1,
107 | "column": 1,
108 | "offset": 0
109 | },
110 | "end": {
111 | "line": 2,
112 | "column": 1,
113 | "offset": 9
114 | }
115 | }
116 | }
117 |
118 | module.exports = [tree, truetree]
119 |
--------------------------------------------------------------------------------
/src/config/optionsTodo.js:
--------------------------------------------------------------------------------
1 | // defaultConfig options
2 | /**
3 | * @description
4 | * @param {String|Boolean} option
5 | * @param {Function} callback
6 | * @param {any} args
7 | * @returns {Function}
8 | */
9 | function setDefault(option, callback, args) {
10 | return callback(option, args);
11 | }
12 |
13 | /**
14 | * @description add match and skip Arr
15 | * @param {any} mS
16 | * @param {string} mS.n
17 | * @param {any} args
18 | */
19 | function matchAndSkip(mS, args) {
20 | let BeArr = [];
21 | if (mS.n) {
22 | BeArr = BeArr.concat(mS.n.split(','));
23 | }
24 | // init
25 | if (mS.type == 'M') {
26 | args.matchs = BeArr;
27 | } else {
28 | args.skips = BeArr;
29 | }
30 | return BeArr;
31 | }
32 |
33 | /**
34 | * @description add md AST types
35 | * @param {any} mS
36 | * @param {string} mS.n
37 | * @param {any} args
38 | */
39 | function typesTodo(mS, args) {
40 | let BeArr = [];
41 | if (mS.n) {
42 | BeArr = BeArr.concat(mS.n.trim().split(','));
43 | }
44 | // init
45 | if (mS.type == 'T') {
46 | args.types = BeArr;
47 | }
48 | return BeArr;
49 | }
50 |
51 | /**
52 | * @description
53 | * @param {String|Boolean} debug
54 | * @param {any} args
55 | * @returns {String}
56 | */
57 | function debugTodo(debug, args) {
58 | if (debug) {
59 | args.logger.level = 'debug';
60 | }
61 | if (typeof debug == 'string') {
62 | args.logger.level = debug;
63 | }
64 | return args.logger.level;
65 | }
66 |
67 | /**
68 | * @description
69 | * @param {String} tranFrom
70 | * @param {any} args
71 | * @returns {String}
72 | */
73 | function fromTodo(tranFrom, args) {
74 | if (tranFrom) {
75 | args.from = tranFrom;
76 | }
77 | return args.from;
78 | }
79 |
80 | /**
81 | * @description
82 | * @param {String} tranTo
83 | * @param {any} args
84 | * @returns {String}
85 | */
86 | function toTodo(tranTo, args) {
87 | if (tranTo) {
88 | args.to = tranTo;
89 | }
90 | return args.to;
91 | }
92 |
93 | /**
94 | * @description
95 | * @param {number} num
96 | * @param {any} args
97 | * @returns {number}
98 | */
99 | function numTodo(num, args) {
100 | if (typeof num == 'number') {
101 | if (num > 0) {
102 | args.num = num;
103 | }
104 | }
105 | return args.num;
106 | }
107 |
108 | /**
109 | * @description api {``baidu | google | youdao``}
110 | * @param {String} api
111 | * @param {any} args
112 | * @returns {String}
113 | */
114 | function apiTodo(api, args) {
115 | if (api) {
116 | args.api = api;
117 | }
118 | return args.api;
119 | }
120 |
121 | /**
122 | * @description
123 | * @param {Boolean} rewrite
124 | * @param {any} args
125 | * @returns {Boolean}
126 | */
127 | function rewriteTodo(rewrite, args) {
128 | args.rewrite = rewrite ? true : false;
129 | return args.rewrite;
130 | }
131 |
132 | module.exports = {
133 | setDefault,
134 | debugTodo,
135 | fromTodo,
136 | toTodo,
137 | apiTodo,
138 | rewriteTodo,
139 | numTodo,
140 | matchAndSkip,
141 | typesTodo
142 | };
143 |
--------------------------------------------------------------------------------
/src/translateMds.js:
--------------------------------------------------------------------------------
1 | 'use script'
2 | const fs = require('mz/fs')
3 | const path = require('path')
4 | const remark = require('remark')
5 |
6 | const Listmd = require('./util/readmd.js')
7 | const cutMdhead = require('./util/cutMdhead.js')
8 | const { O2A } = require('./util/util.js')
9 |
10 | const {
11 | logger
12 | } = require('./config/loggerConfig.js') // winston config
13 |
14 | // config
15 | const mergeConfig = require('./config/mergeConfig')
16 |
17 | // Object to Array
18 |
19 | /**
20 | * @description translateMds main
21 | * @param {Array|Object} options
22 | * @param {Boolean|String} debug
23 | * @param {boolean} [isCli=false]
24 | * @returns {Array