diff --git a/src/main/scala/app/CreateRepositoryController.scala b/src/main/scala/app/CreateRepositoryController.scala index 0a9ebe7..560b828 100644 --- a/src/main/scala/app/CreateRepositoryController.scala +++ b/src/main/scala/app/CreateRepositoryController.scala @@ -1,6 +1,7 @@ package app import util.Directory._ +import util.ControlUtil._ import util._ import service._ import java.io.File @@ -149,7 +150,7 @@ 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 => diff --git a/src/main/scala/app/PullRequestsController.scala b/src/main/scala/app/PullRequestsController.scala index e7035d6..46bae76 100644 --- a/src/main/scala/app/PullRequestsController.scala +++ b/src/main/scala/app/PullRequestsController.scala @@ -3,6 +3,7 @@ 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 @@ 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 @@ } 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 @@ 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")) diff --git a/src/main/scala/app/RepositorySettingsController.scala b/src/main/scala/app/RepositorySettingsController.scala index 5640e8e..bc4cf86 100644 --- a/src/main/scala/app/RepositorySettingsController.scala +++ b/src/main/scala/app/RepositorySettingsController.scala @@ -2,15 +2,14 @@ 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 @@ * 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)) diff --git a/src/main/scala/app/RepositoryViewerController.scala b/src/main/scala/app/RepositoryViewerController.scala index df7fd8a..adb9d04 100644 --- a/src/main/scala/app/RepositoryViewerController.scala +++ b/src/main/scala/app/RepositoryViewerController.scala @@ -2,6 +2,7 @@ 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 @@ 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 @@ 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 @@ 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 @@ * 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 @@ // 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,10 +234,10 @@ 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) => + JGitUtil.getDefaultBranch(git, repository, revstr).map { case (objectId, revision) => val revCommit = JGitUtil.getRevCommitFromId(git, objectId) // get files diff --git a/src/main/scala/app/WikiController.scala b/src/main/scala/app/WikiController.scala index 8a27bb2..a44f9af 100644 --- a/src/main/scala/app/WikiController.scala +++ b/src/main/scala/app/WikiController.scala @@ -3,7 +3,9 @@ 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 @@ 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 @@ 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 @@ 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 @@ }) 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 diff --git a/src/main/scala/service/RepositorySearchService.scala b/src/main/scala/service/RepositorySearchService.scala index 4c80441..1baed45 100644 --- a/src/main/scala/service/RepositorySearchService.scala +++ b/src/main/scala/service/RepositorySearchService.scala @@ -2,6 +2,7 @@ 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 @@ } 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 { diff --git a/src/main/scala/service/WikiService.scala b/src/main/scala/service/WikiService.scala index ae5e300..2a1a945 100644 --- a/src/main/scala/service/WikiService.scala +++ b/src/main/scala/service/WikiService.scala @@ -5,6 +5,7 @@ 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 @@ * 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 @@ * 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 @@ * 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 @@ 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 @@ // 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 @@ .call git.getRepository.close // close .git resources. } else { - JGitUtil.withGit(workDir){ git => + using(Git.open(workDir)){ git => git.pull.call } } diff --git a/src/main/scala/servlet/GitRepositoryServlet.scala b/src/main/scala/servlet/GitRepositoryServlet.scala index 73b5f7e..944363d 100644 --- a/src/main/scala/servlet/GitRepositoryServlet.scala +++ b/src/main/scala/servlet/GitRepositoryServlet.scala @@ -10,10 +10,10 @@ 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 @@ 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("/") diff --git a/src/main/scala/util/Directory.scala b/src/main/scala/util/Directory.scala index 73cee55..5409962 100644 --- a/src/main/scala/util/Directory.scala +++ b/src/main/scala/util/Directory.scala @@ -1,6 +1,7 @@ package util import java.io.File +import util.ControlUtil._ /** * Provides directories used by GitBucket. @@ -21,17 +22,17 @@ /** * Repository names of the specified user. */ - def getRepositories(owner: String): List[String] = { - val dir = new File(s"${RepositoryHome}/${owner}") - if(dir.exists){ - dir.listFiles.filter { file => - file.isDirectory && !file.getName.endsWith(".wiki.git") - }.map(_.getName.replaceFirst("\\.git$", "")).toList - } else { - Nil + 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") + }.map(_.getName.replaceFirst("\\.git$", "")).toList + } else { + Nil + } } - } - + /** * Substance directory of the repository. */ diff --git a/src/main/scala/util/FileUtil.scala b/src/main/scala/util/FileUtil.scala index 1c35444..fad4067 100644 --- a/src/main/scala/util/FileUtil.scala +++ b/src/main/scala/util/FileUtil.scala @@ -4,19 +4,18 @@ 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 + } } - } - + def isImage(name: String): Boolean = getMimeType(name).startsWith("image/") def isLarge(size: Long): Boolean = (size > 1024 * 1000) @@ -36,21 +35,15 @@ } } - 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 _ => "" } - } } \ No newline at end of file diff --git a/src/main/scala/util/Implicits.scala b/src/main/scala/util/Implicits.scala index 388f9f6..5d8f77b 100644 --- a/src/main/scala/util/Implicits.scala +++ b/src/main/scala/util/Implicits.scala @@ -12,7 +12,7 @@ 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 { @@ -21,7 +21,6 @@ } case Nil => result } - } } implicit class RichString(value: String){ diff --git a/src/main/scala/util/JGitUtil.scala b/src/main/scala/util/JGitUtil.scala index 9114364..3878736 100644 --- a/src/main/scala/util/JGitUtil.scala +++ b/src/main/scala/util/JGitUtil.scala @@ -3,6 +3,7 @@ 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._ @@ -113,24 +114,6 @@ 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. * * @param git the Git object @@ -151,7 +134,7 @@ * 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 @@ 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 @@ } 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 } }