<commit_before>package welove

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

func FarmSign(love Love) (*http.Response, error) {
	u := "http://api.welove520.com/v1/game/farm/signin"
	sigEncoder := NewSig([]byte(KEY))
	// TODO access_token=xxxx&sig=5d74e30439a6656c12aa6dd2f2a5cd85(md5 possible)&ts=1546446867977(current timestamp)
	timestamp := strconv.FormatInt(time.Now().UnixNano()/1e6, 10)

	d1 := Data{"access_token", love.AccessToken}
	d3 := Data{"app_key", love.AppKey}
	d2 := Data{"ts", timestamp}
	sig := sigEncoder.Encode("POST", u, d1, d3, d2)

	data := make(url.Values)
	data.Add("access_token", love.AccessToken)
	data.Add("sig", sig)
	data.Add("ts", timestamp)

	return NewWlHttpClient().Post(u, data)
}

type QueryItem struct {
	Result   int `json:"result"`
	Messages []struct {
		OpTime  int64 `json:"op_time"`
		MsgType int   `json:"msg_type"`
		AdItems []struct {
			ItemID        int    `json:"item_id"`
			Count         int    `json:"count"`
			OpTime        int64  `json:"op_time"`
			NeedHelp      int    `json:"need_help"`
			SellerFarmID  string `json:"seller_farm_id"`
			HeadURLFamale string `json:"head_url_famale"`
			HeadURLMale   string `json:"head_url_male"`
			ID            int    `json:"id"`
			FarmName      string `json:"farm_name"`
			Coin          int    `json:"coin"`
		} `json:"ad_items"`
	} `json:"messages"`
}

func QueryItems(accessToken string) QueryItem {
	u := "http://api.welove520.com/v1/game/farm/ad/query"
	d1 := Data{"access_token", accessToken}
	sigEncoder := NewSig([]byte(KEY))
	sig := sigEncoder.Encode("POST", u, d1)
	data := make(url.Values)
	data.Add("access_token", accessToken)
	data.Add("sig", sig)
	res, err := http.PostForm(u, data)
	if err != nil {
		panic(err)
	}
	bytes, _ := ioutil.ReadAll(res.Body)
	queryItem := QueryItem{}
	json.Unmarshal(bytes, &queryItem)
	return queryItem
}

type BuyItemStatus struct {
	Result   int `json:"result"`
	Messages []struct {
		StallItem struct {
			BuyerHeadURL  string `json:"buyer_head_url"`
			BuyerFarmName string `json:"buyer_farm_name"`
			ID            int    `json:"id"`
		} `json:"stall_item,omitempty"`
		OpTime     int64 `json:"op_time"`
		MsgType    int   `json:"msg_type"`
		Warehouses []struct {
			Category int `json:"category"`
			ItemsInc []struct {
				ItemID int `json:"item_id"`
				Count  int `json:"count"`
			} `json:"items_inc"`
		} `json:"warehouses,omitempty"`
		FarmID   string `json:"farm_id,omitempty"`
		GoldCost int    `json:"gold_cost,omitempty"`
	} `json:"messages"`
}

func BuyItem(accessToken, sellerFarmId string, stallSaleId int) BuyItemStatus {
	u := "http://api.welove520.com/v1/game/farm/stall/buy"
	d1 := Data{"access_token", accessToken}
	d2 := Data{"seller_farm_id", sellerFarmId}
	d3 := Data{"stall_sale_id", strconv.Itoa(stallSaleId)}
	sigEncoder := NewSig([]byte(KEY))
	sig := sigEncoder.Encode("POST", u, d1, d2, d3)

	data := make(url.Values)
	data.Add("access_token", accessToken)
	data.Add("seller_farm_id", sellerFarmId)
	data.Add("stall_sale_id", strconv.Itoa(stallSaleId))
	data.Add("sig", sig)
	res, err := http.PostForm(u, data)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	bytes, _ := ioutil.ReadAll(res.Body)
	buyItemStatus := BuyItemStatus{}
	json.Unmarshal(bytes, &buyItemStatus)
	return buyItemStatus
}
<commit_msg>Return empty struct when error found<commit_after>package welove

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

func FarmSign(love Love) (*http.Response, error) {
	u := "http://api.welove520.com/v1/game/farm/signin"
	sigEncoder := NewSig([]byte(KEY))
	// TODO access_token=xxxx&sig=5d74e30439a6656c12aa6dd2f2a5cd85(md5 possible)&ts=1546446867977(current timestamp)
	timestamp := strconv.FormatInt(time.Now().UnixNano()/1e6, 10)

	d1 := Data{"access_token", love.AccessToken}
	d3 := Data{"app_key", love.AppKey}
	d2 := Data{"ts", timestamp}
	sig := sigEncoder.Encode("POST", u, d1, d3, d2)

	data := make(url.Values)
	data.Add("access_token", love.AccessToken)
	data.Add("sig", sig)
	data.Add("ts", timestamp)

	return NewWlHttpClient().Post(u, data)
}

type QueryItem struct {
	Result   int `json:"result"`
	Messages []struct {
		OpTime  int64 `json:"op_time"`
		MsgType int   `json:"msg_type"`
		AdItems []struct {
			ItemID        int    `json:"item_id"`
			Count         int    `json:"count"`
			OpTime        int64  `json:"op_time"`
			NeedHelp      int    `json:"need_help"`
			SellerFarmID  string `json:"seller_farm_id"`
			HeadURLFamale string `json:"head_url_famale"`
			HeadURLMale   string `json:"head_url_male"`
			ID            int    `json:"id"`
			FarmName      string `json:"farm_name"`
			Coin          int    `json:"coin"`
		} `json:"ad_items"`
	} `json:"messages"`
}

func QueryItems(accessToken string) QueryItem {
	u := "http://api.welove520.com/v1/game/farm/ad/query"
	d1 := Data{"access_token", accessToken}
	sigEncoder := NewSig([]byte(KEY))
	sig := sigEncoder.Encode("POST", u, d1)
	data := make(url.Values)
	data.Add("access_token", accessToken)
	data.Add("sig", sig)
	res, err := http.PostForm(u, data)
	if err != nil {
		panic(err)
	}
	bytes, _ := ioutil.ReadAll(res.Body)
	queryItem := QueryItem{}
	err = json.Unmarshal(bytes, &queryItem)
	if err != nil {
		return QueryItem{}
	}
	return queryItem
}

type BuyItemStatus struct {
	Result   int `json:"result"`
	Messages []struct {
		StallItem struct {
			BuyerHeadURL  string `json:"buyer_head_url"`
			BuyerFarmName string `json:"buyer_farm_name"`
			ID            int    `json:"id"`
		} `json:"stall_item,omitempty"`
		OpTime     int64 `json:"op_time"`
		MsgType    int   `json:"msg_type"`
		Warehouses []struct {
			Category int `json:"category"`
			ItemsInc []struct {
				ItemID int `json:"item_id"`
				Count  int `json:"count"`
			} `json:"items_inc"`
		} `json:"warehouses,omitempty"`
		FarmID   string `json:"farm_id,omitempty"`
		GoldCost int    `json:"gold_cost,omitempty"`
	} `json:"messages"`
}

func BuyItem(accessToken, sellerFarmId string, stallSaleId int) BuyItemStatus {
	u := "http://api.welove520.com/v1/game/farm/stall/buy"
	d1 := Data{"access_token", accessToken}
	d2 := Data{"seller_farm_id", sellerFarmId}
	d3 := Data{"stall_sale_id", strconv.Itoa(stallSaleId)}
	sigEncoder := NewSig([]byte(KEY))
	sig := sigEncoder.Encode("POST", u, d1, d2, d3)

	data := make(url.Values)
	data.Add("access_token", accessToken)
	data.Add("seller_farm_id", sellerFarmId)
	data.Add("stall_sale_id", strconv.Itoa(stallSaleId))
	data.Add("sig", sig)
	res, err := http.PostForm(u, data)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	bytes, _ := ioutil.ReadAll(res.Body)
	buyItemStatus := BuyItemStatus{}
	json.Unmarshal(bytes, &buyItemStatus)
	return buyItemStatus
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"flag"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"strconv"
	"strings"
)

type Album struct {
	Title, Artist, Folder string
}

var albums []Album

var html *template.Template

var mplayer io.Writer

func handler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/favicon.ico" {
		http.NotFound(w, r)
		return
	}

	if r.FormValue("u") != "" {
		mplayer.Write([]byte("loadlist '" + r.FormValue("u") + "'\n"))
	} else if r.FormValue("f") != "" {
		mplayer.Write([]byte("loadfile '" + r.FormValue("f") + "'\n"))
	} else if r.FormValue("d") != "" {
		folder := r.FormValue("d")
		cmd := exec.Command("find", folder, "-type", "f")
		var out bytes.Buffer
		cmd.Stdout = &out
		cmd.Run()
		playlist, _ := ioutil.TempFile("", "jukebox")
		ioutil.WriteFile(playlist.Name(), []byte(out.String()), 0644)
		mplayer.Write([]byte("loadlist '" + playlist.Name() + "'\n"))
	} else if r.FormValue("c") != "" {
		mplayer.Write([]byte(r.FormValue("c") + "\n"))
	}

	html.Execute(w, albums)
}

func buildTemplates() {
	const _html = `<!DOCTYPE html>
<title>jukebox</title><meta name="viewport" content="width=device-width, initial-scale=1.0">

[stop]

Radio 4

Radio 5 live

Groove Salad

<form><input name="f" placeholder="URL"></form>
  {{range .}}
{{.Artist}} - {{.Title}}{{end}}

`
	html = template.Must(template.New("html").Parse(_html))
}

func findAlbums(root string) {
	cmd := exec.Command("find", root, "-mindepth", "2", "-maxdepth", "2", "-type", "d")
	output, err := cmd.Output()
	if err != nil {
		log.Fatal("find: ", err)
	}
	lines := strings.Split(string(output), "\n")

	albums = make([]Album, len(lines)-1)
	for i, line := range lines {
		if len(line) > 0 {
			parts := strings.Split(line, "/")
			albums[i] = Album{
				parts[len(parts)-1],
				parts[len(parts)-2],
				line,
			}
		}
	}
}

func startMPlayer() {
	cmd := exec.Command("mplayer", "-slave", "-really-quiet", "-cache", "64", "-idle")
	mplayer, _ = cmd.StdinPipe()
	err := cmd.Start()
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	port := flag.Int("port", 80, "port")
	root := flag.String("root", "", "root")
	flag.Parse()
	if *root == "" {
		panic("root required")
	}

	buildTemplates()
	findAlbums(*root)
	startMPlayer()

	http.HandleFunc("/", handler)
	err := http.ListenAndServe(":"+strconv.Itoa(*port), nil)
	if err != nil {
		log.Fatal("http: ", err)
	}
}
<commit_msg>Redirect on action<commit_after>package main

import (
	"bytes"
	"flag"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"strconv"
	"strings"
)

type Album struct {
	Title, Artist, Folder string
}

var albums []Album

var html *template.Template

var mplayer io.Writer

func handler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/favicon.ico" {
		http.NotFound(w, r)
		return
	}

	if r.URL.RawQuery == "" {
		html.Execute(w, albums)
		return
	}

	if r.FormValue("u") != "" {
		mplayer.Write([]byte("loadlist '" + r.FormValue("u") + "'\n"))
	} else if r.FormValue("f") != "" {
		mplayer.Write([]byte("loadfile '" + r.FormValue("f") + "'\n"))
	} else if r.FormValue("d") != "" {
		folder := r.FormValue("d")
		cmd := exec.Command("find", folder, "-type", "f")
		var out bytes.Buffer
		cmd.Stdout = &out
		cmd.Run()
		playlist, _ := ioutil.TempFile("", "jukebox")
		ioutil.WriteFile(playlist.Name(), []byte(out.String()), 0644)
		mplayer.Write([]byte("loadlist '" + playlist.Name() + "'\n"))
	} else if r.FormValue("c") != "" {
		mplayer.Write([]byte(r.FormValue("c") + "\n"))
	}
	http.Redirect(w, r, "", http.StatusFound)
}

func buildTemplates() {
	const _html = `<!DOCTYPE html>
<title>jukebox</title><meta name="viewport" content="width=device-width, initial-scale=1.0">

[stop]

Radio 4

Radio 5 live

Groove Salad

<form><input name="f" placeholder="URL"></form>
  {{range .}}
{{.Artist}} - {{.Title}}{{end}}

`
	html = template.Must(template.New("html").Parse(_html))
}

func findAlbums(root string) {
	cmd := exec.Command("find", root, "-mindepth", "2", "-maxdepth", "2", "-type", "d")
	output, err := cmd.Output()
	if err != nil {
		log.Fatal("find: ", err)
	}
	lines := strings.Split(string(output), "\n")

	albums = make([]Album, len(lines)-1)
	for i, line := range lines {
		if len(line) > 0 {
			parts := strings.Split(line, "/")
			albums[i] = Album{
				parts[len(parts)-1],
				parts[len(parts)-2],
				line,
			}
		}
	}
}

