Skip to content

Commit

Permalink
Finish things
Browse files Browse the repository at this point in the history
  • Loading branch information
lydell committed Feb 3, 2024
1 parent 6a02410 commit d5bdd2e
Show file tree
Hide file tree
Showing 7 changed files with 261 additions and 101 deletions.
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,15 @@ import g from ".";
import h from "./constants";
import i from "./styles";

// TypeScript import assignments.
import J = require("../parent");
import J = require("./sibling");
export import K = require("an-npm-package");
import L = require("different-npm-package");
import M = Namespace;
export import N = Namespace.A.B.C;
import O = Namespace.A.C;

// Different types of exports:
export { a } from "../..";
export { b } from "/";
Expand Down Expand Up @@ -365,6 +374,8 @@ Side effect imports have `\u0000` _prepended_ to their `from` string (starts wit

Type imports have `\u0000` _appended_ to their `from` string (ends with `\u0000`). You can match them with `"\\u0000$"` – but you probably need more than that to avoid them also being matched by other regexes.

TypeScript import assignments have `\u0001` (for `import A = B.C.D`) or `\u0002` (for `import A = require("A")`) prepended to their `from` string (starts with `\u0001` or `\u0002`). It is _not_ possible to distinguish `export import A =` and `import A =`.

All imports that match the same regex are sorted internally as mentioned in [Sort order].

This is the default value for the `groups` option:
Expand All @@ -384,6 +395,8 @@ This is the default value for the `groups` option:
// Relative imports.
// Anything that starts with a dot.
["^\\."],
// TypeScript import assignments.
["^\\u0001", "^\\u0002"],
];
```

Expand Down Expand Up @@ -677,7 +690,7 @@ Use [custom grouping], setting the `groups` option to only have a single inner a
For example, here’s the default value but changed to a single inner array:

```js
[["^\\u0000", "^node:", "^@?\\w", "^", "^\\."]];
[["^\\u0000", "^node:", "^@?\\w", "^", "^\\.", "^\\u0001", "^\\u0002"]];
```

(By default, each string is in its _own_ array (that’s 5 inner arrays) – causing a blank line between each.)
Expand Down
11 changes: 7 additions & 4 deletions examples/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ module.exports = {
"error",
{
// The default grouping, but with no blank lines.
groups: [["^\\u0000", "^node:", "^@?\\w", "^", "^\\."]],
groups: [["^\\u0000", "^node:", "^@?\\w", "^", "^\\.", "^\\u0001", "^\\u0002"]],
},
],
},
Expand All @@ -115,7 +115,7 @@ module.exports = {
"error",
{
// The default grouping, but in reverse.
groups: [["^\\."], ["^"], ["^@?\\w"], ["^node:"], ["^\\u0000"]],
groups: [["^\\u0001", "^\\u0002"], ["^\\."], ["^"], ["^@?\\w"], ["^node:"], ["^\\u0000"]],
},
],
},
Expand All @@ -128,7 +128,7 @@ module.exports = {
"error",
{
// The default grouping, but with type imports first as a separate group.
groups: [["^.*\\u0000$"], ["^\\u0000"], ["^node:"], ["^@?\\w"], ["^"], ["^\\."]],
groups: [["^.*\\u0000$"], ["^\\u0000"], ["^node:"], ["^@?\\w"], ["^"], ["^\\."], ["^\\u0001", "^\\u0002"]],
},
],
},
Expand All @@ -141,7 +141,7 @@ module.exports = {
"error",
{
// The default grouping, but with type imports last as a separate group.
groups: [["^\\u0000"], ["^node:"], ["^@?\\w"], ["^"], ["^\\."], ["^.+\\u0000$"]],
groups: [["^\\u0000"], ["^node:"], ["^@?\\w"], ["^"], ["^\\."], ["^\\u0001", "^\\u0002"], ["^.+\\u0000$"]],
},
],
},
Expand All @@ -162,6 +162,7 @@ module.exports = {
["^@?\\w"],
["^"],
["^\\."],
["^\\u0001", "^\\u0002"],
],
},
],
Expand All @@ -182,6 +183,7 @@ module.exports = {
["^@?\\w"],
["^"],
["^\\."],
["^\\u0001", "^\\u0002"],
["^node:.*\\u0000$", "^@?\\w.*\\u0000$", "^[^.].*\\u0000$", "^\\..*\\u0000$"],
],
},
Expand All @@ -202,6 +204,7 @@ module.exports = {
["^@?\\w.*\\u0000$", "^@?\\w"],
["(?<=\\u0000)$", "^"],
["^\\..*\\u0000$", "^\\."],
["^\\u0001", "^\\u0002"],
],
},
],
Expand Down
9 changes: 9 additions & 0 deletions examples/readme-order.prettier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ import g from ".";
import h from "./constants";
import i from "./styles";

// TypeScript import assignments.
import J = require("../parent");
import J = require("./sibling");
export import K = require("an-npm-package");
import L = require("different-npm-package");
import M = Namespace;
export import N = Namespace.A.B.C;
import O = Namespace.A.C;

// Different types of exports:
export { a } from "../..";
export { b } from "/";
Expand Down
33 changes: 24 additions & 9 deletions src/imports.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ const defaultGroups = [
// Relative imports.
// Anything that starts with a dot.
["^\\."],
// Namespace import.
// Anything that starts with an equal sign.
["^= "],
// TypeScript import assignments.
["^\\u0001", "^\\u0002"],
];

module.exports = {
Expand Down Expand Up @@ -100,14 +99,15 @@ function makeSortedItems(items, outerGroups) {

for (const item of items) {
const { originalSource } = item.source;
const source = item.isSideEffectImport
const sourceWithControlCharacter = item.isSideEffectImport
? `\0${originalSource}`
: item.source.kind !== "value"
? `${originalSource}\0`
: originalSource;
: getSourceWithControlCharacterFromKind(originalSource, item.source.kind);
const [matchedGroup] = shared
.flatMap(itemGroups, (groups) =>
groups.map((group) => [group, group.regex.exec(source)])
groups.map((group) => [
group,
group.regex.exec(sourceWithControlCharacter),
])
)
.reduce(
([group, longestMatch], [nextGroup, nextMatch]) =>
Expand All @@ -133,6 +133,20 @@ function makeSortedItems(items, outerGroups) {
);
}

function getSourceWithControlCharacterFromKind(originalSource, kind) {
switch (kind) {
case shared.KIND_VALUE:
return originalSource;
case shared.KIND_TS_IMPORT_ASSIGNMENT_REQUIRE:
return `\u0001${originalSource}`;
case shared.KIND_TS_IMPORT_ASSIGNMENT_NAMESPACE:
return `\u0002${originalSource}`;
default:
// `type` and `typeof`.
return `${originalSource}\u0000`;
}
}

// Exclude "ImportDefaultSpecifier" – the "def" in `import def, {a, b}`.
function getSpecifiers(importNode) {
switch (importNode.type) {
Expand Down Expand Up @@ -167,7 +181,8 @@ function isSideEffectImport(importNode, sourceCode) {
default:
return (
importNode.specifiers.length === 0 &&
(!importNode.importKind || importNode.importKind === "value") &&
(!importNode.importKind ||
importNode.importKind === shared.KIND_VALUE) &&
!shared.isPunctuator(
sourceCode.getFirstToken(importNode, { skip: 1 }),
"{"
Expand Down
136 changes: 65 additions & 71 deletions src/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -795,72 +795,8 @@ function isNewline(node) {
return node.type === "Newline";
}

function getSourceFromTSQualifiedName(sourceCode, node) {
let left;
let right;
switch (node.left.type) {
case "Identifier": {
left = node.left.name;
break;
}
case "TSQualifiedName": {
left = getSourceFromTSQualifiedName(sourceCode, node.left);
break;
}
default: {
left = ``;
break;
}
}
switch (node.right.type) {
case "Identifier": {
right = `.${node.right.name}`;
break;
}
default: {
right = ``;
break;
}
}
return left + right;
}

function getSourceFromModuleReference(sourceCode, node) {
switch (node.type) {
case "TSExternalModuleReference": {
switch (node.expression.type) {
case "Literal": {
return node.expression.value;
}
default: {
return sourceCode.text.slice(...node.expression.range);
}
}
}
case "TSQualifiedName": {
return `= ${getSourceFromTSQualifiedName(sourceCode, node)}`;
}
case "Identifier": {
return `= ${node.name}`;
}
default: {
return ``;
}
}
}

function getSource(sourceCode, node) {
let source;
switch (node.type) {
case "TSImportEqualsDeclaration": {
source = getSourceFromModuleReference(sourceCode, node.moduleReference);
break;
}
default: {
source = node.source.value;
break;
}
}
const [source, kind] = getSourceTextAndKind(sourceCode, node);

return {
// Sort by directory level rather than by string length.
Expand All @@ -870,7 +806,7 @@ function getSource(sourceCode, node) {
// Make `../` sort after `../../` but before `../a` etc.
// Why a comma? See the next comment.
.replace(/^[./]*\/$/, "$&,")
// Make `.` and `/` sort before any other punctation.
// Make `.` and `/` sort before any other punctuation.
// The default order is: _ - , x x x . x x x / x x x
// We’re changing it to: . / , x x x _ x x x - x x x
.replace(/[./_-]/g, (char) => {
Expand All @@ -889,16 +825,71 @@ function getSource(sourceCode, node) {
}
}),
originalSource: source,
kind: getImportExportKind(node),
kind,
};
}

function getSourceTextAndKind(sourceCode, node) {
switch (node.type) {
case "TSImportEqualsDeclaration":
return getSourceTextAndKindFromModuleReference(
sourceCode,
node.moduleReference
);
default:
return [node.source.value, getImportExportKind(node)];
}
}

const KIND_VALUE = "value";
const KIND_TS_IMPORT_ASSIGNMENT_REQUIRE = "z_require";
const KIND_TS_IMPORT_ASSIGNMENT_NAMESPACE = "z_namespace";

function getSourceTextAndKindFromModuleReference(sourceCode, node) {
switch (node.type) {
case "TSExternalModuleReference":
switch (node.expression.type) {
case "Literal":
return [
typeof node.expression.value === "string"
? node.expression.value
: node.expression.raw,
KIND_TS_IMPORT_ASSIGNMENT_REQUIRE,
];
default: {
const [start, end] = node.expression.range;
return [
sourceCode.text.slice(start, end),
KIND_TS_IMPORT_ASSIGNMENT_REQUIRE,
];
}
}
case "TSQualifiedName":
return [
getSourceTextFromTSQualifiedName(sourceCode, node),
KIND_TS_IMPORT_ASSIGNMENT_NAMESPACE,
];
default:
return [node.name, KIND_TS_IMPORT_ASSIGNMENT_NAMESPACE];
}
}

function getSourceTextFromTSQualifiedName(sourceCode, node) {
switch (node.left.type) {
case "TSQualifiedName":
return `${getSourceTextFromTSQualifiedName(sourceCode, node.left)}.${
node.right.name
}`;
default: {
return `${node.left.name}.${node.right.name}`;
}
}
}

function getImportExportKind(node) {
// `type` and `typeof` imports, as well as `type` exports (there are no
// `typeof` exports). In Flow, import specifiers can also have a kind. Default
// to "value" (like TypeScript) to make regular imports/exports come after the
// type imports/exports.
return node.importKind || node.exportKind || "value";
// `typeof` exports).
return node.importKind || node.exportKind || KIND_VALUE;
}

// Like `Array.prototype.findIndex`, but searches from the end.
Expand All @@ -923,6 +914,9 @@ module.exports = {
flatMap,
getImportExportItems,
isPunctuator,
KIND_TS_IMPORT_ASSIGNMENT_NAMESPACE,
KIND_TS_IMPORT_ASSIGNMENT_REQUIRE,
KIND_VALUE,
maybeReportSorting,
printSortedItems,
printWithSortedSpecifiers,
Expand Down
9 changes: 9 additions & 0 deletions test/__snapshots__/examples.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,15 @@ import g from ".";
import h from "./constants";
import i from "./styles";
// TypeScript import assignments.
import J = require("../parent");
import J = require("./sibling");
export import K = require("an-npm-package");
import L = require("different-npm-package");
import M = Namespace;
export import N = Namespace.A.B.C;
import O = Namespace.A.C;
// Different types of exports:
export { a } from "../..";
export { b } from "/";
Expand Down
Loading

0 comments on commit d5bdd2e

Please sign in to comment.