<commit_before>package main

import (
	"os"
	//"context"

	//"github.com/docker/docker/client"
	log "github.com/Sirupsen/logrus"
	"github.com/opalmer/gerrittest"
	"github.com/spf13/cobra"
)

var (
	// Command represents the base command when called without
	// any subcommands
	Command = &cobra.Command{
		Use: "gerrittest",
		Short: "A command line tool for running Gerrit in docker " +
			"for testing."}

	// ShowCommand shows information about running containers
	ShowCommand = &cobra.Command{
		Use:   "show",
		Short: "Shows information about running containers",
		RunE: func(cmd *cobra.Command, args []string) error {
			client, err := setup(cmd)
			if err != nil {
				return err
			}

			containers, err := client.Containers()
			if err != nil {
				return err
			}

			for _, container := range containers {

				entry := log.WithFields(log.Fields{
					"id":   container.ID,
					"http": container.HTTP,
					"ssh":  container.SSH,
				})

				entry.Info()
			}

			return nil
		}}
)

func setup(cmd *cobra.Command) (*gerrittest.DockerClient, error) {
	if cmd.Flag("log-level").Changed {
		resolved, err := log.ParseLevel(cmd.Flag("log-level").Value.String())
		if err != nil {
			return nil, err
		}
		log.SetLevel(resolved)
	}

	client, err := gerrittest.NewDockerClient()
	return client, err
}

func init() {
	persistent := Command.PersistentFlags()
	persistent.String(
		"image", "opalmer/gerrittest:latest",
		"The name of the image that should be run.")
	persistent.String(
		"log-level", "", "Override the default log level.")
	Command.AddCommand(ShowCommand)
}

func main() {
	if err := Command.Execute(); err != nil {
		log.WithError(err).Error()
		os.Exit(1)
	}
}
<commit_msg>adding initial run command<commit_after>package main

import (
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/opalmer/gerrittest"
	"github.com/spf13/cobra"
)

var (
	// Command represents the base command when called without
	// any subcommands
	Command = &cobra.Command{
		Use: "gerrittest",
		Short: "A command line tool for running Gerrit in docker " +
			"for testing."}

	// ShowCommand shows information about running containers
	ShowCommand = &cobra.Command{
		Use:   "show",
		Short: "Shows information about running containers",
		RunE: func(cmd *cobra.Command, args []string) error {
			client, err := newdockerclient(cmd)
			if err != nil {
				return err
			}

			containers, err := client.Containers()
			if err != nil {
				return err
			}

			for _, container := range containers {
				entry := log.WithFields(log.Fields{
					"id":   container.ID,
					"http": container.HTTP,
					"ssh":  container.SSH,
				})

				entry.Info()
			}

			return nil
		}}

	// RunCommand is the command used to run a container
	RunCommand = &cobra.Command{
		Use:   "run",
		Short: "Runs Gerrit in a docker container and returns information about it",
		RunE: func(cmd *cobra.Command, args []string) error {
			client, err := newdockerclient(cmd)
			if err != nil {
				return err
			}
			created, err := client.RunGerrit(nil)
			if err != nil {
				return err
			}
			log.Info(created.ID)
			return nil
		}}
)

func newdockerclient(cmd *cobra.Command) (*gerrittest.DockerClient, error) {
	if cmd.Flag("log-level").Changed {
		resolved, err := log.ParseLevel(cmd.Flag("log-level").Value.String())
		if err != nil {
			return nil, err
		}
		log.SetLevel(resolved)
	}

	image := "opalmer/gerrittest:latest"
	if cmd.Flag("image").Changed {
		image = cmd.Flag("image").Value.String()
	}

	client, err := gerrittest.NewDockerClient(image)
	return client, err
}

func init() {
	persistent := Command.PersistentFlags()
	persistent.String(
		"image", "opalmer/gerrittest:latest",
		"The name of the image that should be run.")
	persistent.String(
		"log-level", "", "Override the default log level.")

	// Add commands
	Command.AddCommand(ShowCommand)
	Command.AddCommand(RunCommand)
}

func main() {
	if err := Command.Execute(); err != nil {
		log.WithError(err).Error()
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"time"

	"github.com/toomore/gogrs/twse"
	"github.com/toomore/gogrs/utils"
)

var stock = &twse.DailyData{
	No:   "2329",
	Date: time.Date(2015, 3, 20, 0, 0, 0, 0, time.Local),
}

func ShowAll(stock *twse.DailyData) {
	fmt.Println(stock.RawData)
	fmt.Println(stock.MA(6))
	fmt.Println(stock.MAV(6))
	fmt.Println(stock.GetPriceList())
	fmt.Println(utils.ThanPastFloat64(stock.GetPriceList(), 3, true))
	fmt.Println(utils.ThanPastFloat64(stock.GetPriceList(), 3, false))
	fmt.Println(stock.GetVolumeList())
	fmt.Println(utils.ThanPastUint64(stock.GetVolumeList(), 3, true))
	fmt.Println(utils.ThanPastUint64(stock.GetVolumeList(), 3, false))
	fmt.Println(stock.GetRangeList())
	fmt.Println(stock.IsRed())
}

func main() {
	stock.GetData()
	ShowAll(stock)
	fmt.Println("-----------------------------")
	stock.PlusData()
	ShowAll(stock)
}
<commit_msg>Fixed main.<commit_after>package main

import (
	"fmt"
	"time"

	"github.com/toomore/gogrs/twse"
	"github.com/toomore/gogrs/utils"
)

var stock = &twse.DailyData{
	No:   "2329",
	Date: time.Date(2015, 3, 20, 0, 0, 0, 0, time.Local),
}

// ShowAll is lazy to show all XD.
func ShowAll(stock *twse.DailyData) {
	fmt.Println(stock.RawData)
	fmt.Println(stock.MA(6))
	fmt.Println(stock.MAV(6))
	fmt.Println(stock.GetPriceList())
	fmt.Println(utils.ThanPastFloat64(stock.GetPriceList(), 3, true))
	fmt.Println(utils.ThanPastFloat64(stock.GetPriceList(), 3, false))
	fmt.Println(stock.GetVolumeList())
	fmt.Println(utils.ThanPastUint64(stock.GetVolumeList(), 3, true))
	fmt.Println(utils.ThanPastUint64(stock.GetVolumeList(), 3, false))
	fmt.Println(stock.GetRangeList())
	fmt.Println(stock.IsRed())
}

func main() {
	stock.Get()
	ShowAll(stock)
	fmt.Println("-----------------------------")
	stock.PlusData()
	ShowAll(stock)
}
<|endoftext|>


<commit_before>package cmd

import (
	"bytes"
	"fmt"
	"os/exec"
	"runtime"

	"github.com/spf13/cobra"
	"github.com/wallix/awless/database"
)

func init() {
	RootCmd.AddCommand(openCmd)
}

var openCmd = &cobra.Command{
	Use:   "open",
	Short: "Open your AWS console in your default browser",

	RunE: func(c *cobra.Command, args []string) error {
		console := fmt.Sprintf("https://%s.console.aws.amazon.com/console/home", database.MustGetDefaultRegion())

		var verb string
		switch runtime.GOOS {
		case "darwin":
			verb = "open"
		default:
			verb = "xdg-open"
		}

		var stderr bytes.Buffer
		cmd := exec.Command(verb, console)
		cmd.Stderr = &stderr
		if err := cmd.Run(); err != nil || stderr.String() != "" {
			return fmt.Errorf("%s:%s", err, stderr.String())
		}
		return nil
	},
}
<commit_msg>Remove unneeded open command<commit_after><|endoftext|>


<commit_before>package cmd

import (
	"errors"
	"fmt"
	"os"

	"github.com/apex/log"
	"github.com/apex/log/handlers/cli"
	"github.com/fatih/color"
	"github.com/spf13/cobra"
)

func Execute(version string, exit func(int), args []string) {
	// enable colored output on travis
	if os.Getenv("CI") != "" {
		color.NoColor = false
	}

	log.SetHandler(cli.Default)

	fmt.Println()
	defer fmt.Println()
	newRootCmd(version, exit).Execute(args)
}

func (cmd *rootCmd) Execute(args []string) {
	cmd.cmd.SetArgs(args)

	if shouldPrependRelease(cmd.cmd, args) {
		cmd.cmd.SetArgs(append([]string{"release"}, args...))
	}

	if err := cmd.cmd.Execute(); err != nil {
		var code = 1
		var msg = "command failed"
		var eerr = &exitError{}
		if errors.As(err, &eerr) {
			code = eerr.code
			if eerr.details != "" {
				msg = eerr.details
			}
		}
		log.WithError(err).Error(msg)
		cmd.exit(code)
	}
}

type rootCmd struct {
	cmd   *cobra.Command
	debug bool
	exit  func(int)
}

func newRootCmd(version string, exit func(int)) *rootCmd {
	var root = &rootCmd{
		exit: exit,
	}
	var cmd = &cobra.Command{
		Use:           "goreleaser",
		Short:         "Deliver Go binaries as fast and easily as possible",
		Version:       version,
		SilenceUsage:  true,
		SilenceErrors: true,
		Args:          cobra.NoArgs,
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			if root.debug {
				log.SetLevel(log.DebugLevel)
				log.Debug("debug logs enabled")
			}
		},
	}

	cmd.PersistentFlags().BoolVar(&root.debug, "debug", false, "Enable debug mode")
	cmd.AddCommand(
		newBuildCmd().cmd,
		newReleaseCmd().cmd,
		newCheckCmd().cmd,
		newInitCmd().cmd,
		newCompletionCmd().cmd,
	)

	root.cmd = cmd
	return root
}

func shouldPrependRelease(cmd *cobra.Command, args []string) bool {
	// find current cmd, if its not root, it means the user actively
	// set a command, so let it go
	xmd, _, _ := cmd.Find(args)
	if xmd != cmd {
		return false
	}

	// allow help and __complete commands.
	if len(args) > 0 && (args[0] == "help" || args[0] == "__complete") {
		return false
	}

	// if we have != 1 args, assume its a release
	if len(args) != 1 {
		return true
	}

	// given that its 1, check if its one of the valid standalone flags
	// for the root cmd
	for _, s := range []string{"-h", "--help", "-v", "--version"} {
		if s == args[0] {
			// if it is, we should run the root cmd
			return false
		}
	}

	// otherwise, we should probably prepend release
	return true
}
<commit_msg>fix: completions on fish<commit_after>package cmd

