<commit_before>package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path"
	"sort"

	"sync"

	"github.com/BurntSushi/toml"
	"github.com/k0pernicus/goyave/configurationFile"
	"github.com/k0pernicus/goyave/consts"
	"github.com/k0pernicus/goyave/traces"
	"github.com/k0pernicus/goyave/utils"
	"github.com/k0pernicus/goyave/walk"
	"github.com/spf13/cobra"
)

var configurationFileStructure configurationFile.ConfigurationFile
var configurationFilePath string
var userHomeDir string

/*initialize get the configuration file existing in the system (or create it), and return
 *a pointer to his content.
 */
func initialize(configurationFileStructure *configurationFile.ConfigurationFile) {
	// Initialize all different traces structures
	traces.InitTraces(os.Stdout, os.Stderr, os.Stdout, os.Stdout)

	// Get the user home directory
	userHomeDir = utils.GetUserHomeDir()
	if len(userHomeDir) == 0 {
		log.Fatalf("Cannot get the user home dir.\n")
	}
	// Set the configuration path file
	configurationFilePath = path.Join(userHomeDir, consts.ConfigurationFileName)
	filePointer, err := os.OpenFile(configurationFilePath, os.O_RDWR|os.O_CREATE, 0755)
	if err != nil {
		log.Fatalf("Cannot open the file %s, due to error '%s'.\n", configurationFilePath, err)
	}
	defer filePointer.Close()
	var bytesArray []byte
	// Get the content of the goyave configuration file
	configurationFile.GetConfigurationFileContent(filePointer, &bytesArray)
	if _, err = toml.Decode(string(bytesArray[:]), configurationFileStructure); err != nil {
		log.Fatalln(err)
	}
}

/*kill saves the current state of the configuration structure in the configuration file
 */
func kill() {
	var outputBuffer bytes.Buffer
	currentGroupIndex := utils.SliceIndex(len(configurationFileStructure.Groups), func(i int) bool {
		return configurationFileStructure.Groups[i].Name == configurationFileStructure.Local.Group
	})
	var newVisibleRepositories []string
	for _, visibleRepository := range configurationFileStructure.VisibleRepositories {
		newVisibleRepositories = append(newVisibleRepositories, visibleRepository.Name)
	}
	configurationFileStructure.Groups[currentGroupIndex].VisibleRepositories = newVisibleRepositories
	if err := configurationFileStructure.Encode(&outputBuffer); err != nil {
		log.Fatalln("Cannot save the current configurationFile structure!")
	}
	if err := ioutil.WriteFile(configurationFilePath, outputBuffer.Bytes(), 0777); err != nil {
		log.Fatalln("Cannot access to your file to save the configurationFile structure!")
	}
}

func main() {

	/*rootCmd defines the global app, and some actions to run before and after the command running
	 */
	var rootCmd = &cobra.Command{
		Use:   "goyave",
		Short: "Goyave is a tool to take a look at your local git repositories",
		// Initialize the structure
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			initialize(&configurationFileStructure)
		},
		// Save the current configuration file structure, in the configuration file
		PersistentPostRun: func(cmd *cobra.Command, args []string) {
			kill()
		},
	}

	/*addCmd is a subcommand to add the current working directory as a VISIBLE one
	 */
	// var addCmd = &cobra.Command{
	// 	Use:   "add",
	// 	Short: "Add the current path as a VISIBLE repository",
	// 	Run: func(cmd *cobra.Command, args []string) {
	// 		// Get the path where the command has been executed
	// 		currentDir, err := os.Getwd()
	// 		if err != nil {
	// 			log.Fatalln("There was a problem retrieving the current directory")
	// 		}
	// 		if !utils.IsGitRepository(currentDir) {
	// 			log.Fatalf("%s is not a git repository!\n", currentDir)
	// 		}
	// 		if err := configurationFileStructure.Extract(); err != nil {
	// 			traces.ErrorTracer.Fatalln(err)
	// 		}
	// 		// If the path is/contains a .git directory, add this one as a VISIBLE repository
	// 		if err := configurationFileStructure.AddRepository(currentDir, consts.VisibleFlag); err != nil {
	// 			traces.WarningTracer.Printf("[%s] %s\n", currentDir, err)
	// 		}
	// 	},
	// }

	/*crawlCmd is a subcommand to crawl your hard drive in order to get and save new git repositories
	 */
	var crawlCmd = &cobra.Command{
		Use:   "crawl",
		Short: "Crawl the hard drive in order to find git repositories",
		Run: func(cmd *cobra.Command, args []string) {
			var wg sync.WaitGroup
			// Get all git paths, and display them
			gitPaths, err := walk.RetrieveGitRepositories(userHomeDir)
			if err != nil {
				log.Fatalf("There was an error retrieving your git repositories: '%s'\n", err)
			}
			if err := configurationFileStructure.Extract(false); err != nil {
				traces.ErrorTracer.Fatalln(err)
			}
			// For each git repository, check if it exists, and if not add it to the default target visibility
			for _, gitPath := range gitPaths {
				wg.Add(1)
				go func(gitPath string) {
					defer wg.Done()
					if err := configurationFileStructure.AddRepository(gitPath, configurationFileStructure.Local.DefaultTarget); err != nil {
						traces.WarningTracer.Printf("[%s] %s\n", gitPath, err)
					}
				}(gitPath)
			}
			wg.Wait()
		},
	}

	/*loadCmd permits to load visible repositories from the goyave configuration file
	 */
	// var loadCmd = &cobra.Command{
	// 	Use:   "load",
	// 	Short: "Load the configuration file to restore your previous work space",
	// 	Run: func(cmd *cobra.Command, args []string) {
	// 		currentLocalhost := utils.GetLocalhost()
	// 		fmt.Printf("Current localhost is %s\n", currentLocalhost)
	// 		configGroups := configurationFileStructure.Groups
	// 		var visibleRepositories []string
	// 		for {
	// 			index := utils.SliceIndex(len(configGroups), func(i int) bool { return configGroups[i].Name == currentLocalhost })
	// 			if index == -1 {
	// 				traces.WarningTracer.Printf("Your current local host (%s) has not been found!", currentLocalhost)
	// 				fmt.Println("Please to choose one of those, to load the configuration file:")
	// 				for _, group := range configGroups {
	// 					fmt.Printf("\t%s\n", group.Name)
	// 				}
	// 				scanner := bufio.NewScanner(os.Stdin)
	// 				currentLocalhost = scanner.Text()
	// 				continue
	// 			} else {
	// 				visibleRepositories = configurationFileStructure.Groups[index].VisibleRepositories
	// 			}
	// 			break
	// 		}
	// 		traces.InfoTracer.Printf("Importing configuration from group %s\n", currentLocalhost)
	// 		for _, visibleRepository := range visibleRepositories {
	// 			traces.InfoTracer.Printf("* Importing %s...\n", visibleRepository)
	// 			index := utils.SliceIndex(len(configurationFileStructure.Repositories), func(i int) bool { return configurationFileStructure.Repositories[i].Name == visibleRepository })
	// 			// Check the local path, and the remote URL
	// 			if index == -1 {
	// 				traces.WarningTracer.Printf("\tThe repository \"%s\" does not exists in your configuration file.\n", visibleRepository)
	// 				continue
	// 			}
	// 			// Check if the repository exists locally
	// 			pathRepository, URLRepository := configurationFileStructure.Repositories[index].Path, configurationFileStructure.Repositories[index].URL
	// 			if _, err := os.Stat(pathRepository); err == nil {
	// 				traces.InfoTracer.Printf("\tThe repository \"%s\" already exists as a local git repository.\n", visibleRepository)
	// 				continue
	// 			}
	// 			// If it does not exists, clone it
	// 			if err := gitManip.Clone(pathRepository, URLRepository); err != nil {
	// 				traces.ErrorTracer.Printf("\tThe repository \"%s\" can't be cloned: %s\n", visibleRepository, err)
	// 			} else {
	// 				traces.InfoTracer.Printf("\tThe repository \"%s\" has been successfully cloned!\n", visibleRepository)
	// 			}
	// 		}
	// 	},
	// }

	/*pathCmd is a subcommand to get the path of a given git repository.
	 *This subcommand is useful to change directory, like `cd $(goyave path mygitrepo)`
	 */
	// var pathCmd = &cobra.Command{
	// 	Use:   "path",
	// 	Short: "Get the path of a given repository, if this one exists",
	// 	Run: func(cmd *cobra.Command, args []string) {
	// 		if len(args) == 0 {
	// 			log.Fatalln("Needs a repository name!")
	// 		}
	// 		repo := args[0]
	// 		if err := configurationFileStructure.Extract(); err != nil {
	// 			traces.ErrorTracer.Fatalln(err)
	// 		}
	// 		repoPath := configurationFileStructure.GetPathFromRepository(repo)
	// 		if repoPath != "" {
	// 			fmt.Println(repoPath)
	// 		} else {
	// 			log.Fatalf("The repository %s does not exists!\n", repo)
	// 		}
	// 	},
	// }

	/*stateCmd is a subcommand to list the state of each local git repository.
	 */
	var stateCmd = &cobra.Command{
		Use:     "state",
		Example: "goyave state\ngoyave state myRepositoryName\ngoyave state myRepositoryName1 myRepositoryName2",
		Short:   "Get the state of each local visible git repository",
		Long:    "Check only visible git repositories.\nIf some repository names have been setted, goyave will only check those repositories, otherwise it checks all visible repositories of your system.",
		Run: func(cmd *cobra.Command, args []string) {
			if err := configurationFileStructure.Extract(true); err != nil {
				traces.ErrorTracer.Fatalln(err)
			}
			var gitStructs []configurationFile.GitRepository
			if len(args) == 0 {
				gitStructs = configurationFileStructure.VisibleRepositories
			} else {
				// Sort visible repositories by name
				sort.Sort(configurationFile.ByName(configurationFileStructure.VisibleRepositories))
				repositoriesListLength := len(configurationFileStructure.VisibleRepositories)
				// Looking for given repository names - if the looking one does not exists, let the function prints a warning message.
				for _, repositoryName := range args {
					repositoryIndex := sort.Search(repositoriesListLength, func(i int) bool { return configurationFileStructure.VisibleRepositories[i].Name >= repositoryName })
					if repositoryIndex != repositoriesListLength {
						gitStructs = append(gitStructs, configurationFileStructure.VisibleRepositories[repositoryIndex])
					} else {
						traces.WarningTracer.Printf("%s cannot be found in your visible repositories!\n", repositoryName)
					}
				}
			}
			var wg sync.WaitGroup
			for _, gitStruct := range gitStructs {
				wg.Add(1)
				go func(gitStruct configurationFile.GitRepository) {
					defer wg.Done()
					gitStruct.Init(gitStruct.Path)
					gitStruct.GitObject.Status()
				}(gitStruct)
			}
			wg.Wait()
		},
	}

	/*switchCmd is a subcommand to switch the visibility of the current git repository.
	 */
	// var switchCmd = &cobra.Command{
	// 	Use:   "switch",
	// 	Short: "Switch the visibility of the current git repository (given by the current path)",
	// 	Run: func(cmd *cobra.Command, args []string) {
	// 		// Get the path where the command has been executed
	// 		currentDir, err := os.Getwd()
	// 		if err != nil {
	// 			log.Fatalln("There was a problem retrieving the current directory")
	// 		}
	// 		if err := configurationFileStructure.Extract(); err != nil {
	// 			traces.ErrorTracer.Fatalln(err)
	// 		}
	// 		if err := configurationFileStructure.RemoveRepositoryFromSlice(currentDir, consts.VisibleFlag); err == nil {
	// 			configurationFileStructure.AddRepository(currentDir, consts.HiddenFlag)
	// 			traces.InfoTracer.Printf("%s has been set to an hidden repository!", currentDir)
	// 			return
	// 		}
	// 		if err := configurationFileStructure.RemoveRepositoryFromSlice(currentDir, consts.HiddenFlag); err == nil {
	// 			configurationFileStructure.AddRepository(currentDir, consts.VisibleFlag)
	// 			traces.InfoTracer.Printf("%s has been set to a visible repository!", currentDir)
	// 			return
	// 		}
	// 		log.Fatalf("The repository %s is not saved as a VISIBLE or HIDDEN repository! Please to add it before.\n", currentDir)
	// 	},
	// }

	rootCmd.AddCommand(crawlCmd, stateCmd)

	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
