<commit_before>package command

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"github.com/hashicorp/terraform/terraform"
)

// OutputCommand is a Command implementation that reads an output
// from a Terraform state and prints it.
type OutputCommand struct {
	Meta
}

func (c *OutputCommand) Run(args []string) int {
	var statePath string

	args = c.Meta.process(args, false)

	cmdFlags := flag.NewFlagSet("output", flag.ContinueOnError)
	cmdFlags.StringVar(&statePath, "state", DefaultStateFilename, "path")
	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
	if err := cmdFlags.Parse(args); err != nil {
		return 1
	}

	args = cmdFlags.Args()
	if len(args) != 1 || args[0] == "" {
		c.Ui.Error(
			"The output command expects exactly one argument with the name\n" +
				"of an output variable.\n")
		cmdFlags.Usage()
		return 1
	}
	name := args[0]

	f, err := os.Open(statePath)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error loading file: %s", err))
		return 1
	}

	state, err := terraform.ReadState(f)
	f.Close()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error reading state: %s", err))
		return 1
	}

	if len(state.RootModule().Outputs) == 0 {
		c.Ui.Error(fmt.Sprintf(
			"The state file has no outputs defined. Define an output\n" +
				"in your configuration with the `output` directive and re-run\n" +
				"`terraform apply` for it to become available."))
		return 1
	}
	v, ok := state.RootModule().Outputs[name]
	if !ok {
		c.Ui.Error(fmt.Sprintf(
			"The output variable requested could not be found in the state\n" +
				"file. If you recently added this to your configuration, be\n" +
				"sure to run `terraform apply`, since the state won't be updated\n" +
				"with new output variables until that command is run."))
		return 1
	}

	c.Ui.Output(v)
	return 0
}

func (c *OutputCommand) Help() string {
	helpText := `
Usage: terraform output [options] NAME

  Reads an output variable from a Terraform state file and prints
  the value.

Options:

  -state=path      Path to the state file to read. Defaults to
                   "terraform.tfstate".

`
	return strings.TrimSpace(helpText)
}

func (c *OutputCommand) Synopsis() string {
	return "Read an output from a state file"
}
<commit_msg>command/output: Remote enable<commit_after>package command

import (
	"flag"
	"fmt"
	"strings"
)

// OutputCommand is a Command implementation that reads an output
// from a Terraform state and prints it.
type OutputCommand struct {
	Meta
}

func (c *OutputCommand) Run(args []string) int {
	args = c.Meta.process(args, false)

	cmdFlags := flag.NewFlagSet("output", flag.ContinueOnError)
	cmdFlags.StringVar(&c.Meta.statePath, "state", DefaultStateFilename, "path")
	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
	if err := cmdFlags.Parse(args); err != nil {
		return 1
	}

	args = cmdFlags.Args()
	if len(args) != 1 || args[0] == "" {
		c.Ui.Error(
			"The output command expects exactly one argument with the name\n" +
				"of an output variable.\n")
		cmdFlags.Usage()
		return 1
	}
	name := args[0]

	state, err := c.Meta.loadState()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error reading state: %s", err))
		return 1
	}

	if len(state.RootModule().Outputs) == 0 {
		c.Ui.Error(fmt.Sprintf(
			"The state file has no outputs defined. Define an output\n" +
				"in your configuration with the `output` directive and re-run\n" +
				"`terraform apply` for it to become available."))
		return 1
	}
	v, ok := state.RootModule().Outputs[name]
	if !ok {
		c.Ui.Error(fmt.Sprintf(
			"The output variable requested could not be found in the state\n" +
				"file. If you recently added this to your configuration, be\n" +
				"sure to run `terraform apply`, since the state won't be updated\n" +
				"with new output variables until that command is run."))
		return 1
	}

	c.Ui.Output(v)
	return 0
}

func (c *OutputCommand) Help() string {
	helpText := `
Usage: terraform output [options] NAME

  Reads an output variable from a Terraform state file and prints
  the value.

Options:

  -state=path      Path to the state file to read. Defaults to
                   "terraform.tfstate".

`
	return strings.TrimSpace(helpText)
}

func (c *OutputCommand) Synopsis() string {
	return "Read an output from a state file"
}
<|endoftext|>


<commit_before>package commands

import (
	"github.com/jingweno/gh/github"
	"regexp"
	"strings"
)

var cmdClone = &Command{
	Run:          clone,
	GitExtension: true,
	Usage:        "clone [-p] OPTIONS [USER] REPOSITORY DIRECTORY",
	Short:        "clone a remote repository into a new directory",
}

/**
  $ gh clone jingweno/gh
  > git clone git://github.com/jingweno/gh

  $ gh clone -p jingweno/gh
  > git clone git@github.com:jingweno/gh.git

  $ gh clone jekyll_and_hype
  > git clone git://github.com/YOUR_LOGIN/jekyll_and_hype.

  $ hub clone -p jekyll_and_hype
  > git clone git@github.com:YOUR_LOGIN/jekyll_and_hype.git
*/
func clone(command *Command, args *Args) {
	if !args.IsEmpty() {
		transformCloneArgs(args)
	}
}

func transformCloneArgs(args *Args) {
	isSSH := parseClonePrivateFlag(args)
	hasValueRegxp := regexp.MustCompile("^(--(upload-pack|template|depth|origin|branch|reference|name)|-[ubo])$")
	nameWithOwnerRegexp := regexp.MustCompile(NameWithOwnerRe)
	for i, a := range args.Array() {
		if hasValueRegxp.MatchString(a) {
			continue
		}

		if nameWithOwnerRegexp.MatchString(a) && !isDir(a) {
			name, owner := parseCloneNameAndOwner(a)
			project := github.Project{Name: name, Owner: owner}
			url := project.GitURL(name, owner, isSSH)
			args.Replace(i, url)

			break
		}
	}
}

func parseClonePrivateFlag(args *Args) bool {
	if i := args.IndexOf("-p"); i != -1 {
		args.Remove(i)
		return true
	}

	return false
}

func parseCloneNameAndOwner(arg string) (name, owner string) {
	name, owner = arg, ""
	if strings.Contains(arg, "/") {
		split := strings.SplitN(arg, "/", 2)
		name = split[1]
		owner = split[0]
	}

	if owner == "" {
    config := github.CurrentConfig()
		owner = config.User
	}

	return
}
<commit_msg>Add long description to `clone`<commit_after>package commands

import (
	"github.com/jingweno/gh/github"
	"regexp"
	"strings"
)

var cmdClone = &Command{
	Run:          clone,
	GitExtension: true,
	Usage:        "clone [-p] OPTIONS [USER/]REPOSITORY DIRECTORY",
	Short:        "clone a remote repository into a new directory",
	Long: `Clone repository "git://github.com/USER/REPOSITORY.git" into
DIRECTORY as with git-clone(1). When USER/ is omitted, assumes
your GitHub login. With -p, clone private repositories over SSH.
For repositories under your GitHub login, -p is implicit.
`,
}

/**
  $ gh clone jingweno/gh
  > git clone git://github.com/jingweno/gh

  $ gh clone -p jingweno/gh
  > git clone git@github.com:jingweno/gh.git

  $ gh clone jekyll_and_hype
  > git clone git://github.com/YOUR_LOGIN/jekyll_and_hype.

  $ hub clone -p jekyll_and_hype
  > git clone git@github.com:YOUR_LOGIN/jekyll_and_hype.git
*/
func clone(command *Command, args *Args) {
	if !args.IsEmpty() {
		transformCloneArgs(args)
	}
}

func transformCloneArgs(args *Args) {
	isSSH := parseClonePrivateFlag(args)
	hasValueRegxp := regexp.MustCompile("^(--(upload-pack|template|depth|origin|branch|reference|name)|-[ubo])$")
	nameWithOwnerRegexp := regexp.MustCompile(NameWithOwnerRe)
	for i, a := range args.Array() {
		if hasValueRegxp.MatchString(a) {
			continue
		}

		if nameWithOwnerRegexp.MatchString(a) && !isDir(a) {
			name, owner := parseCloneNameAndOwner(a)
			project := github.Project{Name: name, Owner: owner}
			url := project.GitURL(name, owner, isSSH)
			args.Replace(i, url)

			break
		}
	}
}

func parseClonePrivateFlag(args *Args) bool {
	if i := args.IndexOf("-p"); i != -1 {
		args.Remove(i)
		return true
	}

	return false
}

func parseCloneNameAndOwner(arg string) (name, owner string) {
	name, owner = arg, ""
	if strings.Contains(arg, "/") {
		split := strings.SplitN(arg, "/", 2)
		name = split[1]
		owner = split[0]
	}

	if owner == "" {
		config := github.CurrentConfig()
		owner = config.User
	}

	return
}
<|endoftext|>


<commit_before>package commands

import (
	"fmt"
	"io"
	"net"
	"os"

	"github.com/moul/advanced-ssh-config/vendor/github.com/codegangsta/cli"

	"github.com/moul/advanced-ssh-config/config"
)

func cmdProxy(c *cli.Context) {
	if len(c.Args()) < 1 {
		os.Exit(1)
	}

	dest := c.Args()[0]

	conf, err := config.Open()
	if err != nil {
		panic(err)
	}

	// Get host configuration
	host := conf.GetHostSafe(dest)

	// Dial
	var port uint
	if c.Int("port") > 0 {
		port = uint(c.Int("port"))
	} else {
		port = host.Port
	}
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host.Host, port))
	if err != nil {
		panic(err)
	}

	defer conn.Close()

	fmt.Fprintf(os.Stderr, "Connected to %s:%d\n", host.Host, host.Port)

	// Create Stdio pipes
	go func() {
		_, err := io.Copy(conn, os.Stdin)
		if err != nil {
			panic(err)
		}
	}()
	go func() {
		_, err := io.Copy(os.Stderr, conn)
		if err != nil {
			panic(err)
		}
	}()
	_, err = io.Copy(os.Stdout, conn)
	if err != nil {
		panic(err)
	}

	return
}
<commit_msg>Refactored 'proxy' command<commit_after>package commands

import (
	"fmt"
	"io"
	"net"
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/moul/advanced-ssh-config/vendor/github.com/codegangsta/cli"

	"github.com/moul/advanced-ssh-config/config"
)

func cmdProxy(c *cli.Context) {
	if len(c.Args()) < 1 {
		logrus.Fatalf("assh: \"proxy\" requires 1 argument. See 'assh proxy --help'.")
	}

	host, port, err := configGetHostPort(c.Args()[0], c.Int("port"))
	if err != nil {
		logrus.Fatalf("Cannot get host '%s': %v", c.Args()[0], err)
	}

	err = proxy(host, port)
	if err != nil {
		logrus.Fatalf("Proxy error: %v", err)
	}
}