import (
	"errors"
	"os"

	"github.com/apex/log"
	"github.com/apex/log/handlers/cli"
	"github.com/fatih/color"
	"github.com/spf13/cobra"
)

func Execute(version string, exit func(int), args []string) {
	// enable colored output on travis
	if os.Getenv("CI") != "" {
		color.NoColor = false
	}
	log.SetHandler(cli.Default)
	newRootCmd(version, exit).Execute(args)
}

func (cmd *rootCmd) Execute(args []string) {
	cmd.cmd.SetArgs(args)

	if shouldPrependRelease(cmd.cmd, args) {
		cmd.cmd.SetArgs(append([]string{"release"}, args...))
	}

	if err := cmd.cmd.Execute(); err != nil {
		var code = 1
		var msg = "command failed"
		var eerr = &exitError{}
		if errors.As(err, &eerr) {
			code = eerr.code
			if eerr.details != "" {
				msg = eerr.details
			}
		}
		log.WithError(err).Error(msg)
		cmd.exit(code)
	}
}

type rootCmd struct {
	cmd   *cobra.Command
	debug bool
	exit  func(int)
}

func newRootCmd(version string, exit func(int)) *rootCmd {
	var root = &rootCmd{
		exit: exit,
	}
	var cmd = &cobra.Command{
		Use:           "goreleaser",
		Short:         "Deliver Go binaries as fast and easily as possible",
		Version:       version,
		SilenceUsage:  true,
		SilenceErrors: true,
		Args:          cobra.NoArgs,
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			if root.debug {
				log.SetLevel(log.DebugLevel)
				log.Debug("debug logs enabled")
			}
		},
	}

	cmd.PersistentFlags().BoolVar(&root.debug, "debug", false, "Enable debug mode")
	cmd.AddCommand(
		newBuildCmd().cmd,
		newReleaseCmd().cmd,
		newCheckCmd().cmd,
		newInitCmd().cmd,
		newCompletionCmd().cmd,
	)

	root.cmd = cmd
	return root
}

func shouldPrependRelease(cmd *cobra.Command, args []string) bool {
	// find current cmd, if its not root, it means the user actively
	// set a command, so let it go
	xmd, _, _ := cmd.Find(args)
	if xmd != cmd {
		return false
	}

	// allow help and __complete commands.
	if len(args) > 0 && (args[0] == "help" || args[0] == "__complete") {
		return false
	}

	// if we have != 1 args, assume its a release
	if len(args) != 1 {
		return true
	}

	// given that its 1, check if its one of the valid standalone flags
	// for the root cmd
	for _, s := range []string{"-h", "--help", "-v", "--version"} {
		if s == args[0] {
			// if it is, we should run the root cmd
			return false
		}
	}

	// otherwise, we should probably prepend release
	return true
}
<|endoftext|>


<commit_before>// Copyright c 2017 tadaken3 <k.tanaka6057@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"fmt"
	"os"
	"runtime"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string
var message string
var token string
var version string

var RootCmd = &cobra.Command{
	Use:   "notify",
	Short: `This application can notify any chat serviece`,
	Long:  `This application is a simple CLI tool. You can quickly notify to any chat serviece`,
}

func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	RootCmd.PersistentFlags().StringVarP(&message, "message", "m", "This message is from notify", "message")
	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.notify.yaml)")
	RootCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "access token")
	RootCmd.AddCommand(versionCmd)
}

func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".notify")
	if runtime.GOOS == "windows" {
		viper.AddConfigPath(os.Getenv("HOMEPATH"))
	} else {
		viper.AddConfigPath(os.Getenv("HOME"))
	}

	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the version number of notify",
	Long:  `All software has versions. This is notify`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("notify version:" + version)
	},
}
<commit_msg>modify version<commit_after>// Copyright c 2017 tadaken3 <k.tanaka6057@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"fmt"
	"os"
	"runtime"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string
var message string
var token string

const version = "0.0.4"

var RootCmd = &cobra.Command{
	Use:   "notify",
	Short: `This application can notify any chat serviece`,
	Long:  `This application is a simple CLI tool. You can quickly notify to any chat serviece`,
}

func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	RootCmd.PersistentFlags().StringVarP(&message, "message", "m", "This message is from notify", "message")
	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.notify.yaml)")
	RootCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "access token")
	RootCmd.AddCommand(versionCmd)
}

func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".notify")
	if runtime.GOOS == "windows" {
		viper.AddConfigPath(os.Getenv("HOMEPATH"))
	} else {
		viper.AddConfigPath(os.Getenv("HOME"))
	}

	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the version number of notify",
	Long:  `All software has versions. This is notify`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("notify version:" + version)
	},
}
<|endoftext|>


<commit_before>package cmd

import (
	"github.com/spf13/cobra"
)

var (
	actionWebsite string

	rootCmd = &cobra.Command{
		Use:   "beaker",
		Short: "Beaker is a simple blog system.",
		Long: `Beaker is a CS architecture blog system,
you can manage your numerous beaker blogs through beaker.`,
	}
)

// Execute executes the root command.
func Execute() error {
	return rootCmd.Execute()
}

func init() {
	cobra.OnInitialize(initConfig)

	rootCmd.PersistentFlags().StringVarP(&actionWebsite, "website", "w", "default", "Set the blog you want to push, the blog can be set in the config command")
	rootCmd.PersistentFlags().BoolP("refresh", "r", true, "refresh server cache")

	rootCmd.AddCommand(addCmd)
	rootCmd.AddCommand(rmCmd)
	rootCmd.AddCommand(modifyCmd)
	rootCmd.AddCommand(cleanCmd)
	rootCmd.AddCommand(versionCmd)
	rootCmd.AddCommand(configCmd)
	rootCmd.AddCommand(lsCmd)
	rootCmd.AddCommand(lwCmd)
}
<commit_msg>chanag help content<commit_after>package cmd

import (
	"github.com/spf13/cobra"
)

var (
	actionWebsite string

	rootCmd = &cobra.Command{
		Use:   "beaker",
		Short: "Beaker is a simple blog system.",
		Long: `Beaker is a very fast, simple and
smart blog system. It is very suitable for geeks.
At the same time, Beaker advocates using markdown
to edit articles and manage your blog through the
terminal. It is completely open source, you can
add and modify functions at will, and its source
code can be accessed at https://github.com/mebiusashan/beaker.`,
	}
)

// Execute executes the root command.
func Execute() error {
	return rootCmd.Execute()
}

func init() {
	cobra.OnInitialize(initConfig)

	rootCmd.PersistentFlags().StringVarP(&actionWebsite, "website", "w", "default", "Set the blog you want to push, the blog can be set in the config command")
	rootCmd.PersistentFlags().BoolP("refresh", "r", true, "refresh server cache")

	rootCmd.AddCommand(addCmd)
	rootCmd.AddCommand(rmCmd)
	rootCmd.AddCommand(modifyCmd)
	rootCmd.AddCommand(cleanCmd)
	rootCmd.AddCommand(versionCmd)
	rootCmd.AddCommand(configCmd)
	rootCmd.AddCommand(lsCmd)
	rootCmd.AddCommand(lwCmd)
}
<|endoftext|>


<commit_before>// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
//
// 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 cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "go-logsink",
	Short: "go-logsink is a simplistic log aggregator",
	Long: `You can use go-logsink to combine multiple log streams
into one. For example you can combine multiple tails into one
output.

To do this start a server and connect any number of clients.

TODO: show sample`,
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	// Here you will define your flags and configuration settings.
	// Cobra supports Persistent Flags, which, if defined here,
	// will be global for your application.

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.go-logsink.yaml)")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".go-logsink") // name of config file (without extension)
	viper.AddConfigPath("$HOME")       // adding home directory as first search path
	viper.AutomaticEnv()               // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}
<commit_msg>Removed TODO hint<commit_after>// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
//
// 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 cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "go-logsink",
	Short: "go-logsink is a simplistic log aggregator",
	Long: `You can use go-logsink to combine multiple log streams
into one. For example you can combine multiple tails into one
output.

To do this start a server and connect any number of clients.`,
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	// Here you will define your flags and configuration settings.
	// Cobra supports Persistent Flags, which, if defined here,
	// will be global for your application.

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.go-logsink.yaml)")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".go-logsink") // name of config file (without extension)
	viper.AddConfigPath("$HOME")       // adding home directory as first search path
	viper.AutomaticEnv()               // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"strconv"

	"github.com/bjyoungblood/gozw/zwave"
	"github.com/bjyoungblood/gozw/zwave/commandclass"
	"github.com/peterh/liner"
)

func main() {

	transport, err := zwave.NewTransportLayer("/tmp/usbmodem", 115200)
	if err != nil {
		panic(err)
	}

	frameLayer := zwave.NewFrameLayer(transport)
	sessionLayer := zwave.NewSessionLayer(frameLayer)
	manager := zwave.NewManager(sessionLayer)

	defer manager.Close()

	fmt.Printf("Home ID: 0x%x; Node ID: %d\n", manager.HomeId, manager.NodeId)
	fmt.Println("API Version:", manager.ApiVersion)
	fmt.Println("Library:", manager.ApiLibraryType)
	fmt.Println("Version:", manager.Version)
	fmt.Println("API Type:", manager.ApiType)
	fmt.Println("Timer Functions Supported:", manager.TimerFunctionsSupported)
	fmt.Println("Is Primary Controller:", manager.IsPrimaryController)
	fmt.Println("Node count:", len(manager.Nodes))

	// manager.SetApplicationNodeInformation()
	// manager.FactoryReset()

	for _, node := range manager.Nodes {
		fmt.Println(node.String())
	}

	// manager.SendData(3, cc.NewSwitchMultilevelCommand(0))

	line := liner.NewLiner()
	defer line.Close()

	for {
		cmd, _ := line.Prompt("(a)dd node\n(r)emove node\n(g)et nonce\n(q)uit\n> ")
		switch cmd {
		case "a":
			manager.AddNode()
		case "r":
			manager.RemoveNode()
		case "s":
			input, _ := line.Prompt("node id: ")
			nodeId, _ := strconv.Atoi(input)
			manager.SendData(uint8(nodeId), commandclass.NewSecuritySchemeGet())
		case "g":
			input, _ := line.Prompt("node id: ")
			nodeId, _ := strconv.Atoi(input)
			manager.SendData(uint8(nodeId), commandclass.NewSecurityNonceGet())
		case "q":
			return
		default:
			fmt.Println("invalid selection")
		}
	}

}
<commit_msg>test version get command<commit_after>package main

