github.com/xiaq/elvish@v0.12.0/website/macros.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"log"
     9  	"os"
    10  	"path"
    11  	"strings"
    12  )
    13  
    14  const (
    15  	ttyshot = "$ttyshot "
    16  	cf      = "$cf "
    17  	dl      = "$dl "
    18  )
    19  
    20  func main() {
    21  	scanner := bufio.NewScanner(os.Stdin)
    22  	for scanner.Scan() {
    23  		line := scanner.Text()
    24  		line = expandTtyshot(line)
    25  		line = expandCf(line)
    26  		line = expandDl(line)
    27  		fmt.Println(line)
    28  	}
    29  }
    30  
    31  func expandTtyshot(line string) string {
    32  	i := strings.Index(line, ttyshot)
    33  	if i < 0 {
    34  		return line
    35  	}
    36  	name := line[i+len(ttyshot):]
    37  	content, err := ioutil.ReadFile(path.Join("tty", name+".html"))
    38  	if err != nil {
    39  		log.Fatal(err)
    40  	}
    41  	var buf bytes.Buffer
    42  	buf.WriteString(line[:i])
    43  	buf.WriteString(`<pre class="ttyshot"><code>`)
    44  	buf.Write(bytes.Replace(
    45  		content, []byte("\n"), []byte("<br>"), -1))
    46  	buf.WriteString("</code></pre>")
    47  	return buf.String()
    48  }
    49  
    50  func expandCf(line string) string {
    51  	i := strings.Index(line, cf)
    52  	if i < 0 {
    53  		return line
    54  	}
    55  	targets := strings.Split(line[i+len(cf):], " ")
    56  	var buf bytes.Buffer
    57  	buf.WriteString("See also")
    58  	for i, target := range targets {
    59  		var sep string
    60  		if i == 0 {
    61  			sep = " "
    62  		} else if i == len(targets)-1 {
    63  			sep = " and "
    64  		} else {
    65  			sep = ", "
    66  		}
    67  		fmt.Fprintf(&buf, "%s[`%s`](#%s)", sep, target, target)
    68  	}
    69  	buf.WriteString(".")
    70  	return buf.String()
    71  }
    72  
    73  func expandDl(line string) string {
    74  	i := strings.Index(line, dl)
    75  	if i < 0 {
    76  		return line
    77  	}
    78  	fields := strings.SplitN(line[i+len(dl):], " ", 2)
    79  	name := fields[0]
    80  	url := name
    81  	if len(fields) == 2 {
    82  		url = fields[1]
    83  	}
    84  	return line[:i] + fmt.Sprintf(
    85  		`<a href="https://dl.elv.sh/%s">%s</a>`, url, name)
    86  }