-
Notifications
You must be signed in to change notification settings - Fork 0
/
projtmpl.go
338 lines (275 loc) · 8.19 KB
/
projtmpl.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
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Copyright (C) 2017, 2018 Damon Revoe. All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"strings"
)
type fileProcessor func(sourcePathname, relativePathname string,
info os.FileInfo) error
// processAllFiles calls the processFile() function for every file in
// sourceDir. All hidden files and all files in hidden subdirectories
// as well as package definition files are skipped.
func processAllFiles(sourceDir string, processFile fileProcessor) error {
sourceDir = filepath.Clean(sourceDir)
sourceDirWithSlash := sourceDir + "/"
return filepath.Walk(sourceDir, func(sourcePathname string,
info os.FileInfo, err error) error {
if err != nil {
return err
}
// Ignore the top-level directory (sourceDir itself).
if len(sourcePathname) <= len(sourceDirWithSlash) {
return nil
}
// Panic if filepath.Walk() does not behave as expected.
if !strings.HasPrefix(sourcePathname, sourceDirWithSlash) {
panic(sourcePathname + " does not start with " +
sourceDirWithSlash)
}
// Relative pathname of the source file in the source
// directory (and the target file in the target directory).
relativePathname := sourcePathname[len(sourceDirWithSlash):]
// Ignore hidden files and the package definition file.
if filepath.Base(relativePathname)[0] == '.' {
if info.IsDir() {
return filepath.SkipDir
}
return nil
} else if info.IsDir() {
return nil
} else if relativePathname == packageDefinitionFilename {
return nil
}
return processFile(sourcePathname, relativePathname, info)
})
}
// directoryTree represents a directory structure.
// The 'entries' map contains directory entries.
// If an entry name resolves into nil, it's a file,
// otherwise, it's a subtree.
type directoryTree struct {
entries map[string]*directoryTree
}
// newDirectoryTree creates a new directory tree
// consisting of an empty root directory.
func newDirectoryTree() *directoryTree {
return &directoryTree{make(map[string]*directoryTree)}
}
// addFile adds the specified pathname to the directory tree.
func (dirTree *directoryTree) addFile(filePath string) {
pathComponents := strings.Split(filePath, "/")
nComp := len(pathComponents)
if nComp == 0 {
return
}
node := dirTree
for _, pathComponent := range pathComponents[:nComp-1] {
child := node.entries[pathComponent]
if child == nil {
child = newDirectoryTree()
node.entries[pathComponent] = child
}
node = child
}
node.entries[pathComponents[nComp-1]] = nil
}
// hasFile() can be used to check for whether the specified
// file is in the directory tree.
func (dirTree *directoryTree) hasFile(filePath string) bool {
pathComponents := strings.Split(filePath, "/")
nComp := len(pathComponents)
if nComp == 0 {
return false
}
node := dirTree
for _, pathComponent := range pathComponents[:nComp-1] {
child := node.entries[pathComponent]
if child == nil {
return false
}
node = child
}
entry, entryExists := node.entries[pathComponents[nComp-1]]
return entryExists && entry == nil
}
// subtree returns a pointer to the branch of the directory tree
// rooted at the specified pathname.
func (dirTree *directoryTree) subtree(pathname string) *directoryTree {
node := dirTree
for _, pathComponent := range strings.Split(pathname, "/") {
if pathComponent == "." {
continue
}
child := node.entries[pathComponent]
if child == nil {
return nil
}
node = child
}
return node
}
func listFiles(basePath string, dirTree *directoryTree) []string {
var list []string
basePath += "/"
for entry, child := range dirTree.entries {
if child == nil {
list = append(list, basePath+entry)
} else {
list = append(list, listFiles(basePath+entry, child)...)
}
}
return list
}
func (dirTree *directoryTree) list() []string {
var list []string
for entry, child := range dirTree.entries {
if child == nil {
list = append(list, entry)
} else {
list = append(list, listFiles(entry, child)...)
}
}
sort.Strings(list)
return list
}
func linkFilesFromSourceDir(pd *packageDefinition,
projectDir string) (*directoryTree, bool, error) {
dirTree := newDirectoryTree()
sourceDir := filepath.Dir(pd.pathname)
changesMade := false
linkFile := func(sourcePathname, relativePathname string,
sourceFileInfo os.FileInfo) error {
dirTree.addFile(relativePathname)
targetPathname := path.Join(projectDir, relativePathname)
targetFileInfo, err := os.Lstat(targetPathname)
if err == nil {
if (targetFileInfo.Mode() & os.ModeSymlink) != 0 {
originalLink, err := os.Readlink(targetPathname)
if err != nil {
return err
}
if originalLink == sourcePathname {
return nil
}
}
if err = os.Remove(targetPathname); err != nil {
return err
}
}
fmt.Println("L", targetPathname)
if err = os.MkdirAll(filepath.Dir(targetPathname),
os.ModePerm); err != nil {
return err
}
changesMade = true
return os.Symlink(sourcePathname, targetPathname)
}
err := processAllFiles(sourceDir, linkFile)
return dirTree, changesMade, err
}
func pathnamesNotInDir(pathnameTemplate string, params templateParams,
dirTree *directoryTree) []outputFileParams {
var fileParams []outputFileParams
for _, fp := range expandPathnameTemplate(pathnameTemplate, params) {
if !dirTree.hasFile(fp.filename) {
fileParams = append(fileParams, fp)
}
}
return fileParams
}
// generateBuildFilesFromProjectTemplate generates an output file inside
// 'projectDir' with the same relative pathname as the respective source
// file in 'templateDir'.
func generateBuildFilesFromProjectTemplate(templateDir,
projectDir string, pd *packageDefinition) (bool, error) {
dirTree, changesMade, err := linkFilesFromSourceDir(pd, projectDir)
if err != nil {
return false, err
}
generateFile := func(sourcePathname, relativePathname string,
sourceFileInfo os.FileInfo) error {
fileParams := pathnamesNotInDir(relativePathname,
pd.params, dirTree)
if len(fileParams) == 0 {
return nil
}
// Read the contents of the template file. Cannot use
// template.ParseFiles() because a Funcs() call must be
// made between New() and Parse().
templateContents, err := ioutil.ReadFile(sourcePathname)
if err != nil {
return err
}
filesUpdated, err := generateFilesFromProjectFileTemplate(
projectDir, relativePathname, templateContents,
sourceFileInfo.Mode(), pd, dirTree, fileParams)
if err != nil {
return err
}
if filesUpdated {
changesMade = true
}
return nil
}
err = processAllFiles(templateDir, generateFile)
return changesMade, err
}
// embeddedTemplateFile defines the file mode and the contents
// of a single file that is a part of an embedded project template.
type embeddedTemplateFile struct {
pathname string
mode os.FileMode
contents []byte
}
// generateBuildFilesFromEmbeddedTemplate generates project build
// files from a built-in template pointed to by the 't' parameter.
func generateBuildFilesFromEmbeddedTemplate(t []embeddedTemplateFile,
projectDir string, pd *packageDefinition) (bool, error) {
dirTree, changesMade, err := linkFilesFromSourceDir(pd, projectDir)
if err != nil {
return false, err
}
for _, fileInfo := range append(t, commonTemplateFiles...) {
fileParams := pathnamesNotInDir(fileInfo.pathname,
pd.params, dirTree)
if len(fileParams) == 0 {
continue
}
filesUpdated, err := generateFilesFromProjectFileTemplate(
projectDir, fileInfo.pathname, fileInfo.contents,
fileInfo.mode, pd, dirTree, fileParams)
if err != nil {
return false, err
}
if filesUpdated {
changesMade = true
}
}
return changesMade, nil
}
func (pd *packageDefinition) getPackageGeneratorFunc(
packageDir string) (func() (bool, error), error) {
switch pd.packageType {
case "app", "application":
return func() (bool, error) {
return generateBuildFilesFromEmbeddedTemplate(
appTemplate, packageDir, pd)
}, nil
case "lib", "library":
return func() (bool, error) {
return generateBuildFilesFromEmbeddedTemplate(
libTemplate, packageDir, pd)
}, nil
default:
return nil, errors.New(pd.PackageName +
": unknown package type '" + pd.packageType + "'")
}
}