import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;
public final class DirToRepoStructure {
private static final Pattern jarNamePattern = Pattern.compile( "(.*)_(\\d+\\.\\d+\\.\\d+)\\.v?(\\d+)\\.jar" );
public static void main( String[] args ) throws IOException {
Path root = Paths.get( args[ 0 ] );
int rootNameCount = root.getNameCount( );
String rootName = root.getFileName( )
.toString( );
Path tempDir = Files.createTempDirectory( Paths.get( "." ), rootName );
System.out.println( "using temporary directory: " + tempDir );
Path achievePath = tempDir.getParent( )
.resolve( rootName + ".zip" );
System.out.println( "Archiving at: " + achievePath );
DirectoryStream< Path > stream = Files.newDirectoryStream( root, "*.jar" );
stream.forEach( jar -> {
String fullName = jar.getFileName( )
.toString( );
System.out.println( fullName );
Matcher matcher = jarNamePattern.matcher( fullName );
if ( matcher.matches( ) ) {
String jarName = matcher.group( 1 );
String version = matcher.group( 2 );
String snap = matcher.group( 3 );
System.out.println( "reading: " + jarName + ", " + version );
createJarStructure( tempDir, jar, jarName, version, snap );
}
else {
throw new IllegalArgumentException( "file name does not match regex" );
}
} );
try ( FileSystem zipFs = getZipFs( achievePath ) ) {
Files.walk( tempDir )
.skip( rootNameCount )
.forEach( source -> copyIntoZip( zipFs, source, rootNameCount ) );
}
}
private static void copyIntoZip( FileSystem zipFs, Path source, int rootNameCount ) {
try {
Path zipRoot = zipFs.getPath( "/" );
int tempRootNameCount = rootNameCount + 1;
int sourceNameCount = source.getNameCount( );
String newPathName = source.subpath( tempRootNameCount, sourceNameCount )
.toString( );
Path pathInZipFile = zipRoot.resolve( newPathName );
Files.copy( source, pathInZipFile, StandardCopyOption.REPLACE_EXISTING );
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
}
private static void createJarStructure( Path tempDir, Path jar, String jarName, String version, String snap ) {
try {
Path jarRoot = jar.getParent( )
.resolve( jarName )
.resolve( version + "-SNAPSHOT" );
Path jarDirectory = Files.createDirectories( tempDir.resolve( jarRoot ) );
String shortSnap = snap.substring( 0,8 );
Path jarTarget = jarDirectory.resolve( jarName + "-" + version + "-"+ shortSnap + ".jar" ); Files.copy( jar, jarTarget );
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
}
private static FileSystem getZipFs( Path archivePath ) throws IOException {
Map< String, String > env = new HashMap<>( );
env.put( "create", "true" );
env.put( "encoding", StandardCharsets.UTF_8.toString( ) );
System.out.println( archivePath );
URI uri = URI.create( "jar:file:" + archivePath.toAbsolutePath( ) );
return FileSystems.newFileSystem( uri, env );
}
}