<commit_before>package fix

// A Fixer is something that can perform a fix operation on a template.
type Fixer interface {
	// DeprecatedOptions returns the name(s) of the option(s) being replaced in
	// this fixer. It is used to generate a list of deprecated options that the
	// template parser checks against to warn users that they need to call
	// `packer fix` against their templates after upgrading.
	DeprecatedOptions() []string

	// Fix takes a raw map structure input, potentially transforms it
	// in some way, and returns the new, transformed structure. The
	// Fix method is allowed to mutate the input.
	Fix(input map[string]interface{}) (map[string]interface{}, error)

	// Synopsis returns a string description of what the fixer actually
	// does.
	Synopsis() string
}

// Fixers is the map of all available fixers, by name.
var Fixers map[string]Fixer

// FixerOrder is the default order the fixers should be run.
var FixerOrder []string

func init() {
	Fixers = map[string]Fixer{
		"iso-md5":                    new(FixerISOMD5),
		"createtime":                 new(FixerCreateTime),
		"pp-vagrant-override":        new(FixerVagrantPPOverride),
		"virtualbox-gaattach":        new(FixerVirtualBoxGAAttach),
		"virtualbox-rename":          new(FixerVirtualBoxRename),
		"vmware-rename":              new(FixerVMwareRename),
		"parallels-headless":         new(FixerParallelsHeadless),
		"parallels-deprecations":     new(FixerParallelsDeprecations),
		"sshkeypath":                 new(FixerSSHKeyPath),
		"sshdisableagent":            new(FixerSSHDisableAgent),
		"scaleway-access-key":        new(FixerScalewayAccessKey),
		"manifest-filename":          new(FixerManifestFilename),
		"amazon-shutdown_behavior":   new(FixerAmazonShutdownBehavior),
		"amazon-enhanced-networking": new(FixerAmazonEnhancedNetworking),
		"amazon-private-ip":          new(FixerAmazonPrivateIP),
		"amazon-temp-sec-cidrs":      new(FixerAmazonTemporarySecurityCIDRs),
		"docker-email":               new(FixerDockerEmail),
		"powershell-escapes":         new(FixerPowerShellEscapes),
		"hyperv-deprecations":        new(FixerHypervDeprecations),
		"hyperv-vmxc-typo":           new(FixerHypervVmxcTypo),
		"hyperv-cpu-and-ram":         new(FizerHypervCPUandRAM),
		"vmware-compaction":          new(FixerVMwareCompaction),
		"clean-image-name":           new(FixerCleanImageName),
		"spot-price-auto-product":    new(FixerAmazonSpotPriceProductDeprecation),
		"qemu-disk-size":             new(FixerQEMUDiskSize),
		"galaxy-command":             new(FixerGalaxyCommand),
		"comm-config":                new(FixerCommConfig),
		"ssh-wait-timeout":           new(FixerSSHTimout),
		"docker-tag-tags":            new(FixerDockerTagtoTags),
		"vsphere-iso-net-disk":       new(FixerVSphereNetworkDisk),
		"iso-checksum-type-and-url":  new(FixerISOChecksumTypeAndURL),
		"qemu-host-port":             new(FixerQEMUHostPort),
	}

	FixerOrder = []string{
		"iso-md5",
		"createtime",
		"virtualbox-gaattach",
		"pp-vagrant-override",
		"virtualbox-rename",
		"vmware-rename",
		"parallels-headless",
		"parallels-deprecations",
		"sshkeypath",
		"sshdisableagent",
		"scaleway-access-key",
		"manifest-filename",
		"amazon-shutdown_behavior",
		"amazon-enhanced-networking",
		"amazon-private-ip",
		"amazon-temp-sec-cidrs",
		"docker-email",
		"docker-tag-tags",
		"powershell-escapes",
		"vmware-compaction",
		"hyperv-deprecations",
		"hyperv-vmxc-typo",
		"hyperv-cpu-and-ram",
		"clean-image-name",
		"spot-price-auto-product",
		"qemu-disk-size",
		"galaxy-command",
		"comm-config",
		"ssh-wait-timeout",
		"vsphere-iso-net-disk",
		"iso-checksum-type-and-url",
		"qemu-host-port",
	}
}
<commit_msg>Add proxmox fixer<commit_after>package fix

// A Fixer is something that can perform a fix operation on a template.
type Fixer interface {
	// DeprecatedOptions returns the name(s) of the option(s) being replaced in
	// this fixer. It is used to generate a list of deprecated options that the
	// template parser checks against to warn users that they need to call
	// `packer fix` against their templates after upgrading.
	DeprecatedOptions() []string

	// Fix takes a raw map structure input, potentially transforms it
	// in some way, and returns the new, transformed structure. The
	// Fix method is allowed to mutate the input.
	Fix(input map[string]interface{}) (map[string]interface{}, error)

	// Synopsis returns a string description of what the fixer actually
	// does.
	Synopsis() string
}

// Fixers is the map of all available fixers, by name.
var Fixers map[string]Fixer

// FixerOrder is the default order the fixers should be run.
var FixerOrder []string

func init() {
	Fixers = map[string]Fixer{
		"iso-md5":                    new(FixerISOMD5),
		"createtime":                 new(FixerCreateTime),
		"pp-vagrant-override":        new(FixerVagrantPPOverride),
		"virtualbox-gaattach":        new(FixerVirtualBoxGAAttach),
		"virtualbox-rename":          new(FixerVirtualBoxRename),
		"vmware-rename":              new(FixerVMwareRename),
		"parallels-headless":         new(FixerParallelsHeadless),
		"parallels-deprecations":     new(FixerParallelsDeprecations),
		"sshkeypath":                 new(FixerSSHKeyPath),
		"sshdisableagent":            new(FixerSSHDisableAgent),
		"scaleway-access-key":        new(FixerScalewayAccessKey),
		"manifest-filename":          new(FixerManifestFilename),
		"amazon-shutdown_behavior":   new(FixerAmazonShutdownBehavior),
		"amazon-enhanced-networking": new(FixerAmazonEnhancedNetworking),
		"amazon-private-ip":          new(FixerAmazonPrivateIP),
		"amazon-temp-sec-cidrs":      new(FixerAmazonTemporarySecurityCIDRs),
		"docker-email":               new(FixerDockerEmail),
		"powershell-escapes":         new(FixerPowerShellEscapes),
		"hyperv-deprecations":        new(FixerHypervDeprecations),
		"hyperv-vmxc-typo":           new(FixerHypervVmxcTypo),
		"hyperv-cpu-and-ram":         new(FizerHypervCPUandRAM),
		"vmware-compaction":          new(FixerVMwareCompaction),
		"clean-image-name":           new(FixerCleanImageName),
		"spot-price-auto-product":    new(FixerAmazonSpotPriceProductDeprecation),
		"qemu-disk-size":             new(FixerQEMUDiskSize),
		"galaxy-command":             new(FixerGalaxyCommand),
		"comm-config":                new(FixerCommConfig),
		"ssh-wait-timeout":           new(FixerSSHTimout),
		"docker-tag-tags":            new(FixerDockerTagtoTags),
		"vsphere-iso-net-disk":       new(FixerVSphereNetworkDisk),
		"iso-checksum-type-and-url":  new(FixerISOChecksumTypeAndURL),
		"qemu-host-port":             new(FixerQEMUHostPort),
		"proxmox-type":               new(FixerProxmoxType),
	}

	FixerOrder = []string{
		"iso-md5",
		"createtime",
		"virtualbox-gaattach",
		"pp-vagrant-override",
		"virtualbox-rename",
		"vmware-rename",
		"parallels-headless",
		"parallels-deprecations",
		"sshkeypath",
		"sshdisableagent",
		"scaleway-access-key",
		"manifest-filename",
		"amazon-shutdown_behavior",
		"amazon-enhanced-networking",
		"amazon-private-ip",
		"amazon-temp-sec-cidrs",
		"docker-email",
		"docker-tag-tags",
		"powershell-escapes",
		"vmware-compaction",
		"hyperv-deprecations",
		"hyperv-vmxc-typo",
		"hyperv-cpu-and-ram",
		"clean-image-name",
		"spot-price-auto-product",
		"qemu-disk-size",
		"galaxy-command",
		"comm-config",
		"ssh-wait-timeout",
		"vsphere-iso-net-disk",
		"iso-checksum-type-and-url",
		"qemu-host-port",
		"proxmox-type",
	}
}
<|endoftext|>


<commit_before>package gifGrabber

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"time"
	"gifjam/config"
)

var (
	mongoURL = os.Getenv("GIFJAM_MONGO")
	session  *mgo.Session
	db       *mgo.Database
	storage  *mgo.GridFS
)

func initDB() {
	if len(config.GlobalConfig.Mongo) > 0 {
		mongoURL = config.GlobalConfig.Mongo
	}

	// making database on package init
	var err error
	session, err = mgo.Dial(mongoURL)
	if err != nil {
		log.Println("Unable to connect to MongoDB database as a storage backend at url[", mongoURL, "] -> ", err.Error())
		os.Exit(1)
	}

	session.SetMode(mgo.Monotonic, true)

	// Pinging every 1 second to keep connection alive
	go func() {
		for {
			time.Sleep(time.Second * 1)
			err = session.Ping()
			if err != nil {
				log.Println("Error while trying to ping to MongoDB, restting connection -> ", err.Error())
				os.Exit(1)
			}
		}
	}()

	db = session.DB("gifjam")
	storage = db.GridFS("fs")
}

func SaveItem(item *FeedItem) (bool, error) {
	found, err := storage.Find(bson.M{"filename": item.Link}).Count()
	if err != nil {
		return false, err
	}

	// if we already have this image, just returning
	if found > 0 {
		return false, nil
	}

	retry_count := 0

	// if we don't have it downloading it from url
	for {
		if retry_count > 20 {
			log.Println("Retry count existed for url -> ", item.Link)
			return false, nil
		}

		res, err := http.Get(strings.Replace(item.Link, " ", "", -1))
		if err != nil {
			log.Println("Unable to get Gif Image from url ", item.Link, " to save it to DB -> ", err.Error())
			retry_count++
			time.Sleep(time.Second * 1)
			continue
		}

		if !strings.Contains(res.Header.Get("Content-Type"), "image/gif") {
			return false, nil
		}

		file, err := storage.Create(item.Link)
		if err != nil {
			return false, err
		}

		file.SetMeta(item)
		_, err = io.Copy(file, res.Body)
		if err != nil {
			return false, err
		}

		file.Close()

		break
	}

	return true, nil
}

// Getting FileID's for downloading them from client
func GetItems(offset, limit int) (ids []string, err error) {
	files := []bson.M{}
	err = storage.Find(bson.M{"metadata.visible": true}).Skip(offset).Limit(limit).All(&files)
	if err != nil {
		return nil, err
	}

	for _, file := range files {
		ids = append(ids, file["_id"].(bson.ObjectId).Hex())
	}

	return ids, nil
}

func GetFileIO(id string) (int64, io.ReadCloser, error) {
	file, err := storage.OpenId(bson.ObjectIdHex(id))
	if err != nil {
		return 0, nil, err
	}

	return file.Size(), file, nil
}

