<commit_before>// Package httpauth implements cookie/session based authentication and
// authorization. Intended for use with the net/http or github.com/gorilla/mux
// packages, but may work with github.com/codegangsta/martini as well.
// Credentials are stored as a username + password hash, computed with bcrypt.
//
// Three user storage systems are currently implemented: file based
// (encoding/gob), sql databases (database/sql), and MongoDB databases.
//
// Access can be restricted by a users' role. A higher role will give more
// access.
//
// Users can be redirected to the page that triggered an authentication error.
//
// Messages describing the reason a user could not authenticate are saved in a
// cookie, and can be accessed with the Messages function.
//
// Example source can be found at
// https://github.com/apexskier/httpauth/blob/master/examples/server.go
package httpauth

import (
	"errors"
	"net/http"

	"github.com/gorilla/sessions"
	"golang.org/x/crypto/bcrypt"
)

// ErrDeleteNull is returned by DeleteUser when that user didn't exist at the
// time of call.
// ErrMissingUser is returned by Users when a user is not found.
var (
	ErrDeleteNull  = mkerror("deleting non-existant user")
	ErrMissingUser = mkerror("can't find user")
)

// Role represents an interal role. Roles are essentially a string mapped to an
// integer. Roles must be greater than zero.
type Role int

// UserData represents a single user. It contains the users username, email,
// and role as well as a hash of their username and password. When creating
// users, you should not specify a hash; it will be generated in the Register
// and Update functions.
type UserData struct {
	Username string `bson:"Username"`
	Email    string `bson:"Email"`
	Hash     []byte `bson:"Hash"`
	Role     string `bson:"Role"`
}

// Authorizer structures contain the store of user session cookies a reference
// to a backend storage system.
type Authorizer struct {
	cookiejar   *sessions.CookieStore
	backend     AuthBackend
	defaultRole string
	roles       map[string]Role
}

// The AuthBackend interface defines a set of methods an AuthBackend must
// implement.
type AuthBackend interface {
	SaveUser(u UserData) error
	User(username string) (user UserData, e error)
	Users() (users []UserData, e error)
	DeleteUser(username string) error
	Close()
}

// Helper function to add a user directed message to a message queue.
func (a Authorizer) addMessage(rw http.ResponseWriter, req *http.Request, message string) {
	messageSession, _ := a.cookiejar.Get(req, "messages")
	defer messageSession.Save(req, rw)
	messageSession.AddFlash(message)
}

// Helper function to save a redirect to the page a user tried to visit before
// logging in.
func (a Authorizer) goBack(rw http.ResponseWriter, req *http.Request) {
	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	defer redirectSession.Save(req, rw)
	redirectSession.Flashes()
	redirectSession.AddFlash(req.URL.Path)
}

func mkerror(msg string) error {
	return errors.New("httpauth: " + msg)
}

// NewAuthorizer returns a new Authorizer given an AuthBackend, a cookie store
// key, a default user role, and a map of roles. If the key changes, logged in
// users will need to reauthenticate.
//
// Roles are a map of string to httpauth.Role values (integers). Higher Role values
// have more access.
//
// Example roles:
//
//     var roles map[string]httpauth.Role
//     roles["user"] = 2
//     roles["admin"] = 4
//     roles["moderator"] = 3
func NewAuthorizer(backend AuthBackend, key []byte, defaultRole string, roles map[string]Role) (Authorizer, error) {
	var a Authorizer
	a.cookiejar = sessions.NewCookieStore([]byte(key))
	a.backend = backend
	a.roles = roles
	a.defaultRole = defaultRole
	if _, ok := roles[defaultRole]; !ok {
		return a, mkerror("httpauth: defaultRole missing")
	}
	return a, nil
}

// Login logs a user in. They will be redirected to dest or to the last
// location an authorization redirect was triggered (if found) on success. A
// message will be added to the session on failure with the reason.
func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string, dest string) error {
	session, _ := a.cookiejar.Get(req, "auth")
	if session.Values["username"] != nil {
		return mkerror("already authenticated")
	}
	if user, err := a.backend.User(u); err == nil {
		verify := bcrypt.CompareHashAndPassword(user.Hash, []byte(u+p))
		if verify != nil {
			a.addMessage(rw, req, "Invalid username or password.")
			return mkerror("password doesn't match")
		}
	} else {
		a.addMessage(rw, req, "Invalid username or password.")
		return mkerror("user not found")
	}
	session.Values["username"] = u
	session.Save(req, rw)

	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	if flashes := redirectSession.Flashes(); len(flashes) > 0 {
		dest = flashes[0].(string)
	}
	http.Redirect(rw, req, dest, http.StatusSeeOther)
	return nil
}

// Register and save a new user. Returns an error and adds a message if the
// username is in use.
//
// Pass in a instance of UserData with at least a username and email specified. If no role
// is given, the default one is used.
func (a Authorizer) Register(rw http.ResponseWriter, req *http.Request, user UserData, password string) error {
	if user.Username == "" {
		return mkerror("no username given")
	}
	if user.Email == "" {
		return mkerror("no email given")
	}
	if user.Hash != nil {
		return mkerror("hash will be overwritten")
	}
	if password == "" {
		return mkerror("no password given")
	}

	// Validate username
	_, err := a.backend.User(user.Username)
	if err == nil {
		a.addMessage(rw, req, "Username has been taken.")
		return mkerror("user already exists")
	} else if err != ErrMissingUser {
		if err != nil {
			return mkerror(err.Error())
		}
		return nil
	}

	// Generate and save hash
	hash, err := bcrypt.GenerateFromPassword([]byte(user.Username+password), 8)
	if err != nil {
		return mkerror("couldn't save password: " + err.Error())
	}
	user.Hash = hash

	// Validate role
	if user.Role == "" {
		user.Role = a.defaultRole
	} else {
		if _, ok := a.roles[user.Role]; !ok {
			return mkerror("non-existant role")
		}
	}

	err = a.backend.SaveUser(user)
	if err != nil {
		a.addMessage(rw, req, err.Error())
		return mkerror(err.Error())
	}
	return nil
}

// Update changes data for an existing user. Needs thought...
func (a Authorizer) Update(rw http.ResponseWriter, req *http.Request, p string, e string) error {
	var (
		hash  []byte
		email string
	)
	authSession, err := a.cookiejar.Get(req, "auth")
	username, ok := authSession.Values["username"].(string)
	if !ok {
		return mkerror("not logged in")
	}
	user, err := a.backend.User(username)
	if err == ErrMissingUser {
		a.addMessage(rw, req, "User doesn't exist.")
		return mkerror("user doesn't exists")
	} else if err != nil {
		return mkerror(err.Error())
	}
	if p != "" {
		hash, err = bcrypt.GenerateFromPassword([]byte(username+p), 8)
		if err != nil {
			return mkerror("couldn't save password: " + err.Error())
		}
	} else {
		hash = user.Hash
	}
	if e != "" {
		email = e
	} else {
		email = user.Email
	}

	newuser := UserData{username, email, hash, user.Role}

	err = a.backend.SaveUser(newuser)
	if err != nil {
		a.addMessage(rw, req, err.Error())
	}
	return nil
}

// Authorize checks if a user is logged in and returns an error on failed
// authentication. If redirectWithMessage is set, the page being authorized
// will be saved and a "Login to do that." message will be saved to the
// messages list. The next time the user logs in, they will be redirected back
// to the saved page.
func (a Authorizer) Authorize(rw http.ResponseWriter, req *http.Request, redirectWithMessage bool) error {
	authSession, err := a.cookiejar.Get(req, "auth")
	if err != nil {
		if redirectWithMessage {
			a.goBack(rw, req)
		}
		return mkerror("new authorization session")
	}
	/*if authSession.IsNew {
	    if redirectWithMessage {
	        a.goBack(rw, req)
	        a.addMessage(rw, req, "Log in to do that.")
	    }
	    return mkerror("no session existed")
	}*/
	username := authSession.Values["username"]
	if !authSession.IsNew && username != nil {
		_, err := a.backend.User(username.(string))
		if err == ErrMissingUser {
			authSession.Options.MaxAge = -1 // kill the cookie
			authSession.Save(req, rw)
			if redirectWithMessage {
				a.goBack(rw, req)
				a.addMessage(rw, req, "Log in to do that.")
			}
			return mkerror("user not found")
		} else if err != nil {
			return mkerror(err.Error())
		}
	}
	if username == nil {
		if redirectWithMessage {
			a.goBack(rw, req)
			a.addMessage(rw, req, "Log in to do that.")
		}
		return mkerror("user not logged in")
	}
	return nil
}

// AuthorizeRole runs Authorize on a user, then makes sure their role is at
// least as high as the specified one, failing if not.
func (a Authorizer) AuthorizeRole(rw http.ResponseWriter, req *http.Request, role string, redirectWithMessage bool) error {
	r, ok := a.roles[role]
	if !ok {
		return mkerror("role not found")
	}
	if err := a.Authorize(rw, req, redirectWithMessage); err != nil {
		return mkerror(err.Error())
	}
	authSession, _ := a.cookiejar.Get(req, "auth") // should I check err? I've already checked in call to Authorize
	username := authSession.Values["username"]
	if user, err := a.backend.User(username.(string)); err == nil {
		if a.roles[user.Role] >= r {
			return nil
		}
		a.addMessage(rw, req, "You don't have sufficient privileges.")
		return mkerror("user doesn't have high enough role")
	}
	return mkerror("user not found")
}

// CurrentUser returns the currently logged in user and a boolean validating
// the information.
func (a Authorizer) CurrentUser(rw http.ResponseWriter, req *http.Request) (user UserData, e error) {
	if err := a.Authorize(rw, req, false); err != nil {
		return user, mkerror(err.Error())
	}
	authSession, _ := a.cookiejar.Get(req, "auth")

	username, ok := authSession.Values["username"].(string)
	if !ok {
		return user, mkerror("User not found in authsession")
	}
	return a.backend.User(username)
}

// Logout clears an authentication session and add a logged out message.
func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {
	session, _ := a.cookiejar.Get(req, "auth")
	defer session.Save(req, rw)

	session.Options.MaxAge = -1 // kill the cookie
	a.addMessage(rw, req, "Logged out.")
	return nil
}

