buildscript {
  repositories { 
    jcenter()
    mavenCentral()
    maven {
        url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "ru.vyarus:gradle-animalsniffer-plugin:1.2.0"
    classpath "gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.13.1"
    classpath "me.champeau.gradle:jmh-gradle-plugin:0.4.5"
    classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3"
    classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.5.2"
  }
}

group = "io.reactivex.rxjava2"
ext.githubProjectName = "rxjava"

version = project.properties["release.version"]

def releaseTag = System.getenv("TRAVIS_TAG");
if (releaseTag != null && !releaseTag.isEmpty()) {
    if (releaseTag.startsWith("v")) {
        releaseTag = releaseTag.substring(1);
    }
    version = releaseTag;
    project.properties.put("release.version", releaseTag);

    println("Releasing with version " + version);
}

description = "RxJava: Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM."

apply plugin: "java-library"
apply plugin: "checkstyle"
apply plugin: "jacoco"
apply plugin: "ru.vyarus.animalsniffer"
apply plugin: "maven"
apply plugin: "osgi"
apply plugin: "me.champeau.gradle.jmh"
apply plugin: "com.github.hierynomus.license"
apply plugin: "com.jfrog.bintray"
apply plugin: "com.jfrog.artifactory"
apply plugin: "eclipse"

sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6

// Dependency versions
// ---------------------------------------

def junitVersion = "4.12"
def reactiveStreamsVersion = "1.0.2"
def mockitoVersion = "2.1.0"
def jmhLibVersion = "1.20"
def testNgVersion = "6.11"
def guavaVersion = "24.0-jre"
def jacocoVersion = "0.8.0"
// --------------------------------------

repositories {
  mavenCentral()
}

dependencies {
    signature "org.codehaus.mojo.signature:java16:1.1@signature"

    api "org.reactivestreams:reactive-streams:$reactiveStreamsVersion"
    jmh "org.reactivestreams:reactive-streams:$reactiveStreamsVersion"

    testImplementation "junit:junit:$junitVersion"
    testImplementation "org.mockito:mockito-core:$mockitoVersion"

    testImplementation "org.reactivestreams:reactive-streams-tck:$reactiveStreamsVersion"
    testImplementation "org.testng:testng:$testNgVersion"
    testImplementation "com.google.guava:guava:$guavaVersion"
}

javadoc {
    failOnError = false
    exclude "**/internal/**"
    exclude "**/test/**"
    exclude "**/perf/**"
    exclude "**/jmh/**"
    options {
        windowTitle = "RxJava Javadoc ${project.version}"
    }
    // Clear the following options to make the docs consistent with the old format
    options.addStringOption("top").value = ""
    options.addStringOption("doctitle").value = ""
    options.addStringOption("header").value = ""

    options.links(
        "https://docs.oracle.com/javase/7/docs/api/",
        "http://www.reactive-streams.org/reactive-streams-${reactiveStreamsVersion}-javadoc/"
    )

    if (JavaVersion.current().isJava7()) {
        // "./gradle/stylesheet.css" only supports Java 7
        options.addStringOption("stylesheetfile", rootProject.file("./gradle/stylesheet.css").toString())
    }
}

animalsniffer {
    annotation = "io.reactivex.internal.util.SuppressAnimalSniffer"
}

task sourcesJar(type: Jar, dependsOn: classes) {
    classifier = "sources"
    from sourceSets.main.allSource
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = "javadoc"
    from javadoc.destinationDir
}

artifacts {
    archives jar
    archives sourcesJar
    archives javadocJar
}

jar {
    manifest {
        name = "rxjava"
        instruction "Bundle-Vendor", "RxJava Contributors"
        instruction "Bundle-DocURL", "https://github.com/ReactiveX/RxJava"
        instruction "Import-Package", "!org.junit,!junit.framework,!org.mockito.*,!org.testng.*,*"
        instruction "Eclipse-ExtensibleAPI", "true"
        instruction "Automatic-Module-Name", "io.reactivex.rxjava2"
    }
}

license {
    header rootProject.file("HEADER")
    ext.year = Calendar.getInstance().get(Calendar.YEAR)
    skipExistingHeaders true
    ignoreFailures true
    excludes(["**/*.md", "**/*.txt"])
}

apply plugin: "maven-publish"

install {
    repositories.mavenInstaller.pom.project {
        name "RxJava"
        description "Reactive Extensions for Java"
        url "https://github.com/ReactiveX/RxJava"
        licenses {
            license {
                name "The Apache Software License, Version 2.0"
                url "http://www.apache.org/licenses/LICENSE-2.0.txt"
                distribution "repo"
            }
        }
        developers {
            developer {
                id "akarnokd"
                name "David Karnok"
                email "akarnokd@gmail.com"
            }
        }
        scm {
            connection "scm:git:git@github.com:ReactiveX/RxJava.git"
            url "scm:git:git@github.com:ReactiveX/RxJava.git"
            developerConnection "scm:git:git@github.com:ReactiveX/RxJava.git"
        }
        issueManagement {
            system "github"
            url "https://github.com/ReactiveX/RxJava/issues"
        }
    }
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
            artifact (sourcesJar) { 
                classifier = "sources"
            }
        }
    }
}

