-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
70 lines (60 loc) · 1.45 KB
/
file.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
package main
import (
"fmt"
"os"
"path"
"path/filepath"
mmap "github.com/edsrzf/mmap-go"
termutil "github.com/japanoise/termbox-util"
homedir "github.com/mitchellh/go-homedir"
)
type ZerzFile struct {
File *os.File
Filename string
FilenameWidth int
Filepath string
Bytes mmap.MMap
Size int64
}
func OpenFile(filename string) (*ZerzFile, error) {
absname, err := AbsPath(filename)
if err != nil {
return nil, fmt.Errorf("Can't get abspath: %s", err.Error())
}
file, err := os.OpenFile(absname, os.O_RDWR, 0)
if err != nil {
return nil, fmt.Errorf("Can't open file: %s", err.Error())
}
fs, err := file.Stat()
if err != nil {
file.Close()
return nil, fmt.Errorf("Can't stat file: %s", err.Error())
}
mm, err := mmap.Map(file, mmap.RDWR, 0)
if err != nil {
file.Close()
return nil, fmt.Errorf("Can't mmap file: %s", err.Error())
}
ret := ZerzFile{Filename: filepath.Base(absname), Filepath: absname,
Size: fs.Size(), Bytes: mm, File: file}
ret.FilenameWidth = termutil.RunewidthStr(ret.Filename)
return &ret, nil
}
func (zfile *ZerzFile) Close() {
zfile.Bytes.Unmap()
zfile.File.Close()
}
func AbsPath(filename string) (string, error) {
hdpath, perr := homedir.Expand(filename)
if perr != nil {
return filename, perr
}
if len(hdpath) > 0 && hdpath[0] == '/' {
return hdpath, nil
}
cwd, cerr := os.Getwd()
if cerr != nil {
return filename, cerr
}
return path.Join(cwd, filename), nil
}