<commit_msg>Add path command<commit_after>package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path"
	"sort"

	"sync"

	"github.com/BurntSushi/toml"
	"github.com/k0pernicus/goyave/configurationFile"
	"github.com/k0pernicus/goyave/consts"
	"github.com/k0pernicus/goyave/traces"
	"github.com/k0pernicus/goyave/utils"
	"github.com/k0pernicus/goyave/walk"
	"github.com/spf13/cobra"
)

var configurationFileStructure configurationFile.ConfigurationFile
var configurationFilePath string
var userHomeDir string

/*initialize get the configuration file existing in the system (or create it), and return
 *a pointer to his content.
 */
func initialize(configurationFileStructure *configurationFile.ConfigurationFile) {
	// Initialize all different traces structures
	traces.InitTraces(os.Stdout, os.Stderr, os.Stdout, os.Stdout)

	// Get the user home directory
	userHomeDir = utils.GetUserHomeDir()
	if len(userHomeDir) == 0 {
		log.Fatalf("Cannot get the user home dir.\n")
	}
	// Set the configuration path file
	configurationFilePath = path.Join(userHomeDir, consts.ConfigurationFileName)
	filePointer, err := os.OpenFile(configurationFilePath, os.O_RDWR|os.O_CREATE, 0755)
	if err != nil {
		log.Fatalf("Cannot open the file %s, due to error '%s'.\n", configurationFilePath, err)
	}
	defer filePointer.Close()
	var bytesArray []byte
	// Get the content of the goyave configuration file
	configurationFile.GetConfigurationFileContent(filePointer, &bytesArray)
	if _, err = toml.Decode(string(bytesArray[:]), configurationFileStructure); err != nil {
		log.Fatalln(err)
	}
}

/*kill saves the current state of the configuration structure in the configuration file
 */
func kill() {
	var outputBuffer bytes.Buffer
	currentGroupIndex := utils.SliceIndex(len(configurationFileStructure.Groups), func(i int) bool {
		return configurationFileStructure.Groups[i].Name == configurationFileStructure.Local.Group
	})
	var newVisibleRepositories []string
	for _, visibleRepository := range configurationFileStructure.VisibleRepositories {
		newVisibleRepositories = append(newVisibleRepositories, visibleRepository.Name)
	}
	configurationFileStructure.Groups[currentGroupIndex].VisibleRepositories = newVisibleRepositories
	if err := configurationFileStructure.Encode(&outputBuffer); err != nil {
		log.Fatalln("Cannot save the current configurationFile structure!")
	}
	if err := ioutil.WriteFile(configurationFilePath, outputBuffer.Bytes(), 0777); err != nil {
		log.Fatalln("Cannot access to your file to save the configurationFile structure!")
	}
}

func main() {

	/*rootCmd defines the global app, and some actions to run before and after the command running
	 */
	var rootCmd = &cobra.Command{
		Use:   "goyave",
		Short: "Goyave is a tool to take a look at your local git repositories",
		// Initialize the structure
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			initialize(&configurationFileStructure)
		},
		// Save the current configuration file structure, in the configuration file
		PersistentPostRun: func(cmd *cobra.Command, args []string) {
			kill()
		},
	}

	/*addCmd is a subcommand to add the current working directory as a VISIBLE one
	 */
	// var addCmd = &cobra.Command{
	// 	Use:   "add",
	// 	Short: "Add the current path as a VISIBLE repository",
	// 	Run: func(cmd *cobra.Command, args []string) {
	// 		// Get the path where the command has been executed
	// 		currentDir, err := os.Getwd()
	// 		if err != nil {
	// 			log.Fatalln("There was a problem retrieving the current directory")
	// 		}
	// 		if !utils.IsGitRepository(currentDir) {
	// 			log.Fatalf("%s is not a git repository!\n", currentDir)
	// 		}
	// 		if err := configurationFileStructure.Extract(); err != nil {
	// 			traces.ErrorTracer.Fatalln(err)
	// 		}
	// 		// If the path is/contains a .git directory, add this one as a VISIBLE repository
	// 		if err := configurationFileStructure.AddRepository(currentDir, consts.VisibleFlag); err != nil {
	// 			traces.WarningTracer.Printf("[%s] %s\n", currentDir, err)
	// 		}
	// 	},
	// }

	/*crawlCmd is a subcommand to crawl your hard drive in order to get and save new git repositories
	 */
	var crawlCmd = &cobra.Command{
		Use:   "crawl",
		Short: "Crawl the hard drive in order to find git repositories",
		Run: func(cmd *cobra.Command, args []string) {
			var wg sync.WaitGroup
			// Get all git paths, and display them
			gitPaths, err := walk.RetrieveGitRepositories(userHomeDir)
			if err != nil {
				log.Fatalf("There was an error retrieving your git repositories: '%s'\n", err)
			}
			if err := configurationFileStructure.Extract(false); err != nil {
				traces.ErrorTracer.Fatalln(err)
			}
			// For each git repository, check if it exists, and if not add it to the default target visibility
			for _, gitPath := range gitPaths {
				wg.Add(1)
				go func(gitPath string) {
					defer wg.Done()
					if err := configurationFileStructure.AddRepository(gitPath, configurationFileStructure.Local.DefaultTarget); err != nil {
						traces.WarningTracer.Printf("[%s] %s\n", gitPath, err)
					}
				}(gitPath)
			}
			wg.Wait()
		},
	}

	/*loadCmd permits to load visible repositories from the goyave configuration file
	 */
	// var loadCmd = &cobra.Command{
	// 	Use:   "load",
	// 	Short: "Load the configuration file to restore your previous work space",
	// 	Run: func(cmd *cobra.Command, args []string) {
	// 		currentLocalhost := utils.GetLocalhost()
	// 		fmt.Printf("Current localhost is %s\n", currentLocalhost)
	// 		configGroups := configurationFileStructure.Groups
	// 		var visibleRepositories []string
	// 		for {
	// 			index := utils.SliceIndex(len(configGroups), func(i int) bool { return configGroups[i].Name == currentLocalhost })
	// 			if index == -1 {
	// 				traces.WarningTracer.Printf("Your current local host (%s) has not been found!", currentLocalhost)
	// 				fmt.Println("Please to choose one of those, to load the configuration file:")
	// 				for _, group := range configGroups {
	// 					fmt.Printf("\t%s\n", group.Name)
	// 				}
	// 				scanner := bufio.NewScanner(os.Stdin)
	// 				currentLocalhost = scanner.Text()
	// 				continue
	// 			} else {
	// 				visibleRepositories = configurationFileStructure.Groups[index].VisibleRepositories
	// 			}
	// 			break
	// 		}
	// 		traces.InfoTracer.Printf("Importing configuration from group %s\n", currentLocalhost)
	// 		for _, visibleRepository := range visibleRepositories {
	// 			traces.InfoTracer.Printf("* Importing %s...\n", visibleRepository)
	// 			index := utils.SliceIndex(len(configurationFileStructure.Repositories), func(i int) bool { return configurationFileStructure.Repositories[i].Name == visibleRepository })
	// 			// Check the local path, and the remote URL
	// 			if index == -1 {
	// 				traces.WarningTracer.Printf("\tThe repository \"%s\" does not exists in your configuration file.\n", visibleRepository)
	// 				continue
	// 			}
	// 			// Check if the repository exists locally
	// 			pathRepository, URLRepository := configurationFileStructure.Repositories[index].Path, configurationFileStructure.Repositories[index].URL
	// 			if _, err := os.Stat(pathRepository); err == nil {
	// 				traces.InfoTracer.Printf("\tThe repository \"%s\" already exists as a local git repository.\n", visibleRepository)
	// 				continue
	// 			}
	// 			// If it does not exists, clone it
	// 			if err := gitManip.Clone(pathRepository, URLRepository); err != nil {
	// 				traces.ErrorTracer.Printf("\tThe repository \"%s\" can't be cloned: %s\n", visibleRepository, err)
	// 			} else {
	// 				traces.InfoTracer.Printf("\tThe repository \"%s\" has been successfully cloned!\n", visibleRepository)
	// 			}
	// 		}
	// 	},
	// }

	/*pathCmd is a subcommand to get the path of a given git repository.
	 *This subcommand is useful to change directory, like `cd $(goyave path mygitrepo)`
	 */
	var pathCmd = &cobra.Command{
		Use:   "path",
		Short: "Get the path of a given repository, if this one exists",
		Run: func(cmd *cobra.Command, args []string) {
			if len(args) == 0 {
				log.Fatalln("Needs a repository name!")
			}
			repo := args[0]
			if err := configurationFileStructure.Extract(true); err != nil {
				traces.ErrorTracer.Fatalln(err)
			}
			repoPath := configurationFileStructure.GetPathFromRepository(repo)
			if repoPath != "" {
				fmt.Println(repoPath)
			} else {
				log.Fatalf("The repository %s does not exists!\n", repo)
			}
		},
	}

	/*stateCmd is a subcommand to list the state of each local git repository.
	 */
	var stateCmd = &cobra.Command{
		Use:     "state",
		Example: "goyave state\ngoyave state myRepositoryName\ngoyave state myRepositoryName1 myRepositoryName2",
		Short:   "Get the state of each local visible git repository",
		Long:    "Check only visible git repositories.\nIf some repository names have been setted, goyave will only check those repositories, otherwise it checks all visible repositories of your system.",
		Run: func(cmd *cobra.Command, args []string) {
			if err := configurationFileStructure.Extract(true); err != nil {
				traces.ErrorTracer.Fatalln(err)
			}
			var gitStructs []configurationFile.GitRepository
			if len(args) == 0 {
				gitStructs = configurationFileStructure.VisibleRepositories
			} else {
				// Sort visible repositories by name
				sort.Sort(configurationFile.ByName(configurationFileStructure.VisibleRepositories))
				repositoriesListLength := len(configurationFileStructure.VisibleRepositories)
				// Looking for given repository names - if the looking one does not exists, let the function prints a warning message.
				for _, repositoryName := range args {
					repositoryIndex := sort.Search(repositoriesListLength, func(i int) bool { return configurationFileStructure.VisibleRepositories[i].Name >= repositoryName })
					if repositoryIndex != repositoriesListLength {
						gitStructs = append(gitStructs, configurationFileStructure.VisibleRepositories[repositoryIndex])
					} else {
						traces.WarningTracer.Printf("%s cannot be found in your visible repositories!\n", repositoryName)
					}
				}
			}
			var wg sync.WaitGroup
			for _, gitStruct := range gitStructs {
				wg.Add(1)
				go func(gitStruct configurationFile.GitRepository) {
					defer wg.Done()
					gitStruct.Init(gitStruct.Path)
					gitStruct.GitObject.Status()
				}(gitStruct)
			}
			wg.Wait()
		},
	}

	/*switchCmd is a subcommand to switch the visibility of the current git repository.
	 */
	// var switchCmd = &cobra.Command{
	// 	Use:   "switch",
	// 	Short: "Switch the visibility of the current git repository (given by the current path)",
	// 	Run: func(cmd *cobra.Command, args []string) {
	// 		// Get the path where the command has been executed
	// 		currentDir, err := os.Getwd()
	// 		if err != nil {
	// 			log.Fatalln("There was a problem retrieving the current directory")
	// 		}
	// 		if err := configurationFileStructure.Extract(); err != nil {
	// 			traces.ErrorTracer.Fatalln(err)
	// 		}
	// 		if err := configurationFileStructure.RemoveRepositoryFromSlice(currentDir, consts.VisibleFlag); err == nil {
	// 			configurationFileStructure.AddRepository(currentDir, consts.HiddenFlag)
	// 			traces.InfoTracer.Printf("%s has been set to an hidden repository!", currentDir)
	// 			return
	// 		}
	// 		if err := configurationFileStructure.RemoveRepositoryFromSlice(currentDir, consts.HiddenFlag); err == nil {
	// 			configurationFileStructure.AddRepository(currentDir, consts.VisibleFlag)
	// 			traces.InfoTracer.Printf("%s has been set to a visible repository!", currentDir)
	// 			return
	// 		}
	// 		log.Fatalf("The repository %s is not saved as a VISIBLE or HIDDEN repository! Please to add it before.\n", currentDir)
	// 	},
	// }

	rootCmd.AddCommand(crawlCmd, pathCmd, stateCmd)

	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import "crypto/md5"
