<commit_before>// Copyright 2016-2017 Authors of Cilium
//
// 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 policy

import (
	"github.com/cilium/cilium/pkg/labels"
	"github.com/cilium/cilium/pkg/lock"
	"github.com/cilium/cilium/pkg/logging/logfields"
	"github.com/cilium/cilium/pkg/maps/policymap"

	"github.com/sirupsen/logrus"
)

// Consumable holds all of the policies relevant to this security identity,
// including label-based policies, L4Policy, and L7 policy.
type Consumable struct {
	// ID of the consumable (same as security ID)
	ID NumericIdentity `json:"id"`
	// Mutex protects all variables from this structure below this line
	Mutex lock.RWMutex
	// Labels are the SecurityIdentity of this consumable
	Labels *Identity `json:"labels"`
	// LabelArray contains the same labels from identity in a form of a list, used for faster lookup
	LabelArray labels.LabelArray `json:"-"`
	// Iteration policy of the Consumable
	Iteration uint64 `json:"-"`
	// Map from bpf map fd to the policymap, the go representation of an endpoint's bpf policy map.
	Maps map[int]*policymap.PolicyMap `json:"-"`
	// IngressIdentities is the set of security identities from which ingress
	// traffic is allowed. The value corresponds to whether the corresponding
	// key (security identity) should be garbage collected upon policy calculation.
	IngressIdentities map[NumericIdentity]bool `json:"ingress-identities"`
	// L4Policy contains the policy of this consumable
	L4Policy *L4Policy `json:"l4-policy"`
	// L3L4Policy contains the L3, L4 and L7 ingress policy of this consumable
	L3L4Policy *SecurityIDContexts `json:"l3-l4-policy"`
	cache      *ConsumableCache
}

// NewConsumable creates a new consumable
func NewConsumable(id NumericIdentity, lbls *Identity, cache *ConsumableCache) *Consumable {
	consumable := &Consumable{
		ID:                id,
		Iteration:         0,
		Labels:            lbls,
		Maps:              map[int]*policymap.PolicyMap{},
		IngressIdentities: map[NumericIdentity]bool{},
		cache:             cache,
	}
	if lbls != nil {
		consumable.LabelArray = lbls.Labels.ToSlice()
	}

	return consumable
}

func (c *Consumable) AddMap(m *policymap.PolicyMap) {
	c.Mutex.Lock()
	defer c.Mutex.Unlock()
	if c.Maps == nil {
		c.Maps = make(map[int]*policymap.PolicyMap)
	}

	// Check if map is already associated with this consumable
	if _, ok := c.Maps[m.Fd]; ok {
		return
	}

	log.WithFields(logrus.Fields{
		"policymap":  m,
		"consumable": c,
	}).Debug("Adding policy map to consumable")
	c.Maps[m.Fd] = m

	// Populate the new map with the already established allowed identities from
	// which ingress traffic is allowed.
	for ingressIdentity := range c.IngressIdentities {
		if err := m.AllowIdentity(ingressIdentity.Uint32()); err != nil {
			log.WithError(err).Warn("Update of policy map failed")
		}
	}
}

func (c *Consumable) delete() {
	for ingressIdentity := range c.IngressIdentities {
		// FIXME: This explicit removal could be removed eventually to
		// speed things up as the policy map should get deleted anyway
		if c.wasLastRule(ingressIdentity) {
			c.removeFromMaps(ingressIdentity)
		}
	}

	if c.cache != nil {
		c.cache.Remove(c)
	}
}

func (c *Consumable) RemoveMap(m *policymap.PolicyMap) {
	if m != nil {
		c.Mutex.Lock()
		delete(c.Maps, m.Fd)
		log.WithFields(logrus.Fields{
			"policymap":  m,
			"consumable": c,
			"count":      len(c.Maps),
		}).Debug("Removing map from consumable")

		// If the last map of the consumable is gone the consumable is no longer
		// needed and should be removed from the cache and all cross references
		// must be undone.
		if len(c.Maps) == 0 {
			c.delete()
		}
		c.Mutex.Unlock()
	}

}

func (c *Consumable) addToMaps(id NumericIdentity) {
	for _, m := range c.Maps {
		if m.IdentityExists(id.Uint32()) {
			continue
		}

		scopedLog := log.WithFields(logrus.Fields{
			"policymap":        m,
			logfields.Identity: id,
		})

		scopedLog.Debug("Updating policy BPF map: allowing Identity")
		if err := m.AllowIdentity(id.Uint32()); err != nil {
			scopedLog.WithError(err).Warn("Update of policy map failed")
		}
	}
}

// A rule is the 'last rule' for an identity if it does not exist as a key
// in any of the maps for this Consumable.
func (c *Consumable) wasLastRule(id NumericIdentity) bool {
	_, existsIngressIdentity := c.IngressIdentities[id]
	return !existsIngressIdentity
}

func (c *Consumable) removeFromMaps(id NumericIdentity) {
	for _, m := range c.Maps {
		scopedLog := log.WithFields(logrus.Fields{
			"policymap":        m,
			logfields.Identity: id,
		})

		scopedLog.Debug("Updating policy BPF map: denying Identity")
		if err := m.DeleteIdentity(id.Uint32()); err != nil {
			scopedLog.WithError(err).Warn("Update of policy map failed")
		}
	}
}

// AllowIngressIdentityLocked adds the given security identity to the Consumable's
// IngressIdentities map. Must be called with Consumable mutex Locked.
// Returns true if the identity was not present in this Consumable's
// IngressIdentities map, and thus had to be added, false if it is already added.
func (c *Consumable) AllowIngressIdentityLocked(cache *ConsumableCache, id NumericIdentity) bool {
	_, exists := c.IngressIdentities[id]
	if !exists {
		log.WithFields(logrus.Fields{
			logfields.Identity: id,
			"consumable":       logfields.Repr(c),
		}).Debug("Allowing security identity on ingress for consumable")
		c.addToMaps(id)

		// If id corresponds to a reserved identity, Consumable corresponding to
		// that security identity needs to be updated explicitly, as reserved
		// identities do not have a corresponding endpoint for which policy
		// recalculation (when Consumables are updated) is done.
		if id.IsReservedIdentity() {
			reservedConsumable := cache.Lookup(id)
			if reservedConsumable != nil {
				// Avoid deadlock ; is this necessary? Being cautious.
				if id != c.ID {
					reservedConsumable.Mutex.Lock()
					reservedConsumable.AllowIngressIdentityLocked(cache, c.ID)
					reservedConsumable.Mutex.Unlock()
				} else {
					reservedConsumable.AllowIngressIdentityLocked(cache, c.ID)
				}
			} else {
				log.WithField(logfields.Identity, id).Warningf("unable to allow ingress from identity %d", c.ID)
			}

		}
	}

	c.IngressIdentities[id] = true

	return !exists // not changed, was already in map.
}

// RemoveIngressIdentityLocked removes the given security identity from Consumable's
// IngressIdentities map.
// Must be called with the Consumable mutex locked.
func (c *Consumable) RemoveIngressIdentityLocked(id NumericIdentity) {
	if _, ok := c.IngressIdentities[id]; ok {
		log.WithField(logfields.Identity, id).Debug("Removing identity from ingress map")
		delete(c.IngressIdentities, id)

		// Consumables corresponding to reserved identities need to be updated
		// explicitly because they are not updated or regenerated.
		if id.IsReservedIdentity() {
			reservedConsumable := c.cache.Lookup(id)
			if reservedConsumable != nil {
				// Avoid deadlock!
				if id != c.ID {
					reservedConsumable.Mutex.Lock()
					reservedConsumable.RemoveIngressIdentityLocked(c.ID)
					reservedConsumable.Mutex.Unlock()
				} else {
					reservedConsumable.RemoveIngressIdentityLocked(c.ID)
				}
			} else {
				log.WithField(logfields.Identity, id).Warningf("unable to disallow ingress from identity %d", c.ID)
			}

		}
		if c.wasLastRule(id) {
			c.removeFromMaps(id)
		}
	}
}

func (c *Consumable) Allows(id NumericIdentity) bool {
	c.Mutex.RLock()
	isIdentityAllowed, _ := c.IngressIdentities[id]
	c.Mutex.RUnlock()
	return isIdentityAllowed
}
<commit_msg>pkg/policy: specify when lock is acquired for reserved identity Consumables<commit_after>// Copyright 2016-2017 Authors of Cilium
//
// 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 policy

import (
	"github.com/cilium/cilium/pkg/labels"
	"github.com/cilium/cilium/pkg/lock"
	"github.com/cilium/cilium/pkg/logging/logfields"
	"github.com/cilium/cilium/pkg/maps/policymap"

	"github.com/sirupsen/logrus"
)

// Consumable holds all of the policies relevant to this security identity,
// including label-based policies, L4Policy, and L7 policy.
type Consumable struct {
	// ID of the consumable (same as security ID)
	ID NumericIdentity `json:"id"`
	// Mutex protects all variables from this structure below this line
	Mutex lock.RWMutex
	// Labels are the SecurityIdentity of this consumable
	Labels *Identity `json:"labels"`
	// LabelArray contains the same labels from identity in a form of a list, used for faster lookup
	LabelArray labels.LabelArray `json:"-"`
	// Iteration policy of the Consumable
	Iteration uint64 `json:"-"`
	// Map from bpf map fd to the policymap, the go representation of an endpoint's bpf policy map.
	Maps map[int]*policymap.PolicyMap `json:"-"`
	// IngressIdentities is the set of security identities from which ingress
	// traffic is allowed. The value corresponds to whether the corresponding
	// key (security identity) should be garbage collected upon policy calculation.
	IngressIdentities map[NumericIdentity]bool `json:"ingress-identities"`
	// L4Policy contains the policy of this consumable
	L4Policy *L4Policy `json:"l4-policy"`
	// L3L4Policy contains the L3, L4 and L7 ingress policy of this consumable
	L3L4Policy *SecurityIDContexts `json:"l3-l4-policy"`
	cache      *ConsumableCache
}

// NewConsumable creates a new consumable
func NewConsumable(id NumericIdentity, lbls *Identity, cache *ConsumableCache) *Consumable {
	consumable := &Consumable{
		ID:                id,
		Iteration:         0,
		Labels:            lbls,
		Maps:              map[int]*policymap.PolicyMap{},
		IngressIdentities: map[NumericIdentity]bool{},
		cache:             cache,
	}
	if lbls != nil {
		consumable.LabelArray = lbls.Labels.ToSlice()
	}

	return consumable
}

func (c *Consumable) AddMap(m *policymap.PolicyMap) {
	c.Mutex.Lock()
	defer c.Mutex.Unlock()
	if c.Maps == nil {
		c.Maps = make(map[int]*policymap.PolicyMap)
	}

	// Check if map is already associated with this consumable
	if _, ok := c.Maps[m.Fd]; ok {
		return
	}

	log.WithFields(logrus.Fields{
		"policymap":  m,
		"consumable": c,
	}).Debug("Adding policy map to consumable")
	c.Maps[m.Fd] = m

	// Populate the new map with the already established allowed identities from
	// which ingress traffic is allowed.
	for ingressIdentity := range c.IngressIdentities {
		if err := m.AllowIdentity(ingressIdentity.Uint32()); err != nil {
			log.WithError(err).Warn("Update of policy map failed")
		}
	}
}

func (c *Consumable) delete() {
	for ingressIdentity := range c.IngressIdentities {
		// FIXME: This explicit removal could be removed eventually to
		// speed things up as the policy map should get deleted anyway
		if c.wasLastRule(ingressIdentity) {
			c.removeFromMaps(ingressIdentity)
		}
	}

	if c.cache != nil {
		c.cache.Remove(c)
	}
}

