Add per-directory build targets

Build a map of blueprint directory to modules built from that
directory, and then add phony rules to build.ninja that emulate
the behavior of mma in the current build system.

Also fixes checkbuild to depend on checkbuild files and installable
files, but not installed files.

Change-Id: I8bad6e93387940df7439dbd4554f6d79f924c65f
diff --git a/Android.bp b/Android.bp
index c9480c7..3eb86e5 100644
--- a/Android.bp
+++ b/Android.bp
@@ -80,7 +80,6 @@
     ],
     srcs: [
         "common/arch.go",
-        "common/checkbuild.go",
         "common/config.go",
         "common/defs.go",
         "common/env.go",
diff --git a/build.ninja.in b/build.ninja.in
index 988b2f9..2af6e08 100644
--- a/build.ninja.in
+++ b/build.ninja.in
@@ -53,7 +53,7 @@
 # Variant:
 # Type:    bootstrap_go_binary
 # Factory: github.com/google/blueprint/bootstrap.newGoBinaryModule
-# Defined: build/soong/Android.bp:186:1
+# Defined: build/soong/Android.bp:185:1
 
 build .bootstrap/androidbp/obj/androidbp.a: g.bootstrap.gc $
         ${g.bootstrap.srcDir}/build/soong/androidbp/cmd/androidbp.go $
@@ -77,7 +77,7 @@
 # Variant:
 # Type:    bootstrap_go_binary
 # Factory: github.com/google/blueprint/bootstrap.newGoBinaryModule
-# Defined: build/soong/Android.bp:162:1
+# Defined: build/soong/Android.bp:161:1
 
 build .bootstrap/androidmk/obj/androidmk.a: g.bootstrap.gc $
         ${g.bootstrap.srcDir}/build/soong/androidmk/cmd/androidmk/android.go $
@@ -103,7 +103,7 @@
 # Variant:
 # Type:    bootstrap_go_package
 # Factory: github.com/google/blueprint/bootstrap.newGoPackageModule
-# Defined: build/soong/Android.bp:175:1
+# Defined: build/soong/Android.bp:174:1
 
 build .bootstrap/androidmk-parser/pkg/android/soong/androidmk/parser.a: $
         g.bootstrap.gc $
@@ -334,7 +334,7 @@
 # Variant:
 # Type:    bootstrap_go_package
 # Factory: github.com/google/blueprint/bootstrap.newGoPackageModule
-# Defined: build/soong/Android.bp:94:1
+# Defined: build/soong/Android.bp:93:1
 
 build .bootstrap/soong-cc/pkg/android/soong/cc.a: g.bootstrap.gc $
         ${g.bootstrap.srcDir}/build/soong/cc/builder.go $
@@ -371,7 +371,6 @@
 
 build .bootstrap/soong-common/pkg/android/soong/common.a: g.bootstrap.gc $
         ${g.bootstrap.srcDir}/build/soong/common/arch.go $
-        ${g.bootstrap.srcDir}/build/soong/common/checkbuild.go $
         ${g.bootstrap.srcDir}/build/soong/common/config.go $
         ${g.bootstrap.srcDir}/build/soong/common/defs.go $
         ${g.bootstrap.srcDir}/build/soong/common/env.go $
@@ -409,7 +408,7 @@
 # Variant:
 # Type:    bootstrap_go_package
 # Factory: github.com/google/blueprint/bootstrap.newGoPackageModule
-# Defined: build/soong/Android.bp:119:1
+# Defined: build/soong/Android.bp:118:1
 
 build .bootstrap/soong-genrule/pkg/android/soong/genrule.a: g.bootstrap.gc $
         ${g.bootstrap.srcDir}/build/soong/genrule/genrule.go | $
@@ -447,7 +446,7 @@
 # Variant:
 # Type:    bootstrap_go_package
 # Factory: github.com/google/blueprint/bootstrap.newGoPackageModule
-# Defined: build/soong/Android.bp:139:1
+# Defined: build/soong/Android.bp:138:1
 
 build .bootstrap/soong-java/pkg/android/soong/java.a: g.bootstrap.gc $
         ${g.bootstrap.srcDir}/build/soong/java/app_builder.go $
@@ -560,7 +559,7 @@
 # Variant:
 # Type:    bootstrap_go_binary
 # Factory: github.com/google/blueprint/bootstrap.newGoBinaryModule
-# Defined: build/soong/Android.bp:132:1
+# Defined: build/soong/Android.bp:131:1
 
 build .bootstrap/soong_jar/obj/soong_jar.a: g.bootstrap.gc $
         ${g.bootstrap.srcDir}/build/soong/cmd/soong_jar/soong_jar.go | $
diff --git a/cmd/soong_build/main.go b/cmd/soong_build/main.go
index b7c4198..9ef0d06 100644
--- a/cmd/soong_build/main.go
+++ b/cmd/soong_build/main.go
@@ -81,7 +81,7 @@
 	ctx.RegisterEarlyMutator("test_per_src", cc.TestPerSrcMutator)
 
 	// Singletons
-	ctx.RegisterSingletonType("checkbuild", common.CheckbuildSingleton)
+	ctx.RegisterSingletonType("buildtarget", common.BuildTargetSingleton)
 	ctx.RegisterSingletonType("env", common.EnvSingleton)
 	ctx.RegisterSingletonType("logtags", java.LogtagsSingleton)
 
diff --git a/common/checkbuild.go b/common/checkbuild.go
deleted file mode 100644
index 17ec37f..0000000
--- a/common/checkbuild.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2015 Google Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package common
-
-import (
-	"github.com/google/blueprint"
-)
-
-func CheckbuildSingleton() blueprint.Singleton {
-	return &checkbuildSingleton{}
-}
-
-type checkbuildSingleton struct{}
-
-func (c *checkbuildSingleton) GenerateBuildActions(ctx blueprint.SingletonContext) {
-	deps := []string{}
-	ctx.VisitAllModules(func(module blueprint.Module) {
-		if a, ok := module.(AndroidModule); ok {
-			if len(a.base().checkbuildFiles) > 0 {
-				deps = append(deps, ctx.ModuleName(module)+"-checkbuild")
-			}
-		}
-	})
-
-	ctx.Build(pctx, blueprint.BuildParams{
-		Rule:      blueprint.Phony,
-		Outputs:   []string{"checkbuild"},
-		Implicits: deps,
-		// HACK: checkbuild should be an optional build, but force it enabled for now
-		//Optional:  true,
-	})
-}
diff --git a/common/module.go b/common/module.go
index ef7c63a..327aeca 100644
--- a/common/module.go
+++ b/common/module.go
@@ -194,6 +194,12 @@
 	noAddressSanitizer bool
 	installFiles       []string
 	checkbuildFiles    []string
+
+	// Used by buildTargetSingleton to create checkbuild and per-directory build targets
+	// Only set on the final variant of each module
+	installTarget    string
+	checkbuildTarget string
+	blueprintDir     string
 }
 
 func (a *AndroidModuleBase) base() *AndroidModuleBase {
@@ -273,6 +279,7 @@
 			Implicits: allInstalledFiles,
 		})
 		deps = append(deps, name)