func SetVisibility(id string, is_visible bool) error {
	return db.C("fs.files").Update(bson.M{"_id": bson.ObjectIdHex(id)}, bson.M{"$set": bson.M{"metadata.visible": is_visible}})
}
<commit_msg>replacing spaces in url<commit_after>package gifGrabber

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"time"
	"gifjam/config"
)

var (
	mongoURL = os.Getenv("GIFJAM_MONGO")
	session  *mgo.Session
	db       *mgo.Database
	storage  *mgo.GridFS
)

func initDB() {
	if len(config.GlobalConfig.Mongo) > 0 {
		mongoURL = config.GlobalConfig.Mongo
	}

	// making database on package init
	var err error
	session, err = mgo.Dial(mongoURL)
	if err != nil {
		log.Println("Unable to connect to MongoDB database as a storage backend at url[", mongoURL, "] -> ", err.Error())
		os.Exit(1)
	}

	session.SetMode(mgo.Monotonic, true)

	// Pinging every 1 second to keep connection alive
	go func() {
		for {
			time.Sleep(time.Second * 1)
			err = session.Ping()
			if err != nil {
				log.Println("Error while trying to ping to MongoDB, restting connection -> ", err.Error())
				os.Exit(1)
			}
		}
	}()

	db = session.DB("gifjam")
	storage = db.GridFS("fs")
}

func SaveItem(item *FeedItem) (bool, error) {
	found, err := storage.Find(bson.M{"filename": item.Link}).Count()
	if err != nil {
		return false, err
	}

	// if we already have this image, just returning
	if found > 0 {
		return false, nil
	}

	retry_count := 0

	// if we don't have it downloading it from url
	for {
		if retry_count > 20 {
			log.Println("Retry count existed for url -> ", item.Link)
			return false, nil
		}

		res, err := http.Get(strings.Replace(strings.Replace(item.Link, " ", "", -1), "\t", "", -1))
		if err != nil {
			log.Println("Unable to get Gif Image from url ", item.Link, " to save it to DB -> ", err.Error())
			retry_count++
			time.Sleep(time.Second * 1)
			continue
		}

		if !strings.Contains(res.Header.Get("Content-Type"), "image/gif") {
			return false, nil
		}

		file, err := storage.Create(item.Link)
		if err != nil {
			return false, err
		}

		file.SetMeta(item)
		_, err = io.Copy(file, res.Body)
		if err != nil {
			return false, err
		}

		file.Close()

		break
	}

	return true, nil
}

// Getting FileID's for downloading them from client
func GetItems(offset, limit int) (ids []string, err error) {
	files := []bson.M{}
	err = storage.Find(bson.M{"metadata.visible": true}).Skip(offset).Limit(limit).All(&files)
	if err != nil {
		return nil, err
	}

	for _, file := range files {
		ids = append(ids, file["_id"].(bson.ObjectId).Hex())
	}

	return ids, nil
}

func GetFileIO(id string) (int64, io.ReadCloser, error) {
	file, err := storage.OpenId(bson.ObjectIdHex(id))
	if err != nil {
		return 0, nil, err
	}

	return file.Size(), file, nil
}

func SetVisibility(id string, is_visible bool) error {
	return db.C("fs.files").Update(bson.M{"_id": bson.ObjectIdHex(id)}, bson.M{"$set": bson.M{"metadata.visible": is_visible}})
}
<|endoftext|>


<commit_before>package jwt

import (
	"testing"
	"time"

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

func stdClaims() Claims {
	now := time.Now()
	return Claims{
		Issuer:   "me",
		Audience: []string{"some_aud", "some_aud2"},
		Expiry:   NewNumericDate(now.Add(20 * time.Minute)),
		IssuedAt: NewNumericDate(now),
		ID:       "id",
		Subject:  "sub",
	}
}

type TestPayload struct {
	SomeSlice        []string `json:"slice"`
	SomeString       string   `json:"string"`
	SomeInt          int      `json:"int"`
	SomeNestedStruct Claims   `json:"nested"`
}

func payload() TestPayload {
	return TestPayload{
		SomeSlice: []string{
			"openid",
			"email",
			"groups",
			"profile",
			"offline_access",
		},
		SomeString:       "sdfsf",
		SomeInt:          1243,
		SomeNestedStruct: stdClaims(),
	}
}

func TestBuilder_ExampleSerializeObtain_OK(t *testing.T) {
	p := "some_payload"
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.SignedAndEncryptedJWT().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	obtainer := b.FromSignedAndEncryptedJWT(token)

	// Test payload.
	var fetched string
	err = obtainer.Payload(&fetched)
	require.NoError(t, err)

	assert.EqualValues(t, p, fetched)

	// Test std claims from StdClaims() method.
	fetchedStdClaims, err := obtainer.StdClaims()
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedStdClaims, cl)
	assert.NoError(t, err)
}

func TestBuilder_NestedJWTSerializeObtain_OK(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.SignedAndEncryptedJWT().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	obtainer := b.FromSignedAndEncryptedJWT(token)

	// Test payload.
	fetched := TestPayload{}
	err = obtainer.Payload(&fetched)
	require.NoError(t, err)

	assert.EqualValues(t, p, fetched)

	// Test std claims from Claims() method.
	var fetchedCl Claims
	err = obtainer.Claims(&fetchedCl)
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedCl, cl)
	assert.NoError(t, err)

	// Test std claims from StdClaims() method.
	fetchedStdClaims, err := obtainer.StdClaims()
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedStdClaims, cl)
	assert.NoError(t, err)
}

func TestBuilder_NestedJWTSerializeObtain_DifferentKeys(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.SignedAndEncryptedJWT().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	yetAnotherBuilder, err := NewDefaultBuilder()
	require.NoError(t, err)

	fetched := TestPayload{}
	obtainer := yetAnotherBuilder.FromSignedAndEncryptedJWT(token)

	// Test payload.
	err = obtainer.Payload(&fetched)
	require.Error(t, err, "Different builder is used, so keys are different")
}

func TestBuilder_JWESerializeObtain_OK(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.JWE().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	obtainer := b.FromJWE(token)

	// Test payload.
	fetched := TestPayload{}
	err = obtainer.Payload(&fetched)
	require.NoError(t, err)

	assert.EqualValues(t, p, fetched)

	// Test std claims from Claims() method.
	var fetchedCl Claims
	err = obtainer.Claims(&fetchedCl)
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedCl, cl)
	assert.NoError(t, err)

	// Test std claims from StdClaims() method.
	fetchedStdClaims, err := obtainer.StdClaims()
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedStdClaims, cl)
	assert.NoError(t, err)
}

func TestBuilder_JWESerializeObtain_DifferentKeys(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.JWE().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	yetAnotherBuilder, err := NewDefaultBuilder()
	require.NoError(t, err)

	fetched := TestPayload{}
	obtainer := yetAnotherBuilder.FromJWE(token)

	// Test payload.
	err = obtainer.Payload(&fetched)
	require.Error(t, err, "Different builder is used, so keys are different")
}

func TestBuilder_JWSSerializeObtain_OK(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.JWS().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	signedObtainer := NewSignedObtainer(
		newPubJWK(
			&b.prvKey.PublicKey,
			string(defaultSignatureAlgorithm),
			signatureJWKUse,
		),
	)

	// TODO: first if first part is in form of {kid:<>, alg:<>}

	obtainer := signedObtainer.FromJWS(token)

	// Test payload.
	fetched := TestPayload{}
	err = obtainer.Payload(&fetched)
	require.NoError(t, err)

	assert.EqualValues(t, p, fetched)

	// Test std claims from Claims() method.
	var fetchedCl Claims
	err = obtainer.Claims(&fetchedCl)
	require.NoError(t, err)

	err = signedObtainer.VerifyStdClaims(fetchedCl, cl)
	assert.NoError(t, err)

	// Test std claims from StdClaims() method.
	fetchedStdClaims, err := obtainer.StdClaims()
	require.NoError(t, err)

	err = signedObtainer.VerifyStdClaims(fetchedStdClaims, cl)
	assert.NoError(t, err)
}

func TestBuilder_JWSSerializeObtain_DifferentKeys(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.JWS().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	yetAnotherBuilder, err := NewDefaultBuilder()
	require.NoError(t, err)

	signedObtainer := NewSignedObtainer(
		newPubJWK(
			&yetAnotherBuilder.prvKey.PublicKey,
			string(defaultSignatureAlgorithm),
			signatureJWKUse,
		),
	)

	fetched := TestPayload{}
	obtainer := signedObtainer.FromJWS(token)

	// Test payload.
	err = obtainer.Payload(&fetched)
	require.Error(t, err, "Different builder is used, so keys are different")
}

func TestSignedObtainer_ValidJWK(t *testing.T) {
	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	jwk := b.PublicJWK()
	assert.Equal(t, jwk.Algorithm, string(defaultSignatureAlgorithm))
	assert.Equal(t, jwk.Use, signatureJWKUse)

	signedObtainer := NewSignedObtainer(
		newPubJWK(
			&b.prvKey.PublicKey,
			string(defaultSignatureAlgorithm),
			signatureJWKUse,
		),
	)
	jwkFromObtainer := signedObtainer.PublicJWK()

	assert.EqualValues(t, jwk, jwkFromObtainer)
}
<commit_msg>Added extra test case.<commit_after>package jwt

import (
	"testing"
	"time"

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

func stdClaims() Claims {
	now := time.Now()
	return Claims{
		Issuer:   "me",
		Audience: []string{"some_aud", "some_aud2"},
		Expiry:   NewNumericDate(now.Add(20 * time.Minute)),
		IssuedAt: NewNumericDate(now),
		ID:       "id",
		Subject:  "sub",
	}
}

type TestPayload struct {
	SomeSlice        []string `json:"slice"`
	SomeString       string   `json:"string"`
	SomeInt          int      `json:"int"`
	SomeNestedStruct Claims   `json:"nested"`
}

func payload() TestPayload {
	return TestPayload{
		SomeSlice: []string{
			"openid",
			"email",
			"groups",
			"profile",
			"offline_access",
		},
		SomeString:       "sdfsf",
		SomeInt:          1243,
		SomeNestedStruct: stdClaims(),
	}
}

func TestBuilder_ExampleSerializeObtain_OK(t *testing.T) {
	p := "some_payload"
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.SignedAndEncryptedJWT().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	obtainer := b.FromSignedAndEncryptedJWT(token)

	// Test payload.
	var fetched string
	err = obtainer.Payload(&fetched)
	require.NoError(t, err)

	assert.EqualValues(t, p, fetched)

	// Test std claims from StdClaims() method.
	fetchedStdClaims, err := obtainer.StdClaims()
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedStdClaims, cl)
	assert.NoError(t, err)
}