// DeleteUser removes a user from the Authorize. ErrMissingUser is returned if
// the user to be deleted isn't found.
func (a Authorizer) DeleteUser(username string) error {
	err := a.backend.DeleteUser(username)
	if err != nil && err != ErrDeleteNull {
		return mkerror(err.Error())
	}
	return err
}

// Messages fetches a list of saved messages. Use this to get a nice message to print to
// the user on a login page or registration page in case something happened
// (username taken, invalid credentials, successful logout, etc).
func (a Authorizer) Messages(rw http.ResponseWriter, req *http.Request) []string {
	session, _ := a.cookiejar.Get(req, "messages")
	flashes := session.Flashes()
	session.Save(req, rw)
	var messages []string
	for _, val := range flashes {
		messages = append(messages, val.(string))
	}
	return messages
}
<commit_msg>Increased default bcrypt cost<commit_after>// Package httpauth implements cookie/session based authentication and
// authorization. Intended for use with the net/http or github.com/gorilla/mux
// packages, but may work with github.com/codegangsta/martini as well.
// Credentials are stored as a username + password hash, computed with bcrypt.
//
// Three user storage systems are currently implemented: file based
// (encoding/gob), sql databases (database/sql), and MongoDB databases.
//
// Access can be restricted by a users' role. A higher role will give more
// access.
//
// Users can be redirected to the page that triggered an authentication error.
//
// Messages describing the reason a user could not authenticate are saved in a
// cookie, and can be accessed with the Messages function.
//
// Example source can be found at
// https://github.com/apexskier/httpauth/blob/master/examples/server.go
package httpauth

import (
	"errors"
	"net/http"

	"github.com/gorilla/sessions"
	"golang.org/x/crypto/bcrypt"
)

// ErrDeleteNull is returned by DeleteUser when that user didn't exist at the
// time of call.
// ErrMissingUser is returned by Users when a user is not found.
var (
	ErrDeleteNull  = mkerror("deleting non-existant user")
	ErrMissingUser = mkerror("can't find user")
)

// Role represents an interal role. Roles are essentially a string mapped to an
// integer. Roles must be greater than zero.
type Role int

// UserData represents a single user. It contains the users username, email,
// and role as well as a hash of their username and password. When creating
// users, you should not specify a hash; it will be generated in the Register
// and Update functions.
type UserData struct {
	Username string `bson:"Username"`
	Email    string `bson:"Email"`
	Hash     []byte `bson:"Hash"`
	Role     string `bson:"Role"`
}

// Authorizer structures contain the store of user session cookies a reference
// to a backend storage system.
type Authorizer struct {
	cookiejar   *sessions.CookieStore
	backend     AuthBackend
	defaultRole string
	roles       map[string]Role
}

// The AuthBackend interface defines a set of methods an AuthBackend must
// implement.
type AuthBackend interface {
	SaveUser(u UserData) error
	User(username string) (user UserData, e error)
	Users() (users []UserData, e error)
	DeleteUser(username string) error
	Close()
}

// Helper function to add a user directed message to a message queue.
func (a Authorizer) addMessage(rw http.ResponseWriter, req *http.Request, message string) {
	messageSession, _ := a.cookiejar.Get(req, "messages")
	defer messageSession.Save(req, rw)
	messageSession.AddFlash(message)
}

// Helper function to save a redirect to the page a user tried to visit before
// logging in.
func (a Authorizer) goBack(rw http.ResponseWriter, req *http.Request) {
	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	defer redirectSession.Save(req, rw)
	redirectSession.Flashes()
	redirectSession.AddFlash(req.URL.Path)
}

func mkerror(msg string) error {
	return errors.New("httpauth: " + msg)
}

// NewAuthorizer returns a new Authorizer given an AuthBackend, a cookie store
// key, a default user role, and a map of roles. If the key changes, logged in
// users will need to reauthenticate.
//
// Roles are a map of string to httpauth.Role values (integers). Higher Role values
// have more access.
//
// Example roles:
//
//     var roles map[string]httpauth.Role
//     roles["user"] = 2
//     roles["admin"] = 4
//     roles["moderator"] = 3
func NewAuthorizer(backend AuthBackend, key []byte, defaultRole string, roles map[string]Role) (Authorizer, error) {
	var a Authorizer
	a.cookiejar = sessions.NewCookieStore([]byte(key))
	a.backend = backend
	a.roles = roles
	a.defaultRole = defaultRole
	if _, ok := roles[defaultRole]; !ok {
		return a, mkerror("httpauth: defaultRole missing")
	}
	return a, nil
}

// Login logs a user in. They will be redirected to dest or to the last
// location an authorization redirect was triggered (if found) on success. A
// message will be added to the session on failure with the reason.
func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string, dest string) error {
	session, _ := a.cookiejar.Get(req, "auth")
	if session.Values["username"] != nil {
		return mkerror("already authenticated")
	}
	if user, err := a.backend.User(u); err == nil {
		verify := bcrypt.CompareHashAndPassword(user.Hash, []byte(u+p))
		if verify != nil {
			a.addMessage(rw, req, "Invalid username or password.")
			return mkerror("password doesn't match")
		}
	} else {
		a.addMessage(rw, req, "Invalid username or password.")
		return mkerror("user not found")
	}
	session.Values["username"] = u
	session.Save(req, rw)

	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	if flashes := redirectSession.Flashes(); len(flashes) > 0 {
		dest = flashes[0].(string)
	}
	http.Redirect(rw, req, dest, http.StatusSeeOther)
	return nil
}

// Register and save a new user. Returns an error and adds a message if the
// username is in use.
//
// Pass in a instance of UserData with at least a username and email specified. If no role
// is given, the default one is used.
func (a Authorizer) Register(rw http.ResponseWriter, req *http.Request, user UserData, password string) error {
	if user.Username == "" {
		return mkerror("no username given")
	}
	if user.Email == "" {
		return mkerror("no email given")
	}
	if user.Hash != nil {
		return mkerror("hash will be overwritten")
	}
	if password == "" {
		return mkerror("no password given")
	}

	// Validate username
	_, err := a.backend.User(user.Username)
	if err == nil {
		a.addMessage(rw, req, "Username has been taken.")
		return mkerror("user already exists")
	} else if err != ErrMissingUser {
		if err != nil {
			return mkerror(err.Error())
		}
		return nil
	}

	// Generate and save hash
	hash, err := bcrypt.GenerateFromPassword([]byte(user.Username+password), bcrypt.DefaultCost)
	if err != nil {
		return mkerror("couldn't save password: " + err.Error())
	}
	user.Hash = hash

	// Validate role
	if user.Role == "" {
		user.Role = a.defaultRole
	} else {
		if _, ok := a.roles[user.Role]; !ok {
			return mkerror("non-existant role")
		}
	}

	err = a.backend.SaveUser(user)
	if err != nil {
		a.addMessage(rw, req, err.Error())
		return mkerror(err.Error())
	}
	return nil
}

// Update changes data for an existing user. Needs thought...
func (a Authorizer) Update(rw http.ResponseWriter, req *http.Request, p string, e string) error {
	var (
		hash  []byte
		email string
	)
	authSession, err := a.cookiejar.Get(req, "auth")
	username, ok := authSession.Values["username"].(string)
	if !ok {
		return mkerror("not logged in")
	}
	user, err := a.backend.User(username)
	if err == ErrMissingUser {
		a.addMessage(rw, req, "User doesn't exist.")
		return mkerror("user doesn't exists")
	} else if err != nil {
		return mkerror(err.Error())
	}
	if p != "" {
		hash, err = bcrypt.GenerateFromPassword([]byte(username+p), 8)
		if err != nil {
			return mkerror("couldn't save password: " + err.Error())
		}
	} else {
		hash = user.Hash
	}
	if e != "" {
		email = e
	} else {
		email = user.Email
	}

	newuser := UserData{username, email, hash, user.Role}

	err = a.backend.SaveUser(newuser)
	if err != nil {
		a.addMessage(rw, req, err.Error())
	}
	return nil
}

// Authorize checks if a user is logged in and returns an error on failed
// authentication. If redirectWithMessage is set, the page being authorized
// will be saved and a "Login to do that." message will be saved to the
// messages list. The next time the user logs in, they will be redirected back
// to the saved page.
func (a Authorizer) Authorize(rw http.ResponseWriter, req *http.Request, redirectWithMessage bool) error {
	authSession, err := a.cookiejar.Get(req, "auth")
	if err != nil {
		if redirectWithMessage {
			a.goBack(rw, req)
		}
		return mkerror("new authorization session")
	}
	/*if authSession.IsNew {
	    if redirectWithMessage {
	        a.goBack(rw, req)
	        a.addMessage(rw, req, "Log in to do that.")
	    }
	    return mkerror("no session existed")
	}*/
	username := authSession.Values["username"]
	if !authSession.IsNew && username != nil {
		_, err := a.backend.User(username.(string))
		if err == ErrMissingUser {
			authSession.Options.MaxAge = -1 // kill the cookie
			authSession.Save(req, rw)
			if redirectWithMessage {
				a.goBack(rw, req)
				a.addMessage(rw, req, "Log in to do that.")
			}
			return mkerror("user not found")
		} else if err != nil {
			return mkerror(err.Error())
		}
	}
	if username == nil {
		if redirectWithMessage {
			a.goBack(rw, req)
			a.addMessage(rw, req, "Log in to do that.")
		}
		return mkerror("user not logged in")
	}
	return nil
}

// AuthorizeRole runs Authorize on a user, then makes sure their role is at
// least as high as the specified one, failing if not.
func (a Authorizer) AuthorizeRole(rw http.ResponseWriter, req *http.Request, role string, redirectWithMessage bool) error {
	r, ok := a.roles[role]
	if !ok {
		return mkerror("role not found")
	}
	if err := a.Authorize(rw, req, redirectWithMessage); err != nil {
		return mkerror(err.Error())
	}
	authSession, _ := a.cookiejar.Get(req, "auth") // should I check err? I've already checked in call to Authorize
	username := authSession.Values["username"]
	if user, err := a.backend.User(username.(string)); err == nil {
		if a.roles[user.Role] >= r {
			return nil
		}
		a.addMessage(rw, req, "You don't have sufficient privileges.")
		return mkerror("user doesn't have high enough role")
	}
	return mkerror("user not found")
}

