Skip to content

Commit

Permalink
feat: #154 - Configuration for spaces surrounding named imports and e…
Browse files Browse the repository at this point in the history
…xports.

Named imports and exports are now written with a surrounding space. Set the `insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces` manipulation setting to false to disable this behaviour.
  • Loading branch information
dsherret committed Mar 25, 2018
1 parent 4da80ba commit 76ce4ad
Show file tree
Hide file tree
Showing 53 changed files with 482 additions and 222 deletions.
12 changes: 12 additions & 0 deletions docs/manipulation/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,15 @@ project.manipulationSettings.set({
indentationText: IndentationText.TwoSpaces
});
```

### Formatting

There are some additional manipulation settings that are taken from the `ts.FormatCodeSettings`.
They will slowly be supported and added to the manipulation settings. For example:

```ts
project.manipulationSettings.set({
// only one for now... will add more in the future
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: false // default: true
});
```
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
},
"dependencies": {
"@dsherret/to-absolute-glob": "^2.0.2",
"code-block-writer": "^6.6.0",
"code-block-writer": "^6.7.0",
"globby": "^6.1.0",
"multimatch": "^2.1.0",
"object-assign": "^4.1.1",
Expand Down
3 changes: 2 additions & 1 deletion scripts/common/getProject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ export function getProject() {
tsConfigFilePath: path.join(rootFolder, "tsconfig.json"),
addFilesFromTsConfig: false,
manipulationSettings: {
newLineKind: NewLineKind.CarriageReturnLineFeed
newLineKind: NewLineKind.CarriageReturnLineFeed,
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: false
}
});
project.addExistingSourceFiles(path.join(rootFolder, "src/**/*{.d.ts,.ts}"));
Expand Down
7 changes: 7 additions & 0 deletions src/GlobalContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ export class GlobalContainer {
return this.compilerOptions.get().charset || "utf-8";
}

/**
* Helper for getting the format code settings.
*/
getFormatCodeSettings() {
return this.manipulationSettings.getFormatCodeSettings();
}

/**
* Resets the program.
*/
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/base/ArgumentedNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export function ArgumentedNode<T extends Constructor<ArgumentedNodeExtensionType
parent: this.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken).getNextSiblingIfKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: args,
insertIndex: index,
newTexts: argumentTexts
newText: argumentTexts.join(", ")
});

return getNodesToReturn(this.getArguments(), index, argumentTexts.length);
Expand Down
10 changes: 8 additions & 2 deletions src/compiler/base/ExtendsClauseableNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {Constructor} from "../../Constructor";
import {getNodeOrNodesToReturn, insertIntoCommaSeparatedNodes, verifyAndGetIndex, insertIntoCreatableSyntaxList} from "../../manipulation";
import * as errors from "../../errors";
import {ExtendsClauseableNodeStructure} from "../../structures";
import {CommaSeparatedStructuresToText, StringStructureToText} from "../../structureToTexts";
import {callBaseFill} from "../callBaseFill";
import {Node} from "../common";
import {HeritageClause} from "../general";
Expand Down Expand Up @@ -73,6 +74,11 @@ export function ExtendsClauseableNode<T extends Constructor<ExtendsClauseableNod
return [];
}

const writer = this.getWriterWithQueuedChildIndentation();
const structureToText = new CommaSeparatedStructuresToText(writer, new StringStructureToText(writer));

structureToText.writeText(texts);

const extendsTypes = this.getExtends();
index = verifyAndGetIndex(index, extendsTypes.length);

Expand All @@ -82,15 +88,15 @@ export function ExtendsClauseableNode<T extends Constructor<ExtendsClauseableNod
parent: extendsClause.getFirstChildByKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: extendsTypes,
insertIndex: index,
newTexts: texts
newText: writer.toString()
});
return getNodeOrNodesToReturn(this.getExtends(), index, length);
}

const openBraceToken = this.getFirstChildByKindOrThrow(SyntaxKind.OpenBraceToken);
const openBraceStart = openBraceToken.getStart();
const isLastSpace = /\s/.test(this.getSourceFile().getFullText()[openBraceStart - 1]);
let insertText = `extends ${texts.join(", ")} `;
let insertText = `extends ${writer.toString()} `;
if (!isLastSpace)
insertText = " " + insertText;

Expand Down
10 changes: 8 additions & 2 deletions src/compiler/base/ImplementsClauseableNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {ts, SyntaxKind} from "../../typescript";
import {Constructor} from "../../Constructor";
import {getNodeOrNodesToReturn, insertIntoCommaSeparatedNodes, verifyAndGetIndex, insertIntoCreatableSyntaxList} from "../../manipulation";
import {ImplementsClauseableNodeStructure} from "../../structures";
import {CommaSeparatedStructuresToText, StringStructureToText} from "../../structureToTexts";
import {callBaseFill} from "../callBaseFill";
import * as errors from "../../errors";
import {Node} from "../common";
Expand Down Expand Up @@ -73,6 +74,11 @@ export function ImplementsClauseableNode<T extends Constructor<ImplementsClausea
return [];
}

const writer = this.getWriterWithQueuedChildIndentation();
const structureToText = new CommaSeparatedStructuresToText(writer, new StringStructureToText(writer));

structureToText.writeText(texts);

const heritageClauses = this.getHeritageClauses();
const implementsTypes = this.getImplements();
index = verifyAndGetIndex(index, implementsTypes.length);
Expand All @@ -83,15 +89,15 @@ export function ImplementsClauseableNode<T extends Constructor<ImplementsClausea
parent: implementsClause.getFirstChildByKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: implementsTypes,
insertIndex: index,
newTexts: texts
newText: writer.toString()
});
return getNodeOrNodesToReturn(this.getImplements(), index, length);
}

const openBraceToken = this.getFirstChildByKindOrThrow(SyntaxKind.OpenBraceToken);
const openBraceStart = openBraceToken.getStart();
const isLastSpace = /\s/.test(this.getSourceFile().getFullText()[openBraceStart - 1]);
let insertText = `implements ${texts.join(", ")} `;
let insertText = `implements ${writer.toString()} `;
if (!isLastSpace)
insertText = " " + insertText;

Expand Down
15 changes: 6 additions & 9 deletions src/compiler/base/ParameteredNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {Constructor} from "../../Constructor";
import * as errors from "../../errors";
import {insertIntoCommaSeparatedNodes, verifyAndGetIndex, getEndIndexFromArray, getNodesToReturn} from "../../manipulation";
import {ParameterDeclarationStructure, ParameteredNodeStructure} from "../../structures";
import {ParameterDeclarationStructureToText} from "../../structureToTexts";
import {ParameterDeclarationStructureToText, CommaSeparatedStructuresToText} from "../../structureToTexts";
import {callBaseFill} from "../callBaseFill";
import {ArrayUtils, getNodeByNameOrFindFunction, getNotFoundErrorMessageForNameOrFindFunction} from "../../utils";
import {Node} from "../common";
Expand Down Expand Up @@ -94,19 +94,16 @@ export function ParameteredNode<T extends Constructor<ParameteredNodeExtensionTy
const syntaxList = this.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken).getNextSiblingIfKindOrThrow(SyntaxKind.SyntaxList);
index = verifyAndGetIndex(index, parameters.length);

const newTexts = structures.map(s => {
// todo: pass the structure to text to the function below
const writer = this.getWriter();
const structureToText = new ParameterDeclarationStructureToText(writer);
structureToText.writeText(s);
return writer.toString();
});
const writer = this.getWriterWithQueuedChildIndentation();
const structureToText = new CommaSeparatedStructuresToText(writer, new ParameterDeclarationStructureToText(writer));

structureToText.writeText(structures);

insertIntoCommaSeparatedNodes({
parent: syntaxList,
currentNodes: parameters,
insertIndex: index,
newTexts
newText: writer.toString()
});

const newParameters = getNodesToReturn(this.getParameters(), index, structures.length);
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/base/TypeArgumentedNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export function TypeArgumentedNode<T extends Constructor<TypeArgumentedNodeExten
parent: this.getFirstChildByKindOrThrow(SyntaxKind.LessThanToken).getNextSiblingIfKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: typeArguments,
insertIndex: index,
newTexts: argumentTexts
newText: argumentTexts.join(", ")
});
}

Expand Down
17 changes: 7 additions & 10 deletions src/compiler/base/TypeParameteredNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as errors from "../../errors";
import {insertIntoCommaSeparatedNodes, getEndIndexFromArray, verifyAndGetIndex, insertIntoParentTextRange,
getNodesToReturn} from "../../manipulation";
import {TypeParameteredNodeStructure, TypeParameterDeclarationStructure} from "../../structures";
import {CommaSeparatedStructuresToText, TypeParameterDeclarationStructureToText} from "../../structureToTexts";
import {ArrayUtils, getNodeByNameOrFindFunction, getNotFoundErrorMessageForNameOrFindFunction, TypeGuards} from "../../utils";
import {callBaseFill} from "../callBaseFill";
import {NamedNode} from "../base";
Expand Down Expand Up @@ -95,22 +96,25 @@ export function TypeParameteredNode<T extends Constructor<TypeParameteredNodeExt
return [];

const typeParameters = this.getTypeParameters();
const typeParamCodes = structures.map(s => getStructureCode(s));
const writer = this.getWriterWithQueuedChildIndentation();
const structureToText = new CommaSeparatedStructuresToText(writer, new TypeParameterDeclarationStructureToText(writer));
index = verifyAndGetIndex(index, typeParameters.length);

structureToText.writeText(structures);

if (typeParameters.length === 0) {
insertIntoParentTextRange({
insertPos: getInsertPos(this),
parent: this,
newText: `<${typeParamCodes.join(", ")}>`
newText: `<${writer.toString()}>`
});
}
else {
insertIntoCommaSeparatedNodes({
parent: this.getFirstChildByKindOrThrow(SyntaxKind.LessThanToken).getNextSiblingIfKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: typeParameters,
insertIndex: index,
newTexts: typeParamCodes
newText: writer.toString()
});
}

Expand All @@ -128,13 +132,6 @@ export function TypeParameteredNode<T extends Constructor<TypeParameteredNodeExt
};
}

function getStructureCode(structure: TypeParameterDeclarationStructure) {
let code = structure.name;
if (structure.constraint != null && structure.constraint.length > 0)
code += ` extends ${structure.constraint}`;
return code;
}

function getInsertPos(node: TypeParameteredNode & Node) {
const namedNode = node as any as (NamedNode & Node);
if (namedNode.getNameNode != null)
Expand Down
15 changes: 6 additions & 9 deletions src/compiler/enum/EnumDeclaration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {ts, SyntaxKind} from "../../typescript";
import * as errors from "../../errors";
import {EnumMemberStructure, EnumDeclarationStructure} from "../../structures";
import {insertIntoCommaSeparatedNodes, verifyAndGetIndex, getNodesToReturn} from "../../manipulation";
import {EnumMemberStructureToText} from "../../structureToTexts";
import {EnumMemberStructureToText, CommaNewLineSeparatedStructuresToText} from "../../structureToTexts";
import {getNodeByNameOrFindFunction, getNotFoundErrorMessageForNameOrFindFunction, TypeGuards} from "../../utils";
import {callBaseFill} from "../callBaseFill";
import {NamedNode, ExportableNode, ModifierableNode, AmbientableNode, JSDocableNode, TextInsertableNode, ChildOrderableNode} from "../base";
Expand Down Expand Up @@ -68,20 +68,17 @@ export class EnumDeclaration extends EnumDeclarationBase<ts.EnumDeclaration> {
return [];

// create member code
const newTexts = structures.map(s => {
// todo: pass in the StructureToText to the function below
const writer = this.getWriterWithChildIndentation();
const structureToText = new EnumMemberStructureToText(writer);
structureToText.writeText(s);
return writer.toString();
});
// todo: pass in the StructureToText to the function below
const writer = this.getWriterWithChildIndentation();
const structureToText = new CommaNewLineSeparatedStructuresToText(writer, new EnumMemberStructureToText(writer));
structureToText.writeText(structures);

// insert
insertIntoCommaSeparatedNodes({
parent: this.getChildSyntaxListOrThrow(),
currentNodes: members,
insertIndex: index,
newTexts,
newText: writer.toString(),
useNewLines: true
});

Expand Down
23 changes: 12 additions & 11 deletions src/compiler/expression/array/ArrayLiteralExpression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {ts, SyntaxKind} from "../../../typescript";
import CodeBlockWriter from "code-block-writer";
import * as errors from "../../../errors";
import {insertIntoCommaSeparatedNodes, verifyAndGetIndex, removeCommaSeparatedChild, getNodesToReturn} from "../../../manipulation";
import {CommaNewLineSeparatedStructuresToText, CommaSeparatedStructuresToText, StringStructureToText} from "../../../structureToTexts";
import {Expression} from "../Expression";
import {PrimaryExpression} from "../PrimaryExpression";

Expand Down Expand Up @@ -60,22 +61,22 @@ export class ArrayLiteralExpression extends PrimaryExpression<ts.ArrayLiteralExp
index = verifyAndGetIndex(index, elements.length);
const useNewLines = getUseNewLines(this);

if (textsOrWriterFunction instanceof Function) {
const writer = this.getWriterWithChildIndentation();
textsOrWriterFunction(writer);
return insertTexts(this, [writer.toString()]);
}
else {
const childIndentationText = useNewLines ? this.getChildIndentationText() : "";
return insertTexts(this, textsOrWriterFunction.map(t => childIndentationText + t));
}
const writer = useNewLines ? this.getWriterWithChildIndentation() : this.getWriterWithQueuedChildIndentation();
const stringStructureToText = new StringStructureToText(writer);
const structureToText = useNewLines ?
new CommaNewLineSeparatedStructuresToText(writer, stringStructureToText) :
new CommaSeparatedStructuresToText(writer, stringStructureToText);

structureToText.writeText(textsOrWriterFunction instanceof Function ? [textsOrWriterFunction] : textsOrWriterFunction);

return insertTexts(this);

function insertTexts(node: ArrayLiteralExpression, newTexts: string[]) {
function insertTexts(node: ArrayLiteralExpression) {
insertIntoCommaSeparatedNodes({
parent: node.getFirstChildByKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: elements,
insertIndex: index,
newTexts,
newText: writer.toString(),
useNewLines
});

Expand Down
16 changes: 7 additions & 9 deletions src/compiler/expression/object/ObjectLiteralExpression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import * as errors from "../../../errors";
import {ArrayUtils} from "../../../utils";
import {verifyAndGetIndex, insertIntoCommaSeparatedNodes, getNodesToReturn} from "../../../manipulation";
import {StructureToText, PropertyAssignmentStructureToText, ShorthandPropertyAssignmentStructureToText, SpreadAssignmentStructureToText,
MethodDeclarationStructureToText, GetAccessorDeclarationStructureToText, SetAccessorDeclarationStructureToText} from "../../../structureToTexts";
MethodDeclarationStructureToText, GetAccessorDeclarationStructureToText, SetAccessorDeclarationStructureToText,
CommaNewLineSeparatedStructuresToText} from "../../../structureToTexts";
import {PropertyAssignmentStructure, ShorthandPropertyAssignmentStructure, SpreadAssignmentStructure,
MethodDeclarationStructure, GetAccessorDeclarationStructure, SetAccessorDeclarationStructure} from "../../../structures";
import {ObjectLiteralElementLike} from "../../aliases";
Expand Down Expand Up @@ -287,19 +288,16 @@ export class ObjectLiteralExpression extends ObjectLiteralExpressionBase<ts.Obje
*/
private _insertProperty<T>(index: number, structures: T[], createStructureToText: (writer: CodeBlockWriter) => StructureToText<T>) {
index = verifyAndGetIndex(index, this.compilerNode.properties.length);
const newTexts = structures.map(s => {
// todo: pass in the StructureToText to the function below
const writer = this.getWriterWithChildIndentation();
const structureToText = createStructureToText(writer);
structureToText.writeText(s);
return writer.toString();
});
const writer = this.getWriterWithChildIndentation();
const structureToText = new CommaNewLineSeparatedStructuresToText(writer, createStructureToText(writer));

structureToText.writeText(structures);

insertIntoCommaSeparatedNodes({
parent: this.getFirstChildByKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: this.getProperties(),
insertIndex: index,
newTexts,
newText: writer.toString(),
useNewLines: true
});

Expand Down
19 changes: 9 additions & 10 deletions src/compiler/file/ExportDeclaration.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {ts, SyntaxKind} from "../../typescript";
import * as errors from "../../errors";
import {ExportSpecifierStructure} from "../../structures";
import {NamedImportExportSpecifierStructureToText} from "../../structureToTexts";
import {insertIntoParentTextRange, verifyAndGetIndex, insertIntoCommaSeparatedNodes, getNodesToReturn} from "../../manipulation";
import {ArrayUtils, TypeGuards, ModuleUtils} from "../../utils";
import {Identifier} from "../common";
Expand Down Expand Up @@ -165,33 +166,31 @@ export class ExportDeclaration extends Statement<ts.ExportDeclaration> {
return [];

const namedExports = this.getNamedExports();
const codes = structuresOrNames.map(s => {
if (typeof s === "string")
return s;
let text = s.name;
if (s.alias != null && s.alias.length > 0)
text += ` as ${s.alias}`;
return text;
});
const writer = this.getWriterWithQueuedChildIndentation();
const namedExportStructureToText = new NamedImportExportSpecifierStructureToText(writer, this.global.getFormatCodeSettings());

index = verifyAndGetIndex(index, namedExports.length);

if (namedExports.length === 0) {
namedExportStructureToText.writeTextsWithBraces(structuresOrNames);
const asteriskToken = this.getFirstChildByKindOrThrow(SyntaxKind.AsteriskToken);
insertIntoParentTextRange({
insertPos: asteriskToken.getStart(),
parent: this,
newText: `{${codes.join(", ")}}`,
newText: writer.toString(),
replacing: {
textLength: 1
}
});
}
else {
namedExportStructureToText.writeTexts(structuresOrNames);
insertIntoCommaSeparatedNodes({
parent: this.getFirstChildByKindOrThrow(SyntaxKind.NamedExports).getFirstChildByKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: namedExports,
insertIndex: index,
newTexts: codes
newText: writer.toString(),
surroundWithSpaces: this.global.getFormatCodeSettings().insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces
});
}

Expand Down

0 comments on commit 76ce4ad

Please sign in to comment.