no-addtask-setup.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * @fileoverview Reject `add_task(async function setup` or similar patterns in
  3. * favour of add_setup.
  4. *
  5. * This Source Code Form is subject to the terms of the Mozilla Public
  6. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. */
  9. "use strict";
  10. function isNamedLikeSetup(name) {
  11. return /^(init|setup)$/i.test(name);
  12. }
  13. module.exports = {
  14. meta: {
  15. type: "suggestion",
  16. fixable: "code",
  17. },
  18. create(context) {
  19. return {
  20. "Program > ExpressionStatement > CallExpression": function(node) {
  21. let callee = node.callee;
  22. if (callee.type === "Identifier" && callee.name === "add_task") {
  23. let arg = node.arguments[0];
  24. if (
  25. arg.type !== "FunctionExpression" ||
  26. !arg.id ||
  27. !isNamedLikeSetup(arg.id.name)
  28. ) {
  29. return;
  30. }
  31. context.report({
  32. node,
  33. message:
  34. "Do not use add_task() for setup, use add_setup() instead.",
  35. fix: fixer => {
  36. let range = [node.callee.range[0], arg.id.range[1]];
  37. let asyncOrNot = arg.async ? "async " : "";
  38. return fixer.replaceTextRange(
  39. range,
  40. `add_setup(${asyncOrNot}function`
  41. );
  42. },
  43. });
  44. }
  45. },
  46. };
  47. },
  48. };