<commit_before>package ginServer

import (
	"encoding/json"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"strings"
)

type ErrorResponse struct {
	Message string `json:"message"`
}

type LocaleLanguage struct {
	Locale   string
	Language string
}

func GetSessionKey(c *gin.Context, key string) string {
	session := sessions.Default(c)
	value := session.Get(key)
	if value == nil {
		return ""
	} else {
		return session.Get(key).(string)
	}
}

func SetSessionKey(c *gin.Context, key string, value string) {
	session := sessions.Default(c)
	session.Set(key, value)
	session.Save()
}

func SaveSession(c *gin.Context) {
	session := sessions.Default(c)
	session.Save()
}

func ClearSession(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
}

func GetLocaleLanguage(c *gin.Context) (ll LocaleLanguage) {
	header := c.Request.Header.Get("Accept-Language")
	locals := strings.Split(header, ",")
	localsSplit := strings.Split(locals[0], "-")
	ll.Language = localsSplit[0]
	ll.Locale = localsSplit[1]
	return
}

func GetRequestBody(c *gin.Context) ([]byte, error) {
	body := c.Request.Body
	return ioutil.ReadAll(body)
}

// Reads a file from the path parameter and returns to the client as text/html.
func ReadHTMLFile(path string, c *gin.Context) {
	page, err := ioutil.ReadFile(path)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	pageHTML := string(page)

	c.Header("Content-Type", "text/html")
	c.String(http.StatusOK, pageHTML)
}

func ReadJSFile(path string, c *gin.Context) {
	page, err := ioutil.ReadFile(path)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	pageHTML := string(page)

	c.Header("Content-Type", "text/javascript")
	c.String(http.StatusOK, pageHTML)
}

// Takes a string and returns to the client as text/html.
func RenderHTML(html string, c *gin.Context) {
	c.Header("Content-Type", "text/html")
	c.String(http.StatusOK, html)
}

// Reads a file from the path parameter and returns to the client application/json
func ReadJSONFile(path string, c *gin.Context) {
	js, err := ioutil.ReadFile(path)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	c.Header("Content-Type", "application/json")
	c.Writer.Write(js)
}

// Returns to the client application/json format for the passed interface.
func RespondJSON(v interface{}, c *gin.Context) {

	if v == nil {
		c.JSON(http.StatusNotFound, v)
		return
	}
	c.JSON(http.StatusOK, v)
}

//  Returns an byte array comprised of a JSON formated object with the error message.
func RespondError(message string) []byte {
	var msg ErrorResponse
	msg.Message = message
	b, _ := json.Marshal(msg)
	return b
}

func ReadGzipJSFile(path string, c *gin.Context) {

	c.Header("Content-Type", "application/javascript")
	c.Header("Content-Encoding", "gzip")
	c.File(path)

}

func ReadGzipCSSFile(path string, c *gin.Context) {

	c.Header("Content-Type", "text/css")
	c.Header("Content-Encoding", "gzip")
	c.File(path)

}

func ReadPngFile(path string, c *gin.Context) {

	c.Header("Content-Type", "image/png")
	c.File(path)

}
<commit_msg>Fix Language Header parsing.<commit_after>package ginServer

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
)

type ErrorResponse struct {
	Message string `json:"message"`
}

type LocaleLanguage struct {
	Locale   string
	Language string
}

func GetSessionKey(c *gin.Context, key string) string {
	session := sessions.Default(c)
	value := session.Get(key)
	if value == nil {
		return ""
	} else {
		return session.Get(key).(string)
	}
}

func SetSessionKey(c *gin.Context, key string, value string) {
	session := sessions.Default(c)
	session.Set(key, value)
	session.Save()
}

func SaveSession(c *gin.Context) {
	session := sessions.Default(c)
	session.Save()
}

func ClearSession(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
}

func GetLocaleLanguage(c *gin.Context) (ll LocaleLanguage) {
	header := c.Request.Header.Get("Accept-Language")
	allLanguages := strings.Split(header, ";")

	locals := strings.Split(allLanguages[0], ",")
	localsSplit := strings.Split(locals[0], "-")

	if len(localsSplit) == 1 && len(locals) == 2 {
		localsSplit = strings.Split(locals[1], "-")
	}

	ll.Language = localsSplit[0]
	if len(localsSplit) == 2 {
		ll.Locale = localsSplit[1]
	}
	return
}

func GetRequestBody(c *gin.Context) ([]byte, error) {
	body := c.Request.Body
	return ioutil.ReadAll(body)
}

// Reads a file from the path parameter and returns to the client as text/html.
func ReadHTMLFile(path string, c *gin.Context) {
	page, err := ioutil.ReadFile(path)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	pageHTML := string(page)

	c.Header("Content-Type", "text/html")
	c.String(http.StatusOK, pageHTML)
}

func ReadJSFile(path string, c *gin.Context) {
	page, err := ioutil.ReadFile(path)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	pageHTML := string(page)

	c.Header("Content-Type", "text/javascript")
	c.String(http.StatusOK, pageHTML)
}

// Takes a string and returns to the client as text/html.
func RenderHTML(html string, c *gin.Context) {
	c.Header("Content-Type", "text/html")
	c.String(http.StatusOK, html)
}

// Reads a file from the path parameter and returns to the client application/json
func ReadJSONFile(path string, c *gin.Context) {
	js, err := ioutil.ReadFile(path)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	c.Header("Content-Type", "application/json")
	c.Writer.Write(js)
}

// Returns to the client application/json format for the passed interface.
func RespondJSON(v interface{}, c *gin.Context) {

	if v == nil {
		c.JSON(http.StatusNotFound, v)
		return
	}
	c.JSON(http.StatusOK, v)
}

//  Returns an byte array comprised of a JSON formated object with the error message.
func RespondError(message string) []byte {
	var msg ErrorResponse
	msg.Message = message
	b, _ := json.Marshal(msg)
	return b
}

func ReadGzipJSFile(path string, c *gin.Context) {

	c.Header("Content-Type", "application/javascript")
	c.Header("Content-Encoding", "gzip")
	c.File(path)

}

func ReadGzipCSSFile(path string, c *gin.Context) {

	c.Header("Content-Type", "text/css")
	c.Header("Content-Encoding", "gzip")
	c.File(path)

}

func ReadPngFile(path string, c *gin.Context) {

	c.Header("Content-Type", "image/png")
	c.File(path)

}
<|endoftext|>


<commit_before>package check

import (
	"bytes"
	"os/exec"
)

// License is the check for the existance of a license file
type License struct {
	Dir       string
	Filenames []string
}

// Name returns the name of the display name of the command
func (g License) Name() string {
	return "license"
}

// Weight returns the weight this check has in the overall average
func (g License) Weight() float64 {
	return .10
}

// Percentage returns 0 if no LICENSE, 1 if LICENSE
func (g License) Percentage() (float64, []FileSummary, error) {
	cmd := exec.Command("find", g.Dir, "-maxdepth", "1", "-type", "f", "-name", "LICENSE*")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return 0.0, []FileSummary{}, err
	}
	if out.String() == "" {
		return 0.0, []FileSummary{{"", "http://choosealicense.com/", []Error{}}}, nil
	}

	return 1.0, []FileSummary{}, nil
}

// Description returns the description of License
func (g License) Description() string {
	return "Checks whether your project has a LICENSE file."
}
<commit_msg>fix typo<commit_after>package check

import (
	"bytes"
	"os/exec"
)

// License is the check for the existence of a license file
type License struct {
	Dir       string
	Filenames []string
}

// Name returns the name of the display name of the command
func (g License) Name() string {
	return "license"
}

// Weight returns the weight this check has in the overall average
func (g License) Weight() float64 {
	return .10
}

// Percentage returns 0 if no LICENSE, 1 if LICENSE
func (g License) Percentage() (float64, []FileSummary, error) {
	cmd := exec.Command("find", g.Dir, "-maxdepth", "1", "-type", "f", "-name", "LICENSE*")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return 0.0, []FileSummary{}, err
	}
	if out.String() == "" {
		return 0.0, []FileSummary{{"", "http://choosealicense.com/", []Error{}}}, nil
	}

	return 1.0, []FileSummary{}, nil
}

// Description returns the description of License
func (g License) Description() string {
	return "Checks whether your project has a LICENSE file."
}
<|endoftext|>


<commit_before>package main

// commandline tool to grab, scrape and output a news article
// NOTE: currently assumes you've got a local http proxy running,
// to cache articles.
// I use squid, tweaked to cache for an hour or two, even if the web site
// says not to (which is really common. A lot of newspapers think the little
// clock in their page header is vitally important ;-)
// The idea is that the cachine proxy will be used by both article scraping,
// and article discovery (and maybe for other operations too). So if you need
// to crawl a site to find article, you won't need to hit the server again if
// the articles were part of the crawl.
//
// for now, I'm using this in my squid.conf:
//   refresh_pattern ^http: 60 20% 4320 ignore-no-cache ignore-no-store override-expire
//
//
import (
	"errors"
	"flag"
	"fmt"
	"github.com/bcampbell/arts"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
)

// quote a string for yaml output
func quote(s string) string {
	if strings.ContainsAny(s, `:|`) {
		if !strings.Contains(s, `"`) {
			return fmt.Sprintf(`"%s"`, s)
		} else {
			if strings.Contains(s, "'") {
				s = strings.Replace(s, "'", "''", -1)
			}
			return fmt.Sprintf(`'%s'`, s)
		}
	}
	return s
}

func main() {
	var debug string
	flag.StringVar(&debug, "d", "", "log debug info to stderr (h=headline, c=content, a=authors d=dates all=hcad)")
	flag.Parse()

	if len(flag.Args()) != 1 {
		fmt.Println("Usage: ", os.Args[0], "<article url>")
		os.Exit(1)
	}

	artURL := flag.Arg(0)
	u, err := url.Parse(artURL)
	if err != nil {
		panic(err)
	}

	// set up the debug logging
	debug = strings.ToLower(debug)
	if debug == "name" {
		debug = ""
	}
	if debug == "all" {
		debug = "hcad"
	}
	for _, flag := range debug {
		switch flag {
		case 'h':
			arts.Debug.HeadlineLogger = log.New(os.Stderr, "", 0)
		case 'c':
			arts.Debug.ContentLogger = log.New(os.Stderr, "", 0)
		case 'a':
			arts.Debug.AuthorsLogger = log.New(os.Stderr, "", 0)
		case 'd':
			arts.Debug.DatesLogger = log.New(os.Stderr, "", 0)
		}
	}

	var in io.ReadCloser
	switch strings.ToLower(u.Scheme) {
	case "http", "https":
		in, err = openHttp(artURL)
		if err != nil {
			panic(err)
		}
	case "file", "":
		in, err = os.Open(u.Path)
		if err != nil {
			panic(err)
		}
	}

	defer in.Close()
	raw_html, err := ioutil.ReadAll(in)
	if err != nil {
		panic(err)
	}

	art, err := arts.Extract(raw_html, artURL)
	if err != nil {
		panic(err)
	}

	writeYaml(os.Stdout, artURL, art)
}

func openHttp(artURL string) (io.ReadCloser, error) {
	proxyString := "http://localhost:3128"
	proxyURL, err := url.Parse(proxyString)
	if err != nil {
		return nil, err
	}

	transport := &http.Transport{Proxy: http.ProxyURL(proxyURL)}
	client := &http.Client{Transport: transport}

	request, err := http.NewRequest("GET", artURL, nil)
	if err != nil {
		return nil, err
	}
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}

	if response.StatusCode != 200 {
		return nil, errors.New(fmt.Sprintf("Request failed: %s", response.Status))
	}
	return response.Body, nil
}

// The plan is to store a big set of example articles in this format:
// YAML front matter (like in jekyll), with headline, authors etc...
// The rest of the file has the expected article text.
func writeYaml(w io.Writer, url string, art *arts.Article) {
	// yaml front matter
	fmt.Fprintf(w, "---\n")
	fmt.Fprintf(w, "canonical_url: %s\n", quote(art.CanonicalUrl))
	if len(art.AlternateUrls) > 0 {
		fmt.Fprintf(w, "alternate_urls:\n")
		for _, url := range art.AlternateUrls {
			fmt.Fprintf(w, "  - %s\n", quote(url))
		}
	}
	fmt.Fprintf(w, "headline: %s\n", quote(art.Headline))
	if len(art.Authors) > 0 {
		fmt.Fprintf(w, "authors:\n")
		for _, author := range art.Authors {
			fmt.Fprintf(w, "  - name: %s\n", quote(author.Name))
		}
	}
	if art.Published != "" {
		fmt.Fprintf(w, "published: %s\n", art.Published)
	}
	if art.Updated != "" {
		fmt.Fprintf(w, "updated: %s\n", art.Updated)
	}
	fmt.Fprintf(w, "---\n")
	// the text content
	fmt.Fprint(w, art.Content)
}
<commit_msg>add profiling support<commit_after>package main

// commandline tool to grab, scrape and output a news article
// NOTE: currently assumes you've got a local http proxy running,
// to cache articles.
// I use squid, tweaked to cache for an hour or two, even if the web site
// says not to (which is really common. A lot of newspapers think the little
// clock in their page header is vitally important ;-)
// The idea is that the cachine proxy will be used by both article scraping,
// and article discovery (and maybe for other operations too). So if you need
// to crawl a site to find article, you won't need to hit the server again if
// the articles were part of the crawl.
//
// for now, I'm using this in my squid.conf:
//   refresh_pattern ^http: 60 20% 4320 ignore-no-cache ignore-no-store override-expire
//
//
import (
	"errors"
	"flag"
	"fmt"
	"github.com/bcampbell/arts"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"runtime/pprof"
	"strings"
)