func TestBuilder_NestedJWTSerializeObtain_OK(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.SignedAndEncryptedJWT().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	obtainer := b.FromSignedAndEncryptedJWT(token)

	// Test payload.
	fetched := TestPayload{}
	err = obtainer.Payload(&fetched)
	require.NoError(t, err)

	assert.EqualValues(t, p, fetched)

	// Test std claims from Claims() method.
	var fetchedCl Claims
	err = obtainer.Claims(&fetchedCl)
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedCl, cl)
	assert.NoError(t, err)

	// Test std claims from StdClaims() method.
	fetchedStdClaims, err := obtainer.StdClaims()
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedStdClaims, cl)
	assert.NoError(t, err)
}

func TestBuilder_NestedJWTSerializeObtain_DifferentKeys(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.SignedAndEncryptedJWT().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	yetAnotherBuilder, err := NewDefaultBuilder()
	require.NoError(t, err)

	fetched := TestPayload{}
	obtainer := yetAnotherBuilder.FromSignedAndEncryptedJWT(token)

	// Test payload.
	err = obtainer.Payload(&fetched)
	require.Error(t, err, "Different builder is used, so keys are different")
}

func TestBuilder_JWESerializeObtain_OK(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.JWE().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	obtainer := b.FromJWE(token)

	// Test payload.
	fetched := TestPayload{}
	err = obtainer.Payload(&fetched)
	require.NoError(t, err)

	assert.EqualValues(t, p, fetched)

	// Test std claims from Claims() method.
	var fetchedCl Claims
	err = obtainer.Claims(&fetchedCl)
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedCl, cl)
	assert.NoError(t, err)

	// Test std claims from StdClaims() method.
	fetchedStdClaims, err := obtainer.StdClaims()
	require.NoError(t, err)

	err = b.VerifyStdClaims(fetchedStdClaims, cl)
	assert.NoError(t, err)
}

func TestBuilder_JWESerializeObtain_DifferentKeys(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.JWE().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	yetAnotherBuilder, err := NewDefaultBuilder()
	require.NoError(t, err)

	fetched := TestPayload{}
	obtainer := yetAnotherBuilder.FromJWE(token)

	// Test payload.
	err = obtainer.Payload(&fetched)
	require.Error(t, err, "Different builder is used, so keys are different")
}

func TestBuilder_JWSSerializeObtain_OK(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.JWS().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	signedObtainer := NewSignedObtainer(
		newPubJWK(
			&b.prvKey.PublicKey,
			string(defaultSignatureAlgorithm),
			signatureJWKUse,
		),
	)

	// TODO: first if first part is in form of {kid:<>, alg:<>}

	obtainer := signedObtainer.FromJWS(token)

	// Test payload.
	fetched := TestPayload{}
	err = obtainer.Payload(&fetched)
	require.NoError(t, err)

	assert.EqualValues(t, p, fetched)

	// Test std claims from Claims() method.
	var fetchedCl Claims
	err = obtainer.Claims(&fetchedCl)
	require.NoError(t, err)

	err = signedObtainer.VerifyStdClaims(fetchedCl, cl)
	assert.NoError(t, err)

	// Test std claims from StdClaims() method.
	fetchedStdClaims, err := obtainer.StdClaims()
	require.NoError(t, err)

	err = signedObtainer.VerifyStdClaims(fetchedStdClaims, cl)
	assert.NoError(t, err)
}

func TestBuilder_JWSSerializeObtain_DifferentKeys(t *testing.T) {
	p := payload()
	cl := stdClaims()

	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	token, err := b.JWS().
		Claims(cl).
		Payload(p).
		CompactSerialize()
	require.NoError(t, err)

	yetAnotherBuilder, err := NewDefaultBuilder()
	require.NoError(t, err)

	signedObtainer := NewSignedObtainer(
		newPubJWK(
			&yetAnotherBuilder.prvKey.PublicKey,
			string(defaultSignatureAlgorithm),
			signatureJWKUse,
		),
	)

	fetched := TestPayload{}
	obtainer := signedObtainer.FromJWS(token)

	// Test payload.
	err = obtainer.Payload(&fetched)
	require.Error(t, err, "Different builder is used, so keys are different")
}

func TestSignedObtainer_ValidJWK(t *testing.T) {
	b, err := NewDefaultBuilder()
	require.NoError(t, err)

	jwk := b.PublicJWK()
	assert.Equal(t, jwk.Algorithm, string(defaultSignatureAlgorithm))
	assert.Equal(t, jwk.Use, signatureJWKUse)
	assert.True(t, jwk.KeyID != "")

	signedObtainer := NewSignedObtainer(
		newPubJWK(
			&b.prvKey.PublicKey,
			string(defaultSignatureAlgorithm),
			signatureJWKUse,
		),
	)
	jwkFromObtainer := signedObtainer.PublicJWK()

	assert.EqualValues(t, jwk, jwkFromObtainer)
}
<|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 http

import (
	"bytes"
	"reflect"
	"strings"
	"testing"
)

type stringMultimap map[string][]string

type parseTest struct {
	query string
	out   stringMultimap
}

var parseTests = []parseTest{
	parseTest{
		query: "a=1&b=2",
		out:   stringMultimap{"a": []string{"1"}, "b": []string{"2"}},
	},
	parseTest{
		query: "a=1&a=2&a=banana",
		out:   stringMultimap{"a": []string{"1", "2", "banana"}},
	},
	parseTest{
		query: "ascii=%3Ckey%3A+0x90%3E",
		out:   stringMultimap{"ascii": []string{"<key: 0x90>"}},
	},
}

func TestParseForm(t *testing.T) {
	for i, test := range parseTests {
		form, err := ParseQuery(test.query)
		if err != nil {
			t.Errorf("test %d: Unexpected error: %v", i, err)
			continue
		}
		if len(form) != len(test.out) {
			t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out))
		}
		for k, evs := range test.out {
			vs, ok := form[k]
			if !ok {
				t.Errorf("test %d: Missing key %q", i, k)
				continue
			}
			if len(vs) != len(evs) {
				t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs))
				continue
			}
			for j, ev := range evs {
				if v := vs[j]; v != ev {
					t.Errorf("test %d: form[%q][%d] = %q, want %q", i, k, j, v, ev)
				}
			}
		}
	}
}

func TestQuery(t *testing.T) {
	req := &Request{Method: "GET"}
	req.URL, _ = ParseURL("http://www.google.com/search?q=foo&q=bar")
	if q := req.FormValue("q"); q != "foo" {
		t.Errorf(`req.FormValue("q") = %q, want "foo"`, q)
	}
}

func TestPostQuery(t *testing.T) {
	req := &Request{Method: "POST"}
	req.URL, _ = ParseURL("http://www.google.com/search?q=foo&q=bar&both=x")
	req.Header = map[string]string{"Content-Type": "application/x-www-form-urlencoded; boo!"}
	req.Body = nopCloser{strings.NewReader("z=post&both=y")}
	if q := req.FormValue("q"); q != "foo" {
		t.Errorf(`req.FormValue("q") = %q, want "foo"`, q)
	}
	if z := req.FormValue("z"); z != "post" {
		t.Errorf(`req.FormValue("z") = %q, want "post"`, z)
	}
	if both := req.Form["both"]; !reflect.DeepEqual(both, []string{"x", "y"}) {
		t.Errorf(`req.FormValue("both") = %q, want ["x", "y"]`, both)
	}
}

type stringMap map[string]string
type parseContentTypeTest struct {
	contentType stringMap
	error       bool
}

var parseContentTypeTests = []parseContentTypeTest{
	parseContentTypeTest{contentType: stringMap{"Content-Type": "text/plain"}},
	parseContentTypeTest{contentType: stringMap{"Content-Type": ""}},
	parseContentTypeTest{contentType: stringMap{"Content-Type": "text/plain; boundary="}},
	parseContentTypeTest{
		contentType: stringMap{"Content-Type": "application/unknown"},
		error:       true,
	},
}

func TestPostContentTypeParsing(t *testing.T) {
	for i, test := range parseContentTypeTests {
		req := &Request{
			Method: "POST",
			Header: test.contentType,
			Body:   nopCloser{bytes.NewBufferString("body")},
		}
		err := req.ParseForm()
		if !test.error && err != nil {
			t.Errorf("test %d: Unexpected error: %v", i, err)
		}
		if test.error && err == nil {
			t.Errorf("test %d should have returned error", i)
		}
	}
}

func TestMultipartReader(t *testing.T) {
	req := &Request{
		Method: "POST",
		Header: stringMap{"Content-Type": `multipart/form-data; boundary="foo123"`},
		Body:   nopCloser{new(bytes.Buffer)},
	}
	multipart, err := req.MultipartReader()
	if multipart == nil {
		t.Errorf("expected multipart; error: %v", err)
	}

	req.Header = stringMap{"Content-Type": "text/plain"}
	multipart, err = req.MultipartReader()
	if multipart != nil {
		t.Errorf("unexpected multipart for text/plain")
	}
}

func TestRedirect(t *testing.T) {
	const (
		start = "http://codesearch.google.com/"
		end   = "http://www.google.com/codesearch"
	)
	r, url, err := Get(start)
	if err != nil {
		t.Fatal(err)
	}
	r.Body.Close()
	if r.StatusCode != 200 || url != end {
		t.Fatalf("Get(%s) got status %d at %s, want 200 at %s", start, r.StatusCode, url, end)
	}
}
<commit_msg>http: Change redirect test URL, as the old one now fails.<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 http

import (
	"bytes"
	"reflect"
	"strings"
	"testing"
)

type stringMultimap map[string][]string

type parseTest struct {
	query string
	out   stringMultimap
}

var parseTests = []parseTest{
	parseTest{
		query: "a=1&b=2",
		out:   stringMultimap{"a": []string{"1"}, "b": []string{"2"}},
	},
	parseTest{
		query: "a=1&a=2&a=banana",
		out:   stringMultimap{"a": []string{"1", "2", "banana"}},
	},
	parseTest{
		query: "ascii=%3Ckey%3A+0x90%3E",
		out:   stringMultimap{"ascii": []string{"<key: 0x90>"}},
	},
}

func TestParseForm(t *testing.T) {
	for i, test := range parseTests {
		form, err := ParseQuery(test.query)
		if err != nil {
			t.Errorf("test %d: Unexpected error: %v", i, err)
			continue
		}
		if len(form) != len(test.out) {
			t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out))
		}
		for k, evs := range test.out {
			vs, ok := form[k]
			if !ok {
				t.Errorf("test %d: Missing key %q", i, k)
				continue
			}
			if len(vs) != len(evs) {
				t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs))
				continue
			}
			for j, ev := range evs {
				if v := vs[j]; v != ev {
					t.Errorf("test %d: form[%q][%d] = %q, want %q", i, k, j, v, ev)
				}
			}
		}
	}
}

func TestQuery(t *testing.T) {
	req := &Request{Method: "GET"}
	req.URL, _ = ParseURL("http://www.google.com/search?q=foo&q=bar")
	if q := req.FormValue("q"); q != "foo" {
		t.Errorf(`req.FormValue("q") = %q, want "foo"`, q)
	}
}

