Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 39 additions & 22 deletions scala/scala.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -29,39 +29,53 @@ def _adjust_resources_path(path):
return dir_1 + dir_2, rel_path
return "", path

def _add_resources_cmd(ctx):
def _add_resources_cmd(ctx, dest):
res_cmd = ""
for f in ctx.files.resources:
c_dir, res_path = _adjust_resources_path(f.path)
change_dir = "-C " + c_dir if c_dir else ""
res_cmd += "\n{jar} uf {out} " + change_dir + " " + res_path
res_cmd += "\nmkdir -p $(dirname {out_dir}{res_path})\ncp {c_dir}{res_path} {out_dir}{res_path}".format(
out_dir=dest,
res_path=res_path,
c_dir=c_dir)
return res_cmd

def _get_jar_path(paths):
for p in paths:
path = p.path
if path.endswith("/jar_deploy.jar"):
return path
return None

def _build_nosrc_jar(ctx, buildijar):
res_cmd = _add_resources_cmd(ctx)
cp_resources = _add_resources_cmd(ctx, "{out}_tmp".format(out=ctx.outputs.jar.path))
ijar_cmd = ""
if buildijar:
ijar_cmd = "\ncp {out} {ijar_out}".format(
out=ctx.outputs.jar.path,
ijar_out=ctx.outputs.ijar.path)
cmd = """
rm -rf {out}_tmp
set -e
# Make jar file deterministic by setting the timestamp of files
touch -t 198001010000 {manifest}
{jar} cmf {manifest} {out}
""" + ijar_cmd + res_cmd
mkdir -p {out}_tmp
# copy any resources
{cp_resources}
{java} -jar {jar} -m {manifest} {out}
""" + ijar_cmd
cmd = cmd.format(
cp_resources=cp_resources,
out=ctx.outputs.jar.path,
manifest=ctx.outputs.manifest.path,
jar=ctx.file._jar.path)
java=ctx.file._java.path,
jar=_get_jar_path(ctx.files._jar))
outs = [ctx.outputs.jar]
if buildijar:
outs.extend([ctx.outputs.ijar])
ctx.action(
inputs=
ctx.files.resources +
ctx.files._jdk +
[ctx.outputs.manifest, ctx.file._jar],
ctx.files._jar +
[ctx.outputs.manifest, ctx.file._java],
outputs=outs,
command=cmd,
progress_message="scala %s" % ctx.label,
Expand All @@ -83,7 +97,7 @@ def _collect_plugin_paths(plugins):

def _compile(ctx, _jars, dep_srcjars, buildijar):
jars = _jars
res_cmd = _add_resources_cmd(ctx)
cp_resources = _add_resources_cmd(ctx, "{out}_tmp".format(out=ctx.outputs.jar.path))
ijar_cmd = ""
if buildijar:
ijar_cmd = "\n{ijar} {out} {ijar_out}".format(
Expand Down Expand Up @@ -135,22 +149,22 @@ touch {out}_args/files_from_jar
mkdir -p {out}_tmp""" + srcjar_cmd + """
cat {scalac_args} {out}_args/files_from_jar > {out}_args/args
env JAVACMD={java} {scalac} {jvm_flags} @{out}_args/args
# Make jar file deterministic by setting the timestamp of files
find {out}_tmp -exec touch -t 198001010000 {{}} \;
touch -t 198001010000 {manifest}
{jar} cmf {manifest} {out} -C {out}_tmp .
# add any resources
{cp_resources}
{java} -jar {jar} -m {manifest} {out} {out}_tmp
rm -rf {out}_args
rm -rf {out}_tmp
rm -rf {out}_tmp_expand_srcjars
""" + ijar_cmd + res_cmd
""" + ijar_cmd
cmd = cmd.format(
cp_resources=cp_resources,
java=ctx.file._java.path,
jvm_flags=" ".join(["-J" + flag for flag in ctx.attr.jvm_flags]),
scalac=ctx.file._scalac.path,
scalac_args=scalac_args_file.path,
out=ctx.outputs.jar.path,
manifest=ctx.outputs.manifest.path,
jar=ctx.file._jar.path,
jar=_get_jar_path(ctx.files._jar),
ijar=ctx.file._ijar.path,
)
outs = [ctx.outputs.jar]
Expand All @@ -165,11 +179,12 @@ rm -rf {out}_tmp_expand_srcjars
ctx.files.plugins +
ctx.files.resources +
ctx.files._jdk +
ctx.files._jar +
ctx.files._scalasdk +
[ctx.outputs.manifest,
ctx.file._jar,
ctx.file._ijar,
ctx.file._scalac,
ctx.file._java,
scalac_args_file],
outputs=outs,
command=cmd,
Expand Down Expand Up @@ -197,15 +212,16 @@ def _build_deployable(ctx, jars):
cmd += "mkdir -p {out}_tmp\n"
for jar in jars:
cmd += "unzip -o {jar} -d {{out}}_tmp >/dev/null\n".format(jar=jar.path)
cmd += "{jar} cmf {manifest} {out} -C {out}_tmp .\n"
cmd += "{java} -jar {jar} -m {manifest} {out} {out}_tmp\n"
cmd += "rm -rf {out}_tmp\n"

cmd = cmd.format(
out=ctx.outputs.deploy_jar.path,
jar=ctx.file._jar.path,
jar=_get_jar_path(ctx.files._jar),
java=ctx.file._java.path,
manifest=ctx.outputs.manifest.path)
ctx.action(
inputs=list(jars) + ctx.files._jdk + [ctx.outputs.manifest, ctx.file._jar],
inputs=list(jars) + ctx.files._jdk + ctx.files._jar + [ctx.outputs.manifest],
outputs=[ctx.outputs.deploy_jar],
command=cmd,
progress_message="scala deployable %s" % ctx.label,
Expand Down Expand Up @@ -317,6 +333,7 @@ def _lib(ctx, non_macro_lib):
files = list(rjars),
collect_data = True)
return struct(
files = set([ctx.outputs.jar]), # Here is the default output
scala = scalaattr,
runfiles=runfiles,
# This is a free monoid given to the graph for the purpose of
Expand Down Expand Up @@ -417,7 +434,7 @@ _implicit_deps = {
"_scalasdk": attr.label(default=Label("@scala//:sdk"), allow_files=True),
"_scalareflect": attr.label(default=Label("@scala//:lib/scala-reflect.jar"), single_file=True, allow_files=True),
"_java": attr.label(executable=True, default=Label("@bazel_tools//tools/jdk:java"), single_file=True, allow_files=True),
"_jar": attr.label(executable=True, default=Label("@bazel_tools//tools/jdk:jar"), single_file=True, allow_files=True),
"_jar": attr.label(executable=True, default=Label("//src/java/io/bazel/rulesscala/jar:jar_deploy.jar"), allow_files=True),
"_jdk": attr.label(default=Label("//tools/defaults:jdk"), allow_files=True),
}

Expand Down
5 changes: 5 additions & 0 deletions src/java/io/bazel/rulesscala/jar/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
java_binary(name = "jar",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, @bazel_tools//tools/zip:zipper is a zip implementation that strip out timestamp. Might be easier to refer to it that to fork SingleJar's Jar implementation. (Also faster)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is good to know about instead of using system zip, but what about making manifests? Seems nice to reuse that bit?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I see, then maybe you can use directly the SingleJar binary. Just ask if you need to get rid of the file fork and I can probably help you sort that out.

srcs = ["JarCreator.java", "JarHelper.java"],
main_class = "io.bazel.rulesscala.jar.JarCreator",
visibility = ["//visibility:public"],
)
207 changes: 207 additions & 0 deletions src/java/io/bazel/rulesscala/jar/JarCreator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
// Copyright 2014 The Bazel Authors. 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 io.bazel.rulesscala.jar;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

/**
* A class for creating Jar files. Allows normalization of Jar entries by setting their timestamp to
* the DOS epoch. All Jar entries are sorted alphabetically.
*/
public class JarCreator extends JarHelper {

// Map from Jar entry names to files. Use TreeMap so we can establish a canonical order for the
// entries regardless in what order they get added.
private final Map<String, String> jarEntries = new TreeMap<>();
private String manifestFile;
private String mainClass;

public JarCreator(String fileName) {
super(fileName);
}

/**
* Adds an entry to the Jar file, normalizing the name.
*
* @param entryName the name of the entry in the Jar file
* @param fileName the name of the input file for the entry
* @return true iff a new entry was added
*/
public boolean addEntry(String entryName, String fileName) {
if (entryName.startsWith("/")) {
entryName = entryName.substring(1);
} else if (entryName.startsWith("./")) {
entryName = entryName.substring(2);
}
return jarEntries.put(entryName, fileName) == null;
}

/**
* Adds the contents of a directory to the Jar file. All files below this
* directory will be added to the Jar file using the name relative to the
* directory as the name for the Jar entry.
*
* @param directory the directory to add to the jar
*/
public void addDirectory(String directory) {
addDirectory(null, new File(directory));
}

/**
* Adds the contents of a directory to the Jar file. All files below this
* directory will be added to the Jar file using the prefix and the name
* relative to the directory as the name for the Jar entry. Always uses '/' as
* the separator char for the Jar entries.
*
* @param prefix the prefix to prepend to every Jar entry name found below the
* directory
* @param directory the directory to add to the Jar
*/
private void addDirectory(String prefix, File directory) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
String entryName = prefix != null ? prefix + "/" + file.getName() : file.getName();
jarEntries.put(entryName, file.getAbsolutePath());
if (file.isDirectory()) {
addDirectory(entryName, file);
}
}
}
}

/**
* Adds a collection of entries to the jar, each with a given source path, and with
* the resulting file in the root of the jar.
* <pre>
* some/long/path.foo => (path.foo, some/long/path.foo)
* </pre>
*/
public void addRootEntries(Collection<String> entries) {
for (String entry : entries) {
jarEntries.put(new File(entry).getName(), entry);
}
}

/**
* Sets the main.class entry for the manifest. A value of <code>null</code>
* (the default) will omit the entry.
*
* @param mainClass the fully qualified name of the main class
*/
public void setMainClass(String mainClass) {
this.mainClass = mainClass;
}

/**
* Sets filename for the manifest content. If this is set the manifest will be
* read from this file otherwise the manifest content will get generated on
* the fly.
*
* @param manifestFile the filename of the manifest file.
*/
public void setManifestFile(String manifestFile) {
this.manifestFile = manifestFile;
}

private byte[] manifestContent() throws IOException {
Manifest manifest;
if (manifestFile != null) {
FileInputStream in = new FileInputStream(manifestFile);
manifest = new Manifest(in);
} else {
manifest = new Manifest();
}
Attributes attributes = manifest.getMainAttributes();
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
Attributes.Name createdBy = new Attributes.Name("Created-By");
if (attributes.getValue(createdBy) == null) {
attributes.put(createdBy, "blaze");
}
if (mainClass != null) {
attributes.put(Attributes.Name.MAIN_CLASS, mainClass);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
manifest.write(out);
return out.toByteArray();
}

/**
* Executes the creation of the Jar file.
*
* @throws IOException if the Jar cannot be written or any of the entries
* cannot be read.
*/
public void execute() throws IOException {
out = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jarFile)));

// Create the manifest entry in the Jar file
writeManifestEntry(manifestContent());
try {
for (Map.Entry<String, String> entry : jarEntries.entrySet()) {
copyEntry(entry.getKey(), new File(entry.getValue()));
}
} finally {
out.closeEntry();
out.close();
}
}

/**
* A simple way to create Jar file using the JarCreator class.
*/
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("usage: CreateJar [-m manifest] output [root directories]");
System.exit(1);
}

int idx = 0;
String manifestFile = null;
if (args[0].equals("-m")) {
manifestFile = args[1];
idx = 2;
}
String output = args[idx];
JarCreator createJar = new JarCreator(output);
createJar.setManifestFile(manifestFile);
for (int i = (idx+1); i < args.length; i++) {
createJar.addDirectory(args[i]);
}
createJar.setCompression(true);
createJar.setNormalize(true);
long start = System.currentTimeMillis();
try {
createJar.execute();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
long stop = System.currentTimeMillis();
//System.err.println((stop - start) + "ms.");
//System.err.println(output);
}
}
Loading