// CurrentUser returns the currently logged in user and a boolean validating
// the information.
func (a Authorizer) CurrentUser(rw http.ResponseWriter, req *http.Request) (user UserData, e error) {
	if err := a.Authorize(rw, req, false); err != nil {
		return user, mkerror(err.Error())
	}
	authSession, _ := a.cookiejar.Get(req, "auth")

	username, ok := authSession.Values["username"].(string)
	if !ok {
		return user, mkerror("User not found in authsession")
	}
	return a.backend.User(username)
}

// Logout clears an authentication session and add a logged out message.
func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {
	session, _ := a.cookiejar.Get(req, "auth")
	defer session.Save(req, rw)

	session.Options.MaxAge = -1 // kill the cookie
	a.addMessage(rw, req, "Logged out.")
	return nil
}

// DeleteUser removes a user from the Authorize. ErrMissingUser is returned if
// the user to be deleted isn't found.
func (a Authorizer) DeleteUser(username string) error {
	err := a.backend.DeleteUser(username)
	if err != nil && err != ErrDeleteNull {
		return mkerror(err.Error())
	}
	return err
}

// Messages fetches a list of saved messages. Use this to get a nice message to print to
// the user on a login page or registration page in case something happened
// (username taken, invalid credentials, successful logout, etc).
func (a Authorizer) Messages(rw http.ResponseWriter, req *http.Request) []string {
	session, _ := a.cookiejar.Get(req, "messages")
	flashes := session.Flashes()
	session.Save(req, rw)
	var messages []string
	for _, val := range flashes {
		messages = append(messages, val.(string))
	}
	return messages
}
<|endoftext|>


<commit_before>package winrm

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

	"github.com/masterzen/azure-sdk-for-go/core/http"
	"github.com/masterzen/azure-sdk-for-go/core/tls"

	"github.com/masterzen/winrm/soap"
)

type ClientAuthRequest struct {
	transport http.RoundTripper
}

func (c *ClientAuthRequest) Transport(endpoint *Endpoint) error {
	cert, err := tls.X509KeyPair(endpoint.Cert, endpoint.Key)
	if err != nil {
		return err
	}

	transport := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: endpoint.Insecure,
			Certificates:       []tls.Certificate{cert},
		},
		Dial: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
		ResponseHeaderTimeout: endpoint.Timeout,
	}

	if endpoint.CACert != nil && len(endpoint.CACert) > 0 {
		certPool, err := readCACerts(endpoint.CACert)
		if err != nil {
			return err
		}

		transport.TLSClientConfig.RootCAs = certPool
	}

	c.transport = transport

	return nil
}

// parse func reads the response body and return it as a string
func parse(response *http.Response) (string, error) {

	// if we recived the content we expected
	if strings.Contains(response.Header.Get("Content-Type"), "application/soap+xml") {
		body, err := ioutil.ReadAll(response.Body)
		defer func() {
			// defer can modify the returned value before
			// it is actually passed to the calling statement
			if errClose := response.Body.Close(); errClose != nil && err == nil {
				err = errClose
			}
		}()
		if err != nil {
			return "", fmt.Errorf("error while reading request body %s", err)
		}

		return string(body), nil
	}

	return "", fmt.Errorf("invalid content type")
}

func (c ClientAuthRequest) Post(client *Client, request *soap.SoapMessage) (string, error) {
	httpClient := &http.Client{Transport: c.transport}

	req, err := http.NewRequest("POST", client.url, strings.NewReader(request.String()))
	if err != nil {
		return "", fmt.Errorf("impossible to create http request %s", err)
	}

	req.Header.Set("Content-Type", soapXML+";charset=UTF-8")
	req.Header.Set("Authorization", "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/mutual")

	resp, err := httpClient.Do(req)
	if err != nil {
		return "", fmt.Errorf("unknown error %s", err)
	}

	body, err := parse(resp)
	if err != nil {
		return "", fmt.Errorf("http response error: %d - %s", resp.StatusCode, err.Error())
	}

	// if we have different 200 http status code
	// we must replace the error
	defer func() {
		if resp.StatusCode != 200 {
			body, err = "", fmt.Errorf("http error %d: %s", resp.StatusCode, body)
		}
	}()

	return body, err
}
<commit_msg>also add ProxyFromEnvironment to auth transport.<commit_after>package winrm

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

	"github.com/masterzen/azure-sdk-for-go/core/http"
	"github.com/masterzen/azure-sdk-for-go/core/tls"

	"github.com/masterzen/winrm/soap"
)

type ClientAuthRequest struct {
	transport http.RoundTripper
}

func (c *ClientAuthRequest) Transport(endpoint *Endpoint) error {
	cert, err := tls.X509KeyPair(endpoint.Cert, endpoint.Key)
	if err != nil {
		return err
	}

	transport := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: endpoint.Insecure,
			Certificates:       []tls.Certificate{cert},
		},
		Dial: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
		ResponseHeaderTimeout: endpoint.Timeout,
	}

	if endpoint.CACert != nil && len(endpoint.CACert) > 0 {
		certPool, err := readCACerts(endpoint.CACert)
		if err != nil {
			return err
		}

		transport.TLSClientConfig.RootCAs = certPool
	}

	c.transport = transport

	return nil
}

// parse func reads the response body and return it as a string
func parse(response *http.Response) (string, error) {

	// if we recived the content we expected
	if strings.Contains(response.Header.Get("Content-Type"), "application/soap+xml") {
		body, err := ioutil.ReadAll(response.Body)
		defer func() {
			// defer can modify the returned value before
			// it is actually passed to the calling statement
			if errClose := response.Body.Close(); errClose != nil && err == nil {
				err = errClose
			}
		}()
		if err != nil {
			return "", fmt.Errorf("error while reading request body %s", err)
		}

		return string(body), nil
	}

	return "", fmt.Errorf("invalid content type")
}

func (c ClientAuthRequest) Post(client *Client, request *soap.SoapMessage) (string, error) {
	httpClient := &http.Client{Transport: c.transport}

	req, err := http.NewRequest("POST", client.url, strings.NewReader(request.String()))
	if err != nil {
		return "", fmt.Errorf("impossible to create http request %s", err)
	}

	req.Header.Set("Content-Type", soapXML+";charset=UTF-8")
	req.Header.Set("Authorization", "http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/mutual")

	resp, err := httpClient.Do(req)
	if err != nil {
		return "", fmt.Errorf("unknown error %s", err)
	}

	body, err := parse(resp)
	if err != nil {
		return "", fmt.Errorf("http response error: %d - %s", resp.StatusCode, err.Error())
	}

	// if we have different 200 http status code
	// we must replace the error
	defer func() {
		if resp.StatusCode != 200 {
			body, err = "", fmt.Errorf("http error %d: %s", resp.StatusCode, body)
		}
	}()

	return body, err
}
<|endoftext|>


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

// Package bank was made for the Master Go course at appliedgo.com.
package bank

import (
	"encoding/gob"
	"fmt"
	"os"

	"github.com/pkg/errors"
)

// Account is a bank account with a name, a balance, and a
// transaction history.
// The fields should be unexported and accessed via Name(), Balance(),
// and History() only. However, `gob` enconding and
// decoding (used by Save and Load) requires struct fields to be exported.

type Account struct {
	Name string
	Bal  int
	Hist []history
}

type history struct {
	Amt, Bal int
}

var accounts map[string]*Account

// NewAccount creates a new account with a name. Initial balance is 0.
// The new account is added to the bank's map of accounts.
func NewAccount(s string) *Account {
	if accounts == nil {
		accounts = make(map[string]*Account)
	}
	a := &Account{Name: s}
	accounts[s] = a
	return a
}

// GetAccount receives a name and returns the account of that name, if it exists.
// GetAccount panics if the bank has no accounts.
func GetAccount(name string) (*Account, error) {
	accnt, ok := accounts[name]
	if !ok {
		return nil, errors.New("account '" + name + "' does not exist")
	}
	return accnt, nil
}

// ListAccounts returns a formatted string that lists
// each account and its current balance.
func ListAccounts() string {
	list := "Accounts:\n"
	for _, v := range accounts {
		list += fmt.Sprintf("Account: %s, balance: %d\n", v.Name, v.Bal)
	}
	return list
}

// Name returns the name of account a.
func Name(a *Account) string {
	return a.Name
}

// Balance returns the current balance of account a.
func Balance(a *Account) int {
	return a.Bal
}

// Deposit adds amount m to account a's balance.
// The amount must be positive.
func Deposit(a *Account, m int) (int, error) {
	if m < 0 {
		return a.Bal, errors.Errorf("Deposit: amount must be positive, but is %d.", m)
	}
	a.Bal += m
	a.Hist = append(a.Hist, history{m, a.Bal})
	return a.Bal, nil
}

// Withdraw removes amount m from account a's balance.
// The amount must be positive.
func Withdraw(a *Account, m int) (int, error) {
	if m < 0 {
		return a.Bal, errors.Errorf("Withdraw: amount must be positive, but is %d.", m)
	}
	if m > a.Bal {
		return a.Bal, errors.Errorf("Withdraw: amount (%d) must be less than actual balance (%d).", m, a.Bal)
	}
	a.Bal -= m
	a.Hist = append(a.Hist, history{-m, a.Bal})
	return a.Bal, nil
}

// Transfer transfers amount m from account a to account b.
// The amount must be positive.
// The sending account must have at least as much money as the
// amount to be transferred.
func Transfer(a, b *Account, m int) (int, int, error) {
	switch {
	case m < 0:
		return a.Bal, b.Bal, errors.Errorf("Transfer: amount must be positive, but is %d.", m)
	case m > a.Bal:
		return 0, a.Bal, errors.Errorf("Withdraw: amount (%d) must be less than actual balance of sending account (%d).", m, a.Bal)
	}
	a.Bal -= m
	b.Bal += m
	a.Hist = append(a.Hist, history{-m, a.Bal})
	b.Hist = append(b.Hist, history{m, b.Bal})
	return a.Bal, b.Bal, nil
}

