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

8335912: Add an operation mode to the jar command when extracting to not overwriting existing files #608

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
23 changes: 22 additions & 1 deletion jdk/src/share/classes/sun/tools/jar/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,10 @@ class Main {
* iflag: generate jar index
* nflag: Perform jar normalization at the end
* pflag: preserve/don't strip leading slash and .. component from file name
* kflag: keep existing file
*
*/
boolean cflag, uflag, xflag, tflag, vflag, flag0, Mflag, iflag, nflag, pflag;
boolean cflag, uflag, xflag, tflag, vflag, flag0, Mflag, iflag, nflag, pflag, kflag;

static final String MANIFEST_DIR = "META-INF/";
static final String VERSION = "1.0";
Expand Down Expand Up @@ -397,6 +398,9 @@ boolean parseArgs(String args[]) {
case '0':
flag0 = true;
break;
case 'k':
kflag = true;
break;
case 'i':
if (cflag || uflag || xflag || tflag) {
usageError();
Expand Down Expand Up @@ -431,6 +435,10 @@ boolean parseArgs(String args[]) {
usageError();
return false;
}
if (kflag && !xflag) {
warn(formatMsg("warn.option.is.ignored", "-k/k"));
}

/* parse file arguments */
int n = args.length - count;
if (n > 0) {
Expand Down Expand Up @@ -1058,6 +1066,12 @@ ZipEntry extractFile(InputStream is, ZipEntry e) throws IOException {
output(formatMsg("out.create", name));
}
} else {
if (f.exists() && kflag) {
if (vflag) {
output(formatMsg("out.kept", name));
}
return rc;
}
if (f.getParent() != null) {
File d = new File(f.getParent());
if (!d.exists() && !d.mkdirs() || !d.isDirectory()) {
Expand Down Expand Up @@ -1280,6 +1294,13 @@ protected void error(String s) {
err.println(s);
}

/**
* Print a warning message
*/
void warn(String s) {
err.println(s);
}

/**
* Main routine to start program.
*/
Expand Down
16 changes: 15 additions & 1 deletion jdk/src/share/classes/sun/tools/jar/resources/jar.properties
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ error.incorrect.length=\
incorrect length while processing: {0}
error.create.tempfile=\
Could not create a temporary file
warn.option.is.ignored=\
Warning: The {0} option is not valid with current usage, will be ignored.
out.added.manifest=\
added manifest
out.update.manifest=\
Expand All @@ -62,6 +64,8 @@ out.create=\
\ \ created: {0}
out.extracted=\
extracted: {0}
out.kept=\
\ \ skipped: {0} exists
out.inflated=\
\ inflated: {0}
out.size=\
Expand All @@ -72,7 +76,10 @@ Usage: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] f
Options:\n\
\ \ -c create new archive\n\
\ \ -t list table of contents for archive\n\
\ \ -x extract named (or all) files from archive\n\
\ \ -x, Extract named (or all) files from the archive.\n\
\ \ If a file with the same name appears more than once in\n\
\ \ the archive, each copy will be extracted, with later copies\n\
\ \ overwriting (replacing) earlier copies unless -k is specified.\n\
\ \ -u update existing archive\n\
\ \ -v generate verbose output on standard output\n\
\ \ -f specify archive file name\n\
Expand All @@ -85,6 +92,13 @@ Options:\n\
\ \ -M do not create a manifest file for the entries\n\
\ \ -i generate index information for the specified jar files\n\
\ \ -C change to the specified directory and include the following file\n\
Operation modifiers valid only in extract mode:\n\
\ \ -k Do not overwrite existing files.\n\
\ \ If a Jar file entry with the same name exists in the target\n\
\ \ directory, the existing file will not be overwritten.\n\
\ \ As a result, if a file appears more than once in an\n\
\ \ archive, later copies will not overwrite earlier copies.\n\
\ \ Also note that some file system can be case insensitive.\n\
If any file is a directory then it is processed recursively.\n\
The manifest file name, the archive file name and the entry point name are\n\
specified in the same order as the 'm', 'f' and 'e' flags.\n\n\
Expand Down
241 changes: 241 additions & 0 deletions jdk/test/tools/jar/ExtractFilesTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

/*
* @test
* @bug 8335912
* @summary test extract jar files overwrite existing files behavior
* @library /test/lib /lib/testlibrary
* @build jdk.test.lib.Platform
* jdk.testlibrary.FileUtils
* @run junit/othervm ExtractFilesTest
*/

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Stream;

import jdk.testlibrary.FileUtils;
import sun.tools.jar.Main;

@TestInstance(Lifecycle.PER_CLASS)
public class ExtractFilesTest {
private final String nl = System.lineSeparator();
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final PrintStream out = new PrintStream(baos);

@BeforeAll
public void setupJar() throws IOException {
mkdir("test1 test2");
echo("testfile1", "test1/testfile1");
echo("testfile2", "test2/testfile2");
jar("cf test.jar -C test1 . -C test2 .");
rm("test1 test2");
}

@AfterAll
public void cleanup() {
rm("test.jar");
}

/**
* Regular clean extract with expected output.
*/
@Test
public void testExtract() throws IOException {
jar("xvf test.jar");
println();
String output = " created: META-INF/" + nl +
" inflated: META-INF/MANIFEST.MF" + nl +
" inflated: testfile1" + nl +
" inflated: testfile2" + nl;
rm("META-INF testfile1 testfile2");
Assertions.assertArrayEquals(baos.toByteArray(), output.getBytes());
}

/**
* Extract should overwrite existing file as default behavior.
*/
@Test
public void testOverwrite() throws IOException {
touch("testfile1");
jar("xvf test.jar");
println();
String output = " created: META-INF/" + nl +
" inflated: META-INF/MANIFEST.MF" + nl +
" inflated: testfile1" + nl +
" inflated: testfile2" + nl;
Assertions.assertEquals("testfile1", cat("testfile1"));
rm("META-INF testfile1 testfile2");
Assertions.assertArrayEquals(baos.toByteArray(), output.getBytes());
}

/**
* Extract with legacy style option `k` should preserve existing files.
*/
@Test
public void testKeptOldFile() throws IOException {
touch("testfile1");
jar("xkvf test.jar");
println();
String output = " created: META-INF/" + nl +
" inflated: META-INF/MANIFEST.MF" + nl +
" skipped: testfile1 exists" + nl +
" inflated: testfile2" + nl;
Assertions.assertEquals("", cat("testfile1"));
Assertions.assertEquals("testfile2", cat("testfile2"));
rm("META-INF testfile1 testfile2");
Assertions.assertArrayEquals(baos.toByteArray(), output.getBytes());
}

/**
* Extract with gnu style -k should preserve existing files.
*/
@Test
public void testGnuOptionsKeptOldFile() throws IOException {
touch("testfile1 testfile2");
jar("-xkvf test.jar");
println();
String output = " created: META-INF/" + nl +
" inflated: META-INF/MANIFEST.MF" + nl +
" skipped: testfile1 exists" + nl +
" skipped: testfile2 exists" + nl;
Assertions.assertEquals("", cat("testfile1"));
Assertions.assertEquals("", cat("testfile2"));
rm("META-INF testfile1 testfile2");
Assertions.assertArrayEquals(baos.toByteArray(), output.getBytes());
}

/**
* Test jar will issue warning when use keep option in non-extraction mode.
*/
@Test
public void testWarningOnInvalidKeepOption() throws IOException {
String err = jar("tkf test.jar");
println();

String output = "META-INF/" + nl +
"META-INF/MANIFEST.MF" + nl +
"testfile1" + nl +
"testfile2" + nl;

Assertions.assertArrayEquals(baos.toByteArray(), output.getBytes());
Assertions.assertEquals("Warning: The -k/k option is not valid with current usage, will be ignored." + nl, err);
}

private Stream<Path> mkpath(String... args) {
return Arrays.stream(args).map(d -> Paths.get(".", d.split("/")));
}

private void mkdir(String cmdline) {
System.out.println("mkdir -p " + cmdline);
mkpath(cmdline.split(" +")).forEach(p -> {
try {
Files.createDirectories(p);
} catch (IOException x) {
throw new UncheckedIOException(x);
}
});
}

private void touch(String cmdline) {
System.out.println("touch " + cmdline);
mkpath(cmdline.split(" +")).forEach(p -> {
try {
Files.createFile(p);
} catch (IOException x) {
throw new UncheckedIOException(x);
}
});
}

private void echo(String text, String path) {
System.out.println("echo '" + text + "' > " + path);
try {
Path p = Paths.get(".", path.split("/"));
Files.write(p, text.getBytes());
} catch (IOException x) {
throw new UncheckedIOException(x);
}
}

private String cat(String path) {
System.out.println("cat " + path);
try {
return new String(Files.readAllBytes(Paths.get(path)));
} catch (IOException x) {
throw new UncheckedIOException(x);
}
}

private void rm(String cmdline) {
System.out.println("rm -rf " + cmdline);
mkpath(cmdline.split(" +")).forEach(p -> {
try {
if (Files.isDirectory(p)) {
FileUtils.deleteFileTreeWithRetry(p);
} else {
FileUtils.deleteFileIfExistsWithRetry(p);
}
} catch (IOException x) {
throw new UncheckedIOException(x);
}
});
}

private String jar(String cmdline) throws IOException {
System.out.println("jar " + cmdline);
baos.reset();

// the run method catches IOExceptions, we need to expose them
ByteArrayOutputStream baes = new ByteArrayOutputStream();
PrintStream err = new PrintStream(baes);
PrintStream saveErr = System.err;
System.setErr(err);
try {
if (!new Main(out, err, "jar").run(cmdline.split(" +"))) {
throw new IOException(baes.toString());
}
} finally {
System.setErr(saveErr);
}
return baes.toString();
}

private void println() throws IOException {
System.out.println(new String(baos.toByteArray()));
}
}
Loading