aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/AbstractLibraryBuilder.java
blob: a503414ca331a4a413f635639ec5ba2e6a06bf05 (plain)
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
// 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 com.google.devtools.build.buildjar;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.io.ByteStreams;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Base class for java_library builders.
 *
 * <p>Implements common functionality like source files preparation and
 * output jar creation.
 */
public abstract class AbstractLibraryBuilder extends CommonJavaLibraryProcessor {

  /**
   * Prepares a compilation run. This involves cleaning up temporary dircectories and
   * writing the classpath files.
   */
  protected void prepareSourceCompilation(JavaLibraryBuildRequest build) throws IOException {
    File classDirectory = new File(build.getClassDir());
    if (classDirectory.exists()) {
      try {
        // Necessary for local builds in order to discard previous outputs
        cleanupOutputDirectory(classDirectory);
      } catch (IOException e) {
        throw new IOException("Cannot clean output directory '" + classDirectory + "'", e);
      }
    }
    classDirectory.mkdirs();

    setUpSourceJars(build);
  }

  public void buildJar(JavaLibraryBuildRequest build) throws IOException {
    JarCreator jar = new JarCreator(build.getOutputJar());
    jar.setNormalize(true);
    jar.setCompression(build.compressJar());

    // The easiest way to handle resource jars is to unpack them into the class directory, just
    // before we start zipping it up.
    for (String resourceJar : build.getResourceJars()) {
      setUpSourceJar(new File(resourceJar), build.getClassDir(),
          new ArrayList<SourceJarEntryListener>());
    }

    jar.addDirectory(build.getClassDir());

    jar.addRootEntries(build.getRootResourceFiles());
    addResourceEntries(jar, build.getResourceFiles());
    addMessageEntries(jar, build.getMessageFiles());

    jar.execute();
  }

  /**
   * Adds a collection of resource entries. Each entry is a string composed of a
   * pair of parts separated by a colon ':'. The name of the resource comes from
   * the second part, and the path to the resource comes from the whole string
   * with the colon replaced by a slash '/'.
   * <pre>
   * prefix:name => (name, prefix/name)
   * </pre>
   */
  private static void addResourceEntries(JarCreator jar, Collection<String> resources)
      throws IOException {
    for (String resource : resources) {
      int colon = resource.indexOf(':');
      if (colon < 0) {
        throw new IOException("" + resource + ": Illegal resource entry.");
      }
      String prefix = resource.substring(0, colon);
      String name = resource.substring(colon + 1);
      String path = colon > 0 ? prefix + "/" + name : name;
      addEntryWithParents(jar, name, path);
    }
  }

  private static void addMessageEntries(JarCreator jar, List<String> messages)
      throws IOException {
    for (String message : messages) {
      int colon = message.indexOf(':');
      if (colon < 0) {
        throw new IOException("" + message + ": Illegal message entry.");
      }
      String prefix = message.substring(0, colon);
      String name = message.substring(colon + 1);
      String path = colon > 0 ? prefix + "/" + name : name;
      File messageFile = new File(path);
      // Ignore empty messages. They get written by the translation importer
      // when there is no translation for a particular language.
      if (messageFile.length() != 0L) {
        addEntryWithParents(jar, name, path);
      }
    }
  }

  /**
   * Adds an entry to the jar, making sure that all the parent dirs up to the
   * base of {@code entry} are also added.
   *
   * @param entry the PathFragment of the entry going into the Jar file
   * @param file the PathFragment of the input file for the entry
   */
  @VisibleForTesting
  static void addEntryWithParents(JarCreator creator, String entry, String file) {
    while ((entry != null) && creator.addEntry(entry, file)) {
      entry = new File(entry).getParent();
      file = new File(file).getParent();
    }
  }

  /**
   * Internal interface which will listen on each entry of the source jar
   * files during the source jar setup process.
   */
  protected interface SourceJarEntryListener {
    void onEntry(ZipEntry entry) throws IOException;
    void finish() throws IOException;
  }

  protected List<SourceJarEntryListener> getSourceJarEntryListeners(JavaLibraryBuildRequest build) {
    List<SourceJarEntryListener> result = new ArrayList<>();
    result.add(new SourceJavaFileCollector(build));
    return result;
  }