// History returns a closure that returns one account transaction at a time.
// On each call, the closure returns the amount of the transaction, the resulting balance,
// and a boolean that is true as long as there are more history elements to read.
// The closure returns the history items from oldest to newest.
func History(a *Account) func() (int, int, bool) {
	i := 0
	more := true
	return func() (int, int, bool) {
		if i >= len(a.Hist)-1 {
			more = false
		}
		h := a.Hist[i]
		i++
		return h.Amt, h.Bal, more
	}
}

// Save persists the accounts map on disk.
func Save() (err error) {
	f, err := os.OpenFile("bank.data", os.O_WRONLY, 0666) // Note: octal #
	if err != nil {
		f, err = os.Create("bank.data")
		if err != nil {
			return errors.Wrap(err, "Save: Create failed")
		}
	}
	defer func() {
		e := f.Close()
		if e != nil {
			if err == nil {
				err = e
				return
			}
			err = errors.Wrap(err, e.Error())
		}
	}()

	e := gob.NewEncoder(f)
	err = e.Encode(accounts)
	if err != nil {
		return errors.Wrap(err, "Save: Encode failed")
	}
	return nil
}

// Load restores the accounts map from disk.
func Load() error {
	f, err := os.Open("bank.data")
	if err != nil {
		if os.IsNotExist(err) {
			// Expected. The file does not exist initially.
			return nil
		}
		return errors.Wrap(err, "Load: Open failed")
	}
	defer f.Close() // closing a readonly file needs no error checking
	d := gob.NewDecoder(f)
	err = d.Decode(&accounts)
	if err != nil {
		return errors.Wrap(err, "Load: Decode failed")
	}
	return nil
}
<commit_msg>Add check for empty history. Add comment on panicking if calling the closure despite more == false.<commit_after>// Copyright 2017 Christoph Berger. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package bank was made for the Master Go course at appliedgo.com.
package bank

import (
	"encoding/gob"
	"fmt"
	"os"

	"github.com/pkg/errors"
)

// Account is a bank account with a name, a balance, and a
// transaction history.
// The fields should be unexported and accessed via Name(), Balance(),
// and History() only. However, `gob` enconding and
// decoding (used by Save and Load) requires struct fields to be exported.

type Account struct {
	Name string
	Bal  int
	Hist []history
}

type history struct {
	Amt, Bal int
}

var accounts map[string]*Account

// NewAccount creates a new account with a name. Initial balance is 0.
// The new account is added to the bank's map of accounts.
func NewAccount(s string) *Account {
	if accounts == nil {
		accounts = make(map[string]*Account)
	}
	a := &Account{Name: s}
	accounts[s] = a
	return a
}

// GetAccount receives a name and returns the account of that name, if it exists.
// GetAccount panics if the bank has no accounts.
func GetAccount(name string) (*Account, error) {
	accnt, ok := accounts[name]
	if !ok {
		return nil, errors.New("account '" + name + "' does not exist")
	}
	return accnt, nil
}

// ListAccounts returns a formatted string that lists
// each account and its current balance.
func ListAccounts() string {
	list := "Accounts:\n"
	for _, v := range accounts {
		list += fmt.Sprintf("Account: %s, balance: %d\n", v.Name, v.Bal)
	}
	return list
}

// Name returns the name of account a.
func Name(a *Account) string {
	return a.Name
}

// Balance returns the current balance of account a.
func Balance(a *Account) int {
	return a.Bal
}

// Deposit adds amount m to account a's balance.
// The amount must be positive.
func Deposit(a *Account, m int) (int, error) {
	if m < 0 {
		return a.Bal, errors.Errorf("Deposit: amount must be positive, but is %d.", m)
	}
	a.Bal += m
	a.Hist = append(a.Hist, history{m, a.Bal})
	return a.Bal, nil
}

// Withdraw removes amount m from account a's balance.
// The amount must be positive.
func Withdraw(a *Account, m int) (int, error) {
	if m < 0 {
		return a.Bal, errors.Errorf("Withdraw: amount must be positive, but is %d.", m)
	}
	if m > a.Bal {
		return a.Bal, errors.Errorf("Withdraw: amount (%d) must be less than actual balance (%d).", m, a.Bal)
	}
	a.Bal -= m
	a.Hist = append(a.Hist, history{-m, a.Bal})
	return a.Bal, nil
}

// Transfer transfers amount m from account a to account b.
// The amount must be positive.
// The sending account must have at least as much money as the
// amount to be transferred.
func Transfer(a, b *Account, m int) (int, int, error) {
	switch {
	case m < 0:
		return a.Bal, b.Bal, errors.Errorf("Transfer: amount must be positive, but is %d.", m)
	case m > a.Bal:
		return 0, a.Bal, errors.Errorf("Withdraw: amount (%d) must be less than actual balance of sending account (%d).", m, a.Bal)
	}
	a.Bal -= m
	b.Bal += m
	a.Hist = append(a.Hist, history{-m, a.Bal})
	b.Hist = append(b.Hist, history{m, b.Bal})
	return a.Bal, b.Bal, nil
}

// History returns a closure that returns one account transaction at a time.
// On each call, the closure returns the amount of the transaction, the resulting balance,
// and a boolean that is true as long as there are more history elements to read.
// The closure returns the history items from oldest to newest.
// The closure panics if it is called again after its third return value has
// turned "false".
func History(a *Account) func() (int, int, bool) {
	i := 0
	more := true
	return func() (int, int, bool) {
		if len(a.Hist) == 0 {
			return 0, 0, false
		}
		if i >= len(a.Hist)-1 {
			more = false
		}
		h := a.Hist[i]
		i++
		return h.Amt, h.Bal, more
	}
}

// Save stores the accounts map on disk.
func Save() (err error) {
	f, err := os.OpenFile("bank.data", os.O_WRONLY, 0666) // Note: octal #
	if err != nil {
		f, err = os.Create("bank.data")
		if err != nil {
			return errors.Wrap(err, "Save: Create failed")
		}
	}
	defer func() {
		e := f.Close()
		if e != nil {
			if err == nil {
				err = e
				return
			}
			err = errors.Wrap(err, e.Error())
		}
	}()

	e := gob.NewEncoder(f)
	err = e.Encode(accounts)
	if err != nil {
		return errors.Wrap(err, "Save: Encode failed")
	}
	return nil
}

// Load restores the accounts map from disk.
func Load() error {
	f, err := os.Open("bank.data")
	if err != nil {
		if os.IsNotExist(err) {
			// Expected. The file does not exist initially.
			return nil
		}
		return errors.Wrap(err, "Load: Open failed")
	}
	defer f.Close() // closing a readonly file needs no error checking
	d := gob.NewDecoder(f)
	err = d.Decode(&accounts)
	if err != nil {
		return errors.Wrap(err, "Load: Decode failed")
	}
	return nil
}
<|endoftext|>


<commit_before>package redis

import (
	"fmt"
	"github.com/chrislusf/seaweedfs/weed/filer2"
	"github.com/chrislusf/seaweedfs/weed/glog"
	"github.com/go-redis/redis"
	"sort"
	"strings"
)

const (
	DIR_LIST_MARKER = "\x00"
)

type UniversalRedisStore struct {
	Client redis.UniversalClient
}

func (store *UniversalRedisStore) InsertEntry(entry *filer2.Entry) (err error) {

	value, err := entry.EncodeAttributesAndChunks()
	if err != nil {
		return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
	}

	_, err = store.Client.Set(string(entry.FullPath), value, 0).Result()

	if err != nil {
		return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
	}

	dir, name := entry.FullPath.DirAndName()
	if name != "" {
		_, err = store.Client.SAdd(genDirectoryListKey(dir), name).Result()
		if err != nil {
			return fmt.Errorf("persisting %s in parent dir: %v", entry.FullPath, err)
		}
	}

	return nil
}

func (store *UniversalRedisStore) UpdateEntry(entry *filer2.Entry) (err error) {

	return store.InsertEntry(entry)
}

func (store *UniversalRedisStore) FindEntry(fullpath filer2.FullPath) (entry *filer2.Entry, err error) {

	data, err := store.Client.Get(string(fullpath)).Result()
	if err == redis.Nil {
		return nil, filer2.ErrNotFound
	}

	if err != nil {
		return nil, fmt.Errorf("get %s : %v", entry.FullPath, err)
	}

	entry = &filer2.Entry{
		FullPath: fullpath,
	}
	err = entry.DecodeAttributesAndChunks([]byte(data))
	if err != nil {
		return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
	}

	return entry, nil
}

func (store *UniversalRedisStore) DeleteEntry(fullpath filer2.FullPath) (err error) {

	_, err = store.Client.Del(string(fullpath)).Result()

	if err != nil {
		return fmt.Errorf("delete %s : %v", fullpath, err)
	}

	dir, name := fullpath.DirAndName()
	if name != "" {
		_, err = store.Client.SRem(genDirectoryListKey(dir), name).Result()
		if err != nil {
			return fmt.Errorf("delete %s in parent dir: %v", fullpath, err)
		}
	}

	return nil
}

func (store *UniversalRedisStore) ListDirectoryEntries(fullpath filer2.FullPath, startFileName string, inclusive bool,
	limit int) (entries []*filer2.Entry, err error) {

	members, err := store.Client.SMembers(genDirectoryListKey(string(fullpath))).Result()
	if err != nil {
		return nil, fmt.Errorf("list %s : %v", fullpath, err)
	}

	// skip
	if startFileName != "" {
		var t []string
		for _, m := range members {
			if strings.Compare(m, startFileName) >= 0 {
				if m == startFileName {
					if inclusive {
						t = append(t, m)
					}
				} else {
					t = append(t, m)
				}
			}
		}
		members = t
	}

	// sort
	sort.Slice(members, func(i, j int) bool {
		return strings.Compare(members[i], members[j]) < 0
	})

	// limit
	if limit < len(members) {
		members = members[:limit]
	}

	// fetch entry meta
	for _, fileName := range members {
		path := filer2.NewFullPath(string(fullpath), fileName)
		entry, err := store.FindEntry(path)
		if err != nil {
			glog.V(0).Infof("list %s : %v", path, err)
		} else {
			entries = append(entries, entry)
		}
	}

	return entries, err
}

func genDirectoryListKey(dir string) (dirList string) {
	return dir + DIR_LIST_MARKER
}
<commit_msg>fix a bug on error reporting<commit_after>package redis

import (
	"fmt"
	"github.com/chrislusf/seaweedfs/weed/filer2"
	"github.com/chrislusf/seaweedfs/weed/glog"
	"github.com/go-redis/redis"
	"sort"
	"strings"
)

const (
	DIR_LIST_MARKER = "\x00"
)

type UniversalRedisStore struct {
	Client redis.UniversalClient
}

func (store *UniversalRedisStore) InsertEntry(entry *filer2.Entry) (err error) {

	value, err := entry.EncodeAttributesAndChunks()
	if err != nil {
		return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
	}

	_, err = store.Client.Set(string(entry.FullPath), value, 0).Result()

	if err != nil {
		return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
	}

	dir, name := entry.FullPath.DirAndName()
	if name != "" {
		_, err = store.Client.SAdd(genDirectoryListKey(dir), name).Result()
		if err != nil {
			return fmt.Errorf("persisting %s in parent dir: %v", entry.FullPath, err)
		}
	}

	return nil
}

func (store *UniversalRedisStore) UpdateEntry(entry *filer2.Entry) (err error) {

	return store.InsertEntry(entry)
}

func (store *UniversalRedisStore) FindEntry(fullpath filer2.FullPath) (entry *filer2.Entry, err error) {

	data, err := store.Client.Get(string(fullpath)).Result()
	if err == redis.Nil {
		return nil, filer2.ErrNotFound
	}

	if err != nil {
		return nil, fmt.Errorf("get %s : %v", fullpath, err)
	}

	entry = &filer2.Entry{
		FullPath: fullpath,
	}
	err = entry.DecodeAttributesAndChunks([]byte(data))
	if err != nil {
		return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
	}

	return entry, nil
}

func (store *UniversalRedisStore) DeleteEntry(fullpath filer2.FullPath) (err error) {

	_, err = store.Client.Del(string(fullpath)).Result()

	if err != nil {
		return fmt.Errorf("delete %s : %v", fullpath, err)
	}

	dir, name := fullpath.DirAndName()
	if name != "" {
		_, err = store.Client.SRem(genDirectoryListKey(dir), name).Result()
		if err != nil {
			return fmt.Errorf("delete %s in parent dir: %v", fullpath, err)
		}
	}

	return nil
}

func (store *UniversalRedisStore) ListDirectoryEntries(fullpath filer2.FullPath, startFileName string, inclusive bool,
	limit int) (entries []*filer2.Entry, err error) {

	members, err := store.Client.SMembers(genDirectoryListKey(string(fullpath))).Result()
	if err != nil {
		return nil, fmt.Errorf("list %s : %v", fullpath, err)
	}

	// skip
	if startFileName != "" {
		var t []string
		for _, m := range members {
			if strings.Compare(m, startFileName) >= 0 {
				if m == startFileName {
					if inclusive {
						t = append(t, m)
					}
				} else {
					t = append(t, m)
				}
			}
		}
		members = t
	}

	// sort
	sort.Slice(members, func(i, j int) bool {
		return strings.Compare(members[i], members[j]) < 0
	})

	// limit
	if limit < len(members) {
		members = members[:limit]
	}

	// fetch entry meta
	for _, fileName := range members {
		path := filer2.NewFullPath(string(fullpath), fileName)
		entry, err := store.FindEntry(path)
		if err != nil {
			glog.V(0).Infof("list %s : %v", path, err)
		} else {
			entries = append(entries, entry)
		}
	}

	return entries, err
}

func genDirectoryListKey(dir string) (dirList string) {
	return dir + DIR_LIST_MARKER
}
<|endoftext|>


<commit_before>package main

import (
    "github.com/bwmarrin/discordgo"
    "github.com/sn0w/Karen/logger"
    "time"
)

var BETA_GUILDS = [...]string{
    "259831440064118784", // FADED's Sandbox
    "180818466847064065", // Karen's Sandbox
    "172041631258640384", // P0WERPLANT
    "161637499939192832", // Coding Lounge
    "225168913808228352", // Emily's Space
}

// Automatically leaves guilds that are not registered beta testers
func autoLeaver(session *discordgo.Session) {
    for {
        for _, guild := range session.State.Guilds {
            match := false

            for _, betaGuild := range BETA_GUILDS {
                if guild.ID == betaGuild {
                    match = true
                    break
                }
            }

            if !match {
                logger.WARNING.L("beta", "Leaving guild " + guild.ID + " (" + guild.Name + ") because it didn't apply for the beta")
                session.GuildLeave(guild.ID)
            }
        }

        time.Sleep(10 * time.Second)
    }
}
<commit_msg>Enable the Shinda-Sekai-Sensen guild<commit_after>package main

import (
    "github.com/bwmarrin/discordgo"
    "github.com/sn0w/Karen/logger"
    "time"
)

var BETA_GUILDS = [...]string{
    "259831440064118784", // FADED's Sandbox
    "180818466847064065", // Karen's Sandbox
    "172041631258640384", // P0WERPLANT
    "161637499939192832", // Coding Lounge
    "225168913808228352", // Emily's Space
    "267186654312136704", // Shinda Sekai Sensen
}

// Automatically leaves guilds that are not registered beta testers
func autoLeaver(session *discordgo.Session) {
    for {
        for _, guild := range session.State.Guilds {
            match := false

            for _, betaGuild := range BETA_GUILDS {
                if guild.ID == betaGuild {
                    match = true
                    break
                }
            }

            if !match {
                logger.WARNING.L("beta", "Leaving guild " + guild.ID + " (" + guild.Name + ") because it didn't apply for the beta")
                session.GuildLeave(guild.ID)
            }
        }

        time.Sleep(10 * time.Second)
    }
}
<|endoftext|>


<commit_before>package null

import (
	"database/sql"
	"encoding/json"
	"errors"
)

// Bool is an even nuller nullable bool.
// It does not consider false values to be null.
// It will decode to null, not false, if null.
type Bool struct {
	sql.NullBool
}

// NewBool creates a new Bool
func NewBool(b bool, valid bool) Bool {
	return Bool{
		NullBool: sql.NullBool{
			Bool:  b,
			Valid: valid,
		},
	}
}

// BoolFrom creates a new Bool that will always be valid.
func BoolFrom(b bool) Bool {
	return NewBool(b, true)
}

// BoolFromPtr creates a new Bool that be null if f is nil.
func BoolFromPtr(b *bool) Bool {
	if b == nil {
		return NewBool(false, false)
	}
	return NewBool(*b, true)
}

// UnmarshalJSON implements json.Unmarshaler.
// It supports number and null input.
// 0 will not be considered a null Bool.
// It also supports unmarshalling a sql.NullBool.
func (b *Bool) UnmarshalJSON(data []byte) error {
	var err error
	var v interface{}
	json.Unmarshal(data, &v)
	switch x := v.(type) {
	case bool:
		b.Bool = x
	case map[string]interface{}:
		err = json.Unmarshal(data, &b.NullBool)
	case nil:
		b.Valid = false
		return nil
	}
	b.Valid = err == nil
	return err
}

// UnmarshalText implements encoding.TextUnmarshaler.
// It will unmarshal to a null Bool if the input is a blank or not an integer.
// It will return an error if the input is not an integer, blank, or "null".
func (b *Bool) UnmarshalText(text []byte) error {
	str := string(text)
	switch str {
	case "", "null":
		b.Valid = false
		return nil
	case "true":
		b.Bool = true
	case "false":
		b.Bool = false
	default:
		b.Valid = false
		return errors.New("invalid input:" + str)
	}
	b.Valid = true
	return nil
}

// MarshalJSON implements json.Marshaler.
// It will encode null if this Bool is null.
func (b Bool) MarshalJSON() ([]byte, error) {
	if !b.Valid {
		return []byte("null"), nil
	}
	if !b.Bool {
		return []byte("false"), nil
	}
	return []byte("true"), nil
}

// MarshalText implements encoding.TextMarshaler.
// It will encode a blank string if this Bool is null.
func (b Bool) MarshalText() ([]byte, error) {
	if !b.Valid {
		return []byte{}, nil
	}
	if !b.Bool {
		return []byte("false"), nil
	}
	return []byte("true"), nil
}

// SetValid changes this Bool's value and also sets it to be non-null.
func (b *Bool) SetValid(v bool) {
	b.Bool = v
	b.Valid = true
}

// Ptr returns a pointer to this Bool's value, or a nil pointer if this Bool is null.
func (b Bool) Ptr() *bool {
	if !b.Valid {
		return nil
	}
	return &b.Bool
}

// IsZero returns true for invalid Bools, for future omitempty support (Go 1.4?)
// A non-null Bool with a 0 value will not be considered zero.
func (b Bool) IsZero() bool {
	return !b.Valid
}
<commit_msg>fix grammar in godoc<commit_after>package null

import (
	"database/sql"
	"encoding/json"
	"errors"
)

// Bool is an even nuller nullable bool.
// It does not consider false values to be null.
// It will decode to null, not false, if null.
type Bool struct {
	sql.NullBool
}

// NewBool creates a new Bool
func NewBool(b bool, valid bool) Bool {
	return Bool{
		NullBool: sql.NullBool{
			Bool:  b,
			Valid: valid,
		},
	}
}

// BoolFrom creates a new Bool that will always be valid.
func BoolFrom(b bool) Bool {
	return NewBool(b, true)
}

// BoolFromPtr creates a new Bool that will be null if f is nil.
func BoolFromPtr(b *bool) Bool {
	if b == nil {
		return NewBool(false, false)
	}
	return NewBool(*b, true)
}

// UnmarshalJSON implements json.Unmarshaler.
// It supports number and null input.
// 0 will not be considered a null Bool.
// It also supports unmarshalling a sql.NullBool.
func (b *Bool) UnmarshalJSON(data []byte) error {
	var err error
	var v interface{}
	json.Unmarshal(data, &v)
	switch x := v.(type) {
	case bool:
		b.Bool = x
	case map[string]interface{}:
		err = json.Unmarshal(data, &b.NullBool)
	case nil:
		b.Valid = false
		return nil
	}
	b.Valid = err == nil
	return err
}

