<commit_before>package fsutils

func copyFile(src string, dst string) (int64, error) {
	srcFile, err := os.Open(src)
	if err != nil {
		return -1, err
	}

	defer srcFile.Close()
	dstFile, err := os.Create(dst)
	if err != nil {
		return -1, err
	}

	read, err := io.Copy(dstFile, srcFile)
	if err != nil {
		dstFile.Close()
		return -1, err
	}

	err = dstFile.Close()
	return read, err
}

func dirExists(filePath string) bool {
	stat, err := os.Stat(filePath)
	if err != nil || !stat.IsDir() {
		return false
	}

	return true
}

func clearDirectory(dirPath string) error {
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		return err
	}

	for _, f := range files {
		p := filepath.Join(dirPath, f.Name())
		if f.IsDir() {
			err = os.RemoveAll(p)
		} else {
			err = os.Remove(p)
		}

		if err != nil {
			return err
		}
	}

	return nil
}

func fileExists(filePath string) bool {
	_, err := os.Stat(filePath)
	if err != nil {
		return false
	}

	return true
}
<commit_msg>fix fsutils and export functions<commit_after>package fsutils

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

func CopyFile(src string, dst string) (int64, error) {
	srcFile, err := os.Open(src)
	if err != nil {
		return -1, err
	}

	defer srcFile.Close()
	dstFile, err := os.Create(dst)
	if err != nil {
		return -1, err
	}

	read, err := io.Copy(dstFile, srcFile)
	if err != nil {
		dstFile.Close()
		return -1, err
	}

	err = dstFile.Close()
	return read, err
}

func DirExists(filePath string) bool {
	stat, err := os.Stat(filePath)
	if err != nil || !stat.IsDir() {
		return false
	}

	return true
}

func ClearDirectory(dirPath string) error {
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		return err
	}

	for _, f := range files {
		p := filepath.Join(dirPath, f.Name())
		if f.IsDir() {
			err = os.RemoveAll(p)
		} else {
			err = os.Remove(p)
		}

		if err != nil {
			return err
		}
	}

	return nil
}

func FileExists(filePath string) bool {
	_, err := os.Stat(filePath)
	if err != nil {
		return false
	}

	return true
}
<|endoftext|>


<commit_before>package ndb

import (
	"testing"
	"os"
	"fmt"
	"strconv"
)

func LoadTestData() *Node {

	dataSource := "local"

	if dataSource == "local" {

		NewChild := func(node string, name string, age string, sex string) *Node {
			child := new(Node)

			child.SetName(node)
			child.SetValue("name", []string{name})
			child.SetValue("age", []string{age})
			child.SetValue("sex", []string{sex})

			return child
		}

		child1 := NewChild("child", "jim", "20", "male")
		child2 := NewChild("child", "lily", "17", "female")
		child3 := NewChild("child", "tom", "28", "male")
		child4 := NewChild("nephew", "lucy", "12", "female")

		parent := new(Node)
		parent.SetName("parent")
		parent.SetValue("name", []string{"green"})
		parent.AddChildren([]*Node{child1, child2, child3, child4})

		root := new(Node)
		root.SetName("root")
		root.AddChild(parent)

		node := new(Node)
		node.AddChild(root)

		return node
	} else {
		node, _ := Read(dataSource)
		return node
	}
}

func ValueAssert(node *Node, field string, expect string, query string) {
	if node.GetValue(field)[0] != expect {
		fmt.Printf("expect %s but %s, %s\n", expect, node.GetValue(field)[0], query)
	}
}

func NullAssert(node *Node, field string, query string) {
	length := len(node.GetValue(field))
	if length > 0 {
		fmt.Printf("expect null but not, %s\n", query)
	}
}

func LengthAssert(nodes []*Node, expect int, query string) {
	if len(nodes) != expect {
		fmt.Printf("expect %d but %d, %s\n", expect, len(nodes), query)
	}
}

func TestStart(t *testing.T) {
	pid := os.Getpid()
	fmt.Println("PID : " + strconv.Itoa(pid))
}

func TestExits(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "exist:root->parent->child->name:jim"
		result, found, _ := Execute(node, query)
		if result != nil && found == false {
			t.Fatalf("exits test fail : %s", query)
		}

		query = "exist:root->parent->child->sex:male && name:m$"
		result, found, _ = Execute(node, query)
		if found == false {
			t.Fatalf("exits test fail : %s", query)
		}

		query = "exist:root->parent->child->sex:female && name:m$"
		result, found, _ = Execute(node, query)
		if found == true {
			t.Fatalf("exits test fail : %s", query)
		}
	}
}

func TestOne(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "one:root->parent->child->sex:male"
		result, _, _ := Execute(node, query)
		child, ok := result.(*Node)
		if ok {
			if child.GetValueString("name") != "jim" || child.GetValueString("age") != "20" {
				t.Fatalf("one test fail : %s", query)
			}
		}
	}
}

func TestSelect(t *testing.T) {
	node := LoadTestData()

	if node != nil {

		SelectAssert := func(query string, expect []string) {
			result, found, _ := Execute(node, query)
			if found {
				children, ok := result.([]*Node)
				if ok && len(children) == len(expect) {
					for i := 0; i < len(expect); i++ {
						child := children[i]
						if child.GetValueString("name") != expect[i] {
							t.Fatalf("select test fail : %s", query)
							break
						}
					}
				} else {
					t.Fatalf("select test fail len(children) %d != %d : %s", len(children), len(expect), query)
				}
			} else {
				t.Fatalf("select test fail : %s", query)
			}
		}

		query := "select:root->parent->child->name:/.*m/"
		SelectAssert(query, []string{"jim", "tom"})

		query = "select:root->parent->child->age:[15,25]"
		SelectAssert(query, []string{"jim", "lily"})

		query = "select:root->parent->child->sex:^fe"
		SelectAssert(query, []string{"lily"})

		query = "select:root->parent->child->name:m$"
		SelectAssert(query, []string{"jim", "tom"})

		query = "select:root->parent->child->sex:male && age:[15,25]"
		SelectAssert(query, []string{"jim"})

		query = "select:root->parent->child"
		SelectAssert(query, []string{"jim", "lily", "tom"})

		query = "select:root->parent->:/child|nephew/->sex:female"
		SelectAssert(query, []string{"lily", "lucy"})
	}
}

func TestUpdate(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "update:root->parent->child->name:jim !! age=21, address=China"
		result, found, _ := Execute(node, query)
		if found {
			updateResult, _, _ := Execute(result.(*Node), "one:root->parent->child->name:jim")
			child, ok := updateResult.(*Node)
			if ok {
				ValueAssert(child, "name", "jim", query)
				ValueAssert(child, "age", "21", query)
				ValueAssert(child, "address", "China", query)
			} else {
				t.Fatalf("update test fail : %s", query)
			}
		} else {
			t.Fatalf("update test fail : %s", query)
		}
	}
}

func TestDelete(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "delete:root->parent->child->name:jim !! [sex, age]"
		result, found, _ := Execute(node, query)
		if found {
			deleteResult, _, _ := Execute(result.(*Node), "one:root->parent->child->name:jim")
			child, ok := deleteResult.(*Node)
			if ok {
				ValueAssert(child, "name", "jim", query)
				NullAssert(child, "sex", query)
				NullAssert(child, "age", query)
			} else {
				t.Fatalf("delete test fail : %s", query)
			}
		} else {
			t.Fatalf("delete test fail : %s", query)
		}

		query = "delete:root->parent->child->name:jim !! block"
		result, found, _ = Execute(node, query)
		if found {
			deleteResult, _, _ := Execute(result.(*Node), "select:root->parent->child->name:jim")
			children, _ := deleteResult.([]*Node)
			LengthAssert(children, 0, query)
		} else {
			t.Fatalf("delete test fail : %s", query)
		}
	}
}

func TestInsert(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "insert:root->parent->child !! name=bill, sex=male, age=31"
		result, _, _ := Execute(node, query)

		insertResult, _, _ := Execute(result.(*Node), "one:root->parent->child->name:bill")
		child, ok := insertResult.(*Node)
		if ok {
			ValueAssert(child, "name", "bill", query)
			ValueAssert(child, "sex", "male", query)
			ValueAssert(child, "age", "31", query)
		} else {
			t.Fatalf("insert test fail : %s", query)
		}
	}
}

/*
func TestRedirect(t *testing.T) {

	node := LoadTestData()
	if node != nil {
		query := "select:root->parent->:/child|nephew/->sex:female >> select.ndb"
		Execute(node, query)
		tempNode, _ := Read("select.ndb")
		result, found, err := Execute(tempNode, "select:result->sex:female")
		if found && err == nil {
			children := result.([]*Node)

			LengthAssert(children, 2, query)
			ValueAssert(children[0], "name", "lucy", query)
			ValueAssert(children[1], "name", "lily", query)
		}

		query = "insert:root->parent->child !! name=bill, sex=male, age=31 >> insert.ndb"
		Execute(node, query)
		tempNode, _ = Read("insert.ndb")
		result, found, err = Execute(tempNode, "select:root->parent->child->name:bill")
		if found && err == nil {
			children := result.([]*Node)

			LengthAssert(children, 1, query)
			ValueAssert(children[0], "name", "bill", query)
			ValueAssert(children[0], "sex", "male", query)
			ValueAssert(children[0], "age", "31", query)
		}

		query = "update:root->parent->child->name:jim !! age=21, address=China >> update.ndb"
		Execute(node, query)
		tempNode, _ = Read("update.ndb")
		result, found, err = Execute(tempNode, "select:root->parent->child->name:jim")
		if found && err == nil {
			children := result.([]*Node)
			LengthAssert(children, 1, query)
			ValueAssert(children[0], "name", "jim", query)
			ValueAssert(children[0], "address", "China", query)
			ValueAssert(children[0], "age", "21", query)
		}

		tempFiles := []string{"select.ndb", "insert.ndb", "update.ndb"}
		for _, tempFile := range tempFiles {
			os.Remove(tempFile)
		}
	}
}
*/

func TestScript(t *testing.T) {
	node := LoadTestData()
	if node != nil {
		query := "script:d:/example.script"
		result, _, _ := Execute(node, query)
		tempNode, ok := result.(*Node)

		if ok {
			selectResult, found, err := Execute(tempNode, "select:root->parent->child->name:bill")
			if found && err == nil {
				children := selectResult.([]*Node)
				LengthAssert(children, 1, query)
				ValueAssert(children[0], "name", "bill", query)
				ValueAssert(children[0], "sex", "male", query)
				ValueAssert(children[0], "age", "31", query)
			}

			selectResult, found, err = Execute(tempNode, "select:root->parent->child->name:lily")
			if found && err == nil {
				children := selectResult.([]*Node)
				LengthAssert(children, 1, query)
				ValueAssert(children[0], "name", "lily", query)
				ValueAssert(children[0], "sex", "China", query)
				ValueAssert(children[0], "age", "21", query)
			}

			selectResult, found, err = Execute(tempNode, "select:root->parent->child->name:jim")
			if found && err == nil {
				children := selectResult.([]*Node)
				LengthAssert(children, 1, query)
				ValueAssert(children[0], "name", "jim", query)
				NullAssert(children[0], "sex", query)
				NullAssert(children[0], "age", query)
			}
		}
	}
}<commit_msg>Update test example path<commit_after>package ndb

import (
	"testing"
	"os"
	"fmt"
	"strconv"
)

