objectLiteralSortKeysRule.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright 2013 Palantir Technologies, Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. Object.defineProperty(exports, "__esModule", { value: true });
  19. var tslib_1 = require("tslib");
  20. var tsutils_1 = require("tsutils");
  21. var ts = require("typescript");
  22. var Lint = require("../index");
  23. var OPTION_IGNORE_CASE = "ignore-case";
  24. var OPTION_MATCH_DECLARATION_ORDER = "match-declaration-order";
  25. var OPTION_SHORTHAND_FIRST = "shorthand-first";
  26. var Rule = /** @class */ (function (_super) {
  27. tslib_1.__extends(Rule, _super);
  28. function Rule() {
  29. return _super !== null && _super.apply(this, arguments) || this;
  30. }
  31. /* tslint:enable:object-literal-sort-keys */
  32. Rule.FAILURE_STRING_ALPHABETICAL = function (name) {
  33. return "The key '" + name + "' is not sorted alphabetically";
  34. };
  35. Rule.FAILURE_STRING_USE_DECLARATION_ORDER = function (propName, typeName) {
  36. var type = typeName === undefined ? "its type declaration" : "'" + typeName + "'";
  37. return "The key '" + propName + "' is not in the same order as it is in " + type + ".";
  38. };
  39. Rule.FAILURE_STRING_SHORTHAND_FIRST = function (name) {
  40. return "The shorthand property '" + name + "' should appear before normal properties";
  41. };
  42. Rule.prototype.apply = function (sourceFile) {
  43. var options = parseOptions(this.ruleArguments);
  44. if (options.matchDeclarationOrder) {
  45. throw new Error(this.ruleName + " needs type info to use \"" + OPTION_MATCH_DECLARATION_ORDER + "\".");
  46. }
  47. return this.applyWithFunction(sourceFile, walk, options);
  48. };
  49. Rule.prototype.applyWithProgram = function (sourceFile, program) {
  50. return this.applyWithFunction(sourceFile, walk, parseOptions(this.ruleArguments), program.getTypeChecker());
  51. };
  52. /* tslint:disable:object-literal-sort-keys */
  53. Rule.metadata = {
  54. ruleName: "object-literal-sort-keys",
  55. description: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Checks ordering of keys in object literals.\n\n When using the default alphabetical ordering, additional blank lines may be used to group\n object properties together while keeping the elements within each group in alphabetical order.\n "], ["\n Checks ordering of keys in object literals.\n\n When using the default alphabetical ordering, additional blank lines may be used to group\n object properties together while keeping the elements within each group in alphabetical order.\n "]))),
  56. rationale: "Useful in preventing merge conflicts",
  57. optionsDescription: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n By default, this rule checks that keys are in alphabetical order.\n The following may optionally be passed:\n\n * \"", "\" will compare keys in a case insensitive way.\n * \"", "\" will prefer to use the key ordering of the contextual type of the object literal, as in:\n\n interface I { foo: number; bar: number; }\n const obj: I = { foo: 1, bar: 2 };\n\n If a contextual type is not found, alphabetical ordering will be used instead.\n * \"", "\" will enforce shorthand properties to appear first, as in:\n\n const obj = { a, c, b: true };\n "], ["\n By default, this rule checks that keys are in alphabetical order.\n The following may optionally be passed:\n\n * \"", "\" will compare keys in a case insensitive way.\n * \"", "\" will prefer to use the key ordering of the contextual type of the object literal, as in:\n\n interface I { foo: number; bar: number; }\n const obj: I = { foo: 1, bar: 2 };\n\n If a contextual type is not found, alphabetical ordering will be used instead.\n * \"", "\" will enforce shorthand properties to appear first, as in:\n\n const obj = { a, c, b: true };\n "])), OPTION_IGNORE_CASE, OPTION_MATCH_DECLARATION_ORDER, OPTION_SHORTHAND_FIRST),
  58. options: {
  59. type: "string",
  60. enum: [OPTION_IGNORE_CASE, OPTION_MATCH_DECLARATION_ORDER, OPTION_SHORTHAND_FIRST],
  61. },
  62. optionExamples: [
  63. true,
  64. [true, OPTION_IGNORE_CASE, OPTION_MATCH_DECLARATION_ORDER, OPTION_SHORTHAND_FIRST],
  65. ],
  66. type: "maintainability",
  67. typescriptOnly: false,
  68. };
  69. return Rule;
  70. }(Lint.Rules.OptionallyTypedRule));
  71. exports.Rule = Rule;
  72. function parseOptions(ruleArguments) {
  73. return {
  74. ignoreCase: has(OPTION_IGNORE_CASE),
  75. matchDeclarationOrder: has(OPTION_MATCH_DECLARATION_ORDER),
  76. shorthandFirst: has(OPTION_SHORTHAND_FIRST),
  77. };
  78. function has(name) {
  79. return ruleArguments.indexOf(name) !== -1;
  80. }
  81. }
  82. function walk(ctx, checker) {
  83. var sourceFile = ctx.sourceFile, _a = ctx.options, ignoreCase = _a.ignoreCase, matchDeclarationOrder = _a.matchDeclarationOrder, shorthandFirst = _a.shorthandFirst;
  84. ts.forEachChild(sourceFile, function cb(node) {
  85. if (tsutils_1.isObjectLiteralExpression(node) && node.properties.length > 1) {
  86. check(node);
  87. }
  88. ts.forEachChild(node, cb);
  89. });
  90. function check(node) {
  91. if (matchDeclarationOrder) {
  92. var type = getContextualType(node, checker);
  93. // If type has an index signature, we can't check ordering.
  94. // If type has call/construct signatures, it can't be satisfied by an object literal anyway.
  95. if (type !== undefined
  96. && type.members.every(function (m) { return m.kind === ts.SyntaxKind.PropertySignature || m.kind === ts.SyntaxKind.MethodSignature; })) {
  97. checkMatchesDeclarationOrder(node, type, type.members);
  98. return;
  99. }
  100. }
  101. checkAlphabetical(node);
  102. }
  103. function checkAlphabetical(node) {
  104. if (tsutils_1.isSameLine(ctx.sourceFile, node.properties.pos, node.end)) {
  105. return;
  106. }
  107. var lastKey;
  108. var lastPropertyWasShorthand;
  109. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
  110. var property = _a[_i];
  111. switch (property.kind) {
  112. case ts.SyntaxKind.SpreadAssignment:
  113. lastKey = undefined; // reset at spread
  114. lastPropertyWasShorthand = undefined; // reset at spread
  115. break;
  116. case ts.SyntaxKind.ShorthandPropertyAssignment:
  117. case ts.SyntaxKind.PropertyAssignment:
  118. if (shorthandFirst) {
  119. if (property.kind === ts.SyntaxKind.ShorthandPropertyAssignment) {
  120. if (lastPropertyWasShorthand === false) {
  121. ctx.addFailureAtNode(property.name, Rule.FAILURE_STRING_SHORTHAND_FIRST(property.name.text));
  122. return; // only show warning on first out-of-order property
  123. }
  124. lastPropertyWasShorthand = true;
  125. }
  126. else {
  127. if (lastPropertyWasShorthand === true) {
  128. lastKey = undefined; // reset on change from shorthand to normal
  129. }
  130. lastPropertyWasShorthand = false;
  131. }
  132. }
  133. if (property.name.kind === ts.SyntaxKind.Identifier ||
  134. property.name.kind === ts.SyntaxKind.StringLiteral) {
  135. var key = ignoreCase ? property.name.text.toLowerCase() : property.name.text;
  136. // comparison with undefined is expected
  137. if (lastKey > key && !hasBlankLineBefore(ctx.sourceFile, property)) {
  138. ctx.addFailureAtNode(property.name, Rule.FAILURE_STRING_ALPHABETICAL(property.name.text));
  139. return; // only show warning on first out-of-order property
  140. }
  141. lastKey = key;
  142. }
  143. }
  144. }
  145. }
  146. function checkMatchesDeclarationOrder(_a, type, members) {
  147. var properties = _a.properties;
  148. var memberIndex = 0;
  149. outer: for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
  150. var prop = properties_1[_i];
  151. if (prop.kind === ts.SyntaxKind.SpreadAssignment) {
  152. memberIndex = 0;
  153. continue;
  154. }
  155. if (prop.name.kind === ts.SyntaxKind.ComputedPropertyName) {
  156. continue;
  157. }
  158. var propName = prop.name.text;
  159. for (; memberIndex !== members.length; memberIndex++) {
  160. var memberName = members[memberIndex].name;
  161. if (memberName.kind !== ts.SyntaxKind.ComputedPropertyName && propName === memberName.text) {
  162. continue outer;
  163. }
  164. }
  165. // This We didn't find the member we were looking for past the previous member,
  166. // so it must have come before it and is therefore out of order.
  167. ctx.addFailureAtNode(prop.name, Rule.FAILURE_STRING_USE_DECLARATION_ORDER(propName, getTypeName(type)));
  168. // Don't bother with multiple errors.
  169. break;
  170. }
  171. }
  172. }
  173. function hasBlankLineBefore(sourceFile, element) {
  174. var comments = ts.getLeadingCommentRanges(sourceFile.text, element.pos);
  175. if (comments === undefined) {
  176. comments = []; // it will be easier to work with an empty array down below...
  177. }
  178. var elementStart = comments.length > 0 ? comments[comments.length - 1].end : element.getFullStart();
  179. // either the element itself, or one of its leading comments must have an extra new line before them
  180. return hasDoubleNewLine(sourceFile, elementStart) || comments.some(function (comment) {
  181. var commentLine = ts.getLineAndCharacterOfPosition(sourceFile, comment.pos).line;
  182. var commentLineStartPosition = ts.getPositionOfLineAndCharacter(sourceFile, commentLine, 0);
  183. return hasDoubleNewLine(sourceFile, commentLineStartPosition - 4);
  184. });
  185. }
  186. function hasDoubleNewLine(sourceFile, position) {
  187. return /(\r?\n){2}/.test(sourceFile.text.slice(position, position + 4));
  188. }
  189. function getTypeName(t) {
  190. var parent = t.parent;
  191. return t.kind === ts.SyntaxKind.InterfaceDeclaration
  192. ? t.name.text
  193. : tsutils_1.isTypeAliasDeclaration(parent)
  194. ? parent.name.text
  195. : undefined;
  196. }
  197. function getContextualType(node, checker) {
  198. var c = checker.getContextualType(node);
  199. if (c === undefined || c.symbol === undefined) {
  200. return undefined;
  201. }
  202. var declarations = c.symbol.declarations;
  203. if (declarations === undefined || declarations.length !== 1) {
  204. return undefined;
  205. }
  206. var decl = declarations[0];
  207. return tsutils_1.isInterfaceDeclaration(decl) || tsutils_1.isTypeLiteralNode(decl) ? decl : undefined;
  208. }
  209. var templateObject_1, templateObject_2;