// UnmarshalText implements encoding.TextUnmarshaler.
// It will unmarshal to a null Bool if the input is a blank or not an integer.
// It will return an error if the input is not an integer, blank, or "null".
func (b *Bool) UnmarshalText(text []byte) error {
	str := string(text)
	switch str {
	case "", "null":
		b.Valid = false
		return nil
	case "true":
		b.Bool = true
	case "false":
		b.Bool = false
	default:
		b.Valid = false
		return errors.New("invalid input:" + str)
	}
	b.Valid = true
	return nil
}

// MarshalJSON implements json.Marshaler.
// It will encode null if this Bool is null.
func (b Bool) MarshalJSON() ([]byte, error) {
	if !b.Valid {
		return []byte("null"), nil
	}
	if !b.Bool {
		return []byte("false"), nil
	}
	return []byte("true"), nil
}

// MarshalText implements encoding.TextMarshaler.
// It will encode a blank string if this Bool is null.
func (b Bool) MarshalText() ([]byte, error) {
	if !b.Valid {
		return []byte{}, nil
	}
	if !b.Bool {
		return []byte("false"), nil
	}
	return []byte("true"), nil
}

// SetValid changes this Bool's value and also sets it to be non-null.
func (b *Bool) SetValid(v bool) {
	b.Bool = v
	b.Valid = true
}

// Ptr returns a pointer to this Bool's value, or a nil pointer if this Bool is null.
func (b Bool) Ptr() *bool {
	if !b.Valid {
		return nil
	}
	return &b.Bool
}

// IsZero returns true for invalid Bools, for future omitempty support (Go 1.4?)
// A non-null Bool with a 0 value will not be considered zero.
func (b Bool) IsZero() bool {
	return !b.Valid
}
<|endoftext|>


<commit_before>package accumulate

import (
	"fmt"
	"strings"
	"testing"
)

func echo(c string) string {
	return c
}

var tests = []struct {
	expected  []string
	slice     []string
	converter func(string) string
}{
	{[]string{}, []string{}, echo},
	{[]string{"HELLO", "WORLD"}, []string{"hello", "world"}, strings.ToUpper},
}

func TestAccumulate(t *testing.T) {
	for _, test := range tests {
		actual := Accumulate(test.slice, test.converter)
		if fmt.Sprintf("%s", actual) != fmt.Sprintf("%s", test.expected) {
			t.Errorf("Allergies(%s, %s): expected %s, actual %s", test.slice, test.converter, test.expected, actual)
		}
	}
}
<commit_msg>Tweak test output for accumulate in Go<commit_after>package accumulate

import (
	"fmt"
	"strings"
	"testing"
)

func echo(c string) string {
	return c
}

var tests = []struct {
	expected    []string
	given       []string
	converter   func(string) string
	description string
}{
	{[]string{}, []string{}, echo, "echo"},
	{[]string{"HELLO", "WORLD"}, []string{"hello", "world"}, strings.ToUpper, "upcase"},
}

func TestAccumulate(t *testing.T) {
	for _, test := range tests {
		actual := Accumulate(test.given, test.converter)
		if fmt.Sprintf("%s", actual) != fmt.Sprintf("%s", test.expected) {
			t.Fatalf("Allergies(%s, %s): expected %s, actual %s", test.given, test.converter, test.expected, actual)
		} else {
			t.Logf("PASS: %s %v", test.description, test.given)
		}
	}
}
<|endoftext|>


<commit_before>package common

import (
	"context"
	"path/filepath"
	"testing"

	"github.com/hashicorp/packer/helper/multistep"
)

func TestStepExportVm_impl(t *testing.T) {
	var _ multistep.Step = new(StepExportVm)
}

func TestStepExportVm(t *testing.T) {
	state := testState(t)
	step := new(StepExportVm)

	// ExportVirtualMachine needs the VM name and a path to export to
	vmName := "foo"
	state.Put("vmName", vmName)
	outputDir := "foopath"
	step.OutputDir = outputDir

	driver := state.Get("driver").(*DriverMock)

	// Test the run
	if action := step.Run(context.Background(), state); action != multistep.ActionContinue {
		t.Fatalf("Bad action: %v", action)
	}
	if _, ok := state.GetOk("error"); ok {
		t.Fatal("Should NOT have error")
	}

	// Test the driver
	if !driver.ExportVirtualMachine_Called {
		t.Fatal("Should have called ExportVirtualMachine")
	}
	if driver.ExportVirtualMachine_Path != outputDir {
		t.Fatalf("Should call with correct path. Got: %s Wanted: %s",
			driver.ExportVirtualMachine_Path, outputDir)
	}
	if driver.ExportVirtualMachine_VmName != vmName {
		t.Fatalf("Should call with correct vm name. Got: %s Wanted: %s",
			driver.ExportVirtualMachine_VmName, vmName)
	}

	if !driver.PreserveLegacyExportBehaviour_Called {
		t.Fatal("Should have called PreserveLegacyExportBehaviour")
	}
	exportPath := filepath.Join(outputDir, vmName)
	if driver.PreserveLegacyExportBehaviour_SrcPath != exportPath {
		t.Fatalf("Should call with correct srcPath. Got: %s Wanted: %s",
			driver.PreserveLegacyExportBehaviour_SrcPath, exportPath)
	}
	if driver.PreserveLegacyExportBehaviour_DstPath != outputDir {
		t.Fatalf("Should call with correct dstPath. Got: %s Wanted: %s",
			driver.PreserveLegacyExportBehaviour_DstPath, outputDir)
	}

}

func TestStepExportVm_skip(t *testing.T) {
	state := testState(t)
	step := new(StepExportVm)
	step.SkipExport = true

	// ExportVirtualMachine needs the VM name and a path to export to
	vmName := "foo"
	state.Put("vmName", vmName)
	outputDir := "foopath"
	step.OutputDir = outputDir

	driver := state.Get("driver").(*DriverMock)

	// Test the run
	if action := step.Run(context.Background(), state); action != multistep.ActionContinue {
		t.Fatalf("Bad action: %v", action)
	}
	if _, ok := state.GetOk("error"); ok {
		t.Fatalf("Should NOT have error")
	}

	// Test the driver
	if driver.ExportVirtualMachine_Called {
		t.Fatal("Should not have called ExportVirtualMachine")
	}

	if driver.PreserveLegacyExportBehaviour_Called {
		t.Fatal("Should NOT have called PreserveLegacyExportBehaviour")
	}
}
<commit_msg>Fix up tests. Ensure export step stores the export path in state<commit_after>package common

import (
	"context"
	"path/filepath"
	"testing"

	"github.com/hashicorp/packer/helper/multistep"
)

func TestStepExportVm_impl(t *testing.T) {
	var _ multistep.Step = new(StepExportVm)
}

func TestStepExportVm(t *testing.T) {
	state := testState(t)
	step := new(StepExportVm)

	// ExportVirtualMachine needs the VM name and a path to export to
	vmName := "foo"
	state.Put("vmName", vmName)
	outputDir := "foopath"
	step.OutputDir = outputDir

	driver := state.Get("driver").(*DriverMock)

	// Test the run
	if action := step.Run(context.Background(), state); action != multistep.ActionContinue {
		t.Fatalf("Bad action: %v", action)
	}
	if _, ok := state.GetOk("error"); ok {
		t.Fatal("Should NOT have error")
	}

	// Test the driver
	if !driver.ExportVirtualMachine_Called {
		t.Fatal("Should have called ExportVirtualMachine")
	}
	if driver.ExportVirtualMachine_Path != outputDir {
		t.Fatalf("Should call with correct path. Got: %s Wanted: %s",
			driver.ExportVirtualMachine_Path, outputDir)
	}
	if driver.ExportVirtualMachine_VmName != vmName {
		t.Fatalf("Should call with correct vm name. Got: %s Wanted: %s",
			driver.ExportVirtualMachine_VmName, vmName)
	}

	// Test we stored the export path in the statebag and it is correct
	expectedPath := filepath.Join(outputDir, vmName)
	if exportPath, ok := state.GetOk("export_path"); !ok {
		t.Fatal("Should set export_path")
	} else if exportPath != expectedPath {
		t.Fatalf("Bad path stored for export_path. Got: %#v Wanted: %#v", exportPath, expectedPath)
	}
}

func TestStepExportVm_skip(t *testing.T) {
	state := testState(t)
	step := new(StepExportVm)
	step.SkipExport = true

	// ExportVirtualMachine needs the VM name and a path to export to
	vmName := "foo"
	state.Put("vmName", vmName)
	outputDir := "foopath"
	step.OutputDir = outputDir

	driver := state.Get("driver").(*DriverMock)

	// Test the run
	if action := step.Run(context.Background(), state); action != multistep.ActionContinue {
		t.Fatalf("Bad action: %v", action)
	}
	if _, ok := state.GetOk("error"); ok {
		t.Fatalf("Should NOT have error")
	}

	// Test the driver
	if driver.ExportVirtualMachine_Called {
		t.Fatal("Should NOT have called ExportVirtualMachine")
	}

	// Should not store the export path in the statebag
	if _, ok := state.GetOk("export_path"); ok {
		t.Fatal("Should NOT have stored export_path in the statebag")
	}
}
<|endoftext|>


<commit_before>package newManager

import (
	t "testing"
	"github.com/AitorGuerrero/UserGo/user"
	"github.com/AitorGuerrero/UserGo/implementation/services"
)

var id = "dabfe523-fae0-4a1c-8923-5e51ffeb3e91"
var uuidId, _ = user.ParseId(id)
var passkey = "userPasskey"
var namespace = "userPasskey"

var managerSource = services.ManagerSource()

var com = Command{managerSource, services.UserFactory()}

func TestIfTheIdIsAInvalidUuidShouldThrowAnError(t *t.T) {
	err := com.Execute(Request{"incorrectUUID", passkey, namespace})
	if nil == err {
		t.Error("Should return an error")
	}
}

func TestIfPasskeyIsBlankShouldReturnAError(t *t.T) {
	err := com.Execute(Request{id, "", namespace})
	if nil == err {
		t.Error()
	}
}

func TestShouldAddInASource(t *t.T) {
	com.Execute(Request{id, passkey, namespace})
	manager, err := managerSource.Get(uuidId)
	if nil != err {
		t.Error(err, uuidId, managerSource)
		return
	}
	if !manager.Id().Equal(uuidId) {
		t.Error("the user stored is not the same")
		return
	}
}

