-
Notifications
You must be signed in to change notification settings - Fork 10
/
project.go
94 lines (78 loc) · 1.86 KB
/
project.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
//
// Copyright (c) 2018 Dean Jackson <[email protected]>
//
// MIT Licence. See http://opensource.org/licenses/MIT
//
// Created on 2018-01-27
//
package main
import (
"encoding/json"
"io/ioutil"
"path/filepath"
"strings"
// Supports comments in JSON, which is required to read
// Sublime Text or VS Code project files.
"github.com/tidwall/jsonc"
)
// Project is a Sublime Text or VS Code project.
type Project struct {
Path string // to project file
Folders []string
}
// Folder returns the path of the first project folder, falling
// back to the path of the folder containing the project file.
func (p Project) Folder() string {
if len(p.Folders) == 0 {
return filepath.Dir(p.Path)
}
return p.Folders[0]
}
// Name returns the name of the project (the filename w/o extension).
func (p Project) Name() string {
if p.Path == "" {
return ""
}
s, x := filepath.Base(p.Path), filepath.Ext(p.Path)
if x == "" || x == "." {
return s
}
return s[0 : len(s)-len(x)]
}
type sublimeProject struct {
Folders []sublimeFolder `json:"folders"`
}
type sublimeFolder struct {
Path string `json:"path"`
}
// NewProject reads a .sublime-project or .code-workspace file.
func NewProject(path string) (Project, error) {
var (
dir = filepath.Dir(path)
proj = Project{Path: path}
raw = sublimeProject{}
data []byte
err error
)
if data, err = ioutil.ReadFile(path); err != nil {
return proj, err
}
if err = json.Unmarshal(jsonc.ToJSON(data), &raw); err == nil {
proj.Folders = []string{}
for _, f := range raw.Folders {
if p := resolvePath(dir, f.Path); p != "" {
proj.Folders = append(proj.Folders, p)
}
}
}
return proj, err
}
func resolvePath(base, relpath string) string {
if strings.HasPrefix(relpath, "/") {
return relpath
}
if base == "" || relpath == "" {
return ""
}
return filepath.Clean(filepath.Join(base, relpath))
}