func configGetHostPort(dest string, portFlag int) (string, uint, error) {
	conf, err := config.Open()
	if err != nil {
		return "", 0, err
	}

	// Get host configuration
	host := conf.GetHostSafe(dest)

	// Dial
	var port uint
	if portFlag > 0 {
		port = uint(portFlag)
	} else {
		port = host.Port
	}

	return host.Host, port, nil
}

func proxy(host string, port uint) error {
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host, port))
	if err != nil {
		return err
	}

	defer conn.Close()

	logrus.Debugf("Connected to %s:%d\n", host, port)

	// Create Stdio pipes
	go func() {
		_, err := io.Copy(conn, os.Stdin)
		if err != nil {
			logrus.Fatalf("Stdin pipe error: %v", err)
		}
	}()
	go func() {
		_, err := io.Copy(os.Stderr, conn)
		if err != nil {
			logrus.Fatalf("Stdout pipe error: %v", err)
		}
	}()
	_, err = io.Copy(os.Stdout, conn)
	if err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>package json

import (
	"database/sql/driver"
	"fmt"
	"net"
)

// This type of time would be serialized to UNIX time for MarshalJSON()
type IP net.IP

// Implement MarshalJSON() here if needed
// func (ip IP) MarshalJSON() ([]byte, error) {
// }

// UnmarshalJSON parses the JSON-encoded IP string
func (ip *IP) UnmarshalJSON(data []byte) error {
	str := UnmarshalToJson(data).MustString()
	parsed := net.ParseIP(str)
	if parsed == nil {
		return fmt.Errorf("Cannot parse IP string: %s\n", str)
	}
	*ip = IP(parsed)
	return nil
}

func (ip IP) Value() (driver.Value, error) {
	// If ip is not an IPv4 address, To4 returns nil.
	if v4 := net.IP(ip).To4(); v4 != nil {
		return []byte(v4), nil
	}
	// ip must be IPv6 address
	return []byte(net.IP(ip).To16()), nil
}
<commit_msg>[OWL-1730][common] Use `strconv.Unquote`<commit_after>package json

import (
	"database/sql/driver"
	"fmt"
	"net"
	"strconv"
)

// This type of time would be serialized to UNIX time for MarshalJSON()
type IP net.IP

// Implement MarshalJSON() here if needed
// func (ip IP) MarshalJSON() ([]byte, error) {
// }

// UnmarshalJSON parses the JSON-encoded IP string
func (ip *IP) UnmarshalJSON(data []byte) error {
	str, err := strconv.Unquote(string(data))
	if err != nil {
		return fmt.Errorf("Unquote string %s error: %s\n", string(data), err)
	}
	parsed := net.ParseIP(str)
	if parsed == nil {
		return fmt.Errorf("Cannot parse IP string: %s\n", str)
	}
	*ip = IP(parsed)
	return nil
}

func (ip IP) Value() (driver.Value, error) {
	// If ip is not an IPv4 address, To4 returns nil.
	if v4 := net.IP(ip).To4(); v4 != nil {
		return []byte(v4), nil
	}
	// ip must be IPv6 address
	return []byte(net.IP(ip).To16()), 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 net

import (
	"reflect"
	"testing"
)

// loopbackInterface returns an available logical network interface
// for loopback tests.  It returns nil if no suitable interface is
// found.
func loopbackInterface() *Interface {
	ift, err := Interfaces()
	if err != nil {
		return nil
	}
	for _, ifi := range ift {
		if ifi.Flags&FlagLoopback != 0 && ifi.Flags&FlagUp != 0 {
			return &ifi
		}
	}
	return nil
}

// ipv6LinkLocalUnicastAddr returns an IPv6 link-local unicast address
// on the given network interface for tests. It returns "" if no
// suitable address is found.
func ipv6LinkLocalUnicastAddr(ifi *Interface) string {
	if ifi == nil {
		return ""
	}
	ifat, err := ifi.Addrs()
	if err != nil {
		return ""
	}
	for _, ifa := range ifat {
		switch ifa := ifa.(type) {
		case *IPAddr:
			if ifa.IP.To4() == nil && ifa.IP.IsLinkLocalUnicast() {
				return ifa.IP.String()
			}
		case *IPNet:
			if ifa.IP.To4() == nil && ifa.IP.IsLinkLocalUnicast() {
				return ifa.IP.String()
			}
		}
	}
	return ""
}

func TestInterfaces(t *testing.T) {
	ift, err := Interfaces()
	if err != nil {
		t.Fatalf("Interfaces failed: %v", err)
	}
	t.Logf("table: len/cap = %v/%v", len(ift), cap(ift))

	for _, ifi := range ift {
		ifxi, err := InterfaceByIndex(ifi.Index)
		if err != nil {
			t.Fatalf("InterfaceByIndex(%v) failed: %v", ifi.Index, err)
		}
		if !reflect.DeepEqual(ifxi, &ifi) {
			t.Fatalf("InterfaceByIndex(%v) = %v, want %v", ifi.Index, ifxi, ifi)
		}
		ifxn, err := InterfaceByName(ifi.Name)
		if err != nil {
			t.Fatalf("InterfaceByName(%q) failed: %v", ifi.Name, err)
		}
		if !reflect.DeepEqual(ifxn, &ifi) {
			t.Fatalf("InterfaceByName(%q) = %v, want %v", ifi.Name, ifxn, ifi)
		}
		t.Logf("%q: flags %q, ifindex %v, mtu %v", ifi.Name, ifi.Flags.String(), ifi.Index, ifi.MTU)
		t.Logf("\thardware address %q", ifi.HardwareAddr.String())
		testInterfaceAddrs(t, &ifi)
		testInterfaceMulticastAddrs(t, &ifi)
	}
}

func TestInterfaceAddrs(t *testing.T) {
	ifat, err := InterfaceAddrs()
	if err != nil {
		t.Fatalf("InterfaceAddrs failed: %v", err)
	}
	t.Logf("table: len/cap = %v/%v", len(ifat), cap(ifat))
	testAddrs(t, ifat)
}

func testInterfaceAddrs(t *testing.T, ifi *Interface) {
	ifat, err := ifi.Addrs()
	if err != nil {
		t.Fatalf("Interface.Addrs failed: %v", err)
	}
	testAddrs(t, ifat)
}

func testInterfaceMulticastAddrs(t *testing.T, ifi *Interface) {
	ifmat, err := ifi.MulticastAddrs()
	if err != nil {
		t.Fatalf("Interface.MulticastAddrs failed: %v", err)
	}
	testMulticastAddrs(t, ifmat)
}

func testAddrs(t *testing.T, ifat []Addr) {
	for _, ifa := range ifat {
		switch ifa := ifa.(type) {
		case *IPAddr:
			if ifa == nil || ifa.IP == nil {
				t.Errorf("\tunexpected value: %v, %v", ifa, ifa.IP)
			} else {
				t.Logf("\tinterface address %q", ifa.String())
			}
		case *IPNet:
			if ifa == nil || ifa.IP == nil || ifa.Mask == nil {
				t.Errorf("\tunexpected value: %v, %v, %v", ifa, ifa.IP, ifa.Mask)
			} else {
				_, prefixLen := ifa.Mask.Size()
				if ifa.IP.To4() != nil && prefixLen != 8*IPv4len || ifa.IP.To16() != nil && ifa.IP.To4() == nil && prefixLen != 8*IPv6len {
					t.Errorf("\tunexpected value: %v, %v, %v, %v", ifa, ifa.IP, ifa.Mask, prefixLen)
				} else {
					t.Logf("\tinterface address %q", ifa.String())
				}
			}
		default:
			t.Errorf("\tunexpected type: %T", ifa)
		}
	}
}

func testMulticastAddrs(t *testing.T, ifmat []Addr) {
	for _, ifma := range ifmat {
		switch ifma := ifma.(type) {
		case *IPAddr:
			if ifma == nil {
				t.Errorf("\tunexpected value: %v", ifma)
			} else {
				t.Logf("\tjoined group address %q", ifma.String())
			}
		default:
			t.Errorf("\tunexpected type: %T", ifma)
		}
	}
}

func BenchmarkInterfaces(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if _, err := Interfaces(); err != nil {
			b.Fatalf("Interfaces failed: %v", err)
		}
	}
}

func BenchmarkInterfaceByIndex(b *testing.B) {
	ifi := loopbackInterface()
	if ifi == nil {
		b.Skip("loopback interface not found")
	}
	for i := 0; i < b.N; i++ {
		if _, err := InterfaceByIndex(ifi.Index); err != nil {
			b.Fatalf("InterfaceByIndex failed: %v", err)
		}
	}
}

func BenchmarkInterfaceByName(b *testing.B) {
	ifi := loopbackInterface()
	if ifi == nil {
		b.Skip("loopback interface not found")
	}
	for i := 0; i < b.N; i++ {
		if _, err := InterfaceByName(ifi.Name); err != nil {
			b.Fatalf("InterfaceByName failed: %v", err)
		}
	}
}

func BenchmarkInterfaceAddrs(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if _, err := InterfaceAddrs(); err != nil {
			b.Fatalf("InterfaceAddrs failed: %v", err)
		}
	}
}

func BenchmarkInterfacesAndAddrs(b *testing.B) {
	ifi := loopbackInterface()
	if ifi == nil {
		b.Skip("loopback interface not found")
	}
	for i := 0; i < b.N; i++ {
		if _, err := ifi.Addrs(); err != nil {
			b.Fatalf("Interface.Addrs failed: %v", err)
		}
	}
}

func BenchmarkInterfacesAndMulticastAddrs(b *testing.B) {
	ifi := loopbackInterface()
	if ifi == nil {
		b.Skip("loopback interface not found")
	}
	for i := 0; i < b.N; i++ {
		if _, err := ifi.MulticastAddrs(); err != nil {
			b.Fatalf("Interface.MulticastAddrs failed: %v", err)
		}
	}
}
<commit_msg>net: update test cases for network interface API<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 net

import (
	"reflect"
	"runtime"
	"testing"
)

// loopbackInterface returns an available logical network interface
// for loopback tests.  It returns nil if no suitable interface is
// found.
func loopbackInterface() *Interface {
	ift, err := Interfaces()
	if err != nil {
		return nil
	}
	for _, ifi := range ift {
		if ifi.Flags&FlagLoopback != 0 && ifi.Flags&FlagUp != 0 {
			return &ifi
		}
	}
	return nil
}

// ipv6LinkLocalUnicastAddr returns an IPv6 link-local unicast address
// on the given network interface for tests. It returns "" if no
// suitable address is found.
func ipv6LinkLocalUnicastAddr(ifi *Interface) string {
	if ifi == nil {
		return ""
	}
	ifat, err := ifi.Addrs()
	if err != nil {
		return ""
	}
	for _, ifa := range ifat {
		switch ifa := ifa.(type) {
		case *IPNet:
			if ifa.IP.To4() == nil && ifa.IP.IsLinkLocalUnicast() {
				return ifa.IP.String()
			}
		}
	}
	return ""
}