// Reactive-Streams as compile dependency
publishing.publications.all {
  pom.withXml {
    asNode().dependencies."*".findAll() {
      it.scope.text() == "runtime" && project.configurations.compile.allDependencies.find { dep ->
        dep.name == it.artifactId.text()
      }
    }.each { it.scope*.value = "compile"}
  }
}

jmh {
    jmhVersion = jmhLibVersion
    humanOutputFile = null
    includeTests = false
    jvmArgs = ["-Djmh.ignoreLock=true"]
    jvmArgsAppend = ["-Djmh.separateClasspathJAR=true"]

    if (project.hasProperty("jmh")) {
        include = ".*" + project.jmh + ".*"
        println("JMH: " + include);
    }

}

plugins.withType(EclipsePlugin) {
    project.eclipse.classpath.plusConfigurations += [ configurations.jmh ]
}

test {
    
    testLogging  {
        // showing skipped occasionally should prevent CI timeout due to lack of standard output
        events=["skipped", "failed"] // "started", "passed"
        // showStandardStreams = true
        exceptionFormat="full"

        debug.events = ["skipped", "failed"]
        debug.exceptionFormat="full"

        info.events = ["failed", "skipped"]
        info.exceptionFormat="full"
        
        warn.events = ["failed", "skipped"]
        warn.exceptionFormat="full"
    }

    maxHeapSize = "1200m"

    if (System.getenv("CI") == null) {
        maxParallelForks = Runtime.runtime.availableProcessors().intdiv(2) ?: 1
    }
}

task testng(type: Test) { 
     useTestNG()
     testLogging  {
        events=["skipped", "failed"]
        exceptionFormat="full"

        debug.events = ["skipped", "failed"]
        debug.exceptionFormat="full"

        info.events = ["failed", "skipped"]
        info.exceptionFormat="full"
        
        warn.events = ["failed", "skipped"]
        warn.exceptionFormat="full"
     }
} 

check.dependsOn testng 

jacoco {
    toolVersion = jacocoVersion // See http://www.eclemma.org/jacoco/.
}

task GCandMem(dependsOn: "check") doLast {
    print("Memory usage before: ")
    println(java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1024.0 / 1024.0)
    System.gc()
    Thread.sleep(200)
    print("Memory usage: ")
    println(java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1024.0 / 1024.0)
}

task GCandMem2(dependsOn: "test") doLast {
    print("Memory usage before: ")
    println(java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1024.0 / 1024.0)
    System.gc()
    Thread.sleep(200)
    print("Memory usage: ")
    println(java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1024.0 / 1024.0)
}

testng.dependsOn GCandMem2

jacocoTestReport {
    reports {
        xml.enabled = true
        html.enabled = true
    }
    
    afterEvaluate {
        classDirectories = files(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: ["io/reactivex/tck/**"])
        })
    }
}

jacocoTestReport.dependsOn GCandMem

build.dependsOn jacocoTestReport

checkstyle {
    configFile file("checkstyle.xml")
    ignoreFailures = true
    toolVersion ="6.19" 
}

if (rootProject.hasProperty("releaseMode")) {

  if ("branch".equals(rootProject.releaseMode)) {
    // From https://github.com/ReactiveX/RxAndroid/blob/2.x/rxandroid/build.gradle#L94
  
    println("ReleaseMode: " + rootProject.releaseMode);
    artifactory {
        contextUrl = "https://oss.jfrog.org"
    
        publish {
            repository {
                repoKey = "oss-snapshot-local"
    
                username = rootProject.bintrayUser
                password = rootProject.bintrayKey
            }
    
            defaults {
                publishConfigs("archives")
            }
        }
    }
    
    build.finalizedBy(artifactoryPublish)
  }

   if ("full".equals(rootProject.releaseMode)) {
      // based on https://github.com/bintray/gradle-bintray-plugin
      def rver = version;

      println("ReleaseMode: " + rootProject.releaseMode + " version " + rver);

      bintray {
         user = rootProject.bintrayUser
         key = rootProject.bintrayKey
         configurations = ["archives"]
         publish = true
         pkg {
           repo = "RxJava"
           name = "RxJava"
           userOrg = "reactivex"
           labels = ["rxjava", "reactivex"]
           licenses = ["Apache-2.0"]
           vcsUrl = "https://github.com/ReactiveX/RxJava.git"
           version {
             name = rver
             gpg {
                sign = true
             }
             mavenCentralSync {
               sync = true 
               user = rootProject.sonatypeUsername
               password = rootProject.sonatypePassword
               close = "1"
             }
           }
         }
      }
      
      build.finalizedBy(bintrayUpload)
   }
}

apply from: file("gradle/javadoc_cleanup.gradle")
