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

529 views Asked by At

I am working on a project which need to be open source now and we need to add Apache license string at top of the each file.

Having said that, I want my tslint to check if a particular string is present at top of each typescript file and show error if that string is not present.

/*
* 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
*

I did not see any TS Lint configuration to check if a string is present or not.

Is there any way I can achieve it.

2

There are 2 answers

0
Aniruddha Das On BEST ANSWER

After reviewing many options, I placed a pre-commit hook in our code and configure the node script to execute before a commit is tried on the repository.

There is a module available in npmjs which will make it more easy and you can do it easily

1.install the module

npm i --save-dev pre-commit

2.develop a script which will run as procommit hook to find specific sting in your code.

// 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 the hook to be executed in the 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"
  ]
}
0
wrager On

You should write custom rule, include it into your tslint.json and define it's directory in the rulesDirectory property.

I think that there are no suitable 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.