File: writer.go

package info (click to toggle)
golang-github-tideland-golib 4.24.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,144 kB
  • sloc: makefile: 4
file content (313 lines) | stat: -rw-r--r-- 7,464 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// Tideland Go Library - Simple Markup Language - Writer
//
// Copyright (C) 2009-2017 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.

package sml

//--------------------
// IMPORTS
//--------------------

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"io"
	"strings"

	"github.com/tideland/golib/errors"
)

//--------------------
// SML WRITER
//--------------------

// WriterProcessor a processor
type WriterProcessor interface {
	// WriterProcessor is a processor itself.
	Processor

	// SetContext sets the writer context.
	SetContext(ctx *WriterContext)
}

// WriterProcessors is a map of processors that can be plugged
// into the used SML writer. The key is the first part of each
// tag.
type WriterProcessors map[string]WriterProcessor

// WriterContext controls the parameters of a writing.
type WriterContext struct {
	plugins     WriterProcessors
	writer      io.Writer
	prettyPrint bool
	indentStr   string
}

// NewWriterContext creates a new writer context.
func NewWriterContext(wp WriterProcessor, w io.Writer, pretty bool, indentStr string) *WriterContext {
	ctx := &WriterContext{
		plugins:     WriterProcessors{"": wp},
		writer:      w,
		prettyPrint: pretty,
		indentStr:   indentStr,
	}
	wp.SetContext(ctx)
	return ctx
}

// Register adds a writer processor which will be responsible for
// processing if the tag is matching.
func (ctx *WriterContext) Register(tag string, wp WriterProcessor) error {
	if _, ok := ctx.plugins[tag]; ok {
		return errors.New(ErrRegisteredPlugin, errorMessages, tag)
	}
	wp.SetContext(ctx)
	ctx.plugins[tag] = wp
	return nil
}

// Writef writes a formatted string to the writer.
func (ctx *WriterContext) Writef(format string, args ...interface{}) error {
	_, err := fmt.Fprintf(ctx.writer, format, args...)
	return err
}

// mlWriter writes it to an io.Writer.
type mlWriter struct {
	context *WriterContext
	stack   []WriterProcessor
	indent  int
}

// WriteSML uses one WriterProcessor and possible more as plugins to write the
// SML node to the passed writer. The prettyPrint flag controls if the writing
// is in a more beautiful formatted way.
func WriteSML(node Node, ctx *WriterContext) error {
	wp := ctx.plugins[""]
	if wp == nil {
		return errors.New(ErrNoRootProcessor, errorMessages)
	}
	w := &mlWriter{
		context: ctx,
		stack:   []WriterProcessor{wp},
		indent:  0,
	}
	// Process the node with the new writer.
	if err := node.ProcessWith(w); err != nil {
		return err
	}
	return nil
}

// OpenTag writes the opening of a tag.
func (w *mlWriter) OpenTag(tag []string) error {
	w.activatePlugin(tag[0])
	w.writeIndent(true)
	if err := w.activePlugin().OpenTag(tag); err != nil {
		return err
	}
	w.writeNewline()
	w.indent++
	return nil
}

// CloseTag writes the closing of a tag.
func (w *mlWriter) CloseTag(tag []string) error {
	w.indent--
	w.writeIndent(false)
	if err := w.activePlugin().CloseTag(tag); err != nil {
		return err
	}
	w.writeNewline()
	// Check if a plugin is to deactivate.
	if len(w.stack) > 1 {
		w.deactivatePlugin()
	}
	return nil
}

// Text writes a text with an encoding of special runes.
func (w *mlWriter) Text(text string) error {
	w.writeIndent(true)
	if err := w.activePlugin().Text(text); err != nil {
		return err
	}
	w.writeNewline()
	return nil
}

// Raw writes raw data without any encoding.
func (w *mlWriter) Raw(raw string) error {
	w.writeIndent(true)
	if err := w.activePlugin().Raw(raw); err != nil {
		return err
	}
	w.writeNewline()
	return nil
}

// Comment writes comment data without any encoding.
func (w *mlWriter) Comment(comment string) error {
	w.writeIndent(true)
	if err := w.activePlugin().Comment(comment); err != nil {
		return err
	}
	w.writeNewline()
	return nil
}

