Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gradle maven command macro #22

Open
wants to merge 8 commits into
base: 0.0.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion gdkexamples/asciidoc/commons/test-application.adoc
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
To run the tests, use the following command:

++++
<div id="tabs-doc3">
<ul>
<li class="tabs-gradle"><a href="#gradle">Gradle</a></li>
Expand All @@ -10,4 +12,5 @@ To run the tests, use the following command:
<div id="maven">
<pre><code class="language-bash">./mvnw test</code></pre>
</div>
</div>
</div>
++++
10 changes: 8 additions & 2 deletions gdkexamples/guides/micronaut-data-jdbc-repository/metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,18 @@
"publicationDate": "2024-11-19",
"zipIncludes": [
"create_resources.sh",
"settings.sh"
"settings.sh",
"test_app.sh"
],
"apps": [
{
"name": "default",
"features": []
"features": [
"graalvm"
],
"services": [
"database"
]
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ Create an application using the GDK Launcher.

Alternatively, use the link:/gdk/get-started/using-gdk-cli/[GDK CLI] as follows:

create-app:default[]

If you enable sample code generation, the GDK Launcher creates the main controller, repository interface, entity, service classes, and tests for you.
In the _micronaut-cli.yml_ file you can find all features packaged with the application:

Expand Down Expand Up @@ -96,7 +98,7 @@ include::asciidoc/commons/graalvm-prereq.adoc[]

To generate a native executable, use the following command:

// TODO: command to build the native executable
gradle-maven-command:[gradle=./gradlew nativeCompile,maven=./mvnw package -Dpackaging=native-image]

Before running this native executable, you need to start and then connect to a MySQL database.

Expand All @@ -114,20 +116,20 @@ include::asciidoc/commons/connect-mysql-db.adoc[]

Run the application from the native executable which starts the application on port 8080:

gradle-maven-command:[gradle=build/native/nativeCompile/db-demo,maven=target/db-demo]

Save one genre and your `genre` database table will now contain an entry:

[source,bash]
----
curl -X "POST" "http://localhost:8080/genres" \
-H 'Content-Type: application/json; charset=utf-8' \
-d '{ "name": "music" }'
include::{guidesourcedir}/test_app.sh[tag=add-genre]
----

Access the `genres` endpoint exposed by the application:

[source,bash]
----
curl localhost:8080/genres/list
include::{guidesourcedir}/test_app.sh[tag=get-genres]
----

When you run the application, Micronaut Test Resources do not start a MySQL container because you have provided values for `datasources.default.*` properties
Expand Down
67 changes: 67 additions & 0 deletions gdkexamples/guides/micronaut-data-jdbc-repository/test_app.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/bin/bash
. ./common.sh
if [ -f resources.sh ]
then
. ./resources.sh
fi

echo 'Waiting for resources to be created...'

check_app_running_or_exit 200

echo 'Test started...'

EXIT_VALUE=0

echo "Testing POST request..."

#tag::add-genre[]
TEST_RES=$(curl -X "POST" "http://localhost:8080/genres" \
-H 'Content-Type: application/json; charset=utf-8' \
-d $'{ "name": "music" }')

echo "Result: $TEST_RES"
#end::add-genre[]

ITEM_ID=$(jq -r '.id' <<< "$TEST_RES")
ITEM_NAME=$(jq -r '.name' <<< "$TEST_RES")

if [[ $ITEM_NAME != "music" ]]; then
echo -e "${RED}Failed${RESET}"
EXIT_VALUE=1
else
echo -e "${GREEN}Ok${RESET}"
fi

echo "Test GET request..."

#tag::get-genres[]
TEST_RES=$(curl -s localhost:8080/genres/list | jq -r ".[] | select(.id == $ITEM_ID) | .name")

echo "Result: $TEST_RES"
#end::get-genres[]

if [[ $TEST_RES != "music" ]]; then
echo -e "${RED}Failed${RESET}"
EXIT_VALUE=1
else
echo -e "${GREEN}Ok${RESET}"
fi


echo "Test DELETE request..."

curl -s -X "DELETE" "http://localhost:8080/genres/$ITEM_ID"

TEST_RES=$(curl -s localhost:8080/genres/list | jq -r ".[] | select(.id == $ITEM_ID) | .name")

echo "Result: $TEST_RES"

if [[ $TEST_RES == "music" ]]; then
echo -e "${RED}Failed${RESET}"
EXIT_VALUE=1
else
echo -e "${GREEN}Ok${RESET}"
fi

reportResultAndExit $EXIT_VALUE
3 changes: 3 additions & 0 deletions guides-cli/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@ repositories {
dependencies {
annotationProcessor("info.picocli:picocli-codegen")
annotationProcessor("io.micronaut.serde:micronaut-serde-processor")
annotationProcessor(mnJsonSchema.micronaut.json.schema.processor)
implementation("info.picocli:picocli")
implementation(projects.guides)
implementation("io.micronaut.picocli:micronaut-picocli")
implementation("io.micronaut.serde:micronaut-serde-jackson")
implementation(mnJsonSchema.json.schema.validator)
compileOnly(mnJsonSchema.micronaut.json.schema.annotations)
runtimeOnly("ch.qos.logback:logback-classic")
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package io.micronaut.guides.cli;

import io.micronaut.core.io.ResourceLoader;
import io.micronaut.guides.core.*;
import io.micronaut.guides.core.asciidoc.AsciidocMacro;
import jakarta.inject.Singleton;

import java.util.Optional;

import static io.micronaut.guides.core.MacroUtils.findMacroLines;

@Singleton
public class CreateAppMacro extends GradleMavenTabs implements MacroSubstitution {

public static final String MACRO = "create-app";

private final GuidesConfiguration guidesConfiguration;

protected CreateAppMacro(ResourceLoader resourceLoader, GuidesTemplatesConfiguration guidesTemplatesConfiguration, GuidesConfiguration guidesConfiguration) {
super(resourceLoader, guidesTemplatesConfiguration);
this.guidesConfiguration = guidesConfiguration;
}

@Override
public String substitute(String str, Guide guide, GuidesOption option) {
for (String line : findMacroLines(str, MACRO)) {
Optional<AsciidocMacro> asciidocMacroOptional = AsciidocMacro.of(MACRO, line);
if (asciidocMacroOptional.isEmpty()) {
continue;
}
String target = asciidocMacroOptional.get().target();
GdkApp app = (GdkApp) guide.apps().
stream()
.filter(a -> a.name().equals(target))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("App not found: " + target));
String template = new StringBuilder()
.append("<code class=\"language-bash hljs\" data-highlighted=\"yes\" style=\"white-space: pre-line;\">")
.append("gdk create-app ")
.append(guidesConfiguration.getPackageName())
.append(".")
.append(app.name())
.append((" \\\n"))
.append((" --services="))
.append(String.join(",", app.services()))
.append((" \\\n"))
.append(" --features=")
.append(String.join(",", app.features()))
.append((" \\\n"))
.append(" --lang=")
.append(option.getLanguage().name().toLowerCase())
.append((" \\\n"))
.append(" --build={buildTool}\n")
.append("</code>")
.toString();


String gradle = template.replace("{buildTool}", "gradle");
String maven = template.replace("{buildTool}", "maven");
str = str.replace(line, "++++\n" + gradleMavenTabsHtml.replace("{gradle}", gradle).replace("{maven}", maven) + "\n++++\n");
}
return str;
}
}
51 changes: 51 additions & 0 deletions guides-cli/src/main/java/io/micronaut/guides/cli/GdkApp.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package io.micronaut.guides.cli;

import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.guides.core.App;
import io.micronaut.jsonschema.JsonSchema;
import io.micronaut.serde.annotation.Serdeable;
import io.micronaut.starter.api.TestFramework;
import io.micronaut.starter.application.ApplicationType;

import java.util.ArrayList;
import java.util.List;

@Serdeable
@JsonSchema
public class GdkApp extends App {
@JsonPropertyDescription("The GDK Starter services' name that the app requires")
@Nullable
private List<String> services;

/**
* Represents the app metadata.
*
* @param name The app's name. For single application guides, the application needs to be named default
* @param packageName The app's package name. If you don't specify, the package name example.micronaut is used
* @param applicationType The app type. If you don't specify, default is used
* @param framework The app's framework. Default is Micronaut but Spring Boot is also supported
* @param features The Micronaut Starter features' name that the app requires
* @param services The GDK Starter services' name that the app requires
* @param invisibleFeatures The app's invisible features
* @param kotlinFeatures The app's Kotlin features
* @param javaFeatures The app's Java features
* @param groovyFeatures The app's Groovy features
* @param testFramework The app's test framework
* @param excludeTest The tests that should not be run
* @param excludeSource The source files that should not be included
* @param validateLicense To enable Spotless code check
*/
public GdkApp(String name, String packageName, ApplicationType applicationType, String framework, List<String> features, List<String> services, List<String> invisibleFeatures, List<String> kotlinFeatures, List<String> javaFeatures, List<String> groovyFeatures, TestFramework testFramework, List<String> excludeTest, List<String> excludeSource, Boolean validateLicense) {
super(name, packageName, applicationType, framework, features, invisibleFeatures, kotlinFeatures, javaFeatures, groovyFeatures, testFramework, excludeTest, excludeSource, validateLicense);
this.services = services != null ? services : new ArrayList<>();
}

public @Nullable List<String> services() {
return services;
}

public void setServices(@Nullable List<String> services) {
this.services = services;
}
}
84 changes: 84 additions & 0 deletions guides-cli/src/main/java/io/micronaut/guides/cli/GdkGuide.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package io.micronaut.guides.cli;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.util.StringUtils;
import io.micronaut.guides.core.App;
import io.micronaut.guides.core.Cloud;
import io.micronaut.guides.core.Guide;
import io.micronaut.jsonschema.JsonSchema;
import io.micronaut.serde.annotation.Serdeable;
import io.micronaut.starter.api.TestFramework;
import io.micronaut.starter.options.BuildTool;
import io.micronaut.starter.options.Language;
import jakarta.validation.constraints.NotEmpty;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Serdeable
@JsonSchema
public class GdkGuide extends Guide {
@JsonPropertyDescription("Set it to true to not generate code samples for the guide")
@JsonProperty(defaultValue = StringUtils.FALSE)
@Nullable
private Boolean skipCodeSamples;

@JsonPropertyDescription("Applications created for the guide")
@NotEmpty
@NonNull
private List<GdkApp> apps;

/**
* Represents a guide metadata.
*
* @param title The guide's title
* @param intro The guide introduction
* @param authors The guide's authors
* @param categories The guide's categories
* @param publicationDate The guide publication date. It should follow the format YYYY-MM-DD
* @param minimumJavaVersion If the guide needs a minimum Java version, define it here
* @param maximumJavaVersion If the guide needs a maximum Java version, define it here
* @param cloud The acronym for the cloud service provider of the guide. For example, OCI for Oracle Cloud Infrastructure
* @param skipGradleTests Set it to true to skip running the tests for the Gradle applications for the guide
* @param skipMavenTests Set it to true to skip running the tests for the Maven applications for the guide
* @param asciidoctor The guide asciidoc file. If not specified, the guide slug followed by the .adoc suffix is used
* @param languages The guide supported languages
* @param tags List of tags added to the guide. features are added automatically as tags. No need to repeat them here
* @param buildTools By default the code in the guide is generated for Gradle and Maven. If a guide is specific only for a build tool, define it here
* @param testFramework The guide's test framework. By default Java and Kotlin applications are tested with JUnit5 and Groovy applications with Spock
* @param zipIncludes List of additional files with a relative path to include in the generated zip file for the guide
* @param slug The guide's slug. If not specified, the guides folder is used
* @param publish Whether the guide should be published, it defaults to true. You can set it to false for draft or base guides
* @param base Defaults to null; if set, indicates directory name of the base guide to copy before copying the current one
* @param env The guide's environment variables
* @param apps Applications created for the guide
* @param skipCodeSamples Set it to true to not generate code samples for the guide
*/
public GdkGuide(String title, String intro, List<String> authors, List<String> categories, LocalDate publicationDate, Integer minimumJavaVersion, Integer maximumJavaVersion, Cloud cloud, Boolean skipGradleTests, Boolean skipMavenTests, String asciidoctor, List<Language> languages, List<String> tags, List<BuildTool> buildTools, TestFramework testFramework, List<String> zipIncludes, String slug, Boolean publish, String base, Map<String, String> env, List<GdkApp> apps, Boolean skipCodeSamples) {
super(title, intro, authors, categories, publicationDate, minimumJavaVersion, maximumJavaVersion, cloud, skipGradleTests, skipMavenTests, asciidoctor, languages, tags, buildTools, testFramework, zipIncludes, slug, publish, base, env, null);
this.skipCodeSamples = skipCodeSamples;
this.apps = apps;
}

public @Nullable Boolean skipCodeSamples() {
return skipCodeSamples;
}

public void setSkipCodeSamples(@Nullable Boolean skipCodeSamples) {
this.skipCodeSamples = skipCodeSamples;
}

@Override
public @NonNull List<GdkApp> apps() {
return apps;
}

@Override
public void setApps(@NotEmpty @NonNull List<? extends App> apps) {
this.apps = (List<GdkApp>) apps;
}
}
Loading
Loading