Skip to content

Commit

Permalink
Merge pull request #21 from fleaz/development
Browse files Browse the repository at this point in the history
Relase small changes into master
  • Loading branch information
fleaz authored Sep 17, 2018
2 parents 997dbbc + 3e64442 commit 69e8757
Show file tree
Hide file tree
Showing 11 changed files with 217 additions and 89 deletions.
20 changes: 19 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,28 @@ script:
- cp cpthook.yml.example cpthook.yml
- go test
- CGO_ENABLED="0" GOARCH="amd64" GOOS="linux" go build -a -installsuffix cgo -o CptHook
- docker build -f Dockerfile -t $IMAGE .

deploy:
- provider: script
skip_cleanup: true
script: bash scripts/deploy.sh
script: bash scripts/deploy.sh stable
on:
branch: master
- provider: script
skip_cleanup: true
script: bash scripts/deploy.sh development
on:
branch: development

notifications:
webhooks:
urls:
- http://webhooks.rainbownerds.de:12345
on_success: always # default: always
on_failure: always # default: always
on_start: always # default: never
on_cancel: always # default: always
on_error: always # default: always

email: false
96 changes: 61 additions & 35 deletions gitlab.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@ import (
"bytes"
"encoding/json"
"fmt"
"html"
"html/template"
"log"
"net/http"
"strings"
"text/template"

"github.com/spf13/viper"
)

