Newer
Older
GitBucket / src / main / scala / gitbucket / core / service / ProtectedBrancheService.scala
@nazoking nazoking on 2 Jan 2016 5 KB use real database
package gitbucket.core.service

import gitbucket.core.model.{Collaborator, Repository, Account, CommitState, CommitStatus, ProtectedBranch, ProtectedBranchContext}
import gitbucket.core.model.Profile._
import gitbucket.core.util.JGitUtil
import profile.simple._

import org.eclipse.jgit.transport.ReceiveCommand
import org.eclipse.jgit.transport.ReceivePack
import org.eclipse.jgit.lib.ObjectId


trait ProtectedBrancheService {
  import ProtectedBrancheService._
  private def getProtectedBranchInfoOpt(owner: String, repository: String, branch: String)(implicit session: Session): Option[ProtectedBranchInfo] =
    ProtectedBranches
      .leftJoin(ProtectedBrancheContexts)
      .on{ case (pb, c) => pb.byBranch(c.userName, c.repositoryName, c.branch) }
      .map{ case (pb, c) => pb -> c.context.? }
      .filter(_._1.byPrimaryKey(owner, repository, branch))
      .list
      .groupBy(_._1)
      .map(p => p._1 -> p._2.flatMap(_._2))
      .map{ case (t1, contexts) =>
        new ProtectedBranchInfo(t1.userName, t1.repositoryName, true, contexts, t1.statusCheckAdmin)
      }.headOption

  def getProtectedBranchInfo(owner: String, repository: String, branch: String)(implicit session: Session): ProtectedBranchInfo =
    getProtectedBranchInfoOpt(owner, repository, branch).getOrElse(ProtectedBranchInfo.disabled(owner, repository))

  def isProtectedBranchNeedStatusCheck(owner: String, repository: String, branch: String, user: String)(implicit session: Session): Boolean =
    getProtectedBranchInfo(owner, repository, branch).needStatusCheck(user)

  def getProtectedBranchList(owner: String, repository: String)(implicit session: Session): List[String] =
    ProtectedBranches.filter(_.byRepository(owner, repository)).map(_.branch).list

  def enableBranchProtection(owner: String, repository: String, branch:String, includeAdministrators: Boolean, contexts: Seq[String])(implicit session: Session): Unit = {
    disableBranchProtection(owner, repository, branch)
    ProtectedBranches.insert(new ProtectedBranch(owner, repository, branch, includeAdministrators))
    contexts.map{ context =>
      ProtectedBrancheContexts.insert(new ProtectedBranchContext(owner, repository, branch, context))
    }
  }

  def disableBranchProtection(owner: String, repository: String, branch:String)(implicit session: Session): Unit =
    ProtectedBranches.filter(_.byPrimaryKey(owner, repository, branch)).delete

  def getBranchProtectedReason(owner: String, repository: String, receivePack: ReceivePack, command: ReceiveCommand, pusher: String)(implicit session: Session): Option[String] = {
    val branch = command.getRefName.stripPrefix("refs/heads/")
    if(branch != command.getRefName){
      getProtectedBranchInfo(owner, repository, branch).getStopReason(receivePack, command, pusher)
    }else{
      None
    }
  }
}
object ProtectedBrancheService {
  case class ProtectedBranchInfo(
    owner: String,
    repository: String,
    enabled: Boolean,
    /**
     * Require status checks to pass before merging
     * Choose which status checks must pass before branches can be merged into test.
     * When enabled, commits must first be pushed to another branch,
     * then merged or pushed directly to test after status checks have passed.
     */
    contexts: Seq[String],
    /**
     * Include administrators
     * Enforce required status checks for repository administrators.
     */
    includeAdministrators: Boolean) extends AccountService with CommitStatusService {

    def isAdministrator(pusher: String)(implicit session: Session): Boolean = pusher == owner || getGroupMembers(owner).filter(gm => gm.userName == pusher && gm.isManager).nonEmpty

    /**
     * Can't be force pushed
     * Can't be deleted
     * Can't have changes merged into them until required status checks pass
     */
    def getStopReason(receivePack: ReceivePack, command: ReceiveCommand, pusher: String)(implicit session: Session): Option[String] = {
      if(enabled){
        command.getType() match {
          case ReceiveCommand.Type.UPDATE|ReceiveCommand.Type.UPDATE_NONFASTFORWARD if receivePack.isAllowNonFastForwards =>
            Some("Cannot force-push to a protected branch")
          case ReceiveCommand.Type.UPDATE|ReceiveCommand.Type.UPDATE_NONFASTFORWARD if needStatusCheck(pusher) =>
            unSuccessedContexts(command.getNewId.name) match {
              case s if s.size == 1 => Some(s"""Required status check "${s.toSeq(0)}" is expected""")
              case s if s.size >= 1 => Some(s"${s.size} of ${contexts.size} required status checks are expected")
              case _ => None
            }
          case ReceiveCommand.Type.DELETE =>
            Some("Cannot delete a protected branch")
          case _ => None
        }
      }else{
        None
      }
    }
    def unSuccessedContexts(sha1: String)(implicit session: Session): Set[String] = if(contexts.isEmpty){
      Set.empty
    } else {
      contexts.toSet -- getCommitStatues(owner, repository, sha1).filter(_.state == CommitState.SUCCESS).map(_.context).toSet
    }
    def needStatusCheck(pusher: Option[String])(implicit session: Session): Boolean = pusher.map(needStatusCheck).getOrElse(false)
    def needStatusCheck(pusher: String)(implicit session: Session): Boolean =
      if(!enabled || contexts.isEmpty){
        false
      }else if(includeAdministrators){
        true
      }else{
        !isAdministrator(pusher)
      }
    def pendingCommitStatus(context: String) = CommitStatus(
        commitStatusId = 0,
        userName = owner,
        repositoryName = repository,
        commitId = "",
        context = context,
        state = CommitState.PENDING,
        targetUrl = None,
        description = Some("Waiting for status to be reported"),
        creator = "",
        registeredDate = new java.util.Date(),
        updatedDate = new java.util.Date())
  }
  object ProtectedBranchInfo{
    def disabled(owner: String, repository: String): ProtectedBranchInfo = ProtectedBranchInfo(owner, repository, false, Nil, false)
  }
}