private emitMavenPom()

in packages/jsii-pacmak/lib/targets/java.ts [1093:1357]


  private emitMavenPom(assm: spec.Assembly, fingerprint: boolean) {
    if (!assm.targets?.java) {
      throw new Error(`Assembly ${assm.name} does not declare a java target`);
    }

    const comment = fingerprint
      ? {
          '#comment': [
            `Generated by jsii-pacmak@${VERSION_DESC} on ${new Date().toISOString()}`,
            `@jsii-pacmak:meta@ ${JSON.stringify(this.metadata)}`,
          ],
        }
      : {};

    this.code.openFile('pom.xml');
    this.code.line(
      xmlbuilder
        .create(
          {
            project: {
              '@xmlns': 'http://maven.apache.org/POM/4.0.0',
              '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
              '@xsi:schemaLocation':
                'http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd',

              ...comment,

              modelVersion: '4.0.0',
              name: '${project.groupId}:${project.artifactId}',
              description: assm.description,
              url: assm.homepage,

              licenses: {
                license: getLicense(),
              },

              developers: {
                developer: mavenDevelopers(),
              },

              scm: {
                connection: `scm:${assm.repository.type}:${assm.repository.url}`,
                url: assm.repository.url,
              },

              groupId: assm.targets.java.maven.groupId,
              artifactId: assm.targets.java.maven.artifactId,
              version: makeVersion(
                assm.version,
                assm.targets.java.maven.versionSuffix,
              ),
              packaging: 'jar',

              properties: { 'project.build.sourceEncoding': 'UTF-8' },

              dependencies: { dependency: mavenDependencies.call(this) },

              build: {
                plugins: {
                  plugin: [
                    {
                      groupId: 'org.apache.maven.plugins',
                      artifactId: 'maven-compiler-plugin',
                      version: '3.11.0',
                      configuration: {
                        source: '1.8',
                        target: '1.8',
                        fork: 'true',
                        maxmem: '4096m',
                      },
                    },
                    {
                      groupId: 'org.apache.maven.plugins',
                      artifactId: 'maven-jar-plugin',
                      version: '3.3.0',
                      configuration: {
                        archive: {
                          index: true,
                          manifest: {
                            addDefaultImplementationEntries: true,
                            addDefaultSpecificationEntries: true,
                          },
                        },
                      },
                    },
                    {
                      groupId: 'org.apache.maven.plugins',
                      artifactId: 'maven-source-plugin',
                      version: '3.3.0',
                      executions: {
                        execution: {
                          id: 'attach-sources',
                          goals: { goal: 'jar' },
                        },
                      },
                    },
                    {
                      groupId: 'org.apache.maven.plugins',
                      artifactId: 'maven-javadoc-plugin',
                      version: '3.5.0',
                      executions: {
                        execution: {
                          id: 'attach-javadocs',
                          goals: { goal: 'jar' },
                        },
                      },
                      configuration: {
                        failOnError: false,
                        show: 'protected',
                        sourceFileExcludes: {
                          // Excluding the $Module classes so they won't pollute the docsite. They otherwise
                          // are all collected at the top of the classlist, burrying useful information under
                          // a lot of dry scrolling.
                          exclude: ['**/$Module.java'],
                        },
                        // Adding these makes JavaDoc generation about a 3rd faster (which is far and away the most
                        // expensive part of the build)
                        additionalJOption: [
                          '-J-XX:+TieredCompilation',
                          '-J-XX:TieredStopAtLevel=1',
                        ],
                        doclint: 'none',
                        quiet: 'true',
                      },
                    },
                    {
                      groupId: 'org.apache.maven.plugins',
                      artifactId: 'maven-enforcer-plugin',
                      version: '3.3.0',
                      executions: {
                        execution: {
                          id: 'enforce-maven',
                          goals: { goal: 'enforce' },
                          configuration: {
                            rules: {
                              requireMavenVersion: { version: '3.6' },
                            },
                          },
                        },
                      },
                    },
                    {
                      groupId: 'org.codehaus.mojo',
                      artifactId: 'versions-maven-plugin',
                      version: '2.16.0',
                      configuration: {
                        generateBackupPoms: false,
                      },
                    },
                  ],
                },
              },
            },
          },
          { encoding: 'UTF-8' },
        )
        .end({ pretty: true }),
    );
    this.code.closeFile('pom.xml');

    /**
     * Combines a version number with an optional suffix. The suffix, when present, must begin with
     * '-' or '.', and will be concatenated as-is to the version number..
     *
     * @param version the semantic version number
     * @param suffix  the suffix, if any.
     */
    function makeVersion(version: string, suffix?: string): string {
      if (!suffix) {
        return toReleaseVersion(version, TargetName.JAVA);
      }
      if (!suffix.startsWith('-') && !suffix.startsWith('.')) {
        throw new Error(
          `versionSuffix must start with '-' or '.', but received ${suffix}`,
        );
      }
      return `${version}${suffix}`;
    }

    function mavenDependencies(this: JavaGenerator) {
      const dependencies = new Array<MavenDependency>();
      for (const [depName, version] of Object.entries(
        this.assembly.dependencies ?? {},
      )) {
        const dep = this.assembly.dependencyClosure?.[depName];
        if (!dep?.targets?.java) {
          throw new Error(
            `Assembly ${assm.name} depends on ${depName}, which does not declare a java target`,
          );
        }
        dependencies.push({
          groupId: dep.targets.java.maven.groupId,
          artifactId: dep.targets.java.maven.artifactId,
          version: toMavenVersionRange(
            version,
            dep.targets.java.maven.versionSuffix,
          ),
        });
      }
      // The JSII java runtime base classes
      dependencies.push({
        groupId: 'software.amazon.jsii',
        artifactId: 'jsii-runtime',
        version:
          VERSION === '0.0.0'
            ? '[0.0.0-SNAPSHOT]'
            : // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
              toMavenVersionRange(`^${VERSION}`),
      });

      // Provides @org.jetbrains.*
      dependencies.push({
        groupId: 'org.jetbrains',
        artifactId: 'annotations',
        version: '[16.0.3,20.0.0)',
      });

      // Provides @javax.annotation.Generated for JDKs >= 9
      dependencies.push({
        '#comment': 'Provides @javax.annotation.Generated for JDKs >= 9',
        groupId: 'javax.annotation',
        artifactId: 'javax.annotation-api',
        version: '[1.3.2,1.4.0)',
        scope: 'compile',
      });

      return dependencies;
    }

    function mavenDevelopers() {
      return [assm.author, ...(assm.contributors ?? [])].map(toDeveloper);

      function toDeveloper(person: spec.Person) {
        const developer: any = {
          [person.organization ? 'organization' : 'name']: person.name,
          roles: { role: person.roles },
        };
        // We cannot set "undefined" or "null" to a field - this causes invalid XML to be emitted (per POM schema).
        if (person.email) {
          developer.email = person.email;
        }
        if (person.url) {
          developer[person.organization ? 'organizationUrl' : 'url'] =
            person.url;
        }
        return developer;
      }
    }

    /**
     * Get the maven-style license block for a the assembly.
     * @see https://maven.apache.org/pom.html#Licenses
     */
    function getLicense() {
      const spdx = spdxLicenseList[assm.license];
      return (
        spdx && {
          name: spdx.name,
          url: spdx.url,
          distribution: 'repo',
          comments: spdx.osiApproved ? 'An OSI-approved license' : undefined,
        }
      );
    }
  }