type Mapping struct {
type GitlabModule struct {
channelMapping mapping
}

type mapping struct {
DefaultChannel string `mapstructure:"default"`
GroupMappings map[string][]string `mapstructure:"groups"`
ExplicitMappings map[string][]string `mapstructure:"explicit"`
Expand All @@ -28,20 +31,20 @@ func contains(mapping map[string][]string, entry string) bool {
return false
}

func sendMessage(message string, projectName string, namespace string, channelMapping Mapping) {
func (m GitlabModule) sendMessage(message string, projectName string, namespace string) {
var channelNames []string
var full_projectName = namespace + "/" + projectName
var fullProjectName = namespace + "/" + projectName

if contains(channelMapping.ExplicitMappings, full_projectName) { // Check if explizit mapping exists
for _, channelName := range channelMapping.ExplicitMappings[full_projectName] {
if contains(m.channelMapping.ExplicitMappings, fullProjectName) { // Check if explizit mapping exists
for _, channelName := range m.channelMapping.ExplicitMappings[fullProjectName] {
channelNames = append(channelNames, channelName)
}
} else if contains(channelMapping.GroupMappings, namespace) { // Check if group mapping exists
for _, channelName := range channelMapping.GroupMappings[namespace] {
} else if contains(m.channelMapping.GroupMappings, namespace) { // Check if group mapping exists
for _, channelName := range m.channelMapping.GroupMappings[namespace] {
channelNames = append(channelNames, channelName)
}
} else { // Fall back to default channel
channelNames = append(channelNames, channelMapping.DefaultChannel)
channelNames = append(channelNames, m.channelMapping.DefaultChannel)
}

for _, channelName := range channelNames {
Expand All @@ -53,7 +56,36 @@ func sendMessage(message string, projectName string, namespace string, channelMa

}

func gitlabHandler(c *viper.Viper) http.HandlerFunc {
func (m *GitlabModule) init(c *viper.Viper) {
err := c.Unmarshal(&m.channelMapping)
if err != nil {
log.Fatal("Failed to unmarshal channelmapping into struct")
}
}

func (m GitlabModule) getChannelList() []string {
var all []string

for _, v := range m.channelMapping.ExplicitMappings {
for _, name := range v {
all = append(all, name)
}
}
for _, v := range m.channelMapping.GroupMappings {
for _, name := range v {
all = append(all, name)
}
}
all = append(all, m.channelMapping.DefaultChannel)

return all
}

func (m GitlabModule) getEndpoint() string {
return "/gitlab"
}

func (m GitlabModule) getHandler() http.HandlerFunc {

const pushCompareString = "[\x0312{{ .Project.Name }}\x03] {{ .UserName }} pushed {{ .TotalCommits }} commits to \x0305{{ .Branch }}\x03 {{ .Project.WebURL }}/compare/{{ .BeforeCommit }}...{{ .AfterCommit }}"
const pushCommitLogString = "[\x0312{{ .Project.Name }}\x03] {{ .UserName }} pushed {{ .TotalCommits }} commits to \x0305{{ .Branch }}\x03 {{ .Project.WebURL }}/commits/{{ .Branch }}"
Expand All @@ -62,9 +94,9 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
const commitString = "\x0315{{ .ShortID }}\x03 (\x0303+{{ .AddedFiles }}\x03|\x0308±{{ .ModifiedFiles }}\x03|\x0304-{{ .RemovedFiles }}\x03) \x0306{{ .Author.Name }}\x03: {{ .Message }}"
const issueString = "[\x0312{{ .Project.Name }}\x03] {{ .User.Name }} {{ .Issue.Action }} issue \x0308#{{ .Issue.Iid }}\x03: {{ .Issue.Title }} {{ .Issue.URL }}"
const mergeString = "[\x0312{{ .Project.Name }}\x03] {{ .User.Name }} {{ .Merge.Action }} merge request \x0308#{{ .Merge.Iid }}\x03: {{ .Merge.Title }} {{ .Merge.URL }}"
const pipelineCreateString = "[\x0312{{ .Project.Name }}\x03] Pipeline for commit {{ .Pipeline.Commit }} {{ .Pipeline.Status }} {{ .Project.WebURL }}/pipelines/{{ .Pipeline.Id }}"
const pipelineCompleteString = "[\x0312{{ .Project.Name }}\x03] Pipeline for commit {{ .Pipeline.Commit }} {{ .Pipeline.Status }} in {{ .Pipeline.Duration }} seconds {{ .Project.WebURL }}/pipelines/{{ .Pipeline.Id }}"
const jobCompleteString = "[\x0312{{ .Repository.Name }}\x03] Job \x0308{{ .Name }}\x03 for commit {{ .Commit }} {{ .Status }} in {{ .Duration }} seconds {{ .Repository.Homepage }}/-/jobs/{{ .Id }}"
const pipelineCreateString = "[\x0312{{ .Project.Name }}\x03] Pipeline for commit {{ .Pipeline.Commit }} {{ .Pipeline.Status }} {{ .Project.WebURL }}/pipelines/{{ .Pipeline.ID }}"
const pipelineCompleteString = "[\x0312{{ .Project.Name }}\x03] Pipeline for commit {{ .Pipeline.Commit }} {{ .Pipeline.Status }} in {{ .Pipeline.Duration }} seconds {{ .Project.WebURL }}/pipelines/{{ .Pipeline.ID }}"
const jobCompleteString = "[\x0312{{ .Repository.Name }}\x03] Job \x0308{{ .Name }}\x03 for commit {{ .Commit }} {{ .Status }} in {{ .Duration }} seconds {{ .Repository.Homepage }}/-/jobs/{{ .ID }}"

JobStatus := map[string]string{
"pending": "is \x0315pending\x03",
Expand All @@ -82,12 +114,6 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
"merge": "merged",
}

channelMapping := Mapping{}
err := c.Unmarshal(&channelMapping)
if err != nil {
log.Fatal("Failed to unmarshal channelmapping into struct")
}

const NullCommit = "0000000000000000000000000000000000000000"

pushCompareTemplate, err := template.New("push notification").Parse(pushCompareString)
Expand Down Expand Up @@ -169,7 +195,7 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
}

type Commit struct {
Id string `json:"id"`
ID string `json:"id"`
Message string `json:"message"`
Added []string `json:"added"`
Modified []string `json:"modified"`
Expand Down Expand Up @@ -207,7 +233,7 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
}

type Pipeline struct {
Id int `json:"id"`
ID int `json:"id"`
Commit string `json:"sha"`
Status string `json:"status"`
Duration float64 `json:"duration"`
Expand All @@ -225,7 +251,7 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
}

type JobEvent struct {
Id int `json:"build_id"`
ID int `json:"build_id"`
Name string `json:"build_name"`
Status string `json:"build_status"`
Duration float64 `json:"build_duration"`
Expand Down Expand Up @@ -259,14 +285,14 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
pipelineEvent.Pipeline.Status = JobStatus[pipelineEvent.Pipeline.Status]

err = pipelineCreateTemplate.Execute(&buf, &pipelineEvent)
sendMessage(buf.String(), pipelineEvent.Project.Name, pipelineEvent.Project.Namespace, channelMapping)
m.sendMessage(buf.String(), pipelineEvent.Project.Name, pipelineEvent.Project.Namespace)

} else if pipelineEvent.Pipeline.Status == "success" || pipelineEvent.Pipeline.Status == "failed" {
// colorize status
pipelineEvent.Pipeline.Status = JobStatus[pipelineEvent.Pipeline.Status]

err = pipelineCompleteTemplate.Execute(&buf, &pipelineEvent)
sendMessage(buf.String(), pipelineEvent.Project.Name, pipelineEvent.Project.Namespace, channelMapping)
m.sendMessage(buf.String(), pipelineEvent.Project.Name, pipelineEvent.Project.Namespace)
}

case "Job Hook":
Expand All @@ -292,7 +318,7 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
jobEvent.Status = JobStatus[jobEvent.Status]

err = jobCompleteTemplate.Execute(&buf, &jobEvent)
sendMessage(buf.String(), jobEvent.Repository.Name, namespace, channelMapping)
m.sendMessage(buf.String(), jobEvent.Repository.Name, namespace)

case "Merge Request Hook", "Merge Request Event":
log.Printf("Got Hook for a Merge Request")
Expand All @@ -306,7 +332,7 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {

err = mergeTemplate.Execute(&buf, &mergeEvent)

sendMessage(buf.String(), mergeEvent.Project.Name, mergeEvent.Project.Namespace, channelMapping)
m.sendMessage(buf.String(), mergeEvent.Project.Name, mergeEvent.Project.Namespace)

case "Issue Hook", "Issue Event":
log.Printf("Got Hook for an Issue")
Expand All @@ -320,7 +346,7 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {

err = issueTemplate.Execute(&buf, &issueEvent)

sendMessage(buf.String(), issueEvent.Project.Name, issueEvent.Project.Namespace, channelMapping)
m.sendMessage(buf.String(), issueEvent.Project.Name, issueEvent.Project.Namespace)

case "Push Hook", "Push Event":
log.Printf("Got Hook for a Push Event")
Expand All @@ -336,13 +362,13 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
// Branch was deleted
var buf bytes.Buffer
err = branchDeleteTemplate.Execute(&buf, &pushEvent)
sendMessage(buf.String(), pushEvent.Project.Name, pushEvent.Project.Namespace, channelMapping)
m.sendMessage(buf.String(), pushEvent.Project.Name, pushEvent.Project.Namespace)
} else {
if pushEvent.BeforeCommit == NullCommit {
// Branch was created
var buf bytes.Buffer
err = branchCreateTemplate.Execute(&buf, &pushEvent)
sendMessage(buf.String(), pushEvent.Project.Name, pushEvent.Project.Namespace, channelMapping)
m.sendMessage(buf.String(), pushEvent.Project.Name, pushEvent.Project.Namespace)
}

if pushEvent.TotalCommits > 0 {
Expand All @@ -356,7 +382,7 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
err = pushCompareTemplate.Execute(&buf, &pushEvent)
}

sendMessage(buf.String(), pushEvent.Project.Name, pushEvent.Project.Namespace, channelMapping)
m.sendMessage(buf.String(), pushEvent.Project.Name, pushEvent.Project.Namespace)

// Limit number of commit meessages to 3
if pushEvent.TotalCommits > 3 {
Expand All @@ -374,8 +400,8 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
}

context := CommitContext{
ShortID: commit.Id[0:7],
Message: html.UnescapeString(commit.Message),
ShortID: commit.ID[0:7],
Message: commit.Message,
Author: commit.Author,
AddedFiles: len(commit.Added),
ModifiedFiles: len(commit.Modified),
Expand All @@ -389,12 +415,12 @@ func gitlabHandler(c *viper.Viper) http.HandlerFunc {
log.Printf("ERROR: %v", err)
return
}
sendMessage(buf.String(), pushEvent.Project.Name, pushEvent.Project.Namespace, channelMapping)
m.sendMessage(buf.String(), pushEvent.Project.Name, pushEvent.Project.Namespace)
}

if pushEvent.TotalCommits > 3 {
var message = fmt.Sprintf("and %d more commits.", pushEvent.TotalCommits-3)
sendMessage(message, pushEvent.Project.Name, pushEvent.Project.Namespace, channelMapping)
m.sendMessage(message, pushEvent.Project.Name, pushEvent.Project.Namespace)
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion gitlab_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ func TestGitlabHandler(t *testing.T) {
}

rr := httptest.NewRecorder()
handler := http.HandlerFunc(gitlabHandler(viper.Sub("modules.gitlab")))
var gitlabModule Module = &GitlabModule{}
gitlabModule.init(viper.Sub("modules.gitlab"))
handler := http.HandlerFunc(gitlabModule.getHandler())

handler.ServeHTTP(rr, req)

Expand Down
17 changes: 12 additions & 5 deletions irc.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import (
"io/ioutil"
"log"
"strings"
"time"

"github.com/lrstanley/girc"
"github.com/spf13/viper"
)

var client *girc.Client

func ircConnection(config *viper.Viper) {
func ircConnection(config *viper.Viper, channelList []string) {
clientConfig := girc.Config{
Server: config.GetString("host"),
Port: config.GetInt("port"),
Expand Down Expand Up @@ -79,14 +80,20 @@ func ircConnection(config *viper.Viper) {
client = girc.New(clientConfig)

client.Handlers.Add(girc.CONNECTED, func(c *girc.Client, e girc.Event) {
c.Cmd.Whois(clientConfig.Nick)
for _, name := range channelList {
joinChannel(name)
}
})

// Start thread to process message queue
go channelReceiver()

if err := client.Connect(); err != nil {
log.Fatalf("An error occurred while attempting to connect to %s: %s", client.Server(), err)
for {
if err := client.Connect(); err != nil {
log.Printf("Connection to %s terminated: %s", client.Server(), err)
log.Printf("Reconnecting to %s in 30 seconds...", client.Server())
time.Sleep(30 * time.Second)
}
}

}
Expand All @@ -109,6 +116,6 @@ func joinChannel(newChannel string) {
return
}
}
fmt.Printf("Need to join new channel %s\n", newChannel)
fmt.Printf("Need to join new channel %q\n", newChannel)
client.Cmd.Join(newChannel)
}
Loading

0 comments on commit 69e8757

Please sign in to comment.