// quote a string for yaml output
func quote(s string) string {
	if strings.ContainsAny(s, `:|`) {
		if !strings.Contains(s, `"`) {
			return fmt.Sprintf(`"%s"`, s)
		} else {
			if strings.Contains(s, "'") {
				s = strings.Replace(s, "'", "''", -1)
			}
			return fmt.Sprintf(`'%s'`, s)
		}
	}
	return s
}

func main() {
	var debug string
	flag.StringVar(&debug, "d", "", "log debug info to stderr (h=headline, c=content, a=authors d=dates all=hcad)")
	var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
	flag.Parse()

	if len(flag.Args()) != 1 {
		fmt.Println("Usage: ", os.Args[0], "<article url>")
		os.Exit(1)
	}

	artURL := flag.Arg(0)
	u, err := url.Parse(artURL)
	if err != nil {
		panic(err)
	}

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	// set up the debug logging
	debug = strings.ToLower(debug)
	if debug == "name" {
		debug = ""
	}
	if debug == "all" {
		debug = "hcad"
	}
	for _, flag := range debug {
		switch flag {
		case 'h':
			arts.Debug.HeadlineLogger = log.New(os.Stderr, "", 0)
		case 'c':
			arts.Debug.ContentLogger = log.New(os.Stderr, "", 0)
		case 'a':
			arts.Debug.AuthorsLogger = log.New(os.Stderr, "", 0)
		case 'd':
			arts.Debug.DatesLogger = log.New(os.Stderr, "", 0)
		}
	}

	var in io.ReadCloser
	switch strings.ToLower(u.Scheme) {
	case "http", "https":
		in, err = openHttp(artURL)
		if err != nil {
			panic(err)
		}
	case "file", "":
		in, err = os.Open(u.Path)
		if err != nil {
			panic(err)
		}
	}

	defer in.Close()
	raw_html, err := ioutil.ReadAll(in)
	if err != nil {
		panic(err)
	}

	art, err := arts.Extract(raw_html, artURL)
	if err != nil {
		panic(err)
	}

	writeYaml(os.Stdout, artURL, art)
}

func openHttp(artURL string) (io.ReadCloser, error) {
	proxyString := "http://localhost:3128"
	proxyURL, err := url.Parse(proxyString)
	if err != nil {
		return nil, err
	}

	transport := &http.Transport{Proxy: http.ProxyURL(proxyURL)}
	client := &http.Client{Transport: transport}

	request, err := http.NewRequest("GET", artURL, nil)
	if err != nil {
		return nil, err
	}
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}

	if response.StatusCode != 200 {
		return nil, errors.New(fmt.Sprintf("Request failed: %s", response.Status))
	}
	return response.Body, nil
}

// The plan is to store a big set of example articles in this format:
// YAML front matter (like in jekyll), with headline, authors etc...
// The rest of the file has the expected article text.
func writeYaml(w io.Writer, url string, art *arts.Article) {
	// yaml front matter
	fmt.Fprintf(w, "---\n")
	fmt.Fprintf(w, "canonical_url: %s\n", quote(art.CanonicalUrl))
	if len(art.AlternateUrls) > 0 {
		fmt.Fprintf(w, "alternate_urls:\n")
		for _, url := range art.AlternateUrls {
			fmt.Fprintf(w, "  - %s\n", quote(url))
		}
	}
	fmt.Fprintf(w, "headline: %s\n", quote(art.Headline))
	if len(art.Authors) > 0 {
		fmt.Fprintf(w, "authors:\n")
		for _, author := range art.Authors {
			fmt.Fprintf(w, "  - name: %s\n", quote(author.Name))
		}
	}
	if art.Published != "" {
		fmt.Fprintf(w, "published: %s\n", art.Published)
	}
	if art.Updated != "" {
		fmt.Fprintf(w, "updated: %s\n", art.Updated)
	}
	fmt.Fprintf(w, "---\n")
	// the text content
	fmt.Fprint(w, art.Content)
}
<|endoftext|>


<commit_before>package appcast

import (
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestNewChecksum(t *testing.T) {
	// SHA256
	c := NewChecksum(Sha256, "test")
	assert.IsType(t, Checksum{}, *c)
	assert.Equal(t, Sha256, c.Algorithm)
	assert.Equal(t, "test", c.Source)
	assert.Equal(t, "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", c.Result)
}

func TestGenerate(t *testing.T) {
	testCases := map[string][]string{
		"sourceforge_default.xml": []string{
			"cf45ae9ba4be292c198c30663bd6bf76e3b66260b2675d5a699f10953c251288",
			"1eed329e29aa768b242d23361adf225a654e7df74d58293a44d14862ef7ef975",
			"75b31fefbd17e918078477236035a54a",
		},
		"sourceforge_empty.xml": []string{
			"b6ee64001ab00dbedea8fede21abb78d011c36e38bbd5aaa1004872df170c022",
			"568863d4a2540349db3987320525303f7cdd26bba6e0cada704ce2191afc9ae5",
			"30eaf5f22d3fa94b017581681886b77a",
		},
		"sourceforge_single.xml": []string{
			"fb59e0dba21bb8ec56d73de0f9af56547ed1951842eb682dddcb1ce453ee5443",
			"aae4e241300ef6abaf1d855b3acc613344541207159cf85064124f0a207e37ab",
			"1c177e9949f45af03df6bb83e4eeb979",
		},
		"sparkle_attributes_as_elements.xml": []string{
			"898628bcbf1005995c4a1e8200f6336da11fae771fc724f8fc7a9cfde8f4e85e",
			"06a16fc0d5c7f8e18ca04dbc52138159b5438cdb929e033dae6ddebca7e710fc",
			"05d4e5b0b4d005e3512a7bc24bb94925",
		},
		"sparkle_default_asc.xml": []string{
			"9e319d5eb9929ea069a7db81d8b46e403f05ada0dec5a4601c552a2ab08cca27",
			"8ad0cd8d67f12ed75fdfbf74e904ef8b82084875c959bec00abd5a166c512b5d",
			"da2bc13c30e16a585c0a012bcae110d5",
		},
		"sparkle_default.xml": []string{
			"3401290b3e7d32d01653c10668a34d53862d81f8046d7e5988bdd8b54443c2c4",
			"583743f5e8662cb223baa5e718224fa11317b0983dbf8b3c9c8d412600b6936c",
			"279ea1e0dc339ef3d04a1b9e4fd4dd82",
		},
		"sparkle_incorrect_namespace.xml": []string{
			"798f122b491661373cc207753dd7571590bb910860ce57ca9f3ee1ed2f9e197c",
			"f7ced8023765dc7f37c3597da7a1f8d33b3c22cc764e329babd3df16effdd245",
			"b473e0071d84b60d516e518a111d849f",
		},
		"sparkle_multiple_enclosure.xml": []string{
			"48fc8531b253c5d3ed83abfe040edeeafb327d103acbbacf12c2288769dc80b9",
			"6ba0ab0e37d4280803ff2f197aaf362a3553849fb296a64bc946eda1bdb759c7",
			"9f1c1a667efc3080f1dcf020eca97c7b",
		},
		"sparkle_no_releases.xml": []string{
			"65911706576dab873c2b30b2d6505581d17f8e2c763da7320cfb06bbc2d4eaca",
			"65911706576dab873c2b30b2d6505581d17f8e2c763da7320cfb06bbc2d4eaca",
			"f63b85384e4c7fff3ebc14017d2edcdd",
		},
		"sparkle_single.xml": []string{
			"12be6a3f8d15a049e030ea09c176321278867c05742f5c2cd87aa2c368b11713",
			"98c94ba87d4eb1d99b56652b537a26d3c68efa7efa5f497839a3832a31147a7a",
			"ce7be28ec30341d08d0b4b6f24ea5c28",
		},
		"sparkle_without_comments.xml": []string{
			"fecbdf715eef8e743cd720d1d7799e12d569349228d3d3357cb47fee0532fec3",
			"88ceb464f652d7bf43f351f41637facd671f8f04e9a32b4b077886d24251e472",
			"f54aa1aaf762e95f86ec768f7c2e98c3",
		},
		"sparkle_without_namespaces.xml": []string{
			"a3f5c793c6e72f6b2cf5a24b35d8bb26b424441b22a6186c81ddc508fe0f2ae2",
			"d4cdd55c6dbf944d03c5267f3f7be4a9f7c2f1b94929359ce7e21aeef3b0747b",
			"89d619d29be8e5b03fed41465b22591e",
		},
		"unknown.xml": []string{
			"a4161a72df970e6fca434e2b9e256b850f12d2934cdde057985b77ea892f35d8",
			"a4161a72df970e6fca434e2b9e256b850f12d2934cdde057985b77ea892f35d8",
			"492a7260f7f43fef03d72ccffd4d27bf",
		},
	}

	for filename, checkpoints := range testCases {
		content := string(getTestdata(filename))

		// SHA256
		c := &Checksum{Sha256, content, ""}
		assert.Equal(t, checkpoints[0], c.Generate(), fmt.Sprintf("Checksum doesn't match (Sha256): %s", filename))

		// SHA256 (Homebrew-Cask)
		c = &Checksum{Sha256HomebrewCask, content, ""}
		assert.Equal(t, checkpoints[1], c.Generate(), fmt.Sprintf("Checksum doesn't match (Sha256HomebrewCask): %s", filename))

		// MD5
		c = &Checksum{Md5, content, ""}
		assert.Equal(t, checkpoints[2], c.Generate(), fmt.Sprintf("Checksum doesn't match (Md5): %s", filename))
	}
}
<commit_msg>Add sparkle_invalid_version.xml in checksum tests<commit_after>package appcast

import (
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestNewChecksum(t *testing.T) {
	c := NewChecksum(Sha256, "test")
	assert.IsType(t, Checksum{}, *c)
	assert.Equal(t, Sha256, c.Algorithm)
	assert.Equal(t, "test", c.Source)
	assert.Equal(t, "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", c.Result)
}

func TestGenerate(t *testing.T) {
	testCases := map[string][]string{
		"sourceforge_default.xml": {
			"cf45ae9ba4be292c198c30663bd6bf76e3b66260b2675d5a699f10953c251288",
			"1eed329e29aa768b242d23361adf225a654e7df74d58293a44d14862ef7ef975",
			"75b31fefbd17e918078477236035a54a",
		},
		"sourceforge_empty.xml": {
			"b6ee64001ab00dbedea8fede21abb78d011c36e38bbd5aaa1004872df170c022",
			"568863d4a2540349db3987320525303f7cdd26bba6e0cada704ce2191afc9ae5",
			"30eaf5f22d3fa94b017581681886b77a",
		},
		"sourceforge_single.xml": {
			"fb59e0dba21bb8ec56d73de0f9af56547ed1951842eb682dddcb1ce453ee5443",
			"aae4e241300ef6abaf1d855b3acc613344541207159cf85064124f0a207e37ab",
			"1c177e9949f45af03df6bb83e4eeb979",
		},
		"sparkle_attributes_as_elements.xml": {
			"898628bcbf1005995c4a1e8200f6336da11fae771fc724f8fc7a9cfde8f4e85e",
			"06a16fc0d5c7f8e18ca04dbc52138159b5438cdb929e033dae6ddebca7e710fc",
			"05d4e5b0b4d005e3512a7bc24bb94925",
		},
		"sparkle_default_asc.xml": {
			"9e319d5eb9929ea069a7db81d8b46e403f05ada0dec5a4601c552a2ab08cca27",
			"8ad0cd8d67f12ed75fdfbf74e904ef8b82084875c959bec00abd5a166c512b5d",
			"da2bc13c30e16a585c0a012bcae110d5",
		},
		"sparkle_default.xml": {
			"3401290b3e7d32d01653c10668a34d53862d81f8046d7e5988bdd8b54443c2c4",
			"583743f5e8662cb223baa5e718224fa11317b0983dbf8b3c9c8d412600b6936c",
			"279ea1e0dc339ef3d04a1b9e4fd4dd82",
		},
		"sparkle_incorrect_namespace.xml": {
			"798f122b491661373cc207753dd7571590bb910860ce57ca9f3ee1ed2f9e197c",
			"f7ced8023765dc7f37c3597da7a1f8d33b3c22cc764e329babd3df16effdd245",
			"b473e0071d84b60d516e518a111d849f",
		},
		"sparkle_invalid_version.xml": {
			"5678aee518c7aaeed32bf8b8ff836d946e3baa415bc36824cc6bf4c90a96d7f3",
			"ac8bf225fb789f8174fccf26b52cde07b884e26e89546ab3ad9433cbe38ecb20",
			"a3d2cb7053b25a811f216d486469f30a",
		},
		"sparkle_multiple_enclosure.xml": {
			"48fc8531b253c5d3ed83abfe040edeeafb327d103acbbacf12c2288769dc80b9",
			"6ba0ab0e37d4280803ff2f197aaf362a3553849fb296a64bc946eda1bdb759c7",
			"9f1c1a667efc3080f1dcf020eca97c7b",
		},
		"sparkle_no_releases.xml": {
			"65911706576dab873c2b30b2d6505581d17f8e2c763da7320cfb06bbc2d4eaca",
			"65911706576dab873c2b30b2d6505581d17f8e2c763da7320cfb06bbc2d4eaca",
			"f63b85384e4c7fff3ebc14017d2edcdd",
		},
		"sparkle_single.xml": {
			"12be6a3f8d15a049e030ea09c176321278867c05742f5c2cd87aa2c368b11713",
			"98c94ba87d4eb1d99b56652b537a26d3c68efa7efa5f497839a3832a31147a7a",
			"ce7be28ec30341d08d0b4b6f24ea5c28",
		},
		"sparkle_without_comments.xml": {
			"fecbdf715eef8e743cd720d1d7799e12d569349228d3d3357cb47fee0532fec3",
			"88ceb464f652d7bf43f351f41637facd671f8f04e9a32b4b077886d24251e472",
			"f54aa1aaf762e95f86ec768f7c2e98c3",
		},
		"sparkle_without_namespaces.xml": {
			"a3f5c793c6e72f6b2cf5a24b35d8bb26b424441b22a6186c81ddc508fe0f2ae2",
			"d4cdd55c6dbf944d03c5267f3f7be4a9f7c2f1b94929359ce7e21aeef3b0747b",
			"89d619d29be8e5b03fed41465b22591e",
		},
		"unknown.xml": {
			"a4161a72df970e6fca434e2b9e256b850f12d2934cdde057985b77ea892f35d8",
			"a4161a72df970e6fca434e2b9e256b850f12d2934cdde057985b77ea892f35d8",
			"492a7260f7f43fef03d72ccffd4d27bf",
		},
	}

	for filename, checkpoints := range testCases {
		content := string(getTestdata(filename))

		// SHA256
		c := &Checksum{Sha256, content, ""}
		assert.Equal(t, checkpoints[0], c.Generate(), fmt.Sprintf("Checksum doesn't match (Sha256): %s", filename))

		// SHA256 (Homebrew-Cask)
		c = &Checksum{Sha256HomebrewCask, content, ""}
		assert.Equal(t, checkpoints[1], c.Generate(), fmt.Sprintf("Checksum doesn't match (Sha256HomebrewCask): %s", filename))

		// MD5
		c = &Checksum{Md5, content, ""}
		assert.Equal(t, checkpoints[2], c.Generate(), fmt.Sprintf("Checksum doesn't match (Md5): %s", filename))
	}
}
<|endoftext|>


<commit_before>package negotiator

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestShouldProcessJSONAcceptHeader(t *testing.T) {
	var fibTests = []struct {
		acceptheader string // input
	}{
		{"application/json"},
		{"application/json-"},
		{"text/json"},
		{"+json"},
	}

	jsonProcessor := &JSONProcessor{}

	for _, tt := range fibTests {
		result := jsonProcessor.CanProcess(tt.acceptheader)
		assert.True(t, result, "Should process "+tt.acceptheader)
	}
}
<commit_msg>renamed variable in test<commit_after>package negotiator

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestShouldProcessJSONAcceptHeader(t *testing.T) {
	var acceptTests = []struct {
		acceptheader string // input
	}{
		{"application/json"},
		{"application/json-"},
		{"text/json"},
		{"+json"},
	}

	jsonProcessor := &JSONProcessor{}

	for _, tt := range acceptTests {
		result := jsonProcessor.CanProcess(tt.acceptheader)
		assert.True(t, result, "Should process "+tt.acceptheader)
	}
}
<|endoftext|>


<commit_before>package osc

import (
	"net"
	"testing"
)

func TestInvalidAddress(t *testing.T) {
	dispatcher := map[string]Method{
		"/address*/test": func(msg Message) error {
			return nil
		},
	}
	laddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	server, err := ListenUDP("udp", laddr)
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = server.Close() }() // Best effort.

	if err := server.Serve(dispatcher); err != ErrInvalidAddress {
		t.Fatal("expected invalid address error")
	}
	if server != nil {
		_ = server.Close()
	}
}

func TestMessageDispatching(t *testing.T) {
	// dispatcher := map[string]Method{
	// 	"/address/test": func(msg *Message) error {
	// 		val, err := msg.ReadInt32()
	// 		if err != nil {
	// 			return err
	// 		}
	// 		if expected, got := int32(1122), val; expected != got {
	// 			return fmt.Errorf("Expected %d got %d", expected, got)
	// 		}
	// 		return nil
	// 	},
	// }

	laddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}

	server, err := ListenUDP("udp", laddr)
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = server.Close() }() // Best effort.
}

