Skip to content
This repository has been archived by the owner on Oct 23, 2020. It is now read-only.

Commit

Permalink
refactor into sub package
Browse files Browse the repository at this point in the history
  • Loading branch information
sairam committed Jan 6, 2017
1 parent a6c6db8 commit 4dd881d
Show file tree
Hide file tree
Showing 29 changed files with 276 additions and 169 deletions.
2 changes: 2 additions & 0 deletions .codeclimate.yml
Expand Up @@ -14,3 +14,5 @@ engines:
ratings:
paths:
- "**.go"
exclude_paths:
- "**/**_test.go"
75 changes: 75 additions & 0 deletions .test.go
@@ -0,0 +1,75 @@
package main

// type Setting struct {
// Version string `yaml:"version"`
// Data map[string]Information `yaml:"fetched_info"`
// }
//
// type Information struct {
// RepoInformation `yaml:",inline"`
// OrgInformation `yaml:",inline"`
// Type string `yaml:"type"`
// }
//
// type OrgInformation struct {
// Name string `yaml:"org_name,omitempty"`
// RefType string `yaml:"org_type,omitempty"`
// }
//
// type RepoInformation struct {
// Tags []string `yaml:"tags,omitempty"`
// Branches []string `yaml:"branches,omitempty"`
// Commits interface{} `yaml:"commits,omitempty"`
// }

// func (i *Information) UnmarshalYAML(unmarshal func(interface{}) error) error {
// var slice struct {
// Type string `yaml:"type"`
// }
// unmarshal(&slice)
// if slice.Type == "test" {
// var r RepoInformation
// unmarshal(&r)
// fmt.Println(r)
// var a Information
// a.RepoInformation = r
// a.Type = "repo"
// *i = a
// // i.Data = &r
// } else {
// r := OrgInformation{"asiram", "user"}
// var a Information
// a.OrgInformation = r
// a.Type = "org"
// *i = a
// // unmarshal(&r)
//
// }
// return nil
// }
//

// func main() {
// c := &Setting{}
// data, err := ioutil.ReadFile("data/github/sairam/settings.yml")
// if os.IsNotExist(err) {
// fmt.Println(err)
// }
//
// err = yaml.Unmarshal(data, c)
// fmt.Println(err)
// // t := c.Data["minio/minio"].(RepoInformation)
// // fmt.Println(t)
// // t, _ := yaml.Marshal(c.Data["minio/minio"])
// // r := &RepoInformation{}
// // yaml.Unmarshal(t, r)
// // fmt.Println(r.Branches)
//
// fmt.Println(reflect.TypeOf(c.Data["avelino/awesome-go"].OrgInformation))
// fmt.Println(c.Data["avelino/awesome-go"])
//
// out, err := yaml.Marshal(c)
// fmt.Println(err)
// fmt.Println(string(out))
//
// }
8 changes: 8 additions & 0 deletions .travis.yml
@@ -0,0 +1,8 @@
language: go

go:
- master

addons:
code_climate:
repo_token: 363a0f3545bcbc246895864b449b6d8a0bbf6946925ef2c5c0232e9fcfb16a30
4 changes: 2 additions & 2 deletions auth.go → gitnotify/auth.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"errors"
Expand Down Expand Up @@ -53,7 +53,7 @@ func (userInfo *Authentication) getConfigFile() string {
return fmt.Sprintf("%s/%s", userInfo.getConfigDir(), config.SettingsFile)
}