func startMPlayer() {
	cmd := exec.Command("mplayer", "-slave", "-really-quiet", "-cache", "64", "-idle")
	mplayer, _ = cmd.StdinPipe()
	err := cmd.Start()
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	port := flag.Int("port", 80, "port")
	root := flag.String("root", "", "root")
	flag.Parse()
	if *root == "" {
		panic("root required")
	}

	buildTemplates()
	findAlbums(*root)
	startMPlayer()

	http.HandleFunc("/", handler)
	err := http.ListenAndServe(":"+strconv.Itoa(*port), nil)
	if err != nil {
		log.Fatal("http: ", err)
	}
}
<|endoftext|>


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

// Package jws provides encoding and decoding utilities for
// signed JWS messages.
package jws // import "golang.org/x/oauth2/jws"

import (
	"bytes"
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"
)

// ClaimSet contains information about the JWT signature including the
// permissions being requested (scopes), the target of the token, the issuer,
// the time the token was issued, and the lifetime of the token.
type ClaimSet struct {
	Iss   string `json:"iss"`             // email address of the client_id of the application making the access token request
	Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
	Aud   string `json:"aud"`             // descriptor of the intended target of the assertion (Optional).
	Exp   int64  `json:"exp"`             // the expiration time of the assertion (seconds since Unix epoch)
	Iat   int64  `json:"iat"`             // the time the assertion was issued (seconds since Unix epoch)
	Typ   string `json:"typ,omitempty"`   // token type (Optional).

	// Email for which the application is requesting delegated access (Optional).
	Sub string `json:"sub,omitempty"`

	// The old name of Sub. Client keeps setting Prn to be
	// complaint with legacy OAuth 2.0 providers. (Optional)
	Prn string `json:"prn,omitempty"`

	// See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3
	// This array is marshalled using custom code (see (c *ClaimSet) encode()).
	PrivateClaims map[string]interface{} `json:"-"`
}

func (c *ClaimSet) encode() (string, error) {
	// Reverting time back for machines whose time is not perfectly in sync.
	// If client machine's time is in the future according
	// to Google servers, an access token will not be issued.
	now := time.Now().Add(-10 * time.Second)
	if c.Iat == 0 {
		c.Iat = now.Unix()
	}
	if c.Exp == 0 {
		c.Exp = now.Add(time.Hour).Unix()
	}
	if c.Exp < c.Iat {
		return "", fmt.Errorf("jws: invalid Exp = %v; must be later than Iat = %v", c.Exp, c.Iat)
	}

	b, err := json.Marshal(c)
	if err != nil {
		return "", err
	}

	if len(c.PrivateClaims) == 0 {
		return base64.RawURLEncoding.EncodeToString(b), nil
	}

	// Marshal private claim set and then append it to b.
	prv, err := json.Marshal(c.PrivateClaims)
	if err != nil {
		return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims)
	}

	// Concatenate public and private claim JSON objects.
	if !bytes.HasSuffix(b, []byte{'}'}) {
		return "", fmt.Errorf("jws: invalid JSON %s", b)
	}
	if !bytes.HasPrefix(prv, []byte{'{'}) {
		return "", fmt.Errorf("jws: invalid JSON %s", prv)
	}
	b[len(b)-1] = ','         // Replace closing curly brace with a comma.
	b = append(b, prv[1:]...) // Append private claims.
	return base64.RawURLEncoding.EncodeToString(b), nil
}

// Header represents the header for the signed JWS payloads.
type Header struct {
	// The algorithm used for signature.
	Algorithm string `json:"alg"`

	// Represents the token type.
	Typ string `json:"typ"`

	// The optional hint of which key is being used.
	KeyID string `json:"kid,omitempty"`
}

func (h *Header) encode() (string, error) {
	b, err := json.Marshal(h)
	if err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(b), nil
}

// Decode decodes a claim set from a JWS payload.
func Decode(payload string) (*ClaimSet, error) {
	// decode returned id token to get expiry
	s := strings.Split(payload, ".")
	if len(s) < 2 {
		// TODO(jbd): Provide more context about the error.
		return nil, errors.New("jws: invalid token received")
	}
	decoded, err := base64.RawURLEncoding.DecodeString(s[1])
	if err != nil {
		return nil, err
	}
	c := &ClaimSet{}
	err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c)
	return c, err
}

// Signer returns a signature for the given data.
type Signer func(data []byte) (sig []byte, err error)

// EncodeWithSigner encodes a header and claim set with the provided signer.
func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) {
	head, err := header.encode()
	if err != nil {
		return "", err
	}
	cs, err := c.encode()
	if err != nil {
		return "", err
	}
	ss := fmt.Sprintf("%s.%s", head, cs)
	sig, err := sg([]byte(ss))
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil
}

// Encode encodes a signed JWS with provided header and claim set.
// This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key.
func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error) {
	sg := func(data []byte) (sig []byte, err error) {
		h := sha256.New()
		h.Write(data)
		return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil))
	}
	return EncodeWithSigner(header, c, sg)
}

// Verify tests whether the provided JWT token's signature was produced by the private key
// associated with the supplied public key.
func Verify(token string, key *rsa.PublicKey) error {
	parts := strings.Split(token, ".")
	if len(parts) != 3 {
		return errors.New("jws: invalid token received, token must have 3 parts")
	}

	signedContent := parts[0] + "." + parts[1]
	signatureString, err := base64.RawURLEncoding.DecodeString(parts[2])
	if err != nil {
		return err
	}

	h := sha256.New()
	h.Write([]byte(signedContent))
	return rsa.VerifyPKCS1v15(key, crypto.SHA256, h.Sum(nil), []byte(signatureString))
}
<commit_msg>jws: add notice that the package might be removed<commit_after>// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package jws provides a partial implementation
// of JSON Web Signature encoding and decoding.
// It exists to support the golang.org/x/oauth2 package.
//
// See RFC 7515.
//
// Deprecated: this package is not intended for public use and might be
// removed in the future. It exists for internal use only.
// Please switch to another JWS package or copy this package into your own
// source tree.
package jws // import "golang.org/x/oauth2/jws"

import (
	"bytes"
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"
)

// ClaimSet contains information about the JWT signature including the
// permissions being requested (scopes), the target of the token, the issuer,
// the time the token was issued, and the lifetime of the token.
type ClaimSet struct {
	Iss   string `json:"iss"`             // email address of the client_id of the application making the access token request
	Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
	Aud   string `json:"aud"`             // descriptor of the intended target of the assertion (Optional).
	Exp   int64  `json:"exp"`             // the expiration time of the assertion (seconds since Unix epoch)
	Iat   int64  `json:"iat"`             // the time the assertion was issued (seconds since Unix epoch)
	Typ   string `json:"typ,omitempty"`   // token type (Optional).

	// Email for which the application is requesting delegated access (Optional).
	Sub string `json:"sub,omitempty"`

	// The old name of Sub. Client keeps setting Prn to be
	// complaint with legacy OAuth 2.0 providers. (Optional)
	Prn string `json:"prn,omitempty"`

	// See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3
	// This array is marshalled using custom code (see (c *ClaimSet) encode()).
	PrivateClaims map[string]interface{} `json:"-"`
}

func (c *ClaimSet) encode() (string, error) {
	// Reverting time back for machines whose time is not perfectly in sync.
	// If client machine's time is in the future according
	// to Google servers, an access token will not be issued.
	now := time.Now().Add(-10 * time.Second)
	if c.Iat == 0 {
		c.Iat = now.Unix()
	}
	if c.Exp == 0 {
		c.Exp = now.Add(time.Hour).Unix()
	}
	if c.Exp < c.Iat {
		return "", fmt.Errorf("jws: invalid Exp = %v; must be later than Iat = %v", c.Exp, c.Iat)
	}

	b, err := json.Marshal(c)
	if err != nil {
		return "", err
	}

	if len(c.PrivateClaims) == 0 {
		return base64.RawURLEncoding.EncodeToString(b), nil
	}

	// Marshal private claim set and then append it to b.
	prv, err := json.Marshal(c.PrivateClaims)
	if err != nil {
		return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims)
	}

	// Concatenate public and private claim JSON objects.
	if !bytes.HasSuffix(b, []byte{'}'}) {
		return "", fmt.Errorf("jws: invalid JSON %s", b)
	}
	if !bytes.HasPrefix(prv, []byte{'{'}) {
		return "", fmt.Errorf("jws: invalid JSON %s", prv)
	}
	b[len(b)-1] = ','         // Replace closing curly brace with a comma.
	b = append(b, prv[1:]...) // Append private claims.
	return base64.RawURLEncoding.EncodeToString(b), nil
}

// Header represents the header for the signed JWS payloads.
type Header struct {
	// The algorithm used for signature.
	Algorithm string `json:"alg"`

	// Represents the token type.
	Typ string `json:"typ"`

	// The optional hint of which key is being used.
	KeyID string `json:"kid,omitempty"`
}

func (h *Header) encode() (string, error) {
	b, err := json.Marshal(h)
	if err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(b), nil
}

// Decode decodes a claim set from a JWS payload.
func Decode(payload string) (*ClaimSet, error) {
	// decode returned id token to get expiry
	s := strings.Split(payload, ".")
	if len(s) < 2 {
		// TODO(jbd): Provide more context about the error.
		return nil, errors.New("jws: invalid token received")
	}
	decoded, err := base64.RawURLEncoding.DecodeString(s[1])
	if err != nil {
		return nil, err
	}
	c := &ClaimSet{}
	err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c)
	return c, err
}

// Signer returns a signature for the given data.
type Signer func(data []byte) (sig []byte, err error)

// EncodeWithSigner encodes a header and claim set with the provided signer.
func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) {
	head, err := header.encode()
	if err != nil {
		return "", err
	}
	cs, err := c.encode()
	if err != nil {
		return "", err
	}
	ss := fmt.Sprintf("%s.%s", head, cs)
	sig, err := sg([]byte(ss))
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil
}

// Encode encodes a signed JWS with provided header and claim set.
// This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key.
func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error) {
	sg := func(data []byte) (sig []byte, err error) {
		h := sha256.New()
		h.Write(data)
		return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil))
	}
	return EncodeWithSigner(header, c, sg)
}

// Verify tests whether the provided JWT token's signature was produced by the private key
// associated with the supplied public key.
func Verify(token string, key *rsa.PublicKey) error {
	parts := strings.Split(token, ".")
	if len(parts) != 3 {
		return errors.New("jws: invalid token received, token must have 3 parts")
	}

	signedContent := parts[0] + "." + parts[1]
	signatureString, err := base64.RawURLEncoding.DecodeString(parts[2])
	if err != nil {
		return err
	}

	h := sha256.New()
	h.Write([]byte(signedContent))
	return rsa.VerifyPKCS1v15(key, crypto.SHA256, h.Sum(nil), []byte(signatureString))
}
<|endoftext|>


<commit_before>package set

import (
	"reflect"
	"testing"
)

func Test_Union(t *testing.T) {
	s := newTS()
	s.Add("1", "2", "3")
	r := newTS()
	r.Add("3", "4", "5")
	x := newNonTS()
	x.Add("5", "6", "7")

	u := Union(s, r, x)
	if settype := reflect.TypeOf(u).String(); settype != "*set.Set" {
		t.Error("Union should derive its set type from the first passed set, got", settype)
	}
	if u.Size() != 7 {
		t.Error("Union: the merged set doesn't have all items in it.")
	}

	if !u.Has("1", "2", "3", "4", "5", "6", "7") {
		t.Error("Union: merged items are not availabile in the set.")
	}

	z := Union(x, r)
	if z.Size() != 5 {
		t.Error("Union: Union of 2 sets doesn't have the proper number of items.")
	}
	if settype := reflect.TypeOf(z).String(); settype != "*set.SetNonTS" {
		t.Error("Union should derive its set type from the first passed set, got", settype)
	}

}

func Test_Difference(t *testing.T) {
	s := newTS()
	s.Add("1", "2", "3")
	r := newTS()
	r.Add("3", "4", "5")
	x := newNonTS()
	x.Add("5", "6", "7")

	u := Difference(s, r, x)

	if u.Size() != 2 {
		t.Error("Difference: the set doesn't have all items in it.")
	}

	if !u.Has("1", "2") {
		t.Error("Difference: items are not availabile in the set.")
	}

	y := Difference(r, r)
	if y.Size() != 0 {
		t.Error("Difference: size should be zero")
	}

}

func Test_Intersection(t *testing.T) {
	s1 := newTS()
	s1.Add("1", "3", "4", "5")
	s2 := newTS()
	s2.Add("3", "5", "6")
	s3 := newTS()
	s3.Add("4", "5", "6", "7")
	u := Intersection(s1, s2, s3)

	if u.Size() != 1 {
		t.Error("Intersection: the set doesn't have all items in it.")
	}

	if !u.Has("5") {
		t.Error("Intersection: items after intersection are not availabile in the set.")
	}
}

func Test_SymmetricDifference(t *testing.T) {
	s := newTS()
	s.Add("1", "2", "3")
	r := newTS()
	r.Add("3", "4", "5")
	u := SymmetricDifference(s, r)

	if u.Size() != 4 {
		t.Error("SymmetricDifference: the set doesn't have all items in it.")
	}

	if !u.Has("1", "2", "4", "5") {
		t.Error("SymmetricDifference: items are not availabile in the set.")
	}
}

func Test_StringSlice(t *testing.T) {
	s := newTS()
	s.Add("san francisco", "istanbul", 3.14, 1321, "ankara")
	u := StringSlice(s)

	if len(u) != 3 {
		t.Error("StringSlice: slice should only have three items")
	}

	for _, item := range u {
		r := reflect.TypeOf(item)
		if r.Kind().String() != "string" {
			t.Error("StringSlice: slice item should be a string")
		}
	}
}