import "flag"
import "fmt"
import "github.com/brianjriddle/pws3/gpgagent"
import "log"
import "os"
import "path/filepath"
import "regexp"

/**
* Inspired from https://metacpan.org/source/TLINDEN/Crypt-PWSafe3-1.14/lib/Crypt/PWSafe3.pm
* ,http://sourceforge.net/p/passwordsafe/code/HEAD/tree/trunk/pwsafe/pwsafe/docs/formatV3.txt,
* https://github.com/sommer/loxodo
*/

func makeCacheId(fileName string) string {
    fullpath, _ := filepath.Abs(fileName)
    cacheid := fmt.Sprintf("%x", md5.Sum([]byte(fullpath)))
    return cacheid
}

func main() {
    forget := flag.Bool("forget", false, "Forgets the password for given file")
    flag.Parse()
    if (len(flag.Args()) == 0 ) {
        flag.Usage()
        log.Fatal("No file given")
    }
    fileName := flag.Args()[0]
    if(*forget == true){
        gpgagent.ClearPassphrase(makeCacheId(fileName))
        os.Exit(0)
    }
    password := gpgagent.GetPassphrase(makeCacheId(fileName), "X", "X", "X")
    v := OpenVault(fileName, password)
    v.DumpVault()
    if len(flag.Args()) >= 2 {
        find := flag.Args()[1]
        r, err := regexp.Compile(find)
        if err != nil {
            log.Fatal("There is a problem with your regexp.", err)
        }
        for i := range v.Records {
            if r.MatchString(v.Records[i].Title) {
                fmt.Printf("%s\t%s\n", v.Records[i].Title, v.Records[i].Password)
            }
        }
    }

}
<commit_msg>Dump don't print an individual field.<commit_after>package main

import "crypto/md5"
import "flag"
import "fmt"
import "github.com/brianjriddle/pws3/gpgagent"
import "log"
import "os"
import "path/filepath"
import "regexp"

/**
* Inspired from https://metacpan.org/source/TLINDEN/Crypt-PWSafe3-1.14/lib/Crypt/PWSafe3.pm
* ,http://sourceforge.net/p/passwordsafe/code/HEAD/tree/trunk/pwsafe/pwsafe/docs/formatV3.txt,
* https://github.com/sommer/loxodo
*/

func makeCacheId(fileName string) string {
    fullpath, _ := filepath.Abs(fileName)
    cacheid := fmt.Sprintf("%x", md5.Sum([]byte(fullpath)))
    return cacheid
}

func main() {
    forget := flag.Bool("forget", false, "Forgets the password for given file")
    flag.Parse()
    if (len(flag.Args()) == 0 ) {
        flag.Usage()
        log.Fatal("No file given")
    }
    fileName := flag.Args()[0]
    if(*forget == true){
        gpgagent.ClearPassphrase(makeCacheId(fileName))
        os.Exit(0)
    }
    password := gpgagent.GetPassphrase(makeCacheId(fileName), "X", "X", "X")
    v := OpenVault(fileName, password)
    v.DumpVault()
    if len(flag.Args()) >= 2 {
        find := flag.Args()[1]
        r, err := regexp.Compile(find)
        if err != nil {
            log.Fatal("There is a problem with your regexp.", err)
        }
        for i := range v.Records {
            if r.MatchString(v.Records[i].Title) {
                v.Records[i].DumpRecord()
            }
        }
    }

}
<|endoftext|>


<commit_before>package main

import (
	"log"

	"github.com/mcuadros/docker-volume-gce/driver"

	"github.com/docker/go-plugins-helpers/volume"
)

func main() {
	d := &driver.Volume{}
	h := volume.NewHandler(d)
	log.Fatal(h.ServeTCP("test", ":57895"))
}
<commit_msg>main command<commit_after>package main

import (
	"os"

	"github.com/mcuadros/docker-volume-gce/driver"

	"github.com/docker/go-plugins-helpers/volume"
	"golang.org/x/net/context"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/compute/v1"
	"google.golang.org/cloud/compute/metadata"
	"gopkg.in/inconshreveable/log15.v2"
)

func main() {
	if !metadata.OnGCE() {
		log15.Error("docker-volume-gce driver only runs on Google Compute Engine")
		os.Exit(126)
	}

	ctx := context.Background()
	c, err := google.DefaultClient(ctx, compute.ComputeScope)
	if err != nil {
		log15.Error("error building compute client", "error", err)
		os.Exit(1)
	}

	project, zone, instance := getMetadataInfo()
	log15.Info("starting volume driver", "project", project, "zone", zone, "instance", instance)

	d, err := driver.NewVolume(c, project, zone, instance)
	if err != nil {
		log15.Error("error creating volume driver", "error", err)
		os.Exit(1)
	}

	h := volume.NewHandler(d)
	if err := h.ServeTCP("test", ":0"); err != nil {
		log15.Error("error starting volume driver server", "error", err)
		os.Exit(1)
	}

	log15.Info("http server started")
}

func getMetadataInfo() (project string, zone string, instance string) {
	var err error
	instance, err = metadata.InstanceName()
	if err != nil {
		log15.Error("error retrieving instance name", "error", err)
		os.Exit(126)
	}

	zone, err = metadata.Zone()
	if err != nil {
		log15.Error("error retrieving zone", "error", err)
		os.Exit(126)
	}

	project, err = metadata.ProjectID()
	if err != nil {
		log15.Error("error retrieving project", "error", err)
		os.Exit(126)
	}

	return
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"flag"
	"fmt"
	"github.com/skratchdot/open-golang/open" // Opens file in external editor
	"github.com/tarm/serial"
	"os"
	"strings"
	"time"
)

var port = flag.String("port", "", "What port is the Arduino connected to?")

const (
	FILENAME = "output.txt"
	EOM      = "END OF FILE"
)

func main() {
	flag.Parse()
	if *port == "" {
		fmt.Println("Port is required")
		return
	}

	findArduino()
	export_data("Hello World")
}

func findArduino() {
	config := &serial.Config{Name: *port, Baud: 9600,
		ReadTimeout: time.Second * 5}

	s, err := serial.OpenPort(config)

	if err != nil {
		fmt.Printf("Unable to open serial port: %s", err.Error())
		return
	}

	scanner := bufio.NewScanner(s)

	var lines []string

	var line string
	for line != EOM && len(lines) < 10 {

		success := scanner.Scan()
		line := scanner.Text()

		if !success {
			fmt.Printf("Unable to read scanner: %s", scanner.Err().Error())
			return
		}
		if len(line) == 0 {
			fmt.Printf("No data recieved")
			return
		}

		lines = append(lines, line)

	}

	fmt.Printf("Data read: \n\n%s\n\n", strings.Join(lines, "\n"))
}

func export_data(data string) {
	file, err := os.Create(FILENAME)

	if err != nil {
		fmt.Printf("Error opening file: %s", err.Error())
		return
	}

	file.WriteString(data)
	file.Close()
	open.Run(FILENAME)
}
<commit_msg>Switched to bufio.Reader with little impact.<commit_after>package main

import (
	"bufio"
	"flag"
	"fmt"
	"github.com/skratchdot/open-golang/open" // Opens file in external editor
	"github.com/tarm/serial"
	"os"
	"strings"
	"time"
)

var port = flag.String("port", "", "What port is the Arduino connected to?")

const (
	FILENAME = "output.txt"
	EOM      = "END OF FILE"
)

func main() {
	flag.Parse()
	if *port == "" {
		fmt.Println("Port is required")
		return
	}

	findArduino()
	export_data("Hello World")
}

func findArduino() {
	config := &serial.Config{Name: *port, Baud: 9600,
		ReadTimeout: time.Second * 10}

	s, err := serial.OpenPort(config)

	if err != nil {
		fmt.Printf("Unable to open serial port: %s", err.Error())
		return
	}

	reader := bufio.NewReader(s)

	var lines []string

	var line string
	for line != EOM && len(lines) < 10 {

		line, err := reader.ReadString('\n')

		if err != nil {
			fmt.Printf("Unable to read reader: %s", err.Error())
			return
		}
		if len(line) == 0 {
			fmt.Printf("No data recieved")
			return
		}

		lines = append(lines, line)

	}

	fmt.Printf("Data read: \n\n%s\n\n", strings.Join(lines, ""))
}

