tslint 检查每个文件是否在文件开头存在特定字符串

tslint to check each file if there is specific string present at the start of the file

我正在做一个现在需要开源的项目,我们需要在每个文件的顶部添加 Apache 许可证字符串。

话虽如此,我希望我的 tslint 检查每个打字稿文件顶部是否存在特定字符串,如果该字符串不存在则显示错误。

/*
* Copyright 2017 proje*** contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*

我没有看到任何 TS Lint 配置来检查字符串是否存在。

有什么办法可以实现吗

您应该编写 custom rule,将其包含到您的 tslint.json 中并在 rulesDirectory 属性.

中定义它的目录

我认为没有合适的built-in visit function for leading comment in source file, so you can use the applyWithFunction abstract method from the Lint.Rules.AbstractRule class. Examples can be found in tslint built-in rules sources

查看许多选项后,我在我们的代码中放置了一个预提交挂钩,并将节点脚本配置为在对存储库尝试提交之前执行。

npmjs 中有一个模块可以使它更容易,你可以轻松做到

1.install 模块

npm i --save-dev pre-commit

2.develop 一个脚本,它将 运行 作为 procommit 挂钩以在您的代码中查找特定的 sting。

// code to find specific string
(function () {
  var fs = require('fs');
  var glob = require('glob-fs')();
  var path = require('path');
  var result = 0;
  var exclude = ['LICENSE',
    path.join('e2e', 'util', 'db-ca', 'rds-combined-ca-bundle.pem'),
    path.join('src', 'favicon.ico')];
  var files = [];
  files = glob.readdirSync('**');
  files.map((file) => {
    try {
      if (!fs.lstatSync(file).isDirectory() && file.indexOf('.json') === -1 
           && exclude.indexOf(file) === -1) {
        var data = fs.readFileSync(file, 'utf8');

        if (data.indexOf('Copyright 2017 candifood contributors') === -1) {
          console.log('Please add License text in coment in the file ' + file);
          result = 1;
        }
      }
    } catch (e) {
      console.log('Error:', e.stack);
    }
  });
  process.exit(result);
})();

3.place中要执行的钩子package.json

{
  "name": "project-name",
  "version": 1.0.0",
  "license": "Apache 2.0",
  "scripts": {
    "license-check": "node license-check",
  },
  "private": true,
  "dependencies": {
  },
  "devDependencies": {
    "pre-commit": "1.2.2",
  },
  "pre-commit": [
    "license-check"
  ]
}