func init() {
func initGoth() {
gothic.Store = store
gothic.GetProviderName = getProviderName
}
Expand Down
2 changes: 1 addition & 1 deletion changes.go → gitnotify/changes.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"compress/gzip"
Expand Down
8 changes: 6 additions & 2 deletions config.go → gitnotify/config.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"io/ioutil"
Expand Down Expand Up @@ -53,7 +53,7 @@ func (c *AppConfig) isEmailSetup() bool {

var config = new(AppConfig)

func loadConfig() {
func LoadConfig() {
if _, err := os.Stat(appConfigFile); os.IsNotExist(err) {
panic(err)
}
Expand Down Expand Up @@ -81,6 +81,10 @@ func loadConfig() {
}
}

initGoth()
initTmpl()
initSession()
initTZ()
preInitAuth()

// variables used by views
Expand Down
4 changes: 2 additions & 2 deletions cron.go → gitnotify/cron.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"fmt"
Expand Down Expand Up @@ -141,7 +141,7 @@ func startCronFor(cronEntry, filename string) {
runningCrons[filename] = id
}

func initCron() {
func InitCron() {
crons = cron.New()
crons.Start()

Expand Down
2 changes: 1 addition & 1 deletion github.go → gitnotify/github.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"errors"
Expand Down
2 changes: 1 addition & 1 deletion gitlab.go → gitnotify/gitlab.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"fmt"
Expand Down
2 changes: 1 addition & 1 deletion gitnull.go → gitnotify/gitnull.go
@@ -1,4 +1,4 @@
package main
package gitnotify

type localGitnull struct {
provider string
Expand Down
2 changes: 1 addition & 1 deletion gitremote.go → gitnotify/gitremote.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"errors"
Expand Down
12 changes: 11 additions & 1 deletion mail.go → gitnotify/mail.go
@@ -1,9 +1,10 @@
package main
package gitnotify

import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
"time"
)
Expand All @@ -17,6 +18,15 @@ type MailContent struct {
SavedFile string
}

// InitMailer initialises mailer if config is setup
func InitMailer() {
if config.isEmailSetup() {
go mailDaemon()
} else {
log.Print("Email is not configured")
}
}

func processForMail(diff gnDiffDatum, conf *Setting, fileName string) error {
if config.isEmailSetup() == false || !isValidEmail(conf.usersEmail()) {
return nil
Expand Down
2 changes: 1 addition & 1 deletion mailer.go → gitnotify/mailer.go
@@ -1,4 +1,4 @@
package main
package gitnotify

// Mail helper methods
import (
Expand Down
2 changes: 1 addition & 1 deletion page.go → gitnotify/page.go
@@ -1,4 +1,4 @@
package main
package gitnotify

//Page has all information about the page
type Page struct {
Expand Down
2 changes: 1 addition & 1 deletion repos.go → gitnotify/repos.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"fmt"
Expand Down
136 changes: 136 additions & 0 deletions gitnotify/routes.go
@@ -0,0 +1,136 @@
package gitnotify

import (
"fmt"
"log"
"net/http"
"strings"
"text/template"
"time"

"github.com/gorilla/mux"
)

const (
appConfigFile = "config.yml"
runModeDev = "dev"
gitRefBranch = "branches"
gitRefTag = "tags"
formUpdateString = "update"
)

var (
githubRepoEndPoint string
githubTreeURLEndPoint string
githubCommitURLEndPoint string
githubCompareURLEndPoint string

gitlabRepoEndPoint string
gitlabTreeURLEndPoint string
gitlabCommitURLEndPoint string
gitlabCompareURLEndPoint string
)

// InitRouter initialises the routes
func InitRouter() {
r := mux.NewRouter()
auth := r.PathPrefix("/auth").Subrouter()
initAuth(auth)

r.HandleFunc("/", settingsShowHandler).Methods("GET")
// POST is responsible for create, update and delete
r.HandleFunc("/", settingsSaveHandler).Methods("POST")
r.HandleFunc("/run", forceRunHandler).Methods("POST")

r.HandleFunc("/user", userSettingsShowHandler).Methods("GET")
r.HandleFunc("/user", userSettingsSaveHandler).Methods("POST")

r.HandleFunc("/typeahead/repo", repoTypeAheadHandler).Methods("GET")
r.HandleFunc("/typeahead/branch", branchTypeAheadHandler).Methods("GET")
r.HandleFunc("/typeahead/tz", timezoneTypeAheadHandler).Methods("GET")

r.HandleFunc("/changes", listAllDiffs).Methods("GET")
r.HandleFunc("/changes/", listAllDiffs).Methods("GET")
r.HandleFunc("/changes/{diffentry}", renderThisDiff).Methods("GET")

r.HandleFunc("/logout", func(res http.ResponseWriter, req *http.Request) {
hc := &httpContext{w: res, r: req}
hc.clearSession()

http.Redirect(res, req, homePageForNonLoggedIn, 302)
}).Methods("GET")

r.HandleFunc("/home", func(res http.ResponseWriter, req *http.Request) {
hc := &httpContext{w: res, r: req}
page := newPage(hc, "Get Daily Code Diffs from public Repositories", "Get Daily Code Diffs from Open Source Repositories", nil, nil)
displayPage(res, "home", page)
}).Methods("GET")

r.HandleFunc("/faq", func(res http.ResponseWriter, req *http.Request) {
hc := &httpContext{w: res, r: req}
page := newPage(hc, "Frequently Asked Questions", "Frequently Asked Questions", nil, nil)
displayPage(res, "faq", page)
}).Methods("GET")

r.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "favicon.ico")
})

r.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
http.ServeContent(w, r, "robots.txt", time.Now(), strings.NewReader("User-agent: *\nSitemap: /sitemap.xml"))
})

r.HandleFunc("/sitemap.xml", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/xml")
t, _ := template.New("foo").Parse(sitemapTemplate)
t.Execute(w, &struct {
Host string
Pages []string
Changed string
}{config.ServerProto + config.ServerHost, []string{"/", "/faq"}, time.Now().Format("2006-01-02T15:00:00-07:00")})
})

r.HandleFunc("/opensearch.xml", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/xml")
t, _ := template.New("foo").Parse(opensearchTemplate)
t.Execute(w, &struct{ Host string }{config.ServerProto + config.ServerHost})
})

r.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
d := fmt.Sprintf("status:%s\ntime:%s\n", "pong", time.Now())
http.ServeContent(w, r, "ping", time.Now(), strings.NewReader(d))
})

srv := &http.Server{
Handler: r,
Addr: config.LocalHost,
WriteTimeout: 60 * time.Second,
ReadTimeout: 60 * time.Second,
}

log.Fatal(srv.ListenAndServe())
}

