create-rule.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env node --harmony
  2. const path = require('path');
  3. const fs = require('fs');
  4. const { exec } = require('child_process');
  5. const argv = require('minimist')(process.argv.slice(2)); // eslint-disable-line import/no-extraneous-dependencies
  6. const jscodeshiftJSON = require('jscodeshift/package.json'); // eslint-disable-line import/no-extraneous-dependencies
  7. const ruleBoilerplateGenerator = require('./boilerplate/rule');
  8. const testBoilerplateGenerator = require('./boilerplate/test');
  9. const docBoilerplateGenerator = require('./boilerplate/doc');
  10. const ruleName = argv._[0];
  11. const author = argv.author || '$AUTHOR';
  12. const description = argv.description || '$DESCRIPTION';
  13. const rulePath = path.resolve(`src/rules/${ruleName}.js`);
  14. const testPath = path.resolve(`__tests__/src/rules/${ruleName}-test.js`);
  15. const docsPath = path.resolve(`docs/rules/${ruleName}.md`);
  16. const jscodeshiftMain = jscodeshiftJSON.main;
  17. const jscodeshiftPath = require.resolve('jscodeshift');
  18. const jscodeshiftRoot = jscodeshiftPath.slice(0, jscodeshiftPath.indexOf(jscodeshiftMain));
  19. // Validate
  20. if (!ruleName) {
  21. throw new Error('Rule name is required');
  22. } else if (fs.existsSync(rulePath)) {
  23. throw new Error('Rule already exists!');
  24. }
  25. // Generate file boilerplate
  26. const ruleBoilerplate = ruleBoilerplateGenerator(author, description);
  27. const testBoilerplate = testBoilerplateGenerator(ruleName, author, description);
  28. const docBoilerplate = docBoilerplateGenerator(ruleName);
  29. // Create new files
  30. fs.writeFileSync(rulePath, ruleBoilerplate);
  31. fs.writeFileSync(testPath, testBoilerplate);
  32. fs.writeFileSync(docsPath, docBoilerplate);
  33. // Add the rule to the index
  34. exec(
  35. [
  36. path.join(jscodeshiftRoot, jscodeshiftJSON.bin.jscodeshift),
  37. './src/index.js',
  38. '-t ./scripts/addRuleToIndex.js',
  39. '--extensions js',
  40. '--parser flow',
  41. `--ruleName=${ruleName}`,
  42. `--rulePath=${rulePath}`,
  43. ].join(' '),
  44. (error) => {
  45. if (error) {
  46. console.error(`exec error: ${error}`); // eslint-disable-line no-console
  47. }
  48. },
  49. );