func TestSend(t *testing.T) {
	// var (
	// 	doneChan = make(chan *Message)
	// 	errChan  = make(chan error, 1)
	// )

	// dispatcher := map[string]Method{
	// 	"/osc/address": func(msg *Message) error {
	// 		doneChan <- msg
	// 		return nil
	// 	},
	// }

	// laddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
	// if err != nil {
	// 	t.Fatal(err)
	// }

	// server, err := ListenUDP("udp", laddr)
	// if err != nil {
	// 	t.Fatal(err)
	// }
	// defer func() { _ = server.Close() }() // Best effort.

	// go func() {
	// 	errChan <- server.Serve(dispatcher) // Best effort.
	// }()

	// serverAddr := server.LocalAddr()
	// raddr, err := net.ResolveUDPAddr(serverAddr.Network(), serverAddr.String())
	// if err != nil {
	// 	t.Fatal(err)
	// }

	// client, err := DialUDP("udp", nil, raddr)
	// if err != nil {
	// 	t.Fatal(err)
	// }

	// msg, err := NewMessage("/osc/address")
	// if err != nil {
	// 	t.Fatal(err)
	// }
	// if err := msg.WriteInt32(111); err != nil {
	// 	t.Fatal(err)
	// }
	// if err := msg.WriteBool(true); err != nil {
	// 	t.Fatal(err)
	// }
	// if err := msg.WriteString("hello"); err != nil {
	// 	t.Fatal(err)
	// }

	// // Send a message.
	// if err := client.Send(msg); err != nil {
	// 	t.Fatal(err)
	// }

	// select {
	// default:
	// case err := <-errChan:
	// 	if err != nil {
	// 		t.Fatal(err)
	// 	}
	// }

	// recvMsg := <-doneChan

	// recvData, err := recvMsg.Contents()
	// if err != nil {
	// 	t.Fatal(err)
	// }

	// data, err := msg.Contents()
	// if err != nil {
	// 	t.Fatal(err)
	// }

	// if 0 != bytes.Compare(data, recvData[0:len(data)]) {
	// 	t.Fatalf("Expected %s got %s", data, recvData)
	// }
}
<commit_msg>removed a bunch of commented-out test code<commit_after>package osc

import (
	"net"
	"testing"
)

func TestInvalidAddress(t *testing.T) {
	dispatcher := map[string]Method{
		"/address*/test": func(msg Message) error {
			return nil
		},
	}
	laddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	server, err := ListenUDP("udp", laddr)
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = server.Close() }() // Best effort.

	if err := server.Serve(dispatcher); err != ErrInvalidAddress {
		t.Fatal("expected invalid address error")
	}
	if server != nil {
		_ = server.Close()
	}
}

func TestMessageDispatching(t *testing.T) {
	laddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}

	server, err := ListenUDP("udp", laddr)
	if err != nil {
		t.Fatal(err)
	}
	defer func() { _ = server.Close() }() // Best effort.
}

func TestSend(t *testing.T) {
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/koding/asgd"
	"github.com/koding/logging"
	"github.com/koding/multiconfig"
)

const Name = "asgd"

func main() {

	conf := &asgd.Config{}
	mc := multiconfig.New()
	mc.Loader = multiconfig.MultiLoader(
		&multiconfig.TagLoader{},
		&multiconfig.EnvironmentLoader{},
		&multiconfig.EnvironmentLoader{Prefix: "ASGD"},
		&multiconfig.FlagLoader{},
	)

	mc.MustLoad(conf)

	session, err := asgd.Configure(conf)
	if err != nil {
		log.Fatal("Reading config failed: ", err.Error())
	}

	log := logging.NewCustom(Name, conf.Debug)
	// remove formatting from call stack and output correct line
	log.SetCallDepth(1)

	// create lifecycle
	l := asgd.NewLifeCycle(session, log, conf.AutoScalingName)

	// configure lifecycle with system name
	if err := l.Configure(conf.Name); err != nil {
		log.Fatal(err.Error())
	}

	done := registerSignalHandler(l, log)

	// listen to lifecycle events
	if err := l.Listen(process); err != nil {
		log.Fatal(err.Error())
	}

	<-done
}

func process(instances []*ec2.Instance) error {
	return nil
}

func registerSignalHandler(l *asgd.LifeCycle, log logging.Logger) chan struct{} {
	done := make(chan struct{}, 1)

	go func() {
		signals := make(chan os.Signal, 1)
		signal.Notify(signals)

		signal := <-signals
		switch signal {
		case syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGSTOP, syscall.SIGKILL:
			log.Info("recieved exit signal, closing...")
			err := l.Close()
			if err != nil {
				log.Critical(err.Error())
			}
			close(done)
		}

	}()
	return done
}
<commit_msg>go: update koding/asgd<commit_after>package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/signal"
	"syscall"

	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/koding/asgd"
	"github.com/koding/logging"
	"github.com/koding/multiconfig"
)

type Conf struct {
	Name string

	// required
	AccessKeyID     string
	SecretAccessKey string

	// can be overriden
	Region          string
	AutoScalingName string

	Execute string

	// optional
	Debug bool
}

func main() {
	c := &Conf{}
	mc := multiconfig.New()
	mc.Loader = multiconfig.MultiLoader(
		&multiconfig.TagLoader{},
		&multiconfig.EnvironmentLoader{},
		&multiconfig.EnvironmentLoader{Prefix: "ASGD"},
		&multiconfig.FlagLoader{},
	)
	mc.MustLoad(c)

	conf := &asgd.Config{
		Name:            c.Name,
		AccessKeyID:     c.AccessKeyID,
		SecretAccessKey: c.SecretAccessKey,
		Region:          c.Region,
		AutoScalingName: c.AutoScalingName,
		Debug:           c.Debug,
	}

	session, err := asgd.Configure(conf)
	if err != nil {
		log.Fatal("Reading config failed: ", err.Error())
	}

	log := logging.NewCustom("asgd", conf.Debug)
	// remove formatting from call stack and output correct line
	log.SetCallDepth(1)

	// create lifecycle
	l := asgd.NewLifeCycle(session, log, conf.AutoScalingName)

	// configure lifecycle with system name
	if err := l.Configure(conf.Name); err != nil {
		log.Fatal(err.Error())
	}

	done := registerSignalHandler(l, log)
	// listen to lifecycle events
	if err := l.Listen(process(c.Execute)); err != nil {
		log.Fatal(err.Error())
	}

	<-done
}

func process(execute string) func(instances []*ec2.Instance) error {
	return func(instances []*ec2.Instance) error {
		tmpfile, err := ioutil.TempFile("", "content")
		if err != nil {
			log.Fatal(err)
		}

		defer os.Remove(tmpfile.Name()) // clean up
		if err := json.NewEncoder(tmpfile).Encode(instances); err != nil {
			return err
		}

		if err := tmpfile.Close(); err != nil {
			return err
		}

		cmd := exec.Command(execute, "-file", tmpfile.Name())
		if err := cmd.Run(); err != nil {
			return err
		}

		return nil
	}
}

func registerSignalHandler(l *asgd.LifeCycle, log logging.Logger) chan struct{} {
	done := make(chan struct{}, 1)

	go func() {
		signals := make(chan os.Signal, 1)
		signal.Notify(signals)

		signal := <-signals
		switch signal {
		case syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGSTOP, syscall.SIGKILL:
			log.Info("recieved exit signal, closing...")
			err := l.Close()
			if err != nil {
				log.Critical(err.Error())
			}
			close(done)
		}

	}()
	return done
}
<|endoftext|>


<commit_before>package cmd

import (
	//"database/sql"
	"fmt"
	"os"

	"github.com/spf13/cobra"

	"github.com/cvmfs/docker-graphdriver/daemon/lib"
)

func init() {
	rootCmd.AddCommand(garbageCollectionCmd)
}

var garbageCollectionCmd = &cobra.Command{
	Use:     "garbage-collection",
	Short:   "Removes layers that are not necessary anymore",
	Aliases: []string{"gc"},
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Start")
		lib.RemoveUselessLayers()
		os.Exit(0)
	},
}
<commit_msg>remove commented out import<commit_after>package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"

	"github.com/cvmfs/docker-graphdriver/daemon/lib"
)

func init() {
	rootCmd.AddCommand(garbageCollectionCmd)
}

var garbageCollectionCmd = &cobra.Command{
	Use:     "garbage-collection",
	Short:   "Removes layers that are not necessary anymore",
	Aliases: []string{"gc"},
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Start")
		lib.RemoveUselessLayers()
		os.Exit(0)
	},
}
<|endoftext|>


<commit_before>package state

import (
	"fmt"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/txn"
	"sort"
)

const (
	ItemAdded = iota
	ItemModified
	ItemDeleted
)

// ItemChange represents the change of an item in a configNode.
type ItemChange struct {
	Type     int
	Key      string
	OldValue interface{}
	NewValue interface{}
}

// String returns the item change in a readable format.
func (ic *ItemChange) String() string {
	switch ic.Type {
	case ItemAdded:
		return fmt.Sprintf("setting added: %v = %v", ic.Key, ic.NewValue)
	case ItemModified:
		return fmt.Sprintf("setting modified: %v = %v (was %v)",
			ic.Key, ic.NewValue, ic.OldValue)
	case ItemDeleted:
		return fmt.Sprintf("setting deleted: %v (was %v)", ic.Key, ic.OldValue)
	}
	return fmt.Sprintf("unknown setting change type %d: %v = %v (was %v)",
		ic.Type, ic.Key, ic.NewValue, ic.OldValue)
}

