使用AST将中文字符扣出

前言

首先我们看看AST的格式,通过下面这个网站

https://astexplorer.net/

我们可以很清楚的看到AST的格式

parser

这里推荐使用@babel/parser这个库

parse(code, {
      sourceType: 'module',
      plugins: ['jsx', 'flow', 'classProperties', ['decorators', { legacy: true, decoratorsBeforeExport: true }]],
    });

实现

这里我们实现一个简单的截取中文的例子

/* eslint-disable no-continue */
/* eslint-disable guard-for-in */
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const { get, isEmpty, each, find, isObject, includes, map, endsWith } = require('lodash');
const fsFind = require('fs-find');
const { parse } = require('@babel/parser');

const srcPath = path.resolve(__dirname, '../src');
const intlFile = path.resolve(__dirname, 'data', 'intl.json');

const ZH_REG = /.*[\u4e00-\u9fa5]+.*/;
const writeStream = fs.createWriteStream(intlFile);
// 需要排除的文件
// TODO: 排除Modal文件夹下
const EXCLUDE_FILES = ['messages.js', 'Demo/.*', 'fallback.js', 'form/config.js', 'TableContainer/searchs-demo.js'];

class Intl {
  constructor() {
    this.commentType = ['CommentLine', 'CommentBlock'];

    this.init();
  }

  parser(code) {
    return parse(code, {
      sourceType: 'module',
      plugins: ['jsx', 'flow', 'classProperties', ['decorators', { legacy: true, decoratorsBeforeExport: true }]],
    });
  }

  async init() {
    const files = await this.findAllFile();
    each(files, file => {
      let code;
      try {
        code = this.parser(fs.readFileSync(file, 'utf-8'));
      } catch (error) {
        console.log(chalk.red.bold(file));
        console.error(error);
      }
      const body = get(code, 'program.body');
      const data = this.pickZh(body);
      const dataStream = {
        file,
        data,
      };
      if (!isEmpty(data)) {
        writeStream.write(`${JSON.stringify(dataStream, null, 2)}\n`);
      }
    });
    console.log(`扫描文件保存在${chalk.red.underline('webx/server/data/intl.json')}`);
    writeStream.end();
  }

  getIntlValue(data) {
    const value = get(data, 'value');
    if (isEmpty(value)) return undefined;
    if (isObject(value)) return get(data, 'value.raw');
    return value;
  }

  isConsoleExpression(item) {
    const CONSOLE_TAG = 'console';
    return get(item, 'type') === 'ExpressionStatement' && get(item, 'expression.callee.object.name') === CONSOLE_TAG;
  }

  pickZh(initData) {
    const me = this;
    const zhEnum = [];

    const pichZhFn = data => {
      for (const i in data) {
        const item = data[i];
        if (me.isConsoleExpression(item) || !isObject(item) || includes(me.commentType, item.type)) continue;

        const value = me.getIntlValue(item);
        if (ZH_REG.test(value)) {
          zhEnum.push(`${get(item, 'loc.start.line')}行:${value}`);
          continue;
        }
        pichZhFn(item);
      }
    };
    pichZhFn(initData);
    return zhEnum;
  }

  includeFile(str) {
    const names = ['.js'];
    return find(names, name => endsWith(str, name));
  }

  excludeFile(str) {
    return find(EXCLUDE_FILES, name => new RegExp(`^.*${name}$`).test(str));
  }

  findAllFile() {
    const me = this;
    return new Promise((reslove, reject) => {
      fsFind(
        srcPath,
        {
          absolute: false,
          file(name) {
            const isIncludes = me.includeFile(name);
            const isExcludes = me.excludeFile(name);
            if (isIncludes) {
              return !isExcludes;
            }
          },
        },
        (err, results) => {
          if (err) {
            reject(err);
          }
          reslove(map(results, item => item.file));
        },
      );
    });
  }
}

new Intl();

你可能感兴趣的:(使用AST将中文字符扣出)