<commit_before>// Copyright © 2017 Mladen Popadic <mladen.popadic.4@gmail.com>

package cmd

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/mpopadic/go_n_find/colors"
	"github.com/spf13/cobra"
)

var (
	pathFlag              string
	nameFlag              string
	replaceFlag           string
	ignoreCaseFlag        bool
	showAbsolutePathsFlag bool
	forceReplaceFlag      bool
	contentFlag           string
)

var (
	_numberOfResults     int
	_renameMap           map[string]string
	_replaceContentFiles []string
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "go_n_find",
	Short: "CLI for finding files and folders",
	Long:  `CLI tool for finding files and folders by name or content`,
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if pathFlag == "" {
			return fmt.Errorf("path flag is required")
		}
		if nameFlag == "" && contentFlag == "" {
			return fmt.Errorf("name flag or content flag are required")
		}
		return nil
	},
	// Uncomment the following line if your bare application
	// has an action associated with it:
	RunE: func(cmd *cobra.Command, args []string) error {

		// Set findOptions
		options := &findOptions{
			Path:              pathFlag,
			Name:              nameFlag,
			Content:           contentFlag,
			ReplaceWith:       replaceFlag,
			IgnoreCase:        ignoreCaseFlag,
			ShowAbsolutePaths: showAbsolutePathsFlag,
			ForceReplace:      forceReplaceFlag,
		}

		_numberOfResults = 0

		if options.ReplaceWith != "" && !options.ForceReplace {
			_renameMap = make(map[string]string)
		}

		if err := findInTree(options); err != nil {
			return err
		}

		colors.CYAN.Printf("Number of results: %d\n", _numberOfResults)
		if options.ReplaceWith != "" && !options.ForceReplace && options.Content == "" {
			response := waitResponse("Are you sure? [Yes/No] ", map[string][]string{
				"Yes": []string{"Yes", "Y", "y"},
				"No":  []string{"No", "N", "n"},
			})
			switch response {
			case "Yes":
				renamePaths(_renameMap)
			case "No":
				colors.RED.Print(response)
			}
		}

		if options.ReplaceWith != "" && !options.ForceReplace && options.Content != "" {
			response := waitResponse("Are you sure? [Yes/No] ", map[string][]string{
				"Yes": []string{"Yes", "Y", "y"},
				"No":  []string{"No", "N", "n"},
			})
			switch response {
			case "Yes":
				renamePaths(_renameMap)
			case "No":
				colors.RED.Print(response)
			}
		}

		return nil
	},
}

// Execute adds all child commands to the root command and 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() {
	colors.InitColors()

	RootCmd.Flags().StringVarP(&pathFlag, "path", "p", "", "path to directory")
	RootCmd.Flags().StringVarP(&nameFlag, "name", "n", "", "regular expression for matching file or directory name; This flag filter files if content flag is used")
	RootCmd.Flags().StringVarP(&replaceFlag, "replace", "r", "", "replaces mached regular expression parts with given value")
	RootCmd.Flags().BoolVarP(&ignoreCaseFlag, "ignore-case", "i", false, "ignore case for all regular expresions; Add '(?i)' in front of specific regex for ignore case")
	RootCmd.Flags().BoolVarP(&showAbsolutePathsFlag, "absolute-paths", "a", false, "print absolute paths in result")
	RootCmd.Flags().BoolVarP(&forceReplaceFlag, "force-replace", "f", false, "Force replace without responding")
	RootCmd.Flags().StringVarP(&contentFlag, "content", "c", "", "regular expression for matching file content")

}

func findInTree(options *findOptions) error {
	fileInfo, err := os.Stat(options.Path)
	if err != nil {
		return fmt.Errorf("could not get fileInfo for %s: %v", options.Path, err)
	}

	if fileInfo.IsDir() {
		files, err := ioutil.ReadDir(options.Path)
		if err != nil {
			return fmt.Errorf("could not read directory %s: %v", options.Path, err)
		}
		for _, file := range files {
			childOptions := options.CreateCopy()
			childOptions.Path = path.Join(options.Path, file.Name())
			findInTree(childOptions)
		}
	}

	doAction(options, fileInfo)
	return nil
}

func doAction(options *findOptions, fileInfo os.FileInfo) {
	absolutePath, err := filepath.Abs(options.Path)
	if err != nil {
		log.Fatalf("could not get absolute path: %v", err)
	}
	finalPathPrint := getPathPrintFormat(options.Path, absolutePath, options.ShowAbsolutePaths)

	if options.Name != "" && options.Content == "" {
		re := createRegex(options.Name, options.IgnoreCase)

		if re.MatchString(fileInfo.Name()) {
			_numberOfResults++
			if options.ReplaceWith != "" {
				pathDir := filepath.Dir(absolutePath)
				newFileName := re.ReplaceAllString(fileInfo.Name(), options.ReplaceWith)

				if options.ForceReplace {
					err := os.Rename(absolutePath, filepath.FromSlash(path.Join(pathDir, newFileName)))
					if err != nil {
						fmt.Printf("could not rename file: %v", err)
					}
					colors.RED.Print(absolutePath)
					colors.CYAN.Print(" => ")
					colors.GREEN.Println(filepath.FromSlash(path.Join(pathDir, newFileName)))
				} else {
					_renameMap[absolutePath] = filepath.FromSlash(path.Join(pathDir, newFileName))

					fmt.Print(absolutePath)
					colors.CYAN.Print(" => ")
					fmt.Println(filepath.FromSlash(path.Join(pathDir, newFileName)))
				}
			} else {
				fmt.Println(filepath.FromSlash(finalPathPrint))
			}
		}
	}
	if options.Content != "" {
		if options.Name != "" {
			regName := createRegex(options.Name, options.IgnoreCase)
			if regName.MatchString(fileInfo.Name()) && !fileInfo.IsDir() {
				re := createRegex(options.Content, options.IgnoreCase)

				fileBytes, err := ioutil.ReadFile(absolutePath)
				if err != nil {
					log.Fatalf("could not read file content: %v", err)
				}
				fileString := string(fileBytes)

				fileLines := strings.Split(fileString, "\n")

				printedFileName := false
				for lineNumber, line := range fileLines {
					if re.MatchString(line) {
						_numberOfResults++
						if !printedFileName {
							colors.CYAN.Printf("%s:\n", finalPathPrint)
							printedFileName = !printedFileName
						}
						allIndexes := re.FindAllStringIndex(line, -1)

						colors.YELLOW.Printf("%v:", lineNumber+1)
						location := 0
						for _, match := range allIndexes {
							fmt.Printf("%s", line[location:match[0]])
							colors.GREEN.Printf("%s", line[match[0]:match[1]])
							location = match[1]
						}
						fmt.Printf("%s", line[location:])
						fmt.Println()
					}
				}
			}
		} else {
			if !fileInfo.IsDir() {
				re := createRegex(options.Content, options.IgnoreCase)

				fileBytes, err := ioutil.ReadFile(absolutePath)
				if err != nil {
					log.Fatalf("could not read file content: %v", err)
				}
				fileString := string(fileBytes)

				fileLines := strings.Split(fileString, "\n")

				printedFileName := false
				for lineNumber, line := range fileLines {
					if re.MatchString(line) {
						_numberOfResults++
						if !printedFileName {
							colors.CYAN.Printf("%s:\n", finalPathPrint)
							printedFileName = !printedFileName
						}
						allIndexes := re.FindAllStringIndex(line, -1)

						colors.YELLOW.Printf("%v:", lineNumber+1)
						location := 0
						for _, match := range allIndexes {
							fmt.Printf("%s", line[location:match[0]])
							colors.GREEN.Printf("%s", line[match[0]:match[1]])
							location = match[1]
						}
						fmt.Printf("%s", line[location:])
						fmt.Println()
					}
				}
			}
		}
	}
}

type findOptions struct {
	Path              string
	Name              string
	Content           string
	ReplaceWith       string
	IgnoreCase        bool
	ShowAbsolutePaths bool
	ForceReplace      bool
}

func (o *findOptions) CreateCopy() *findOptions {
	newFindOptions := &findOptions{
		Path:              o.Path,
		Name:              o.Name,
		Content:           o.Content,
		ReplaceWith:       o.ReplaceWith,
		IgnoreCase:        o.IgnoreCase,
		ShowAbsolutePaths: o.ShowAbsolutePaths,
		ForceReplace:      o.ForceReplace,
	}
	return newFindOptions
}

func waitResponse(question string, responseAliases map[string][]string) string {
	colors.YELLOW.Printf("%s ", question)
	var respond string

	for {
		fmt.Scanf("%s\n", &respond)

		for response, aliases := range responseAliases {
			for _, alias := range aliases {
				if respond == alias {
					return response
				}
			}
		}

		colors.YELLOW.Printf("%s ", question)
	}
}

func renamePaths(paths map[string]string) error {
	for oldPath, newPath := range paths {
		err := os.Rename(oldPath, newPath)
		if err != nil {
			return fmt.Errorf("could not rename file: %v", err)
		}
		colors.RED.Print(oldPath)
		colors.CYAN.Print(" => ")
		colors.GREEN.Println(newPath)
	}
	return nil
}

func getPathPrintFormat(filePath, absolutePath string, showAbsolute bool) string {
	var result = ""
	if showAbsolute {
		result = absolutePath
	} else {
		result = filePath
	}
	return filepath.Clean(result)
}

func createRegex(text string, ignoreCase bool) *regexp.Regexp {
	re, err := regexp.Compile(text)
	if err != nil {
		colors.RED.Printf("regular expresion for name flag is not valid\n")
		os.Exit(1)
	}
	if ignoreCase {
		re, err = regexp.Compile("(?i)" + text)
		if err != nil {
			colors.RED.Printf("regular expresion for name flag is not valid\n")
			os.Exit(1)
		}
	}
	return re
}

func replaceContent(filePaths []string, oldContent *regexp.Regexp, newContent string, fileInfo os.FileInfo) {
	for _, filePath := range filePaths {
		fileBytes, err := ioutil.ReadFile(filePath)
		if err != nil {
			log.Fatalf("could not read file content: %v", err)
		}
		fileString := string(fileBytes)

		newFileString := oldContent.ReplaceAllString(fileString, newContent)

		err = ioutil.WriteFile(filePath, []byte(newFileString), fileInfo.Mode())
		if err != nil {
			fmt.Printf("could not write to file: %v", err)
		} else {
			colors.GREEN.Printf("%s\n", filePath)
		}
	}
}
<commit_msg>replace content created<commit_after>// Copyright © 2017 Mladen Popadic <mladen.popadic.4@gmail.com>

package cmd

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/mpopadic/go_n_find/colors"
	"github.com/spf13/cobra"
)

var (
	pathFlag              string
	nameFlag              string
	replaceFlag           string
	ignoreCaseFlag        bool
	showAbsolutePathsFlag bool
	forceReplaceFlag      bool
	contentFlag           string
)

var (
	_numberOfResults     int
	_renameMap           map[string]string
	_replaceContentFiles []string
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "go_n_find",
	Short: "CLI for finding files and folders",
	Long:  `CLI tool for finding files and folders by name or content`,
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if pathFlag == "" {
			return fmt.Errorf("path flag is required")
		}
		if nameFlag == "" && contentFlag == "" {
			return fmt.Errorf("name flag or content flag are required")
		}
		return nil
	},
	// Uncomment the following line if your bare application
	// has an action associated with it:
	RunE: func(cmd *cobra.Command, args []string) error {

		// Set findOptions
		options := &findOptions{
			Path:              pathFlag,
			Name:              nameFlag,
			Content:           contentFlag,
			ReplaceWith:       replaceFlag,
			IgnoreCase:        ignoreCaseFlag,
			ShowAbsolutePaths: showAbsolutePathsFlag,
			ForceReplace:      forceReplaceFlag,
		}

		_numberOfResults = 0

		if options.ReplaceWith != "" && !options.ForceReplace {
			_renameMap = make(map[string]string)
		}

		if err := findInTree(options); err != nil {
			return err
		}

		colors.CYAN.Printf("Number of results: %d\n", _numberOfResults)
		if options.ReplaceWith != "" && !options.ForceReplace && options.Content == "" {
			response := waitResponse("Are you sure? [Yes/No] ", map[string][]string{
				"Yes": []string{"Yes", "Y", "y"},
				"No":  []string{"No", "N", "n"},
			})
			switch response {
			case "Yes":
				renamePaths(_renameMap)
			case "No":
				colors.RED.Print(response)
			}
		}

		if options.ReplaceWith != "" && !options.ForceReplace && options.Content != "" {
			response := waitResponse("Are you sure? [Yes/No] ", map[string][]string{
				"Yes": []string{"Yes", "Y", "y"},
				"No":  []string{"No", "N", "n"},
			})
			switch response {
			case "Yes":
				reg, err := regexp.Compile(options.Content)
				if err != nil {
					colors.RED.Printf("invalid content regular expresion\n")
					os.Exit(1)
				}
				replaceContent(_replaceContentFiles, reg, options.ReplaceWith)
			case "No":
				colors.RED.Print(response)
			}
		}

		return nil
	},
}