func LoadTestData() *Node {

	dataSource := "local"

	if dataSource == "local" {

		NewChild := func(node string, name string, age string, sex string) *Node {
			child := new(Node)

			child.SetName(node)
			child.SetValue("name", []string{name})
			child.SetValue("age", []string{age})
			child.SetValue("sex", []string{sex})

			return child
		}

		child1 := NewChild("child", "jim", "20", "male")
		child2 := NewChild("child", "lily", "17", "female")
		child3 := NewChild("child", "tom", "28", "male")
		child4 := NewChild("nephew", "lucy", "12", "female")

		parent := new(Node)
		parent.SetName("parent")
		parent.SetValue("name", []string{"green"})
		parent.AddChildren([]*Node{child1, child2, child3, child4})

		root := new(Node)
		root.SetName("root")
		root.AddChild(parent)

		node := new(Node)
		node.AddChild(root)

		return node
	} else {
		node, _ := Read(dataSource)
		return node
	}
}

func ValueAssert(node *Node, field string, expect string, query string) {
	if node.GetValue(field)[0] != expect {
		fmt.Printf("expect %s but %s, %s\n", expect, node.GetValue(field)[0], query)
	}
}

func NullAssert(node *Node, field string, query string) {
	length := len(node.GetValue(field))
	if length > 0 {
		fmt.Printf("expect null but not, %s\n", query)
	}
}

func LengthAssert(nodes []*Node, expect int, query string) {
	if len(nodes) != expect {
		fmt.Printf("expect %d but %d, %s\n", expect, len(nodes), query)
	}
}

func TestStart(t *testing.T) {
	pid := os.Getpid()
	fmt.Println("PID : " + strconv.Itoa(pid))
}

func TestExits(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "exist:root->parent->child->name:jim"
		result, found, _ := Execute(node, query)
		if result != nil && found == false {
			t.Fatalf("exits test fail : %s", query)
		}

		query = "exist:root->parent->child->sex:male && name:m$"
		result, found, _ = Execute(node, query)
		if found == false {
			t.Fatalf("exits test fail : %s", query)
		}

		query = "exist:root->parent->child->sex:female && name:m$"
		result, found, _ = Execute(node, query)
		if found == true {
			t.Fatalf("exits test fail : %s", query)
		}
	}
}

func TestOne(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "one:root->parent->child->sex:male"
		result, _, _ := Execute(node, query)
		child, ok := result.(*Node)
		if ok {
			if child.GetValueString("name") != "jim" || child.GetValueString("age") != "20" {
				t.Fatalf("one test fail : %s", query)
			}
		}
	}
}

func TestSelect(t *testing.T) {
	node := LoadTestData()

	if node != nil {

		SelectAssert := func(query string, expect []string) {
			result, found, _ := Execute(node, query)
			if found {
				children, ok := result.([]*Node)
				if ok && len(children) == len(expect) {
					for i := 0; i < len(expect); i++ {
						child := children[i]
						if child.GetValueString("name") != expect[i] {
							t.Fatalf("select test fail : %s", query)
							break
						}
					}
				} else {
					t.Fatalf("select test fail len(children) %d != %d : %s", len(children), len(expect), query)
				}
			} else {
				t.Fatalf("select test fail : %s", query)
			}
		}

		query := "select:root->parent->child->name:/.*m/"
		SelectAssert(query, []string{"jim", "tom"})

		query = "select:root->parent->child->age:[15,25]"
		SelectAssert(query, []string{"jim", "lily"})

		query = "select:root->parent->child->sex:^fe"
		SelectAssert(query, []string{"lily"})

		query = "select:root->parent->child->name:m$"
		SelectAssert(query, []string{"jim", "tom"})

		query = "select:root->parent->child->sex:male && age:[15,25]"
		SelectAssert(query, []string{"jim"})

		query = "select:root->parent->child"
		SelectAssert(query, []string{"jim", "lily", "tom"})

		query = "select:root->parent->:/child|nephew/->sex:female"
		SelectAssert(query, []string{"lily", "lucy"})
	}
}

func TestUpdate(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "update:root->parent->child->name:jim !! age=21, address=China"
		result, found, _ := Execute(node, query)
		if found {
			updateResult, _, _ := Execute(result.(*Node), "one:root->parent->child->name:jim")
			child, ok := updateResult.(*Node)
			if ok {
				ValueAssert(child, "name", "jim", query)
				ValueAssert(child, "age", "21", query)
				ValueAssert(child, "address", "China", query)
			} else {
				t.Fatalf("update test fail : %s", query)
			}
		} else {
			t.Fatalf("update test fail : %s", query)
		}
	}
}

func TestDelete(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "delete:root->parent->child->name:jim !! [sex, age]"
		result, found, _ := Execute(node, query)
		if found {
			deleteResult, _, _ := Execute(result.(*Node), "one:root->parent->child->name:jim")
			child, ok := deleteResult.(*Node)
			if ok {
				ValueAssert(child, "name", "jim", query)
				NullAssert(child, "sex", query)
				NullAssert(child, "age", query)
			} else {
				t.Fatalf("delete test fail : %s", query)
			}
		} else {
			t.Fatalf("delete test fail : %s", query)
		}

		query = "delete:root->parent->child->name:jim !! block"
		result, found, _ = Execute(node, query)
		if found {
			deleteResult, _, _ := Execute(result.(*Node), "select:root->parent->child->name:jim")
			children, _ := deleteResult.([]*Node)
			LengthAssert(children, 0, query)
		} else {
			t.Fatalf("delete test fail : %s", query)
		}
	}
}

func TestInsert(t *testing.T) {
	node := LoadTestData()

	if node != nil {
		query := "insert:root->parent->child !! name=bill, sex=male, age=31"
		result, _, _ := Execute(node, query)

		insertResult, _, _ := Execute(result.(*Node), "one:root->parent->child->name:bill")
		child, ok := insertResult.(*Node)
		if ok {
			ValueAssert(child, "name", "bill", query)
			ValueAssert(child, "sex", "male", query)
			ValueAssert(child, "age", "31", query)
		} else {
			t.Fatalf("insert test fail : %s", query)
		}
	}
}

/*
func TestRedirect(t *testing.T) {

	node := LoadTestData()
	if node != nil {
		query := "select:root->parent->:/child|nephew/->sex:female >> select.ndb"
		Execute(node, query)
		tempNode, _ := Read("select.ndb")
		result, found, err := Execute(tempNode, "select:result->sex:female")
		if found && err == nil {
			children := result.([]*Node)

			LengthAssert(children, 2, query)
			ValueAssert(children[0], "name", "lucy", query)
			ValueAssert(children[1], "name", "lily", query)
		}

		query = "insert:root->parent->child !! name=bill, sex=male, age=31 >> insert.ndb"
		Execute(node, query)
		tempNode, _ = Read("insert.ndb")
		result, found, err = Execute(tempNode, "select:root->parent->child->name:bill")
		if found && err == nil {
			children := result.([]*Node)

			LengthAssert(children, 1, query)
			ValueAssert(children[0], "name", "bill", query)
			ValueAssert(children[0], "sex", "male", query)
			ValueAssert(children[0], "age", "31", query)
		}

		query = "update:root->parent->child->name:jim !! age=21, address=China >> update.ndb"
		Execute(node, query)
		tempNode, _ = Read("update.ndb")
		result, found, err = Execute(tempNode, "select:root->parent->child->name:jim")
		if found && err == nil {
			children := result.([]*Node)
			LengthAssert(children, 1, query)
			ValueAssert(children[0], "name", "jim", query)
			ValueAssert(children[0], "address", "China", query)
			ValueAssert(children[0], "age", "21", query)
		}

		tempFiles := []string{"select.ndb", "insert.ndb", "update.ndb"}
		for _, tempFile := range tempFiles {
			os.Remove(tempFile)
		}
	}
}
*/

func TestScript(t *testing.T) {
	node := LoadTestData()
	if node != nil {
		query := "script:example.script"
		result, _, _ := Execute(node, query)
		tempNode, ok := result.(*Node)

		if ok {
			selectResult, found, err := Execute(tempNode, "select:root->parent->child->name:bill")
			if found && err == nil {
				children := selectResult.([]*Node)
				LengthAssert(children, 1, query)
				ValueAssert(children[0], "name", "bill", query)
				ValueAssert(children[0], "sex", "male", query)
				ValueAssert(children[0], "age", "31", query)
			}

			selectResult, found, err = Execute(tempNode, "select:root->parent->child->name:lily")
			if found && err == nil {
				children := selectResult.([]*Node)
				LengthAssert(children, 1, query)
				ValueAssert(children[0], "name", "lily", query)
				ValueAssert(children[0], "sex", "China", query)
				ValueAssert(children[0], "age", "21", query)
			}

			selectResult, found, err = Execute(tempNode, "select:root->parent->child->name:jim")
			if found && err == nil {
				children := selectResult.([]*Node)
				LengthAssert(children, 1, query)
				ValueAssert(children[0], "name", "jim", query)
				NullAssert(children[0], "sex", query)
				NullAssert(children[0], "age", query)
			}
		}
	}
}<|endoftext|>


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

// Package tls partially implements TLS 1.2, as specified in RFC 5246.
package tls

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"io/ioutil"
	"net"
	"strings"
	"time"
)

// Server returns a new TLS server side connection
// using conn as the underlying transport.
// The configuration config must be non-nil and must have
// at least one certificate.
func Server(conn net.Conn, config *Config) *Conn {
	return &Conn{conn: conn, config: config}
}

// Client returns a new TLS client side connection
// using conn as the underlying transport.
// The config cannot be nil: users must set either ServerHostname or
// InsecureSkipVerify in the config.
func Client(conn net.Conn, config *Config) *Conn {
	return &Conn{conn: conn, config: config, isClient: true}
}

// A listener implements a network listener (net.Listener) for TLS connections.
type listener struct {
	net.Listener
	config *Config
}

// Accept waits for and returns the next incoming TLS connection.
// The returned connection c is a *tls.Conn.
func (l *listener) Accept() (c net.Conn, err error) {
	c, err = l.Listener.Accept()
	if err != nil {
		return
	}
	c = Server(c, l.config)
	return
}

// NewListener creates a Listener which accepts connections from an inner
// Listener and wraps each connection with Server.
// The configuration config must be non-nil and must have
// at least one certificate.
func NewListener(inner net.Listener, config *Config) net.Listener {
	l := new(listener)
	l.Listener = inner
	l.config = config
	return l
}

// Listen creates a TLS listener accepting connections on the
// given network address using net.Listen.
// The configuration config must be non-nil and must have
// at least one certificate.
func Listen(network, laddr string, config *Config) (net.Listener, error) {
	if config == nil || len(config.Certificates) == 0 {
		return nil, errors.New("tls.Listen: no certificates in configuration")
	}
	l, err := net.Listen(network, laddr)
	if err != nil {
		return nil, err
	}
	return NewListener(l, config), nil
}

type timeoutError struct{}

func (timeoutError) Error() string   { return "tls: DialWithDialer timed out" }
func (timeoutError) Timeout() bool   { return true }
func (timeoutError) Temporary() bool { return true }

// DialWithDialer connects to the given network address using dialer.Dial and
// then initiates a TLS handshake, returning the resulting TLS connection. Any
// timeout or deadline given in the dialer apply to connection and TLS
// handshake as a whole.
//
// DialWithDialer interprets a nil configuration as equivalent to the zero
// configuration; see the documentation of Config for the defaults.
func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
	// We want the Timeout and Deadline values from dialer to cover the
	// whole process: TCP connection and TLS handshake. This means that we
	// also need to start our own timers now.
	timeout := dialer.Timeout

	if !dialer.Deadline.IsZero() {
		deadlineTimeout := dialer.Deadline.Sub(time.Now())
		if timeout == 0 || deadlineTimeout < timeout {
			timeout = deadlineTimeout
		}
	}

	var errChannel chan error

	if timeout != 0 {
		errChannel = make(chan error, 2)
		time.AfterFunc(timeout, func() {
			errChannel <- timeoutError{}
		})
	}

	rawConn, err := dialer.Dial(network, addr)
	if err != nil {
		return nil, err
	}

	colonPos := strings.LastIndex(addr, ":")
	if colonPos == -1 {
		colonPos = len(addr)
	}
	hostname := addr[:colonPos]

	if config == nil {
		config = defaultConfig()
	}
	// If no ServerName is set, infer the ServerName
	// from the hostname we're connecting to.
	if config.ServerName == "" {
		// Make a copy to avoid polluting argument or default.
		c := *config
		c.ServerName = hostname
		config = &c
	}

	conn := Client(rawConn, config)

	if timeout == 0 {
		err = conn.Handshake()
	} else {
		go func() {
			errChannel <- conn.Handshake()
		}()

		err = <-errChannel
	}

	if err != nil {
		rawConn.Close()
		return nil, err
	}

	return conn, nil
}

// Dial connects to the given network address using net.Dial
// and then initiates a TLS handshake, returning the resulting
// TLS connection.
// Dial interprets a nil configuration as equivalent to
// the zero configuration; see the documentation of Config
// for the defaults.
func Dial(network, addr string, config *Config) (*Conn, error) {
	return DialWithDialer(new(net.Dialer), network, addr, config)
}

// LoadX509KeyPair reads and parses a public/private key pair from a pair of
// files. The files must contain PEM encoded data.
func LoadX509KeyPair(certFile, keyFile string) (cert Certificate, err error) {
	certPEMBlock, err := ioutil.ReadFile(certFile)
	if err != nil {
		return
	}
	keyPEMBlock, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return
	}
	return X509KeyPair(certPEMBlock, keyPEMBlock)
}

// X509KeyPair parses a public/private key pair from a pair of
// PEM encoded data.
func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err error) {
	var certDERBlock *pem.Block
	for {
		certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
		if certDERBlock == nil {
			break
		}
		if certDERBlock.Type == "CERTIFICATE" {
			cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
		}
	}

	if len(cert.Certificate) == 0 {
		err = errors.New("crypto/tls: failed to parse certificate PEM data")
		return
	}

	var keyDERBlock *pem.Block
	for {
		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
		if keyDERBlock == nil {
			err = errors.New("crypto/tls: failed to parse key PEM data")
			return
		}
		if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
			break
		}
	}

	cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
	if err != nil {
		return
	}

	// We don't need to parse the public key for TLS, but we so do anyway
	// to check that it looks sane and matches the private key.
	x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
	if err != nil {
		return
	}

	switch pub := x509Cert.PublicKey.(type) {
	case *rsa.PublicKey:
		priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
		if !ok {
			err = errors.New("crypto/tls: private key type does not match public key type")
			return
		}
		if pub.N.Cmp(priv.N) != 0 {
			err = errors.New("crypto/tls: private key does not match public key")
			return
		}
	case *ecdsa.PublicKey:
		priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
		if !ok {
			err = errors.New("crypto/tls: private key type does not match public key type")
			return

		}
		if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
			err = errors.New("crypto/tls: private key does not match public key")
			return
		}
	default:
		err = errors.New("crypto/tls: unknown public key algorithm")
		return
	}

	return
}

// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
	if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
		return key, nil
	}
	if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
		switch key := key.(type) {
		case *rsa.PrivateKey, *ecdsa.PrivateKey:
			return key, nil
		default:
			return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping")
		}
	}
	if key, err := x509.ParseECPrivateKey(der); err == nil {
		return key, nil
	}

	return nil, errors.New("crypto/tls: failed to parse private key")
}
<commit_msg>[release-branch.go1.3] crypto/tls: fix typo referencing the required Config field<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package tls partially implements TLS 1.2, as specified in RFC 5246.
package tls

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"io/ioutil"
	"net"
	"strings"
	"time"
)

// Server returns a new TLS server side connection
// using conn as the underlying transport.
// The configuration config must be non-nil and must have
// at least one certificate.
func Server(conn net.Conn, config *Config) *Conn {
	return &Conn{conn: conn, config: config}
}

// Client returns a new TLS client side connection
// using conn as the underlying transport.
// The config cannot be nil: users must set either ServerName or
// InsecureSkipVerify in the config.
func Client(conn net.Conn, config *Config) *Conn {
	return &Conn{conn: conn, config: config, isClient: true}
}

// A listener implements a network listener (net.Listener) for TLS connections.
type listener struct {
	net.Listener
	config *Config
}

// Accept waits for and returns the next incoming TLS connection.
// The returned connection c is a *tls.Conn.
func (l *listener) Accept() (c net.Conn, err error) {
	c, err = l.Listener.Accept()
	if err != nil {
		return
	}
	c = Server(c, l.config)
	return
}

// NewListener creates a Listener which accepts connections from an inner
// Listener and wraps each connection with Server.
// The configuration config must be non-nil and must have
// at least one certificate.
func NewListener(inner net.Listener, config *Config) net.Listener {
	l := new(listener)
	l.Listener = inner
	l.config = config
	return l
}

// Listen creates a TLS listener accepting connections on the
// given network address using net.Listen.
// The configuration config must be non-nil and must have
// at least one certificate.
func Listen(network, laddr string, config *Config) (net.Listener, error) {
	if config == nil || len(config.Certificates) == 0 {
		return nil, errors.New("tls.Listen: no certificates in configuration")
	}
	l, err := net.Listen(network, laddr)
	if err != nil {
		return nil, err
	}
	return NewListener(l, config), nil
}

type timeoutError struct{}

func (timeoutError) Error() string   { return "tls: DialWithDialer timed out" }
func (timeoutError) Timeout() bool   { return true }
func (timeoutError) Temporary() bool { return true }

// DialWithDialer connects to the given network address using dialer.Dial and
// then initiates a TLS handshake, returning the resulting TLS connection. Any
// timeout or deadline given in the dialer apply to connection and TLS
// handshake as a whole.
//
// DialWithDialer interprets a nil configuration as equivalent to the zero
// configuration; see the documentation of Config for the defaults.
func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
	// We want the Timeout and Deadline values from dialer to cover the
	// whole process: TCP connection and TLS handshake. This means that we
	// also need to start our own timers now.
	timeout := dialer.Timeout

	if !dialer.Deadline.IsZero() {
		deadlineTimeout := dialer.Deadline.Sub(time.Now())
		if timeout == 0 || deadlineTimeout < timeout {
			timeout = deadlineTimeout
		}
	}

	var errChannel chan error

	if timeout != 0 {
		errChannel = make(chan error, 2)
		time.AfterFunc(timeout, func() {
			errChannel <- timeoutError{}
		})
	}

	rawConn, err := dialer.Dial(network, addr)
	if err != nil {
		return nil, err
	}

	colonPos := strings.LastIndex(addr, ":")
	if colonPos == -1 {
		colonPos = len(addr)
	}
	hostname := addr[:colonPos]

	if config == nil {
		config = defaultConfig()
	}
	// If no ServerName is set, infer the ServerName
	// from the hostname we're connecting to.
	if config.ServerName == "" {
		// Make a copy to avoid polluting argument or default.
		c := *config
		c.ServerName = hostname
		config = &c
	}

	conn := Client(rawConn, config)

	if timeout == 0 {
		err = conn.Handshake()
	} else {
		go func() {
			errChannel <- conn.Handshake()
		}()

		err = <-errChannel
	}

	if err != nil {
		rawConn.Close()
		return nil, err
	}

	return conn, nil
}

// Dial connects to the given network address using net.Dial
// and then initiates a TLS handshake, returning the resulting
// TLS connection.
// Dial interprets a nil configuration as equivalent to
// the zero configuration; see the documentation of Config
// for the defaults.
func Dial(network, addr string, config *Config) (*Conn, error) {
	return DialWithDialer(new(net.Dialer), network, addr, config)
}

// LoadX509KeyPair reads and parses a public/private key pair from a pair of
// files. The files must contain PEM encoded data.
func LoadX509KeyPair(certFile, keyFile string) (cert Certificate, err error) {
	certPEMBlock, err := ioutil.ReadFile(certFile)
	if err != nil {
		return
	}
	keyPEMBlock, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return
	}
	return X509KeyPair(certPEMBlock, keyPEMBlock)
}

// X509KeyPair parses a public/private key pair from a pair of
// PEM encoded data.
func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err error) {
	var certDERBlock *pem.Block
	for {
		certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
		if certDERBlock == nil {
			break
		}
		if certDERBlock.Type == "CERTIFICATE" {
			cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
		}
	}

	if len(cert.Certificate) == 0 {
		err = errors.New("crypto/tls: failed to parse certificate PEM data")
		return
	}

	var keyDERBlock *pem.Block
	for {
		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
		if keyDERBlock == nil {
			err = errors.New("crypto/tls: failed to parse key PEM data")
			return
		}
		if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
			break
		}
	}

	cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
	if err != nil {
		return
	}

	// We don't need to parse the public key for TLS, but we so do anyway
	// to check that it looks sane and matches the private key.
	x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
	if err != nil {
		return
	}

	switch pub := x509Cert.PublicKey.(type) {
	case *rsa.PublicKey:
		priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
		if !ok {
			err = errors.New("crypto/tls: private key type does not match public key type")
			return
		}
		if pub.N.Cmp(priv.N) != 0 {
			err = errors.New("crypto/tls: private key does not match public key")
			return
		}
	case *ecdsa.PublicKey:
		priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
		if !ok {
			err = errors.New("crypto/tls: private key type does not match public key type")
			return

		}
		if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
			err = errors.New("crypto/tls: private key does not match public key")
			return
		}
	default:
		err = errors.New("crypto/tls: unknown public key algorithm")
		return
	}

	return
}

// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
	if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
		return key, nil
	}
	if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
		switch key := key.(type) {
		case *rsa.PrivateKey, *ecdsa.PrivateKey:
			return key, nil
		default:
			return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping")
		}
	}
	if key, err := x509.ParseECPrivateKey(der); err == nil {
		return key, nil
	}

	return nil, errors.New("crypto/tls: failed to parse private key")
}
<|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.

// This file provides Go implementations of elementary multi-precision
// arithmetic operations on word vectors. Needed for platforms without
// assembly implementations of these routines.

package big

// TODO(gri) Decide if Word needs to remain exported.

type Word uintptr

const (
	// Compute the size _S of a Word in bytes.
	_m    = ^Word(0)
	_logS = _m>>8&1 + _m>>16&1 + _m>>32&1
	_S    = 1 << _logS

	_W = _S << 3 // word size in bits
	_B = 1 << _W // digit base
	_M = _B - 1  // digit mask

	_W2 = _W / 2   // half word size in bits
	_B2 = 1 << _W2 // half digit base
	_M2 = _B2 - 1  // half digit mask
)

// ----------------------------------------------------------------------------
// Elementary operations on words
//
// These operations are used by the vector operations below.

// z1<<_W + z0 = x+y+c, with c == 0 or 1
func addWW_g(x, y, c Word) (z1, z0 Word) {
	yc := y + c
	z0 = x + yc
	if z0 < x || yc < y {
		z1 = 1
	}
	return
}

// z1<<_W + z0 = x-y-c, with c == 0 or 1
func subWW_g(x, y, c Word) (z1, z0 Word) {
	yc := y + c
	z0 = x - yc
	if z0 > x || yc < y {
		z1 = 1
	}
	return
}

// z1<<_W + z0 = x*y
// Adapted from Warren, Hacker's Delight, p. 132.
func mulWW_g(x, y Word) (z1, z0 Word) {
	x0 := x & _M2
	x1 := x >> _W2
	y0 := y & _M2
	y1 := y >> _W2
	w0 := x0 * y0
	t := x1*y0 + w0>>_W2
	w1 := t & _M2
	w2 := t >> _W2
	w1 += x0 * y1
	z1 = x1*y1 + w2 + w1>>_W2
	z0 = x * y
	return
}