func Test_IntSlice(t *testing.T) {
	s := newTS()
	s.Add("san francisco", "istanbul", 3.14, 1321, "ankara", 8876)
	u := IntSlice(s)

	if len(u) != 2 {
		t.Error("IntSlice: slice should only have two items")
	}

	for _, item := range u {
		r := reflect.TypeOf(item)
		if r.Kind().String() != "int" {
			t.Error("Intslice: slice item should be a int")
		}
	}
}

func BenchmarkSetEquality(b *testing.B) {
	s := newTS()
	u := newTS()

	for i := 0; i < b.N; i++ {
		s.Add(i)
		u.Add(i)
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		s.IsEqual(u)
	}
}

func BenchmarkSubset(b *testing.B) {
	s := newTS()
	u := newTS()

	for i := 0; i < b.N; i++ {
		s.Add(i)
		u.Add(i)
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		s.IsSubset(u)
	}
}

func benchmarkIntersection(b *testing.B, numberOfItems int) {
	s1 := newTS()
	s2 := newTS()

	for i := 0; i < numberOfItems/2; i++ {
		s1.Add(i)
	}
	for i := 0; i < numberOfItems; i++ {
		s2.Add(i)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		Intersection(s1, s2)
	}
}

func BenchmarkIntersection10(b *testing.B) {
	benchmarkIntersection(b, 10)
}

func BenchmarkIntersection100(b *testing.B) {
	benchmarkIntersection(b, 100)
}

func BenchmarkIntersection1000(b *testing.B) {
	benchmarkIntersection(b, 1000)
}

func BenchmarkIntersection10000(b *testing.B) {
	benchmarkIntersection(b, 10000)
}

func BenchmarkIntersection100000(b *testing.B) {
	benchmarkIntersection(b, 100000)
}

func BenchmarkIntersection1000000(b *testing.B) {
	benchmarkIntersection(b, 1000000)
}
<commit_msg>test demonstrating bug in intersection<commit_after>package set

import (
	"reflect"
	"testing"
)

func Test_Union(t *testing.T) {
	s := newTS()
	s.Add("1", "2", "3")
	r := newTS()
	r.Add("3", "4", "5")
	x := newNonTS()
	x.Add("5", "6", "7")

	u := Union(s, r, x)
	if settype := reflect.TypeOf(u).String(); settype != "*set.Set" {
		t.Error("Union should derive its set type from the first passed set, got", settype)
	}
	if u.Size() != 7 {
		t.Error("Union: the merged set doesn't have all items in it.")
	}

	if !u.Has("1", "2", "3", "4", "5", "6", "7") {
		t.Error("Union: merged items are not availabile in the set.")
	}

	z := Union(x, r)
	if z.Size() != 5 {
		t.Error("Union: Union of 2 sets doesn't have the proper number of items.")
	}
	if settype := reflect.TypeOf(z).String(); settype != "*set.SetNonTS" {
		t.Error("Union should derive its set type from the first passed set, got", settype)
	}

}

func Test_Difference(t *testing.T) {
	s := newTS()
	s.Add("1", "2", "3")
	r := newTS()
	r.Add("3", "4", "5")
	x := newNonTS()
	x.Add("5", "6", "7")

	u := Difference(s, r, x)

	if u.Size() != 2 {
		t.Error("Difference: the set doesn't have all items in it.")
	}

	if !u.Has("1", "2") {
		t.Error("Difference: items are not availabile in the set.")
	}

	y := Difference(r, r)
	if y.Size() != 0 {
		t.Error("Difference: size should be zero")
	}

}

func Test_Intersection(t *testing.T) {
	s1 := newTS()
	s1.Add("1", "3", "4", "5")
	s2 := newTS()
	s2.Add("3", "5", "6")
	s3 := newTS()
	s3.Add("4", "5", "6", "7")
	u := Intersection(s1, s2, s3)

	if u.Size() != 1 {
		t.Error("Intersection: the set doesn't have all items in it.")
	}

	if !u.Has("5") {
		t.Error("Intersection: items after intersection are not availabile in the set.")
	}
}

func Test_Intersection2(t *testing.T) {
	s1 := newTS()
	s1.Add("1", "3", "4", "5")
	s2 := newTS()
	s2.Add("5", "6")
	i := Intersection(s1, s2)

	if i.Size() != 1 {
		t.Error("Intersection: size should be 1, it was", i.Size())
	}

	if !i.Has("5") {
		t.Error("Intersection: items after intersection are not availabile in the set.")
	}
}

func Test_SymmetricDifference(t *testing.T) {
	s := newTS()
	s.Add("1", "2", "3")
	r := newTS()
	r.Add("3", "4", "5")
	u := SymmetricDifference(s, r)

	if u.Size() != 4 {
		t.Error("SymmetricDifference: the set doesn't have all items in it.")
	}

	if !u.Has("1", "2", "4", "5") {
		t.Error("SymmetricDifference: items are not availabile in the set.")
	}
}

func Test_StringSlice(t *testing.T) {
	s := newTS()
	s.Add("san francisco", "istanbul", 3.14, 1321, "ankara")
	u := StringSlice(s)

	if len(u) != 3 {
		t.Error("StringSlice: slice should only have three items")
	}

	for _, item := range u {
		r := reflect.TypeOf(item)
		if r.Kind().String() != "string" {
			t.Error("StringSlice: slice item should be a string")
		}
	}
}

func Test_IntSlice(t *testing.T) {
	s := newTS()
	s.Add("san francisco", "istanbul", 3.14, 1321, "ankara", 8876)
	u := IntSlice(s)

	if len(u) != 2 {
		t.Error("IntSlice: slice should only have two items")
	}

	for _, item := range u {
		r := reflect.TypeOf(item)
		if r.Kind().String() != "int" {
			t.Error("Intslice: slice item should be a int")
		}
	}
}

func BenchmarkSetEquality(b *testing.B) {
	s := newTS()
	u := newTS()

	for i := 0; i < b.N; i++ {
		s.Add(i)
		u.Add(i)
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		s.IsEqual(u)
	}
}

func BenchmarkSubset(b *testing.B) {
	s := newTS()
	u := newTS()

	for i := 0; i < b.N; i++ {
		s.Add(i)
		u.Add(i)
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		s.IsSubset(u)
	}
}

func benchmarkIntersection(b *testing.B, numberOfItems int) {
	s1 := newTS()
	s2 := newTS()

	for i := 0; i < numberOfItems/2; i++ {
		s1.Add(i)
	}
	for i := 0; i < numberOfItems; i++ {
		s2.Add(i)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		Intersection(s1, s2)
	}
}

func BenchmarkIntersection10(b *testing.B) {
	benchmarkIntersection(b, 10)
}

func BenchmarkIntersection100(b *testing.B) {
	benchmarkIntersection(b, 100)
}

func BenchmarkIntersection1000(b *testing.B) {
	benchmarkIntersection(b, 1000)
}

func BenchmarkIntersection10000(b *testing.B) {
	benchmarkIntersection(b, 10000)
}

func BenchmarkIntersection100000(b *testing.B) {
	benchmarkIntersection(b, 100000)
}

func BenchmarkIntersection1000000(b *testing.B) {
	benchmarkIntersection(b, 1000000)
}
<|endoftext|>


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

package os

import (
	"syscall"
	"time"
)

// Getpagesize returns the underlying system's memory page size.
func Getpagesize() int { return syscall.Getpagesize() }

// A FileInfo describes a file and is returned by Stat and Lstat
type FileInfo interface {
	Name() string       // base name of the file
	Size() int64        // length in bytes for regular files; system-dependent for others
	Mode() FileMode     // file mode bits
	ModTime() time.Time // modification time
	IsDir() bool        // abbreviation for Mode().IsDir()
	Sys() interface{}   // underlying data source (can return nil)
}

// A FileMode represents a file's mode and permission bits.
// The bits have the same definition on all systems, so that
// information about files can be moved from one system
// to another portably.  Not all bits apply to all systems.
// The only required bit is ModeDir for directories.
type FileMode uint32

// The defined file mode bits are the most significant bits of the FileMode.
// The nine least-significant bits are the standard Unix rwxrwxrwx permissions.
// The values of these bits should be considered part of the public API and
// may be used in wire protocols or disk representations: they must not be
// changed, although new bits might be added.
const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
	ModeAppend                                     // a: append-only
	ModeExclusive                                  // l: exclusive use
	ModeTemporary                                  // T: temporary file (not backed up)
	ModeSymlink                                    // L: symbolic link
	ModeDevice                                     // D: device file
	ModeNamedPipe                                  // p: named pipe (FIFO)
	ModeSocket                                     // S: Unix domain socket
	ModeSetuid                                     // u: setuid
	ModeSetgid                                     // g: setgid
	ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
	ModeSticky                                     // t: sticky

	// Mask for the type bits. For regular files, none will be set.
	ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice

	ModePerm FileMode = 0777 // permission bits
)

func (m FileMode) String() string {
	const str = "dalTLDpSugct"
	var buf [20]byte
	w := 0
	for i, c := range str {
		if m&(1<<uint(32-1-i)) != 0 {
			buf[w] = byte(c)
			w++
		}
	}
	if w == 0 {
		buf[w] = '-'
		w++
	}
	const rwx = "rwxrwxrwx"
	for i, c := range rwx {
		if m&(1<<uint(9-1-i)) != 0 {
			buf[w] = byte(c)
		} else {
			buf[w] = '-'
		}
		w++
	}
	return string(buf[:w])
}

// IsDir reports whether m describes a directory.
// That is, it tests for the ModeDir bit being set in m.
func (m FileMode) IsDir() bool {
	return m&ModeDir != 0
}

// Perm returns the Unix permission bits in m.
func (m FileMode) Perm() FileMode {
	return m & ModePerm
}

// A fileStat is the implementation of FileInfo returned by Stat and Lstat.
type fileStat struct {
	name    string
	size    int64
	mode    FileMode
	modTime time.Time
	sys     interface{}
}

func (fs *fileStat) Name() string       { return fs.name }
func (fs *fileStat) Size() int64        { return fs.size }
func (fs *fileStat) Mode() FileMode     { return fs.mode }
func (fs *fileStat) ModTime() time.Time { return fs.modTime }
func (fs *fileStat) IsDir() bool        { return fs.mode.IsDir() }
func (fs *fileStat) Sys() interface{}   { return fs.sys }

// SameFile reports whether fi1 and fi2 describe the same file.
// For example, on Unix this means that the device and inode fields
// of the two underlying structures are identical; on other systems
// the decision may be based on the path names.
// SameFile only applies to results returned by this package's Stat.
// It returns false in other cases.
func SameFile(fi1, fi2 FileInfo) bool {
	fs1, ok1 := fi1.(*fileStat)
	fs2, ok2 := fi2.(*fileStat)
	if !ok1 || !ok2 {
		return false
	}
	return sameFile(fs1.sys, fs2.sys)
}
<commit_msg>os: add missing byte to FileMode buffer<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package os

import (
	"syscall"
	"time"
)

// Getpagesize returns the underlying system's memory page size.
func Getpagesize() int { return syscall.Getpagesize() }

// A FileInfo describes a file and is returned by Stat and Lstat
type FileInfo interface {
	Name() string       // base name of the file
	Size() int64        // length in bytes for regular files; system-dependent for others
	Mode() FileMode     // file mode bits
	ModTime() time.Time // modification time
	IsDir() bool        // abbreviation for Mode().IsDir()
	Sys() interface{}   // underlying data source (can return nil)
}

// A FileMode represents a file's mode and permission bits.
// The bits have the same definition on all systems, so that
// information about files can be moved from one system
// to another portably.  Not all bits apply to all systems.
// The only required bit is ModeDir for directories.
type FileMode uint32

// The defined file mode bits are the most significant bits of the FileMode.
// The nine least-significant bits are the standard Unix rwxrwxrwx permissions.
// The values of these bits should be considered part of the public API and
// may be used in wire protocols or disk representations: they must not be
// changed, although new bits might be added.
const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
	ModeAppend                                     // a: append-only
	ModeExclusive                                  // l: exclusive use
	ModeTemporary                                  // T: temporary file (not backed up)
	ModeSymlink                                    // L: symbolic link
	ModeDevice                                     // D: device file
	ModeNamedPipe                                  // p: named pipe (FIFO)
	ModeSocket                                     // S: Unix domain socket
	ModeSetuid                                     // u: setuid
	ModeSetgid                                     // g: setgid
	ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
	ModeSticky                                     // t: sticky

	// Mask for the type bits. For regular files, none will be set.
	ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice

	ModePerm FileMode = 0777 // permission bits
)

func (m FileMode) String() string {
	const str = "dalTLDpSugct"
	var buf [32]byte // Mode is uint32.
	w := 0
	for i, c := range str {
		if m&(1<<uint(32-1-i)) != 0 {
			buf[w] = byte(c)
			w++
		}
	}
	if w == 0 {
		buf[w] = '-'
		w++
	}
	const rwx = "rwxrwxrwx"
	for i, c := range rwx {
		if m&(1<<uint(9-1-i)) != 0 {
			buf[w] = byte(c)
		} else {
			buf[w] = '-'
		}
		w++
	}
	return string(buf[:w])
}

