-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileinfo.go
491 lines (443 loc) · 13.7 KB
/
fileinfo.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
// 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 (
"fmt"
"io"
"io/ioutil"
"log"
"mime"
"os"
"path/filepath"
"strings"
"time"
"github.com/alecthomas/chroma/lexers"
"github.com/c2h5oh/datasize"
// "github.com/gabriel-vasile/mimetype" // too slow.
"github.com/goki/gi/gi"
"github.com/goki/ki"
"github.com/goki/ki/kit"
"github.com/h2non/filetype"
)
// FileInfo represents the information about a given file / directory,
// including icon, mimetype, etc
type FileInfo struct {
Ic gi.IconName `tableview:"no-header" desc:"icon for file"` // tableview:"no-header"
Name string `width:"40" desc:"name of the file, without any path"`
Size FileSize `desc:"size of the file in bytes"`
Kind string `width:"20" max-width:"20" desc:"type of file / directory -- shorter, more user-friendly version of mime type"`
Mime string `tableview:"-" desc:"full official mime type of the contents"`
Mode os.FileMode `desc:"file mode bits"`
ModTime FileTime `desc:"time that contents (only) were last modified"`
Path string `view:"-" tableview:"-" desc:"full path to file, including name -- for file functions"`
}
var KiT_FileInfo = kit.Types.AddType(&FileInfo{}, FileInfoProps)
// NewFileInfo returns a new FileInfo based on a filename -- directly returns
// filepath.Abs or os.Stat error on the given file. filename can be anything
// that works given current directory -- Path will contain the full
// filepath.Abs path, and Name will be just the filename.
func NewFileInfo(fname string) (*FileInfo, error) {
fi := &FileInfo{}
err := fi.InitFile(fname)
return fi, err
}
// InitFile initializes a FileInfo based on a filename -- directly returns
// filepath.Abs or os.Stat error on the given file. filename can be anything
// that works given current directory -- Path will contain the full
// filepath.Abs path, and Name will be just the filename.
func (fi *FileInfo) InitFile(fname string) error {
path, err := filepath.Abs(fname)
if err != nil {
return err
}
fi.Path = path
_, fi.Name = filepath.Split(path)
return fi.Stat()
}
// Stat runs os.Stat on file, returns any error directly but otherwise updates
// file info, including mime type, which then drives Kind and Icon -- this is
// the main function to call to update state.
func (fi *FileInfo) Stat() error {
info, err := os.Stat(fi.Path)
if err != nil {
return err
}
fi.Size = FileSize(info.Size())
fi.Mode = info.Mode()
fi.ModTime = FileTime(info.ModTime())
if info.IsDir() {
fi.Kind = "folder"
} else {
mtyp, _, err := MimeFromFile(fi.Path)
if err == nil {
fi.Mime = mtyp
fi.Kind = FileKindFromMime(fi.Mime)
}
}
icn, _ := fi.FindIcon()
fi.Ic = icn
return nil
}
// IsDir returns true if file is a directory (folder)
func (fi *FileInfo) IsDir() bool {
return fi.Mode.IsDir()
}
// IsExec returns true if file is an executable file
func (fi *FileInfo) IsExec() bool {
return fi.Mode&0111 != 0
}
// IsSymLink returns true if file is a symbolic link
func (fi *FileInfo) IsSymlink() bool {
return fi.Mode&os.ModeSymlink != 0
}
//////////////////////////////////////////////////////////////////////////////
// File ops
// Duplicate creates a copy of given file -- only works for regular files, not
// directories.
func (fi *FileInfo) Duplicate() error {
if fi.IsDir() {
err := fmt.Errorf("giv.Duplicate: cannot copy directory: %v", fi.Path)
log.Println(err)
return err
}
ext := filepath.Ext(fi.Path)
noext := strings.TrimSuffix(fi.Path, ext)
dst := noext + "_Copy" + ext
return CopyFile(dst, fi.Path, fi.Mode)
}
// Delete deletes this file -- does not work on directories (todo: fix)
func (fi *FileInfo) Delete() error {
if fi.IsDir() {
err := fmt.Errorf("giv.Delete: cannot deleted directory: %v", fi.Path)
log.Println(err)
return err
}
return os.Remove(fi.Path)
// note: we should be deleted now!
}
// Rename renames file to new name
func (fi *FileInfo) Rename(newpath string) error {
if newpath == "" {
err := fmt.Errorf("giv.Rename: new name is empty")
log.Println(err)
return err
}
if newpath == fi.Path {
return nil
}
ndir, np := filepath.Split(newpath)
if ndir == "" {
if np == fi.Name {
return nil
}
dir, _ := filepath.Split(fi.Path)
newpath = filepath.Join(dir, newpath)
}
err := os.Rename(fi.Path, newpath)
if err == nil {
fi.InitFile(newpath)
}
return err
}
// MimeFromFile gets mime type from file, using Gabriel Vasile's mimetype
// package, mime.TypeByExtension, the chroma syntax highlighter,
// CustomExtMimeMap, and finally FileExtMimeMap. Use the mimetype package's
// extension mechanism to add further content-based matchers as needed, and
// set CustomExtMimeMap to your own map or call AddCustomExtMime for
// extension-based ones.
func MimeFromFile(fname string) (mtype, ext string, err error) {
// mtyp, ext, err := mimetype.DetectFile(fname) // too slow
mtypt, err := filetype.MatchFile(fname)
ptyp := ""
isplain := false
if err == nil {
mtyp := mtypt.MIME.Value
ext = mtypt.Extension
if strings.HasPrefix(mtyp, "text/plain") {
isplain = true
ptyp = mtyp
} else if mtyp != "" {
return mtyp, ext, err
}
}
ext = filepath.Ext(fname)
mtyp := mime.TypeByExtension(ext)
if mtyp != "" {
return mtyp, strings.ToLower(ext), nil
}
lexer := lexers.Match(fname) // todo: could get start of file and pass to
// Analyze, but might be too slow..
if lexer != nil {
config := lexer.Config()
if len(config.MimeTypes) > 0 {
mtyp = config.MimeTypes[0]
return mtyp, ext, nil
}
mtyp := "application/" + strings.ToLower(config.Name)
return mtyp, ext, nil
}
ext = strings.ToLower(ext)
if CustomExtMimeMap != nil {
if mtyp, ok := CustomExtMimeMap[ext]; ok {
return mtyp, ext, nil
}
}
if mtyp, ok := FileExtMimeMap[ext]; ok {
return mtyp, ext, nil
}
if isplain {
return ptyp, ext, nil
}
return "", ext, fmt.Errorf("giv.MimeFromFile could not find mime type for ext: %v file: %v", ext, fname)
}
// FileKindFromMime returns simplfied Kind description based on the given full
// mime type string. Strips out application/ prefix, and converts all the
// chroma-based mime-types to their basic names
func FileKindFromMime(mime string) string {
if CustomMimeToKindMap != nil {
if kind, ok := CustomMimeToKindMap[mime]; ok {
return kind
}
}
MimeToKindMapInit()
if kind, ok := MimeToKindMap[mime]; ok {
return kind
}
// todo: get rid of charset
if csidx := strings.Index(mime, "; charset="); csidx > 0 {
mime = mime[:csidx]
}
switch {
case strings.HasPrefix(mime, "application/"):
return strings.TrimPrefix(mime, "application/")
}
return mime
}
// MimeToKindMapInit makes sure the MimeToKindMap is initialized from
// InitMimeToKindMap plus chroma lexer types.
func MimeToKindMapInit() {
if MimeToKindMap != nil {
return
}
MimeToKindMap = InitMimeToKindMap
for _, l := range lexers.Registry.Lexers {
config := l.Config()
nm := strings.ToLower(config.Name)
if len(config.MimeTypes) > 0 {
mtyp := config.MimeTypes[0]
MimeToKindMap[mtyp] = nm
} else {
MimeToKindMap["application/"+nm] = nm
}
}
}
// FindIcon uses file info to find an appropriate icon for this file -- uses
// Kind string first to find a correspondingly-named icon, and then tries the
// extension. Returns true on success.
func (fi *FileInfo) FindIcon() (gi.IconName, bool) {
kind := fi.Kind
icn := gi.IconName(kind)
if icn.IsValid() {
return icn, true
}
kind = strings.ToLower(kind)
icn = gi.IconName(kind)
if icn.IsValid() {
return icn, true
}
if fi.IsDir() {
return gi.IconName("folder"), true
}
if icn = "file-" + gi.IconName(kind); icn.IsValid() {
return icn, true
}
if ms, ok := KindToIconMap[kind]; ok {
if icn = gi.IconName(ms); icn.IsValid() {
return icn, true
}
}
if strings.Contains(kind, "/") {
si := strings.IndexByte(kind, '/')
typ := kind[:si]
subtyp := kind[si+1:]
if icn = "file-" + gi.IconName(subtyp); icn.IsValid() {
return icn, true
}
if icn = gi.IconName(subtyp); icn.IsValid() {
return icn, true
}
if ms, ok := KindToIconMap[string(subtyp)]; ok {
if icn = gi.IconName(ms); icn.IsValid() {
return icn, true
}
}
if icn = "file-" + gi.IconName(typ); icn.IsValid() {
return icn, true
}
if icn = gi.IconName(typ); icn.IsValid() {
return icn, true
}
if ms, ok := KindToIconMap[string(typ)]; ok {
if icn = gi.IconName(ms); icn.IsValid() {
return icn, true
}
}
}
ext := filepath.Ext(fi.Name)
if ext != "" {
if icn = gi.IconName(ext[1:]); icn.IsValid() {
return icn, true
}
}
icn = gi.IconName("none")
return icn, false
}
var FileInfoProps = ki.Props{
"CtxtMenu": ki.PropSlice{
{"Duplicate", ki.Props{
"updtfunc": ActionUpdateFunc(func(fii interface{}, act *gi.Action) {
fi := fii.(*FileInfo)
act.SetInactiveState(fi.IsDir())
}),
}},
{"Delete", ki.Props{
"desc": "Ok to delete this file? This is not undoable and is not moving to trash / recycle bin",
"confirm": true,
"updtfunc": ActionUpdateFunc(func(fii interface{}, act *gi.Action) {
fi := fii.(*FileInfo)
act.SetInactiveState(fi.IsDir())
}),
}},
{"Rename", ki.Props{
"desc": "Rename file to new file name",
"Args": ki.PropSlice{
{"New Name", ki.Props{
"default-field": "Name",
}},
},
}},
},
}
//////////////////////////////////////////////////////////////////////////////
// FileTime, FileSize
// Note: can get all the detailed birth, access, change times from this package
// "github.com/djherbis/times"
// FileTime provides a default String format for file modification times, and
// other useful methods -- will plug into ValueView with date / time editor.
type FileTime time.Time
// Int satisfies the ints.Inter interface for sorting etc
func (ft FileTime) Int() int64 {
return (time.Time(ft)).Unix()
}
// FromInt satisfies the ints.Inter interface
func (ft *FileTime) FromInt(val int64) {
*ft = FileTime(time.Unix(val, 0))
}
func (ft FileTime) String() string {
return (time.Time)(ft).Format("Mon Jan 2 15:04:05 MST 2006")
}
func (ft FileTime) MarshalBinary() ([]byte, error) {
return time.Time(ft).MarshalBinary()
}
func (ft FileTime) MarshalJSON() ([]byte, error) {
return time.Time(ft).MarshalJSON()
}
func (ft FileTime) MarshalText() ([]byte, error) {
return time.Time(ft).MarshalText()
}
func (ft *FileTime) UnmarshalBinary(data []byte) error {
return (*time.Time)(ft).UnmarshalBinary(data)
}
func (ft *FileTime) UnmarshalJSON(data []byte) error {
return (*time.Time)(ft).UnmarshalJSON(data)
}
func (ft *FileTime) UnmarshalText(data []byte) error {
return (*time.Time)(ft).UnmarshalText(data)
}
type FileSize datasize.ByteSize
// Int satisfies the kit.Inter interface for sorting etc
func (fs FileSize) Int() int64 {
return int64(fs) // note: is actually uint64
}
// FromInt satisfies the ints.Inter interface
func (fs *FileSize) FromInt(val int64) {
*fs = FileSize(val)
}
func (fs FileSize) String() string {
return (datasize.ByteSize)(fs).HumanReadable()
}
//////////////////////////////////////////////////////////////////////////////
// CopyFile
// here's all the discussion about why CopyFile is not in std lib:
// https://old.reddit.com/r/golang/comments/3lfqoh/why_golang_does_not_provide_a_copy_file_func/
// https://github.com/golang/go/issues/8868
// CopyFile copies the contents from src to dst atomically.
// If dst does not exist, CopyFile creates it with permissions perm.
// If the copy fails, CopyFile aborts and dst is preserved.
func CopyFile(dst, src string, perm os.FileMode) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
tmp, err := ioutil.TempFile(filepath.Dir(dst), "")
if err != nil {
return err
}
_, err = io.Copy(tmp, in)
if err != nil {
tmp.Close()
os.Remove(tmp.Name())
return err
}
if err = tmp.Close(); err != nil {
os.Remove(tmp.Name())
return err
}
if err = os.Chmod(tmp.Name(), perm); err != nil {
os.Remove(tmp.Name())
return err
}
return os.Rename(tmp.Name(), dst)
}
//////////////////////////////////////////////////////////////////////////////
// Mime type / Icon name maps
// FileExtMimeMap is the builtin map of extensions (lowercase) to mime types
// -- used as a last resort when everything else fails!
var FileExtMimeMap = map[string]string{
".gide": "application/gide",
".dmg": "application/x-apple-diskimage",
}
// CustomExtMimeMap can be set to your own map of extensions (lowercase) to
// mime types to cover any special cases needed for your app, not otherwise
// covered
var CustomExtMimeMap map[string]string
// AddCustomExtMime adds given extension (lowercase), mime to the
// FileExtMimeMap -- see also CustomExtMimeMap to install a full map.
func AddCustomExtMime(ext, mime string) {
FileExtMimeMap[ext] = mime
}
// MimeToKindMap maps from mime type names to kind names. Add any standard
// manual cases to InitMimeToKindMap, which will be used here along with the
// chroma lexer mime to name mapping.
var MimeToKindMap map[string]string
// InitMimeToKindMap maps from mime type names to kind names. Add any
// standard manual cases here -- will be used as start of MimeToKindMap, which
// is kept empty as trigger for initialization.
var InitMimeToKindMap = map[string]string{}
// CustomMimeToKindMap maps from mime type names to kind names, and can be set
// by user for any special cases. This is used before the standard one.
var CustomMimeToKindMap map[string]string
// KindToIconMap has special cases for mapping mime type to icon, for those
// that basic string doesn't work
var KindToIconMap = map[string]string{
"svg+xml": "svg",
"msword": "file-word",
"postscript": "file-pdf",
"vnd.ms-excel": "file-excel",
"vnd.ms-powerpoint": "file-powerpoint",
"x-apple-diskimage": "file-zip",
"octet-stream": "file-binary",
"gzip": "file-zip",
}