Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,47 @@ node.update({

The `update` method reconciles the new content with the existing document, preserving comments, indentation, and spacing.

To merge two documents while preserving comments, use the `merge` method:

```ts

const destinationCode = `{
// Destination pre-foo comment
"foo": "value",
// Destination post-foo comment
"baz": [1, 2, 3]
}
`;

const sourceCode = `{
/* Source pre-bar comment */
"bar": 123, /* Inline comment */
/* Source post-bar comment */
"baz": true /* Another inline comment */
}
`;

const source = JsonParser.parse(sourceCode, JsonObjectNode);
const destination = JsonParser.parse(destinationCode, JsonObjectNode);

console.log(JsonObjectNode.merge(source, destination).toString());
```

Output:

```json5
{
// Destination pre-foo comment
"foo": "value",
/* Source pre-bar comment */
"bar": 123, /* Inline comment */
/* Source post-bar comment */
"baz": true /* Another inline comment */
}
```

The `merge` method removes any existing destination properties that clash with source, along with their leading/trailing trivia, to avoid duplicate keys.

## Contributing

Contributions are welcome!
Expand Down
160 changes: 160 additions & 0 deletions src/node/objectNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ import {JsonPrimitiveNode, JsonStringNode} from './primitiveNode';
import {JsonValueFactory} from './factory';
import {JsonIdentifierNode} from './identifierNode';
import {JsonError} from '../error';
import {NodeMatcher} from '../manipulator';
import {JsonTokenNode} from './tokenNode';
import {JsonTokenType} from '../token';
import INSIGNIFICANT = NodeMatcher.INSIGNIFICANT;
import NEWLINE = NodeMatcher.NEWLINE;
import SIGNIFICANT = NodeMatcher.SIGNIFICANT;
import SPACE = NodeMatcher.SPACE;

export interface JsonObjectDefinition extends JsonCompositeDefinition {
readonly properties: readonly JsonPropertyNode[];
Expand All @@ -33,6 +40,159 @@ export class JsonObjectNode extends JsonStructureNode implements JsonCompositeDe
});
}

public merge(source: JsonObjectNode): void {
if (source.propertyNodes.length === 0) {
return;
}

if (this.propertyNodes.length === 0) {
this.propertyNodes.push(...source.propertyNodes.map(property => property.clone()));
this.children.splice(0, this.children.length, ...source.children.map(child => child.clone()));

return;
}

for (const property of source.propertyNodes) {
const key = property.key.toJSON();
const sourceRange = source.findPropertyRange(key);

let sourceChildren: JsonNode[] = [property];

if (sourceRange !== null) {
sourceChildren = source.children.slice(sourceRange[0], sourceRange[1] + 1);
}

const newProperty = property.clone();

sourceChildren = sourceChildren.map(node => (node === property ? newProperty : node.clone()));

const range = this.findPropertyRange(key);

if (range === null) {
this.propertyNodes.push(newProperty);
this.insert(sourceChildren);

continue;
}

const currentIndex = this.propertyNodes.findIndex(candidate => candidate.key.toJSON() === key);

this.propertyNodes.splice(currentIndex, 1, newProperty);
this.children.splice(range[0], range[1] - range[0] + 1, ...sourceChildren);
}
}

private insert(nodes: JsonNode[]): void {
let insertionIndex = this.children.length;

for (let index = this.children.length - 1; index >= 0; index--) {
const child = this.children[index];

if (child instanceof JsonTokenNode) {
if (child.isType(JsonTokenType.BRACE_RIGHT)) {
insertionIndex = index;

continue;
}

if (child.isType(JsonTokenType.COMMA)) {
insertionIndex = index + 1;

break;
}
}

if (SIGNIFICANT(child)) {
break;
}

if (NEWLINE(child)) {
while (index > 0 && SPACE(this.children[index - 1])) {
index--;
}

insertionIndex = index;

break;
}

insertionIndex = index;
}

let needsComma = false;

for (let index = insertionIndex - 1; index >= 0; index--) {
const child = this.children[index];

if (child instanceof JsonTokenNode) {
if (child.isType(JsonTokenType.COMMA)) {
needsComma = false;

break;
}
}

if (SIGNIFICANT(child)) {
needsComma = true;

break;
}
}

if (needsComma) {
this.children.splice(insertionIndex, 0, new JsonTokenNode({
type: JsonTokenType.COMMA,
value: ',',
}));

insertionIndex++;
}

this.children.splice(insertionIndex, 0, ...nodes);
}

private findPropertyRange(name: string): [number, number] | null {
let startIndex = this.children.findIndex(
node => node instanceof JsonPropertyNode && node.key.toJSON() === name,
);

if (startIndex === -1) {
return null;
}

let endIndex = startIndex;

for (let lookBehind = startIndex - 1; lookBehind >= 0; lookBehind--) {
const child = this.children[lookBehind];

if (!INSIGNIFICANT(child)) {
break;
}

if (NEWLINE(child)) {
startIndex = lookBehind;
}
}

for (let lookAhead = endIndex + 1; lookAhead < this.children.length; lookAhead++) {
const child = this.children[lookAhead];

if (!(child instanceof JsonTokenNode) || (SIGNIFICANT(child) && !child.isType(JsonTokenType.COMMA))) {
break;
}

if (NEWLINE(child)) {
endIndex = lookAhead - 1;

break;
}

endIndex = lookAhead;
}

return [startIndex, endIndex];
}

public update(other: JsonValueNode|JsonValue): JsonValueNode {
if (!(other instanceof JsonValueNode)) {
if (typeof other !== 'object' || other === null || Array.isArray(other)) {
Expand Down
Loading
Loading