Revised version of A2Copy tool, which copies whole dirs in and out of image files.

This commit is contained in:
Martin Haye 2013-08-09 12:48:32 -07:00
parent 908d248af6
commit 751d997a04
10 changed files with 1872 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/OutlawEditor/target/
/Platform/Apple/tools/A2Copy/nbproject/private/
/Platform/Apple/tools/A2Copy/dist/
/Platform/Apple/tools/A2Copy/build/

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="A2Copy" default="default" basedir=".">
<description>Builds, tests, and runs the project A2Copy.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="A2Copy-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>

View File

@ -0,0 +1 @@
ac.jar = AppleCommander-1.3.5.13-ac.jar with Martn's patch for proper sub-directory creation

Binary file not shown.

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
build.xml.data.CRC32=5246bcd2
build.xml.script.CRC32=6c234e50
build.xml.stylesheet.CRC32=28e38971@1.56.1.46
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=5246bcd2
nbproject/build-impl.xml.script.CRC32=17d64078
nbproject/build-impl.xml.stylesheet.CRC32=c6d2a60f@1.56.1.46

View File

@ -0,0 +1,75 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=A2Copy
application.vendor=mhaye
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/A2Copy.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
file.reference.ac.jar=lib/ac.jar
includes=**
jar.compress=false
javac.classpath=\
${file.reference.ac.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.7
javac.target=1.7
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=a2copy.A2Copy
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=default_platform
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project.
# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value.
# To set system properties for unit tests define test-sys-prop.name=value:
run.jvmargs=
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=UTF-8
src.dir=src
test.src.dir=test

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>A2Copy</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
</configuration>
</project>

View File

@ -0,0 +1,281 @@
package a2copy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.webcodepro.applecommander.storage.DirectoryEntry;
import com.webcodepro.applecommander.storage.Disk;
import com.webcodepro.applecommander.storage.DiskFullException;
import com.webcodepro.applecommander.storage.FileEntry;
import com.webcodepro.applecommander.storage.FormattedDisk;
import com.webcodepro.applecommander.storage.os.prodos.ProdosFileEntry;
/*
* This class uses AppleCommander's command-line interface to extract an entire
* set of files and directories from an image, or build a whole image from
* files and directories.
*
* Has specific hard-coded addresses for Lawless Legends files; should fix this
* at some point to use a metadata configuration file or something like that.
*/
public class A2Copy
{
/*
* Main command-line driver
*/
public static void main(String[] args)
throws IOException, DiskFullException
{
try
{
if (args[0].equals("-get")) {
getDirFromImg(args[1], args[2], args[3]);
return;
}
if (args[0].equals("-put")) {
putDirToImg(args[1], args[2], args[3]);
return;
}
}
catch (ArrayIndexOutOfBoundsException e)
{ }
System.err.format("Usage: A2copy [-get imgFile srcImgDir destLocalDir] | [-put imgFile dstImgDir srcLocalDir]\n");
System.err.format(" where srcImgDir/dstImgDir is a subdirectory in the image, or / for the root directory.\n");
System.exit(1);
}
/** Patterns used for parsing filenames and paths */
static Pattern extPat = Pattern.compile("^(.*)\\.([^.]+)$");
static Pattern hashPat = Pattern.compile("^(.*)#([^#]+$)");
static Pattern pathPat = Pattern.compile("^/?([^/]+)(.*$)");
/**
* Extract all the files and subdirectories from one directory in an image file, and
* write them to the local filesystem.
*
* @throws IOException if something goes wrong
* @throws DiskFullException this actually can't happen (because we're not creating dirs)
*/
static void getDirFromImg(String imgFile, String srcImgDir, String dstLocalDir) throws IOException, DiskFullException
{
// Create the local dir if necessary.
File localDirFile = new File(dstLocalDir);
localDirFile.mkdirs();
// Open the image file and get the disk inside it.
FormattedDisk fd = new Disk(imgFile).getFormattedDisks()[0];
// Locate the right subdirectory on the disk.
DirectoryEntry imgDir = findSubDir(fd, srcImgDir, false);
// Recursively extract the files from that subdirectory.
getAllFiles((List<FileEntry>)imgDir.getFiles(), localDirFile);
}
static DirectoryEntry findSubDir(DirectoryEntry imgDir, String subDirs, boolean create)
throws DiskFullException
{
Matcher m = pathPat.matcher(subDirs);
if (m.matches())
{
// Process next component of the directory path.
String subName = m.group(1);
String remaining = m.group(2);
for (FileEntry e : (List<FileEntry>)imgDir.getFiles()) {
if (!e.isDeleted() && e.isDirectory() && e.getFilename().equalsIgnoreCase(subName))
return findSubDir((DirectoryEntry)e, remaining, create);
}
// Not found. If we're not allowed to create it, error out.
if (!create) {
System.err.format("Error: subdirectory '%s' not found.\n", subDirs);
System.exit(2);
}
// Create the subdirectory and continue to sub-sub-dirs.
return findSubDir(imgDir.createDirectory(subName.toUpperCase()), remaining, create);
}
return imgDir;
}
/**
* Helper for file/directory extraction.
* @param files set of files to extract
* @param dstTargetDir where to put them
* @throws IOException if something goes wrong
*/
static void getAllFiles(List<FileEntry> files, File dstTargetDir) throws IOException
{
// Ensure the target directory exists
dstTargetDir.mkdir();
// Make a map of the existing filesystem files so we can match them. This way,
// we can retain whatever case regime the user has established on the filesystem.
//
HashMap<String, File> existingFiles = new HashMap<>();
HashMap<String, String> baseMap = new HashMap<>();
for (File f: dstTargetDir.listFiles())
{
if (!f.isFile())
continue;
String name = f.getName();
existingFiles.put(name.toLowerCase(), f);
Matcher m = hashPat.matcher(name);
if (m.matches())
name = m.group(1);
existingFiles.put(name.toLowerCase(), f);
m = extPat.matcher(name);
if (m.matches())
name = m.group(1);
existingFiles.put(name.toLowerCase(), f);
baseMap.put(f.getName(), name);
}
// Process each entry in the list
for (FileEntry e : files)
{
// Skip deleted things
if (e.isDeleted())
continue;
// Determine the filename we should use locally. If there's a matching
// file already here, use its base.
//
String baseName = e.getFilename().toLowerCase();
if (existingFiles.containsKey(baseName)) {
File existingFile = existingFiles.get(baseName);
baseName = baseMap.get(existingFile.getName());
existingFile.delete();
}
// Recursively process sub-directories
if (e.isDirectory()) {
File subDir = new File(dstTargetDir, baseName);
getAllFiles(((DirectoryEntry)e).getFiles(), subDir);
continue;
}
// Add a hash for the file type.
String outName = baseName + "." + e.getFiletype().toLowerCase();
// Add a hash for the address if this kind of entry uses one.
if (e.needsAddress()) {
int auxType = ((ProdosFileEntry)e).getAuxiliaryType();
outName = outName + "#" + Integer.toHexString(auxType);
}
// Ready to copy the data.
byte[] data = e.getFileData();
try (FileOutputStream out = new FileOutputStream(new File(dstTargetDir, outName))) {
out.write(data);
}
}
}
/**
* Put a whole directory of files/subdirs from the local filesystem into a
* subdirectory of an image file.
*
* @param imgFilePath path to the image file
* @param dstImgDir subdirectory in the image file, or "/" for the root
* @param srcLocalDir directory containing files and subdirs
* @throws DiskFullException if the image file fills up
* @throws IOException if something else goes wrong
*/
static void putDirToImg(String imgFilePath, String dstImgDir, String srcLocalDir)
throws IOException, DiskFullException
{
// Make sure the local dir exists.
File localDirFile = new File(srcLocalDir);
if (!localDirFile.isDirectory()) {
System.err.format("Error: Local directory '%s' not found.\n", srcLocalDir);
System.exit(2);
}
// Open the image file.
FormattedDisk fd = new Disk(imgFilePath).getFormattedDisks()[0];
// Get to the right sub-directory.
DirectoryEntry ent = findSubDir(fd, dstImgDir, true);
// And fill it up.
putAllFiles(fd, ent, localDirFile);
}
/**
* Helper for image creation.
*
* @param fd disk to insert files into
* @param targetDir directory within the disk
* @param srcDir filesystem directory to read
* @throws DiskFullException if the image file fills up
* @throws IOException if something else goes wrong
*/
private static void putAllFiles(FormattedDisk fd, DirectoryEntry targetDir, File srcDir)
throws DiskFullException, IOException
{
// Process each file in the source directory
for (File srcFile : srcDir.listFiles())
{
if (srcFile.isDirectory()) {
DirectoryEntry subDir = targetDir.createDirectory(srcFile.getName().toUpperCase());
putAllFiles(fd, subDir, srcFile);
continue;
}
// Parse and strip the hash (address) and extension if any
String name = srcFile.getName();
String hash = "0";
Matcher m = hashPat.matcher(name);
if (m.matches()) {
name = m.group(1);
hash = m.group(2);
}
String ext = "0";
m = extPat.matcher(name);
if (m.matches()) {
name = m.group(1);
ext = m.group(2);
}
// Create a new entry in the disk image for this file.
FileEntry ent = targetDir.createFile();
ent.setFilename(name.toUpperCase());
// Set the file type using the extension we parsed above.
ent.setFiletype(ext);
// Set the address if we have one and this kind of file wants one.
if (ent.needsAddress())
{
try {
ent.setAddress(Integer.parseInt(hash, 16));
}
catch (NumberFormatException e) { /*pass*/ }
}
// Copy the file data
FileInputStream in = new FileInputStream(srcFile);
byte[] buf = new byte[(int) srcFile.length()];
int nRead = in.read(buf);
if (nRead != srcFile.length())
throw new IOException(String.format("Error reading file '%s'", srcFile.toString()));
ent.setFileData(buf);
// And save the new entry.
fd.save();
}
}
}