-
Notifications
You must be signed in to change notification settings - Fork 5
/
cmd-print.go
61 lines (49 loc) · 1.38 KB
/
cmd-print.go
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
package main
import (
. "github.com/spf13/cobra"
"html"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strconv"
)
func cmdPrint(rootCmd *Command) {
rootCmd.AddCommand(&Command{
Use: "print [item id]",
Short: "Print out item",
Long: "Print out item",
Run: func(cmd *Command, args []string) {
if len(args) != 1 {
fatal("item id is required")
}
itemId, err := strconv.Atoi(args[0])
failOnError(err)
item, err := itemRepository.ItemOfId(itemId)
failOnError(err)
tempDir, err := ioutil.TempDir("/tmp", "kobito")
failOnError(err)
// HTML に印刷JSを埋め込む
itemHtml := item.Html + `<script>window.print();</script>`
// タイトルを変更する
itemHtml = regexp.MustCompile("<title>.*</title>").ReplaceAllString(itemHtml, "<title>"+html.EscapeString(item.Title)+"</title>")
// HTML を書き込む
ioutil.WriteFile(tempDir+"/index.html", []byte(itemHtml), os.ModePerm)
// CSS などをコピーする
assets := []string{
"highlight.pack.js",
"github.min.css",
"markdown.css",
}
kobitoPath, err := kobitoPath()
failOnError(err)
for _, asset := range assets {
err := os.Symlink(kobitoPath+"/Contents/Resources/"+asset, tempDir+"/"+asset)
failOnError(err)
}
// ブラウザで開く
_, err = exec.Command("open", "-a", "Safari", tempDir+"/index.html").Output()
failOnError(err)
},
})
}