// IsDir reports whether m describes a directory.
// That is, it tests for the ModeDir bit being set in m.
func (m FileMode) IsDir() bool {
	return m&ModeDir != 0
}

// Perm returns the Unix permission bits in m.
func (m FileMode) Perm() FileMode {
	return m & ModePerm
}

// A fileStat is the implementation of FileInfo returned by Stat and Lstat.
type fileStat struct {
	name    string
	size    int64
	mode    FileMode
	modTime time.Time
	sys     interface{}
}

func (fs *fileStat) Name() string       { return fs.name }
func (fs *fileStat) Size() int64        { return fs.size }
func (fs *fileStat) Mode() FileMode     { return fs.mode }
func (fs *fileStat) ModTime() time.Time { return fs.modTime }
func (fs *fileStat) IsDir() bool        { return fs.mode.IsDir() }
func (fs *fileStat) Sys() interface{}   { return fs.sys }

// SameFile reports whether fi1 and fi2 describe the same file.
// For example, on Unix this means that the device and inode fields
// of the two underlying structures are identical; on other systems
// the decision may be based on the path names.
// SameFile only applies to results returned by this package's Stat.
// It returns false in other cases.
func SameFile(fi1, fi2 FileInfo) bool {
	fs1, ok1 := fi1.(*fileStat)
	fs2, ok2 := fi2.(*fileStat)
	if !ok1 || !ok2 {
		return false
	}
	return sameFile(fs1.sys, fs2.sys)
}
<|endoftext|>


<commit_before>package server

import (
	"testing"

	"github.com/garyburd/redigo/redis"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"

	"warcluster/entities/db"
)

const (
	user        = "{\"Command\": \"login\", \"Username\": \"JohnDoe\", \"TwitterId\": \"some twitter ID\"}"
	setupParams = "{\"Command\": \"setup_parameters\", \"Fraction\": 0, \"SunTextureId\": 0}"
)

type ClientTestSuite struct {
	suite.Suite
	conn    redis.Conn
	session *testSession
}

func (suite *ClientTestSuite) SetupTest() {
	suite.conn = db.Pool.Get()
	suite.conn.Do("FLUSHDB")
	suite.session = new(testSession)
}

func (suite *ClientTestSuite) TearDownTest() {
	suite.conn.Close()
}

func (suite *ClientTestSuite) TestRegisterNewUser() {
	suite.session.Send([]byte(user))
	suite.session.Send([]byte(setupParams))

	players_before, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	before := len(players_before)

	_, err = authenticate(suite.session)

	assert.Nil(suite.T(), err)

	players_after, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	after := len(players_after)

	assert.Nil(suite.T(), err)

	assert.Equal(suite.T(), before+1, after)
}

func (suite *ClientTestSuite) TestAuthenticateExcistingUser() {
	suite.session.Send([]byte(user))
	suite.session.Send([]byte(setupParams))
	suite.session.Send([]byte(user))

	players_before, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	before := len(players_before)

	authenticate(suite.session)
	authenticate(suite.session)

	players_after, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	after := len(players_after)

	assert.Nil(suite.T(), err)

	assert.Equal(suite.T(), before+1, after)
}

func (suite *ClientTestSuite) TestAuthenticateUserWithIncompleteData() {
	suite.session.Send([]byte("{\"Command\": \"login\", \"TwitterId\": \"some twitter ID\"}"))

	players_before, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	before := len(players_before)

	authenticate(suite.session)

	players_after, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	after := len(players_after)

	assert.Nil(suite.T(), err)

	assert.Equal(suite.T(), before, after)
}

func (suite *ClientTestSuite) TestUnableToRegisterNewUserWithWrongCommand() {
	setup := "{\"Command\": \"setup\", \"Fraction\": 0, \"SunTextureId\": 0}"

	suite.session.Send([]byte(user))
	suite.session.Send([]byte(setup))

	players_before, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	before := len(players_before)

	_, err = authenticate(suite.session)

	assert.NotNil(suite.T(), err)

	players_after, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	after := len(players_after)

	assert.Nil(suite.T(), err)

	assert.Equal(suite.T(), before, after)
}

func (suite *ClientTestSuite) TestAuthenticateUserWithNilData() {
	suite.session.Send(nil)
	_, err := authenticate(suite.session)

	assert.NotNil(suite.T(), err)
}

func (suite *ClientTestSuite) TestAuthenticateUserWithInvalidJSONData() {
	suite.session.Send([]byte("panda"))
	_, err := authenticate(suite.session)

	assert.NotNil(suite.T(), err)
}

func (suite *ClientTestSuite) TestAuthenticateUserWithNilSetupData() {
	suite.session.Send([]byte(user))
	suite.session.Send(nil)
	_, err := authenticate(suite.session)

	assert.NotNil(suite.T(), err)
}

func TestClientTestSuite(t *testing.T) {
	suite.Run(t, new(ClientTestSuite))
}
<commit_msg>Manually select database after dialing to redis<commit_after>package server

import (
	"testing"

	"github.com/garyburd/redigo/redis"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"

	"warcluster/entities/db"
)

const (
	user        = "{\"Command\": \"login\", \"Username\": \"JohnDoe\", \"TwitterId\": \"some twitter ID\"}"
	setupParams = "{\"Command\": \"setup_parameters\", \"Fraction\": 0, \"SunTextureId\": 0}"
)

type ClientTestSuite struct {
	suite.Suite
	conn    redis.Conn
	session *testSession
}

func (suite *ClientTestSuite) SetupTest() {
	suite.conn = db.Pool.Get()
	suite.conn.Do("FLUSHDB")
	suite.session = new(testSession)
}

func (suite *ClientTestSuite) TearDownTest() {
	suite.conn.Close()
}

func (suite *ClientTestSuite) TestRegisterNewUser() {
	suite.session.Send([]byte(user))
	suite.session.Send([]byte(setupParams))

	players_before, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	before := len(players_before)

	_, err = authenticate(suite.session)

	assert.Nil(suite.T(), err)

	players_after, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	after := len(players_after)

	assert.Nil(suite.T(), err)

	assert.Equal(suite.T(), before+1, after)
}

