-
Notifications
You must be signed in to change notification settings - Fork 67
/
common.go
112 lines (99 loc) · 2.11 KB
/
common.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
package core
import (
"fmt"
"io"
"os"
"unicode/utf8"
)
var exitCallbacks []func()
func ExitJoker(rc int) {
for _, f := range exitCallbacks {
f()
}
os.Exit(rc)
}
func OnExit(f func()) {
exitCallbacks = append(exitCallbacks, f)
}
func writeIndent(w io.Writer, n int) {
space := []byte(" ")
for i := 0; i < n; i++ {
w.Write(space)
}
}
func pprintObject(obj Object, indent int, w io.Writer) int {
switch obj := obj.(type) {
case Pprinter:
return obj.Pprint(w, indent)
default:
s := obj.ToString(true)
fmt.Fprint(w, s)
return indent + len(s)
}
}
func formatObject(obj Object, indent int, w io.Writer) int {
if info := obj.GetInfo(); info != nil {
fmt.Fprint(w, info.prefix)
indent += utf8.RuneCountInString(info.prefix)
}
switch obj := obj.(type) {
case Formatter:
return obj.Format(w, indent)
default:
s := obj.ToString(true)
fmt.Fprint(w, s)
return indent + utf8.RuneCountInString(s)
}
}
func isComment(obj Object) bool {
if _, ok := obj.(Comment); ok {
return true
}
info := obj.GetInfo()
if info == nil {
return false
}
return info.prefix == "^" || info.prefix == "#^" || info.prefix == "#_"
}
func isComma(obj Object) bool {
if c, ok := obj.(Comment); ok && c.C == "," {
return true
}
return false
}
func maybeNewLine(w io.Writer, obj, nextObj Object, baseIndent, currentIndent int) int {
if writeNewLines(w, obj, nextObj) > 0 {
writeIndent(w, baseIndent)
return baseIndent
}
if !isComma(nextObj) {
fmt.Fprint(w, " ")
}
return currentIndent + 1
}
func FileInfoMap(name string, info os.FileInfo) Map {
m := EmptyArrayMap()
m.Add(MakeKeyword("name"), MakeString(name))
m.Add(MakeKeyword("size"), MakeInt(int(info.Size())))
m.Add(MakeKeyword("mode"), MakeInt(int(info.Mode())))
m.Add(MakeKeyword("modtime"), MakeTime(info.ModTime()))
m.Add(MakeKeyword("dir?"), MakeBoolean(info.IsDir()))
return m
}
func ToBool(obj Object) bool {
switch obj := obj.(type) {
case Nil:
return false
case Boolean:
return obj.B
default:
return true
}
}
func HomeDir() string {
home, ok := os.LookupEnv("HOME")
if !ok {
home, _ = os.LookupEnv("USERPROFILE")
}
return home
}