// Execute adds all child commands to the root command and 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() {
	colors.InitColors()

	RootCmd.Flags().StringVarP(&pathFlag, "path", "p", "", "path to directory")
	RootCmd.Flags().StringVarP(&nameFlag, "name", "n", "", "regular expression for matching file or directory name; This flag filter files if content flag is used")
	RootCmd.Flags().StringVarP(&replaceFlag, "replace", "r", "", "replaces mached regular expression parts with given value")
	RootCmd.Flags().BoolVarP(&ignoreCaseFlag, "ignore-case", "i", false, "ignore case for all regular expresions; Add '(?i)' in front of specific regex for ignore case")
	RootCmd.Flags().BoolVarP(&showAbsolutePathsFlag, "absolute-paths", "a", false, "print absolute paths in result")
	RootCmd.Flags().BoolVarP(&forceReplaceFlag, "force-replace", "f", false, "Force replace without responding")
	RootCmd.Flags().StringVarP(&contentFlag, "content", "c", "", "regular expression for matching file content")

}

func findInTree(options *findOptions) error {
	fileInfo, err := os.Stat(options.Path)
	if err != nil {
		return fmt.Errorf("could not get fileInfo for %s: %v", options.Path, err)
	}

	if fileInfo.IsDir() {
		files, err := ioutil.ReadDir(options.Path)
		if err != nil {
			return fmt.Errorf("could not read directory %s: %v", options.Path, err)
		}
		for _, file := range files {
			childOptions := options.CreateCopy()
			childOptions.Path = path.Join(options.Path, file.Name())
			findInTree(childOptions)
		}
	}

	doAction(options, fileInfo)
	return nil
}

func doAction(options *findOptions, fileInfo os.FileInfo) {
	absolutePath, err := filepath.Abs(options.Path)
	if err != nil {
		log.Fatalf("could not get absolute path: %v", err)
	}
	finalPathPrint := getPathPrintFormat(options.Path, absolutePath, options.ShowAbsolutePaths)

	if options.Name != "" && options.Content == "" {
		re := createRegex(options.Name, options.IgnoreCase)

		if re.MatchString(fileInfo.Name()) {
			_numberOfResults++
			if options.ReplaceWith != "" {
				pathDir := filepath.Dir(absolutePath)
				newFileName := re.ReplaceAllString(fileInfo.Name(), options.ReplaceWith)

				if options.ForceReplace {
					err := os.Rename(absolutePath, filepath.FromSlash(path.Join(pathDir, newFileName)))
					if err != nil {
						fmt.Printf("could not rename file: %v", err)
					}
					colors.RED.Print(absolutePath)
					colors.CYAN.Print(" => ")
					colors.GREEN.Println(filepath.FromSlash(path.Join(pathDir, newFileName)))
				} else {
					_renameMap[absolutePath] = filepath.FromSlash(path.Join(pathDir, newFileName))

					fmt.Print(absolutePath)
					colors.CYAN.Print(" => ")
					fmt.Println(filepath.FromSlash(path.Join(pathDir, newFileName)))
				}
			} else {
				fmt.Println(filepath.FromSlash(finalPathPrint))
			}
		}
	}
	if options.Content != "" {
		if options.Name != "" {
			regName := createRegex(options.Name, options.IgnoreCase)
			if regName.MatchString(fileInfo.Name()) && !fileInfo.IsDir() {
				_replaceContentFiles = append(_replaceContentFiles, absolutePath)
				re := createRegex(options.Content, options.IgnoreCase)

				fileBytes, err := ioutil.ReadFile(absolutePath)
				if err != nil {
					log.Fatalf("could not read file content: %v", err)
				}
				fileString := string(fileBytes)

				fileLines := strings.Split(fileString, "\n")

				printedFileName := false
				for lineNumber, line := range fileLines {
					if re.MatchString(line) {
						_numberOfResults++
						if !printedFileName {
							colors.CYAN.Printf("%s:\n", finalPathPrint)
							printedFileName = !printedFileName
						}
						allIndexes := re.FindAllStringIndex(line, -1)

						colors.YELLOW.Printf("%v:", lineNumber+1)
						location := 0
						for _, match := range allIndexes {
							fmt.Printf("%s", line[location:match[0]])
							colors.GREEN.Printf("%s", line[match[0]:match[1]])
							location = match[1]
						}
						fmt.Printf("%s", line[location:])
						fmt.Println()
					}
				}
			}
		} else {
			if !fileInfo.IsDir() {
				_replaceContentFiles = append(_replaceContentFiles, absolutePath)
				re := createRegex(options.Content, options.IgnoreCase)

				fileBytes, err := ioutil.ReadFile(absolutePath)
				if err != nil {
					log.Fatalf("could not read file content: %v", err)
				}
				fileString := string(fileBytes)

				fileLines := strings.Split(fileString, "\n")

				printedFileName := false
				for lineNumber, line := range fileLines {
					if re.MatchString(line) {
						_numberOfResults++
						if !printedFileName {
							colors.CYAN.Printf("%s:\n", finalPathPrint)
							printedFileName = !printedFileName
						}
						allIndexes := re.FindAllStringIndex(line, -1)

						colors.YELLOW.Printf("%v:", lineNumber+1)
						location := 0
						for _, match := range allIndexes {
							fmt.Printf("%s", line[location:match[0]])
							colors.GREEN.Printf("%s", line[match[0]:match[1]])
							location = match[1]
						}
						fmt.Printf("%s", line[location:])
						fmt.Println()
					}
				}
			}
		}
	}
}

type findOptions struct {
	Path              string
	Name              string
	Content           string
	ReplaceWith       string
	IgnoreCase        bool
	ShowAbsolutePaths bool
	ForceReplace      bool
}

func (o *findOptions) CreateCopy() *findOptions {
	newFindOptions := &findOptions{
		Path:              o.Path,
		Name:              o.Name,
		Content:           o.Content,
		ReplaceWith:       o.ReplaceWith,
		IgnoreCase:        o.IgnoreCase,
		ShowAbsolutePaths: o.ShowAbsolutePaths,
		ForceReplace:      o.ForceReplace,
	}
	return newFindOptions
}

func waitResponse(question string, responseAliases map[string][]string) string {
	colors.YELLOW.Printf("%s ", question)
	var respond string

	for {
		fmt.Scanf("%s\n", &respond)

		for response, aliases := range responseAliases {
			for _, alias := range aliases {
				if respond == alias {
					return response
				}
			}
		}

		colors.YELLOW.Printf("%s ", question)
	}
}

func renamePaths(paths map[string]string) error {
	for oldPath, newPath := range paths {
		err := os.Rename(oldPath, newPath)
		if err != nil {
			return fmt.Errorf("could not rename file: %v", err)
		}
		colors.RED.Print(oldPath)
		colors.CYAN.Print(" => ")
		colors.GREEN.Println(newPath)
	}
	return nil
}

func getPathPrintFormat(filePath, absolutePath string, showAbsolute bool) string {
	var result = ""
	if showAbsolute {
		result = absolutePath
	} else {
		result = filePath
	}
	return filepath.Clean(result)
}

func createRegex(text string, ignoreCase bool) *regexp.Regexp {
	re, err := regexp.Compile(text)
	if err != nil {
		colors.RED.Printf("regular expresion for name flag is not valid\n")
		os.Exit(1)
	}
	if ignoreCase {
		re, err = regexp.Compile("(?i)" + text)
		if err != nil {
			colors.RED.Printf("regular expresion for name flag is not valid\n")
			os.Exit(1)
		}
	}
	return re
}

func replaceContent(filePaths []string, oldContent *regexp.Regexp, newContent string) {
	for _, filePath := range filePaths {

		fileInfo, err := os.Stat(filePath)
		if err != nil {
			log.Fatalf("could not get file info; %v", err)
		}
		fileBytes, err := ioutil.ReadFile(filePath)
		if err != nil {
			log.Fatalf("could not read file content: %v", err)
		}
		fileString := string(fileBytes)

		newFileString := oldContent.ReplaceAllString(fileString, newContent)

		err = ioutil.WriteFile(filePath, []byte(newFileString), fileInfo.Mode())
		if err != nil {
			fmt.Printf("could not write to file: %v", err)
		} else {
			colors.GREEN.Printf("%s\n", filePath)
		}
	}
}
<|endoftext|>


<commit_before>package cmd

import "github.com/spf13/cobra"

//RootCmd main cmd entrypoint
var RootCmd = &cobra.Command{
	Use: "chkit",
}
<commit_msg>add debug flag<commit_after>package cmd

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

//RootCmd main cmd entrypoint
var RootCmd = &cobra.Command{
	Use: "chkit",
	Run: func(cmd *cobra.Command, args []string) {
		if cmd.Flags().NFlag() == 0 {
			cmd.Usage()
		}
		var err error
		debug, err = cmd.Flags().GetBool("debug")
		if err != nil {
			jww.ERROR.Println(err)
			return
		}
	},
}

var debug bool

func init() {
	RootCmd.PersistentFlags().BoolP("debug", "d", false, "turn on debugging messages")
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"time"

	"github.com/evandroflores/claimr/model"
	"github.com/evandroflores/claimr/utils"
	"github.com/shomali11/slacker"
	log "github.com/sirupsen/logrus"
)

func init() {
	Register("show <container-name>", "Shows a container details.", show)
}

func show(request *slacker.Request, response slacker.ResponseWriter) {
	response.Typing()

	isDirect, msg := checkDirect(request.Event.Channel)
	if isDirect {
		response.Reply(msg.Error())
		return
	}

	containerName := request.Param("container-name")

	container, err := model.GetContainer(request.Event.Team, request.Event.Channel, containerName)

	if err != nil {
		log.Errorf("SHOW. [%s, %s, %s] %s", request.Event.Team, request.Event.Channel, containerName, err)
		response.Reply(err.Error())
		return
	}

	if container == (model.Container{}) {
		response.Reply(fmt.Sprintf("I couldn't find the container `%s` on <#%s>.", containerName, request.Event.Channel))
		return
	}

	text := fmt.Sprintf("Container `%s`.\nCreated by <@%s>.\n", containerName, container.CreatedByUser)

	if container.InUseBy == "" {
		text += "_Available_"
	} else {
		text += fmt.Sprintf("In use by <@%s>%s", container.InUseBy,
			utils.IfThenElse(container.InUseForReason != "", fmt.Sprintf(" for %s", container.InUseForReason), ""))
	}
	text += fmt.Sprintf(" since _%s_.", container.UpdatedAt.Format(time.RFC1123))
	response.Reply(text)
}
<commit_msg>Changing how to get event cmd.show<commit_after>package cmd

import (
	"fmt"
	"time"

	"github.com/evandroflores/claimr/model"
	"github.com/evandroflores/claimr/utils"
	"github.com/shomali11/slacker"
	log "github.com/sirupsen/logrus"
)

func init() {
	Register("show <container-name>", "Shows a container details.", show)
}

func show(request *slacker.Request, response slacker.ResponseWriter) {
	response.Typing()

	event := getEvent(request)
	isDirect, msg := checkDirect(event.Channel)
	if isDirect {
		response.Reply(msg.Error())
		return
	}

	containerName := request.Param("container-name")

	container, err := model.GetContainer(event.Team, event.Channel, containerName)

	if err != nil {
		log.Errorf("SHOW. [%s, %s, %s] %s", event.Team, event.Channel, containerName, err)
		response.Reply(err.Error())
		return
	}

	if container == (model.Container{}) {
		response.Reply(fmt.Sprintf("I couldn't find the container `%s` on <#%s>.", containerName, event.Channel))
		return
	}

	text := fmt.Sprintf("Container `%s`.\nCreated by <@%s>.\n", containerName, container.CreatedByUser)

	if container.InUseBy == "" {
		text += "_Available_"
	} else {
		text += fmt.Sprintf("In use by <@%s>%s", container.InUseBy,
			utils.IfThenElse(container.InUseForReason != "", fmt.Sprintf(" for %s", container.InUseForReason), ""))
	}
	text += fmt.Sprintf(" since _%s_.", container.UpdatedAt.Format(time.RFC1123))
	response.Reply(text)
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strings"

	"github.com/aquasecurity/kube-bench/check"
	"github.com/fatih/color"
	"github.com/golang/glog"
	"github.com/spf13/viper"
)

var (
	// Print colors
	colors = map[check.State]*color.Color{
		check.PASS: color.New(color.FgGreen),
		check.FAIL: color.New(color.FgRed),
		check.WARN: color.New(color.FgYellow),
		check.INFO: color.New(color.FgBlue),
	}
)

var psFunc func(string) string
var statFunc func(string) (os.FileInfo, error)

func init() {
	psFunc = ps
	statFunc = os.Stat
}

func printlnWarn(msg string) {
	fmt.Fprintf(os.Stderr, "[%s] %s\n",
		colors[check.WARN].Sprintf("%s", check.WARN),
		msg,
	)
}