func TestPostQuery(t *testing.T) {
	req := &Request{Method: "POST"}
	req.URL, _ = ParseURL("http://www.google.com/search?q=foo&q=bar&both=x")
	req.Header = map[string]string{"Content-Type": "application/x-www-form-urlencoded; boo!"}
	req.Body = nopCloser{strings.NewReader("z=post&both=y")}
	if q := req.FormValue("q"); q != "foo" {
		t.Errorf(`req.FormValue("q") = %q, want "foo"`, q)
	}
	if z := req.FormValue("z"); z != "post" {
		t.Errorf(`req.FormValue("z") = %q, want "post"`, z)
	}
	if both := req.Form["both"]; !reflect.DeepEqual(both, []string{"x", "y"}) {
		t.Errorf(`req.FormValue("both") = %q, want ["x", "y"]`, both)
	}
}

type stringMap map[string]string
type parseContentTypeTest struct {
	contentType stringMap
	error       bool
}

var parseContentTypeTests = []parseContentTypeTest{
	parseContentTypeTest{contentType: stringMap{"Content-Type": "text/plain"}},
	parseContentTypeTest{contentType: stringMap{"Content-Type": ""}},
	parseContentTypeTest{contentType: stringMap{"Content-Type": "text/plain; boundary="}},
	parseContentTypeTest{
		contentType: stringMap{"Content-Type": "application/unknown"},
		error:       true,
	},
}

func TestPostContentTypeParsing(t *testing.T) {
	for i, test := range parseContentTypeTests {
		req := &Request{
			Method: "POST",
			Header: test.contentType,
			Body:   nopCloser{bytes.NewBufferString("body")},
		}
		err := req.ParseForm()
		if !test.error && err != nil {
			t.Errorf("test %d: Unexpected error: %v", i, err)
		}
		if test.error && err == nil {
			t.Errorf("test %d should have returned error", i)
		}
	}
}

func TestMultipartReader(t *testing.T) {
	req := &Request{
		Method: "POST",
		Header: stringMap{"Content-Type": `multipart/form-data; boundary="foo123"`},
		Body:   nopCloser{new(bytes.Buffer)},
	}
	multipart, err := req.MultipartReader()
	if multipart == nil {
		t.Errorf("expected multipart; error: %v", err)
	}

	req.Header = stringMap{"Content-Type": "text/plain"}
	multipart, err = req.MultipartReader()
	if multipart != nil {
		t.Errorf("unexpected multipart for text/plain")
	}
}

func TestRedirect(t *testing.T) {
	const (
		start = "http://google.com/"
		end   = "http://www.google.com/"
	)
	r, url, err := Get(start)
	if err != nil {
		t.Fatal(err)
	}
	r.Body.Close()
	if r.StatusCode != 200 || url != end {
		t.Fatalf("Get(%s) got status %d at %s, want 200 at %s", start, r.StatusCode, url, end)
	}
}
<|endoftext|>


<commit_before>package dnode

// Function is the type for sending and receiving functions in dnode messages.
type Function struct {
	Caller caller
}

// Call the received function.
func (f Function) Call(args ...interface{}) error {
	return f.Caller.Call(args...)
}

func (f Function) MarshalJSON() ([]byte, error) {
	if _, ok := f.Caller.(callback); !ok {
		return []byte(`null`), nil
	}
	return []byte(`"[Function]"`), nil
}

func (*Function) UnmarshalJSON(data []byte) error {
	return nil
}

type caller interface {
	Call(args ...interface{}) error
}

// Callback is the wrapper for function when sending.
func Callback(f func(*Partial)) Function {
	return Function{callback(f)}
}

type callback func(*Partial)

func (f callback) Call(args ...interface{}) error {
	// Callback is only for sending functions to the remote side
	panic("you cannot call your own callback method")
}

// functionReceived is a type implementing caller interface.
// It is used to set the Function when a callback function is received.
type functionReceived func(...interface{}) error

func (f functionReceived) Call(args ...interface{}) error {
	return f(args...)
}

// Path represents a callback function's path in the arguments structure.
// Contains mixture of string and integer values.
type Path []interface{}

// CallbackSpec is a structure encapsulating a Function and it's Path.
// It is the type of the values in callbacks map.
type CallbackSpec struct {
	// Path represents the callback's path in the arguments structure.
	Path     Path
	Function Function
}
<commit_msg>reorder code<commit_after>package dnode

// Function is the type for sending and receiving functions in dnode messages.
type Function struct {
	Caller caller
}

type caller interface {
	Call(args ...interface{}) error
}

// Call the received function.
func (f Function) Call(args ...interface{}) error {
	return f.Caller.Call(args...)
}

func (f Function) MarshalJSON() ([]byte, error) {
	if _, ok := f.Caller.(callback); !ok {
		return []byte(`null`), nil
	}
	return []byte(`"[Function]"`), nil
}

func (*Function) UnmarshalJSON(data []byte) error {
	return nil
}

// Callback is the wrapper for function when sending.
func Callback(f func(*Partial)) Function {
	return Function{callback(f)}
}

type callback func(*Partial)

func (f callback) Call(args ...interface{}) error {
	// Callback is only for sending functions to the remote side
	panic("you cannot call your own callback method")
}

// functionReceived is a type implementing caller interface.
// It is used to set the Function when a callback function is received.
type functionReceived func(...interface{}) error

func (f functionReceived) Call(args ...interface{}) error {
	return f(args...)
}

// CallbackSpec is a structure encapsulating a Function and it's Path.
// It is the type of the values in callbacks map.
type CallbackSpec struct {
	// Path represents the callback's path in the arguments structure.
	Path     Path
	Function Function
}

// Path represents a callback function's path in the arguments structure.
// Contains mixture of string and integer values.
type Path []interface{}
<|endoftext|>


<commit_before>// Copyright 2010 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 json

import (
	"bytes"
	"math"
	"rand"
	"testing"
)

// Tests of simple examples.

type example struct {
	compact string
	indent  string
}

var examples = []example{
	{`1`, `1`},
	{`{}`, `{}`},
	{`[]`, `[]`},
	{`{"":2}`, "{\n\t\"\": 2\n}"},
	{`[3]`, "[\n\t3\n]"},
	{`[1,2,3]`, "[\n\t1,\n\t2,\n\t3\n]"},
	{`{"x":1}`, "{\n\t\"x\": 1\n}"},
	{ex1, ex1i},
}

var ex1 = `[true,false,null,"x",1,1.5,0,-5e+2]`

var ex1i = `[
	true,
	false,
	null,
	"x",
	1,
	1.5,
	0,
	-5e+2
]`

func TestCompact(t *testing.T) {
	var buf bytes.Buffer
	for _, tt := range examples {
		buf.Reset()
		if err := Compact(&buf, []byte(tt.compact)); err != nil {
			t.Errorf("Compact(%#q): %v", tt.compact, err)
		} else if s := buf.String(); s != tt.compact {
			t.Errorf("Compact(%#q) = %#q, want original", tt.compact, s)
		}

		buf.Reset()
		if err := Compact(&buf, []byte(tt.indent)); err != nil {
			t.Errorf("Compact(%#q): %v", tt.indent, err)
			continue
		} else if s := buf.String(); s != tt.compact {
			t.Errorf("Compact(%#q) = %#q, want %#q", tt.indent, s, tt.compact)
		}
	}
}

func TestIndent(t *testing.T) {
	var buf bytes.Buffer
	for _, tt := range examples {
		buf.Reset()
		if err := Indent(&buf, []byte(tt.indent), "", "\t"); err != nil {
			t.Errorf("Indent(%#q): %v", tt.indent, err)
		} else if s := buf.String(); s != tt.indent {
			t.Errorf("Indent(%#q) = %#q, want original", tt.indent, s)
		}

		buf.Reset()
		if err := Indent(&buf, []byte(tt.compact), "", "\t"); err != nil {
			t.Errorf("Indent(%#q): %v", tt.compact, err)
			continue
		} else if s := buf.String(); s != tt.indent {
			t.Errorf("Indent(%#q) = %#q, want %#q", tt.compact, s, tt.indent)
		}
	}
}

// Tests of a large random structure.

func TestCompactBig(t *testing.T) {
	initBig()
	var buf bytes.Buffer
	if err := Compact(&buf, jsonBig); err != nil {
		t.Fatalf("Compact: %v", err)
	}
	b := buf.Bytes()
	if bytes.Compare(b, jsonBig) != 0 {
		t.Error("Compact(jsonBig) != jsonBig")
		diff(t, b, jsonBig)
		return
	}
}

func TestIndentBig(t *testing.T) {
	initBig()
	var buf bytes.Buffer
	if err := Indent(&buf, jsonBig, "", "\t"); err != nil {
		t.Fatalf("Indent1: %v", err)
	}
	b := buf.Bytes()
	if len(b) == len(jsonBig) {
		// jsonBig is compact (no unnecessary spaces);
		// indenting should make it bigger
		t.Fatalf("Indent(jsonBig) did not get bigger")
	}

	// should be idempotent
	var buf1 bytes.Buffer
	if err := Indent(&buf1, b, "", "\t"); err != nil {
		t.Fatalf("Indent2: %v", err)
	}
	b1 := buf1.Bytes()
	if bytes.Compare(b1, b) != 0 {
		t.Error("Indent(Indent(jsonBig)) != Indent(jsonBig)")
		diff(t, b1, b)
		return
	}

	// should get back to original
	buf1.Reset()
	if err := Compact(&buf1, b); err != nil {
		t.Fatalf("Compact: %v", err)
	}
	b1 = buf1.Bytes()
	if bytes.Compare(b1, jsonBig) != 0 {
		t.Error("Compact(Indent(jsonBig)) != jsonBig")
		diff(t, b1, jsonBig)
		return
	}
}

func TestNextValueBig(t *testing.T) {
	initBig()
	var scan scanner
	item, rest, err := nextValue(jsonBig, &scan)
	if err != nil {
		t.Fatalf("nextValue: %s", err)
	}
	if len(item) != len(jsonBig) || &item[0] != &jsonBig[0] {
		t.Errorf("invalid item: %d %d", len(item), len(jsonBig))
	}
	if len(rest) != 0 {
		t.Errorf("invalid rest: %d", len(rest))
	}

	item, rest, err = nextValue(append(jsonBig, []byte("HELLO WORLD")...), &scan)
	if err != nil {
		t.Fatalf("nextValue extra: %s", err)
	}
	if len(item) != len(jsonBig) {
		t.Errorf("invalid item: %d %d", len(item), len(jsonBig))
	}
	if string(rest) != "HELLO WORLD" {
		t.Errorf("invalid rest: %d", len(rest))
	}
}

func BenchmarkSkipValue(b *testing.B) {
	initBig()
	var scan scanner
	for i := 0; i < b.N; i++ {
		nextValue(jsonBig, &scan)
	}
	b.SetBytes(int64(len(jsonBig)))
}

func diff(t *testing.T, a, b []byte) {
	for i := 0; ; i++ {
		if i >= len(a) || i >= len(b) || a[i] != b[i] {
			j := i - 10
			if j < 0 {
				j = 0
			}
			t.Errorf("diverge at %d: «%s» vs «%s»", i, trim(a[j:]), trim(b[j:]))
			return
		}
	}
}