// itemChangeSlice contains a slice of item changes in a config node.
// It implements the sort interface to sort the items changes by key.
type itemChangeSlice []ItemChange

func (ics itemChangeSlice) Len() int           { return len(ics) }
func (ics itemChangeSlice) Less(i, j int) bool { return ics[i].Key < ics[j].Key }
func (ics itemChangeSlice) Swap(i, j int)      { ics[i], ics[j] = ics[j], ics[i] }

// A ConfigNode manages changes to settings as a delta in memory and merges
// them back in the database when explicitly requested.
type ConfigNode struct {
	st   *State
	path string
	// disk holds the values in the config node before
	// any keys have been changed. It is reset on Read and Write
	// operations.
	disk map[string]interface{}
	// cache holds the current values in the config node.
	// The difference between disk and core
	// determines the delta to be applied when ConfigNode.Write
	// is called.
	core map[string]interface{}
}

// NotFoundError represents the error that something is not found.
type NotFoundError struct {
	what string
}

func (e *NotFoundError) Error() string {
	return fmt.Sprintf("%s not found", e.what)
}

// Keys returns the current keys in alphabetical order.
func (c *ConfigNode) Keys() []string {
	keys := []string{}
	for key := range c.core {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	return keys
}

// Get returns the value of key and whether it was found.
func (c *ConfigNode) Get(key string) (value interface{}, found bool) {
	value, found = c.core[key]
	return
}

// Map returns all keys and values of the node.
func (c *ConfigNode) Map() map[string]interface{} {
	return copyMap(c.core)
}

// Set sets key to value
func (c *ConfigNode) Set(key string, value interface{}) {
	c.core[key] = value
}

// Update sets multiple key/value pairs.
func (c *ConfigNode) Update(kv map[string]interface{}) {
	for key, value := range kv {
		c.core[key] = value
	}
}

// Delete removes key.
func (c *ConfigNode) Delete(key string) {
	delete(c.core, key)
}

// copyMap copies the keys and values of one map into a new one.
func copyMap(in map[string]interface{}) (out map[string]interface{}) {
	out = make(map[string]interface{})
	for key, value := range in {
		out[key] = value
	}
	return
}

// cacheKeys returns the keys of all caches as a key=>true map.
func cacheKeys(caches ...map[string]interface{}) map[string]bool {
	keys := make(map[string]bool)
	for _, cache := range caches {
		for key := range cache {
			keys[key] = true
		}
	}
	return keys
}

// Write writes changes made to c back onto its node.  Changes are written
// as a delta applied on top of the latest version of the node, to prevent
// overwriting unrelated changes made to the node since it was last read.
func (c *ConfigNode) Write() ([]ItemChange, error) {
	changes := []ItemChange{}
	upserts := map[string]interface{}{}
	deletions := map[string]int{}
	for key := range cacheKeys(c.disk, c.core) {
		old, ondisk := c.disk[key]
		new, incore := c.core[key]
		if new == old {
			continue
		}
		var change ItemChange
		switch {
		case incore && ondisk:
			change = ItemChange{ItemModified, key, old, new}
			upserts[key] = new
		case incore && !ondisk:
			change = ItemChange{ItemAdded, key, nil, new}
			upserts[key] = new
		case ondisk && !incore:
			change = ItemChange{ItemDeleted, key, old, nil}
			deletions[key] = 1
		default:
			panic("unreachable")
		}
		changes = append(changes, change)
	}
	if len(changes) == 0 {
		return []ItemChange{}, nil
	}
	sort.Sort(itemChangeSlice(changes))
	inserts := copyMap(upserts)
	ops := []txn.Op{{
		C:      c.st.settings.Name,
		Id:     c.path,
		Insert: inserts,
	}}
	if err := c.st.runner.Run(ops, "", nil); err != nil {
		return nil, fmt.Errorf("cannot write configuration node %q: %v", c.path, err)
	}
	ops = []txn.Op{{
		C:  c.st.settings.Name,
		Id: c.path,
		Update: D{
			{"$set", upserts},
			{"$unset", deletions},
		},
	}}
	if err := c.st.runner.Run(ops, "", nil); err != nil {
		return nil, fmt.Errorf("cannot write configuration node %q: %v", c.path, err)
	}
	c.disk = copyMap(c.core)
	return changes, nil
}

func newConfigNode(st *State, path string) *ConfigNode {
	return &ConfigNode{
		st:   st,
		path: path,
		core: make(map[string]interface{}),
	}
}

// cleanMap cleans the map of version and _id fields.
func cleanMap(in map[string]interface{}) {
	delete(in, "_id")
	delete(in, "txn-revno")
	delete(in, "txn-queue")
}

// Read (re)reads the node data into c.
func (c *ConfigNode) Read() error {
	config := map[string]interface{}{}
	err := c.st.settings.FindId(c.path).One(config)
	if err == mgo.ErrNotFound {
		c.disk = nil
		c.core = make(map[string]interface{})
		return nil
	}
	if err != nil {
		return fmt.Errorf("cannot read configuration node %q: %v", c.path, err)
	}
	cleanMap(config)
	c.disk = copyMap(config)
	c.core = copyMap(config)
	return nil
}

// readConfigNode returns the ConfigNode for path.
func readConfigNode(st *State, path string) (*ConfigNode, error) {
	c := newConfigNode(st, path)
	if err := c.Read(); err != nil {
		return nil, err
	}
	return c, nil
}

// createConfigNode writes an initial config node.
func createConfigNode(st *State, path string, values map[string]interface{}) (*ConfigNode, error) {
	c := newConfigNode(st, path)
	c.core = copyMap(values)
	_, err := c.Write()
	if err != nil {
		return nil, err
	}
	return c, nil
}
<commit_msg>state: config nodes remember their version<commit_after>package state

import (
	"fmt"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/txn"
	"sort"
)

const (
	ItemAdded = iota
	ItemModified
	ItemDeleted
)

// ItemChange represents the change of an item in a configNode.
type ItemChange struct {
	Type     int
	Key      string
	OldValue interface{}
	NewValue interface{}
}

// String returns the item change in a readable format.
func (ic *ItemChange) String() string {
	switch ic.Type {
	case ItemAdded:
		return fmt.Sprintf("setting added: %v = %v", ic.Key, ic.NewValue)
	case ItemModified:
		return fmt.Sprintf("setting modified: %v = %v (was %v)",
			ic.Key, ic.NewValue, ic.OldValue)
	case ItemDeleted:
		return fmt.Sprintf("setting deleted: %v (was %v)", ic.Key, ic.OldValue)
	}
	return fmt.Sprintf("unknown setting change type %d: %v = %v (was %v)",
		ic.Type, ic.Key, ic.NewValue, ic.OldValue)
}

// itemChangeSlice contains a slice of item changes in a config node.
// It implements the sort interface to sort the items changes by key.
type itemChangeSlice []ItemChange

func (ics itemChangeSlice) Len() int           { return len(ics) }
func (ics itemChangeSlice) Less(i, j int) bool { return ics[i].Key < ics[j].Key }
func (ics itemChangeSlice) Swap(i, j int)      { ics[i], ics[j] = ics[j], ics[i] }

// A ConfigNode manages changes to settings as a delta in memory and merges
// them back in the database when explicitly requested.
type ConfigNode struct {
	st   *State
	path string
	// disk holds the values in the config node before
	// any keys have been changed. It is reset on Read and Write
	// operations.
	disk map[string]interface{}
	// cache holds the current values in the config node.
	// The difference between disk and core
	// determines the delta to be applied when ConfigNode.Write
	// is called.
	core     map[string]interface{}
	txnRevno int64
}

// NotFoundError represents the error that something is not found.
type NotFoundError struct {
	what string
}

func (e *NotFoundError) Error() string {
	return fmt.Sprintf("%s not found", e.what)
}

// Keys returns the current keys in alphabetical order.
func (c *ConfigNode) Keys() []string {
	keys := []string{}
	for key := range c.core {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	return keys
}

// Get returns the value of key and whether it was found.
func (c *ConfigNode) Get(key string) (value interface{}, found bool) {
	value, found = c.core[key]
	return
}

// Map returns all keys and values of the node.
func (c *ConfigNode) Map() map[string]interface{} {
	return copyMap(c.core)
}

// Set sets key to value
func (c *ConfigNode) Set(key string, value interface{}) {
	c.core[key] = value
}

// Update sets multiple key/value pairs.
func (c *ConfigNode) Update(kv map[string]interface{}) {
	for key, value := range kv {
		c.core[key] = value
	}
}

// Delete removes key.
func (c *ConfigNode) Delete(key string) {
	delete(c.core, key)
}

// copyMap copies the keys and values of one map into a new one.
func copyMap(in map[string]interface{}) (out map[string]interface{}) {
	out = make(map[string]interface{})
	for key, value := range in {
		out[key] = value
	}
	return
}

// cacheKeys returns the keys of all caches as a key=>true map.
func cacheKeys(caches ...map[string]interface{}) map[string]bool {
	keys := make(map[string]bool)
	for _, cache := range caches {
		for key := range cache {
			keys[key] = true
		}
	}
	return keys
}

// Write writes changes made to c back onto its node.  Changes are written
// as a delta applied on top of the latest version of the node, to prevent
// overwriting unrelated changes made to the node since it was last read.
func (c *ConfigNode) Write() ([]ItemChange, error) {
	changes := []ItemChange{}
	upserts := map[string]interface{}{}
	deletions := map[string]int{}
	for key := range cacheKeys(c.disk, c.core) {
		old, ondisk := c.disk[key]
		new, incore := c.core[key]
		if new == old {
			continue
		}
		var change ItemChange
		switch {
		case incore && ondisk:
			change = ItemChange{ItemModified, key, old, new}
			upserts[key] = new
		case incore && !ondisk:
			change = ItemChange{ItemAdded, key, nil, new}
			upserts[key] = new
		case ondisk && !incore:
			change = ItemChange{ItemDeleted, key, old, nil}
			deletions[key] = 1
		default:
			panic("unreachable")
		}
		changes = append(changes, change)
	}
	if len(changes) == 0 {
		return []ItemChange{}, nil
	}
	sort.Sort(itemChangeSlice(changes))
	inserts := copyMap(upserts)
	ops := []txn.Op{{
		C:      c.st.settings.Name,
		Id:     c.path,
		Insert: inserts,
	}}
	if err := c.st.runner.Run(ops, "", nil); err != nil {
		return nil, fmt.Errorf("cannot write configuration node %q: %v", c.path, err)
	}
	ops = []txn.Op{{
		C:  c.st.settings.Name,
		Id: c.path,
		Update: D{
			{"$set", upserts},
			{"$unset", deletions},
		},
	}}
	if err := c.st.runner.Run(ops, "", nil); err != nil {
		return nil, fmt.Errorf("cannot write configuration node %q: %v", c.path, err)
	}
	c.disk = copyMap(c.core)
	return changes, nil
}

func newConfigNode(st *State, path string) *ConfigNode {
	return &ConfigNode{
		st:   st,
		path: path,
		core: make(map[string]interface{}),
	}
}

// cleanMap cleans the map of version and _id fields.
func cleanMap(in map[string]interface{}) {
	delete(in, "_id")
	delete(in, "txn-revno")
	delete(in, "txn-queue")
}

// Read (re)reads the node data into c.
func (c *ConfigNode) Read() error {
	config := map[string]interface{}{}
	err := c.st.settings.FindId(c.path).One(config)
	if err == mgo.ErrNotFound {
		c.disk = nil
		c.core = make(map[string]interface{})
		return nil
	}
	if err != nil {
		return fmt.Errorf("cannot read configuration node %q: %v", c.path, err)
	}
	c.txnRevno = config["txn-revno"]
	cleanMap(config)
	c.disk = copyMap(config)
	c.core = copyMap(config)
	return nil
}

// readConfigNode returns the ConfigNode for path.
func readConfigNode(st *State, path string) (*ConfigNode, error) {
	c := newConfigNode(st, path)
	if err := c.Read(); err != nil {
		return nil, err
	}
	return c, nil
}

// createConfigNode writes an initial config node.
func createConfigNode(st *State, path string, values map[string]interface{}) (*ConfigNode, error) {
	c := newConfigNode(st, path)
	c.core = copyMap(values)
	_, err := c.Write()
	if err != nil {
		return nil, err
	}
	return c, nil
}
<|endoftext|>


<commit_before>// launchpad.net/juju/go/state
//
// Copyright (c) 2011-2012 Canonical Ltd.
package state_test

import (
	. "launchpad.net/gocheck"
	"time"
)

func (s *StateSuite) TestServiceWatchConfig(c *C) {
	dummy, _ := addDummyCharm(c, s.st)
	wordpress, err := s.st.AddService("wordpress", dummy)
	c.Assert(err, IsNil)
	c.Assert(wordpress.Name(), Equals, "wordpress")

	config, err := wordpress.Config()
	c.Assert(err, IsNil)
	c.Assert(config.Keys(), HasLen, 0)

	watcher := wordpress.WatchConfig()

	go func() {
		time.Sleep(100 * time.Millisecond)
		config.Set("foo", "bar")
		config.Set("baz", "yadda")
		config.Write()

		time.Sleep(100 * time.Millisecond)
		config.Delete("foo")
		config.Write()
	}()

	// Receive the two changes.
	changedConfig := <-watcher.Changes()
	c.Assert(changedConfig.Keys(), HasLen, 2)
	foo, found := changedConfig.Get("foo")
	c.Assert(found, Equals, true)
	c.Assert(foo, Equals, "bar")

	changedConfig = <-watcher.Changes()
	c.Assert(changedConfig.Keys(), HasLen, 1)
	foo, found = changedConfig.Get("foo")
	c.Assert(found, Equals, false)
	baz, found := changedConfig.Get("baz")
	c.Assert(found, Equals, true)
	c.Assert(baz, Equals, "yadda")

	// No more changes.
	select {
	case <-watcher.Changes():
		c.Fail()
	case <-time.After(2 * time.Second):
		// The timeout is expected.
	}

	err = watcher.Stop()
	c.Assert(err, IsNil)
}
<commit_msg>Commit of test for merge of current trunk.<commit_after><|endoftext|>


<commit_before>package mpgostats

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/fukata/golang-stats-api-handler"
	mp "github.com/mackerelio/go-mackerel-plugin-helper"
)

// GostatsPlugin mackerel plugin for go server
type GostatsPlugin struct {
	URI    string
	Prefix string
}

/*
{
  "time": 1449124022112358000,
  "go_version": "go1.5.1",
  "go_os": "darwin",
  "go_arch": "amd64",
  "cpu_num": 4,
  "goroutine_num": 6,
  "gomaxprocs": 4,
  "cgo_call_num": 5,
  "memory_alloc": 213360,
  "memory_total_alloc": 213360,
  "memory_sys": 3377400,
  "memory_lookups": 15,
  "memory_mallocs": 1137,
  "memory_frees": 0,
  "memory_stack": 393216,
  "heap_alloc": 213360,
  "heap_sys": 655360,
  "heap_idle": 65536,
  "heap_inuse": 589824,
  "heap_released": 0,
  "heap_objects": 1137,
  "gc_next": 4194304,
  "gc_last": 0,
  "gc_num": 0,
  "gc_per_second": 0,
  "gc_pause_per_second": 0,
  "gc_pause": []
}
*/

// GraphDefinition interface for mackerelplugin
func (m GostatsPlugin) GraphDefinition() map[string]mp.Graphs {
	labelPrefix := strings.Title(m.Prefix)
	return map[string]mp.Graphs{
		(m.Prefix + ".runtime"): {
			Label: (labelPrefix + " Runtime"),
			Unit:  "integer",
			Metrics: []mp.Metrics{
				{Name: "goroutine_num", Label: "Gorotine Num"},
				{Name: "cgo_call_num", Label: "CGO Call Num", Diff: true},
			},
		},
		(m.Prefix + ".memory"): {
			Label: (labelPrefix + " Memory"),
			Unit:  "bytes",
			Metrics: []mp.Metrics{
				{Name: "memory_alloc", Label: "Alloc"},
				{Name: "memory_sys", Label: "Sys"},
				{Name: "memory_stack", Label: "Stack In Use"},
			},
		},
		(m.Prefix + ".operation"): {
			Label: (labelPrefix + " Operation"),
			Unit:  "integer",
			Metrics: []mp.Metrics{
				{Name: "memory_lookups", Label: "Pointer Lookups", Diff: true},
				{Name: "memory_mallocs", Label: "Mallocs", Diff: true},
				{Name: "memory_frees", Label: "Frees", Diff: true},
			},
		},
		(m.Prefix + ".heap"): {
			Label: (labelPrefix + " Heap"),
			Unit:  "bytes",
			Metrics: []mp.Metrics{
				{Name: "heap_sys", Label: "Sys"},
				{Name: "heap_idle", Label: "Idle"},
				{Name: "heap_inuse", Label: "In Use"},
				{Name: "heap_released", Label: "Released", Diff: true},
			},
		},
		(m.Prefix + ".gc"): {
			Label: (labelPrefix + " GC"),
			Unit:  "float",
			Metrics: []mp.Metrics{
				{Name: "gc_num", Label: "GC Num", Diff: true},
				{Name: "gc_per_second", Label: "GC Per Second"},
				{Name: "gc_pause_per_second", Label: "GC Pause Per Second"},
			},
		},
	}
}

// FetchMetrics interface for mackerelplugin
func (m GostatsPlugin) FetchMetrics() (map[string]interface{}, error) {
	resp, err := http.Get(m.URI)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return m.parseStats(resp.Body)
}

func (m GostatsPlugin) parseStats(body io.Reader) (map[string]interface{}, error) {
	stat := make(map[string]interface{})
	decoder := json.NewDecoder(body)

	s := stats_api.Stats{}
	err := decoder.Decode(&s)
	if err != nil {
		return nil, err
	}
	stat["goroutine_num"] = uint64(s.GoroutineNum)
	stat["cgo_call_num"] = uint64(s.CgoCallNum)
	stat["memory_sys"] = s.MemorySys
	stat["memory_alloc"] = s.MemoryAlloc
	stat["memory_stack"] = s.StackInUse
	stat["memory_lookups"] = s.MemoryLookups
	stat["memory_frees"] = s.MemoryFrees
	stat["memory_mallocs"] = s.MemoryMallocs
	stat["heap_sys"] = s.HeapSys
	stat["heap_idle"] = s.HeapIdle
	stat["heap_inuse"] = s.HeapInuse
	stat["heap_released"] = s.HeapReleased
	stat["gc_num"] = s.GcNum
	stat["gc_per_second"] = s.GcPerSecond
	stat["gc_pause_per_second"] = s.GcPausePerSecond

	return stat, nil
}

// Do the plugin
func Do() {
	optURI := flag.String("uri", "", "URI")
	optScheme := flag.String("scheme", "http", "Scheme")
	optHost := flag.String("host", "localhost", "Hostname")
	optPort := flag.String("port", "8080", "Port")
	optPath := flag.String("path", "/api/stats", "Path")
	optPrefix := flag.String("metric-key-prefix", "gostats", "Metric key prefix")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	gosrv := GostatsPlugin{
		Prefix: *optPrefix,
	}
	if *optURI != "" {
		gosrv.URI = *optURI
	} else {
		gosrv.URI = fmt.Sprintf("%s://%s:%s%s", *optScheme, *optHost, *optPort, *optPath)
	}

	helper := mp.NewMackerelPlugin(gosrv)
	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = fmt.Sprintf("/tmp/mackerel-plugin-gosrv")
	}

	helper.Run()
}
<commit_msg>[gostats] don't set default tempfile name by plugin<commit_after>package mpgostats

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/fukata/golang-stats-api-handler"
	mp "github.com/mackerelio/go-mackerel-plugin-helper"
)

