Skip to content

Commit a547cea

Browse files
simuonsAndre Rocha
authored andcommitted
Bundle input protos together with generated/compiled classes (bazel-contrib#949)
* Init * Pass bazel test //test/... with single _adjust_resources_path * adjust_resources_path returns string instead of tuple * remove prefix handling from ScalacProcessor.copyResources * Remove unused method * Remove resourceStripPrefix from CompileOptions * Remove special path handling from ScalacProcessor because it is done in rule_impls.bzl * Fix macro visibility * Remove print * Formatting * Add comments * more test cases * lint * Rebase on master * extract resources.bzl
1 parent 497524d commit a547cea

File tree

12 files changed

+198
-146
lines changed

12 files changed

+198
-146
lines changed

scala/private/phases/phase_compile.bzl

Lines changed: 4 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
#
44
# DOCUMENT THIS
55
#
6-
load("@bazel_skylib//lib:paths.bzl", _paths = "paths")
76
load("@bazel_skylib//lib:dicts.bzl", "dicts")
87
load("@bazel_tools//tools/jdk:toolchain_utils.bzl", "find_java_runtime_toolchain", "find_java_toolchain")
98
load(
@@ -12,10 +11,10 @@ load(
1211
)
1312
load(
1413
"@io_bazel_rules_scala//scala/private:rule_impls.bzl",
15-
_adjust_resources_path_by_default_prefixes = "adjust_resources_path_by_default_prefixes",
1614
_compile_scala = "compile_scala",
1715
_expand_location = "expand_location",
1816
)
17+
load(":resources.bzl", _resource_paths = "paths")
1918

2019
_java_extension = ".java"
2120

@@ -492,38 +491,10 @@ def _try_to_compile_java_jar(
492491
java_compilation_provider = provider,
493492
)
494493

495-
def _adjust_resources_path(resource, resource_strip_prefix):
496-
if resource_strip_prefix:
497-
return _adjust_resources_path_by_strip_prefix(resource, resource_strip_prefix)
498-
else:
499-
return _adjust_resources_path_by_default_prefixes(resource.path)
500-
501494
def _add_resources_cmd(ctx):
502-
res_cmd = []
503-
for f in ctx.files.resources:
504-
c_dir, res_path = _adjust_resources_path(
505-
f,
506-
ctx.attr.resource_strip_prefix,
507-
)
508-
target_path = res_path
509-
if target_path[0] == "/":
510-
target_path = target_path[1:]
511-
line = "{target_path}={c_dir}{res_path}\n".format(
512-
res_path = res_path,
513-
target_path = target_path,
514-
c_dir = c_dir,
515-
)
516-
res_cmd.extend([line])
517-
return "".join(res_cmd)
518-
519-
def _adjust_resources_path_by_strip_prefix(resource, resource_strip_prefix):
520-
path = resource.path
521-
prefix = _paths.join(resource.owner.workspace_root, resource_strip_prefix)
522-
if not path.startswith(prefix):
523-
fail("Resource file %s is not under the specified prefix %s to strip" % (path, prefix))
524-
525-
clean_path = path[len(prefix):]
526-
return prefix, clean_path
495+
paths = _resource_paths(ctx.files.resources, ctx.attr.resource_strip_prefix)
496+
lines = ["{target}={source}\n".format(target = p[0], source = p[1]) for p in paths]
497+
return "".join(lines)
527498

528499
def _collect_java_providers_of(deps):
529500
providers = []

scala/private/resources.bzl

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
load("@bazel_skylib//lib:paths.bzl", _paths = "paths")
2+
3+
def paths(resources, resource_strip_prefix):
4+
"""Return a list of path tuples (target, source) where:
5+
target - is a path in the archive (with given prefix stripped off)
6+
source - is an absolute path of the resource file
7+
8+
Tuple ordering is aligned with zipper format ie zip_path=file
9+
10+
Args:
11+
resources: list of file objects
12+
resource_strip_prefix: string to strip from resource path
13+
"""
14+
return [(_target_path(resource, resource_strip_prefix), resource.path) for resource in resources]
15+
16+
def _target_path(resource, resource_strip_prefix):
17+
path = _target_path_by_strip_prefix(resource, resource_strip_prefix) if resource_strip_prefix else _target_path_by_default_prefixes(resource.path)
18+
return _strip_prefix(path, "/")
19+
20+
def _target_path_by_strip_prefix(resource, resource_strip_prefix):
21+
# Start from absolute resource path and then strip roots so we get to correct short path
22+
# resource.short_path sometimes give weird results ie '../' prefix
23+
path = resource.path
24+
path = _strip_prefix(path, resource.owner.workspace_root + "/")
25+
path = _strip_prefix(path, resource.root.path + "/")
26+
27+
# proto_library translates strip_import_prefix to proto_source_root which includes root so we have to strip it
28+
prefix = _strip_prefix(resource_strip_prefix, resource.root.path + "/")
29+
if not path.startswith(prefix):
30+
fail("Resource file %s is not under the specified prefix %s to strip" % (path, prefix))
31+
return path[len(prefix):]
32+
33+
def _target_path_by_default_prefixes(path):
34+
# Here we are looking to find out the offset of this resource inside
35+
# any resources folder. We want to return the root to the resources folder
36+
# and then the sub path inside it
37+
dir_1, dir_2, rel_path = path.partition("resources")
38+
if rel_path:
39+
return rel_path
40+
41+
# The same as the above but just looking for java
42+
(dir_1, dir_2, rel_path) = path.partition("java")
43+
if rel_path:
44+
return rel_path
45+
46+
return path
47+
48+
def _strip_prefix(path, prefix):
49+
return path[len(prefix):] if path.startswith(prefix) else path

scala/private/rule_impls.bzl

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,7 @@ load(
2121
":common.bzl",
2222
_collect_plugin_paths = "collect_plugin_paths",
2323
)
24-
25-
def adjust_resources_path_by_default_prefixes(path):
26-
# Here we are looking to find out the offset of this resource inside
27-
# any resources folder. We want to return the root to the resources folder
28-
# and then the sub path inside it
29-
dir_1, dir_2, rel_path = path.partition("resources")
30-
if rel_path:
31-
return dir_1 + dir_2, rel_path
32-
33-
# The same as the above but just looking for java
34-
(dir_1, dir_2, rel_path) = path.partition("java")
35-
if rel_path:
36-
return dir_1 + dir_2, rel_path
37-
38-
return "", path
24+
load(":resources.bzl", _resource_paths = "paths")
3925

4026
def expand_location(ctx, flags):
4127
if hasattr(ctx.attr, "data"):
@@ -151,6 +137,7 @@ CurrentTarget: {current_target}
151137

152138
toolchain = ctx.toolchains["@io_bazel_rules_scala//scala:toolchain_type"]
153139
scalacopts = [ctx.expand_location(v, input_plugins) for v in toolchain.scalacopts + in_scalacopts]
140+
resource_paths = _resource_paths(resources, resource_strip_prefix)
154141

155142
scalac_args = """
156143
Classpath: {cp}
@@ -161,11 +148,9 @@ Manifest: {manifest}
161148
Plugins: {plugin_arg}
162149
PrintCompileTime: {print_compile_time}
163150
ExpectJavaOutput: {expect_java_output}
164-
ResourceDests: {resource_dest}
151+
ResourceTargets: {resource_targets}
152+
ResourceSources: {resource_sources}
165153
ResourceJars: {resource_jars}
166-
ResourceSrcs: {resource_src}
167-
ResourceShortPaths: {resource_short_paths}
168-
ResourceStripPrefix: {resource_strip_prefix}
169154
ScalacOpts: {scala_opts}
170155
SourceJars: {srcjars}
171156
DependencyAnalyzerMode: {dependency_analyzer_mode}
@@ -184,13 +169,8 @@ DiagnosticsFile: {diagnostics_output}
184169
files = _join_path(sources),
185170
srcjars = _join_path(all_srcjars.to_list()),
186171
# the resource paths need to be aligned in order
187-
resource_src = ",".join([f.path for f in resources]),
188-
resource_short_paths = ",".join([f.short_path for f in resources]),
189-
resource_dest = ",".join([
190-
adjust_resources_path_by_default_prefixes(f.short_path)[1]
191-
for f in resources
192-
]),
193-
resource_strip_prefix = resource_strip_prefix,
172+
resource_targets = ",".join([p[0] for p in resource_paths]),
173+
resource_sources = ",".join([p[1] for p in resource_paths]),
194174
resource_jars = _join_path(resource_jars),
195175
dependency_analyzer_mode = dependency_analyzer_mode,
196176
unused_dependency_checker_mode = unused_dependency_checker_mode,

scala_proto/private/scalapb_aspect.bzl

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@ def _compile_scala(
5151
output,
5252
scalapb_jar,
5353
deps_java_info,
54-
implicit_deps):
54+
implicit_deps,
55+
resources,
56+
resource_strip_prefix):
5557
manifest = ctx.actions.declare_file(
5658
label.name + "_MANIFEST.MF",
5759
sibling = scalapb_jar,
@@ -78,8 +80,8 @@ def _compile_scala(
7880
all_srcjars = depset([scalapb_jar]),
7981
transitive_compile_jars = merged_deps.transitive_compile_time_jars,
8082
plugins = [],
81-
resource_strip_prefix = "",
82-
resources = [],
83+
resource_strip_prefix = resource_strip_prefix,
84+
resources = resources,
8385
resource_jars = [],
8486
labels = {},
8587
in_scalacopts = [],
@@ -193,6 +195,8 @@ def _scalapb_aspect_impl(target, ctx):
193195
scalapb_file,
194196
deps,
195197
imps,
198+
compile_protos,
199+
"" if target_ti.proto_source_root == "." else target_ti.proto_source_root,
196200
)
197201
else:
198202
# this target is only an aggregation target

src/java/io/bazel/rulesscala/scalac/CompileOptions.java

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package io.bazel.rulesscala.scalac;
22

3-
3+
import java.util.ArrayList;
44
import java.util.HashMap;
55
import java.util.List;
66
import java.util.Map;
@@ -16,8 +16,7 @@ public class CompileOptions {
1616
public final String[] files;
1717
public final String[] sourceJars;
1818
public final String[] javaFiles;
19-
public final Map<String, Resource> resourceFiles;
20-
public final String resourceStripPrefix;
19+
public final List<Resource> resourceFiles;
2120
public final String[] resourceJars;
2221
public final String[] classpathResourceFiles;
2322
public final String[] directJars;
@@ -52,7 +51,6 @@ public CompileOptions(List<String> args) {
5251

5352
sourceJars = getCommaList(argMap, "SourceJars");
5453
resourceFiles = getResources(argMap);
55-
resourceStripPrefix = getOrEmpty(argMap, "ResourceStripPrefix");
5654
resourceJars = getCommaList(argMap, "ResourceJars");
5755
classpathResourceFiles = getCommaList(argMap, "ClasspathResourceSrcs");
5856

@@ -70,29 +68,21 @@ public CompileOptions(List<String> args) {
7068
diagnosticsFile = getOrElse(argMap, "DiagnosticsFile", null);
7169
}
7270

73-
private static Map<String, Resource> getResources(Map<String, String> args) {
74-
String[] keys = getCommaList(args, "ResourceSrcs");
75-
String[] dests = getCommaList(args, "ResourceDests");
76-
String[] shortPaths = getCommaList(args, "ResourceShortPaths");
77-
78-
if (keys.length != dests.length)
79-
throw new RuntimeException(
80-
String.format(
81-
"mismatch in resources: keys: %s dests: %s",
82-
getOrEmpty(args, "ResourceSrcs"), getOrEmpty(args, "ResourceDests")));
71+
private static List<Resource> getResources(Map<String, String> args) {
72+
String[] targets = getCommaList(args, "ResourceTargets");
73+
String[] sources = getCommaList(args, "ResourceSources");
8374

84-
if (keys.length != shortPaths.length)
75+
if (targets.length != sources.length)
8576
throw new RuntimeException(
8677
String.format(
87-
"mismatch in resources: keys: %s shortPaths: %s",
88-
getOrEmpty(args, "ResourceSrcs"), getOrEmpty(args, "ResourceShortPaths")));
78+
"mismatch in resources: targets: %s sources: %s",
79+
getOrEmpty(args, "ResourceTargets"), getOrEmpty(args, "ResourceSources")));
8980

90-
HashMap<String, Resource> res = new HashMap();
91-
for (int idx = 0; idx < keys.length; idx++) {
92-
Resource resource = new Resource(dests[idx], shortPaths[idx]);
93-
res.put(keys[idx], resource);
81+
List<Resource> resources = new ArrayList<Resource>();
82+
for (int idx = 0; idx < targets.length; idx++) {
83+
resources.add(new Resource(targets[idx], sources[idx]));
9484
}
95-
return res;
85+
return resources;
9686
}
9787

9888
private static HashMap<String, String> buildArgMap(List<String> lines) {
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
package io.bazel.rulesscala.scalac;
22

33
public class Resource {
4-
public final String destination;
5-
public final String shortPath;
4+
public final String target;
5+
public final String source;
66

7-
public Resource(String destination, String shortPath) {
8-
this.destination = destination;
9-
this.shortPath = shortPath;
7+
public Resource(String target, String source) {
8+
this.target = target;
9+
this.source = source;
1010
}
1111
}

src/java/io/bazel/rulesscala/scalac/ScalacProcessor.java

Lines changed: 6 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ public void processRequest(List<String> args) throws Exception {
7474
}
7575

7676
/** Copy the resources */
77-
copyResources(ops.resourceFiles, ops.resourceStripPrefix, tmpPath);
77+
copyResources(ops.resourceFiles, tmpPath);
7878

7979
/** Extract and copy resources from resource jars */
8080
copyResourceJars(ops.resourceJars, tmpPath);
@@ -313,44 +313,11 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc)
313313
}
314314
}
315315

316-
private static void copyResources(
317-
Map<String, Resource> resources, String resourceStripPrefix, Path dest) throws IOException {
318-
for (Entry<String, Resource> e : resources.entrySet()) {
319-
Path source = Paths.get(e.getKey());
320-
Resource resource = e.getValue();
321-
Path shortPath = Paths.get(resource.shortPath);
322-
String dstr;
323-
// Check if we need to modify resource destination path
324-
if (!"".equals(resourceStripPrefix)) {
325-
/**
326-
* NOTE: We are not using the Resource Hash Value as the destination path when
327-
* `resource_strip_prefix` present. The path in the hash value is computed by the
328-
* `_adjust_resources_path` in `scala.bzl`. These are the default paths, ie, path that are
329-
* automatically computed when there is no `resource_strip_prefix` present. But when
330-
* `resource_strip_prefix` is present, we need to strip the prefix from the Source Path and
331-
* use that as the new destination path Refer Bazel -> BazelJavaRuleClasses.java#L227 for
332-
* details
333-
*/
334-
dstr = getResourcePath(shortPath, resourceStripPrefix);
335-
} else {
336-
dstr = resource.destination;
337-
}
338-
339-
if (dstr.charAt(0) == '/') {
340-
// we don't want to copy to an absolute destination
341-
dstr = dstr.substring(1);
342-
}
343-
if (dstr.startsWith("../")) {
344-
// paths to external repositories, for some reason, start with a leading ../
345-
// we don't want to copy the resource out of our temporary directory, so
346-
// instead we replace ../ with external/
347-
// since "external" is a bit of reserved directory in bazel for these kinds
348-
// of purposes, we don't expect a collision in the paths.
349-
dstr = "external" + dstr.substring(2);
350-
}
351-
Path target = dest.resolve(dstr);
352-
File tfile = target.getParent().toFile();
353-
tfile.mkdirs();
316+
private static void copyResources(List<Resource> resources, Path dest) throws IOException {
317+
for (Resource r : resources) {
318+
Path source = Paths.get(r.source);
319+
Path target = dest.resolve(r.target);
320+
target.getParent().toFile().mkdirs();
354321
Files.copy(source, target);
355322
}
356323
}
@@ -373,24 +340,6 @@ private static void copyClasspathResourcesToRoot(String[] classpathResourceFiles
373340
}
374341
}
375342

376-
private static String getResourcePath(Path source, String resourceStripPrefix)
377-
throws RuntimeException {
378-
String sourcePath = source.toString();
379-
// convert strip prefix to a Path first and back to handle different file systems
380-
String resourceStripPrefixPath = Paths.get(resourceStripPrefix).toString();
381-
// check if the Resource file is under the specified prefix to strip
382-
if (!sourcePath.startsWith(resourceStripPrefixPath)) {
383-
// Resource File is not under the specified prefix to strip
384-
throw new RuntimeException(
385-
"Resource File "
386-
+ sourcePath
387-
+ " is not under the specified strip prefix "
388-
+ resourceStripPrefix);
389-
}
390-
String newResPath = sourcePath.substring(resourceStripPrefix.length());
391-
return newResPath;
392-
}
393-
394343
private static void copyResourceJars(String[] resourceJars, Path dest) throws IOException {
395344
for (String jarPath : resourceJars) {
396345
extractJar(jarPath, dest.toString(), null);

src/rules_scala1.iml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" inherit-compiler-output="true">
4+
<exclude-output />
5+
<content url="file://$MODULE_DIR$">
6+
<sourceFolder url="file://$MODULE_DIR$/java" isTestSource="false" />
7+
<sourceFolder url="file://$MODULE_DIR$/scala" isTestSource="false" />
8+
</content>
9+
<orderEntry type="inheritedJdk" />
10+
<orderEntry type="sourceFolder" forTests="false" />
11+
</component>
12+
</module>

0 commit comments

Comments
 (0)