Skip to content

Instantly share code, notes, and snippets.

@bric3
Last active December 12, 2022 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bric3/391d936566782c75f515fbd91f2d8525 to your computer and use it in GitHub Desktop.
Save bric3/391d936566782c75f515fbd91f2d8525 to your computer and use it in GitHub Desktop.
Makes gradle go automatically go offline
/**
* 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)")
}
}
}
@bric3
Copy link
Author

bric3 commented Jul 31, 2018

Modified version of Schalk Cronjé he gave me in his tweet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment