<commit_before>package personnummer

import (
	"math"
	"reflect"
	"regexp"
	"strconv"
	"time"
)

// The Luhn algorithm.
func luhn(str string) int {
	sum := 0

	for i, r := range str {
		c := string(r)
		v, _ := strconv.Atoi(c)
		v *= 2 - (i % 2)
		if v > 9 {
			v -= 9
		}
		sum += v
	}

	return int(math.Ceil(float64(sum)/10)*10 - float64(sum))
}

// Test date if lunh is true
func testDate(century string, year string, month string, day string) bool {
	t, err := time.Parse("01/02/2006", month+"/"+day+"/"+century+year)

	if err != nil {
		return false
	}

	y, _ := strconv.Atoi(century + year)
	m, _ := strconv.Atoi(month)
	d, _ := strconv.Atoi(day)

	if y > time.Now().Year() {
		return false
	}

	return !(t.Year() != y || int(t.Month()) != m || t.Day() != d)
}

// Get co-ordination number day
func getCoOrdinationDay(day string) string {
	d, _ := strconv.Atoi(day)
	d -= 60
	day = strconv.Itoa(d)

	if d < 10 {
		day = "0" + day
	}

	return day
}

// Validate Swedish personal identity numbers.
func Valid(str interface{}) bool {
	if reflect.TypeOf(str).Kind() != reflect.Int && reflect.TypeOf(str).Kind() != reflect.String {
		return false
	}

	pr := ""

	if reflect.TypeOf(str).Kind() == reflect.Int {
		pr = strconv.Itoa(str.(int))
	} else {
		pr = str.(string)
	}

	re, _ := regexp.Compile(`^(\d{2}){0,1}(\d{2})(\d{2})(\d{2})([\-|\+]{0,1})?(\d{3})(\d{0,1})$`)
	match := re.FindStringSubmatch(pr)

	if len(match) == 0 {
		return false
	}

	century := match[1]
	year := match[2]
	month := match[3]
	day := match[4]
	num := match[6]
	check := match[7]

	if len(century) == 0 {
		yearNow := time.Now().Year()
		years := [...]int{yearNow, yearNow - 100, yearNow - 150}

		for _, yi := range years {
			ys := strconv.Itoa(yi)

			if Valid(ys[:2] + pr) {
				return true
			}
		}

		return false
	}

	if len(year) == 4 {
		year = year[2:]
	}

	c, _ := strconv.Atoi(check)

	valid := luhn(year+month+day+num) == c && len(check) != 0

	if valid && testDate(century, year, month, day) {
		return valid
	}

	day = getCoOrdinationDay(day)

	return valid && testDate(century, year, month, day)
}
<commit_msg>Update comments<commit_after>package personnummer

import (
	"math"
	"reflect"
	"regexp"
	"strconv"
	"time"
)

// luhn will test if the given string is a valid luhn string.
func luhn(str string) int {
	sum := 0

	for i, r := range str {
		c := string(r)
		v, _ := strconv.Atoi(c)
		v *= 2 - (i % 2)
		if v > 9 {
			v -= 9
		}
		sum += v
	}

	return int(math.Ceil(float64(sum)/10)*10 - float64(sum))
}

// testDate will test if date is valid or not.
func testDate(century string, year string, month string, day string) bool {
	t, err := time.Parse("01/02/2006", month+"/"+day+"/"+century+year)

	if err != nil {
		return false
	}

	y, _ := strconv.Atoi(century + year)
	m, _ := strconv.Atoi(month)
	d, _ := strconv.Atoi(day)

	if y > time.Now().Year() {
		return false
	}

	return !(t.Year() != y || int(t.Month()) != m || t.Day() != d)
}

// getCoOrdinationDay will return co-ordination day.
func getCoOrdinationDay(day string) string {
	d, _ := strconv.Atoi(day)
	d -= 60
	day = strconv.Itoa(d)

	if d < 10 {
		day = "0" + day
	}

	return day
}

// Valid will validate Swedish social security numbers.
func Valid(str interface{}) bool {
	if reflect.TypeOf(str).Kind() != reflect.Int && reflect.TypeOf(str).Kind() != reflect.String {
		return false
	}

	pr := ""

	if reflect.TypeOf(str).Kind() == reflect.Int {
		pr = strconv.Itoa(str.(int))
	} else {
		pr = str.(string)
	}

	re, _ := regexp.Compile(`^(\d{2}){0,1}(\d{2})(\d{2})(\d{2})([\-|\+]{0,1})?(\d{3})(\d{0,1})$`)
	match := re.FindStringSubmatch(pr)

	if len(match) == 0 {
		return false
	}

	century := match[1]
	year := match[2]
	month := match[3]
	day := match[4]
	num := match[6]
	check := match[7]

	if len(century) == 0 {
		yearNow := time.Now().Year()
		years := [...]int{yearNow, yearNow - 100, yearNow - 150}

		for _, yi := range years {
			ys := strconv.Itoa(yi)

			if Valid(ys[:2] + pr) {
				return true
			}
		}

		return false
	}

	if len(year) == 4 {
		year = year[2:]
	}

	c, _ := strconv.Atoi(check)

	valid := luhn(year+month+day+num) == c && len(check) != 0

	if valid && testDate(century, year, month, day) {
		return valid
	}

	day = getCoOrdinationDay(day)

	return valid && testDate(century, year, month, day)
}<|endoftext|>


<commit_before>package controller

import (
	"time"

	"github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1"
	"github.com/giantswarm/apiextensions/pkg/clientset/versioned"
	"github.com/giantswarm/microerror"
	"github.com/giantswarm/micrologger"
	"github.com/giantswarm/operatorkit/client/k8scrdclient"
	"github.com/giantswarm/operatorkit/controller"
	"github.com/giantswarm/operatorkit/informer"
	apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
	"k8s.io/client-go/kubernetes"

	awsclient "github.com/giantswarm/aws-operator/client/aws"
	"github.com/giantswarm/aws-operator/service/controller/v10"
	"github.com/giantswarm/aws-operator/service/controller/v11"
	"github.com/giantswarm/aws-operator/service/controller/v7"
	"github.com/giantswarm/aws-operator/service/controller/v8"
	"github.com/giantswarm/aws-operator/service/controller/v9"
	"github.com/giantswarm/aws-operator/service/controller/v9patch1"
)

type DrainerConfig struct {
	G8sClient    versioned.Interface
	K8sClient    kubernetes.Interface
	K8sExtClient apiextensionsclient.Interface
	Logger       micrologger.Logger

	GuestAWSConfig     DrainerConfigAWS
	GuestUpdateEnabled bool
	HostAWSConfig      DrainerConfigAWS
	ProjectName        string
}

type DrainerConfigAWS struct {
	AccessKeyID     string
	AccessKeySecret string
	Region          string
	SessionToken    string
}

type Drainer struct {
	*controller.Controller
}

