Skip to content

Commit

Permalink
fix(build): update build configurations
Browse files Browse the repository at this point in the history
- Generate missing api docs.
- Moved custom tasks to buildSrc.
  • Loading branch information
puneetbehl committed Apr 17, 2024
1 parent 0f52af8 commit e3bbf6b
Show file tree
Hide file tree
Showing 2 changed files with 204 additions and 31 deletions.
74 changes: 43 additions & 31 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,14 @@ asciidoctor {
}

options template_dirs: ["${projectDir}/src/docs/templates"]

attributes 'experimental': 'true',
'compat-mode': 'true',
'icons': 'font',
'linkcss': 'true',
'docinfo1': '',
'toc': 'left',
'version': project.version,
'sourcedir': "$checkOutDir/grails-src"
'sourcedir': grailsHome
}


Expand All @@ -80,27 +79,17 @@ tasks.withType(org.gradle.api.tasks.javadoc.Groovydoc) {

task migrate(type: grails.doc.gradle.MigrateLegacyDocs)

tasks.register("docs") {
dependsOn "publishPdf"
finalizedBy "createReleasesDropdown"
}

tasks.register("dist", Zip) {
dependsOn "docs"
from outputDir
}

tasks.register("createReleasesDropdown", grails.doc.dropdown.CreateReleasesDropdownTask) {
mustRunAfter "dist"
slug = githubSlug as String
version = projectVersion
guide = file("${buildDir.absolutePath}/docs/guide/single.html")
index = file("${buildDir.absolutePath}/docs/index.html")
mustRunAfter "dist"
onlyIf {
new File("${buildDir.absolutePath}/docs/guide/single.html").exists() &&
new File("${buildDir.absolutePath}/docs/index.html").exists()
}
tasks.register("createReleaseDropdown", grails.doc.AddReleaseDropDown) {
dependsOn "publishGuide", "publishPdf"
inputFiles = [file("${buildDir.absolutePath}/manual/guide/single.html"), file("${buildDir.absolutePath}/manual/index.html")]

inputs.files(inputFiles)
outputs.dir(outputDir)
}

tasks.register('fetchGrailsSource', grails.doc.FetchGrailsSourceTask) {
Expand All @@ -110,24 +99,25 @@ tasks.register('fetchGrailsSource', grails.doc.FetchGrailsSourceTask) {
tasks.register("editProjectArtificat", Exec) {
onlyIf { project.hasProperty("editGrailsVersion") }
dependsOn 'fetchGrailsSource'

executable Os.isFamily(Os.FAMILY_WINDOWS) ? "cmd" : "bash"
args Os.isFamily(Os.FAMILY_WINDOWS) ? "/c" : "-c", "sed -i 's/^projectVersion.*\$/projectVersion=$version/' ${explicitGrailsHome ?: "${checkOutDir}/grails-src"}/gradle.properties"
args Os.isFamily(Os.FAMILY_WINDOWS) ? "/c" : "-c", "sed -i 's/^projectVersion.*\$/projectVersion=$version/' ${grailsHome}/gradle.properties"
}

tasks.register("apiDocs", Exec) {
onlyIf { !System.getProperty("disable.groovydocs") }
dependsOn 'fetchGrailsSource'
finalizedBy "copyApiDocs"

inputs.files(fileTree(grailsHome) {
exclude '**/*.lock'
exclude '**/.gradle'
})
outputs.dir(grailsHome + "/doc")

String command = Os.isFamily(Os.FAMILY_WINDOWS) ? "gradlew.bat" : "./gradlew"
commandLine = [command, "groovydoc", '--info', '--stacktrace']
commandLine = [command, "groovydoc", "--quiet", "--no-daemon", "--console=plain", "--project-dir=${grailsHome}"]
workingDir = grailsHome
environment "GRADLE_OPTS", "-Xmx2048m -Xms256m -XX:MaxPermSize=512m -XX:+CMSClassUnloadingEnabled -XX:+HeapDumpOnOutOfMemoryError"
}

tasks.register('copyApiDocs', Copy) {
dependsOn 'apiDocs'
from "${project.grailsHome}/doc/api"
into "${outputDir}/api"
environment "GRADLE_OPTS", "-Xmx2048m -Xms256m -XX:+CMSClassUnloadingEnabled -XX:+HeapDumpOnOutOfMemoryError"
}

tasks.register('downloadPom', grails.doc.DownloadPomTask) {
Expand All @@ -140,8 +130,8 @@ tasks.register('extractPomVersions', grails.doc.ExtractPomVersionsTask) {
}

tasks.register('publishGuide', grails.doc.gradle.PublishGuide) {
dependsOn(['apiDocs', 'copyApiDocs', 'extractPomVersions'])
targetDir = project.layout.buildDirectory.dir("docs").get().asFile
dependsOn(['apiDocs', 'extractPomVersions'])
targetDir = project.layout.buildDirectory.dir("manual").get().asFile

doFirst {
def searchDirs = project.file(project.grailsHome).listFiles().findAll {
Expand Down Expand Up @@ -185,9 +175,31 @@ tasks.register('publishGuide', grails.doc.gradle.PublishGuide) {

tasks.register('publishPdf', grails.doc.gradle.PublishPdf) {
dependsOn 'publishGuide'
outputDirectory = project.layout.buildDirectory.dir("docs").get().asFile
outputDirectory = new File(project.buildDir, "/manual")
}

tasks.register("docs", Copy) {
dependsOn "apiDocs", "publishGuide", "createReleaseDropdown", "publishPdf"

def manualDocsDir = publishGuide.targetDir
def apiDocsDir = file(grailsHome + '/doc')
def modifiedPagesDir = createReleaseDropdown.outputDir
def mergedDocsDir = project.layout.buildDirectory.dir('docs')

inputs.dir manualDocsDir
inputs.dir apiDocsDir
inputs.dir modifiedPagesDir
inputs.dir project.layout.projectDirectory.dir("src")

outputs.dir mergedDocsDir

from manualDocsDir, apiDocsDir, modifiedPagesDir
into mergedDocsDir

duplicatesStrategy = DuplicatesStrategy.INCLUDE
}


artifacts {
archives dist
}
161 changes: 161 additions & 0 deletions buildSrc/src/main/groovy/grails/doc/AddReleaseDropDown.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* Copyright 2024 The Unity Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package grails.doc

import grails.doc.dropdown.SoftwareVersion
import groovy.json.JsonSlurper
import groovy.transform.CompileDynamic
import groovy.transform.CompileStatic
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.*

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.stream.Collectors

/**
* Task to add a release dropdown to the documentation
*
* @author Puneet Behl
* @since 6.2.1
*/
@CompileStatic
class AddReleaseDropDown extends DefaultTask {

private static final String GRAILS_DOC_BASE_URL = "https://docs.grails.org"
private static final String GITHUB_API_BASE_URL = "https://api.github.com"

@Optional
@Input
String slug = "grails/grails-doc"

@Optional
@Input
String docsDirName = "manual"

@Optional
@Input
String version = project.version

@InputFiles
List<File> inputFiles = []

@OutputDirectory
String outputDir = project.layout.buildDirectory.dir("modified-pages").get().asFile.absolutePath

/**
* Add the release dropdown to the documentation
*/
@TaskAction
void addReleaseDropDown() {
final String versionHtml = "<p><strong>Version:</strong> ${version}</p>"
inputFiles.forEach { inputFile ->
final String absolutePath = inputFile.absolutePath
String page = absolutePath.substring(absolutePath.lastIndexOf(docsDirName) + docsDirName.size(), absolutePath.size())
String selectHtml = select(options(version, page))
final Path modifiedPage = Paths.get(outputDir + page)
Files.createDirectories(modifiedPage.getParent())
final String versionWithSelectHtml = "<p><strong>Version:</strong>&nbsp;<span style='width:100px;display:inline-block;'>${selectHtml}</span></p>"
modifiedPage.toFile().text = inputFile.text.replace(versionHtml, versionWithSelectHtml)
}
}

/**
* Generate the options for the select tag.
*
* @param version The current version of the documentation
* @param page The page to add the dropdown to
* @return The list of options for the select tag
*/
private List<String> options(String version, String page) {
List<String> options = []
final String snapshotHref = GRAILS_DOC_BASE_URL + "/snapshot" + page
options << option(snapshotHref, "SNAPSHOT", version.endsWith("-SNAPSHOT"))

final Object result = listRepoTags("grails/grails-core")
parseSoftwareVersions(result)
.forEach { softwareVersion ->
final String versionName = softwareVersion.versionText
final String href = GRAILS_DOC_BASE_URL + "/" + versionName + page
options << option(href, versionName, version == versionName)
}
options
}

/**
* List all tags in the repository using the GitHub API.
*
* @param repoSlug The slug of the repository. e.g. grails/grails-core
* @return The list of tags in the repository
*/
private Object listRepoTags(String repoSlug) {
final String json = new URL(GITHUB_API_BASE_URL + "/repos/" + repoSlug + "/tags").text
def result = new JsonSlurper().parseText(json)
result
}


/**
* Generate the select tag
*
* @param options The List of options tags for the select tag
* @return The select tag with the options
*/
private String select(List<String> options) {
String selectHtml = "<select onChange='window.document.location.href=this.options[this.selectedIndex].value;'>"
options.each { option ->
selectHtml += option
}
selectHtml += '</select>'
selectHtml
}

/**
* Generate the option tag
*
* @param value The URL to navigate to
* @param text The version to display
* @param selected Whether the option is selected
*
* @return The option tag
*/
private String option(String value, String text, boolean selected = false) {
if (selected) {
return "<option selected='selected' value='${value}'>${text}</option>"
} else {
return "<option value='${value}'>${text}</option>"
}
}

/**
* Parse the software versions from the resultant JSON
*
* @param result List of all tags in the repository.
* @return The list of software versions
*/
@CompileDynamic
private List<SoftwareVersion> parseSoftwareVersions(def result) {
result.stream()
.filter(v -> v.name.startsWith('v'))
.map(v -> v.name.replace('v', ''))
.map(SoftwareVersion::build)
.sorted()
.distinct()
.collect(Collectors.toList())
.reverse()
}
}

0 comments on commit e3bbf6b

Please sign in to comment.