-
Notifications
You must be signed in to change notification settings - Fork 8
/
filepath.go
99 lines (83 loc) · 1.73 KB
/
filepath.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
package kak
import (
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
)
type Filepath struct {
Name string
Line int
Column int
Raw []string
}
func NewFilepath(args []string) *Filepath {
fp := &Filepath{Raw: args}
if len(args) > 0 {
name, line, col, err := fp.parse()
if err != nil {
return nil
}
fp.Name = name
fp.Line = line
fp.Column = col
}
return fp
}
func (fp *Filepath) Dir() (dir string, err error) {
info, err := os.Stat(fp.Name)
if err != nil {
return "", err
}
if info.IsDir() {
dir = fp.Name
} else {
dir = path.Dir(fp.Name)
}
return
}
func (fp *Filepath) ParseGitDir() string {
dir, _ := fp.Dir()
gitOut, err := exec.Command("git", "-C", dir, "rev-parse", "--show-toplevel").Output()
if err != nil {
return ""
}
sessName := strings.Trim(strings.TrimSpace(strings.ReplaceAll(path.Base(string(gitOut)), ".", "-")), "-")
return sessName
}
func (fp *Filepath) parse() (absName string, line, col int, err error) {
r := fp.Raw
rawName := r[0]
if filepath.IsAbs(rawName) {
absName = rawName
} else {
cwd, _ := os.Getwd()
absName = path.Join(cwd, rawName)
}
if len(r) > 1 && strings.HasPrefix(r[1], "+") {
if strings.Contains(r[1], ":") {
lineStr := strings.ReplaceAll(strings.Split(r[1], ":")[0], "+", "")
lineInt, err := strconv.Atoi(lineStr)
if err != nil {
return "", 0, 0, err
}
line = lineInt
colStr := strings.Split(r[1], ":")[1]
colInt, err := strconv.Atoi(colStr)
if err != nil {
return "", 0, 0, err
}
col = colInt
} else {
lineStr := strings.ReplaceAll(r[1], "+", "")
lineInt, err := strconv.Atoi(lineStr)
if err != nil {
return "", 0, 0, err
}
line = lineInt
}
}
return absName, line, col, err
}