func NewDrainer(config DrainerConfig) (*Drainer, error) {
	if config.G8sClient == nil {
		return nil, microerror.Maskf(invalidConfigError, "%T.G8sClient must not be empty", config)
	}
	if config.K8sClient == nil {
		return nil, microerror.Maskf(invalidConfigError, "%T.K8sClient must not be empty", config)
	}
	if config.K8sExtClient == nil {
		return nil, microerror.Maskf(invalidConfigError, "%T.K8sExtClient must not be empty", config)
	}
	if config.Logger == nil {
		return nil, microerror.Maskf(invalidConfigError, "%T.Logger must not be empty", config)
	}

	if config.GuestAWSConfig.AccessKeyID == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.GuestAWSConfig.AccessKeyID must not be empty", config)
	}
	if config.GuestAWSConfig.AccessKeySecret == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.GuestAWSConfig.AccessKeySecret must not be empty", config)
	}
	if config.GuestAWSConfig.Region == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.GuestAWSConfig.Region must not be empty", config)
	}
	if config.HostAWSConfig.AccessKeyID == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.HostAWSConfig.AccessKeyID must not be empty", config)
	}
	if config.HostAWSConfig.AccessKeySecret == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.HostAWSConfig.AccessKeySecret must not be empty", config)
	}
	if config.HostAWSConfig.Region == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.HostAWSConfig.Region must not be empty", config)
	}
	if config.ProjectName == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.ProjectName must not be empty", config)
	}

	var err error

	var crdClient *k8scrdclient.CRDClient
	{
		c := k8scrdclient.Config{
			K8sExtClient: config.K8sExtClient,
			Logger:       config.Logger,
		}

		crdClient, err = k8scrdclient.New(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	resourceRouter, err := newDrainerResourceRouter(config)
	if err != nil {
		return nil, microerror.Mask(err)
	}

	var newInformer *informer.Informer
	{
		c := informer.Config{
			Logger:  config.Logger,
			Watcher: config.G8sClient.ProviderV1alpha1().AWSConfigs(""),

			RateWait:     informer.DefaultRateWait,
			ResyncPeriod: 30 * time.Second,
		}

		newInformer, err = informer.New(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var operatorkitController *controller.Controller
	{
		c := controller.Config{
			CRD:            v1alpha1.NewAWSConfigCRD(),
			CRDClient:      crdClient,
			Informer:       newInformer,
			Logger:         config.Logger,
			ResourceRouter: resourceRouter,
			RESTClient:     config.G8sClient.ProviderV1alpha1().RESTClient(),

			// Name is used to compute finalizer names. This here results in something
			// like operatorkit.giantswarm.io/aws-operator-drainer.
			Name: config.ProjectName + "-drainer",
		}

		operatorkitController, err = controller.New(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	d := &Drainer{
		Controller: operatorkitController,
	}

	return d, nil
}

func newDrainerResourceRouter(config DrainerConfig) (*controller.ResourceRouter, error) {
	var err error

	guestAWSConfig := awsclient.Config{
		AccessKeyID:     config.GuestAWSConfig.AccessKeyID,
		AccessKeySecret: config.GuestAWSConfig.AccessKeySecret,
		SessionToken:    config.GuestAWSConfig.SessionToken,
		Region:          config.GuestAWSConfig.Region,
	}

	hostAWSConfig := awsclient.Config{
		AccessKeyID:     config.HostAWSConfig.AccessKeyID,
		AccessKeySecret: config.HostAWSConfig.AccessKeySecret,
		SessionToken:    config.HostAWSConfig.SessionToken,
		Region:          config.HostAWSConfig.Region,
	}

	awsClients := awsclient.NewClients(guestAWSConfig)

	var v7ResourceSet *controller.ResourceSet
	{
		c := v7.DrainerResourceSetConfig{
			GuestAWSClients: awsClients,
			Logger:          config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v7ResourceSet, err = v7.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v8ResourceSet *controller.ResourceSet
	{
		c := v8.DrainerResourceSetConfig{
			AWS:       awsClients,
			G8sClient: config.G8sClient,
			Logger:    config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v8ResourceSet, err = v8.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v9ResourceSet *controller.ResourceSet
	{
		c := v9.DrainerResourceSetConfig{
			AWS:       awsClients,
			G8sClient: config.G8sClient,
			Logger:    config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v9ResourceSet, err = v9.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v9patch1ResourceSet *controller.ResourceSet
	{
		c := v9patch1.DrainerResourceSetConfig{
			AWS:       awsClients,
			G8sClient: config.G8sClient,
			Logger:    config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v9patch1ResourceSet, err = v9patch1.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v10ResourceSet *controller.ResourceSet
	{
		c := v10.DrainerResourceSetConfig{
			AWS:       awsClients,
			G8sClient: config.G8sClient,
			Logger:    config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v10ResourceSet, err = v10.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v11ResourceSet *controller.ResourceSet
	{
		c := v11.DrainerResourceSetConfig{
			G8sClient:     config.G8sClient,
			HostAWSConfig: hostAWSConfig,
			K8sClient:     config.K8sClient,
			Logger:        config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v11ResourceSet, err = v11.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var resourceRouter *controller.ResourceRouter
	{
		c := controller.ResourceRouterConfig{
			Logger: config.Logger,

			ResourceSets: []*controller.ResourceSet{
				v7ResourceSet,
				v8ResourceSet,
				v9ResourceSet,
				v9patch1ResourceSet,
				v10ResourceSet,
				v11ResourceSet,
			},
		}

		resourceRouter, err = controller.NewResourceRouter(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	return resourceRouter, nil
}
<commit_msg>drainer: use GuestAWSConfig as HostAWSConfig when not present (#959)<commit_after>package controller

import (
	"time"

	"github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1"
	"github.com/giantswarm/apiextensions/pkg/clientset/versioned"
	"github.com/giantswarm/microerror"
	"github.com/giantswarm/micrologger"
	"github.com/giantswarm/operatorkit/client/k8scrdclient"
	"github.com/giantswarm/operatorkit/controller"
	"github.com/giantswarm/operatorkit/informer"
	apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
	"k8s.io/client-go/kubernetes"

	awsclient "github.com/giantswarm/aws-operator/client/aws"
	"github.com/giantswarm/aws-operator/service/controller/v10"
	"github.com/giantswarm/aws-operator/service/controller/v11"
	"github.com/giantswarm/aws-operator/service/controller/v7"
	"github.com/giantswarm/aws-operator/service/controller/v8"
	"github.com/giantswarm/aws-operator/service/controller/v9"
	"github.com/giantswarm/aws-operator/service/controller/v9patch1"
)

type DrainerConfig struct {
	G8sClient    versioned.Interface
	K8sClient    kubernetes.Interface
	K8sExtClient apiextensionsclient.Interface
	Logger       micrologger.Logger

	GuestAWSConfig     DrainerConfigAWS
	GuestUpdateEnabled bool
	HostAWSConfig      DrainerConfigAWS
	ProjectName        string
}

type DrainerConfigAWS struct {
	AccessKeyID     string
	AccessKeySecret string
	Region          string
	SessionToken    string
}

type Drainer struct {
	*controller.Controller
}

func NewDrainer(config DrainerConfig) (*Drainer, error) {
	if config.G8sClient == nil {
		return nil, microerror.Maskf(invalidConfigError, "%T.G8sClient must not be empty", config)
	}
	if config.K8sClient == nil {
		return nil, microerror.Maskf(invalidConfigError, "%T.K8sClient must not be empty", config)
	}
	if config.K8sExtClient == nil {
		return nil, microerror.Maskf(invalidConfigError, "%T.K8sExtClient must not be empty", config)
	}
	if config.Logger == nil {
		return nil, microerror.Maskf(invalidConfigError, "%T.Logger must not be empty", config)
	}

	if config.GuestAWSConfig.AccessKeyID == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.GuestAWSConfig.AccessKeyID must not be empty", config)
	}
	if config.GuestAWSConfig.AccessKeySecret == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.GuestAWSConfig.AccessKeySecret must not be empty", config)
	}
	if config.GuestAWSConfig.Region == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.GuestAWSConfig.Region must not be empty", config)
	}
	// TODO: remove this when all version prior to v11 are removed
	if config.HostAWSConfig.AccessKeyID == "" && config.HostAWSConfig.AccessKeySecret == "" {
		config.Logger.Log("debug", "no host cluster account credentials supplied, assuming guest and host uses same account")
		config.HostAWSConfig = config.GuestAWSConfig
	} else {
		if config.HostAWSConfig.AccessKeyID == "" {
			return nil, microerror.Maskf(invalidConfigError, "config.HostAWSConfig.AccessKeyID must not be empty")
		}
		if config.HostAWSConfig.AccessKeySecret == "" {
			return nil, microerror.Maskf(invalidConfigError, "config.HostAWSConfig.AccessKeySecret must not be empty")
		}
		if config.HostAWSConfig.Region == "" {
			return nil, microerror.Maskf(invalidConfigError, "config.HostAWSConfig.Region must not be empty")
		}
	}
	if config.ProjectName == "" {
		return nil, microerror.Maskf(invalidConfigError, "%T.ProjectName must not be empty", config)
	}

	var err error

	var crdClient *k8scrdclient.CRDClient
	{
		c := k8scrdclient.Config{
			K8sExtClient: config.K8sExtClient,
			Logger:       config.Logger,
		}

		crdClient, err = k8scrdclient.New(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	resourceRouter, err := newDrainerResourceRouter(config)
	if err != nil {
		return nil, microerror.Mask(err)
	}

	var newInformer *informer.Informer
	{
		c := informer.Config{
			Logger:  config.Logger,
			Watcher: config.G8sClient.ProviderV1alpha1().AWSConfigs(""),

			RateWait:     informer.DefaultRateWait,
			ResyncPeriod: 30 * time.Second,
		}

		newInformer, err = informer.New(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var operatorkitController *controller.Controller
	{
		c := controller.Config{
			CRD:            v1alpha1.NewAWSConfigCRD(),
			CRDClient:      crdClient,
			Informer:       newInformer,
			Logger:         config.Logger,
			ResourceRouter: resourceRouter,
			RESTClient:     config.G8sClient.ProviderV1alpha1().RESTClient(),

			// Name is used to compute finalizer names. This here results in something
			// like operatorkit.giantswarm.io/aws-operator-drainer.
			Name: config.ProjectName + "-drainer",
		}

		operatorkitController, err = controller.New(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	d := &Drainer{
		Controller: operatorkitController,
	}

	return d, nil
}

func newDrainerResourceRouter(config DrainerConfig) (*controller.ResourceRouter, error) {
	var err error

	guestAWSConfig := awsclient.Config{
		AccessKeyID:     config.GuestAWSConfig.AccessKeyID,
		AccessKeySecret: config.GuestAWSConfig.AccessKeySecret,
		SessionToken:    config.GuestAWSConfig.SessionToken,
		Region:          config.GuestAWSConfig.Region,
	}

	hostAWSConfig := awsclient.Config{
		AccessKeyID:     config.HostAWSConfig.AccessKeyID,
		AccessKeySecret: config.HostAWSConfig.AccessKeySecret,
		SessionToken:    config.HostAWSConfig.SessionToken,
		Region:          config.HostAWSConfig.Region,
	}

	awsClients := awsclient.NewClients(guestAWSConfig)

	var v7ResourceSet *controller.ResourceSet
	{
		c := v7.DrainerResourceSetConfig{
			GuestAWSClients: awsClients,
			Logger:          config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v7ResourceSet, err = v7.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v8ResourceSet *controller.ResourceSet
	{
		c := v8.DrainerResourceSetConfig{
			AWS:       awsClients,
			G8sClient: config.G8sClient,
			Logger:    config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v8ResourceSet, err = v8.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v9ResourceSet *controller.ResourceSet
	{
		c := v9.DrainerResourceSetConfig{
			AWS:       awsClients,
			G8sClient: config.G8sClient,
			Logger:    config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v9ResourceSet, err = v9.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v9patch1ResourceSet *controller.ResourceSet
	{
		c := v9patch1.DrainerResourceSetConfig{
			AWS:       awsClients,
			G8sClient: config.G8sClient,
			Logger:    config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v9patch1ResourceSet, err = v9patch1.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v10ResourceSet *controller.ResourceSet
	{
		c := v10.DrainerResourceSetConfig{
			AWS:       awsClients,
			G8sClient: config.G8sClient,
			Logger:    config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v10ResourceSet, err = v10.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var v11ResourceSet *controller.ResourceSet
	{
		c := v11.DrainerResourceSetConfig{
			G8sClient:     config.G8sClient,
			HostAWSConfig: hostAWSConfig,
			K8sClient:     config.K8sClient,
			Logger:        config.Logger,

			GuestUpdateEnabled: config.GuestUpdateEnabled,
			ProjectName:        config.ProjectName,
		}

		v11ResourceSet, err = v11.NewDrainerResourceSet(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	var resourceRouter *controller.ResourceRouter
	{
		c := controller.ResourceRouterConfig{
			Logger: config.Logger,

			ResourceSets: []*controller.ResourceSet{
				v7ResourceSet,
				v8ResourceSet,
				v9ResourceSet,
				v9patch1ResourceSet,
				v10ResourceSet,
				v11ResourceSet,
			},
		}

		resourceRouter, err = controller.NewResourceRouter(c)
		if err != nil {
			return nil, microerror.Mask(err)
		}
	}

	return resourceRouter, nil
}
<|endoftext|>


<commit_before>package luddite

import (
	"net/http"
	"net/url"
	"strconv"
)

const (
	HeaderAccept               = "Accept"
	HeaderAuthorization        = "Authorization"
	HeaderContentType          = "Content-Type"
	HeaderETag                 = "ETag"
	HeaderForwardedFor         = "X-Forwarded-For"
	HeaderLocation             = "Location"
	HeaderRequestId            = "X-Request-Id"
	HeaderSpirentApiVersion    = "X-Spirent-Api-Version"
	HeaderSpirentInhibitPaging = "X-Spirent-Inhibit-Paging"
	HeaderSpirentNextLink      = "X-Spirent-Next-Link"
	HeaderSpirentResourceNonce = "X-Spirent-Resource-Nonce"

	CursorNever = "never"
)

func RequestId(r *http.Request) string {
	return r.Header.Get(HeaderRequestId)
}

func RequestBearerToken(r *http.Request) (token string) {
	if authStr := r.Header.Get(HeaderAuthorization); authStr != "" && authStr[:7] == "Bearer " {
		token = authStr[7:]
	}
	return
}

func RequestApiVersion(r *http.Request, defaultVersion int) (version int) {
	version = defaultVersion
	if versionStr := r.Header.Get(HeaderSpirentApiVersion); versionStr != "" {
		if i, err := strconv.Atoi(versionStr); err == nil && i > 0 {
			version = i
		}
	}
	return
}

func RequestQueryCursor(r *http.Request) string {
	if _, ok := r.Header[HeaderSpirentInhibitPaging]; ok {
		return CursorNever
	}
	return r.URL.Query().Get("cursor")
}

func RequestNextLink(r *http.Request, cursor string) *url.URL {
	next := *r.URL
	v := next.Query()
	v.Set("cursor", cursor)
	next.RawQuery = v.Encode()
	return &next
}

func RequestResourceNonce(r *http.Request) string {
	return r.Header.Get(HeaderSpirentResourceNonce)
}
<commit_msg>Adding 'X-Spirent-Meta-' HTTP header prefix<commit_after>package luddite

import (
	"net/http"
	"net/url"
	"strconv"
)

const (
	HeaderAccept               = "Accept"
	HeaderAuthorization        = "Authorization"
	HeaderContentType          = "Content-Type"
	HeaderETag                 = "ETag"
	HeaderForwardedFor         = "X-Forwarded-For"
	HeaderLocation             = "Location"
	HeaderRequestId            = "X-Request-Id"
	HeaderSpirentApiVersion    = "X-Spirent-Api-Version"
	HeaderSpirentInhibitPaging = "X-Spirent-Inhibit-Paging"
	HeaderSpirentMetaPrefix    = "X-Spirent-Meta-"
	HeaderSpirentNextLink      = "X-Spirent-Next-Link"
	HeaderSpirentResourceNonce = "X-Spirent-Resource-Nonce"

	CursorNever = "never"
)

func RequestId(r *http.Request) string {
	return r.Header.Get(HeaderRequestId)
}

func RequestBearerToken(r *http.Request) (token string) {
	if authStr := r.Header.Get(HeaderAuthorization); authStr != "" && authStr[:7] == "Bearer " {
		token = authStr[7:]
	}
	return
}

func RequestApiVersion(r *http.Request, defaultVersion int) (version int) {
	version = defaultVersion
	if versionStr := r.Header.Get(HeaderSpirentApiVersion); versionStr != "" {
		if i, err := strconv.Atoi(versionStr); err == nil && i > 0 {
			version = i
		}
	}
	return
}

func RequestQueryCursor(r *http.Request) string {
	if _, ok := r.Header[HeaderSpirentInhibitPaging]; ok {
		return CursorNever
	}
	return r.URL.Query().Get("cursor")
}

func RequestNextLink(r *http.Request, cursor string) *url.URL {
	next := *r.URL
	v := next.Query()
	v.Set("cursor", cursor)
	next.RawQuery = v.Encode()
	return &next
}

func RequestResourceNonce(r *http.Request) string {
	return r.Header.Get(HeaderSpirentResourceNonce)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	// "fmt"
	"io/ioutil"
	"log"
	"os/exec"
	"strings"
)

var source = flag.String("source", "", "Directory containing image assets")
var destination = flag.String("destination", "", "Destination for image assets")

func main() {
	flag.Parse()
	out, err := exec.Command("bash", "-c", "/usr/bin/find "+*source+" -name *.png -print").CombinedOutput()
	if err != nil {
		log.Fatal(err, string(out))
	}
	imagePaths := strings.Split(string(out), "\n")
	for _, imagePath := range imagePaths {
		paths := strings.Split(imagePath, "/")
		fileName := paths[len(paths)-1]
		if len(fileName) < 4 {
			continue
		}
		imageName := fileName[0 : len(fileName)-4]
		mkdirOut, err := exec.Command("bash", "-c", "mkdir -p "+*destination+"/"+imageName+".imageset").CombinedOutput()
		if err != nil {
			log.Fatal(err, string(mkdirOut))
		}

		newPath := *destination + "/" + imageName + ".imageset"
		cpOut, err := exec.Command("bash", "-c", "cp "+imagePath+" "+newPath).CombinedOutput()
		if err != nil {
			log.Fatal(err, string(cpOut))
		}
		writeErr := ioutil.WriteFile(newPath+"/Contents.json", []byte(contentsFileTemplate(fileName)), 0644)
		if writeErr != nil {
			log.Fatal(writeErr)
		}

	}
}

func contentsFileTemplate(imageName string) string {
	return `{
		"images" : [
		{
			"idiom" : "universal",
			"scale" : "2x",
			"filename" : "` + imageName + `"
			}
			],
		"info" : {
				"version" : 1,
				"author" : "xcode"
			}
	}`
}
<commit_msg>fix png search<commit_after>package main

import (
	"flag"
	// "fmt"
	"io/ioutil"
	"log"
	"os/exec"
	"strings"
)

var source = flag.String("source", "", "Directory containing image assets")
var destination = flag.String("destination", "", "Destination for image assets")

func main() {
	flag.Parse()
	out, err := exec.Command("bash", "-c", "/usr/bin/find "+*source+" -name \\*.png -print").CombinedOutput()
	if err != nil {
		log.Fatal(err, string(out))
	}
	imagePaths := strings.Split(string(out), "\n")
	for _, imagePath := range imagePaths {
		paths := strings.Split(imagePath, "/")
		fileName := paths[len(paths)-1]
		if len(fileName) < 4 {
			continue
		}
		imageName := fileName[0 : len(fileName)-4]
		mkdirOut, err := exec.Command("bash", "-c", "mkdir -p "+*destination+"/"+imageName+".imageset").CombinedOutput()
		if err != nil {
			log.Fatal(err, string(mkdirOut))
		}

		newPath := *destination + "/" + imageName + ".imageset"
		cpOut, err := exec.Command("bash", "-c", "cp "+imagePath+" "+newPath).CombinedOutput()
		if err != nil {
			log.Fatal(err, string(cpOut))
		}
		writeErr := ioutil.WriteFile(newPath+"/Contents.json", []byte(contentsFileTemplate(fileName)), 0644)
		if writeErr != nil {
			log.Fatal(writeErr)
		}

	}
}

func contentsFileTemplate(imageName string) string {
	return `{
		"images" : [
		{
			"idiom" : "universal",
			"scale" : "2x",
			"filename" : "` + imageName + `"
			}
			],
		"info" : {
				"version" : 1,
				"author" : "xcode"
			}
	}`
}
<|endoftext|>


<commit_before><commit_msg>change<commit_after><|endoftext|>


<commit_before>package common

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go/aws"

	"encoding/json"

	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/hashicorp/packer/common/uuid"
	"github.com/hashicorp/packer/helper/multistep"
	"github.com/hashicorp/packer/packer"
)

type StepIamInstanceProfile struct {
	IamInstanceProfile                        string
	TemporaryIamInstanceProfilePolicyDocument *PolicyDocument
	createdInstanceProfileName                string
	createdRoleName                           string
	createdPolicyName                         string
	roleIsAttached                            bool
}

func (s *StepIamInstanceProfile) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	iamsvc := state.Get("iam").(*iam.IAM)
	ui := state.Get("ui").(packer.Ui)

	state.Put("iamInstanceProfile", "")

	if len(s.IamInstanceProfile) > 0 {
		_, err := iamsvc.GetInstanceProfile(
			&iam.GetInstanceProfileInput{
				InstanceProfileName: aws.String(s.IamInstanceProfile),
			},
		)
		if err != nil {
			err := fmt.Errorf("Couldn't find specified instance profile: %s", err)
			log.Printf("[DEBUG] %s", err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}
		log.Printf("Using specified instance profile: %v", s.IamInstanceProfile)
		state.Put("iamInstanceProfile", s.IamInstanceProfile)
		return multistep.ActionContinue
	}

	if s.TemporaryIamInstanceProfilePolicyDocument != nil {
		// Create the profile
		profileName := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())

		policy, err := json.Marshal(s.TemporaryIamInstanceProfilePolicyDocument)
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		ui.Say(fmt.Sprintf("Creating temporary instance profile for this instance: %s", profileName))

		profileResp, err := iamsvc.CreateInstanceProfile(&iam.CreateInstanceProfileInput{
			InstanceProfileName: aws.String(profileName),
		})
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}
		s.createdInstanceProfileName = aws.StringValue(profileResp.InstanceProfile.InstanceProfileName)

		log.Printf("[DEBUG] Waiting for temporary instance profile: %s", s.createdInstanceProfileName)
		err = iamsvc.WaitUntilInstanceProfileExists(&iam.GetInstanceProfileInput{
			InstanceProfileName: aws.String(s.createdInstanceProfileName),
		})

		if err == nil {
			log.Printf("[DEBUG] Found instance profile %s", s.createdInstanceProfileName)
		} else {
			err := fmt.Errorf("Timed out waiting for instance profile %s: %s", s.createdInstanceProfileName, err)
			log.Printf("[DEBUG] %s", err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		ui.Say(fmt.Sprintf("Creating temporary role for this instance: %s", profileName))

		roleResp, err := iamsvc.CreateRole(&iam.CreateRoleInput{
			RoleName:                 aws.String(profileName),
			Description:              aws.String("Temporary role for Packer"),
			AssumeRolePolicyDocument: aws.String("{\"Version\": \"2012-10-17\",\"Statement\": [{\"Effect\": \"Allow\",\"Principal\": {\"Service\": \"ec2.amazonaws.com\"},\"Action\": \"sts:AssumeRole\"}]}"),
		})
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		s.createdRoleName = aws.StringValue(roleResp.Role.RoleName)

		log.Printf("[DEBUG] Waiting for temporary role: %s", s.createdInstanceProfileName)
		err = iamsvc.WaitUntilRoleExists(&iam.GetRoleInput{
			RoleName: aws.String(s.createdRoleName),
		})
		if err == nil {
			log.Printf("[DEBUG] Found temporary role %s", s.createdRoleName)
		} else {
			err := fmt.Errorf("Timed out waiting for temporary role %s: %s", s.createdRoleName, err)
			log.Printf("[DEBUG] %s", err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		ui.Say(fmt.Sprintf("Attaching policy to the temporary role: %s", profileName))

		_, err = iamsvc.PutRolePolicy(&iam.PutRolePolicyInput{
			RoleName:       roleResp.Role.RoleName,
			PolicyName:     aws.String(profileName),
			PolicyDocument: aws.String(string(policy)),
		})
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		s.createdPolicyName = aws.StringValue(roleResp.Role.RoleName)

		_, err = iamsvc.AddRoleToInstanceProfile(&iam.AddRoleToInstanceProfileInput{
			RoleName:            roleResp.Role.RoleName,
			InstanceProfileName: profileResp.InstanceProfile.InstanceProfileName,
		})
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		s.roleIsAttached = true
		state.Put("iamInstanceProfile", aws.StringValue(profileResp.InstanceProfile.InstanceProfileName))
	}

	return multistep.ActionContinue
}

func (s *StepIamInstanceProfile) Cleanup(state multistep.StateBag) {
	iamsvc := state.Get("iam").(*iam.IAM)
	ui := state.Get("ui").(packer.Ui)
	var err error

	if s.roleIsAttached == true {
		ui.Say("Detaching temporary role from instance profile...")

		_, err := iamsvc.RemoveRoleFromInstanceProfile(&iam.RemoveRoleFromInstanceProfileInput{
			InstanceProfileName: aws.String(s.createdInstanceProfileName),
			RoleName:            aws.String(s.createdRoleName),
		})
		if err != nil {
			ui.Error(fmt.Sprintf(
				"Error %s. Please delete the role manually: %s", err.Error(), s.createdRoleName))
		}
	}

	if s.createdPolicyName != "" {
		ui.Say("Removing policy from temporary role...")
		iamsvc.DeleteRolePolicy(&iam.DeleteRolePolicyInput{
			PolicyName: aws.String(s.createdPolicyName),
			RoleName:   aws.String(s.createdRoleName),
		})
	}
	if s.createdRoleName != "" {
		ui.Say("Deleting temporary role...")

		_, err = iamsvc.DeleteRole(&iam.DeleteRoleInput{RoleName: &s.createdRoleName})
		if err != nil {
			ui.Error(fmt.Sprintf(
				"Error %s. Please delete the role manually: %s", err.Error(), s.createdRoleName))
		}
	}

	if s.createdInstanceProfileName != "" {
		ui.Say("Deleting temporary instance profile...")

		_, err = iamsvc.DeleteInstanceProfile(&iam.DeleteInstanceProfileInput{
			InstanceProfileName: &s.createdInstanceProfileName})

		if err != nil {
			ui.Error(fmt.Sprintf(
				"Error %s. Please delete the instance profile manually: %s", err.Error(), s.createdInstanceProfileName))
		}
	}
}
<commit_msg>Organize imports<commit_after>package common

import (
	"context"
	"fmt"
	"log"

	"encoding/json"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/hashicorp/packer/common/uuid"
	"github.com/hashicorp/packer/helper/multistep"
	"github.com/hashicorp/packer/packer"
)

type StepIamInstanceProfile struct {
	IamInstanceProfile                        string
	TemporaryIamInstanceProfilePolicyDocument *PolicyDocument
	createdInstanceProfileName                string
	createdRoleName                           string
	createdPolicyName                         string
	roleIsAttached                            bool
}

func (s *StepIamInstanceProfile) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	iamsvc := state.Get("iam").(*iam.IAM)
	ui := state.Get("ui").(packer.Ui)

	state.Put("iamInstanceProfile", "")

	if len(s.IamInstanceProfile) > 0 {
		_, err := iamsvc.GetInstanceProfile(
			&iam.GetInstanceProfileInput{
				InstanceProfileName: aws.String(s.IamInstanceProfile),
			},
		)
		if err != nil {
			err := fmt.Errorf("Couldn't find specified instance profile: %s", err)
			log.Printf("[DEBUG] %s", err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}
		log.Printf("Using specified instance profile: %v", s.IamInstanceProfile)
		state.Put("iamInstanceProfile", s.IamInstanceProfile)
		return multistep.ActionContinue
	}

	if s.TemporaryIamInstanceProfilePolicyDocument != nil {
		// Create the profile
		profileName := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())

		policy, err := json.Marshal(s.TemporaryIamInstanceProfilePolicyDocument)
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		ui.Say(fmt.Sprintf("Creating temporary instance profile for this instance: %s", profileName))

		profileResp, err := iamsvc.CreateInstanceProfile(&iam.CreateInstanceProfileInput{
			InstanceProfileName: aws.String(profileName),
		})
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}
		s.createdInstanceProfileName = aws.StringValue(profileResp.InstanceProfile.InstanceProfileName)

		log.Printf("[DEBUG] Waiting for temporary instance profile: %s", s.createdInstanceProfileName)
		err = iamsvc.WaitUntilInstanceProfileExists(&iam.GetInstanceProfileInput{
			InstanceProfileName: aws.String(s.createdInstanceProfileName),
		})

		if err == nil {
			log.Printf("[DEBUG] Found instance profile %s", s.createdInstanceProfileName)
		} else {
			err := fmt.Errorf("Timed out waiting for instance profile %s: %s", s.createdInstanceProfileName, err)
			log.Printf("[DEBUG] %s", err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		ui.Say(fmt.Sprintf("Creating temporary role for this instance: %s", profileName))

		roleResp, err := iamsvc.CreateRole(&iam.CreateRoleInput{
			RoleName:                 aws.String(profileName),
			Description:              aws.String("Temporary role for Packer"),
			AssumeRolePolicyDocument: aws.String("{\"Version\": \"2012-10-17\",\"Statement\": [{\"Effect\": \"Allow\",\"Principal\": {\"Service\": \"ec2.amazonaws.com\"},\"Action\": \"sts:AssumeRole\"}]}"),
		})
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		s.createdRoleName = aws.StringValue(roleResp.Role.RoleName)

		log.Printf("[DEBUG] Waiting for temporary role: %s", s.createdInstanceProfileName)
		err = iamsvc.WaitUntilRoleExists(&iam.GetRoleInput{
			RoleName: aws.String(s.createdRoleName),
		})
		if err == nil {
			log.Printf("[DEBUG] Found temporary role %s", s.createdRoleName)
		} else {
			err := fmt.Errorf("Timed out waiting for temporary role %s: %s", s.createdRoleName, err)
			log.Printf("[DEBUG] %s", err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		ui.Say(fmt.Sprintf("Attaching policy to the temporary role: %s", profileName))

		_, err = iamsvc.PutRolePolicy(&iam.PutRolePolicyInput{
			RoleName:       roleResp.Role.RoleName,
			PolicyName:     aws.String(profileName),
			PolicyDocument: aws.String(string(policy)),
		})
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		s.createdPolicyName = aws.StringValue(roleResp.Role.RoleName)

		_, err = iamsvc.AddRoleToInstanceProfile(&iam.AddRoleToInstanceProfileInput{
			RoleName:            roleResp.Role.RoleName,
			InstanceProfileName: profileResp.InstanceProfile.InstanceProfileName,
		})
		if err != nil {
			ui.Error(err.Error())
			state.Put("error", err)
			return multistep.ActionHalt
		}

		s.roleIsAttached = true
		state.Put("iamInstanceProfile", aws.StringValue(profileResp.InstanceProfile.InstanceProfileName))
	}

	return multistep.ActionContinue
}

func (s *StepIamInstanceProfile) Cleanup(state multistep.StateBag) {
	iamsvc := state.Get("iam").(*iam.IAM)
	ui := state.Get("ui").(packer.Ui)
	var err error

	if s.roleIsAttached == true {
		ui.Say("Detaching temporary role from instance profile...")

		_, err := iamsvc.RemoveRoleFromInstanceProfile(&iam.RemoveRoleFromInstanceProfileInput{
			InstanceProfileName: aws.String(s.createdInstanceProfileName),
			RoleName:            aws.String(s.createdRoleName),
		})
		if err != nil {
			ui.Error(fmt.Sprintf(
				"Error %s. Please delete the role manually: %s", err.Error(), s.createdRoleName))
		}
	}

	if s.createdPolicyName != "" {
		ui.Say("Removing policy from temporary role...")
		iamsvc.DeleteRolePolicy(&iam.DeleteRolePolicyInput{
			PolicyName: aws.String(s.createdPolicyName),
			RoleName:   aws.String(s.createdRoleName),
		})
	}
	if s.createdRoleName != "" {
		ui.Say("Deleting temporary role...")

		_, err = iamsvc.DeleteRole(&iam.DeleteRoleInput{RoleName: &s.createdRoleName})
		if err != nil {
			ui.Error(fmt.Sprintf(
				"Error %s. Please delete the role manually: %s", err.Error(), s.createdRoleName))
		}
	}

	if s.createdInstanceProfileName != "" {
		ui.Say("Deleting temporary instance profile...")

		_, err = iamsvc.DeleteInstanceProfile(&iam.DeleteInstanceProfileInput{
			InstanceProfileName: &s.createdInstanceProfileName})

		if err != nil {
			ui.Error(fmt.Sprintf(
				"Error %s. Please delete the instance profile manually: %s", err.Error(), s.createdInstanceProfileName))
		}
	}
}
<|endoftext|>


<commit_before>package xcontext

import (
	"context"
	"time"
)

type ctxKey int

const timeKkey ctxKey = iota

// WithTime stores a mock time in a context for testing timeouts and other operations.
func WithTime(ctx context.Context, t time.Time) context.Context {
	return context.WithValue(ctx, timeKey, t)
}

func TimeFuncFrom(ctx context.Context) func() time.Time {
	t, ok := ctx.Value(timeKey).(time.Time)

	if !ok {
		return time.Now
	}

	return func() time.Time { return t }
}
<commit_msg>xcontext: back out<commit_after><|endoftext|>


<commit_before>// Copyright 2020 The etcd Authors
//
// 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 clientv3

import (
	"context"

	"go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
	"go.etcd.io/etcd/version"
	"google.golang.org/grpc/metadata"
)

// WithRequireLeader requires client requests to only succeed
// when the cluster has a leader.
func WithRequireLeader(ctx context.Context) context.Context {
	md, ok := metadata.FromOutgoingContext(ctx)
	if !ok { // no outgoing metadata ctx key, create one
		md = metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
		return metadata.NewOutgoingContext(ctx, md)
	}
	// overwrite/add 'hasleader' key/value
	md.Set(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
	return metadata.NewOutgoingContext(ctx, md)
}

// embeds client version
func withVersion(ctx context.Context) context.Context {
	md, ok := metadata.FromOutgoingContext(ctx)
	if !ok { // no outgoing metadata ctx key, create one
		md = metadata.Pairs(rpctypes.MetadataClientAPIVersionKey, version.APIVersion)
		return metadata.NewOutgoingContext(ctx, md)
	}
	// overwrite/add version key/value
	md.Set(rpctypes.MetadataClientAPIVersionKey, version.APIVersion)
	return metadata.NewOutgoingContext(ctx, md)
}
<commit_msg>clientv3: fix racy writes to context key<commit_after>// Copyright 2020 The etcd Authors
//
// 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 clientv3

import (
	"context"

	"go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
	"go.etcd.io/etcd/version"
	"google.golang.org/grpc/metadata"
)

// WithRequireLeader requires client requests to only succeed
// when the cluster has a leader.
func WithRequireLeader(ctx context.Context) context.Context {
	md, ok := metadata.FromOutgoingContext(ctx)
	if !ok { // no outgoing metadata ctx key, create one
		md = metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
		return metadata.NewOutgoingContext(ctx, md)
	}
	copied := md.Copy() // avoid racey updates
	// overwrite/add 'hasleader' key/value
	copied.Set(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
	return metadata.NewOutgoingContext(ctx, copied)
}

// embeds client version
func withVersion(ctx context.Context) context.Context {
	md, ok := metadata.FromOutgoingContext(ctx)
	if !ok { // no outgoing metadata ctx key, create one
		md = metadata.Pairs(rpctypes.MetadataClientAPIVersionKey, version.APIVersion)
		return metadata.NewOutgoingContext(ctx, md)
	}
	copied := md.Copy() // avoid racey updates
	// overwrite/add version key/value
	copied.Set(rpctypes.MetadataClientAPIVersionKey, version.APIVersion)
	return metadata.NewOutgoingContext(ctx, copied)
}
<|endoftext|>


<commit_before>/*
Copyright 2015 Oscar Ruckdeschel, Janik Schmidt, Jonathan Kuhse.

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 bestmatches

import (
	"github.com/ibiBgOR/GoTrimapNews/data"
	"github.com/ibiBgOR/GoTrimapNews/ngram"
	"sort"
)

// returns n=count titles matching to the title
func GetBestMatches(title string, count int) []string {
	var trigram_matches []int

	// first calculate ngrams of the search string
	for _, trigram := range ngram.BuildNGram(title, 3) {
		for _, match := range data.GetIdsOfTrigram(trigram) {
			trigram_matches = append(trigram_matches, match)
		}
	}

	// now get the *count* most frequent news ids
	// TODO: sort by occurence and remove duplicates
	sort.Ints(trigram_matches)
	var bestMatches []int
	for i := 0; i < count; i += 1 {
		bestMatches = append(bestMatches, trigram_matches[i])
	}

	// get the according titles
	var titles []string
	for id := range bestMatches {
		titles = append(titles, data.GetNewsTitle(id))
	}

	return titles
}
<commit_msg>first approach<commit_after>/*
Copyright 2015 Oscar Ruckdeschel, Janik Schmidt, Jonathan Kuhse.

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 bestmatches

import (
	"github.com/ibiBgOR/GoTrimapNews/data"
	"github.com/ibiBgOR/GoTrimapNews/ngram"
	"sort"
)

// returns n=count titles matching to the title
func GetBestMatches(title string, count int) []string {
	var trigram_matches []int

	// first calculate ngrams of the search string
	for _, trigram := range ngram.BuildNGram(title, 3) {
		for _, match := range data.GetIdsOfTrigram(trigram) {
			trigram_matches = append(trigram_matches, match)
		}
	}

	// now get the *count* most frequent news ids
	var frequencies map[int]int
	bestMatches := (SortByFrequency(trigram_matches, frequencies))
	for i := 0; i < count; i += 1 {
		bestMatches = append(bestMatches, trigram_matches[i])
	}

	// get the according titles
	var titles []string
	for id := range bestMatches {
		titles = append(titles, data.GetNewsTitle(id))
	}

	return titles
}

type IdFrequency struct {
	Id        int
	Frequency int
}

type ByFrequency []IdFrequency

func (nf ByFrequency) Len() int      { return len(nf) }
func (nf ByFrequency) Swap(i, j int) { nf[i], nf[j] = nf[j], nf[i] }
func (nf ByFrequency) Less(i, j int) bool {
	less := nf[i].Frequency > nf[j].Frequency
	if nf[i].Frequency == nf[j].Frequency {
		less = nf[i].Id < nf[j].Id
	}
	return less
}

func SortByFrequency(ids []int, frequencies map[int]int) []int {
	nf := make(ByFrequency, len(ids))
	for i, id := range ids {
		nf[i] = IdFrequency{id, frequencies[id]}
	}
	sort.Sort(ByFrequency(nf))
	sortedIds := make([]int, len(ids))
	for i, nf := range nf {
		sortedIds[i] = nf.Id
	}
	return sortedIds
}

func RemoveDuplicates(xs *[]int) {
	found := make(map[int]bool)
	j := 0
	for i, x := range *xs {
		if !found[x] {
			found[x] = true
			(*xs)[j] = (*xs)[i]
			j++
		}
	}
	*xs = (*xs)[:j]
}
<|endoftext|>


<commit_before>// +build ignore

/*
Copyright 2013 Brandon Philips

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.
*/

// This program builds a project and is a copy of third_party.go. See
// github.com/philips/third_party.go
//
// $ go run third_party.go
//
// See the README file for more details.
package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
)

const (
	DefaultThirdParty = "third_party"
)

// thirdPartyDir creates a string path to the third_party directory based on
// the current working directory.
func thirdPartyDir() string {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}
	return path.Join(root, DefaultThirdParty)
}

func srcDir() string {
	return path.Join(thirdPartyDir(), "src")
}

// binDir creates a string path to the GOBIN directory based on the current
// working directory.
func binDir() string {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}
	return path.Join(root, "bin")
}

// run execs a command like a shell script piping everything to the parent's
// stderr/stdout and uses the given environment.
func run(name string, arg ...string) *os.ProcessState {
	cmd := exec.Command(name, arg...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	err = cmd.Start()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)
	cmd.Wait()

	return cmd.ProcessState
}

// setupProject does the initial setup of the third_party src directory
// including setting up the symlink to the cwd from the src directory.
func setupProject(pkg string) {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}

	src := path.Join(thirdPartyDir(), "src", pkg)
	srcdir := path.Dir(src)

	os.MkdirAll(srcdir, 0755)

	rel, err := filepath.Rel(srcdir, root)
	if err != nil {
		log.Fatalf("creating relative third party path: %v", err)
	}

	err = os.Symlink(rel, src)
	if err != nil && os.IsExist(err) == false {
		log.Fatalf("creating project third party symlink: %v", err)
	}
}

func getVc(root string) versionControl {
	for _, v := range []string{".git", ".hg"} {
		r := path.Join(root, v)
		info, err := os.Stat(r)

		if err != nil || !info.IsDir() {
			continue
		}

		base := path.Base(r)
		switch base {
		case ".git":
			return vcGit(r)
		case ".hg":
			return vcHg(r)
		}
	}
	return new(vcNoop)
}

type versionControl interface {
	commit() string
	update(string) error
}

//  Performs noops on all VC operations.
type vcNoop struct{}

func (v *vcNoop) commit() string {
	return ""
}

func (v *vcNoop) update(dir string) error {
	return nil
}

type vcHg string

// vcHg.commit returns the current HEAD commit hash for a given hg dir.
func (v vcHg) commit() string {
	out, err := exec.Command("hg",
		"id",
		"-i",
		"-R", string(v),
	).Output()
	if err != nil {
		return ""
	}
	return string(out)
}

// vcHg.update updates the given hg dir to ref.
func (v vcHg) update(ref string) error {
	_, err := exec.Command("hg",
		"update",
		"-r", ref,
		"-R", string(v),
		"--cwd", path.Dir(string(v)),
	).Output()
	if err != nil {
		return err
	}
	return nil
}

type vcGit string

// vcGit.commit returns the current HEAD commit hash for a given git dir.
func (v vcGit) commit() string {
	out, err := exec.Command(
		"git",
		"--git-dir="+string(v),
		"rev-parse",
		"HEAD",
	).Output()
	if err != nil {
		return ""
	}
	return string(out)
}

// vcHg.udpate updates the given git dir to ref.
func (v vcGit) update(ref string) error {
	_, err := exec.Command("git",
		"--work-tree="+path.Dir(string(v)),
		"--git-dir="+string(v),
		"reset", "--hard", ref,
	).Output()
	if err != nil {
		return err
	}
	return nil
}

// commit grabs the commit id from hg or git as a string.
func commit(dir string) string {
	return getVc(dir).commit()
}

// removeVcs removes a .git or .hg directory from the given root if it exists.
func removeVcs(root string) (bool, string) {
	for _, v := range []string{".git", ".hg"} {
		r := path.Join(root, v)
		info, err := os.Stat(r)

		if err != nil {
			continue
		}

		// We didn't find it, next!
		if info.IsDir() == false {
			continue
		}

		// We found it, grab the commit and remove the directory
		c := commit(root)
		err = os.RemoveAll(r)
		if err != nil {
			log.Fatalf("removeVcs: %v", err)
		}
		return true, c
	}

	return false, ""
}

// bump takes care of grabbing a package, getting the package git hash and
// removing all of the version control stuff.
func bump(pkg, version string) {
	tpd := thirdPartyDir()

	temp, err := ioutil.TempDir(tpd, "bump")
	if err != nil {
		log.Fatalf("bump: %v", err)
	}
	defer os.RemoveAll(temp)

	os.Setenv("GOPATH", temp)
	run("go", "get", "-u", "-d", pkg)

	for {
		root := path.Join(temp, "src", pkg) // the temp installation root
		home := path.Join(tpd, "src", pkg)  // where the package will end up

		if version != "" {
			err := getVc(root).update(version)
			if err != nil {
				log.Fatalf("bump: %v", err)
			}
		}

		ok, c := removeVcs(root)
		if ok {
			// Create the path leading up to the package
			err := os.MkdirAll(path.Dir(home), 0755)
			if err != nil {
				log.Fatalf("bump: %v", err)
			}

			// Remove anything that might have been there
			err = os.RemoveAll(home)
			if err != nil {
				log.Fatalf("bump: %v", err)
			}

			// Finally move the package
			err = os.Rename(root, home)
			if err != nil {
				log.Fatalf("bump: %v", err)
			}

			fmt.Printf("%s %s\n", pkg, strings.TrimSpace(c))
			break
		}

		// Pop off and try to find this directory!
		pkg = path.Dir(pkg)
		if pkg == "." {
			return
		}
	}
}

// validPkg uses go list to decide if the given path is a valid go package.
// This is used by the bumpAll walk to bump all of the existing packages.
func validPkg(pkg string) bool {
	env := append(os.Environ())
	cmd := exec.Command("go", "list", pkg)
	cmd.Env = env

	out, err := cmd.Output()
	if err != nil {
		return false
	}

	if pkg == strings.TrimSpace(string(out)) {
		return true
	}

	return false
}

// bumpWalk walks the third_party directory and bumps all of the packages that it finds.
func bumpWalk(path string, info os.FileInfo, err error) error {
	if err != nil {
		return nil
	}

	// go packages are always directories
	if info.IsDir() == false {
		return nil
	}

	parts := strings.Split(path, srcDir()+"/")
	if len(parts) == 1 {
		return nil
	}

	pkg := parts[1]

	if validPkg(pkg) == false {
		return nil
	}

	bump(pkg, "")

	return nil
}

func bumpAll() {
	err := filepath.Walk(srcDir(), bumpWalk)
	if err != nil {
		log.Fatalf(err.Error())
	}
}

func main() {
	log.SetFlags(0)

	// third_party manages GOPATH, no one else
	os.Setenv("GOPATH", thirdPartyDir())
	os.Setenv("GOBIN", binDir())

	if len(os.Args) <= 1 {
		log.Fatalf("No command")
	}

	cmd := os.Args[1]

	if cmd == "setup" && len(os.Args) > 2 {
		setupProject(os.Args[2])
		return
	}

	if cmd == "bump" && len(os.Args) > 2 {
		ref := ""
		if len(os.Args) > 3 {
			ref = os.Args[3]
		}

		bump(os.Args[2], ref)
		return
	}

	if cmd == "bump-all" && len(os.Args) > 1 {
		bumpAll()
		return
	}

	ps := run("go", os.Args[1:]...)

	if ps.Success() == false {
		os.Exit(1)
	}
}
<commit_msg>use srcDir function and rename variables slightly more logically<commit_after>// +build ignore

/*
Copyright 2013 Brandon Philips

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.
*/

// This program builds a project and is a copy of third_party.go. See
// github.com/philips/third_party.go
//
// $ go run third_party.go
//
// See the README file for more details.
package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
)

const (
	DefaultThirdParty = "third_party"
)

// thirdPartyDir creates a string path to the third_party directory based on
// the current working directory.
func thirdPartyDir() string {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}
	return path.Join(root, DefaultThirdParty)
}

func srcDir() string {
	return path.Join(thirdPartyDir(), "src")
}

// binDir creates a string path to the GOBIN directory based on the current
// working directory.
func binDir() string {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}
	return path.Join(root, "bin")
}

// run execs a command like a shell script piping everything to the parent's
// stderr/stdout and uses the given environment.
func run(name string, arg ...string) *os.ProcessState {
	cmd := exec.Command(name, arg...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	err = cmd.Start()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)
	cmd.Wait()

	return cmd.ProcessState
}

// setupProject does the initial setup of the third_party src directory
// including setting up the symlink to the cwd from the src directory.
func setupProject(pkg string) {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}

	pkgsrc := path.Join(srcDir(), pkg)
	pkgsrcdir := path.Dir(pkgsrc)

	os.MkdirAll(pkgsrcdir, 0755)

	rel, err := filepath.Rel(pkgsrcdir, root)
	if err != nil {
		log.Fatalf("creating relative third party path: %v", err)
	}

	err = os.Symlink(rel, pkgsrc)
	if err != nil && os.IsExist(err) == false {
		log.Fatalf("creating project third party symlink: %v", err)
	}
}

func getVc(root string) versionControl {
	for _, v := range []string{".git", ".hg"} {
		r := path.Join(root, v)
		info, err := os.Stat(r)

		if err != nil || !info.IsDir() {
			continue
		}

		base := path.Base(r)
		switch base {
		case ".git":
			return vcGit(r)
		case ".hg":
			return vcHg(r)
		}
	}
	return new(vcNoop)
}

type versionControl interface {
	commit() string
	update(string) error
}

//  Performs noops on all VC operations.
type vcNoop struct{}

func (v *vcNoop) commit() string {
	return ""
}

func (v *vcNoop) update(dir string) error {
	return nil
}

type vcHg string

// vcHg.commit returns the current HEAD commit hash for a given hg dir.
func (v vcHg) commit() string {
	out, err := exec.Command("hg",
		"id",
		"-i",
		"-R", string(v),
	).Output()
	if err != nil {
		return ""
	}
	return string(out)
}

// vcHg.update updates the given hg dir to ref.
func (v vcHg) update(ref string) error {
	_, err := exec.Command("hg",
		"update",
		"-r", ref,
		"-R", string(v),
		"--cwd", path.Dir(string(v)),
	).Output()
	if err != nil {
		return err
	}
	return nil
}

type vcGit string

// vcGit.commit returns the current HEAD commit hash for a given git dir.
func (v vcGit) commit() string {
	out, err := exec.Command(
		"git",
		"--git-dir="+string(v),
		"rev-parse",
		"HEAD",
	).Output()
	if err != nil {
		return ""
	}
	return string(out)
}

// vcHg.update updates the given git dir to ref.
func (v vcGit) update(ref string) error {
	_, err := exec.Command("git",
		"--work-tree="+path.Dir(string(v)),
		"--git-dir="+string(v),
		"reset", "--hard", ref,
	).Output()
	if err != nil {
		return err
	}
	return nil
}

// commit grabs the commit id from hg or git as a string.
func commit(dir string) string {
	return getVc(dir).commit()
}

// removeVcs removes a .git or .hg directory from the given root if it exists.
func removeVcs(root string) (bool, string) {
	for _, v := range []string{".git", ".hg"} {
		r := path.Join(root, v)
		info, err := os.Stat(r)

		if err != nil {
			continue
		}

		// We didn't find it, next!
		if info.IsDir() == false {
			continue
		}

		// We found it, grab the commit and remove the directory
		c := commit(root)
		err = os.RemoveAll(r)
		if err != nil {
			log.Fatalf("removeVcs: %v", err)
		}
		return true, c
	}

	return false, ""
}

// bump takes care of grabbing a package, getting the package git hash and
// removing all of the version control stuff.
func bump(pkg, version string) {
	tpd := thirdPartyDir()

	temp, err := ioutil.TempDir(tpd, "bump")
	if err != nil {
		log.Fatalf("bump: %v", err)
	}
	defer os.RemoveAll(temp)

	os.Setenv("GOPATH", temp)
	run("go", "get", "-u", "-d", pkg)

	for {
		root := path.Join(temp, "src", pkg) // the temp installation root
		home := path.Join(tpd, "src", pkg)  // where the package will end up

		if version != "" {
			err := getVc(root).update(version)
			if err != nil {
				log.Fatalf("bump: %v", err)
			}
		}

		ok, c := removeVcs(root)
		if ok {
			// Create the path leading up to the package
			err := os.MkdirAll(path.Dir(home), 0755)
			if err != nil {
				log.Fatalf("bump: %v", err)
			}

			// Remove anything that might have been there
			err = os.RemoveAll(home)
			if err != nil {
				log.Fatalf("bump: %v", err)
			}

			// Finally move the package
			err = os.Rename(root, home)
			if err != nil {
				log.Fatalf("bump: %v", err)
			}

			fmt.Printf("%s %s\n", pkg, strings.TrimSpace(c))
			break
		}

		// Pop off and try to find this directory!
		pkg = path.Dir(pkg)
		if pkg == "." {
			return
		}
	}
}

// validPkg uses go list to decide if the given path is a valid go package.
// This is used by the bumpAll walk to bump all of the existing packages.
func validPkg(pkg string) bool {
	env := append(os.Environ())
	cmd := exec.Command("go", "list", pkg)
	cmd.Env = env

	out, err := cmd.Output()
	if err != nil {
		return false
	}

	if pkg == strings.TrimSpace(string(out)) {
		return true
	}

	return false
}

// bumpWalk walks the third_party directory and bumps all of the packages that it finds.
func bumpWalk(path string, info os.FileInfo, err error) error {
	if err != nil {
		return nil
	}

	// go packages are always directories
	if info.IsDir() == false {
		return nil
	}

	parts := strings.Split(path, srcDir()+"/")
	if len(parts) == 1 {
		return nil
	}

	pkg := parts[1]

	if validPkg(pkg) == false {
		return nil
	}

	bump(pkg, "")

	return nil
}

func bumpAll() {
	err := filepath.Walk(srcDir(), bumpWalk)
	if err != nil {
		log.Fatalf(err.Error())
	}
}

func main() {
	log.SetFlags(0)

	// third_party manages GOPATH, no one else
	os.Setenv("GOPATH", thirdPartyDir())
	os.Setenv("GOBIN", binDir())

	if len(os.Args) <= 1 {
		log.Fatalf("No command")
	}

	cmd := os.Args[1]

	if cmd == "setup" && len(os.Args) > 2 {
		setupProject(os.Args[2])
		return
	}

	if cmd == "bump" && len(os.Args) > 2 {
		ref := ""
		if len(os.Args) > 3 {
			ref = os.Args[3]
		}

		bump(os.Args[2], ref)
		return
	}

	if cmd == "bump-all" && len(os.Args) > 1 {
		bumpAll()
		return
	}

	ps := run("go", os.Args[1:]...)

	if ps.Success() == false {
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package tftest

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
)

const subprocessCurrentSigil = "4acd63807899403ca4859f5bb948d2c6"
const subprocessPreviousSigil = "2279afb8cf71423996be1fd65d32f13b"

// AutoInitProviderHelper is the main entrypoint for testing provider plugins
// using this package. It is intended to be called during TestMain to prepare
// for provider testing.
//
// AutoInitProviderHelper will discover the location of a current Terraform CLI
// executable to test against, detect whether a prior version of the plugin is
// available for upgrade tests, and then will return an object containing the
// results of that initialization which can then be stored in a global variable
// for use in other tests.
func AutoInitProviderHelper(name string, sourceDir string) *Helper {
	helper, err := AutoInitHelper("terraform-provider-"+name, sourceDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "cannot run Terraform provider tests: %s\n", err)
		os.Exit(1)
	}
	return helper
}

// Helper is intended as a per-package singleton created in TestMain which
// other tests in a package can use to create Terraform execution contexts
type Helper struct {
	baseDir string

	// sourceDir is the dir containing the provider source code, needed
	// for tests that use fixture files.
	sourceDir                    string
	pluginName                   string
	terraformExec                string
	thisPluginDir, prevPluginDir string
}

// AutoInitHelper uses the auto-discovery behavior of DiscoverConfig to prepare
// a configuration and then calls InitHelper with it. This is a convenient
// way to get the standard init behavior based on environment variables, and
// callers should use this unless they have an unusual requirement that calls
// for constructing a config in a different way.
func AutoInitHelper(pluginName string, sourceDir string) (*Helper, error) {
	config, err := DiscoverConfig(pluginName, sourceDir)
	if err != nil {
		return nil, err
	}

	return InitHelper(config)
}

// InitHelper prepares a testing helper with the given configuration.
//
// For most callers it is sufficient to call AutoInitHelper instead, which
// will construct a configuration automatically based on certain environment
// variables.
//
// If this function returns an error then it may have left some temporary files
// behind in the system's temporary directory. There is currently no way to
// automatically clean those up.
func InitHelper(config *Config) (*Helper, error) {
	tempDir := os.Getenv("TF_ACC_TEMP_DIR")
	baseDir, err := ioutil.TempDir(tempDir, "tftest-"+config.PluginName)
	if err != nil {
		return nil, fmt.Errorf("failed to create temporary directory for test helper: %s", err)
	}

	var thisPluginDir, prevPluginDir string
	if config.CurrentPluginExec != "" {
		thisPluginDir, err = ioutil.TempDir(baseDir, "plugins-current")
		if err != nil {
			return nil, fmt.Errorf("failed to create temporary directory for -plugin-dir: %s", err)
		}
		currentExecPath := filepath.Join(thisPluginDir, config.PluginName)
		err = symlinkFile(config.CurrentPluginExec, currentExecPath)
		if err != nil {
			return nil, fmt.Errorf("failed to create symlink at %s to %s: %s", currentExecPath, config.CurrentPluginExec, err)
		}

		err = symlinkAuxiliaryProviders(thisPluginDir)
		if err != nil {
			return nil, fmt.Errorf("failed to symlink auxiliary providers: %s", err)
		}
	} else {
		return nil, fmt.Errorf("CurrentPluginExec is not set")
	}
	if config.PreviousPluginExec != "" {
		prevPluginDir, err = ioutil.TempDir(baseDir, "plugins-previous")
		if err != nil {
			return nil, fmt.Errorf("failed to create temporary directory for previous -plugin-dir: %s", err)
		}
		prevExecPath := filepath.Join(prevPluginDir, config.PluginName)
		err = symlinkFile(config.PreviousPluginExec, prevExecPath)
		if err != nil {
			return nil, fmt.Errorf("failed to create symlink at %s to %s: %s", prevExecPath, config.PreviousPluginExec, err)
		}

		err = symlinkAuxiliaryProviders(prevPluginDir)
		if err != nil {
			return nil, fmt.Errorf("failed to symlink auxiliary providers: %s", err)
		}
	}

	return &Helper{
		baseDir:       baseDir,
		sourceDir:     config.SourceDir,
		pluginName:    config.PluginName,
		terraformExec: config.TerraformExec,
		thisPluginDir: thisPluginDir,
		prevPluginDir: prevPluginDir,
	}, nil
}

// symlinkAuxiliaryProviders discovers auxiliary provider binaries, used in
// multi-provider tests, and symlinks them to the plugin directory.
//
// Auxiliary provider binaries should be included in the provider source code
// directory, under the path terraform.d/plugins/$GOOS_$GOARCH/provider-name.
//
// The environment variable TF_ACC_PROVIDER_ROOT_DIR must be set to the path of
// the provider source code directory root in order to use this feature.
func symlinkAuxiliaryProviders(pluginDir string) error {
	providerRootDir := os.Getenv("TF_ACC_PROVIDER_ROOT_DIR")
	if providerRootDir == "" {
		// common case; assume intentional and do not log
		return nil
	}

	_, err := os.Stat(filepath.Join(providerRootDir, "terraform.d", "plugins"))
	if err != nil {
		fmt.Printf("No terraform.d/plugins directory found: continuing. Unset TF_ACC_PROVIDER_ROOT_DIR or supply provider binaries in terraform.d/plugins/$GOOS_$GOARCH to disable this message.")
		return nil
	}

	auxiliaryProviderDir := filepath.Join(providerRootDir, "terraform.d", "plugins", runtime.GOOS+"_"+runtime.GOARCH)

	// If we can't os.Stat() terraform.d/plugins/$GOOS_$GOARCH, however,
	// assume the omission was unintentional, and error.
	_, err = os.Stat(auxiliaryProviderDir)
	if err != nil {
		return fmt.Errorf("error finding auxiliary provider dir %s: %s", auxiliaryProviderDir, err)
	}

	// now find all the providers in that dir and symlink them to the plugin dir
	providers, err := ioutil.ReadDir(auxiliaryProviderDir)
	if err != nil {
		return fmt.Errorf("error reading auxiliary providers: %s", err)
	}

	for _, provider := range providers {
		providerName := provider.Name()
		err := symlinkFile(filepath.Join(auxiliaryProviderDir, providerName), filepath.Join(pluginDir, providerName))
		if err != nil {
			return fmt.Errorf("error symlinking auxiliary provider %s: %s", providerName, err)
		}
	}

	return nil
}

// Close cleans up temporary files and directories created to support this
// helper, returning an error if any of the cleanup fails.
//
// Call this before returning from TestMain to minimize the amount of detritus
// left behind in the filesystem after the tests complete.
func (h *Helper) Close() error {
	return os.RemoveAll(h.baseDir)
}

// NewWorkingDir creates a new working directory for use in the implementation
// of a single test, returning a WorkingDir object representing that directory.
//
// If the working directory object is not itself closed by the time the test
// program exits, the Close method on the helper itself will attempt to
// delete it.
func (h *Helper) NewWorkingDir() (*WorkingDir, error) {
	dir, err := ioutil.TempDir(h.baseDir, "work")
	if err != nil {
		return nil, err
	}

	// copy the provider source files into the base directory
	err = symlinkDir(h.sourceDir, dir)
	if err != nil {
		return nil, err
	}

	return &WorkingDir{
		h:        h,
		baseArgs: []string{"-no-color"},
		baseDir:  dir,
	}, nil
}

// RequireNewWorkingDir is a variant of NewWorkingDir that takes a TestControl
// object and will immediately fail the running test if the creation of the
// working directory fails.
func (h *Helper) RequireNewWorkingDir(t TestControl) *WorkingDir {
	t.Helper()

	wd, err := h.NewWorkingDir()
	if err != nil {
		t := testingT{t}
		t.Fatalf("failed to create new working directory: %s", err)
		return nil
	}
	return wd
}

// HasPreviousVersion returns true if and only if the receiving helper has a
// previous plugin version available for use in tests.
func (h *Helper) HasPreviousVersion() bool {
	return h.prevPluginDir != ""
}

// TerraformExecPath returns the location of the Terraform CLI executable that
// should be used when running tests.
func (h *Helper) TerraformExecPath() string {
	return h.terraformExec
}

// PluginDir returns the directory that should be used as the -plugin-dir when
// running "terraform init" in order to make Terraform detect the current
// version of the plugin.
func (h *Helper) PluginDir() string {
	return h.thisPluginDir
}

// PreviousPluginDir returns the directory that should be used as the -plugin-dir
// when running "terraform init" in order to make Terraform detect the previous
// version of the plugin, if available.
//
// If no previous version is available, this method will panic. Use
// RequirePreviousVersion or HasPreviousVersion to ensure a previous version is
// available before calling this.
func (h *Helper) PreviousPluginDir() string {
	if h.prevPluginDir != "" {
		panic("PreviousPluginDir not available")
	}
	return h.prevPluginDir
}
<commit_msg>Allow auxiliary providers in .zip format<commit_after>package tftest

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"

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

const subprocessCurrentSigil = "4acd63807899403ca4859f5bb948d2c6"
const subprocessPreviousSigil = "2279afb8cf71423996be1fd65d32f13b"

// AutoInitProviderHelper is the main entrypoint for testing provider plugins
// using this package. It is intended to be called during TestMain to prepare
// for provider testing.
//
// AutoInitProviderHelper will discover the location of a current Terraform CLI
// executable to test against, detect whether a prior version of the plugin is
// available for upgrade tests, and then will return an object containing the
// results of that initialization which can then be stored in a global variable
// for use in other tests.
func AutoInitProviderHelper(name string, sourceDir string) *Helper {
	helper, err := AutoInitHelper("terraform-provider-"+name, sourceDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "cannot run Terraform provider tests: %s\n", err)
		os.Exit(1)
	}
	return helper
}

// Helper is intended as a per-package singleton created in TestMain which
// other tests in a package can use to create Terraform execution contexts
type Helper struct {
	baseDir string

	// sourceDir is the dir containing the provider source code, needed
	// for tests that use fixture files.
	sourceDir                    string
	pluginName                   string
	terraformExec                string
	thisPluginDir, prevPluginDir string
}

// AutoInitHelper uses the auto-discovery behavior of DiscoverConfig to prepare
// a configuration and then calls InitHelper with it. This is a convenient
// way to get the standard init behavior based on environment variables, and
// callers should use this unless they have an unusual requirement that calls
// for constructing a config in a different way.
func AutoInitHelper(pluginName string, sourceDir string) (*Helper, error) {
	config, err := DiscoverConfig(pluginName, sourceDir)
	if err != nil {
		return nil, err
	}

	return InitHelper(config)
}

// InitHelper prepares a testing helper with the given configuration.
//
// For most callers it is sufficient to call AutoInitHelper instead, which
// will construct a configuration automatically based on certain environment
// variables.
//
// If this function returns an error then it may have left some temporary files
// behind in the system's temporary directory. There is currently no way to
// automatically clean those up.
func InitHelper(config *Config) (*Helper, error) {
	tempDir := os.Getenv("TF_ACC_TEMP_DIR")
	baseDir, err := ioutil.TempDir(tempDir, "tftest-"+config.PluginName)
	if err != nil {
		return nil, fmt.Errorf("failed to create temporary directory for test helper: %s", err)
	}

	var thisPluginDir, prevPluginDir string
	if config.CurrentPluginExec != "" {
		thisPluginDir, err = ioutil.TempDir(baseDir, "plugins-current")
		if err != nil {
			return nil, fmt.Errorf("failed to create temporary directory for -plugin-dir: %s", err)
		}
		currentExecPath := filepath.Join(thisPluginDir, config.PluginName)
		err = symlinkFile(config.CurrentPluginExec, currentExecPath)
		if err != nil {
			return nil, fmt.Errorf("failed to create symlink at %s to %s: %s", currentExecPath, config.CurrentPluginExec, err)
		}

		err = symlinkAuxiliaryProviders(thisPluginDir)
		if err != nil {
			return nil, fmt.Errorf("failed to symlink auxiliary providers: %s", err)
		}
	} else {
		return nil, fmt.Errorf("CurrentPluginExec is not set")
	}
	if config.PreviousPluginExec != "" {
		prevPluginDir, err = ioutil.TempDir(baseDir, "plugins-previous")
		if err != nil {
			return nil, fmt.Errorf("failed to create temporary directory for previous -plugin-dir: %s", err)
		}
		prevExecPath := filepath.Join(prevPluginDir, config.PluginName)
		err = symlinkFile(config.PreviousPluginExec, prevExecPath)
		if err != nil {
			return nil, fmt.Errorf("failed to create symlink at %s to %s: %s", prevExecPath, config.PreviousPluginExec, err)
		}

		err = symlinkAuxiliaryProviders(prevPluginDir)
		if err != nil {
			return nil, fmt.Errorf("failed to symlink auxiliary providers: %s", err)
		}
	}

	return &Helper{
		baseDir:       baseDir,
		sourceDir:     config.SourceDir,
		pluginName:    config.PluginName,
		terraformExec: config.TerraformExec,
		thisPluginDir: thisPluginDir,
		prevPluginDir: prevPluginDir,
	}, nil
}

// symlinkAuxiliaryProviders discovers auxiliary provider binaries, used in
// multi-provider tests, and symlinks them to the plugin directory.
//
// Auxiliary provider binaries should be included in the provider source code
// directory, under the path terraform.d/plugins/$GOOS_$GOARCH/provider-name.
//
// The environment variable TF_ACC_PROVIDER_ROOT_DIR must be set to the path of
// the provider source code directory root in order to use this feature.
func symlinkAuxiliaryProviders(pluginDir string) error {
	providerRootDir := os.Getenv("TF_ACC_PROVIDER_ROOT_DIR")
	if providerRootDir == "" {
		// common case; assume intentional and do not log
		return nil
	}

	_, err := os.Stat(filepath.Join(providerRootDir, "terraform.d", "plugins"))
	if os.IsNotExist(err) {
		fmt.Printf("No terraform.d/plugins directory found: continuing. Unset TF_ACC_PROVIDER_ROOT_DIR or supply provider binaries in terraform.d/plugins/$GOOS_$GOARCH to disable this message.")
		return nil
	} else if err != nil {
		return fmt.Errorf("Unexpected error: %s", err)
	}

	auxiliaryProviderDir := filepath.Join(providerRootDir, "terraform.d", "plugins", runtime.GOOS+"_"+runtime.GOARCH)

	// If we can't os.Stat() terraform.d/plugins/$GOOS_$GOARCH, however,
	// assume the omission was unintentional, and error.
	_, err = os.Stat(auxiliaryProviderDir)
	if os.IsNotExist(err) {
		return fmt.Errorf("error finding auxiliary provider dir %s: %s", auxiliaryProviderDir, err)
	} else if err != nil {
		return fmt.Errorf("Unexpected error: %s", err)
	}

	// now find all the providers in that dir and symlink them to the plugin dir
	providers, err := ioutil.ReadDir(auxiliaryProviderDir)
	if err != nil {
		return fmt.Errorf("error reading auxiliary providers: %s", err)
	}

	zipDecompressor := new(getter.ZipDecompressor)

	for _, provider := range providers {
		filename := provider.Name()
		filenameExt := filepath.Ext(filename)
		name := strings.TrimSuffix(filename, filenameExt)
		path := filepath.Join(auxiliaryProviderDir, name)
		symlinkPath := filepath.Join(pluginDir, name)

		// exit early if we have already symlinked this provider
		_, err := os.Stat(symlinkPath)
		if err == nil {
			continue
		}

		// if filename ends in .zip, assume it is a zip and extract it
		// otherwise assume it is a provider binary
		if filenameExt == ".zip" {
			_, err = os.Stat(path)
			if os.IsNotExist(err) {
				zipDecompressor.Decompress(path, filepath.Join(auxiliaryProviderDir, filename), false)
			} else if err != nil {
				return fmt.Errorf("Unexpected error: %s", err)
			}
		}

		err = symlinkFile(path, symlinkPath)
		if err != nil {
			return fmt.Errorf("error symlinking auxiliary provider %s: %s", name, err)
		}
	}

	return nil
}

// Close cleans up temporary files and directories created to support this
// helper, returning an error if any of the cleanup fails.
//
// Call this before returning from TestMain to minimize the amount of detritus
// left behind in the filesystem after the tests complete.
func (h *Helper) Close() error {
	return os.RemoveAll(h.baseDir)
}

// NewWorkingDir creates a new working directory for use in the implementation
// of a single test, returning a WorkingDir object representing that directory.
//
// If the working directory object is not itself closed by the time the test
// program exits, the Close method on the helper itself will attempt to
// delete it.
func (h *Helper) NewWorkingDir() (*WorkingDir, error) {
	dir, err := ioutil.TempDir(h.baseDir, "work")
	if err != nil {
		return nil, err
	}

	// copy the provider source files into the base directory
	err = symlinkDir(h.sourceDir, dir)
	if err != nil {
		return nil, err
	}

	return &WorkingDir{
		h:        h,
		baseArgs: []string{"-no-color"},
		baseDir:  dir,
	}, nil
}

// RequireNewWorkingDir is a variant of NewWorkingDir that takes a TestControl
// object and will immediately fail the running test if the creation of the
// working directory fails.
func (h *Helper) RequireNewWorkingDir(t TestControl) *WorkingDir {
	t.Helper()

	wd, err := h.NewWorkingDir()
	if err != nil {
		t := testingT{t}
		t.Fatalf("failed to create new working directory: %s", err)
		return nil
	}
	return wd
}

// HasPreviousVersion returns true if and only if the receiving helper has a
// previous plugin version available for use in tests.
func (h *Helper) HasPreviousVersion() bool {
	return h.prevPluginDir != ""
}

// TerraformExecPath returns the location of the Terraform CLI executable that
// should be used when running tests.
func (h *Helper) TerraformExecPath() string {
	return h.terraformExec
}

// PluginDir returns the directory that should be used as the -plugin-dir when
// running "terraform init" in order to make Terraform detect the current
// version of the plugin.
func (h *Helper) PluginDir() string {
	return h.thisPluginDir
}

// PreviousPluginDir returns the directory that should be used as the -plugin-dir
// when running "terraform init" in order to make Terraform detect the previous
// version of the plugin, if available.
//
// If no previous version is available, this method will panic. Use
// RequirePreviousVersion or HasPreviousVersion to ensure a previous version is
// available before calling this.
func (h *Helper) PreviousPluginDir() string {
	if h.prevPluginDir != "" {
		panic("PreviousPluginDir not available")
	}
	return h.prevPluginDir
}
<|endoftext|>


<commit_before>package response

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"github.com/volatile/core"
	"github.com/volatile/core/httputil"
)

const templatesDir = "templates"

var (
	// ErrNoTemplatesDir is used when a template feature is used without having the templates directory.
	ErrNoTemplatesDir = fmt.Errorf("response: templates can't be used without a %q directory", templatesDir)

	templates     *template.Template
	templatesData map[string]interface{}
)

func init() {
	if _, err := os.Stat(templatesDir); err != nil {
		return
	}

	templates = template.New(templatesDir)

	// Built-in templates funcs
	templates.Funcs(template.FuncMap{
		"html":  templatesFuncHTML,
		"nl2br": templatesFuncNL2BR,
	})

	core.BeforeRun(func() {
		if err := filepath.Walk(templatesDir, templatesWalk); err != nil {
			panic("response: " + err.Error())
		}
	})
}

// walk is the path/filepath.WalkFunc used to walk templatesDir in order to initialize templates.
// It will try to parse all files it encounters and recurse into subdirectories.
func templatesWalk(path string, f os.FileInfo, err error) error {
	if err != nil {
		return err
	}

	if f.IsDir() {
		return nil
	}

	_, err = templates.ParseFiles(path)
	return err
}

// FuncMap is the type of the map defining the mapping from names to functions.
// Each function must have either a single return value, or two return values of which the second has type error.
// In that case, if the second (error) argument evaluates to non-nil during execution, execution terminates and Execute returns that error.
// FuncMap has the same base type as FuncMap in "text/template", copied here so clients need not import "text/template".
type FuncMap map[string]interface{}

// TemplatesFuncs adds functions that will be available to all templates.
func TemplatesFuncs(funcMap FuncMap) {
	if templates == nil {
		panic(ErrNoTemplatesDir)
	}

	templates.Funcs(template.FuncMap(funcMap))
}

// TemplatesData adds data that will be available to all templates.
// It can be called multiple times. Existent keys will be replaced.
func TemplatesData(data map[string]interface{}) {
	if templates == nil {
		panic(ErrNoTemplatesDir)
	}
	if data == nil || len(data) == 0 {
		return
	}

	if templatesData == nil {
		templatesData = make(map[string]interface{})
	}
	for k, v := range data {
		templatesData[k] = v
	}
}

// Status responds with the status code.
func Status(c *core.Context, code int) {
	http.Error(c.ResponseWriter, http.StatusText(code), code)
}

// String responds with the string s.
func String(c *core.Context, s string) {
	StringStatus(c, http.StatusOK, s)
}

// StringStatus responds with the status code and the string s.
func StringStatus(c *core.Context, code int, s string) {
	httputil.SetDetectedContentType(c.ResponseWriter, []byte(s))
	c.ResponseWriter.WriteHeader(code)
	c.ResponseWriter.Write([]byte(s))
}

// Bytes responds with the slice of bytes b.
func Bytes(c *core.Context, b []byte) {
	BytesStatus(c, http.StatusOK, b)
}

// BytesStatus responds with the status code and the slice of bytes b.
func BytesStatus(c *core.Context, code int, b []byte) {
	httputil.SetDetectedContentType(c.ResponseWriter, b)
	c.ResponseWriter.WriteHeader(code)
	c.ResponseWriter.Write(b)
}

// JSON responds with the JSON marshalled v.
func JSON(c *core.Context, v interface{}) {
	JSONStatus(c, http.StatusOK, v)
}

// JSONStatus responds with the status code and the JSON marshalled v.
func JSONStatus(c *core.Context, code int, v interface{}) {
	b, err := json.Marshal(v)
	if err != nil {
		panic(err)
	}

	c.ResponseWriter.Header().Set("Content-Type", "application/json")
	c.ResponseWriter.WriteHeader(code)
	c.ResponseWriter.Write(b)
}

// Template responds with the template associated to name.
func Template(c *core.Context, name string, data map[string]interface{}) {
	TemplateStatus(c, http.StatusOK, name, data)
}

// TemplateStatus responds with the status code and the template associated to name.
func TemplateStatus(c *core.Context, code int, name string, data map[string]interface{}) {
	if templates == nil {
		panic(ErrNoTemplatesDir)
	}

	c.ResponseWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
	c.ResponseWriter.WriteHeader(code)
	if err := ExecuteTemplate(c.ResponseWriter, c, name, data); err != nil {
		panic(err)
	}
}

// ExecuteTemplate works like the standard html/template.Template.ExecuteTemplate function but ensures that the context is part of the data.
func ExecuteTemplate(wr io.Writer, c *core.Context, name string, data map[string]interface{}) error {
	if templates == nil {
		return ErrNoTemplatesDir
	}

	if data == nil {
		data = make(map[string]interface{})
	}
	data["c"] = c
	for k, v := range templatesData {
		if _, ok := data[k]; !ok {
			data[k] = v
		}
	}

	return templates.ExecuteTemplate(wr, name, data)
}
<commit_msg>Add DataMap<commit_after>package response

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"github.com/volatile/core"
	"github.com/volatile/core/httputil"
)

const templatesDir = "templates"

var (
	// ErrNoTemplatesDir is used when a template feature is used without having the templates directory.
	ErrNoTemplatesDir = fmt.Errorf("response: templates can't be used without a %q directory", templatesDir)

	templates     *template.Template
	templatesData map[string]interface{}
)

func init() {
	if _, err := os.Stat(templatesDir); err != nil {
		return
	}

	templates = template.New(templatesDir)

	// Built-in templates funcs
	templates.Funcs(template.FuncMap{
		"html":  templatesFuncHTML,
		"nl2br": templatesFuncNL2BR,
	})

	core.BeforeRun(func() {
		if err := filepath.Walk(templatesDir, templatesWalk); err != nil {
			panic("response: " + err.Error())
		}
	})
}

// walk is the path/filepath.WalkFunc used to walk templatesDir in order to initialize templates.
// It will try to parse all files it encounters and recurse into subdirectories.
func templatesWalk(path string, f os.FileInfo, err error) error {
	if err != nil {
		return err
	}

	if f.IsDir() {
		return nil
	}

	_, err = templates.ParseFiles(path)
	return err
}

// FuncMap is the type of the map defining the mapping from names to functions.
// Each function must have either a single return value, or two return values of which the second has type error.
// In that case, if the second (error) argument evaluates to non-nil during execution, execution terminates and Execute returns that error.
// FuncMap has the same base type as FuncMap in "text/template", copied here so clients need not import "text/template".
type FuncMap map[string]interface{}

// TemplatesFuncs adds functions that will be available to all templates.
// It is legal to overwrite elements of the map.
func TemplatesFuncs(funcMap FuncMap) {
	if templates == nil {
		panic(ErrNoTemplatesDir)
	}

	templates.Funcs(template.FuncMap(funcMap))
}

// DataMap is the type of the map defining the mapping from names to data.
type DataMap map[string]interface{}

// TemplatesData adds data that will be available to all templates.
// It is legal to overwrite elements of the map.
func TemplatesData(data DataMap) {
	if templates == nil {
		panic(ErrNoTemplatesDir)
	}
	if data == nil || len(data) == 0 {
		return
	}

	if templatesData == nil {
		templatesData = make(map[string]interface{})
	}
	for k, v := range data {
		templatesData[k] = v
	}
}

// Status responds with the status code.
func Status(c *core.Context, code int) {
	http.Error(c.ResponseWriter, http.StatusText(code), code)
}

// String responds with the string s.
func String(c *core.Context, s string) {
	StringStatus(c, http.StatusOK, s)
}

// StringStatus responds with the status code and the string s.
func StringStatus(c *core.Context, code int, s string) {
	httputil.SetDetectedContentType(c.ResponseWriter, []byte(s))
	c.ResponseWriter.WriteHeader(code)
	c.ResponseWriter.Write([]byte(s))
}

// Bytes responds with the slice of bytes b.
func Bytes(c *core.Context, b []byte) {
	BytesStatus(c, http.StatusOK, b)
}

// BytesStatus responds with the status code and the slice of bytes b.
func BytesStatus(c *core.Context, code int, b []byte) {
	httputil.SetDetectedContentType(c.ResponseWriter, b)
	c.ResponseWriter.WriteHeader(code)
	c.ResponseWriter.Write(b)
}

// JSON responds with the JSON marshalled v.
func JSON(c *core.Context, v interface{}) {
	JSONStatus(c, http.StatusOK, v)
}

// JSONStatus responds with the status code and the JSON marshalled v.
func JSONStatus(c *core.Context, code int, v interface{}) {
	b, err := json.Marshal(v)
	if err != nil {
		panic(err)
	}

	c.ResponseWriter.Header().Set("Content-Type", "application/json")
	c.ResponseWriter.WriteHeader(code)
	c.ResponseWriter.Write(b)
}

// Template responds with the template associated to name.
func Template(c *core.Context, name string, data DataMap) {
	TemplateStatus(c, http.StatusOK, name, data)
}

// TemplateStatus responds with the status code and the template associated to name.
func TemplateStatus(c *core.Context, code int, name string, data DataMap) {
	if templates == nil {
		panic(ErrNoTemplatesDir)
	}

	c.ResponseWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
	c.ResponseWriter.WriteHeader(code)
	if err := ExecuteTemplate(c.ResponseWriter, c, name, data); err != nil {
		panic(err)
	}
}

// ExecuteTemplate works like the standard html/template.Template.ExecuteTemplate function but ensures that the context is part of the data.
func ExecuteTemplate(wr io.Writer, c *core.Context, name string, data DataMap) error {
	if templates == nil {
		return ErrNoTemplatesDir
	}

	if data == nil {
		data = make(map[string]interface{})
	}
	data["c"] = c
	for k, v := range templatesData {
		if _, ok := data[k]; !ok {
			data[k] = v
		}
	}

	return templates.ExecuteTemplate(wr, name, data)
}
<|endoftext|>


<commit_before>package helper

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"fmt"
	"net/smtp"
	"reflect"
	"strconv"
	"time"
)

func Base64Encode(message string) string {
	return base64.StdEncoding.EncodeToString([]byte(message))
}

func ToHmacSha1(message string, secret string) string {
	key := []byte(secret)
	h := hmac.New(sha1.New, key)
	h.Write([]byte(message))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

// 寄送 mail
func SendMail(user string, password string, host string, port string, msg string, subject string, from string, to []string) error {
	auth := smtp.PlainAuth("", user, password, host)
	sub := "subject: " + subject + "\r\n\r\n"
	return smtp.SendMail(host+":"+port, auth, from, to, []byte(sub+msg))
}

//返回現在時間 mysql datetime
//格式:2014-12-21 21:20:32
func NowTime() string {
	t := time.Now()
	y, m, d := t.Date()
	H := t.Hour()
	i := t.Minute()
	se := t.Second()
	return fmt.Sprintf("%4d-%02d-%02d %02d:%02d:%02d", y, m, d, H, i, se)
}

//返回現在時間 mysql datetime
//格式:2014-12-21 21:20:32
func NowTime8601() string {
	t := time.Now()
	y, m, d := t.Date()
	H := t.Hour()
	i := t.Minute()
	se := t.Second()
	return fmt.Sprintf("%4d-%02d-%02dT%02d:%02d:%02d.000Z", y, m, d, H, i, se)
}

// 轉換成int
func ToInt(i interface{}) int {
	kind := reflect.TypeOf(i).Kind()
	if kind == reflect.String {
		v, err := strconv.Atoi(i.(string))
		if err == nil {
			return int(v)
		}
	}
	if kind == reflect.Int {
		return int(i.(int))
	}
	if kind == reflect.Int8 {
		return int(i.(int8))
	}
	if kind == reflect.Int16 {
		return int(i.(int16))
	}
	if kind == reflect.Int32 {
		return int(i.(int32))
	}
	if kind == reflect.Int64 {
		return int(i.(int64))
	}
	if kind == reflect.Uint {
		return int(i.(uint))
	}
	if kind == reflect.Uint8 {
		return int(i.(uint8))
	}
	if kind == reflect.Uint16 {
		return int(i.(uint16))
	}
	if kind == reflect.Uint32 {
		return int(i.(uint32))
	}
	if kind == reflect.Uint64 {
		return int(i.(uint64))
	}
	if kind == reflect.Float32 {
		return int(i.(float32))
	}
	if kind == reflect.Float64 {
		return int(i.(float64))
	}
	if kind == reflect.Bool {
		if i.(bool) == true {
			return int(1)
		} else {
			return int(0)
		}
	}
	return int(0)
}

func ToString(s interface{}) string {
	kind := reflect.TypeOf(s).Kind()
	if kind == reflect.String {
		return s.(string)
	}
	if kind == reflect.Int {
		return strconv.Itoa(s.(int))
	}
	if kind == reflect.Int8 {
		return strconv.Itoa(int(s.(int8)))
	}
	if kind == reflect.Int16 {
		return strconv.Itoa(int(s.(int16)))
	}
	if kind == reflect.Int32 {
		return strconv.Itoa(int(s.(int32)))
	}
	if kind == reflect.Int64 {
		return strconv.Itoa(int(s.(int64)))
	}
	if kind == reflect.Uint {
		return strconv.Itoa(int(s.(uint)))
	}
	if kind == reflect.Uint8 {
		return strconv.Itoa(int(s.(uint8)))
	}
	if kind == reflect.Uint16 {
		return strconv.Itoa(int(s.(uint16)))
	}
	if kind == reflect.Uint32 {
		return strconv.Itoa(int(s.(uint32)))
	}
	if kind == reflect.Uint64 {
		return strconv.Itoa(int(s.(uint64)))
	}
	return ""
}
<commit_msg>add JoinInt<commit_after>package helper

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"fmt"
	"net/smtp"
	"reflect"
	"strconv"
	"strings"
	"time"
)

func Log(a ...interface{}) {
	fmt.Println(a)
}

func JoinInt(ints []int, glue string) string {
	return fmt.Sprintf(strings.Trim(strings.Replace(fmt.Sprintf("%d", ints), " ", glue, -1), "[]"))
}

func Base64Encode(message string) string {
	return base64.StdEncoding.EncodeToString([]byte(message))
}

func ToHmacSha1(message string, secret string) string {
	key := []byte(secret)
	h := hmac.New(sha1.New, key)
	h.Write([]byte(message))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

// 寄送 mail
func SendMail(user string, password string, host string, port string, msg string, subject string, from string, to []string) error {
	auth := smtp.PlainAuth("", user, password, host)
	sub := "subject: " + subject + "\r\n\r\n"
	return smtp.SendMail(host+":"+port, auth, from, to, []byte(sub+msg))
}

//返回現在時間 mysql datetime
//格式:2014-12-21 21:20:32
func NowTime() string {
	t := time.Now()
	y, m, d := t.Date()
	H := t.Hour()
	i := t.Minute()
	se := t.Second()
	return fmt.Sprintf("%4d-%02d-%02d %02d:%02d:%02d", y, m, d, H, i, se)
}

//返回現在時間 mysql datetime
//格式:2014-12-21 21:20:32
func NowTime8601() string {
	t := time.Now()
	y, m, d := t.Date()
	H := t.Hour()
	i := t.Minute()
	se := t.Second()
	return fmt.Sprintf("%4d-%02d-%02dT%02d:%02d:%02d.000Z", y, m, d, H, i, se)
}

// 轉換成int
func ToInt(i interface{}) int {
	kind := reflect.TypeOf(i).Kind()
	if kind == reflect.String {
		v, err := strconv.Atoi(i.(string))
		if err == nil {
			return int(v)
		}
	}
	if kind == reflect.Int {
		return int(i.(int))
	}
	if kind == reflect.Int8 {
		return int(i.(int8))
	}
	if kind == reflect.Int16 {
		return int(i.(int16))
	}
	if kind == reflect.Int32 {
		return int(i.(int32))
	}
	if kind == reflect.Int64 {
		return int(i.(int64))
	}
	if kind == reflect.Uint {
		return int(i.(uint))
	}
	if kind == reflect.Uint8 {
		return int(i.(uint8))
	}
	if kind == reflect.Uint16 {
		return int(i.(uint16))
	}
	if kind == reflect.Uint32 {
		return int(i.(uint32))
	}
	if kind == reflect.Uint64 {
		return int(i.(uint64))
	}
	if kind == reflect.Float32 {
		return int(i.(float32))
	}
	if kind == reflect.Float64 {
		return int(i.(float64))
	}
	if kind == reflect.Bool {
		if i.(bool) == true {
			return int(1)
		} else {
			return int(0)
		}
	}
	return int(0)
}

func ToString(s interface{}) string {
	kind := reflect.TypeOf(s).Kind()
	if kind == reflect.String {
		return s.(string)
	}
	if kind == reflect.Int {
		return strconv.Itoa(s.(int))
	}
	if kind == reflect.Int8 {
		return strconv.Itoa(int(s.(int8)))
	}
	if kind == reflect.Int16 {
		return strconv.Itoa(int(s.(int16)))
	}
	if kind == reflect.Int32 {
		return strconv.Itoa(int(s.(int32)))
	}
	if kind == reflect.Int64 {
		return strconv.Itoa(int(s.(int64)))
	}
	if kind == reflect.Uint {
		return strconv.Itoa(int(s.(uint)))
	}
	if kind == reflect.Uint8 {
		return strconv.Itoa(int(s.(uint8)))
	}
	if kind == reflect.Uint16 {
		return strconv.Itoa(int(s.(uint16)))
	}
	if kind == reflect.Uint32 {
		return strconv.Itoa(int(s.(uint32)))
	}
	if kind == reflect.Uint64 {
		return strconv.Itoa(int(s.(uint64)))
	}
	return ""
}
<|endoftext|>