func TestShouldCreateAToken(t * t.T) {
	com.Execute(Request{id, passkey, namespace})
	manager, _ := managerSource.Get(uuidId)
	if !manager.HasToken() {
		t.Error("Should create a token")
	}
}
<commit_msg>sources uses pointers<commit_after>package newManager

import (
	t "testing"
	"github.com/AitorGuerrero/UserGo/user"
	"github.com/AitorGuerrero/UserGo/implementation/services"
)

var id = "dabfe523-fae0-4a1c-8923-5e51ffeb3e91"
var uuidId, _ = user.ParseId(id)
var passkey = "userPasskey"
var namespace = "userPasskey"

var managerSource = services.ManagerSource()

var com = Command{managerSource, services.UserFactory()}

func TestIfTheIdIsAInvalidUuidShouldThrowAnError(t *t.T) {
	err := com.Execute(Request{"incorrectUUID", passkey, namespace})
	if nil == err {
		t.Error()
	}
}

func TestIfPasskeyIsBlankShouldReturnAError(t *t.T) {
	err := com.Execute(Request{id, "", namespace})
	if nil == err {
		t.Error()
	}
}

func TestShouldAddInASource(t *t.T) {
	com.Execute(Request{id, passkey, namespace})
	manager, err := managerSource.Get(uuidId)
	if nil != err {
		t.Error("Error loading the user:", err)
		return
	}
	if !manager.Id().Equal(uuidId) {
		t.Error("the user stored is not the same")
		return
	}
}

