github.com/munnerz/test-infra@v0.0.0-20190108210205-ce3d181dc989/prow/plugins/branchcleaner/branchcleaner.go (about)

     1  /*
     2  Copyright 2018 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package branchcleaner
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/sirupsen/logrus"
    23  
    24  	"k8s.io/test-infra/prow/github"
    25  	"k8s.io/test-infra/prow/pluginhelp"
    26  	"k8s.io/test-infra/prow/plugins"
    27  )
    28  
    29  const (
    30  	pluginName = "branchcleaner"
    31  )
    32  
    33  func init() {
    34  	plugins.RegisterPullRequestHandler(pluginName, handlePullRequest, helpProvider)
    35  }
    36  
    37  func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) {
    38  	return &pluginhelp.PluginHelp{
    39  		Description: "The branchcleaner plugin automatically deletes source branches for merged PRs between two branches on the same repository. This is helpful to keep repos that don't allow forking clean."}, nil
    40  }
    41  
    42  func handlePullRequest(pc plugins.Agent, pre github.PullRequestEvent) error {
    43  	return handle(pc.GitHubClient, pc.Logger, pre)
    44  }
    45  
    46  type githubClient interface {
    47  	DeleteRef(owner, repo, ref string) error
    48  }
    49  
    50  func handle(gc githubClient, log *logrus.Entry, pre github.PullRequestEvent) error {
    51  	// Only consider closed PRs that got merged
    52  	if pre.Action != github.PullRequestActionClosed || !pre.PullRequest.Merged {
    53  		return nil
    54  	}
    55  
    56  	pr := pre.PullRequest
    57  
    58  	//Only consider PRs from the same repo
    59  	if pr.Base.Repo.FullName != pr.Head.Repo.FullName {
    60  		return nil
    61  	}
    62  
    63  	if err := gc.DeleteRef(pr.Base.Repo.Owner.Login, pr.Base.Repo.Name, fmt.Sprintf("heads/%s", pr.Head.Ref)); err != nil {
    64  		return fmt.Errorf("failed to delete branch %s on repo %s/%s after Pull Request #%d got merged: %v",
    65  			pr.Head.Ref, pr.Base.Repo.Owner.Login, pr.Base.Repo.Name, pre.PullRequest.Number, err)
    66  	}
    67  
    68  	return nil
    69  }