// z1<<_W + z0 = x*y + c
func mulAddWWW_g(x, y, c Word) (z1, z0 Word) {
	z1, zz0 := mulWW(x, y)
	if z0 = zz0 + c; z0 < zz0 {
		z1++
	}
	return
}

// Length of x in bits.
func bitLen_g(x Word) (n int) {
	for ; x >= 0x8000; x >>= 16 {
		n += 16
	}
	if x >= 0x80 {
		x >>= 8
		n += 8
	}
	if x >= 0x8 {
		x >>= 4
		n += 4
	}
	if x >= 0x2 {
		x >>= 2
		n += 2
	}
	if x >= 0x1 {
		n++
	}
	return
}

// log2 computes the integer binary logarithm of x.
// The result is the integer n for which 2^n <= x < 2^(n+1).
// If x == 0, the result is -1.
func log2(x Word) int {
	return bitLen(x) - 1
}

// Number of leading zeros in x.
func leadingZeros(x Word) uint {
	return uint(_W - bitLen(x))
}

// q = (u1<<_W + u0 - r)/y
// Adapted from Warren, Hacker's Delight, p. 152.
func divWW_g(u1, u0, v Word) (q, r Word) {
	if u1 >= v {
		return 1<<_W - 1, 1<<_W - 1
	}

	s := leadingZeros(v)
	v <<= s

	vn1 := v >> _W2
	vn0 := v & _M2
	un32 := u1<<s | u0>>(_W-s)
	un10 := u0 << s
	un1 := un10 >> _W2
	un0 := un10 & _M2
	q1 := un32 / vn1
	rhat := un32 - q1*vn1

again1:
	if q1 >= _B2 || q1*vn0 > _B2*rhat+un1 {
		q1--
		rhat += vn1
		if rhat < _B2 {
			goto again1
		}
	}

	un21 := un32*_B2 + un1 - q1*v
	q0 := un21 / vn1
	rhat = un21 - q0*vn1

again2:
	if q0 >= _B2 || q0*vn0 > _B2*rhat+un0 {
		q0--
		rhat += vn1
		if rhat < _B2 {
			goto again2
		}
	}

	return q1*_B2 + q0, (un21*_B2 + un0 - q0*v) >> s
}

func addVV_g(z, x, y []Word) (c Word) {
	for i := range z {
		c, z[i] = addWW_g(x[i], y[i], c)
	}
	return
}

func subVV_g(z, x, y []Word) (c Word) {
	for i := range z {
		c, z[i] = subWW_g(x[i], y[i], c)
	}
	return
}

func addVW_g(z, x []Word, y Word) (c Word) {
	c = y
	for i := range z {
		c, z[i] = addWW_g(x[i], c, 0)
	}
	return
}

func subVW_g(z, x []Word, y Word) (c Word) {
	c = y
	for i := range z {
		c, z[i] = subWW_g(x[i], c, 0)
	}
	return
}

func shlVU_g(z, x []Word, s uint) (c Word) {
	if n := len(z); n > 0 {
		ŝ := _W - s
		w1 := x[n-1]
		c = w1 >> ŝ
		for i := n - 1; i > 0; i-- {
			w := w1
			w1 = x[i-1]
			z[i] = w<<s | w1>>ŝ
		}
		z[0] = w1 << s
	}
	return
}

func shrVU_g(z, x []Word, s uint) (c Word) {
	if n := len(z); n > 0 {
		ŝ := _W - s
		w1 := x[0]
		c = w1 << ŝ
		for i := 0; i < n-1; i++ {
			w := w1
			w1 = x[i+1]
			z[i] = w>>s | w1<<ŝ
		}
		z[n-1] = w1 >> s
	}
	return
}

func mulAddVWW_g(z, x []Word, y, r Word) (c Word) {
	c = r
	for i := range z {
		c, z[i] = mulAddWWW_g(x[i], y, c)
	}
	return
}

func addMulVVW_g(z, x []Word, y Word) (c Word) {
	for i := range z {
		z1, z0 := mulAddWWW_g(x[i], y, z[i])
		c, z[i] = addWW_g(z0, c, 0)
		c += z1
	}
	return
}

func divWVW_g(z []Word, xn Word, x []Word, y Word) (r Word) {
	r = xn
	for i := len(z) - 1; i >= 0; i-- {
		z[i], r = divWW_g(r, x[i], y)
	}
	return
}
<commit_msg>math/big: document Word type<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.

// This file provides Go implementations of elementary multi-precision
// arithmetic operations on word vectors. Needed for platforms without
// assembly implementations of these routines.

package big

// A Word represents a single digit of a multi-precision unsigned integer.
type Word uintptr

const (
	// Compute the size _S of a Word in bytes.
	_m    = ^Word(0)
	_logS = _m>>8&1 + _m>>16&1 + _m>>32&1
	_S    = 1 << _logS

	_W = _S << 3 // word size in bits
	_B = 1 << _W // digit base
	_M = _B - 1  // digit mask

	_W2 = _W / 2   // half word size in bits
	_B2 = 1 << _W2 // half digit base
	_M2 = _B2 - 1  // half digit mask
)

// ----------------------------------------------------------------------------
// Elementary operations on words
//
// These operations are used by the vector operations below.

// z1<<_W + z0 = x+y+c, with c == 0 or 1
func addWW_g(x, y, c Word) (z1, z0 Word) {
	yc := y + c
	z0 = x + yc
	if z0 < x || yc < y {
		z1 = 1
	}
	return
}

// z1<<_W + z0 = x-y-c, with c == 0 or 1
func subWW_g(x, y, c Word) (z1, z0 Word) {
	yc := y + c
	z0 = x - yc
	if z0 > x || yc < y {
		z1 = 1
	}
	return
}

// z1<<_W + z0 = x*y
// Adapted from Warren, Hacker's Delight, p. 132.
func mulWW_g(x, y Word) (z1, z0 Word) {
	x0 := x & _M2
	x1 := x >> _W2
	y0 := y & _M2
	y1 := y >> _W2
	w0 := x0 * y0
	t := x1*y0 + w0>>_W2
	w1 := t & _M2
	w2 := t >> _W2
	w1 += x0 * y1
	z1 = x1*y1 + w2 + w1>>_W2
	z0 = x * y
	return
}

// z1<<_W + z0 = x*y + c
func mulAddWWW_g(x, y, c Word) (z1, z0 Word) {
	z1, zz0 := mulWW(x, y)
	if z0 = zz0 + c; z0 < zz0 {
		z1++
	}
	return
}

// Length of x in bits.
func bitLen_g(x Word) (n int) {
	for ; x >= 0x8000; x >>= 16 {
		n += 16
	}
	if x >= 0x80 {
		x >>= 8
		n += 8
	}
	if x >= 0x8 {
		x >>= 4
		n += 4
	}
	if x >= 0x2 {
		x >>= 2
		n += 2
	}
	if x >= 0x1 {
		n++
	}
	return
}

// log2 computes the integer binary logarithm of x.
// The result is the integer n for which 2^n <= x < 2^(n+1).
// If x == 0, the result is -1.
func log2(x Word) int {
	return bitLen(x) - 1
}

// Number of leading zeros in x.
func leadingZeros(x Word) uint {
	return uint(_W - bitLen(x))
}

// q = (u1<<_W + u0 - r)/y
// Adapted from Warren, Hacker's Delight, p. 152.
func divWW_g(u1, u0, v Word) (q, r Word) {
	if u1 >= v {
		return 1<<_W - 1, 1<<_W - 1
	}

	s := leadingZeros(v)
	v <<= s

	vn1 := v >> _W2
	vn0 := v & _M2
	un32 := u1<<s | u0>>(_W-s)
	un10 := u0 << s
	un1 := un10 >> _W2
	un0 := un10 & _M2
	q1 := un32 / vn1
	rhat := un32 - q1*vn1

again1:
	if q1 >= _B2 || q1*vn0 > _B2*rhat+un1 {
		q1--
		rhat += vn1
		if rhat < _B2 {
			goto again1
		}
	}

	un21 := un32*_B2 + un1 - q1*v
	q0 := un21 / vn1
	rhat = un21 - q0*vn1

again2:
	if q0 >= _B2 || q0*vn0 > _B2*rhat+un0 {
		q0--
		rhat += vn1
		if rhat < _B2 {
			goto again2
		}
	}

	return q1*_B2 + q0, (un21*_B2 + un0 - q0*v) >> s
}

func addVV_g(z, x, y []Word) (c Word) {
	for i := range z {
		c, z[i] = addWW_g(x[i], y[i], c)
	}
	return
}

func subVV_g(z, x, y []Word) (c Word) {
	for i := range z {
		c, z[i] = subWW_g(x[i], y[i], c)
	}
	return
}

func addVW_g(z, x []Word, y Word) (c Word) {
	c = y
	for i := range z {
		c, z[i] = addWW_g(x[i], c, 0)
	}
	return
}

func subVW_g(z, x []Word, y Word) (c Word) {
	c = y
	for i := range z {
		c, z[i] = subWW_g(x[i], c, 0)
	}
	return
}

func shlVU_g(z, x []Word, s uint) (c Word) {
	if n := len(z); n > 0 {
		ŝ := _W - s
		w1 := x[n-1]
		c = w1 >> ŝ
		for i := n - 1; i > 0; i-- {
			w := w1
			w1 = x[i-1]
			z[i] = w<<s | w1>>ŝ
		}
		z[0] = w1 << s
	}
	return
}

func shrVU_g(z, x []Word, s uint) (c Word) {
	if n := len(z); n > 0 {
		ŝ := _W - s
		w1 := x[0]
		c = w1 << ŝ
		for i := 0; i < n-1; i++ {
			w := w1
			w1 = x[i+1]
			z[i] = w>>s | w1<<ŝ
		}
		z[n-1] = w1 >> s
	}
	return
}

func mulAddVWW_g(z, x []Word, y, r Word) (c Word) {
	c = r
	for i := range z {
		c, z[i] = mulAddWWW_g(x[i], y, c)
	}
	return
}

func addMulVVW_g(z, x []Word, y Word) (c Word) {
	for i := range z {
		z1, z0 := mulAddWWW_g(x[i], y, z[i])
		c, z[i] = addWW_g(z0, c, 0)
		c += z1
	}
	return
}

func divWVW_g(z []Word, xn Word, x []Word, y Word) (r Word) {
	r = xn
	for i := len(z) - 1; i >= 0; i-- {
		z[i], r = divWW_g(r, x[i], y)
	}
	return
}
<|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.

// +build darwin freebsd linux netbsd openbsd windows

package net

import (
	"syscall"
	"time"
)

var listenerBacklog = maxListenerBacklog()

// Generic POSIX socket creation.
func socket(net string, f, t, p int, ipv6only bool, ulsa, ursa syscall.Sockaddr, deadline time.Time, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err error) {
	s, err := sysSocket(f, t, p)
	if err != nil {
		return nil, err
	}

	if err = setDefaultSockopts(s, f, t, ipv6only); err != nil {
		closesocket(s)
		return nil, err
	}

	if ulsa != nil {
		// We provide a socket that listens to a wildcard
		// address with reusable UDP port when the given ulsa
		// is an appropriate UDP multicast address prefix.
		// This makes it possible for a single UDP listener
		// to join multiple different group addresses, for
		// multiple UDP listeners that listen on the same UDP
		// port to join the same group address.
		if ulsa, err = listenerSockaddr(s, f, ulsa, toAddr); err != nil {
			closesocket(s)
			return nil, err
		}
		if err = syscall.Bind(s, ulsa); err != nil {
			closesocket(s)
			return nil, err
		}
	}

	if fd, err = newFD(s, f, t, net); err != nil {
		closesocket(s)
		return nil, err
	}

	if ursa != nil {
		if !deadline.IsZero() {
			setWriteDeadline(fd, deadline)
		}
		if err = fd.connect(ursa); err != nil {
			closesocket(s)
			return nil, err
		}
		fd.isConnected = true
		if !deadline.IsZero() {
			setWriteDeadline(fd, time.Time{})
		}
	}

	lsa, _ := syscall.Getsockname(s)
	laddr := toAddr(lsa)
	rsa, _ := syscall.Getpeername(s)
	if rsa == nil {
		rsa = ursa
	}
	raddr := toAddr(rsa)
	fd.setAddr(laddr, raddr)
	return fd, nil
}
<commit_msg>net: avoid use of listener socket options on active open sockets<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.

