github.com/marinho/drone@v0.2.1-0.20140504195434-d3ba962e89a7/pkg/handler/badges.go (about)

     1  package handler
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/drone/drone/pkg/database"
     8  )
     9  
    10  const (
    11  	badgeSuccess = "https://img.shields.io/badge/build-success-brightgreen.svg"
    12  	badgeFailure = "https://img.shields.io/badge/build-failure-red.svg"
    13  	badgeUnknown = "https://img.shields.io/badge/build-unknown-lightgray.svg"
    14  )
    15  
    16  // Display a static badge (svg format) for a specific
    17  // repository and an optional branch.
    18  // TODO this needs to implement basic caching
    19  func Badge(w http.ResponseWriter, r *http.Request) error {
    20  	successParam := r.FormValue("success")
    21  	failureParam := r.FormValue("failure")
    22  	branchParam := r.FormValue("branch")
    23  	hostParam := r.FormValue(":host")
    24  	ownerParam := r.FormValue(":owner")
    25  	nameParam := r.FormValue(":name")
    26  	repoSlug := fmt.Sprintf("%s/%s/%s", hostParam, ownerParam, nameParam)
    27  
    28  	// get the repo from the database
    29  	repo, err := database.GetRepoSlug(repoSlug)
    30  	if err != nil {
    31  		http.NotFound(w, r)
    32  		return nil
    33  	}
    34  
    35  	// get the default branch for the repository
    36  	// if no branch is provided.
    37  	if len(branchParam) == 0 {
    38  		branchParam = repo.DefaultBranch()
    39  	}
    40  
    41  	var badge string
    42  
    43  	// get the latest commit from the database
    44  	// for the requested branch
    45  	commit, err := database.GetBranch(repo.ID, branchParam)
    46  	if err == nil {
    47  		switch {
    48  		case commit.Status == "Success" && len(successParam) == 0:
    49  			// if no success image is provided, we serve a
    50  			// badge using the shields.io service
    51  			badge = badgeSuccess
    52  		case commit.Status == "Success" && len(successParam) != 0:
    53  			// otherwise we serve the user defined success badge
    54  			badge = successParam
    55  		case commit.Status == "Failure" && len(failureParam) == 0:
    56  			// if no failure image is provided, we serve a
    57  			// badge using the shields.io service
    58  			badge = badgeFailure
    59  		case commit.Status == "Failure" && len(failureParam) != 0:
    60  			// otherwise we serve the user defined failure badge
    61  			badge = failureParam
    62  		default:
    63  			// otherwise load unknown image
    64  			badge = badgeUnknown
    65  		}
    66  	}
    67  
    68  	http.Redirect(w, r, badge, http.StatusSeeOther)
    69  	return nil
    70  }