import (
	"fmt"
	"strconv"

	"github.com/bjyoungblood/gozw/zwave"
	"github.com/bjyoungblood/gozw/zwave/commandclass"
	"github.com/peterh/liner"
)

func main() {

	transport, err := zwave.NewTransportLayer("/tmp/usbmodem", 115200)
	if err != nil {
		panic(err)
	}

	frameLayer := zwave.NewFrameLayer(transport)
	sessionLayer := zwave.NewSessionLayer(frameLayer)
	manager := zwave.NewManager(sessionLayer)

	defer manager.Close()

	fmt.Printf("Home ID: 0x%x; Node ID: %d\n", manager.HomeId, manager.NodeId)
	fmt.Println("API Version:", manager.ApiVersion)
	fmt.Println("Library:", manager.ApiLibraryType)
	fmt.Println("Version:", manager.Version)
	fmt.Println("API Type:", manager.ApiType)
	fmt.Println("Timer Functions Supported:", manager.TimerFunctionsSupported)
	fmt.Println("Is Primary Controller:", manager.IsPrimaryController)
	fmt.Println("Node count:", len(manager.Nodes))

	// manager.SetApplicationNodeInformation()
	// manager.FactoryReset()

	for _, node := range manager.Nodes {
		fmt.Println(node.String())
	}

	// manager.SendData(3, cc.NewSwitchMultilevelCommand(0))

	line := liner.NewLiner()
	defer line.Close()

	for {
		cmd, _ := line.Prompt("(a)dd node\n(r)emove node\n(g)et nonce\n(q)uit\n> ")
		switch cmd {
		case "a":
			manager.AddNode()
		case "r":
			manager.RemoveNode()
		case "s":
			input, _ := line.Prompt("node id: ")
			nodeId, _ := strconv.Atoi(input)
			manager.SendData(uint8(nodeId), commandclass.NewSecuritySchemeGet())
		case "g":
			input, _ := line.Prompt("node id: ")
			nodeId, _ := strconv.Atoi(input)
			manager.SendData(uint8(nodeId), commandclass.NewSecurityNonceGet())
		case "v":
			input, _ := line.Prompt("node id: ")
			nodeId, _ := strconv.Atoi(input)
			manager.SendData(uint8(nodeId), commandclass.NewVersionGet())
		case "q":
			return
		default:
			fmt.Println("invalid selection")
		}
	}

}
<|endoftext|>


<commit_before>// Copyright 2017, 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 cmp

import (
	"fmt"
	"reflect"
	"strings"
	"unicode"
	"unicode/utf8"

	"github.com/google/go-cmp/cmp/internal/value"
)

// Path is a list of PathSteps describing the sequence of operations to get
// from some root type to the current position in the value tree.
// The first Path element is always an operation-less PathStep that exists
// simply to identify the initial type.
//
// When traversing structs with embedded structs, the embedded struct will
// always be accessed as a field before traversing the fields of the
// embedded struct themselves. That is, an exported field from the
// embedded struct will never be accessed directly from the parent struct.
type Path []PathStep

// PathStep is a union-type for specific operations to traverse
// a value's tree structure. Users of this package never need to implement
// these types as values of this type will be returned by this package.
//
// Implementations of this interface are
// StructField, SliceIndex, MapIndex, Indirect, TypeAssertion, and Transform.
type PathStep interface {
	String() string

	// Type is the resulting type after performing the path step.
	Type() reflect.Type

	// Values is the resulting values after performing the path step.
	// The type of each valid value is guaranteed to be identical to Type.
	//
	// In some cases, one or both may be invalid or have restrictions:
	//	• For StructField, both are not interface-able if the current field
	//	is unexported and the struct type is not explicitly permitted by
	//	an Exporter to traverse unexported fields.
	//	• For SliceIndex, one may be invalid if an element is missing from
	//	either the x or y slice.
	//	• For MapIndex, one may be invalid if an entry is missing from
	//	either the x or y map.
	//
	// The provided values must not be mutated.
	Values() (vx, vy reflect.Value)
}

var (
	_ PathStep = StructField{}
	_ PathStep = SliceIndex{}
	_ PathStep = MapIndex{}
	_ PathStep = Indirect{}
	_ PathStep = TypeAssertion{}
	_ PathStep = Transform{}
)

func (pa *Path) push(s PathStep) {
	*pa = append(*pa, s)
}

func (pa *Path) pop() {
	*pa = (*pa)[:len(*pa)-1]
}

// Last returns the last PathStep in the Path.
// If the path is empty, this returns a non-nil PathStep that reports a nil Type.
func (pa Path) Last() PathStep {
	return pa.Index(-1)
}

// Index returns the ith step in the Path and supports negative indexing.
// A negative index starts counting from the tail of the Path such that -1
// refers to the last step, -2 refers to the second-to-last step, and so on.
// If index is invalid, this returns a non-nil PathStep that reports a nil Type.
func (pa Path) Index(i int) PathStep {
	if i < 0 {
		i = len(pa) + i
	}
	if i < 0 || i >= len(pa) {
		return pathStep{}
	}
	return pa[i]
}

// String returns the simplified path to a node.
// The simplified path only contains struct field accesses.
//
// For example:
//	MyMap.MySlices.MyField
func (pa Path) String() string {
	var ss []string
	for _, s := range pa {
		if _, ok := s.(StructField); ok {
			ss = append(ss, s.String())
		}
	}
	return strings.TrimPrefix(strings.Join(ss, ""), ".")
}

// GoString returns the path to a specific node using Go syntax.
//
// For example:
//	(*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField
func (pa Path) GoString() string {
	var ssPre, ssPost []string
	var numIndirect int
	for i, s := range pa {
		var nextStep PathStep
		if i+1 < len(pa) {
			nextStep = pa[i+1]
		}
		switch s := s.(type) {
		case Indirect:
			numIndirect++
			pPre, pPost := "(", ")"
			switch nextStep.(type) {
			case Indirect:
				continue // Next step is indirection, so let them batch up
			case StructField:
				numIndirect-- // Automatic indirection on struct fields
			case nil:
				pPre, pPost = "", "" // Last step; no need for parenthesis
			}
			if numIndirect > 0 {
				ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect))
				ssPost = append(ssPost, pPost)
			}
			numIndirect = 0
			continue
		case Transform:
			ssPre = append(ssPre, s.trans.name+"(")
			ssPost = append(ssPost, ")")
			continue
		}
		ssPost = append(ssPost, s.String())
	}
	for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 {
		ssPre[i], ssPre[j] = ssPre[j], ssPre[i]
	}
	return strings.Join(ssPre, "") + strings.Join(ssPost, "")
}

type pathStep struct {
	typ    reflect.Type
	vx, vy reflect.Value
}

func (ps pathStep) Type() reflect.Type             { return ps.typ }
func (ps pathStep) Values() (vx, vy reflect.Value) { return ps.vx, ps.vy }
func (ps pathStep) String() string {
	if ps.typ == nil {
		return "<nil>"
	}
	s := ps.typ.String()
	if s == "" || strings.ContainsAny(s, "{}\n") {
		return "root" // Type too simple or complex to print
	}
	return fmt.Sprintf("{%s}", s)
}

// StructField represents a struct field access on a field called Name.
type StructField struct{ *structField }
type structField struct {
	pathStep
	name string
	idx  int

	// These fields are used for forcibly accessing an unexported field.
	// pvx, pvy, and field are only valid if unexported is true.
	unexported bool
	mayForce   bool                // Forcibly allow visibility
	paddr      bool                // Was parent addressable?
	pvx, pvy   reflect.Value       // Parent values (always addressible)
	field      reflect.StructField // Field information
}

func (sf StructField) Type() reflect.Type { return sf.typ }
func (sf StructField) Values() (vx, vy reflect.Value) {
	if !sf.unexported {
		return sf.vx, sf.vy // CanInterface reports true
	}

	// Forcibly obtain read-write access to an unexported struct field.
	if sf.mayForce {
		vx = retrieveUnexportedField(sf.pvx, sf.field, sf.paddr)
		vy = retrieveUnexportedField(sf.pvy, sf.field, sf.paddr)
		return vx, vy // CanInterface reports true
	}
	return sf.vx, sf.vy // CanInterface reports false
}
func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) }

// Name is the field name.
func (sf StructField) Name() string { return sf.name }

// Index is the index of the field in the parent struct type.
// See reflect.Type.Field.
func (sf StructField) Index() int { return sf.idx }

// SliceIndex is an index operation on a slice or array at some index Key.
type SliceIndex struct{ *sliceIndex }
type sliceIndex struct {
	pathStep
	xkey, ykey int
	isSlice    bool // False for reflect.Array
}

func (si SliceIndex) Type() reflect.Type             { return si.typ }
func (si SliceIndex) Values() (vx, vy reflect.Value) { return si.vx, si.vy }
func (si SliceIndex) String() string {
	switch {
	case si.xkey == si.ykey:
		return fmt.Sprintf("[%d]", si.xkey)
	case si.ykey == -1:
		// [5->?] means "I don't know where X[5] went"
		return fmt.Sprintf("[%d->?]", si.xkey)
	case si.xkey == -1:
		// [?->3] means "I don't know where Y[3] came from"
		return fmt.Sprintf("[?->%d]", si.ykey)
	default:
		// [5->3] means "X[5] moved to Y[3]"
		return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey)
	}
}

// Key is the index key; it may return -1 if in a split state
func (si SliceIndex) Key() int {
	if si.xkey != si.ykey {
		return -1
	}
	return si.xkey
}

// SplitKeys are the indexes for indexing into slices in the
// x and y values, respectively. These indexes may differ due to the
// insertion or removal of an element in one of the slices, causing
// all of the indexes to be shifted. If an index is -1, then that
// indicates that the element does not exist in the associated slice.
//
// Key is guaranteed to return -1 if and only if the indexes returned
// by SplitKeys are not the same. SplitKeys will never return -1 for
// both indexes.
func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey }

// MapIndex is an index operation on a map at some index Key.
type MapIndex struct{ *mapIndex }
type mapIndex struct {
	pathStep
	key reflect.Value
}

func (mi MapIndex) Type() reflect.Type             { return mi.typ }
func (mi MapIndex) Values() (vx, vy reflect.Value) { return mi.vx, mi.vy }
func (mi MapIndex) String() string                 { return fmt.Sprintf("[%#v]", mi.key) }