// GostatsPlugin mackerel plugin for go server
type GostatsPlugin struct {
	URI    string
	Prefix string
}

/*
{
  "time": 1449124022112358000,
  "go_version": "go1.5.1",
  "go_os": "darwin",
  "go_arch": "amd64",
  "cpu_num": 4,
  "goroutine_num": 6,
  "gomaxprocs": 4,
  "cgo_call_num": 5,
  "memory_alloc": 213360,
  "memory_total_alloc": 213360,
  "memory_sys": 3377400,
  "memory_lookups": 15,
  "memory_mallocs": 1137,
  "memory_frees": 0,
  "memory_stack": 393216,
  "heap_alloc": 213360,
  "heap_sys": 655360,
  "heap_idle": 65536,
  "heap_inuse": 589824,
  "heap_released": 0,
  "heap_objects": 1137,
  "gc_next": 4194304,
  "gc_last": 0,
  "gc_num": 0,
  "gc_per_second": 0,
  "gc_pause_per_second": 0,
  "gc_pause": []
}
*/

// GraphDefinition interface for mackerelplugin
func (m GostatsPlugin) GraphDefinition() map[string]mp.Graphs {
	labelPrefix := strings.Title(m.Prefix)
	return map[string]mp.Graphs{
		(m.Prefix + ".runtime"): {
			Label: (labelPrefix + " Runtime"),
			Unit:  "integer",
			Metrics: []mp.Metrics{
				{Name: "goroutine_num", Label: "Gorotine Num"},
				{Name: "cgo_call_num", Label: "CGO Call Num", Diff: true},
			},
		},
		(m.Prefix + ".memory"): {
			Label: (labelPrefix + " Memory"),
			Unit:  "bytes",
			Metrics: []mp.Metrics{
				{Name: "memory_alloc", Label: "Alloc"},
				{Name: "memory_sys", Label: "Sys"},
				{Name: "memory_stack", Label: "Stack In Use"},
			},
		},
		(m.Prefix + ".operation"): {
			Label: (labelPrefix + " Operation"),
			Unit:  "integer",
			Metrics: []mp.Metrics{
				{Name: "memory_lookups", Label: "Pointer Lookups", Diff: true},
				{Name: "memory_mallocs", Label: "Mallocs", Diff: true},
				{Name: "memory_frees", Label: "Frees", Diff: true},
			},
		},
		(m.Prefix + ".heap"): {
			Label: (labelPrefix + " Heap"),
			Unit:  "bytes",
			Metrics: []mp.Metrics{
				{Name: "heap_sys", Label: "Sys"},
				{Name: "heap_idle", Label: "Idle"},
				{Name: "heap_inuse", Label: "In Use"},
				{Name: "heap_released", Label: "Released", Diff: true},
			},
		},
		(m.Prefix + ".gc"): {
			Label: (labelPrefix + " GC"),
			Unit:  "float",
			Metrics: []mp.Metrics{
				{Name: "gc_num", Label: "GC Num", Diff: true},
				{Name: "gc_per_second", Label: "GC Per Second"},
				{Name: "gc_pause_per_second", Label: "GC Pause Per Second"},
			},
		},
	}
}

// FetchMetrics interface for mackerelplugin
func (m GostatsPlugin) FetchMetrics() (map[string]interface{}, error) {
	resp, err := http.Get(m.URI)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return m.parseStats(resp.Body)
}

func (m GostatsPlugin) parseStats(body io.Reader) (map[string]interface{}, error) {
	stat := make(map[string]interface{})
	decoder := json.NewDecoder(body)

	s := stats_api.Stats{}
	err := decoder.Decode(&s)
	if err != nil {
		return nil, err
	}
	stat["goroutine_num"] = uint64(s.GoroutineNum)
	stat["cgo_call_num"] = uint64(s.CgoCallNum)
	stat["memory_sys"] = s.MemorySys
	stat["memory_alloc"] = s.MemoryAlloc
	stat["memory_stack"] = s.StackInUse
	stat["memory_lookups"] = s.MemoryLookups
	stat["memory_frees"] = s.MemoryFrees
	stat["memory_mallocs"] = s.MemoryMallocs
	stat["heap_sys"] = s.HeapSys
	stat["heap_idle"] = s.HeapIdle
	stat["heap_inuse"] = s.HeapInuse
	stat["heap_released"] = s.HeapReleased
	stat["gc_num"] = s.GcNum
	stat["gc_per_second"] = s.GcPerSecond
	stat["gc_pause_per_second"] = s.GcPausePerSecond

	return stat, nil
}

// Do the plugin
func Do() {
	optURI := flag.String("uri", "", "URI")
	optScheme := flag.String("scheme", "http", "Scheme")
	optHost := flag.String("host", "localhost", "Hostname")
	optPort := flag.String("port", "8080", "Port")
	optPath := flag.String("path", "/api/stats", "Path")
	optPrefix := flag.String("metric-key-prefix", "gostats", "Metric key prefix")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	gosrv := GostatsPlugin{
		Prefix: *optPrefix,
	}
	if *optURI != "" {
		gosrv.URI = *optURI
	} else {
		gosrv.URI = fmt.Sprintf("%s://%s:%s%s", *optScheme, *optHost, *optPort, *optPath)
	}

	helper := mp.NewMackerelPlugin(gosrv)
	helper.Tempfile = *optTempfile

	helper.Run()
}
<|endoftext|>


<commit_before>package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/mattn/go-sqlite3"
	"github.com/oschwald/geoip2-golang"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
)

var db *sql.DB
var visitorsStmt *sql.Stmt
var visitStmt *sql.Stmt

type Visit struct {
	timse    string
	location string
	ip       string
}

func handler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" || r.Method == "" {
		get(w)
	} else if r.Method == "POST" {
		post(w, r)
	}
}

func get(w http.ResponseWriter) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	rows, err := db.Query("select count(id), strftime(\"%Y-%m-%d %H:00:00\", datetime(time, 'localtime')) from visits where time > datetime('now', '-500 hours') group by strftime(\"%Y%j%H\", time);")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	result := map[string][]map[string]string{}
	counts := []map[string]string{}
	for rows.Next() {
		var count string
		var time string

		rows.Scan(&count, &time)
		counts = append(counts, map[string]string{
			"time":  time,
			"count": count,
		})
	}
	result["counts"] = counts

	lrows, err := db.Query("select count(city), city, country, iso from visitors group by city, iso;")
	if err != nil {
		log.Fatal(err)
	}
	defer lrows.Close()
	locations := []map[string]string{}
	for lrows.Next() {
		var count string
		var city string
		var country string
		var iso string

		lrows.Scan(&count, &city, &country, &iso)
		locations = append(locations, map[string]string{
			"city":    city,
			"country": country,
			"iso":     iso,
			"count":   count,
		})
	}
	result["locations"] = locations

	b, _ := json.Marshal(result)
	fmt.Fprintf(w, string(b))

	rows.Close()
}

func post(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	if strings.Contains(r.UserAgent(), "Googlebot") {
		return
	}

	if r.FormValue("action") == "enter" {
		var id int64
		avid := r.FormValue("avid")

		if avid == "" {
			host, _, _ := net.SplitHostPort(r.RemoteAddr)
			if host != "" {
				gr := geo(host)
				result, err := visitorsStmt.Exec(gr["city"], gr["country"], gr["iso"], host, r.UserAgent())

				if err != nil {
					log.Print(err)
					return
				}

				id, _ = result.LastInsertId()
				response := map[string]string{}
				response["vid"] = strconv.FormatInt(id, 10)

				rj, _ := json.Marshal(response)
				fmt.Fprintf(w, string(rj))
			}
		} else {
			id_s, _ := strconv.Atoi(avid)
			id = int64(id_s)
		}

		_, err := visitStmt.Exec(r.FormValue("url"), r.FormValue("referrer"), id)

		if err != nil {
			log.Print(err)
			return
		}
	}
}

