Debian Codegraph @

maven-packager-utils/src/main/java/org/debian/maven/packager/GenerateDebianFilesMojo.java

raw
1 /*
2 * Copyright 2009 Ludovic Claude.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.debian.maven.packager;
18
19 import java.io.File;
20 import java.io.FileReader;
21 import java.io.FileWriter;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Calendar;
25 import java.util.GregorianCalendar;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Properties;
29 import java.util.Set;
30 import java.util.StringTokenizer;
31 import java.util.TreeSet;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34
35 import org.apache.maven.artifact.repository.ArtifactRepository;
36 import org.apache.maven.model.Developer;
37 import org.apache.maven.plugin.AbstractMojo;
38 import org.apache.maven.plugin.MojoExecutionException;
39 import org.apache.maven.plugins.annotations.LifecyclePhase;
40 import org.apache.maven.plugins.annotations.Mojo;
41 import org.apache.maven.plugins.annotations.Parameter;
42 import org.apache.maven.plugins.annotations.ResolutionScope;
43 import org.apache.maven.project.MavenProject;
44 import org.apache.velocity.VelocityContext;
45 import org.apache.velocity.app.Velocity;
46 import org.debian.maven.packager.interaction.MultilineQuestion;
47 import org.debian.maven.packager.interaction.SimpleQuestion;
48 import org.debian.maven.packager.util.LicensesScanner;
49 import org.debian.maven.packager.util.PackageScanner;
50 import org.debian.maven.repo.ListOfPOMs;
51 import org.debian.maven.repo.POMOptions;
52
53 /**
54 * Generate the Debian files for packaging the current Maven project.
55 *
56 * @author Ludovic Claude
57 */
58 @Mojo(name = "generate", defaultPhase = LifecyclePhase.PROCESS_SOURCES, aggregator = true, requiresDependencyResolution = ResolutionScope.RUNTIME)
59 public class GenerateDebianFilesMojo extends AbstractMojo {
60
61 /**
62 * The Maven Project Object
63 */
64 @Parameter(defaultValue = "${project}", readonly = true, required = true)
65 protected MavenProject project;
66
67 /**
68 * A list of every project in this reactor; provided by Maven
69 */
70 @Parameter(defaultValue = "${project.collectedProjects}")
71 protected List<MavenProject> collectedProjects;
72
73 @Parameter(defaultValue = "${localRepository}", readonly = true, required = true)
74 protected ArtifactRepository localRepository;
75
76 /**
77 * Location of the file.
78 */
79 @Parameter(property = "debian.directory", defaultValue = "debian")
80 protected File outputDirectory;
81
82 /**
83 * Name of the packager (e.g. 'Ludovic Claude')
84 */
85 @Parameter(property = "packager", required = true)
86 protected String packager;
87
88 /**
89 * Email of the packager (e.g. '[email protected]')
90 */
91 @Parameter(property = "email", required = true)
92 protected String email;
93
94 /**
95 * License used by the packager (e.g. 'GPL-3' or 'Apache-2.0')
96 * See http://dep.debian.net/deps/dep5/ for the list of licenses.
97 */
98 @Parameter(property = "packagerLicense", defaultValue = "Apache-2.0", required = true)
99 protected String packagerLicense;
100
101 /**
102 * Name of the source package (e.g. 'commons-lang')
103 */
104 @Parameter(property = "package", required = true)
105 protected String packageName;
106
107 /**
108 * Name of the binary package (e.g. 'libcommons-lang-java')
109 */
110 @Parameter(property = "bin.package", required = true)
111 protected String binPackageName;
112
113 /**
114 * URL for downloading the source code, in the form scm:[svn|cvs]:http://xxx/
115 * for downloads using a source code repository,
116 * or http://xxx.[tar|zip|gz|tgz] for downloads using source tarballs.
117 */
118 @Parameter(property = "downloadUrl")
119 protected String downloadUrl;
120
121 /**
122 * If true, include running the tests during the build.
123 */
124 @Parameter(property = "runTests", defaultValue = "false")
125 protected boolean runTests;
126
127 /**
128 * If true, generate the Javadoc packaged in a separate package.
129 */
130 @Parameter(property = "generateJavadoc", defaultValue = "false")
131 protected boolean generateJavadoc;
132
133 private PackageScanner scanner = new PackageScanner(false);
134 private LicensesScanner licensesScanner = new LicensesScanner();
135
136 public void execute() throws MojoExecutionException {
137 if (project.getName() == null || project.getName().isEmpty()) {
138 project.setName(new SimpleQuestion("POM does not contain the project name. Please enter the name of the project:").ask());
139 }
140 if (project.getUrl() == null || project.getUrl().isEmpty()) {
141 project.setUrl(new SimpleQuestion("POM does not contain the project URL. Please enter the URL of the project:").ask());
142 }
143 if (project.getDescription() == null || project.getDescription().trim().isEmpty()) {
144 project.setDescription(new MultilineQuestion("Please enter a short description of the project (press Enter twice to stop):").ask());
145 }
146
147 try {
148 Properties velocityProperties = new Properties();
149 velocityProperties.put("resource.loader", "class");
150 velocityProperties.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
151 Velocity.init(velocityProperties);
152 VelocityContext context = new VelocityContext();
153 context.put("package", packageName);
154 context.put("binPackage", binPackageName);
155 context.put("packager", packager);
156 context.put("packagerEmail", extractEmail(email));
157 context.put("project", project);
158 context.put("collectedProjects", wrapMavenProjects(collectedProjects));
159 context.put("runTests", Boolean.valueOf(runTests));
160 context.put("generateJavadoc", Boolean.valueOf(generateJavadoc));
161 context.put("hasBuildXml", new File(project.getBasedir().getAbsolutePath(), "build.xml").exists());
162
163 Set<String> licenses = licensesScanner.discoverLicenses(project.getLicenses());
164 context.put("licenses", licenses);
165
166 if (licenses.size() == 1) {
167 packagerLicense = licenses.iterator().next();
168 }
169 if (packagerLicense == null) {
170 String q = "Packager license for the debian/ files was not found, please enter a license name preferably in one of:\n"
171 + "Apache Artistic BSD FreeBSD ISC CC-BY CC-BY-SA CC-BY-ND CC-BY-NC CC-BY-NC-SA CC-BY-NC-ND CC0 CDDL CPL Eiffel"
172 + "Expat GPL LGPL GFDL GFDL-NIV LPPL MPL Perl PSF QPL W3C-Software ZLIB Zope";
173 String s = new SimpleQuestion(q).ask();
174 if (s.length() > 0) {
175 packagerLicense = s;
176 }
177 }
178 context.put("packagerLicense", packagerLicense);
179
180 String copyrightOwner = "";
181 String projectTeam = "";
182 if (project.getOrganization() != null) {
183 copyrightOwner = project.getOrganization().getName();
184 projectTeam = project.getOrganization().getName() + " developers";
185 }
186 if (copyrightOwner == null || copyrightOwner.isEmpty()) {
187 if (!project.getDevelopers().isEmpty()) {
188 Developer developer = project.getDevelopers().get(0);
189 copyrightOwner = developer.getName();
190 if (developer.getEmail() != null && !developer.getEmail().isEmpty()) {
191 copyrightOwner += " <" + developer.getEmail() + ">";
192 }
193 }
194 }
195 if (copyrightOwner == null || copyrightOwner.isEmpty()) {
196 copyrightOwner = new SimpleQuestion("Could not find the copyright owner(s) for the upstream sources, please enter their name(s):").ask();
197 }
198 context.put("copyrightOwner", copyrightOwner);
199
200 if (projectTeam.isEmpty()) {
201 projectTeam = project.getName() + " developers";
202 }
203 context.put("projectTeam", projectTeam);
204
205 String copyrightYear;
206 int currentYear = new GregorianCalendar().get(Calendar.YEAR);
207 if (project.getInceptionYear() != null) {
208 copyrightYear = project.getInceptionYear();
209 if (Integer.parseInt(copyrightYear) < currentYear) {
210 copyrightYear += "-" + currentYear;
211 }
212 } else {
213 copyrightYear = String.valueOf(currentYear);
214 }
215 context.put("copyrightYear", copyrightYear);
216 context.put("currentYear", currentYear);
217 context.put("description", formatDescription(project.getDescription()));
218
219 File substvarsFile = new File(outputDirectory, binPackageName + ".substvars");
220 if (substvarsFile.exists()) {
221 Properties substvars = new Properties();
222 substvars.load(new FileReader(substvarsFile));
223 Set<String> compileDepends = new TreeSet<String>();
224 compileDepends.addAll(split(substvars.getProperty("maven.CompileDepends")));
225 compileDepends.addAll(split(substvars.getProperty("maven.Depends")));
226 Set<String> buildDepends = new TreeSet<String>(compileDepends);
227 Set<String> testDepends = new TreeSet<String>(split(substvars.getProperty("maven.TestDepends")));
228 if (runTests) {
229 buildDepends.addAll(testDepends);
230 }
231 if (generateJavadoc) {
232 buildDepends.addAll(split(substvars.getProperty("maven.DocDepends")));
233 buildDepends.addAll(split(substvars.getProperty("maven.DocOptionalDepends")));
234 }
235 // Remove dependencies that are implied by maven-debian-helper
236 for (Iterator<String> i = buildDepends.iterator(); i.hasNext();) {
237 String dependency = i.next();
238 if (dependency.startsWith("libmaven-clean-plugin-java") ||
239 dependency.startsWith("libmaven-resources-plugin-java") ||
240 dependency.startsWith("libmaven-compiler-plugin-java") ||
241 dependency.startsWith("libmaven-jar-plugin-java") ||
242 dependency.startsWith("libmaven-site-plugin-java") ||
243 dependency.startsWith("libsurefire-java") ||
244 dependency.startsWith("velocity") ||
245 dependency.startsWith("libplexus-velocity-java")) {
246 i.remove();
247 }
248 }
249 if (generateJavadoc) {
250 buildDepends.add("libmaven-javadoc-plugin-java");
251 }
252 context.put("buildDependencies", buildDepends);
253 context.put("runtimeDependencies", split(substvars.getProperty("maven.Depends")));
254 context.put("testDependencies", split(substvars.getProperty("maven.TestDepends")));
255 context.put("optionalDependencies", split(substvars.getProperty("maven.OptionalDepends")));
256 context.put("javadocDependencies", split(substvars.getProperty("maven.DocDepends")));
257 context.put("javadocOptionalDependencies", split(substvars.getProperty("maven.DocOptionalDepends")));
258 } else {
259 getLog().warn("Cannot find file " + substvarsFile);
260 }
261
262 int downloadType = DownloadType.UNKNOWN;
263
264 if (downloadUrl == null) {
265 if (project.getScm() != null) {
266 downloadUrl = project.getScm().getConnection();
267 }
268 }
269 if (downloadUrl != null && downloadUrl.startsWith("scm:svn:")) {
270 downloadType = DownloadType.SVN;
271 downloadUrl = downloadUrl.substring("scm:svn:".length());
272 String tag = project.getVersion();
273 int tagPos = downloadUrl.indexOf(tag);
274 String baseUrl = null;
275 String suffixUrl = null;
276 String tagMarker = null;
277 if (tagPos >= 0) {
278 baseUrl = downloadUrl.substring(0, tagPos);
279 suffixUrl = downloadUrl.substring(tagPos + tag.length());
280 if (!suffixUrl.endsWith("/")) {
281 suffixUrl += "/";
282 }
283 int slashPos = baseUrl.lastIndexOf("/");
284 tagMarker = baseUrl.substring(slashPos + 1);
285 baseUrl = baseUrl.substring(0, slashPos);
286 }
287 if (tagPos < 0 && downloadUrl.contains("/trunk")) {
288 getLog().warn("Download URL does not include a tagged revision but /trunk found,");
289 getLog().warn("Trying to guess the address of the tagged revision.");
290 tag = "trunk";
291 tagPos = downloadUrl.indexOf(tag);
292 baseUrl = downloadUrl.substring(0, tagPos);
293 baseUrl += "tags";
294 tagMarker = packageName + "-";
295 suffixUrl = "";
296 }
297 if (tagPos >= 0) {
298 context.put("baseUrl", baseUrl);
299 context.put("tagMarker", tagMarker);
300 context.put("suffixUrl", suffixUrl);
301
302 generateFile(context, "watch.svn.vm", outputDirectory, "watch");
303
304 } else {
305 getLog().warn("Cannot locate the version in the download url (" + downloadUrl + ").");
306 getLog().warn("Please run again and provide the download location with an explicit version tag, e.g.");
307 getLog().warn("-DdownloadUrl=scm:svn:http://svn.codehaus.org/modello/tags/modello-1.0-alpha-21/");
308 }
309 }
310
311 if (downloadUrl != null && downloadUrl.startsWith("scm:git:") && downloadUrl.contains("github")) {
312 Pattern pattern = Pattern.compile("github\\.com[/:]([^/]+)/([^/\\.]+)");
313 Matcher matcher = pattern.matcher(downloadUrl);
314 if (matcher.find()) {
315 downloadType = DownloadType.GITHUB;
316 downloadUrl = downloadUrl.substring("scm:git:".length());
317
318 context.put("userId", matcher.group(1));
319 context.put("repository", matcher.group(2));
320
321 generateFile(context, "watch.github.vm", outputDirectory, "watch");
322 }
323 }
324
325 if (downloadType == DownloadType.UNKNOWN) {
326 getLog().warn("Cannot recognize the download url (" + downloadUrl + ").");
327 }
328
329 generateFile(context, "README.source.vm", outputDirectory, "README.source");
330 generateFile(context, "copyright.vm", outputDirectory, "copyright");
331 generateFile(context, "rules.vm", outputDirectory, "rules", true);
332
333 context.put("version.vm", mangleVersion(project.getVersion()) + "-1");
334
335 generateFile(context, "rules.vm", new File("."), ".debianVersion");
336
337 if (generateJavadoc) {
338 if (project.getPackaging().equals("pom") && collectedProjects.size() > 1) {
339 generateFile(context, "java-doc.doc-base.api.multi.vm", outputDirectory, binPackageName + "-doc.doc-base.api");
340 generateFile(context, "java-doc.install.multi.vm", outputDirectory, binPackageName + "-doc.install");
341 } else {
342 generateFile(context, "java-doc.doc-base.api.vm", outputDirectory, binPackageName + "-doc.doc-base.api");
343 generateFile(context, "java-doc.install.vm", outputDirectory, binPackageName + "-doc.install");
344 }
345 }
346
347 generateFile(context, "maven.properties.vm", outputDirectory, "maven.properties");
348 generateFile(context, "control.vm", outputDirectory, "control");
349 generateFile(context, "format.vm", new File(outputDirectory, "source"), "format");
350
351 } catch (IOException ex) {
352 ex.printStackTrace();
353 }
354 }
355
356 /**
357 * Returns the email enclosed in &lt; ... &gt;.
358 *
359 * @see <a href="https://bugs.debian.org/638788">Bug #638788</a>
360 */
361 private String extractEmail(String email) {
362 if (email != null && email.indexOf('<') >= 0 && email.indexOf('>') >= 0) {
363 email = email.substring(email.indexOf('<') + 1, email.indexOf('>') - 1);
364 }
365 return email;
366 }
367
368 /**
369 * Normalizes the project version for use as a Debian package version.
370 */
371 private String mangleVersion(String projectVersion) {
372 String debianVersion = projectVersion.replace("-alpha-", "~alpha");
373 debianVersion = debianVersion.replace("-beta-", "~beta");
374 debianVersion = debianVersion.replace("-rc-", "~rc");
375 return debianVersion;
376 }
377
378 /**
379 * Format the specified text to be suitable as a package long description.
380 * Lines are wrapped after 70 characters and a dot is placed on empty lines.
381 *
382 * @param description
383 */
384 List<String> formatDescription(String description) {
385 List<String> lines = new ArrayList<String>();
386
387 if (description != null) {
388 StringTokenizer st = new StringTokenizer(description.trim(), "\n\t ");
389 StringBuilder descLine = new StringBuilder();
390 while (st.hasMoreTokens()) {
391 descLine.append(st.nextToken());
392 descLine.append(" ");
393 if (descLine.length() > 70 || !st.hasMoreTokens()) {
394 String line = descLine.toString().trim();
395 if (line.isEmpty()) {
396 line = ".";
397 }
398 lines.add(line);
399 descLine = new StringBuilder();
400 }
401 }
402 }
403
404 return lines;
405 }
406
407 private List<WrappedProject> wrapMavenProjects(List<MavenProject> projects) {
408 List<WrappedProject> wrappedProjects = new ArrayList<WrappedProject>();
409 for (MavenProject aProject: projects) {
410 wrappedProjects.add(new WrappedProject(this.project, aProject));
411 }
412 return wrappedProjects;
413 }
414
415 private void setupArtifactLocation(ListOfPOMs listOfPOMs, ListOfPOMs listOfJavadocPOMs, MavenProject mavenProject) {
416 String dirRelPath = new WrappedProject(project, mavenProject).getBaseDir();
417
418 if (! "pom".equals(mavenProject.getPackaging())) {
419 String pomFile = dirRelPath + "pom.xml";
420 listOfPOMs.getOrCreatePOMOptions(pomFile).setJavaLib(true);
421 String extension = mavenProject.getPackaging();
422 if (extension.equals("bundle")) {
423 extension = "jar";
424 }
425 if (extension.equals("webapp")) {
426 extension = "war";
427 }
428 if (mavenProject.getArtifact() != null && mavenProject.getArtifact().getFile() != null) {
429 extension = mavenProject.getArtifact().getFile().toString();
430 extension = extension.substring(extension.lastIndexOf('.') + 1);
431 }
432 POMOptions pomOptions = listOfPOMs.getOrCreatePOMOptions(pomFile);
433 pomOptions.setArtifact(dirRelPath + "target/" + mavenProject.getArtifactId() + "-*."
434 + extension);
435 pomOptions.setJavaLib(true);
436 if (mavenProject.getArtifactId().matches(packageName + "\\d")) {
437 pomOptions.setUsjName(packageName);
438 }
439 }
440 }
441
442 private void generateFile(VelocityContext context, String templateName, File destDir, String fileName) throws IOException {
443 generateFile(context, templateName, destDir, fileName, false);
444 }
445
446 private void generateFile(VelocityContext context, String templateName, File destDir, String fileName, boolean executable) throws IOException {
447 destDir.mkdirs();
448 File file = new File(destDir, fileName);
449 FileWriter out = new FileWriter(file);
450 Velocity.mergeTemplate(templateName, "UTF8", context, out);
451 out.flush();
452 out.close();
453 if (executable) {
454 file.setExecutable(true);
455 }
456 }
457
458 private List<String> split(String s) {
459 List<String> l = new ArrayList<String>();
460 if (s != null) {
461 StringTokenizer st = new StringTokenizer(s, ",");
462 while (st.hasMoreTokens()) {
463 l.add(st.nextToken().trim());
464 }
465 }
466 return l;
467 }
468
469 public static class WrappedProject {
470 private final MavenProject baseProject;
471 private final MavenProject mavenProject;
472
473 public WrappedProject(MavenProject baseProject, MavenProject mavenProject) {
474 this.baseProject = baseProject;
475 this.mavenProject = mavenProject;
476 }
477
478 public String getBaseDir() {
479 String basedir = baseProject.getBasedir().getAbsolutePath();
480 String dirRelPath = "";
481 if (! mavenProject.getBasedir().equals(baseProject.getBasedir())) {
482 dirRelPath = mavenProject.getBasedir().getAbsolutePath().substring(basedir.length() + 1) + "/";
483 }
484 return dirRelPath;
485 }
486
487 public String getArtifactId() {
488 return mavenProject.getArtifactId();
489 }
490
491 public String getGroupId() {
492 return mavenProject.getGroupId();
493 }
494
495 public String getVersion() {
496 return mavenProject.getVersion();
497 }
498
499 public String getPackaging() {
500 return mavenProject.getPackaging();
501 }
502 }
503
504 interface DownloadType {
505
506 int UNKNOWN = 0;
507 int SVN = 1;
508 int CVS = 2;
509 int TARBALL = 3;
510 int GITHUB = 4;
511 }
512 }
513