Skip to content

Instantly share code, notes, and snippets.

@rz7d
Last active May 24, 2019 14:48
Show Gist options
  • Save rz7d/2f7c471115ffacd6366ec1c95285a978 to your computer and use it in GitHub Desktop.
Save rz7d/2f7c471115ffacd6366ec1c95285a978 to your computer and use it in GitHub Desktop.
generate <dependency></dependency> tags from maven repository (pwd)
/*
* Copyright (C) 2019 azure.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
public class Depends {
private static final Path PWD = Paths.get(System.getProperty("user.dir"));
public static void main(String[] args) throws Exception {
Files.walk(PWD)
.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".jar"))
.sorted()
.map(Depends::toMavenDeclartion)
.forEach(System.out::println);
}
enum Context {
NONE, VERSION, ARTIFACT_ID, GROUP_ID;
Context increment() {
switch (this) {
case VERSION:
return ARTIFACT_ID;
case ARTIFACT_ID:
return GROUP_ID;
case GROUP_ID:
return GROUP_ID;
default:
return NONE;
}
}
}
public static String toMavenDeclartion(Path path) {
Path current = path;
Context context = Context.VERSION;
String groupId = null;
String artifactId = null;
String version = null;
// skips first token (JAR file name)
make: while (isValidPath(current = current.getParent())) {
String token = current.getFileName().toString();
switch (context) {
case VERSION:
version = token;
break;
case ARTIFACT_ID:
artifactId = token;
break;
case GROUP_ID:
if (groupId == null)
groupId = token;
else
groupId = token + "." + groupId;
break;
default:
break make;
}
context = context.increment();
}
Objects.requireNonNull(groupId);
Objects.requireNonNull(artifactId);
Objects.requireNonNull(version);
return makeXML(groupId, artifactId, version);
}
private static String makeXML(String group, String artifact, String version) {
return String.join(System.lineSeparator(), new String[] {
"<dependency>",
" <groupId>" + group + "</groupId>",
" <artifactId>" + artifact + "</artifactId>",
" <version>" + version + "</version>",
"</dependency>"
});
}
private static boolean isValidPath(Path path) {
return path != null && !path.equals(PWD);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment