Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring + Issue #56 GitHub default branch #263

Merged
merged 5 commits into from Feb 15, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 6 additions & 3 deletions app/src/main/scala/giter8.scala
Expand Up @@ -17,6 +17,8 @@

package giter8

import java.io.File

class Giter8 extends xsbti.AppMain {
java.util.logging.Logger.getLogger("").setLevel(java.util.logging.Level.SEVERE)

Expand All @@ -26,16 +28,17 @@ class Giter8 extends xsbti.AppMain {

/** Runner shared my main-class runner */
def run(args: Array[String]): Int = {
val helper = new JgitHelper(new Git(new JGitInteractor), G8TemplateRenderer)
val result = (args.partition { s =>
G8.Param.pattern.matcher(s).matches
} match {
case (params, options) =>
parser.parse(options, Config()).map { config =>
JgitHelper.run(config, params)
parser.parse(options, Config("")).map { config =>
helper.run(config, params, new File("."))
}.getOrElse(Left(""))
case _ => Left(parser.usage)
})
JgitHelper.cleanup()
helper.cleanup()
result.fold ({ (error: String) =>
System.err.println(s"\n$error\n")
1
Expand Down
3 changes: 2 additions & 1 deletion build.sbt
Expand Up @@ -100,7 +100,8 @@ lazy val lib = (project in file("library")).
crossScalaVersions := List(scala210, scala211, scala212),
libraryDependencies ++= Seq(
scalasti, jgit, commonsIo, plexusArchiver,
scalacheck % Test, sbtIo % Test, scalatest % Test
scalacheck % Test, sbtIo % Test, scalatest % Test,
scalamock % Test, "org.slf4j" % "slf4j-simple" % "1.7.12" % Test
) ++
(CrossVersion.partialVersion(scalaVersion.value) match {
case Some((2, scalaMajor)) if scalaMajor >= 11 =>
Expand Down
215 changes: 0 additions & 215 deletions library/src/main/scala/JgitHelper.scala

This file was deleted.

7 changes: 0 additions & 7 deletions library/src/main/scala/g8.scala
Expand Up @@ -447,13 +447,6 @@ object G8 {
}
}

case class Config(
repo: String = "",
branch: Option[String] = None,
// tag: Option[String] = None,
forceOverwrite: Boolean = false
// search: Boolean = false
)
case class Path(paths: List[String]) {
def /(child: String): Path = copy(paths = paths ::: List(child))
}
Expand Down
42 changes: 42 additions & 0 deletions library/src/main/scala/giter8/ConsoleCredentialsProvider.scala
@@ -0,0 +1,42 @@
package giter8

import org.eclipse.jgit.transport.{CredentialItem, CredentialsProvider, URIish}

object ConsoleCredentialsProvider extends CredentialsProvider {

def isInteractive = true

def supports(items: CredentialItem*) = true

def get(uri: URIish, items: CredentialItem*): Boolean = {
items foreach {
case i: CredentialItem.Username =>
val username = System.console.readLine("%s: ", i.getPromptText)
i.setValue(username)

case i: CredentialItem.Password =>
val password = System.console.readPassword("%s: ", i.getPromptText)
i.setValueNoCopy(password)

case i: CredentialItem.InformationalMessage =>
System.console.printf("%s\n", i.getPromptText)

case i: CredentialItem.YesNoType =>
i.setValue(askYesNo(i.getPromptText))

case i: CredentialItem.StringType if uri.getScheme == "ssh" =>
val password = String.valueOf(System.console.readPassword("%s: ", i.getPromptText))
i.setValue(password)
}
true
}

@scala.annotation.tailrec
def askYesNo(prompt: String): Boolean = {
System.console.readLine("%s: ", prompt).trim.toLowerCase match {
case "yes" => true
case "no" => false
case _ => askYesNo(prompt)
}
}
}
69 changes: 69 additions & 0 deletions library/src/main/scala/giter8/Git.scala
@@ -0,0 +1,69 @@
package giter8

import java.io.File

import giter8.GitInteractor.TransportError
import giter8.GitRepository.{GitHub, Local, Remote}
import org.apache.commons.io.FileUtils
import org.apache.commons.io.filefilter.TrueFileFilter

import scala.language.implicitConversions
import scala.util.{Failure, Try}
import scala.collection.JavaConverters._

class Git(gitInteractor: GitInteractor) {
import Git._

def clone(repository: GitRepository, branch: Option[String], destination: File): Try[Unit] = repository match {
case remote: Remote => cloneWithGivenOrDefaultBranch(remote.url, branch, destination)
case local: Local => branch match {
// for file:// repositories with no named branch, just do a file copy (assume current branch)
case None => copy(new File(local.path), destination)
case Some(_) => cloneWithGivenOrDefaultBranch(local.path, branch, destination)
}
case github: GitHub => cloneWithGivenOrDefaultBranch(github.publicUrl, branch, destination) recoverWith {
case _: TransportError =>
cleanDir(destination)
cloneWithGivenOrDefaultBranch(github.privateUrl, branch, destination)
}
}

private def cloneWithGivenOrDefaultBranch(url: String, branch: Option[String], dest: File): Try[Unit] = branch match {
case None => gitInteractor.cloneRepository(url, dest) flatMap { _ =>
gitInteractor.getDefaultBranch(dest) flatMap { branch =>
gitInteractor.checkoutBranch(dest, branch)
}
}
case Some(br) => gitInteractor.getRemoteBranches(url) flatMap { remoteBranches =>
if (!remoteBranches.contains(br)) Failure(NoBranchError(br))
else gitInteractor.cloneRepository(url, dest) flatMap { _ =>
gitInteractor.checkoutBranch(dest, br)
}
}
}

// Protected for testing: see GitTest.scala
protected def cleanDir(dir: File): Unit = dir.listFiles().foreach(_.delete())

// Protected for testing: see GitTest.scala
protected def copy(from: File, to: File): Try[Unit] = Try {
if (!from.isDirectory) throw CloneError("Not a readable directory: " + from.getAbsolutePath)
FileUtils.copyDirectory(from, to)
copyExecutableAttribute(from, to)
}

private def copyExecutableAttribute(fromDir: File, toDir: File): Unit = {
val files = FileUtils.iterateFiles(fromDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE).asScala
val executables = files.filter(_.canExecute)
executables foreach {
file =>
val relativePath = fromDir.toURI.relativize(file.toURI).getPath
new File(toDir, relativePath).setExecutable(true)
}
}
}

object Git {
case class CloneError(message: String) extends RuntimeException(message)
case class NoBranchError(branchName: String) extends RuntimeException(s"No branch $branchName")
}