func geo(ipstring string) map[string]string {
	db, err := geoip2.Open("GeoLite2-City.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	ip := net.ParseIP(ipstring)
	if ip != nil {
		record, err := db.City(ip)
		if err != nil {
			log.Fatal(err)
		}
		return map[string]string{
			"city":    record.City.Names["en"],
			"country": record.Country.Names["en"],
			"iso":     record.Country.IsoCode,
		}
	}

	return map[string]string{
		"city":    "",
		"country": "",
		"iso":     "",
	}
}

func main() {
	isNew := false

	_, err := os.Open("./alight.db")
	if err != nil {
		isNew = true
	}

	db, err = sql.Open("sqlite3", "./alight.db")
	defer db.Close()

	if isNew {
		sqlStmt := `
		create table visits (id integer primary key, url text, time integer, referrer text, vid integer references visitors);
		create table visitors (vid integer primary key, city text, country text, iso text, ip text, ua text);
		`

		_, err = db.Exec(sqlStmt)
		if err != nil {
			os.Remove("./alight.db")
			log.Printf("%q: %s\n", err, sqlStmt)
			return
		}
	}

	db.Exec("pragma synchronous = OFF")

	visitorsStmt, err = db.Prepare("insert into visitors values (null, ?, ?, ?, ?, ?)")
	if err != nil {
		log.Fatal(err)
	}
	visitStmt, err = db.Prepare("insert into visits values (null, ?, datetime('now'), ?, ?);")
	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/", handler)
	http.ListenAndServe(":8000", nil)
}
<commit_msg>timeframe for locations<commit_after>package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/mattn/go-sqlite3"
	"github.com/oschwald/geoip2-golang"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
)

var db *sql.DB
var visitorsStmt *sql.Stmt
var visitStmt *sql.Stmt

type Visit struct {
	timse    string
	location string
	ip       string
}

func handler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" || r.Method == "" {
		get(w)
	} else if r.Method == "POST" {
		post(w, r)
	}
}

func get(w http.ResponseWriter) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	rows, err := db.Query("select count(id), strftime(\"%Y-%m-%d %H:00:00\", datetime(time, 'localtime')) from visits where time > datetime('now', '-500 hours') group by strftime(\"%Y%j%H\", time);")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	result := map[string][]map[string]string{}
	counts := []map[string]string{}
	for rows.Next() {
		var count string
		var time string

		rows.Scan(&count, &time)
		counts = append(counts, map[string]string{
			"time":  time,
			"count": count,
		})
	}
	result["counts"] = counts

	lrows, err := db.Query("select count(city), city, country, iso from visitors natural join visits where visits.time > datetime('now', '-500 hours') group by city, iso;")
	if err != nil {
		log.Fatal(err)
	}
	defer lrows.Close()
	locations := []map[string]string{}
	for lrows.Next() {
		var count string
		var city string
		var country string
		var iso string

		lrows.Scan(&count, &city, &country, &iso)
		locations = append(locations, map[string]string{
			"city":    city,
			"country": country,
			"iso":     iso,
			"count":   count,
		})
	}
	result["locations"] = locations

	b, _ := json.Marshal(result)
	fmt.Fprintf(w, string(b))

	rows.Close()
}

func post(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	if strings.Contains(r.UserAgent(), "Googlebot") {
		return
	}

	if r.FormValue("action") == "enter" {
		var id int64
		avid := r.FormValue("avid")

		if avid == "" {
			host, _, _ := net.SplitHostPort(r.RemoteAddr)
			if host != "" {
				gr := geo(host)
				result, err := visitorsStmt.Exec(gr["city"], gr["country"], gr["iso"], host, r.UserAgent())

				if err != nil {
					log.Print(err)
					return
				}

				id, _ = result.LastInsertId()
				response := map[string]string{}
				response["vid"] = strconv.FormatInt(id, 10)

				rj, _ := json.Marshal(response)
				fmt.Fprintf(w, string(rj))
			}
		} else {
			id_s, _ := strconv.Atoi(avid)
			id = int64(id_s)
		}

		_, err := visitStmt.Exec(r.FormValue("url"), r.FormValue("referrer"), id)

		if err != nil {
			log.Print(err)
			return
		}
	}
}