func sprintlnWarn(msg string) string {
	return fmt.Sprintf("[%s] %s",
		colors[check.WARN].Sprintf("%s", check.WARN),
		msg,
	)
}

func exitWithError(err error) {
	fmt.Fprintf(os.Stderr, "\n%v\n", err)
	os.Exit(1)
}

func continueWithError(err error, msg string) string {
	if err != nil {
		glog.V(2).Info(err)
	}

	if msg != "" {
		fmt.Fprintf(os.Stderr, "%s\n", msg)
	}

	return ""
}

func cleanIDs(list string) []string {
	list = strings.Trim(list, ",")
	ids := strings.Split(list, ",")

	for _, id := range ids {
		id = strings.Trim(id, " ")
	}

	return ids
}

// ps execs out to the ps command; it's separated into a function so we can write tests
func ps(proc string) string {
	cmd := exec.Command("ps", "-C", proc, "-o", "cmd", "--no-headers")
	out, err := cmd.Output()
	if err != nil {
		continueWithError(fmt.Errorf("%s: %s", cmd.Args, err), "")
	}

	return string(out)
}

// getBinaries finds which of the set of candidate executables are running
func getBinaries(v *viper.Viper) map[string]string {
	binmap := make(map[string]string)

	for _, component := range v.GetStringSlice("components") {
		s := v.Sub(component)
		if s == nil {
			continue
		}

		optional := s.GetBool("optional")
		bins := s.GetStringSlice("bins")
		if len(bins) > 0 {
			bin, err := findExecutable(bins)
			if err != nil && !optional {
				exitWithError(fmt.Errorf("need %s executable but none of the candidates are running", component))
			}

			// Default the executable name that we'll substitute to the name of the component
			if bin == "" {
				bin = component
				glog.V(2).Info(fmt.Sprintf("Component %s not running", component))
			} else {
				glog.V(2).Info(fmt.Sprintf("Component %s uses running binary %s", component, bin))
			}
			binmap[component] = bin
		}
	}

	return binmap
}

// getConfigFiles finds which of the set of candidate config files exist
// accepts a string 't' which indicates the type of config file, conf,
// podspec or untifile.
func getConfigFiles(v *viper.Viper, t string) map[string]string {
	confmap := make(map[string]string)

	for _, component := range v.GetStringSlice("components") {
		s := v.Sub(component)
		if s == nil {
			continue
		}

		// See if any of the candidate config files exist
		conf := findConfigFile(s.GetStringSlice(t + "s"))
		if conf == "" {
			if s.IsSet("default" + t) {
				conf = s.GetString("default" + t)
				glog.V(2).Info(fmt.Sprintf("Using default config file name '%s' for component %s", conf, component))
			} else {
				// Default the config file name that we'll substitute to the name of the component
				printlnWarn(fmt.Sprintf("Missing config file for %s", component))
				conf = component
			}
		} else {
			glog.V(2).Info(fmt.Sprintf("Component %s uses config file '%s'", component, conf))
		}

		confmap[component] = conf
	}

	return confmap
}

// verifyBin checks that the binary specified is running
func verifyBin(bin string) bool {

	// Strip any quotes
	bin = strings.Trim(bin, "'\"")

	// bin could consist of more than one word
	// We'll search for running processes with the first word, and then check the whole
	// proc as supplied is included in the results
	proc := strings.Fields(bin)[0]
	out := psFunc(proc)

	// There could be multiple lines in the ps output
	// The binary needs to be the first word in the ps output, except that it could be preceded by a path
	// e.g. /usr/bin/kubelet is a match for kubelet
	// but apiserver is not a match for kube-apiserver
	reFirstWord := regexp.MustCompile(`^(\S*\/)*` + bin)
	lines := strings.Split(out, "\n")
	for _, l := range lines {
		if reFirstWord.Match([]byte(l)) {
			return true
		}
	}

	return false
}

// fundConfigFile looks through a list of possible config files and finds the first one that exists
func findConfigFile(candidates []string) string {
	for _, c := range candidates {
		_, err := statFunc(c)
		if err == nil {
			return c
		}
		if !os.IsNotExist(err) {
			exitWithError(fmt.Errorf("error looking for file %s: %v", c, err))
		}
	}

	return ""
}

// findExecutable looks through a list of possible executable names and finds the first one that's running
func findExecutable(candidates []string) (string, error) {
	for _, c := range candidates {
		if verifyBin(c) {
			return c, nil
		} else {
			glog.V(1).Info(fmt.Sprintf("executable '%s' not running", c))
		}
	}

	return "", fmt.Errorf("no candidates running")
}

func multiWordReplace(s string, subname string, sub string) string {
	f := strings.Fields(sub)
	if len(f) > 1 {
		sub = "'" + sub + "'"
	}

	return strings.Replace(s, subname, sub, -1)
}

func getKubeVersion() string {
	var ver string
	var matched bool

	failmsg := "kubernetes version check failed"
	// These executables might not be on the user's path.
	_, err := exec.LookPath("kubectl")
	if err != nil {
		continueWithError(err, failmsg)
	}

	cmd := exec.Command("kubectl", "version", "--short")
	out, err := cmd.CombinedOutput()
	if err != nil {
		continueWithError(fmt.Errorf("%s", out), "")
	}

	serverVersionRe := regexp.MustCompile(`Server Version: v(\d+.\d+)`)
	subs := serverVersionRe.FindStringSubmatch(string(out))
	if len(subs) > 2 {
		ver = string(subs[1])
		validVersionPttn := `\d.\d`
		if matched, _ = regexp.MatchString(validVersionPttn, ver); !matched {
			continueWithError(fmt.Errorf("%s: invalid server version ", ver), failmsg)
		}
	}

	if ver == "" || !matched {
		printlnWarn(fmt.Sprintf("Unable to get kubectl version, using default version: %s", defaultKubeVersion))
		ver = defaultKubeVersion
	}

	return ver
}

func makeSubstitutions(s string, ext string, m map[string]string) string {
	for k, v := range m {
		subst := "$" + k + ext
		if v == "" {
			glog.V(2).Info(fmt.Sprintf("No subsitution for '%s'\n", subst))
			continue
		}
		glog.V(1).Info(fmt.Sprintf("Substituting %s with '%s'\n", subst, v))
		s = multiWordReplace(s, subst, v)
	}

	return s
}
<commit_msg>Fix bug causing kubectl version to always return default version.<commit_after>package cmd

import (
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strings"

	"github.com/aquasecurity/kube-bench/check"
	"github.com/fatih/color"
	"github.com/golang/glog"
	"github.com/spf13/viper"
)

var (
	// Print colors
	colors = map[check.State]*color.Color{
		check.PASS: color.New(color.FgGreen),
		check.FAIL: color.New(color.FgRed),
		check.WARN: color.New(color.FgYellow),
		check.INFO: color.New(color.FgBlue),
	}
)

var psFunc func(string) string
var statFunc func(string) (os.FileInfo, error)

func init() {
	psFunc = ps
	statFunc = os.Stat
}

func printlnWarn(msg string) {
	fmt.Fprintf(os.Stderr, "[%s] %s\n",
		colors[check.WARN].Sprintf("%s", check.WARN),
		msg,
	)
}

func sprintlnWarn(msg string) string {
	return fmt.Sprintf("[%s] %s",
		colors[check.WARN].Sprintf("%s", check.WARN),
		msg,
	)
}

func exitWithError(err error) {
	fmt.Fprintf(os.Stderr, "\n%v\n", err)
	os.Exit(1)
}

func continueWithError(err error, msg string) string {
	if err != nil {
		glog.V(2).Info(err)
	}

	if msg != "" {
		fmt.Fprintf(os.Stderr, "%s\n", msg)
	}

	return ""
}

func cleanIDs(list string) []string {
	list = strings.Trim(list, ",")
	ids := strings.Split(list, ",")

	for _, id := range ids {
		id = strings.Trim(id, " ")
	}

	return ids
}

// ps execs out to the ps command; it's separated into a function so we can write tests
func ps(proc string) string {
	cmd := exec.Command("ps", "-C", proc, "-o", "cmd", "--no-headers")
	out, err := cmd.Output()
	if err != nil {
		continueWithError(fmt.Errorf("%s: %s", cmd.Args, err), "")
	}

	return string(out)
}

// getBinaries finds which of the set of candidate executables are running
func getBinaries(v *viper.Viper) map[string]string {
	binmap := make(map[string]string)

	for _, component := range v.GetStringSlice("components") {
		s := v.Sub(component)
		if s == nil {
			continue
		}

		optional := s.GetBool("optional")
		bins := s.GetStringSlice("bins")
		if len(bins) > 0 {
			bin, err := findExecutable(bins)
			if err != nil && !optional {
				exitWithError(fmt.Errorf("need %s executable but none of the candidates are running", component))
			}

			// Default the executable name that we'll substitute to the name of the component
			if bin == "" {
				bin = component
				glog.V(2).Info(fmt.Sprintf("Component %s not running", component))
			} else {
				glog.V(2).Info(fmt.Sprintf("Component %s uses running binary %s", component, bin))
			}
			binmap[component] = bin
		}
	}

	return binmap
}

// getConfigFiles finds which of the set of candidate config files exist
// accepts a string 't' which indicates the type of config file, conf,
// podspec or untifile.
func getConfigFiles(v *viper.Viper, t string) map[string]string {
	confmap := make(map[string]string)

	for _, component := range v.GetStringSlice("components") {
		s := v.Sub(component)
		if s == nil {
			continue
		}

		// See if any of the candidate config files exist
		conf := findConfigFile(s.GetStringSlice(t + "s"))
		if conf == "" {
			if s.IsSet("default" + t) {
				conf = s.GetString("default" + t)
				glog.V(2).Info(fmt.Sprintf("Using default config file name '%s' for component %s", conf, component))
			} else {
				// Default the config file name that we'll substitute to the name of the component
				printlnWarn(fmt.Sprintf("Missing config file for %s", component))
				conf = component
			}
		} else {
			glog.V(2).Info(fmt.Sprintf("Component %s uses config file '%s'", component, conf))
		}

		confmap[component] = conf
	}

	return confmap
}

// verifyBin checks that the binary specified is running
func verifyBin(bin string) bool {

	// Strip any quotes
	bin = strings.Trim(bin, "'\"")

	// bin could consist of more than one word
	// We'll search for running processes with the first word, and then check the whole
	// proc as supplied is included in the results
	proc := strings.Fields(bin)[0]
	out := psFunc(proc)

	// There could be multiple lines in the ps output
	// The binary needs to be the first word in the ps output, except that it could be preceded by a path
	// e.g. /usr/bin/kubelet is a match for kubelet
	// but apiserver is not a match for kube-apiserver
	reFirstWord := regexp.MustCompile(`^(\S*\/)*` + bin)
	lines := strings.Split(out, "\n")
	for _, l := range lines {
		if reFirstWord.Match([]byte(l)) {
			return true
		}
	}

	return false
}

// fundConfigFile looks through a list of possible config files and finds the first one that exists
func findConfigFile(candidates []string) string {
	for _, c := range candidates {
		_, err := statFunc(c)
		if err == nil {
			return c
		}
		if !os.IsNotExist(err) {
			exitWithError(fmt.Errorf("error looking for file %s: %v", c, err))
		}
	}

	return ""
}

// findExecutable looks through a list of possible executable names and finds the first one that's running
func findExecutable(candidates []string) (string, error) {
	for _, c := range candidates {
		if verifyBin(c) {
			return c, nil
		} else {
			glog.V(1).Info(fmt.Sprintf("executable '%s' not running", c))
		}
	}

	return "", fmt.Errorf("no candidates running")
}

func multiWordReplace(s string, subname string, sub string) string {
	f := strings.Fields(sub)
	if len(f) > 1 {
		sub = "'" + sub + "'"
	}

	return strings.Replace(s, subname, sub, -1)
}

func getKubeVersion() string {
	var ver string
	var matched bool

	failmsg := "kubernetes version check failed"
	// These executables might not be on the user's path.
	_, err := exec.LookPath("kubectl")
	if err != nil {
		continueWithError(err, failmsg)
	}

	cmd := exec.Command("kubectl", "version", "--short")
	out, err := cmd.CombinedOutput()
	if err != nil {
		continueWithError(fmt.Errorf("%s", out), "")
	}

	serverVersionRe := regexp.MustCompile(`Server Version: v(\d+.\d+)`)
	subs := serverVersionRe.FindStringSubmatch(string(out))
	if len(subs) == 2 {
		ver = string(subs[1])
		validVersionPttn := `\d.\d`
		if matched, _ = regexp.MatchString(validVersionPttn, ver); !matched {
			continueWithError(fmt.Errorf("%s: invalid server version ", ver), failmsg)
		}
	}

	if ver == "" || !matched {
		printlnWarn(fmt.Sprintf("Unable to get kubectl version, using default version: %s", defaultKubeVersion))
		ver = defaultKubeVersion
	}

	return ver
}