func trim(b []byte) []byte {
	if len(b) > 20 {
		return b[0:20]
	}
	return b
}

// Generate a random JSON object.

var jsonBig []byte

const (
	big   = 10000
	small = 100
)

func initBig() {
	n := big
	if testing.Short() {
		n = small
	}
	if len(jsonBig) != n {
		b, err := Marshal(genValue(n))
		if err != nil {
			panic(err)
		}
		jsonBig = b
	}
}

func genValue(n int) interface{} {
	if n > 1 {
		switch rand.Intn(2) {
		case 0:
			return genArray(n)
		case 1:
			return genMap(n)
		}
	}
	switch rand.Intn(3) {
	case 0:
		return rand.Intn(2) == 0
	case 1:
		return rand.NormFloat64()
	case 2:
		return genString(30)
	}
	panic("unreachable")
}

func genString(stddev float64) string {
	n := int(math.Fabs(rand.NormFloat64()*stddev + stddev/2))
	c := make([]int, n)
	for i := range c {
		f := math.Fabs(rand.NormFloat64()*64 + 32)
		if f > 0x10ffff {
			f = 0x10ffff
		}
		c[i] = int(f)
	}
	return string(c)
}

func genArray(n int) []interface{} {
	f := int(math.Fabs(rand.NormFloat64()) * math.Fmin(10, float64(n/2)))
	if f > n {
		f = n
	}
	x := make([]interface{}, int(f))
	for i := range x {
		x[i] = genValue(((i+1)*n)/f - (i*n)/f)
	}
	return x
}

func genMap(n int) map[string]interface{} {
	f := int(math.Fabs(rand.NormFloat64()) * math.Fmin(10, float64(n/2)))
	if f > n {
		f = n
	}
	if n > 0 && f == 0 {
		f = 1
	}
	x := make(map[string]interface{})
	for i := 0; i < f; i++ {
		x[genString(10)] = genValue(((i+1)*n)/f - (i*n)/f)
	}
	return x
}
<commit_msg>json: fix test if rand returns 0.<commit_after>// Copyright 2010 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 json

import (
	"bytes"
	"math"
	"rand"
	"testing"
)

// Tests of simple examples.

type example struct {
	compact string
	indent  string
}

var examples = []example{
	{`1`, `1`},
	{`{}`, `{}`},
	{`[]`, `[]`},
	{`{"":2}`, "{\n\t\"\": 2\n}"},
	{`[3]`, "[\n\t3\n]"},
	{`[1,2,3]`, "[\n\t1,\n\t2,\n\t3\n]"},
	{`{"x":1}`, "{\n\t\"x\": 1\n}"},
	{ex1, ex1i},
}

var ex1 = `[true,false,null,"x",1,1.5,0,-5e+2]`

var ex1i = `[
	true,
	false,
	null,
	"x",
	1,
	1.5,
	0,
	-5e+2
]`

func TestCompact(t *testing.T) {
	var buf bytes.Buffer
	for _, tt := range examples {
		buf.Reset()
		if err := Compact(&buf, []byte(tt.compact)); err != nil {
			t.Errorf("Compact(%#q): %v", tt.compact, err)
		} else if s := buf.String(); s != tt.compact {
			t.Errorf("Compact(%#q) = %#q, want original", tt.compact, s)
		}

		buf.Reset()
		if err := Compact(&buf, []byte(tt.indent)); err != nil {
			t.Errorf("Compact(%#q): %v", tt.indent, err)
			continue
		} else if s := buf.String(); s != tt.compact {
			t.Errorf("Compact(%#q) = %#q, want %#q", tt.indent, s, tt.compact)
		}
	}
}

func TestIndent(t *testing.T) {
	var buf bytes.Buffer
	for _, tt := range examples {
		buf.Reset()
		if err := Indent(&buf, []byte(tt.indent), "", "\t"); err != nil {
			t.Errorf("Indent(%#q): %v", tt.indent, err)
		} else if s := buf.String(); s != tt.indent {
			t.Errorf("Indent(%#q) = %#q, want original", tt.indent, s)
		}

		buf.Reset()
		if err := Indent(&buf, []byte(tt.compact), "", "\t"); err != nil {
			t.Errorf("Indent(%#q): %v", tt.compact, err)
			continue
		} else if s := buf.String(); s != tt.indent {
			t.Errorf("Indent(%#q) = %#q, want %#q", tt.compact, s, tt.indent)
		}
	}
}

// Tests of a large random structure.

func TestCompactBig(t *testing.T) {
	initBig()
	var buf bytes.Buffer
	if err := Compact(&buf, jsonBig); err != nil {
		t.Fatalf("Compact: %v", err)
	}
	b := buf.Bytes()
	if bytes.Compare(b, jsonBig) != 0 {
		t.Error("Compact(jsonBig) != jsonBig")
		diff(t, b, jsonBig)
		return
	}
}

func TestIndentBig(t *testing.T) {
	initBig()
	var buf bytes.Buffer
	if err := Indent(&buf, jsonBig, "", "\t"); err != nil {
		t.Fatalf("Indent1: %v", err)
	}
	b := buf.Bytes()
	if len(b) == len(jsonBig) {
		// jsonBig is compact (no unnecessary spaces);
		// indenting should make it bigger
		t.Fatalf("Indent(jsonBig) did not get bigger")
	}

	// should be idempotent
	var buf1 bytes.Buffer
	if err := Indent(&buf1, b, "", "\t"); err != nil {
		t.Fatalf("Indent2: %v", err)
	}
	b1 := buf1.Bytes()
	if bytes.Compare(b1, b) != 0 {
		t.Error("Indent(Indent(jsonBig)) != Indent(jsonBig)")
		diff(t, b1, b)
		return
	}

	// should get back to original
	buf1.Reset()
	if err := Compact(&buf1, b); err != nil {
		t.Fatalf("Compact: %v", err)
	}
	b1 = buf1.Bytes()
	if bytes.Compare(b1, jsonBig) != 0 {
		t.Error("Compact(Indent(jsonBig)) != jsonBig")
		diff(t, b1, jsonBig)
		return
	}
}

func TestNextValueBig(t *testing.T) {
	initBig()
	var scan scanner
	item, rest, err := nextValue(jsonBig, &scan)
	if err != nil {
		t.Fatalf("nextValue: %s", err)
	}
	if len(item) != len(jsonBig) || &item[0] != &jsonBig[0] {
		t.Errorf("invalid item: %d %d", len(item), len(jsonBig))
	}
	if len(rest) != 0 {
		t.Errorf("invalid rest: %d", len(rest))
	}

	item, rest, err = nextValue(append(jsonBig, []byte("HELLO WORLD")...), &scan)
	if err != nil {
		t.Fatalf("nextValue extra: %s", err)
	}
	if len(item) != len(jsonBig) {
		t.Errorf("invalid item: %d %d", len(item), len(jsonBig))
	}
	if string(rest) != "HELLO WORLD" {
		t.Errorf("invalid rest: %d", len(rest))
	}
}

func BenchmarkSkipValue(b *testing.B) {
	initBig()
	var scan scanner
	for i := 0; i < b.N; i++ {
		nextValue(jsonBig, &scan)
	}
	b.SetBytes(int64(len(jsonBig)))
}

func diff(t *testing.T, a, b []byte) {
	for i := 0; ; i++ {
		if i >= len(a) || i >= len(b) || a[i] != b[i] {
			j := i - 10
			if j < 0 {
				j = 0
			}
			t.Errorf("diverge at %d: «%s» vs «%s»", i, trim(a[j:]), trim(b[j:]))
			return
		}
	}
}

func trim(b []byte) []byte {
	if len(b) > 20 {
		return b[0:20]
	}
	return b
}

// Generate a random JSON object.

var jsonBig []byte

const (
	big   = 10000
	small = 100
)

func initBig() {
	n := big
	if testing.Short() {
		n = small
	}
	if len(jsonBig) != n {
		b, err := Marshal(genValue(n))
		if err != nil {
			panic(err)
		}
		jsonBig = b
	}
}

func genValue(n int) interface{} {
	if n > 1 {
		switch rand.Intn(2) {
		case 0:
			return genArray(n)
		case 1:
			return genMap(n)
		}
	}
	switch rand.Intn(3) {
	case 0:
		return rand.Intn(2) == 0
	case 1:
		return rand.NormFloat64()
	case 2:
		return genString(30)
	}
	panic("unreachable")
}

func genString(stddev float64) string {
	n := int(math.Fabs(rand.NormFloat64()*stddev + stddev/2))
	c := make([]int, n)
	for i := range c {
		f := math.Fabs(rand.NormFloat64()*64 + 32)
		if f > 0x10ffff {
			f = 0x10ffff
		}
		c[i] = int(f)
	}
	return string(c)
}

func genArray(n int) []interface{} {
	f := int(math.Fabs(rand.NormFloat64()) * math.Fmin(10, float64(n/2)))
	if f > n {
		f = n
	}
	if n > 0 && f == 0 {
		f = 1
	}
	x := make([]interface{}, f)
	for i := range x {
		x[i] = genValue(((i+1)*n)/f - (i*n)/f)
	}
	return x
}

func genMap(n int) map[string]interface{} {
	f := int(math.Fabs(rand.NormFloat64()) * math.Fmin(10, float64(n/2)))
	if f > n {
		f = n
	}
	if n > 0 && f == 0 {
		f = 1
	}
	x := make(map[string]interface{})
	for i := 0; i < f; i++ {
		x[genString(10)] = genValue(((i+1)*n)/f - (i*n)/f)
	}
	return x
}
<|endoftext|>


<commit_before>package tracker

import (
  "github.com/coreos/go-etcd/etcd"
  "strconv"
  "path"
  "math/rand"
)

type Stat struct {
  StatType string
  Value float64
}

func NewStat(statType string) (stat *Stat) {
  stat = &Stat{StatType: statType}
  return
}

func (stat *Stat) GetStatValue() float64 {
  switch stat.StatType {
  case "cpu":
    return rand.Float64()
  default:
    return 0.0
  }
}

func (stat *Stat) write(myid string, cli *etcd.Client) {
  stat.Value = stat.GetStatValue()

  value := strconv.FormatFloat(stat.Value, 'f', -1, 64)
  cli.Set(path.Join("/stats",myid,stat.StatType), value, 60)
}<commit_msg>start to get stat pool working<commit_after>package tracker

import (
  "github.com/coreos/go-etcd/etcd"
  "strconv"
  "path"
  "bitbucket.org/hayesgm/systemstat"
  "log"
)

type Stat struct {
  StatType string
  Value float64
}

func NewStat(statType string) (stat *Stat) {
  stat = &Stat{StatType: statType}
  return
}

func (stat *Stat) GetStatValue() float64 {
  defer func() {
    if e := recover(); e != nil {
      // We're going to squash issues pull stats
      log.Println("Failed to pull `", stat.StatType, "` stat data:", e)
    }
  }()
  switch stat.StatType {
  case "cpu":
    one := systemstat.GetCPUSample()
    two := systemstat.GetCPUSample()
    avg := systemstat.GetSimpleCPUAverage(one, two)
    return avg.BusyPct
  case "free-mem":
    return float64(systemstat.GetMemSample().MemFree)
  default:
    return 0.0
  }
}