func TestShouldCreateAToken(t * t.T) {
	com.Execute(Request{id, passkey, namespace})
	manager, _ := managerSource.Get(uuidId)
	if !manager.HasToken() {
		t.Error("Should create a token")
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2015 The Kubernetes 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 errors

import (
	"errors"
)

var (
	NoSuchPodErr               = errors.New("No such pod exists")
	NoSuchTaskErr              = errors.New("No such task exists")
	ReconciliationCancelledErr = errors.New("explicit task reconciliation cancelled")
	NoSuitableOffersErr        = errors.New("No suitable offers for pod/task")
)
<commit_msg> The first letter should be small in errors.New<commit_after>/*
Copyright 2015 The Kubernetes 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 errors

import (
	"errors"
)

var (
	NoSuchPodErr               = errors.New("no such pod exists")
	NoSuchTaskErr              = errors.New("no such task exists")
	ReconciliationCancelledErr = errors.New("explicit task reconciliation cancelled")
	NoSuitableOffersErr        = errors.New("no suitable offers for pod/task")
)
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

var FIELD = regexp.MustCompile(`(?:[^,\\]|\\.)*`)

type Selector interface {
	DropHeaders() bool
	ParseHeaders(headers []string) error
	Select(recode []string) ([]string, error)
}

type All struct {
}

func NewAll() *All {
	return &All{}
}

func (a *All) DropHeaders() bool {
	return false
}

func (a *All) ParseHeaders(headers []string) error {
	return nil
}

func (a *All) Select(recode []string) ([]string, error) {
	return recode, nil
}

type Indexes struct {
	indexes []int
}

func NewIndexes(list string) (*Indexes, error) {
	if list == "" {
		return &Indexes{
			indexes: []int{},
		}, nil
	}
	fields := FIELD.FindAllString(list, -1)

	indexes := make([]int, len(fields))
	for i, field := range fields {
		index, err := strconv.Atoi(field)
		if err != nil {
			return nil, err
		}
		if index < 1 {
			return nil, fmt.Errorf("indexes are numberd from 1")
		}
		indexes[i] = index - 1
	}
	return &Indexes{
		indexes: indexes,
	}, nil
}

func (i *Indexes) DropHeaders() bool {
	return false
}

func (i *Indexes) ParseHeaders(headers []string) error {
	return nil
}

func (i *Indexes) Select(recode []string) ([]string, error) {
	a := make([]string, len(i.indexes))
	for j, index := range i.indexes {
		if index >= 0 && index < len(recode) {
			a[j] = recode[index]
		}
	}
	return a, nil
}

type Headers struct {
	indexes []int
	headers []string
}

func NewHeaders(list string) (*Headers, error) {
	if list == "" {
		return &Headers{
			headers: []string{},
		}, nil
	}

	headers := FIELD.FindAllString(list, -1)
	for i := 0; i < len(headers); i++ {
		headers[i] = strings.Replace(headers[i], `\,`, `,`, -1)
	}
	return &Headers{
		headers: headers,
	}, nil
}

func (h *Headers) DropHeaders() bool {
	return true
}

func (h *Headers) ParseHeaders(headers []string) error {
	indexMap := make(map[string]int)
	for i, header := range headers {
		if _, ok := indexMap[header]; ok {
			return fmt.Errorf("%q: duplicated header", header)
		}
		indexMap[header] = i
	}

	h.indexes = make([]int, len(h.headers))
	for i, header := range h.headers {
		if index, ok := indexMap[header]; ok {
			h.indexes[i] = index
		} else {
			h.indexes[i] = -1
		}
	}
	return nil
}

func (h *Headers) Select(recode []string) ([]string, error) {
	a := make([]string, len(h.indexes))
	for i, index := range h.indexes {
		if index != -1 {
			a[i] = recode[index]
		}
	}
	return a, nil
}
<commit_msg>Rename FIELD to HEADER<commit_after>package main

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

var HEADER = regexp.MustCompile(`(?:[^,\\]|\\.)*`)

type Selector interface {
	DropHeaders() bool
	ParseHeaders(headers []string) error
	Select(recode []string) ([]string, error)
}

type All struct {
}

func NewAll() *All {
	return &All{}
}

func (a *All) DropHeaders() bool {
	return false
}

func (a *All) ParseHeaders(headers []string) error {
	return nil
}

func (a *All) Select(recode []string) ([]string, error) {
	return recode, nil
}

type Indexes struct {
	indexes []int
}

func NewIndexes(list string) (*Indexes, error) {
	if list == "" {
		return &Indexes{
			indexes: []int{},
		}, nil
	}
	fields := HEADER.FindAllString(list, -1)

	indexes := make([]int, len(fields))
	for i, field := range fields {
		index, err := strconv.Atoi(field)
		if err != nil {
			return nil, err
		}
		if index < 1 {
			return nil, fmt.Errorf("indexes are numberd from 1")
		}
		indexes[i] = index - 1
	}
	return &Indexes{
		indexes: indexes,
	}, nil
}

func (i *Indexes) DropHeaders() bool {
	return false
}

func (i *Indexes) ParseHeaders(headers []string) error {
	return nil
}

func (i *Indexes) Select(recode []string) ([]string, error) {
	a := make([]string, len(i.indexes))
	for j, index := range i.indexes {
		if index >= 0 && index < len(recode) {
			a[j] = recode[index]
		}
	}
	return a, nil
}

type Headers struct {
	indexes []int
	headers []string
}

func NewHeaders(list string) (*Headers, error) {
	if list == "" {
		return &Headers{
			headers: []string{},
		}, nil
	}

	headers := HEADER.FindAllString(list, -1)
	for i := 0; i < len(headers); i++ {
		headers[i] = strings.Replace(headers[i], `\,`, `,`, -1)
	}
	return &Headers{
		headers: headers,
	}, nil
}

func (h *Headers) DropHeaders() bool {
	return true
}

func (h *Headers) ParseHeaders(headers []string) error {
	indexMap := make(map[string]int)
	for i, header := range headers {
		if _, ok := indexMap[header]; ok {
			return fmt.Errorf("%q: duplicated header", header)
		}
		indexMap[header] = i
	}

	h.indexes = make([]int, len(h.headers))
	for i, header := range h.headers {
		if index, ok := indexMap[header]; ok {
			h.indexes[i] = index
		} else {
			h.indexes[i] = -1
		}
	}
	return nil
}

func (h *Headers) Select(recode []string) ([]string, error) {
	a := make([]string, len(h.indexes))
	for i, index := range h.indexes {
		if index != -1 {
			a[i] = recode[index]
		}
	}
	return a, nil
}
<|endoftext|>


<commit_before>package datalayer

import (
	"encoding/json"
	"os"
	"path/filepath"
	"regexp"
)

const MAX_VOLUME_NAME_LENGTH int = 40

// ClusterHQ data layer, naive vfs (directory-based) implementation

func ValidVolumeName(volumeName string) bool {
	var validVolumeRegex = regexp.MustCompile(`^[a-zA-Z]+[a-zA-Z0-9-]*$`)
	return validVolumeRegex.MatchString(volumeName) && len(volumeName) <= MAX_VOLUME_NAME_LENGTH
}

func VolumeExists(basePath string, volumeName string) bool {
	volumePath := filepath.FromSlash(basePath + "/" + volumeName)
	_, err := os.Stat(volumePath)
	return err == nil
}

func setActiveVolume(basePath, volumeName string) error {
	currentVolumeJsonPath := filepath.FromSlash(basePath + "/" + "current_volume.json")
	currentVolumeContent := map[string]string{
		"current_volume": volumeName,
	}
	// Create or update this file
	file, err := os.Create(currentVolumeJsonPath)
	if err != nil {
		return err
	}
	encoder := json.NewEncoder(file)
	encoder.Encode(currentVolumeContent)
	file.Sync()
	return nil
}

func CreateVolume(basePath string, volumeName string) error {
	volumePath := filepath.FromSlash(basePath + "/" + volumeName)
	// TODO Factor this into a data layer object.
	os.MkdirAll(volumePath, 0777) // XXX SEC
	err := setActiveVolume(basePath, volumeName)
	if err != nil {
		return err
	}
	return nil
}
func CreateVariant(basePath, volumeName, variantName string) error {
	// XXX Variants are meant to be tagged commits???
	variantPath := filepath.FromSlash(basePath + "/" + volumeName + "/branches/master")
	os.MkdirAll(variantPath, 0777) // XXX SEC
	return nil
}

func SwitchVolume(basePath, volumeName string) error {
	return setActiveVolume(basePath, volumeName)
}
<commit_msg>Close the file using a defer<commit_after>package datalayer

import (
	"encoding/json"
	"os"
	"path/filepath"
	"regexp"
)

const MAX_VOLUME_NAME_LENGTH int = 40

// ClusterHQ data layer, naive vfs (directory-based) implementation

func ValidVolumeName(volumeName string) bool {
	var validVolumeRegex = regexp.MustCompile(`^[a-zA-Z]+[a-zA-Z0-9-]*$`)
	return validVolumeRegex.MatchString(volumeName) && len(volumeName) <= MAX_VOLUME_NAME_LENGTH
}

func VolumeExists(basePath string, volumeName string) bool {
	volumePath := filepath.FromSlash(basePath + "/" + volumeName)
	_, err := os.Stat(volumePath)
	return err == nil
}

func setActiveVolume(basePath, volumeName string) error {
	currentVolumeJsonPath := filepath.FromSlash(basePath + "/" + "current_volume.json")
	currentVolumeContent := map[string]string{
		"current_volume": volumeName,
	}
	// Create or update this file
	file, err := os.Create(currentVolumeJsonPath)
	if err != nil {
		return err
	}
	defer file.Close()
	encoder := json.NewEncoder(file)
	encoder.Encode(currentVolumeContent)
	return nil
}

func CreateVolume(basePath string, volumeName string) error {
	volumePath := filepath.FromSlash(basePath + "/" + volumeName)
	// TODO Factor this into a data layer object.
	os.MkdirAll(volumePath, 0777) // XXX SEC
	err := setActiveVolume(basePath, volumeName)
	if err != nil {
		return err
	}
	return nil
}
func CreateVariant(basePath, volumeName, variantName string) error {
	// XXX Variants are meant to be tagged commits???
	variantPath := filepath.FromSlash(basePath + "/" + volumeName + "/branches/master")
	os.MkdirAll(variantPath, 0777) // XXX SEC
	return nil
}

func SwitchVolume(basePath, volumeName string) error {
	return setActiveVolume(basePath, volumeName)
}
<|endoftext|>


<commit_before>package gcss

import (
	"bytes"
	"fmt"
	"io"
	"strings"
)

// selector represents a selector of CSS.
type selector struct {
	elementBase
	name string
	sels []*selector
	decs []*declaration
}

// WriteTo writes the selector to the writer.
func (sel *selector) WriteTo(w io.Writer) (int64, error) {
	bf := new(bytes.Buffer)

	// Write the declarations.
	if len(sel.decs) > 0 {
		names, err := sel.names()

		if err != nil {
			return 0, err
		}

		if _, err := bf.WriteString(names + openBrace); err != nil {
			return 0, err
		}

		for _, dec := range sel.decs {
			if _, err := bf.WriteString(dec.property + colon + dec.value + semicolon); err != nil {
				return 0, err
			}
		}

		if _, err := bf.WriteString(closeBrace); err != nil {
			return 0, err
		}
	}

	// Write the child selectors.
	for _, childSel := range sel.sels {
		if _, err := childSel.WriteTo(bf); err != nil {
			return 0, err
		}
	}

	n, err := w.Write(bf.Bytes())

	return int64(n), err
}

// AppendChild appends a selector or declaration to the selector.
func (sel *selector) AppendChild(child element) error {
	switch child.(type) {
	case *selector:
		sel.sels = append(sel.sels, child.(*selector))
	case *declaration:
		sel.decs = append(sel.decs, child.(*declaration))
	default:
		return fmt.Errorf("invalid child's type [line: %d]", sel.ln.no)
	}

	return nil
}

// names returns the selector names.
func (sel *selector) names() (string, error) {
	if sel.parent == nil {
		names := strings.Split(sel.name, comma)

		for i, name := range names {
			names[i] = strings.TrimSpace(name)
		}

		return strings.Join(names, comma), nil
	}

	bf := new(bytes.Buffer)

	names, err := sel.parent.(*selector).names()

	if err != nil {
		return "", err
	}

	for _, parentS := range strings.Split(names, comma) {
		for _, s := range strings.Split(sel.name, comma) {
			s = strings.TrimSpace(s)

			if strings.HasPrefix(s, ampersand) {
				s = strings.TrimPrefix(s, ampersand)
			} else {
				s = space + s
			}

			if bf.Len() > 0 {
				if _, err := bf.WriteString(comma); err != nil {
					return "", err
				}
			}

			if _, err := bf.WriteString(parentS + s); err != nil {
				return "", err
			}
		}
	}

	return bf.String(), nil
}

// newSelector creates and returns a selector.
func newSelector(ln *line, parent element) *selector {
	return &selector{
		elementBase: newElementBase(ln, parent),
		name:        strings.TrimSpace(ln.s),
	}
}
<commit_msg>Update selector.go<commit_after>package gcss

import (
	"bytes"
	"fmt"
	"io"
	"strings"
)

// selector represents a selector of CSS.
type selector struct {
	elementBase
	name string
	sels []*selector
	decs []*declaration
}

// WriteTo writes the selector to the writer.
func (sel *selector) WriteTo(w io.Writer) (int64, error) {
	bf := new(bytes.Buffer)

	// Write the declarations.
	if len(sel.decs) > 0 {
		bf.WriteString(sel.names())
		bf.WriteString(openBrace)

		for _, dec := range sel.decs {
			bf.WriteString(dec.property)
			bf.WriteString(colon)
			bf.WriteString(dec.value)
			bf.WriteString(semicolon)
		}

		bf.WriteString(closeBrace)
	}

	// Write the child selectors.
	for _, childSel := range sel.sels {
		if _, err := childSel.WriteTo(bf); err != nil {
			return 0, err
		}
	}

	n, err := w.Write(bf.Bytes())

	return int64(n), err
}

// AppendChild appends a selector or declaration to the selector.
func (sel *selector) AppendChild(child element) error {
	switch child.(type) {
	case *selector:
		sel.sels = append(sel.sels, child.(*selector))
	case *declaration:
		sel.decs = append(sel.decs, child.(*declaration))
	default:
		return fmt.Errorf("invalid child's type [line: %d]", sel.ln.no)
	}

	return nil
}

// names returns the selector names.
func (sel *selector) names() string {
	bf := new(bytes.Buffer)

	switch sel.parent.(type) {
	case nil:
		for _, name := range strings.Split(sel.name, comma) {
			if bf.Len() > 0 {
				bf.WriteString(comma)
			}

			bf.WriteString(strings.TrimSpace(name))
		}
	case *selector:
		for _, parentS := range strings.Split(sel.parent.(*selector).names(), comma) {
			for _, s := range strings.Split(sel.name, comma) {
				if bf.Len() > 0 {
					bf.WriteString(comma)
				}

				bf.WriteString(parentS)

				s = strings.TrimSpace(s)

				if strings.HasPrefix(s, ampersand) {
					bf.WriteString(strings.TrimPrefix(s, ampersand))
				} else {
					bf.WriteString(space)
					bf.WriteString(s)
				}
			}
		}
	}

	return bf.String()
}

// newSelector creates and returns a selector.
func newSelector(ln *line, parent element) *selector {
	return &selector{
		elementBase: newElementBase(ln, parent),
		name:        strings.TrimSpace(ln.s),
	}
}
<|endoftext|>


<commit_before>package connection

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"math/rand"
	"net"
	"os/exec"
)

type NoTLSConnErr string

func (f NoTLSConnErr) Error() string {
	return fmt.Sprintf("No TLS Conn Received")
}

func Connect(domain, cipherscanbinPath string) ([]byte, error) {

	ip := getRandomIP(domain)

	if ip == "" {
		e := fmt.Errorf("Could not resolve ip for: ", domain)
		log.Println(e)
		return nil, e
	}

	cmd := cipherscanbinPath + " -j --curves -servername " + domain + " " + ip + ":443 "
	log.Println(cmd)
	comm := exec.Command("bash", "-c", cmd)
	var out bytes.Buffer
	var stderr bytes.Buffer
	comm.Stdout = &out
	comm.Stderr = &stderr
	err := comm.Run()
	if err != nil {
		log.Println(err)
		return nil, err
	}

	info := CipherscanOutput{}
	err = json.Unmarshal([]byte(out.String()), &info)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	info.Target = domain
	info.IP = ip

	c, err := info.Stored()

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

	return json.Marshal(c)
}

func getRandomIP(domain string) string {
	ips, err := net.LookupIP(domain)
	if err != nil {
		return ""
	}

	max := len(ips)

	for {
		if max == 0 {
			return ""
		}
		index := rand.Intn(len(ips))

		if ips[index].To4() != nil {
			return ips[index].String()
		} else {
			ips = append(ips[:index], ips[index+1:]...)
		}
		max--
	}
}
<commit_msg>Disable tolerance testing in cipherscan<commit_after>package connection

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"math/rand"
	"net"
	"os/exec"
)

type NoTLSConnErr string

func (f NoTLSConnErr) Error() string {
	return fmt.Sprintf("No TLS Conn Received")
}

func Connect(domain, cipherscanbinPath string) ([]byte, error) {

	ip := getRandomIP(domain)

	if ip == "" {
		e := fmt.Errorf("Could not resolve ip for: ", domain)
		log.Println(e)
		return nil, e
	}

	cmd := cipherscanbinPath + " --no-tolerance -j --curves -servername " + domain + " " + ip + ":443 "
	log.Println(cmd)
	comm := exec.Command("bash", "-c", cmd)
	var out bytes.Buffer
	var stderr bytes.Buffer
	comm.Stdout = &out
	comm.Stderr = &stderr
	err := comm.Run()
	if err != nil {
		log.Println(err)
		return nil, err
	}

	info := CipherscanOutput{}
	err = json.Unmarshal([]byte(out.String()), &info)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	info.Target = domain
	info.IP = ip

	c, err := info.Stored()

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

	return json.Marshal(c)
}

func getRandomIP(domain string) string {
	ips, err := net.LookupIP(domain)
	if err != nil {
		return ""
	}

	max := len(ips)

	for {
		if max == 0 {
			return ""
		}
		index := rand.Intn(len(ips))

		if ips[index].To4() != nil {
			return ips[index].String()
		} else {
			ips = append(ips[:index], ips[index+1:]...)
		}
		max--
	}
}
<|endoftext|>