<<<<<<< HEAD
func (suite *ClientTestSuite) TestAuthenticateExcistingUser() {
	suite.session.Send([]byte(user))
	suite.session.Send([]byte(setupParams))
	suite.session.Send([]byte(user))
=======
func TestAuthenticateExcistingUser(t *testing.T) {
	conn := db.Pool.Get()
	defer conn.Close()
	conn.Do("FLUSHDB")
>>>>>>> Manually select database after dialing to redis

	players_before, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	before := len(players_before)

	authenticate(suite.session)
	authenticate(suite.session)

	players_after, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	after := len(players_after)

	assert.Nil(suite.T(), err)

	assert.Equal(suite.T(), before+1, after)
}

<<<<<<< HEAD
func (suite *ClientTestSuite) TestAuthenticateUserWithIncompleteData() {
	suite.session.Send([]byte("{\"Command\": \"login\", \"TwitterId\": \"some twitter ID\"}"))
=======
func TestAuthenticateUserWithIncompleteData(t *testing.T) {
	conn := db.Pool.Get()
	defer conn.Close()
	conn.Do("FLUSHDB")

	var session testSession
	session.Send([]byte("{\"Command\": \"login\", \"TwitterId\": \"some twitter ID\"}"))
>>>>>>> Manually select database after dialing to redis

	players_before, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	before := len(players_before)

	authenticate(suite.session)

	players_after, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	after := len(players_after)

	assert.Nil(suite.T(), err)

	assert.Equal(suite.T(), before, after)
}

func (suite *ClientTestSuite) TestUnableToRegisterNewUserWithWrongCommand() {
	setup := "{\"Command\": \"setup\", \"Fraction\": 0, \"SunTextureId\": 0}"

	suite.session.Send([]byte(user))
	suite.session.Send([]byte(setup))

	players_before, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	before := len(players_before)

	_, err = authenticate(suite.session)

	assert.NotNil(suite.T(), err)

	players_after, err := redis.Strings(suite.conn.Do("KEYS", "player.*"))
	after := len(players_after)

	assert.Nil(suite.T(), err)

	assert.Equal(suite.T(), before, after)
}

<<<<<<< HEAD
func (suite *ClientTestSuite) TestAuthenticateUserWithNilData() {
	suite.session.Send(nil)
	_, err := authenticate(suite.session)
=======
func TestAuthenticateUserWithNilData(t *testing.T) {
	conn := db.Pool.Get()
	defer conn.Close()
	conn.Do("FLUSHDB")

	session := new(testSession)
	session.Send(nil)
	_, err := authenticate(session)
>>>>>>> Manually select database after dialing to redis

	assert.NotNil(suite.T(), err)
}

<<<<<<< HEAD
func (suite *ClientTestSuite) TestAuthenticateUserWithInvalidJSONData() {
	suite.session.Send([]byte("panda"))
	_, err := authenticate(suite.session)
=======
func TestAuthenticateUserWithInvalidJSONData(t *testing.T) {
	conn := db.Pool.Get()
	defer conn.Close()
	conn.Do("FLUSHDB")
>>>>>>> Manually select database after dialing to redis

	assert.NotNil(suite.T(), err)
}

<<<<<<< HEAD
func (suite *ClientTestSuite) TestAuthenticateUserWithNilSetupData() {
	suite.session.Send([]byte(user))
	suite.session.Send(nil)
	_, err := authenticate(suite.session)
=======
func TestAuthenticateUserWithNilSetupData(t *testing.T) {
	conn := db.Pool.Get()
	defer conn.Close()
	conn.Do("FLUSHDB")
>>>>>>> Manually select database after dialing to redis

	assert.NotNil(suite.T(), err)
}

func TestClientTestSuite(t *testing.T) {
	suite.Run(t, new(ClientTestSuite))
}
<|endoftext|>


<commit_before>package field

import (
	"errors"
)

const (
	TYPE_TEXT         = "text"
	TYPE_NUMBER       = "number"
	TYPE_CHECKBOXES   = "checkboxes"
	TYPE_RADIOBUTTONS = "radiobuttons"
	TYPE_IMAGES       = "images"
)

var ErrMissingType error = errors.New("Missing type.")
var ErrInvalidType error = errors.New("Invalid type.")
var ErrMissingLabel error = errors.New("Missing label.")
var ErrInvalidLabel error = errors.New("Invalid label.")
var ErrMissingValue error = errors.New("Missing value.")
var ErrInvalidValue error = errors.New("Invalid value.")

type Field struct {
	Type         string        `json:"type"`
	Label        string        `json:"label"`
	Required     bool          `json:"required"`
	Text         *Text         `json:"text,omitempty"`
	Number       *Number       `json:"number,omitempty"`
	Checkboxes   *Checkboxes   `json:"checkboxes,omitempty"`
	Radiobuttons *Radiobuttons `json:"radiobuttons,omitempty"`
	Images       *Images       `json:"images,omitempty"`
}

type Value interface {
	Validate() error
	IsEmpty() bool
}

func (field *Field) Validate() error {
	// ensure that only one field is filled out
	if field.Type != TYPE_TEXT && field.Text != nil ||
		field.Type != TYPE_NUMBER && field.Number != nil ||
		field.Type != TYPE_CHECKBOXES && field.Checkboxes != nil ||
		field.Type != TYPE_RADIOBUTTONS && field.Radiobuttons != nil ||
		field.Type != TYPE_IMAGES && field.Images != nil {
		return ErrInvalidValue
	}

	var value Value
	switch field.Type {
	case TYPE_TEXT:
		value = field.Text
	case TYPE_NUMBER:
		value = field.Number
	case TYPE_CHECKBOXES:
		value = field.Checkboxes
	case TYPE_RADIOBUTTONS:
		value = field.Radiobuttons
	case TYPE_IMAGES:
		value = field.Images
	default:
		return ErrInvalidType
	}

	err := value.Validate()
	if err != nil {
		return err
	}
	if field.Required && value.IsEmpty() {
		return ErrInvalidValue
	}
	return nil
}
<commit_msg>Move field value logic into seperate function<commit_after>package field

import (
	"errors"
)

const (
	TYPE_TEXT         = "text"
	TYPE_NUMBER       = "number"
	TYPE_CHECKBOXES   = "checkboxes"
	TYPE_RADIOBUTTONS = "radiobuttons"
	TYPE_IMAGES       = "images"
)

var ErrMissingType error = errors.New("Missing type.")
var ErrInvalidType error = errors.New("Invalid type.")
var ErrMissingLabel error = errors.New("Missing label.")
var ErrInvalidLabel error = errors.New("Invalid label.")
var ErrMissingValue error = errors.New("Missing value.")
var ErrInvalidValue error = errors.New("Invalid value.")
var ErrMultipleValues error = errors.New("Multiple values.")

type Field struct {
	Type         string        `json:"type"`
	Label        string        `json:"label"`
	Required     bool          `json:"required"`
	Text         *Text         `json:"text,omitempty"`
	Number       *Number       `json:"number,omitempty"`
	Checkboxes   *Checkboxes   `json:"checkboxes,omitempty"`
	Radiobuttons *Radiobuttons `json:"radiobuttons,omitempty"`
	Images       *Images       `json:"images,omitempty"`
}

type Value interface {
	Validate() error
	IsEmpty() bool
}

func (field *Field) Validate() error {
	value, err := field.GetValue()
	if err != nil {
		return err
	}
	err = value.Validate()
	if err != nil {
		return err
	}
	if field.Required && value.IsEmpty() {
		return ErrInvalidValue
	}
	return nil
}

func (field *Field) GetValue() (Value, error) {
	// Ensure that at most one value exists, and that it matches the type
	if field.Type != TYPE_TEXT && field.Text != nil ||
		field.Type != TYPE_NUMBER && field.Number != nil ||
		field.Type != TYPE_CHECKBOXES && field.Checkboxes != nil ||
		field.Type != TYPE_RADIOBUTTONS && field.Radiobuttons != nil ||
		field.Type != TYPE_IMAGES && field.Images != nil {
		return nil, ErrMultipleValues
	}

	switch field.Type {
	case TYPE_TEXT:
		return field.Text, nil
	case TYPE_NUMBER:
		return field.Number, nil
	case TYPE_CHECKBOXES:
		return field.Checkboxes, nil
	case TYPE_RADIOBUTTONS:
		return field.Radiobuttons, nil
	case TYPE_IMAGES:
		return field.Images, nil
	default:
		return nil, ErrInvalidType
	}
}
<|endoftext|>


<commit_before>package xsdvalidate

/*
#cgo pkg-config: libxml-2.0
#include <string.h>
#include <libxml/xmlschemastypes.h>
#include <errno.h>
#include <malloc.h>
#include <stdbool.h>
#define GO_ERR_INIT 256
#define P_ERR_DEFAULT 1
#define P_ERR_EXT 2
#define LIBXML_STATIC

struct xsdParserResult {
	xmlSchemaPtr schemaPtr;
	char *errorStr;
};

struct xmlParserResult {
	xmlDocPtr docPtr;
	char *errorStr;
};

struct errCtx {
	char *errBuf;
};

struct simpleXmlError {
	int	code;
	char*	message;
	int 	level;
	int	line;
	char*	node;
};

static void noOutputCallback(void *ctx, const char *message, ...) {
}

static void init() {
	xmlInitParser();
}

static void cleanup() {
	xmlSchemaCleanupTypes();
	xmlCleanupParser();
}

static void genErrorCallback(void *ctx, const char *message, ...) {
	struct errCtx *ectx = ctx;
	char *newLine = malloc(GO_ERR_INIT);

	va_list varArgs;
        va_start(varArgs, message);

	int oldLen = strlen(ectx->errBuf) + 1;
	int lineLen = 1 + vsnprintf(newLine, GO_ERR_INIT, message, varArgs);

	if (lineLen  > GO_ERR_INIT) {
		free(newLine);
		newLine = malloc(lineLen);
		vsnprintf(newLine, lineLen, message, varArgs);
	}
	va_end(varArgs);

	char *tmp = malloc(oldLen + lineLen);
	memcpy(tmp, ectx->errBuf, oldLen);
	strcat(tmp, newLine);
	free(newLine);
	free(ectx->errBuf);
	ectx->errBuf = tmp;
}

void structErrorCallback(void *ctx, xmlErrorPtr p) {
	struct errCtx *ectx = ctx;
	char *newLine = malloc(GO_ERR_INIT);

	//pid_t pid = syscall(__NR_gettid);

	//printf("threadId: %li, code: %d, level: %d, node: %s, line: %d, message: %s", pid, p->code, p->level, ((xmlNodePtr) p->node)->name, p->line, p->message);
	int oldLen = strlen(ectx->errBuf) + 1;
	int lineLen = 1 + snprintf(newLine, GO_ERR_INIT, "%s", p->message);

	if (lineLen  > GO_ERR_INIT) {
		free(newLine);
		newLine = malloc(lineLen);
		snprintf(newLine, lineLen, "%s", p->message);
	}

	char *tmp = malloc(oldLen + lineLen);
	memcpy(tmp, ectx->errBuf, oldLen);
	strcat(tmp, newLine);
	free(newLine);
	free(ectx->errBuf);
	ectx->errBuf = tmp;
}

void simpleStructErrorCallback(void *ctx, xmlErrorPtr p) {
	struct simpleXmlError *sErr = ctx;
	sErr->code = p->code;
	sErr->level = p->level;
	sErr->line = p->line;

        int cpyLen = 1 + snprintf(sErr->message, GO_ERR_INIT, "%s", p->message);
	if (cpyLen > GO_ERR_INIT) {
		free(sErr->message);
		sErr->message = malloc(cpyLen);
		snprintf(sErr->message, cpyLen, "%s", p->message);
	}

	if (p->node !=NULL) {
		cpyLen = 1 + snprintf(sErr->node, GO_ERR_INIT, "%s", (((xmlNodePtr) p->node)->name));
		if (cpyLen > GO_ERR_INIT) {
			free(sErr->node);
			sErr->node= malloc(cpyLen);
			snprintf(sErr->node, cpyLen, "%s", (((xmlNodePtr) p->node)->name));
		}
	}

}

static struct xsdParserResult cParseUrlSchema(const char *url, const short int options) {
	bool err = false;
	struct xsdParserResult parserResult;
	char *errBuf=NULL;
	struct errCtx *ectx=malloc(sizeof(struct errCtx));
	ectx->errBuf=calloc(GO_ERR_INIT, sizeof(char));
	struct errCtx *genEctx=malloc(sizeof(struct errCtx));;
	genEctx->errBuf=calloc(GO_ERR_INIT, sizeof(char));

	xmlSchemaPtr schema = NULL;
	xmlSchemaParserCtxtPtr schemaParserCtxt = NULL;

	xmlLineNumbersDefault(1);

	schemaParserCtxt = xmlSchemaNewParserCtxt(url);

	if (schemaParserCtxt == NULL) {
		err = true;
		strcpy(ectx->errBuf, "Xsd parser internal error");
	}
	else
	{
		if (options & P_ERR_EXT) {
			xmlSetGenericErrorFunc(genEctx, genErrorCallback);
		} else {
			xmlSetGenericErrorFunc(NULL, noOutputCallback);
		}

		xmlSchemaSetParserErrors(schemaParserCtxt, genErrorCallback, noOutputCallback, ectx);

		schema = xmlSchemaParse(schemaParserCtxt);

		xmlSchemaFreeParserCtxt(schemaParserCtxt);
		if (schema == NULL) {
			err = true;
			char *tmp = NULL;
			if (options & P_ERR_EXT) {
				tmp = (char *) malloc(strlen(ectx->errBuf) + strlen(genEctx->errBuf) + 1);
				memcpy(tmp, ectx->errBuf, strlen(ectx->errBuf) + 1);
				strcat(tmp, genEctx->errBuf);
			} else {
				tmp = (char *) malloc(strlen(ectx->errBuf) + 1);
				memcpy(tmp, ectx->errBuf, strlen(ectx->errBuf) + 1);
			}
			free(ectx->errBuf);
			ectx->errBuf = tmp;
		}
	}
	errBuf=malloc(strlen(ectx->errBuf)+1);
	memcpy(errBuf,  ectx->errBuf, strlen(ectx->errBuf)+1);

	free(ectx->errBuf);
	free(ectx);
	free(genEctx->errBuf);
	free(genEctx);
	parserResult.schemaPtr=schema;
	parserResult.errorStr=errBuf;
	errno = err ? -1 : 0;
	return parserResult;
}

static struct xmlParserResult cParseDoc(const char *goXmlSource, const int goXmlSourceLen, const short int options) {
	bool err = false;
	struct xmlParserResult parserResult;
	char *errBuf=NULL;
	struct errCtx *ectx=malloc(sizeof(struct errCtx));
	ectx->errBuf=calloc(GO_ERR_INIT, sizeof(char));;

	xmlLineNumbersDefault(1);

	xmlDocPtr doc=NULL;
	xmlParserCtxtPtr xmlParserCtxt=NULL;

	xmlParserCtxt = xmlNewParserCtxt();

	if (xmlParserCtxt == NULL) {
		err = true;
		strcpy(ectx->errBuf, "Xml parser internal error");
	}
	else
	{
		if (options & P_ERR_EXT) {
			xmlSetGenericErrorFunc(ectx, genErrorCallback);
		} else {
			xmlSetGenericErrorFunc(NULL, noOutputCallback);
		}

		doc = xmlParseMemory(goXmlSource, goXmlSourceLen);

		xmlFreeParserCtxt(xmlParserCtxt);

		if (doc == NULL) {
			if (options & P_ERR_EXT) {
				err = true;
				char *tmp = malloc(strlen(ectx->errBuf) + 1);
				memcpy(tmp, ectx->errBuf, strlen(ectx->errBuf) + 1);
				free(ectx->errBuf);
				ectx->errBuf = tmp;
			} else {
				err = true;
				strcpy(ectx->errBuf, "Malformed xml document");
			}
		}
	}

	errBuf=malloc(strlen(ectx->errBuf)+1);
	memcpy(errBuf,  ectx->errBuf, strlen(ectx->errBuf)+1);
	free(ectx->errBuf);
	free(ectx);
	parserResult.docPtr=doc;
	parserResult.errorStr=errBuf;
	errno = err ? -1 : 0;
	return parserResult;
}

static struct simpleXmlError *cValidate(const xmlDocPtr doc, const xmlSchemaPtr schema) {
	bool err = false;
	int schemaErr=0;

	struct simpleXmlError *simpleError = malloc(sizeof(struct simpleXmlError));
	simpleError->message = calloc(GO_ERR_INIT, sizeof(char));
	simpleError->node = calloc(GO_ERR_INIT, sizeof(char));

	//xmlErrorPtr errPtr= malloc(sizeof(xmlError));

	xmlLineNumbersDefault(1);

	if (schema == NULL) {
		err = true;
		strcpy(simpleError->message, "Xsd schema null pointer");
	}
	else if (doc == NULL) {
		err = true;
		strcpy(simpleError->message, "Xml schema null pointer");
	}
	else
	{
		xmlSchemaValidCtxtPtr schemaCtxt;
		schemaCtxt = xmlSchemaNewValidCtxt(schema);

		if (schemaCtxt == NULL) {
			err = true;
			strcpy(simpleError->message, "Xml validation internal error");
		}
		else
		{

			xmlSchemaSetValidStructuredErrors(schemaCtxt, simpleStructErrorCallback, simpleError);
			schemaErr = xmlSchemaValidateDoc(schemaCtxt, doc);
			xmlSchemaFreeValidCtxt(schemaCtxt);

			if (schemaErr > 0)
			{
				err = true;
			}
			else if (schemaErr < 0)
			{
				err = true;
				strcpy(simpleError->message, "Xml validation internal error");
			}
		}
	}

	errno = err ? -1 : 0;
	return simpleError;
}

*/
import "C"
import (
	"runtime"
	"strings"
	"time"
	"unsafe"
)

// Handles schema parsing and validation, wraps a pointer to libxml2's xmlSchemaPtr.
type XsdHandler struct {
	schemaPtr C.xmlSchemaPtr
}

// Handles xml parsing, wraps a pointer to libxml2's xmlDocPtr.
type XmlHandler struct {
	docPtr C.xmlDocPtr
}

// Initializes the libxml2 parser, suggested for multithreading
func libXml2Init() {
	C.init()
}

// Cleans up the libxml2 parser
func libXml2Cleanup() {
	C.cleanup()
}

// The helper function for parsing xml
func parseXmlMem(inXml []byte, options Options) (C.xmlDocPtr, error) {

	strXml := C.CString(string(inXml))
	defer C.free(unsafe.Pointer(strXml))
	pRes, err := C.cParseDoc(strXml, C.int(len(inXml)), C.short(options))

	defer C.free(unsafe.Pointer(pRes.errorStr))
	if err != nil {
		rStr := C.GoString(pRes.errorStr)
		return nil, XmlParserError{errorMessage{strings.Trim(rStr, "\n")}}
	}
	return pRes.docPtr, nil
}

// The helper function for parsing the schema
func parseUrlSchema(url string, options Options) (C.xmlSchemaPtr, error) {
	strUrl := C.CString(url)
	defer C.free(unsafe.Pointer(strUrl))

	pRes, err := C.cParseUrlSchema(strUrl, C.short(options))
	defer C.free(unsafe.Pointer(pRes.errorStr))
	if err != nil {
		rStr := C.GoString(pRes.errorStr)
		return nil, XsdParserError{errorMessage{strings.Trim(rStr, "\n")}}
	}
	return pRes.schemaPtr, nil
}

// Helper function for validating given an xml document
func validateWithXsd(xmlHandler *XmlHandler, xsdHandler *XsdHandler) error {
	sErr, err := C.cValidate(xmlHandler.docPtr, xsdHandler.schemaPtr)
	defer freeSimpleXmlError(sErr)
	if err != nil {
		return ValidationError{
			Code:     int(sErr.code),
			Message:  strings.Trim(C.GoString(sErr.message), "\n"),
			Level:    int(sErr.level),
			Line:     int(sErr.line),
			NodeName: C.GoString(sErr.node),
		}
	}
	return nil
}

// Wrapper for the xmlSchemaFree function
func freeSchemaPtr(xsdHandler *XsdHandler) {
	if xsdHandler.schemaPtr != nil {
		C.xmlSchemaFree(xsdHandler.schemaPtr)
	}
}

// Wrapper for the xmlFreeDoc function
func freeDocPtr(xmlHandler *XmlHandler) {
	if xmlHandler.docPtr != nil {
		C.xmlFreeDoc(xmlHandler.docPtr)
	}
}

// Free C struct
func freeSimpleXmlError(sxe *C.struct_simpleXmlError) {
	C.free(unsafe.Pointer(sxe.message))
	C.free(unsafe.Pointer(sxe.node))
	C.free(unsafe.Pointer(sxe))
}

// Ticker for gc and malloc_trim
func gcTicker(d time.Duration, quit chan struct{}) {
	ticker := time.NewTicker(d)
	for {
		select {
		case <-ticker.C:
			runtime.GC()
			C.malloc_trim(0)
		case <-quit:
			ticker.Stop()
			return
		}
	}
}
<commit_msg>Some cleaning up<commit_after>package xsdvalidate

/*
#cgo pkg-config: libxml-2.0
#include <string.h>
#include <libxml/xmlschemastypes.h>
#include <errno.h>
#include <malloc.h>
#include <stdbool.h>
#define GO_ERR_INIT 256
#define P_ERR_DEFAULT 1
#define P_ERR_EXT 2
#define LIBXML_STATIC

struct xsdParserResult {
	xmlSchemaPtr schemaPtr;
	char *errorStr;
};

struct xmlParserResult {
	xmlDocPtr docPtr;
	char *errorStr;
};

struct errCtx {
	char *errBuf;
};

struct simpleXmlError {
	int	code;
	char*	message;
	int 	level;
	int	line;
	char*	node;
};

static void noOutputCallback(void *ctx, const char *message, ...) {
}

static void init() {
	xmlInitParser();
}

static void cleanup() {
	xmlSchemaCleanupTypes();
	xmlCleanupParser();
}

static void genErrorCallback(void *ctx, const char *message, ...) {
	struct errCtx *ectx = ctx;
	char *newLine = malloc(GO_ERR_INIT);

	va_list varArgs;
        va_start(varArgs, message);

	int oldLen = strlen(ectx->errBuf) + 1;
	int lineLen = 1 + vsnprintf(newLine, GO_ERR_INIT, message, varArgs);

	if (lineLen  > GO_ERR_INIT) {
		free(newLine);
		newLine = malloc(lineLen);
		vsnprintf(newLine, lineLen, message, varArgs);
	}
	va_end(varArgs);

	char *tmp = malloc(oldLen + lineLen);
	memcpy(tmp, ectx->errBuf, oldLen);
	strcat(tmp, newLine);
	free(newLine);
	free(ectx->errBuf);
	ectx->errBuf = tmp;
}

void simpleStructErrorCallback(void *ctx, xmlErrorPtr p) {
	struct simpleXmlError *sErr = ctx;
	sErr->code = p->code;
	sErr->level = p->level;
	sErr->line = p->line;

        int cpyLen = 1 + snprintf(sErr->message, GO_ERR_INIT, "%s", p->message);
	if (cpyLen > GO_ERR_INIT) {
		free(sErr->message);
		sErr->message = malloc(cpyLen);
		snprintf(sErr->message, cpyLen, "%s", p->message);
	}

	if (p->node !=NULL) {
		cpyLen = 1 + snprintf(sErr->node, GO_ERR_INIT, "%s", (((xmlNodePtr) p->node)->name));
		if (cpyLen > GO_ERR_INIT) {
			free(sErr->node);
			sErr->node= malloc(cpyLen);
			snprintf(sErr->node, cpyLen, "%s", (((xmlNodePtr) p->node)->name));
		}
	}
}

static struct xsdParserResult cParseUrlSchema(const char *url, const short int options) {
	bool err = false;
	struct xsdParserResult parserResult;
	char *errBuf=NULL;
	struct errCtx *ectx=malloc(sizeof(struct errCtx));
	ectx->errBuf=calloc(GO_ERR_INIT, sizeof(char));
	struct errCtx *genEctx=malloc(sizeof(struct errCtx));;
	genEctx->errBuf=calloc(GO_ERR_INIT, sizeof(char));

	xmlSchemaPtr schema = NULL;
	xmlSchemaParserCtxtPtr schemaParserCtxt = NULL;

	xmlLineNumbersDefault(1);

	schemaParserCtxt = xmlSchemaNewParserCtxt(url);

	if (schemaParserCtxt == NULL) {
		err = true;
		strcpy(ectx->errBuf, "Xsd parser internal error");
	}
	else
	{
		if (options & P_ERR_EXT) {
			xmlSetGenericErrorFunc(genEctx, genErrorCallback);
		} else {
			xmlSetGenericErrorFunc(NULL, noOutputCallback);
		}

		xmlSchemaSetParserErrors(schemaParserCtxt, genErrorCallback, noOutputCallback, ectx);

		schema = xmlSchemaParse(schemaParserCtxt);

		xmlSchemaFreeParserCtxt(schemaParserCtxt);
		if (schema == NULL) {
			err = true;
			char *tmp = NULL;
			if (options & P_ERR_EXT) {
				tmp = (char *) malloc(strlen(ectx->errBuf) + strlen(genEctx->errBuf) + 1);
				memcpy(tmp, ectx->errBuf, strlen(ectx->errBuf) + 1);
				strcat(tmp, genEctx->errBuf);
			} else {
				tmp = (char *) malloc(strlen(ectx->errBuf) + 1);
				memcpy(tmp, ectx->errBuf, strlen(ectx->errBuf) + 1);
			}
			free(ectx->errBuf);
			ectx->errBuf = tmp;
		}
	}
	errBuf=malloc(strlen(ectx->errBuf)+1);
	memcpy(errBuf,  ectx->errBuf, strlen(ectx->errBuf)+1);

	free(ectx->errBuf);
	free(ectx);
	free(genEctx->errBuf);
	free(genEctx);
	parserResult.schemaPtr=schema;
	parserResult.errorStr=errBuf;
	errno = err ? -1 : 0;
	return parserResult;
}

static struct xmlParserResult cParseDoc(const char *goXmlSource, const int goXmlSourceLen, const short int options) {
	bool err = false;
	struct xmlParserResult parserResult;
	char *errBuf=NULL;
	struct errCtx *ectx=malloc(sizeof(struct errCtx));
	ectx->errBuf=calloc(GO_ERR_INIT, sizeof(char));;

	xmlLineNumbersDefault(1);

	xmlDocPtr doc=NULL;
	xmlParserCtxtPtr xmlParserCtxt=NULL;

	xmlParserCtxt = xmlNewParserCtxt();

	if (xmlParserCtxt == NULL) {
		err = true;
		strcpy(ectx->errBuf, "Xml parser internal error");
	}
	else
	{
		if (options & P_ERR_EXT) {
			xmlSetGenericErrorFunc(ectx, genErrorCallback);
		} else {
			xmlSetGenericErrorFunc(NULL, noOutputCallback);
		}

		doc = xmlParseMemory(goXmlSource, goXmlSourceLen);

		xmlFreeParserCtxt(xmlParserCtxt);

		if (doc == NULL) {
			if (options & P_ERR_EXT) {
				err = true;
				char *tmp = malloc(strlen(ectx->errBuf) + 1);
				memcpy(tmp, ectx->errBuf, strlen(ectx->errBuf) + 1);
				free(ectx->errBuf);
				ectx->errBuf = tmp;
			} else {
				err = true;
				strcpy(ectx->errBuf, "Malformed xml document");
			}
		}
	}

	errBuf=malloc(strlen(ectx->errBuf)+1);
	memcpy(errBuf,  ectx->errBuf, strlen(ectx->errBuf)+1);
	free(ectx->errBuf);
	free(ectx);
	parserResult.docPtr=doc;
	parserResult.errorStr=errBuf;
	errno = err ? -1 : 0;
	return parserResult;
}

static struct simpleXmlError *cValidate(const xmlDocPtr doc, const xmlSchemaPtr schema) {
	bool err = false;
	int schemaErr=0;

	struct simpleXmlError *simpleError = malloc(sizeof(struct simpleXmlError));
	simpleError->message = calloc(GO_ERR_INIT, sizeof(char));
	simpleError->node = calloc(GO_ERR_INIT, sizeof(char));

	xmlLineNumbersDefault(1);

	if (schema == NULL) {
		err = true;
		strcpy(simpleError->message, "Xsd schema null pointer");
	}
	else if (doc == NULL) {
		err = true;
		strcpy(simpleError->message, "Xml schema null pointer");
	}
	else
	{
		xmlSchemaValidCtxtPtr schemaCtxt;
		schemaCtxt = xmlSchemaNewValidCtxt(schema);

		if (schemaCtxt == NULL) {
			err = true;
			strcpy(simpleError->message, "Xml validation internal error");
		}
		else
		{

			xmlSchemaSetValidStructuredErrors(schemaCtxt, simpleStructErrorCallback, simpleError);
			schemaErr = xmlSchemaValidateDoc(schemaCtxt, doc);
			xmlSchemaFreeValidCtxt(schemaCtxt);

			if (schemaErr > 0)
			{
				err = true;
			}
			else if (schemaErr < 0)
			{
				err = true;
				strcpy(simpleError->message, "Xml validation internal error");
			}
		}
	}

	errno = err ? -1 : 0;
	return simpleError;
}

*/
import "C"
import (
	"runtime"
	"strings"
	"time"
	"unsafe"
)

// Handles schema parsing and validation, wraps a pointer to libxml2's xmlSchemaPtr.
type XsdHandler struct {
	schemaPtr C.xmlSchemaPtr
}

// Handles xml parsing, wraps a pointer to libxml2's xmlDocPtr.
type XmlHandler struct {
	docPtr C.xmlDocPtr
}

// Initializes the libxml2 parser, suggested for multithreading
func libXml2Init() {
	C.init()
}

// Cleans up the libxml2 parser
func libXml2Cleanup() {
	C.cleanup()
}

// The helper function for parsing xml
func parseXmlMem(inXml []byte, options Options) (C.xmlDocPtr, error) {

	strXml := C.CString(string(inXml))
	defer C.free(unsafe.Pointer(strXml))
	pRes, err := C.cParseDoc(strXml, C.int(len(inXml)), C.short(options))

	defer C.free(unsafe.Pointer(pRes.errorStr))
	if err != nil {
		rStr := C.GoString(pRes.errorStr)
		return nil, XmlParserError{errorMessage{strings.Trim(rStr, "\n")}}
	}
	return pRes.docPtr, nil
}

// The helper function for parsing the schema
func parseUrlSchema(url string, options Options) (C.xmlSchemaPtr, error) {
	strUrl := C.CString(url)
	defer C.free(unsafe.Pointer(strUrl))

	pRes, err := C.cParseUrlSchema(strUrl, C.short(options))
	defer C.free(unsafe.Pointer(pRes.errorStr))
	if err != nil {
		rStr := C.GoString(pRes.errorStr)
		return nil, XsdParserError{errorMessage{strings.Trim(rStr, "\n")}}
	}
	return pRes.schemaPtr, nil
}

// Helper function for validating given an xml document
func validateWithXsd(xmlHandler *XmlHandler, xsdHandler *XsdHandler) error {
	sErr, err := C.cValidate(xmlHandler.docPtr, xsdHandler.schemaPtr)
	defer freeSimpleXmlError(sErr)
	if err != nil {
		return ValidationError{
			Code:     int(sErr.code),
			Message:  strings.Trim(C.GoString(sErr.message), "\n"),
			Level:    int(sErr.level),
			Line:     int(sErr.line),
			NodeName: C.GoString(sErr.node),
		}
	}
	return nil
}

// Wrapper for the xmlSchemaFree function
func freeSchemaPtr(xsdHandler *XsdHandler) {
	if xsdHandler.schemaPtr != nil {
		C.xmlSchemaFree(xsdHandler.schemaPtr)
	}
}

// Wrapper for the xmlFreeDoc function
func freeDocPtr(xmlHandler *XmlHandler) {
	if xmlHandler.docPtr != nil {
		C.xmlFreeDoc(xmlHandler.docPtr)
	}
}

// Free C struct
func freeSimpleXmlError(sxe *C.struct_simpleXmlError) {
	C.free(unsafe.Pointer(sxe.message))
	C.free(unsafe.Pointer(sxe.node))
	C.free(unsafe.Pointer(sxe))
}

// Ticker for gc and malloc_trim
func gcTicker(d time.Duration, quit chan struct{}) {
	ticker := time.NewTicker(d)
	for {
		select {
		case <-ticker.C:
			runtime.GC()
			C.malloc_trim(0)
		case <-quit:
			ticker.Stop()
			return
		}
	}
}
<|endoftext|>


<commit_before>package pagoda

import (
	"io"
	"text/template"
)

// LayoutTemplateManager loads and executes templates with a layout page
type LayoutTemplateManager struct {
	*TemplateManager
	layoutTemplate string
}

func getLayoutTemplateManager(templateManager *TemplateManager, layoutTemplateName string) *LayoutTemplateManager {
	return &LayoutTemplateManager{templateManager, layoutTemplateName}
}

// GetTemplate gets a template from the templateFolder based on the templateName
func (layoutTemplateManager *LayoutTemplateManager) GetTemplate(templateName string) (tpl *template.Template, err error) {
	templateName = layoutTemplateManager.getTemplateName(templateName)

	funcs := layoutTemplateManager.funcs
	funcs["pagoda_layout_placeholder"] = func(data interface{}) string {
		return layoutTemplateManager.execSubTemplate(templateName, data)
	}

	rootTemplate := layoutTemplateManager.layoutTemplates[templateName]
	if rootTemplate == nil {
		rootTemplate = template.New("ROOT")
		layoutTemplateManager.layoutTemplates[templateName] = rootTemplate
	}

	layoutTemplateName := layoutTemplateManager.getTemplateName(layoutTemplateManager.layoutTemplate)

	return layoutTemplateManager.getTemplate(layoutTemplateName, funcs, rootTemplate)
}

// Execute a template named templateName
func (layoutTemplateManager *LayoutTemplateManager) Execute(templateName string, writer io.Writer, data interface{}) (err error) {
	tpl, err := layoutTemplateManager.GetTemplate(templateName)

	if err == nil {
		err = tpl.Execute(writer, data)
	}
	return
}
<commit_msg>some comments<commit_after>package pagoda

import (
	"io"
	"text/template"
)

// LayoutTemplateManager loads and executes templates with a layout page
type LayoutTemplateManager struct {
	*TemplateManager
	layoutTemplate string
}

func getLayoutTemplateManager(templateManager *TemplateManager, layoutTemplateName string) *LayoutTemplateManager {
	return &LayoutTemplateManager{templateManager, layoutTemplateName}
}

// GetTemplate gets a template from the templateFolder based on the templateName
func (layoutTemplateManager *LayoutTemplateManager) GetTemplate(templateName string) (tpl *template.Template, err error) {
	templateName = layoutTemplateManager.getTemplateName(templateName)

	// add layout placeholder func
	funcs := layoutTemplateManager.funcs
	funcs["pagoda_layout_placeholder"] = func(data interface{}) string {
		return layoutTemplateManager.execSubTemplate(templateName, data)
	}

	// try to get the layout root template from cache, otherwise create a new one
	rootTemplate := layoutTemplateManager.layoutTemplates[templateName]
	if rootTemplate == nil {
		rootTemplate = template.New("ROOT")
		layoutTemplateManager.layoutTemplates[templateName] = rootTemplate
	}

	layoutTemplateName := layoutTemplateManager.getTemplateName(layoutTemplateManager.layoutTemplate)
	return layoutTemplateManager.getTemplate(layoutTemplateName, funcs, rootTemplate)
}

// Execute a template named templateName
func (layoutTemplateManager *LayoutTemplateManager) Execute(templateName string, writer io.Writer, data interface{}) (err error) {
	tpl, err := layoutTemplateManager.GetTemplate(templateName)

	if err == nil {
		err = tpl.Execute(writer, data)
	}
	return
}
<|endoftext|>


<commit_before>package version

// VERSION ...
const VERSION = "2.3.0"
<commit_msg>version bump (#194)<commit_after>package version

// VERSION ...
const VERSION = "2.3.1"
<|endoftext|>


<commit_before>package version

import (
	// Stdlib
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strconv"

	// Internal
	"github.com/salsita/salsaflow/git"
)

const (
	PackageFileName    = "package.json"
	GroupMatcherString = "([0-9]+)[.]([0-9]+)[.]([0-9]+)"
	MatcherString      = "[0-9]+[.][0-9]+[.][0-9]+"
)

type packageFile struct {
	Version string
}

type Version struct {
	Major uint
	Minor uint
	Patch uint
}

func ReadFromBranch(branch string) (ver *Version, stderr *bytes.Buffer, err error) {
	content, stderr, err := git.ShowByBranch(branch, PackageFileName)
	if err != nil {
		return
	}

	var pkg packageFile
	err = json.Unmarshal(content.Bytes(), &pkg)
	if err != nil {
		return
	}
	if pkg.Version == "" {
		err = fmt.Errorf("version key not found in %v", PackageFileName)
		return
	}

	ver, err = parseVersion(pkg.Version)
	return
}

func (ver *Version) Zero() bool {
	return ver.Major == 0 && ver.Minor == 0 && ver.Patch == 0
}

func (ver *Version) IncrementMinor() *Version {
	return &Version{ver.Major, ver.Minor + 1, 0}
}

func (ver *Version) IncrementPatch() *Version {
	return &Version{ver.Major, ver.Minor, ver.Patch + 1}
}

func (ver *Version) Set(versionString string) error {
	newVer, err := parseVersion(versionString)
	if err != nil {
		return err
	}
	ver.Major = newVer.Major
	ver.Minor = newVer.Minor
	ver.Patch = newVer.Patch
	return nil
}

func (ver *Version) String() string {
	return fmt.Sprintf("%v.%v.%v", ver.Major, ver.Minor, ver.Patch)
}

func (ver *Version) ReleaseTagString() string {
	return "v" + ver.String()
}

func (ver *Version) CommitToBranch(branch string) (stderr *bytes.Buffer, err error) {
	// Make sure package.json is clean.
	stderr, err = git.EnsureFileClean(PackageFileName)
	if err != nil {
		return
	}

	// Checkout the branch.
	stderr, err = git.Checkout(branch)
	if err != nil {
		return
	}

	// Get the absolute path of package.json
	root, stderr, err := git.RepositoryRootAbsolutePath()
	if err != nil {
		return
	}
	path := filepath.Join(root, PackageFileName)

	// Read package.json
	file, err := os.OpenFile(path, os.O_RDWR, 0)
	if err != nil {
		return
	}
	defer file.Close()

	content, err := ioutil.ReadAll(file)
	if err != nil {
		return
	}

	// Parse and replace stuff in package.json
	pattern := regexp.MustCompile(fmt.Sprintf("\"version\": \"%v\"", MatcherString))
	newContent := pattern.ReplaceAllLiteral(content,
		[]byte(fmt.Sprintf("\"version\": \"%v\"", ver)))
	if bytes.Equal(content, newContent) {
		err = fmt.Errorf("%v: failed to replace version string", PackageFileName)
		return
	}

	// Write package.json
	_, err = file.Seek(0, os.SEEK_SET)
	if err != nil {
		return
	}
	err = file.Truncate(0)
	if err != nil {
		return
	}
	_, err = io.Copy(file, bytes.NewReader(newContent))
	if err != nil {
		return
	}

	// Commit package.json
	_, stderr, err = git.Git("add", path)
	if err != nil {
		return
	}
	// XXX: Somehow unstage package.json?
	_, stderr, err = git.Git("commit", "-m", fmt.Sprintf("Bump version to %v", ver))
	return
}

func parseVersion(versionString string) (ver *Version, err error) {
	pattern := regexp.MustCompile("^" + GroupMatcherString + "$")
	parts := pattern.FindStringSubmatch(versionString)
	if len(parts) != 4 {
		return nil, fmt.Errorf("invalid version string: %v", versionString)
	}

	// regexp passed, we know that we are not going to fail here.
	major, _ := strconv.ParseUint(parts[1], 10, 32)
	minor, _ := strconv.ParseUint(parts[2], 10, 32)
	patch, _ := strconv.ParseUint(parts[3], 10, 32)

	return &Version{uint(major), uint(minor), uint(patch)}, nil
}
<commit_msg>version: Roll back package.json on error<commit_after>package version

import (
	// Stdlib
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strconv"

	// Internal
	"github.com/salsita/salsaflow/errs"
	"github.com/salsita/salsaflow/git"
	"github.com/salsita/salsaflow/log"
)

const (
	PackageFileName    = "package.json"
	GroupMatcherString = "([0-9]+)[.]([0-9]+)[.]([0-9]+)"
	MatcherString      = "[0-9]+[.][0-9]+[.][0-9]+"
)

type packageFile struct {
	Version string
}

type Version struct {
	Major uint
	Minor uint
	Patch uint
}

func ReadFromBranch(branch string) (ver *Version, stderr *bytes.Buffer, err error) {
	content, stderr, err := git.ShowByBranch(branch, PackageFileName)
	if err != nil {
		return
	}

	var pkg packageFile
	err = json.Unmarshal(content.Bytes(), &pkg)
	if err != nil {
		return
	}
	if pkg.Version == "" {
		err = fmt.Errorf("version key not found in %v", PackageFileName)
		return
	}

	ver, err = parseVersion(pkg.Version)
	return
}

func (ver *Version) Zero() bool {
	return ver.Major == 0 && ver.Minor == 0 && ver.Patch == 0
}

func (ver *Version) IncrementMinor() *Version {
	return &Version{ver.Major, ver.Minor + 1, 0}
}

func (ver *Version) IncrementPatch() *Version {
	return &Version{ver.Major, ver.Minor, ver.Patch + 1}
}

func (ver *Version) Set(versionString string) error {
	newVer, err := parseVersion(versionString)
	if err != nil {
		return err
	}
	ver.Major = newVer.Major
	ver.Minor = newVer.Minor
	ver.Patch = newVer.Patch
	return nil
}

func (ver *Version) String() string {
	return fmt.Sprintf("%v.%v.%v", ver.Major, ver.Minor, ver.Patch)
}

func (ver *Version) ReleaseTagString() string {
	return "v" + ver.String()
}

func (ver *Version) CommitToBranch(branch string) (stderr *bytes.Buffer, err error) {
	// Make sure package.json is clean.
	stderr, err = git.EnsureFileClean(PackageFileName)
	if err != nil {
		return
	}

	// Checkout the branch.
	stderr, err = git.Checkout(branch)
	if err != nil {
		return
	}

	// Get the absolute path of package.json
	root, stderr, err := git.RepositoryRootAbsolutePath()
	if err != nil {
		return
	}
	absPath := filepath.Join(root, PackageFileName)

	// Read package.json
	file, err := os.OpenFile(absPath, os.O_RDWR, 0)
	if err != nil {
		return
	}
	defer file.Close()

	content, err := ioutil.ReadAll(file)
	if err != nil {
		return
	}

	// Parse and replace stuff in package.json
	pattern := regexp.MustCompile(fmt.Sprintf("\"version\": \"%v\"", MatcherString))
	newContent := pattern.ReplaceAllLiteral(content,
		[]byte(fmt.Sprintf("\"version\": \"%v\"", ver)))
	if bytes.Equal(content, newContent) {
		err = fmt.Errorf("%v: failed to replace version string", PackageFileName)
		return
	}

	// Write package.json
	_, err = file.Seek(0, os.SEEK_SET)
	if err != nil {
		return
	}
	err = file.Truncate(0)
	if err != nil {
		return
	}
	_, err = io.Copy(file, bytes.NewReader(newContent))
	if err != nil {
		return
	}

	// Commit package.json
	_, stderr, err = git.Git("add", absPath)
	if err != nil {
		return
	}
	defer func() {
		if err == nil {
			return
		}
		// On error, checkout package.json to cancel the changes.
		//
		// We cannot loose any changes by doing so, because make sure that
		// package.json is clean at the beginning of CommitToBranch.
		_, serr, ex := git.Git("checkout", "--", absPath)
		if ex != nil {
			errs.NewError(
				fmt.Sprintf("Roll back changes to %v", PackageFileName),
				serr,
				err).Log(log.V(log.Info))
		}
	}()

	_, stderr, err = git.Git("commit", "-m", fmt.Sprintf("Bump version to %v", ver))
	return
}

func parseVersion(versionString string) (ver *Version, err error) {
	pattern := regexp.MustCompile("^" + GroupMatcherString + "$")
	parts := pattern.FindStringSubmatch(versionString)
	if len(parts) != 4 {
		return nil, fmt.Errorf("invalid version string: %v", versionString)
	}

	// regexp passed, we know that we are not going to fail here.
	major, _ := strconv.ParseUint(parts[1], 10, 32)
	minor, _ := strconv.ParseUint(parts[2], 10, 32)
	patch, _ := strconv.ParseUint(parts[3], 10, 32)

	return &Version{uint(major), uint(minor), uint(patch)}, nil
}
<|endoftext|>


<commit_before>//create: 2015/05/14 15:55:20 Change: 2019/06/04 18:43:36 author:lijiao
package version

import (
	"fmt"
)

var (
	VERSION string
	COMPILE string
)

func Show() {
	fmt.Printf("version: %s   compile at: %s  golib v1\n", VERSION, COMPILE)
}
<commit_msg>v2 test<commit_after>//create: 2015/05/14 15:55:20 Change: 2019/06/04 18:54:10 author:lijiao
package version

import (
	"fmt"
)

var (
	VERSION string
	COMPILE string
)

func Show() {
	fmt.Printf("version: %s   compile at: %s  golib v2\n", VERSION, COMPILE)
}
<|endoftext|>


<commit_before>package version

const (
	// Version is the current version of SensorBee.
	Version = "0.6.1"

	// Major is the major version of the current SensorBee.
	Major = 0

	// Minor is the minor version of the current SensorBee.
	Minor = 6

	// Revision is the revision number of the current SensorBee version.
	Revision = 1
)
<commit_msg>Version 0.7.0<commit_after>package version

const (
	// Version is the current version of SensorBee.
	Version = "0.7.0"

	// Major is the major version of the current SensorBee.
	Major = 0

	// Minor is the minor version of the current SensorBee.
	Minor = 7

	// Revision is the revision number of the current SensorBee version.
	Revision = 0
)
<|endoftext|>


<commit_before>// The version package provides a location to set the release versions for all
// packages to consume, without creating import cycles.
//
// This package should not import any other terraform packages.
package version

import (
	"fmt"

	version "github.com/hashicorp/go-version"
)

// The main version number that is being run at the moment.
var Version = "0.12.21"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
var Prerelease = "dev"

// SemVer is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVer *version.Version

func init() {
	SemVer = version.Must(version.NewVersion(Version))
}

// Header is the header name used to send the current terraform version
// in http requests.
const Header = "Terraform-Version"

// String returns the complete version string, including prerelease
func String() string {
	if Prerelease != "" {
		return fmt.Sprintf("%s-%s", Version, Prerelease)
	}
	return Version
}
<commit_msg>Update to 0.13 version (#24106)<commit_after>// The version package provides a location to set the release versions for all
// packages to consume, without creating import cycles.
//
// This package should not import any other terraform packages.
package version

import (
	"fmt"

	version "github.com/hashicorp/go-version"
)

// The main version number that is being run at the moment.
var Version = "0.13.0"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
var Prerelease = "dev"

// SemVer is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVer *version.Version

func init() {
	SemVer = version.Must(version.NewVersion(Version))
}

// Header is the header name used to send the current terraform version
// in http requests.
const Header = "Terraform-Version"

// String returns the complete version string, including prerelease
func String() string {
	if Prerelease != "" {
		return fmt.Sprintf("%s-%s", Version, Prerelease)
	}
	return Version
}
<|endoftext|>


<commit_before>package version

import "fmt"

const (
	// VersionMajor is for an API incompatible changes
	VersionMajor = 5
	// VersionMinor is for functionality in a backwards-compatible manner
	VersionMinor = 1
	// VersionPatch is for backwards-compatible bug fixes
	VersionPatch = 0

	// VersionDev indicates development branch. Releases will be empty string.
	VersionDev = ""
)

// Version is the specification version that the package types support.
var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev)
<commit_msg>Move to v5.1.1-dev<commit_after>package version

import "fmt"

const (
	// VersionMajor is for an API incompatible changes
	VersionMajor = 5
	// VersionMinor is for functionality in a backwards-compatible manner
	VersionMinor = 1
	// VersionPatch is for backwards-compatible bug fixes
	VersionPatch = 1

	// VersionDev indicates development branch. Releases will be empty string.
	VersionDev = "-dev"
)

// Version is the specification version that the package types support.
var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev)
<|endoftext|>


<commit_before>package ln

import (
	"fmt"
	"image"
	"image/color"
	"image/draw"
	"io/ioutil"
	"strings"

	"github.com/llgcode/draw2d"
	"github.com/llgcode/draw2d/draw2dimg"
)

type Path []Vector

func (p Path) BoundingBox() Box {
	box := Box{p[0], p[0]}
	for _, v := range p {
		box = box.Extend(Box{v, v})
	}
	return box
}

func (p Path) Transform(matrix Matrix) Path {
	var result Path
	for _, v := range p {
		result = append(result, matrix.MulPosition(v))
	}
	return result
}

func (p Path) Chop(step float64) Path {
	var result Path
	for i := 0; i < len(p)-1; i++ {
		a := p[i]
		b := p[i+1]
		v := b.Sub(a)
		l := v.Length()
		if i == 0 {
			result = append(result, a)
		}
		d := step
		for d < l {
			result = append(result, a.Add(v.MulScalar(d/l)))
			d += step
		}
		result = append(result, b)
	}
	return result
}

func (p Path) Filter(f Filter) Paths {
	var result Paths
	var path Path
	for _, v := range p {
		v, ok := f.Filter(v)
		// ok = ok || i%8 < 4 // show hidden lines
		if ok {
			path = append(path, v)
		} else {
			if len(path) > 1 {
				result = append(result, path)
			}
			path = nil
		}
	}
	if len(path) > 1 {
		result = append(result, path)
	}
	return result
}

func (p Path) Simplify(threshold float64) Path {
	if len(p) < 3 {
		return p
	}
	a := p[0]
	b := p[len(p)-1]
	index := -1
	distance := 0.0
	for i := 1; i < len(p)-1; i++ {
		d := p[i].SegmentDistance(a, b)
		if d > distance {
			index = i
			distance = d
		}
	}
	if distance > threshold {
		r1 := p[:index+1].Simplify(threshold)
		r2 := p[index:].Simplify(threshold)
		return append(r1[:len(r1)-1], r2...)
	} else {
		return Path{a, b}
	}
}

func (p Path) Print() {
	for _, v := range p {
		fmt.Printf("%g,%g;", v.X, v.Y)
	}
	fmt.Println()
}

func (p Path) String() string {
	var parts []string
	for _, v := range p {
		parts = append(parts, fmt.Sprintf("%g,%g", v.X, v.Y))
	}
	return strings.Join(parts, ";")
}

func (p Path) ToSVG() string {
	var coords []string
	for _, v := range p {
		coords = append(coords, fmt.Sprintf("%f,%f", v.X, v.Y))
	}
	points := strings.Join(coords, " ")
	return fmt.Sprintf("<polyline stroke=\"black\" fill=\"none\" points=\"%s\" />", points)
}

type Paths []Path

func (p Paths) BoundingBox() Box {
	box := p[0].BoundingBox()
	for _, path := range p {
		box = box.Extend(path.BoundingBox())
	}
	return box
}

func (p Paths) Transform(matrix Matrix) Paths {
	var result Paths
	for _, path := range p {
		result = append(result, path.Transform(matrix))
	}
	return result
}

func (p Paths) Chop(step float64) Paths {
	var result Paths
	for _, path := range p {
		result = append(result, path.Chop(step))
	}
	return result
}

func (p Paths) Filter(f Filter) Paths {
	var result Paths
	for _, path := range p {
		result = append(result, path.Filter(f)...)
	}
	return result
}

func (p Paths) Simplify(threshold float64) Paths {
	var result Paths
	for _, path := range p {
		result = append(result, path.Simplify(threshold))
	}
	return result
}

func (p Paths) Print() {
	for _, path := range p {
		path.Print()
	}
}

func (p Paths) String() string {
	var parts []string
	for _, path := range p {
		parts = append(parts, path.String())
	}
	return strings.Join(parts, "\n")
}

func (p Paths) ToDraw2D(width, height, scale float64) *image.RGBA {
	im := image.NewRGBA(image.Rect(0, 0, int(width*scale), int(height*scale)))
	draw.Draw(im, im.Bounds(), image.White, image.ZP, draw.Src)
	dc := draw2dimg.NewGraphicContext(im)
	dc.SetLineCap(draw2d.RoundCap)
	dc.SetLineJoin(draw2d.RoundJoin)
	dc.SetLineWidth(3)
	dc.Scale(1, -1)
	dc.Translate(0, -height*scale)
	dc.SetStrokeColor(color.RGBA{0, 0, 0, 255})
	for _, path := range p {
		for i, v := range path {
			if i == 0 {
				dc.MoveTo(v.X*scale, v.Y*scale)
			} else {
				dc.LineTo(v.X*scale, v.Y*scale)
			}
		}
	}
	dc.Stroke()
	return im
}

func (p Paths) WriteToPNG(path string, width, height float64) {
	dc := p.ToDraw2D(width, height, 1)
	draw2dimg.SaveToPngFile(path, dc)
}

func (p Paths) ToSVG(width, height float64) string {
	var lines []string
	lines = append(lines, fmt.Sprintf("<svg width=\"%f\" height=\"%f\" version=\"1.1\" baseProfile=\"full\" xmlns=\"http://www.w3.org/2000/svg\">", width, height))
	lines = append(lines, fmt.Sprintf("<g transform=\"translate(0,%f) scale(1,-1)\">", height))
	for _, path := range p {
		lines = append(lines, path.ToSVG())
	}
	lines = append(lines, "</g></svg>")
	return strings.Join(lines, "\n")
}

func (p Paths) WriteToSVG(path string, width, height float64) error {
	return ioutil.WriteFile(path, []byte(p.ToSVG(width, height)), 0644)
}

func (p Paths) WriteToTXT(path string) error {
	return ioutil.WriteFile(path, []byte(p.String()), 0644)
}
<commit_msg>use dd library for rendering<commit_after>package ln

import (
	"fmt"
	"io/ioutil"
	"strings"

	"github.com/fogleman/dd"
)

type Path []Vector

func (p Path) BoundingBox() Box {
	box := Box{p[0], p[0]}
	for _, v := range p {
		box = box.Extend(Box{v, v})
	}
	return box
}

func (p Path) Transform(matrix Matrix) Path {
	var result Path
	for _, v := range p {
		result = append(result, matrix.MulPosition(v))
	}
	return result
}

func (p Path) Chop(step float64) Path {
	var result Path
	for i := 0; i < len(p)-1; i++ {
		a := p[i]
		b := p[i+1]
		v := b.Sub(a)
		l := v.Length()
		if i == 0 {
			result = append(result, a)
		}
		d := step
		for d < l {
			result = append(result, a.Add(v.MulScalar(d/l)))
			d += step
		}
		result = append(result, b)
	}
	return result
}

func (p Path) Filter(f Filter) Paths {
	var result Paths
	var path Path
	for _, v := range p {
		v, ok := f.Filter(v)
		// ok = ok || i%8 < 4 // show hidden lines
		if ok {
			path = append(path, v)
		} else {
			if len(path) > 1 {
				result = append(result, path)
			}
			path = nil
		}
	}
	if len(path) > 1 {
		result = append(result, path)
	}
	return result
}

func (p Path) Simplify(threshold float64) Path {
	if len(p) < 3 {
		return p
	}
	a := p[0]
	b := p[len(p)-1]
	index := -1
	distance := 0.0
	for i := 1; i < len(p)-1; i++ {
		d := p[i].SegmentDistance(a, b)
		if d > distance {
			index = i
			distance = d
		}
	}
	if distance > threshold {
		r1 := p[:index+1].Simplify(threshold)
		r2 := p[index:].Simplify(threshold)
		return append(r1[:len(r1)-1], r2...)
	} else {
		return Path{a, b}
	}
}

func (p Path) Print() {
	for _, v := range p {
		fmt.Printf("%g,%g;", v.X, v.Y)
	}
	fmt.Println()
}

func (p Path) String() string {
	var parts []string
	for _, v := range p {
		parts = append(parts, fmt.Sprintf("%g,%g", v.X, v.Y))
	}
	return strings.Join(parts, ";")
}

func (p Path) ToSVG() string {
	var coords []string
	for _, v := range p {
		coords = append(coords, fmt.Sprintf("%f,%f", v.X, v.Y))
	}
	points := strings.Join(coords, " ")
	return fmt.Sprintf("<polyline stroke=\"black\" fill=\"none\" points=\"%s\" />", points)
}

type Paths []Path

func (p Paths) BoundingBox() Box {
	box := p[0].BoundingBox()
	for _, path := range p {
		box = box.Extend(path.BoundingBox())
	}
	return box
}

func (p Paths) Transform(matrix Matrix) Paths {
	var result Paths
	for _, path := range p {
		result = append(result, path.Transform(matrix))
	}
	return result
}

func (p Paths) Chop(step float64) Paths {
	var result Paths
	for _, path := range p {
		result = append(result, path.Chop(step))
	}
	return result
}

func (p Paths) Filter(f Filter) Paths {
	var result Paths
	for _, path := range p {
		result = append(result, path.Filter(f)...)
	}
	return result
}

func (p Paths) Simplify(threshold float64) Paths {
	var result Paths
	for _, path := range p {
		result = append(result, path.Simplify(threshold))
	}
	return result
}

func (p Paths) Print() {
	for _, path := range p {
		path.Print()
	}
}

func (p Paths) String() string {
	var parts []string
	for _, path := range p {
		parts = append(parts, path.String())
	}
	return strings.Join(parts, "\n")
}

func (p Paths) WriteToPNG(path string, width, height float64) {
	scale := 1.0
	w, h := int(width*scale), int(height*scale)
	dc := dd.NewContext(w, h)
	dc.SetSourceRGB(1, 1, 1)
	dc.Paint()
	dc.SetSourceRGB(0, 0, 0)
	dc.SetLineWidth(3)
	for _, path := range p {
		for i, v := range path {
			if i == 0 {
				dc.MoveTo(v.X*scale, float64(h)-v.Y*scale)
			} else {
				dc.LineTo(v.X*scale, float64(h)-v.Y*scale)
			}
		}
	}
	dc.Stroke()
	dc.WriteToPNG(path)
}

func (p Paths) ToSVG(width, height float64) string {
	var lines []string
	lines = append(lines, fmt.Sprintf("<svg width=\"%f\" height=\"%f\" version=\"1.1\" baseProfile=\"full\" xmlns=\"http://www.w3.org/2000/svg\">", width, height))
	lines = append(lines, fmt.Sprintf("<g transform=\"translate(0,%f) scale(1,-1)\">", height))
	for _, path := range p {
		lines = append(lines, path.ToSVG())
	}
	lines = append(lines, "</g></svg>")
	return strings.Join(lines, "\n")
}

func (p Paths) WriteToSVG(path string, width, height float64) error {
	return ioutil.WriteFile(path, []byte(p.ToSVG(width, height)), 0644)
}

func (p Paths) WriteToTXT(path string) error {
	return ioutil.WriteFile(path, []byte(p.String()), 0644)
}
<|endoftext|>