UNPKG

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