// +build darwin freebsd linux netbsd openbsd windows

package net

import (
	"syscall"
	"time"
)

var listenerBacklog = maxListenerBacklog()

// Generic POSIX socket creation.
func socket(net string, f, t, p int, ipv6only bool, ulsa, ursa syscall.Sockaddr, deadline time.Time, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err error) {
	s, err := sysSocket(f, t, p)
	if err != nil {
		return nil, err
	}

	if err = setDefaultSockopts(s, f, t, ipv6only); err != nil {
		closesocket(s)
		return nil, err
	}

	// This socket is used by a listener.
	if ulsa != nil && ursa == nil {
		// We provide a socket that listens to a wildcard
		// address with reusable UDP port when the given ulsa
		// is an appropriate UDP multicast address prefix.
		// This makes it possible for a single UDP listener
		// to join multiple different group addresses, for
		// multiple UDP listeners that listen on the same UDP
		// port to join the same group address.
		if ulsa, err = listenerSockaddr(s, f, ulsa, toAddr); err != nil {
			closesocket(s)
			return nil, err
		}
	}

	if ulsa != nil {
		if err = syscall.Bind(s, ulsa); err != nil {
			closesocket(s)
			return nil, err
		}
	}

	if fd, err = newFD(s, f, t, net); err != nil {
		closesocket(s)
		return nil, err
	}

	// This socket is used by a dialer.
	if ursa != nil {
		if !deadline.IsZero() {
			setWriteDeadline(fd, deadline)
		}
		if err = fd.connect(ursa); err != nil {
			closesocket(s)
			return nil, err
		}
		fd.isConnected = true
		if !deadline.IsZero() {
			setWriteDeadline(fd, time.Time{})
		}
	}

	lsa, _ := syscall.Getsockname(s)
	laddr := toAddr(lsa)
	rsa, _ := syscall.Getpeername(s)
	if rsa == nil {
		rsa = ursa
	}
	raddr := toAddr(rsa)
	fd.setAddr(laddr, raddr)
	return fd, nil
}
<|endoftext|>


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

package os

func isExist(err error) bool {
	if pe, ok := err.(*PathError); ok {
		err = pe.Err
	}
	return contains(err.Error(), " exists")
}

func isNotExist(err error) bool {
	if pe, ok := err.(*PathError); ok {
		err = pe.Err
	}
	return contains(err.Error(), "does not exist")
}

func isPermission(err error) bool {
	if pe, ok := err.(*PathError); ok {
		err = pe.Err
	}
	return contains(err.Error(), "permission denied")
}

// contains is a local version of strings.Contains. It knows len(sep) > 1.
func contains(s, sep string) bool {
	n := len(sep)
	c := sep[0]
	for i := 0; i+n <= len(s); i++ {
		if s[i] == c && s[i:i+n] == sep {
			return true
		}
	}
	return false
}
<commit_msg>os: avoid panic when testing errors on Plan 9<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package os

func isExist(err error) bool {
	if err == nil {
		return false
	}
	if pe, ok := err.(*PathError); ok {
		err = pe.Err
	}
	return contains(err.Error(), " exists")
}

func isNotExist(err error) bool {
	if err == nil {
		return false
	}
	if pe, ok := err.(*PathError); ok {
		err = pe.Err
	}
	return contains(err.Error(), "does not exist")
}

func isPermission(err error) bool {
	if err == nil {
		return false
	}
	if pe, ok := err.(*PathError); ok {
		err = pe.Err
	}
	return contains(err.Error(), "permission denied")
}

// contains is a local version of strings.Contains. It knows len(sep) > 1.
func contains(s, sep string) bool {
	n := len(sep)
	c := sep[0]
	for i := 0; i+n <= len(s); i++ {
		if s[i] == c && s[i:i+n] == sep {
			return true
		}
	}
	return false
}
<|endoftext|>


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

package time_test

import (
	"testing"
	. "time"
)

func TestTicker(t *testing.T) {
	const Count = 10
	Delta := 100 * Millisecond
	ticker := NewTicker(Delta)
	t0 := Now()
	for i := 0; i < Count; i++ {
		<-ticker.C
	}
	ticker.Stop()
	t1 := Now()
	dt := t1.Sub(t0)
	target := Delta * Count
	slop := target * 2 / 10
	if dt < target-slop || (!testing.Short() && dt > target+slop) {
		t.Fatalf("%d %s ticks took %s, expected [%s,%s]", Count, Delta, dt, target-slop, target+slop)
	}
	// Now test that the ticker stopped
	Sleep(2 * Delta)
	select {
	case <-ticker.C:
		t.Fatal("Ticker did not shut down")
	default:
		// ok
	}
}

// Test that a bug tearing down a ticker has been fixed.  This routine should not deadlock.
func TestTeardown(t *testing.T) {
	Delta := 100 * Millisecond
	if testing.Short() {
		Delta = 20 * Millisecond
	}
	for i := 0; i < 3; i++ {
		ticker := NewTicker(Delta)
		<-ticker.C
		ticker.Stop()
	}
}

func BenchmarkTicker(b *testing.B) {
	ticker := NewTicker(1)
	b.ResetTimer()
	b.StartTimer()
	for i := 0; i < b.N; i++ {
		<-ticker.C
	}
	b.StopTimer()
	ticker.Stop()
}
<commit_msg>time: add tests for Tick, NewTicker with negative duration<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package time_test

import (
	"testing"
	. "time"
)

func TestTicker(t *testing.T) {
	const Count = 10
	Delta := 100 * Millisecond
	ticker := NewTicker(Delta)
	t0 := Now()
	for i := 0; i < Count; i++ {
		<-ticker.C
	}
	ticker.Stop()
	t1 := Now()
	dt := t1.Sub(t0)
	target := Delta * Count
	slop := target * 2 / 10
	if dt < target-slop || (!testing.Short() && dt > target+slop) {
		t.Fatalf("%d %s ticks took %s, expected [%s,%s]", Count, Delta, dt, target-slop, target+slop)
	}
	// Now test that the ticker stopped
	Sleep(2 * Delta)
	select {
	case <-ticker.C:
		t.Fatal("Ticker did not shut down")
	default:
		// ok
	}
}

// Test that a bug tearing down a ticker has been fixed.  This routine should not deadlock.
func TestTeardown(t *testing.T) {
	Delta := 100 * Millisecond
	if testing.Short() {
		Delta = 20 * Millisecond
	}
	for i := 0; i < 3; i++ {
		ticker := NewTicker(Delta)
		<-ticker.C
		ticker.Stop()
	}
}

// Test the Tick convenience wrapper.
func TestTick(t *testing.T) {
	// Test that giving a negative duration returns nil.
	if got := Tick(-1); got != nil {
		t.Errorf("Tick(-1) = %v; want nil", got)
	}
}

// Test that NewTicker panics when given a duration less than zero.
func TestNewTickerLtZeroDuration(t *testing.T) {
	defer func() {
		if err := recover(); err == nil {
			t.Errorf("NewTicker(-1) should have panicked")
		}
	}()
	NewTicker(-1)
}

func BenchmarkTicker(b *testing.B) {
	ticker := NewTicker(1)
	b.ResetTimer()
	b.StartTimer()
	for i := 0; i < b.N; i++ {
		<-ticker.C
	}
	b.StopTimer()
	ticker.Stop()
}
<|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.

// This package provides data and functions to test some properties of Unicode code points.
package unicode

const (
	MaxRune         = 0x10FFFF // Maximum valid Unicode code point.
	ReplacementChar = 0xFFFD   // Represents invalid code points.
)

// The representation of a range of Unicode code points.  The range runs from Lo to Hi
// inclusive and has the specified stride.
type Range struct {
	Lo     int
	Hi     int
	Stride int
}

// The representation of a range of Unicode code points for case conversion.
// The range runs from Lo to Hi inclusive, with a fixed stride of 1.  Deltas
// are the number to add to the code point to reach the code point for a
// different case for that character.  They may be negative.  If zero, it
// means the character is in the corresponding case. There is a special
// case representing sequences of alternating corresponding Upper and Lower
// pairs.  It appears with a fixed Delta of
//	{UpperLower, UpperLower, UpperLower}
// The constant UpperLower has an otherwise impossible delta value.
type CaseRange struct {
	Lo    int
	Hi    int
	Delta d
}

// Indices into the Delta arrays inside CaseRanges for case mapping.
const (
	UpperCase = iota
	LowerCase
	TitleCase
	MaxCase
)

type d [MaxCase]int32 // to make the CaseRanges text shorter

// If the Delta field of a CaseRange is UpperLower or LowerUpper, it means
// this CaseRange represents a sequence of the form (say)
// Upper Lower Upper Lower.
const (
	UpperLower = MaxRune + 1 // (Cannot be a valid delta.)
)

// Is tests whether rune is in the specified table of ranges.
func Is(ranges []Range, rune int) bool {
	// common case: rune is ASCII or Latin-1
	if rune < 0x100 {
		for _, r := range ranges {
			if rune > r.Hi {
				continue
			}
			if rune < r.Lo {
				return false
			}
			return (rune-r.Lo)%r.Stride == 0
		}
		return false
	}

	// binary search over ranges
	lo := 0
	hi := len(ranges)
	for lo < hi {
		m := lo + (hi-lo)/2
		r := ranges[m]
		if r.Lo <= rune && rune <= r.Hi {
			return (rune-r.Lo)%r.Stride == 0
		}
		if rune < r.Lo {
			hi = m
		} else {
			lo = m + 1
		}
	}
	return false
}

// IsUpper reports whether the rune is an upper case letter.
func IsUpper(rune int) bool {
	if rune < 0x80 { // quick ASCII check
		return 'A' <= rune && rune <= 'Z'
	}
	return Is(Upper, rune)
}

// IsLower reports whether the rune is a lower case letter.
func IsLower(rune int) bool {
	if rune < 0x80 { // quick ASCII check
		return 'a' <= rune && rune <= 'z'
	}
	return Is(Lower, rune)
}

// IsTitle reports whether the rune is a title case letter.
func IsTitle(rune int) bool {
	if rune < 0x80 { // quick ASCII check
		return false
	}
	return Is(Title, rune)
}

// IsLetter reports whether the rune is a letter.
func IsLetter(rune int) bool {
	if rune < 0x80 { // quick ASCII check
		rune &^= 'a' - 'A'
		return 'A' <= rune && rune <= 'Z'
	}
	return Is(Letter, rune)
}

// IsSpace reports whether the rune is a white space character.
func IsSpace(rune int) bool {
	if rune <= 0xFF { // quick Latin-1 check
		switch rune {
		case '\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xA0:
			return true
		}
		return false
	}
	return Is(White_Space, rune)
}