func makeSubstitutions(s string, ext string, m map[string]string) string {
	for k, v := range m {
		subst := "$" + k + ext
		if v == "" {
			glog.V(2).Info(fmt.Sprintf("No subsitution for '%s'\n", subst))
			continue
		}
		glog.V(1).Info(fmt.Sprintf("Substituting %s with '%s'\n", subst, v))
		s = multiWordReplace(s, subst, v)
	}

	return s
}
<|endoftext|>


<commit_before>package intercept_parse

import (
    "encoding/hex"
    "io"
    "log"
    "os"

    "chunkymonkey/proto"
    .   "chunkymonkey/types"
)

// Hex dumps the input to the log
func (p *MessageParser) dumpInput(logPrefix string, reader io.Reader) {
    buf := make([]byte, 16, 16)
    for {
        _, err := io.ReadAtLeast(reader, buf, 1)
        if err != nil {
            return
        }

        hexData := hex.EncodeToString(buf)
        p.printf("Unparsed data: %s", hexData)
    }
}

// Consumes data from reader until an error occurs
func (p *MessageParser) consumeUnrecognizedInput(reader io.Reader) {
    p.printf("Lost packet sync. Ignoring further data.")
    buf := make([]byte, 4096)
    for {
        _, err := io.ReadAtLeast(reader, buf, 1)
        if err != nil {
            return
        }
    }
}

type MessageParser struct {
    logPrefix string
}

func (p *MessageParser) printf(format string, v ...interface{}) {
    log.Printf(p.logPrefix+format, v...)
}

func (p *MessageParser) PacketKeepAlive() {
    // Not logging this packet as it's a bit spammy
}

func (p *MessageParser) PacketChatMessage(message string) {
    p.printf("PacketChatMessage(%s)", message)
}

func (p *MessageParser) PacketRespawn() {
    p.printf("PacketRespawn()")
}

func (p *MessageParser) PacketPlayer(onGround bool) {
    // Not logging this packet as it's a bit spammy
}

func (p *MessageParser) PacketPlayerPosition(position *AbsXYZ, stance AbsCoord, onGround bool) {
    p.printf("PacketPlayerPosition(position=%v, stance=%v, onGround=%v)", position, stance, onGround)
}

func (p *MessageParser) PacketPlayerLook(look *LookDegrees, onGround bool) {
    p.printf("PacketPlayerLook(look=%v, onGround=%v)", look, onGround)
}

func (p *MessageParser) PacketPlayerDigging(status DigStatus, blockLoc *BlockXYZ, face Face) {
    p.printf("PacketPlayerDigging(status=%v, blockLoc=%v, face=%v)", status, blockLoc, face)
}

func (p *MessageParser) PacketPlayerBlockPlacement(itemID ItemID, blockLoc *BlockXYZ, face Face, amount ItemCount, uses ItemUses) {
    p.printf("PacketPlayerBlockPlacement(itemId=%d, blockLoc=%v, face=%d, amount=%d, uses=%d)",
        itemID, blockLoc, face, amount, uses)
}

func (p *MessageParser) PacketHoldingChange(itemID ItemID) {
    p.printf("PacketHoldingChange(%d)", itemID)
}

func (p *MessageParser) PacketEntityAnimation(entityID EntityID, animation EntityAnimation) {
    p.printf("PacketEntityAnimation(%v)", animation)
}

func (p *MessageParser) PacketEntityAction(entityID EntityID, action EntityAction) {
    p.printf("PacketEntityAction(entityID=%d, action=%d)",
        entityID, action)
}

func (p *MessageParser) PacketSignUpdate(position *BlockXYZ, lines [4]string) {
    p.printf("PacketSignUpdate(position=%v, lines=%v)",
        position, lines)
}

func (p *MessageParser) PacketDisconnect(reason string) {
    p.printf("PacketDisconnect(%s)", reason)
}

func (p *MessageParser) ClientPacketLogin(entityID EntityID, mapSeed RandomSeed, dimension DimensionID) {
    p.printf("PacketLogin(entityID=%d, mapSeed=%d, dimension=%d)",
        entityID, mapSeed, dimension)
}

func (p *MessageParser) PacketTimeUpdate(time TimeOfDay) {
    p.printf("PacketTime(time=%d)", time)
}

func (p *MessageParser) PacketEntityEquipment(entityID EntityID, slot SlotID, itemID ItemID, uses ItemUses) {
    p.printf("PacketEntityEquipment(entityID=%d, slot=%d, itemID=%d, uses=%d)",
        entityID, slot, itemID, uses)
}

func (p *MessageParser) PacketSpawnPosition(position *BlockXYZ) {
    p.printf("PacketSpawnPosition(position=%v)", position)
}

func (p *MessageParser) PacketUseEntity(user EntityID, target EntityID, leftClick bool) {
    p.printf("PacketUseEntity(user=%d, target=%d, leftClick=%v)", user, target, leftClick)
}

func (p *MessageParser) PacketUpdateHealth(health int16) {
    p.printf("PacketUpdateHealth(health=%d)", health)
}

func (p *MessageParser) PacketNamedEntitySpawn(entityID EntityID, name string, position *AbsIntXYZ, look *LookBytes, currentItem ItemID) {
    p.printf("PacketNamedEntitySpawn(entityID=%d, name=%v, position=%v, look=%v, currentItem=%d)",
        entityID, name, position, look, currentItem)
}

func (p *MessageParser) PacketItemSpawn(entityID EntityID, itemID ItemID, count ItemCount, uses ItemUses, location *AbsIntXYZ, yaw, pitch, roll AngleBytes) {
    p.printf("PacketItemSpawn(entityID=%d, itemID=%d, count=%d, uses=%d, location=%v, yaw=%d, pitch=%d, roll=%d)",
        entityID, itemID, count, uses, location, yaw, pitch, roll)
}

func (p *MessageParser) PacketItemCollect(collectedItem EntityID, collector EntityID) {
    p.printf("PacketItemCollect(collectedItem=%d, collector=%d)",
        collectedItem, collector)
}

func (p *MessageParser) PacketObjectSpawn(entityID EntityID, objType ObjTypeID, position *AbsIntXYZ) {
    p.printf("PacketObjectSpawn(entityID=%d, objType=%d, position=%v)",
        entityID, objType, position)
}

func (p *MessageParser) PacketEntitySpawn(entityID EntityID, mobType EntityMobType, position *AbsIntXYZ, yaw AngleBytes, pitch AngleBytes, metadata []proto.EntityMetadata) {
    p.printf("PacketEntitySpawn(entityID=%d, mobType=%d, position=%v, yaw=%d, pitch=%d, metadata=%v)",
        entityID, mobType, position, yaw, pitch, metadata)
}

func (p *MessageParser) PacketUnknownX19(field1 int32, field2 string, field3, field4, field5, field6 int32) {
    p.printf("PacketUnknownX19(field1=%d, field2=%v, field3=%d, field4=%d, field5=%d, field6=%d)",
        field1, field2, field3, field4, field5, field6)
}

func (p *MessageParser) PacketPaintingSpawn(entityID EntityID, title string, position *BlockXYZ, paintingType PaintingTypeID) {
    p.printf("PacketPaintingSpawn(entityID=%d, title=%s, position=%v, paintingType=%d)",
        entityID, title, position, position, paintingType)
}

func (p *MessageParser) PacketEntityVelocity(entityID EntityID, velocity *Velocity) {
    p.printf("PacketEntityVelocity(entityID=%d, velocity=%v)",
        entityID, velocity)
}

func (p *MessageParser) PacketEntityDestroy(entityID EntityID) {
    p.printf("PacketEntityDestroy(entityID=%d)", entityID)
}

func (p *MessageParser) PacketEntity(entityID EntityID) {
    p.printf("PacketEntity(entityID=%d)", entityID)
}

func (p *MessageParser) PacketEntityRelMove(entityID EntityID, movement *RelMove) {
    p.printf("PacketEntityRelMove(entityID=%d, movement=%v)",
        entityID, movement)
}

func (p *MessageParser) PacketEntityLook(entityID EntityID, yaw, pitch AngleBytes) {
    p.printf("PacketEntityLook(entityID=%d, yaw=%d, pitch=%d)",
        entityID, yaw, pitch)
}

func (p *MessageParser) PacketEntityTeleport(entityID EntityID, position *AbsIntXYZ, look *LookBytes) {
    p.printf("PacketEntityTeleport(entityID=%d, position=%v, look=%v",
        entityID, position, look)
}

func (p *MessageParser) PacketEntityStatus(entityID EntityID, status EntityStatus) {
    p.printf("PacketEntityStatus(entityID=%d, status=%d",
        entityID, status)
}

func (p *MessageParser) PacketEntityMetadata(entityID EntityID, metadata []proto.EntityMetadata) {
    p.printf("PacketEntityMetadata(entityID=%d, metadata=%v)", entityID, metadata)
}

func (p *MessageParser) PacketPreChunk(position *ChunkXZ, mode ChunkLoadMode) {
    p.printf("PacketPreChunk(position=%v, mode=%d)", position, mode)
}

func (p *MessageParser) PacketMapChunk(position *BlockXYZ, size *SubChunkSize, data []byte) {
    p.printf("PacketMapChunk(position=%v, size=%v, len(data)=%d)",
        position, size, len(data))
}

func (p *MessageParser) PacketBlockChangeMulti(chunkLoc *ChunkXZ, blockCoords []SubChunkXYZ, blockTypes []BlockID, blockMetaData []byte) {
    p.printf("PacketBlockChangeMulti(chunkLoc=%v, blockCoords=%v, blockTypes=%v, blockMetaData=%v)",
        chunkLoc, blockCoords, blockTypes, blockMetaData)
}

func (p *MessageParser) PacketBlockChange(blockLoc *BlockXYZ, blockType BlockID, blockMetaData byte) {
    p.printf("PacketBlockChange(blockLoc=%v, blockType=%d, blockMetaData=%d)",
        blockLoc, blockType, blockMetaData)
}

func (p *MessageParser) PacketNoteBlockPlay(position *BlockXYZ, instrument InstrumentID, pitch NotePitch) {
    p.printf("PacketNoteBlockPlay(position=%v, instrument=%d, pitch=%d)",
        position, instrument, pitch)
}

func (p *MessageParser) PacketExplosion(position *AbsXYZ, power float32, blockOffsets []proto.ExplosionOffsetXYZ) {
    p.printf("PacketExplosion(position=%v, power=%f, blockOffsets=%v)",
        position, power, blockOffsets)
}

func (p *MessageParser) PacketWindowOpen(windowID WindowID, invTypeID InvTypeID, windowTitle string, numSlots byte) {
    p.printf("PacketWindowOpen(windowID=%d, invTypeID=%d, windowTitle=%v, numSlots=%d)",
        windowID, invTypeID, windowTitle, numSlots)
}

func (p *MessageParser) PacketWindowClose(windowID WindowID) {
    p.printf("PacketWindowClose(windowID=%d)", windowID)
}

func (p *MessageParser) PacketWindowProgressBar(windowID WindowID, prgBarID PrgBarID, value PrgBarValue) {
    p.printf("PacketWindowProgressBar(windowID=%d, prgBarID=%d, value=%d)",
        windowID, prgBarID, value)
}

func (p *MessageParser) PacketWindowTransaction(windowID WindowID, txID TxID, accepted bool) {
    p.printf("PacketWindowTransaction(windowID=%d, txID=%d, accepted=%v)")
}

func (p *MessageParser) PacketWindowClick(windowID WindowID, slot SlotID, rightClick bool, txID TxID, itemID ItemID, amount ItemCount, uses ItemUses) {
    p.printf("PacketWindowClick(windowID=%d, slot=%d, rightClick=%v, txID=%d, itemID=%d, amount=%d, uses=%d)",
        windowID, slot, rightClick, txID, itemID, amount, uses)
}

func (p *MessageParser) PacketWindowSetSlot(windowID WindowID, slot SlotID, itemID ItemID, amount ItemCount, uses ItemUses) {
    p.printf("PacketWindowSetSlot(windowID=%d, slot=%d, itemID=%d, amount=%d, uses=%d)",
        windowID, slot, itemID, amount, uses)
}

func (p *MessageParser) PacketWindowItems(windowID WindowID, items []proto.WindowSlot) {
    p.printf("PacketWindowItems(windowID=%d, items=%v)",
        windowID, items)
}

// Parses messages from the client
func (p *MessageParser) CSParse(reader io.Reader) {
    // If we return, we should consume all input to avoid blocking the pipe
    // we're listening on. TODO Maybe we could just close it?
    defer p.consumeUnrecognizedInput(reader)

    defer func() {
        if err := recover(); err != nil {
            p.printf("Parsing failed: %v", err)
        }
    }()

    p.logPrefix = "(C->S) "

    username, err := proto.ServerReadHandshake(reader)
    if err != nil {
        p.printf("ServerReadHandshake error: %v", err)
        return
    }
    p.printf("ServerReadHandshake(username=%v)", username)

    loginUsername, _, err := proto.ServerReadLogin(reader)
    if err != nil {
        p.printf("ServerReadLogin error: %v", err)
        return
    }
    p.printf("ServerReadLogin(username=%v)", loginUsername)

    for {
        err := proto.ServerReadPacket(reader, p)
        if err != nil {
            if err != os.EOF {
                p.printf("ReceiveLoop failed: %v", err)
            } else {
                p.printf("ReceiveLoop hit EOF")
            }
            return
        }
    }
}

