-
Notifications
You must be signed in to change notification settings - Fork 0
/
filetree.go
2622 lines (2444 loc) · 72 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"
"time"
"github.com/Masterminds/vcs"
"github.com/goki/gi/gi"
"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"`
}
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
}
// 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.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()
}
// 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)
}
}
// 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)
}
// 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)
}
// 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, ki.NonUniqueNames) // 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 true
})
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 true
})
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.PathUnique())
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, ki.NonUniqueNames) // 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
}
for _, tn := range config2 {
config1 = append(config1, tn)
}
} 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 {
log.Printf("giv.FileNode Path: %v could not be opened -- error: %v\n", effpath, 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
}
// 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)
fn.FuncDownMeFirst(0, fn, func(k ki.Ki, level int, d interface{}) bool {
sfn := k.Embed(KiT_FileNode).(*FileNode)
if cat != filecat.Unknown {
if sfn.Info.Cat != cat {
return ki.Continue
}
}
ext := strings.ToLower(filepath.Ext(sfn.Nm))
if ec, has := cmap[ext]; has {
cmap[ext] = ec + 1
} else {
cmap[ext] = 1
}
return ki.Continue
})
ecs := make([]FileNodeNameCount, len(cmap))
idx := 0
for key, val := range cmap {
ecs[idx] = FileNodeNameCount{Name: key, Count: val}
idx++
}
FileNodeNameCountSort(ecs)
return ecs
}
// LatestFileMod returns the most recent mod time of files in the tree.
// 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) LatestFileMod(cat filecat.Cat) time.Time {
tmod := time.Time{}
fn.FuncDownMeFirst(0, fn, func(k ki.Ki, level int, d interface{}) bool {
sfn := k.Embed(KiT_FileNode).(*FileNode)
if cat != filecat.Unknown {
if sfn.Info.Cat != cat {
return ki.Continue
}
}
ft := (time.Time)(sfn.Info.ModTime)
if ft.After(tmod) {
tmod = ft
}
return ki.Continue
})
return tmod
}
//////////////////////////////////////////////////////////////////////////////
// File ops
// OSOpenCommand returns the generic file 'open' command to open file with default app
// open on Mac, xdg-open on Linux, and start on Windows
func OSOpenCommand() string {
switch oswin.TheApp.Platform() {
case oswin.MacOS:
return "open"
case oswin.LinuxX11:
return "xdg-open"
case oswin.Windows:
return "start"
}
return "open"
}
// OpenFileDefault opens file with default app for that file type (os defined)
// runs open on Mac, xdg-open on Linux, and start on Windows
func (fn *FileNode) OpenFileDefault() error {
cstr := OSOpenCommand()
cmd := exec.Command(cstr, string(fn.FPath))
out, err := cmd.CombinedOutput()
fmt.Printf("%s\n", out)
return err
}
// OpenFileWith opens file with given command.
// does not wait for command to finish in this routine (separate routine Waits)
func (fn *FileNode) OpenFileWith(command string) error {
cmd := exec.Command(command, string(fn.FPath))
err := cmd.Start()
go func() {
err := cmd.Wait()
if err != nil {
log.Println(err)
}
}()
return err
}
// Duplicate creates a copy of given file -- only works for regular files, not
// directories
func (fn *FileNode) DuplicateFile() error {
_, err := fn.Info.Duplicate()
if err == nil && fn.Par != nil {
fnp := fn.Par.Embed(KiT_FileNode).(*FileNode)
fnp.UpdateNode()
}
return err
}
// DeleteFile deletes this file
func (fn *FileNode) DeleteFile() (err error) {
if fn.IsExternal() {
return nil
}
fn.CloseBuf()
repo, _ := fn.Repo()
if !fn.Info.IsDir() && repo != nil && fn.Info.Vcs >= vci.Stored {
// fmt.Printf("del repo: %v\n", fn.FPath)
err = repo.Delete(string(fn.FPath))
} else {
// fmt.Printf("del raw: %v\n", fn.FPath)
err = fn.Info.Delete()
}
if err == nil {
fn.Delete(true)
}
return err
}
// RenameFile renames file to new name
func (fn *FileNode) RenameFile(newpath string) (err error) {
if fn.IsExternal() {
return nil
}
fn.CloseBuf() // invalid after this point
orgpath := fn.FPath
newpath, err = fn.Info.Rename(newpath)
if len(newpath) == 0 || err != nil {
return err
}
if fn.IsDir() {
if fn.FRoot.IsDirOpen(orgpath) {
fn.FRoot.SetDirOpen(gi.FileName(newpath))
}
}
repo, _ := fn.Repo()
stored := false
if fn.IsDir() && !fn.HasChildren() {
err = os.Rename(string(orgpath), newpath)
} else if repo != nil && fn.Info.Vcs >= vci.Stored {
stored = true
err = repo.Move(string(orgpath), newpath)
} else {
err = os.Rename(string(orgpath), newpath)
}
if err == nil {
err = fn.Info.InitFile(newpath)
}
if err == nil {
fn.FPath = gi.FileName(fn.Info.Path)
fn.SetName(fn.Info.Name)
}
if stored {
fn.AddToVcs()
} else {
fn.UpdateSig()
fn.FRoot.UpdateDir() // need full update
}
return err
}
// NewFile makes a new file in given selected directory node
func (fn *FileNode) NewFile(filename string, addToVcs bool) {
if fn.IsExternal() {
return
}
ppath := string(fn.FPath)
if !fn.IsDir() {
ppath, _ = filepath.Split(ppath)
}