Как сделать gradle сгенерировать действительный файл pom.xml в корне проекта для пользователей maven?
Пока только два дня, я определенно продаюсь с использованием gradle для всех моих проектов Java и отбрасываю pom.xml из корня всех моих проектов.
Однако я хотел бы оставаться maven-совместимым в том смысле, что я хотел бы, чтобы задача gradle могла генерировать подходящий pom.xml в корне проекта, если пользователь этого захочет.
В настоящий момент единственная ссылка на pom.xml, который у меня есть, находится в этом разделе файла build.gradle(это, с очень небольшими изменениями, то, что найдено здесь):
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment {
MavenDeployment deployment -> signing.signPom(deployment);
}
repository(url: sonatypeRepoURI) {
authentication(userName: sonatypeUsername,
password: sonatypePassword);
}
pom.project {
name "${name}";
packaging "bundle";
description "${description}";
url "${projectURL}";
scm {
url "${gitroscm}";
connection "${gitroscm}";
developerConnection "${gitrwscm}";
}
licenses {
license {
name "Lesser General Public License, version 3 or greater";
url "http://www.gnu.org/licenses/lgpl.html";
distribution "repo";
}
}
developers {
developer {
id "whocares";
name "whocares";
email "whocares";
}
}
}
}
}
}
Как извлечь pom.project
из этой очень глубоко вложенной конструкции в задачу, которая могла бы генерировать pom.xml(по умолчанию сгенерированный pom.xml находится в build/poms/pom-default.xml
и выглядит неплохо)?
Что еще более важно, возможно ли извлечь этот pom.project
из uploadArchives
, все еще имея возможность ссылаться на него?
Полная ссылка на файл build.gradle: здесь.
Ответы
Ответ 1
Вы можете использовать gradle плагин maven. Это добавляет к вашему проекту условный метод pom
, который вы можете использовать в задаче для создания файла pom.xml
, например
apply plugin: 'maven'
task createPom << {
pom {
project {
groupId 'org.example'
artifactId 'test'
version '1.0.0'
inceptionYear '2008'
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution 'repo'
}
}
}
}.writeTo("pom.xml")
}
Затем вы вызываете gradle createPom
для генерации pom.xml в корне проекта. Из всех вещей в определении pom вы должны действительно предоставить groupId
, artifactId
и version
, другие тонкости, такие как licenses
, не так важны.
Вы также можете посмотреть этот пример для определения проекта с некоторыми зависимостями и попробовать запустить его, чтобы увидеть, что он производит.
Ответ 2
Вот мой build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'maven'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile 'org.springframework:spring-core:4.0.5.RELEASE'
compile 'org.springframework:spring-webmvc:4.0.5.RELEASE'
compile 'org.slf4j:slf4j-api:1.7.5'
runtime 'org.slf4j:slf4j-log4j12:1.7.5'
testCompile 'org.springframework:spring-test:4.0.5.RELEASE'
testCompile 'junit:junit:4.11'
testCompile "org.mockito:mockito-core:1.9.5"
testCompile "org.hamcrest:hamcrest-library:1.3"
testCompile 'javax.servlet:javax.servlet-api:3.0.1'
}
test {
testLogging {
// Show that tests are run in the command-line output
events 'started', 'passed'
}
}
task wrapper(type: Wrapper) { gradleVersion = '1.12' }
task createPom {
pom {
project {
groupId 'sg.test.spring.web.guide'
artifactId 'sg-web-initial'
version '1.0.0-SNAPSHOT'
inceptionYear '2008'
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution 'repo'
}
}
}
}.writeTo("pom.xml")
}
Вы можете назвать задачу createPom
на anyTaskName
по своему усмотрению.
Затем просто запустите gradle clean
или grale build
или просто gradle createPom
.
Это создаст его как pom.xml в корне проекта. Хотя вы можете заменить writeTo("pom.xml")
на writeTo("<anyDir>/newpom.xml")
.
Результат pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>sg.test.spring.web.guide</groupId>
<artifactId>sg-web-initial</artifactId>
<version>1.0.0-SNAPSHOT</version>
<inceptionYear>2008</inceptionYear>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.5.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.5.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.5.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>