7 Nisan 2022 Perşembe

Custom Task Örnekleri

Örnek
Elimizde şöyle bir xml vardı
<dependencyManagement>
  <dependencies>
    <dependency>
      ...
    </dependency>
  <dependencies>
<dependencyManagement>

<dependencyManagement>
  <dependencies>
    <dependency>
      ...
    </dependency>
  <dependencies>
<dependencyManagement>
Bu ikisini birleştirmek için şöyle yaptım. Aslında kod buradan geldi
import java.util.regex.Matcher
task fixPom { doLast { File file = new File("$buildDir/publications/maven_1/pom-default.xml") if (!file.exists()) { return; } println("Fixing pom for " + file.getPath()) def text = file.text def pattern = "(?s)(<dependencyManagement>.+?<dependencies>)(.+?)(</dependencies>.+?</dependencyManagement>)" Matcher matcher = text =~ pattern if (matcher.find()) { //Remove the first <dependencyManagement> tag text = text.replaceFirst(pattern, "") //Get all all <dependency> tags def firstDeps = matcher.group(2) //Get (<dependencyManagement>.+?<dependencies>)(.+?) part //add new dependencies and close the tag text = text.replaceFirst(pattern, '$1$2' + firstDeps + '$3') } file.write(text) } }
Bu yeni task'ı şöyle kullandım
generatePomPropertiesFile.dependsOn("fixPom")
Çünkü asemble için sıra şöyleydi
ompileJava
processResources
classes
createPropertiesFileForJar
generatePomFileForMaven_1Publication

fixPom //Burada araya girdim

generatePomPropertiesFile
writeManifestProperties
jar
createPropertiesFileForSourcesJar
sourcesJar
assemble




maven-publish Plugin - Artifactory veya Nexus'a Yükler

Giriş
Herhangi bir Maven repository sunucusuna jar ve pom dosyalarını yüklemek içindir. 

Tasks
Gradle menüsü altında şu menüleri görürüz
publishing
  publish : Artifactory veya Nexus'a Yükler
  publishToMavenLocal : Yerel Maven'a yükler

Örnek
Şöyle yaparız
plugins {
  id 'java-library'
  id 'maven-publish'
}
publications alanına
- earLibrary(MavenPublication)
- warLibrary(MavenPublication)
- mavenJava(MavenPublication)
gibi şeyler yazılır. Böylece neyi publish edeceğini anlar

repositories alanına
url ve authentication yazılır

Ear Dosyası
Örnek
Şöyle yaparız
plugins {
    id 'java-library'
    id 'maven-publish'
    id 'ear'
}

//Configure maven-publish plugin to publish ear file
publishing {

  publications {
    earLibrary(MavenPublication) {
      artifact ear
    }
  }
}

jar.enabled = false
War Dosyası
Örnek
Şöyle yaparız
plugins {
  id 'java-library'
  id 'maven-publish'
  id 'war'
}


//Configure maven-publish plugin to publish war file
publishing {

  publications {
    warLibrary(MavenPublication) {
      from components.web
    }
  }
}
jar.enabled = false
Jar Dosyası
Örnek
Şöyle yaparız
publishing {
  publications {

    mavenJava(MavenPublication) {
      artifactId = 'ms-commons'
      from components.java
      versionMapping {
        usage('java-api') {
          fromResolutionOf('runtimeClasspath')
        }
        usage('java-runtime') {
          fromResolutionResult()
        }
      }
      pom {
        name = 'MS Commons'
        description = 'A concise description of my library'
        url = 'http://www.example.com/library'
        licenses {
          license {
            name = 'The Apache License, Version 2.0'
            url =       'http://www.apache.org/licenses/LICENSE-2.0.txt'
          }
        }
        developers {
          developer {
            id = 'johnd'
            name = 'John Doe'
            email = 'john.doe@example.com'
          }
        }
      }
    }
  } //publications

  repositories {
    maven {
      name = "MyJfrog" //  optional target repository name
      url = "https://foo.jfrog.io/artifactory/my-repo"
      credentials {
        username = System.getenv('ARTIFACTORY_USERNAME')
        password = System.getenv('ARTIFACTORY_USER_PASSWORD')
      }
    }
  }
}
1. Seçenekler
publish
Jenkins ile şöyle yaparız
def shouldDeployToArtifactory() {
  return "${params.ARTIFACTORY_PUBLISH}" == "true"
}

if (shouldDeployToArtifactory()) {
  stage("Push to Artifactory") {
    echo "Publishing to Artifactory..."
    withCredentials([usernamePassword(
      credentialsId: 'ARTIFACTORY_PUBLISH',
      passwordVariable: 'ARTIFACTORY_PASSWORD', 
      usernameVariable: 'ARTIFACTORY_USER')
    ]) {
      runGradleSteps("publish")
    }
  }
}


2. Alanlar
repositories Alanı
Örnek
Şöyle yaparız
publishing {
  publications {
  }
  repositories {
    maven {
      name = "MyRepo" //  optional target repository name
      url = "http://my.org.server/repo/url"
      credentials {
        username = 'alice'
          password = 'my-password'
        }
      }
  }
}
Örnek
Şöyle yaparız
allprojects { 
  apply plugin: 'java' 
  apply plugin: 'maven-publish' 
  publishing { 
    publications { 
	     (MavenPublication) { 
	    from components.java 
	  } 
	} //publications 
	repositories { 
	  maven { 
	    url "s3://my.private.maven" 
		authentication { 
		  awsIm(AwsImAuthentication) 
		} //authentication 
	  } //maven" 
	} /repositories
  } //publishing 
} //allprojects
Çalıştırmak için şöyle yaparız
cp init-client.gradle build/client/init-client.gradle cd build/client && 
./gradlew --init-script init.gradle publish && 
cd -

1 Nisan 2022 Cuma

Zip Task

Giriş
Açıklaması şöyle
Sometimes we might need to replace one or more files in an existing archive file. The archive file could be a zip, jar, war or other archive. Without Gradle we would unpack the archive file, copy our new file into the destination directory of the unpacked archive and archive the directory again. To achieve this with Gradle we can simply create a single task of type Zip. To get the content of the original archive we can use the project.zipTree method. We leave out the file we want to replace and define the new file as replacement. As extra safeguard we can let the tsak fail if duplicate files are in the archive, because of our replacement.
archiveBaseName Alanı
Modul ismi ile aynıdır. Property olduğu için get() olarak kullanılmalıdır

Örnek
Şöyle yaparız. Böylece eğer module ismi foo ise "foo.zip" içinde "foo/scripts" diye bir dizin oluşur
//Create a new zip file
task scriptsZip(type: Zip) {
  archiveAppendix = 'scripts'
  from 'scripts'
  into "${archiveBaseName.get()}/scripts"
}
assemble.dependsOn('scriptsZip')
Örnek
Açıklaması şöyle
The following code shows an example of a task to replace a README file in an archive sample.zip using Groovy and Kotlin DSL.
Şöyle yaparız
// Register new task replaceZip of type org.gradle.api.tasks.bundling.Zip.
tasks.register("replaceZip", Zip) {
  archiveBaseName = "new-sample"
  destinationDirectory = file("${buildDir}/archives")

  // Include the content of the original archive.
  from(zipTree("${buildDir}/archives/sample.zip")) {
    // But leave out the file we want to replace.
    exclude("README")
  }

  // Add files with same name to replace.
  from("src/new-archive") {
    include("README")
  }

  // As archives allow duplicate file names we want to fail
  // the build when that happens, because we want to replace
  // an existing file.
  duplicatesStrategy = "FAIL"
}
archiveFileName Alanı
Zip dosyasının ismini belirtir
Örnek
resources dizinini zip'lemek için şöyle yaparız
task packageDistribution(type: Zip) {
  archiveFileName = "vitesstestservertemplate.zip"
  destinationDirectory = file("$buildDir/libs")
  from "$buildDir/resources/main"

}

assemble.dependsOn packageDistribution
archiveAppendix Alanı
"module ismi + archiveAppendix " şeklinde yeni bir zip dosyası oluşturur. Açıklaması şöyle
The appendix part of the archive name, if any.
Örnek
Şöyle yaparız
task scriptsZip(type: Zip) {
  archiveAppendix = 'scripts'
  from 'scripts'
  into "${archiveBaseName}/scripts"
}
assemble.dependsOn('scriptsZip')


Copy Task

Giriş
Açıklaması şöyle
The Copy task is a task type provided by core Gradle. At execution, a copy task copies files into a destination directory from one or more sources, optionally transforming files as it copies. You tell the copy task where to get files, where to put them, and how to filter them through a configuration block. 
from ve into Alanları
Örnek
Şöyle yaparız
task copyPoems(type: Copy) {
  from 'text-files'
  into 'build/poems'
}
duplicatesStrategy Alanı
Açıklaması şöyle
EXCLUDE
Do not allow duplicates by ignoring subsequent items to be created at the same path.
FAIL
Throw a DuplicateFileCopyingException when subsequent items are to be created at the same path.
INCLUDE
Do not attempt to prevent duplicates.
INHERIT
The default strategy, which is to inherit the strategy from the parent copy spec, if any, or INCLUDE if the copy spec has no parent.
WARN
Do not attempt to prevent duplicates, but log a warning message when multiple items are to be created at the same path.
Açıklaması şöyle. Yani Gradle 7'den itibaren duplicatesStrategy açıkça atanmalı
If there is already rebel.xml present among the source files then the behavior will depend on Gradle version. Versions below 7.0 do not require any additional configuration and the generated rebel.xml will be included to the build result by default. Since Gradle 7.0, duplicatesStrategy must be configured in build.gradle in order to prevent a duplicate entry error at build time:
...
The value 'include' will force the generated rebel.xml to be copied to the build result. Contrariwise, 'exclude' will favor rebel.xml that is present among the source files.
Örnek
Şöyle yaparız
tasks.withType<Jar>() {

  duplicatesStrategy = DuplicatesStrategy.EXCLUDE

  manifest {
    attributes["Main-Class"] = "MainKt"
  }

  configurations["compileClasspath"].forEach { file: File ->
    from(zipTree(file.absoluteFile))
  }
}

Gradle Daemon Nedir?

Giriş Açıklaması  şöyle . Gradle Daemon arka planda çalışır. Çünkü Gradle'ı ayağa kaldırmak ve ilklendirmek çok uzun sürüyor.  Gradle ru...