forked from b3log/wide
/
files.go
854 lines (634 loc) · 19.8 KB
/
files.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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
// Copyright (c) 2014-2015, b3log.org
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package file includes file related manipulations.
package file
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"github.com/b3log/wide/conf"
"github.com/b3log/wide/event"
"github.com/b3log/wide/log"
"github.com/b3log/wide/session"
"github.com/b3log/wide/util"
)
// Logger.
var logger = log.NewLogger(os.Stdout)
// Node represents a file node in file tree.
type Node struct {
Id string `json:"id"`
Name string `json:"name"`
Path string `json:"path"`
IconSkin string `json:"iconSkin"` // Value should be end with a space
IsParent bool `json:"isParent"`
Type string `json:"type"` // "f": file, "d": directory
Creatable bool `json:"creatable"` // whether can create file in this file node
Removable bool `json:"removable"` // whether can remove this file node
IsGoAPI bool `json:"isGOAPI"`
Mode string `json:"mode"`
Children []*Node `json:"children"`
}
// Snippet represents a source code snippet, used to as the result of "Find Usages", "Search".
type Snippet struct {
Path string `json:"path"` // file path
Line int `json:"line"` // line number
Ch int `json:"ch"` // column number
Contents []string `json:"contents"` // lines nearby
}
var apiNode *Node
// initAPINode builds the Go API file node.
func initAPINode() {
apiPath := util.Go.GetAPIPath()
apiNode = &Node{Name: "Go API", Path: apiPath, IconSkin: "ico-ztree-dir-api ", Type: "d",
Creatable: false, Removable: false, IsGoAPI: true, Children: []*Node{}}
walk(apiPath, apiNode, false, false, true)
}
// GetFilesHandler handles request of constructing user workspace file tree.
//
// The Go API source code package also as a child node,
// so that users can easily view the Go API source code in file tree.
func GetFilesHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
username := httpSession.Values["username"].(string)
data := map[string]interface{}{"succ": true}
defer util.RetGzJSON(w, r, data)
userWorkspace := conf.GetUserWorkspace(username)
workspaces := filepath.SplitList(userWorkspace)
root := Node{Name: "root", Path: "", IconSkin: "ico-ztree-dir ", Type: "d", IsParent: true, Children: []*Node{}}
if nil == apiNode { // lazy init
initAPINode()
}
// workspace node process
for _, workspace := range workspaces {
workspacePath := workspace + conf.PathSeparator + "src"
workspaceNode := Node{
Id: filepath.ToSlash(workspacePath), // jQuery API can't accept "\", so we convert it to "/"
Name: workspace[strings.LastIndex(workspace, conf.PathSeparator)+1:],
Path: filepath.ToSlash(workspacePath),
IconSkin: "ico-ztree-dir-workspace ",
Type: "d",
Creatable: true,
Removable: false,
IsGoAPI: false,
Children: []*Node{}}
walk(workspacePath, &workspaceNode, true, true, false)
// add workspace node
root.Children = append(root.Children, &workspaceNode)
}
// add Go API node
root.Children = append(root.Children, apiNode)
data["root"] = root
}
// RefreshDirectoryHandler handles request of refresh a directory of file tree.
func RefreshDirectoryHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
username := httpSession.Values["username"].(string)
r.ParseForm()
path := r.FormValue("path")
if !util.Go.IsAPI(path) && !session.CanAccess(username, path) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
node := Node{Name: "root", Path: path, IconSkin: "ico-ztree-dir ", Type: "d", Children: []*Node{}}
walk(path, &node, true, true, false)
w.Header().Set("Content-Type", "application/json")
data, err := json.Marshal(node.Children)
if err != nil {
logger.Error(err)
return
}
w.Write(data)
}
// GetFileHandler handles request of opening file by editor.
func GetFileHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
username := httpSession.Values["username"].(string)
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
logger.Error(err)
data["succ"] = false
return
}
path := args["path"].(string)
if !util.Go.IsAPI(path) && !session.CanAccess(username, path) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
size := util.File.GetFileSize(path)
if size > 5242880 { // 5M
data["succ"] = false
data["msg"] = "This file is too large to open :("
return
}
buf, _ := ioutil.ReadFile(path)
extension := filepath.Ext(path)
if util.File.IsImg(extension) {
// image file will be open in a browser tab
data["mode"] = "img"
username := conf.GetOwner(path)
if "" == username {
logger.Warnf("The path [%s] has no owner")
data["path"] = ""
return
}
user := conf.GetUser(username)
data["path"] = "/workspace/" + user.Name + "/" + strings.Replace(path, user.GetWorkspace(), "", 1)
return
}
content := string(buf)
if util.File.IsBinary(content) {
data["succ"] = false
data["msg"] = "Can't open a binary file :("
} else {
data["content"] = content
data["path"] = path
}
}
// SaveFileHandler handles request of saving file.
func SaveFileHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
username := httpSession.Values["username"].(string)
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
logger.Error(err)
data["succ"] = false
return
}
filePath := args["file"].(string)
sid := args["sid"].(string)
if util.Go.IsAPI(filePath) || !session.CanAccess(username, filePath) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
fout, err := os.Create(filePath)
if nil != err {
logger.Error(err)
data["succ"] = false
return
}
code := args["code"].(string)
fout.WriteString(code)
if err := fout.Close(); nil != err {
logger.Error(err)
data["succ"] = false
wSession := session.WideSessions.Get(sid)
wSession.EventQueue.Queue <- &event.Event{Code: event.EvtCodeServerInternalError, Sid: sid,
Data: "can't save file " + filePath}
return
}
}
// NewFileHandler handles request of creating file or directory.
func NewFileHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
username := httpSession.Values["username"].(string)
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
logger.Error(err)
data["succ"] = false
return
}
path := args["path"].(string)
if util.Go.IsAPI(path) || !session.CanAccess(username, path) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
fileType := args["fileType"].(string)
sid := args["sid"].(string)
wSession := session.WideSessions.Get(sid)
if !createFile(path, fileType) {
data["succ"] = false
wSession.EventQueue.Queue <- &event.Event{Code: event.EvtCodeServerInternalError, Sid: sid,
Data: "can't create file " + path}
return
}
if "f" == fileType {
logger.Debugf("Created a file [%s] by user [%s]", path, wSession.Username)
} else {
logger.Debugf("Created a dir [%s] by user [%s]", path, wSession.Username)
}
}
// RemoveFileHandler handles request of removing file or directory.
func RemoveFileHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
username := httpSession.Values["username"].(string)
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
logger.Error(err)
data["succ"] = false
return
}
path := args["path"].(string)
if util.Go.IsAPI(path) || !session.CanAccess(username, path) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
sid := args["sid"].(string)
wSession := session.WideSessions.Get(sid)
if !removeFile(path) {
data["succ"] = false
wSession.EventQueue.Queue <- &event.Event{Code: event.EvtCodeServerInternalError, Sid: sid,
Data: "can't remove file " + path}
return
}
logger.Debugf("Removed a file [%s] by user [%s]", path, wSession.Username)
}
// RenameFileHandler handles request of renaming file or directory.
func RenameFileHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
username := httpSession.Values["username"].(string)
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
logger.Error(err)
data["succ"] = false
return
}
oldPath := args["oldPath"].(string)
if util.Go.IsAPI(oldPath) ||
!session.CanAccess(username, oldPath) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
newPath := args["newPath"].(string)
if util.Go.IsAPI(newPath) || !session.CanAccess(username, newPath) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
sid := args["sid"].(string)
wSession := session.WideSessions.Get(sid)
if !renameFile(oldPath, newPath) {
data["succ"] = false
wSession.EventQueue.Queue <- &event.Event{Code: event.EvtCodeServerInternalError, Sid: sid,
Data: "can't rename file " + oldPath}
return
}
logger.Debugf("Renamed a file [%s] to [%s] by user [%s]", oldPath, newPath, wSession.Username)
}
// Use to find results sorting.
type foundPath struct {
Path string `json:"path"`
score int
}
type foundPaths []*foundPath
func (f foundPaths) Len() int { return len(f) }
func (f foundPaths) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
func (f foundPaths) Less(i, j int) bool { return f[i].score > f[j].score }
// FindHandler handles request of find files under the specified directory with the specified filename pattern.
func FindHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
username := httpSession.Values["username"].(string)
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
logger.Error(err)
data["succ"] = false
return
}
path := args["path"].(string) // path of selected file in file tree
if !util.Go.IsAPI(path) && !session.CanAccess(username, path) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
name := args["name"].(string)
userWorkspace := conf.GetUserWorkspace(username)
workspaces := filepath.SplitList(userWorkspace)
if "" != path && !util.File.IsDir(path) {
path = filepath.Dir(path)
}
founds := foundPaths{}
for _, workspace := range workspaces {
rs := find(workspace+conf.PathSeparator+"src", name, []*string{})
for _, r := range rs {
substr := util.Str.LCS(path, *r)
founds = append(founds, &foundPath{Path: filepath.ToSlash(*r), score: len(substr)})
}
}
sort.Sort(founds)
data["founds"] = founds
}
// SearchTextHandler handles request of searching files under the specified directory with the specified keyword.
func SearchTextHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
logger.Error(err)
data["succ"] = false
return
}
sid := args["sid"].(string)
wSession := session.WideSessions.Get(sid)
if nil == wSession {
data["succ"] = false
return
}
// XXX: just one directory
dir := args["dir"].(string)
if "" == dir {
userWorkspace := conf.GetUserWorkspace(wSession.Username)
workspaces := filepath.SplitList(userWorkspace)
dir = workspaces[0]
}
extension := args["extension"].(string)
text := args["text"].(string)
founds := []*Snippet{}
if util.File.IsDir(dir) {
founds = search(dir, extension, text, []*Snippet{})
} else {
founds = searchInFile(dir, text)
}
data["founds"] = founds
}
// walk traverses the specified path to build a file tree.
func walk(path string, node *Node, creatable, removable, isGOAPI bool) {
files := listFiles(path)
for _, filename := range files {
fpath := filepath.Join(path, filename)
fio, _ := os.Lstat(fpath)
child := Node{
Id: filepath.ToSlash(fpath), // jQuery API can't accept "\", so we convert it to "/"
Name: filename,
Path: filepath.ToSlash(fpath),
Removable: removable,
IsGoAPI: isGOAPI,
Children: []*Node{}}
node.Children = append(node.Children, &child)
if nil == fio {
logger.Warnf("Path [%s] is nil", fpath)
continue
}
if fio.IsDir() {
child.Type = "d"
child.Creatable = creatable
child.IconSkin = "ico-ztree-dir "
child.IsParent = true
walk(fpath, &child, creatable, removable, isGOAPI)
} else {
child.Type = "f"
child.Creatable = creatable
ext := filepath.Ext(fpath)
child.IconSkin = getIconSkin(ext)
}
}
return
}
// listFiles lists names of files under the specified dirname.
func listFiles(dirname string) []string {
f, _ := os.Open(dirname)
names, _ := f.Readdirnames(-1)
f.Close()
sort.Strings(names)
dirs := []string{}
files := []string{}
// sort: directories in front of files
for _, name := range names {
path := filepath.Join(dirname, name)
fio, err := os.Lstat(path)
if nil != err {
logger.Warnf("Can't read file info [%s]", path)
continue
}
if fio.IsDir() {
// exclude the .git direcitory
if ".git" == fio.Name() {
continue
}
dirs = append(dirs, name)
} else {
// exclude the .DS_Store directory on Mac OS X
if ".DS_Store" == fio.Name() {
continue
}
files = append(files, name)
}
}
return append(dirs, files...)
}
// getIconSkin gets CSS class name of icon with the specified filename extension.
//
// Refers to the zTree document for CSS class names.
func getIconSkin(filenameExtension string) string {
if util.File.IsImg(filenameExtension) {
return "ico-ztree-img "
}
switch filenameExtension {
case ".html", ".htm":
return "ico-ztree-html "
case ".go":
return "ico-ztree-go "
case ".css":
return "ico-ztree-css "
case ".txt":
return "ico-ztree-text "
case ".sql":
return "ico-ztree-sql "
case ".properties":
return "ico-ztree-pro "
case ".md":
return "ico-ztree-md "
case ".js", ".json":
return "ico-ztree-js "
case ".xml":
return "ico-ztree-xml "
default:
return "ico-ztree-other "
}
}
// createFile creates file on the specified path.
//
// fileType:
//
// "f": file
// "d": directory
func createFile(path, fileType string) bool {
switch fileType {
case "f":
file, err := os.OpenFile(path, os.O_CREATE, 0775)
if nil != err {
logger.Error(err)
return false
}
defer file.Close()
logger.Tracef("Created file [%s]", path)
return true
case "d":
err := os.Mkdir(path, 0775)
if nil != err {
logger.Error(err)
return false
}
logger.Tracef("Created directory [%s]", path)
return true
default:
logger.Errorf("Unsupported file type [%s]", fileType)
return false
}
}
// removeFile removes file on the specified path.
func removeFile(path string) bool {
if err := os.RemoveAll(path); nil != err {
logger.Errorf("Removes [%s] failed: [%s]", path, err.Error())
return false
}
logger.Tracef("Removed [%s]", path)
return true
}
// renameFile renames (moves) a file from the specified old path to the specified new path.
func renameFile(oldPath, newPath string) bool {
if err := os.Rename(oldPath, newPath); nil != err {
logger.Errorf("Renames [%s] failed: [%s]", oldPath, err.Error())
return false
}
logger.Tracef("Renamed [%s] to [%s]", oldPath, newPath)
return true
}
// Default exclude file name patterns when find.
var defaultExcludesFind = []string{".git", ".svn", ".repository", "CVS", "RCS", "SCCS", ".bzr", ".metadata", ".hg"}
// find finds files under the specified dir and its sub-directoryies with the specified name,
// likes the command 'find dir -name name'.
func find(dir, name string, results []*string) []*string {
if !strings.HasSuffix(dir, conf.PathSeparator) {
dir += conf.PathSeparator
}
f, _ := os.Open(dir)
fileInfos, err := f.Readdir(-1)
f.Close()
if nil != err {
logger.Errorf("Read dir [%s] failed: [%s]", dir, err.Error())
return results
}
for _, fileInfo := range fileInfos {
fname := fileInfo.Name()
path := dir + fname
if fileInfo.IsDir() {
if util.Str.Contains(fname, defaultExcludesFind) {
continue
}
// enter the directory recursively
results = find(path, name, results)
} else {
// match filename
pattern := filepath.Dir(path) + conf.PathSeparator + name
match, err := filepath.Match(strings.ToLower(pattern), strings.ToLower(path))
if nil != err {
logger.Errorf("Find match filename failed: [%s]", err.Error())
continue
}
if match {
results = append(results, &path)
}
}
}
return results
}
// search finds file under the specified dir and its sub-directories with the specified text, likes the command 'grep'
// or 'findstr'.
func search(dir, extension, text string, snippets []*Snippet) []*Snippet {
if !strings.HasSuffix(dir, conf.PathSeparator) {
dir += conf.PathSeparator
}
f, _ := os.Open(dir)
fileInfos, err := f.Readdir(-1)
f.Close()
if nil != err {
logger.Errorf("Read dir [%s] failed: [%s]", dir, err.Error())
return snippets
}
for _, fileInfo := range fileInfos {
path := dir + fileInfo.Name()
if fileInfo.IsDir() {
// enter the directory recursively
snippets = search(path, extension, text, snippets)
} else if strings.HasSuffix(path, extension) {
// grep in file
ss := searchInFile(path, text)
snippets = append(snippets, ss...)
}
}
return snippets
}
// searchInFile finds file with the specified path and text.
func searchInFile(path string, text string) []*Snippet {
ret := []*Snippet{}
bytes, err := ioutil.ReadFile(path)
if nil != err {
logger.Errorf("Read file [%s] failed: [%s]", path, err.Error())
return ret
}
content := string(bytes)
if util.File.IsBinary(content) {
return ret
}
lines := strings.Split(content, "\n")
for idx, line := range lines {
ch := strings.Index(strings.ToLower(line), strings.ToLower(text))
if -1 != ch {
snippet := &Snippet{Path: filepath.ToSlash(path),
Line: idx + 1, Ch: ch + 1, Contents: []string{line}}
ret = append(ret, snippet)
}
}
return ret
}