func TestInterfaces(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("temporarily disabled until golang.org/issue/5395 is fixed")
	}

	ift, err := Interfaces()
	if err != nil {
		t.Fatal(err)
	}
	var nifs, naf4, naf6, nmaf4, nmaf6 int
	for _, ifi := range ift {
		ifxi, err := InterfaceByIndex(ifi.Index)
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(ifxi, &ifi) {
			t.Errorf("got %v; want %v", ifxi, ifi)
		}
		ifxn, err := InterfaceByName(ifi.Name)
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(ifxn, &ifi) {
			t.Errorf("got %v; want %v", ifxn, ifi)
		}
		t.Logf("%q: flags %q, ifindex %v, mtu %v", ifi.Name, ifi.Flags.String(), ifi.Index, ifi.MTU)
		t.Logf("hardware address %q", ifi.HardwareAddr.String())
		if ifi.Flags&FlagUp != 0 && ifi.Flags&FlagLoopback == 0 {
			nifs++ // active interfaces except loopback interfaces
		}
		n4, n6 := testInterfaceAddrs(t, &ifi)
		naf4 += n4
		naf6 += n6
		n4, n6 = testInterfaceMulticastAddrs(t, &ifi)
		nmaf4 += n4
		nmaf6 += n6
	}
	switch runtime.GOOS {
	case "nacl", "plan9", "solaris":
	default:
		if supportsIPv4 && nifs > 0 && naf4 == 0 {
			t.Errorf("got %v; want more than or equal to one", naf4)
		}
		if supportsIPv6 && nifs > 0 && naf6 == 0 {
			t.Errorf("got %v; want more than or equal to one", naf6)
		}
	}
	switch runtime.GOOS {
	case "dragonfly", "nacl", "netbsd", "openbsd", "plan9", "solaris":
	default:
		// Unlike IPv6, IPv4 multicast capability is not a
		// mandatory feature.
		//if supportsIPv4 && nactvifs > 0 && nmaf4 == 0 {
		//	t.Errorf("got %v; want more than or equal to one", nmaf4)
		//}
		if supportsIPv6 && nifs > 0 && nmaf6 == 0 {
			t.Errorf("got %v; want more than or equal to one", nmaf6)
		}
	}
}

func TestInterfaceAddrs(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("temporarily disabled until golang.org/issue/5395 is fixed")
	}

	ift, err := Interfaces()
	if err != nil {
		t.Fatal(err)
	}
	var nifs int
	for _, ifi := range ift {
		if ifi.Flags&FlagUp != 0 && ifi.Flags&FlagLoopback == 0 {
			nifs++ // active interfaces except loopback interfaces
		}
	}
	ifat, err := InterfaceAddrs()
	if err != nil {
		t.Fatal(err)
	}
	naf4, naf6 := testAddrs(t, ifat)
	if supportsIPv4 && nifs > 0 && naf4 == 0 {
		t.Errorf("got %v; want more than or equal to one", naf4)
	}
	if supportsIPv6 && nifs > 0 && naf6 == 0 {
		t.Errorf("got %v; want more than or equal to one", naf6)
	}
}

func testInterfaceAddrs(t *testing.T, ifi *Interface) (naf4, naf6 int) {
	ifat, err := ifi.Addrs()
	if err != nil {
		t.Fatal(err)
	}
	return testAddrs(t, ifat)
}

func testInterfaceMulticastAddrs(t *testing.T, ifi *Interface) (nmaf4, nmaf6 int) {
	ifmat, err := ifi.MulticastAddrs()
	if err != nil {
		t.Fatal(err)
	}
	return testMulticastAddrs(t, ifmat)
}

func testAddrs(t *testing.T, ifat []Addr) (naf4, naf6 int) {
	for _, ifa := range ifat {
		switch ifa := ifa.(type) {
		case *IPNet:
			if ifa == nil || ifa.IP == nil || ifa.IP.IsUnspecified() || ifa.IP.IsMulticast() || ifa.Mask == nil {
				t.Errorf("unexpected value: %#v", ifa)
				continue
			}
			prefixLen, maxPrefixLen := ifa.Mask.Size()
			if ifa.IP.To4() != nil {
				if 0 >= prefixLen || prefixLen > 8*IPv4len || maxPrefixLen != 8*IPv4len {
					t.Errorf("unexpected prefix length: %v/%v", prefixLen, maxPrefixLen)
					continue
				}
				naf4++
			} else if ifa.IP.To16() != nil {
				if 0 >= prefixLen || prefixLen > 8*IPv6len || maxPrefixLen != 8*IPv6len {
					t.Errorf("unexpected prefix length: %v/%v", prefixLen, maxPrefixLen)
					continue
				}
				naf6++
			}
			t.Logf("interface address %q", ifa.String())
		default:
			t.Errorf("unexpected type: %T", ifa)
		}
	}
	return
}

func testMulticastAddrs(t *testing.T, ifmat []Addr) (nmaf4, nmaf6 int) {
	for _, ifma := range ifmat {
		switch ifma := ifma.(type) {
		case *IPAddr:
			if ifma == nil || ifma.IP == nil || ifma.IP.IsUnspecified() || !ifma.IP.IsMulticast() {
				t.Errorf("unexpected value: %#v", ifma)
				continue
			}
			if ifma.IP.To4() != nil {
				nmaf4++
			} else if ifma.IP.To16() != nil {
				nmaf6++
			}
			t.Logf("joined group address %q", ifma.String())
		default:
			t.Errorf("unexpected type: %T", ifma)
		}
	}
	return
}

