Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify FileSignature so that it can be relocated based on content #573

Closed
wants to merge 3 commits into from
Closed
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
3 changes: 3 additions & 0 deletions gradle/java-setup.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ tasks.named('spotbugsTest') {
tasks.named('spotbugsMain') {
// only run on Java 8 (no benefit to running twice)
enabled = org.gradle.api.JavaVersion.current() == org.gradle.api.JavaVersion.VERSION_1_8
reports {
html.enabled = true
}
}
dependencies {
compileOnly 'net.jcip:jcip-annotations:1.0'
Expand Down
33 changes: 24 additions & 9 deletions lib/src/main/java/com/diffplug/spotless/FileSignature.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
Expand All @@ -40,9 +42,8 @@ public final class FileSignature implements Serializable {
@SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED")
private final transient List<File> files;

private final String[] filenames;
private final long[] filesizes;
private final long[] lastModified;
private final String[] unixPaths;
private final long[] lastModifieds;

/** Method has been renamed to {@link FileSignature#signAsSet}.
* In case no sorting and removal of duplicates is required,
Expand Down Expand Up @@ -83,19 +84,33 @@ public static FileSignature signAsSet(Iterable<File> files) throws IOException {
private FileSignature(final List<File> files) throws IOException {
this.files = files;

filenames = new String[this.files.size()];
filesizes = new long[this.files.size()];
lastModified = new long[this.files.size()];
unixPaths = new String[this.files.size()];
lastModifieds = new long[this.files.size()];

int i = 0;
for (File file : this.files) {
filenames[i] = file.getCanonicalPath();
filesizes[i] = file.length();
lastModified[i] = file.lastModified();
unixPaths[i] = file.getCanonicalPath().replace('\\', '/');
lastModifieds[i] = file.lastModified();
++i;
}
}

private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException {
throw new UnsupportedOperationException();
}

private void writeObject(ObjectOutputStream outputStream) throws IOException {
FileSignatureRelocatableApi api = FileSignatureRelocatable.api();
if (api == null) {
for (int i = 0; i < files.size(); ++i) {
outputStream.writeLong(lastModifieds[i]);
outputStream.writeBytes(unixPaths[i]);
}
} else {
api.writeRelocatable(outputStream, unixPaths);
}
}

/** Returns all of the files in this signature, throwing an exception if there are more or less than 1 file. */
public Collection<File> files() {
return Collections.unmodifiableList(files);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright 2016 DiffPlug
*
* 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.diffplug.spotless;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

import javax.annotation.Nullable;

/**
* You give it a root directory and an object which contains FileSignatures - this class will now implement `Serializable`
* and `equalsTo` in terms of content hashes and relative path names, which makes it possible to relocate up-to-date checks
* between machines. If you pass a file which is not a subfile of `rootDir`, it will use the file's name as its full path (likely
* to be jar files resolved as dependencies).
*/
public class FileSignatureRelocatable extends LazyForwardingEquality<byte[]> implements FileSignatureRelocatableApi {
private static final long serialVersionUID = 7134847654770187954L;

private transient final String rootDir;
private transient final Object containsFileSignatures;

public FileSignatureRelocatable(File rootDir, Object containsFileSignatures) throws IOException {
this.rootDir = rootDir.getCanonicalPath().replace('\\', '/') + "/";
this.containsFileSignatures = Objects.requireNonNull(containsFileSignatures);
}

@Override
protected byte[] calculateState() throws Exception {
api.set(this);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (ObjectOutputStream objectOutput = new ObjectOutputStream(output)) {
objectOutput.writeObject(containsFileSignatures);
} finally {
api.set(null);
}
return output.toByteArray();
}

private static final ThreadLocal<FileSignatureRelocatableApi> api = new ThreadLocal<FileSignatureRelocatableApi>();

static @Nullable FileSignatureRelocatableApi api() {
return api.get();
}

@Override
public void writeRelocatable(ObjectOutputStream outputStream, String[] unixPaths) throws IOException {
try {
for (String unixPath : unixPaths) {
String pathToWrite;
if (unixPath.startsWith(rootDir)) {
// relocate files in the root dir
pathToWrite = unixPath.substring(rootDir.length());
} else {
// files outside the root dir are referenced based only on their name, not path
int lastSlash = unixPath.lastIndexOf('/');
pathToWrite = lastSlash == -1 ? unixPath : unixPath.substring(lastSlash + 1);
}
outputStream.writeBytes(pathToWrite);

MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(Files.readAllBytes(Paths.get(unixPath)));
outputStream.write(hash);
}
} catch (NoSuchAlgorithmException e) {
throw ThrowingEx.asRuntime(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright 2016 DiffPlug
*
* 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.diffplug.spotless;

import java.io.IOException;
import java.io.ObjectOutputStream;

interface FileSignatureRelocatableApi {
void writeRelocatable(ObjectOutputStream outputStream, String[] unixPaths) throws IOException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.diffplug.gradle.spotless;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
Expand All @@ -39,6 +40,7 @@

import com.diffplug.common.collect.ImmutableList;
import com.diffplug.common.collect.Iterables;
import com.diffplug.spotless.FileSignatureRelocatable;
import com.diffplug.spotless.FormatExceptionPolicy;
import com.diffplug.spotless.FormatExceptionPolicyStrict;
import com.diffplug.spotless.Formatter;
Expand All @@ -62,11 +64,17 @@ public void setEncoding(String encoding) {

protected LineEnding.Policy lineEndingsPolicy = LineEnding.UNIX.createPolicy();

@Input
@Internal
public LineEnding.Policy getLineEndingsPolicy() {
return lineEndingsPolicy;
}

@Input
public Object getLineEndingsPolicyRelocatable() throws IOException {
// allows gradle buildcache to relocate between machines
return new FileSignatureRelocatable(getProject().getRootProject().getRootDir(), getLineEndingsPolicy());
}

public void setLineEndingsPolicy(LineEnding.Policy lineEndingsPolicy) {
this.lineEndingsPolicy = Objects.requireNonNull(lineEndingsPolicy);
}
Expand Down Expand Up @@ -140,11 +148,17 @@ private File getCacheFile() {

protected List<FormatterStep> steps = new ArrayList<>();

@Input
@Internal
public List<FormatterStep> getSteps() {
return Collections.unmodifiableList(steps);
}

@Input
public Object getStepsRelocatable() throws IOException {
// allows gradle buildcache to relocate between machines
return new FileSignatureRelocatable(getProject().getRootProject().getRootDir(), getSteps());
}

public void setSteps(List<FormatterStep> steps) {
this.steps = PluginGradlePreconditions.requireElementsNonNull(steps);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright 2016 DiffPlug
*
* 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.diffplug.spotless;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import org.assertj.core.api.Assertions;
import org.junit.Test;

public class FileSignatureRelocatableTest extends ResourceHarness {
@Test
public void relocateWorks() throws IOException {
// paths much match
FileSignature local = FileSignature.signAsSet(setFile("local/test").toContent("123"));
FileSignature remote = FileSignature.signAsSet(setFile("remote/test").toContent("123"));
assertNotEqual(local, remote);

// but can be relocated
FileSignatureRelocatable localRelocatable = new FileSignatureRelocatable(newFile("local"), local);
FileSignatureRelocatable remoteRelocatable = new FileSignatureRelocatable(newFile("remote"), remote);
assertAreEqual(localRelocatable, remoteRelocatable);

// root directory matters
FileSignatureRelocatable localFromRoot = new FileSignatureRelocatable(this.rootFolder(), local);
assertNotEqual(localFromRoot, localRelocatable);
assertNotEqual(localFromRoot, remoteRelocatable);

// and so does content
FileSignature content = FileSignature.signAsSet(setFile("content/test").toContent("abc"));
FileSignatureRelocatable contentRelocatable = new FileSignatureRelocatable(newFile("content"), content);
assertNotEqual(localRelocatable, contentRelocatable);
}

private void assertNotEqual(Object a, Object b) {
Assertions.assertThat(serialize(a)).isNotEqualTo(serialize(b));
}

private void assertAreEqual(Object a, Object b) {
Assertions.assertThat(serialize(a)).isEqualTo(serialize(b));
}

private byte[] serialize(Object in) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (ObjectOutputStream outputObj = new ObjectOutputStream(output)) {
outputObj.writeObject(in);
} catch (IOException e) {
throw new AssertionError(e);
}
return output.toByteArray();
}
}