Update archetype to keep consistent behavior with `func init` (#170)

* Bump version

* Using velocity template for dynamtic content

* Throwing exception instead of show warning in post script

* Make -Dtriger case insensitive and support parameter without 'Trigger'

* Remove unused file and fix issue when path contains space

* Fix inline expression issue

* Fix default pricingtier for docker archetype
This commit is contained in:
Hanxiao Liu 2021-04-20 13:41:15 +08:00 коммит произвёл GitHub
Родитель 575364f3e2
Коммит 07a31a052c
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
6 изменённых файлов: 57 добавлений и 225 удалений

Просмотреть файл

@ -6,7 +6,7 @@
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-functions-archetype</artifactId>
<version>1.37</version>
<version>1.38-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Maven Archetype for Azure Functions</name>

Просмотреть файл

@ -1,42 +1,23 @@
import java.nio.file.Files
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.nio.file.Paths;
def isDocker = request.getProperties().get("docker")
def artifactId = request.getProperties().get("artifactId")
def dockerFile = "Dockerfile"
def pomFile = "pom.xml"
def dockerPomFile = "pom-docker.xml"
def rootDir = Paths.get(request.getOutputDirectory(), artifactId).toFile()
if (Boolean.valueOf(isDocker)) {
// For docker, replace origin pom.xml with pom-docker.xml
Files.move(new File(rootDir, dockerPomFile).toPath(), new File(rootDir, pomFile).toPath(), StandardCopyOption.REPLACE_EXISTING)
} else {
// Otherwise, remove Dockerfile and pom-docker.xml
Files.deleteIfExists(new File(rootDir, dockerFile).toPath())
Files.deleteIfExists(new File(rootDir, dockerPomFile).toPath())
}
def appName = request.getProperties().get("appName")
def javaVersion = request.getProperties().get("javaVersion")
def pom = Paths.get(request.getOutputDirectory(), artifactId, pomFile).toFile()
def pomText = pom.text
// Update java compile version & java runtime version
// Supported values are 8/11, otherwise will use java 8 by default
pomText = pomText.replaceFirst("<java.version>.*</java.version>", String.format("<java.version>%s</java.version>", "11".equals(javaVersion) ? "11" : "1.8"))
pomText = pomText.replaceFirst("<javaVersion>.*</javaVersion>", String.format("<javaVersion>%s</javaVersion>", "11".equals(javaVersion) ? "11" : "8"))
// If user didn't modify appName, replace the expression with real value
// Set the values here as users will get prompt if we use expressions in <defaultValue> of <requiredProperty> in archetype metadata
if (appName == null || appName.equals("\$(artifactId)-\$(timestamp)")) {
def finalAppName = String.format("%s-%s", artifactId, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")))
// Replace the string directly as use XmlNodePrinter will break origin file style and comments
pomText = pomText.replace("<functionAppName>\$(artifactId)-\$(timestamp)</functionAppName>", String.format("<functionAppName>%s</functionAppName>", finalAppName))
def isDocker = request.getProperties().get("docker")
if (!Boolean.valueOf(isDocker)) {
def artifactId = request.getProperties().get("artifactId")
def dockerFile = "Dockerfile"
Files.deleteIfExists(new File(rootDir, dockerFile).toPath()) // Delete Dockerfile for none-docker project
}
pom.text = pomText
def trigger = request.getProperties().get("trigger");
if ("HttpTrigger".equalsIgnoreCase(trigger) || "Http".equalsIgnoreCase(trigger)) {
return
}
// Remove origin source dir which contains unused test cases
def sourceFolder = new File(rootDir, "src")
sourceFolder.deleteDir()
// todo: remove the parameter with default values, may need to update maven plugin
def templateMap = [
"BlobTrigger" : "-Dfunctions.template=BlobTrigger -Dconnection=\"<connection>\" -Dpath=mycontainer",
@ -48,28 +29,24 @@ def templateMap = [
"ServiceBusQueueTrigger": "-Dfunctions.template=ServiceBusQueueTrigger -Dconnection=\"<connection>\" -DqueueName=mysbqueue",
"ServiceBusTopicTrigger": "-Dfunctions.template=ServiceBusTopicTrigger -Dconnection=\"<connection>\" -DtopicName=mysbtopic -DsubscriptionName=mysubscription",
];
if (!"HttpTrigger".equalsIgnoreCase(trigger)) {
println("Generating trigger from template, please replace the values with placeholder in annotation with real value if necessary")
def triggerParameter = templateMap.get(trigger)
if (triggerParameter == null) {
println(String.format("Invalid trigger type, supported values are %s and HttpTrigger, using HttpTrigger by default", String.join(",", templateMap.keySet())));
return
}
def sourceFolder = new File(rootDir, "src")
sourceFolder.deleteDir(); // Remove origin source dir which contains unused test cases
def isWindows = System.properties['os.name'].toLowerCase().contains('windows')
def starter = isWindows ? "cmd.exe" : "/bin/sh"
def switcher = isWindows ? "/c" : "-c"
def command = "mvn azure-functions:add -f ${pom.getAbsolutePath()} -Dfunctions.package=${request.getProperties().get("groupId")} -Dfunctions.name=Function ${triggerParameter} -B"
if (!isWindows) {
command = command.replace("\$", "\\\$")
}
def output = new StringBuilder()
def proc = [starter, switcher, command].execute();
proc.consumeProcessOutput(output, output)
proc.waitForOrKill(60 * 1000); // wait for 60s
if (proc.exitValue() != 0 || output == null || !output.contains("BUILD SUCCESS")) {
println("Failed to generate target trigger, please run `mvn azure-functions:add` manually in project root")
println("Output: \n${output}")
}
def triggerParameter = templateMap.keySet().stream()
.filter({ key -> key.equalsIgnoreCase(trigger) || key.substring(0, key.lastIndexOf("Trigger")).equalsIgnoreCase(trigger) }).findFirst()
.map(templateMap.&get)
.orElseThrow({ -> new RuntimeException(String.format("Invalid trigger type `%s`, supported values are %s and HttpTrigger", trigger, String.join(",", templateMap.keySet()))) })
println("Generating trigger from template, please replace the values with placeholder in annotation with real value if necessary")
def pomFile = new File(rootDir, "pom.xml")
def isWindows = System.properties['os.name'].toLowerCase().contains('windows')
def starter = isWindows ? "cmd.exe" : "/bin/sh"
def switcher = isWindows ? "/c" : "-c"
def command = "mvn azure-functions:add -f \"${pomFile.getAbsolutePath()}\" -Dfunctions.package=\"${request.getProperties().get("groupId")}\" -Dfunctions.name=\"Function\" ${triggerParameter} -B"
if (!isWindows) {
command = command.replace("\$", "\\\$")
}
def output = new StringBuilder()
def proc = [starter, switcher, command].execute();
proc.consumeProcessOutput(output, output)
proc.waitForOrKill(60 * 1000); // wait for 60s
if (proc.exitValue() != 0 || output == null || !output.contains("BUILD SUCCESS")) {
println("${output}")
throw new RuntimeException("Failed to generate target trigger, please run `mvn azure-functions:add` manually in project root")
}

Просмотреть файл

@ -60,7 +60,6 @@
<include>*.json</include>
<include>.gitignore</include>
<include>Dockerfile</include>
<include>pom-docker.xml</include>
</includes>
</fileSet>
</fileSets>

Просмотреть файл

@ -1,162 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>${groupId}</groupId>
<artifactId>${artifactId}</artifactId>
<version>${version}</version>
<packaging>jar</packaging>
<name>Azure Java Functions</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<azure.functions.maven.plugin.version>1.10.1</azure.functions.maven.plugin.version>
<azure.functions.java.library.version>1.4.2</azure.functions.java.library.version>
<functionAppName>${appName}</functionAppName>
<stagingDirectory>${project.build.directory}/azure-functions/${functionAppName}</stagingDirectory>
</properties>
<dependencies>
<dependency>
<groupId>com.microsoft.azure.functions</groupId>
<artifactId>azure-functions-java-library</artifactId>
<version>${azure.functions.java.library.version}</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.4.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-functions-maven-plugin</artifactId>
<version>${azure.functions.maven.plugin.version}</version>
<configuration>
<!-- function app name -->
<appName>${functionAppName}</appName>
<!-- function app resource group -->
<resourceGroup>${resourceGroup}</resourceGroup>
<!-- function app service plan name -->
<appServicePlanName>${appServicePlanName}</appServicePlanName>
<!-- function app region-->
<!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details#supported-regions for all valid values -->
<region>${appRegion}</region>
<!-- function pricingTier, default to be consumption if not specified -->
<!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details#supported-pricing-tiers for all valid values -->
<pricingTier>EP1</pricingTier>
<!-- Whether to disable application insights, default is false -->
<!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details for all valid configurations for application insights-->
<!-- <disableAppInsights></disableAppInsights> -->
<runtime>
<!-- runtime os, could be windows, linux or docker-->
<os>docker</os>
<image>[hub-user/]repo-name[:tag]</image>
<serverId></serverId>
<registryUrl></registryUrl>
</runtime>
<appSettings>
<property>
<name>FUNCTIONS_EXTENSION_VERSION</name>
<value>~3</value>
</property>
</appSettings>
</configuration>
<executions>
<execution>
<id>package-functions</id>
<goals>
<goal>package</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<overwrite>true</overwrite>
<outputDirectory>${stagingDirectory}</outputDirectory>
<resources>
<resource>
<directory>${project.basedir}</directory>
<includes>
<include>host.json</include>
<include>local.settings.json</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${stagingDirectory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
<includeScope>runtime</includeScope>
<excludeArtifactIds>azure-functions-java-library</excludeArtifactIds>
</configuration>
</execution>
</executions>
</plugin>
<!--Remove obj folder generated by .NET SDK in maven clean-->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<filesets>
<fileset>
<directory>obj</directory>
</fileset>
</filesets>
</configuration>
</plugin>
</plugins>
</build>
</project>

Просмотреть файл

@ -11,10 +11,18 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
#if(${javaVersion}=="11")
<java.version>11</java.version>
#else
<java.version>1.8</java.version>
#end
<azure.functions.maven.plugin.version>1.10.1</azure.functions.maven.plugin.version>
<azure.functions.java.library.version>1.4.2</azure.functions.java.library.version>
#if(${appName}=="$(artifactId)-$(timestamp)")
<functionAppName>${artifactId.toLowerCase()}-${package.getClass().forName("java.time.LocalDateTime").getMethod("now").invoke(null).format($package.Class.forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.Class).invoke(null, "yyyyMMddHHmmssSSS"))}</functionAppName>
#else
<functionAppName>${appName}</functionAppName>
#end
<stagingDirectory>${project.build.directory}/azure-functions/${functionAppName}</stagingDirectory>
</properties>
@ -69,19 +77,29 @@
<region>${appRegion}</region>
<!-- function pricingTier, default to be consumption if not specified -->
<!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details#supported-pricing-tiers for all valid values -->
#if(${docker}==true)
<pricingTier>EP1</pricingTier>
#else
<!-- <pricingTier></pricingTier> -->
#end
<!-- Whether to disable application insights, default is false -->
<!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details for all valid configurations for application insights-->
<!-- <disableAppInsights></disableAppInsights> -->
<runtime>
#if(${docker}==true)
<os>docker</os>
<image>[hub-user/]repo-name[:tag]</image>
<serverId></serverId>
<registryUrl></registryUrl>
#else
<!-- runtime os, could be windows, linux or docker-->
<os>windows</os>
<javaVersion>${javaVersion}</javaVersion>
<!-- for docker function, please set the following parameters -->
<!-- <image>[hub-user/]repo-name[:tag]</image> -->
<!-- <serverId></serverId> -->
<!-- <registryUrl></registryUrl> -->
#if(${javaVersion}=="11")
<javaVersion>11</javaVersion>
#else
<javaVersion>8</javaVersion>
#end
#end
</runtime>
<appSettings>
<property>

Просмотреть файл

@ -6,7 +6,7 @@
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-maven-archetypes</artifactId>
<version>1.37-SNAPSHOT</version>
<version>1.38-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Maven Archetypes for Azure</name>
<description>Maven Archetypes for Microsoft Azure services</description>