UNPKG

3.1 kBJavaScriptView Raw
1/*
2 * Licensed under the Apache License, Version 2.0 (the "License");
3 * you may not use this file except in compliance with the License.
4 * You may obtain a copy of the License at
5 *
6 * http://www.apache.org/licenses/LICENSE-2.0
7 *
8 * Unless required by applicable law or agreed to in writing, software
9 * distributed under the License is distributed on an "AS IS" BASIS,
10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 * See the License for the specific language governing permissions and
12 * limitations under the License.
13 */
14
15'use strict';
16
17/**
18 * Writer buffers text to be written in memory. It handles simple
19 * indentation and tracks the number of lines written.
20 * @private
21 * @class
22 * @memberof module:concerto-core
23 */
24class Writer {
25
26 /**
27 * Create a Writer.
28 *
29 */
30 constructor() {
31 this.beforeBuffer = '';
32 this.buffer = '';
33 this.linesWritten = 0;
34 }
35
36 /**
37 * Writes text to the start of the buffer
38 * @param {int} tabs - the number of tabs to use
39 * @param {string} text - the text to write
40 */
41 writeBeforeLine(tabs,text) {
42 for(let n=0; n < tabs; n++) {
43 this.beforeBuffer += ' ';
44 }
45 this.beforeBuffer += text;
46 this.beforeBuffer += '\n';
47 this.linesWritten++;
48 }
49
50 /**
51 * Append text to the buffer
52 * @param {int} tabs - the number of tabs to use
53 * @param {string} text - the text to write
54 */
55 writeLine(tabs,text) {
56 for(let n=0; n < tabs; n++) {
57 this.write(' ');
58 }
59 this.write(text);
60 this.write('\n');
61 this.linesWritten++;
62 }
63
64 /**
65 * Returns the number of lines that have been written to the buffer.
66 * @return {int} the number of lines written to the buffer.
67 */
68 getLineCount() {
69 return this.linesWritten;
70 }
71
72
73 /**
74 * Append text to the buffer, prepending tabs
75 * @param {int} tabs - the number of tabs to use
76 * @param {string} text - the text to write
77 */
78 writeIndented(tabs,text) {
79 for(let n=0; n < tabs; n++) {
80 this.write(' ');
81 }
82 this.write(text);
83 }
84
85 /**
86 * Append text to the buffer (no automatic newline). The
87 * text may contain newline, and these will increment the linesWritten
88 * counter.
89 * @param {string} msg - the text to write
90 */
91 write(msg) {
92 if(typeof msg !== 'string' ) {
93 throw new Error('Can only append strings. Argument ' + msg + ' has type ' + typeof msg);
94 }
95
96 this.buffer += msg;
97 this.linesWritten += msg.split(/\r\n|\r|\n/).length;
98 }
99
100 /**
101 * Returns the text that has been buffered in this Writer.
102 * @return {string} the buffered text.
103 */
104 getBuffer() {
105 return this.beforeBuffer + this.buffer;
106 }
107
108 /**
109 * Empties the underyling buffer and resets the line count.
110 */
111 clearBuffer() {
112 this.beforeBuffer = '';
113 this.buffer = '';
114 this.linesWritten = 0;
115 }
116}
117
118module.exports = Writer;