// AddFlags adds flags for a specific LocalkubeServer func AddFlags(s *localkube.LocalkubeServer) { flag.BoolVar(&s.Containerized, "containerized", s.Containerized, "If kubelet should run in containerized mode") flag.BoolVar(&s.EnableDNS, "enable-dns", s.EnableDNS, "If dns should be enabled") flag.StringVar(&s.DNSDomain, "dns-domain", s.DNSDomain, "The cluster dns domain") flag.IPVar(&s.DNSIP, "dns-ip", s.DNSIP, "The cluster dns IP") flag.StringVar(&s.LocalkubeDirectory, "localkube-directory", s.LocalkubeDirectory, "The directory localkube will store files in") flag.IPNetVar(&s.ServiceClusterIPRange, "service-cluster-ip-range", s.ServiceClusterIPRange, "The service-cluster-ip-range for the apiserver") flag.IPVar(&s.APIServerAddress, "apiserver-address", s.APIServerAddress, "The address the apiserver will listen securely on") flag.IntVar(&s.APIServerPort, "apiserver-port", s.APIServerPort, "The port the apiserver will listen securely on") flag.IPVar(&s.APIServerInsecureAddress, "apiserver-insecure-address", s.APIServerInsecureAddress, "The address the apiserver will listen insecurely on") flag.IntVar(&s.APIServerInsecurePort, "apiserver-insecure-port", s.APIServerInsecurePort, "The port the apiserver will listen insecurely on") flag.BoolVar(&s.ShouldGenerateCerts, "generate-certs", s.ShouldGenerateCerts, "If localkube should generate it's own certificates") flag.BoolVar(&s.ShowVersion, "version", s.ShowVersion, "If localkube should just print the version and exit.") flag.Var(&s.RuntimeConfig, "runtime-config", "A set of key=value pairs that describe runtime configuration that may be passed to apiserver. apis/<groupVersion> key can be used to turn on/off specific api versions. apis/<groupVersion>/<resource> can be used to turn on/off specific resources. api/all and api/legacy are special keys to control all and legacy api versions respectively.") flag.IPVar(&s.NodeIP, "node-ip", s.NodeIP, "IP address of the node. If set, kubelet will use this IP address for the node.") flag.StringVar(&s.ContainerRuntime, "container-runtime", "", "The container runtime to be used") flag.StringVar(&s.NetworkPlugin, "network-plugin", "", "The name of the network plugin") // These two come from vendor/ packages that use flags. We should hide them flag.CommandLine.MarkHidden("google-json-key") flag.CommandLine.MarkHidden("log-flush-frequency") // Parse them flag.Parse() }
func initializeFlags() { flag.Set("logtostderr", "true") flag.BoolVar(&options.CleanKeystore, "clean", false, "Clean-up keystore and start over?") flag.StringVar(&options.EtcdHost, "etcd_host", "127.0.0.1", "Hostname or IP address where Etcd is listening on") flag.Uint64Var(&options.LeaderTTL, "ttl", 10, "Leader health-check interval in seconds") flag.BoolVar(&options.MemberElectable, "electable", true, "Is member elegible for leader?") flag.Uint64Var(&options.MemberTTL, "member_ttl", 30, "Member health-check interval in seconds") flag.StringVar(&options.PgHost, "pg_host", "127.0.0.1", "Hostname or IP address where PostgreSQL server is listening on") flag.IntVar(&options.PgPort, "pg_port", 5432, "TCP port where PostgreSQL server is listening on") flag.Parse() }
func init() { flag.IntVar(&last, "last-release-pr", 0, "The PR number of the last versioned release.") flag.IntVar(¤t, "current-release-pr", 0, "The PR number of the current versioned release.") flag.StringVar(&token, "api-token", "", "Github api token for rate limiting. Background: https://developer.github.com/v3/#rate-limiting and create a token: https://github.com/settings/tokens") flag.StringVar(&base, "base", "master", "The base branch name for PRs to look for.") flag.BoolVar(&relnoteFilter, "relnote-filter", true, "Whether to filter PRs by the release-note label.") }
func realMain() error { flag.StringSliceVarP(&configFiles, "file", "f", nil, "file") flag.BoolVar(&jsonOut, "json", false, "") flag.BoolVarP(&versionFlag, "version", "v", false, "") flag.Parse() if jsonOut { logrus.SetFormatter(&logrus.JSONFormatter{}) } if versionFlag { fmt.Printf("gcron version %s\n", VERSION) os.Exit(0) } c := internal.NewCron() if len(configFiles) == 0 { return errors.New("No cronfiles") } if err := loadFiles(c); err != nil { return err } c.Start() return listen(c) }
func initFlags() { flag.IntVarP(&options.Port, "port", "p", 80, "The port to listen on") flag.StringVarP(&options.StaticDir, "www", "w", ".", "Directory to serve static files from") flag.StringVar(&options.StaticPrefix, "www-prefix", "/", "Prefix to serve static files on") flag.DurationVar(&options.StaticCacheMaxAge, "max-age", 0, "Set the Cache-Control header for static content with the max-age set to this value, e.g. 24h. Must confirm to http://golang.org/pkg/time/#ParseDuration") flag.StringVarP(&options.DefaultPage, "default-page", "d", "", "Default page to send if page not found") flag.VarP(&options.Services, "service", "s", "The Kubernetes services to proxy to in the form \"<prefix>=<serviceUrl>\"") flag.VarP(&options.Configs, "config-file", "c", "The configuration files to create in the form \"<template>=<output>\"") flag.Var(&options.CACerts, "ca-cert", "CA certs used to verify proxied server certificates") flag.StringVar(&options.TlsCertFile, "tls-cert", "", "Certificate file to use to serve using TLS") flag.StringVar(&options.TlsKeyFile, "tls-key", "", "Certificate file to use to serve using TLS") flag.BoolVar(&options.SkipCertValidation, "skip-cert-validation", false, "Skip remote certificate validation - dangerous!") flag.BoolVarP(&options.AccessLogging, "access-logging", "l", false, "Enable access logging") flag.BoolVar(&options.CompressHandler, "compress", false, "Enable gzip/deflate response compression") flag.BoolVar(&options.FailOnUnknownServices, "fail-on-unknown-services", false, "Fail on unknown services in DNS") flag.BoolVar(&options.ServeWww, "serve-www", true, "Whether to serve static content") flag.Parse() }
func initFlags(c *config) { pflag.StringSliceVar(&c.etcdServers, "etcd-servers", []string{}, "The comma-seprated list of etcd servers to use") pflag.BoolVar(&c.etcdSecure, "etcd-secure", false, "Set to true if etcd has https") pflag.StringVar(&c.etcdCertfile, "etcd-certfile", "", "Etcd TLS cert file, needed if etcd-secure") pflag.StringVar(&c.etcdKeyfile, "etcd-keyfile", "", "Etcd TLS key file, needed if etcd-secure") pflag.StringVar(&c.etcdCafile, "etcd-cafile", "", "Etcd CA file, needed if etcd-secure") pflag.StringVar(&c.key, "key", "", "The key to use for the lock") pflag.StringVar(&c.whoami, "whoami", "", "The name to use for the reservation. If empty use os.Hostname") pflag.Uint64Var(&c.ttl, "ttl-secs", 30, "The time to live for the lock.") pflag.StringVar(&c.src, "source-file", "", "The source file to copy from.") pflag.StringVar(&c.dest, "dest-file", "", "The destination file to copy to.") pflag.DurationVar(&c.sleep, "sleep", 5*time.Second, "The length of time to sleep between checking the lock.") }
func init() { pflag.StringVar(&formula, "price-formula", "static", "What price formular to use? static, random, old, young") pflag.Float32Var(&formulaStaticPrice, "price-static", 1.0, "Price for static formular") pflag.Float32Var(&formulaDefaultPrice, "price-default", 1.0, "Default Price for old/young formular") pflag.Float32Var(&formulaOldPrice, "price-old", 1.0, "Age Price for old formular") pflag.Float32Var(&formulaYoungPrice, "price-young", 1.0, "Age Price for young formular") pflag.DurationVar(&formulaOldAge, "price-old-age", 6*30*24*time.Hour, "Minimum age before start bidding price-old") pflag.DurationVar(&formulaYoungAge, "price-young-age", 60*24*time.Hour, "Maximum age before stop bidding price-old") pflag.StringVar(&volumePath, "volume", "./lib", "What files to sync") pflag.StringVar(&fsConfig.Addr, "http-addr", "127.0.0.1", "IP to listen on. Must be resolvable by all peers") pflag.IntVar(&fsConfig.Port, "http-port", 8080, "Port for HTTP FileServer") pflag.IntVar(&p2pConfig.BindPort, "bind-port", 8000, "The port to bind to") pflag.StringVar(&p2pConfig.Name, "name", "mediasyncer", "The name of this process. Must be unique for the memberlist cluster") pflag.BoolVar(&printNetworkMessages, "debug", false, "Print network messages received/sent") }
func main() { options := &gbuild.Options{CreateMapFile: true} var pkgObj string pflag.BoolVarP(&options.Verbose, "verbose", "v", false, "print the names of packages as they are compiled") flagVerbose := pflag.Lookup("verbose") pflag.BoolVarP(&options.Quiet, "quiet", "q", false, "suppress non-fatal warnings") flagQuiet := pflag.Lookup("quiet") pflag.BoolVarP(&options.Watch, "watch", "w", false, "watch for changes to the source files") flagWatch := pflag.Lookup("watch") pflag.BoolVarP(&options.Minify, "minify", "m", false, "minify generated code") flagMinify := pflag.Lookup("minify") pflag.BoolVar(&options.Color, "color", terminal.IsTerminal(int(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb", "colored output") flagColor := pflag.Lookup("color") tags := pflag.String("tags", "", "a list of build tags to consider satisfied during the build") flagTags := pflag.Lookup("tags") cmdBuild := &cobra.Command{ Use: "build [packages]", Short: "compile packages and dependencies", } cmdBuild.Flags().StringVarP(&pkgObj, "output", "o", "", "output file") cmdBuild.Flags().AddFlag(flagVerbose) cmdBuild.Flags().AddFlag(flagQuiet) cmdBuild.Flags().AddFlag(flagWatch) cmdBuild.Flags().AddFlag(flagMinify) cmdBuild.Flags().AddFlag(flagColor) cmdBuild.Flags().AddFlag(flagTags) cmdBuild.Run = func(cmd *cobra.Command, args []string) { options.BuildTags = strings.Fields(*tags) for { s := gbuild.NewSession(options) exitCode := handleError(func() error { if len(args) == 0 { return s.BuildDir(currentDirectory, currentDirectory, pkgObj) } if strings.HasSuffix(args[0], ".go") || strings.HasSuffix(args[0], ".inc.js") { for _, arg := range args { if !strings.HasSuffix(arg, ".go") && !strings.HasSuffix(arg, ".inc.js") { return fmt.Errorf("named files must be .go or .inc.js files") } } if pkgObj == "" { basename := filepath.Base(args[0]) pkgObj = basename[:len(basename)-3] + ".js" } names := make([]string, len(args)) for i, name := range args { name = filepath.ToSlash(name) names[i] = name } if err := s.BuildFiles(args, pkgObj, currentDirectory); err != nil { return err } return nil } for _, pkgPath := range args { pkgPath = filepath.ToSlash(pkgPath) pkg, err := gbuild.Import(pkgPath, 0, s.InstallSuffix(), options.BuildTags) if err != nil { return err } archive, err := s.BuildPackage(pkg) if err != nil { return err } if pkgObj == "" { pkgObj = filepath.Base(args[0]) + ".js" } if pkg.IsCommand() && !pkg.UpToDate { if err := s.WriteCommandPackage(archive, pkgObj); err != nil { return err } } } return nil }, options, nil) os.Exit(exitCode) } } cmdInstall := &cobra.Command{ Use: "install [packages]", Short: "compile and install packages and dependencies", } cmdInstall.Flags().AddFlag(flagVerbose) cmdInstall.Flags().AddFlag(flagQuiet) cmdInstall.Flags().AddFlag(flagWatch) cmdInstall.Flags().AddFlag(flagMinify) cmdInstall.Flags().AddFlag(flagColor) cmdInstall.Flags().AddFlag(flagTags) cmdInstall.Run = func(cmd *cobra.Command, args []string) { options.BuildTags = strings.Fields(*tags) for { s := gbuild.NewSession(options) exitCode := handleError(func() error { pkgs := args if len(pkgs) == 0 { firstGopathWorkspace := filepath.SplitList(build.Default.GOPATH)[0] // TODO: The GOPATH workspace that contains the package source should be chosen. srcDir, err := filepath.EvalSymlinks(filepath.Join(firstGopathWorkspace, "src")) if err != nil { return err } if !strings.HasPrefix(currentDirectory, srcDir) { return fmt.Errorf("gopherjs install: no install location for directory %s outside GOPATH", currentDirectory) } pkgPath, err := filepath.Rel(srcDir, currentDirectory) if err != nil { return err } pkgs = []string{pkgPath} } if cmd.Name() == "get" { goGet := exec.Command("go", append([]string{"get", "-d", "-tags=js"}, pkgs...)...) goGet.Stdout = os.Stdout goGet.Stderr = os.Stderr if err := goGet.Run(); err != nil { return err } } for _, pkgPath := range pkgs { pkgPath = filepath.ToSlash(pkgPath) pkg, err := gbuild.Import(pkgPath, 0, s.InstallSuffix(), options.BuildTags) if err != nil { return err } archive, err := s.BuildPackage(pkg) if err != nil { return err } if pkg.IsCommand() && !pkg.UpToDate { if err := s.WriteCommandPackage(archive, pkg.PkgObj); err != nil { return err } } } return nil }, options, nil) os.Exit(exitCode) } } cmdGet := &cobra.Command{ Use: "get [packages]", Short: "download and install packages and dependencies", } cmdGet.Flags().AddFlag(flagVerbose) cmdGet.Flags().AddFlag(flagQuiet) cmdGet.Flags().AddFlag(flagWatch) cmdGet.Flags().AddFlag(flagMinify) cmdGet.Flags().AddFlag(flagColor) cmdGet.Flags().AddFlag(flagTags) cmdGet.Run = cmdInstall.Run cmdRun := &cobra.Command{ Use: "run [gofiles...] [arguments...]", Short: "compile and run Go program", } cmdRun.Run = func(cmd *cobra.Command, args []string) { os.Exit(handleError(func() error { lastSourceArg := 0 for { if lastSourceArg == len(args) || !(strings.HasSuffix(args[lastSourceArg], ".go") || strings.HasSuffix(args[lastSourceArg], ".inc.js")) { break } lastSourceArg++ } if lastSourceArg == 0 { return fmt.Errorf("gopherjs run: no go files listed") } tempfile, err := ioutil.TempFile(currentDirectory, filepath.Base(args[0])+".") if err != nil && strings.HasPrefix(currentDirectory, runtime.GOROOT()) { tempfile, err = ioutil.TempFile("", filepath.Base(args[0])+".") } if err != nil { return err } defer func() { tempfile.Close() os.Remove(tempfile.Name()) os.Remove(tempfile.Name() + ".map") }() s := gbuild.NewSession(options) if err := s.BuildFiles(args[:lastSourceArg], tempfile.Name(), currentDirectory); err != nil { return err } if err := runNode(tempfile.Name(), args[lastSourceArg:], "", options.Quiet); err != nil { return err } return nil }, options, nil)) } cmdTest := &cobra.Command{ Use: "test [packages]", Short: "test packages", } bench := cmdTest.Flags().String("bench", "", "Run benchmarks matching the regular expression. By default, no benchmarks run. To run all benchmarks, use '--bench=.'.") run := cmdTest.Flags().String("run", "", "Run only those tests and examples matching the regular expression.") short := cmdTest.Flags().Bool("short", false, "Tell long-running tests to shorten their run time.") verbose := cmdTest.Flags().BoolP("verbose", "v", false, "Log all tests as they are run. Also print all text from Log and Logf calls even if the test succeeds.") compileOnly := cmdTest.Flags().BoolP("compileonly", "c", false, "Compile the test binary to pkg.test.js but do not run it (where pkg is the last element of the package's import path). The file name can be changed with the -o flag.") outputFilename := cmdTest.Flags().StringP("output", "o", "", "Compile the test binary to the named file. The test still runs (unless -c is specified).") cmdTest.Flags().AddFlag(flagMinify) cmdTest.Flags().AddFlag(flagColor) cmdTest.Run = func(cmd *cobra.Command, args []string) { os.Exit(handleError(func() error { pkgs := make([]*gbuild.PackageData, len(args)) for i, pkgPath := range args { pkgPath = filepath.ToSlash(pkgPath) var err error pkgs[i], err = gbuild.Import(pkgPath, 0, "", nil) if err != nil { return err } } if len(pkgs) == 0 { firstGopathWorkspace := filepath.SplitList(build.Default.GOPATH)[0] srcDir, err := filepath.EvalSymlinks(filepath.Join(firstGopathWorkspace, "src")) if err != nil { return err } var pkg *gbuild.PackageData if strings.HasPrefix(currentDirectory, srcDir) { pkgPath, err := filepath.Rel(srcDir, currentDirectory) if err != nil { return err } if pkg, err = gbuild.Import(pkgPath, 0, "", nil); err != nil { return err } } if pkg == nil { if pkg, err = gbuild.ImportDir(currentDirectory, 0); err != nil { return err } pkg.ImportPath = "_" + currentDirectory } pkgs = []*gbuild.PackageData{pkg} } var exitErr error for _, pkg := range pkgs { if len(pkg.TestGoFiles) == 0 && len(pkg.XTestGoFiles) == 0 { fmt.Printf("? \t%s\t[no test files]\n", pkg.ImportPath) continue } s := gbuild.NewSession(options) tests := &testFuncs{Package: pkg.Package} collectTests := func(testPkg *gbuild.PackageData, testPkgName string, needVar *bool) error { archive, err := s.BuildPackage(testPkg) if err != nil { return err } for _, decl := range archive.Declarations { if strings.HasPrefix(decl.FullName, testPkg.ImportPath+".Test") { tests.Tests = append(tests.Tests, testFunc{Package: testPkgName, Name: decl.FullName[len(testPkg.ImportPath)+1:]}) *needVar = true } if strings.HasPrefix(decl.FullName, testPkg.ImportPath+".Benchmark") { tests.Benchmarks = append(tests.Benchmarks, testFunc{Package: testPkgName, Name: decl.FullName[len(testPkg.ImportPath)+1:]}) *needVar = true } } return nil } if err := collectTests(&gbuild.PackageData{ Package: &build.Package{ ImportPath: pkg.ImportPath, Dir: pkg.Dir, GoFiles: append(pkg.GoFiles, pkg.TestGoFiles...), Imports: append(pkg.Imports, pkg.TestImports...), }, IsTest: true, JSFiles: pkg.JSFiles, }, "_test", &tests.NeedTest); err != nil { return err } if err := collectTests(&gbuild.PackageData{ Package: &build.Package{ ImportPath: pkg.ImportPath + "_test", Dir: pkg.Dir, GoFiles: pkg.XTestGoFiles, Imports: pkg.XTestImports, }, IsTest: true, }, "_xtest", &tests.NeedXtest); err != nil { return err } buf := bytes.NewBuffer(nil) if err := testmainTmpl.Execute(buf, tests); err != nil { return err } fset := token.NewFileSet() mainFile, err := parser.ParseFile(fset, "_testmain.go", buf, 0) if err != nil { return err } importContext := &compiler.ImportContext{ Packages: s.Types, Import: func(path string) (*compiler.Archive, error) { if path == pkg.ImportPath || path == pkg.ImportPath+"_test" { return s.Archives[path], nil } return s.BuildImportPath(path) }, } mainPkgArchive, err := compiler.Compile("main", []*ast.File{mainFile}, fset, importContext, options.Minify) if err != nil { return err } if *compileOnly && *outputFilename == "" { *outputFilename = pkg.Package.Name + "_test.js" } var outfile *os.File if *outputFilename != "" { outfile, err = os.Create(*outputFilename) if err != nil { return err } } else { outfile, err = ioutil.TempFile(currentDirectory, "test.") if err != nil { return err } } defer func() { outfile.Close() if *outputFilename == "" { os.Remove(outfile.Name()) os.Remove(outfile.Name() + ".map") } }() if err := s.WriteCommandPackage(mainPkgArchive, outfile.Name()); err != nil { return err } if *compileOnly { continue } var args []string if *bench != "" { args = append(args, "-test.bench", *bench) } if *run != "" { args = append(args, "-test.run", *run) } if *short { args = append(args, "-test.short") } if *verbose { args = append(args, "-test.v") } status := "ok " start := time.Now() if err := runNode(outfile.Name(), args, pkg.Dir, options.Quiet); err != nil { if _, ok := err.(*exec.ExitError); !ok { return err } exitErr = err status = "FAIL" } fmt.Printf("%s\t%s\t%.3fs\n", status, pkg.ImportPath, time.Now().Sub(start).Seconds()) } return exitErr }, options, nil)) } cmdTool := &cobra.Command{ Use: "tool [command] [args...]", Short: "run specified go tool", } cmdTool.Flags().BoolP("e", "e", false, "") cmdTool.Flags().BoolP("l", "l", false, "") cmdTool.Flags().StringP("o", "o", "", "") cmdTool.Flags().StringP("D", "D", "", "") cmdTool.Flags().StringP("I", "I", "", "") cmdTool.Run = func(cmd *cobra.Command, args []string) { os.Exit(handleError(func() error { if len(args) == 2 { switch args[0][1] { case 'g': basename := filepath.Base(args[1]) s := gbuild.NewSession(options) if err := s.BuildFiles([]string{args[1]}, basename[:len(basename)-3]+".js", currentDirectory); err != nil { return err } return nil } } cmdTool.Help() return nil }, options, nil)) } cmdServe := &cobra.Command{ Use: "serve [root]", Short: "compile on-the-fly and serve", } cmdServe.Flags().AddFlag(flagVerbose) cmdServe.Flags().AddFlag(flagQuiet) cmdServe.Flags().AddFlag(flagMinify) cmdServe.Flags().AddFlag(flagColor) cmdServe.Flags().AddFlag(flagTags) var addr string cmdServe.Flags().StringVarP(&addr, "http", "", ":8080", "HTTP bind address to serve") cmdServe.Run = func(cmd *cobra.Command, args []string) { options.BuildTags = strings.Fields(*tags) dirs := append(filepath.SplitList(build.Default.GOPATH), build.Default.GOROOT) var root string if len(args) > 1 { cmdServe.Help() return } if len(args) == 1 { root = args[0] } sourceFiles := http.FileServer(serveCommandFileSystem{ serveRoot: root, options: options, dirs: dirs, sourceMaps: make(map[string][]byte), }) ln, err := net.Listen("tcp", addr) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if tcpAddr := ln.Addr().(*net.TCPAddr); tcpAddr.IP.Equal(net.IPv4zero) || tcpAddr.IP.Equal(net.IPv6zero) { // Any available addresses. fmt.Printf("serving at http://localhost:%d and on port %d of any available addresses\n", tcpAddr.Port, tcpAddr.Port) } else { // Specific address. fmt.Printf("serving at http://%s\n", tcpAddr) } fmt.Fprintln(os.Stderr, http.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)}, sourceFiles)) } rootCmd := &cobra.Command{ Use: "gopherjs", Long: "GopherJS is a tool for compiling Go source code to JavaScript.", } rootCmd.AddCommand(cmdBuild, cmdGet, cmdInstall, cmdRun, cmdTest, cmdTool, cmdServe) rootCmd.Execute() }
func init() { pflag.BoolVar(&debug, "debug", false, "debug mode") }
func init() { flag.BoolVar(&readinessCheck, "readiness-check", false, "Set to true when checking if local pod is ready") flag.Parse() }
func init() { flag.StringVar(&inputFile, "input", defaultInputFile, "Go source code containing types to be documented") flag.StringVar(&outputFile, "output", defaultOutputFile, "file to which generated Go code should be written") flag.BoolVar(&verify, "verify", defaultVerify, "verify that types being documented are not missing any comments, write no output") }
func main() { options := &gbuild.Options{CreateMapFile: true} var pkgObj string pflag.BoolVarP(&options.Verbose, "verbose", "v", false, "print the names of packages as they are compiled") flagVerbose := pflag.Lookup("verbose") pflag.BoolVarP(&options.Watch, "watch", "w", false, "watch for changes to the source files") flagWatch := pflag.Lookup("watch") pflag.BoolVarP(&options.Minify, "minify", "m", false, "minify generated code") flagMinify := pflag.Lookup("minify") pflag.BoolVar(&options.Color, "color", terminal.IsTerminal(int(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb", "colored output") flagColor := pflag.Lookup("color") tags := pflag.String("tags", "", "a list of build tags to consider satisfied during the build") flagTags := pflag.Lookup("tags") cmdBuild := &cobra.Command{ Use: "build [packages]", Short: "compile packages and dependencies", } cmdBuild.Flags().StringVarP(&pkgObj, "output", "o", "", "output file") cmdBuild.Flags().AddFlag(flagVerbose) cmdBuild.Flags().AddFlag(flagWatch) cmdBuild.Flags().AddFlag(flagMinify) cmdBuild.Flags().AddFlag(flagColor) cmdBuild.Flags().AddFlag(flagTags) cmdBuild.Run = func(cmd *cobra.Command, args []string) { options.BuildTags = strings.Fields(*tags) for { s := gbuild.NewSession(options) exitCode := handleError(func() error { if len(args) == 0 { return s.BuildDir(currentDirectory, currentDirectory, pkgObj) } if strings.HasSuffix(args[0], ".go") || strings.HasSuffix(args[0], ".inc.js") { for _, arg := range args { if !strings.HasSuffix(arg, ".go") && !strings.HasSuffix(arg, ".inc.js") { return fmt.Errorf("named files must be .go or .inc.js files") } } if pkgObj == "" { basename := filepath.Base(args[0]) pkgObj = basename[:len(basename)-3] + ".js" } names := make([]string, len(args)) for i, name := range args { name = filepath.ToSlash(name) names[i] = name if s.Watcher != nil { s.Watcher.Add(name) } } if err := s.BuildFiles(args, pkgObj, currentDirectory); err != nil { return err } return nil } for _, pkgPath := range args { pkgPath = filepath.ToSlash(pkgPath) if s.Watcher != nil { s.Watcher.Add(pkgPath) } buildPkg, err := gbuild.Import(pkgPath, 0, s.InstallSuffix(), options.BuildTags) if err != nil { return err } pkg := &gbuild.PackageData{Package: buildPkg} if err := s.BuildPackage(pkg); err != nil { return err } if pkgObj == "" { pkgObj = filepath.Base(args[0]) + ".js" } if err := s.WriteCommandPackage(pkg, pkgObj); err != nil { return err } } return nil }, options, nil) if s.Watcher == nil { os.Exit(exitCode) } s.WaitForChange() } } cmdInstall := &cobra.Command{ Use: "install [packages]", Short: "compile and install packages and dependencies", } cmdInstall.Flags().AddFlag(flagVerbose) cmdInstall.Flags().AddFlag(flagWatch) cmdInstall.Flags().AddFlag(flagMinify) cmdInstall.Flags().AddFlag(flagColor) cmdInstall.Flags().AddFlag(flagTags) cmdInstall.Run = func(cmd *cobra.Command, args []string) { options.BuildTags = strings.Fields(*tags) for { s := gbuild.NewSession(options) exitCode := handleError(func() error { pkgs := args if len(pkgs) == 0 { firstGopathWorkspace := filepath.SplitList(build.Default.GOPATH)[0] // TODO: The GOPATH workspace that contains the package source should be chosen. srcDir, err := filepath.EvalSymlinks(filepath.Join(firstGopathWorkspace, "src")) if err != nil { return err } if !strings.HasPrefix(currentDirectory, srcDir) { return fmt.Errorf("gopherjs install: no install location for directory %s outside GOPATH", currentDirectory) } pkgPath, err := filepath.Rel(srcDir, currentDirectory) if err != nil { return err } pkgs = []string{pkgPath} } if cmd.Name() == "get" { goGet := exec.Command("go", append([]string{"get", "-d"}, pkgs...)...) goGet.Stdout = os.Stdout goGet.Stderr = os.Stderr if err := goGet.Run(); err != nil { return err } } for _, pkgPath := range pkgs { pkgPath = filepath.ToSlash(pkgPath) if _, err := s.ImportPackage(pkgPath); err != nil { return err } pkg := s.Packages[pkgPath] if err := s.WriteCommandPackage(pkg, pkg.PkgObj); err != nil { return err } } return nil }, options, nil) if s.Watcher == nil { os.Exit(exitCode) } s.WaitForChange() } } cmdGet := &cobra.Command{ Use: "get [packages]", Short: "download and install packages and dependencies", } cmdGet.Flags().AddFlag(flagVerbose) cmdGet.Flags().AddFlag(flagWatch) cmdGet.Flags().AddFlag(flagMinify) cmdGet.Flags().AddFlag(flagColor) cmdGet.Flags().AddFlag(flagTags) cmdGet.Run = cmdInstall.Run cmdRun := &cobra.Command{ Use: "run [gofiles...] [arguments...]", Short: "compile and run Go program", } cmdRun.Run = func(cmd *cobra.Command, args []string) { os.Exit(handleError(func() error { lastSourceArg := 0 for { if lastSourceArg == len(args) || !(strings.HasSuffix(args[lastSourceArg], ".go") || strings.HasSuffix(args[lastSourceArg], ".inc.js")) { break } lastSourceArg++ } if lastSourceArg == 0 { return fmt.Errorf("gopherjs run: no go files listed") } tempfile, err := ioutil.TempFile("", filepath.Base(args[0])+".") if err != nil { return err } defer func() { tempfile.Close() os.Remove(tempfile.Name()) os.Remove(tempfile.Name() + ".map") }() s := gbuild.NewSession(options) if err := s.BuildFiles(args[:lastSourceArg], tempfile.Name(), currentDirectory); err != nil { return err } if err := runNode(tempfile.Name(), args[lastSourceArg:], ""); err != nil { return err } return nil }, options, nil)) } cmdTest := &cobra.Command{ Use: "test [packages]", Short: "test packages", } bench := cmdTest.Flags().String("bench", "", "Run benchmarks matching the regular expression. By default, no benchmarks run. To run all benchmarks, use '--bench=.'.") run := cmdTest.Flags().String("run", "", "Run only those tests and examples matching the regular expression.") short := cmdTest.Flags().Bool("short", false, "Tell long-running tests to shorten their run time.") verbose := cmdTest.Flags().BoolP("verbose", "v", false, "Log all tests as they are run. Also print all text from Log and Logf calls even if the test succeeds.") cmdTest.Flags().AddFlag(flagMinify) cmdTest.Flags().AddFlag(flagColor) cmdTest.Run = func(cmd *cobra.Command, args []string) { os.Exit(handleError(func() error { pkgs := make([]*build.Package, len(args)) for i, pkgPath := range args { pkgPath = filepath.ToSlash(pkgPath) var err error pkgs[i], err = gbuild.Import(pkgPath, 0, "", nil) if err != nil { return err } } if len(pkgs) == 0 { firstGopathWorkspace := filepath.SplitList(build.Default.GOPATH)[0] srcDir, err := filepath.EvalSymlinks(filepath.Join(firstGopathWorkspace, "src")) if err != nil { return err } var pkg *build.Package if strings.HasPrefix(currentDirectory, srcDir) { pkgPath, err := filepath.Rel(srcDir, currentDirectory) if err != nil { return err } if pkg, err = gbuild.Import(pkgPath, 0, "", nil); err != nil { return err } } if pkg == nil { if pkg, err = build.ImportDir(currentDirectory, 0); err != nil { return err } pkg.ImportPath = "_" + currentDirectory } pkgs = []*build.Package{pkg} } var exitErr error for _, pkg := range pkgs { if len(pkg.TestGoFiles) == 0 && len(pkg.XTestGoFiles) == 0 { fmt.Printf("? \t%s\t[no test files]\n", pkg.ImportPath) continue } s := gbuild.NewSession(options) tests := &testFuncs{Package: pkg} collectTests := func(buildPkg *build.Package, testPkgName string, needVar *bool) error { testPkg := &gbuild.PackageData{Package: buildPkg} if err := s.BuildPackage(testPkg); err != nil { return err } for _, decl := range testPkg.Archive.Declarations { if strings.HasPrefix(decl.FullName, testPkg.ImportPath+".Test") { tests.Tests = append(tests.Tests, testFunc{Package: testPkgName, Name: decl.FullName[len(testPkg.ImportPath)+1:]}) *needVar = true } if strings.HasPrefix(decl.FullName, testPkg.ImportPath+".Benchmark") { tests.Benchmarks = append(tests.Benchmarks, testFunc{Package: testPkgName, Name: decl.FullName[len(testPkg.ImportPath)+1:]}) *needVar = true } } return nil } if err := collectTests(&build.Package{ ImportPath: pkg.ImportPath, Dir: pkg.Dir, GoFiles: append(pkg.GoFiles, pkg.TestGoFiles...), Imports: append(pkg.Imports, pkg.TestImports...), }, "_test", &tests.NeedTest); err != nil { return err } if err := collectTests(&build.Package{ ImportPath: pkg.ImportPath + "_test", Dir: pkg.Dir, GoFiles: pkg.XTestGoFiles, Imports: pkg.XTestImports, }, "_xtest", &tests.NeedXtest); err != nil { return err } buf := bytes.NewBuffer(nil) if err := testmainTmpl.Execute(buf, tests); err != nil { return err } fset := token.NewFileSet() mainFile, err := parser.ParseFile(fset, "_testmain.go", buf, 0) if err != nil { return err } mainPkg := &gbuild.PackageData{ Package: &build.Package{ Name: "main", ImportPath: "main", }, } mainPkg.Archive, err = compiler.Compile("main", []*ast.File{mainFile}, fset, s.ImportContext, options.Minify) if err != nil { return err } tempfile, err := ioutil.TempFile("", "test.") if err != nil { return err } defer func() { tempfile.Close() os.Remove(tempfile.Name()) os.Remove(tempfile.Name() + ".map") }() if err := s.WriteCommandPackage(mainPkg, tempfile.Name()); err != nil { return err } var args []string if *bench != "" { args = append(args, "-test.bench", *bench) } if *run != "" { args = append(args, "-test.run", *run) } if *short { args = append(args, "-test.short") } if *verbose { args = append(args, "-test.v") } status := "ok " start := time.Now() if err := runNode(tempfile.Name(), args, pkg.Dir); err != nil { if _, ok := err.(*exec.ExitError); !ok { return err } exitErr = err status = "FAIL" } fmt.Printf("%s\t%s\t%.3fs\n", status, pkg.ImportPath, time.Now().Sub(start).Seconds()) } return exitErr }, options, nil)) } cmdTool := &cobra.Command{ Use: "tool [command] [args...]", Short: "run specified go tool", } cmdTool.Flags().BoolP("e", "e", false, "") cmdTool.Flags().BoolP("l", "l", false, "") cmdTool.Flags().BoolP("m", "m", false, "") cmdTool.Flags().StringP("o", "o", "", "") cmdTool.Flags().StringP("D", "D", "", "") cmdTool.Flags().StringP("I", "I", "", "") cmdTool.Run = func(cmd *cobra.Command, args []string) { os.Exit(handleError(func() error { if len(args) == 2 { switch args[0][1] { case 'g': basename := filepath.Base(args[1]) s := gbuild.NewSession(options) if err := s.BuildFiles([]string{args[1]}, basename[:len(basename)-3]+".js", currentDirectory); err != nil { return err } return nil } } cmdTool.Help() return nil }, options, nil)) } cmdServe := &cobra.Command{ Use: "serve", Short: "compile on-the-fly and serve", } cmdServe.Flags().AddFlag(flagVerbose) cmdServe.Flags().AddFlag(flagMinify) cmdServe.Flags().AddFlag(flagColor) cmdServe.Flags().AddFlag(flagTags) var port int cmdServe.Flags().IntVarP(&port, "port", "p", 8080, "HTTP port") cmdServe.Run = func(cmd *cobra.Command, args []string) { options.BuildTags = strings.Fields(*tags) dirs := append(filepath.SplitList(build.Default.GOPATH), build.Default.GOROOT) sourceFiles := http.FileServer(serveCommandFileSystem{options: options, dirs: dirs, sourceMaps: make(map[string][]byte)}) fmt.Printf("serving at http://localhost:%d\n", port) fmt.Println(http.ListenAndServe(fmt.Sprintf(":%d", port), sourceFiles)) } rootCmd := &cobra.Command{ Use: "gopherjs", Long: "GopherJS is a tool for compiling Go source code to JavaScript.", } rootCmd.AddCommand(cmdBuild, cmdGet, cmdInstall, cmdRun, cmdTest, cmdTool, cmdServe) rootCmd.Execute() }
func init() { pflag.IntVar(&l, "logLevel", 0, "log level in which gologger logs to") pflag.StringVar(&c, "logCatagory", "", "log catagory which used for logging") pflag.BoolVar(&forceToGlog, "forceToGlog", false, "use glog for all logging. cancel other logging.") pflag.BoolVar(&alsoLogToGlog, "alsoLogToGlog", false, "also use glog as side logging.") }
func main() { pflag.BoolVar(&sentinelMode, "sentinel-mode", false, "Whether using Sentinel") pflag.StringVar(&redisAddress, "redis-addr", ":6379", "Redis address, can be ignored while setting sentinel mode") pflag.StringVar(&conf.MasterName, "master-name", "mymaster", "Redis Sentinel master name") pflag.StringSliceVar(&conf.Addresses, "sentinel-ips", []string{"172.31.33.2:26379", "172.31.33.3:26379", "172.31.75.4:26379"}, "Sentinel failover addresses") pflag.Parse() if sentinelMode { fmt.Println("block to wait connection") var err error //go func() {store, err = connectSentinel()}() store, err = connectSentinel() if err != nil { fmt.Println("Failed to create connection! Please contact SysOps") return } } else { //store = sessions.NewCookieStore([]byte("something-very-secret")) //store = sessions.NewFilesystemStore("", []byte("something-very-secret")) //store, err := redistore.NewRediStore(10, "tcp", ".6379", "", []byte("secret-key")) redistore, err := redistore.NewRediStore(10, "tcp", redisAddress, "", []byte("authentication-secret-key")) if err != nil { fmt.Println("Failed to ping Redis! Please contact SysOps") return } store = redistore } gob.Register(&Person{}) port := os.Getenv("PORT") if port == "" { port = "80" } router := mux.NewRouter() router.HandleFunc("/signup/{signup}", makeHandler(signupHandler)).Methods("GET", "POST") router.HandleFunc("/signin/{signin}", makeHandler(signinHandler)).Methods("GET", "POST") router.HandleFunc("/profile/{profile}", makeHandler(profileHandler)).Methods("GET", "POST") router.HandleFunc("/signout/{signout}", makeHandler(signoutHandler)).Methods("GET", "POST") //router.HandleFunc("/index.html", makeHandler(indexHandler)).Methods("GET") // substituted by following statement router.HandleFunc("/{others}", func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) others := vars["others"] if m := indexRegex.FindStringSubmatch(strings.ToLower(others)); m != nil { indexHandler(w, r, others[:len("index")]) return } http.NotFound(w, r) }).Methods("GET") router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { http.Redirect(w, r, "/index.html", http.StatusFound) } }).Methods("GET") http.Handle("/", router) loadTemplates() fmt.Printf("Listening on port %s\n", port) log.Fatal(http.ListenAndServe(":"+port, nil)) }