// Parses messages from the server
func (p *MessageParser) SCParse(reader io.Reader) {
    // If we return, we should consume all input to avoid blocking the pipe
    // we're listening on. TODO Maybe we could just close it?
    defer p.consumeUnrecognizedInput(reader)

    defer func() {
        if err := recover(); err != nil {
            p.printf("Parsing failed: %v", err)
        }
    }()

    p.logPrefix = "(S->C) "

    connectionHash, err := proto.ClientReadHandshake(reader)
    if err != nil {
        p.printf("ClientReadHandshake error: %v", err)
        return
    }
    p.printf("ClientReadHandshake(connectionHash=%v)", connectionHash)

    for {
        err := proto.ClientReadPacket(reader, p)
        if err != nil {
            if err != os.EOF {
                p.printf("ReceiveLoop failed: %v", err)
            } else {
                p.printf("ReceiveLoop hit EOF")
            }
            return
        }
    }
}
<commit_msg>Improved packet intercept logging a little.<commit_after>package intercept_parse

import (
    "encoding/hex"
    "io"
    "log"
    "os"

    "chunkymonkey/proto"
    .   "chunkymonkey/types"
)

// Hex dumps the input to the log
func (p *MessageParser) dumpInput(logPrefix string, reader io.Reader) {
    buf := make([]byte, 16, 16)
    for {
        _, err := io.ReadAtLeast(reader, buf, 1)
        if err != nil {
            return
        }

        hexData := hex.EncodeToString(buf)
        p.printf("Unparsed data: %s", hexData)
    }
}

// Consumes data from reader until an error occurs
func (p *MessageParser) consumeUnrecognizedInput(reader io.Reader) {
    p.printf("Lost packet sync. Ignoring further data.")
    buf := make([]byte, 4096)
    for {
        _, err := io.ReadAtLeast(reader, buf, 1)
        if err != nil {
            return
        }
    }
}

type MessageParser struct {
    logPrefix string
}

func (p *MessageParser) printf(format string, v ...interface{}) {
    log.Printf(p.logPrefix+format, v...)
}

func (p *MessageParser) PacketKeepAlive() {
    // Not logging this packet as it's a bit spammy
}

func (p *MessageParser) PacketChatMessage(message string) {
    p.printf("PacketChatMessage(%s)", message)
}

func (p *MessageParser) PacketRespawn() {
    p.printf("PacketRespawn()")
}

func (p *MessageParser) PacketPlayer(onGround bool) {
    // Not logging this packet as it's a bit spammy
}

func (p *MessageParser) PacketPlayerPosition(position *AbsXYZ, stance AbsCoord, onGround bool) {
    p.printf("PacketPlayerPosition(position=%v, stance=%v, onGround=%v)", position, stance, onGround)
}

func (p *MessageParser) PacketPlayerLook(look *LookDegrees, onGround bool) {
    p.printf("PacketPlayerLook(look=%v, onGround=%v)", look, onGround)
}

func (p *MessageParser) PacketPlayerDigging(status DigStatus, blockLoc *BlockXYZ, face Face) {
    p.printf("PacketPlayerDigging(status=%v, blockLoc=%v, face=%v)", status, blockLoc, face)
}

func (p *MessageParser) PacketPlayerBlockPlacement(itemID ItemID, blockLoc *BlockXYZ, face Face, amount ItemCount, uses ItemUses) {
    p.printf("PacketPlayerBlockPlacement(itemId=%d, blockLoc=%v, face=%d, amount=%d, uses=%d)",
        itemID, blockLoc, face, amount, uses)
}

func (p *MessageParser) PacketHoldingChange(itemID ItemID) {
    p.printf("PacketHoldingChange(itemID=%d)", itemID)
}

func (p *MessageParser) PacketEntityAnimation(entityID EntityID, animation EntityAnimation) {
    p.printf("PacketEntityAnimation(entityID=%d, animation=%v)", entityID, animation)
}

func (p *MessageParser) PacketEntityAction(entityID EntityID, action EntityAction) {
    p.printf("PacketEntityAction(entityID=%d, action=%d)",
        entityID, action)
}

func (p *MessageParser) PacketSignUpdate(position *BlockXYZ, lines [4]string) {
    p.printf("PacketSignUpdate(position=%v, lines=[%q, %q, %q, %q])",
        position,
        lines[0], lines[1], lines[2], lines[3])
}

func (p *MessageParser) PacketDisconnect(reason string) {
    p.printf("PacketDisconnect(%s)", reason)
}

func (p *MessageParser) ClientPacketLogin(entityID EntityID, mapSeed RandomSeed, dimension DimensionID) {
    p.printf("PacketLogin(entityID=%d, mapSeed=%d, dimension=%d)",
        entityID, mapSeed, dimension)
}

func (p *MessageParser) PacketTimeUpdate(time TimeOfDay) {
    p.printf("PacketTime(time=%d)", time)
}

func (p *MessageParser) PacketEntityEquipment(entityID EntityID, slot SlotID, itemID ItemID, uses ItemUses) {
    p.printf("PacketEntityEquipment(entityID=%d, slot=%d, itemID=%d, uses=%d)",
        entityID, slot, itemID, uses)
}

func (p *MessageParser) PacketSpawnPosition(position *BlockXYZ) {
    p.printf("PacketSpawnPosition(position=%v)", position)
}

func (p *MessageParser) PacketUseEntity(user EntityID, target EntityID, leftClick bool) {
    p.printf("PacketUseEntity(user=%d, target=%d, leftClick=%v)", user, target, leftClick)
}

func (p *MessageParser) PacketUpdateHealth(health int16) {
    p.printf("PacketUpdateHealth(health=%d)", health)
}

func (p *MessageParser) PacketNamedEntitySpawn(entityID EntityID, name string, position *AbsIntXYZ, look *LookBytes, currentItem ItemID) {
    p.printf("PacketNamedEntitySpawn(entityID=%d, name=%q, position=%v, look=%v, currentItem=%d)",
        entityID, name, position, look, currentItem)
}

func (p *MessageParser) PacketItemSpawn(entityID EntityID, itemID ItemID, count ItemCount, uses ItemUses, location *AbsIntXYZ, yaw, pitch, roll AngleBytes) {
    p.printf("PacketItemSpawn(entityID=%d, itemID=%d, count=%d, uses=%d, location=%v, yaw=%d, pitch=%d, roll=%d)",
        entityID, itemID, count, uses, location, yaw, pitch, roll)
}

func (p *MessageParser) PacketItemCollect(collectedItem EntityID, collector EntityID) {
    p.printf("PacketItemCollect(collectedItem=%d, collector=%d)",
        collectedItem, collector)
}

func (p *MessageParser) PacketObjectSpawn(entityID EntityID, objType ObjTypeID, position *AbsIntXYZ) {
    p.printf("PacketObjectSpawn(entityID=%d, objType=%d, position=%v)",
        entityID, objType, position)
}

func (p *MessageParser) PacketEntitySpawn(entityID EntityID, mobType EntityMobType, position *AbsIntXYZ, yaw AngleBytes, pitch AngleBytes, metadata []proto.EntityMetadata) {
    p.printf("PacketEntitySpawn(entityID=%d, mobType=%d, position=%v, yaw=%d, pitch=%d, metadata=%v)",
        entityID, mobType, position, yaw, pitch, metadata)
}

func (p *MessageParser) PacketUnknownX19(field1 int32, field2 string, field3, field4, field5, field6 int32) {
    p.printf("PacketUnknownX19(field1=%d, field2=%q, field3=%d, field4=%d, field5=%d, field6=%d)",
        field1, field2, field3, field4, field5, field6)
}

func (p *MessageParser) PacketPaintingSpawn(entityID EntityID, title string, position *BlockXYZ, paintingType PaintingTypeID) {
    p.printf("PacketPaintingSpawn(entityID=%d, title=%s, position=%v, paintingType=%d)",
        entityID, title, position, position, paintingType)
}

func (p *MessageParser) PacketEntityVelocity(entityID EntityID, velocity *Velocity) {
    p.printf("PacketEntityVelocity(entityID=%d, velocity=%v)",
        entityID, velocity)
}

func (p *MessageParser) PacketEntityDestroy(entityID EntityID) {
    p.printf("PacketEntityDestroy(entityID=%d)", entityID)
}

func (p *MessageParser) PacketEntity(entityID EntityID) {
    p.printf("PacketEntity(entityID=%d)", entityID)
}

func (p *MessageParser) PacketEntityRelMove(entityID EntityID, movement *RelMove) {
    p.printf("PacketEntityRelMove(entityID=%d, movement=%v)",
        entityID, movement)
}

func (p *MessageParser) PacketEntityLook(entityID EntityID, yaw, pitch AngleBytes) {
    p.printf("PacketEntityLook(entityID=%d, yaw=%d, pitch=%d)",
        entityID, yaw, pitch)
}

func (p *MessageParser) PacketEntityTeleport(entityID EntityID, position *AbsIntXYZ, look *LookBytes) {
    p.printf("PacketEntityTeleport(entityID=%d, position=%v, look=%v",
        entityID, position, look)
}

func (p *MessageParser) PacketEntityStatus(entityID EntityID, status EntityStatus) {
    p.printf("PacketEntityStatus(entityID=%d, status=%d",
        entityID, status)
}

func (p *MessageParser) PacketEntityMetadata(entityID EntityID, metadata []proto.EntityMetadata) {
    p.printf("PacketEntityMetadata(entityID=%d, metadata=%v)", entityID, metadata)
}

func (p *MessageParser) PacketPreChunk(position *ChunkXZ, mode ChunkLoadMode) {
    p.printf("PacketPreChunk(position=%v, mode=%d)", position, mode)
}

func (p *MessageParser) PacketMapChunk(position *BlockXYZ, size *SubChunkSize, data []byte) {
    p.printf("PacketMapChunk(position=%v, size=%v, len(data)=%d)",
        position, size, len(data))
}

func (p *MessageParser) PacketBlockChangeMulti(chunkLoc *ChunkXZ, blockCoords []SubChunkXYZ, blockTypes []BlockID, blockMetaData []byte) {
    p.printf("PacketBlockChangeMulti(chunkLoc=%v, blockCoords=%v, blockTypes=%v, blockMetaData=%v)",
        chunkLoc, blockCoords, blockTypes, blockMetaData)
}

func (p *MessageParser) PacketBlockChange(blockLoc *BlockXYZ, blockType BlockID, blockMetaData byte) {
    p.printf("PacketBlockChange(blockLoc=%v, blockType=%d, blockMetaData=%d)",
        blockLoc, blockType, blockMetaData)
}

func (p *MessageParser) PacketNoteBlockPlay(position *BlockXYZ, instrument InstrumentID, pitch NotePitch) {
    p.printf("PacketNoteBlockPlay(position=%v, instrument=%d, pitch=%d)",
        position, instrument, pitch)
}

func (p *MessageParser) PacketExplosion(position *AbsXYZ, power float32, blockOffsets []proto.ExplosionOffsetXYZ) {
    p.printf("PacketExplosion(position=%v, power=%f, blockOffsets=%v)",
        position, power, blockOffsets)
}

func (p *MessageParser) PacketWindowOpen(windowID WindowID, invTypeID InvTypeID, windowTitle string, numSlots byte) {
    p.printf("PacketWindowOpen(windowID=%d, invTypeID=%d, windowTitle=%q, numSlots=%d)",
        windowID, invTypeID, windowTitle, numSlots)
}

func (p *MessageParser) PacketWindowClose(windowID WindowID) {
    p.printf("PacketWindowClose(windowID=%d)", windowID)
}

func (p *MessageParser) PacketWindowProgressBar(windowID WindowID, prgBarID PrgBarID, value PrgBarValue) {
    p.printf("PacketWindowProgressBar(windowID=%d, prgBarID=%d, value=%d)",
        windowID, prgBarID, value)
}

func (p *MessageParser) PacketWindowTransaction(windowID WindowID, txID TxID, accepted bool) {
    p.printf("PacketWindowTransaction(windowID=%d, txID=%d, accepted=%v)")
}

func (p *MessageParser) PacketWindowClick(windowID WindowID, slot SlotID, rightClick bool, txID TxID, itemID ItemID, amount ItemCount, uses ItemUses) {
    p.printf("PacketWindowClick(windowID=%d, slot=%d, rightClick=%v, txID=%d, itemID=%d, amount=%d, uses=%d)",
        windowID, slot, rightClick, txID, itemID, amount, uses)
}