func export_data(data string) {
	file, err := os.Create(FILENAME)

	if err != nil {
		fmt.Printf("Error opening file: %s", err.Error())
		return
	}

	file.WriteString(data)
	file.Close()
	open.Run(FILENAME)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"html/template"
	"net/http"
)

type clock struct {
	cid string
}

var clocklist []clock

func main() {
	fmt.Println("Running:D")
	http.HandleFunc("/", root)
	http.HandleFunc("/create", create)
	http.HandleFunc("/clock", clockHandler)
	err := http.ListenAndServe(":1337", nil)
	if err != nil {
		panic(err)
	}
}

func root(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("templates/root.html")
	t.Execute(w, nil)
}

func create(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		_ = r.ParseForm()
		clockid := r.FormValue("clockid")
		clocklist = append(clocklist, clock{clockid})
		fmt.Println("added clock; list: ", clocklist)

		http.Redirect(w, r, "/clock", http.StatusSeeOther)

		return
	}

	fmt.Fprint(w, "404 you should not see this")
}

func clockHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "yeay, created a clock")
}
<commit_msg>Retrieve created clocks by the /clock path<commit_after>package main

import (
	"fmt"
	"html/template"
	"net/http"
	"time"
)

type clock struct {
	cid    string
	create time.Time
}

var clocklist []clock

func main() {
	fmt.Println("Running:D")
	http.HandleFunc("/", root)
	http.HandleFunc("/create", create)
	http.HandleFunc("/clock", clockHandler)
	err := http.ListenAndServe(":1337", nil)
	if err != nil {
		panic(err)
	}
}

func root(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("templates/root.html")
	t.Execute(w, nil)
}

func create(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		_ = r.ParseForm()
		clockid := r.FormValue("clockid")
		clocklist = append(clocklist, clock{clockid, time.Now()})
		fmt.Println("added clock; list: ", clocklist)

		http.Redirect(w, r, "/clock?cid="+clockid, http.StatusSeeOther)

		return
	}

	fmt.Fprint(w, "404 you should not see this")
}

