forked from avioli/douceur
-
Notifications
You must be signed in to change notification settings - Fork 1
/
douceur.go
126 lines (103 loc) · 2.31 KB
/
douceur.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
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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/slt/douceur/inliner"
"github.com/slt/douceur/parser"
)
const (
// Version is package version
Version = "0.3.2"
)
var (
flagVersion bool
noAttributes bool
cssPath string
)
func init() {
flag.BoolVar(&flagVersion, "version", false, "Display version")
flag.BoolVar(&noAttributes, "n", false, "Don't inline obsolete attributes like bgcolor & valign")
flag.StringVar(&cssPath, "c", "", "Include external stylesheet when inlining")
}
func main() {
flag.Parse()
if flagVersion {
fmt.Println(Version)
os.Exit(0)
}
action := flag.Arg(0)
if action == "" {
fmt.Println("No action supplied")
usage()
os.Exit(1)
}
switch action {
case "parse":
parseCSS(flag.Arg(1))
case "inline":
inlineCSS(flag.Arg(1), cssPath)
default:
fmt.Println("Unexpected action: ", action)
usage()
os.Exit(1)
}
}
func usage() {
fmt.Printf("Help: %s -h", os.Args[0])
fmt.Printf("Usage: %s %s %s\n", os.Args[0], "(parse|inline)", "/path/to/file")
fmt.Printf("Usage: %s %s < %s\n", os.Args[0], "(parse|inline)", "/path/to/file")
}
// parse and display CSS file
func parseCSS(filePath string) {
input := read(filePath)
stylesheet, err := parser.Parse(string(input))
if err != nil {
fmt.Println("Parsing error: ", err)
os.Exit(1)
}
fmt.Println(stylesheet.String())
}
// inlines CSS into HTML and display result
func inlineCSS(filePath string, cssPath string) {
htmlInput := string(read(filePath))
instance := inliner.NewInliner(htmlInput)
if cssPath != "" {
cssInput := string(readFile(cssPath))
err := instance.ParseStylesheet(cssInput)
if err != nil {
fmt.Println("Inlining error: ", err)
os.Exit(1)
}
}
instance.InlineAttributes(!noAttributes)
output, err := instance.Inline()
if err != nil {
fmt.Println("Inlining error: ", err)
os.Exit(1)
}
fmt.Println(output)
}
func read(filePath string) []byte {
if filePath == "" {
return readStandardInput()
}
return readFile(filePath)
}
func readFile(filePath string) []byte {
file, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Println("Failed to open file: ", filePath, err)
os.Exit(1)
}
return file
}
func readStandardInput() []byte {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Println("Failed read stdin: ", err)
os.Exit(1)
}
return data
}