// activatePlugin activates a new one of the
// registered plugins.
func (w *mlWriter) activatePlugin(tag string) {
	if p := w.context.plugins[tag]; p != nil {
		w.stack = append(w.stack, p)
	}
}

// deactivatePlugin deactivates the top plugin.
func (w *mlWriter) deactivatePlugin() {
	w.stack = w.stack[:len(w.stack)-1]
}

// activePlugin returns the current active plugin.
func (w *mlWriter) activePlugin() WriterProcessor {
	return w.stack[len(w.stack)-1]
}

// writeIndent writes an indentation if wanted.
func (w *mlWriter) writeIndent(open bool) {
	if w.context.prettyPrint {
		for i := 0; i < w.indent; i++ {
			w.context.Writef(w.context.indentStr)
		}
	} else if open {
		w.context.Writef(" ")
	}
}

// writeNewline writes a newline if wanted.
func (w *mlWriter) writeNewline() {
	if w.context.prettyPrint {
		w.context.Writef("\n")
	}
}

//--------------------
// STANDARD SML WRITER PROCESSOR
//--------------------

// standardSMLWriter writes a SML document in its standard
// notation to a writer.
type standardSMLWriter struct {
	context *WriterContext
}

// NewStandardSMLWriter creates a new writer for a ML
// document in standard notation.
func NewStandardSMLWriter() WriterProcessor {
	return &standardSMLWriter{}
}

// SetContext sets the writer context.
func (w *standardSMLWriter) SetContext(ctx *WriterContext) {
	w.context = ctx
}

// OpenTag writes the opening of a tag.
func (w *standardSMLWriter) OpenTag(tag []string) error {
	return w.context.Writef("{%s", strings.Join(tag, ":"))
}

// CloseTag writes the closing of a tag.
func (w *standardSMLWriter) CloseTag(tag []string) error {
	return w.context.Writef("}")
}

// Text writes a text with an encoding of special runes.
func (w *standardSMLWriter) Text(text string) error {
	var buf bytes.Buffer
	for _, r := range text {
		switch r {
		case '^':
			buf.WriteString("^^")
		case '{':
			buf.WriteString("^{")
		case '}':
			buf.WriteString("^}")
		default:
			buf.WriteRune(r)
		}
	}
	return w.context.Writef(buf.String())
}

// Raw writes raw data without any encoding.
func (w *standardSMLWriter) Raw(raw string) error {
	return w.context.Writef("{! %s !}", raw)
}

// Comment writes comment data without any encoding.
func (w *standardSMLWriter) Comment(comment string) error {
	return w.context.Writef("{# %s #}", comment)
}

//--------------------
// XML WRITER PROCESSOR
//--------------------

// xmlWriter writes a ML document in XML notation.
type xmlWriter struct {
	context *WriterContext
	rawTag  string
}

// NewXMLWriter creates a new writer for a ML
// document in XML notation.
func NewXMLWriter(rawTag string) WriterProcessor {
	return &xmlWriter{
		rawTag: rawTag,
	}
}

// SetContext sets the writer context.
func (w *xmlWriter) SetContext(ctx *WriterContext) {
	w.context = ctx
}

// OpenTag writes the opening of a tag.
func (w *xmlWriter) OpenTag(tag []string) error {
	w.context.Writef("<%s", tag[0])
	if len(tag) > 1 {
		w.context.Writef(" id=%q", tag[1])
	}
	if len(tag) > 2 {
		w.context.Writef(" class=%q", tag[2])
	}
	return w.context.Writef(">")
}

// CloseTag writes the closing of a tag.
func (w *xmlWriter) CloseTag(tag []string) error {
	return w.context.Writef("</%s>", tag[0])
}

// Text writes a text with an encoding of special runes.
func (w *xmlWriter) Text(text string) error {
	return xml.EscapeText(w.context.writer, []byte(text))
}

// Raw writes raw data without any encoding.
func (w *xmlWriter) Raw(raw string) error {
	return w.context.Writef("<%s>%s</%s>", w.rawTag, raw, w.rawTag)
}

// Comment writes comment data without any encoding.
func (w *xmlWriter) Comment(comment string) error {
	return w.context.Writef("<!-- %s -->", comment)
}

// EOF