-
Notifications
You must be signed in to change notification settings - Fork 0
/
filetree.go
2831 lines (2643 loc) · 77.8 KB
/
filetree.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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2018, The GoKi Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package giv
import (
"bytes"
"errors"
"fmt"
"image/color"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"reflect"
"sort"
"strings"
"sync"
"time"
"github.com/Masterminds/vcs"
"github.com/fsnotify/fsnotify"
"github.com/goki/gi/gi"
"github.com/goki/gi/gist"
"github.com/goki/gi/giv/textbuf"
"github.com/goki/gi/histyle"
"github.com/goki/gi/oswin"
"github.com/goki/gi/oswin/dnd"
"github.com/goki/gi/oswin/key"
"github.com/goki/gi/oswin/mimedata"
"github.com/goki/gi/oswin/mouse"
"github.com/goki/gi/units"
"github.com/goki/ki/bitflag"
"github.com/goki/ki/ints"
"github.com/goki/ki/ki"
"github.com/goki/ki/kit"
"github.com/goki/pi/filecat"
"github.com/goki/vci"
)
// DirAndFile returns the final dir and file name.
func DirAndFile(file string) string {
dir, fnm := filepath.Split(file)
return filepath.Join(filepath.Base(dir), fnm)
}
// RelFilePath returns the file name relative to given root file path, if it is
// under that root -- otherwise it returns the final dir and file name.
func RelFilePath(file, root string) string {
rp, err := filepath.Rel(root, file)
if err == nil && !strings.HasPrefix(rp, "..") {
return rp
}
return DirAndFile(file)
}
const (
// FileTreeExtFilesName is the name of the node that represents external files
FileTreeExtFilesName = "[external files]"
)
// FileTree is the root of a tree representing files in a given directory (and
// subdirectories thereof), and has some overall management state for how to
// view things. The FileTree can be viewed by a TreeView to provide a GUI
// interface into it.
type FileTree struct {
FileNode
ExtFiles []string `desc:"external files outside the root path of the tree -- abs paths are stored -- these are shown in the first sub-node if present -- use AddExtFile to add and update"`
Dirs DirFlagMap `desc:"records state of directories within the tree (encoded using paths relative to root), e.g., open (have been opened by the user) -- can persist this to restore prior view of a tree"`
DirsOnTop bool `desc:"if true, then all directories are placed at the top of the tree view -- otherwise everything is mixed"`
NodeType reflect.Type `view:"-" json:"-" xml:"-" desc:"type of node to create -- defaults to giv.FileNode but can use custom node types"`
InOpenAll bool `desc:"if true, we are in midst of an OpenAll call -- nodes should open all dirs"`
Watcher *fsnotify.Watcher `view:"-" desc:"change notify for all dirs"`
DoneWatcher chan bool `view:"-" desc:"channel to close watcher watcher"`
WatchedPaths map[string]bool `view:"-" desc:"map of paths that have been added to watcher -- only active if bool = true"`
LastWatchUpdt string `view:"-" desc:"last path updated by watcher"`
LastWatchTime time.Time `view:"-" desc:"timestamp of last update"`
UpdtMu sync.Mutex `view:"-" desc:"Update mutex"`
}
var KiT_FileTree = kit.Types.AddType(&FileTree{}, FileTreeProps)
var FileTreeProps = ki.Props{
"EnumType:Flag": KiT_FileNodeFlags,
}
func (ft *FileTree) CopyFieldsFrom(frm interface{}) {
fr := frm.(*FileTree)
ft.FileNode.CopyFieldsFrom(&fr.FileNode)
ft.DirsOnTop = fr.DirsOnTop
ft.NodeType = fr.NodeType
}
func (fv *FileTree) Disconnect() {
if fv.Watcher != nil {
fv.Watcher.Close()
fv.Watcher = nil
}
if fv.DoneWatcher != nil {
fv.DoneWatcher <- true
close(fv.DoneWatcher)
fv.DoneWatcher = nil
}
fv.FileNode.Disconnect()
}
// OpenPath opens a filetree at given directory path -- reads all the files at
// given path into this tree -- uses config children to preserve extra info
// already stored about files. Only paths listed in Dirs will be opened.
func (ft *FileTree) OpenPath(path string) {
ft.FRoot = ft // we are our own root..
if ft.NodeType == nil {
ft.NodeType = KiT_FileNode
}
ft.FPath = gi.FileName(path)
ft.UpdateAll()
}
// UpdateAll does a full update of the tree -- calls ReadDir on current path
func (ft *FileTree) UpdateAll() {
ft.UpdtMu.Lock()
ft.Dirs.ClearMarks()
ft.ReadDir(string(ft.FPath))
// the problem here is that closed dirs are not visited but we want to keep their settings:
// ft.Dirs.DeleteStale()
ft.UpdtMu.Unlock()
}
// UpdatePath updates the tree at the directory level for given path
// and everything below it
func (ft *FileTree) UpdatePath(path string) {
ft.UpdtMu.Lock()
ft.UpdtMu.Unlock()
}
// todo: rewrite below to use UpdatePath
// UpdateNewFile should be called with path to a new file that has just been
// created -- will update view to show that file, and if that file doesn't
// exist, it updates the directory containing that file
func (ft *FileTree) UpdateNewFile(filename string) {
ft.DirsTo(filename)
fpath, _ := filepath.Split(filename)
fpath = filepath.Clean(fpath)
if fn, ok := ft.FindFile(filename); ok {
// fmt.Printf("updating node for file: %v\n", filename)
fn.UpdateNode()
} else if fn, ok := ft.FindFile(fpath); ok {
// fmt.Printf("updating node for path: %v\n", fpath)
fn.UpdateNode()
// } else {
// log.Printf("giv.FileTree UpdateNewFile: no node found for path to update: %v\n", filename)
}
}
// ConfigWatcher configures a new watcher for tree
func (ft *FileTree) ConfigWatcher() error {
if ft.Watcher != nil {
return nil
}
ft.WatchedPaths = make(map[string]bool)
var err error
ft.Watcher, err = fsnotify.NewWatcher()
return err
}
// WatchWatcher monitors the watcher channel for update events.
// It must be called once some paths have been added to watcher --
// safe to call multiple times.
func (ft *FileTree) WatchWatcher() {
if ft.Watcher == nil || ft.Watcher.Events == nil {
return
}
if ft.DoneWatcher != nil {
return
}
ft.DoneWatcher = make(chan bool)
go func() {
watch := ft.Watcher
done := ft.DoneWatcher
for {
select {
case <-done:
return
case event := <-watch.Events:
switch {
case event.Op&fsnotify.Create == fsnotify.Create ||
event.Op&fsnotify.Remove == fsnotify.Remove ||
event.Op&fsnotify.Rename == fsnotify.Rename:
ft.WatchUpdt(event.Name)
}
case err := <-watch.Errors:
_ = err
}
}
}()
}
// WatchUpdt does the update for given path
func (ft *FileTree) WatchUpdt(path string) {
ft.UpdtMu.Lock()
defer ft.UpdtMu.Unlock()
// fmt.Println(path)
dir, _ := filepath.Split(path)
rp := ft.RelPath(gi.FileName(dir))
if rp == ft.LastWatchUpdt {
now := time.Now()
lagMs := int(now.Sub(ft.LastWatchTime) / time.Millisecond)
if lagMs < 100 {
// fmt.Printf("skipping update to: %s due to lag: %v\n", rp, lagMs)
return // no update
}
}
fn, err := ft.FindDirNode(rp)
if err != nil {
// log.Println(err)
return
}
ft.LastWatchUpdt = rp
ft.LastWatchTime = time.Now()
if !fn.IsOpen() {
// fmt.Printf("warning: watcher updating closed node: %s\n", rp)
return // shouldn't happen
}
// update node
fn.UpdateNode()
}
// WatchPath adds given path to those watched
func (ft *FileTree) WatchPath(path gi.FileName) error {
return nil // disable for all platforms for now -- getting some issues
if oswin.TheApp.Platform() == oswin.MacOS {
return nil // mac is not supported in a high-capacity fashion at this point
}
rp := ft.RelPath(path)
on, has := ft.WatchedPaths[rp]
if on || has {
return nil
}
ft.ConfigWatcher()
// fmt.Printf("watching path: %s\n", path)
err := ft.Watcher.Add(string(path))
if err == nil {
ft.WatchedPaths[rp] = true
ft.WatchWatcher()
} else {
log.Println(err)
}
return err
}
// UnWatchPath removes given path from those watched
func (ft *FileTree) UnWatchPath(path gi.FileName) {
rp := ft.RelPath(path)
on, has := ft.WatchedPaths[rp]
if !on || !has {
return
}
ft.ConfigWatcher()
ft.Watcher.Remove(string(path))
ft.WatchedPaths[rp] = false
}
// IsDirOpen returns true if given directory path is open (i.e., has been
// opened in the view)
func (ft *FileTree) IsDirOpen(fpath gi.FileName) bool {
if fpath == ft.FPath { // we are always open
return true
}
return ft.Dirs.IsOpen(ft.RelPath(fpath))
}
// SetDirOpen sets the given directory path to be open
func (ft *FileTree) SetDirOpen(fpath gi.FileName) {
rp := ft.RelPath(fpath)
ft.Dirs.SetOpen(rp, true)
ft.Dirs.SetMark(rp)
ft.WatchPath(fpath)
}
// SetDirClosed sets the given directory path to be closed
func (ft *FileTree) SetDirClosed(fpath gi.FileName) {
rp := ft.RelPath(fpath)
ft.Dirs.SetOpen(rp, false)
ft.Dirs.SetMark(rp)
ft.UnWatchPath(fpath)
}
// SetDirSortBy sets the given directory path sort by option
func (ft *FileTree) SetDirSortBy(fpath gi.FileName, modTime bool) {
ft.Dirs.SetSortBy(ft.RelPath(fpath), modTime)
}
// DirSortByName returns true if dir is sorted by name
func (ft *FileTree) DirSortByName(fpath gi.FileName) bool {
return ft.Dirs.SortByName(ft.RelPath(fpath))
}
// DirSortByModTime returns true if dir is sorted by mod time
func (ft *FileTree) DirSortByModTime(fpath gi.FileName) bool {
return ft.Dirs.SortByModTime(ft.RelPath(fpath))
}
// AddExtFile adds an external file outside of root of file tree
// and triggers an update, returning the FileNode for it, or
// error if filepath.Abs fails.
func (ft *FileTree) AddExtFile(fpath string) (*FileNode, error) {
pth, err := filepath.Abs(fpath)
if err != nil {
return nil, err
}
if _, err := os.Stat(pth); err != nil {
return nil, err
}
if has, _ := ft.HasExtFile(pth); has {
return ft.ExtFileNodeByPath(pth)
}
ft.ExtFiles = append(ft.ExtFiles, pth)
ft.UpdateDir()
return ft.ExtFileNodeByPath(pth)
}
// RemoveExtFile removes external file from maintained list, returns true if removed
func (ft *FileTree) RemoveExtFile(fpath string) bool {
for i, ef := range ft.ExtFiles {
if ef == fpath {
ft.ExtFiles = append(ft.ExtFiles[:i], ft.ExtFiles[i+1:]...)
return true
}
}
return false
}
// HasExtFile returns true and index if given abs path exists on ExtFiles list.
// false and -1 if not.
func (ft *FileTree) HasExtFile(fpath string) (bool, int) {
for i, f := range ft.ExtFiles {
if f == fpath {
return true, i
}
}
return false, -1
}
// ExtFileNodeByPath returns FileNode for given file path, and true, if it
// exists in the external files list. Otherwise returns nil, false.
func (ft *FileTree) ExtFileNodeByPath(fpath string) (*FileNode, error) {
ehas, i := ft.HasExtFile(fpath)
if !ehas {
return nil, fmt.Errorf("ExtFile not found on list: %v", fpath)
}
ekid, err := ft.ChildByNameTry(FileTreeExtFilesName, 0)
if err != nil {
return nil, fmt.Errorf("ExtFile not updated -- no ExtFiles node")
}
ekids := *ekid.Children()
err = ekids.IsValidIndex(i)
if err == nil {
kn := ekids.Elem(i).Embed(KiT_FileNode).(*FileNode)
return kn, nil
}
return nil, fmt.Errorf("ExtFile not updated: %v", err)
}
// UpdateExtFiles returns a type-and-name list for configuring nodes
// for ExtFiles
func (ft *FileTree) UpdateExtFiles(efn *FileNode) {
efn.Info.Mode = os.ModeDir | os.ModeIrregular // mark as dir, irregular
efn.SetOpen()
config := kit.TypeAndNameList{}
typ := ft.NodeType
for _, f := range ft.ExtFiles {
config.Add(typ, DirAndFile(f))
}
mods, updt := efn.ConfigChildren(config) // NOT unique names
if mods {
// fmt.Printf("got mods: %v\n", path)
}
// always go through kids, regardless of mods
for i, sfk := range efn.Kids {
sf := sfk.Embed(KiT_FileNode).(*FileNode)
sf.FRoot = ft
fp := ft.ExtFiles[i]
sf.SetNodePath(fp)
sf.Info.Vcs = vci.Stored // no vcs in general
}
if mods {
efn.UpdateEnd(updt)
}
}
//////////////////////////////////////////////////////////////////////////////
// FileNode
// FileNodeHiStyle is the default style for syntax highlighting to use for
// file node buffers
var FileNodeHiStyle = histyle.StyleDefault
// FileNode represents a file in the file system -- the name of the node is
// the name of the file. Folders have children containing further nodes.
type FileNode struct {
ki.Node
FPath gi.FileName `json:"-" xml:"-" copy:"-" desc:"full path to this file"`
Info FileInfo `json:"-" xml:"-" copy:"-" desc:"full standard file info about this file"`
Buf *TextBuf `json:"-" xml:"-" copy:"-" desc:"file buffer for editing this file"`
FRoot *FileTree `json:"-" xml:"-" copy:"-" desc:"root of the tree -- has global state"`
DirRepo vci.Repo `json:"-" xml:"-" copy:"-" desc:"version control system repository for this directory, only non-nil if this is the highest-level directory in the tree under vcs control"`
RepoFiles vci.Files `json:"-" xml:"-" copy:"-" desc:"version control system repository file status -- only valid during ReadDir"`
}
var KiT_FileNode = kit.Types.AddType(&FileNode{}, FileNodeProps)
func (fn *FileNode) CopyFieldsFrom(frm interface{}) {
// note: not copying ki.Node as it doesn't have any copy fields
// fr := frm.(*FileNode)
// and indeed nothing here should be copied!
}
// IsDir returns true if file is a directory (folder)
func (fn *FileNode) IsDir() bool {
return fn.Info.IsDir()
}
// IsIrregular returns true if file is a special "Irregular" node
func (fn *FileNode) IsIrregular() bool {
return (fn.Info.Mode & os.ModeIrregular) != 0
}
// IsExternal returns true if file is external to main file tree
func (fn *FileNode) IsExternal() bool {
isExt := false
fn.FuncUp(0, fn, func(k ki.Ki, level int, d interface{}) bool {
sfni := k.Embed(KiT_FileNode)
if sfni == nil {
return ki.Break
}
sfn := sfni.(*FileNode)
if sfn.IsIrregular() {
isExt = true
return ki.Break
}
return ki.Continue
})
return isExt
}
// HasClosedParent returns true if node has a parent node with !IsOpen flag set
func (fn *FileNode) HasClosedParent() bool {
hasClosed := false
fn.FuncUpParent(0, fn, func(k ki.Ki, level int, d interface{}) bool {
sfni := k.Embed(KiT_FileNode)
if sfni == nil {
return ki.Break
}
sfn := sfni.(*FileNode)
if !sfn.IsOpen() {
hasClosed = true
return ki.Break
}
return ki.Continue
})
return hasClosed
}
// IsSymLink returns true if file is a symlink
func (fn *FileNode) IsSymLink() bool {
return fn.HasFlag(int(FileNodeSymLink))
}
// IsExec returns true if file is an executable file
func (fn *FileNode) IsExec() bool {
return fn.Info.IsExec()
}
// IsOpen returns true if file is flagged as open
func (fn *FileNode) IsOpen() bool {
return fn.HasFlag(int(FileNodeOpen))
}
// SetOpen sets the open flag
func (fn *FileNode) SetOpen() {
fn.SetFlag(int(FileNodeOpen))
}
// SetClosed clears the open flag
func (fn *FileNode) SetClosed() {
fn.ClearFlag(int(FileNodeOpen))
}
// IsChanged returns true if the file is open and has been changed (edited) since last save
func (fn *FileNode) IsChanged() bool {
if fn.Buf != nil && fn.Buf.IsChanged() {
return true
}
return false
}
// IsAutoSave returns true if file is an auto-save file (starts and ends with #)
func (fn *FileNode) IsAutoSave() bool {
if strings.HasPrefix(fn.Info.Name, "#") && strings.HasSuffix(fn.Info.Name, "#") {
return true
}
return false
}
// MyRelPath returns the relative path from root for this node
func (fn *FileNode) MyRelPath() string {
if fn.IsIrregular() {
return fn.Nm
}
return RelFilePath(string(fn.FPath), string(fn.FRoot.FPath))
}
// ReadDir reads all the files at given directory into this directory node --
// uses config children to preserve extra info already stored about files. The
// root node represents the directory at the given path. Returns os.Stat
// error if path cannot be accessed.
func (fn *FileNode) ReadDir(path string) error {
_, fnm := filepath.Split(path)
fn.SetName(fnm)
pth, err := filepath.Abs(path)
if err != nil {
return err
}
fn.FPath = gi.FileName(pth)
err = fn.Info.InitFile(string(fn.FPath))
if err != nil {
log.Printf("giv.FileTree: could not read directory: %v err: %v\n", fn.FPath, err)
return err
}
fn.UpdateDir()
return nil
}
// DetectVcsRepo detects and configures DirRepo if this directory is root of
// a VCS repository. if updateFiles is true, gets the files in the dir.
// returns true if a repository was newly found here.
func (fn *FileNode) DetectVcsRepo(updateFiles bool) bool {
repo, _ := fn.Repo()
if repo != nil {
if updateFiles {
fn.UpdateRepoFiles()
}
return false
}
path := string(fn.FPath)
rtyp := vci.DetectRepo(path)
if rtyp == vcs.NoVCS {
return false
}
var err error
repo, err = vci.NewRepo("origin", path)
if err != nil {
log.Println(err)
return false
}
fn.DirRepo = repo
if updateFiles {
fn.UpdateRepoFiles()
}
return true
}
// UpdateDir updates the directory and all the nodes under it
func (fn *FileNode) UpdateDir() {
fn.DetectVcsRepo(true) // update files
path := string(fn.FPath)
// fmt.Printf("path: %v node: %v\n", path, fn.Path())
repo, rnode := fn.Repo()
fn.SetOpen()
fn.FRoot.SetDirOpen(fn.FPath)
config := fn.ConfigOfFiles(path)
hasExtFiles := false
if fn.This() == fn.FRoot.This() {
if len(fn.FRoot.ExtFiles) > 0 {
config = append([]kit.TypeAndName{{Type: fn.FRoot.NodeType, Name: FileTreeExtFilesName}}, config...)
hasExtFiles = true
}
}
mods, updt := fn.ConfigChildren(config) // NOT unique names
if mods {
// fmt.Printf("got mods: %v\n", path)
}
// always go through kids, regardless of mods
for _, sfk := range fn.Kids {
sf := sfk.Embed(KiT_FileNode).(*FileNode)
sf.FRoot = fn.FRoot
if hasExtFiles && sf.Nm == FileTreeExtFilesName {
fn.FRoot.UpdateExtFiles(sf)
continue
}
fp := filepath.Join(path, sf.Nm)
// if sf.Buf != nil {
// fmt.Printf("fp: %v nm: %v\n", fp, sf.Nm)
// }
sf.SetNodePath(fp)
if sf.IsDir() {
sf.Info.Vcs = vci.Stored // always
} else if repo != nil {
rstat := rnode.RepoFiles.Status(repo, string(sf.FPath))
sf.Info.Vcs = rstat
} else {
sf.Info.Vcs = vci.Stored
}
}
if mods {
fn.UpdateEnd(updt)
}
}
// ConfigOfFiles returns a type-and-name list for configuring nodes based on
// files immediately within given path
func (fn *FileNode) ConfigOfFiles(path string) kit.TypeAndNameList {
config1 := kit.TypeAndNameList{}
config2 := kit.TypeAndNameList{}
typ := fn.FRoot.NodeType
filepath.Walk(path, func(pth string, info os.FileInfo, err error) error {
if err != nil {
emsg := fmt.Sprintf("giv.FileNode ConfigFilesIn Path %q: Error: %v", path, err)
log.Println(emsg)
return nil // ignore
}
if pth == path { // proceed..
return nil
}
_, fnm := filepath.Split(pth)
if fn.FRoot.DirsOnTop {
if info.IsDir() {
config1.Add(typ, fnm)
} else {
config2.Add(typ, fnm)
}
} else {
config1.Add(typ, fnm)
}
if info.IsDir() {
return filepath.SkipDir
}
return nil
})
modSort := fn.FRoot.DirSortByModTime(gi.FileName(path))
if fn.FRoot.DirsOnTop {
if modSort {
fn.SortConfigByModTime(config2) // just sort files, not dirs
}
config1 = append(config1, config2...)
} else {
if modSort {
fn.SortConfigByModTime(config1) // all
}
}
return config1
}
// SortConfigByModTime sorts given config list by mod time
func (fn *FileNode) SortConfigByModTime(confg kit.TypeAndNameList) {
sort.Slice(confg, func(i, j int) bool {
ifn, _ := os.Stat(filepath.Join(string(fn.FPath), confg[i].Name))
jfn, _ := os.Stat(filepath.Join(string(fn.FPath), confg[j].Name))
return ifn.ModTime().After(jfn.ModTime()) // descending
})
}
// SetNodePath sets the path for given node and updates it based on associated file
func (fn *FileNode) SetNodePath(path string) error {
pth, err := filepath.Abs(path)
if err != nil {
return err
}
fn.FPath = gi.FileName(pth)
err = fn.InitFileInfo()
if err != nil {
return err
}
if fn.IsDir() && !fn.IsIrregular() {
openAll := fn.FRoot.InOpenAll && !fn.Info.IsHidden()
if openAll || fn.FRoot.IsDirOpen(fn.FPath) {
fn.ReadDir(string(fn.FPath)) // keep going down..
}
}
return nil
}
// InitFileInfo initializes file info
func (fn *FileNode) InitFileInfo() error {
effpath, err := filepath.EvalSymlinks(string(fn.FPath))
if err != nil {
// this happens too often for links -- skip
// log.Printf("giv.FileNode Path: %v could not be opened -- error: %v\n", fn.FPath, err)
return err
}
fn.FPath = gi.FileName(effpath)
err = fn.Info.InitFile(string(fn.FPath))
if err != nil {
emsg := fmt.Errorf("giv.FileNode InitFileInfo Path %q: Error: %v", fn.FPath, err)
log.Println(emsg)
return emsg
}
return nil
}
// UpdateNode updates information in node based on its associated file in FPath.
// This is intended to be called ad-hoc for individual nodes that might need
// updating -- use ReadDir for mass updates as it is more efficient.
func (fn *FileNode) UpdateNode() error {
err := fn.InitFileInfo()
if err != nil {
return err
}
if fn.IsIrregular() {
return nil
}
if fn.IsDir() {
openAll := fn.FRoot.InOpenAll && !fn.Info.IsHidden()
if openAll || fn.FRoot.IsDirOpen(fn.FPath) {
fn.SetOpen()
fn.FRoot.SetDirOpen(fn.FPath)
repo, rnode := fn.Repo()
if repo != nil {
rnode.UpdateRepoFiles()
}
fn.UpdateDir()
}
} else {
repo, _ := fn.Repo()
if repo != nil {
fn.Info.Vcs, _ = repo.Status(string(fn.FPath))
}
fn.UpdateSig()
fn.FRoot.UpdateSig()
}
return nil
}
// OpenDir opens given directory node
func (fn *FileNode) OpenDir() {
fn.SetOpen()
fn.FRoot.SetDirOpen(fn.FPath)
fn.UpdateNode()
}
// CloseDir closes given directory node -- updates memory state
func (fn *FileNode) CloseDir() {
fn.SetClosed()
fn.FRoot.SetDirClosed(fn.FPath)
// note: not doing anything with open files within directory..
}
// SortBy determines how to sort the files in the directory -- default is alpha by name,
// optionally can be sorted by modification time.
func (fn *FileNode) SortBy(modTime bool) {
fn.FRoot.SetDirSortBy(fn.FPath, modTime)
fn.UpdateNode()
fn.UpdateSig() // make sure
}
// OpenAll opens all directories under this one
func (fn *FileNode) OpenAll() {
fn.FRoot.InOpenAll = true
fn.SetOpen()
fn.FRoot.SetDirOpen(fn.FPath)
fn.UpdateNode()
fn.FRoot.InOpenAll = false
// note: FileTreeView must actually do the open all too!
}
// CloseAll closes all directories under this one, this included
func (fn *FileNode) CloseAll() {
fn.SetClosed()
fn.FRoot.SetDirClosed(fn.FPath)
fn.FuncDownMeFirst(0, fn, func(k ki.Ki, level int, d interface{}) bool {
sfn := k.Embed(KiT_FileNode).(*FileNode)
if sfn.IsDir() {
sfn.SetClosed()
sfn.FRoot.SetDirClosed(sfn.FPath)
}
return ki.Continue
})
// note: FileTreeView must actually do the close all too!
}
// OpenBuf opens the file in its buffer if it is not already open.
// returns true if file is newly opened
func (fn *FileNode) OpenBuf() (bool, error) {
if fn.IsDir() {
err := fmt.Errorf("giv.FileNode cannot open directory in editor: %v", fn.FPath)
log.Println(err.Error())
return false, err
}
if fn.Buf != nil {
if fn.Buf.Filename == fn.FPath { // close resets filename
return false, nil
}
} else {
fn.Buf = &TextBuf{}
fn.Buf.InitName(fn.Buf, fn.Nm)
fn.Buf.AddFileNode(fn)
}
fn.Buf.Hi.Style = FileNodeHiStyle
return true, fn.Buf.Open(fn.FPath)
}
// CloseBuf closes the file in its buffer if it is open -- returns true if closed
// Connect to the fn.Buf.TextBufSig and look for the TextBufClosed signal to be
// notified when the buffer is closed.
func (fn *FileNode) CloseBuf() bool {
if fn.Buf == nil {
return false
}
fn.Buf.Close(nil)
fn.Buf = nil
fn.SetClosed()
return true
}
// FindDirNode finds directory node by given path -- must be a relative
// path already rooted at tree, or absolute path within tree
func (fn *FileNode) FindDirNode(path string) (*FileNode, error) {
rp := fn.RelPath(gi.FileName(path))
if rp == "" {
return nil, fmt.Errorf("FindDirNode: path: %s is not relative to this node's path: %s", path, fn.FPath)
}
if rp == "." {
return fn, nil
}
dirs := filepath.SplitList(rp)
dir := dirs[0]
dni, err := fn.ChildByNameTry(dir, 0)
if err != nil {
return nil, err
}
dn := dni.Embed(KiT_FileNode).(*FileNode)
if len(dirs) == 1 {
if dn.IsDir() {
return dn, nil
}
return nil, fmt.Errorf("FindDirNode: item at path: %s is not a Directory", path)
}
return dn.FindDirNode(filepath.Join(dirs[1:]...))
}
// RelPath returns the relative path from node for given full path
func (fn *FileNode) RelPath(fpath gi.FileName) string {
return RelFilePath(string(fpath), string(fn.FPath))
}
// DirsTo opens all the directories above the given filename, and returns the node
// for element at given path (can be a file or directory itself -- not opened -- just returned)
func (fn *FileNode) DirsTo(path string) (*FileNode, error) {
pth, err := filepath.Abs(path)
if err != nil {
log.Printf("giv.FileNode DirsTo path %v could not be turned into an absolute path: %v\n", path, err)
return nil, err
}
rpath := fn.RelPath(gi.FileName(pth))
if rpath == "." {
return fn, nil
}
dirs := strings.Split(rpath, string(filepath.Separator))
cfn := fn
sz := len(dirs)
for i := 0; i < sz; i++ {
dr := dirs[i]
sfni, err := cfn.ChildByNameTry(dr, 0)
if err != nil {
if i == sz-1 { // ok for terminal -- might not exist yet
return cfn, nil
} else {
err = fmt.Errorf("giv.FileNode could not find node %v in: %v", dr, cfn.FPath)
// log.Println(err)
return nil, err
}
}
sfn := sfni.Embed(KiT_FileNode).(*FileNode)
if sfn.IsDir() || i == sz-1 {
if i < sz-1 && !sfn.IsOpen() {
sfn.OpenDir()
} else {
cfn = sfn
}
} else {
err := fmt.Errorf("giv.FileNode non-terminal node %v is not a directory in: %v", dr, cfn.FPath)
log.Println(err)
return nil, err
}
cfn = sfn
}
return cfn, nil
}
// FindFile finds first node representing given file (false if not found) --
// looks for full path names that have the given string as their suffix, so
// you can include as much of the path (including whole thing) as is relevant
// to disambiguate. See FilesMatching for a list of files that match a given
// string.
func (fn *FileNode) FindFile(fnm string) (*FileNode, bool) {
if fnm == "" {
return nil, false
}
fneff := fnm
if len(fneff) > 2 && fneff[:2] == ".." { // relative path -- get rid of it and just look for relative part
dirs := strings.Split(fneff, string(filepath.Separator))
for i, dr := range dirs {
if dr != ".." {
fneff = filepath.Join(dirs[i:]...)
break
}
}
}
if efn, err := fn.FRoot.ExtFileNodeByPath(fnm); err == nil {
return efn, true
}
if strings.HasPrefix(fneff, string(fn.FPath)) { // full path
ffn, err := fn.DirsTo(fneff)
if err == nil {
return ffn, true
}
return nil, false
}
var ffn *FileNode
found := false
fn.FuncDownMeFirst(0, fn, func(k ki.Ki, level int, d interface{}) bool {
sfn := k.Embed(KiT_FileNode).(*FileNode)
if strings.HasSuffix(string(sfn.FPath), fneff) {
ffn = sfn
found = true
return ki.Break
}
return ki.Continue
})
return ffn, found
}
// FilesMatching returns list of all nodes whose file name contains given
// string (no regexp) -- ignoreCase transforms everything into lowercase
func (fn *FileNode) FilesMatching(match string, ignoreCase bool) []*FileNode {
mls := make([]*FileNode, 0)
if ignoreCase {
match = strings.ToLower(match)
}
fn.FuncDownMeFirst(0, fn, func(k ki.Ki, level int, d interface{}) bool {
sfn := k.Embed(KiT_FileNode).(*FileNode)
if ignoreCase {
nm := strings.ToLower(sfn.Nm)
if strings.Contains(nm, match) {
mls = append(mls, sfn)
}
} else {
if strings.Contains(sfn.Nm, match) {
mls = append(mls, sfn)
}
}
return ki.Continue
})
return mls
}
// FileNodeNameCount is used to report counts of different string-based things
// in the file tree
type FileNodeNameCount struct {
Name string
Count int
}
func FileNodeNameCountSort(ecs []FileNodeNameCount) {
sort.Slice(ecs, func(i, j int) bool {
return ecs[i].Count > ecs[j].Count
})
}
// FirstVCS returns the first VCS repository starting from this node and going down.
// also returns the node having that repository
func (fn *FileNode) FirstVCS() (vci.Repo, *FileNode) {
var repo vci.Repo
var rnode *FileNode
fn.FuncDownMeFirst(0, fn, func(k ki.Ki, level int, d interface{}) bool {
sfn := k.Embed(KiT_FileNode).(*FileNode)
if sfn.DirRepo != nil {
repo = sfn.DirRepo
rnode = sfn
return ki.Break
}
return ki.Continue
})
return repo, rnode
}
// FileExtCounts returns a count of all the different file extensions, sorted
// from highest to lowest.
// If cat is != filecat.Unknown then it only uses files of that type
// (e.g., filecat.Code to find any code files)
func (fn *FileNode) FileExtCounts(cat filecat.Cat) []FileNodeNameCount {
cmap := make(map[string]int, 20)