1package bp2build
2
3import (
4	"fmt"
5	"io/ioutil"
6	"os"
7	"path/filepath"
8
9	"android/soong/shared"
10)
11
12// A tree structure that describes what to do at each directory in the created
13// symlink tree. Currently it is used to enumerate which files/directories
14// should be excluded from symlinking. Each instance of "node" represents a file
15// or a directory. If excluded is true, then that file/directory should be
16// excluded from symlinking. Otherwise, the node is not excluded, but one of its
17// descendants is (otherwise the node in question would not exist)
18type node struct {
19	name     string
20	excluded bool // If false, this is just an intermediate node
21	children map[string]*node
22}
23
24// Ensures that the a node for the given path exists in the tree and returns it.
25func ensureNodeExists(root *node, path string) *node {
26	if path == "" {
27		return root
28	}
29
30	if path[len(path)-1] == '/' {
31		path = path[:len(path)-1] // filepath.Split() leaves a trailing slash
32	}
33
34	dir, base := filepath.Split(path)
35
36	// First compute the parent node...
37	dn := ensureNodeExists(root, dir)
38
39	// then create the requested node as its direct child, if needed.
40	if child, ok := dn.children[base]; ok {
41		return child
42	} else {
43		dn.children[base] = &node{base, false, make(map[string]*node)}
44		return dn.children[base]
45	}
46}
47
48// Turns a list of paths to be excluded into a tree made of "node" objects where
49// the specified paths are marked as excluded.
50func treeFromExcludePathList(paths []string) *node {
51	result := &node{"", false, make(map[string]*node)}
52
53	for _, p := range paths {
54		ensureNodeExists(result, p).excluded = true
55	}
56
57	return result
58}
59
60// Calls readdir() and returns it as a map from the basename of the files in dir
61// to os.FileInfo.
62func readdirToMap(dir string) map[string]os.FileInfo {
63	entryList, err := ioutil.ReadDir(dir)
64	result := make(map[string]os.FileInfo)
65
66	if err != nil {
67		if os.IsNotExist(err) {
68			// It's okay if a directory doesn't exist; it just means that one of the
69			// trees to be merged contains parts the other doesn't
70			return result
71		} else {
72			fmt.Fprintf(os.Stderr, "Cannot readdir '%s': %s\n", dir, err)
73			os.Exit(1)
74		}
75	}
76
77	for _, fi := range entryList {
78		result[fi.Name()] = fi
79	}
80
81	return result
82}
83
84// Creates a symbolic link at dst pointing to src
85func symlinkIntoForest(topdir, dst, src string) {
86	err := os.Symlink(shared.JoinPath(topdir, src), shared.JoinPath(topdir, dst))
87	if err != nil {
88		fmt.Fprintf(os.Stderr, "Cannot create symlink at '%s' pointing to '%s': %s", dst, src, err)
89		os.Exit(1)
90	}
91}
92
93// Recursively plants a symlink forest at forestDir. The symlink tree will
94// contain every file in buildFilesDir and srcDir excluding the files in
95// exclude. Collects every directory encountered during the traversal of srcDir
96// into acc.
97func plantSymlinkForestRecursive(topdir string, forestDir string, buildFilesDir string, srcDir string, exclude *node, acc *[]string, okay *bool) {
98	if exclude != nil && exclude.excluded {
99		// This directory is not needed, bail out
100		return
101	}
102
103	*acc = append(*acc, srcDir)
104	srcDirMap := readdirToMap(shared.JoinPath(topdir, srcDir))
105	buildFilesMap := readdirToMap(shared.JoinPath(topdir, buildFilesDir))
106
107	allEntries := make(map[string]bool)
108	for n, _ := range srcDirMap {
109		allEntries[n] = true
110	}
111
112	for n, _ := range buildFilesMap {
113		allEntries[n] = true
114	}
115
116	err := os.MkdirAll(shared.JoinPath(topdir, forestDir), 0777)
117	if err != nil {
118		fmt.Fprintf(os.Stderr, "Cannot mkdir '%s': %s\n", forestDir, err)
119		os.Exit(1)
120	}
121
122	for f, _ := range allEntries {
123		if f[0] == '.' {
124			continue // Ignore dotfiles
125		}
126
127		// The full paths of children in the input trees and in the output tree
128		forestChild := shared.JoinPath(forestDir, f)
129		srcChild := shared.JoinPath(srcDir, f)
130		buildFilesChild := shared.JoinPath(buildFilesDir, f)
131
132		// Descend in the exclusion tree, if there are any excludes left
133		var excludeChild *node
134		if exclude == nil {
135			excludeChild = nil
136		} else {
137			excludeChild = exclude.children[f]
138		}
139
140		srcChildEntry, sExists := srcDirMap[f]
141		buildFilesChildEntry, bExists := buildFilesMap[f]
142		excluded := excludeChild != nil && excludeChild.excluded
143
144		if excluded {
145			continue
146		}
147
148		if !sExists {
149			if buildFilesChildEntry.IsDir() && excludeChild != nil {
150				// Not in the source tree, but we have to exclude something from under
151				// this subtree, so descend
152				plantSymlinkForestRecursive(topdir, forestChild, buildFilesChild, srcChild, excludeChild, acc, okay)
153			} else {
154				// Not in the source tree, symlink BUILD file
155				symlinkIntoForest(topdir, forestChild, buildFilesChild)
156			}
157		} else if !bExists {
158			if srcChildEntry.IsDir() && excludeChild != nil {
159				// Not in the build file tree, but we have to exclude something from
160				// under this subtree, so descend
161				plantSymlinkForestRecursive(topdir, forestChild, buildFilesChild, srcChild, excludeChild, acc, okay)
162			} else {
163				// Not in the build file tree, symlink source tree, carry on
164				symlinkIntoForest(topdir, forestChild, srcChild)
165			}
166		} else if srcChildEntry.IsDir() && buildFilesChildEntry.IsDir() {
167			// Both are directories. Descend.
168			plantSymlinkForestRecursive(topdir, forestChild, buildFilesChild, srcChild, excludeChild, acc, okay)
169		} else if !srcChildEntry.IsDir() && !buildFilesChildEntry.IsDir() {
170			// Neither is a directory. Prioritize BUILD files generated by bp2build
171			// over any BUILD file imported into external/.
172			fmt.Fprintf(os.Stderr, "Both '%s' and '%s' exist, symlinking the former to '%s'\n",
173				buildFilesChild, srcChild, forestChild)
174			symlinkIntoForest(topdir, forestChild, buildFilesChild)
175		} else {
176			// Both exist and one is a file. This is an error.
177			fmt.Fprintf(os.Stderr,
178				"Conflict in workspace symlink tree creation: both '%s' and '%s' exist and exactly one is a directory\n",
179				srcChild, buildFilesChild)
180			*okay = false
181		}
182	}
183}
184
185// Creates a symlink forest by merging the directory tree at "buildFiles" and
186// "srcDir" while excluding paths listed in "exclude". Returns the set of paths
187// under srcDir on which readdir() had to be called to produce the symlink
188// forest.
189func PlantSymlinkForest(topdir string, forest string, buildFiles string, srcDir string, exclude []string) []string {
190	deps := make([]string, 0)
191	os.RemoveAll(shared.JoinPath(topdir, forest))
192	excludeTree := treeFromExcludePathList(exclude)
193	okay := true
194	plantSymlinkForestRecursive(topdir, forest, buildFiles, srcDir, excludeTree, &deps, &okay)
195	if !okay {
196		os.Exit(1)
197	}
198	return deps
199}
200