// Key is the value of the map key.
func (mi MapIndex) Key() reflect.Value { return mi.key }

// Indirect represents pointer indirection on the parent type.
type Indirect struct{ *indirect }
type indirect struct {
	pathStep
}

func (in Indirect) Type() reflect.Type             { return in.typ }
func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy }
func (in Indirect) String() string                 { return "*" }

// TypeAssertion represents a type assertion on an interface.
type TypeAssertion struct{ *typeAssertion }
type typeAssertion struct {
	pathStep
}

func (ta TypeAssertion) Type() reflect.Type             { return ta.typ }
func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy }
func (ta TypeAssertion) String() string                 { return fmt.Sprintf(".(%v)", ta.typ) }

// Transform is a transformation from the parent type to the current type.
type Transform struct{ *transform }
type transform struct {
	pathStep
	trans *transformer
}

func (tf Transform) Type() reflect.Type             { return tf.typ }
func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy }
func (tf Transform) String() string                 { return fmt.Sprintf("%s()", tf.trans.name) }

// Name is the name of the Transformer.
func (tf Transform) Name() string { return tf.trans.name }

// Func is the function pointer to the transformer function.
func (tf Transform) Func() reflect.Value { return tf.trans.fnc }

// Option returns the originally constructed Transformer option.
// The == operator can be used to detect the exact option used.
func (tf Transform) Option() Option { return tf.trans }

// pointerPath represents a dual-stack of pointers encountered when
// recursively traversing the x and y values. This data structure supports
// detection of cycles and determining whether the cycles are equal.
// In Go, cycles can occur via pointers, slices, and maps.
//
// The pointerPath uses a map to represent a stack; where descension into a
// pointer pushes the address onto the stack, and ascension from a pointer
// pops the address from the stack. Thus, when traversing into a pointer from
// reflect.Ptr, reflect.Slice element, or reflect.Map, we can detect cycles
// by checking whether the pointer has already been visited. The cycle detection
// uses a seperate stack for the x and y values.
//
// If a cycle is detected we need to determine whether the two pointers
// should be considered equal. The definition of equality chosen by Equal
// requires two graphs to have the same structure. To determine this, both the
// x and y values must have a cycle where the previous pointers were also
// encountered together as a pair.
//
// Semantically, this is equivalent to augmenting Indirect, SliceIndex, and
// MapIndex with pointer information for the x and y values.
// Suppose px and py are two pointers to compare, we then search the
// Path for whether px was ever encountered in the Path history of x, and
// similarly so with py. If either side has a cycle, the comparison is only
// equal if both px and py have a cycle resulting from the same PathStep.
//
// Using a map as a stack is more performant as we can perform cycle detection
// in O(1) instead of O(N) where N is len(Path).
type pointerPath struct {
	// mx is keyed by x pointers, where the value is the associated y pointer.
	mx map[value.Pointer]value.Pointer
	// my is keyed by y pointers, where the value is the associated x pointer.
	my map[value.Pointer]value.Pointer
}

func (p *pointerPath) Init() {
	p.mx = make(map[value.Pointer]value.Pointer)
	p.my = make(map[value.Pointer]value.Pointer)
}

// Push indicates intent to descend into pointers vx and vy where
// visited reports whether either has been seen before. If visited before,
// equal reports whether both pointers were encountered together.
// Pop must be called if and only if the pointers were never visited.
//
// The pointers vx and vy must be a reflect.Ptr, reflect.Slice, or reflect.Map
// and be non-nil.
func (p pointerPath) Push(vx, vy reflect.Value) (equal, visited bool) {
	px := value.PointerOf(vx)
	py := value.PointerOf(vy)
	_, ok1 := p.mx[px]
	_, ok2 := p.my[py]
	if ok1 || ok2 {
		equal = p.mx[px] == py && p.my[py] == px // Pointers paired together
		return equal, true
	}
	p.mx[px] = py
	p.my[py] = px
	return false, false
}

// Pop ascends from pointers vx and vy.
func (p pointerPath) Pop(vx, vy reflect.Value) {
	delete(p.mx, value.PointerOf(vx))
	delete(p.my, value.PointerOf(vy))
}

// isExported reports whether the identifier is exported.
func isExported(id string) bool {
	r, _ := utf8.DecodeRuneInString(id)
	return unicode.IsUpper(r)
}
<commit_msg>Fix typo in path.go (#256)<commit_after>// Copyright 2017, 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 cmp

import (
	"fmt"
	"reflect"
	"strings"
	"unicode"
	"unicode/utf8"

	"github.com/google/go-cmp/cmp/internal/value"
)

// Path is a list of PathSteps describing the sequence of operations to get
// from some root type to the current position in the value tree.
// The first Path element is always an operation-less PathStep that exists
// simply to identify the initial type.
//
// When traversing structs with embedded structs, the embedded struct will
// always be accessed as a field before traversing the fields of the
// embedded struct themselves. That is, an exported field from the
// embedded struct will never be accessed directly from the parent struct.
type Path []PathStep

// PathStep is a union-type for specific operations to traverse
// a value's tree structure. Users of this package never need to implement
// these types as values of this type will be returned by this package.
//
// Implementations of this interface are
// StructField, SliceIndex, MapIndex, Indirect, TypeAssertion, and Transform.
type PathStep interface {
	String() string

	// Type is the resulting type after performing the path step.
	Type() reflect.Type

	// Values is the resulting values after performing the path step.
	// The type of each valid value is guaranteed to be identical to Type.
	//
	// In some cases, one or both may be invalid or have restrictions:
	//	• For StructField, both are not interface-able if the current field
	//	is unexported and the struct type is not explicitly permitted by
	//	an Exporter to traverse unexported fields.
	//	• For SliceIndex, one may be invalid if an element is missing from
	//	either the x or y slice.
	//	• For MapIndex, one may be invalid if an entry is missing from
	//	either the x or y map.
	//
	// The provided values must not be mutated.
	Values() (vx, vy reflect.Value)
}

var (
	_ PathStep = StructField{}
	_ PathStep = SliceIndex{}
	_ PathStep = MapIndex{}
	_ PathStep = Indirect{}
	_ PathStep = TypeAssertion{}
	_ PathStep = Transform{}
)

func (pa *Path) push(s PathStep) {
	*pa = append(*pa, s)
}

func (pa *Path) pop() {
	*pa = (*pa)[:len(*pa)-1]
}

// Last returns the last PathStep in the Path.
// If the path is empty, this returns a non-nil PathStep that reports a nil Type.
func (pa Path) Last() PathStep {
	return pa.Index(-1)
}

// Index returns the ith step in the Path and supports negative indexing.
// A negative index starts counting from the tail of the Path such that -1
// refers to the last step, -2 refers to the second-to-last step, and so on.
// If index is invalid, this returns a non-nil PathStep that reports a nil Type.
func (pa Path) Index(i int) PathStep {
	if i < 0 {
		i = len(pa) + i
	}
	if i < 0 || i >= len(pa) {
		return pathStep{}
	}
	return pa[i]
}

// String returns the simplified path to a node.
// The simplified path only contains struct field accesses.
//
// For example:
//	MyMap.MySlices.MyField
func (pa Path) String() string {
	var ss []string
	for _, s := range pa {
		if _, ok := s.(StructField); ok {
			ss = append(ss, s.String())
		}
	}
	return strings.TrimPrefix(strings.Join(ss, ""), ".")
}

// GoString returns the path to a specific node using Go syntax.
//
// For example:
//	(*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField
func (pa Path) GoString() string {
	var ssPre, ssPost []string
	var numIndirect int
	for i, s := range pa {
		var nextStep PathStep
		if i+1 < len(pa) {
			nextStep = pa[i+1]
		}
		switch s := s.(type) {
		case Indirect:
			numIndirect++
			pPre, pPost := "(", ")"
			switch nextStep.(type) {
			case Indirect:
				continue // Next step is indirection, so let them batch up
			case StructField:
				numIndirect-- // Automatic indirection on struct fields
			case nil:
				pPre, pPost = "", "" // Last step; no need for parenthesis
			}
			if numIndirect > 0 {
				ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect))
				ssPost = append(ssPost, pPost)
			}
			numIndirect = 0
			continue
		case Transform:
			ssPre = append(ssPre, s.trans.name+"(")
			ssPost = append(ssPost, ")")
			continue
		}
		ssPost = append(ssPost, s.String())
	}
	for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 {
		ssPre[i], ssPre[j] = ssPre[j], ssPre[i]
	}
	return strings.Join(ssPre, "") + strings.Join(ssPost, "")
}

type pathStep struct {
	typ    reflect.Type
	vx, vy reflect.Value
}

func (ps pathStep) Type() reflect.Type             { return ps.typ }
func (ps pathStep) Values() (vx, vy reflect.Value) { return ps.vx, ps.vy }
func (ps pathStep) String() string {
	if ps.typ == nil {
		return "<nil>"
	}
	s := ps.typ.String()
	if s == "" || strings.ContainsAny(s, "{}\n") {
		return "root" // Type too simple or complex to print
	}
	return fmt.Sprintf("{%s}", s)
}

// StructField represents a struct field access on a field called Name.
type StructField struct{ *structField }
type structField struct {
	pathStep
	name string
	idx  int

	// These fields are used for forcibly accessing an unexported field.
	// pvx, pvy, and field are only valid if unexported is true.
	unexported bool
	mayForce   bool                // Forcibly allow visibility
	paddr      bool                // Was parent addressable?
	pvx, pvy   reflect.Value       // Parent values (always addressible)
	field      reflect.StructField // Field information
}

func (sf StructField) Type() reflect.Type { return sf.typ }
func (sf StructField) Values() (vx, vy reflect.Value) {
	if !sf.unexported {
		return sf.vx, sf.vy // CanInterface reports true
	}

	// Forcibly obtain read-write access to an unexported struct field.
	if sf.mayForce {
		vx = retrieveUnexportedField(sf.pvx, sf.field, sf.paddr)
		vy = retrieveUnexportedField(sf.pvy, sf.field, sf.paddr)
		return vx, vy // CanInterface reports true
	}
	return sf.vx, sf.vy // CanInterface reports false
}
func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) }

// Name is the field name.
func (sf StructField) Name() string { return sf.name }

// Index is the index of the field in the parent struct type.
// See reflect.Type.Field.
func (sf StructField) Index() int { return sf.idx }