// To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase
func To(_case int, rune int) int {
	if _case < 0 || MaxCase <= _case {
		return ReplacementChar // as reasonable an error as any
	}
	// binary search over ranges
	lo := 0
	hi := len(CaseRanges)
	for lo < hi {
		m := lo + (hi-lo)/2
		r := CaseRanges[m]
		if r.Lo <= rune && rune <= r.Hi {
			delta := int(r.Delta[_case])
			if delta > MaxRune {
				// In an Upper-Lower sequence, which always starts with
				// an UpperCase letter, the real deltas always look like:
				//	{0, 1, 0}    UpperCase (Lower is next)
				//	{-1, 0, -1}  LowerCase (Upper, Title are previous)
				// The characters at even offsets from the beginning of the
				// sequence are upper case; the ones at odd offsets are lower.
				// The correct mapping can be done by clearing or setting the low
				// bit in the sequence offset.
				// The constants UpperCase and TitleCase are even while LowerCase
				// is odd so we take the low bit from _case.
				return r.Lo + ((rune-r.Lo)&^1 | _case&1)
			}
			return rune + delta
		}
		if rune < r.Lo {
			hi = m
		} else {
			lo = m + 1
		}
	}
	return rune
}

// ToUpper maps the rune to upper case
func ToUpper(rune int) int {
	if rune < 0x80 { // quick ASCII check
		if 'a' <= rune && rune <= 'z' {
			rune -= 'a' - 'A'
		}
		return rune
	}
	return To(UpperCase, rune)
}

// ToLower maps the rune to lower case
func ToLower(rune int) int {
	if rune < 0x80 { // quick ASCII check
		if 'A' <= rune && rune <= 'Z' {
			rune += 'a' - 'A'
		}
		return rune
	}
	return To(LowerCase, rune)
}

// ToTitle maps the rune to title case
func ToTitle(rune int) int {
	if rune < 0x80 { // quick ASCII check
		if 'a' <= rune && rune <= 'z' { // title case is upper case for ASCII
			rune -= 'a' - 'A'
		}
		return rune
	}
	return To(TitleCase, rune)
}
<commit_msg>added some missing periods<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.

// This package provides data and functions to test some properties of Unicode code points.
package unicode

const (
	MaxRune         = 0x10FFFF // Maximum valid Unicode code point.
	ReplacementChar = 0xFFFD   // Represents invalid code points.
)

// The representation of a range of Unicode code points.  The range runs from Lo to Hi
// inclusive and has the specified stride.
type Range struct {
	Lo     int
	Hi     int
	Stride int
}

// The representation of a range of Unicode code points for case conversion.
// The range runs from Lo to Hi inclusive, with a fixed stride of 1.  Deltas
// are the number to add to the code point to reach the code point for a
// different case for that character.  They may be negative.  If zero, it
// means the character is in the corresponding case. There is a special
// case representing sequences of alternating corresponding Upper and Lower
// pairs.  It appears with a fixed Delta of
//	{UpperLower, UpperLower, UpperLower}
// The constant UpperLower has an otherwise impossible delta value.
type CaseRange struct {
	Lo    int
	Hi    int
	Delta d
}

// Indices into the Delta arrays inside CaseRanges for case mapping.
const (
	UpperCase = iota
	LowerCase
	TitleCase
	MaxCase
)

type d [MaxCase]int32 // to make the CaseRanges text shorter

// If the Delta field of a CaseRange is UpperLower or LowerUpper, it means
// this CaseRange represents a sequence of the form (say)
// Upper Lower Upper Lower.
const (
	UpperLower = MaxRune + 1 // (Cannot be a valid delta.)
)

// Is tests whether rune is in the specified table of ranges.
func Is(ranges []Range, rune int) bool {
	// common case: rune is ASCII or Latin-1
	if rune < 0x100 {
		for _, r := range ranges {
			if rune > r.Hi {
				continue
			}
			if rune < r.Lo {
				return false
			}
			return (rune-r.Lo)%r.Stride == 0
		}
		return false
	}

	// binary search over ranges
	lo := 0
	hi := len(ranges)
	for lo < hi {
		m := lo + (hi-lo)/2
		r := ranges[m]
		if r.Lo <= rune && rune <= r.Hi {
			return (rune-r.Lo)%r.Stride == 0
		}
		if rune < r.Lo {
			hi = m
		} else {
			lo = m + 1
		}
	}
	return false
}

// IsUpper reports whether the rune is an upper case letter.
func IsUpper(rune int) bool {
	if rune < 0x80 { // quick ASCII check
		return 'A' <= rune && rune <= 'Z'
	}
	return Is(Upper, rune)
}

// IsLower reports whether the rune is a lower case letter.
func IsLower(rune int) bool {
	if rune < 0x80 { // quick ASCII check
		return 'a' <= rune && rune <= 'z'
	}
	return Is(Lower, rune)
}

// IsTitle reports whether the rune is a title case letter.
func IsTitle(rune int) bool {
	if rune < 0x80 { // quick ASCII check
		return false
	}
	return Is(Title, rune)
}

// IsLetter reports whether the rune is a letter.
func IsLetter(rune int) bool {
	if rune < 0x80 { // quick ASCII check
		rune &^= 'a' - 'A'
		return 'A' <= rune && rune <= 'Z'
	}
	return Is(Letter, rune)
}

// IsSpace reports whether the rune is a white space character.
func IsSpace(rune int) bool {
	if rune <= 0xFF { // quick Latin-1 check
		switch rune {
		case '\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xA0:
			return true
		}
		return false
	}
	return Is(White_Space, rune)
}

// To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase.
func To(_case int, rune int) int {
	if _case < 0 || MaxCase <= _case {
		return ReplacementChar // as reasonable an error as any
	}
	// binary search over ranges
	lo := 0
	hi := len(CaseRanges)
	for lo < hi {
		m := lo + (hi-lo)/2
		r := CaseRanges[m]
		if r.Lo <= rune && rune <= r.Hi {
			delta := int(r.Delta[_case])
			if delta > MaxRune {
				// In an Upper-Lower sequence, which always starts with
				// an UpperCase letter, the real deltas always look like:
				//	{0, 1, 0}    UpperCase (Lower is next)
				//	{-1, 0, -1}  LowerCase (Upper, Title are previous)
				// The characters at even offsets from the beginning of the
				// sequence are upper case; the ones at odd offsets are lower.
				// The correct mapping can be done by clearing or setting the low
				// bit in the sequence offset.
				// The constants UpperCase and TitleCase are even while LowerCase
				// is odd so we take the low bit from _case.
				return r.Lo + ((rune-r.Lo)&^1 | _case&1)
			}
			return rune + delta
		}
		if rune < r.Lo {
			hi = m
		} else {
			lo = m + 1
		}
	}
	return rune
}

// ToUpper maps the rune to upper case.
func ToUpper(rune int) int {
	if rune < 0x80 { // quick ASCII check
		if 'a' <= rune && rune <= 'z' {
			rune -= 'a' - 'A'
		}
		return rune
	}
	return To(UpperCase, rune)
}

// ToLower maps the rune to lower case.
func ToLower(rune int) int {
	if rune < 0x80 { // quick ASCII check
		if 'A' <= rune && rune <= 'Z' {
			rune += 'a' - 'A'
		}
		return rune
	}
	return To(LowerCase, rune)
}

// ToTitle maps the rune to title case.
func ToTitle(rune int) int {
	if rune < 0x80 { // quick ASCII check
		if 'a' <= rune && rune <= 'z' { // title case is upper case for ASCII
			rune -= 'a' - 'A'
		}
		return rune
	}
	return To(TitleCase, rune)
}
<|endoftext|>


<commit_before>package parsing

import (
	"fmt"
	"net/url"
	"regexp"
	"strings"
	"time"
)

type WhoisRecord struct {
	// times
	LastUpdatedAt time.Time
	CreatedAt time.Time
	ExpiresAt time.Time

	// contact points
	Registrar string
	ContactEmails []string
	ContactPhoneNumbers []string

	// tech details
	NameServers []url.URL
	DNSSECEnabled bool
}

func ParseWhoisResponse(resp string) (WhoisRecord, error) {
	record := WhoisRecord{}
	rp := &record

	last_updated_at, err := find_last_updated_at(resp)
	if err == nil {
		rp.LastUpdatedAt = last_updated_at
	}

	created_at, err := find_created_at(resp)
	if err == nil {
		rp.CreatedAt = created_at
	}

	expires_at, err := find_expires_at(resp)
	if err == nil {
		rp.ExpiresAt = expires_at
	}

	registar_name, err := find_registar_name(resp)
	if err == nil {
		rp.Registrar = registar_name
	}

	registar_email, err := find_registar_email(resp)
	if err == nil {
		rp.ContactEmails = []string{registar_email}
	}

	return record, nil
}

func find_registar_name(blob string) (string, error) {
	patterns_and_formats := []*regexp.Regexp{
		regexp.MustCompile(`(?im)Registrant Name: (.+)$`),
		regexp.MustCompile(`(?im)Registrar Handle:(.+)$`),
		regexp.MustCompile(`(?im)Registrar:(.+)$`),
	}
	return find_string(blob, patterns_and_formats, "ContactEmails")
}

func find_registar_email(blob string) (string, error) {
	patterns_and_formats := []*regexp.Regexp{
		regexp.MustCompile(`(?im)Registrant Email: (.+)$`),
	}
	return find_string(blob, patterns_and_formats, "ContactEmails")
}

func find_string(resp string, patterns []*regexp.Regexp, key string) (string, error) {
	for p := range patterns {
		res := patterns[p].FindStringSubmatch(resp)
		// Grab the first match
		if len(res) > 1 {
			return strings.TrimSpace(res[1]), nil
		}
	}
	return "", fmt.Errorf("unable to find patern for %s", key)
}

func find_last_updated_at(resp string) (time.Time, error) {
	patterns_and_formats := map[*regexp.Regexp]string{
		regexp.MustCompile(`(?im)Last Updated Date: \s+(.+)$`): "Mon Jan 2 15:04:05 MST 2006",
		regexp.MustCompile(`(?im)Last updated:(.+)$`): "2006-01-02",
		regexp.MustCompile(`(?im)Updated Date:\s+(.+)$`): "02-Jan-2006",
		regexp.MustCompile(`(?im)Updated Date:\s+(.+)$`): "2006-01-02T15:04:05Z",
	}
	return find_date_time(resp, patterns_and_formats, "LastUpdatedAt")
}

func find_created_at(resp string) (time.Time, error) {
	patterns_and_formats := map[*regexp.Regexp]string{
		regexp.MustCompile(`(?im)Registration Date: \s+(.+)$`): "Mon Jan 2 15:04:05 MST 2006",
		regexp.MustCompile(`(?im)Creation Date:\s+(.+)$`): "02-Jan-2006",
		regexp.MustCompile(`(?im)Creation Date:\s+(.+)$`): "2006-01-02T15:04:05Z",
		regexp.MustCompile(`(?im)Created: \s+(.+)$`): "2006-01-02",
	}
	return find_date_time(resp, patterns_and_formats, "CreatedAt")
}

func find_expires_at(resp string) (time.Time, error) {
	patterns_and_formats := map[*regexp.Regexp]string{
		regexp.MustCompile(`(?im)Domain Expiration Date: \s+(.+)$`): "Mon Jan 2 15:04:05 MST 2006",
		regexp.MustCompile(`(?im)Expiration Date:\s+(.+)$`): "02-Jan-2006",
		regexp.MustCompile(`(?im)Registry Expiry Date:\s+(.+)$`): "2006-01-02T15:04:05Z",
	}
	return find_date_time(resp, patterns_and_formats, "ExpiresAt")
}

func find_date_time(resp string, patterns_and_formats map[*regexp.Regexp]string, key string) (time.Time, error) {
	for r, format := range patterns_and_formats {
		res := r.FindStringSubmatch(resp)

		// Grab the first match
		if len(res) > 1 {
			t, err := time.Parse(format, res[1])
			if err == nil {
				return t, nil
			}
		}
	}
	return time.Now(), fmt.Errorf("unable to find patern for %s", key)
}
<commit_msg>parsing: Trim dates before formatting<commit_after>package parsing

import (
	"fmt"
	"net/url"
	"regexp"
	"strings"
	"time"
)