func (c *Consumable) RemoveMap(m *policymap.PolicyMap) {
	if m != nil {
		c.Mutex.Lock()
		delete(c.Maps, m.Fd)
		log.WithFields(logrus.Fields{
			"policymap":  m,
			"consumable": c,
			"count":      len(c.Maps),
		}).Debug("Removing map from consumable")

		// If the last map of the consumable is gone the consumable is no longer
		// needed and should be removed from the cache and all cross references
		// must be undone.
		if len(c.Maps) == 0 {
			c.delete()
		}
		c.Mutex.Unlock()
	}

}

func (c *Consumable) addToMaps(id NumericIdentity) {
	for _, m := range c.Maps {
		if m.IdentityExists(id.Uint32()) {
			continue
		}

		scopedLog := log.WithFields(logrus.Fields{
			"policymap":        m,
			logfields.Identity: id,
		})

		scopedLog.Debug("Updating policy BPF map: allowing Identity")
		if err := m.AllowIdentity(id.Uint32()); err != nil {
			scopedLog.WithError(err).Warn("Update of policy map failed")
		}
	}
}

// A rule is the 'last rule' for an identity if it does not exist as a key
// in any of the maps for this Consumable.
func (c *Consumable) wasLastRule(id NumericIdentity) bool {
	_, existsIngressIdentity := c.IngressIdentities[id]
	return !existsIngressIdentity
}

func (c *Consumable) removeFromMaps(id NumericIdentity) {
	for _, m := range c.Maps {
		scopedLog := log.WithFields(logrus.Fields{
			"policymap":        m,
			logfields.Identity: id,
		})

		scopedLog.Debug("Updating policy BPF map: denying Identity")
		if err := m.DeleteIdentity(id.Uint32()); err != nil {
			scopedLog.WithError(err).Warn("Update of policy map failed")
		}
	}
}

// AllowIngressIdentityLocked adds the given security identity to the Consumable's
// IngressIdentities map. Must be called with Consumable mutex Locked.
// Returns true if the identity was not present in this Consumable's
// IngressIdentities map, and thus had to be added, false if it is already added.
func (c *Consumable) AllowIngressIdentityLocked(cache *ConsumableCache, id NumericIdentity) bool {
	_, exists := c.IngressIdentities[id]
	if !exists {
		log.WithFields(logrus.Fields{
			logfields.Identity: id,
			"consumable":       logfields.Repr(c),
		}).Debug("Allowing security identity on ingress for consumable")
		c.addToMaps(id)

		// If id corresponds to a reserved identity, Consumable corresponding to
		// that security identity needs to be updated explicitly, as reserved
		// identities do not have a corresponding endpoint for which policy
		// recalculation (when Consumables are updated) is done.
		if id.IsReservedIdentity() {
			reservedConsumable := cache.Lookup(id)
			if reservedConsumable != nil {
				// If we are accessing the same Consumable (allowing traffic
				// to itself), we don't need to take its mutex because it was
				// already taken before calling this function.
				if id != c.ID {
					reservedConsumable.Mutex.Lock()
					reservedConsumable.AllowIngressIdentityLocked(cache, c.ID)
					reservedConsumable.Mutex.Unlock()
				} else {
					reservedConsumable.AllowIngressIdentityLocked(cache, c.ID)
				}
			} else {
				log.WithField(logfields.Identity, id).Warningf("unable to allow ingress from identity %d", c.ID)
			}

		}
	}

	c.IngressIdentities[id] = true

	return !exists // not changed, was already in map.
}

// RemoveIngressIdentityLocked removes the given security identity from Consumable's
// IngressIdentities map.
// Must be called with the Consumable mutex locked.
func (c *Consumable) RemoveIngressIdentityLocked(id NumericIdentity) {
	if _, ok := c.IngressIdentities[id]; ok {
		log.WithField(logfields.Identity, id).Debug("Removing identity from ingress map")
		delete(c.IngressIdentities, id)

		// Consumables corresponding to reserved identities need to be updated
		// explicitly because they are not updated or regenerated.
		if id.IsReservedIdentity() {
			reservedConsumable := c.cache.Lookup(id)
			if reservedConsumable != nil {
				// If we are accessing the same Consumable (allowing traffic
				// to itself), we don't need to take its mutex because it was
				// already taken before calling this function.
				if id != c.ID {
					reservedConsumable.Mutex.Lock()
					reservedConsumable.RemoveIngressIdentityLocked(c.ID)
					reservedConsumable.Mutex.Unlock()
				} else {
					reservedConsumable.RemoveIngressIdentityLocked(c.ID)
				}
			} else {
				log.WithField(logfields.Identity, id).Warningf("unable to disallow ingress from identity %d", c.ID)
			}

		}
		if c.wasLastRule(id) {
			c.removeFromMaps(id)
		}
	}
}

func (c *Consumable) Allows(id NumericIdentity) bool {
	c.Mutex.RLock()
	isIdentityAllowed, _ := c.IngressIdentities[id]
	c.Mutex.RUnlock()
	return isIdentityAllowed
}
<|endoftext|>


<commit_before>package project

var (
	description        = "The aws-operator manages Kubernetes clusters running on AWS."
	gitSHA             = "n/a"
	name        string = "aws-operator"
	source      string = "https://github.com/giantswarm/aws-operator"
	version            = "8.8.0"
)

func Description() string {
	return description
}

func GitSHA() string {
	return gitSHA
}

func Name() string {
	return name
}

func Source() string {
	return source
}

