Skip to content

AStyle格式化代码

Published: at 10:16 AM | 2 min read

通过Node.js脚本来调用AStyle.exe格式化代码。
src:需要格式化的代码目录
params:AStyle参数,默认使用linux风格
filterNameList:不进行格式化的目录,跳过这些目录
regSuffix:需要格式化的文件名正则

const fs = require('fs')
const path = require('path')
const { exec } = require('child_process');

/**
 * 通过配置这几个参数来更改行为
 */
const src = path.normalize(__dirname)
const params = '--style=linux --align-reference=type --align-pointer=type --pad-header --pad-comma --pad-oper --indent-preproc-block'
const filterNameList = ['3rd', 'protobuf', 'tinyxml', 'websocket', 'win32']
const regSuffix = /\.(h|cpp)/

function syncReadAllFile(dir, cb) {
  const subDir = fs.readdirSync(dir);
  for (let dirName of subDir) {
    const subPath = path.normalize(dir + '/' + dirName);
    if (fs.lstatSync(subPath).isDirectory()) {
      syncReadAllFile(subPath, cb);
    } else {
      cb(subPath)
    }
  }
}

let count = 0;
syncReadAllFile(src, function(subpath) {
  const dirname = path.dirname(subpath);
  const basename = path.basename(subpath);
  let isFilter = false;
  for (let filterName of filterNameList) {
    if (dirname.indexOf(filterName) >= 0) {
      isFilter = true;
      break;
    }
  }
  if (!isFilter && regSuffix.test(subpath)) {
    ++count;
    console.log(subpath)
    exec(path.normalize(src + '/AStyle.exe') + ' ' + subpath + ' ' + params)
  }
})

console.log('finished total:' + count)

AStyle.exe下载地址