Last active
December 12, 2022 10:34
-
-
Save bric3/391d936566782c75f515fbd91f2d8525 to your computer and use it in GitHub Desktop.
Makes gradle go automatically go offline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Makes gradle go automatically offline. | |
* | |
* Store in $HOME/.gradle/init.d/checknetwork.init.gradle.kts | |
*/ | |
import java.io.IOException | |
import java.net.InetSocketAddress | |
import java.net.Socket | |
import java.net.SocketException | |
import java.net.UnknownHostException | |
import org.gradle.api.logging.Logging | |
apply<CheckNetwork>() | |
class CheckNetwork: Plugin<Gradle> { | |
private val logger = Logging.getLogger(CheckNetwork::class.java) | |
override fun apply(gradle: Gradle) { | |
if (gradle.startParameter.isOffline) { | |
// Gradle is run with `--offline` | |
return | |
} | |
var goOffline = false | |
val address = InetSocketAddress("google.com", 80) | |
try { | |
Socket().use { | |
it.connect(address, 3_000) | |
goOffline = !it.isConnected() | |
} | |
} catch(e: UnknownHostException) { | |
logger.info("[CheckNetwork] Unknown host: ${e.message}") | |
goOffline = true | |
} catch(e: SocketException) { | |
logger.info("[CheckNetwork] Connect failure: ${e.message}") | |
goOffline = true | |
} catch(e: IOException) { | |
logger.error("[CheckNetwork] io error", e) | |
goOffline = false | |
} | |
gradle.startParameter.setOffline(goOffline) | |
if (goOffline) { | |
logger.lifecycle("[CheckNetwork] Going offline (--offline)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Modified version of Schalk Cronjé he gave me in his tweet