type WhoisRecord struct {
	// times
	LastUpdatedAt time.Time
	CreatedAt time.Time
	ExpiresAt time.Time

	// contact points
	Registrar string
	ContactEmails []string
	ContactPhoneNumbers []string

	// tech details
	NameServers []url.URL
	DNSSECEnabled bool
}

func ParseWhoisResponse(resp string) (WhoisRecord, error) {
	record := WhoisRecord{}
	rp := &record

	last_updated_at, err := find_last_updated_at(resp)
	if err == nil {
		rp.LastUpdatedAt = last_updated_at
	}

	created_at, err := find_created_at(resp)
	if err == nil {
		rp.CreatedAt = created_at
	}

	expires_at, err := find_expires_at(resp)
	if err == nil {
		rp.ExpiresAt = expires_at
	}

	registar_name, err := find_registar_name(resp)
	if err == nil {
		rp.Registrar = registar_name
	}

	registar_email, err := find_registar_email(resp)
	if err == nil {
		rp.ContactEmails = []string{registar_email}
	}

	return record, nil
}

func find_registar_name(blob string) (string, error) {
	patterns_and_formats := []*regexp.Regexp{
		regexp.MustCompile(`(?im)Registrant Name: (.+)$`),
		regexp.MustCompile(`(?im)Registrar Handle:(.+)$`),
		regexp.MustCompile(`(?im)Registrar:(.+)$`),
	}
	return find_string(blob, patterns_and_formats, "ContactEmails")
}

func find_registar_email(blob string) (string, error) {
	patterns_and_formats := []*regexp.Regexp{
		regexp.MustCompile(`(?im)Registrant Email: (.+)$`),
	}
	return find_string(blob, patterns_and_formats, "ContactEmails")
}

func find_string(resp string, patterns []*regexp.Regexp, key string) (string, error) {
	for p := range patterns {
		res := patterns[p].FindStringSubmatch(resp)
		// Grab the first match
		if len(res) > 1 {
			return strings.TrimSpace(res[1]), nil
		}
	}
	return "", fmt.Errorf("unable to find patern for %s", key)
}

func find_last_updated_at(resp string) (time.Time, error) {
	patterns_and_formats := map[*regexp.Regexp]string{
		regexp.MustCompile(`(?im)Last Updated Date: \s+(.+)$`): "Mon Jan 2 15:04:05 MST 2006",
		regexp.MustCompile(`(?im)Last updated:(.+)$`): "2006-01-02",
		regexp.MustCompile(`(?im)Updated Date:\s+(.+)$`): "02-Jan-2006",
		regexp.MustCompile(`(?im)Updated Date:\s+(.+)$`): "2006-01-02T15:04:05Z",
	}
	return find_date_time(resp, patterns_and_formats, "LastUpdatedAt")
}

func find_created_at(resp string) (time.Time, error) {
	patterns_and_formats := map[*regexp.Regexp]string{
		regexp.MustCompile(`(?im)Registration Date: \s+(.+)$`): "Mon Jan 2 15:04:05 MST 2006",
		regexp.MustCompile(`(?im)Creation Date:\s+(.+)$`): "02-Jan-2006",
		regexp.MustCompile(`(?im)Creation Date:\s+(.+)$`): "2006-01-02T15:04:05Z",
		regexp.MustCompile(`(?im)Created: \s+(.+)$`): "2006-01-02",
	}
	return find_date_time(resp, patterns_and_formats, "CreatedAt")
}

func find_expires_at(resp string) (time.Time, error) {
	patterns_and_formats := map[*regexp.Regexp]string{
		regexp.MustCompile(`(?im)Domain Expiration Date: \s+(.+)$`): "Mon Jan 2 15:04:05 MST 2006",
		regexp.MustCompile(`(?im)Expiration Date:\s+(.+)$`): "02-Jan-2006",
		regexp.MustCompile(`(?im)Registry Expiry Date:\s+(.+)$`): "2006-01-02T15:04:05Z",
	}
	return find_date_time(resp, patterns_and_formats, "ExpiresAt")
}

func find_date_time(resp string, patterns_and_formats map[*regexp.Regexp]string, key string) (time.Time, error) {
	for r, format := range patterns_and_formats {
		res := r.FindStringSubmatch(resp)

		// Grab the first match
		if len(res) > 1 {
			t, err := time.Parse(format, strings.TrimSpace(res[1]))
			if err == nil {
				return t, nil
			}
		}
	}
	return time.Now(), fmt.Errorf("unable to find patern for %s", key)
}
<|endoftext|>


<commit_before>package isolated

import (
	. "code.cloudfoundry.org/cli/cf/util/testhelpers/matchers"
	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("events command", func() {
	var (
		orgName   string
		spaceName string
		appName   string
	)

	BeforeEach(func() {
		orgName = helpers.NewOrgName()
		spaceName = helpers.NewSpaceName()
		appName = helpers.PrefixedRandomName("app1")
	})

	Describe("help", func() {
		When("--help flag is set", func() {
			It("appears in cf help -a", func() {
				session := helpers.CF("help", "-a")
				Eventually(session).Should(Exit(0))
				Expect(session).To(HaveCommandInCategoryWithDescription("events", "APPS", "Show recent app events"))
			})

			It("Displays command usage to output", func() {
				session := helpers.CF("events", "--help")

				Eventually(session).Should(Say("NAME:"))
				Eventually(session).Should(Say("events - Show recent app events"))
				Eventually(session).Should(Say("USAGE:"))
				Eventually(session).Should(Say("cf events APP_NAME"))
				Eventually(session).Should(Say("SEE ALSO:"))
				Eventually(session).Should(Say("app, logs, map-route, unmap-route"))

				Eventually(session).Should(Exit(0))
			})
		})
	})

	When("the environment is not setup correctly", func() {
		It("fails with the appropriate errors", func() {
			helpers.CheckEnvironmentTargetedCorrectly(true, true, ReadOnlyOrg, "events", appName)
		})
	})

	When("the environment is set up correctly", func() {
		var userName string

		BeforeEach(func() {
			helpers.SetupCF(orgName, spaceName)
			userName, _ = helpers.GetCredentials()
		})

		AfterEach(func() {
			helpers.QuickDeleteOrg(orgName)
		})

		Context("with an existing app", func() {
			BeforeEach(func() {
				session := helpers.CF("create-app", appName)
				Eventually(session).Should(Exit(0))
				session = helpers.CF("rename", appName, "other-app-name")
				Eventually(session).Should(Exit(0))
				session = helpers.CF("rename", "other-app-name", appName)
				Eventually(session).Should(Exit(0))
			})

			It("displays events in the list", func() {
				session := helpers.CF("events", appName)

				Eventually(session).Should(Say(`Getting events for app %s in org %s / space %s as %s\.\.\.`, appName, orgName, spaceName, userName))
				Eventually(session).Should(Say(`time\s+event\s+actor\s+description`))
				Eventually(session).Should(Say(`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{2}[-+]\d{4}\s+audit\.app\.update\s+%s`, userName))
				Eventually(session).Should(Say(`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{2}[-+]\d{4}\s+audit\.app\.update\s+%s`, userName))
				Eventually(session).Should(Say(`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{2}[-+]\d{4}\s+audit\.app\.create\s+%s`, userName))

				Eventually(session).Should(Exit(0))
			})
		})
	})
})
<commit_msg>Remove strict ordering assertion<commit_after>package isolated

import (
	. "code.cloudfoundry.org/cli/cf/util/testhelpers/matchers"
	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("events command", func() {
	var (
		orgName   string
		spaceName string
		appName   string
	)

	BeforeEach(func() {
		orgName = helpers.NewOrgName()
		spaceName = helpers.NewSpaceName()
		appName = helpers.PrefixedRandomName("app1")
	})

	Describe("help", func() {
		When("--help flag is set", func() {
			It("appears in cf help -a", func() {
				session := helpers.CF("help", "-a")
				Eventually(session).Should(Exit(0))
				Expect(session).To(HaveCommandInCategoryWithDescription("events", "APPS", "Show recent app events"))
			})

			It("Displays command usage to output", func() {
				session := helpers.CF("events", "--help")

				Eventually(session).Should(Say("NAME:"))
				Eventually(session).Should(Say("events - Show recent app events"))
				Eventually(session).Should(Say("USAGE:"))
				Eventually(session).Should(Say("cf events APP_NAME"))
				Eventually(session).Should(Say("SEE ALSO:"))
				Eventually(session).Should(Say("app, logs, map-route, unmap-route"))

				Eventually(session).Should(Exit(0))
			})
		})
	})

	When("the environment is not setup correctly", func() {
		It("fails with the appropriate errors", func() {
			helpers.CheckEnvironmentTargetedCorrectly(true, true, ReadOnlyOrg, "events", appName)
		})
	})

	When("the environment is set up correctly", func() {
		var userName string

		BeforeEach(func() {
			helpers.SetupCF(orgName, spaceName)
			userName, _ = helpers.GetCredentials()
		})

		AfterEach(func() {
			helpers.QuickDeleteOrg(orgName)
		})

		Context("with an existing app", func() {
			BeforeEach(func() {
				session := helpers.CF("create-app", appName)
				Eventually(session).Should(Exit(0))
				session = helpers.CF("rename", appName, "other-app-name")
				Eventually(session).Should(Exit(0))
				session = helpers.CF("rename", "other-app-name", appName)
				Eventually(session).Should(Exit(0))
			})

			It("displays events in the list", func() {

				// Order of output is hard to assert here so we will just asseert we output only the events we expect and then rely on the unit
				// tests to validate we are passing the `order_by=-created_at` query param to CAPI. The actual ordering is CAPIs concern.
				session := helpers.CF("events", appName)

				Eventually(session).Should(Say(`Getting events for app %s in org %s / space %s as %s\.\.\.`, appName, orgName, spaceName, userName))
				Eventually(session).Should(Say(`time\s+event\s+actor\s+description`))
				Eventually(session).Should(Say(`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{2}[-+]\d{4}\s+audit\.app\.(update|create)\s+%s`, userName))
				Eventually(session).Should(Say(`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{2}[-+]\d{4}\s+audit\.app\.(update|create)\s+%s`, userName))
				Eventually(session).Should(Say(`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{2}[-+]\d{4}\s+audit\.app\.(update|create)\s+%s`, userName))

				Eventually(session).Should(Exit(0))
			})
		})
	})
})
<|endoftext|>


<commit_before>package outputs

import (
	"log"

	"github.com/prometheus/client_golang/prometheus"
)

type Output interface {
	Init(map[string]interface{}, *log.Logger) error
	Write([]byte)
	Close() error
	Metrics() []prometheus.Collector
}
type Initializer func() Output

var Outputs = map[string]Initializer{}

func Register(name string, initFn Initializer) {
	Outputs[name] = initFn
}
<commit_msg>add meta to output Write method<commit_after>package outputs

import (
	"log"

	"github.com/prometheus/client_golang/prometheus"
)

type Output interface {
	Init(map[string]interface{}, *log.Logger) error
	Write([]byte, Meta)
	Close() error
	Metrics() []prometheus.Collector
}
type Initializer func() Output

var Outputs = map[string]Initializer{}

func Register(name string, initFn Initializer) {
	Outputs[name] = initFn
}

type Meta map[string]interface{}
<|endoftext|>


<commit_before>/*

guest-agent-update.

Example:
        { "execute": "guest-agent-update", "arguments": {
                "path": string // required, http/https/file path to qemu-ga binary for update
                "timeout": int // optional, timeout for http transport
                }
        }

*/

package guest_agent_update

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"syscall"
	"time"

	"github.com/vtolstov/qemu-ga/qga"
)

var cmdUpdate = &Command{
	Name:    "guest-agent-update",
	Func:    fnGuestAgentUpdate,
	Enabled: true,
}

func init() {
	commands = append(commands, cmdUpdate)
}

func fnGuestAgentUpdate(req *qga.Request) *qga.Response {
	res := &qga.Response{}
	var r io.ReadCloser
	var httpClient *http.Client

	httpTransport := &http.Transport{
		Dial:            (&net.Dialer{DualStack: true}).Dial,
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	reqData := struct {
		Path    string `json:"path"`
		Timeout int64  `json:"timeout,omitempty"`
	}{}

	err := json.Unmarshal(req.RawArgs, &reqData)
	if err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}

	if reqData.Timeout == 0 {
		reqData.Timeout = 30
	}

	httpClient = &http.Client{Transport: httpTransport, Timeout: reqData.Timeout * time.Second}

	u, err := url.Parse(reqData.Path)
	if err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	switch u.Scheme {
	case "http", "https":
		hres, err := httpClient.Get(reqData.Path)
		if err != nil {
			res.Error = &Error{Code: -1, Desc: err.Error()}
			return res
		}
		r = hres.Body
	case "file":
		r, err = os.Open(u.Path)
		if err != nil {
			res.Error = &Error{Code: -1, Desc: err.Error()}
			return res
		}
	default:
		res.Error = &Error{Code: -1, Desc: fmt.Sprintf("invalid path %s", u)}
		return res
	}
	defer r.Close()

	dirname, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	filename := fmt.Sprintf(".%s", filepath.Base(os.Args[0]))
	w, err := os.OpenFile(filepath.Join(dirname, filename), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(0755))
	if err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	_, err = io.Copy(w, r)
	if err != nil {
		defer w.Close()
		defer os.Remove(filepath.Join(dirname, filename))
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	w.Sync()
	w.Close()

	if err = os.Rename(filepath.Join(dirname, filename), filepath.Join(dirname, filepath.Base(os.Args[0]))); err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	time.Sleep(2 * time.Second)
	defer func() {
		cmd := exec.Command(os.Args[0])
		cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Noctty: false, Setpgid: false, Foreground: false}

		err = cmd.Start()
		if err != nil {
			fmt.Printf(err.Error())
		}
	}()

	return res
}
<commit_msg>up<commit_after>/*

guest-agent-update.

Example:
        { "execute": "guest-agent-update", "arguments": {
                "path": string // required, http/https/file path to qemu-ga binary for update
                "timeout": int // optional, timeout for http transport
                }
        }

*/
package guest_agent_update

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"syscall"
	"time"

	"github.com/vtolstov/qemu-ga/qga"
)