// SliceIndex is an index operation on a slice or array at some index Key.
type SliceIndex struct{ *sliceIndex }
type sliceIndex struct {
	pathStep
	xkey, ykey int
	isSlice    bool // False for reflect.Array
}

func (si SliceIndex) Type() reflect.Type             { return si.typ }
func (si SliceIndex) Values() (vx, vy reflect.Value) { return si.vx, si.vy }
func (si SliceIndex) String() string {
	switch {
	case si.xkey == si.ykey:
		return fmt.Sprintf("[%d]", si.xkey)
	case si.ykey == -1:
		// [5->?] means "I don't know where X[5] went"
		return fmt.Sprintf("[%d->?]", si.xkey)
	case si.xkey == -1:
		// [?->3] means "I don't know where Y[3] came from"
		return fmt.Sprintf("[?->%d]", si.ykey)
	default:
		// [5->3] means "X[5] moved to Y[3]"
		return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey)
	}
}

// Key is the index key; it may return -1 if in a split state
func (si SliceIndex) Key() int {
	if si.xkey != si.ykey {
		return -1
	}
	return si.xkey
}

// SplitKeys are the indexes for indexing into slices in the
// x and y values, respectively. These indexes may differ due to the
// insertion or removal of an element in one of the slices, causing
// all of the indexes to be shifted. If an index is -1, then that
// indicates that the element does not exist in the associated slice.
//
// Key is guaranteed to return -1 if and only if the indexes returned
// by SplitKeys are not the same. SplitKeys will never return -1 for
// both indexes.
func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey }

// MapIndex is an index operation on a map at some index Key.
type MapIndex struct{ *mapIndex }
type mapIndex struct {
	pathStep
	key reflect.Value
}

func (mi MapIndex) Type() reflect.Type             { return mi.typ }
func (mi MapIndex) Values() (vx, vy reflect.Value) { return mi.vx, mi.vy }
func (mi MapIndex) String() string                 { return fmt.Sprintf("[%#v]", mi.key) }

// Key is the value of the map key.
func (mi MapIndex) Key() reflect.Value { return mi.key }

// Indirect represents pointer indirection on the parent type.
type Indirect struct{ *indirect }
type indirect struct {
	pathStep
}

func (in Indirect) Type() reflect.Type             { return in.typ }
func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy }
func (in Indirect) String() string                 { return "*" }

// TypeAssertion represents a type assertion on an interface.
type TypeAssertion struct{ *typeAssertion }
type typeAssertion struct {
	pathStep
}

func (ta TypeAssertion) Type() reflect.Type             { return ta.typ }
func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy }
func (ta TypeAssertion) String() string                 { return fmt.Sprintf(".(%v)", ta.typ) }

// Transform is a transformation from the parent type to the current type.
type Transform struct{ *transform }
type transform struct {
	pathStep
	trans *transformer
}

func (tf Transform) Type() reflect.Type             { return tf.typ }
func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy }
func (tf Transform) String() string                 { return fmt.Sprintf("%s()", tf.trans.name) }

// Name is the name of the Transformer.
func (tf Transform) Name() string { return tf.trans.name }

// Func is the function pointer to the transformer function.
func (tf Transform) Func() reflect.Value { return tf.trans.fnc }

// Option returns the originally constructed Transformer option.
// The == operator can be used to detect the exact option used.
func (tf Transform) Option() Option { return tf.trans }

// pointerPath represents a dual-stack of pointers encountered when
// recursively traversing the x and y values. This data structure supports
// detection of cycles and determining whether the cycles are equal.
// In Go, cycles can occur via pointers, slices, and maps.
//
// The pointerPath uses a map to represent a stack; where descension into a
// pointer pushes the address onto the stack, and ascension from a pointer
// pops the address from the stack. Thus, when traversing into a pointer from
// reflect.Ptr, reflect.Slice element, or reflect.Map, we can detect cycles
// by checking whether the pointer has already been visited. The cycle detection
// uses a separate stack for the x and y values.
//
// If a cycle is detected we need to determine whether the two pointers
// should be considered equal. The definition of equality chosen by Equal
// requires two graphs to have the same structure. To determine this, both the
// x and y values must have a cycle where the previous pointers were also
// encountered together as a pair.
//
// Semantically, this is equivalent to augmenting Indirect, SliceIndex, and
// MapIndex with pointer information for the x and y values.
// Suppose px and py are two pointers to compare, we then search the
// Path for whether px was ever encountered in the Path history of x, and
// similarly so with py. If either side has a cycle, the comparison is only
// equal if both px and py have a cycle resulting from the same PathStep.
//
// Using a map as a stack is more performant as we can perform cycle detection
// in O(1) instead of O(N) where N is len(Path).
type pointerPath struct {
	// mx is keyed by x pointers, where the value is the associated y pointer.
	mx map[value.Pointer]value.Pointer
	// my is keyed by y pointers, where the value is the associated x pointer.
	my map[value.Pointer]value.Pointer
}

func (p *pointerPath) Init() {
	p.mx = make(map[value.Pointer]value.Pointer)
	p.my = make(map[value.Pointer]value.Pointer)
}

// Push indicates intent to descend into pointers vx and vy where
// visited reports whether either has been seen before. If visited before,
// equal reports whether both pointers were encountered together.
// Pop must be called if and only if the pointers were never visited.
//
// The pointers vx and vy must be a reflect.Ptr, reflect.Slice, or reflect.Map
// and be non-nil.
func (p pointerPath) Push(vx, vy reflect.Value) (equal, visited bool) {
	px := value.PointerOf(vx)
	py := value.PointerOf(vy)
	_, ok1 := p.mx[px]
	_, ok2 := p.my[py]
	if ok1 || ok2 {
		equal = p.mx[px] == py && p.my[py] == px // Pointers paired together
		return equal, true
	}
	p.mx[px] = py
	p.my[py] = px
	return false, false
}

// Pop ascends from pointers vx and vy.
func (p pointerPath) Pop(vx, vy reflect.Value) {
	delete(p.mx, value.PointerOf(vx))
	delete(p.my, value.PointerOf(vy))
}