func BenchmarkInterfaces(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if _, err := Interfaces(); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkInterfaceByIndex(b *testing.B) {
	ifi := loopbackInterface()
	if ifi == nil {
		b.Skip("loopback interface not found")
	}
	for i := 0; i < b.N; i++ {
		if _, err := InterfaceByIndex(ifi.Index); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkInterfaceByName(b *testing.B) {
	ifi := loopbackInterface()
	if ifi == nil {
		b.Skip("loopback interface not found")
	}
	for i := 0; i < b.N; i++ {
		if _, err := InterfaceByName(ifi.Name); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkInterfaceAddrs(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if _, err := InterfaceAddrs(); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkInterfacesAndAddrs(b *testing.B) {
	ifi := loopbackInterface()
	if ifi == nil {
		b.Skip("loopback interface not found")
	}
	for i := 0; i < b.N; i++ {
		if _, err := ifi.Addrs(); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkInterfacesAndMulticastAddrs(b *testing.B) {
	ifi := loopbackInterface()
	if ifi == nil {
		b.Skip("loopback interface not found")
	}
	for i := 0; i < b.N; i++ {
		if _, err := ifi.MulticastAddrs(); err != nil {
			b.Fatal(err)
		}
	}
}
<|endoftext|>


<commit_before>// Copyright 2013 The Prometheus 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 remote

import (
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/prometheus/common/model"
)

type TestStorageClient struct {
	receivedSamples model.Samples
	expectedSamples model.Samples
	wg              sync.WaitGroup
}

func (c *TestStorageClient) expectSamples(s model.Samples) {
	c.expectedSamples = append(c.expectedSamples, s...)
	c.wg.Add(len(s))
}

func (c *TestStorageClient) waitForExpectedSamples(t *testing.T) {
	c.wg.Wait()
	for i, expected := range c.expectedSamples {
		if !expected.Equal(c.receivedSamples[i]) {
			t.Fatalf("%d. Expected %v, got %v", i, expected, c.receivedSamples[i])
		}
	}
}

func (c *TestStorageClient) Store(s model.Samples) error {
	c.receivedSamples = append(c.receivedSamples, s...)
	c.wg.Add(-len(s))
	return nil
}

func (c *TestStorageClient) Name() string {
	return "teststorageclient"
}

func TestSampleDelivery(t *testing.T) {
	// Let's create an even number of send batches so we don't run into the
	// batch timeout case.
	n := maxSamplesPerSend * 2

	samples := make(model.Samples, 0, n)
	for i := 0; i < n; i++ {
		samples = append(samples, &model.Sample{
			Metric: model.Metric{
				model.MetricNameLabel: "test_metric",
			},
			Value: model.SampleValue(i),
		})
	}

	c := &TestStorageClient{}
	c.expectSamples(samples[:len(samples)/2])
	m := NewStorageQueueManager(c, len(samples)/2)

	// These should be received by the client.
	for _, s := range samples[:len(samples)/2] {
		m.Append(s)
	}
	// These will be dropped because the queue is full.
	for _, s := range samples[len(samples)/2:] {
		m.Append(s)
	}
	go m.Run()
	defer m.Stop()

	c.waitForExpectedSamples(t)
}

// TestBlockingStorageClient is a queue_manager StorageClient which will block
// on any calls to Store(), until the `block` channel is closed, at which point
// the `numCalls` property will contain a count of how many times Store() was
// called.
type TestBlockingStorageClient struct {
	block    chan bool
	numCalls uint64
}

func NewTestBlockedStorageClient() *TestBlockingStorageClient {
	return &TestBlockingStorageClient{
		block:    make(chan bool),
		numCalls: 0,
	}
}

func (c *TestBlockingStorageClient) Store(s model.Samples) error {
	atomic.AddUint64(&c.numCalls, 1)
	<-c.block
	return nil
}

func (c *TestBlockingStorageClient) NumCalls() uint64 {
	return atomic.LoadUint64(&c.numCalls)
}

func (c *TestBlockingStorageClient) unlock() {
	close(c.block)
}

func (c *TestBlockingStorageClient) Name() string {
	return "testblockingstorageclient"
}

func TestSpawnNotMoreThanMaxConcurrentSendsGoroutines(t *testing.T) {
	// Our goal is to fully empty the queue:
	// `maxSamplesPerSend*maxConcurrentSends` samples should be consumed by the
	// semaphore-controlled goroutines, and then another `maxSamplesPerSend`
	// should be consumed by the Run() loop calling sendSample and immediately
	// blocking.
	n := maxSamplesPerSend*maxConcurrentSends + maxSamplesPerSend

	samples := make(model.Samples, 0, n)
	for i := 0; i < n; i++ {
		samples = append(samples, &model.Sample{
			Metric: model.Metric{
				model.MetricNameLabel: "test_metric",
			},
			Value: model.SampleValue(i),
		})
	}

	c := NewTestBlockedStorageClient()
	m := NewStorageQueueManager(c, n)

	go m.Run()
	defer m.Stop()

	for _, s := range samples {
		m.Append(s)
	}

	// Wait until the Run() loop drains the queue.  If things went right, it
	// should then immediately block in sendSamples(), but, in case of error,
	// it would spawn too many goroutines, and thus we'd see more calls to
	// client.Store()
	//
	// The timed wait is maybe non-ideal, but, in order to verify that we're
	// not spawning too many concurrent goroutines, we have to wait on the
	// Run() loop to consume a specific number of elements from the
	// queue... and it doesn't signal that in any obvious way, except by
	// draining the queue.  Also, this way, if something goes surprisingly
	// wrong that prevents the queue from being drained (aka, not just spawning
	// extra goroutines, but something totally unexpected), we deadlock, which
	// is a clear signal of a problem.
	for len(m.queue) > 0 {
		time.Sleep(10 * time.Millisecond)
	}

	numCalls := c.NumCalls()
	if numCalls != maxConcurrentSends {
		t.Errorf("Saw %d concurrent sends, expected %d", numCalls, maxConcurrentSends)
	}

	c.unlock()
}
<commit_msg>Add timeout to test, cap waiting at 1 second<commit_after>// Copyright 2013 The Prometheus 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 remote

import (
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/prometheus/common/model"
)

type TestStorageClient struct {
	receivedSamples model.Samples
	expectedSamples model.Samples
	wg              sync.WaitGroup
}

func (c *TestStorageClient) expectSamples(s model.Samples) {
	c.expectedSamples = append(c.expectedSamples, s...)
	c.wg.Add(len(s))
}

func (c *TestStorageClient) waitForExpectedSamples(t *testing.T) {
	c.wg.Wait()
	for i, expected := range c.expectedSamples {
		if !expected.Equal(c.receivedSamples[i]) {
			t.Fatalf("%d. Expected %v, got %v", i, expected, c.receivedSamples[i])
		}
	}
}

func (c *TestStorageClient) Store(s model.Samples) error {
	c.receivedSamples = append(c.receivedSamples, s...)
	c.wg.Add(-len(s))
	return nil
}

func (c *TestStorageClient) Name() string {
	return "teststorageclient"
}

func TestSampleDelivery(t *testing.T) {
	// Let's create an even number of send batches so we don't run into the
	// batch timeout case.
	n := maxSamplesPerSend * 2

	samples := make(model.Samples, 0, n)
	for i := 0; i < n; i++ {
		samples = append(samples, &model.Sample{
			Metric: model.Metric{
				model.MetricNameLabel: "test_metric",
			},
			Value: model.SampleValue(i),
		})
	}

	c := &TestStorageClient{}
	c.expectSamples(samples[:len(samples)/2])
	m := NewStorageQueueManager(c, len(samples)/2)

	// These should be received by the client.
	for _, s := range samples[:len(samples)/2] {
		m.Append(s)
	}
	// These will be dropped because the queue is full.
	for _, s := range samples[len(samples)/2:] {
		m.Append(s)
	}
	go m.Run()
	defer m.Stop()

	c.waitForExpectedSamples(t)
}

// TestBlockingStorageClient is a queue_manager StorageClient which will block
// on any calls to Store(), until the `block` channel is closed, at which point
// the `numCalls` property will contain a count of how many times Store() was
// called.
type TestBlockingStorageClient struct {
	block    chan bool
	numCalls uint64
}

func NewTestBlockedStorageClient() *TestBlockingStorageClient {
	return &TestBlockingStorageClient{
		block:    make(chan bool),
		numCalls: 0,
	}
}

func (c *TestBlockingStorageClient) Store(s model.Samples) error {
	atomic.AddUint64(&c.numCalls, 1)
	<-c.block
	return nil
}

func (c *TestBlockingStorageClient) NumCalls() uint64 {
	return atomic.LoadUint64(&c.numCalls)
}

func (c *TestBlockingStorageClient) unlock() {
	close(c.block)
}

func (c *TestBlockingStorageClient) Name() string {
	return "testblockingstorageclient"
}

func TestSpawnNotMoreThanMaxConcurrentSendsGoroutines(t *testing.T) {
	// Our goal is to fully empty the queue:
	// `maxSamplesPerSend*maxConcurrentSends` samples should be consumed by the
	// semaphore-controlled goroutines, and then another `maxSamplesPerSend`
	// should be consumed by the Run() loop calling sendSample and immediately
	// blocking.
	n := maxSamplesPerSend*maxConcurrentSends + maxSamplesPerSend

	samples := make(model.Samples, 0, n)
	for i := 0; i < n; i++ {
		samples = append(samples, &model.Sample{
			Metric: model.Metric{
				model.MetricNameLabel: "test_metric",
			},
			Value: model.SampleValue(i),
		})
	}

	c := NewTestBlockedStorageClient()
	m := NewStorageQueueManager(c, n)

	go m.Run()

	defer func() {
		c.unlock()
		m.Stop()
	}()

	for _, s := range samples {
		m.Append(s)
	}

	// Wait until the Run() loop drains the queue.  If things went right, it
	// should then immediately block in sendSamples(), but, in case of error,
	// it would spawn too many goroutines, and thus we'd see more calls to
	// client.Store()
	//
	// The timed wait is maybe non-ideal, but, in order to verify that we're
	// not spawning too many concurrent goroutines, we have to wait on the
	// Run() loop to consume a specific number of elements from the
	// queue... and it doesn't signal that in any obvious way, except by
	// draining the queue.  We cap the waiting at 1 second -- that should give
	// plenty of time, and keeps the failure fairly quick if we're not draining
	// the queue properly.
	for i := 0; i < 100 && len(m.queue) > 0; i++ {
		time.Sleep(10 * time.Millisecond)
	}

	if len(m.queue) > 0 {
		t.Fatalf("Failed to drain StorageQueueManager queue, %d elements left",
			len(m.queue),
		)
	}

	numCalls := c.NumCalls()
	if numCalls != maxConcurrentSends {
		t.Errorf("Saw %d concurrent sends, expected %d", numCalls, maxConcurrentSends)
	}

}
<|endoftext|>


<commit_before>//Generated by gRPC Go plugin
//If you make any local changes, they will be lost
//source: schema

package symbol

import (
	flatbuffers "github.com/google/flatbuffers/go"
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// ClangClient API for Clang service
type ClangClient interface {
	Store(ctx context.Context, opts ...grpc.CallOption) (Clang_StoreClient, error)
	Retrieve(ctx context.Context, opts ...grpc.CallOption) (Clang_RetrieveClient, error)
}

type clangClient struct {
	cc *grpc.ClientConn
}

func NewClangClient(cc *grpc.ClientConn) ClangClient {
	return &clangClient{cc}
}

func (c *clangClient) Store(ctx context.Context, opts ...grpc.CallOption) (Clang_StoreClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_Clang_serviceDesc.Streams[0], c.cc, "/symbol.Clang/Store", opts...)
	if err != nil {
		return nil, err
	}
	x := &clangStoreClient{stream}
	return x, nil
}

type Clang_StoreClient interface {
	Send(*flatbuffers.Builder) error
	Recv() (*Location, error)
	grpc.ClientStream
}

type clangStoreClient struct {
	grpc.ClientStream
}

func (x *clangStoreClient) Send(m *flatbuffers.Builder) error {
	return x.ClientStream.SendMsg(m)
}

func (x *clangStoreClient) Recv() (*Location, error) {
	m := new(Location)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *clangClient) Retrieve(ctx context.Context, opts ...grpc.CallOption) (Clang_RetrieveClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_Clang_serviceDesc.Streams[1], c.cc, "/symbol.Clang/Retrieve", opts...)
	if err != nil {
		return nil, err
	}
	x := &clangRetrieveClient{stream}
	return x, nil
}

type Clang_RetrieveClient interface {
	Send(*flatbuffers.Builder) error
	Recv() (*Info, error)
	grpc.ClientStream
}

type clangRetrieveClient struct {
	grpc.ClientStream
}

func (x *clangRetrieveClient) Send(m *flatbuffers.Builder) error {
	return x.ClientStream.SendMsg(m)
}

func (x *clangRetrieveClient) Recv() (*Info, error) {
	m := new(Info)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// ClangServer API for Clang service
type ClangServer interface {
	Store(Clang_StoreServer) error
	Retrieve(Clang_RetrieveServer) error
}

func RegisterClangServer(s *grpc.Server, srv ClangServer) {
	s.RegisterService(&_Clang_serviceDesc, srv)
}

func _Clang_Store_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(ClangServer).Store(&clangStoreServer{stream})
}

type Clang_StoreServer interface {
	Send(*flatbuffers.Builder) error
	Recv() (*Info, error)
	grpc.ServerStream
}

type clangStoreServer struct {
	grpc.ServerStream
}

func (x *clangStoreServer) Send(m *flatbuffers.Builder) error {
	return x.ServerStream.SendMsg(m)
}

func (x *clangStoreServer) Recv() (*Info, error) {
	m := new(Info)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func _Clang_Retrieve_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(ClangServer).Retrieve(&clangRetrieveServer{stream})
}

type Clang_RetrieveServer interface {
	Send(*flatbuffers.Builder) error
	Recv() (*Location, error)
	grpc.ServerStream
}

type clangRetrieveServer struct {
	grpc.ServerStream
}

func (x *clangRetrieveServer) Send(m *flatbuffers.Builder) error {
	return x.ServerStream.SendMsg(m)
}

func (x *clangRetrieveServer) Recv() (*Location, error) {
	m := new(Location)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

var _Clang_serviceDesc = grpc.ServiceDesc{
	ServiceName: "symbol.Clang",
	HandlerType: (*ClangServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "Store",
			Handler:       _Clang_Store_Handler,
			ServerStreams: true,
			ClientStreams: true,
		},
		{
			StreamName:    "Retrieve",
			Handler:       _Clang_Retrieve_Handler,
			ServerStreams: true,
			ClientStreams: true,
		},
	},
}
<commit_msg>symbol/internal: regenerate flatbuffers Go files<commit_after>//Generated by gRPC Go plugin
//If you make any local changes, they will be lost
//source: schema

package symbol

import (
	flatbuffers "github.com/google/flatbuffers/go"
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// ClangClient API for Clang service
type ClangClient interface {
	Completion(ctx context.Context, opts ...grpc.CallOption) (Clang_CompletionClient, error)
}

type clangClient struct {
	cc *grpc.ClientConn
}

func NewClangClient(cc *grpc.ClientConn) ClangClient {
	return &clangClient{cc}
}

func (c *clangClient) Completion(ctx context.Context, opts ...grpc.CallOption) (Clang_CompletionClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_Clang_serviceDesc.Streams[0], c.cc, "/symbol.Clang/Completion", opts...)
	if err != nil {
		return nil, err
	}
	x := &clangCompletionClient{stream}
	return x, nil
}

type Clang_CompletionClient interface {
	Send(*flatbuffers.Builder) error
	Recv() (*File, error)
	grpc.ClientStream
}

type clangCompletionClient struct {
	grpc.ClientStream
}

func (x *clangCompletionClient) Send(m *flatbuffers.Builder) error {
	return x.ClientStream.SendMsg(m)
}

func (x *clangCompletionClient) Recv() (*File, error) {
	m := new(File)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// ClangServer API for Clang service
type ClangServer interface {
	Completion(Clang_CompletionServer) error
}

func RegisterClangServer(s *grpc.Server, srv ClangServer) {
	s.RegisterService(&_Clang_serviceDesc, srv)
}

func _Clang_Completion_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(ClangServer).Completion(&clangCompletionServer{stream})
}

type Clang_CompletionServer interface {
	Send(*flatbuffers.Builder) error
	Recv() (*Location, error)
	grpc.ServerStream
}

type clangCompletionServer struct {
	grpc.ServerStream
}

func (x *clangCompletionServer) Send(m *flatbuffers.Builder) error {
	return x.ServerStream.SendMsg(m)
}

func (x *clangCompletionServer) Recv() (*Location, error) {
	m := new(Location)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

var _Clang_serviceDesc = grpc.ServiceDesc{
	ServiceName: "symbol.Clang",
	HandlerType: (*ClangServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "Completion",
			Handler:       _Clang_Completion_Handler,
			ServerStreams: true,
			ClientStreams: true,
		},
	},
}
<|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 unicode 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.
	MaxASCII        = 0x7F     // maximum ASCII value.
	MaxLatin1       = 0xFF     // maximum Latin-1 value.
)

// RangeTable defines a set of Unicode code points by listing the ranges of
// code points within the set. The ranges are listed in two slices
// to save space: a slice of 16-bit ranges and a slice of 32-bit ranges.
// The two slices must be in sorted order and non-overlapping.
// Also, R32 should contain only values >= 0x10000 (1<<16).
type RangeTable struct {
	R16 []Range16
	R32 []Range32
}

// Range16 represents of a range of 16-bit Unicode code points.  The range runs from Lo to Hi
// inclusive and has the specified stride.
type Range16 struct {
	Lo     uint16
	Hi     uint16
	Stride uint16
}

// Range32 represents of a range of Unicode code points and is used when one or
//  more of the values will not fit in 16 bits.  The range runs from Lo to Hi
// inclusive and has the specified stride. Lo and Hi must always be >= 1<<16.
type Range32 struct {
	Lo     uint32
	Hi     uint32
	Stride uint32
}

// CaseRange represents a range of Unicode code points for simple (one
// code point to one code point) 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    uint32
	Hi    uint32
	Delta d
}

// SpecialCase represents language-specific case mappings such as Turkish.
// Methods of SpecialCase customize (by overriding) the standard mappings.
type SpecialCase []CaseRange

//BUG(r): Provide a mechanism for full case folding (those that involve
// multiple runes in the input or output).

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

// is16 uses binary search to test whether rune is in the specified slice of 16-bit ranges.
func is16(ranges []Range16, rune uint16) bool {
	// 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
}

// is32 uses binary search to test whether rune is in the specified slice of 32-bit ranges.
func is32(ranges []Range32, rune uint32) bool {
	// 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
}

// Is tests whether rune is in the specified table of ranges.
func Is(rangeTab *RangeTable, rune int) bool {
	// common case: rune is ASCII or Latin-1.
	if uint32(rune) <= MaxLatin1 {
		// Only need to check R16, since R32 is always >= 1<<16.
		r16 := uint16(rune)
		for _, r := range rangeTab.R16 {
			if r16 > r.Hi {
				continue
			}
			if r16 < r.Lo {
				return false
			}
			return (r16-r.Lo)%r.Stride == 0
		}
		return false
	}
	r16 := rangeTab.R16
	if len(r16) > 0 && rune <= int(r16[len(r16)-1].Hi) {
		return is16(r16, uint16(rune))
	}
	r32 := rangeTab.R32
	if len(r32) > 0 && rune >= int(r32[0].Lo) {
		return is32(r32, uint32(rune))
	}
	return false
}

// IsUpper reports whether the rune is an upper case letter.
func IsUpper(rune int) bool {
	// See comment in IsGraphic.
	if uint32(rune) <= MaxLatin1 {
		return properties[uint8(rune)]&pLu != 0
	}
	return Is(Upper, rune)
}

// IsLower reports whether the rune is a lower case letter.
func IsLower(rune int) bool {
	// See comment in IsGraphic.
	if uint32(rune) <= MaxLatin1 {
		return properties[uint8(rune)]&pLl != 0
	}
	return Is(Lower, rune)
}

// IsTitle reports whether the rune is a title case letter.
func IsTitle(rune int) bool {
	if rune <= MaxLatin1 {
		return false
	}
	return Is(Title, rune)
}

// to maps the rune using the specified case mapping.
func to(_case int, rune int, caseRange []CaseRange) int {
	if _case < 0 || MaxCase <= _case {
		return ReplacementChar // as reasonable an error as any
	}
	// binary search over ranges
	lo := 0
	hi := len(caseRange)
	for lo < hi {
		m := lo + (hi-lo)/2
		r := caseRange[m]
		if int(r.Lo) <= rune && rune <= int(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 int(r.Lo) + ((rune-int(r.Lo))&^1 | _case&1)
			}
			return rune + delta
		}
		if rune < int(r.Lo) {
			hi = m
		} else {
			lo = m + 1
		}
	}
	return rune
}

// To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase.
func To(_case int, rune int) int {
	return to(_case, rune, CaseRanges)
}

// ToUpper maps the rune to upper case.
func ToUpper(rune int) int {
	if rune <= MaxASCII {
		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 <= MaxASCII {
		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 <= MaxASCII {
		if 'a' <= rune && rune <= 'z' { // title case is upper case for ASCII
			rune -= 'a' - 'A'
		}
		return rune
	}
	return To(TitleCase, rune)
}

// ToUpper maps the rune to upper case giving priority to the special mapping.
func (special SpecialCase) ToUpper(rune int) int {
	r := to(UpperCase, rune, []CaseRange(special))
	if r == rune {
		r = ToUpper(rune)
	}
	return r
}

// ToTitle maps the rune to title case giving priority to the special mapping.
func (special SpecialCase) ToTitle(rune int) int {
	r := to(TitleCase, rune, []CaseRange(special))
	if r == rune {
		r = ToTitle(rune)
	}
	return r
}

// ToLower maps the rune to lower case giving priority to the special mapping.
func (special SpecialCase) ToLower(rune int) int {
	r := to(LowerCase, rune, []CaseRange(special))
	if r == rune {
		r = ToLower(rune)
	}
	return r
}

// caseOrbit is defined in tables.go as []foldPair.  Right now all the
// entries fit in uint16, so use uint16.  If that changes, compilation
// will fail (the constants in the composite literal will not fit in uint16)
// and the types here can change to uint32.
type foldPair struct {
	From uint16
	To   uint16
}

// SimpleFold iterates over Unicode code points equivalent under
// the Unicode-defined simple case folding.  Among the code points
// equivalent to rune (including rune itself), SimpleFold returns the
// smallest r >= rune if one exists, or else the smallest r >= 0.
//
// For example:
//	SimpleFold('A') = 'a'
//	SimpleFold('a') = 'A'
//
//	SimpleFold('K') = 'k'
//	SimpleFold('k') = '\u212A' (Kelvin symbol, K)
//	SimpleFold('\u212A') = 'K'
//
//	SimpleFold('1') = '1'
//
func SimpleFold(rune int) int {
	// Consult caseOrbit table for special cases.
	lo := 0
	hi := len(caseOrbit)
	for lo < hi {
		m := lo + (hi-lo)/2
		if int(caseOrbit[m].From) < rune {
			lo = m + 1
		} else {
			hi = m
		}
	}
	if lo < len(caseOrbit) && int(caseOrbit[lo].From) == rune {
		return int(caseOrbit[lo].To)
	}

	// No folding specified.  This is a one- or two-element
	// equivalence class containing rune and ToLower(rune)
	// and ToUpper(rune) if they are different from rune.
	if l := ToLower(rune); l != rune {
		return l
	}
	return ToUpper(rune)
}
<commit_msg>unicode: fix doc comment for Range32<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 unicode 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.
	MaxASCII        = 0x7F     // maximum ASCII value.
	MaxLatin1       = 0xFF     // maximum Latin-1 value.
)

// RangeTable defines a set of Unicode code points by listing the ranges of
// code points within the set. The ranges are listed in two slices
// to save space: a slice of 16-bit ranges and a slice of 32-bit ranges.
// The two slices must be in sorted order and non-overlapping.
// Also, R32 should contain only values >= 0x10000 (1<<16).
type RangeTable struct {
	R16 []Range16
	R32 []Range32
}

// Range16 represents of a range of 16-bit Unicode code points.  The range runs from Lo to Hi
// inclusive and has the specified stride.
type Range16 struct {
	Lo     uint16
	Hi     uint16
	Stride uint16
}

// Range32 represents of a range of Unicode code points and is used when one or
// more of the values will not fit in 16 bits.  The range runs from Lo to Hi
// inclusive and has the specified stride. Lo and Hi must always be >= 1<<16.
type Range32 struct {
	Lo     uint32
	Hi     uint32
	Stride uint32
}

// CaseRange represents a range of Unicode code points for simple (one
// code point to one code point) 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    uint32
	Hi    uint32
	Delta d
}

// SpecialCase represents language-specific case mappings such as Turkish.
// Methods of SpecialCase customize (by overriding) the standard mappings.
type SpecialCase []CaseRange

//BUG(r): Provide a mechanism for full case folding (those that involve
// multiple runes in the input or output).

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

// is16 uses binary search to test whether rune is in the specified slice of 16-bit ranges.
func is16(ranges []Range16, rune uint16) bool {
	// 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
}

// is32 uses binary search to test whether rune is in the specified slice of 32-bit ranges.
func is32(ranges []Range32, rune uint32) bool {
	// 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
}

// Is tests whether rune is in the specified table of ranges.
func Is(rangeTab *RangeTable, rune int) bool {
	// common case: rune is ASCII or Latin-1.
	if uint32(rune) <= MaxLatin1 {
		// Only need to check R16, since R32 is always >= 1<<16.
		r16 := uint16(rune)
		for _, r := range rangeTab.R16 {
			if r16 > r.Hi {
				continue
			}
			if r16 < r.Lo {
				return false
			}
			return (r16-r.Lo)%r.Stride == 0
		}
		return false
	}
	r16 := rangeTab.R16
	if len(r16) > 0 && rune <= int(r16[len(r16)-1].Hi) {
		return is16(r16, uint16(rune))
	}
	r32 := rangeTab.R32
	if len(r32) > 0 && rune >= int(r32[0].Lo) {
		return is32(r32, uint32(rune))
	}
	return false
}

// IsUpper reports whether the rune is an upper case letter.
func IsUpper(rune int) bool {
	// See comment in IsGraphic.
	if uint32(rune) <= MaxLatin1 {
		return properties[uint8(rune)]&pLu != 0
	}
	return Is(Upper, rune)
}

// IsLower reports whether the rune is a lower case letter.
func IsLower(rune int) bool {
	// See comment in IsGraphic.
	if uint32(rune) <= MaxLatin1 {
		return properties[uint8(rune)]&pLl != 0
	}
	return Is(Lower, rune)
}

// IsTitle reports whether the rune is a title case letter.
func IsTitle(rune int) bool {
	if rune <= MaxLatin1 {
		return false
	}
	return Is(Title, rune)
}

// to maps the rune using the specified case mapping.
func to(_case int, rune int, caseRange []CaseRange) int {
	if _case < 0 || MaxCase <= _case {
		return ReplacementChar // as reasonable an error as any
	}
	// binary search over ranges
	lo := 0
	hi := len(caseRange)
	for lo < hi {
		m := lo + (hi-lo)/2
		r := caseRange[m]
		if int(r.Lo) <= rune && rune <= int(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 int(r.Lo) + ((rune-int(r.Lo))&^1 | _case&1)
			}
			return rune + delta
		}
		if rune < int(r.Lo) {
			hi = m
		} else {
			lo = m + 1
		}
	}
	return rune
}

// To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase.
func To(_case int, rune int) int {
	return to(_case, rune, CaseRanges)
}

// ToUpper maps the rune to upper case.
func ToUpper(rune int) int {
	if rune <= MaxASCII {
		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 <= MaxASCII {
		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 <= MaxASCII {
		if 'a' <= rune && rune <= 'z' { // title case is upper case for ASCII
			rune -= 'a' - 'A'
		}
		return rune
	}
	return To(TitleCase, rune)
}

// ToUpper maps the rune to upper case giving priority to the special mapping.
func (special SpecialCase) ToUpper(rune int) int {
	r := to(UpperCase, rune, []CaseRange(special))
	if r == rune {
		r = ToUpper(rune)
	}
	return r
}

// ToTitle maps the rune to title case giving priority to the special mapping.
func (special SpecialCase) ToTitle(rune int) int {
	r := to(TitleCase, rune, []CaseRange(special))
	if r == rune {
		r = ToTitle(rune)
	}
	return r
}

// ToLower maps the rune to lower case giving priority to the special mapping.
func (special SpecialCase) ToLower(rune int) int {
	r := to(LowerCase, rune, []CaseRange(special))
	if r == rune {
		r = ToLower(rune)
	}
	return r
}

// caseOrbit is defined in tables.go as []foldPair.  Right now all the
// entries fit in uint16, so use uint16.  If that changes, compilation
// will fail (the constants in the composite literal will not fit in uint16)
// and the types here can change to uint32.
type foldPair struct {
	From uint16
	To   uint16
}

// SimpleFold iterates over Unicode code points equivalent under
// the Unicode-defined simple case folding.  Among the code points
// equivalent to rune (including rune itself), SimpleFold returns the
// smallest r >= rune if one exists, or else the smallest r >= 0.
//
// For example:
//	SimpleFold('A') = 'a'
//	SimpleFold('a') = 'A'
//
//	SimpleFold('K') = 'k'
//	SimpleFold('k') = '\u212A' (Kelvin symbol, K)
//	SimpleFold('\u212A') = 'K'
//
//	SimpleFold('1') = '1'
//
func SimpleFold(rune int) int {
	// Consult caseOrbit table for special cases.
	lo := 0
	hi := len(caseOrbit)
	for lo < hi {
		m := lo + (hi-lo)/2
		if int(caseOrbit[m].From) < rune {
			lo = m + 1
		} else {
			hi = m
		}
	}
	if lo < len(caseOrbit) && int(caseOrbit[lo].From) == rune {
		return int(caseOrbit[lo].To)
	}

	// No folding specified.  This is a one- or two-element
	// equivalence class containing rune and ToLower(rune)
	// and ToUpper(rune) if they are different from rune.
	if l := ToLower(rune); l != rune {
		return l
	}
	return ToUpper(rune)
}
<|endoftext|>


<commit_before>package qshell

import (
	"bufio"
	"fmt"
	"github.com/astaxie/beego/logs"
	"io"
	"os"
	"qiniu/api.v6/auth/digest"
	"qiniu/api.v6/rsf"
	"qiniu/rpc"
)

/*
*@param bucket
*@param prefix
*@param marker
*@param listResultFile
*@return listError
 */
func ListBucket(mac *digest.Mac, bucket, prefix, marker, listResultFile string) (retErr error) {
	var listResultFh *os.File
	if listResultFile == "stdout" {
		listResultFh = os.Stdout
	} else {
		var openErr error
		//if marker not empty, continue the list
		if marker != "" {
			listResultFh, openErr = os.OpenFile(listResultFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
			if openErr != nil {
				retErr = openErr
				logs.Error("Failed to open list result file `%s`", listResultFile)
				return
			}
		} else {
			listResultFh, openErr = os.Create(listResultFile)
			if openErr != nil {
				retErr = openErr
				logs.Error("Failed to open list result file `%s`", listResultFile)
				return
			}
		}
	}
	defer listResultFh.Close()
	bWriter := bufio.NewWriter(listResultFh)

	//init
	client := rsf.New(mac)
	limit := 1000
	run := true
	maxRetryTimes := 5
	retryTimes := 1

	//start to list
	for run {
		entries, markerOut, listErr := client.ListPrefix(nil, bucket, prefix, marker, limit)
		if listErr != nil {
			if listErr == io.EOF {
				run = false
			} else {
				if v, ok := listErr.(*rpc.ErrorInfo); ok {
					logs.Error("List error for marker `%s`, %s", marker, v.Err)
				} else {
					logs.Error("List error for marker `%s`, %s", marker, listErr)
				}
				if retryTimes <= maxRetryTimes {
					logs.Warning("Retry list for marker `%s` for %d times", marker, retryTimes)
					retryTimes += 1
					continue
				} else {
					logs.Error("List failed too many times for marker `%s`", marker)
					break
				}
			}
		} else {
			retryTimes = 1
			if markerOut == "" {
				run = false
			} else {
				marker = markerOut
			}
		}

		//append entries
		for _, entry := range entries {
			lineData := fmt.Sprintf("%s\t%d\t%s\t%d\t%s\t%d\t%s\r\n",
				entry.Key, entry.Fsize, entry.Hash, entry.PutTime, entry.MimeType, entry.FileType, entry.EndUser)
			_, wErr := bWriter.WriteString(lineData)
			if wErr != nil {
				logs.Error("Write line data `%s` to list result file failed.", lineData)
			}
		}

		//flush
		fErr := bWriter.Flush()
		if fErr != nil {
			logs.Error("Flush data to list result file error", listErr)
		}
	}

	return
}
<commit_msg>set list limit to 1 when list failed<commit_after>package qshell

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"qiniu/rpc"

	"github.com/astaxie/beego/logs"
	"qiniu/api.v6/auth/digest"
	"qiniu/api.v6/rsf"
)

/*
*@param bucket
*@param prefix
*@param marker
*@param listResultFile
*@return listError
 */
func ListBucket(mac *digest.Mac, bucket, prefix, marker, listResultFile string) (retErr error) {
	var listResultFh *os.File
	if listResultFile == "stdout" {
		listResultFh = os.Stdout
	} else {
		var openErr error
		//if marker not empty, continue the list
		if marker != "" {
			listResultFh, openErr = os.OpenFile(listResultFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
			if openErr != nil {
				retErr = openErr
				logs.Error("Failed to open list result file `%s`", listResultFile)
				return
			}
		} else {
			listResultFh, openErr = os.Create(listResultFile)
			if openErr != nil {
				retErr = openErr
				logs.Error("Failed to open list result file `%s`", listResultFile)
				return
			}
		}
	}
	defer listResultFh.Close()
	bWriter := bufio.NewWriter(listResultFh)

	//init
	client := rsf.New(mac)
	limit := 1000
	run := true
	maxRetryTimes := 5
	retryTimes := 1

	//start to list
	for run {
		entries, markerOut, listErr := client.ListPrefix(nil, bucket, prefix, marker, limit)
		limit = 1000
		if listErr != nil {
			limit = 1
			if listErr == io.EOF {
				run = false
			} else {
				if v, ok := listErr.(*rpc.ErrorInfo); ok {
					logs.Error("List error for marker `%s`, %s", marker, v.Err)
				} else {
					logs.Error("List error for marker `%s`, %s", marker, listErr)
				}
				if retryTimes <= maxRetryTimes {
					logs.Warning("Retry list for marker `%s` for %d times", marker, retryTimes)
					retryTimes += 1
					continue
				} else {
					logs.Error("List failed too many times for marker `%s`", marker)
					break
				}
			}
		} else {
			retryTimes = 1
			if markerOut == "" {
				run = false
			} else {
				marker = markerOut
			}
		}

		//append entries
		for _, entry := range entries {
			lineData := fmt.Sprintf("%s\t%d\t%s\t%d\t%s\t%d\t%s\r\n",
				entry.Key, entry.Fsize, entry.Hash, entry.PutTime, entry.MimeType, entry.FileType, entry.EndUser)
			_, wErr := bWriter.WriteString(lineData)
			if wErr != nil {
				logs.Error("Write line data `%s` to list result file failed.", lineData)
			}
		}

		//flush
		fErr := bWriter.Flush()
		if fErr != nil {
			logs.Error("Flush data to list result file error", listErr)
		}
	}

	return
}
<|endoftext|>


<commit_before>package database

import (
	"log"

	"github.com/jfrazelle/udict/api"
	"github.com/paultag/go-dictd/dictd"
)

/*
 *
 */
type UrbanDictionaryDatabase struct {
	dictd.Database
}

/*
 *
 */
func (this *UrbanDictionaryDatabase) Match(name string, query string, strat string) []*dictd.Definition {
	return []*dictd.Definition{}
}

/*
 *
 */
func (this *UrbanDictionaryDatabase) Define(name string, query string) (definitions []*dictd.Definition) {
	response, err := api.DefineWord(query)
	if err != nil {
		log.Printf("Error getting from UD: %s", err)
	}

	for _, el := range response.Results {
		definitions = append(definitions, &dictd.Definition{
			Word:             el.Word,
			Definition:       el.Definition,
			DictDatabase:     this,
			DictDatabaseName: name,
		})
		log.Printf("%s\n", el.Word)
	}
	return
}

/*
 *
 */
func (this *UrbanDictionaryDatabase) Info(name string) string {
	return "Look up words on http://www.urbandictionary.com/"
}

/*
 *
 */
func (this *UrbanDictionaryDatabase) Description(name string) string {
	return "Urban Dictonary"
}
<commit_msg>return<commit_after>package database

import (
	"log"

	"github.com/jfrazelle/udict/api"
	"github.com/paultag/go-dictd/dictd"
)

/*
 *
 */
type UrbanDictionaryDatabase struct {
	dictd.Database
}

/*
 *
 */
func (this *UrbanDictionaryDatabase) Match(name string, query string, strat string) []*dictd.Definition {
	return []*dictd.Definition{}
}

/*
 *
 */
func (this *UrbanDictionaryDatabase) Define(name string, query string) (definitions []*dictd.Definition) {
	response, err := api.DefineWord(query)
	if err != nil {
		log.Printf("Error getting from UD: %s", err)
		return
	}

	for _, el := range response.Results {
		definitions = append(definitions, &dictd.Definition{
			Word:             el.Word,
			Definition:       el.Definition,
			DictDatabase:     this,
			DictDatabaseName: name,
		})
		log.Printf("%s\n", el.Word)
	}
	return
}

/*
 *
 */
func (this *UrbanDictionaryDatabase) Info(name string) string {
	return "Look up words on http://www.urbandictionary.com/"
}

/*
 *
 */
func (this *UrbanDictionaryDatabase) Description(name string) string {
	return "Urban Dictonary"
}
<|endoftext|>


<commit_before>// +build e2e

/*
Copyright 2021 The Knative 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 autotls

import (
	"context"
	"testing"

	"github.com/kelseyhightower/envconfig"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"knative.dev/networking/test/conformance/ingress"
	duckv1 "knative.dev/pkg/apis/duck/v1"
	"knative.dev/pkg/reconciler"
	v1 "knative.dev/serving/pkg/apis/serving/v1"
	"knative.dev/serving/pkg/apis/serving/v1alpha1"
	"knative.dev/serving/test"
	"knative.dev/serving/test/e2e"
	v1test "knative.dev/serving/test/v1"
)

type dmConfig struct {
	// TLSServiceName is the name of testing Knative Service.
	// It is not required for self-signed CA or for the HTTP01 challenge when wildcard domain
	// is mapped to the Ingress IP.
	TLSServiceName string `envconfig:"tls_service_name" required:"false"`
	// TLSTestNamespace is the namespace of where the tls tests run.
	TLSTestNamespace string `envconfig:"tls_test_namespace" required:"false"`
	// CustomDomainSuffix is the custom domain used for the domainMapping.
	CustomDomainSuffix string `envconfig:"custom_domain_suffix" required:"false"`
}

func TestDomainMappingAutoTLS(t *testing.T) {
	if !test.ServingFlags.EnableAlphaFeatures {
		t.Skip("Alpha features not enabled")
	}
	t.Parallel()

	var env dmConfig
	if err := envconfig.Process("", &env); err != nil {
		t.Fatalf("Failed to process environment variable: %v", err)
	}

	ctx := context.Background()

	clients := e2e.SetupWithNamespace(t, test.TLSNamespace)

	names := test.ResourceNames{
		Service: test.ObjectNameForTest(t),
		Image:   "runtime",
	}

	if len(env.TLSServiceName) != 0 {
		names.Service = env.TLSServiceName + "-dmtls"
	}

	// Clean up on test failure or interrupt.
	test.EnsureTearDown(t, clients, &names)

	// Set up initial Service.
	svc, err := v1test.CreateServiceReady(t, clients, &names,
		func(service *v1.Service) {
			service.Annotations = map[string]string{"networking.knative.dev/disableAutoTLS": "True"}
		})
	if err != nil {
		t.Fatalf("Failed to create initial Service %q: %v", names.Service, err)
	}

	// Using fixed hostnames can lead to conflicts when multiple tests run at
	// once, so include the svc name to avoid collisions.
	suffix := "example.com"

	if env.CustomDomainSuffix != "" {
		suffix = env.CustomDomainSuffix
	}

	if env.TLSTestNamespace != "" {
		suffix = env.TLSTestNamespace + "." + suffix
	}

	host := "dm." + suffix

	// Point DomainMapping at our service.
	var dm *v1alpha1.DomainMapping
	if err := reconciler.RetryTestErrors(func(int) error {
		dm, err = clients.ServingAlphaClient.DomainMappings.Create(ctx, &v1alpha1.DomainMapping{
			ObjectMeta: metav1.ObjectMeta{
				Name:      host,
				Namespace: svc.Service.Namespace,
			},
			Spec: v1alpha1.DomainMappingSpec{
				Ref: duckv1.KReference{
					Namespace:  svc.Service.Namespace,
					Name:       svc.Service.Name,
					APIVersion: "serving.knative.dev/v1",
					Kind:       "Service",
				},
			},
		}, metav1.CreateOptions{})
		return err
	}); err != nil {
		t.Fatalf("Create(DomainMapping) = %v, expected no error", err)
	}

	t.Cleanup(func() {
		clients.ServingAlphaClient.DomainMappings.Delete(ctx, dm.Name, metav1.DeleteOptions{})
	})

	// Wait for DomainMapping to go Ready.
	if waitErr := wait.PollImmediate(test.PollInterval, test.PollTimeout, func() (bool, error) {
		state, err := clients.ServingAlphaClient.DomainMappings.Get(ctx, dm.Name, metav1.GetOptions{})

		// DomainMapping can go Ready if only http is available.
		// Hence the checking for the URL scheme to make sure it is ready for https
		dmTLSReady := state.IsReady() && state.Status.URL != nil && state.Status.URL.Scheme == "https"

		return dmTLSReady, err
	}); waitErr != nil {
		t.Fatalf("The DomainMapping %q was not marked as Ready: %v", dm.Name, waitErr)
	}

	certName := dm.Name
	rootCAs := createRootCAs(t, clients, svc.Route.Namespace, certName)
	httpsClient := createHTTPSClient(t, clients, svc, rootCAs)
	ingress.RuntimeRequest(ctx, t, httpsClient, "https://"+host)
}
<commit_msg>Use NetworkingFlags to enable alpha feature in autotls (#11377)<commit_after>// +build e2e

/*
Copyright 2021 The Knative 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 autotls

import (
	"context"
	"testing"

	"github.com/kelseyhightower/envconfig"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	ntest "knative.dev/networking/test"
	"knative.dev/networking/test/conformance/ingress"
	duckv1 "knative.dev/pkg/apis/duck/v1"
	"knative.dev/pkg/reconciler"
	v1 "knative.dev/serving/pkg/apis/serving/v1"
	"knative.dev/serving/pkg/apis/serving/v1alpha1"
	"knative.dev/serving/test"
	"knative.dev/serving/test/e2e"
	v1test "knative.dev/serving/test/v1"
)

type dmConfig struct {
	// TLSServiceName is the name of testing Knative Service.
	// It is not required for self-signed CA or for the HTTP01 challenge when wildcard domain
	// is mapped to the Ingress IP.
	TLSServiceName string `envconfig:"tls_service_name" required:"false"`
	// TLSTestNamespace is the namespace of where the tls tests run.
	TLSTestNamespace string `envconfig:"tls_test_namespace" required:"false"`
	// CustomDomainSuffix is the custom domain used for the domainMapping.
	CustomDomainSuffix string `envconfig:"custom_domain_suffix" required:"false"`
}

func TestDomainMappingAutoTLS(t *testing.T) {
	if !ntest.NetworkingFlags.EnableAlphaFeatures {
		t.Skip("Alpha features not enabled")
	}
	t.Parallel()

	var env dmConfig
	if err := envconfig.Process("", &env); err != nil {
		t.Fatalf("Failed to process environment variable: %v", err)
	}

	ctx := context.Background()

	clients := e2e.SetupWithNamespace(t, test.TLSNamespace)

	names := test.ResourceNames{
		Service: test.ObjectNameForTest(t),
		Image:   "runtime",
	}

	if len(env.TLSServiceName) != 0 {
		names.Service = env.TLSServiceName + "-dmtls"
	}

	// Clean up on test failure or interrupt.
	test.EnsureTearDown(t, clients, &names)

	// Set up initial Service.
	svc, err := v1test.CreateServiceReady(t, clients, &names,
		func(service *v1.Service) {
			service.Annotations = map[string]string{"networking.knative.dev/disableAutoTLS": "True"}
		})
	if err != nil {
		t.Fatalf("Failed to create initial Service %q: %v", names.Service, err)
	}

	// Using fixed hostnames can lead to conflicts when multiple tests run at
	// once, so include the svc name to avoid collisions.
	suffix := "example.com"

	if env.CustomDomainSuffix != "" {
		suffix = env.CustomDomainSuffix
	}

	if env.TLSTestNamespace != "" {
		suffix = env.TLSTestNamespace + "." + suffix
	}

	host := "dm." + suffix

	// Point DomainMapping at our service.
	var dm *v1alpha1.DomainMapping
	if err := reconciler.RetryTestErrors(func(int) error {
		dm, err = clients.ServingAlphaClient.DomainMappings.Create(ctx, &v1alpha1.DomainMapping{
			ObjectMeta: metav1.ObjectMeta{
				Name:      host,
				Namespace: svc.Service.Namespace,
			},
			Spec: v1alpha1.DomainMappingSpec{
				Ref: duckv1.KReference{
					Namespace:  svc.Service.Namespace,
					Name:       svc.Service.Name,
					APIVersion: "serving.knative.dev/v1",
					Kind:       "Service",
				},
			},
		}, metav1.CreateOptions{})
		return err
	}); err != nil {
		t.Fatalf("Create(DomainMapping) = %v, expected no error", err)
	}

	t.Cleanup(func() {
		clients.ServingAlphaClient.DomainMappings.Delete(ctx, dm.Name, metav1.DeleteOptions{})
	})

	// Wait for DomainMapping to go Ready.
	if waitErr := wait.PollImmediate(test.PollInterval, test.PollTimeout, func() (bool, error) {
		state, err := clients.ServingAlphaClient.DomainMappings.Get(ctx, dm.Name, metav1.GetOptions{})

		// DomainMapping can go Ready if only http is available.
		// Hence the checking for the URL scheme to make sure it is ready for https
		dmTLSReady := state.IsReady() && state.Status.URL != nil && state.Status.URL.Scheme == "https"

		return dmTLSReady, err
	}); waitErr != nil {
		t.Fatalf("The DomainMapping %q was not marked as Ready: %v", dm.Name, waitErr)
	}

	certName := dm.Name
	rootCAs := createRootCAs(t, clients, svc.Route.Namespace, certName)
	httpsClient := createHTTPSClient(t, clients, svc, rootCAs)
	ingress.RuntimeRequest(ctx, t, httpsClient, "https://"+host)
}
<|endoftext|>


<commit_before>// +build darwin

/*
 *    Copyright (C) 2014-2017 Christian Muehlhaeuser
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as published
 *    by the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Authors:
 *      Christian Muehlhaeuser <muesli@gmail.com>
 */

// Package notificationbee is a Bee that can trigger desktop notifications.
package notificationbee

import "github.com/deckarep/gosx-notifier"

// Run executes the Bee's event loop.
func (mod *NotificationBee) execAction(text string, urgency uint32) {
	note := gosxnotifier.NewNotification(text)
	note.Subtitle = "this is subtitle"
	note.Push()
}
<commit_msg>fixed notification details<commit_after>// +build darwin

/*
 *    Copyright (C) 2014-2017 Christian Muehlhaeuser
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as published
 *    by the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Authors:
 *      Christian Muehlhaeuser <muesli@gmail.com>
 */

// Package notificationbee is a Bee that can trigger desktop notifications.
package notificationbee

import "github.com/deckarep/gosx-notifier"

// Run executes the Bee's event loop.
func (mod *NotificationBee) execAction(text string, urgency uint32) {
	note := gosxnotifier.NewNotification("Beehive")
	note.Title = text
	note.Push()
}
<|endoftext|>


<commit_before>package version

import (
	"bytes"
	"fmt"
)

// The git commit that was compiled. This will be filled in by the compiler.
var GitCommit string
var GitDescribe string

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

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

// VersionInfo
type VersionInfo struct {
	Revision          string
	Version           string
	VersionPrerelease string
}

func GetVersion() *VersionInfo {
	ver := Version
	rel := VersionPrerelease
	if GitDescribe != "" {
		ver = GitDescribe
	}
	if GitDescribe == "" && rel == "" && VersionPrerelease != "" {
		rel = "dev"
	}

	return &VersionInfo{
		Revision:          GitCommit,
		Version:           ver,
		VersionPrerelease: rel,
	}
}

func (c *VersionInfo) String() string {
	var versionString bytes.Buffer

	fmt.Fprintf(&versionString, "Vault v%s", c.Version)
	if c.VersionPrerelease != "" {
		fmt.Fprintf(&versionString, "-%s", c.VersionPrerelease)

		if c.Revision != "" {
			fmt.Fprintf(&versionString, " (%s)", c.Revision)
		}
	}

	return versionString.String()
}
<commit_msg>Bump version<commit_after>package version

import (
	"bytes"
	"fmt"
)

// The git commit that was compiled. This will be filled in by the compiler.
var GitCommit string
var GitDescribe string

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

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

// VersionInfo
type VersionInfo struct {
	Revision          string
	Version           string
	VersionPrerelease string
}

func GetVersion() *VersionInfo {
	ver := Version
	rel := VersionPrerelease
	if GitDescribe != "" {
		ver = GitDescribe
	}
	if GitDescribe == "" && rel == "" && VersionPrerelease != "" {
		rel = "dev"
	}

	return &VersionInfo{
		Revision:          GitCommit,
		Version:           ver,
		VersionPrerelease: rel,
	}
}

func (c *VersionInfo) String() string {
	var versionString bytes.Buffer

	fmt.Fprintf(&versionString, "Vault v%s", c.Version)
	if c.VersionPrerelease != "" {
		fmt.Fprintf(&versionString, "-%s", c.VersionPrerelease)

		if c.Revision != "" {
			fmt.Fprintf(&versionString, " (%s)", c.Revision)
		}
	}

	return versionString.String()
}
<|endoftext|>


<commit_before>// Copyright (c) 2013-2014 The btcsuite developers
// Copyright (c) 2015-2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package version

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

// semverAlphabet is an alphabet of all characters allowed in semver prerelease
// or build metadata identifiers, and the . separator.
const semverAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-."

// Constants defining the application version number.
const (
	Major = 1
	Minor = 4
	Patch = 0
)

// Integer is an integer encoding of the major.minor.patch version.
const Integer = 1000000*Major + 10000*Minor + 100*Patch

// PreRelease contains the prerelease name of the application.  It is a variable
// so it can be modified at link time (e.g.
// `-ldflags "-X github.com/decred/dcrwallet/version.PreRelease=rc1"`).
// It must only contain characters from the semantic version alphabet.
var PreRelease = "pre"

// BuildMetadata defines additional build metadata.  It is modified at link time
// for official releases.  It must only contain characters from the semantic
// version alphabet.
var BuildMetadata = "dev"

// String returns the application version as a properly formed string per the
// semantic versioning 2.0.0 spec (http://semver.org/).
func String() string {
	// Start with the major, minor, and path versions.
	version := fmt.Sprintf("%d.%d.%d", Major, Minor, Patch)

	// Append pre-release version if there is one.  The hyphen called for
	// by the semantic versioning spec is automatically appended and should
	// not be contained in the pre-release string.  The pre-release version
	// is not appended if it contains invalid characters.
	preRelease := normalizeVerString(PreRelease)
	if preRelease != "" {
		version = version + "-" + preRelease
	}

	// Append build metadata if there is any.  The plus called for
	// by the semantic versioning spec is automatically appended and should
	// not be contained in the build metadata string.  The build metadata
	// string is not appended if it contains invalid characters.
	buildMetadata := normalizeVerString(BuildMetadata)
	if buildMetadata != "" {
		version = version + "+" + buildMetadata
	}

	return version
}

// normalizeVerString returns the passed string stripped of all characters which
// are not valid according to the semantic versioning guidelines for pre-release
// version and build metadata strings.  In particular they MUST only contain
// characters in semanticAlphabet.
func normalizeVerString(str string) string {
	var buf bytes.Buffer
	for _, r := range str {
		if strings.ContainsRune(semverAlphabet, r) {
			_, err := buf.WriteRune(r)
			// Writing to a bytes.Buffer panics on OOM, and all
			// errors are unexpected.
			if err != nil {
				panic(err)
			}
		}
	}
	return buf.String()
}
<commit_msg>Bump version for 1.5 release cycle.<commit_after>// Copyright (c) 2013-2014 The btcsuite developers
// Copyright (c) 2015-2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package version

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

// semverAlphabet is an alphabet of all characters allowed in semver prerelease
// or build metadata identifiers, and the . separator.
const semverAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-."

// Constants defining the application version number.
const (
	Major = 1
	Minor = 5
	Patch = 0
)

// Integer is an integer encoding of the major.minor.patch version.
const Integer = 1000000*Major + 10000*Minor + 100*Patch

// PreRelease contains the prerelease name of the application.  It is a variable
// so it can be modified at link time (e.g.
// `-ldflags "-X github.com/decred/dcrwallet/version.PreRelease=rc1"`).
// It must only contain characters from the semantic version alphabet.
var PreRelease = "pre"

// BuildMetadata defines additional build metadata.  It is modified at link time
// for official releases.  It must only contain characters from the semantic
// version alphabet.
var BuildMetadata = "dev"

// String returns the application version as a properly formed string per the
// semantic versioning 2.0.0 spec (http://semver.org/).
func String() string {
	// Start with the major, minor, and path versions.
	version := fmt.Sprintf("%d.%d.%d", Major, Minor, Patch)

	// Append pre-release version if there is one.  The hyphen called for
	// by the semantic versioning spec is automatically appended and should
	// not be contained in the pre-release string.  The pre-release version
	// is not appended if it contains invalid characters.
	preRelease := normalizeVerString(PreRelease)
	if preRelease != "" {
		version = version + "-" + preRelease
	}

	// Append build metadata if there is any.  The plus called for
	// by the semantic versioning spec is automatically appended and should
	// not be contained in the build metadata string.  The build metadata
	// string is not appended if it contains invalid characters.
	buildMetadata := normalizeVerString(BuildMetadata)
	if buildMetadata != "" {
		version = version + "+" + buildMetadata
	}

	return version
}

// normalizeVerString returns the passed string stripped of all characters which
// are not valid according to the semantic versioning guidelines for pre-release
// version and build metadata strings.  In particular they MUST only contain
// characters in semanticAlphabet.
func normalizeVerString(str string) string {
	var buf bytes.Buffer
	for _, r := range str {
		if strings.ContainsRune(semverAlphabet, r) {
			_, err := buf.WriteRune(r)
			// Writing to a bytes.Buffer panics on OOM, and all
			// errors are unexpected.
			if err != nil {
				panic(err)
			}
		}
	}
	return buf.String()
}
<|endoftext|>


<commit_before>// The version package provides a location to set the release versions for all
// packages to consume, without creating import cycles.
//
// This package should not import any other terraform packages.
package version

import (
	"fmt"

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

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

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

// SemVer is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVer *version.Version

func init() {
	SemVer = version.Must(version.NewVersion(Version))
}

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

// String returns the complete version string, including prerelease
func String() string {
	if Prerelease != "" {
		return fmt.Sprintf("%s-%s", Version, Prerelease)
	}
	return Version
}
<commit_msg>release: clean up after v0.12.0-beta1<commit_after>// The version package provides a location to set the release versions for all
// packages to consume, without creating import cycles.
//
// This package should not import any other terraform packages.
package version

import (
	"fmt"

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

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

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

// SemVer is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVer *version.Version

func init() {
	SemVer = version.Must(version.NewVersion(Version))
}

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

// String returns the complete version string, including prerelease
func String() string {
	if Prerelease != "" {
		return fmt.Sprintf("%s-%s", Version, Prerelease)
	}
	return Version
}
<|endoftext|>


<commit_before>// 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 version

import (
	"fmt"
	"os"
	"runtime"

	log "github.com/golang/glog"
)

var (
	Version = "0.3.0+git"
	GitSHA  = "Not provided."
)

// PrintVersion print version info
func PrintVersion(printVersion bool) {
	if printVersion {
		fmt.Println("tf_operator Version:", Version)
		fmt.Println("Git SHA:", GitSHA)
		fmt.Println("Go Version:", runtime.Version())
		fmt.Printf("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
		os.Exit(0)
	}

	log.Infof("tf_operator Version: %v", Version)
	log.Infof("Git SHA: %s", GitSHA)
	log.Infof("Go Version: %s", runtime.Version())
	log.Infof("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH)
}
<commit_msg>fix(no-dup): reduce dup code in printVersion (#253)<commit_after>// 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 version

import (
	"os"
	"runtime"

	log "github.com/golang/glog"
)

var (
	Version = "0.3.0+git"
	GitSHA  = "Not provided."
)

// PrintVersion print version info
func PrintVersion(shouldExit bool) {
	log.Infof("tf_operator Version: %v", Version)
	log.Infof("Git SHA: %s", GitSHA)
	log.Infof("Go Version: %s", runtime.Version())
	log.Infof("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH)
	if shouldExit {
		os.Exit(0)
	}
}
<|endoftext|>


<commit_before>// Package version returns the version of the application(s)
package version

const (
	version = "0.7.6"
)

// Version returns the current application version
func Version() string {
	return version
}
<commit_msg>bump version to 0.7.7<commit_after>// Package version returns the version of the application(s)
package version

const (
	version = "0.7.7"
)

// Version returns the current application version
func Version() string {
	return version
}
<|endoftext|>


<commit_before>package version

// Version is the version of the build.
const Version = "0.1.28"
<commit_msg>version: bump to v0.1.29-dev<commit_after>package version

// Version is the version of the build.
const Version = "0.1.29-dev"
<|endoftext|>