-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickgo.go
708 lines (564 loc) · 16.2 KB
/
quickgo.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
package quickgo
import (
"archive/zip"
"bytes"
"fmt"
html_template "html/template"
"io"
"io/fs"
"maps"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"github.com/Nigel2392/quickgo/v2/v2/config"
"github.com/Nigel2392/quickgo/v2/v2/logger"
"github.com/Nigel2392/quickgo/v2/v2/quickfs"
"github.com/pkg/errors"
)
var (
cliApplication *App
)
type (
App struct {
Config *config.QuickGo `yaml:"config"` // The configuration for QuickGo.
ProjectConfig *config.Project `yaml:"projectConfig"` // The configuration for the project.
Patterns []string `yaml:"patterns"` // The patterns for the templates.
AppFS fs.FS `yaml:"-"` // The file system for the app, resides in the executable directory.
ProjectFS fs.FS `yaml:"-"` // The file system for the project, resides in the project (working) directory.
}
)
func LoadApp() (*App, error) {
if cliApplication != nil {
return cliApplication, nil
}
var wd, err = os.Getwd()
if err != nil {
return nil, err
}
// Check for the application config directory.
var quickGoDir = filepath.Join(executableDir, config.QUICKGO_DIR)
var projectDir = filepath.Join(executableDir, config.QUICKGO_DIR, "projects")
_, err = os.Stat(projectDir)
// Create the application config directory if it does not exist.
if err != nil && os.IsNotExist(err) {
logger.Infof("Creating new config directory %s", projectDir)
if err = os.MkdirAll(projectDir, os.ModePerm); err != nil {
return nil, err
}
} else if err != nil {
return nil, err
}
// Initialize the application with the proper file systems.
var app = &App{
AppFS: os.DirFS(quickGoDir),
ProjectFS: os.DirFS(wd),
Patterns: []string{
"_templates/base.tmpl",
"_templates/readme.tmpl",
"_templates/index.tmpl",
},
}
// Setup the global application to prevent multiple instances.
cliApplication = app
// Load the QuickGo configuration.
var configPath = filepath.Join(
executableDir, config.QUICKGO_DIR, config.QUICKGO_CONFIG_NAME,
)
cfg, err := config.LoadYamlFS[config.QuickGo](
app.AppFS,
config.QUICKGO_CONFIG_NAME,
)
if err != nil {
// Create a new config file if it does not exist.
if !os.IsNotExist(err) {
return nil, errors.Wrapf(err, "failed to load config file %s", configPath)
}
cfg = &config.QuickGo{
Host: "localhost",
Port: "8080",
}
logger.Infof("Writing new config file %s", configPath)
if err = config.WriteYaml(cfg, configPath); err != nil {
logger.Errorf("Failed to write config file %s", configPath)
return nil, errors.Wrapf(err, "failed to write config file %s", configPath)
}
}
app.Config = cfg
return app, nil
}
// Load the project configuration from the current working directory.
func (a *App) LoadProjectConfig(directory string) (err error) {
logger.Debugf("Loading project config: %s", config.PROJECT_CONFIG_NAME)
if directory == "" {
if directory, err = os.Getwd(); err != nil {
return err
}
}
directory = filepath.ToSlash(directory)
directory = filepath.FromSlash(directory)
proj, err := config.LoadYaml[config.Project](
filepath.Join(directory, config.PROJECT_CONFIG_NAME),
)
if err != nil && os.IsNotExist(err) {
return config.ErrProjectMissing
} else if err != nil {
return err
}
if err = proj.Validate(); err != nil {
return err
}
a.ProjectConfig = proj
logger.Debugf("Loaded project config %s", a.ProjectConfig.Name)
return nil
}
// Write an example configuration for the user.
func (a *App) WriteExampleProjectConfig(directory string) (err error) {
var example = config.ExampleProjectConfig()
if directory == "" {
if directory, err = os.Getwd(); err != nil {
return err
}
}
return config.WriteYaml(example, filepath.Join(directory, config.PROJECT_CONFIG_NAME))
}
func (a *App) WriteProject(proj *config.Project, directory string, raw bool) error {
var (
cwd string
err error
)
// The directory to copy the project files to.
if directory == "" {
cwd, err = os.Getwd()
if err != nil {
return err
}
} else {
cwd = directory
}
logger.Debugf("Checking if project is locked in '%s'", cwd)
if err = config.IsLocked(cwd); err != nil {
return err
}
// Setup context for project templates.
// Also setup the directory paths.
var (
context = maps.Clone(proj.Context)
projectDir = filepath.Join(cwd, proj.Name)
)
if !filepath.IsAbs(projectDir) {
projectDir, err = filepath.Abs(projectDir)
if err != nil {
return errors.Wrapf(err, "failed to get absolute path for %s", projectDir)
}
}
projectDir = strings.ReplaceAll(projectDir, "\\", "/")
// Update the context - also found in config.go.*ProjectCommand.Command.
context["projectName"] = proj.Name
context["projectPath"] = projectDir
// Run commands before copying the project files.
if err = proj.BeforeCopy.Execute(context); err != nil {
return errors.Wrap(err, "failed to execute before copy steps")
}
// Create the project directory.
// This is located in <cwd>/<projectName>.
if err = os.MkdirAll(projectDir, os.ModePerm); err != nil {
return errors.Wrapf(err, "failed to create project directory %s", projectDir)
}
logger.Infof("Copying project files to %s", projectDir)
// Loop over all files in the project.
// This gets recursively called by subdirectories.
_, err = proj.Root.ForEach(func(fl quickfs.FileLike) (cancel bool, err error) {
var p = fl.GetPath()
var b = new(bytes.Buffer)
err = a.executeTemplate(
proj, b, p,
)
if err != nil {
return true, errors.Wrapf(err, "failed to execute template for filename %s", p)
}
var path = filepath.Join(projectDir, b.String())
switch f := fl.(type) {
case *quickfs.FSFile:
// Copy the file content to the new file.
// Replace any template variables.
var dir = filepath.Dir(path)
if err = os.MkdirAll(dir, os.ModePerm); err != nil {
return true, errors.Wrapf(err, "failed to create directory %s", dir)
}
osFile, err := os.Create(path)
if err != nil {
return true, errors.Wrapf(err, "failed to create file %s", path)
}
defer osFile.Close()
if err = a.CopyFileContent(proj, osFile, f, raw); err != nil {
return true, errors.Wrapf(err, "failed to copy file content to %s", path)
}
case *quickfs.FSDirectory:
// Create a new subdirectory inside of the project directory.
if err = os.MkdirAll(path, os.ModePerm); err != nil {
return true, errors.Wrapf(err, "failed to create directory %s", path)
}
}
rel, err := filepath.Rel(projectDir, path)
logger.Debugf("Copied %s to %s",
fl.GetPath(),
rel,
)
return false, nil
})
if err != nil {
logger.Errorf("Failed to copy project files to %s", projectDir)
return err
}
// Run commands after copying the project files.
err = proj.AfterCopy.Execute(context)
if err != nil {
return errors.Wrap(err, "failed to execute after copy steps")
}
logger.Infof("Finished copying project files to %s", projectDir)
return nil
}
func (a *App) WriteProjectConfig(proj *config.Project) error {
var (
err error
file *os.File
dirPath = getProjectFilePath(proj.Name, true)
)
var path = filepath.Join(dirPath, config.PROJECT_CONFIG_NAME)
if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
return err
}
logger.Infof("Writing project config to %s", path)
err = config.WriteYaml(proj, path)
if err != nil {
return err
}
var zipPath = filepath.Join(dirPath, config.PROJECT_ZIP_NAME)
if file, err = os.Create(zipPath); err != nil {
return err
}
defer file.Close()
var zf = zip.NewWriter(file)
defer zf.Close()
logger.Infof("Writing project files to %s", zipPath)
_, err = proj.Root.ForEach(func(fl quickfs.FileLike) (cancel bool, err error) {
var p = fl.GetPath()
switch f := fl.(type) {
case *quickfs.FSFile:
var w, err = zf.Create(p)
if err != nil {
return true, err
}
if _, err = io.Copy(w, f); err != nil {
return true, err
}
case *quickfs.FSDirectory:
if !strings.HasSuffix(p, "/") {
p += "/"
}
if _, err = zf.Create(p); err != nil {
return true, err
}
}
logger.Debugf("Wrote %s to %s", fl.GetPath(), p)
return false, nil
})
if err != nil {
logger.Errorf("Failed to write project to %s: %s", zipPath, err)
return err
}
logger.Infof("Finished writing project to %s", zipPath)
return err
}
func (a *App) ReadProjectConfig(name string) (proj *config.Project, closeFiles func(), err error) {
if name == "" || name == "." || strings.ContainsAny(name, `/\`) {
return nil, nil, config.ErrProjectName
}
var (
file *os.File
// dirPath = getProjectFilePath(name, false)
absDirPath = getProjectFilePath(name, true)
)
proj, err = config.LoadYaml[config.Project](
path.Join(absDirPath, config.PROJECT_CONFIG_NAME),
)
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to load YAML for project config %s", name)
}
proj.Root = quickfs.NewFSDirectory(
proj.Name,
".",
nil,
)
proj.Root.IsExcluded = proj.IsExcluded
file, err = os.Open(
path.Join(absDirPath, config.PROJECT_ZIP_NAME),
)
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to open zip file for project %s", name)
}
stat, err := file.Stat()
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to get file info for %s", file.Name())
}
zf, err := zip.NewReader(file, stat.Size())
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to read zip file %s", file.Name())
}
var zipFiles = make([]io.ReadCloser, 0, len(zf.File))
closeFiles = func() {
for _, f := range zipFiles {
f.Close()
}
}
for _, f := range zf.File {
var (
fInfo = f.FileInfo()
)
if f.Name == "." || f.Name == "./" {
continue
}
if fInfo.IsDir() {
proj.Root.AddDirectory(f.Name)
} else {
zipF, err := f.Open()
if err != nil {
return nil, closeFiles, err
}
zipFiles = append(zipFiles, zipF)
proj.Root.AddFile(f.Name, zipF)
}
}
return proj, closeFiles, nil
}
func (a *App) CopyFileContent(proj *config.Project, file *os.File, f *quickfs.FSFile, raw bool) error {
if raw {
_, err := io.Copy(file, f)
return err
}
var b = new(bytes.Buffer)
if _, err := io.Copy(b, f); err != nil {
return err
}
f.IsText = quickfs.IsText(b.Bytes()) && !strings.HasSuffix(
f.Name, config.PROJECT_CONFIG_NAME,
)
if !f.IsText {
_, err := io.Copy(file, b)
return err
}
content, err := io.ReadAll(b)
if err != nil {
return err
}
return a.executeTemplate(
proj, file, string(content),
)
}
func (a *App) ListProjects() ([]string, error) {
var (
projects = make([]string, 0)
dirPath = getProjectFilePath("", true)
)
dir, err := os.ReadDir(dirPath)
if err != nil {
return nil, errors.Wrapf(err, "failed to read directory %s", dirPath)
}
for _, d := range dir {
if !d.IsDir() {
continue
}
var path = filepath.Join(dirPath, d.Name())
var configName = filepath.Join(path, config.PROJECT_CONFIG_NAME)
if _, err = os.Stat(configName); err != nil {
continue
}
projects = append(projects, d.Name())
}
return projects, nil
}
func (a *App) WriteFile(data []byte, path string) error {
path = filepath.Join(executableDir, config.QUICKGO_DIR, path)
return os.WriteFile(path, data, os.ModePerm)
}
func (a *App) ReadFile(path string) ([]byte, error) {
path = filepath.Join(executableDir, config.QUICKGO_DIR, path)
return os.ReadFile(path)
}
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
go func() {
if err := recover(); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}()
var pathParts = strings.Split(strings.Trim(r.URL.Path, "/"), "/")
var primary = strings.ToLower(pathParts[0])
switch {
case primary == "projects":
a.serveProjects(w, r, pathParts[1:])
case primary == "favicon.ico" && len(pathParts) == 1:
// Write out the favicon file.
// No need to log the happy path here, quite boring.
var f, err = staticFS.Open("quickgo.png")
if err != nil {
logger.Errorf("Failed to open 'quickgo.png': %v", err)
http.Error(w, "Failed to open 'quickgo.png'", http.StatusInternalServerError)
return
}
defer f.Close()
w.Header().Set("Content-Type", "image/x-icon")
if _, err = io.Copy(w, f); err != nil {
logger.Errorf("Failed to read 'quickgo.png': %v", err)
http.Error(w, "Failed to read 'quickgo.png'", http.StatusInternalServerError)
}
case primary == "static":
// Serve static files.
logger.Debugf("Serving static file %s", r.URL.Path)
// Serve from embedded file system.
var handler = http.FileServer(http.FS(staticFS))
handler = http.StripPrefix("/static/", handler)
handler.ServeHTTP(w, r)
default:
logger.Debugf("Invalid request path '%s'", r.URL.Path)
http.Error(w, "Invalid path", http.StatusBadRequest)
}
}
type ProjectTemplateContext struct {
Project *config.Project
File *quickfs.FSFile
Dir *quickfs.FSDirectory
Content string
}
func (a *App) serveProjects(w http.ResponseWriter, r *http.Request, pathParts []string) {
var (
proj *config.Project
parent *quickfs.FSDirectory
fileLike quickfs.FileLike
err error
)
if len(pathParts) == 0 {
logger.Debugf("Invalid request path '%s'", r.URL.Path)
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
proj, closeFiles, err := a.ReadProjectConfig(pathParts[0])
if err != nil {
logger.Errorf("Failed to read project '%s': %v", pathParts[0], err)
http.Error(w, "Invalid project", http.StatusBadRequest)
return
}
defer closeFiles()
parent, fileLike, err = proj.Root.FindWithParent(pathParts[1:])
if err != nil {
logger.Errorf("Failed to find file '%s': %v", path.Join(pathParts...), err)
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
if fileLike.IsDir() {
// logger.Debugf("Invalid request path '%s', cannot open directory.", r.URL.Path)
// http.Error(w, "Invalid path", http.StatusBadRequest)
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Cache-Control", "no-cache")
var dir = fileLike.(*quickfs.FSDirectory)
if dir.Root() != nil {
fmt.Fprintf(w,
"<a href='/%s'>../%s</a><br>",
path.Join(
"projects",
proj.Name,
parent.GetPath(),
),
parent.GetName(),
)
}
quickfs.PrintRootFn(w, dir, " ", func(indent int, fl quickfs.FileLike) string {
var (
p = fl.GetPath()
url = filepath.ToSlash(
path.Join("projects", proj.Name, p),
)
name = fl.GetName()
)
if !strings.HasPrefix(url, "/") {
url = "/" + url
}
return fmt.Sprintf("<a href='%s' data-indent='%d'>%s</a><br>", url, indent, name)
})
return
}
var (
tpl *html_template.Template
file = fileLike.(*quickfs.FSFile)
b = new(bytes.Buffer)
)
if _, err = io.Copy(b, file); err != nil {
logger.Errorf("Failed to read file '%s': %v", file.GetPath(), err)
http.Error(w, "Failed to read file", http.StatusInternalServerError)
return
}
var content = b.String()
file.IsText = quickfs.IsText(content)
if !file.IsText {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename="+file.GetPath())
if _, err = io.Copy(w, b); err != nil {
http.Error(w, "Failed to read file", http.StatusInternalServerError)
}
return
}
if tpl, err = html_template.ParseFS(embedFS, a.Patterns...); err != nil {
logger.Errorf("Failed to parse template: %v", err)
http.Error(w, "Failed to parse file", http.StatusInternalServerError)
return
}
var context = ProjectTemplateContext{
Project: proj,
File: file,
Dir: parent,
Content: content,
}
if err = tpl.ExecuteTemplate(w, "base", context); err != nil {
logger.Errorf("Failed to execute template: %v", err)
http.Error(w, "Failed to execute template", http.StatusInternalServerError)
return
}
}
func (a *App) executeTemplate(proj *config.Project, w io.Writer, content string) error {
var tpl = template.New("file")
tpl.Delims(
proj.DelimLeft,
proj.DelimRight,
)
if _, err := tpl.Parse(content); err != nil {
return errors.Wrapf(
err,
"failed to parse template %s",
content,
)
}
return errors.Wrapf(
tpl.Execute(w, proj),
"failed to execute template %s",
content,
)
}
func getProjectFilePath(name string, absolute bool) string {
var p string
if absolute {
p = path.Join(
executableDir,
config.QUICKGO_DIR,
"projects",
name,
)
} else {
p = path.Join(
"projects",
name,
)
}
return strings.ReplaceAll(p, "\\", "/")
}