func (stat *Stat) write(myid string, cli *etcd.Client) {
  stat.Value = stat.GetStatValue()

  value := strconv.FormatFloat(stat.Value, 'f', -1, 64)
  cli.Set(path.Join("/stats",myid,stat.StatType), value, 60)
}<|endoftext|>


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

package tspi

// #include <trousers/tss.h>
import "C"

import (
	"crypto"
	"unsafe"
)

// Context is a TSS context
type Context struct {
	context C.TSS_HCONTEXT
	tpm     TPM
}

// NewContext returns a TSS daemon context
func NewContext() (*Context, error) {
	context := new(Context)
	err := tspiError(C.Tspi_Context_Create(&context.context))
	return context, err
}

// Connect opens a connection between the context and the TSS daemon. It
// returns an error on failure.
func (context *Context) Connect() error {
	var tpmhandle C.TSS_HTPM
	err := tspiError(C.Tspi_Context_Connect(context.context, nil))
	if err != nil {
		return err
	}
	C.Tspi_Context_GetTpmObject(context.context, &tpmhandle)
	context.tpm = TPM{handle: tpmhandle, context: context.context}
	return nil
}

// Close closes the connection between the context and the TSS daemon. It
// returns an error on failure.
func (context *Context) Close() error {
	err := tspiError(C.Tspi_Context_Close(context.context))
	return err
}

// CreateNV creates a TSS object referring to a TPM NVRAM area. It returns a
// reference to the object and any error.
func (context *Context) CreateNV() (*NV, error) {
	var handle C.TSS_HNVSTORE
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_NV, 0, (*C.TSS_HOBJECT)(&handle)))
	return &NV{handle: handle, context: context.context}, err
}

// CreateKey creates a TSS object referring to a TPM key. It returns a
// reference to the object and any error.
func (context *Context) CreateKey(flags int) (*Key, error) {
	var handle C.TSS_HKEY
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_RSAKEY, (C.TSS_FLAG)(flags), (*C.TSS_HOBJECT)(&handle)))
	return &Key{handle: handle, context: context.context}, err
}

// LoadKeyByUUID loads the key referenced by UUID. The storetype argument
// indicates whether the key should be obtained from the system or user
// stores. It returns a reference to the key and any error.
func (context *Context) LoadKeyByUUID(storetype int, uuid C.TSS_UUID) (*Key, error) {
	var handle C.TSS_HKEY
	err := tspiError(C.Tspi_Context_LoadKeyByUUID(context.context, (C.TSS_FLAG)(storetype), uuid, &handle))
	return &Key{handle: handle, context: context.context}, err
}

// LoadKeyByBlob takes an encrypted key blob and reads it into the TPM. It
// takes a reference to the parent key and the key blob, and returns a
// reference to the key and any error.
func (context *Context) LoadKeyByBlob(parent *Key, blob []byte) (*Key, error) {
	var handle C.TSS_HKEY
	err := tspiError(C.Tspi_Context_LoadKeyByBlob(context.context, parent.handle, (C.UINT32)(len(blob)), (*C.BYTE)(unsafe.Pointer(&blob[0])), &handle))
	return &Key{handle: handle, context: context.context}, err
}

// GetTPM returns a reference to the TPM associated with this context
func (context *Context) GetTPM() *TPM {
	return &context.tpm
}

// CreatePolicy creates an object referring to a TSS policy. It returns a
// reference to the object plus any error.
func (context *Context) CreatePolicy(flags int) (*Policy, error) {
	var handle C.TSS_HPOLICY
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_POLICY, (C.TSS_FLAG)(flags), (*C.TSS_HOBJECT)(&handle)))
	return &Policy{handle: handle, context: context.context}, err
}

// CreatePCRs creates an object referring to a TSS PCR composite. It returns
// a reference to the object plus any error.
func (context *Context) CreatePCRs(flags int) (*PCRs, error) {
	var handle C.TSS_HPCRS
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_PCRS, (C.TSS_FLAG)(flags), (*C.TSS_HOBJECT)(&handle)))
	return &PCRs{handle: handle, context: context.context}, err
}

// CreateHash creates a Hash object for the given hash algorithm. If using an algorithm other than crypto.SHA1 and
// if you are signing with this hash then make sure the key is created with signing algorithm TSS_SS_RSASSAPKCS1V15_DER.
func (context *Context) CreateHash(hash crypto.Hash) (*Hash, error) {
	var hashAlg C.TSS_FLAG
	if hash == crypto.SHA1 {
		hashAlg = C.TSS_HASH_SHA1
	} else {
		hashAlg = C.TSS_HASH_OTHER
	}

	var handle C.TSS_HHASH
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_HASH, hashAlg, (*C.TSS_HOBJECT)(&handle)))
	if err != nil {
		return nil, err
	}

	return &Hash{
		context: context.context,
		handle:  handle,
		hashAlg: hash,
	}, nil
}
<commit_msg>Added GetCapability() Used to query various aspects of the TPM<commit_after>// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tspi

// #include <trousers/tss.h>
import "C"

import (
	"crypto"
	"unsafe"
)

// Context is a TSS context
type Context struct {
	context C.TSS_HCONTEXT
	tpm     TPM
}

// NewContext returns a TSS daemon context
func NewContext() (*Context, error) {
	context := new(Context)
	err := tspiError(C.Tspi_Context_Create(&context.context))
	return context, err
}

// Connect opens a connection between the context and the TSS daemon. It
// returns an error on failure.
func (context *Context) Connect() error {
	var tpmhandle C.TSS_HTPM
	err := tspiError(C.Tspi_Context_Connect(context.context, nil))
	if err != nil {
		return err
	}
	C.Tspi_Context_GetTpmObject(context.context, &tpmhandle)
	context.tpm = TPM{handle: tpmhandle, context: context.context}
	return nil
}

// Close closes the connection between the context and the TSS daemon. It
// returns an error on failure.
func (context *Context) Close() error {
	err := tspiError(C.Tspi_Context_Close(context.context))
	return err
}

// CreateNV creates a TSS object referring to a TPM NVRAM area. It returns a
// reference to the object and any error.
func (context *Context) CreateNV() (*NV, error) {
	var handle C.TSS_HNVSTORE
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_NV, 0, (*C.TSS_HOBJECT)(&handle)))
	return &NV{handle: handle, context: context.context}, err
}

// CreateKey creates a TSS object referring to a TPM key. It returns a
// reference to the object and any error.
func (context *Context) CreateKey(flags int) (*Key, error) {
	var handle C.TSS_HKEY
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_RSAKEY, (C.TSS_FLAG)(flags), (*C.TSS_HOBJECT)(&handle)))
	return &Key{handle: handle, context: context.context}, err
}

// LoadKeyByUUID loads the key referenced by UUID. The storetype argument
// indicates whether the key should be obtained from the system or user
// stores. It returns a reference to the key and any error.
func (context *Context) LoadKeyByUUID(storetype int, uuid C.TSS_UUID) (*Key, error) {
	var handle C.TSS_HKEY
	err := tspiError(C.Tspi_Context_LoadKeyByUUID(context.context, (C.TSS_FLAG)(storetype), uuid, &handle))
	return &Key{handle: handle, context: context.context}, err
}

// LoadKeyByBlob takes an encrypted key blob and reads it into the TPM. It
// takes a reference to the parent key and the key blob, and returns a
// reference to the key and any error.
func (context *Context) LoadKeyByBlob(parent *Key, blob []byte) (*Key, error) {
	var handle C.TSS_HKEY
	err := tspiError(C.Tspi_Context_LoadKeyByBlob(context.context, parent.handle, (C.UINT32)(len(blob)), (*C.BYTE)(unsafe.Pointer(&blob[0])), &handle))
	return &Key{handle: handle, context: context.context}, err
}

// GetTPM returns a reference to the TPM associated with this context
func (context *Context) GetTPM() *TPM {
	return &context.tpm
}

// CreatePolicy creates an object referring to a TSS policy. It returns a
// reference to the object plus any error.
func (context *Context) CreatePolicy(flags int) (*Policy, error) {
	var handle C.TSS_HPOLICY
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_POLICY, (C.TSS_FLAG)(flags), (*C.TSS_HOBJECT)(&handle)))
	return &Policy{handle: handle, context: context.context}, err
}

// CreatePCRs creates an object referring to a TSS PCR composite. It returns
// a reference to the object plus any error.
func (context *Context) CreatePCRs(flags int) (*PCRs, error) {
	var handle C.TSS_HPCRS
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_PCRS, (C.TSS_FLAG)(flags), (*C.TSS_HOBJECT)(&handle)))
	return &PCRs{handle: handle, context: context.context}, err
}

// CreateHash creates a Hash object for the given hash algorithm. If using an algorithm other than crypto.SHA1 and
// if you are signing with this hash then make sure the key is created with signing algorithm TSS_SS_RSASSAPKCS1V15_DER.
func (context *Context) CreateHash(hash crypto.Hash) (*Hash, error) {
	var hashAlg C.TSS_FLAG
	if hash == crypto.SHA1 {
		hashAlg = C.TSS_HASH_SHA1
	} else {
		hashAlg = C.TSS_HASH_OTHER
	}

	var handle C.TSS_HHASH
	err := tspiError(C.Tspi_Context_CreateObject(context.context, C.TSS_OBJECT_TYPE_HASH, hashAlg, (*C.TSS_HOBJECT)(&handle)))
	if err != nil {
		return nil, err
	}

	return &Hash{
		context: context.context,
		handle:  handle,
		hashAlg: hash,
	}, nil
}

// GetCapability reads the requested capability and subcapability from the TPM.
// A list of capabilities and subcapabilities can be found under tspiconst/tpsiconst.
// For usage information see Section 21.1 of the TPM1.2 main specification-part2.
func (context *Context) GetCapability(capa int, subcaplen uint, subcap uint8) ([]byte, error) {
	var resplen C.uint
	var resp *C.BYTE
	err := tspiError(C.Tspi_TPM_GetCapability(context.tpm.handle, (C.TSS_FLAG)(capa), (C.uint)(subcaplen), (*C.BYTE)(unsafe.Pointer(&subcap)), &resplen, &resp))
	return C.GoBytes(unsafe.Pointer(resp), C.int(resplen)), err
}
<|endoftext|>


<commit_before>// Copyright 2015 tsuru-autoscale 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 tsuru

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