// isExported reports whether the identifier is exported.
func isExported(id string) bool {
	r, _ := utf8.DecodeRuneInString(id)
	return unicode.IsUpper(r)
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Pani Networks
// All Rights Reserved.
//
// 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 topology

import (
	"fmt"
	"github.com/romana/core/common"
	"github.com/romana/core/common/store"
	"log"
	"net"
	"strconv"
	"strings"
)

// TopologySvc service
type TopologySvc struct {
	client     *common.RestClient
	config     common.ServiceConfig
	datacenter *common.Datacenter
	store      common.Store
	routes     common.Route
}

const (
	infoListPath  = "/info"
	agentListPath = "/agents"
	hostListPath  = "/hosts"
	torListPath   = "/tors"
	spineListPath = "/spines"
	dcPath        = "/datacenter"
)

// Routes returns various routes used in the service.
func (topology *TopologySvc) Routes() common.Routes {
	infoRouteIndex := common.Route{
		Method:          "GET",
		Pattern:         "/",
		Handler:         topology.handleIndex,
		MakeMessage:     nil,
		UseRequestToken: false,
	}
	routes := common.Routes{
		infoRouteIndex,
		common.Route{
			Method:          "GET",
			Pattern:         hostListPath,
			Handler:         topology.handleHostListGet,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
		common.Route{
			Method:          "POST",
			Pattern:         hostListPath,
			Handler:         topology.handleHostListPost,
			MakeMessage:     func() interface{} { return &common.Host{} },
			UseRequestToken: false,
		},
		common.Route{
			Method:          "GET",
			Pattern:         hostListPath + "/{hostId}",
			Handler:         topology.handleGetHost,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
		common.Route{
			Method:          "GET",
			Pattern:         dcPath,
			Handler:         topology.handleDc,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
		common.Route{
			Method:          "DELETE",
			Pattern:         hostListPath + "/{hostID}",
			Handler:         topology.handleDeleteHost,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
		// TODO to be done generically
		common.Route{
			Method:          "GET",
			Pattern:         "/findLast/hosts",
			Handler:         topology.handleFindHost,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
	}

	// TODO reintroduce (if we need to) the find routes
	//	var h = []common.Host{}
	//	routes = append(routes, common.CreateFindRoutes(&h, &topology.store.DbStore)...)
	return routes
}

func (topology *TopologySvc) handleFindHost(input interface{}, ctx common.RestContext) (interface{}, error) {
	query := ctx.QueryVariables
	var hosts []common.Host
	return topology.store.Find(query, &hosts, common.FindLast)
}

// handleHost handles request for a specific host's info
func (topology *TopologySvc) handleDc(input interface{}, ctx common.RestContext) (interface{}, error) {
	// For now it's from config, later on we can use this to manage multiple dcs.
	return topology.datacenter, nil
}

// Name implements method of Service interface.
func (topology *TopologySvc) Name() string {
	return "topology"
}

// handleGetHost handles request for a specific host's info
func (topology *TopologySvc) handleGetHost(input interface{}, ctx common.RestContext) (interface{}, error) {
	log.Println("In handleHost()")
	idStr := ctx.PathVariables["hostId"]
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return nil, err
	}
	host, err := topology.store.GetHost(id)
	if err != nil {
		return nil, err
	}
	agentURL := fmt.Sprintf("http://%s:%d", host.Ip, host.AgentPort)
	agentLink := common.LinkResponse{Href: agentURL, Rel: "agent"}
	hostLink := common.LinkResponse{Href: hostListPath + "/" + idStr, Rel: "self"}
	collectionLink := common.LinkResponse{Href: hostListPath, Rel: "self"}
	host.Links = []common.LinkResponse{agentLink, hostLink, collectionLink}
	return host, nil
}

func (topology *TopologySvc) handleHostListGet(input interface{}, ctx common.RestContext) (interface{}, error) {
	log.Println("In handleHostListGet()")
	hosts, err := topology.store.ListHosts()
	if err != nil {
		return nil, err
	}
	return hosts, nil
}

// handleHostListPost handles addition of a host to the current datacenter.
// If the Host.AgentPort is not specified, root service is queried for
// the default Agent port.
func (topology *TopologySvc) handleHostListPost(input interface{}, ctx common.RestContext) (interface{}, error) {
	host := input.(*common.Host)
	// If no agent port is specfied in the creation of new host,
	// get the agent port from root service.
	log.Printf("Host requested with agent port %d", host.AgentPort)
	if host.AgentPort == 0 {
		// Get the one from configuration
		agentConfig, err := topology.client.GetServiceConfig("agent")
		if err != nil {
			return nil, err
		}
		host.AgentPort = agentConfig.Common.Api.Port
		if host.AgentPort == 0 {
			return nil, common.NewError500("Cannot determine port for agent")
		}
	}
	log.Printf("Host will be added with agent port %d", host.AgentPort)
	err := topology.store.AddHost(*topology.datacenter, host)
	if err != nil {
		return nil, err
	}
	agentURL := fmt.Sprintf("http://%s:%d", host.Ip, host.AgentPort)
	agentLink := common.LinkResponse{Href: agentURL, Rel: "agent"}
	hostLink := common.LinkResponse{Href: hostListPath + "/" + fmt.Sprintf("%d", host.ID), Rel: "self"}
	collectionLink := common.LinkResponse{Href: hostListPath, Rel: "self"}
	host.Links = []common.LinkResponse{agentLink, hostLink, collectionLink}
	return host, nil
}

func (topology *TopologySvc) handleIndex(input interface{}, ctx common.RestContext) (interface{}, error) {
	retval := common.IndexResponse{}
	retval.ServiceName = "topology"
	myURL := strings.Join([]string{"http://", topology.config.Common.Api.Host, ":", strconv.FormatUint(topology.config.Common.Api.Port, 10)}, "")

	selfLink := common.LinkResponse{Href: myURL, Rel: "self"}
	aboutLink := common.LinkResponse{Href: infoListPath, Rel: "about"}
	agentsLink := common.LinkResponse{Href: agentListPath, Rel: "agent-list"}
	hostsLink := common.LinkResponse{Href: hostListPath, Rel: "host-list"}
	torsLink := common.LinkResponse{Href: torListPath, Rel: "tor-list"}
	spinesLink := common.LinkResponse{Href: spineListPath, Rel: "spine-list"}
	dcLink := common.LinkResponse{Href: dcPath, Rel: "datacenter"}

	retval.Links = []common.LinkResponse{selfLink, aboutLink, agentsLink, hostsLink, torsLink, spinesLink, dcLink}
	return retval, nil
}

// SetConfig implements SetConfig function of the Service interface.
// Returns an error if cannot connect to the data store
func (topology *TopologySvc) SetConfig(config common.ServiceConfig) error {
	topology.config = config
	dcMap := config.ServiceSpecific["datacenter"].(map[string]interface{})
	dc := common.Datacenter{}
	dc.IpVersion = uint(dcMap["ip_version"].(float64))
	if dc.IpVersion != 4 {
		return common.NewError("Only IPv4 is currently supported.")
	}
	dc.Cidr = dcMap["cidr"].(string)
	_, ipNet, err := net.ParseCIDR(dc.Cidr)
	if err != nil {
		return err
	}
	prefixBits, _ := ipNet.Mask.Size()
	dc.PrefixBits = uint(prefixBits)

	dc.PortBits = uint(dcMap["host_bits"].(float64))
	dc.TenantBits = uint(dcMap["tenant_bits"].(float64))
	dc.SegmentBits = uint(dcMap["segment_bits"].(float64))
	dc.EndpointBits = uint(dcMap["endpoint_bits"].(float64))
	dc.EndpointSpaceBits = uint(dcMap["endpoint_space_bits"].(float64))
	if dc.EndpointBits == 0 {
		return common.NewError("Endpoint bits may not be 0")
	}
	bitSum := dc.PrefixBits + dc.PortBits + dc.TenantBits + dc.SegmentBits + dc.EndpointBits + dc.EndpointSpaceBits
	if bitSum != 32 {
		bitSumStr := fmt.Sprintf("%s+%d+%d+%d+%d+%d", dc.Cidr, dc.PortBits, dc.TenantBits, dc.SegmentBits, dc.EndpointBits, dc.EndpointSpaceBits)
		return common.NewError("Sum of prefix, port, tenant, segment, endpoint and endpoint space bits must be exactly 32, but it is %s=%d", bitSumStr, bitSum)
	}

	// TODO this should have worked but it doesn't...
	//	err := mapstructure.Decode(dcMap, &dc)
	//	if err != nil {
	//		return err
	//	}
	log.Printf("Datacenter information: was %s, decoded to %+v\n", dcMap, dc)
	topology.datacenter = &dc

	storeConfigMap := config.ServiceSpecific["store"].(map[string]interface{})
	topology.store, err = store.GetStore(storeConfigMap)
	return err
}

// Initialize the topology service
func (topology *TopologySvc) Initialize(client *common.RestClient) error {
	log.Println("Parsing", topology.datacenter)

	ip, _, err := net.ParseCIDR(topology.datacenter.Cidr)
	if err != nil {
		return err
	}
	topology.client = client
	topology.datacenter.Prefix = common.IPv4ToInt(ip)
	return topology.store.Connect()
}

func (topology *TopologySvc) CreateSchema(overwrite bool) error {
	return topology.store.CreateSchema(overwrite)
}

// handleDeleteHost handles deletion of a host.
func (topology *TopologySvc) handleDeleteHost(input interface{}, ctx common.RestContext) (interface{}, error) {
	log.Println("In handleDeleteHost()")
	idStr := strings.TrimSpace(ctx.PathVariables["hostID"])
	if idStr == "" {
		return nil, common.NewError400("Request must be to /hosts/{hostID}.")
	}
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return nil, err
	}
	err = topology.store.DeleteHost(id)
	if err != nil {
		return nil, err
	}
	return nil, nil
}
<commit_msg>Fixes an issue when topology allows to add host with a same name.<commit_after>// Copyright (c) 2016 Pani Networks
// All Rights Reserved.
//
// 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 topology

import (
	"fmt"
	"github.com/romana/core/common"
	"github.com/romana/core/common/store"
	"log"
	"net"
	"strconv"
	"strings"
)

// TopologySvc service
type TopologySvc struct {
	client     *common.RestClient
	config     common.ServiceConfig
	datacenter *common.Datacenter
	store      common.Store
	routes     common.Route
}

const (
	infoListPath  = "/info"
	agentListPath = "/agents"
	hostListPath  = "/hosts"
	torListPath   = "/tors"
	spineListPath = "/spines"
	dcPath        = "/datacenter"
)

// Routes returns various routes used in the service.
func (topology *TopologySvc) Routes() common.Routes {
	infoRouteIndex := common.Route{
		Method:          "GET",
		Pattern:         "/",
		Handler:         topology.handleIndex,
		MakeMessage:     nil,
		UseRequestToken: false,
	}
	routes := common.Routes{
		infoRouteIndex,
		common.Route{
			Method:          "GET",
			Pattern:         hostListPath,
			Handler:         topology.handleHostListGet,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
		common.Route{
			Method:          "POST",
			Pattern:         hostListPath,
			Handler:         topology.handleHostListPost,
			MakeMessage:     func() interface{} { return &common.Host{} },
			UseRequestToken: false,
		},
		common.Route{
			Method:          "GET",
			Pattern:         hostListPath + "/{hostId}",
			Handler:         topology.handleGetHost,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
		common.Route{
			Method:          "GET",
			Pattern:         dcPath,
			Handler:         topology.handleDc,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
		common.Route{
			Method:          "DELETE",
			Pattern:         hostListPath + "/{hostID}",
			Handler:         topology.handleDeleteHost,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
		// TODO to be done generically
		common.Route{
			Method:          "GET",
			Pattern:         "/findLast/hosts",
			Handler:         topology.handleFindHost,
			MakeMessage:     nil,
			UseRequestToken: false,
		},
	}

	// TODO reintroduce (if we need to) the find routes
	//	var h = []common.Host{}
	//	routes = append(routes, common.CreateFindRoutes(&h, &topology.store.DbStore)...)
	return routes
}

func (topology *TopologySvc) handleFindHost(input interface{}, ctx common.RestContext) (interface{}, error) {
	query := ctx.QueryVariables
	var hosts []common.Host
	return topology.store.Find(query, &hosts, common.FindLast)
}

// handleHost handles request for a specific host's info
func (topology *TopologySvc) handleDc(input interface{}, ctx common.RestContext) (interface{}, error) {
	// For now it's from config, later on we can use this to manage multiple dcs.
	return topology.datacenter, nil
}

// Name implements method of Service interface.
func (topology *TopologySvc) Name() string {
	return "topology"
}

// handleGetHost handles request for a specific host's info
func (topology *TopologySvc) handleGetHost(input interface{}, ctx common.RestContext) (interface{}, error) {
	log.Println("In handleHost()")
	idStr := ctx.PathVariables["hostId"]
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return nil, err
	}
	host, err := topology.store.GetHost(id)
	if err != nil {
		return nil, err
	}
	agentURL := fmt.Sprintf("http://%s:%d", host.Ip, host.AgentPort)
	agentLink := common.LinkResponse{Href: agentURL, Rel: "agent"}
	hostLink := common.LinkResponse{Href: hostListPath + "/" + idStr, Rel: "self"}
	collectionLink := common.LinkResponse{Href: hostListPath, Rel: "self"}
	host.Links = []common.LinkResponse{agentLink, hostLink, collectionLink}
	return host, nil
}

func (topology *TopologySvc) handleHostListGet(input interface{}, ctx common.RestContext) (interface{}, error) {
	log.Println("In handleHostListGet()")
	hosts, err := topology.store.ListHosts()
	if err != nil {
		return nil, err
	}
	return hosts, nil
}

// handleHostListPost handles addition of a host to the current datacenter.
// If the Host.AgentPort is not specified, root service is queried for
// the default Agent port.
func (topology *TopologySvc) handleHostListPost(input interface{}, ctx common.RestContext) (interface{}, error) {
	host := input.(*common.Host)

	// Check name collision.
	hosts, err := topology.store.ListHosts()
	if err != nil {
		return nil, err
	}
	for _, h := range hosts {
		if h.Name == host.Name {
			return nil, common.NewErrorConflict(fmt.Sprintf("Host with name %s already registered in romana", host.Name))
		}
	}

	// If no agent port is specfied in the creation of new host,
	// get the agent port from root service.
	log.Printf("Host requested with agent port %d", host.AgentPort)
	if host.AgentPort == 0 {
		// Get the one from configuration
		agentConfig, err := topology.client.GetServiceConfig("agent")
		if err != nil {
			return nil, err
		}
		host.AgentPort = agentConfig.Common.Api.Port
		if host.AgentPort == 0 {
			return nil, common.NewError500("Cannot determine port for agent")
		}
	}
	log.Printf("Host will be added with agent port %d", host.AgentPort)
	err = topology.store.AddHost(*topology.datacenter, host)
	if err != nil {
		return nil, err
	}
	agentURL := fmt.Sprintf("http://%s:%d", host.Ip, host.AgentPort)
	agentLink := common.LinkResponse{Href: agentURL, Rel: "agent"}
	hostLink := common.LinkResponse{Href: hostListPath + "/" + fmt.Sprintf("%d", host.ID), Rel: "self"}
	collectionLink := common.LinkResponse{Href: hostListPath, Rel: "self"}
	host.Links = []common.LinkResponse{agentLink, hostLink, collectionLink}
	return host, nil
}

func (topology *TopologySvc) handleIndex(input interface{}, ctx common.RestContext) (interface{}, error) {
	retval := common.IndexResponse{}
	retval.ServiceName = "topology"
	myURL := strings.Join([]string{"http://", topology.config.Common.Api.Host, ":", strconv.FormatUint(topology.config.Common.Api.Port, 10)}, "")

	selfLink := common.LinkResponse{Href: myURL, Rel: "self"}
	aboutLink := common.LinkResponse{Href: infoListPath, Rel: "about"}
	agentsLink := common.LinkResponse{Href: agentListPath, Rel: "agent-list"}
	hostsLink := common.LinkResponse{Href: hostListPath, Rel: "host-list"}
	torsLink := common.LinkResponse{Href: torListPath, Rel: "tor-list"}
	spinesLink := common.LinkResponse{Href: spineListPath, Rel: "spine-list"}
	dcLink := common.LinkResponse{Href: dcPath, Rel: "datacenter"}

	retval.Links = []common.LinkResponse{selfLink, aboutLink, agentsLink, hostsLink, torsLink, spinesLink, dcLink}
	return retval, nil
}

// SetConfig implements SetConfig function of the Service interface.
// Returns an error if cannot connect to the data store
func (topology *TopologySvc) SetConfig(config common.ServiceConfig) error {
	topology.config = config
	dcMap := config.ServiceSpecific["datacenter"].(map[string]interface{})
	dc := common.Datacenter{}
	dc.IpVersion = uint(dcMap["ip_version"].(float64))
	if dc.IpVersion != 4 {
		return common.NewError("Only IPv4 is currently supported.")
	}
	dc.Cidr = dcMap["cidr"].(string)
	_, ipNet, err := net.ParseCIDR(dc.Cidr)
	if err != nil {
		return err
	}
	prefixBits, _ := ipNet.Mask.Size()
	dc.PrefixBits = uint(prefixBits)

	dc.PortBits = uint(dcMap["host_bits"].(float64))
	dc.TenantBits = uint(dcMap["tenant_bits"].(float64))
	dc.SegmentBits = uint(dcMap["segment_bits"].(float64))
	dc.EndpointBits = uint(dcMap["endpoint_bits"].(float64))
	dc.EndpointSpaceBits = uint(dcMap["endpoint_space_bits"].(float64))
	if dc.EndpointBits == 0 {
		return common.NewError("Endpoint bits may not be 0")
	}
	bitSum := dc.PrefixBits + dc.PortBits + dc.TenantBits + dc.SegmentBits + dc.EndpointBits + dc.EndpointSpaceBits
	if bitSum != 32 {
		bitSumStr := fmt.Sprintf("%s+%d+%d+%d+%d+%d", dc.Cidr, dc.PortBits, dc.TenantBits, dc.SegmentBits, dc.EndpointBits, dc.EndpointSpaceBits)
		return common.NewError("Sum of prefix, port, tenant, segment, endpoint and endpoint space bits must be exactly 32, but it is %s=%d", bitSumStr, bitSum)
	}

	// TODO this should have worked but it doesn't...
	//	err := mapstructure.Decode(dcMap, &dc)
	//	if err != nil {
	//		return err
	//	}
	log.Printf("Datacenter information: was %s, decoded to %+v\n", dcMap, dc)
	topology.datacenter = &dc

	storeConfigMap := config.ServiceSpecific["store"].(map[string]interface{})
	topology.store, err = store.GetStore(storeConfigMap)
	return err
}

// Initialize the topology service
func (topology *TopologySvc) Initialize(client *common.RestClient) error {
	log.Println("Parsing", topology.datacenter)

	ip, _, err := net.ParseCIDR(topology.datacenter.Cidr)
	if err != nil {
		return err
	}
	topology.client = client
	topology.datacenter.Prefix = common.IPv4ToInt(ip)
	return topology.store.Connect()
}

func (topology *TopologySvc) CreateSchema(overwrite bool) error {
	return topology.store.CreateSchema(overwrite)
}

// handleDeleteHost handles deletion of a host.
func (topology *TopologySvc) handleDeleteHost(input interface{}, ctx common.RestContext) (interface{}, error) {
	log.Println("In handleDeleteHost()")
	idStr := strings.TrimSpace(ctx.PathVariables["hostID"])
	if idStr == "" {
		return nil, common.NewError400("Request must be to /hosts/{hostID}.")
	}
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return nil, err
	}
	err = topology.store.DeleteHost(id)
	if err != nil {
		return nil, err
	}
	return nil, nil
}
<|endoftext|>


<commit_before>// Package google implements a Service which adds !commands for Google custom search engine.
// Initially this package just supports image search but could be expanded to provide other functionality provided by the Google custom search engine API - https://developers.google.com/custom-search/json-api/v1/overview
package google

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math"
	"net/http"
	"net/url"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/matrix-org/go-neb/types"
	"github.com/matrix-org/gomatrix"
)

// ServiceType of the Google service
const ServiceType = "google"

var httpClient = &http.Client{}

type googleSearchResults struct {
	SearchInformation struct {
		TotalResults int64 `json:"totalResults,string"`
	} `json:"searchInformation"`
	Items []googleSearchResult `json:"items"`
}

type googleSearchResult struct {
	Title       string      `json:"title"`
	HTMLTitle   string      `json:"htmlTitle"`
	Link        string      `json:"link"`
	DisplayLink string      `json:"displayLink"`
	Snippet     string      `json:"snippet"`
	HTMLSnippet string      `json:"htmlSnippet"`
	Mime        string      `json:"mime"`
	FileFormat  string      `json:"fileFormat"`
	Image       googleImage `json:"image"`
}

type googleImage struct {
	ContextLink     string  `json:"contextLink"`
	Height          float64 `json:"height"`
	Width           float64 `json:"width"`
	ByteSize        int64   `json:"byteSize"`
	ThumbnailLink   string  `json:"thumbnailLink"`
	ThumbnailHeight float64 `json:"thumbnailHeight"`
	ThumbnailWidth  float64 `json:"thumbnailWidth"`
}

// Service contains the Config fields for the Google service.
//
// Example request:
//   {
//			"api_key": "AIzaSyA4FD39..."
//			"cx": "ASdsaijwdfASD..."
//   }
type Service struct {
	types.DefaultService
	// The Google API key to use when making HTTP requests to Google.
	APIKey string `json:"api_key"`
	// The Google custom search engine ID
	Cx string `json:"cx"`
}

// Commands supported:
//    !google image some_search_query_without_quotes
// Responds with a suitable image into the same room as the command.
func (s *Service) Commands(client *gomatrix.Client) []types.Command {
	return []types.Command{
		types.Command{
			Path: []string{"google", "image"},
			Command: func(roomID, userID string, args []string) (interface{}, error) {
				return s.cmdGoogleImgSearch(client, roomID, userID, args)
			},
		},
		types.Command{
			Path: []string{"google", "help"},
			Command: func(roomID, userID string, args []string) (interface{}, error) {
				return usageMessage(), nil
			},
		},
	}
}

// usageMessage returns a matrix TextMessage representation of the service usage
func usageMessage() *gomatrix.TextMessage {
	return &gomatrix.TextMessage{"m.notice",
		`Usage: !google image image_search_text`}
}

func (s *Service) cmdGoogleImgSearch(client *gomatrix.Client, roomID, userID string, args []string) (interface{}, error) {

	if len(args) < 1 {
		return usageMessage(), nil
	}

	// Get the query text to search for.
	querySentence := strings.Join(args, " ")

	searchResult, err := s.text2imgGoogle(querySentence)

	if err != nil {
		return nil, err
	}

	var imgURL = searchResult.Link
	if imgURL == "" {
		return gomatrix.TextMessage{
			MsgType: "m.text.notice",
			Body:    "No image found!",
		}, nil
	}

	// FIXME -- Sometimes upload fails with a cryptic error - "msg=Upload request failed code=400"
	resUpload, err := client.UploadLink(imgURL)
	if err != nil {
		return nil, fmt.Errorf("Failed to upload Google image to matrix: %s", err.Error())
	}

	return gomatrix.ImageMessage{
		MsgType: "m.image",
		Body:    querySentence,
		URL:     resUpload.ContentURI,
		Info: gomatrix.ImageInfo{
			Height:   uint(math.Floor(searchResult.Image.Height)),
			Width:    uint(math.Floor(searchResult.Image.Width)),
			Mimetype: searchResult.Mime,
		},
	}, nil
}

// text2imgGoogle returns info about an image
func (s *Service) text2imgGoogle(query string) (*googleSearchResult, error) {
	log.Info("Searching Google for an image of a ", query)

	u, err := url.Parse("https://www.googleapis.com/customsearch/v1")
	if err != nil {
		return nil, err
	}

	q := u.Query()
	q.Set("q", query)            // String to search for
	q.Set("num", "1")            // Just return 1 image result
	q.Set("start", "1")          // No search result offset
	q.Set("imgSize", "medium")   // Just search for medium size images
	q.Set("searchType", "image") // Search for images

	q.Set("key", s.APIKey) // Set the API key for the request
	q.Set("cx", s.Cx)      // Set the custom search engine ID

	u.RawQuery = q.Encode()
	// log.Info("Request URL: ", u)

	res, err := http.Get(u.String())
	if res != nil {
		defer res.Body.Close()
	}
	if err != nil {
		return nil, err
	}
	if res.StatusCode > 200 {
		return nil, fmt.Errorf("Request error: %d, %s", res.StatusCode, response2String(res))
	}
	var searchResults googleSearchResults

	// log.Info(response2String(res))
	if err := json.NewDecoder(res.Body).Decode(&searchResults); err != nil || len(searchResults.Items) < 1 {
		return nil, fmt.Errorf("No images found - %s", err.Error())
	}

	// Return only the first search result
	return &searchResults.Items[0], nil
}

// response2String returns a string representation of an HTTP response body
func response2String(res *http.Response) (responseText string) {
	bs, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "Failed to decode response body"
	}
	str := string(bs)
	return str
}

// Initialise the service
func init() {
	types.RegisterService(func(serviceID, serviceUserID, webhookEndpointURL string) types.Service {
		return &Service{
			DefaultService: types.NewDefaultService(serviceID, serviceUserID, ServiceType),
		}
	})
}
<commit_msg>Clean up named return value<commit_after>// Package google implements a Service which adds !commands for Google custom search engine.
// Initially this package just supports image search but could be expanded to provide other functionality provided by the Google custom search engine API - https://developers.google.com/custom-search/json-api/v1/overview
package google

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math"
	"net/http"
	"net/url"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/matrix-org/go-neb/types"
	"github.com/matrix-org/gomatrix"
)

// ServiceType of the Google service
const ServiceType = "google"

var httpClient = &http.Client{}

type googleSearchResults struct {
	SearchInformation struct {
		TotalResults int64 `json:"totalResults,string"`
	} `json:"searchInformation"`
	Items []googleSearchResult `json:"items"`
}

type googleSearchResult struct {
	Title       string      `json:"title"`
	HTMLTitle   string      `json:"htmlTitle"`
	Link        string      `json:"link"`
	DisplayLink string      `json:"displayLink"`
	Snippet     string      `json:"snippet"`
	HTMLSnippet string      `json:"htmlSnippet"`
	Mime        string      `json:"mime"`
	FileFormat  string      `json:"fileFormat"`
	Image       googleImage `json:"image"`
}

type googleImage struct {
	ContextLink     string  `json:"contextLink"`
	Height          float64 `json:"height"`
	Width           float64 `json:"width"`
	ByteSize        int64   `json:"byteSize"`
	ThumbnailLink   string  `json:"thumbnailLink"`
	ThumbnailHeight float64 `json:"thumbnailHeight"`
	ThumbnailWidth  float64 `json:"thumbnailWidth"`
}

// Service contains the Config fields for the Google service.
//
// Example request:
//   {
//			"api_key": "AIzaSyA4FD39..."
//			"cx": "ASdsaijwdfASD..."
//   }
type Service struct {
	types.DefaultService
	// The Google API key to use when making HTTP requests to Google.
	APIKey string `json:"api_key"`
	// The Google custom search engine ID
	Cx string `json:"cx"`
}

// Commands supported:
//    !google image some_search_query_without_quotes
// Responds with a suitable image into the same room as the command.
func (s *Service) Commands(client *gomatrix.Client) []types.Command {
	return []types.Command{
		types.Command{
			Path: []string{"google", "image"},
			Command: func(roomID, userID string, args []string) (interface{}, error) {
				return s.cmdGoogleImgSearch(client, roomID, userID, args)
			},
		},
		types.Command{
			Path: []string{"google", "help"},
			Command: func(roomID, userID string, args []string) (interface{}, error) {
				return usageMessage(), nil
			},
		},
	}
}

// usageMessage returns a matrix TextMessage representation of the service usage
func usageMessage() *gomatrix.TextMessage {
	return &gomatrix.TextMessage{"m.notice",
		`Usage: !google image image_search_text`}
}

func (s *Service) cmdGoogleImgSearch(client *gomatrix.Client, roomID, userID string, args []string) (interface{}, error) {

	if len(args) < 1 {
		return usageMessage(), nil
	}

	// Get the query text to search for.
	querySentence := strings.Join(args, " ")

	searchResult, err := s.text2imgGoogle(querySentence)

	if err != nil {
		return nil, err
	}

	var imgURL = searchResult.Link
	if imgURL == "" {
		return gomatrix.TextMessage{
			MsgType: "m.text.notice",
			Body:    "No image found!",
		}, nil
	}

	// FIXME -- Sometimes upload fails with a cryptic error - "msg=Upload request failed code=400"
	resUpload, err := client.UploadLink(imgURL)
	if err != nil {
		return nil, fmt.Errorf("Failed to upload Google image to matrix: %s", err.Error())
	}

	return gomatrix.ImageMessage{
		MsgType: "m.image",
		Body:    querySentence,
		URL:     resUpload.ContentURI,
		Info: gomatrix.ImageInfo{
			Height:   uint(math.Floor(searchResult.Image.Height)),
			Width:    uint(math.Floor(searchResult.Image.Width)),
			Mimetype: searchResult.Mime,
		},
	}, nil
}

// text2imgGoogle returns info about an image
func (s *Service) text2imgGoogle(query string) (*googleSearchResult, error) {
	log.Info("Searching Google for an image of a ", query)

	u, err := url.Parse("https://www.googleapis.com/customsearch/v1")
	if err != nil {
		return nil, err
	}

	q := u.Query()
	q.Set("q", query)            // String to search for
	q.Set("num", "1")            // Just return 1 image result
	q.Set("start", "1")          // No search result offset
	q.Set("imgSize", "medium")   // Just search for medium size images
	q.Set("searchType", "image") // Search for images

	q.Set("key", s.APIKey) // Set the API key for the request
	q.Set("cx", s.Cx)      // Set the custom search engine ID

	u.RawQuery = q.Encode()
	// log.Info("Request URL: ", u)

	res, err := http.Get(u.String())
	if res != nil {
		defer res.Body.Close()
	}
	if err != nil {
		return nil, err
	}
	if res.StatusCode > 200 {
		return nil, fmt.Errorf("Request error: %d, %s", res.StatusCode, response2String(res))
	}
	var searchResults googleSearchResults

	// log.Info(response2String(res))
	if err := json.NewDecoder(res.Body).Decode(&searchResults); err != nil || len(searchResults.Items) < 1 {
		return nil, fmt.Errorf("No images found - %s", err.Error())
	}

	// Return only the first search result
	return &searchResults.Items[0], nil
}

// response2String returns a string representation of an HTTP response body
func response2String(res *http.Response) string {
	bs, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "Failed to decode response body"
	}
	str := string(bs)
	return str
}

// Initialise the service
func init() {
	types.RegisterService(func(serviceID, serviceUserID, webhookEndpointURL string) types.Service {
		return &Service{
			DefaultService: types.NewDefaultService(serviceID, serviceUserID, ServiceType),
		}
	})
}
<|endoftext|>


<commit_before>// Copyright 2017 aaharu All rights reserved.
// This source code is licensed under the BSD-style license found in
// the LICENSE file in the root directory of this source tree.

package codegen

import (
	"os"
	"reflect"
	"testing"

	"github.com/aaharu/schemarshal/utils"
)

func TestJSONTagOmitEmpty(t *testing.T) {
	tag := &jsonTag{
		omitEmpty: true,
	}
	actual := tag.generate()
	expected := []byte("`json:\",omitempty\"`")
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("got %v\nwant %v", string(actual), string(expected))
	}
}

func TestJSONTag(t *testing.T) {
	tag := &jsonTag{
		name: "key",
	}
	actual := tag.generate()
	expected := []byte("`json:\"key\"`")
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("got %v\nwant %v", actual, expected)
	}
}

