package com.perforce.workshop.tjuricek.gradle import org.gradle.api.tasks.TaskAction /** * Launches perforce in a local working directory named "work". Will cache * versions of p4d and the p4 command line. */ class StartPerforceTask extends PerforceTask { @TaskAction def startPerforce() { if (!areBinariesCached()) { cacheBinaries(); } if (!isRunning()) { start(); } } /** * Looks for "p4d" and "p4" executables in the local cached directory. */ boolean areBinariesCached() { return getP4dFile().exists() && getP4File().exists() } /** * Save p4 and p4d executables locally */ void cacheBinaries() { if (!getCacheDir().exists()) { getCacheDir().mkdirs() } def p4dUri = new URL("${project.perforce.downloadRootUri}/${project.perforce.version}/${getArch()}/${getP4dName()}") def p4dFile = getP4dFile() p4dUri.withInputStream{ is -> p4dFile.withOutputStream{ it << is }} if (!p4dFile.canExecute()) { p4dFile.setExecutable(true) } def p4Uri = new URL("${project.perforce.downloadRootUri}/${project.perforce.version}/${getArch()}/${getP4Name()}") def p4File = getP4File() p4Uri.withInputStream{ i -> p4File.withOutputStream{ it << i }} if (!p4File.canExecute()) { p4File.setExecutable(true) } } boolean isRunning() { def cmd = "${getP4File().absolutePath} -p ${project.perforce.hostname}:${project.perforce.port} info" def process = cmd.execute() process.waitFor() return process.exitValue() == 0 } void start() { if (!getWorkDir().exists()) { getWorkDir().mkdirs() } def cmd = "${getP4dFile().absolutePath} -r ${getWorkDir().absolutePath} ${getVerboseOpt()} -L ${getWorkDir().absolutePath}/log -d" def process = cmd.execute() process.waitFor() def nAttempts = 60 def attempts = nAttempts while (attempts > 0) { if (isRunning()) { return; } sleep(1000); } throw "p4d did not start in ${nAttempts} seconds"; } String getVerboseOpt() { if (project.perforce.verbose != null && !project.perforce.verbose.isEmpty()) { return "-v ${project.perforce.verbose}" } return "" } }