Search in sources :

Example 1 with HashingOutputStream

use of com.google.common.hash.HashingOutputStream in project buck by facebook.

the class AutodepsWriter method writeSignedFile.

/**
   * Writes the file only if the contents are different to avoid creating noise for Watchman/buckd.
   * @param deps Keys must be sorted so the output is generated consistently.
   * @param includeSignature Whether to insert a signature for the contents of the file.
   * @param generatedFile Where to write the generated output.
   * @param mapper To aid in JSON serialization.
   * @return whether the file was written
   */
private static boolean writeSignedFile(SortedMap<String, SortedMap<String, Iterable<String>>> deps, boolean includeSignature, Path generatedFile, ObjectMapper mapper) throws IOException {
    try (ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        HashingOutputStream hashingOutputStream = new HashingOutputStream(Hashing.sha1(), bytes)) {
        ObjectWriter jsonWriter = mapper.writer(PRETTY_PRINTER.get());
        jsonWriter.writeValue(includeSignature ? hashingOutputStream : bytes, deps);
        // Flush a trailing newline through the HashingOutputStream so it is included both the
        // output and the signature calculation.
        hashingOutputStream.write('\n');
        String serializedJson = bytes.toString(Charsets.UTF_8.name());
        String contentsToWrite;
        if (includeSignature) {
            HashCode hash = hashingOutputStream.hash();
            contentsToWrite = String.format(AUTODEPS_CONTENTS_FORMAT_STRING, hash, serializedJson);
        } else {
            contentsToWrite = serializedJson;
        }
        // to indiscriminately invalidate any cached build rules for the associated build file.
        if (generatedFile.toFile().isFile()) {
            String existingContents = com.google.common.io.Files.toString(generatedFile.toFile(), Charsets.UTF_8);
            if (contentsToWrite.equals(existingContents)) {
                return false;
            }
        }
        try (Writer writer = Files.newBufferedWriter(generatedFile, Charsets.UTF_8)) {
            writer.write(contentsToWrite);
        }
        return true;
    }
}
Also used : HashCode(com.google.common.hash.HashCode) HashingOutputStream(com.google.common.hash.HashingOutputStream) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) Writer(java.io.Writer)

Aggregations

ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 HashCode (com.google.common.hash.HashCode)1 HashingOutputStream (com.google.common.hash.HashingOutputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 Writer (java.io.Writer)1