func TestSample1(t *testing.T) {
	file, err := os.Open("../test_data/a.json")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	gen := NewGenerator("test", "")
	if err := gen.ReadSchema(file, utils.FileName(file)); err != nil {
		panic(err)
	}
	actual, _ := gen.Generate()
	if len(actual) < 1 {
		t.Errorf("got %v\n", string(actual))
	}
}

func TestSample2(t *testing.T) {
	file, err := os.Open("../test_data/disk.json")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	gen := NewGenerator("test", "")
	if err := gen.ReadSchema(file, utils.FileName(file)); err != nil {
		panic(err)
	}
	actual, _ := gen.Generate()
	if len(actual) < 1 {
		t.Errorf("got %v\n", string(actual))
	}
}

func TestSample3(t *testing.T) {
	file, err := os.Open("../test_data/qiita.json")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	gen := NewGenerator("test", "")
	if err := gen.ReadSchema(file, utils.FileName(file)); err != nil {
		panic(err)
	}
	actual, _ := gen.Generate()
	if len(actual) < 1 {
		t.Errorf("got %v\n", string(actual))
	}
}
<commit_msg>fix tests<commit_after>// Copyright 2017 aaharu All rights reserved.
// This source code is licensed under the BSD-style license found in
// the LICENSE file in the root directory of this source tree.