var sitemapTemplate = `<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{{$host:=.Host}}
{{$changed:=.Changed}}
{{range $page:=.Pages}}
<url>
<loc>{{$host}}{{$page}}</loc>
<lastmod>{{$changed}}</lastmod>
</url>
{{end}}
</urlset>`

var opensearchTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
<ShortName>gitnotify</ShortName>
<Description>Track Code Diffs from Github &amp; Gitlab</Description>
<InputEncoding>UTF-8</InputEncoding>
<Tags>git notify gitnotify</Tags>
<Image height="16" width="16" type="image/x-icon">{{.Host}}/favicon.ico</Image>
<SearchForm>{{.Host}}</SearchForm>
<Url type="text/html" method="GET" template="{{.Host}}/?repo={searchTerms}&amp;utm_source=opensearch" />
<Query role="example" searchTerms="rails/rails" />
</OpenSearchDescription>`
2 changes: 1 addition & 1 deletion run.go → gitnotify/run.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"fmt"
Expand Down
4 changes: 2 additions & 2 deletions session.go → gitnotify/session.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"net/http"
Expand Down Expand Up @@ -29,7 +29,7 @@ var sv = map[string]string{
"token": "token",
}

func init() {
func initSession() {
// TODO mark session as httpOnly, secure
// http://www.gorillatoolkit.org/pkg/sessions#Options
store.Options = &sessions.Options{
Expand Down
2 changes: 1 addition & 1 deletion setting.go → gitnotify/setting.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"fmt"
Expand Down
2 changes: 1 addition & 1 deletion slackhook.go → gitnotify/slackhook.go
@@ -1,4 +1,4 @@
package main
package gitnotify

import (
"encoding/json"
Expand Down
2 changes: 1 addition & 1 deletion stringify.go → gitnotify/stringify.go
@@ -1,4 +1,4 @@
package main
package gitnotify

// Source: https://github.com/google/go-github/blob/master/github/strings.go

Expand Down

0 comments on commit 4dd881d

Please sign in to comment.