func Version() string {
	return version
}
<commit_msg>manually-bump-version (#2677)<commit_after>package project

var (
	description        = "The aws-operator manages Kubernetes clusters running on AWS."
	gitSHA             = "n/a"
	name        string = "aws-operator"
	source      string = "https://github.com/giantswarm/aws-operator"
	version            = "8.8.1-dev"
)

func Description() string {
	return description
}

func GitSHA() string {
	return gitSHA
}

func Name() string {
	return name
}

func Source() string {
	return source
}

func Version() string {
	return version
}
<|endoftext|>


<commit_before>package version

// VERSION is supplied with the git committish this is built from
var VERSION = ""

// IMPORTANT: These versions are overridden by version ldflags specifications VERSION_VARIABLES in the Makefile

// DdevVersion is the current version of ddev, by default the git committish (should be current git tag)
var DdevVersion = "v0.0.0-overridden-by-make" // Note that this is overridden by make

// DockerVersionConstraint is the current minimum version of docker required for ddev.
// See https://godoc.org/github.com/Masterminds/semver#hdr-Checking_Version_Constraints
// for examples defining version constraints.
var DockerVersionConstraint = ">= 17.05.0-ce-alpha1"

// DockerComposeVersionConstraint is the current minimum version of docker-compose required for ddev.
var DockerComposeVersionConstraint = ">= 1.10.0-alpha1"

// WebImg defines the default web image used for applications.
var WebImg = "drud/nginx-php-fpm-local"

// WebTag defines the default web image tag for drud dev
var WebTag = "20180522_fpm_env_vars" // Note that this can be overridden by make

// DBImg defines the default db image used for applications.
var DBImg = "drud/mariadb-local"

// DBTag defines the default db image tag for drud dev
var DBTag = "20180530_remove_max_allowed_packet" // Note that this may be overridden by make

// DBAImg defines the default phpmyadmin image tag used for applications.
var DBAImg = "drud/phpmyadmin"

// DBATag defines the default phpmyadmin image tag used for applications.
var DBATag = "v0.2.0" // Note that this can be overridden by make

// RouterImage defines the image used for the router.
var RouterImage = "drud/ddev-router"

// RouterTag defines the tag used for the router.
var RouterTag = "v0.18.0-11-gd6cb228c" // Note that this can be overridden by make

// COMMIT is the actual committish, supplied by make
var COMMIT = "COMMIT should be overridden"

// BUILDINFO is information with date and context, supplied by make
var BUILDINFO = "BUILDINFO should have new info"

// DDevTLD defines the tld to use for DDev site URLs.
const DDevTLD = "ddev.local"

// GetVersionInfo returns a map containing the version info defined above.
func GetVersionInfo() map[string]string {
	versionInfo := make(map[string]string)

	versionInfo["cli"] = DdevVersion
	versionInfo["web"] = WebImg + ":" + WebTag
	versionInfo["db"] = DBImg + ":" + DBTag
	versionInfo["dba"] = DBAImg + ":" + DBATag
	versionInfo["router"] = RouterImage + ":" + RouterTag
	versionInfo["commit"] = COMMIT
	versionInfo["domain"] = DDevTLD
	versionInfo["build info"] = BUILDINFO

	return versionInfo
}
<commit_msg>Bump container versions to planned v0.19.0 for release (#897)<commit_after>package version

// VERSION is supplied with the git committish this is built from
var VERSION = ""

// IMPORTANT: These versions are overridden by version ldflags specifications VERSION_VARIABLES in the Makefile

// DdevVersion is the current version of ddev, by default the git committish (should be current git tag)
var DdevVersion = "v0.0.0-overridden-by-make" // Note that this is overridden by make

// DockerVersionConstraint is the current minimum version of docker required for ddev.
// See https://godoc.org/github.com/Masterminds/semver#hdr-Checking_Version_Constraints
// for examples defining version constraints.
var DockerVersionConstraint = ">= 17.05.0-ce-alpha1"

// DockerComposeVersionConstraint is the current minimum version of docker-compose required for ddev.
var DockerComposeVersionConstraint = ">= 1.10.0-alpha1"

// WebImg defines the default web image used for applications.
var WebImg = "drud/nginx-php-fpm-local"

// WebTag defines the default web image tag for drud dev
var WebTag = "v0.19.0" // Note that this can be overridden by make

// DBImg defines the default db image used for applications.
var DBImg = "drud/mariadb-local"

// DBTag defines the default db image tag for drud dev
var DBTag = "v0.19.0" // Note that this may be overridden by make

// DBAImg defines the default phpmyadmin image tag used for applications.
var DBAImg = "drud/phpmyadmin"

// DBATag defines the default phpmyadmin image tag used for applications.
var DBATag = "v0.19.0" // Note that this can be overridden by make

// RouterImage defines the image used for the router.
var RouterImage = "drud/ddev-router"

// RouterTag defines the tag used for the router.
var RouterTag = "v0.19.0" // Note that this can be overridden by make

// COMMIT is the actual committish, supplied by make
var COMMIT = "COMMIT should be overridden"

// BUILDINFO is information with date and context, supplied by make
var BUILDINFO = "BUILDINFO should have new info"

// DDevTLD defines the tld to use for DDev site URLs.
const DDevTLD = "ddev.local"

// GetVersionInfo returns a map containing the version info defined above.
func GetVersionInfo() map[string]string {
	versionInfo := make(map[string]string)

	versionInfo["cli"] = DdevVersion
	versionInfo["web"] = WebImg + ":" + WebTag
	versionInfo["db"] = DBImg + ":" + DBTag
	versionInfo["dba"] = DBAImg + ":" + DBATag
	versionInfo["router"] = RouterImage + ":" + RouterTag
	versionInfo["commit"] = COMMIT
	versionInfo["domain"] = DDevTLD
	versionInfo["build info"] = BUILDINFO

	return versionInfo
}
<|endoftext|>


<commit_before>package terraform

import (
	"fmt"

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

// The main version number that is being run at the moment.
const Version = "0.10.9-dev"

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

// SemVersion is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVersion = version.Must(version.NewVersion(Version))

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

func VersionString() string {
	if VersionPrerelease != "" {
		return fmt.Sprintf("%s-%s", Version, VersionPrerelease)
	}
	return Version
}
<commit_msg>Update version.go<commit_after>package terraform

import (
	"fmt"

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

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

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

// SemVersion is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVersion = version.Must(version.NewVersion(Version))

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

func VersionString() string {
	if VersionPrerelease != "" {
		return fmt.Sprintf("%s-%s", Version, VersionPrerelease)
	}
	return Version
}
<|endoftext|>


<commit_before>package model

import (
    "math/rand"
)

type Word struct {
    Id          int             `json:"-"`
    Word        string
    Prohibited  []string
}

func (w *Word) ProhibitedWords() []string {
    return w.Prohibited
}

func (w *Word) SampleProhibitedWords() []string {
    perm := rand.Perm(len(w.Prohibited))
    sample := make([]string, 5)
    for i := 0; i < 5; i++ {
        sample[i] = w.Prohibited[perm[i]]
    }
    return sample
}
<commit_msg>annotated word with actual json field names<commit_after>package model

import (
    "math/rand"
)

type Word struct {
    Id          int             `json:"-"`
    Word        string          `json:"word"`
    Prohibited  []string        `json:"prohibited_words"`
}

func (w *Word) ProhibitedWords() []string {
    return w.Prohibited
}

func (w *Word) SampleProhibitedWords() []string {
    perm := rand.Perm(len(w.Prohibited))
    sample := make([]string, 5)
    for i := 0; i < 5; i++ {
        sample[i] = w.Prohibited[perm[i]]
    }
    return sample
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/skelterjohn/geom"
	"github.com/skelterjohn/go.uik"
	"github.com/skelterjohn/go.uik/layouts"
	"github.com/skelterjohn/go.uik/widgets"
	"github.com/skelterjohn/go.wde"
	"image/color"
)

func main() {
	go uiktest()
	wde.Run()
}

func uiktest() {

	wbounds := geom.Rect{
		Max: geom.Coord{480, 320},
	}
	w, err := uik.NewWindow(nil, int(wbounds.Max.X), int(wbounds.Max.Y))
	if err != nil {
		fmt.Println(err)
		return
	}
	w.W.SetTitle("go.uik")

	// Create a button with the given size and label
	b := widgets.NewButton("Hi")
	// Here we get the button's label's data
	ld := <-b.Label.GetConfig
	// we modify the copy for a special message to display
	ld.Text = "clicked!"

	l := widgets.NewLabel(geom.Coord{100, 50}, widgets.LabelData{"text", 14, color.Black})
	b2 := widgets.NewButton("there")
	ld2 := <-b2.Label.GetConfig
	ld2.Text = "BAM"

	// the widget.Buttton has a special channels that sends out wde.Buttons
	// whenever its clicked. Here we set up something that changes the
	// label's text every time a click is received.
	clicker := make(widgets.Clicker)
	b.AddClicker <- clicker
	go func() {
		for _ = range clicker {
			b.Label.SetConfig <- ld
			l.SetConfig <- widgets.LabelData{"ohnoes", 20, color.Black}
		}
	}()

	clicker2 := make(widgets.Clicker)
	b2.AddClicker <- clicker2
	go func() {
		for _ = range clicker2 {
			b.Label.SetConfig <- ld2
			b2.Label.SetConfig <- ld
			l.SetConfig <- widgets.LabelData{"oops", 14, color.Black}
		}
	}()

	cb := widgets.NewCheckbox(geom.Coord{50, 50})

	kg := widgets.NewKeyGrab(geom.Coord{50, 50})
	kg2 := widgets.NewKeyGrab(geom.Coord{50, 50})

	g := layouts.NewGrid(layouts.GridConfig{})

	l0_0 := widgets.NewLabel(geom.Coord{}, widgets.LabelData{"0, 0", 12, color.Black})
	l0_1 := widgets.NewLabel(geom.Coord{}, widgets.LabelData{"0, 1", 12, color.Black})
	l1_0 := widgets.NewLabel(geom.Coord{}, widgets.LabelData{"1, 0", 12, color.Black})
	l1_1 := widgets.NewLabel(geom.Coord{}, widgets.LabelData{"1, 1", 12, color.Black})

	g.Add <- layouts.BlockData{
		Block: &l0_0.Block,
		GridX: 0, GridY: 0,
	}
	g.Add <- layouts.BlockData{
		Block: &l0_1.Block,
		GridX: 0, GridY: 1,
	}
	g.Add <- layouts.BlockData{
		Block: &l1_0.Block,
		GridX: 1, GridY: 0,
	}
	g.Add <- layouts.BlockData{
		Block: &l1_1.Block,
		GridX: 1, GridY: 1,
	}

	clicker3 := make(widgets.Clicker)
	b.AddClicker <- clicker3
	go func() {
		for _ = range clicker3 {
			l0_0.SetConfig <- widgets.LabelData{"Pow", 12, color.Black}
		}
	}()
	clicker4 := make(widgets.Clicker)
	b2.AddClicker <- clicker4
	go func() {
		for _ = range clicker4 {
			l0_0.SetConfig <- widgets.LabelData{"gotcha", 12, color.Black}
		}
	}()

	e := widgets.NewEntry(geom.Coord{100, 30})

	// Here we create a flow layout, which just lines up its blocks from
	// left to right.
	if false {
		fl := layouts.NewFlow()

		fl.Add <- &b.Block
		fl.Add <- &l.Block
		fl.Add <- &kg.Block
		fl.Add <- &b2.Block
		fl.Add <- &cb.Block
		fl.Add <- &kg2.Block
		fl.Add <- &g.Block
		fl.Add <- &e.Block
		// We add it to the window, taking up the entire space the window has.
		w.Pane <- &fl.Block
	} else {
		hb := layouts.HBox(layouts.GridConfig{},
			&b.Block, &l.Block, &kg.Block, &b2.Block, &cb.Block, &kg2.Block, &g.Block, &e.Block)
		w.Pane <- &hb.Block
	}

	w.Show()

	// Here we set up a subscription on the window's close events.
	done := make(chan interface{}, 1)
	isDone := func(e interface{}) (accept, done bool) {
		_, accept = e.(uik.CloseEvent)
		done = accept
		return
	}
	w.Block.Subscribe <- uik.Subscription{isDone, done}

	// once a close event comes in on the subscription, end the program
	<-done

	w.W.Close()

	wde.Stop()
}
<commit_msg>grid anchoring<commit_after>package main

import (
	"fmt"
	"github.com/skelterjohn/geom"
	"github.com/skelterjohn/go.uik"
	"github.com/skelterjohn/go.uik/layouts"
	"github.com/skelterjohn/go.uik/widgets"
	"github.com/skelterjohn/go.wde"
	"image/color"
)

func main() {
	go uiktest()
	wde.Run()
}

func uiktest() {

	wbounds := geom.Rect{
		Max: geom.Coord{480, 320},
	}
	w, err := uik.NewWindow(nil, int(wbounds.Max.X), int(wbounds.Max.Y))
	if err != nil {
		fmt.Println(err)
		return
	}
	w.W.SetTitle("go.uik")

	// Create a button with the given size and label
	b := widgets.NewButton("Hi")
	// Here we get the button's label's data
	ld := <-b.Label.GetConfig
	// we modify the copy for a special message to display
	ld.Text = "clicked!"

	l := widgets.NewLabel(geom.Coord{100, 50}, widgets.LabelData{"text", 14, color.Black})
	b2 := widgets.NewButton("there")
	ld2 := <-b2.Label.GetConfig
	ld2.Text = "BAM"

	// the widget.Buttton has a special channels that sends out wde.Buttons
	// whenever its clicked. Here we set up something that changes the
	// label's text every time a click is received.
	clicker := make(widgets.Clicker)
	b.AddClicker <- clicker
	go func() {
		for _ = range clicker {
			b.Label.SetConfig <- ld
			l.SetConfig <- widgets.LabelData{"ohnoes", 20, color.Black}
		}
	}()

	clicker2 := make(widgets.Clicker)
	b2.AddClicker <- clicker2
	go func() {
		for _ = range clicker2 {
			b.Label.SetConfig <- ld2
			b2.Label.SetConfig <- ld
			l.SetConfig <- widgets.LabelData{"oops", 14, color.Black}
		}
	}()

	cb := widgets.NewCheckbox(geom.Coord{50, 50})

	kg := widgets.NewKeyGrab(geom.Coord{50, 50})
	kg2 := widgets.NewKeyGrab(geom.Coord{50, 50})

	g := layouts.NewGrid(layouts.GridConfig{})

	l0_0 := widgets.NewLabel(geom.Coord{}, widgets.LabelData{"0, 0", 12, color.Black})
	l0_1 := widgets.NewLabel(geom.Coord{}, widgets.LabelData{"0, 1", 12, color.Black})
	l1_0 := widgets.NewLabel(geom.Coord{}, widgets.LabelData{"1, 0", 12, color.Black})
	l1_1 := widgets.NewLabel(geom.Coord{}, widgets.LabelData{"1, 1", 12, color.Black})

	g.Add <- layouts.BlockData{
		Block: &l0_0.Block,
		GridX: 0, GridY: 0,
	}
	g.Add <- layouts.BlockData{
		Block: &l0_1.Block,
		GridX: 0, GridY: 1,
	}
	g.Add <- layouts.BlockData{
		Block: &l1_0.Block,
		GridX: 1, GridY: 0,
	}
	g.Add <- layouts.BlockData{
		Block: &l1_1.Block,
		GridX: 1, GridY: 1,
		AnchorX: layouts.AnchorMin | layouts.AnchorMax,
		AnchorY: layouts.AnchorMin | layouts.AnchorMax,
	}

	clicker3 := make(widgets.Clicker)
	b.AddClicker <- clicker3
	go func() {
		for _ = range clicker3 {
			l0_0.SetConfig <- widgets.LabelData{"Pow", 12, color.Black}
		}
	}()
	clicker4 := make(widgets.Clicker)
	b2.AddClicker <- clicker4
	go func() {
		for _ = range clicker4 {
			l0_0.SetConfig <- widgets.LabelData{"gotcha", 12, color.Black}
		}
	}()

	e := widgets.NewEntry(geom.Coord{100, 30})

	// Here we create a flow layout, which just lines up its blocks from
	// left to right.
	if false {
		fl := layouts.NewFlow()

		fl.Add <- &b.Block
		fl.Add <- &l.Block
		fl.Add <- &kg.Block
		fl.Add <- &b2.Block
		fl.Add <- &cb.Block
		fl.Add <- &kg2.Block
		fl.Add <- &g.Block
		fl.Add <- &e.Block
		// We add it to the window, taking up the entire space the window has.
		w.Pane <- &fl.Block
	} else {
		hb := layouts.HBox(layouts.GridConfig{},
			&b.Block, &l.Block, &kg.Block, &b2.Block, &cb.Block, &kg2.Block, &g.Block, &e.Block)
		w.Pane <- &hb.Block
	}

	w.Show()

	// Here we set up a subscription on the window's close events.
	done := make(chan interface{}, 1)
	isDone := func(e interface{}) (accept, done bool) {
		_, accept = e.(uik.CloseEvent)
		done = accept
		return
	}
	w.Block.Subscribe <- uik.Subscription{isDone, done}

	// once a close event comes in on the subscription, end the program
	<-done

	w.W.Close()

	wde.Stop()
}
<|endoftext|>


<commit_before>package routes

import (
	"github.com/go-zoo/bone"
)

// apiRoutes registers the routes prefixed with /api
func apiRoutes() *bone.Mux {
	router := bone.New()

	// users
	router.PostFunc("/users", api.AuthCreateUser)

	return router
}
<commit_msg>fix build<commit_after>package routes

import (
	"github.com/generationtux/brizo/app/handlers/api"
	"github.com/go-zoo/bone"
)

// apiRoutes registers the routes prefixed with /api
func apiRoutes() *bone.Mux {
	router := bone.New()

	// users
	router.PostFunc("/users", api.AuthCreateUser)

	return router
}
<|endoftext|>


<commit_before>// Copyright 2016 The appc 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 main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"

	"github.com/spf13/cobra"
)

const (
	nestedScriptEnvVar = "ACBUILD_NESTED_SCRIPT"
)

var (
	errSingleQuote = fmt.Errorf("unterminated single quote block")
	errDoubleQuote = fmt.Errorf("unterminated double quote block")
	errEscape      = fmt.Errorf("ended with an escape")
	cmdScript      = &cobra.Command{
		Use:     "script SCRIPT_FILE",
		Short:   "Runs an acbuild script",
		Example: "acbuild script build-myapp.acb",
		Run:     runWrapper(runScript),
	}
)

func init() {
	cmdAcbuild.AddCommand(cmdScript)
}

func runScript(cmd *cobra.Command, args []string) (exit int) {
	if len(args) != 1 {
		cmd.Usage()
		return 1
	}

	scriptName := args[0]
	rawScript, err := ioutil.ReadFile(scriptName)
	if err != nil {
		stderr("script: %v", err)
		return getErrorCode(err)
	}

	if debug {
		stderr("Running script from %s", scriptName)
	}

	err = execScript(rawScript)
	if err != nil {
		stderr("script: %v", err)
		return getErrorCode(err)
	}
	return 0
}

func execScript(rawScript []byte) error {
	script := strings.Split(string(rawScript), "\n")
	for i, s := range script {
		s = strings.TrimSpace(s)
		script[i] = s

		if strings.HasPrefix(strings.ToLower(s), "run") && os.Geteuid() != 0 {
			return fmt.Errorf("scripts using the run subcommand must be run as root")
		}
	}
	script = joinLines(script)

	var tmpDir string
	nestedScript := false
	if inheritedPath := os.Getenv(nestedScriptEnvVar); inheritedPath != "" {
		tmpDir = inheritedPath
		nestedScript = true
	} else {
		var err error
		tmpDir, err = ioutil.TempDir("", "acbuild")
		if err != nil {
			return err
		}
		defer os.RemoveAll(tmpDir)
		contextpath = tmpDir
	}

	for _, line := range script {
		if line == "" {
			continue
		}
		err := execACBuild(tmpDir, line)
		if err != nil {
			if !strings.HasPrefix(line, "begin") && !nestedScript {
				err1 := newACBuild().End()
				if err1 != nil {
					stderr("script: %v", err1)
				}
			}
			return err
		}
	}
	if !nestedScript {
		err := newACBuild().End()
		if err != nil {
			return err
		}
	}
	if debug {
		stderr("Script has been completed")
	}

	return nil
}

func execACBuild(workPath, line string) error {
	suppliedArgs, err := tokenizeLine(line)
	if err != nil {
		return err
	}
	if len(suppliedArgs) == 0 {
		return nil
	}
	suppliedArgs[0] = strings.ToLower(suppliedArgs[0])
	if suppliedArgs[0] == "run" || suppliedArgs[0] == "set-exec" {
		suppliedArgs = insertRunTacks(suppliedArgs)
	}
	args := []string{"--debug", "--work-path=" + workPath}
	args = append(args, suppliedArgs...)
	cmd := exec.Command(os.Args[0], args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Env = os.Environ()
	if suppliedArgs[0] == "script" {
		cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", nestedScriptEnvVar, workPath))
	}
	return cmd.Run()
}

func joinLines(script []string) []string {
	for i, line := range script {
		if strings.HasSuffix(line, `\`) && i != len(script)-1 {
			line = strings.TrimSuffix(line, `\`)
			script[i] = ""
			script[i+1] = line + " " + script[i+1]
		}
	}
	return script
}

func tokenizeLine(line string) ([]string, error) {
	var tokens []string
	buf := &bytes.Buffer{}
	inSingleQuoteBlock := false
	inDoubleQuoteBlock := false
	isEscaped := false
lineLoop:
	for _, char := range line {
		if isEscaped {
			buf.WriteRune(char)
			isEscaped = false
			continue
		}
		switch {
		case char == '\\':
			isEscaped = true
		case (char == ' ' || char == '	') && !inSingleQuoteBlock && !inDoubleQuoteBlock:
			if buf.Len() > 0 {
				tokens = append(tokens, buf.String())
				buf.Reset()
			}
		case char == '\'' && !inDoubleQuoteBlock:
			inSingleQuoteBlock = !inSingleQuoteBlock
		case char == '"' && !inSingleQuoteBlock:
			inDoubleQuoteBlock = !inDoubleQuoteBlock
		case char == '#' && !inSingleQuoteBlock && !inDoubleQuoteBlock:
			if buf.Len() > 0 {
				tokens = append(tokens, buf.String())
				buf.Reset()
			}
			break lineLoop
		default:
			buf.WriteRune(char)
		}
	}
	if inSingleQuoteBlock {
		return nil, errSingleQuote
	}
	if inDoubleQuoteBlock {
		return nil, errDoubleQuote
	}
	if isEscaped {
		return nil, errEscape
	}
	if buf.Len() > 0 {
		tokens = append(tokens, buf.String())
	}
	return tokens, nil
}

func insertRunTacks(tokens []string) []string {
	insertLocation := -1
	for i, tok := range tokens {
		if i == 0 {
			continue
		}
		if tok == "--" {
			return tokens
		}
		if tok[0] != '-' {
			insertLocation = i
			break
		}
	}
	if insertLocation == -1 {
		return tokens
	}
	newTokens := make([]string, insertLocation)
	copy(newTokens, tokens[:insertLocation])
	newTokens = append(newTokens, "--")
	newTokens = append(newTokens, tokens[insertLocation:]...)
	return newTokens
}
<commit_msg>script: error if end is detected in a script<commit_after>// Copyright 2016 The appc 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 main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"

	"github.com/spf13/cobra"
)

const (
	nestedScriptEnvVar = "ACBUILD_NESTED_SCRIPT"
)

var (
	errSingleQuote = fmt.Errorf("unterminated single quote block")
	errDoubleQuote = fmt.Errorf("unterminated double quote block")
	errEscape      = fmt.Errorf("ended with an escape")
	cmdScript      = &cobra.Command{
		Use:     "script SCRIPT_FILE",
		Short:   "Runs an acbuild script",
		Example: "acbuild script build-myapp.acb",
		Run:     runWrapper(runScript),
	}
)

func init() {
	cmdAcbuild.AddCommand(cmdScript)
}

func runScript(cmd *cobra.Command, args []string) (exit int) {
	if len(args) != 1 {
		cmd.Usage()
		return 1
	}

	scriptName := args[0]
	rawScript, err := ioutil.ReadFile(scriptName)
	if err != nil {
		stderr("script: %v", err)
		return getErrorCode(err)
	}

	if debug {
		stderr("Running script from %s", scriptName)
	}

	err = execScript(rawScript)
	if err != nil {
		stderr("script: %v", err)
		return getErrorCode(err)
	}
	return 0
}

func execScript(rawScript []byte) error {
	script := strings.Split(string(rawScript), "\n")
	for i, s := range script {
		s = strings.TrimSpace(s)
		script[i] = s

		if strings.HasPrefix(strings.ToLower(s), "run") && os.Geteuid() != 0 {
			return fmt.Errorf("scripts using the run subcommand must be run as root")
		}

		if strings.HasPrefix(strings.ToLower(s), "end") {
			return fmt.Errorf("calling end is unnecessary in a script, cleanup is done automatically")
		}
	}
	script = joinLines(script)

	var tmpDir string
	nestedScript := false
	if inheritedPath := os.Getenv(nestedScriptEnvVar); inheritedPath != "" {
		tmpDir = inheritedPath
		nestedScript = true
	} else {
		var err error
		tmpDir, err = ioutil.TempDir("", "acbuild")
		if err != nil {
			return err
		}
		defer os.RemoveAll(tmpDir)
		contextpath = tmpDir
	}

	for _, line := range script {
		if line == "" {
			continue
		}
		err := execACBuild(tmpDir, line)
		if err != nil {
			if !strings.HasPrefix(line, "begin") && !nestedScript {
				err1 := newACBuild().End()
				if err1 != nil {
					stderr("script: %v", err1)
				}
			}
			return err
		}
	}
	if !nestedScript {
		err := newACBuild().End()
		if err != nil {
			return err
		}
	}
	if debug {
		stderr("Script has been completed")
	}

	return nil
}

func execACBuild(workPath, line string) error {
	suppliedArgs, err := tokenizeLine(line)
	if err != nil {
		return err
	}
	if len(suppliedArgs) == 0 {
		return nil
	}
	suppliedArgs[0] = strings.ToLower(suppliedArgs[0])
	if suppliedArgs[0] == "run" || suppliedArgs[0] == "set-exec" {
		suppliedArgs = insertRunTacks(suppliedArgs)
	}
	args := []string{"--debug", "--work-path=" + workPath}
	args = append(args, suppliedArgs...)
	cmd := exec.Command(os.Args[0], args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Env = os.Environ()
	if suppliedArgs[0] == "script" {
		cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", nestedScriptEnvVar, workPath))
	}
	return cmd.Run()
}

func joinLines(script []string) []string {
	for i, line := range script {
		if strings.HasSuffix(line, `\`) && i != len(script)-1 {
			line = strings.TrimSuffix(line, `\`)
			script[i] = ""
			script[i+1] = line + " " + script[i+1]
		}
	}
	return script
}

func tokenizeLine(line string) ([]string, error) {
	var tokens []string
	buf := &bytes.Buffer{}
	inSingleQuoteBlock := false
	inDoubleQuoteBlock := false
	isEscaped := false
lineLoop:
	for _, char := range line {
		if isEscaped {
			buf.WriteRune(char)
			isEscaped = false
			continue
		}
		switch {
		case char == '\\':
			isEscaped = true
		case (char == ' ' || char == '	') && !inSingleQuoteBlock && !inDoubleQuoteBlock:
			if buf.Len() > 0 {
				tokens = append(tokens, buf.String())
				buf.Reset()
			}
		case char == '\'' && !inDoubleQuoteBlock:
			inSingleQuoteBlock = !inSingleQuoteBlock
		case char == '"' && !inSingleQuoteBlock:
			inDoubleQuoteBlock = !inDoubleQuoteBlock
		case char == '#' && !inSingleQuoteBlock && !inDoubleQuoteBlock:
			if buf.Len() > 0 {
				tokens = append(tokens, buf.String())
				buf.Reset()
			}
			break lineLoop
		default:
			buf.WriteRune(char)
		}
	}
	if inSingleQuoteBlock {
		return nil, errSingleQuote
	}
	if inDoubleQuoteBlock {
		return nil, errDoubleQuote
	}
	if isEscaped {
		return nil, errEscape
	}
	if buf.Len() > 0 {
		tokens = append(tokens, buf.String())
	}
	return tokens, nil
}

func insertRunTacks(tokens []string) []string {
	insertLocation := -1
	for i, tok := range tokens {
		if i == 0 {
			continue
		}
		if tok == "--" {
			return tokens
		}
		if tok[0] != '-' {
			insertLocation = i
			break
		}
	}
	if insertLocation == -1 {
		return tokens
	}
	newTokens := make([]string, insertLocation)
	copy(newTokens, tokens[:insertLocation])
	newTokens = append(newTokens, "--")
	newTokens = append(newTokens, tokens[insertLocation:]...)
	return newTokens
}
<|endoftext|>


<commit_before>// Copyright 2015 Luke Shumaker

package putil

import (
	"encoding/base64"
	"fmt"
	"maildir"
	"net/mail"
	"strings"
)

type RecipientBuilder []mail.Address

func (b RecipientBuilder) String() string {
	s := make([]string, len(b))
	for i, a := range b {
		s[i] = a.String()
	}
	return strings.Join(s, ", ")
}

type MessageBuilder struct {
	Maildir maildir.Maildir
	Headers map[string]string
	Body    string
}

func (b MessageBuilder) Done() {
	b.Headers["MIME-Version"] = "1.0"
	b.Headers["Content-Type"] = "text/plain; charset=\"utf-8\""
	b.Headers["Content-Transfer-Encoding"] = "base64"

	writer := b.Maildir.NewMail()
	for k, v := range b.Headers {
		fmt.Fprintf(writer, "%s: %s\r\n", k, v)
	}
	writer.Write([]byte("\r\n"))
	encoder := base64.NewEncoder(base64.StdEncoding, writer)
	encoder.Write([]byte(b.Body))
	encoder.Close()
	writer.Close()
	// TODO: Acknowledge, add to the database and such; probably
	// share code with periwinkle/email_handlers/email
}
<commit_msg>re-jigger putil.MailBuilder to add stuff to the postfix queue<commit_after>// Copyright 2015 Luke Shumaker

package putil

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"maildir"
	"net/mail"
	"net/smtp"
	"strings"
)

type RecipientBuilder []mail.Address

func (b RecipientBuilder) String() string {
	s := make([]string, len(b))
	for i, a := range b {
		s[i] = a.String()
	}
	return strings.Join(s, ", ")
}

type MessageBuilder struct {
	Maildir maildir.Maildir
	Headers map[string]string
	Body    string
}

func (b MessageBuilder) Done() {
	b.Headers["MIME-Version"] = "1.0"
	b.Headers["Content-Type"] = "text/plain; charset=\"utf-8\""
	b.Headers["Content-Transfer-Encoding"] = "base64"

	msg822 := []byte{}
	for k := range b.Headers {
		msg822 = append(msg822, []byte(fmt.Sprintf("%s: %s\r\n", k, b.Headers[k]))...)
	}
	msg822 = append(msg822, []byte("\r\n")...)

	var body bytes.Buffer
	encoder := base64.NewEncoder(base64.StdEncoding, &body)
	encoder.Write([]byte(b.Body))
	encoder.Close()
	msg822 = append(msg822, body.Bytes()...)

	to_addrs, err := mail.ParseAddressList(b.Headers["To"])
	if err != nil {
		panic(err) // FIXME
	}
	to_strs := make([]string, len(to_addrs))
	for i, addr := range to_addrs {
		to_strs[i] = addr.Address
	}

	if len(to_strs) > 0 {
		// send the message out
		err = smtp.SendMail("localhost:25",
			smtp.PlainAuth("", "", "", ""),
			b.Headers["From"],
			to_strs,
			msg822)
		if err != nil {
			panic(err) // FIXME
		}
	}
}
<|endoftext|>


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

// This file implements objsets.
//
// An objset is similar to a Scope but objset elements
// are identified by their unique id, instead of their
// object name.

package types2

// An objset is a set of objects identified by their unique id.
// The zero value for objset is a ready-to-use empty objset.
type objset map[string]Object // initialized lazily

// insert attempts to insert an object obj into objset s.
// If s already contains an alternative object alt with
// the same name, insert leaves s unchanged and returns alt.
// Otherwise it inserts obj and returns nil.
func (s *objset) insert(obj Object) Object {
	id := obj.Id()
	if alt := (*s)[id]; alt != nil {
		return alt
	}
	if *s == nil {
		*s = make(map[string]Object)
	}
	(*s)[id] = obj
	return nil
}
<commit_msg>[dev.typeparams] cmd/compile/internal/types: review of objset.go<commit_after>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file implements objsets.
//
// An objset is similar to a Scope but objset elements
// are identified by their unique id, instead of their
// object name.

package types2

// An objset is a set of objects identified by their unique id.
// The zero value for objset is a ready-to-use empty objset.
type objset map[string]Object // initialized lazily

// insert attempts to insert an object obj into objset s.
// If s already contains an alternative object alt with
// the same name, insert leaves s unchanged and returns alt.
// Otherwise it inserts obj and returns nil.
func (s *objset) insert(obj Object) Object {
	id := obj.Id()
	if alt := (*s)[id]; alt != nil {
		return alt
	}
	if *s == nil {
		*s = make(map[string]Object)
	}
	(*s)[id] = obj
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"math"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"rais/src/fakehttp"
	"rais/src/iiif"
	"strings"
	"testing"

	"github.com/uoregon-libraries/gopkg/assert"
	"github.com/uoregon-libraries/gopkg/logger"
)

func init() {
	Logger = logger.New(logger.Warn)
}

func rootDir() string {
	p, _ := os.Getwd()
	root, _ := filepath.Abs(p + "/../../../")
	return root
}

// Sets up everything necessary to test an IIIF request
func dorequestGeneric(path string, acceptLD bool, max constraint, fs *iiif.FeatureSet, t *testing.T) *fakehttp.ResponseWriter {
	u, _ := url.Parse("http://example.com/foo/bar")
	w := fakehttp.NewResponseWriter()
	reqPath := fmt.Sprintf("/foo/bar/%s", path)
	req, err := http.NewRequest("get", reqPath, strings.NewReader(""))
	req.RequestURI = reqPath

	if acceptLD {
		req.Header.Add("Accept", "application/ld+json")
	}

	if err != nil {
		t.Errorf("Unable to create fake request: %s", err)
	}
	h := NewImageHandler(rootDir())
	h.Maximums.Width = max.Width
	h.Maximums.Height = max.Height
	h.Maximums.Area = max.Area
	h.EnableIIIF(u)
	h.FeatureSet = fs
	h.IIIFRoute(w, req)

	return w
}

// Sets up everything necessary to test an IIIF request using level 1 support
func dorequest(path string, acceptLD bool, max constraint, t *testing.T) *fakehttp.ResponseWriter {
	return dorequestGeneric(path, acceptLD, max, iiif.FeatureSet1(), t)
}

// Sets up everything necessary to test an IIIF request using level 2 support
func dorequestl2(path string, acceptLD bool, max constraint, t *testing.T) *fakehttp.ResponseWriter {
	return dorequestGeneric(path, acceptLD, max, iiif.FeatureSet2(), t)
}

func request(path string, t *testing.T) *fakehttp.ResponseWriter {
	return dorequest(path, false, unlimited, t)
}

func requestLD(path string, t *testing.T) *fakehttp.ResponseWriter {
	return dorequest(path, true, unlimited, t)
}

func TestInfoHandler404(t *testing.T) {
	w := request("identifier/info.json", t)
	assert.Equal(404, w.StatusCode, "Invalid info request returns 404", t)
}

func TestInfoHandlerJSONOverride(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/info.json", t)
	assert.Equal(-1, w.StatusCode, "Valid info request doesn't explicitly set status code", t)
	var data iiif.Info
	json.Unmarshal(w.Output, &data)
	assert.Equal("http://iiif.io/api/image/2/level2.json", data.Profile.ConformanceURL, "Proper profile string", t)
	assert.Equal(800, data.Width, "JSON-decoded width", t)
	assert.Equal(400, data.Height, "JSON-decoded height", t)
	assert.Equal(512, data.Tiles[0].Width, "JSON-decoded tile width", t)
	assert.Equal(0, data.Tiles[0].Height, "JSON-decoded tile height", t)
	assert.Equal(2, len(data.Tiles[0].ScaleFactors), "1 scale factor exists", t)
	assert.Equal(1, data.Tiles[0].ScaleFactors[0], "First scale factor is 1", t)
	assert.Equal(2, data.Tiles[0].ScaleFactors[1], "Second scale factor is 1", t)
	assert.Equal("http://example.com/foo/bar/docker%2Fimages%2Ftestfile%2Ftest-world.jp2", data.ID, "JSON-decoded ID", t)
	assert.Equal(1, len(w.Headers["Content-Type"]), "Proper content type length", t)
	assert.Equal("application/json", w.Headers["Content-Type"][0], "Proper content type", t)
}

func TestInfoHandlerBuiltJSON(t *testing.T) {
	// We don't want to test the JSON override this time, so we use the symlink
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world-link.jp2/info.json", t)
	assert.Equal(-1, w.StatusCode, "Valid info request doesn't explicitly set status code", t)
	var data iiif.Info
	json.Unmarshal(w.Output, &data)
	assert.Equal("http://iiif.io/api/image/2/level1.json", data.Profile.ConformanceURL, "Proper profile string", t)
	assert.Equal(800, data.Width, "JSON-decoded width", t)
	assert.Equal(400, data.Height, "JSON-decoded height", t)
	assert.Equal(800, data.Tiles[0].Width, "JSON-decoded tile width", t)
	assert.Equal(400, data.Tiles[0].Height, "JSON-decoded tile height", t)
	assert.Equal(1, len(data.Tiles[0].ScaleFactors), "1 scale factor exists", t)
	assert.Equal(1, data.Tiles[0].ScaleFactors[0], "Scale factor is 1", t)
	assert.Equal("http://example.com/foo/bar/docker%2Fimages%2Ftestfile%2Ftest-world-link.jp2", data.ID, "JSON-decoded ID", t)
	assert.Equal(1, len(w.Headers["Content-Type"]), "Proper content type length", t)
	assert.Equal("application/json", w.Headers["Content-Type"][0], "Proper content type", t)
}

func TestInfoHandlerLD(t *testing.T) {
	w := requestLD("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/info.json", t)
	assert.Equal(-1, w.StatusCode, "Valid info request doesn't explicitly set status code", t)
	assert.Equal(1, len(w.Headers["Content-Type"]), "Proper content type length", t)
	assert.Equal("application/ld+json", w.Headers["Content-Type"][0], "Proper content type", t)
}

func TestInfoRedirect(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2", t)
	assert.Equal(303, w.StatusCode, "Base URL redirects to info request", t)
	locHeader := w.Headers["Location"]
	assert.Equal(1, len(locHeader), "There's only 1 location header", t)
	assert.Equal("/foo/bar/docker%2Fimages%2Ftestfile%2Ftest-world.jp2/info.json", locHeader[0], "Location header", t)
}

// TestInfoMaxSize verifies that when the image is bigger than the handler's
// maximums, values are present in the info profile
func TestInfoMaxSize(t *testing.T) {
	w := dorequest("docker%2Fimages%2Ftestfile%2Ftest-world-link.jp2/info.json", false, constraint{60, 80, 480}, t)
	var data iiif.Info
	json.Unmarshal(w.Output, &data)
	assert.Equal(60, data.Profile.MaxWidth, "JSON-decoded max width", t)
	assert.Equal(80, data.Profile.MaxHeight, "JSON-decoded max height", t)
	assert.Equal(int64(480), data.Profile.MaxArea, "JSON-decoded max area", t)

	// Make sure those profile variables are in the output data
	assert.True(bytes.Contains(w.Output, []byte("maxWidth")), "maxWidth", t)
	assert.True(bytes.Contains(w.Output, []byte("maxHeight")), "maxHeight", t)
	assert.True(bytes.Contains(w.Output, []byte("maxArea")), "maxArea", t)
}

// TestInfoNoMaxSize verifies that when the image is smaller than the handler's
// maximums, values are not present in the info profile
func TestInfoNoMaxSize(t *testing.T) {
	w := dorequest("docker%2Fimages%2Ftestfile%2Ftest-world-link.jp2/info.json", false, constraint{6000, 8000, 4800000}, t)
	var data iiif.Info
	json.Unmarshal(w.Output, &data)
	assert.Equal(0, data.Profile.MaxWidth, "JSON-decoded width", t)
	assert.Equal(0, data.Profile.MaxHeight, "JSON-decoded height", t)
	assert.Equal(int64(0), data.Profile.MaxArea, "JSON-decoded height", t)

	// Make sure those profile variables aren't in the output data at all
	assert.False(bytes.Contains(w.Output, []byte("maxWidth")), "no maxWidth", t)
	assert.False(bytes.Contains(w.Output, []byte("maxHeight")), "no maxHeight", t)
	assert.False(bytes.Contains(w.Output, []byte("maxArea")), "no maxArea", t)
}

func TestCommandHandler404(t *testing.T) {
	w := request("identifier/full/full/0/default.jpg", t)
	assert.Equal(404, w.StatusCode, "Valid command on nonexistent file returns 404", t)
}

func TestCommandHandlerInvalidFile(t *testing.T) {
	w := request("Makefile/full/full/0/default.jpg", t)
	assert.Equal(500, w.StatusCode, "Valid command on non-image file returns 500", t)
}

func TestInvalidRequest(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/foo/bar", t)
	assert.Equal(400, w.StatusCode, "Bad request is reported as such", t)
}

func TestUnsupportedRequest(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/pct:10,10,80,80/full/0/default.jpg", t)
	assert.Equal(501, w.StatusCode, "Unsupported operation gets reported as a 501 (not implemented)", t)
}

func TestCommandHandler(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/10,10,80,80/full/0/default.jpg", t)
	assert.Equal(-1, w.StatusCode, "Valid command request doesn't explicitly set status code", t)
}

func TestCommandHandlerInvalidSize(t *testing.T) {
	img := "docker%2Fimages%2Ftestfile%2Ftest-world.jp2/pct:10,10,80,80/full/0/default.jpg"
	areaConstraint := constraint{math.MaxInt32, math.MaxInt32, 480}
	wConstraint := constraint{20, math.MaxInt32, math.MaxInt64}
	hConstraint := constraint{math.MaxInt32, 20, math.MaxInt64}

	// For sanity let's make sure the request has no errors when we don't specify
	// any constraints
	w := dorequestl2(img, false, unlimited, t)
	assert.Equal(-1, w.StatusCode, "Supported request with valid size gets 200", t)

	w = dorequestl2(img, false, wConstraint, t)
	assert.Equal(501, w.StatusCode, "Status code when width is too large", t)
	w = dorequestl2(img, false, hConstraint, t)
	assert.Equal(501, w.StatusCode, "Status code when height is too large", t)
	w = dorequestl2(img, false, areaConstraint, t)
	assert.Equal(501, w.StatusCode, "Status code when area is too large", t)
}
<commit_msg>rais-server: fix handler test<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"math"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"rais/src/fakehttp"
	"rais/src/iiif"
	"strings"
	"testing"

	"github.com/uoregon-libraries/gopkg/assert"
	"github.com/uoregon-libraries/gopkg/logger"
)

func init() {
	Logger = logger.New(logger.Warn)
}

func rootDir() string {
	p, _ := os.Getwd()
	root, _ := filepath.Abs(p + "/../../../")
	return root
}

// Sets up everything necessary to test an IIIF request
func dorequestGeneric(path string, acceptLD bool, max constraint, fs *iiif.FeatureSet, t *testing.T) *fakehttp.ResponseWriter {
	u, _ := url.Parse("http://example.com/foo/bar")
	w := fakehttp.NewResponseWriter()
	reqPath := fmt.Sprintf("/foo/bar/%s", path)
	req, err := http.NewRequest("get", reqPath, strings.NewReader(""))
	req.RequestURI = reqPath

	if acceptLD {
		req.Header.Add("Accept", "application/ld+json")
	}

	if err != nil {
		t.Errorf("Unable to create fake request: %s", err)
	}
	h := NewImageHandler(rootDir())
	h.Maximums.Width = max.Width
	h.Maximums.Height = max.Height
	h.Maximums.Area = max.Area
	h.EnableIIIF(u)
	h.FeatureSet = fs
	h.IIIFRoute(w, req)

	return w
}

// Sets up everything necessary to test an IIIF request using level 1 support
func dorequest(path string, acceptLD bool, max constraint, t *testing.T) *fakehttp.ResponseWriter {
	return dorequestGeneric(path, acceptLD, max, iiif.FeatureSet1(), t)
}

// Sets up everything necessary to test an IIIF request using level 2 support
func dorequestl2(path string, acceptLD bool, max constraint, t *testing.T) *fakehttp.ResponseWriter {
	return dorequestGeneric(path, acceptLD, max, iiif.FeatureSet2(), t)
}

func request(path string, t *testing.T) *fakehttp.ResponseWriter {
	return dorequest(path, false, unlimited, t)
}

func requestLD(path string, t *testing.T) *fakehttp.ResponseWriter {
	return dorequest(path, true, unlimited, t)
}

func TestInfoHandler404(t *testing.T) {
	w := request("identifier/info.json", t)
	assert.Equal(404, w.StatusCode, "Invalid info request returns 404", t)
}

func TestInfoHandlerJSONOverride(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/info.json", t)
	assert.Equal(-1, w.StatusCode, "Valid info request doesn't explicitly set status code", t)
	var data iiif.Info
	json.Unmarshal(w.Output, &data)
	assert.Equal("http://iiif.io/api/image/2/level2.json", data.Profile.ConformanceURL, "Proper profile string", t)
	assert.Equal(800, data.Width, "JSON-decoded width", t)
	assert.Equal(400, data.Height, "JSON-decoded height", t)
	assert.Equal(512, data.Tiles[0].Width, "JSON-decoded tile width", t)
	assert.Equal(0, data.Tiles[0].Height, "JSON-decoded tile height", t)
	assert.Equal(2, len(data.Tiles[0].ScaleFactors), "1 scale factor exists", t)
	assert.Equal(1, data.Tiles[0].ScaleFactors[0], "First scale factor is 1", t)
	assert.Equal(2, data.Tiles[0].ScaleFactors[1], "Second scale factor is 1", t)
	assert.Equal("http://example.com/foo/bar/docker%2Fimages%2Ftestfile%2Ftest-world.jp2", data.ID, "JSON-decoded ID", t)
	assert.Equal(1, len(w.Headers["Content-Type"]), "Proper content type length", t)
	assert.Equal("application/json", w.Headers["Content-Type"][0], "Proper content type", t)
}

func TestInfoHandlerBuiltJSON(t *testing.T) {
	// We don't want to test the JSON override this time, so we use the symlink
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world-link.jp2/info.json", t)
	assert.Equal(-1, w.StatusCode, "Valid info request doesn't explicitly set status code", t)
	var data iiif.Info
	json.Unmarshal(w.Output, &data)
	assert.Equal("http://iiif.io/api/image/2/level1.json", data.Profile.ConformanceURL, "Proper profile string", t)
	assert.Equal(800, data.Width, "JSON-decoded width", t)
	assert.Equal(400, data.Height, "JSON-decoded height", t)
	assert.Equal(800, data.Tiles[0].Width, "JSON-decoded tile width", t)
	assert.Equal(400, data.Tiles[0].Height, "JSON-decoded tile height", t)
	assert.Equal(1, len(data.Tiles[0].ScaleFactors), "1 scale factor exists", t)
	assert.Equal(1, data.Tiles[0].ScaleFactors[0], "Scale factor is 1", t)
	assert.Equal("http://example.com/foo/bar/docker%2Fimages%2Ftestfile%2Ftest-world-link.jp2", data.ID, "JSON-decoded ID", t)
	assert.Equal(1, len(w.Headers["Content-Type"]), "Proper content type length", t)
	assert.Equal("application/json", w.Headers["Content-Type"][0], "Proper content type", t)
}

func TestInfoHandlerLD(t *testing.T) {
	w := requestLD("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/info.json", t)
	assert.Equal(-1, w.StatusCode, "Valid info request doesn't explicitly set status code", t)
	assert.Equal(1, len(w.Headers["Content-Type"]), "Proper content type length", t)
	assert.Equal("application/ld+json", w.Headers["Content-Type"][0], "Proper content type", t)
}

func TestInfoRedirect(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2", t)
	assert.Equal(303, w.StatusCode, "Base URL redirects to info request", t)
	locHeader := w.Headers["Location"]
	assert.Equal(1, len(locHeader), "There's only 1 location header", t)
	assert.Equal("/foo/bar/docker%2Fimages%2Ftestfile%2Ftest-world.jp2/info.json", locHeader[0], "Location header", t)
}

// TestInfoMaxSize verifies that when the image is bigger than the handler's
// maximums, values are present in the info profile
func TestInfoMaxSize(t *testing.T) {
	w := dorequest("docker%2Fimages%2Ftestfile%2Ftest-world-link.jp2/info.json", false, constraint{60, 80, 480}, t)
	var data iiif.Info
	json.Unmarshal(w.Output, &data)
	assert.Equal(60, data.Profile.MaxWidth, "JSON-decoded max width", t)
	assert.Equal(80, data.Profile.MaxHeight, "JSON-decoded max height", t)
	assert.Equal(int64(480), data.Profile.MaxArea, "JSON-decoded max area", t)

	// Make sure those profile variables are in the output data
	assert.True(bytes.Contains(w.Output, []byte("maxWidth")), "maxWidth", t)
	assert.True(bytes.Contains(w.Output, []byte("maxHeight")), "maxHeight", t)
	assert.True(bytes.Contains(w.Output, []byte("maxArea")), "maxArea", t)
}

// TestInfoNoMaxSize verifies that when the image is smaller than the handler's
// maximums, values are not present in the info profile
func TestInfoNoMaxSize(t *testing.T) {
	w := dorequest("docker%2Fimages%2Ftestfile%2Ftest-world-link.jp2/info.json", false, constraint{6000, 8000, 4800000}, t)
	var data iiif.Info
	json.Unmarshal(w.Output, &data)
	assert.Equal(0, data.Profile.MaxWidth, "JSON-decoded width", t)
	assert.Equal(0, data.Profile.MaxHeight, "JSON-decoded height", t)
	assert.Equal(int64(0), data.Profile.MaxArea, "JSON-decoded height", t)

	// Make sure those profile variables aren't in the output data at all
	assert.False(bytes.Contains(w.Output, []byte("maxWidth")), "no maxWidth", t)
	assert.False(bytes.Contains(w.Output, []byte("maxHeight")), "no maxHeight", t)
	assert.False(bytes.Contains(w.Output, []byte("maxArea")), "no maxArea", t)
}

func TestCommandHandler404(t *testing.T) {
	w := request("identifier/full/full/0/default.jpg", t)
	assert.Equal(404, w.StatusCode, "Valid command on nonexistent file returns 404", t)
}

func TestCommandHandlerInvalidFile(t *testing.T) {
	w := request("Makefile/full/full/0/default.jpg", t)
	assert.Equal(500, w.StatusCode, "Valid command on non-image file returns 500", t)
}

func TestInvalidRequest(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/foo/bar", t)
	assert.Equal(400, w.StatusCode, "Bad request is reported as such", t)
}

func TestUnsupportedRequest(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/pct:10,10,80,80/full/0/default.jpg", t)
	assert.Equal(501, w.StatusCode, "Unsupported operation gets reported as a 501 (not implemented)", t)
}

func TestCommandHandler(t *testing.T) {
	w := request("docker%2Fimages%2Ftestfile%2Ftest-world.jp2/10,10,80,80/full/0/default.jpg", t)
	assert.Equal(-1, w.StatusCode, "Valid command request doesn't explicitly set status code", t)
}

func TestCommandHandlerInvalidSize(t *testing.T) {
	img := "docker%2Fimages%2Ftestfile%2Ftest-world-link.jp2/pct:10,10,80,80/full/0/default.jpg"
	areaConstraint := constraint{math.MaxInt32, math.MaxInt32, 480}
	wConstraint := constraint{20, math.MaxInt32, math.MaxInt64}
	hConstraint := constraint{math.MaxInt32, 20, math.MaxInt64}

	// For sanity let's make sure the request has no errors when we don't specify
	// any constraints
	w := dorequestl2(img, false, unlimited, t)
	assert.Equal(-1, w.StatusCode, "Supported request with valid size doesn't set status code", t)

	w = dorequestl2(img, false, wConstraint, t)
	assert.Equal(501, w.StatusCode, "Status code when width is too large", t)
	w = dorequestl2(img, false, hConstraint, t)
	assert.Equal(501, w.StatusCode, "Status code when height is too large", t)
	w = dorequestl2(img, false, areaConstraint, t)
	assert.Equal(501, w.StatusCode, "Status code when area is too large", t)
}
<|endoftext|>


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

// The list package implements a doubly linked list.
package list

// Element is an element in the linked list.
type Element struct {
	// Next and previous pointers in the doubly-linked list of elements.
	// The front of the list has prev = nil, and the back has next = nil.
	next, prev *Element

	// The list to which this element belongs.
	list *List

	// The contents of this list element.
	Value interface{}
}

// Next returns the next list element or nil.
func (e *Element) Next() *Element { return e.next }

// Prev returns the previous list element or nil.
func (e *Element) Prev() *Element { return e.prev }

// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
type List struct {
	front, back *Element
	len         int
}

// Init initializes or clears a List.
func (l *List) Init() *List {
	l.front = nil
	l.back = nil
	l.len = 0
	return l
}

// New returns an initialized list.
func New() *List { return new(List) }

// Front returns the first element in the list.
func (l *List) Front() *Element { return l.front }

// Back returns the last element in the list.
func (l *List) Back() *Element { return l.back }

// Remove removes the element from the list.
func (l *List) Remove(e *Element) {
	l.remove(e)
	e.list = nil // do what remove does not
}

// remove the element from the list, but do not clear the Element's list field.
// This is so that other List methods may use remove when relocating Elements
// without needing to restore the list field.
func (l *List) remove(e *Element) {
	if e.list != l {
		return
	}
	if e.prev == nil {
		l.front = e.next
	} else {
		e.prev.next = e.next
	}
	if e.next == nil {
		l.back = e.prev
	} else {
		e.next.prev = e.prev
	}

	e.prev = nil
	e.next = nil
	l.len--
}

func (l *List) insertBefore(e *Element, mark *Element) {
	if mark.prev == nil {
		// new front of the list
		l.front = e
	} else {
		mark.prev.next = e
	}
	e.prev = mark.prev
	mark.prev = e
	e.next = mark
	l.len++
}

func (l *List) insertAfter(e *Element, mark *Element) {
	if mark.next == nil {
		// new back of the list
		l.back = e
	} else {
		mark.next.prev = e
	}
	e.next = mark.next
	mark.next = e
	e.prev = mark
	l.len++
}

func (l *List) insertFront(e *Element) {
	if l.front == nil {
		// empty list
		l.front, l.back = e, e
		e.prev, e.next = nil, nil
		l.len = 1
		return
	}
	l.insertBefore(e, l.front)
}

func (l *List) insertBack(e *Element) {
	if l.back == nil {
		// empty list
		l.front, l.back = e, e
		e.prev, e.next = nil, nil
		l.len = 1
		return
	}
	l.insertAfter(e, l.back)
}

// PushFront inserts the value at the front of the list and returns a new Element containing the value.
func (l *List) PushFront(value interface{}) *Element {
	e := &Element{nil, nil, l, value}
	l.insertFront(e)
	return e
}

// PushBack inserts the value at the back of the list and returns a new Element containing the value.
func (l *List) PushBack(value interface{}) *Element {
	e := &Element{nil, nil, l, value}
	l.insertBack(e)
	return e
}

// InsertBefore inserts the value immediately before mark and returns a new Element containing the value.
func (l *List) InsertBefore(value interface{}, mark *Element) *Element {
	if mark.list != l {
		return nil
	}
	e := &Element{nil, nil, l, value}
	l.insertBefore(e, mark)
	return e
}

// InsertAfter inserts the value immediately after mark and returns a new Element containing the value.
func (l *List) InsertAfter(value interface{}, mark *Element) *Element {
	if mark.list != l {
		return nil
	}
	e := &Element{nil, nil, l, value}
	l.insertAfter(e, mark)
	return e
}

// MoveToFront moves the element to the front of the list.
func (l *List) MoveToFront(e *Element) {
	if e.list != l || l.front == e {
		return
	}
	l.remove(e)
	l.insertFront(e)
}

// MoveToBack moves the element to the back of the list.
func (l *List) MoveToBack(e *Element) {
	if e.list != l || l.back == e {
		return
	}
	l.remove(e)
	l.insertBack(e)
}

// Len returns the number of elements in the list.
func (l *List) Len() int { return l.len }

// PushBackList inserts each element of ol at the back of the list.
func (l *List) PushBackList(ol *List) {
	last := ol.Back()
	for e := ol.Front(); e != nil; e = e.Next() {
		l.PushBack(e.Value)
		if e == last {
			break
		}
	}
}

// PushFrontList inserts each element of ol at the front of the list. The ordering of the passed list is preserved.
func (l *List) PushFrontList(ol *List) {
	first := ol.Front()
	for e := ol.Back(); e != nil; e = e.Prev() {
		l.PushFront(e.Value)
		if e == first {
			break
		}
	}
}
<commit_msg>container/list: document iteration<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// The list package implements a doubly linked list.
//
// To iterate over a list (where l is a *List):
//	for e := l.Front(); e != nil; e = e.Next() {
//		// do something with e.Value
//	}
//
package list

// Element is an element in the linked list.
type Element struct {
	// Next and previous pointers in the doubly-linked list of elements.
	// The front of the list has prev = nil, and the back has next = nil.
	next, prev *Element

	// The list to which this element belongs.
	list *List

	// The contents of this list element.
	Value interface{}
}

// Next returns the next list element or nil.
func (e *Element) Next() *Element { return e.next }

// Prev returns the previous list element or nil.
func (e *Element) Prev() *Element { return e.prev }

// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
type List struct {
	front, back *Element
	len         int
}

// Init initializes or clears a List.
func (l *List) Init() *List {
	l.front = nil
	l.back = nil
	l.len = 0
	return l
}

// New returns an initialized list.
func New() *List { return new(List) }

// Front returns the first element in the list.
func (l *List) Front() *Element { return l.front }

// Back returns the last element in the list.
func (l *List) Back() *Element { return l.back }

// Remove removes the element from the list.
func (l *List) Remove(e *Element) {
	l.remove(e)
	e.list = nil // do what remove does not
}

// remove the element from the list, but do not clear the Element's list field.
// This is so that other List methods may use remove when relocating Elements
// without needing to restore the list field.
func (l *List) remove(e *Element) {
	if e.list != l {
		return
	}
	if e.prev == nil {
		l.front = e.next
	} else {
		e.prev.next = e.next
	}
	if e.next == nil {
		l.back = e.prev
	} else {
		e.next.prev = e.prev
	}

	e.prev = nil
	e.next = nil
	l.len--
}

func (l *List) insertBefore(e *Element, mark *Element) {
	if mark.prev == nil {
		// new front of the list
		l.front = e
	} else {
		mark.prev.next = e
	}
	e.prev = mark.prev
	mark.prev = e
	e.next = mark
	l.len++
}

func (l *List) insertAfter(e *Element, mark *Element) {
	if mark.next == nil {
		// new back of the list
		l.back = e
	} else {
		mark.next.prev = e
	}
	e.next = mark.next
	mark.next = e
	e.prev = mark
	l.len++
}

func (l *List) insertFront(e *Element) {
	if l.front == nil {
		// empty list
		l.front, l.back = e, e
		e.prev, e.next = nil, nil
		l.len = 1
		return
	}
	l.insertBefore(e, l.front)
}

func (l *List) insertBack(e *Element) {
	if l.back == nil {
		// empty list
		l.front, l.back = e, e
		e.prev, e.next = nil, nil
		l.len = 1
		return
	}
	l.insertAfter(e, l.back)
}

// PushFront inserts the value at the front of the list and returns a new Element containing the value.
func (l *List) PushFront(value interface{}) *Element {
	e := &Element{nil, nil, l, value}
	l.insertFront(e)
	return e
}

// PushBack inserts the value at the back of the list and returns a new Element containing the value.
func (l *List) PushBack(value interface{}) *Element {
	e := &Element{nil, nil, l, value}
	l.insertBack(e)
	return e
}

// InsertBefore inserts the value immediately before mark and returns a new Element containing the value.
func (l *List) InsertBefore(value interface{}, mark *Element) *Element {
	if mark.list != l {
		return nil
	}
	e := &Element{nil, nil, l, value}
	l.insertBefore(e, mark)
	return e
}

// InsertAfter inserts the value immediately after mark and returns a new Element containing the value.
func (l *List) InsertAfter(value interface{}, mark *Element) *Element {
	if mark.list != l {
		return nil
	}
	e := &Element{nil, nil, l, value}
	l.insertAfter(e, mark)
	return e
}

// MoveToFront moves the element to the front of the list.
func (l *List) MoveToFront(e *Element) {
	if e.list != l || l.front == e {
		return
	}
	l.remove(e)
	l.insertFront(e)
}

// MoveToBack moves the element to the back of the list.
func (l *List) MoveToBack(e *Element) {
	if e.list != l || l.back == e {
		return
	}
	l.remove(e)
	l.insertBack(e)
}

// Len returns the number of elements in the list.
func (l *List) Len() int { return l.len }

// PushBackList inserts each element of ol at the back of the list.
func (l *List) PushBackList(ol *List) {
	last := ol.Back()
	for e := ol.Front(); e != nil; e = e.Next() {
		l.PushBack(e.Value)
		if e == last {
			break
		}
	}
}

// PushFrontList inserts each element of ol at the front of the list. The ordering of the passed list is preserved.
func (l *List) PushFrontList(ol *List) {
	first := ol.Front()
	for e := ol.Back(); e != nil; e = e.Prev() {
		l.PushFront(e.Value)
		if e == first {
			break
		}
	}
}
<|endoftext|>


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

package filepath

import (
	"os"
	"sort"
	"strings"
	"utf8"
)

var ErrBadPattern = os.NewError("syntax error in pattern")

// Match returns true if name matches the shell file name pattern.
// The pattern syntax is:
//
//	pattern:
//		{ term }
//	term:
//		'*'         matches any sequence of non-Separator characters
//		'?'         matches any single non-Separator character
//		'[' [ '^' ] { character-range } ']'
//		            character class (must be non-empty)
//		c           matches character c (c != '*', '?', '\\', '[')
//		'\\' c      matches character c
//
//	character-range:
//		c           matches character c (c != '\\', '-', ']')
//		'\\' c      matches character c
//		lo '-' hi   matches character c for lo <= c <= hi
//
// Match requires pattern to match all of name, not just a substring.
// The only possible error return is when pattern is malformed.
//
func Match(pattern, name string) (matched bool, err os.Error) {
Pattern:
	for len(pattern) > 0 {
		var star bool
		var chunk string
		star, chunk, pattern = scanChunk(pattern)
		if star && chunk == "" {
			// Trailing * matches rest of string unless it has a /.
			return strings.Index(name, string(Separator)) < 0, nil
		}
		// Look for match at current position.
		t, ok, err := matchChunk(chunk, name)
		// if we're the last chunk, make sure we've exhausted the name
		// otherwise we'll give a false result even if we could still match
		// using the star
		if ok && (len(t) == 0 || len(pattern) > 0) {
			name = t
			continue
		}
		if err != nil {
			return false, err
		}
		if star {
			// Look for match skipping i+1 bytes.
			// Cannot skip /.
			for i := 0; i < len(name) && name[i] != Separator; i++ {
				t, ok, err := matchChunk(chunk, name[i+1:])
				if ok {
					// if we're the last chunk, make sure we exhausted the name
					if len(pattern) == 0 && len(t) > 0 {
						continue
					}
					name = t
					continue Pattern
				}
				if err != nil {
					return false, err
				}
			}
		}
		return false, nil
	}
	return len(name) == 0, nil
}

// scanChunk gets the next segment of pattern, which is a non-star string
// possibly preceded by a star.
func scanChunk(pattern string) (star bool, chunk, rest string) {
	for len(pattern) > 0 && pattern[0] == '*' {
		pattern = pattern[1:]
		star = true
	}
	inrange := false
	var i int
Scan:
	for i = 0; i < len(pattern); i++ {
		switch pattern[i] {
		case '\\':
			// error check handled in matchChunk: bad pattern.
			if i+1 < len(pattern) {
				i++
			}
		case '[':
			inrange = true
		case ']':
			inrange = false
		case '*':
			if !inrange {
				break Scan
			}
		}
	}
	return star, pattern[0:i], pattern[i:]
}

// matchChunk checks whether chunk matches the beginning of s.
// If so, it returns the remainder of s (after the match).
// Chunk is all single-character operators: literals, char classes, and ?.
func matchChunk(chunk, s string) (rest string, ok bool, err os.Error) {
	for len(chunk) > 0 {
		if len(s) == 0 {
			return
		}
		switch chunk[0] {
		case '[':
			// character class
			r, n := utf8.DecodeRuneInString(s)
			s = s[n:]
			chunk = chunk[1:]
			// possibly negated
			notNegated := true
			if len(chunk) > 0 && chunk[0] == '^' {
				notNegated = false
				chunk = chunk[1:]
			}
			// parse all ranges
			match := false
			nrange := 0
			for {
				if len(chunk) > 0 && chunk[0] == ']' && nrange > 0 {
					chunk = chunk[1:]
					break
				}
				var lo, hi int
				if lo, chunk, err = getEsc(chunk); err != nil {
					return
				}
				hi = lo
				if chunk[0] == '-' {
					if hi, chunk, err = getEsc(chunk[1:]); err != nil {
						return
					}
				}
				if lo <= r && r <= hi {
					match = true
				}
				nrange++
			}
			if match != notNegated {
				return
			}

		case '?':
			if s[0] == Separator {
				return
			}
			_, n := utf8.DecodeRuneInString(s)
			s = s[n:]
			chunk = chunk[1:]

		case '\\':
			chunk = chunk[1:]
			if len(chunk) == 0 {
				err = ErrBadPattern
				return
			}
			fallthrough

		default:
			if chunk[0] != s[0] {
				return
			}
			s = s[1:]
			chunk = chunk[1:]
		}
	}
	return s, true, nil
}

// getEsc gets a possibly-escaped character from chunk, for a character class.
func getEsc(chunk string) (r int, nchunk string, err os.Error) {
	if len(chunk) == 0 || chunk[0] == '-' || chunk[0] == ']' {
		err = ErrBadPattern
		return
	}
	if chunk[0] == '\\' {
		chunk = chunk[1:]
		if len(chunk) == 0 {
			err = ErrBadPattern
			return
		}
	}
	r, n := utf8.DecodeRuneInString(chunk)
	if r == utf8.RuneError && n == 1 {
		err = ErrBadPattern
	}
	nchunk = chunk[n:]
	if len(nchunk) == 0 {
		err = ErrBadPattern
	}
	return
}

// Glob returns the names of all files matching pattern or nil
// if there is no matching file. The syntax of patterns is the same
// as in Match. The pattern may describe hierarchical names such as
// /usr/*/bin/ed (assuming the Separator is '/').
//
func Glob(pattern string) (matches []string) {
	if !hasMeta(pattern) {
		if _, err := os.Stat(pattern); err == nil {
			return []string{pattern}
		}
		return nil
	}

	dir, file := Split(pattern)
	switch dir {
	case "":
		dir = "."
	case string(Separator):
		// nothing
	default:
		dir = dir[0 : len(dir)-1] // chop off trailing separator
	}

	if hasMeta(dir) {
		for _, d := range Glob(dir) {
			matches = glob(d, file, matches)
		}
	} else {
		return glob(dir, file, nil)
	}
	return matches
}

// glob searches for files matching pattern in the directory dir
// and appends them to matches.
func glob(dir, pattern string, matches []string) []string {
	fi, err := os.Stat(dir)
	if err != nil {
		return nil
	}
	if !fi.IsDirectory() {
		return matches
	}
	d, err := os.Open(dir, os.O_RDONLY, 0666)
	if err != nil {
		return nil
	}
	defer d.Close()

	names, err := d.Readdirnames(-1)
	if err != nil {
		return nil
	}
	sort.SortStrings(names)

	for _, n := range names {
		matched, err := Match(pattern, n)
		if err != nil {
			return matches
		}
		if matched {
			matches = append(matches, Join(dir, n))
		}
	}
	return matches
}

// hasMeta returns true if path contains any of the magic characters
// recognized by Match.
func hasMeta(path string) bool {
	// TODO(niemeyer): Should other magic characters be added here?
	return strings.IndexAny(path, "*?[") >= 0
}
<commit_msg>path/filepath.Glob: don't drop known matches on error. Fixes issue 1610.<commit_after>// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package filepath

import (
	"os"
	"sort"
	"strings"
	"utf8"
)

var ErrBadPattern = os.NewError("syntax error in pattern")

// Match returns true if name matches the shell file name pattern.
// The pattern syntax is:
//
//	pattern:
//		{ term }
//	term:
//		'*'         matches any sequence of non-Separator characters
//		'?'         matches any single non-Separator character
//		'[' [ '^' ] { character-range } ']'
//		            character class (must be non-empty)
//		c           matches character c (c != '*', '?', '\\', '[')
//		'\\' c      matches character c
//
//	character-range:
//		c           matches character c (c != '\\', '-', ']')
//		'\\' c      matches character c
//		lo '-' hi   matches character c for lo <= c <= hi
//
// Match requires pattern to match all of name, not just a substring.
// The only possible error return is when pattern is malformed.
//
func Match(pattern, name string) (matched bool, err os.Error) {
Pattern:
	for len(pattern) > 0 {
		var star bool
		var chunk string
		star, chunk, pattern = scanChunk(pattern)
		if star && chunk == "" {
			// Trailing * matches rest of string unless it has a /.
			return strings.Index(name, string(Separator)) < 0, nil
		}
		// Look for match at current position.
		t, ok, err := matchChunk(chunk, name)
		// if we're the last chunk, make sure we've exhausted the name
		// otherwise we'll give a false result even if we could still match
		// using the star
		if ok && (len(t) == 0 || len(pattern) > 0) {
			name = t
			continue
		}
		if err != nil {
			return false, err
		}
		if star {
			// Look for match skipping i+1 bytes.
			// Cannot skip /.
			for i := 0; i < len(name) && name[i] != Separator; i++ {
				t, ok, err := matchChunk(chunk, name[i+1:])
				if ok {
					// if we're the last chunk, make sure we exhausted the name
					if len(pattern) == 0 && len(t) > 0 {
						continue
					}
					name = t
					continue Pattern
				}
				if err != nil {
					return false, err
				}
			}
		}
		return false, nil
	}
	return len(name) == 0, nil
}

// scanChunk gets the next segment of pattern, which is a non-star string
// possibly preceded by a star.
func scanChunk(pattern string) (star bool, chunk, rest string) {
	for len(pattern) > 0 && pattern[0] == '*' {
		pattern = pattern[1:]
		star = true
	}
	inrange := false
	var i int
Scan:
	for i = 0; i < len(pattern); i++ {
		switch pattern[i] {
		case '\\':
			// error check handled in matchChunk: bad pattern.
			if i+1 < len(pattern) {
				i++
			}
		case '[':
			inrange = true
		case ']':
			inrange = false
		case '*':
			if !inrange {
				break Scan
			}
		}
	}
	return star, pattern[0:i], pattern[i:]
}

// matchChunk checks whether chunk matches the beginning of s.
// If so, it returns the remainder of s (after the match).
// Chunk is all single-character operators: literals, char classes, and ?.
func matchChunk(chunk, s string) (rest string, ok bool, err os.Error) {
	for len(chunk) > 0 {
		if len(s) == 0 {
			return
		}
		switch chunk[0] {
		case '[':
			// character class
			r, n := utf8.DecodeRuneInString(s)
			s = s[n:]
			chunk = chunk[1:]
			// possibly negated
			notNegated := true
			if len(chunk) > 0 && chunk[0] == '^' {
				notNegated = false
				chunk = chunk[1:]
			}
			// parse all ranges
			match := false
			nrange := 0
			for {
				if len(chunk) > 0 && chunk[0] == ']' && nrange > 0 {
					chunk = chunk[1:]
					break
				}
				var lo, hi int
				if lo, chunk, err = getEsc(chunk); err != nil {
					return
				}
				hi = lo
				if chunk[0] == '-' {
					if hi, chunk, err = getEsc(chunk[1:]); err != nil {
						return
					}
				}
				if lo <= r && r <= hi {
					match = true
				}
				nrange++
			}
			if match != notNegated {
				return
			}

		case '?':
			if s[0] == Separator {
				return
			}
			_, n := utf8.DecodeRuneInString(s)
			s = s[n:]
			chunk = chunk[1:]

		case '\\':
			chunk = chunk[1:]
			if len(chunk) == 0 {
				err = ErrBadPattern
				return
			}
			fallthrough

		default:
			if chunk[0] != s[0] {
				return
			}
			s = s[1:]
			chunk = chunk[1:]
		}
	}
	return s, true, nil
}

// getEsc gets a possibly-escaped character from chunk, for a character class.
func getEsc(chunk string) (r int, nchunk string, err os.Error) {
	if len(chunk) == 0 || chunk[0] == '-' || chunk[0] == ']' {
		err = ErrBadPattern
		return
	}
	if chunk[0] == '\\' {
		chunk = chunk[1:]
		if len(chunk) == 0 {
			err = ErrBadPattern
			return
		}
	}
	r, n := utf8.DecodeRuneInString(chunk)
	if r == utf8.RuneError && n == 1 {
		err = ErrBadPattern
	}
	nchunk = chunk[n:]
	if len(nchunk) == 0 {
		err = ErrBadPattern
	}
	return
}

// Glob returns the names of all files matching pattern or nil
// if there is no matching file. The syntax of patterns is the same
// as in Match. The pattern may describe hierarchical names such as
// /usr/*/bin/ed (assuming the Separator is '/').
//
func Glob(pattern string) (matches []string) {
	if !hasMeta(pattern) {
		if _, err := os.Stat(pattern); err == nil {
			return []string{pattern}
		}
		return nil
	}

	dir, file := Split(pattern)
	switch dir {
	case "":
		dir = "."
	case string(Separator):
		// nothing
	default:
		dir = dir[0 : len(dir)-1] // chop off trailing separator
	}

	if hasMeta(dir) {
		for _, d := range Glob(dir) {
			matches = glob(d, file, matches)
		}
	} else {
		return glob(dir, file, nil)
	}
	return matches
}

// glob searches for files matching pattern in the directory dir
// and appends them to matches. If the directory cannot be
// opened, it returns the existing matches. New matches are
// added in lexicographical order.
func glob(dir, pattern string, matches []string) (m []string) {
	m = matches
	fi, err := os.Stat(dir)
	if err != nil {
		return
	}
	if !fi.IsDirectory() {
		return
	}
	d, err := os.Open(dir, os.O_RDONLY, 0666)
	if err != nil {
		return
	}
	defer d.Close()

	names, err := d.Readdirnames(-1)
	if err != nil {
		return
	}
	sort.SortStrings(names)

	for _, n := range names {
		matched, err := Match(pattern, n)
		if err != nil {
			break
		}
		if matched {
			m = append(m, Join(dir, n))
		}
	}
	return
}

// hasMeta returns true if path contains any of the magic characters
// recognized by Match.
func hasMeta(path string) bool {
	// TODO(niemeyer): Should other magic characters be added here?
	return strings.IndexAny(path, "*?[") >= 0
}
<|endoftext|>