Introduce ControlUtil which provides control facilities such as using() or defining().

This commit is contained in:
takezoe
2013-09-19 18:53:14 +09:00
parent fd22e2911a
commit b4dd067d61
12 changed files with 67 additions and 91 deletions

View File

@@ -1,6 +1,7 @@
package app
import util.Directory._
import util.ControlUtil._
import util._
import service._
import java.io.File
@@ -149,7 +150,7 @@ trait CreateRepositoryControllerBase extends ControllerBase {
getWikiRepositoryDir(loginUserName, repository.name))
// insert commit id
JGitUtil.withGit(getRepositoryDir(loginUserName, repository.name)){ git =>
using(Git.open(getRepositoryDir(loginUserName, repository.name))){ git =>
JGitUtil.getRepositoryInfo(loginUserName, repository.name, baseUrl).branchList.foreach { branch =>
JGitUtil.getCommitLog(git, branch) match {
case Right((commits, _)) => commits.foreach { commit =>

View File

@@ -3,6 +3,7 @@ package app
import util.{LockUtil, CollaboratorsAuthenticator, JGitUtil, ReferrerAuthenticator, Notifier}
import util.Directory._
import util.Implicits._
import util.ControlUtil._
import service._
import org.eclipse.jgit.api.Git
import jp.sf.amateras.scalatra.forms._
@@ -67,7 +68,7 @@ trait PullRequestsControllerBase extends ControllerBase {
val issueId = params("id").toInt
getPullRequest(owner, name, issueId) map { case(issue, pullreq) =>
JGitUtil.withGit(getRepositoryDir(owner, name)){ git =>
using(Git.open(getRepositoryDir(owner, name))){ git =>
val requestCommitId = git.getRepository.resolve(pullreq.requestBranch)
val (commits, diffs) =
@@ -219,7 +220,7 @@ trait PullRequestsControllerBase extends ControllerBase {
} getOrElse NotFound
}
case _ => {
JGitUtil.withGit(getRepositoryDir(forkedRepository.owner, forkedRepository.name)){ git =>
using(Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))){ git =>
val defaultBranch = JGitUtil.getDefaultBranch(git, forkedRepository).get._2
redirect(s"${context.path}/${forkedRepository.owner}/${forkedRepository.name}/compare/${defaultBranch}...${defaultBranch}")
}
@@ -299,7 +300,7 @@ trait PullRequestsControllerBase extends ControllerBase {
commitIdTo = form.commitIdTo)
// fetch requested branch
JGitUtil.withGit(getRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getRepositoryDir(repository.owner, repository.name))){ git =>
git.fetch
.setRemote(getRepositoryDir(form.requestUserName, repository.name).toURI.toString)
.setRefSpecs(new RefSpec(s"refs/heads/${form.requestBranch}:refs/pull/${issueId}/head"))

View File

@@ -2,15 +2,14 @@ package app
import service._
import util.Directory._
import util.{JGitUtil, UsersAuthenticator, OwnerAuthenticator}
import util.{UsersAuthenticator, OwnerAuthenticator}
import jp.sf.amateras.scalatra.forms._
import org.apache.commons.io.FileUtils
import org.scalatra.FlashMapSupport
import service.WebHookService.{WebHookRepository, WebHookUser, WebHookCommit, WebHookPayload}
import org.eclipse.jgit.diff.DiffEntry
import scala.collection.mutable.ListBuffer
import org.eclipse.jgit.revwalk.RevCommit
import service.WebHookService.WebHookPayload
import util.JGitUtil.CommitInfo
import util.ControlUtil._
import org.eclipse.jgit.api.Git
class RepositorySettingsController extends RepositorySettingsControllerBase
with RepositoryService with AccountService with WebHookService
@@ -132,7 +131,7 @@ trait RepositorySettingsControllerBase extends ControllerBase with FlashMapSuppo
* Send the test request to registered web hook URLs.
*/
get("/:owner/:repository/settings/hooks/test")(ownerOnly { repository =>
JGitUtil.withGit(getRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getRepositoryDir(repository.owner, repository.name))){ git =>
import scala.collection.JavaConverters._
val commits = git.log
.add(git.getRepository.resolve(repository.repository.defaultBranch))

View File

@@ -2,6 +2,7 @@ package app
import util.Directory._
import util.Implicits._
import util.ControlUtil._
import _root_.util.{ReferrerAuthenticator, JGitUtil, FileUtil, StringUtil}
import service._
import org.scalatra._
@@ -56,7 +57,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
val (branchName, path) = splitPath(repository, multiParams("splat").head)
val page = params.getOrElse("page", "1").toInt
JGitUtil.withGit(getRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getRepositoryDir(repository.owner, repository.name))){ git =>
JGitUtil.getCommitLog(git, branchName, page, 30, path) match {
case Right((logs, hasNext)) =>
repo.html.commits(if(path.isEmpty) Nil else path.split("/").toList, branchName, repository,
@@ -75,7 +76,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
val (id, path) = splitPath(repository, multiParams("splat").head)
val raw = params.get("raw").getOrElse("false").toBoolean
JGitUtil.withGit(getRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getRepositoryDir(repository.owner, repository.name))){ git =>
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(id))
@scala.annotation.tailrec
@@ -127,7 +128,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
get("/:owner/:repository/commit/:id")(referrersOnly { repository =>
val id = params("id")
JGitUtil.withGit(getRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getRepositoryDir(repository.owner, repository.name))){ git =>
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(id))
JGitUtil.getDiffs(git, id) match { case (diffs, oldCommitId) =>
@@ -143,7 +144,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
* Displays branches.
*/
get("/:owner/:repository/branches")(referrersOnly { repository =>
JGitUtil.withGit(getRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getRepositoryDir(repository.owner, repository.name))){ git =>
// retrieve latest update date of each branch
val branchInfo = repository.branchList.map { branchName =>
val revCommit = git.log.add(git.getRepository.resolve(branchName)).setMaxCount(1).call.iterator.next
@@ -176,7 +177,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
// clone the repository
val cloneDir = new File(workDir, revision)
JGitUtil.withGit(Git.cloneRepository
using(Git.cloneRepository
.setURI(getRepositoryDir(repository.owner, repository.name).toURI.toString)
.setDirectory(cloneDir)
.call){ git =>
@@ -233,7 +234,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
if(repository.commitCount == 0){
repo.html.guide(repository)
} else {
JGitUtil.withGit(getRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getRepositoryDir(repository.owner, repository.name))){ git =>
val revisions = Seq(if(revstr.isEmpty) repository.repository.defaultBranch else revstr, repository.branchList.head)
// get specified commit
JGitUtil.getDefaultBranch(git, repository, revstr).map { case (objectId, revision) =>

View File

@@ -3,7 +3,9 @@ package app
import service._
import util.{CollaboratorsAuthenticator, ReferrerAuthenticator, JGitUtil, StringUtil}
import util.Directory._
import util.ControlUtil._
import jp.sf.amateras.scalatra.forms._
import org.eclipse.jgit.api.Git
class WikiController extends WikiControllerBase
with WikiService with RepositoryService with AccountService with ActivityService
@@ -46,7 +48,7 @@ trait WikiControllerBase extends ControllerBase {
get("/:owner/:repository/wiki/:page/_history")(referrersOnly { repository =>
val pageName = StringUtil.urlDecode(params("page"))
JGitUtil.withGit(getWikiRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getWikiRepositoryDir(repository.owner, repository.name))){ git =>
JGitUtil.getCommitLog(git, "master", path = pageName + ".md") match {
case Right((logs, hasNext)) => wiki.html.history(Some(pageName), logs, repository)
case Left(_) => NotFound
@@ -58,7 +60,7 @@ trait WikiControllerBase extends ControllerBase {
val pageName = StringUtil.urlDecode(params("page"))
val commitId = params("commitId").split("\\.\\.\\.")
JGitUtil.withGit(getWikiRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getWikiRepositoryDir(repository.owner, repository.name))){ git =>
wiki.html.compare(Some(pageName), JGitUtil.getDiffs(git, commitId(0), commitId(1), true), repository)
}
})
@@ -66,7 +68,7 @@ trait WikiControllerBase extends ControllerBase {
get("/:owner/:repository/wiki/_compare/:commitId")(referrersOnly { repository =>
val commitId = params("commitId").split("\\.\\.\\.")
JGitUtil.withGit(getWikiRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getWikiRepositoryDir(repository.owner, repository.name))){ git =>
wiki.html.compare(None, JGitUtil.getDiffs(git, commitId(0), commitId(1), true), repository)
}
})
@@ -120,7 +122,7 @@ trait WikiControllerBase extends ControllerBase {
})
get("/:owner/:repository/wiki/_history")(referrersOnly { repository =>
JGitUtil.withGit(getWikiRepositoryDir(repository.owner, repository.name)){ git =>
using(Git.open(getWikiRepositoryDir(repository.owner, repository.name))){ git =>
JGitUtil.getCommitLog(git, "master") match {
case Right((logs, hasNext)) => wiki.html.history(None, logs, repository)
case Left(_) => NotFound

View File

@@ -2,6 +2,7 @@ package service
import util.{FileUtil, StringUtil, JGitUtil}
import util.Directory._
import util.ControlUtil._
import model.Issue
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.treewalk.TreeWalk
@@ -27,12 +28,12 @@ trait RepositorySearchService { self: IssuesService =>
}
def countFiles(owner: String, repository: String, query: String): Int =
JGitUtil.withGit(getRepositoryDir(owner, repository)){ git =>
using(Git.open(getRepositoryDir(owner, repository))){ git =>
if(JGitUtil.isEmpty(git)) 0 else searchRepositoryFiles(git, query).length
}
def searchFiles(owner: String, repository: String, query: String): List[FileSearchResult] =
JGitUtil.withGit(getRepositoryDir(owner, repository)){ git =>
using(Git.open(getRepositoryDir(owner, repository))){ git =>
if(JGitUtil.isEmpty(git)){
Nil
} else {

View File

@@ -5,6 +5,7 @@ import java.util.Date
import org.eclipse.jgit.api.Git
import org.apache.commons.io.FileUtils
import util.{Directory, JGitUtil, LockUtil}
import util.ControlUtil._
object WikiService {
@@ -52,7 +53,7 @@ trait WikiService {
* Returns the wiki page.
*/
def getWikiPage(owner: String, repository: String, pageName: String): Option[WikiPageInfo] = {
JGitUtil.withGit(Directory.getWikiRepositoryDir(owner, repository)){ git =>
using(Git.open(Directory.getWikiRepositoryDir(owner, repository))){ git =>
if(!JGitUtil.isEmpty(git)){
JGitUtil.getFileList(git, "master", ".").find(_.name == pageName + ".md").map { file =>
WikiPageInfo(file.name, new String(git.getRepository.open(file.id).getBytes, "UTF-8"), file.committer, file.time)
@@ -65,7 +66,7 @@ trait WikiService {
* Returns the content of the specified file.
*/
def getFileContent(owner: String, repository: String, path: String): Option[Array[Byte]] = {
JGitUtil.withGit(Directory.getWikiRepositoryDir(owner, repository)){ git =>
using(Git.open(Directory.getWikiRepositoryDir(owner, repository))){ git =>
if(!JGitUtil.isEmpty(git)){
val index = path.lastIndexOf('/')
val parentPath = if(index < 0) "." else path.substring(0, index)
@@ -82,7 +83,7 @@ trait WikiService {
* Returns the list of wiki page names.
*/
def getWikiPageList(owner: String, repository: String): List[String] = {
JGitUtil.withGit(Directory.getWikiRepositoryDir(owner, repository)){ git =>
using(Git.open(Directory.getWikiRepositoryDir(owner, repository))){ git =>
JGitUtil.getFileList(git, "master", ".")
.filter(_.name.endsWith(".md"))
.map(_.name.replaceFirst("\\.md$", ""))
@@ -102,7 +103,7 @@ trait WikiService {
cloneOrPullWorkingCopy(workDir, owner, repository)
// write as file
JGitUtil.withGit(workDir){ git =>
using(Git.open(workDir)){ git =>
val file = new File(workDir, newPageName + ".md")
val added = if(!file.exists || FileUtils.readFileToString(file, "UTF-8") != content){
FileUtils.writeStringToFile(file, content, "UTF-8")
@@ -145,7 +146,7 @@ trait WikiService {
// delete file
new File(workDir, pageName + ".md").delete
JGitUtil.withGit(workDir){ git =>
using(Git.open(workDir)){ git =>
git.rm.addFilepattern(pageName + ".md").call
// commit and push
@@ -164,7 +165,7 @@ trait WikiService {
.call
git.getRepository.close // close .git resources.
} else {
JGitUtil.withGit(workDir){ git =>
using(Git.open(workDir)){ git =>
git.pull.call
}
}

View File

@@ -10,10 +10,10 @@ import javax.servlet.ServletConfig
import javax.servlet.ServletContext
import javax.servlet.http.HttpServletRequest
import util.{JGitUtil, Directory}
import util.ControlUtil._
import service._
import WebHookService._
import org.eclipse.jgit.diff.DiffEntry
import org.apache.http.client.methods.HttpPost
import org.eclipse.jgit.api.Git
/**
* Provides Git repository via HTTP.
@@ -80,7 +80,7 @@ class CommitLogHook(owner: String, repository: String, userName: String, baseURL
private val logger = LoggerFactory.getLogger(classOf[CommitLogHook])
def onPostReceive(receivePack: ReceivePack, commands: java.util.Collection[ReceiveCommand]): Unit = {
JGitUtil.withGit(Directory.getRepositoryDir(owner, repository)) { git =>
using(Git.open(Directory.getRepositoryDir(owner, repository))) { git =>
commands.asScala.foreach { command =>
val commits = JGitUtil.getCommitLog(git, command.getOldId.name, command.getNewId.name)
val refName = command.getRefName.split("/")

View File

@@ -1,6 +1,7 @@
package util
import java.io.File
import util.ControlUtil._
/**
* Provides directories used by GitBucket.
@@ -21,8 +22,8 @@ object Directory {
/**
* Repository names of the specified user.
*/
def getRepositories(owner: String): List[String] = {
val dir = new File(s"${RepositoryHome}/${owner}")
def getRepositories(owner: String): List[String] =
defining(new File(s"${RepositoryHome}/${owner}")){ dir =>
if(dir.exists){
dir.listFiles.filter { file =>
file.isDirectory && !file.getName.endsWith(".wiki.git")

View File

@@ -4,16 +4,15 @@ import org.apache.commons.io.{IOUtils, FileUtils}
import java.net.URLConnection
import java.io.File
import org.apache.commons.compress.archivers.zip.{ZipArchiveEntry, ZipArchiveOutputStream}
import util.ControlUtil._
object FileUtil {
def getMimeType(name: String): String = {
val fileNameMap = URLConnection.getFileNameMap()
val mimeType = fileNameMap.getContentTypeFor(name)
if(mimeType == null){
"application/octet-stream"
} else {
mimeType
def getMimeType(name: String): String =
defining(URLConnection.getFileNameMap()){ fileNameMap =>
fileNameMap.getContentTypeFor(name) match {
case null => "application/octet-stream"
case mimeType => mimeType
}
}
@@ -36,21 +35,15 @@ object FileUtil {
}
}
val out = new ZipArchiveOutputStream(dest)
try {
using(new ZipArchiveOutputStream(dest)){ out =>
addDirectoryToZip(out, dir, dir.getName)
} finally {
IOUtils.closeQuietly(out)
}
}
def getExtension(name: String): String = {
val index = name.lastIndexOf('.')
if(index >= 0){
name.substring(index + 1)
} else {
""
}
def getExtension(name: String): String =
name.lastIndexOf('.') match {
case i if(i >= 0) => name.substring(i + 1)
case _ => ""
}
}

View File

@@ -12,7 +12,7 @@ object Implicits {
def splitWith(condition: (A, A) => Boolean): Seq[Seq[A]] = split(seq)(condition)
@scala.annotation.tailrec
private def split[A](list: Seq[A], result: Seq[Seq[A]] = Nil)(condition: (A, A) => Boolean): Seq[Seq[A]] = {
private def split[A](list: Seq[A], result: Seq[Seq[A]] = Nil)(condition: (A, A) => Boolean): Seq[Seq[A]] =
list match {
case x :: xs => {
xs.span(condition(x, _)) match {
@@ -22,7 +22,6 @@ object Implicits {
case Nil => result
}
}
}
implicit class RichString(value: String){
def replaceBy(regex: Regex)(replace: Regex.MatchData => Option[String]): String = {

View File

@@ -3,6 +3,7 @@ package util
import org.eclipse.jgit.api.Git
import util.Directory._
import util.StringUtil._
import util.ControlUtil._
import scala.collection.JavaConverters._
import org.eclipse.jgit.lib._
import org.eclipse.jgit.revwalk._
@@ -112,24 +113,6 @@ object JGitUtil {
*/
case class TagInfo(name: String, time: Date, id: String)
/**
* Use this method to use the Git object.
* Repository resources are released certainly after processing.
*/
def withGit[T](dir: java.io.File)(f: Git => T): T = withGit(Git.open(dir))(f)
/**
* Use this method to use the Git object.
* Repository resources are released certainly after processing.
*/
def withGit[T](git: Git)(f: Git => T): T = {
try {
f(git)
} finally {
git.getRepository.close
}
}
/**
* Returns RevCommit from the commit or tag id.
*
@@ -151,7 +134,7 @@ object JGitUtil {
* Returns the repository information. It contains branch names and tag names.
*/
def getRepositoryInfo(owner: String, repository: String, baseUrl: String): RepositoryInfo = {
withGit(getRepositoryDir(owner, repository)){ git =>
using(Git.open(getRepositoryDir(owner, repository))){ git =>
try {
// get commit count
val commitCount = git.log.all.call.iterator.asScala.map(_ => 1).take(1000).sum
@@ -370,11 +353,8 @@ object JGitUtil {
if(large == false && FileUtil.isLarge(loader.getSize)){
None
} else {
val db = git.getRepository.getObjectDatabase
try {
using(git.getRepository.getObjectDatabase){ db =>
Some(db.open(id).getBytes)
} finally {
db.close
}
}
} catch {
@@ -483,12 +463,9 @@ object JGitUtil {
}
def initRepository(dir: java.io.File): Unit = {
val repository = new RepositoryBuilder().setGitDir(dir).setBare.build
try {
using(new RepositoryBuilder().setGitDir(dir).setBare.build){ repository =>
repository.create
setReceivePack(repository)
} finally {
repository.close
}
}