package codegen

import (
	"os"
	"reflect"
	"testing"

	"github.com/aaharu/schemarshal/utils"
)

func TestJSONTagOmitEmpty(t *testing.T) {
	tag := &jsonTag{
		omitEmpty: true,
	}
	actual := tag.generate()
	expected := []byte("`json:\",omitempty\"`")
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("got %v\nwant %v", string(actual), string(expected))
	}
}

func TestJSONTag(t *testing.T) {
	tag := &jsonTag{
		name: "key",
	}
	actual := tag.generate()
	expected := []byte("`json:\"key\"`")
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("got %v\nwant %v", actual, expected)
	}
}

func TestSample1(t *testing.T) {
	file, err := os.Open("../test_data/a.json")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	gen := NewGenerator("test", "")
	if err := gen.ReadSchema(file, utils.FileName(file)); err != nil {
		panic(err)
	}
	actual, _ := gen.Generate(true)
	if len(actual) < 1 {
		t.Errorf("got %v\n", string(actual))
	}
}

func TestSample2(t *testing.T) {
	file, err := os.Open("../test_data/disk.json")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	gen := NewGenerator("test", "")
	if err := gen.ReadSchema(file, utils.FileName(file)); err != nil {
		panic(err)
	}
	actual, _ := gen.Generate(false)
	if len(actual) < 1 {
		t.Errorf("got %v\n", string(actual))
	}
}

func TestSample3(t *testing.T) {
	file, err := os.Open("../test_data/qiita.json")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	gen := NewGenerator("test", "")
	if err := gen.ReadSchema(file, utils.FileName(file)); err != nil {
		panic(err)
	}
	actual, _ := gen.Generate(false)
	if len(actual) < 1 {
		t.Errorf("got %v\n", string(actual))
	}
}
<|endoftext|>