-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.go
More file actions
143 lines (116 loc) · 2.34 KB
/
loader.go
File metadata and controls
143 lines (116 loc) · 2.34 KB
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
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
)
// FindProjectDir scans current directory and goes up until find a project
func FindProjectDir(dir string) (string, error) {
// Convert to abs
if !path.IsAbs(dir) {
absDir, err := filepath.Abs(dir)
if err != nil {
return "", fmt.Errorf("project not found: %w", err)
}
dir = absDir
}
if isDir(dir, ".made") || isFile(dir, "Madefile") {
return dir, nil
}
if dir == "/" {
return "", fmt.Errorf("project not found")
}
return FindProjectDir(filepath.Dir(dir))
}
func isDir(paths ...string) bool {
p := path.Join(paths...)
dir, err := os.Stat(p)
return err == nil && dir.IsDir()
}
func isFile(paths ...string) bool {
p := path.Join(paths...)
file, err := os.Stat(p)
return err == nil && !file.IsDir()
}
func LoadProject(dir string) (*Project, error) {
prj := &Project{
Dir: dir,
}
f, err := loadFile(path.Join(dir, "Madefile"))
if err == nil {
prj.Files = []*File{f}
}
// Load .made files
files, err := loadDirectory(path.Join(dir, ".made"))
if err != nil {
return nil, err
}
prj.Files = append(prj.Files, files...)
// Load ~/.made files
config, err := os.UserConfigDir()
if err != nil {
log.Println("Can't load global tasks:", err)
} else {
files, err = loadDirectory(path.Join(config, "made"))
if err != nil {
return nil, err
}
for _, f := range files {
for _, t := range f.Tasks {
t.Global = true
}
}
}
prj.Files = append(prj.Files, files...)
return prj, nil
}
func loadDirectory(dir string) ([]*File, error) {
d, err := os.Open(dir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
entries, err := d.Readdir(0)
if err != nil {
return nil, err
}
files := []*File{}
for _, entry := range entries {
if entry.IsDir() {
continue
}
if strings.HasSuffix(entry.Name(), ".made") {
f, err := loadFile(path.Join(dir, entry.Name()))
if err != nil {
return nil, err
}
files = append(files, f)
}
}
return files, nil
}
func loadFile(path string) (*File, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
p, err := ParseString(string(data))
if err != nil {
return nil, err
}
f := &File{
Path: path,
Tasks: p.Tasks,
Vars: p.Vars,
}
for _, t := range f.Tasks {
t.File = f
}
return f, nil
}