tabsep.go 2 KB
Newer Older
Ma_124's avatar
Ma_124 committed
1 2 3 4 5 6 7 8
package awesomefw

import (
	"fmt"
	"io"
	"strings"
)

Ma_124's avatar
Ma_124 committed
9 10 11 12 13 14 15 16 17 18
// Parses the code according to this pattern:
//   <name>\t<url>\t<desc>
//   "literal line
//   'literal without newline
//   " continuation of previous line
//    """
//   block literal
//   which spans over
//   multiple lines
//   """
Ma_124's avatar
Ma_124 committed
19 20 21
var IFFTabSep = &InputFileFormat{parseTabSepLine}

func parseTabSepLine(out io.Writer, l string, outFF *OutputFileFormat, ctx *Ctx) {
Ma_124's avatar
Ma_124 committed
22 23 24 25
	if ctx.InFFCtx["tabsep--in-literal"] == nil {
		ctx.InFFCtx["tabsep--in-literal"] = false
	}

Ma_124's avatar
Ma_124 committed
26
	if l == "\"\"\"\n" || l == "\"\"\"\r\n" { // Start literal block
Ma_124's avatar
Ma_124 committed
27
		ctx.InFFCtx["tabsep--in-literal"] = !ctx.InFFCtx["tabsep--in-literal"].(bool)
Ma_124's avatar
Ma_124 committed
28 29 30
		return
	}

Ma_124's avatar
Ma_124 committed
31
	if ctx.InFFCtx["tabsep--in-literal"].(bool) {
Ma_124's avatar
Ma_124 committed
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
		outFF.Literal(out, l, ctx)
		return
	}

	if len(l) == 1 {
		return
	}

	if l[0] == '"' { // Start line literal
		outFF.Literal(out, l[1:], ctx)
		return
	}

	if l[0] == '\'' { // Start line literal without newline
		outFF.Literal(out, strings.TrimLeft(l[1:len(l)-1], "\r\n"), ctx)
		return
	}

	l = l[:len(l)-1]

	lps := strings.SplitN(l, "\t", 3)
	if len(lps) < 3 {
		panic(fmt.Sprintf("invalid line: %q", l))
	}

	outFF.Item(out, lps[0], lps[1], lps[2], ctx)
}

Ma_124's avatar
Ma_124 committed
60 61 62 63 64 65 66 67
// Prints the code according to this pattern:
//   <name>\t<url>\t<desc>
//   "literal line
//   'literal without newline
//   " continuation of previous line
//   "block literal
//   "which spans over
//   "multiple lines
68
var OFFTabSep = &OutputFileFormat{writeLiteralTabSep, writeItemTabSep, nil, nil}
Ma_124's avatar
Ma_124 committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

func writeLiteralTabSep(out io.Writer, l string, ctx *Ctx) {
	// TODO literal blocks
	// TODO align (once multitab support is added)
	// TODO multiple `'`s to `"`
	if l[len(l)-1] == '\n' {
		out.Write([]byte("\""))
		out.Write([]byte(l))
	} else {
		out.Write([]byte("'"))
		out.Write([]byte(l))
		out.Write([]byte("\n"))
	}
}

func writeItemTabSep(out io.Writer, name, url, desc string, ctx *Ctx) {
	out.Write([]byte(name))
	out.Write([]byte("\t"))
	out.Write([]byte(url))
	out.Write([]byte("\t"))
	out.Write([]byte(desc))
	out.Write([]byte("\n"))
}