func (p *MessageParser) PacketWindowSetSlot(windowID WindowID, slot SlotID, itemID ItemID, amount ItemCount, uses ItemUses) {
    p.printf("PacketWindowSetSlot(windowID=%d, slot=%d, itemID=%d, amount=%d, uses=%d)",
        windowID, slot, itemID, amount, uses)
}

func (p *MessageParser) PacketWindowItems(windowID WindowID, items []proto.WindowSlot) {
    p.printf("PacketWindowItems(windowID=%d, items=%v)",
        windowID, items)
}

// Parses messages from the client
func (p *MessageParser) CSParse(reader io.Reader) {
    // If we return, we should consume all input to avoid blocking the pipe
    // we're listening on. TODO Maybe we could just close it?
    defer p.consumeUnrecognizedInput(reader)

    defer func() {
        if err := recover(); err != nil {
            p.printf("Parsing failed: %v", err)
        }
    }()

    p.logPrefix = "(C->S) "

    username, err := proto.ServerReadHandshake(reader)
    if err != nil {
        p.printf("ServerReadHandshake error: %v", err)
        return
    }
    p.printf("ServerReadHandshake(username=%v)", username)

    loginUsername, _, err := proto.ServerReadLogin(reader)
    if err != nil {
        p.printf("ServerReadLogin error: %v", err)
        return
    }
    p.printf("ServerReadLogin(username=%v)", loginUsername)

    for {
        err := proto.ServerReadPacket(reader, p)
        if err != nil {
            if err != os.EOF {
                p.printf("ReceiveLoop failed: %v", err)
            } else {
                p.printf("ReceiveLoop hit EOF")
            }
            return
        }
    }
}

// Parses messages from the server
func (p *MessageParser) SCParse(reader io.Reader) {
    // If we return, we should consume all input to avoid blocking the pipe
    // we're listening on. TODO Maybe we could just close it?
    defer p.consumeUnrecognizedInput(reader)

    defer func() {
        if err := recover(); err != nil {
            p.printf("Parsing failed: %v", err)
        }
    }()

    p.logPrefix = "(S->C) "

    connectionHash, err := proto.ClientReadHandshake(reader)
    if err != nil {
        p.printf("ClientReadHandshake error: %v", err)
        return
    }
    p.printf("ClientReadHandshake(connectionHash=%v)", connectionHash)

    for {
        err := proto.ClientReadPacket(reader, p)
        if err != nil {
            if err != os.EOF {
                p.printf("ReceiveLoop failed: %v", err)
            } else {
                p.printf("ReceiveLoop hit EOF")
            }
            return
        }
    }
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
)

// `direnv deny [PATH_TO_RC]`
var CmdDeny = &Cmd{
	Name: "deny",
	Desc: "Revokes the auhorization of a given .envrc",
	Args: []string{"[PATH_TO_RC]"},
	Fn: func(env Env, args []string) (err error) {
		var rcPath string
		var config *Config

		if len(args) > 1 {
			rcPath = args[1]
		} else {
			if rcPath, err = os.Getwd(); err != nil {
				return
			}
		}

		if config, err = LoadConfig(env); err != nil {
			return
		}

		rc := FindRC(rcPath, config.AllowDir())
		if rc == nil {
			return fmt.Errorf(".envrc file not found")
		}
		return rc.Deny()
	},
}
<commit_msg>Corrected spelling mistake in deny command<commit_after>package main

import (
	"fmt"
	"os"
)

// `direnv deny [PATH_TO_RC]`
var CmdDeny = &Cmd{
	Name: "deny",
	Desc: "Revokes the authorization of a given .envrc",
	Args: []string{"[PATH_TO_RC]"},
	Fn: func(env Env, args []string) (err error) {
		var rcPath string
		var config *Config

		if len(args) > 1 {
			rcPath = args[1]
		} else {
			if rcPath, err = os.Getwd(); err != nil {
				return
			}
		}

		if config, err = LoadConfig(env); err != nil {
			return
		}

		rc := FindRC(rcPath, config.AllowDir())
		if rc == nil {
			return fmt.Errorf(".envrc file not found")
		}
		return rc.Deny()
	},
}
<|endoftext|>


<commit_before>package pointers

import (
	"testing"
	"time"
)

func TestNewBoolPtr(t *testing.T) {
	t.Log("Create false ptr")
	if *NewBoolPtr(false) != false {
		t.Fatal("Invalid pointer")
	}

	t.Log("Create true ptr")
	if *NewBoolPtr(true) != true {
		t.Fatal("Invalid pointer")
	}

	t.Log("Try to change the original value - should not be affected!")
	mybool := true
	myboolPtr := NewBoolPtr(mybool)
	if *myboolPtr != true {
		t.Fatal("Invalid pointer - original value")
	}
	*myboolPtr = false
	if *myboolPtr != false {
		t.Fatal("Invalid pointer - changed value")
	}
	// the original var should remain intact!
	if mybool != true {
		t.Fatal("The original var was affected!!")
	}
}

func TestNewStringPtr(t *testing.T) {
	t.Log("Create a string")
	if *NewStringPtr("mystr") != "mystr" {
		t.Fatal("Invalid pointer")
	}

	t.Log("Try to change the original value - should not be affected!")
	myStr := "my-orig-str"
	myStrPtr := NewStringPtr(myStr)
	if *myStrPtr != "my-orig-str" {
		t.Fatal("Invalid pointer - original value")
	}
	*myStrPtr = "new-str-value"
	if *myStrPtr != "new-str-value" {
		t.Fatal("Invalid pointer - changed value")
	}
	// the original var should remain intact!
	if myStr != "my-orig-str" {
		t.Fatal("The original var was affected!!")
	}
}

func TestNewTimePtr(t *testing.T) {
	t.Log("Create a time")
	if (*NewTimePtr(time.Date(2009, time.January, 1, 0, 0, 0, 0, time.UTC))).Equal(time.Date(2009, time.January, 1, 0, 0, 0, 0, time.UTC)) == false {
		t.Fatal("Invalid pointer")
	}

	t.Log("Try to change the original value - should not be affected!")
	myTime := time.Date(2012, time.January, 1, 0, 0, 0, 0, time.UTC)
	myTimePtr := NewTimePtr(myTime)
	if (*myTimePtr).Equal(time.Date(2012, time.January, 1, 0, 0, 0, 0, time.UTC)) == false {
		t.Fatal("Invalid pointer - original value")
	}
	*myTimePtr = time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC)
	if *myTimePtr != time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC) {
		t.Fatal("Invalid pointer - changed value")
	}
	// the original var should remain intact!
	if myTime.Equal(time.Date(2012, time.January, 1, 0, 0, 0, 0, time.UTC)) == false {
		t.Fatal("The original var was affected!!")
	}
}

func TestNewIntPtr(t *testing.T) {
	t.Log("Create 1 ptr")
	if *NewIntPtr(1) != 1 {
		t.Fatal("Invalid pointer")
	}

	t.Log("Create 0 ptr")
	if *NewIntPtr(0) != 0 {
		t.Fatal("Invalid pointer")
	}

	t.Log("Try to change the original value - should not be affected!")
	myint := 2
	myintPtr := NewIntPtr(myint)
	if *myintPtr != 2 {
		t.Fatal("Invalid pointer - original value")
	}
	*myintPtr = 3
	if *myintPtr != 3 {
		t.Fatal("Invalid pointer - changed value")
	}
	// the original var should remain intact!
	if myint != 2 {
		t.Fatal("The original var was affected!!")
	}
}
<commit_msg>PR fix<commit_after>package pointers

import (
	"testing"
	"time"
)

func TestNewBoolPtr(t *testing.T) {
	t.Log("Create false ptr")
	if *NewBoolPtr(false) != false {
		t.Fatal("Invalid pointer")
	}

	t.Log("Create true ptr")
	if *NewBoolPtr(true) != true {
		t.Fatal("Invalid pointer")
	}

	t.Log("Try to change the original value - should not be affected!")
	mybool := true
	myboolPtr := NewBoolPtr(mybool)
	if *myboolPtr != true {
		t.Fatal("Invalid pointer - original value")
	}
	*myboolPtr = false
	if *myboolPtr != false {
		t.Fatal("Invalid pointer - changed value")
	}
	// the original var should remain intact!
	if mybool != true {
		t.Fatal("The original var was affected!!")
	}
}

func TestNewStringPtr(t *testing.T) {
	t.Log("Create a string")
	if *NewStringPtr("mystr") != "mystr" {
		t.Fatal("Invalid pointer")
	}

	t.Log("Try to change the original value - should not be affected!")
	myStr := "my-orig-str"
	myStrPtr := NewStringPtr(myStr)
	if *myStrPtr != "my-orig-str" {
		t.Fatal("Invalid pointer - original value")
	}
	*myStrPtr = "new-str-value"
	if *myStrPtr != "new-str-value" {
		t.Fatal("Invalid pointer - changed value")
	}
	// the original var should remain intact!
	if myStr != "my-orig-str" {
		t.Fatal("The original var was affected!!")
	}
}

func TestNewTimePtr(t *testing.T) {
	t.Log("Create a time")
	if (*NewTimePtr(time.Date(2009, time.January, 1, 0, 0, 0, 0, time.UTC))).Equal(time.Date(2009, time.January, 1, 0, 0, 0, 0, time.UTC)) == false {
		t.Fatal("Invalid pointer")
	}

	t.Log("Try to change the original value - should not be affected!")
	myTime := time.Date(2012, time.January, 1, 0, 0, 0, 0, time.UTC)
	myTimePtr := NewTimePtr(myTime)
	if (*myTimePtr).Equal(time.Date(2012, time.January, 1, 0, 0, 0, 0, time.UTC)) == false {
		t.Fatal("Invalid pointer - original value")
	}
	*myTimePtr = time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC)
	if *myTimePtr != time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC) {
		t.Fatal("Invalid pointer - changed value")
	}
	// the original var should remain intact!
	if myTime.Equal(time.Date(2012, time.January, 1, 0, 0, 0, 0, time.UTC)) == false {
		t.Fatal("The original var was affected!!")
	}
}

func TestNewIntPtr(t *testing.T) {
	t.Log("Create 1 ptr")
	if *NewIntPtr(1) != 1 {
		t.Fatal("Invalid pointer")
	}

	t.Log("Create 0 ptr")
	if *NewIntPtr(0) != 0 {
		t.Fatal("Invalid pointer")
	}

	t.Log("Try to change the original value - should not be affected!")
	myint := 2
	myintPtr := NewIntPtr(myint)
	if *myintPtr != 2 {
		t.Fatal("Invalid pointer - original value")
	}

	// the original var should remain intact!
	if myint != 2 {
		t.Fatal("The original var was affected!!")
	}
}
<|endoftext|>


<commit_before>// package constraints contains methods for decoding a compact CPU and Memory
// constraints format. We specify the "constraints" format as the following:
//
// <cpushare>:<memory limit>
//
// CPUShare can be any number between 2 and 1024. For more details on how the
// --cpu-shares flag works in Docker/cgroups, see
// https://docs.docker.com/reference/run/#cpu-share-constraint
//
// Memory limit can contain a number and optionally the units. The following are
// all equivalent:
//
//	6GB
//	6144MB
//	6291456KB
package constraints

import (
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"strings"

	. "github.com/remind101/empire/empire/pkg/bytesize"
)

// ConstraintsSeparator separates the individual resource constraints
const ConstraintsSeparator = ":"

var (
	ErrInvalidCPUShare   = errors.New("CPUShare must be a value between 2 and 1024")
	ErrInvalidMemory     = errors.New("invalid memory format")
	ErrInvalidConstraint = errors.New("invalid constraints format")
)

// bytes is used as a multiplier.
const bytes = uint(1)

// CPUShare represents a CPUShare.
type CPUShare int

// NewCPUShare casts i to a CPUShare and ensures it's validity.
func NewCPUShare(i int) (CPUShare, error) {
	if i < 2 || i > 1024 {
		return 0, ErrInvalidCPUShare
	}

	return CPUShare(i), nil
}

func ParseCPUShare(s string) (CPUShare, error) {
	i, err := strconv.Atoi(s)
	if err != nil {
		return 0, err
	}

	return NewCPUShare(i)
}

// memRegex parses the number of units from a string.
var memRegex = regexp.MustCompile(`(\d+)(\S*)?`)

// Memory represents a memory limit.
type Memory uint

// ParseMemory parses a string in memory format and returns the amount of memory
// in bytes.
func ParseMemory(s string) (Memory, error) {
	i, err := parseMemory(s)
	return Memory(i), err
}

// String returns the string representation of Memory, using the following
// algorithm:
//
// * If the memory is less than 1 KB, it will return "x".
// * If the memory is less than 1 MB, it will return "xKB".
// * If the memory is less than 1 GB, it will return "xMB".
// * etc
func (m Memory) String() string {
	v := uint(m)

	switch {
	case v < KB:
		return fmt.Sprintf("%d", v)
	case v < MB:
		return fmtMemory(m, KB)
	case v < GB:
		return fmtMemory(m, MB)
	case v < TB:
		return fmtMemory(m, GB)
	}

	return fmt.Sprintf("%d", v)
}

