Skip to content

Commit

Permalink
[MSHARED-1330] Always overwrite files (#97)
Browse files Browse the repository at this point in the history
  • Loading branch information
gnodet authored Mar 2, 2024
1 parent ae1842f commit 442b63e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.attribute.PosixFilePermission;
import java.util.EnumSet;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -305,6 +307,8 @@ static boolean isEmpty(final String string) {
* @throws IOException if an IO error occurs during copying or filtering
*/
public static void copyFile(File from, File to, String encoding, FilterWrapper[] wrappers) throws IOException {
setReadWritePermissions(to);

if (wrappers == null || wrappers.length == 0) {
try (OutputStream os = new CachingOutputStream(to.toPath())) {
Files.copy(from.toPath(), os);
Expand Down Expand Up @@ -371,6 +375,23 @@ private static void copyFilePermissions(File source, File destination) throws IO
}
}

@SuppressWarnings("ResultOfMethodCallIgnored")
private static void setReadWritePermissions(File file) throws IOException {
if (file.exists()) {
try {
Files.setPosixFilePermissions(
file.toPath(),
EnumSet.of(
PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE,
PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE,
PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_WRITE));
} catch (UnsupportedOperationException e) {
file.setReadable(true);
file.setWritable(true);
}
}
}

private static Charset charset(String encoding) {
if (encoding == null || encoding.isEmpty()) {
return Charset.defaultCharset();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

import static org.codehaus.plexus.testing.PlexusExtension.getBasedir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;

/**
* @author John Casey
Expand Down Expand Up @@ -148,4 +149,20 @@ void escapeWindowsPathNotAtBeginning() throws Exception {
"jdbc:derby:C:\\\\Users\\\\Administrator/test;create=true",
FilteringUtils.escapeWindowsPath("jdbc:derby:C:\\Users\\Administrator/test;create=true"));
}

// MSHARED-1330
@Test
void copyReadOnlyFileTwice() throws Exception {
File temp = File.createTempFile("pre-", ".txt");
temp.setReadOnly();

File out = File.createTempFile("out-", ".txt");
out.delete();

FilteringUtils.copyFile(temp, out, "UTF-8", new FilterWrapper[0]);
assertFalse(out.canWrite());

FilteringUtils.copyFile(temp, out, "UTF-8", new FilterWrapper[0]);
assertFalse(out.canWrite());
}
}

0 comments on commit 442b63e

Please sign in to comment.