This repository has been archived by the owner on Jan 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
346 lines (280 loc) · 10.6 KB
/
helpers.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
Digivance MVC Application Framework
Generic Package Helper methods
Dan Mayor (dmayor@digivance.com)
This file defines some generic helper methods used in various portions of this package.
*/
package mvcapp
import (
"errors"
"fmt"
"math/rand"
"os"
"path/filepath"
"strings"
"time"
)
// Defines our Loging Levels, these are used to filter what is written to file allowing
// the calling application to easily switch the verbosity of logging at runtime
const (
// LogLevelNone is wreckless...
LogLevelNone = 0
// LogLevelError is the default, only critical errors are reported
LogLevelError = 1
// LogLevelWarning is a bit more verbose and will report errors that were handled internally
LogLevelWarning = 2
// LogLevelInfo is more verbose and will report generic workflow status as it goes
LogLevelInfo = 3
// LogLevelTrace is the most verbose and should only be used when debugging or troubleshooting
LogLevelTrace = 4
)
// TemplateExists checks the standard folder paths based on the provided controllerName
// to see if the template file can be found. (See MakeTemplateList for path structure)
func TemplateExists(controllerName string, template string) bool {
if strings.HasPrefix(template, "~/") || strings.HasPrefix(template, "./") {
template = GetApplicationPath() + template[1:]
}
if _, err := os.Stat(template); !os.IsNotExist(err) {
return true
}
// Try /views/template
viewPath := fmt.Sprintf("%s/views/%s", GetApplicationPath(), template)
if _, err := os.Stat(viewPath); !os.IsNotExist(err) {
return true
}
// Try /Views/controllerName/template
controllerPath := fmt.Sprintf("%s/views/%s/%s", GetApplicationPath(), controllerName, template)
if _, err := os.Stat(controllerPath); !os.IsNotExist(err) {
return true
}
// Try /views/shared/template
sharedPath := fmt.Sprintf("%s/views/shared/%s", GetApplicationPath(), template)
if _, err := os.Stat(sharedPath); !os.IsNotExist(err) {
return true
}
// Try /views/shared/controllerName/template
sharedControllerPath := fmt.Sprintf("%s/views/shared/%s/%s", GetApplicationPath(), controllerName, template)
if _, err := os.Stat(sharedControllerPath); !os.IsNotExist(err) {
return true
}
return false
}
// MakeTemplateList provides some common view template path fallbacks. Will test
// if each of the template file names exist as is, if not will try the following:
//
// ./views/template
// ./views/controllerName/template
// ./views/shared/template
// ./views/shared/controllerName/template
func MakeTemplateList(controllerName string, templates []string) []string {
rtn := []string{}
for _, template := range templates {
if strings.HasPrefix(template, "~/") || strings.HasPrefix(template, "./") {
template = GetApplicationPath() + template[1:]
}
if _, err := os.Stat(template); !os.IsNotExist(err) {
rtn = append(rtn, template)
} else {
// Try /views/template
viewPath := fmt.Sprintf("%s/views/%s", GetApplicationPath(), template)
if _, err := os.Stat(viewPath); !os.IsNotExist(err) {
rtn = append(rtn, viewPath)
} else {
// Try /Views/controllerName/template
controllerPath := fmt.Sprintf("%s/views/%s/%s", GetApplicationPath(), controllerName, template)
if _, err := os.Stat(controllerPath); !os.IsNotExist(err) {
rtn = append(rtn, controllerPath)
} else {
// Try /views/shared/template
sharedPath := fmt.Sprintf("%s/views/shared/%s", GetApplicationPath(), template)
if _, err := os.Stat(sharedPath); !os.IsNotExist(err) {
rtn = append(rtn, sharedPath)
} else {
// Try /views/shared/controllerName/template
sharedControllerPath := fmt.Sprintf("%s/views/shared/%s/%s", GetApplicationPath(), controllerName, template)
if _, err := os.Stat(sharedControllerPath); !os.IsNotExist(err) {
rtn = append(rtn, sharedControllerPath)
}
}
}
}
}
}
return rtn
}
// Some constant configuration values for random string generation methods. Defined here
// to allow for forked copies to easily modify string randomization
const (
// letterBytes : Available characters for random string
letterBytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// letterIDBits : Used in reduced byte masking
letterIDBits = 6
// letterIDMask : Used in reduced byte masking
letterIDMask = 1<<letterIDBits - 1
// letterIDMax : Used in reduced byte masking
letterIDMax = 63 / letterIDBits
)
// randomizer : Internal rand.Source
var randomizer = rand.NewSource(time.Now().UnixNano())
// RandomString returns a randomly generated string of the given length.
func RandomString(length int) string {
data := make([]byte, length)
for i, cache, remain := length-1, randomizer.Int63(), letterIDMax; i >= 0; {
if remain == 0 {
cache, remain = randomizer.Int63(), letterIDMax
}
if id := int(cache & letterIDMask); id < len(letterBytes) {
data[i] = letterBytes[id]
i--
}
cache >>= letterIDBits
remain--
}
return string(data)
}
// appPath is used internally so that we don't have to query the os args
// every time we ask to GetApplicationPath
var appPath = ""
// GetApplicationPath should return the full path to the executable.
// This is the root of the site and where the assembly file is
func GetApplicationPath() string {
if appPath == "" {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
appPath = "."
}
appPath = dir
}
return appPath
}
// LogFilename is used internally to hold the name of the file that holds our
// application logs
var LogFilename = ""
// GetLogFilename returns the current, or default log file that we will write to
func GetLogFilename() string {
return LogFilename
}
// SetLogFilename will set the filename that log messages will be written to
func SetLogFilename(filename string) {
if strings.HasPrefix(filename, "~/") || strings.HasPrefix(filename, "./") {
filename = GetApplicationPath() + filename[1:]
}
LogFilename = filename
}
// LogDateFormat is the golang time formatting string used when rendering the date
// and time portion of logging methods
var LogDateFormat = "1/2/2006 15:04:05 -07:00"
// GetLogDateFormat returns the current Golang time formatting string being used in logging
func GetLogDateFormat() string {
return LogDateFormat
}
// SetLogDateFormat sets the current Golang time formatting string being used in logging
func SetLogDateFormat(format string) {
LogDateFormat = format
}
// LogLevel is the internal value representing what levels of log messages are written
// to our log file. Where 0 = Off 1 = Errors Only, 2 = Warnings (Such as 404),
// 3 = Verbose (It'll say a lot), 4 = Debug Tracing (Won't shut up)
var LogLevel = LogLevelError
// GetLogLevel returns the level of log messages that are written to our log file
func GetLogLevel() int {
return LogLevel
}
// SetLogLevel sets the internal log level of messages that are written to our log file
// Where 0 = Off 1 = Errors Only, 2 = Warnings (Such as 404), 3 = Verbose (It'll say a lot)
func SetLogLevel(level int) {
LogLevel = level
}
// LogMessage writes an information message to the log file if our internal log level is >= 3
func LogMessage(message string) error {
if LogLevel < LogLevelInfo {
return errors.New("Failed to write information message due to log level")
}
if LogFilename == "" {
return errors.New("Failed to write information message due to log filename")
}
f, err := os.OpenFile(LogFilename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
if err != nil {
return err
}
defer f.Close()
if _, err := f.WriteString(fmt.Sprintf("[%s] Information: %s\r\n", time.Now().Format(LogDateFormat), message)); err != nil {
return err
}
return nil
}
// LogMessagef writes a formatted information message to the log file if our internal log
// level is >= 3
func LogMessagef(message string, args ...interface{}) error {
return LogMessage(fmt.Sprintf(message, args))
}
// LogWarning writes a warning message to the log file if our internal log level is >= 2
func LogWarning(message string) error {
if LogLevel < LogLevelWarning {
return errors.New("Failed to write warning message due to log level")
}
if LogFilename == "" {
return errors.New("Failed to write warning message due to log filename")
}
f, err := os.OpenFile(LogFilename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
if err != nil {
return nil
}
defer f.Close()
if _, err := f.WriteString(fmt.Sprintf("[%s] Warning: %s\r\n", time.Now().Format(LogDateFormat), message)); err != nil {
return err
}
return nil
}
// LogWarningf writes a formatted warning message to the log file if our internal log level
// is >= 2
func LogWarningf(message string, args ...interface{}) error {
return LogWarning(fmt.Sprintf(message, args))
}
// LogError writes an error message to the log file if our internal log level is >= 1
func LogError(message string) error {
if LogLevel < LogLevelError {
return errors.New("Failed to write error message due to log level")
}
if LogFilename == "" {
return errors.New("Failed to write error message due to log filename")
}
f, err := os.OpenFile(LogFilename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
if err != nil {
return err
}
defer f.Close()
if _, err := f.WriteString(fmt.Sprintf("[%s] Critical: %s\r\n\r\n", time.Now().Format(LogDateFormat), message)); err != nil {
return err
}
return nil
}
// LogErrorf writes a formatted error message to the log file if our internal log level
// is >= 1
func LogErrorf(message string, args ...interface{}) error {
return LogError(fmt.Sprintf(message, args))
}
// LogTrace is used to log debug tracing messages (such as the most verbose helping the reader to track the
// flow of execution through the program)
func LogTrace(message string) error {
if LogLevel < LogLevelTrace {
return errors.New("Failed to write trace log message due to log level")
}
if LogFilename == "" {
return errors.New("Failed to write trace log message due to log filename")
}
f, err := os.OpenFile(LogFilename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
if err != nil {
return err
}
defer f.Close()
if _, err := f.WriteString(fmt.Sprintf("[%s] Debug Trace: %s\r\n", time.Now().Format(LogDateFormat), message)); err != nil {
return err
}
return nil
}
// LogTracef is used to log formatted debug tracing messages such as the most verbose heling the reader to
// track the flow of execution through the program
func LogTracef(message string, args ...interface{}) error {
return LogTrace(fmt.Sprintf(message, args))
}