func fmtMemory(m Memory, units uint) string {
	var u string
	switch units {
	case KB:
		u = "kb"
	case MB:
		u = "mb"
	case GB:
		u = "gb"
	case TB:
		u = "tb"

	}
	return fmt.Sprintf("%.2f%s", float32(m)/float32(units), u)
}

func parseMemory(s string) (uint, error) {
	p := memRegex.FindStringSubmatch(s)

	var (
		// n is the number part of the memory
		n uint
		// u is the unites parts
		u string
		// mult is a number that will be used to
		// multiply n to return bytes.
		mult uint
	)

	if len(p) == 0 {
		return n, ErrInvalidMemory
	}

	i, err := strconv.Atoi(p[1])
	if err != nil {
		return n, err
	}

	n = uint(i)

	if len(p) > 2 {
		u = strings.ToUpper(p[2])
	}

	switch u {
	case "":
		mult = bytes
	case "KB":
		mult = KB
	case "MB":
		mult = MB
	case "GB":
		mult = GB
	case "TB":
		mult = TB
	default:
		return n, ErrInvalidMemory
	}

	return n * mult, nil
}

// Constraints is a composition of CPUShares and Memory constraints.
type Constraints struct {
	CPUShare
	Memory
}

func Parse(s string) (Constraints, error) {
	var c Constraints

	p := strings.SplitN(s, ConstraintsSeparator, 2)
	if len(p) != 2 {
		return c, ErrInvalidConstraint
	}

	i, err := ParseCPUShare(p[0])
	if err != nil {
		return c, err
	}

	c.CPUShare = i

	m, err := ParseMemory(p[1])
	if err != nil {
		return c, err
	}

	c.Memory = m

	return c, nil
}
<commit_msg>Fix typo.<commit_after>// package constraints contains methods for decoding a compact CPU and Memory
// constraints format. We specify the "constraints" format as the following:
//
// <cpushare>:<memory limit>
//
// CPUShare can be any number between 2 and 1024. For more details on how the
// --cpu-shares flag works in Docker/cgroups, see
// https://docs.docker.com/reference/run/#cpu-share-constraint
//
// Memory limit can contain a number and optionally the units. The following are
// all equivalent:
//
//	6GB
//	6144MB
//	6291456KB
package constraints

import (
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"strings"

	. "github.com/remind101/empire/empire/pkg/bytesize"
)

// ConstraintsSeparator separates the individual resource constraints
const ConstraintsSeparator = ":"

var (
	ErrInvalidCPUShare   = errors.New("CPUShare must be a value between 2 and 1024")
	ErrInvalidMemory     = errors.New("invalid memory format")
	ErrInvalidConstraint = errors.New("invalid constraints format")
)

// bytes is used as a multiplier.
const bytes = uint(1)

// CPUShare represents a CPUShare.
type CPUShare int

// NewCPUShare casts i to a CPUShare and ensures it's validity.
func NewCPUShare(i int) (CPUShare, error) {
	if i < 2 || i > 1024 {
		return 0, ErrInvalidCPUShare
	}

	return CPUShare(i), nil
}

func ParseCPUShare(s string) (CPUShare, error) {
	i, err := strconv.Atoi(s)
	if err != nil {
		return 0, err
	}

	return NewCPUShare(i)
}

// memRegex parses the number of units from a string.
var memRegex = regexp.MustCompile(`(\d+)(\S*)?`)

// Memory represents a memory limit.
type Memory uint

// ParseMemory parses a string in memory format and returns the amount of memory
// in bytes.
func ParseMemory(s string) (Memory, error) {
	i, err := parseMemory(s)
	return Memory(i), err
}

// String returns the string representation of Memory, using the following
// algorithm:
//
// * If the memory is less than 1 KB, it will return "x".
// * If the memory is less than 1 MB, it will return "xKB".
// * If the memory is less than 1 GB, it will return "xMB".
// * etc
func (m Memory) String() string {
	v := uint(m)

	switch {
	case v < KB:
		return fmt.Sprintf("%d", v)
	case v < MB:
		return fmtMemory(m, KB)
	case v < GB:
		return fmtMemory(m, MB)
	case v < TB:
		return fmtMemory(m, GB)
	}

	return fmt.Sprintf("%d", v)
}

func fmtMemory(m Memory, units uint) string {
	var u string
	switch units {
	case KB:
		u = "kb"
	case MB:
		u = "mb"
	case GB:
		u = "gb"
	case TB:
		u = "tb"

	}
	return fmt.Sprintf("%.2f%s", float32(m)/float32(units), u)
}

func parseMemory(s string) (uint, error) {
	p := memRegex.FindStringSubmatch(s)

	var (
		// n is the number part of the memory
		n uint
		// u is the units parts
		u string
		// mult is a number that will be used to
		// multiply n to return bytes.
		mult uint
	)

	if len(p) == 0 {
		return n, ErrInvalidMemory
	}

	i, err := strconv.Atoi(p[1])
	if err != nil {
		return n, err
	}

	n = uint(i)

	if len(p) > 2 {
		u = strings.ToUpper(p[2])
	}

	switch u {
	case "":
		mult = bytes
	case "KB":
		mult = KB
	case "MB":
		mult = MB
	case "GB":
		mult = GB
	case "TB":
		mult = TB
	default:
		return n, ErrInvalidMemory
	}

	return n * mult, nil
}

// Constraints is a composition of CPUShares and Memory constraints.
type Constraints struct {
	CPUShare
	Memory
}

func Parse(s string) (Constraints, error) {
	var c Constraints

	p := strings.SplitN(s, ConstraintsSeparator, 2)
	if len(p) != 2 {
		return c, ErrInvalidConstraint
	}

	i, err := ParseCPUShare(p[0])
	if err != nil {
		return c, err
	}

	c.CPUShare = i

	m, err := ParseMemory(p[1])
	if err != nil {
		return c, err
	}

	c.Memory = m

	return c, nil
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"
	"fmt"
	"github.com/timakin/ts/loader"
	"github.com/codegangsta/cli"
)

var Commands = []cli.Command{
	commandAll,
	commandBiz,
	commandHack,
}

var commandAll = cli.Command{
	Name:  "all",
	Usage: "",
	Description: `
`,
	Action: doAll,
}

var commandBiz = cli.Command{
	Name:  "biz",
	Usage: "",
	Description: `
`,
	Action: doBiz,
}

var commandHack = cli.Command{
	Name:  "hack",
	Usage: "",
	Description: `
`,
	Action: doHack,
}

func debug(v ...interface{}) {
	if os.Getenv("DEBUG") != "" {
		log.Println(v...)
	}
}

