UNPKG

3.18 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ReplaceChange = exports.RemoveChange = exports.InsertChange = exports.NoopChange = void 0;
4/**
5 * An operation that does nothing.
6 */
7class NoopChange {
8 constructor() {
9 this.description = 'No operation.';
10 this.order = Infinity;
11 this.path = null;
12 }
13 apply() { return Promise.resolve(); }
14}
15exports.NoopChange = NoopChange;
16/**
17 * Will add text to the source code.
18 */
19class InsertChange {
20 constructor(path, pos, toAdd) {
21 this.path = path;
22 this.pos = pos;
23 this.toAdd = toAdd;
24 if (pos < 0) {
25 throw new Error('Negative positions are invalid');
26 }
27 this.description = `Inserted ${toAdd} into position ${pos} of ${path}`;
28 this.order = pos;
29 }
30 /**
31 * This method does not insert spaces if there is none in the original string.
32 */
33 apply(host) {
34 return host.read(this.path).then(content => {
35 const prefix = content.substring(0, this.pos);
36 const suffix = content.substring(this.pos);
37 return host.write(this.path, `${prefix}${this.toAdd}${suffix}`);
38 });
39 }
40}
41exports.InsertChange = InsertChange;
42/**
43 * Will remove text from the source code.
44 */
45class RemoveChange {
46 constructor(path, pos, toRemove) {
47 this.path = path;
48 this.pos = pos;
49 this.toRemove = toRemove;
50 if (pos < 0) {
51 throw new Error('Negative positions are invalid');
52 }
53 this.description = `Removed ${toRemove} into position ${pos} of ${path}`;
54 this.order = pos;
55 }
56 apply(host) {
57 return host.read(this.path).then(content => {
58 const prefix = content.substring(0, this.pos);
59 const suffix = content.substring(this.pos + this.toRemove.length);
60 // TODO: throw error if toRemove doesn't match removed string.
61 return host.write(this.path, `${prefix}${suffix}`);
62 });
63 }
64}
65exports.RemoveChange = RemoveChange;
66/**
67 * Will replace text from the source code.
68 */
69class ReplaceChange {
70 constructor(path, pos, oldText, newText) {
71 this.path = path;
72 this.pos = pos;
73 this.oldText = oldText;
74 this.newText = newText;
75 if (pos < 0) {
76 throw new Error('Negative positions are invalid');
77 }
78 this.description = `Replaced ${oldText} into position ${pos} of ${path} with ${newText}`;
79 this.order = pos;
80 }
81 apply(host) {
82 return host.read(this.path).then(content => {
83 const prefix = content.substring(0, this.pos);
84 const suffix = content.substring(this.pos + this.oldText.length);
85 const text = content.substring(this.pos, this.pos + this.oldText.length);
86 if (text !== this.oldText) {
87 return Promise.reject(new Error(`Invalid replace: "${text}" != "${this.oldText}".`));
88 }
89 // TODO: throw error if oldText doesn't match removed string.
90 return host.write(this.path, `${prefix}${this.newText}${suffix}`);
91 });
92 }
93}
94exports.ReplaceChange = ReplaceChange;