func clockHandler(w http.ResponseWriter, r *http.Request) {
	cid := r.URL.Query().Get("cid")
	var c *clock
	for _, clock := range clocklist {
		if clock.cid == cid {
			c = &clock
		}
	}
	if c != nil {
		fmt.Fprint(w, "yeay, we have clock "+c.cid+c.create.String())
	} else {
		fmt.Fprint(w, "NO clock found, stop enumerating.")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"os"

	"github.com/codegangsta/negroni"
	"github.com/julienschmidt/httprouter"
	"github.com/justphil/httprouter-controller"

	"github.com/justphil/denatify-service/controllers"
)

func main() {
	// init router
	r := httprouter.New()

	// add routes
	r.GET("/", controller.Action((*controllers.LandingPageController).Index))
	r.GET("/users", controller.Action((*controllers.UsersController).Users))
	r.GET("/user/new", controller.Action((*controllers.UsersController).NewUser))
	r.POST("/user/new", controller.Action((*controllers.UsersController).CreateNewUser))
	r.GET("/users/:userId", controller.Action((*controllers.UsersController).User))
	r.GET("/users/:userId/delete", controller.Action((*controllers.UsersController).DeleteUser))
	r.GET("/users/:userId/perform-deletion", controller.Action((*controllers.UsersController).PerformUserDeletion))
	r.GET("/users/:userId/update", controller.Action((*controllers.UsersController).UpdateUser))
	r.POST("/users/:userId/perform-update", controller.Action((*controllers.UsersController).PerformUserUpdate))
	r.GET("/bust/:username/:project", controller.Action((*controllers.LandingPageController).Index))

	// initialize middlewares (includes negroni.Recovery, negroni.Logging, negroni.Static)
	n := negroni.Classic()

	// the router should always be the last handler
	n.UseHandler(r)

	// bind server to interface / port and block
	n.Run(":" + getPort())
}

func getPort() string {
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	return port
}
<commit_msg>add ClearHandler that clears context values at the end of a request lifetime<commit_after>package main

import (
	"os"

	"github.com/codegangsta/negroni"
	"github.com/gorilla/context"
	"github.com/julienschmidt/httprouter"
	"github.com/justphil/httprouter-controller"

	"github.com/justphil/denatify-service/controllers"
)

func main() {
	// init router
	r := httprouter.New()

	// add routes
	r.GET("/", controller.Action((*controllers.LandingPageController).Index))
	r.GET("/users", controller.Action((*controllers.UsersController).Users))
	r.GET("/user/new", controller.Action((*controllers.UsersController).NewUser))
	r.POST("/user/new", controller.Action((*controllers.UsersController).CreateNewUser))
	r.GET("/users/:userId", controller.Action((*controllers.UsersController).User))
	r.GET("/users/:userId/delete", controller.Action((*controllers.UsersController).DeleteUser))
	r.GET("/users/:userId/perform-deletion", controller.Action((*controllers.UsersController).PerformUserDeletion))
	r.GET("/users/:userId/update", controller.Action((*controllers.UsersController).UpdateUser))
	r.POST("/users/:userId/perform-update", controller.Action((*controllers.UsersController).PerformUserUpdate))
	r.GET("/bust/:username/:project", controller.Action((*controllers.LandingPageController).Index))

	// initialize middlewares (includes negroni.Recovery, negroni.Logging, negroni.Static)
	n := negroni.Classic()

	// the router should always be the last handler
	n.UseHandler(context.ClearHandler(r)) // ClearHandler clears context values at the end of a request lifetime

	// bind server to interface / port and block
	n.Run(":" + getPort())
}

func getPort() string {
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	return port
}
<|endoftext|>


<commit_before>/*
   Nging is a toolbox for webmasters
   Copyright (C) 2018-present  Wenhui Shen <swh@admpub.com>

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published
   by the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

// 也可以以服务的方式启动nging
// 服务支持的操作有：
// nging service install  	-- 安装服务
// nging service uninstall  -- 卸载服务
// nging service start 		-- 启动服务
// nging service stop 		-- 停止服务
// nging service restart 	-- 重启服务
package main

//go:generate go install github.com/admpub/bindata/v3/go-bindata@latest
//go:generate go-bindata -fs -o bindata_assetfs.go -prefix "vendor/github.com/nging-plugins/caddymanager/|vendor/github.com/nging-plugins/collector/|vendor/github.com/nging-plugins/dbmanager/|vendor/github.com/nging-plugins/ddnsmanager/|vendor/github.com/nging-plugins/dlmanager/|vendor/github.com/nging-plugins/frpmanager/|vendor/github.com/nging-plugins/ftpmanager/|vendor/github.com/nging-plugins/servermanager/|vendor/github.com/nging-plugins/sshmanager/" -ignore "\\.(git|svn|DS_Store|less|scss|gitkeep)$" -minify "\\.(js|css)$" -tags bindata public/assets/... template/... config/i18n/... vendor/github.com/nging-plugins/caddymanager/template/... vendor/github.com/nging-plugins/collector/template/... vendor/github.com/nging-plugins/dbmanager/template/... vendor/github.com/nging-plugins/ddnsmanager/template/... vendor/github.com/nging-plugins/dlmanager/template/... vendor/github.com/nging-plugins/frpmanager/template/... vendor/github.com/nging-plugins/ftpmanager/template/... vendor/github.com/nging-plugins/servermanager/template/... vendor/github.com/nging-plugins/sshmanager/template/...

import (
	_ "github.com/admpub/bindata/v3"
	"github.com/admpub/log"
	"github.com/admpub/nging/v4/application/cmd"
	_ "github.com/admpub/nging/v4/application/ico"

	//"github.com/admpub/nging/v4/application/library/loader"
	"github.com/webx-top/com"
	"github.com/webx-top/echo"

	//register

	_ "github.com/admpub/nging/v4/application"
	_ "github.com/admpub/nging/v4/application/initialize/manager"
	"github.com/admpub/nging/v4/application/library/module"
	_ "github.com/admpub/nging/v4/application/library/sqlite"

	"github.com/admpub/nging/v4/application/version"

	// module
	"github.com/admpub/nging/v4/application/handler/cloud"
	"github.com/admpub/nging/v4/application/handler/task"
	"github.com/nging-plugins/caddymanager"
	"github.com/nging-plugins/collector"
	"github.com/nging-plugins/dbmanager"
	"github.com/nging-plugins/ddnsmanager"
	"github.com/nging-plugins/dlmanager"
	"github.com/nging-plugins/frpmanager"
	"github.com/nging-plugins/ftpmanager"
	"github.com/nging-plugins/servermanager"
	"github.com/nging-plugins/sshmanager"
)

var (
	BUILD_TIME string
	BUILD_OS   string
	BUILD_ARCH string
	CLOUD_GOX  string
	COMMIT     string
	LABEL      = `dev` //beta/alpha/stable
	VERSION    = `4.0.1`
	PACKAGE    = `free`

	schemaVer = version.DBSCHEMA //数据表结构版本
)

func main() {
	log.SetEmoji(com.IsMac)
	defer log.Close()
	// if err := loader.LoadPlugins(); err != nil {
	// 	panic(err)
	// }
	echo.Set(`BUILD_TIME`, BUILD_TIME)
	echo.Set(`BUILD_OS`, BUILD_OS)
	echo.Set(`BUILD_ARCH`, BUILD_ARCH)
	echo.Set(`COMMIT`, COMMIT)
	echo.Set(`LABEL`, LABEL)
	echo.Set(`VERSION`, VERSION)
	echo.Set(`PACKAGE`, PACKAGE)
	echo.Set(`SCHEMA_VER`, schemaVer)
	initModule()
	exec()
}

func exec() {
	cmd.Execute()
}

func initModule() {
	module.Register(
		&caddymanager.Module,
		&servermanager.Module,
		&ftpmanager.Module,
		&collector.Module,
		&task.Module,
		&dlmanager.Module,
		&cloud.Module,
		&dbmanager.Module,
		&frpmanager.Module,
		&sshmanager.Module,
		&ddnsmanager.Module,
	)
}
<commit_msg>update<commit_after>/*
   Nging is a toolbox for webmasters
   Copyright (C) 2018-present  Wenhui Shen <swh@admpub.com>

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published
   by the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

// 也可以以服务的方式启动nging
// 服务支持的操作有：
// nging service install  	-- 安装服务
// nging service uninstall  -- 卸载服务
// nging service start 		-- 启动服务
// nging service stop 		-- 停止服务
// nging service restart 	-- 重启服务
package main

//go:generate go install github.com/admpub/bindata/v3/go-bindata@latest
//go:generate go-bindata -fs -o bindata_assetfs.go -prefix "vendor/github.com/nging-plugins/caddymanager/|vendor/github.com/nging-plugins/collector/|vendor/github.com/nging-plugins/dbmanager/|vendor/github.com/nging-plugins/ddnsmanager/|vendor/github.com/nging-plugins/dlmanager/|vendor/github.com/nging-plugins/frpmanager/|vendor/github.com/nging-plugins/ftpmanager/|vendor/github.com/nging-plugins/servermanager/|vendor/github.com/nging-plugins/sshmanager/" -ignore "\\.(git|svn|DS_Store|less|scss|gitkeep)$" -minify "\\.(js|css)$" -tags bindata public/assets/... template/... config/i18n/... vendor/github.com/nging-plugins/caddymanager/template/... vendor/github.com/nging-plugins/collector/template/... vendor/github.com/nging-plugins/dbmanager/template/... vendor/github.com/nging-plugins/ddnsmanager/template/... vendor/github.com/nging-plugins/dlmanager/template/... vendor/github.com/nging-plugins/frpmanager/template/... vendor/github.com/nging-plugins/ftpmanager/template/... vendor/github.com/nging-plugins/servermanager/template/... vendor/github.com/nging-plugins/sshmanager/template/...

import (
	"os"
	"time"

	_ "github.com/admpub/bindata/v3"
	"github.com/admpub/log"
	"github.com/admpub/nging/v4/application/cmd"
	_ "github.com/admpub/nging/v4/application/ico"

	//"github.com/admpub/nging/v4/application/library/loader"
	"github.com/webx-top/com"
	"github.com/webx-top/echo"

	//register

	_ "github.com/admpub/nging/v4/application"
	_ "github.com/admpub/nging/v4/application/initialize/manager"
	"github.com/admpub/nging/v4/application/library/module"
	_ "github.com/admpub/nging/v4/application/library/sqlite"

	"github.com/admpub/nging/v4/application/version"

	// module
	"github.com/admpub/nging/v4/application/handler/cloud"
	"github.com/admpub/nging/v4/application/handler/task"
	"github.com/nging-plugins/caddymanager"
	"github.com/nging-plugins/collector"
	"github.com/nging-plugins/dbmanager"
	"github.com/nging-plugins/ddnsmanager"
	"github.com/nging-plugins/dlmanager"
	"github.com/nging-plugins/frpmanager"
	"github.com/nging-plugins/ftpmanager"
	"github.com/nging-plugins/servermanager"
	"github.com/nging-plugins/sshmanager"
)

var (
	BUILD_TIME string
	BUILD_OS   string
	BUILD_ARCH string
	CLOUD_GOX  string
	COMMIT     string
	LABEL      = `dev` //beta/alpha/stable
	VERSION    = `4.0.1`
	PACKAGE    = `free`

	schemaVer = version.DBSCHEMA //数据表结构版本
)

func main() {
	log.SetEmoji(com.IsMac)
	defer log.Close()
	// if err := loader.LoadPlugins(); err != nil {
	// 	panic(err)
	// }
	echo.Set(`BUILD_TIME`, BUILD_TIME)
	echo.Set(`BUILD_OS`, BUILD_OS)
	echo.Set(`BUILD_ARCH`, BUILD_ARCH)
	echo.Set(`COMMIT`, COMMIT)
	echo.Set(`LABEL`, LABEL)
	echo.Set(`VERSION`, VERSION)
	echo.Set(`PACKAGE`, PACKAGE)
	echo.Set(`SCHEMA_VER`, schemaVer)
	if com.FileExists(`config/install.sql`) {
		os.Rename(`config/install.sql`, `config/install.sql.`+time.Now().Format(`20060102150405.000`))
	}
	initModule()
	exec()
}

func exec() {
	cmd.Execute()
}

func initModule() {
	module.Register(
		&caddymanager.Module,
		&servermanager.Module,
		&ftpmanager.Module,
		&collector.Module,
		&task.Module,
		&dlmanager.Module,
		&cloud.Module,
		&dbmanager.Module,
		&frpmanager.Module,
		&sshmanager.Module,
		&ddnsmanager.Module,
	)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"math/rand"
	"net"
	"net/http"
	"os"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

var (
	version   = "1.0.0"
	github    = "https://github.com/ekalinin/awsping"
	useragent = fmt.Sprintf("AwsPing/%s (+%s)", version, github)
)

var (
	repeats = flag.Int("repeats", 1, "Number of repeats")
	useHTTP = flag.Bool("http", false, "Use http transport (default is tcp)")
	showVer = flag.Bool("v", false, "Show version")
	verbose = flag.Int("verbose", 0, "Verbosity level")
	service = flag.String("service", "dynamodb", "AWS Service: ec2, sdb, sns, sqs, ...")
)

var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

// Duration2ms converts time.Duration to ms (float64)
func Duration2ms(d time.Duration) float64 {
	return float64(d.Nanoseconds()) / 1000 / 1000
}

func mkRandoString(n int) string {
	b := make([]rune, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

// AWSRegion description of the AWS EC2 region
type AWSRegion struct {
	Name      string
	Code      string
	Service   string
	Latencies []time.Duration
	Error     error
}

// CheckLatencyHTTP Test Latency via HTTP
func (r *AWSRegion) CheckLatencyHTTP(wg *sync.WaitGroup) {
	defer wg.Done()
	url := fmt.Sprintf("http://%s.%s.amazonaws.com/ping?x=%s", r.Service,
		r.Code, mkRandoString(13))
	client := &http.Client{}

	req, err := http.NewRequest("GET", url, nil)
	req.Header.Set("User-Agent", useragent)

	start := time.Now()
	resp, err := client.Do(req)
	r.Latencies = append(r.Latencies, time.Since(start))
	defer resp.Body.Close()

	r.Error = err
}

// CheckLatencyTCP Test Latency via TCP
func (r *AWSRegion) CheckLatencyTCP(wg *sync.WaitGroup) {
	defer wg.Done()
	tcpURI := fmt.Sprintf("%s.%s.amazonaws.com:80", r.Service, r.Code)
	tcpAddr, err := net.ResolveTCPAddr("tcp4", tcpURI)
	if err != nil {
		r.Error = err
		return
	}
	start := time.Now()
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		r.Error = err
		return
	}
	r.Latencies = append(r.Latencies, time.Since(start))
	defer conn.Close()

	r.Error = err
}

// GetLatency returns Latency in ms
func (r *AWSRegion) GetLatency() float64 {
	sum := float64(0)
	for _, l := range r.Latencies {
		sum += Duration2ms(l)
	}
	return sum / float64(len(r.Latencies))
}

// GetLatencyStr returns Latency in string
func (r *AWSRegion) GetLatencyStr() string {
	if r.Error != nil {
		return r.Error.Error()
	}
	return fmt.Sprintf("%.2f ms", r.GetLatency())
}

// AWSRegions slice of the AWSRegion
type AWSRegions []AWSRegion

func (rs AWSRegions) Len() int {
	return len(rs)
}

func (rs AWSRegions) Less(i, j int) bool {
	return rs[i].GetLatency() < rs[j].GetLatency()
}

func (rs AWSRegions) Swap(i, j int) {
	rs[i], rs[j] = rs[j], rs[i]
}

// CalcLatency returns list of aws regions sorted by Latency
func CalcLatency(repeats int, useHTTP bool, service string) *AWSRegions {
	regions := AWSRegions{
		{Service: service, Name: "US-East (Virginia)", Code: "us-east-1"},
		{Service: service, Name: "US-East (Ohio)", Code: "us-east-2"},
		{Service: service, Name: "US-West (California)", Code: "us-west-1"},
		{Service: service, Name: "US-West (Oregon)", Code: "us-west-2"},
		{Service: service, Name: "Canada (Central)", Code: "ca-central-1"},
		{Service: service, Name: "Europe (Ireland)", Code: "eu-west-1"},
		{Service: service, Name: "Europe (Frankfurt)", Code: "eu-central-1"},
		{Service: service, Name: "Europe (London)", Code: "eu-west-2"},
		{Service: service, Name: "Europe (Milan)", Code: "eu-south-1"},
		{Service: service, Name: "Europe (Paris)", Code: "eu-west-3"},
		{Service: service, Name: "Europe (Stockholm)", Code: "eu-north-1"},
		{Service: service, Name: "Africa (Cape Town)", Code: "af-south-1"},
		{Service: service, Name: "Asia Pacific (Osaka-Local)", Code: "ap-northeast-3"},
		{Service: service, Name: "Asia Pacific (Hong Kong)", Code: "ap-east-1"},
		{Service: service, Name: "Asia Pacific (Tokyo)", Code: "ap-northeast-1"},
		{Service: service, Name: "Asia Pacific (Seoul)", Code: "ap-northeast-2"},
		{Service: service, Name: "Asia Pacific (Singapore)", Code: "ap-southeast-1"},
		{Service: service, Name: "Asia Pacific (Mumbai)", Code: "ap-south-1"},
		{Service: service, Name: "Asia Pacific (Sydney)", Code: "ap-southeast-2"},
		{Service: service, Name: "South America (São Paulo)", Code: "sa-east-1"},
		{Service: service, Name: "Middle East (Bahrain)", Code: "me-south-1"},
		{Service: service, Name: "South America (São Paulo)", Code: "sa-east-1"},
	}
	var wg sync.WaitGroup

	for n := 1; n <= repeats; n++ {
		wg.Add(len(regions))
		for i := range regions {
			if useHTTP {
				go regions[i].CheckLatencyHTTP(&wg)
			} else {
				go regions[i].CheckLatencyTCP(&wg)
			}
		}
		wg.Wait()
	}

	sort.Sort(regions)
	return &regions
}

// LatencyOutput prints data into console
type LatencyOutput struct {
	Level int
}

func (lo *LatencyOutput) show0(regions *AWSRegions) {
	for _, r := range *regions {
		fmt.Printf("%-25s %20s\n", r.Name, r.GetLatencyStr())
	}
}

func (lo *LatencyOutput) show1(regions *AWSRegions) {
	outFmt := "%5v %-15s %-30s %20s\n"
	fmt.Printf(outFmt, "", "Code", "Region", "Latency")
	for i, r := range *regions {
		fmt.Printf(outFmt, i, r.Code, r.Name, r.GetLatencyStr())
	}
}

func (lo *LatencyOutput) show2(regions *AWSRegions) {
	// format
	outFmt := "%5v %-15s %-25s"
	outFmt += strings.Repeat(" %15s", *repeats) + " %15s\n"
	// header
	outStr := []interface{}{"", "Code", "Region"}
	for i := 0; i < *repeats; i++ {
		outStr = append(outStr, "Try #"+strconv.Itoa(i+1))
	}
	outStr = append(outStr, "Avg Latency")

	// show header
	fmt.Printf(outFmt, outStr...)

	// each region stats
	for i, r := range *regions {
		outData := []interface{}{strconv.Itoa(i), r.Code, r.Name}
		for n := 0; n < *repeats; n++ {
			outData = append(outData, fmt.Sprintf("%.2f ms",
				Duration2ms(r.Latencies[n])))
		}
		outData = append(outData, fmt.Sprintf("%.2f ms", r.GetLatency()))
		fmt.Printf(outFmt, outData...)
	}
}

// Show print data
func (lo *LatencyOutput) Show(regions *AWSRegions) {
	switch lo.Level {
	case 0:
		lo.show0(regions)
	case 1:
		lo.show1(regions)
	case 2:
		lo.show2(regions)
	}
}

func main() {

	flag.Parse()

	if *showVer {
		fmt.Println(version)
		os.Exit(0)
	}

	regions := CalcLatency(*repeats, *useHTTP, *service)
	lo := LatencyOutput{*verbose}
	lo.Show(regions)
}

func init() {
	rand.Seed(time.Now().UnixNano())
}
<commit_msg>duplicate removal<commit_after>package main

import (
	"flag"
	"fmt"
	"math/rand"
	"net"
	"net/http"
	"os"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

var (
	version   = "1.0.0"
	github    = "https://github.com/ekalinin/awsping"
	useragent = fmt.Sprintf("AwsPing/%s (+%s)", version, github)
)

var (
	repeats = flag.Int("repeats", 1, "Number of repeats")
	useHTTP = flag.Bool("http", false, "Use http transport (default is tcp)")
	showVer = flag.Bool("v", false, "Show version")
	verbose = flag.Int("verbose", 0, "Verbosity level")
	service = flag.String("service", "dynamodb", "AWS Service: ec2, sdb, sns, sqs, ...")
)

var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

// Duration2ms converts time.Duration to ms (float64)
func Duration2ms(d time.Duration) float64 {
	return float64(d.Nanoseconds()) / 1000 / 1000
}

func mkRandoString(n int) string {
	b := make([]rune, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

// AWSRegion description of the AWS EC2 region
type AWSRegion struct {
	Name      string
	Code      string
	Service   string
	Latencies []time.Duration
	Error     error
}

// CheckLatencyHTTP Test Latency via HTTP
func (r *AWSRegion) CheckLatencyHTTP(wg *sync.WaitGroup) {
	defer wg.Done()
	url := fmt.Sprintf("http://%s.%s.amazonaws.com/ping?x=%s", r.Service,
		r.Code, mkRandoString(13))
	client := &http.Client{}

	req, err := http.NewRequest("GET", url, nil)
	req.Header.Set("User-Agent", useragent)

	start := time.Now()
	resp, err := client.Do(req)
	r.Latencies = append(r.Latencies, time.Since(start))
	defer resp.Body.Close()

	r.Error = err
}

// CheckLatencyTCP Test Latency via TCP
func (r *AWSRegion) CheckLatencyTCP(wg *sync.WaitGroup) {
	defer wg.Done()
	tcpURI := fmt.Sprintf("%s.%s.amazonaws.com:80", r.Service, r.Code)
	tcpAddr, err := net.ResolveTCPAddr("tcp4", tcpURI)
	if err != nil {
		r.Error = err
		return
	}
	start := time.Now()
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		r.Error = err
		return
	}
	r.Latencies = append(r.Latencies, time.Since(start))
	defer conn.Close()

	r.Error = err
}

// GetLatency returns Latency in ms
func (r *AWSRegion) GetLatency() float64 {
	sum := float64(0)
	for _, l := range r.Latencies {
		sum += Duration2ms(l)
	}
	return sum / float64(len(r.Latencies))
}

// GetLatencyStr returns Latency in string
func (r *AWSRegion) GetLatencyStr() string {
	if r.Error != nil {
		return r.Error.Error()
	}
	return fmt.Sprintf("%.2f ms", r.GetLatency())
}

// AWSRegions slice of the AWSRegion
type AWSRegions []AWSRegion

func (rs AWSRegions) Len() int {
	return len(rs)
}

func (rs AWSRegions) Less(i, j int) bool {
	return rs[i].GetLatency() < rs[j].GetLatency()
}

func (rs AWSRegions) Swap(i, j int) {
	rs[i], rs[j] = rs[j], rs[i]
}

// CalcLatency returns list of aws regions sorted by Latency
func CalcLatency(repeats int, useHTTP bool, service string) *AWSRegions {
	regions := AWSRegions{
		{Service: service, Name: "US-East (Virginia)", Code: "us-east-1"},
		{Service: service, Name: "US-East (Ohio)", Code: "us-east-2"},
		{Service: service, Name: "US-West (California)", Code: "us-west-1"},
		{Service: service, Name: "US-West (Oregon)", Code: "us-west-2"},
		{Service: service, Name: "Canada (Central)", Code: "ca-central-1"},
		{Service: service, Name: "Europe (Ireland)", Code: "eu-west-1"},
		{Service: service, Name: "Europe (Frankfurt)", Code: "eu-central-1"},
		{Service: service, Name: "Europe (London)", Code: "eu-west-2"},
		{Service: service, Name: "Europe (Milan)", Code: "eu-south-1"},
		{Service: service, Name: "Europe (Paris)", Code: "eu-west-3"},
		{Service: service, Name: "Europe (Stockholm)", Code: "eu-north-1"},
		{Service: service, Name: "Africa (Cape Town)", Code: "af-south-1"},
		{Service: service, Name: "Asia Pacific (Osaka-Local)", Code: "ap-northeast-3"},
		{Service: service, Name: "Asia Pacific (Hong Kong)", Code: "ap-east-1"},
		{Service: service, Name: "Asia Pacific (Tokyo)", Code: "ap-northeast-1"},
		{Service: service, Name: "Asia Pacific (Seoul)", Code: "ap-northeast-2"},
		{Service: service, Name: "Asia Pacific (Singapore)", Code: "ap-southeast-1"},
		{Service: service, Name: "Asia Pacific (Mumbai)", Code: "ap-south-1"},
		{Service: service, Name: "Asia Pacific (Sydney)", Code: "ap-southeast-2"},
		{Service: service, Name: "South America (São Paulo)", Code: "sa-east-1"},
		{Service: service, Name: "Middle East (Bahrain)", Code: "me-south-1"},
	}
	var wg sync.WaitGroup

	for n := 1; n <= repeats; n++ {
		wg.Add(len(regions))
		for i := range regions {
			if useHTTP {
				go regions[i].CheckLatencyHTTP(&wg)
			} else {
				go regions[i].CheckLatencyTCP(&wg)
			}
		}
		wg.Wait()
	}

	sort.Sort(regions)
	return &regions
}

// LatencyOutput prints data into console
type LatencyOutput struct {
	Level int
}

func (lo *LatencyOutput) show0(regions *AWSRegions) {
	for _, r := range *regions {
		fmt.Printf("%-25s %20s\n", r.Name, r.GetLatencyStr())
	}
}

func (lo *LatencyOutput) show1(regions *AWSRegions) {
	outFmt := "%5v %-15s %-30s %20s\n"
	fmt.Printf(outFmt, "", "Code", "Region", "Latency")
	for i, r := range *regions {
		fmt.Printf(outFmt, i, r.Code, r.Name, r.GetLatencyStr())
	}
}

func (lo *LatencyOutput) show2(regions *AWSRegions) {
	// format
	outFmt := "%5v %-15s %-25s"
	outFmt += strings.Repeat(" %15s", *repeats) + " %15s\n"
	// header
	outStr := []interface{}{"", "Code", "Region"}
	for i := 0; i < *repeats; i++ {
		outStr = append(outStr, "Try #"+strconv.Itoa(i+1))
	}
	outStr = append(outStr, "Avg Latency")

	// show header
	fmt.Printf(outFmt, outStr...)

	// each region stats
	for i, r := range *regions {
		outData := []interface{}{strconv.Itoa(i), r.Code, r.Name}
		for n := 0; n < *repeats; n++ {
			outData = append(outData, fmt.Sprintf("%.2f ms",
				Duration2ms(r.Latencies[n])))
		}
		outData = append(outData, fmt.Sprintf("%.2f ms", r.GetLatency()))
		fmt.Printf(outFmt, outData...)
	}
}

// Show print data
func (lo *LatencyOutput) Show(regions *AWSRegions) {
	switch lo.Level {
	case 0:
		lo.show0(regions)
	case 1:
		lo.show1(regions)
	case 2:
		lo.show2(regions)
	}
}

func main() {

	flag.Parse()

	if *showVer {
		fmt.Println(version)
		os.Exit(0)
	}

	regions := CalcLatency(*repeats, *useHTTP, *service)
	lo := LatencyOutput{*verbose}
	lo.Show(regions)
}

func init() {
	rand.Seed(time.Now().UnixNano())
}
<|endoftext|>


<commit_before>// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package process

import (
	"fmt"
)

// Status values specific to workload processes.
const (
	StatusPending Status = iota
	StatusActive
	StatusFailed
	StatusStopped
)

// knownStatuses defines the statuses supported by Juju.
var knownStatuses = []Status{
	StatusPending,
	StatusActive,
	StatusFailed,
	StatusStopped,
}

// Status represents the status of a worload process.
type Status int

// IsUnnown returns true if the status is not known to Juju.
func (s Status) IsUnknown() bool {
	return s.String() == "unknown"
}

// String implements fmt.Stringer.
func (s Status) String() string {
	switch s {
	case StatusPending:
		return "pending"
	case StatusActive:
		return "active"
	case StatusFailed:
		return "failed"
	case StatusStopped:
		return "stopped"
	}
	return "unknown"
}

// String implements fmt.Gostringer.
func (s Status) GoString() string {
	return fmt.Sprintf("<%T %q>", s, s)
}
<commit_msg>Move the status strings to knownStatuses.<commit_after>// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package process

import (
	"fmt"
)

// Status values specific to workload processes.
const (
	StatusPending Status = iota
	StatusActive
	StatusFailed
	StatusStopped
)

// knownStatuses defines the statuses supported by Juju and their string.
var knownStatuses = map[Status]string{
	StatusPending: "pending",
	StatusActive:  "active",
	StatusFailed:  "failed",
	StatusStopped: "stopped",
}

// Status represents the status of a worload process.
type Status int

// IsUnnown returns true if the status is not known to Juju.
func (s Status) IsUnknown() bool {
	_, ok := knownStatuses[s]
	return !ok
}

// String implements fmt.Stringer.
func (s Status) String() string {
	if statusStr, ok := knownStatuses[s]; ok {
		return statusStr
	}
	return "unknown"
}

// String implements fmt.Gostringer.
func (s Status) GoString() string {
	return fmt.Sprintf("<%T %q>", s, s)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io"
	"os"
	"net/http"
	"net/url"
	"path"
	"flag"
	"github.com/Knorkebrot/m3u"
	"github.com/cheggaaa/pb"
)

const (
	PS = string(os.PathSeparator)
)

func usage() {
	fmt.Fprintf(os.Stderr, "Usage: %s list.m3u targetdir\n", os.Args[0])
	flag.PrintDefaults()
}

func main() {
	flag.Usage = usage
	flag.Parse()

	if len(flag.Args()) != 2 {
		flag.Usage()
		os.Exit(1)
	}

	input, err := os.Open(flag.Arg(0))
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error:", err)
		os.Exit(10)
	}

	pls, err := m3u.Parse(input)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error:", err)
		os.Exit(20)
	}
	target := flag.Arg(1)
	stat, err := os.Stat(target)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error:", err)
		os.Exit(30)
	} else if !stat.IsDir() {
		fmt.Fprintln(os.Stderr, "Error: not a directory:", target)
		os.Exit(40)
	}

	for _, song := range pls {
		fmt.Print(song.Title + ":")
		u, err := url.Parse(song.Path)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error: malformed url:", song.Path, "skipping.")
			continue
		}
		if u.Scheme != "http" && u.Scheme != "https" {
			fmt.Fprintln(os.Stderr, "Error: not a valid http(s) url:", song.Path, "skipping.")
			continue
		}

		resp, err := http.Get(song.Path)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error: http get failed:", err)
			continue
		}

		path := target + PS + path.Base(u.Path)

		fi, err := os.Stat(path)
		if err == nil && fi.Size() == resp.ContentLength {
			resp.Body.Close()
			fmt.Println(" already downloaded, skipping.")
			continue
		}

		fmt.Println("")
		file, err := os.OpenFile(path, os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0644)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error: cannot open", path + ":", err)
			resp.Body.Close()
			os.Exit(50)
		}

		bar := pb.New(int(resp.ContentLength))
		bar.SetUnits(pb.U_BYTES)
		bar.SetMaxWidth(79)
		bar.Start()
		writer := io.MultiWriter(file, bar)
		_, err = io.Copy(writer, resp.Body)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error: download failed:", err)
			resp.Body.Close()
			file.Close()
			os.Remove(path)
			continue
		}
		resp.Body.Close()
		file.Close()
		bar.Finish()
	}
}
<commit_msg>go fmt<commit_after>package main

import (
	"flag"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"path"

	"github.com/Knorkebrot/m3u"
	"github.com/cheggaaa/pb"
)

const (
	PS = string(os.PathSeparator)
)

func usage() {
	fmt.Fprintf(os.Stderr, "Usage: %s list.m3u targetdir\n", os.Args[0])
	flag.PrintDefaults()
}

func main() {
	flag.Usage = usage
	flag.Parse()

	if len(flag.Args()) != 2 {
		flag.Usage()
		os.Exit(1)
	}

	input, err := os.Open(flag.Arg(0))
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error:", err)
		os.Exit(10)
	}

	pls, err := m3u.Parse(input)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error:", err)
		os.Exit(20)
	}
	target := flag.Arg(1)
	stat, err := os.Stat(target)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error:", err)
		os.Exit(30)
	} else if !stat.IsDir() {
		fmt.Fprintln(os.Stderr, "Error: not a directory:", target)
		os.Exit(40)
	}

	for _, song := range pls {
		fmt.Print(song.Title + ":")
		u, err := url.Parse(song.Path)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error: malformed url:", song.Path, "skipping.")
			continue
		}
		if u.Scheme != "http" && u.Scheme != "https" {
			fmt.Fprintln(os.Stderr, "Error: not a valid http(s) url:", song.Path, "skipping.")
			continue
		}

		resp, err := http.Get(song.Path)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error: http get failed:", err)
			continue
		}

		path := target + PS + path.Base(u.Path)

		fi, err := os.Stat(path)
		if err == nil && fi.Size() == resp.ContentLength {
			resp.Body.Close()
			fmt.Println(" already downloaded, skipping.")
			continue
		}

		fmt.Println("")
		file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error: cannot open", path+":", err)
			resp.Body.Close()
			os.Exit(50)
		}

		bar := pb.New(int(resp.ContentLength))
		bar.SetUnits(pb.U_BYTES)
		bar.SetMaxWidth(79)
		bar.Start()
		writer := io.MultiWriter(file, bar)
		_, err = io.Copy(writer, resp.Body)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error: download failed:", err)
			resp.Body.Close()
			file.Close()
			os.Remove(path)
			continue
		}
		resp.Body.Close()
		file.Close()
		bar.Finish()
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"

	"github.com/golang/protobuf/proto"
	"github.com/mesos/mesos-go/mesosproto"
	"github.com/mesos/mesos-go/mesosutil"
	"github.com/mesos/mesos-go/scheduler"
	"github.com/sayden/minimal-mesos-go-framework/example_scheduler"

	"os"

	log "github.com/Sirupsen/logrus"
-)

var (
	master = flag.String("master", "127.0.0.1:5050", "Master address <ip:port>")
)

func init() {
	flag.Parse()
}

func main() {
	//ExecutorInfo
	executorUri := "http://s3-eu-west-1.amazonaws.com/enablers/executor"
	executorUris := []*mesosproto.CommandInfo_URI{
		{
			Value:      &executorUri,
			Executable: proto.Bool(true),
		},
	}

	executorInfo := &mesosproto.ExecutorInfo{
		ExecutorId: mesosutil.NewExecutorID("default"),
		Name:       proto.String("Test Executor (Go)"),
		Source:     proto.String("go_test"),
		Command: &mesosproto.CommandInfo{
			Value: proto.String("./executor"),
			Uris:  executorUris,
		},
	}

	//Scheduler
	my_scheduler := &example_scheduler.ExampleScheduler{
		ExecutorInfo: executorInfo,
		NeededCpu:    0.5,
		NeededRam:    128.0,
	}

	//Framework
	frameworkInfo := &mesosproto.FrameworkInfo{
		User: proto.String("root"), // Mesos-go will fill in user.
		Name: proto.String("Stratio Server Framework (Go)"),
	}

	//Scheduler Driver
	config := scheduler.DriverConfig{
		Scheduler:  my_scheduler,
		Framework:  frameworkInfo,
		Master:     *master,
		Credential: (*mesosproto.Credential)(nil),
	}

	driver, err := scheduler.NewMesosSchedulerDriver(config)

	if err != nil {
		log.Fatalf("Unable to create a SchedulerDriver: %v\n", err.Error())
		os.Exit(-3)
	}

	if stat, err := driver.Run(); err != nil {
		log.Fatalf("Framework stopped with status %s and error: %s\n", stat.String(), err.Error())
		os.Exit(-4)
	}
}
<commit_msg>Fix typo<commit_after>package main

import (
	"flag"

	"github.com/golang/protobuf/proto"
	"github.com/mesos/mesos-go/mesosproto"
	"github.com/mesos/mesos-go/mesosutil"
	"github.com/mesos/mesos-go/scheduler"
	"github.com/sayden/minimal-mesos-go-framework/example_scheduler"

	"os"

	log "github.com/Sirupsen/logrus"
)

var (
	master = flag.String("master", "127.0.0.1:5050", "Master address <ip:port>")
)

func init() {
	flag.Parse()
}

func main() {
	//ExecutorInfo
	executorUri := "http://s3-eu-west-1.amazonaws.com/enablers/executor"
	executorUris := []*mesosproto.CommandInfo_URI{
		{
			Value:      &executorUri,
			Executable: proto.Bool(true),
		},
	}

	executorInfo := &mesosproto.ExecutorInfo{
		ExecutorId: mesosutil.NewExecutorID("default"),
		Name:       proto.String("Test Executor (Go)"),
		Source:     proto.String("go_test"),
		Command: &mesosproto.CommandInfo{
			Value: proto.String("./executor"),
			Uris:  executorUris,
		},
	}

	//Scheduler
	my_scheduler := &example_scheduler.ExampleScheduler{
		ExecutorInfo: executorInfo,
		NeededCpu:    0.5,
		NeededRam:    128.0,
	}

	//Framework
	frameworkInfo := &mesosproto.FrameworkInfo{
		User: proto.String("root"), // Mesos-go will fill in user.
		Name: proto.String("Stratio Server Framework (Go)"),
	}

	//Scheduler Driver
	config := scheduler.DriverConfig{
		Scheduler:  my_scheduler,
		Framework:  frameworkInfo,
		Master:     *master,
		Credential: (*mesosproto.Credential)(nil),
	}

	driver, err := scheduler.NewMesosSchedulerDriver(config)

	if err != nil {
		log.Fatalf("Unable to create a SchedulerDriver: %v\n", err.Error())
		os.Exit(-3)
	}

	if stat, err := driver.Run(); err != nil {
		log.Fatalf("Framework stopped with status %s and error: %s\n", stat.String(), err.Error())
		os.Exit(-4)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/tls"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/bkeroack/libwordentropy"
	"github.com/eknkc/amber"
	"html/template"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
)

const (
	TLS_CERT       = "tls/cert-unified.pem"
	TLS_KEY        = "tls/cert.key"
	COUNT_DEFAULT  = 5
	LENGTH_DEFAULT = 5
	LISTEN_PORT    = 443
	STATS_PATH     = "data/stats/"
	DATA_PATH      = "data/"
	URL_FILE       = "data/plot_urls.txt"
)

var g *wordentropy.Generator
var templates = map[string]*template.Template{}
var template_name_map = map[string]string{}
var template_names = [...]string{
	"main.amber",
	"about.amber",
	"random.amber",
}

var localFlag *bool

func init() {
	localFlag = flag.Bool("local", false, "local testing mode (do not generate plots, bind to high port)")
	flag.Parse()

	gomaxprocs := os.ExpandEnv("${GOMAXPROCS}")
	if gomaxprocs == "" {
		log.Printf("GOMAXPROCS not set; default used (1)\n")
	} else {
		log.Printf("GOMAXPROCS: %v\n", gomaxprocs)
	}
}

func main() {

	log.Printf("Loading word map")

	g, err := wordentropy.LoadGenerator(&wordentropy.WordListOptions{
		Wordlist:  "data/part-of-speech.txt",
		Offensive: "data/offensive.txt",
	})
	if err != nil {
		log.Fatalf("Error loading wordlist: %v\n", err)
	}

	word_map := g.GetWordMap()

	wordlist_stats := GenerateStatistics(word_map)

	for k, v := range wordlist_stats {
		log.Printf("Word type: %v; total_count: %v; largest_word: %v\n",
			k, v.Total_count, v.Max_char_count)
	}

	write_distribution_csv()

	port := LISTEN_PORT
	if *localFlag {
		port = 4343
	} else {
		generate_plots()
	}

	get_plots(word_map, wordlist_stats)
	compile_templates()

	config := &tls.Config{MinVersion: tls.VersionTLS10}
	server := &http.Server{Addr: fmt.Sprintf("0.0.0.0:%v", port), Handler: nil, TLSConfig: config}

	log.Printf("Starting and listening on %v\n", port)
	http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("./static"))))
	http.HandleFunc("/", Root)
	http.HandleFunc("/about", About)
	http.HandleFunc("/how-random", Random)
	http.HandleFunc("/passphrases", Passphrases)
	err = server.ListenAndServeTLS(TLS_CERT, TLS_KEY)
	if err != nil {
		log.Fatalf("Error starting HTTP listener: %v\n", err)
	}
}

func compile_template(n string) *template.Template {
	compiler := amber.New()
	err := compiler.ParseFile(fmt.Sprintf("views/%v", n))
	if err != nil {
		log.Fatalf("Bad template: %v: %v\n", n, err)
	}
	tpl, err := compiler.Compile()
	if err != nil {
		log.Fatalf("Error compiling template: %v: %v\n", n, err)
	}
	return tpl
}

func compile_templates() {
	log.Printf("Compiling templates...\n")
	templates = make(map[string]*template.Template)
	template_name_map = make(map[string]string)
	for t := range template_names {
		template := template_names[t]
		n := strings.Split(template, ".")[0]
		templates[n] = compile_template(template)
		template_name_map[n] = template
	}
	log.Printf("Compilation complete\n")
}

func execute_template(n string, w http.ResponseWriter, r *http.Request, data interface{}) {
	log.Printf("%v\t%v\t%v\n", n, r.RemoteAddr, r.UserAgent())
	var err error
	if !*localFlag {
		err = templates[n].Execute(w, data)
	} else {
		tmpl := compile_template(template_name_map[n])
		err = tmpl.Execute(w, data)
	}
	if err != nil {
		log.Printf("Error executing template: %v: %v\n", n, err)
	}
}

func Root(w http.ResponseWriter, r *http.Request) {
	execute_template("main", w, r, nil)
}

func About(w http.ResponseWriter, r *http.Request) {
	execute_template("about", w, r, nil)
}

func Random(w http.ResponseWriter, r *http.Request) {
	log.Printf("random\t%v\t%v\n", r.RemoteAddr, r.UserAgent())
	data := struct {
		Word_stats        []stat_ui
		Plots             map[string]string
		Combined_plot_url string
	}{
		sanitized_stats,
		plot_map,
		combined_plot_url,
	}
	execute_template("random", w, r, &data)
}

func process_passphrases_options(o *wordentropy.GenerateOptions, qv map[string][]string) (bool, string) {

	if val, ok := qv["count"]; ok {
		count, err := strconv.Atoi(val[0])
		if err != nil || count < 0 || count > 99 {
			return false, fmt.Sprintf("Bad count parameter passed: %v; %v\n", err, val[0])
		}
		o.Count = uint(count)
	}

	if val, ok := qv["length"]; ok {
		length, err := strconv.Atoi(val[0])
		if err != nil || length < 0 || length > 99 {
			return false, fmt.Sprintf("Bad length parameter passed: %v; %v\n", err, val[0])
		}
		o.Length = uint(length)
	}

	if val, ok := qv["prudish"]; ok {
		if val[0] == "true" {
			o.Prudish = true
		}
	}
	if val, ok := qv["no_spaces"]; ok {
		if val[0] == "true" {
			o.No_spaces = true
		}
	}
	if val, ok := qv["add_digit"]; ok {
		if val[0] == "true" {
			o.Add_digit = true
		}
	}
	if val, ok := qv["add_symbol"]; ok {
		if val[0] == "true" {
			o.Add_symbol = true
		}
	}
	return true, ""
}

func Passphrases(w http.ResponseWriter, r *http.Request) {
	query_values := r.URL.Query()
	var options wordentropy.GenerateOptions
	w.Header().Set("Content-Type", "application/json")

	type passphrase_output struct {
		Count       uint
		Length      uint
		Passphrases []string
	}

	var output passphrase_output

	ok, msg := process_passphrases_options(&options, query_values)
	if !ok {
		emit_json_error(w, msg, 401)
	}

	log.Printf("passphrases\toptions:%v\t%v\t%v\n", options, r.RemoteAddr, r.UserAgent())

	passphrases, err := g.GeneratePassphrases(&options)
	if err != nil {
		emit_json_error(w, "Error generating passphrases", 500)
	}

	output.Count = options.Count
	output.Length = options.Length
	output.Passphrases = passphrases

	//emit json
	j, err := json.Marshal(output)
	if err != nil {
		log.Printf("ERROR marshalling json: %v\n", err)
		http.Error(w, "{ \"error\": \"Internal Server Error\" }", 500)
	}
	w.Write(j)
}
<commit_msg>fix var scope<commit_after>package main

import (
	"crypto/tls"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/bkeroack/libwordentropy"
	"github.com/eknkc/amber"
	"html/template"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
)

const (
	TLS_CERT       = "tls/cert-unified.pem"
	TLS_KEY        = "tls/cert.key"
	COUNT_DEFAULT  = 5
	LENGTH_DEFAULT = 5
	LISTEN_PORT    = 443
	STATS_PATH     = "data/stats/"
	DATA_PATH      = "data/"
	URL_FILE       = "data/plot_urls.txt"
)

var g *wordentropy.Generator
var templates = map[string]*template.Template{}
var template_name_map = map[string]string{}
var template_names = [...]string{
	"main.amber",
	"about.amber",
	"random.amber",
}

var localFlag *bool

func init() {
	localFlag = flag.Bool("local", false, "local testing mode (do not generate plots, bind to high port)")
	flag.Parse()

	gomaxprocs := os.ExpandEnv("${GOMAXPROCS}")
	if gomaxprocs == "" {
		log.Printf("GOMAXPROCS not set; default used (1)\n")
	} else {
		log.Printf("GOMAXPROCS: %v\n", gomaxprocs)
	}
}

func main() {

	log.Printf("Loading word map")

	var err error
	g, err = wordentropy.LoadGenerator(&wordentropy.WordListOptions{
		Wordlist:  "data/part-of-speech.txt",
		Offensive: "data/offensive.txt",
	})
	if err != nil {
		log.Fatalf("Error loading wordlist: %v\n", err)
	}

	word_map := g.GetWordMap()

	wordlist_stats := GenerateStatistics(word_map)

	for k, v := range wordlist_stats {
		log.Printf("Word type: %v; total_count: %v; largest_word: %v\n",
			k, v.Total_count, v.Max_char_count)
	}

	write_distribution_csv()

	port := LISTEN_PORT
	if *localFlag {
		port = 4343
	} else {
		generate_plots()
	}

	get_plots(word_map, wordlist_stats)
	compile_templates()

	config := &tls.Config{MinVersion: tls.VersionTLS10}
	server := &http.Server{Addr: fmt.Sprintf("0.0.0.0:%v", port), Handler: nil, TLSConfig: config}

	log.Printf("Starting and listening on %v\n", port)
	http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("./static"))))
	http.HandleFunc("/", Root)
	http.HandleFunc("/about", About)
	http.HandleFunc("/how-random", Random)
	http.HandleFunc("/passphrases", Passphrases)
	err = server.ListenAndServeTLS(TLS_CERT, TLS_KEY)
	if err != nil {
		log.Fatalf("Error starting HTTP listener: %v\n", err)
	}
}

func compile_template(n string) *template.Template {
	compiler := amber.New()
	err := compiler.ParseFile(fmt.Sprintf("views/%v", n))
	if err != nil {
		log.Fatalf("Bad template: %v: %v\n", n, err)
	}
	tpl, err := compiler.Compile()
	if err != nil {
		log.Fatalf("Error compiling template: %v: %v\n", n, err)
	}
	return tpl
}

func compile_templates() {
	log.Printf("Compiling templates...\n")
	templates = make(map[string]*template.Template)
	template_name_map = make(map[string]string)
	for t := range template_names {
		template := template_names[t]
		n := strings.Split(template, ".")[0]
		templates[n] = compile_template(template)
		template_name_map[n] = template
	}
	log.Printf("Compilation complete\n")
}

func execute_template(n string, w http.ResponseWriter, r *http.Request, data interface{}) {
	log.Printf("%v\t%v\t%v\n", n, r.RemoteAddr, r.UserAgent())
	var err error
	if !*localFlag {
		err = templates[n].Execute(w, data)
	} else {
		tmpl := compile_template(template_name_map[n])
		err = tmpl.Execute(w, data)
	}
	if err != nil {
		log.Printf("Error executing template: %v: %v\n", n, err)
	}
}

func Root(w http.ResponseWriter, r *http.Request) {
	execute_template("main", w, r, nil)
}

func About(w http.ResponseWriter, r *http.Request) {
	execute_template("about", w, r, nil)
}

func Random(w http.ResponseWriter, r *http.Request) {
	log.Printf("random\t%v\t%v\n", r.RemoteAddr, r.UserAgent())
	data := struct {
		Word_stats        []stat_ui
		Plots             map[string]string
		Combined_plot_url string
	}{
		sanitized_stats,
		plot_map,
		combined_plot_url,
	}
	execute_template("random", w, r, &data)
}

func process_passphrases_options(o *wordentropy.GenerateOptions, qv map[string][]string) (bool, string) {

	if val, ok := qv["count"]; ok {
		count, err := strconv.Atoi(val[0])
		if err != nil || count < 0 || count > 99 {
			return false, fmt.Sprintf("Bad count parameter passed: %v; %v\n", err, val[0])
		}
		o.Count = uint(count)
	}

	if val, ok := qv["length"]; ok {
		length, err := strconv.Atoi(val[0])
		if err != nil || length < 0 || length > 99 {
			return false, fmt.Sprintf("Bad length parameter passed: %v; %v\n", err, val[0])
		}
		o.Length = uint(length)
	}

	if val, ok := qv["prudish"]; ok {
		if val[0] == "true" {
			o.Prudish = true
		}
	}
	if val, ok := qv["no_spaces"]; ok {
		if val[0] == "true" {
			o.No_spaces = true
		}
	}
	if val, ok := qv["add_digit"]; ok {
		if val[0] == "true" {
			o.Add_digit = true
		}
	}
	if val, ok := qv["add_symbol"]; ok {
		if val[0] == "true" {
			o.Add_symbol = true
		}
	}
	return true, ""
}

func Passphrases(w http.ResponseWriter, r *http.Request) {
	query_values := r.URL.Query()
	options := wordentropy.GenerateOptions{}
	w.Header().Set("Content-Type", "application/json")

	type passphrase_output struct {
		Count       uint
		Length      uint
		Passphrases []string
	}

	var output passphrase_output

	ok, msg := process_passphrases_options(&options, query_values)
	if !ok {
		emit_json_error(w, msg, 401)
	}

	log.Printf("passphrases\toptions:%v\t%v\t%v\n", options, r.RemoteAddr, r.UserAgent())

	passphrases, err := g.GeneratePassphrases(&options)
	if err != nil {
		emit_json_error(w, "Error generating passphrases", 500)
	}

	output.Count = options.Count
	output.Length = options.Length
	output.Passphrases = passphrases

	//emit json
	j, err := json.Marshal(output)
	if err != nil {
		log.Printf("ERROR marshalling json: %v\n", err)
		http.Error(w, "{ \"error\": \"Internal Server Error\" }", 500)
	}
	w.Write(j)
}
<|endoftext|>