func assert(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func doAll(c *cli.Context) {
	hn := make(chan loader.ResultData)
	go loader.GetHNFeed(hn)
	phres := <- hn
	fmt.Printf("%s",phres)
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}
<commit_msg>Fix with interface and display method<commit_after>package main

import (
	"log"
	"os"
	"github.com/timakin/ts/loader"
	"github.com/codegangsta/cli"
)

var Commands = []cli.Command{
	commandAll,
	commandBiz,
	commandHack,
}

var commandAll = cli.Command{
	Name:  "all",
	Usage: "",
	Description: `
`,
	Action: doAll,
}

var commandBiz = cli.Command{
	Name:  "biz",
	Usage: "",
	Description: `
`,
	Action: doBiz,
}

var commandHack = cli.Command{
	Name:  "hack",
	Usage: "",
	Description: `
`,
	Action: doHack,
}

func debug(v ...interface{}) {
	if os.Getenv("DEBUG") != "" {
		log.Println(v...)
	}
}

func assert(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func doAll(c *cli.Context) {
	hn := make(chan loader.ResultData)
	go loader.GetHNFeed(hn)
	phres := <- hn
	var HNData loader.Feed = &phres
	HNData.Display()
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}
<|endoftext|>


<commit_before>package render_test

import (
	"fmt"
	"net"
	"testing"

	"github.com/weaveworks/scope/probe/docker"
	"github.com/weaveworks/scope/probe/process"
	"github.com/weaveworks/scope/render"
	"github.com/weaveworks/scope/render/expected"
	"github.com/weaveworks/scope/report"
	"github.com/weaveworks/scope/test"
	"github.com/weaveworks/scope/test/fixture"
	"github.com/weaveworks/scope/test/reflect"
)

func TestMapProcess2Container(t *testing.T) {
	for _, input := range []testcase{
		{"empty", report.MakeNode("empty"), true},
		{"basic process", report.MakeNodeWith("basic", map[string]string{process.PID: "201", docker.ContainerID: "a1b2c3"}), true},
		{"uncontained", report.MakeNodeWith("uncontained", map[string]string{process.PID: "201", report.HostNodeID: report.MakeHostNodeID("foo")}), true},
	} {
		testMap(t, render.MapProcess2Container, input)
	}
}

type testcase struct {
	name string
	n    report.Node
	ok   bool
}

func testMap(t *testing.T, f render.MapFunc, input testcase) {
	_, ipNet, err := net.ParseCIDR("1.2.3.0/16")
	if err != nil {
		t.Fatalf(err.Error())
	}
	localNetworks := report.Networks([]*net.IPNet{ipNet})
	if have := f(input.n, localNetworks); input.ok != (len(have) > 0) {
		name := input.name
		if name == "" {
			name = fmt.Sprintf("%v", input.n)
		}
		t.Errorf("%s: want %v, have %v", name, input.ok, have)
	}
}

func TestContainerRenderer(t *testing.T) {
	have := Prune(render.ContainerRenderer.Render(fixture.Report))
	want := Prune(expected.RenderedContainers)
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}

func TestContainerFilterRenderer(t *testing.T) {
	// tag on of the containers in the topology and ensure
	// it is filtered out correctly.
	input := fixture.Report.Copy()
	input.Container.Nodes[fixture.ClientContainerNodeID] = input.Container.Nodes[fixture.ClientContainerNodeID].WithLatests(map[string]string{
		docker.LabelPrefix + "works.weave.role": "system",
	})
	have := Prune(render.FilterSystem(render.ContainerRenderer).Render(input))
	want := Prune(expected.RenderedContainers.Copy())
	delete(want, fixture.ClientContainerNodeID)
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}

func TestContainerWithHostIPsRenderer(t *testing.T) {
	input := fixture.Report.Copy()
	input.Container.Nodes[fixture.ClientContainerNodeID] = input.Container.Nodes[fixture.ClientContainerNodeID].WithLatests(map[string]string{
		docker.ContainerNetworkMode: "host",
	})
	nodes := render.ContainerWithHostIPsRenderer.Render(input)

	// Test host network nodes get the host IPs added.
	haveNode, ok := nodes[fixture.ClientContainerNodeID]
	if !ok {
		t.Fatal("Expected output to have the client container node")
	}
	have, ok := haveNode.Sets.Lookup(docker.ContainerIPs)
	if !ok {
		t.Fatal("Container had no IPs set.")
	}
	want := report.MakeStringSet("10.10.10.0")
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}

func TestContainerImageRenderer(t *testing.T) {
	have := Prune(render.ContainerImageRenderer.Render(fixture.Report))
	want := Prune(expected.RenderedContainerImages)
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}
<commit_msg>Check counters on expected rendered topologies<commit_after>package render_test

import (
	"fmt"
	"net"
	"testing"

	"github.com/weaveworks/scope/probe/docker"
	"github.com/weaveworks/scope/probe/process"
	"github.com/weaveworks/scope/render"
	"github.com/weaveworks/scope/render/expected"
	"github.com/weaveworks/scope/report"
	"github.com/weaveworks/scope/test"
	"github.com/weaveworks/scope/test/fixture"
	"github.com/weaveworks/scope/test/reflect"
)

func TestMapProcess2Container(t *testing.T) {
	for _, input := range []testcase{
		{"empty", report.MakeNode("empty"), true},
		{"basic process", report.MakeNodeWith("basic", map[string]string{process.PID: "201", docker.ContainerID: "a1b2c3"}), true},
		{"uncontained", report.MakeNodeWith("uncontained", map[string]string{process.PID: "201", report.HostNodeID: report.MakeHostNodeID("foo")}), true},
	} {
		testMap(t, render.MapProcess2Container, input)
	}
}

type testcase struct {
	name string
	n    report.Node
	ok   bool
}

func testMap(t *testing.T, f render.MapFunc, input testcase) {
	_, ipNet, err := net.ParseCIDR("1.2.3.0/16")
	if err != nil {
		t.Fatalf(err.Error())
	}
	localNetworks := report.Networks([]*net.IPNet{ipNet})
	if have := f(input.n, localNetworks); input.ok != (len(have) > 0) {
		name := input.name
		if name == "" {
			name = fmt.Sprintf("%v", input.n)
		}
		t.Errorf("%s: want %v, have %v", name, input.ok, have)
	}
}

func TestContainerRenderer(t *testing.T) {
	have := Prune(render.ContainerRenderer.Render(fixture.Report))
	want := Prune(expected.RenderedContainers)
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}

func TestContainerFilterRenderer(t *testing.T) {
	// tag on of the containers in the topology and ensure
	// it is filtered out correctly.
	input := fixture.Report.Copy()
	input.Container.Nodes[fixture.ClientContainerNodeID] = input.Container.Nodes[fixture.ClientContainerNodeID].WithLatests(map[string]string{
		docker.LabelPrefix + "works.weave.role": "system",
	})
	have := Prune(render.FilterSystem(render.ContainerRenderer).Render(input))
	want := Prune(expected.RenderedContainers.Copy())
	delete(want, fixture.ClientContainerNodeID)
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}

func TestContainerWithHostIPsRenderer(t *testing.T) {
	input := fixture.Report.Copy()
	input.Container.Nodes[fixture.ClientContainerNodeID] = input.Container.Nodes[fixture.ClientContainerNodeID].WithLatests(map[string]string{
		docker.ContainerNetworkMode: "host",
	})
	nodes := render.ContainerWithHostIPsRenderer.Render(input)

	// Test host network nodes get the host IPs added.
	haveNode, ok := nodes[fixture.ClientContainerNodeID]
	if !ok {
		t.Fatal("Expected output to have the client container node")
	}
	have, ok := haveNode.Sets.Lookup(docker.ContainerIPs)
	if !ok {
		t.Fatal("Container had no IPs set.")
	}
	want := report.MakeStringSet("10.10.10.0")
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}

func TestContainerImageRenderer(t *testing.T) {
	have := Prune(render.ContainerImageRenderer.Render(fixture.Report))
	want := Prune(expected.RenderedContainerImages)
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}

func TestContainerImageFilterRenderer(t *testing.T) {
	// add a system container into the topology and ensure
	// it is filtered out correctly.
	input := fixture.Report.Copy()

	// TODO: Add a process and endpoint here to make this test fail, so we can fix it.

	clientContainer2ID = "f6g7h8i9j1"
	clientContainer2NodeID = report.MakeContainerNodeID(fixture.ClientContainerID)
	input.Container.AddNode(report.MakeNodeWith(clientContainer2NodeID, map[string]string{
		docker.LabelPrefix + "works.weave.role": "system",

		docker.ImageID:    fixture.ClientContainerImageID,
		docker.ImageName:  fixture.ClientContainerImageName,
		report.HostNodeID: fixture.ClientHostNodeID,
	}).
		WithParents(report.EmptySets.
			Add("host", report.MakeStringSet(fixture.ClientHostNodeID)),
		).WithTopology(report.ContainerImage))

	have := Prune(render.FilterSystem(render.ContainerImageRenderer).Render(input))
	want := Prune(expected.RenderedContainerImages.Copy())
	// Test works by virtue of the RenderedContainerImage only having a container
	// counter == 1

	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}
<|endoftext|>


<commit_before>package qp

import (
	"fmt"
	"os/exec"
	"testing"
	"time"

	"github.com/qp/go/codecs"
	"github.com/qp/go/exchange"
	"github.com/qp/go/transports"
	"github.com/qp/go/transports/request"
	"github.com/stretchr/testify/assert"
)

var requestTests = []struct {
	name      string
	pre       func() bool
	transport func() transports.RequestTransport
	post      func()
}{
	{
		name: "InProc",
		pre:  func() bool { return true },
		transport: func() transports.RequestTransport {
			return request.MakeInProc(nil)
		},
		post: func() {},
	},
	{
		name: "Redis",
		pre: func() bool {
			err := exec.Command("which", "redis-cli").Run()
			if err != nil {
				return false
			}
			err = exec.Command("redis-cli", "ping").Run()
			if err != nil {
				// Redis is not running. Run it.
				err = exec.Command("redis-server", "--daemonize", "yes").Run()
				if err != nil {
					return false
				}
				time.Sleep(200 * time.Millisecond)
			}
			return true
		},
		transport: func() transports.RequestTransport {
			return request.MakeRedis("127.0.0.1:6379")
		},
		post: func() { exec.Command("redis-cli", "shutdown").Run() },
	},
}

func TestRequestMessenger(t *testing.T) {

	for _, test := range requestTests {

		if !test.pre() {
			continue
		}

		rm := MakeRequestMessenger("test", test.name, codecs.MakeJSON(), test.transport())
		rm2 := MakeRequestMessenger("test2", test.name, codecs.MakeJSON(), test.transport())
		if assert.NotNil(t, rm) && assert.NotNil(t, rm2) {
			rm.OnRequest(func(channel string, request *exchange.Request) {
				request.Data = "hello from handler"
			}, "test")

			rm.Start()
			rm2.Start()

			rf, err := rm2.Request("data", "test")
			if assert.NoError(t, err) {
				assert.Equal(t, rf.Response().Data.(string), "hello from handler")
				assert.Equal(t, rf.Response().From[0], "test2."+test.name)
			}

			rm.Stop()
			rm2.Stop()
		}

		test.post()
	}

}

func TestRequestMessengerMultipleJumps(t *testing.T) {

	for _, test := range requestTests {

		if !test.pre() {
			fmt.Println("Skipping", test.name, "due to pre-func fail.")
			continue
		}

		rm := MakeRequestMessenger("multitest", test.name, codecs.MakeJSON(), test.transport())
		s1 := MakeRequestMessenger("one", test.name, codecs.MakeJSON(), test.transport())
		s2 := MakeRequestMessenger("two", test.name, codecs.MakeJSON(), test.transport())
		s3 := MakeRequestMessenger("three", test.name, codecs.MakeJSON(), test.transport())

		if assert.NotNil(t, rm) &&
			assert.NotNil(t, s1) &&
			assert.NotNil(t, s2) &&
			assert.NotNil(t, s3) {
			s1.OnRequest(func(channel string, request *exchange.Request) {
				request.Data = append(request.Data.([]interface{}), "one")
			}, "one")
			s2.OnRequest(func(channel string, request *exchange.Request) {
				request.Data = append(request.Data.([]interface{}), "two")
			}, "two")
			s3.OnRequest(func(channel string, request *exchange.Request) {
				request.Data = append(request.Data.([]interface{}), "three")
			}, "three")

			rm.Start()
			s1.Start()
			s2.Start()
			s3.Start()

			rf, err := rm.Request([]string{"origin"}, "one", "two", "three")
			if assert.NoError(t, err) {
				assert.Equal(t, rf.Response().Data.([]interface{})[0].(string), "origin")
				assert.Equal(t, rf.Response().Data.([]interface{})[1].(string), "one")
				assert.Equal(t, rf.Response().Data.([]interface{})[2].(string), "two")
				assert.Equal(t, rf.Response().Data.([]interface{})[3].(string), "three")
				assert.Equal(t, rf.Response().From[0], "multitest."+test.name)
				assert.Equal(t, rf.Response().From[1], "one."+test.name)
				assert.Equal(t, rf.Response().From[2], "two."+test.name)
				assert.Equal(t, rf.Response().From[3], "three."+test.name)
			}

			rm.Stop()
			s1.Stop()
			s2.Stop()
			s3.Stop()

			test.post()

		}
	}
}
<commit_msg>Add message<commit_after>package qp

import (
	"fmt"
	"os/exec"
	"testing"
	"time"

	"github.com/qp/go/codecs"
	"github.com/qp/go/exchange"
	"github.com/qp/go/transports"
	"github.com/qp/go/transports/request"
	"github.com/stretchr/testify/assert"
)

var requestTests = []struct {
	name      string
	pre       func() bool
	transport func() transports.RequestTransport
	post      func()
}{
	{
		name: "InProc",
		pre:  func() bool { return true },
		transport: func() transports.RequestTransport {
			return request.MakeInProc(nil)
		},
		post: func() {},
	},
	{
		name: "Redis",
		pre: func() bool {
			err := exec.Command("which", "redis-cli").Run()
			if err != nil {
				return false
			}
			err = exec.Command("redis-cli", "ping").Run()
			if err != nil {
				// Redis is not running. Run it.
				err = exec.Command("redis-server", "--daemonize", "yes").Run()
				if err != nil {
					return false
				}
				time.Sleep(200 * time.Millisecond)
			}
			return true
		},
		transport: func() transports.RequestTransport {
			return request.MakeRedis("127.0.0.1:6379")
		},
		post: func() { exec.Command("redis-cli", "shutdown").Run() },
	},
}

func TestRequestMessenger(t *testing.T) {

	for _, test := range requestTests {

		if !test.pre() {
			fmt.Println("Skipping", test.name, "due to pre-func fail.")
			continue
		}

		rm := MakeRequestMessenger("test", test.name, codecs.MakeJSON(), test.transport())
		rm2 := MakeRequestMessenger("test2", test.name, codecs.MakeJSON(), test.transport())
		if assert.NotNil(t, rm) && assert.NotNil(t, rm2) {
			rm.OnRequest(func(channel string, request *exchange.Request) {
				request.Data = "hello from handler"
			}, "test")

			rm.Start()
			rm2.Start()

			rf, err := rm2.Request("data", "test")
			if assert.NoError(t, err) {
				assert.Equal(t, rf.Response().Data.(string), "hello from handler")
				assert.Equal(t, rf.Response().From[0], "test2."+test.name)
			}

			rm.Stop()
			rm2.Stop()
		}

		test.post()
	}

}

func TestRequestMessengerMultipleJumps(t *testing.T) {

	for _, test := range requestTests {

		if !test.pre() {
			fmt.Println("Skipping", test.name, "due to pre-func fail.")
			continue
		}

		rm := MakeRequestMessenger("multitest", test.name, codecs.MakeJSON(), test.transport())
		s1 := MakeRequestMessenger("one", test.name, codecs.MakeJSON(), test.transport())
		s2 := MakeRequestMessenger("two", test.name, codecs.MakeJSON(), test.transport())
		s3 := MakeRequestMessenger("three", test.name, codecs.MakeJSON(), test.transport())

		if assert.NotNil(t, rm) &&
			assert.NotNil(t, s1) &&
			assert.NotNil(t, s2) &&
			assert.NotNil(t, s3) {
			s1.OnRequest(func(channel string, request *exchange.Request) {
				request.Data = append(request.Data.([]interface{}), "one")
			}, "one")
			s2.OnRequest(func(channel string, request *exchange.Request) {
				request.Data = append(request.Data.([]interface{}), "two")
			}, "two")
			s3.OnRequest(func(channel string, request *exchange.Request) {
				request.Data = append(request.Data.([]interface{}), "three")
			}, "three")

			rm.Start()
			s1.Start()
			s2.Start()
			s3.Start()

			rf, err := rm.Request([]string{"origin"}, "one", "two", "three")
			if assert.NoError(t, err) {
				assert.Equal(t, rf.Response().Data.([]interface{})[0].(string), "origin")
				assert.Equal(t, rf.Response().Data.([]interface{})[1].(string), "one")
				assert.Equal(t, rf.Response().Data.([]interface{})[2].(string), "two")
				assert.Equal(t, rf.Response().Data.([]interface{})[3].(string), "three")
				assert.Equal(t, rf.Response().From[0], "multitest."+test.name)
				assert.Equal(t, rf.Response().From[1], "one."+test.name)
				assert.Equal(t, rf.Response().From[2], "two."+test.name)
				assert.Equal(t, rf.Response().From[3], "three."+test.name)
			}

			rm.Stop()
			s1.Stop()
			s2.Stop()
			s3.Stop()

			test.post()

		}
	}
}
<|endoftext|>


<commit_before>package builtins

import (
	"github.com/coel-lang/coel/src/lib/core"
	"github.com/coel-lang/coel/src/lib/systemt"
)

// Par evaluates arguments in parallel and returns the last one.
var Par = core.NewLazyFunction(
	core.NewSignature(
		nil, nil, "xs",
		nil, nil, "",
	),
	func(ts ...*core.Thunk) core.Value {
		l := ts[0]

		if v := checkEmptyList(l, core.NumArgsError("par", "> 0")); v != nil {
			return v
		}

		for {
			t := core.PApp(core.First, l)
			systemt.Daemonize(func() {
				t.Eval()
			})

			l = core.PApp(core.Rest, l)
			if v := checkEmptyList(l, t); v != nil {
				return v
			}
		}
	})
<commit_msg>Refactor par.go<commit_after>package builtins

import (
	"github.com/coel-lang/coel/src/lib/core"
	"github.com/coel-lang/coel/src/lib/systemt"
)

// Par evaluates arguments in parallel and returns the last one.
var Par = core.NewLazyFunction(
	core.NewSignature(nil, nil, "xs", nil, nil, ""),
	func(ts ...*core.Thunk) core.Value {
		l := ts[0]

		for {
			t := core.PApp(core.First, l)
			l = core.PApp(core.Rest, l)

			if v := checkEmptyList(l, t); v != nil {
				return v
			}

			systemt.Daemonize(func() { t.Eval() })
		}
	})
<|endoftext|>