/
workspace.go
100 lines (87 loc) · 2.03 KB
/
workspace.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
package core
import (
"errors"
"log"
"os"
"path/filepath"
"strings"
"github.com/chrisdail/pile/gitver"
)
type workspace struct {
Project
}
// Workspace project workspace
var Workspace = &workspace{}
// SetWorkingDir sets the workspace working directory
func (ws *workspace) SetDir(dir string) error {
if dir != "" {
if _, err := os.Stat(dir); os.IsNotExist(err) {
return err
}
ws.Dir = dir
} else {
var err error
ws.Dir, err = gitver.GitRootPath()
if err != nil {
return err
}
}
return nil
}
// ProjectPaths get paths for corresponding project names
func (ws *workspace) ProjectPaths(projects []string) []string {
if ws.Dir == "" {
log.Fatalln(errors.New("No workspace found"))
}
paths := make([]string, len(projects))
for i, project := range projects {
paths[i] = filepath.Join(ws.Dir, strings.ReplaceAll(project, ws.Dir, ""))
}
return paths
}
// DiscoverProjectPaths walks the workspace tree, searching for project paths
func (ws *workspace) DiscoverProjectPaths() ([]string, error) {
var paths []string
err := filepath.Walk(ws.Dir, func(path string, info os.FileInfo, err error) error {
if info.Name() == pileConfigName {
paths = append(paths, filepath.Dir(path))
}
return nil
})
return paths, err
}
// ProjectsFromArgs returns a set of configured projects from directory name args
func (ws *workspace) ProjectsFromArgs(args []string) ([]Project, error) {
var (
paths []string
err error
)
if len(args) == 0 {
paths, err = ws.DiscoverProjectPaths()
if err != nil {
return nil, err
}
} else {
paths = ws.ProjectPaths(args)
}
return ws.loadProjects(paths)
}
func (ws *workspace) loadProjects(paths []string) ([]Project, error) {
err := ws.Load(&ProjectConfig{})
if err != nil {
return nil, err
}
projects := make([]Project, len(paths))
for i, path := range paths {
if ws.Dir == path {
projects[i] = ws.Project
} else {
projects[i] = Project{Dir: path}
err := projects[i].Load(&ws.Config)
if err != nil {
return projects, err
}
}
}
return projects, nil
}