func FindServiceInstance(token string) ([]Instance, error) {
	tsuruHost := os.Getenv("TSURU_HOST")
	url := fmt.Sprintf("%s/service/autoscale", tsuruHost)
	resp, err := http.Get(url)
	if err != nil {
		logger().Printf("Got error on get service instances. err: %s", err)
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if resp.StatusCode > 399 {
		logger().Printf("Got error find service instance status code > 399: %s. url: %s", string(body), url)
		return nil, errors.New(string(body))
	}
	if err != nil {
		logger().Printf("Got error while parsing service json: %s", err)
		return nil, err
	}
	var instances []Instance
	err = json.Unmarshal(body, &instances)
	if err != nil {
		logger().Printf("Got error on unmarshal json %s. err: %s", string(body), err)
		return nil, err
	}
	return instances, nil
}
<commit_msg>tsuru: fix services endpoint.<commit_after>// Copyright 2015 tsuru-autoscale 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 tsuru

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

func FindServiceInstance(token string) ([]Instance, error) {
	tsuruHost := os.Getenv("TSURU_HOST")
	url := fmt.Sprintf("%s/services/autoscale", tsuruHost)
	resp, err := http.Get(url)
	if err != nil {
		logger().Printf("Got error on get service instances. err: %s", err)
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if resp.StatusCode > 399 {
		logger().Printf("Got error find service instance status code > 399: %s. url: %s", string(body), url)
		return nil, errors.New(string(body))
	}
	if err != nil {
		logger().Printf("Got error while parsing service json: %s", err)
		return nil, err
	}
	var instances []Instance
	err = json.Unmarshal(body, &instances)
	if err != nil {
		logger().Printf("Got error on unmarshal json %s. err: %s", string(body), err)
		return nil, err
	}
	return instances, nil
}
<|endoftext|>


<commit_before>// The fields package contains all the fields to represent forms and their
// associated metadata.
// Each of these matches a field in the [Fields](http://docs.typeform.io/docs/introduction)
// section of their api documentation.
package tyform

// Field is a generic Field that holds common properties of all Fields in a Form
type Field struct {
	Type        FieldType `json:"type"                  bson:"t"`
	Question    string    `json:"question"              bson:"q"              validate:"nonzero,max=512"`
	Ref         string    `json:"ref,omitempty"         bson:"r,omitempty"    validate:"max=128"`
	Description string    `json:"description,omitempty" bson:"d"              validate:"max=512"`
	Required    bool      `json:"required,omitempty"    bson:"req,omitempty"`
	Tags        []string  `json:"tags,omitempty"        bson:"g,omitempty"    validate:"arrMap=min=1,arrMap=max=128,max=100"`

	// Value is only included so you can pair up a user's answer with the original field
	Value interface{} `json:"value,omitempty"           bson:"-"`
}

// OpinionLabels represents a OpinionScale's labels property
// It contains a label for the left, center, and right sides of the scale
type OpinionLabels struct {
	Left   string `json:"left,omitempty"                bson:"l,omitempty"    validate:"max=100"`
	Center string `json:"center,omitempty"              bson:"c,omitempty"    validate:"max=100"`
	Right  string `json:"right,omitempty"               bson:"r,omitempty"    validate:"max=100"`
}

// OpinionScale is a scale from 0-(steps - 1)
type OpinionScale struct {
	Field      `bson:",inline"`
	Steps      int64 `json:"steps"                      bson:"s"              validate:"min=5,max=11"`
	StartAtOne bool  `json:"start_at_one,omitempty"     bson:"sao,omitempty"`
	// todo: figure out how to validate if completely empty (once https://github.com/go-validator/validator/pull/38)
	Labels OpinionLabels `json:"labels,omitempty"       bson:"l,omitempty"`
}

// MultipleChoiceChoice is a choice in a MultipleChoice's Choices slice
type MultipleChoiceChoice struct {
	Label string `json:"label"                          bson:"l"              validate:"nonzero, max=512"`
}

// MultipleChoice is a question that contains multiple choices
type MultipleChoice struct {
	Field   `bson:",inline"`
	Choices []MultipleChoiceChoice `json:"choices"      bson:"c"              validate:"min=1,max=25"`
}

// Statement is just text, no question to answer
type Statement struct {
	Field      `bson:",inline"`
	ButtonText string `json:"button_text,omitempty"     bson:"b,omitempty"    validate:"max=128"`
	HideMarks  bool   `json:"hide_marks,omitempty"      bson:"h,omitempty"`
}

// YesNo is just text, with yes/no selector
type YesNo struct {
	Field `bson:",inline"`
}

// FieldType describes the type of field
type FieldType string

var (
	TypeStatement      FieldType = "statement"
	TypeOpinionScale   FieldType = "opinion_scale"
	TypeMultipleChoice FieldType = "multiple_choice"
	TypeYesNo          FieldType = "YesNo"
)

// emptyInterface can be used to get an empty specific struct for the type of
// field that the field is. This is used by the Form to unmarshal
func (f *Field) emptyInterface() (dst FieldInterface) {
	switch f.Type {
	case TypeStatement:
		dst = &Statement{}
	case TypeOpinionScale:
		dst = &OpinionScale{}
	case TypeMultipleChoice:
		dst = &MultipleChoice{}
	case TypeYesNo:
		dst = &YesNo{}
	default:
		dst = f
	}
	return
}

// FieldInterface can be used to get common properties off of the various types
// of Field's on a Form
type FieldInterface interface {
	GetType() FieldType
	GetQuestion() string
	GetRef() string
	GetDescription() string
	GetRequired() bool
	GetTags() []string
	GetValue() interface{}
	SetValue(v interface{})
}

/*
	Various methods for getting common fields off of a Field
*/
func (f *Field) GetType() FieldType {
	return f.Type
}
func (f *Field) GetQuestion() string {
	return f.Question
}
func (f *Field) GetRef() string {
	return f.Ref
}
func (f *Field) GetDescription() string {
	return f.Description
}
func (f *Field) GetRequired() bool {
	return f.Required
}
func (f *Field) GetTags() []string {
	return f.Tags
}
func (f *Field) GetValue() interface{} {
	return f.Value
}
func (f *Field) SetValue(v interface{}) {
	f.Value = v
}
<commit_msg>Fixed typeo with type of YesNo<commit_after>// The fields package contains all the fields to represent forms and their
// associated metadata.
// Each of these matches a field in the [Fields](http://docs.typeform.io/docs/introduction)
// section of their api documentation.
package tyform

// Field is a generic Field that holds common properties of all Fields in a Form
type Field struct {
	Type        FieldType `json:"type"                  bson:"t"`
	Question    string    `json:"question"              bson:"q"              validate:"nonzero,max=512"`
	Ref         string    `json:"ref,omitempty"         bson:"r,omitempty"    validate:"max=128"`
	Description string    `json:"description,omitempty" bson:"d"              validate:"max=512"`
	Required    bool      `json:"required,omitempty"    bson:"req,omitempty"`
	Tags        []string  `json:"tags,omitempty"        bson:"g,omitempty"    validate:"arrMap=min=1,arrMap=max=128,max=100"`

	// Value is only included so you can pair up a user's answer with the original field
	Value interface{} `json:"value,omitempty"           bson:"-"`
}

// OpinionLabels represents a OpinionScale's labels property
// It contains a label for the left, center, and right sides of the scale
type OpinionLabels struct {
	Left   string `json:"left,omitempty"                bson:"l,omitempty"    validate:"max=100"`
	Center string `json:"center,omitempty"              bson:"c,omitempty"    validate:"max=100"`
	Right  string `json:"right,omitempty"               bson:"r,omitempty"    validate:"max=100"`
}

// OpinionScale is a scale from 0-(steps - 1)
type OpinionScale struct {
	Field      `bson:",inline"`
	Steps      int64 `json:"steps"                      bson:"s"              validate:"min=5,max=11"`
	StartAtOne bool  `json:"start_at_one,omitempty"     bson:"sao,omitempty"`
	// todo: figure out how to validate if completely empty (once https://github.com/go-validator/validator/pull/38)
	Labels OpinionLabels `json:"labels,omitempty"       bson:"l,omitempty"`
}

// MultipleChoiceChoice is a choice in a MultipleChoice's Choices slice
type MultipleChoiceChoice struct {
	Label string `json:"label"                          bson:"l"              validate:"nonzero, max=512"`
}

// MultipleChoice is a question that contains multiple choices
type MultipleChoice struct {
	Field   `bson:",inline"`
	Choices []MultipleChoiceChoice `json:"choices"      bson:"c"              validate:"min=1,max=25"`
}

// Statement is just text, no question to answer
type Statement struct {
	Field      `bson:",inline"`
	ButtonText string `json:"button_text,omitempty"     bson:"b,omitempty"    validate:"max=128"`
	HideMarks  bool   `json:"hide_marks,omitempty"      bson:"h,omitempty"`
}

// YesNo is just text, with yes/no selector
type YesNo struct {
	Field `bson:",inline"`
}

// FieldType describes the type of field
type FieldType string

var (
	TypeStatement      FieldType = "statement"
	TypeOpinionScale   FieldType = "opinion_scale"
	TypeMultipleChoice FieldType = "multiple_choice"
	TypeYesNo          FieldType = "yes_no"
)

// emptyInterface can be used to get an empty specific struct for the type of
// field that the field is. This is used by the Form to unmarshal
func (f *Field) emptyInterface() (dst FieldInterface) {
	switch f.Type {
	case TypeStatement:
		dst = &Statement{}
	case TypeOpinionScale:
		dst = &OpinionScale{}
	case TypeMultipleChoice:
		dst = &MultipleChoice{}
	case TypeYesNo:
		dst = &YesNo{}
	default:
		dst = f
	}
	return
}

// FieldInterface can be used to get common properties off of the various types
// of Field's on a Form
type FieldInterface interface {
	GetType() FieldType
	GetQuestion() string
	GetRef() string
	GetDescription() string
	GetRequired() bool
	GetTags() []string
	GetValue() interface{}
	SetValue(v interface{})
}

/*
	Various methods for getting common fields off of a Field
*/
func (f *Field) GetType() FieldType {
	return f.Type
}
func (f *Field) GetQuestion() string {
	return f.Question
}
func (f *Field) GetRef() string {
	return f.Ref
}
func (f *Field) GetDescription() string {
	return f.Description
}
func (f *Field) GetRequired() bool {
	return f.Required
}
func (f *Field) GetTags() []string {
	return f.Tags
}
func (f *Field) GetValue() interface{} {
	return f.Value
}
func (f *Field) SetValue(v interface{}) {
	f.Value = v
}
<|endoftext|>


<commit_before>package gitManip

import (
	"fmt"

	"github.com/fatih/color"

	git "gopkg.in/libgit2/git2go.v24"
)

/*Map to match the RepositoryState enum type with a string
 */
var repositoryStateToString = map[git.RepositoryState]string{
	git.RepositoryStateNone:                 "None",
	git.RepositoryStateMerge:                "Merge",
	git.RepositoryStateRevert:               "Revert",
	git.RepositoryStateCherrypick:           "Cherrypick",
	git.RepositoryStateBisect:               "Bisect",
	git.RepositoryStateRebase:               "Rebase",
	git.RepositoryStateRebaseInteractive:    "Rebase Interactive",
	git.RepositoryStateRebaseMerge:          "Rebase Merge",
	git.RepositoryStateApplyMailbox:         "Apply Mailbox",
	git.RepositoryStateApplyMailboxOrRebase: "Apply Mailbox or Rebase",
}

var fileStateToString = map[git.Status]string{
	git.StatusIndexNew:     "You forgot to commit a new file!",
	git.StatusIgnored:      "Ignored",
	git.StatusConflicted:   "Conflicted",
	git.StatusWtNew:        "New file in your working tree!",
	git.StatusWtModified:   "Modified file in your working tree!",
	git.StatusWtDeleted:    "Deleted file in your working tree!",
	git.StatusWtTypeChange: "Type change detected in your working tree!",
	git.StatusWtRenamed:    "Renamed file in your working tree!",
}

/*Global variable to set the StatusOption parameter, in order to list each file status
 */
var statusOption = git.StatusOptions{
	Show:     git.StatusShowIndexAndWorkdir,
	Flags:    git.StatusOptIncludeUntracked,
	Pathspec: []string{},
}

/*GitObject contains informations about the current git repository
 *
 *The structure is:
 *  accessible:
 *		Is the repository still exists in the hard drive?
 *	path:
 *		The path file.
 *	repository:
 *		The object repository.
 */
type GitObject struct {
	accessible error
	path       string
	repository git.Repository
}

/*New is a constructor for GitObject
 *
 * It neeeds:
 *	path:
 *		The path of the current repository.
 */
func New(path string) *GitObject {
	r, err := git.OpenRepository(path)
	return &GitObject{accessible: err, path: path, repository: *r}
}

/*isAccesible returns the information that is the current git repository is existing or not.
 *This method returns a boolean value: true if the git repository is still accesible (still exists), or false if not.
 */
func (g *GitObject) isAccessible() bool {
	return g.accessible == nil
}

/*Status prints the current status of the repository, accessible via the structure path field.
 *This method works only if the repository is accessible.
 */
func (g *GitObject) Status() {
	if g.isAccessible() {
		if err := g.printChanges(); err != nil {
			color.RedString("Impossible to get stats from %s, due to error %s", g.path, err)
		}
	}
}

/*getDiffWithWT returns the difference between the working tree and the index, for the current git repository.
 *If there is an error processing the request, it returns an error.
 */
func (g *GitObject) getDiffWithWT() (*git.Diff, error) {
	// Get the index of the repository
	currentIndex, err := g.repository.Index()
	if err != nil {
		return nil, err
	}
	// Get the default diff options, and add it custom flags
	defaultDiffOptions, err := git.DefaultDiffOptions()
	if err != nil {
		return nil, err
	}
	defaultDiffOptions.Flags = defaultDiffOptions.Flags | git.DiffIncludeUntracked | git.DiffIncludeTypeChange
	// Check the difference between the working directory and the index
	diff, err := g.repository.DiffIndexToWorkdir(currentIndex, &defaultDiffOptions)
	if err != nil {
		return nil, err
	}
	return diff, nil
}

/*printChanges prints out all changes for the current git repository.
 *If there is an error processing the request, it returns this one.
 */
func (g *GitObject) printChanges() error {
	diff, err := g.getDiffWithWT()
	if err != nil {
		return err
	}
	numDeltas, err := diff.NumDeltas()
	if err != nil {
		return err
	}
	if numDeltas > 0 {
		fmt.Printf("%s %s\t[%d modification(s)]\n", color.RedString("/!\\"), g.path, numDeltas)
		for i := 0; i < numDeltas; i++ {
			delta, _ := diff.GetDelta(i)
			currentStatus := delta.Status
			newFile := delta.NewFile.Path
			oldFile := delta.OldFile.Path
			switch currentStatus {
			case git.DeltaAdded:
				fmt.Printf("\t===> %s has been added!\n", color.MagentaString(newFile))
			case git.DeltaDeleted:
				fmt.Printf("\t===> %s has been deleted!\n", color.MagentaString(newFile))
			case git.DeltaModified:
				fmt.Printf("\t===> %s has been modified!\n", color.MagentaString(newFile))
			case git.DeltaRenamed:
				fmt.Printf("\t===> %s has been renamed to %s!\n", color.MagentaString(oldFile), color.MagentaString(newFile))
			case git.DeltaUntracked:
				fmt.Printf("\t===> %s is untracked - please to add it or update the gitignore file!\n", color.MagentaString(newFile))
			case git.DeltaTypeChange:
				fmt.Printf("\t===> the type of %s has been changed from %d to %d!", color.MagentaString(newFile), delta.OldFile.Mode, delta.NewFile.Mode)
			}
		}
	}
	return nil
}

/*getUntrackedFiles is an old version of a tracking function for Goyave.
 *It is already deprecated.
 */
func (g *GitObject) getUntrackedFiles() {
	fmt.Printf("[%s]...", g.path)
	if untrackedFields, err := g.repository.StatusList(&statusOption); err == nil {
		count, _ := untrackedFields.EntryCount()
		if count == 0 {
			fmt.Println(color.GreenString("\tOK!"))
			return
		}
		fmt.Printf(color.RedString("\t%d untracked files!\n", count))
		for i := 0; i < count; i++ {
			statusEntry, _ := untrackedFields.ByIndex(i)
			fmt.Printf("\t%s\n", fileStateToString[statusEntry.Status])
		}
	}
}

/*List lists the path and the accessibility of a list of git repositories
 */
func List(repositories *[]GitObject) {
	for _, object := range *repositories {
		fmt.Printf("* %s ", object.path)
		if object.isAccessible() {
			fmt.Println(color.GreenString(" [accessible]"))
		} else {
			fmt.Println(color.RedString(" [not accessible]"))
		}
	}
}
<commit_msg>Delete useless code<commit_after>package gitManip

import (
	"fmt"

	"github.com/fatih/color"

	git "gopkg.in/libgit2/git2go.v24"
)

/*Map to match the RepositoryState enum type with a string
 */
var repositoryStateToString = map[git.RepositoryState]string{
	git.RepositoryStateNone:                 "None",
	git.RepositoryStateMerge:                "Merge",
	git.RepositoryStateRevert:               "Revert",
	git.RepositoryStateCherrypick:           "Cherrypick",
	git.RepositoryStateBisect:               "Bisect",
	git.RepositoryStateRebase:               "Rebase",
	git.RepositoryStateRebaseInteractive:    "Rebase Interactive",
	git.RepositoryStateRebaseMerge:          "Rebase Merge",
	git.RepositoryStateApplyMailbox:         "Apply Mailbox",
	git.RepositoryStateApplyMailboxOrRebase: "Apply Mailbox or Rebase",
}

var fileStateToString = map[git.Status]string{
	git.StatusIndexNew:     "You forgot to commit a new file!",
	git.StatusIgnored:      "Ignored",
	git.StatusConflicted:   "Conflicted",
	git.StatusWtNew:        "New file in your working tree!",
	git.StatusWtModified:   "Modified file in your working tree!",
	git.StatusWtDeleted:    "Deleted file in your working tree!",
	git.StatusWtTypeChange: "Type change detected in your working tree!",
	git.StatusWtRenamed:    "Renamed file in your working tree!",
}

/*Global variable to set the StatusOption parameter, in order to list each file status
 */
var statusOption = git.StatusOptions{
	Show:     git.StatusShowIndexAndWorkdir,
	Flags:    git.StatusOptIncludeUntracked,
	Pathspec: []string{},
}

/*GitObject contains informations about the current git repository
 *
 *The structure is:
 *  accessible:
 *		Is the repository still exists in the hard drive?
 *	path:
 *		The path file.
 *	repository:
 *		The object repository.
 */
type GitObject struct {
	accessible error
	path       string
	repository git.Repository
}

/*New is a constructor for GitObject
 *
 * It neeeds:
 *	path:
 *		The path of the current repository.
 */
func New(path string) *GitObject {
	r, err := git.OpenRepository(path)
	return &GitObject{accessible: err, path: path, repository: *r}
}

/*isAccesible returns the information that is the current git repository is existing or not.
 *This method returns a boolean value: true if the git repository is still accesible (still exists), or false if not.
 */
func (g *GitObject) isAccessible() bool {
	return g.accessible == nil
}

/*Status prints the current status of the repository, accessible via the structure path field.
 *This method works only if the repository is accessible.
 */
func (g *GitObject) Status() {
	if g.isAccessible() {
		if err := g.printChanges(); err != nil {
			color.RedString("Impossible to get stats from %s, due to error %s", g.path, err)
		}
	}
}

/*getDiffWithWT returns the difference between the working tree and the index, for the current git repository.
 *If there is an error processing the request, it returns an error.
 */
func (g *GitObject) getDiffWithWT() (*git.Diff, error) {
	// Get the index of the repository
	currentIndex, err := g.repository.Index()
	if err != nil {
		return nil, err
	}
	// Get the default diff options, and add it custom flags
	defaultDiffOptions, err := git.DefaultDiffOptions()
	if err != nil {
		return nil, err
	}
	defaultDiffOptions.Flags = defaultDiffOptions.Flags | git.DiffIncludeUntracked | git.DiffIncludeTypeChange
	// Check the difference between the working directory and the index
	diff, err := g.repository.DiffIndexToWorkdir(currentIndex, &defaultDiffOptions)
	if err != nil {
		return nil, err
	}
	return diff, nil
}

/*printChanges prints out all changes for the current git repository.
 *If there is an error processing the request, it returns this one.
 */
func (g *GitObject) printChanges() error {
	diff, err := g.getDiffWithWT()
	if err != nil {
		return err
	}
	numDeltas, err := diff.NumDeltas()
	if err != nil {
		return err
	}
	if numDeltas > 0 {
		fmt.Printf("%s %s\t[%d modification(s)]\n", color.RedString("/!\\"), g.path, numDeltas)
		for i := 0; i < numDeltas; i++ {
			delta, _ := diff.GetDelta(i)
			currentStatus := delta.Status
			newFile := delta.NewFile.Path
			oldFile := delta.OldFile.Path
			switch currentStatus {
			case git.DeltaAdded:
				fmt.Printf("\t===> %s has been added!\n", color.MagentaString(newFile))
			case git.DeltaDeleted:
				fmt.Printf("\t===> %s has been deleted!\n", color.MagentaString(newFile))
			case git.DeltaModified:
				fmt.Printf("\t===> %s has been modified!\n", color.MagentaString(newFile))
			case git.DeltaRenamed:
				fmt.Printf("\t===> %s has been renamed to %s!\n", color.MagentaString(oldFile), color.MagentaString(newFile))
			case git.DeltaUntracked:
				fmt.Printf("\t===> %s is untracked - please to add it or update the gitignore file!\n", color.MagentaString(newFile))
			case git.DeltaTypeChange:
				fmt.Printf("\t===> the type of %s has been changed from %d to %d!", color.MagentaString(newFile), delta.OldFile.Mode, delta.NewFile.Mode)
			}
		}
	}
	return nil
}

/*List lists the path and the accessibility of a list of git repositories
 */
func List(repositories *[]GitObject) {
	for _, object := range *repositories {
		fmt.Printf("* %s ", object.path)
		if object.isAccessible() {
			fmt.Println(color.GreenString(" [accessible]"))
		} else {
			fmt.Println(color.RedString(" [not accessible]"))
		}
	}
}
<|endoftext|>