+		a.installTarget = name
 	}
 
 	if len(allCheckbuildFiles) > 0 {
@@ -284,6 +291,7 @@
 			Optional:  true,
 		})
 		deps = append(deps, name)
+		a.checkbuildTarget = name
 	}
 
 	if len(deps) > 0 {
@@ -293,6 +301,8 @@
 			Implicits: deps,
 			Optional:  true,
 		})
+
+		a.blueprintDir = ctx.ModuleDir()
 	}
 }
 
@@ -424,6 +434,7 @@
 	})
 
 	a.installFiles = append(a.installFiles, fullInstallPath)
+	a.checkbuildFiles = append(a.checkbuildFiles, srcPath)
 	return fullInstallPath
 }
 
@@ -467,3 +478,52 @@
 	srcFiles = expandGlobs(ctx, srcFiles)
 	return srcFiles
 }
+
+func BuildTargetSingleton() blueprint.Singleton {
+	return &buildTargetSingleton{}
+}
+
+type buildTargetSingleton struct{}
+
+func (c *buildTargetSingleton) GenerateBuildActions(ctx blueprint.SingletonContext) {
+	checkbuildDeps := []string{}
+
+	dirModules := make(map[string][]string)
+
+	ctx.VisitAllModules(func(module blueprint.Module) {
+		if a, ok := module.(AndroidModule); ok {
+			blueprintDir := a.base().blueprintDir
+			installTarget := a.base().installTarget
+			checkbuildTarget := a.base().checkbuildTarget
+
+			if checkbuildTarget != "" {
+				checkbuildDeps = append(checkbuildDeps, checkbuildTarget)
+				dirModules[blueprintDir] = append(dirModules[blueprintDir], checkbuildTarget)
+			}
+
+			if installTarget != "" {
+				dirModules[blueprintDir] = append(dirModules[blueprintDir], installTarget)
+			}
+		}
+	})
+
+	// Create a top-level checkbuild target that depends on all modules
+	ctx.Build(pctx, blueprint.BuildParams{
+		Rule:      blueprint.Phony,
+		Outputs:   []string{"checkbuild"},
+		Implicits: checkbuildDeps,
+		// HACK: checkbuild should be an optional build, but force it enabled for now
+		//Optional:  true,
+	})
+
+	// Create a mm/<directory> target that depends on all modules in a directory
+	dirs := sortedKeys(dirModules)
+	for _, dir := range dirs {
+		ctx.Build(pctx, blueprint.BuildParams{
+			Rule:      blueprint.Phony,
+			Outputs:   []string{filepath.Join("mm", dir)},
+			Implicits: dirModules[dir],
+			Optional:  true,
+		})
+	}
+}
diff --git a/common/util.go b/common/util.go
index 599b3b1..0a0ed13 100644
--- a/common/util.go
+++ b/common/util.go
@@ -14,6 +14,8 @@
 
 package common
 
+import "sort"
+
 func JoinWithPrefix(strs []string, prefix string) string {
 	if len(strs) == 0 {
 		return ""
@@ -65,3 +67,12 @@
 	}
 	return string(ret)
 }
+
+func sortedKeys(m map[string][]string) []string {
+	s := make([]string, 0, len(m))
+	for k := range m {
+		s = append(s, k)
+	}
+	sort.Strings(s)
+	return s
+}