[67] | 1 | package gcss
|
---|
| 2 |
|
---|
| 3 | import (
|
---|
| 4 | "fmt"
|
---|
| 5 | "io"
|
---|
| 6 | "strings"
|
---|
| 7 | )
|
---|
| 8 |
|
---|
| 9 | // variable represents a GCSS variable.
|
---|
| 10 | type variable struct {
|
---|
| 11 | elementBase
|
---|
| 12 | name string
|
---|
| 13 | value string
|
---|
| 14 | }
|
---|
| 15 |
|
---|
| 16 | // WriteTo writes the variable to the writer.
|
---|
| 17 | func (v *variable) WriteTo(w io.Writer) (int64, error) {
|
---|
| 18 | n, err := w.Write([]byte(v.value))
|
---|
| 19 |
|
---|
| 20 | return int64(n), err
|
---|
| 21 | }
|
---|
| 22 |
|
---|
| 23 | // variableNV extracts a variable name and value
|
---|
| 24 | // from the line.
|
---|
| 25 | func variableNV(ln *line) (string, string, error) {
|
---|
| 26 | s := strings.TrimSpace(ln.s)
|
---|
| 27 |
|
---|
| 28 | if !strings.HasPrefix(s, dollarMark) {
|
---|
| 29 | return "", "", fmt.Errorf("variable must start with %q [line: %d]", dollarMark, ln.no)
|
---|
| 30 | }
|
---|
| 31 |
|
---|
| 32 | nv := strings.SplitN(s, space, 2)
|
---|
| 33 |
|
---|
| 34 | if len(nv) < 2 {
|
---|
| 35 | return "", "", fmt.Errorf("variable's name and value should be divided by a space [line: %d]", ln.no)
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | if !strings.HasSuffix(nv[0], colon) {
|
---|
| 39 | return "", "", fmt.Errorf("variable's name should end with a colon [line: %d]", ln.no)
|
---|
| 40 | }
|
---|
| 41 |
|
---|
| 42 | return strings.TrimSuffix(strings.TrimPrefix(nv[0], dollarMark), colon), nv[1], nil
|
---|
| 43 | }
|
---|
| 44 |
|
---|
| 45 | // newVariable creates and returns a variable.
|
---|
| 46 | func newVariable(ln *line, parent element) (*variable, error) {
|
---|
| 47 | name, value, err := variableNV(ln)
|
---|
| 48 |
|
---|
| 49 | if err != nil {
|
---|
| 50 | return nil, err
|
---|
| 51 | }
|
---|
| 52 |
|
---|
| 53 | if strings.HasSuffix(value, semicolon) {
|
---|
| 54 | return nil, fmt.Errorf("variable must not end with %q", semicolon)
|
---|
| 55 | }
|
---|
| 56 |
|
---|
| 57 | return &variable{
|
---|
| 58 | elementBase: newElementBase(ln, parent),
|
---|
| 59 | name: name,
|
---|
| 60 | value: value,
|
---|
| 61 | }, nil
|
---|
| 62 | }
|
---|