func geo(ipstring string) map[string]string {
	db, err := geoip2.Open("GeoLite2-City.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	ip := net.ParseIP(ipstring)
	if ip != nil {
		record, err := db.City(ip)
		if err != nil {
			log.Fatal(err)
		}
		return map[string]string{
			"city":    record.City.Names["en"],
			"country": record.Country.Names["en"],
			"iso":     record.Country.IsoCode,
		}
	}

	return map[string]string{
		"city":    "",
		"country": "",
		"iso":     "",
	}
}

func main() {
	isNew := false

	_, err := os.Open("./alight.db")
	if err != nil {
		isNew = true
	}

	db, err = sql.Open("sqlite3", "./alight.db")
	defer db.Close()

	if isNew {
		sqlStmt := `
		create table visits (id integer primary key, url text, time integer, referrer text, vid integer references visitors);
		create table visitors (vid integer primary key, city text, country text, iso text, ip text, ua text);
		`

		_, err = db.Exec(sqlStmt)
		if err != nil {
			os.Remove("./alight.db")
			log.Printf("%q: %s\n", err, sqlStmt)
			return
		}
	}

	db.Exec("pragma synchronous = OFF")

	visitorsStmt, err = db.Prepare("insert into visitors values (null, ?, ?, ?, ?, ?)")
	if err != nil {
		log.Fatal(err)
	}
	visitStmt, err = db.Prepare("insert into visits values (null, ?, datetime('now'), ?, ?);")
	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/", handler)
	http.ListenAndServe(":8000", nil)
}
<|endoftext|>


<commit_before>package cfenv

// An App holds information about the current app running on Cloud Foundry
type App struct {
	ID             string   `json:"instance_id"`      // id of the app
	Index          int      `json:"instance_index"`   // index of the app
	Name           string   `json:"name"`             // name of the app
	Host           string   `json:"host"`             // host of the app
	Port           int      `json:"port"`             // port of the app
	Version        string   `json:"version"`          // version of the app
	ApplicationUri []string `json:"application_uris"` // application uri of the app
	Home           string   // root folder for the deployed app
	MemoryLimit    string   // maximum amount of memory that each instance of the application can consume
	WorkingDir     string   // present working directory, where the buildpack that processed the application ran
	TempDir        string   // directory location where temporary and staging files are stored
	User           string   // user account under which the DEA runs
	Services       Services // services bound to the app
}
<commit_msg>:lipstick: Fix Vet Warning<commit_after>package cfenv

// An App holds information about the current app running on Cloud Foundry
type App struct {
	ID             string   `json:"instance_id"`      // id of the app
	Index          int      `json:"instance_index"`   // index of the app
	Name           string   `json:"name"`             // name of the app
	Host           string   `json:"host"`             // host of the app
	Port           int      `json:"port"`             // port of the app
	Version        string   `json:"version"`          // version of the app
	ApplicationURI []string `json:"application_uris"` // application uri of the app
	Home           string   // root folder for the deployed app
	MemoryLimit    string   // maximum amount of memory that each instance of the application can consume
	WorkingDir     string   // present working directory, where the buildpack that processed the application ran
	TempDir        string   // directory location where temporary and staging files are stored
	User           string   // user account under which the DEA runs
	Services       Services // services bound to the app
}
<|endoftext|>


<commit_before>// Copyright 2014 David Miller. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package sequtil

import (
	"github.com/dmiller/go-seq/iseq"
	"reflect"
)

func DefaultCompareFn(k1 interface{}, k2 interface{}) int {
	if k1 == k2 {
		return 0
	}
	if k1 != nil {
		if k2 == nil {
			return 1
		}
		if c, ok := k1.(iseq.Comparer); ok {
			return c.Compare(k2)
		}
		if c, ok := k2.(iseq.Comparer); ok {
			return -c.Compare(k1)
		}
		if s, ok := k1.(string); ok {
			return CompareString(s, k2)
		}
		if IsComparableNumeric(k1) {
			return CompareComparableNumeric(k1, k2)
		}
		panic("Can't compare")
	}
	return -1
}

func IsComparableNumeric(v interface{}) bool {

	switch v.(type) {
	case bool, int, int8, int32, int64,
		uint, uint8, uint32, uint64,
		float32, float64:

		return true
	}
	return false
}

func CompareString(s string, x interface{}) int {
	if s2, ok := x.(string); ok {
		if s < s2 {
			return -1
		}
		if s == s2 {
			return 0
		}
		return 1
	}

	panic "can't compare string to non-string, non-iseq.Comparer"
}

func CompareComparableNumeric(x1 interface{}, x2 interface{}) int {
	// n1 should be numeric
	switch x1 := x1.(type) {
	case bool:
		b1 := bool(x1)
		if b1 {
			return compareNumericInt(int64(1), x2)
		} else {
			return compareNumericInt(int64(0), x2)
		}
	case int, int8, int32, int64:
		n1 := reflect.ValueOf(x1).Int()
		return compareNumericInt(n1, x2)
	case uint, uint8, uint32, uint64:
		n1 := reflect.ValueOf(x1).Uint()
		return compareNumericUint(n1, x2)
	case float32, float64:
		n1 := reflect.ValueOf(x1).Float()
		return compareNumericFloat(n1, x2)
	}
	panic("Expect first arg to be numeric")
}

func compareNumericInt(n1 int64, x2 interface{}) int {
	switch x2 := x2.(type) {
	case bool:
		b2 := bool(x2)
		var n2 int64
		if b2 {
			n2 = 1
		}
		if n1 < n2 {
			return -1
		}
		if n1 > n2 {
			return 1
		}
		return 0

	case int, int8, int32, int64:
		n2 := reflect.ValueOf(x2).Int()
		if n1 < n2 {
			return -1
		}
		if n1 > n2 {
			return 1
		}
		return 0

	case uint, uint8, uint32, uint64:
		n2 := reflect.ValueOf(x2).Uint()
		if n1 < 0 {
			return -1
		}
		un1 := uint64(n2)
		if un1 < n2 {
			return -1
		}
		if un1 > n2 {
			return 1
		}
		return 0

	case float32, float64:
		n2 := reflect.ValueOf(x2).Float()
		fn1 := float64(n1)
		if fn1 < n2 {
			return -1
		}
		if fn1 > n2 {
			return 1
		}
		return 0
	}
	return -1 // what else, other than panic?
}

func compareNumericUint(n1 uint64, x2 interface{}) int {
	switch x2 := x2.(type) {
	case bool:
		b2 := bool(x2)
		var n2 uint64
		if b2 {
			n2 = 1
		}
		if n1 < n2 {
			return -1
		}
		if n1 > n2 {
			return 1
		}
		return 0

	case int, int8, int32, int64:
		n2 := reflect.ValueOf(x2).Int()
		if n2 < 0 {
			return 1
		}
		un2 := uint64(n2)
		if n1 < un2 {
			return -1
		}
		if n1 > un2 {
			return 1
		}
		return 0

	case uint, uint8, uint32, uint64:
		n2 := reflect.ValueOf(x2).Uint()
		if n1 < n2 {
			return -1
		}
		if n1 > n2 {
			return 1
		}
		return 0

	case float32, float64:
		n2 := reflect.ValueOf(x2).Float()
		fn1 := float64(n1)
		if fn1 < n2 {
			return -1
		}
		if fn1 > n2 {
			return 1
		}
		return 0
	}
	return -1 // what else, other than panic?
}

func compareNumericFloat(n1 float64, x2 interface{}) int {
	var n2 float64
	switch x2 := x2.(type) {
	case bool, int, int8, int32, int64:
		n2 = float64(reflect.ValueOf(x2).Int())
	case uint, uint8, uint32, uint64:
		n2 = float64(reflect.ValueOf(x2).Uint())
	case float32, float64:
		n2 = reflect.ValueOf(x2).Float()
	default:
		return -1 // what else, other than panic?
	}
	if n1 < n2 {
		return -1
	}
	if n1 > n2 {
		return 1
	}
	return 0
}
<commit_msg>Modify panic string in sequtil/CompareString<commit_after>// Copyright 2014 David Miller. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package sequtil

import (
	"github.com/dmiller/go-seq/iseq"
	"reflect"
)

func DefaultCompareFn(k1 interface{}, k2 interface{}) int {
	if k1 == k2 {
		return 0
	}
	if k1 != nil {
		if k2 == nil {
			return 1
		}
		if c, ok := k1.(iseq.Comparer); ok {
			return c.Compare(k2)
		}
		if c, ok := k2.(iseq.Comparer); ok {
			return -c.Compare(k1)
		}
		if s, ok := k1.(string); ok {
			return CompareString(s, k2)
		}
		if IsComparableNumeric(k1) {
			return CompareComparableNumeric(k1, k2)
		}
		panic("Can't compare")
	}
	return -1
}

func IsComparableNumeric(v interface{}) bool {

	switch v.(type) {
	case bool, int, int8, int32, int64,
		uint, uint8, uint32, uint64,
		float32, float64:

		return true
	}
	return false
}

func CompareString(s string, x interface{}) int {
	if s2, ok := x.(string); ok {
		if s < s2 {
			return -1
		}
		if s == s2 {
			return 0
		}
		return 1
	}

	panic "can't compare string to non-string"
}

func CompareComparableNumeric(x1 interface{}, x2 interface{}) int {
	// n1 should be numeric
	switch x1 := x1.(type) {
	case bool:
		b1 := bool(x1)
		if b1 {
			return compareNumericInt(int64(1), x2)
		} else {
			return compareNumericInt(int64(0), x2)
		}
	case int, int8, int32, int64:
		n1 := reflect.ValueOf(x1).Int()
		return compareNumericInt(n1, x2)
	case uint, uint8, uint32, uint64:
		n1 := reflect.ValueOf(x1).Uint()
		return compareNumericUint(n1, x2)
	case float32, float64:
		n1 := reflect.ValueOf(x1).Float()
		return compareNumericFloat(n1, x2)
	}
	panic("Expect first arg to be numeric")
}

func compareNumericInt(n1 int64, x2 interface{}) int {
	switch x2 := x2.(type) {
	case bool:
		b2 := bool(x2)
		var n2 int64
		if b2 {
			n2 = 1
		}
		if n1 < n2 {
			return -1
		}
		if n1 > n2 {
			return 1
		}
		return 0

	case int, int8, int32, int64:
		n2 := reflect.ValueOf(x2).Int()
		if n1 < n2 {
			return -1
		}
		if n1 > n2 {
			return 1
		}
		return 0

	case uint, uint8, uint32, uint64:
		n2 := reflect.ValueOf(x2).Uint()
		if n1 < 0 {
			return -1
		}
		un1 := uint64(n2)
		if un1 < n2 {
			return -1
		}
		if un1 > n2 {
			return 1
		}
		return 0

	case float32, float64:
		n2 := reflect.ValueOf(x2).Float()
		fn1 := float64(n1)
		if fn1 < n2 {
			return -1
		}
		if fn1 > n2 {
			return 1
		}
		return 0
	}
	return -1 // what else, other than panic?
}

func compareNumericUint(n1 uint64, x2 interface{}) int {
	switch x2 := x2.(type) {
	case bool:
		b2 := bool(x2)
		var n2 uint64
		if b2 {
			n2 = 1
		}
		if n1 < n2 {
			return -1
		}
		if n1 > n2 {
			return 1
		}
		return 0

	case int, int8, int32, int64:
		n2 := reflect.ValueOf(x2).Int()
		if n2 < 0 {
			return 1
		}
		un2 := uint64(n2)
		if n1 < un2 {
			return -1
		}
		if n1 > un2 {
			return 1
		}
		return 0

	case uint, uint8, uint32, uint64:
		n2 := reflect.ValueOf(x2).Uint()
		if n1 < n2 {
			return -1
		}
		if n1 > n2 {
			return 1
		}
		return 0

	case float32, float64:
		n2 := reflect.ValueOf(x2).Float()
		fn1 := float64(n1)
		if fn1 < n2 {
			return -1
		}
		if fn1 > n2 {
			return 1
		}
		return 0
	}
	return -1 // what else, other than panic?
}

func compareNumericFloat(n1 float64, x2 interface{}) int {
	var n2 float64
	switch x2 := x2.(type) {
	case bool, int, int8, int32, int64:
		n2 = float64(reflect.ValueOf(x2).Int())
	case uint, uint8, uint32, uint64:
		n2 = float64(reflect.ValueOf(x2).Uint())
	case float32, float64:
		n2 = reflect.ValueOf(x2).Float()
	default:
		return -1 // what else, other than panic?
	}
	if n1 < n2 {
		return -1
	}
	if n1 > n2 {
		return 1
	}
	return 0
}
<|endoftext|>


<commit_before>package server

import (
	//	"bytes"
	"encoding/json"
	//	"errors"
	//	"fmt"
	"github.com/goraft/raft"
	"github.com/gorilla/mux"
	//	"github.com/miekg/dns"
	//	"github.com/rcrowley/go-metrics"
	"github.com/skynetservices/skydns/msg"
	"github.com/skynetservices/skydns/registry"
	"log"
	//	"math"
	//	"net"
	"net/http"
	//	"net/url"
	//	"os"
	//	"os/signal"
	//	"strings"
	//	"sync"
	//	"time"
)

// Handle API add callback requests
func (s *Server) addCallbackHTTPHandler(w http.ResponseWriter, req *http.Request) {
	//	addServiceCount.Inc(1)
	vars := mux.Vars(req)

	var uuid string
	var ok bool
	var secret string

	//read the authorization header to get the secret.
	secret = req.Header.Get("Authorization")

	if err := s.authenticate(secret); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}

	if uuid, ok = vars["uuid"]; !ok {
		http.Error(w, "UUID required", http.StatusBadRequest)
		return
	}

	// find service

	var cb msg.Callback

	if err := json.NewDecoder(req.Body).Decode(&cb); err != nil {
		log.Println("Error: ", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	cb.UUID = uuid

	// Lookup the service(s)
	// TODO: getRegistryKey(s) isn't exported.
	// TODO: version is thus not correctly formatted
	key := cb.Name + "." + cb.Version + "." + cb.Environment + "." + cb.Region +
		"." + cb.Host
	services, err := s.registry.Get(key)
	if err != nil || len(services) == 0 {
		http.Error(w, err.Error(), http.StatusNotFound)
	}
	// Add the callback and then add it to the services, this
	// has a race condition in that services may be deleted
	// before the callback has been added. We check for this, by
	// checking how many services actually use the callback. If zero
	// we delete the callback again.

	for _, s := range services {
		if _, err := s.raftServer.Do(NewAddCallbackCommand(s, cb.UUID)); err != nil {
			switch err {
			case registry.ErrNotExists:
				http.Error(w, err.Error(), http.StatusNotFound)
				// Don't return here, other services might exist
				// TODO(miek): set error in var and check afterwards?
			case raft.NotLeaderError:
				s.redirectToLeader(w, req)
				return
			default:
				log.Println("Error: ", err)
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
	}
	w.WriteHeader(http.StatusCreated)
}
<commit_msg>Make it compile again<commit_after>package server

import (
	//	"bytes"
	"encoding/json"
	//	"errors"
	//	"fmt"
	"github.com/goraft/raft"
	"github.com/gorilla/mux"
	//	"github.com/miekg/dns"
	//	"github.com/rcrowley/go-metrics"
	"github.com/skynetservices/skydns/msg"
	"github.com/skynetservices/skydns/registry"
	"log"
	//	"math"
	//	"net"
	"net/http"
	//	"net/url"
	//	"os"
	//	"os/signal"
	//	"strings"
	//	"sync"
	//	"time"
)

// Handle API add callback requests
func (s *Server) addCallbackHTTPHandler(w http.ResponseWriter, req *http.Request) {
	//	addServiceCount.Inc(1)
	vars := mux.Vars(req)

	var uuid string
	var ok bool
	var secret string

	//read the authorization header to get the secret.
	secret = req.Header.Get("Authorization")

	if err := s.authenticate(secret); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}

	if uuid, ok = vars["uuid"]; !ok {
		http.Error(w, "UUID required", http.StatusBadRequest)
		return
	}

	// find service

	var cb msg.Callback

	if err := json.NewDecoder(req.Body).Decode(&cb); err != nil {
		log.Println("Error: ", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	cb.UUID = uuid

	// Lookup the service(s)
	// TODO: getRegistryKey(s) isn't exported.
	// TODO: version is thus not correctly formatted
	key := cb.Name + "." + cb.Version + "." + cb.Environment + "." + cb.Region +
		"." + cb.Host
	services, err := s.registry.Get(key)
	if err != nil || len(services) == 0 {
		http.Error(w, err.Error(), http.StatusNotFound)
	}
	// Add the callback and then add it to the services, this
	// has a race condition in that services may be deleted
	// before the callback has been added. We check for this, by
	// checking how many services actually use the callback. If zero
	// we delete the callback again.

	for _, serv := range services {
		if _, err := s.raftServer.Do(NewAddCallbackCommand(serv, cb.UUID)); err != nil {
			switch err {
			case registry.ErrNotExists:
				http.Error(w, err.Error(), http.StatusNotFound)
				// Don't return here, other services might exist
				// TODO(miek): set error in var and check afterwards?
			case raft.NotLeaderError:
				s.redirectToLeader(w, req)
				return
			default:
				log.Println("Error: ", err)
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
	}
	w.WriteHeader(http.StatusCreated)
}
<|endoftext|>


<commit_before>package rc_value

import (
	"flag"
	"github.com/watermint/toolbox/domain/github/api/gh_conn"
	"github.com/watermint/toolbox/infra/control/app_control"
	"github.com/watermint/toolbox/quality/infra/qt_control"
	"testing"
)

type ValueGhConnGithubPublicRecipe struct {
	Peer gh_conn.ConnGithubPublic
}

func (z *ValueGhConnGithubPublicRecipe) Preset() {
	z.Peer.SetPeerName("value_test")
}

func (z *ValueGhConnGithubPublicRecipe) Exec(c app_control.Control) error {
	return nil
}

func (z *ValueGhConnGithubPublicRecipe) Test(c app_control.Control) error {
	return nil
}

func TestValueGhConnGithubPublic(t *testing.T) {
	err := qt_control.WithControl(func(c app_control.Control) error {
		rcp0 := &ValueGhConnGithubPublicRecipe{}
		repo := NewRepository(rcp0)

		// Parse flags
		flg := flag.NewFlagSet("value", flag.ContinueOnError)
		repo.ApplyFlags(flg, c.UI())

		// Spin up
		ct := c.WithFeature(c.Feature().AsTest(true))
		rcp2, err := repo.SpinUp(ct)
		if err != nil {
			t.Error(err)
			return err
		}
		mod2 := rcp2.(*ValueGhConnGithubPublicRecipe)
		if mod2.Peer.Context().ClientHash() != "" {
			t.Error(mod2)
		}

		if err := repo.SpinDown(ct); err != nil {
			t.Error(err)
			return err
		}

		return nil
	})
	if err != nil {
		t.Error(err)
	}
}
<commit_msg>#345 : fix test<commit_after>package rc_value

import (
	"flag"
	"github.com/watermint/toolbox/domain/github/api/gh_conn"
	"github.com/watermint/toolbox/infra/control/app_control"
	"github.com/watermint/toolbox/quality/infra/qt_control"
	"testing"
)

type ValueGhConnGithubPublicRecipe struct {
	Peer gh_conn.ConnGithubPublic
}

func (z *ValueGhConnGithubPublicRecipe) Preset() {
	z.Peer.SetPeerName("value_test")
}

func (z *ValueGhConnGithubPublicRecipe) Exec(c app_control.Control) error {
	return nil
}

func (z *ValueGhConnGithubPublicRecipe) Test(c app_control.Control) error {
	return nil
}

func TestValueGhConnGithubPublic(t *testing.T) {
	err := qt_control.WithControl(func(c app_control.Control) error {
		rcp0 := &ValueGhConnGithubPublicRecipe{}
		repo := NewRepository(rcp0)

		// Parse flags
		flg := flag.NewFlagSet("value", flag.ContinueOnError)
		repo.ApplyFlags(flg, c.UI())

		// Spin up
		ct := c.WithFeature(c.Feature().AsTest(true))
		rcp2, err := repo.SpinUp(ct)
		if err != nil {
			t.Error(err)
			return err
		}
		mod2 := rcp2.(*ValueGhConnGithubPublicRecipe)
		if mod2.Peer.Context().ClientHash() == "" {
			t.Error(mod2)
		}

		if err := repo.SpinDown(ct); err != nil {
			t.Error(err)
			return err
		}

		return nil
	})
	if err != nil {
		t.Error(err)
	}
}
<|endoftext|>


<commit_before>// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ogletest

import (
	"github.com/jacobsa/oglematchers"
)

// AssertThat is identical to ExpectThat, except that in the event of failure
// it halts the currently running test immediately. It is thus useful for
// things like bounds checking:
//
//     someSlice := [...]
//     AssertEq(1, len(someSlice))  // Protects next line from panicking.
//     ExpectEq("taco", someSlice[0])
//
func AssertThat(
	x interface{},
	m oglematchers.Matcher,
	errorParts ...interface{}) {
	res := expectThat(x, m, errorParts...)
	res.SetCaller(getCallerForAlias())

	matcherErr := res.MatchResult()
	if matcherErr != nil {
		panic(&assertThatError{})
	}
}

// assertThatError is a sentinel type that is used in a conspiracy between
// AssertThat and runTests. If runTests sees a *assertThatError as the value
// given to a panic() call, it will avoid printing the panic error.
type assertThatError struct {
}
<commit_msg>Fixed assertThat.<commit_after>// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ogletest

import (
	"github.com/jacobsa/oglematchers"
)

func assertThat(
	x interface{},
	m oglematchers.Matcher,
	depth int,
	errorParts []interface{}) {
	passed := expectThat(x, m, depth+1, errorParts)
	if !passed {
		panic(&assertThatError{})
	}
}

// AssertThat is identical to ExpectThat, except that in the event of failure
// it halts the currently running test immediately. It is thus useful for
// things like bounds checking:
//
//     someSlice := [...]
//     AssertEq(1, len(someSlice))  // Protects next line from panicking.
//     ExpectEq("taco", someSlice[0])
//
func AssertThat(
	x interface{},
	m oglematchers.Matcher,
	errorParts ...interface{}) {
	assertThat(x, m, 1, errorParts...)
}

// assertThatError is a sentinel type that is used in a conspiracy between
// AssertThat and runTests. If runTests sees a *assertThatError as the value
// given to a panic() call, it will avoid printing the panic error.
type assertThatError struct {
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/dim13/unifi"
)

type Roaming struct {
	Ap      string
	Channel int
}

func getname(s unifi.Sta) string {
	if s.Hostname != "" {
		return s.Hostname
	}
	if s.Ip != "" {
		return s.Ip
	}
	return s.Mac
}

func main() {
	user := flag.String("user", "admin", "User")
	pass := flag.String("pass", "unifi", "Password")
	url := flag.String("url", "unifi", "URL")
	flag.Parse()

	u := new(unifi.Unifi)
	u.Login(*user, *pass, *url)
	defer u.Logout()

	aps := u.GetAps()
	apmap := make(map[string]string)
	for _, ap := range aps {
		apmap[ap.Mac] = ap.Name
	}

	sta := u.GetClients()
	for _, v := range sta {
		fmt.Printf("%s at %s/%d\n", getname(v), apmap[v.Ap_mac], v.Channel)
	}
}
<commit_msg>remove leftover<commit_after>package main

import (
	"flag"
	"fmt"
	"github.com/dim13/unifi"
)

func getname(s unifi.Sta) string {
	if s.Hostname != "" {
		return s.Hostname
	}
	if s.Ip != "" {
		return s.Ip
	}
	return s.Mac
}

func main() {
	user := flag.String("user", "admin", "User")
	pass := flag.String("pass", "unifi", "Password")
	url := flag.String("url", "unifi", "URL")
	flag.Parse()

	u := new(unifi.Unifi)
	u.Login(*user, *pass, *url)
	defer u.Logout()

	aps := u.GetAps()
	apmap := make(map[string]string)
	for _, ap := range aps {
		apmap[ap.Mac] = ap.Name
	}

	sta := u.GetClients()
	for _, v := range sta {
		fmt.Printf("%s at %s/%d\n", getname(v), apmap[v.Ap_mac], v.Channel)
	}
}
<|endoftext|>


<commit_before>// Copyright (c) Ilia Kravets, 2015. All rights reserved. PROVIDED "AS IS"
// WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. See LICENSE file for details.

package inspect

import (
	"bytes"
	"fmt"

	"github.com/go-yaml/yaml"
	"github.com/ikravets/errs"

	"my/ev/inspect/device"
)

// XXX field tags are only relevant here for marshalling
type block struct {
	Name string `yaml:",omitempty"`
	Desc string `yaml:",omitempty"`
	Regs []*register
}
type register struct {
	Addr   uint64
	Name   string   `yaml:",omitempty"`
	Desc   string   `yaml:",omitempty"`
	Good   *uint64  `yaml:",omitempty"`
	Fields []*field `yaml:",omitempty"`
	value  uint64
	isBad  bool
}
type field struct {
	Bits  []uint  `yaml:",flow,omitempty"`
	Width uint    `yaml:",omitempty"`
	Name  string  `yaml:",omitempty"`
	Desc  string  `yaml:",omitempty"`
	Good  *uint64 `yaml:",omitempty"`
	value uint64
	isBad bool
	reg   *register
}

type Config struct {
	ast []*block
}

func NewConfig() *Config {
	return &Config{}
}
func (c *Config) Parse(yamlDoc string) (err error) {
	defer errs.PassE(&err)
	errs.CheckE(yaml.Unmarshal([]byte(yamlDoc), &c.ast))
	for _, block := range c.ast {
		for _, register := range block.Regs {
			var currentLSB uint = 0
			for _, field := range register.Fields {
				check := func(cond bool, s string) {
					if !cond {
						errs.CheckE(fmt.Errorf("`%s`/`%s`/`%s`: %s", block.Name, register.Name, field.Name, s))
					}
				}

				// the following ensures that field.Width == field.Bits[1] - field.Bits[0] + 1
				l := len(field.Bits)
				if l == 1 {
					field.Bits = append(field.Bits, field.Bits[0])
				}
				check(l <= 2, "too many bits specified")
				if l == 0 {
					check(field.Width != 0, "missing field location")
					field.Bits = []uint{currentLSB, currentLSB + field.Width - 1}
				} else {
					if field.Bits[0] > field.Bits[1] {
						field.Bits = []uint{field.Bits[1], field.Bits[0]}
					}
					width := field.Bits[1] - field.Bits[0] + 1
					if field.Width == 0 {
						field.Width = width
					}
					check(field.Width == width, "field width inconsistent")
				}

				check(currentLSB <= field.Bits[0], "field is out of order")
				check(63 >= field.Bits[1], "field out of range")
				currentLSB = field.Bits[1] + 1
			}
		}
	}
	return
}

func (c *Config) Dump() (yamlDoc string, err error) {
	defer errs.PassE(&err)
	buf, err := yaml.Marshal(c.ast)
	errs.CheckE(err)
	yamlDoc = string(buf)
	return
}

var blockNameFormat = `

---------------------------------
**      %s     **
---------------------------------
`

func (c *Config) Report() string {
	var buf bytes.Buffer
	for _, block := range c.ast {
		fmt.Fprintf(&buf, blockNameFormat, block.Name)
		fmt.Fprintf(&buf, "%s\n", block.Desc)
		for _, register := range block.Regs {
			fmt.Fprintf(&buf, "\n%s %0#16x value: %0#16x", register.Name, register.Addr, register.value)
			if register.isBad {
				fmt.Fprintf(&buf, " EXPECTED: %0#16x", *register.Good)
			}
			fmt.Fprintf(&buf, "     %s\n", register.Desc)
			for _, field := range register.Fields {
				width := int(field.Width+3) / 4
				fmt.Fprintf(&buf, "%s: %0#[2]*x %[3]d", field.Name, width, field.value)
				if field.isBad {
					fmt.Fprintf(&buf, " EXPECTED: %0#[1]*x %[2]d", width, *field.Good)
				}
				fmt.Fprintf(&buf, "     %s\n", field.Desc)
			}
		}
	}
	return buf.String()
}

func (c *Config) Probe(dev device.Device) (err error) {
	defer errs.PassE(&err)
	for _, block := range c.ast {
		for _, register := range block.Regs {
			register.value, err = dev.ReadRegister(4, register.Addr, 8)
			errs.CheckE(err)
			register.isBad = register.Good != nil && register.value != *register.Good
			for _, field := range register.Fields {
				field.value = register.value >> field.Bits[0] & (1<<field.Width - 1)
				field.isBad = field.Good != nil && field.value != *field.Good
			}
		}
	}
	return
}
<commit_msg>inspect: add new default report format<commit_after>// Copyright (c) Ilia Kravets, 2015. All rights reserved. PROVIDED "AS IS"
// WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. See LICENSE file for details.

package inspect

import (
	"bytes"
	"fmt"

	"github.com/go-yaml/yaml"
	"github.com/ikravets/errs"

	"my/ev/inspect/device"
)

// XXX field tags are only relevant here for marshalling
type block struct {
	Name string `yaml:",omitempty"`
	Desc string `yaml:",omitempty"`
	Regs []*register
}
type register struct {
	Addr   uint64
	Name   string   `yaml:",omitempty"`
	Desc   string   `yaml:",omitempty"`
	Good   *uint64  `yaml:",omitempty"`
	Fields []*field `yaml:",omitempty"`
	value  uint64
	isBad  bool
}
type field struct {
	Bits  []uint  `yaml:",flow,omitempty"`
	Width uint    `yaml:",omitempty"`
	Name  string  `yaml:",omitempty"`
	Desc  string  `yaml:",omitempty"`
	Good  *uint64 `yaml:",omitempty"`
	value uint64
	isBad bool
	reg   *register
}

type Config struct {
	ast []*block
}

func NewConfig() *Config {
	return &Config{}
}
func (c *Config) Parse(yamlDoc string) (err error) {
	defer errs.PassE(&err)
	errs.CheckE(yaml.Unmarshal([]byte(yamlDoc), &c.ast))
	for _, block := range c.ast {
		for _, register := range block.Regs {
			var currentLSB uint = 0
			for _, field := range register.Fields {
				check := func(cond bool, s string) {
					if !cond {
						errs.CheckE(fmt.Errorf("`%s`/`%s`/`%s`: %s", block.Name, register.Name, field.Name, s))
					}
				}

				// the following ensures that field.Width == field.Bits[1] - field.Bits[0] + 1
				l := len(field.Bits)
				if l == 1 {
					field.Bits = append(field.Bits, field.Bits[0])
				}
				check(l <= 2, "too many bits specified")
				if l == 0 {
					check(field.Width != 0, "missing field location")
					field.Bits = []uint{currentLSB, currentLSB + field.Width - 1}
				} else {
					if field.Bits[0] > field.Bits[1] {
						field.Bits = []uint{field.Bits[1], field.Bits[0]}
					}
					width := field.Bits[1] - field.Bits[0] + 1
					if field.Width == 0 {
						field.Width = width
					}
					check(field.Width == width, "field width inconsistent")
				}

				check(currentLSB <= field.Bits[0], "field is out of order")
				check(63 >= field.Bits[1], "field out of range")
				currentLSB = field.Bits[1] + 1
			}
		}
	}
	return
}

func (c *Config) Dump() (yamlDoc string, err error) {
	defer errs.PassE(&err)
	buf, err := yaml.Marshal(c.ast)
	errs.CheckE(err)
	yamlDoc = string(buf)
	return
}

func (c *Config) Report() string {
	var buf bytes.Buffer
	pref := map[bool]byte{false: ' ', true: '*'}
	nd := func(name, desc string) string { return fmt.Sprintf("%-55.55s %s", name, desc) }
	for _, block := range c.ast {
		fmt.Fprintf(&buf, "  %s\n", nd(block.Name, block.Desc))
		for _, reg := range block.Regs {
			fmt.Fprintf(&buf, "%c%12c%0#16x %0#16x %s\n", pref[reg.isBad], ' ', reg.value, reg.Addr, nd(reg.Name, reg.Desc))
			for _, f := range reg.Fields {
				mid := fmt.Sprintf("-%-8d", f.Bits[1])
				if f.Width == 1 {
					mid = fmt.Sprintf("%9c", ' ')
				}
				fmt.Fprintf(&buf, "%c %-10d %0#-18.*[2]x %9[4]d%s %s\n", pref[f.isBad], f.value, int(f.Width+3)/4, f.Bits[0], mid, nd(f.Name, f.Desc))
			}
		}
	}
	return buf.String()
}

func (c *Config) ReportLegacy() string {
	var buf bytes.Buffer
	for _, block := range c.ast {
		fmt.Fprintf(&buf, "\n**      %s      **\n", block.Name)
		fmt.Fprintf(&buf, "%s\n", block.Desc)
		for _, register := range block.Regs {
			fmt.Fprintf(&buf, "\n%s %0#16x value: %0#16x", register.Name, register.Addr, register.value)
			if register.isBad {
				fmt.Fprintf(&buf, " EXPECTED: %0#16x", *register.Good)
			}
			fmt.Fprintf(&buf, "     %s\n", register.Desc)
			for _, field := range register.Fields {
				width := int(field.Width+3) / 4
				fmt.Fprintf(&buf, "%s: %0#[2]*x %[3]d", field.Name, width, field.value)
				if field.isBad {
					fmt.Fprintf(&buf, " EXPECTED: %0#[1]*x %[2]d", width, *field.Good)
				}
				fmt.Fprintf(&buf, "     %s\n", field.Desc)
			}
		}
	}
	return buf.String()
}

func (c *Config) Probe(dev device.Device) (err error) {
	defer errs.PassE(&err)
	for _, block := range c.ast {
		for _, register := range block.Regs {
			register.value, err = dev.ReadRegister(4, register.Addr, 8)
			errs.CheckE(err)
			register.isBad = register.Good != nil && register.value != *register.Good
			for _, field := range register.Fields {
				field.value = register.value >> field.Bits[0] & (1<<field.Width - 1)
				field.isBad = field.Good != nil && field.value != *field.Good
			}
		}
	}
	return
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/dim13/unifi"
)

func getname(s unifi.Sta) string {
	if s.Hostname != "" {
		return s.Hostname
	}
	if s.Ip != "" {
		return s.Ip
	}
	return s.Mac
}

func main() {
	user := flag.String("user", "admin", "User")
	pass := flag.String("pass", "unifi", "Password")
	url := flag.String("url", "unifi", "URL")
	flag.Parse()

	u := new(unifi.Unifi)
	u.Login(*user, *pass, *url)
	defer u.Logout()

	aps := u.GetAps()
	apmap := make(map[string]string)
	for _, ap := range aps {
		apmap[ap.Mac] = ap.Name
	}

	sta := u.GetClients()
	for _, v := range sta {
		fmt.Printf("%s at %s/%d\n", getname(v), apmap[v.Ap_mac], v.Channel)
	}
}
<commit_msg>switch to lib func<commit_after>package main

import (
	"flag"
	"fmt"
	"github.com/dim13/unifi"
)

func main() {
	user := flag.String("user", "admin", "User")
	pass := flag.String("pass", "unifi", "Password")
	url := flag.String("url", "unifi", "URL")
	flag.Parse()

	u := new(unifi.Unifi)
	u.Login(*user, *pass, *url)
	defer u.Logout()

	aps := u.GetAps()
	apmap := make(map[string]string)
	for _, ap := range aps {
		apmap[ap.Mac] = ap.Name
	}

	sta := u.GetClients()
	for _, v := range sta {
		fmt.Printf("%s at %s/%d\n", v.GetName(), apmap[v.Ap_mac], v.Channel)
	}
}
<|endoftext|>