var cmdUpdate = &Command{
	Name:    "guest-agent-update",
	Func:    fnGuestAgentUpdate,
	Enabled: true,
}

func init() {
	commands = append(commands, cmdUpdate)
}

func fnGuestAgentUpdate(req *qga.Request) *qga.Response {
	res := &qga.Response{}
	var r io.ReadCloser
	var httpClient *http.Client

	httpTransport := &http.Transport{
		Dial:            (&net.Dialer{DualStack: true}).Dial,
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	reqData := struct {
		Path    string `json:"path"`
		Timeout int64  `json:"timeout,omitempty"`
	}{}

	err := json.Unmarshal(req.RawArgs, &reqData)
	if err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}

	if reqData.Timeout == 0 {
		reqData.Timeout = 30
	}

	httpClient = &http.Client{Transport: httpTransport, Timeout: reqData.Timeout * time.Second}

	u, err := url.Parse(reqData.Path)
	if err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	switch u.Scheme {
	case "http", "https":
		hres, err := httpClient.Get(reqData.Path)
		if err != nil {
			res.Error = &Error{Code: -1, Desc: err.Error()}
			return res
		}
		r = hres.Body
	case "file":
		r, err = os.Open(u.Path)
		if err != nil {
			res.Error = &Error{Code: -1, Desc: err.Error()}
			return res
		}
	default:
		res.Error = &Error{Code: -1, Desc: fmt.Sprintf("invalid path %s", u)}
		return res
	}
	defer r.Close()

	dirname, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	filename := fmt.Sprintf(".%s", filepath.Base(os.Args[0]))
	w, err := os.OpenFile(filepath.Join(dirname, filename), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(0755))
	if err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	_, err = io.Copy(w, r)
	if err != nil {
		defer w.Close()
		defer os.Remove(filepath.Join(dirname, filename))
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	w.Sync()
	w.Close()

	if err = os.Rename(filepath.Join(dirname, filename), filepath.Join(dirname, filepath.Base(os.Args[0]))); err != nil {
		res.Error = &Error{Code: -1, Desc: err.Error()}
		return res
	}
	time.Sleep(2 * time.Second)
	defer func() {
		cmd := exec.Command(os.Args[0])
		cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Noctty: false, Setpgid: false, Foreground: false}

		err = cmd.Start()
		if err != nil {
			fmt.Printf(err.Error())
		}
	}()

	return res
}
<|endoftext|>


<commit_before>package v2

import (
	"os"

	"code.cloudfoundry.org/cli/actors/v2actions"
	oldCmd "code.cloudfoundry.org/cli/cf/cmd"
	"code.cloudfoundry.org/cli/commands"
	"code.cloudfoundry.org/cli/commands/flags"
	"code.cloudfoundry.org/cli/commands/v2/common"
)

//go:generate counterfeiter . UnbindServiceActor

type UnbindServiceActor interface {
	UnbindServiceBySpace(appName string, serviceInstanceName string, spaceGUID string) (v2actions.Warnings, error)
}

type UnbindServiceCommand struct {
	RequiredArgs    flags.BindServiceArgs `positional-args:"yes"`
	usage           interface{}           `usage:"CF_NAME unbind-service APP_NAME SERVICE_INSTANCE"`
	relatedCommands interface{}           `related_commands:"apps, delete-service, services"`

	UI     commands.UI
	Actor  UnbindServiceActor
	Config commands.Config
}

func (cmd UnbindServiceCommand) Setup(config commands.Config, ui commands.UI) error {
	cmd.UI = ui
	cmd.Config = config

	client, err := common.NewCloudControllerClient(config)
	if err != nil {
		return err
	}
	cmd.Actor = v2actions.NewActor(client)

	return nil
}

func (cmd UnbindServiceCommand) Execute(args []string) error {
	if cmd.Config.Experimental() == false {
		oldCmd.Main(os.Getenv("CF_TRACE"), os.Args)
		return nil
	}

	cmd.UI.DisplayText("This command is in EXPERIMENTAL stage and may change without notice")
	cmd.UI.DisplayNewline()

	err := common.CheckTarget(cmd.Config, true, true)
	if err != nil {
		return err
	}

	space := cmd.Config.TargetedSpace()
	user, err := cmd.Config.CurrentUser()
	if err != nil {
		return err
	}

	cmd.UI.DisplayHeaderFlavorText("Unbinding app {{.AppName}} from service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{
		"AppName":     cmd.RequiredArgs.AppName,
		"ServiceName": cmd.RequiredArgs.ServiceInstanceName,
		"OrgName":     cmd.Config.TargetedOrganization().Name,
		"SpaceName":   space.Name,
		"CurrentUser": user.Name,
	})

	warnings, err := cmd.Actor.UnbindServiceBySpace(cmd.RequiredArgs.AppName, cmd.RequiredArgs.ServiceInstanceName, space.GUID)
	cmd.UI.DisplayWarnings(warnings)
	if err != nil {
		if _, ok := err.(v2actions.ServiceBindingNotFoundError); ok {
			cmd.UI.DisplayWarning("Binding between {{.InstanceName}} and {{.AppName}} did not exist", map[string]interface{}{
				"AppName":      cmd.RequiredArgs.AppName,
				"InstanceName": cmd.RequiredArgs.ServiceInstanceName,
			})
		} else {
			return common.HandleError(err)
		}
	}

	cmd.UI.DisplayOK()

	return nil
}
<commit_msg>setup should always be a pointer reciever<commit_after>package v2

import (
	"os"

	"code.cloudfoundry.org/cli/actors/v2actions"
	oldCmd "code.cloudfoundry.org/cli/cf/cmd"
	"code.cloudfoundry.org/cli/commands"
	"code.cloudfoundry.org/cli/commands/flags"
	"code.cloudfoundry.org/cli/commands/v2/common"
)

//go:generate counterfeiter . UnbindServiceActor

type UnbindServiceActor interface {
	UnbindServiceBySpace(appName string, serviceInstanceName string, spaceGUID string) (v2actions.Warnings, error)
}

type UnbindServiceCommand struct {
	RequiredArgs    flags.BindServiceArgs `positional-args:"yes"`
	usage           interface{}           `usage:"CF_NAME unbind-service APP_NAME SERVICE_INSTANCE"`
	relatedCommands interface{}           `related_commands:"apps, delete-service, services"`

	UI     commands.UI
	Actor  UnbindServiceActor
	Config commands.Config
}

func (cmd *UnbindServiceCommand) Setup(config commands.Config, ui commands.UI) error {
	cmd.UI = ui
	cmd.Config = config

	client, err := common.NewCloudControllerClient(config)
	if err != nil {
		return err
	}
	cmd.Actor = v2actions.NewActor(client)

	return nil
}

func (cmd UnbindServiceCommand) Execute(args []string) error {
	if cmd.Config.Experimental() == false {
		oldCmd.Main(os.Getenv("CF_TRACE"), os.Args)
		return nil
	}

	cmd.UI.DisplayText("This command is in EXPERIMENTAL stage and may change without notice")
	cmd.UI.DisplayNewline()

	err := common.CheckTarget(cmd.Config, true, true)
	if err != nil {
		return err
	}

	space := cmd.Config.TargetedSpace()
	user, err := cmd.Config.CurrentUser()
	if err != nil {
		return err
	}

	cmd.UI.DisplayHeaderFlavorText("Unbinding app {{.AppName}} from service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{
		"AppName":     cmd.RequiredArgs.AppName,
		"ServiceName": cmd.RequiredArgs.ServiceInstanceName,
		"OrgName":     cmd.Config.TargetedOrganization().Name,
		"SpaceName":   space.Name,
		"CurrentUser": user.Name,
	})

	warnings, err := cmd.Actor.UnbindServiceBySpace(cmd.RequiredArgs.AppName, cmd.RequiredArgs.ServiceInstanceName, space.GUID)
	cmd.UI.DisplayWarnings(warnings)
	if err != nil {
		if _, ok := err.(v2actions.ServiceBindingNotFoundError); ok {
			cmd.UI.DisplayWarning("Binding between {{.InstanceName}} and {{.AppName}} did not exist", map[string]interface{}{
				"AppName":      cmd.RequiredArgs.AppName,
				"InstanceName": cmd.RequiredArgs.ServiceInstanceName,
			})
		} else {
			return common.HandleError(err)
		}
	}

	cmd.UI.DisplayOK()

	return nil
}
<|endoftext|>


<commit_before>package helpers

import (
	"github.com/carbonsrv/carbon/ctest"
	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestHTMLHelpers(t *testing.T) {
	r := gin.New()
	r.GET("/string", func(c *gin.Context) {
		String(c, 200, "Hello world!")
	})

	w := ctest.Request(r, "GET", "/string")
	assert.Equal(t, w.Code, 200)
	assert.Equal(t, string(w.Body), "Hello world!")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain")
}
<commit_msg>Hooray, it worked!<commit_after>package helpers

import (
	"github.com/carbonsrv/carbon/ctest"
	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestHTMLHelpers(t *testing.T) {
	r := gin.New()
	r.GET("/string", func(c *gin.Context) {
		String(c, 200, "Hello world!")
	})

	w := ctest.Request(r, "GET", "/string")
	assert.Equal(t, w.Code, 200)
	assert.Equal(t, w.Body.String(), "Hello world!")
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain")
}
<|endoftext|>