Skip to content

Commit

Permalink
Clean use of word github that should be more generic
Browse files Browse the repository at this point in the history
  • Loading branch information
Luke Kysow committed Nov 16, 2017
1 parent aeb4025 commit a529bac
Show file tree
Hide file tree
Showing 16 changed files with 72 additions and 53 deletions.
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Package cmd holds all our cli commands.
// These are different from the commands that get run via GitHub comments
// These are different from the commands that get run via pull request comments.
package cmd

import (
Expand Down
16 changes: 10 additions & 6 deletions cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ var stringFlags = []stringFlag{
{
name: GHWebHookSecret,
description: "Optional secret used to validate GitHub webhooks (see https://developer.github.com/webhooks/securing/)." +
" If not specified, Atlantis won't be able to validate that the incoming webhook call came from GitHub.",
" If not specified, Atlantis won't be able to validate that the incoming webhook call came from GitHub. " +
"Can also be specified via the ATLANTIS_GH_WEBHOOK_SECRET environment variable.",
env: "ATLANTIS_GH_WEBHOOK_SECRET",
},
{
Expand All @@ -84,8 +85,10 @@ var stringFlags = []stringFlag{
},
{
name: GitlabWebHookSecret,
description: "Optional secret used to validate GitLab webhooks. If not specified, Atlantis won't be able to validate that the incoming webhook call came from GitLab.",
env: "ATLANTIS_GITLAB_WEBHOOK_SECRET",
description: "Optional secret used to validate GitLab webhooks." +
" If not specified, Atlantis won't be able to validate that the incoming webhook call came from GitLab. " +
"Can also be specified via the ATLANTIS_GITLAB_WEBHOOK_SECRET environment variable.",
env: "ATLANTIS_GITLAB_WEBHOOK_SECRET",
},
{
name: LogLevelFlag,
Expand Down Expand Up @@ -230,7 +233,7 @@ func (s *ServerCmd) run() error {
if err := setDataDir(&config); err != nil {
return err
}
sanitizeGithubUser(&config)
trimAtSymbolFromUsers(&config)

// Config looks good. Start the server.
server, err := s.ServerCreator.NewServer(config)
Expand Down Expand Up @@ -292,9 +295,10 @@ func setDataDir(config *server.Config) error {
return nil
}

// sanitizeGithubUser trims @ from the front of the github username if it exists.
func sanitizeGithubUser(config *server.Config) {
// trimAtSymbolFromUsers trims @ from the front of the github and gitlab usernames
func trimAtSymbolFromUsers(config *server.Config) {
config.GithubUser = strings.TrimPrefix(config.GithubUser, "@")
config.GitlabUser = strings.TrimPrefix(config.GitlabUser, "@")
}

// withErrPrint prints out any errors to a terminal in red.
Expand Down
12 changes: 12 additions & 0 deletions cmd/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,18 @@ func TestExecute_GithubUser(t *testing.T) {
Equals(t, "user", passedConfig.GithubUser)
}

func TestExecute_GitlabUser(t *testing.T) {
t.Log("Should remove the @ from the gitlab username if it's passed.")
c := setup(map[string]interface{}{
cmd.GitlabUserFlag: "@user",
cmd.GitlabTokenFlag: "token",
})
err := c.Execute()
Ok(t, err)

Equals(t, "user", passedConfig.GitlabUser)
}

func TestExecute_Flags(t *testing.T) {
t.Log("Should use all flags that are set.")
c := setup(map[string]interface{}{
Expand Down
10 changes: 5 additions & 5 deletions server/events/command_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ type CommandHandler struct {
VCSClient vcs.ClientProxy
GithubPullGetter GithubPullGetter
GitlabMergeRequestGetter GitlabMergeRequestGetter
GHStatus CommitStatusUpdater
CommitStatusUpdater CommitStatusUpdater
EventParser EventParsing
EnvLocker EnvLocker
GHCommentRenderer *GithubCommentRenderer
MarkdownRenderer *MarkdownRenderer
Logger logging.SimpleLogging
}

Expand Down Expand Up @@ -119,7 +119,7 @@ func (c *CommandHandler) run(ctx *CommandContext) {
return
}

c.GHStatus.Update(ctx.BaseRepo, ctx.Pull, vcs.Pending, ctx.Command, ctx.VCSHost) // nolint: errcheck
c.CommitStatusUpdater.Update(ctx.BaseRepo, ctx.Pull, vcs.Pending, ctx.Command, ctx.VCSHost) // nolint: errcheck
if !c.EnvLocker.TryLock(ctx.BaseRepo.FullName, ctx.Command.Environment, ctx.Pull.Num) {
errMsg := fmt.Sprintf(
"The %s environment is currently locked by another"+
Expand Down Expand Up @@ -155,8 +155,8 @@ func (c *CommandHandler) updatePull(ctx *CommandContext, res CommandResponse) {
}

// Update the pull request's status icon and comment back.
c.GHStatus.UpdateProjectResult(ctx, res) // nolint: errcheck
comment := c.GHCommentRenderer.Render(res, ctx.Command.Name, ctx.Log.History.String(), ctx.Command.Verbose)
c.CommitStatusUpdater.UpdateProjectResult(ctx, res) // nolint: errcheck
comment := c.MarkdownRenderer.Render(res, ctx.Command.Name, ctx.Log.History.String(), ctx.Command.Verbose)
c.VCSClient.CreateComment(ctx.BaseRepo, ctx.Pull, comment, ctx.VCSHost) // nolint: errcheck
}

Expand Down
6 changes: 3 additions & 3 deletions server/events/command_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ func setup(t *testing.T) {
ApplyExecutor: applier,
HelpExecutor: helper,
VCSClient: vcsClient,
GHStatus: ghStatus,
CommitStatusUpdater: ghStatus,
EventParser: eventParsing,
EnvLocker: envLocker,
GHCommentRenderer: &events.GithubCommentRenderer{},
MarkdownRenderer: &events.MarkdownRenderer{},
GithubPullGetter: githubGetter,
GitlabMergeRequestGetter: gitlabGetter,
Logger: logger,
Logger: logger,
}
}

Expand Down
12 changes: 6 additions & 6 deletions server/events/commit_status_updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ type DefaultCommitStatusUpdater struct {
Client vcs.ClientProxy
}

func (g *DefaultCommitStatusUpdater) Update(repo models.Repo, pull models.PullRequest, status vcs.CommitStatus, cmd *Command, host vcs.Host) error {
func (d *DefaultCommitStatusUpdater) Update(repo models.Repo, pull models.PullRequest, status vcs.CommitStatus, cmd *Command, host vcs.Host) error {
description := fmt.Sprintf("%s %s", strings.Title(cmd.Name.String()), strings.Title(status.String()))
return g.Client.UpdateStatus(repo, pull, status, description, host)
return d.Client.UpdateStatus(repo, pull, status, description, host)
}

func (g *DefaultCommitStatusUpdater) UpdateProjectResult(ctx *CommandContext, res CommandResponse) error {
func (d *DefaultCommitStatusUpdater) UpdateProjectResult(ctx *CommandContext, res CommandResponse) error {
var status vcs.CommitStatus
if res.Error != nil || res.Failure != "" {
status = vcs.Failed
Expand All @@ -33,12 +33,12 @@ func (g *DefaultCommitStatusUpdater) UpdateProjectResult(ctx *CommandContext, re
for _, p := range res.ProjectResults {
statuses = append(statuses, p.Status())
}
status = g.worstStatus(statuses)
status = d.worstStatus(statuses)
}
return g.Update(ctx.BaseRepo, ctx.Pull, status, ctx.Command, ctx.VCSHost)
return d.Update(ctx.BaseRepo, ctx.Pull, status, ctx.Command, ctx.VCSHost)
}

func (g *DefaultCommitStatusUpdater) worstStatus(ss []vcs.CommitStatus) vcs.CommitStatus {
func (d *DefaultCommitStatusUpdater) worstStatus(ss []vcs.CommitStatus) vcs.CommitStatus {
for _, s := range ss {
if s == vcs.Failed {
return vcs.Failed
Expand Down
6 changes: 4 additions & 2 deletions server/events/event_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"github.com/lkysow/go-gitlab"
)

const gitlabPullOpened = "opened"

//go:generate pegomock generate --use-experimental-model-gen --package mocks -o mocks/mock_event_parsing.go EventParsing

type Command struct {
Expand Down Expand Up @@ -205,7 +207,7 @@ func (e *EventParser) ParseGithubRepo(ghRepo *github.Repository) (models.Repo, e

func (e *EventParser) ParseGitlabMergeEvent(event gitlab.MergeEvent) (models.PullRequest, models.Repo) {
modelState := models.Closed
if event.ObjectAttributes.State == "opened" {
if event.ObjectAttributes.State == gitlabPullOpened {
modelState = models.Open
}
// GitLab also has a "merged" state, but we map that to Closed so we don't
Expand Down Expand Up @@ -281,7 +283,7 @@ func (e *EventParser) ParseGitlabMergeCommentEvent(event gitlab.MergeCommentEven

func (e *EventParser) ParseGitlabMergeRequest(mr *gitlab.MergeRequest) models.PullRequest {
pullState := models.Closed
if mr.State == "opened" {
if mr.State == gitlabPullOpened {
pullState = models.Open
}
// GitLab also has a "merged" state, but we map that to Closed so we don't
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ var failureTmpl = template.Must(template.New("").Parse(failureTmplText))
var failureWithLogTmpl = template.Must(template.New("").Parse(failureTmplText + logTmpl))
var logTmpl = "{{if .Verbose}}\n<details><summary>Log</summary>\n <p>\n\n```\n{{.Log}}```\n</p></details>{{end}}\n"

// GithubCommentRenderer renders responses as GitHub comments
type GithubCommentRenderer struct{}
// MarkdownRenderer renders responses as markdown
type MarkdownRenderer struct{}

type CommonData struct {
Command string
Expand All @@ -89,7 +89,7 @@ type ResultData struct {

// Render formats the data into a string that can be commented back to GitHub.
// nolint: interfacer
func (g *GithubCommentRenderer) Render(res CommandResponse, cmdName CommandName, log string, verbose bool) string {
func (g *MarkdownRenderer) Render(res CommandResponse, cmdName CommandName, log string, verbose bool) string {
if cmdName == Help {
return g.renderTemplate(helpTmpl, nil)
}
Expand All @@ -104,7 +104,7 @@ func (g *GithubCommentRenderer) Render(res CommandResponse, cmdName CommandName,
return g.renderProjectResults(res.ProjectResults, common)
}

func (g *GithubCommentRenderer) renderProjectResults(pathResults []ProjectResult, common CommonData) string {
func (g *MarkdownRenderer) renderProjectResults(pathResults []ProjectResult, common CommonData) string {
results := make(map[string]string)
for _, result := range pathResults {
if result.Error != nil {
Expand Down Expand Up @@ -141,7 +141,7 @@ func (g *GithubCommentRenderer) renderProjectResults(pathResults []ProjectResult
return g.renderTemplate(tmpl, ResultData{results, common})
}

func (g *GithubCommentRenderer) renderTemplate(tmpl *template.Template, data interface{}) string {
func (g *MarkdownRenderer) renderTemplate(tmpl *template.Template, data interface{}) string {
buf := &bytes.Buffer{}
if err := tmpl.Execute(buf, data); err != nil {
return fmt.Sprintf("Failed to render template, this is a bug: %v", err)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestRenderErr(t *testing.T) {
},
}

r := events.GithubCommentRenderer{}
r := events.MarkdownRenderer{}
for _, c := range cases {
res := events.CommandResponse{
Error: c.Error,
Expand Down Expand Up @@ -68,7 +68,7 @@ func TestRenderFailure(t *testing.T) {
},
}

r := events.GithubCommentRenderer{}
r := events.MarkdownRenderer{}
for _, c := range cases {
res := events.CommandResponse{
Failure: c.Failure,
Expand All @@ -87,7 +87,7 @@ func TestRenderFailure(t *testing.T) {

func TestRenderErrAndFailure(t *testing.T) {
t.Log("if there is an error and a failure, the error should be printed")
r := events.GithubCommentRenderer{}
r := events.MarkdownRenderer{}
res := events.CommandResponse{
Error: errors.New("error"),
Failure: "failure",
Expand Down Expand Up @@ -225,7 +225,7 @@ func TestRenderProjectResults(t *testing.T) {
},
}

r := events.GithubCommentRenderer{}
r := events.MarkdownRenderer{}
for _, c := range cases {
res := events.CommandResponse{
ProjectResults: c.ProjectResults,
Expand Down
11 changes: 6 additions & 5 deletions server/events/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"time"
)

// Repo is a GitHub repository.
// Repo is a VCS repository.
type Repo struct {
// FullName is the owner and repo name separated
// by a "/", ex. "hootsuite/atlantis".
Expand All @@ -25,7 +25,8 @@ type Repo struct {
SanitizedCloneURL string
}

// PullRequest is a GitHub pull request.
// PullRequest is a VCS pull request.
// GitLab calls these Merge Requests.
type PullRequest struct {
// Num is the pull request number or ID.
Num int
Expand All @@ -37,7 +38,7 @@ type PullRequest struct {
URL string
// Branch is the name of the head branch (not the base).
Branch string
// Author is the GitHub username of the pull request author.
// Author is the username of the pull request author.
Author string
// State will be one of Open or Closed.
// Gitlab supports an additional "merged" state but Github doesn't so we map
Expand All @@ -52,7 +53,7 @@ const (
Closed
)

// User is a GitHub user.
// User is a VCS user.
type User struct {
Username string
}
Expand All @@ -64,7 +65,7 @@ type ProjectLock struct {
// Pull is the pull request from which the command was run that
// created this lock.
Pull PullRequest
// User is the GitHub username of the user that ran the command
// User is the username of the user that ran the command
// that created this lock.
User User
// Env is the Terraform environment that this
Expand Down
9 changes: 4 additions & 5 deletions server/events/plan_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,10 @@ type LockURLGenerator interface {
}

// atlantisUserTFVar is the name of the variable we execute terraform
// with containing the github username of who is running the command
// with, containing the vcs username of who is running the command
const atlantisUserTFVar = "atlantis_user"

// PlanExecutor handles everything related to running terraform plan
// including integration with S3, Terraform, and GitHub
// PlanExecutor handles everything related to running terraform plan.
type PlanExecutor struct {
VCSClient vcs.ClientProxy
Terraform terraform.Runner
Expand All @@ -35,7 +34,7 @@ type PlanExecutor struct {
Run run.Runner
Workspace Workspace
ProjectPreExecute ProjectPreExecutor
ModifiedProject ModifiedProjectFinder
ProjectFinder ModifiedProjectFinder
}

type PlanSuccess struct {
Expand All @@ -54,7 +53,7 @@ func (p *PlanExecutor) Execute(ctx *CommandContext) CommandResponse {
return CommandResponse{Error: errors.Wrap(err, "getting modified files")}
}
ctx.Log.Info("found %d files modified in this pull request", len(modifiedFiles))
projects := p.ModifiedProject.FindModified(ctx.Log, modifiedFiles, ctx.BaseRepo.FullName)
projects := p.ProjectFinder.FindModified(ctx.Log, modifiedFiles, ctx.BaseRepo.FullName)
if len(projects) == 0 {
return CommandResponse{Failure: "No Terraform files were modified."}
}
Expand Down
2 changes: 1 addition & 1 deletion server/events/plan_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ func setupPlanExecutorTest(t *testing.T) (*events.PlanExecutor, *tmocks.MockRunn
run := rmocks.NewMockRunner()
p := events.PlanExecutor{
VCSClient: vcsProxy,
ModifiedProject: &events.ProjectFinder{},
ProjectFinder: &events.ProjectFinder{},
Workspace: w,
ProjectPreExecute: ppe,
Terraform: runner,
Expand Down
2 changes: 1 addition & 1 deletion server/events/pull_closed_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (p *PullClosedExecutor) CleanUpPull(repo models.Repo, pull models.PullReque
}

// buildTemplateData formats the lock data into a slice that can easily be templated
// for the GitHub comment. We organize all the environments by their respective project paths
// for the VCS comment. We organize all the environments by their respective project paths
// so the comment can look like: path: {path}, environments: {all-envs}
func (p *PullClosedExecutor) buildTemplateData(locks []models.ProjectLock) []templatedProject {
envsByPath := make(map[string][]string)
Expand Down
2 changes: 1 addition & 1 deletion server/events_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ func (e *EventsController) HandleGitlabMergeRequestEvent(w http.ResponseWriter,
return
}
e.Logger.Info("deleted locks and workspace for repo %s, pull %d", repo.FullName, pull.Num)
fmt.Fprintln(w, "Pull request cleaned successfully")
fmt.Fprintln(w, "Merge request cleaned successfully")
}

// HandleGithubPullRequestEvent will delete any locks associated with the pull request
Expand Down
2 changes: 1 addition & 1 deletion server/logging/simple_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type SimpleLogging interface {

// SimpleLogger wraps the standard logger with leveled logging
// and the ability to store log history for later adding it
// to a GitHub comment.
// to a VCS comment.
type SimpleLogger struct {
// Source is added as a prefix to each log entry.
// It's useful if you want to trace a log entry back to a
Expand Down
Loading

0 comments on commit a529bac

Please sign in to comment.