  /**
   * A SourceJarEntryListener that collects a lists of source Java files from
   * the source jar files.
   */
  private static class SourceJavaFileCollector implements SourceJarEntryListener {
    private final List<String> sources;
    private final JavaLibraryBuildRequest build;

    public SourceJavaFileCollector(JavaLibraryBuildRequest build) {
      this.sources = new ArrayList<>();
      this.build = build;
    }

    @Override
    public void onEntry(ZipEntry entry) {
      String entryName = entry.getName();
      if (entryName.endsWith(".java")) {
        sources.add(build.getTempDir() + File.separator + entryName);
      }
    }

    @Override
    public void finish() {
      build.getSourceFiles().addAll(sources);
    }
  }

  /**
   * Extracts the all source jars from the build request into the temporary
   * directory specified in the build request. Empties the temporary directory,
   * if it exists.
   */
  private void setUpSourceJars(JavaLibraryBuildRequest build) throws IOException {
    String sourcesDir = build.getTempDir();

    File sourceDirFile = new File(sourcesDir);
    if (sourceDirFile.exists()) {
      cleanupDirectory(sourceDirFile, true);
    }

    if (build.getSourceJars().isEmpty()) {
      return;
    }

    List<SourceJarEntryListener> listeners = getSourceJarEntryListeners(build);
    for (String sourceJar : build.getSourceJars()) {
      setUpSourceJar(new File(sourceJar), sourcesDir, listeners);
    }
    for (SourceJarEntryListener listener : listeners) {
      listener.finish();
    }
  }

  /**
   * Extracts the source jar into the directory sourceDir. Calls each of the
   * SourceJarEntryListeners for each non-directory entry to do additional work.
   */
  private void setUpSourceJar(File sourceJar, String sourceDir,
      List<SourceJarEntryListener> listeners)
      throws IOException {
    try (ZipFile zipFile = new ZipFile(sourceJar)) {
      Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
      while (zipEntries.hasMoreElements()) {
        ZipEntry currentEntry = zipEntries.nextElement();
        String entryName = currentEntry.getName();
        File outputFile = new File(sourceDir, entryName);

        outputFile.getParentFile().mkdirs();

        if (currentEntry.isDirectory()) {
          outputFile.mkdir();
        } else {
          // Copy the data from the zip file to the output file.
          try (InputStream in = zipFile.getInputStream(currentEntry);
               OutputStream out = new FileOutputStream(outputFile)) {
            ByteStreams.copy(in, out);
          }

          for (SourceJarEntryListener listener : listeners) {
            listener.onEntry(currentEntry);
          }
        }
      }
    }
  }

  /**
   * Recursively cleans up the files beneath the specified output directory.
   * Does not follow symbolic links. Throws IOException if any deletion fails.
   *
   * Will delete all empty directories.
   *
   * @param dir the directory to clean up.
   * @return true if the directory itself was removed as well.
   */
  boolean cleanupOutputDirectory(File dir) throws IOException {
    return cleanupDirectory(dir, false);
  }

  /**
   * Recursively cleans up the files beneath the specified output directory.
   * Does not follow symbolic links. Throws IOException if any deletion fails.
   * If removeEverything is false, keeps .class files if keepClassFilesDuringCleanup()
   * returns true. If removeEverything is true, removes everything. Will delete all
   * empty directories.
   *
   * @param dir the directory to clean up.
   * @param removeEverything whether to remove all files, or keep flags.xml/.class files.
   * @return true if the directory itself was removed as well.
   */
  private boolean cleanupDirectory(File dir, boolean removeEverything) throws IOException {
    boolean isEmpty = true;
    File[] files = dir.listFiles();
    if (files == null) { return false; } // avoid race condition
    for (File file : files) {
      if (file.isDirectory()) {
        isEmpty &= cleanupDirectory(file, removeEverything);
      } else if (!removeEverything && keepClassFilesDuringCleanup() &&
          file.getName().endsWith(".class")) {
        isEmpty = false;
      } else {
        file.delete();
      }
    }
    if (isEmpty) {
      dir.delete();
    }
    return isEmpty;
  }

  /**
   * Returns true if cleaning the output directory should remove all
   * .class files in the output directory.
   */
  protected boolean keepClassFilesDuringCleanup() {
    return false;
  }

}