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

package controller

import (
	"fmt"
	"strings"

	"github.com/juju/cmd"
	"github.com/juju/errors"
	"launchpad.net/gnuflag"

	"github.com/juju/juju/cmd/modelcmd"
	"github.com/juju/juju/jujuclient"
)

var helpControllersSummary = `
Lists all controllers.`[1:]

var helpControllersDetails = `
The output format may be selected with the '--format' option. In the
default tabular output, the current controller is marked with an asterisk.

Examples:
juju list-controllers
juju list-controllers --format json --output ~/tmp/controllers.json

See also:
list-models
show-controller`[1:]

// NewListControllersCommand returns a command to list registered controllers.
func NewListControllersCommand() cmd.Command {
	cmd := &listControllersCommand{
		store: jujuclient.NewFileClientStore(),
	}
	return modelcmd.WrapBase(cmd)
}

// Info implements Command.Info
func (c *listControllersCommand) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "list-controllers",
		Purpose: helpControllersSummary,
		Doc:     helpControllersDetails,
	}
}

// SetFlags implements Command.SetFlags.
func (c *listControllersCommand) SetFlags(f *gnuflag.FlagSet) {
	c.JujuCommandBase.SetFlags(f)
	c.out.AddFlags(f, "tabular", map[string]cmd.Formatter{
		"yaml":    cmd.FormatYaml,
		"json":    cmd.FormatJson,
		"tabular": formatControllersListTabular,
	})
}

// Run implements Command.Run
func (c *listControllersCommand) Run(ctx *cmd.Context) error {
	controllers, err := c.store.AllControllers()
	if err != nil {
		return errors.Annotate(err, "failed to list controllers")
	}
	details, errs := c.convertControllerDetails(controllers)
	if len(errs) > 0 {
		fmt.Fprintln(ctx.Stderr, strings.Join(errs, "\n"))
	}
	currentController, err := modelcmd.ReadCurrentController()
	if err != nil {
		return errors.Annotate(err, "getting current controller")
	}
	if _, ok := controllers[currentController]; !ok {
		// TODO(axw) move handling of current-controller to
		// the jujuclient code, and make sure the file is
		// kept in-sync with the controllers.yaml file.
		currentController = ""
	}
	controllerSet := ControllerSet{
		Controllers:       details,
		CurrentController: currentController,
	}
	return c.out.Write(ctx, controllerSet)
}

type listControllersCommand struct {
	modelcmd.JujuCommandBase

	out   cmd.Output
	store jujuclient.ClientStore
}
<commit_msg>Update indentation for list-controllers<commit_after>// Copyright 2015,2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package controller

import (
	"fmt"
	"strings"

	"github.com/juju/cmd"
	"github.com/juju/errors"
	"launchpad.net/gnuflag"

	"github.com/juju/juju/cmd/modelcmd"
	"github.com/juju/juju/jujuclient"
)

var helpControllersSummary = `
Lists all controllers.`[1:]

var helpControllersDetails = `
The output format may be selected with the '--format' option. In the
default tabular output, the current controller is marked with an asterisk.

Examples:
    juju list-controllers
    juju list-controllers --format json --output ~/tmp/controllers.json

See also:
    list-models
    show-controller`[1:]

// NewListControllersCommand returns a command to list registered controllers.
func NewListControllersCommand() cmd.Command {
	cmd := &listControllersCommand{
		store: jujuclient.NewFileClientStore(),
	}
	return modelcmd.WrapBase(cmd)
}

// Info implements Command.Info
func (c *listControllersCommand) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "list-controllers",
		Purpose: helpControllersSummary,
		Doc:     helpControllersDetails,
	}
}

// SetFlags implements Command.SetFlags.
func (c *listControllersCommand) SetFlags(f *gnuflag.FlagSet) {
	c.JujuCommandBase.SetFlags(f)
	c.out.AddFlags(f, "tabular", map[string]cmd.Formatter{
		"yaml":    cmd.FormatYaml,
		"json":    cmd.FormatJson,
		"tabular": formatControllersListTabular,
	})
}

// Run implements Command.Run
func (c *listControllersCommand) Run(ctx *cmd.Context) error {
	controllers, err := c.store.AllControllers()
	if err != nil {
		return errors.Annotate(err, "failed to list controllers")
	}
	details, errs := c.convertControllerDetails(controllers)
	if len(errs) > 0 {
		fmt.Fprintln(ctx.Stderr, strings.Join(errs, "\n"))
	}
	currentController, err := modelcmd.ReadCurrentController()
	if err != nil {
		return errors.Annotate(err, "getting current controller")
	}
	if _, ok := controllers[currentController]; !ok {
		// TODO(axw) move handling of current-controller to
		// the jujuclient code, and make sure the file is
		// kept in-sync with the controllers.yaml file.
		currentController = ""
	}
	controllerSet := ControllerSet{
		Controllers:       details,
		CurrentController: currentController,
	}
	return c.out.Write(ctx, controllerSet)
}

type listControllersCommand struct {
	modelcmd.JujuCommandBase

	out   cmd.Output
	store jujuclient.ClientStore
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"flag"
	"fmt"
	"log"
	"net"
	"os"
	"time"

	"github.com/BurntSushi/toml"
	"github.com/Sirupsen/logrus"

	"devroom.ru/lomik/carbon"
)

// Duration wrapper time.Duration for TOML
type Duration struct {
	time.Duration
}

var _ toml.TextMarshaler = &Duration{}

// UnmarshalText from TOML
func (d *Duration) UnmarshalText(text []byte) error {
	var err error
	d.Duration, err = time.ParseDuration(string(text))
	return err
}

// MarshalText encode text with TOML format
func (d *Duration) MarshalText() ([]byte, error) {
	return []byte(d.Duration.String()), nil
}

// Value return time.Duration value
func (d *Duration) Value() time.Duration {
	return d.Duration
}

type whisperConfig struct {
	DataDir string `toml:"data-dir"`
	Schemas string `toml:"data-file"`
	Enabled bool   `toml:"enabled"`
}

type udpConfig struct {
	Listen  string `toml:"listen"`
	Enabled bool   `toml:"enabled"`
}

type tcpConfig struct {
	Listen  string `toml:"listen"`
	Enabled bool   `toml:"enabled"`
}

type carbonlinkConfig struct {
	Listen      string    `toml:"listen"`
	Enabled     bool      `toml:"enabled"`
	ReadTimeout *Duration `toml:"read-timeout"`
}

// Config ...
type Config struct {
	Logfile    string                      `toml:"logfile"`
	Whisper    whisperConfig               `toml:"whisper"`
	Udp        map[string]udpConfig        `toml:"udp"`
	Tcp        map[string]tcpConfig        `toml:"tcp"`
	Carbonlink map[string]carbonlinkConfig `toml:"carbonlink"`
}

func newConfig() *Config {
	cfg := &Config{
		Logfile: "",
		Whisper: whisperConfig{
			DataDir: "/data/graphite/whisper/",
			Schemas: "/data/graphite/schemas",
			Enabled: true,
		},
		Udp: map[string]udpConfig{
			"default": udpConfig{
				Listen:  ":2003",
				Enabled: true,
			},
		},
		Tcp: map[string]tcpConfig{
			"default": tcpConfig{
				Listen:  ":2003",
				Enabled: true,
			},
		},
		Carbonlink: map[string]carbonlinkConfig{
			"default": carbonlinkConfig{
				Listen:  ":2004", //??
				Enabled: true,
				ReadTimeout: &Duration{
					Duration: 30 * time.Second,
				},
			},
		},
	}

	return cfg
}

// PrintConfig ...
func PrintConfig(cfg interface{}) error {
	buf := new(bytes.Buffer)

	encoder := toml.NewEncoder(buf)
	encoder.Indent = ""

	if err := encoder.Encode(cfg); err != nil {
		return err
	}

	fmt.Print(buf.String())
	return nil
}

// ParseConfig ...
func ParseConfig(filename string, cfg interface{}) error {
	if filename != "" {
		if _, err := toml.DecodeFile(filename, cfg); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	/* CONFIG start */
	configFile := flag.String("config", "", "Filename of config")
	printDefaultConfig := flag.Bool("config-print-default", false, "Print default config")

	flag.Parse()

	cfg := newConfig()

	if *printDefaultConfig {
		if err := PrintConfig(cfg); err != nil {
			log.Fatal(err)
		}
		os.Exit(0)
	}

	if err := ParseConfig(*configFile, cfg); err != nil {
		log.Fatal(err)
	}

	// pp.Println(cfg)
	/* CONFIG end */

	cache := carbon.NewCache()
	cache.Start()
	defer cache.Stop()

	/* UDP start */
	for _, udpCfg := range cfg.Udp {
		if udpCfg.Enabled {
			udpAddr, err := net.ResolveUDPAddr("udp", udpCfg.Listen)
			if err != nil {
				log.Fatal(err)
			}

			udpListener := carbon.NewUDPReceiver(cache.In())
			defer udpListener.Stop()
			if err = udpListener.Listen(udpAddr); err != nil {
				log.Fatal(err)
			}
		}
	}
	/* UDP end */

	/* TCP start */
	for _, tcpCfg := range cfg.Tcp {
		if tcpCfg.Enabled {
			tcpAddr, err := net.ResolveTCPAddr("tcp", tcpCfg.Listen)
			if err != nil {
				log.Fatal(err)
			}

			tcpListener := carbon.NewTCPReceiver(cache.In())
			defer tcpListener.Stop()
			if err = tcpListener.Listen(tcpAddr); err != nil {
				log.Fatal(err)
			}
		}
	}
	/* TCP end */

	/* WHISPER start */
	if cfg.Whisper.Enabled {
		whisperSchemas, err := carbon.ReadWhisperSchemas(cfg.Whisper.Schemas)
		if err != nil {
			log.Fatal(err)
		}

		whisperPersister := carbon.NewWhisperPersister(cfg.Whisper.DataDir, whisperSchemas, cache.Out())

		whisperPersister.Start()
		defer whisperPersister.Stop()
	}
	/* WHISPER end */

	logrus.Info("started")
	select {}
}
<commit_msg>solo udp/tcp listeners. simple config<commit_after>package main

import (
	"bytes"
	"flag"
	"fmt"
	"log"
	"net"
	"os"
	"time"

	"github.com/BurntSushi/toml"
	"github.com/Sirupsen/logrus"

	"devroom.ru/lomik/carbon"
)

// Duration wrapper time.Duration for TOML
type Duration struct {
	time.Duration
}

var _ toml.TextMarshaler = &Duration{}

// UnmarshalText from TOML
func (d *Duration) UnmarshalText(text []byte) error {
	var err error
	d.Duration, err = time.ParseDuration(string(text))
	return err
}

// MarshalText encode text with TOML format
func (d *Duration) MarshalText() ([]byte, error) {
	return []byte(d.Duration.String()), nil
}

// Value return time.Duration value
func (d *Duration) Value() time.Duration {
	return d.Duration
}

type whisperConfig struct {
	DataDir string `toml:"data-dir"`
	Schemas string `toml:"data-file"`
	Enabled bool   `toml:"enabled"`
}

type udpConfig struct {
	Listen  string `toml:"listen"`
	Enabled bool   `toml:"enabled"`
}

type tcpConfig struct {
	Listen  string `toml:"listen"`
	Enabled bool   `toml:"enabled"`
}

type carbonlinkConfig struct {
	Listen      string    `toml:"listen"`
	Enabled     bool      `toml:"enabled"`
	ReadTimeout *Duration `toml:"read-timeout"`
}

// Config ...
type Config struct {
	Logfile    string           `toml:"logfile"`
	Whisper    whisperConfig    `toml:"whisper"`
	Udp        udpConfig        `toml:"udp"`
	Tcp        tcpConfig        `toml:"tcp"`
	Carbonlink carbonlinkConfig `toml:"carbonlink"`
}

func newConfig() *Config {
	cfg := &Config{
		Logfile: "",
		Whisper: whisperConfig{
			DataDir: "/data/graphite/whisper/",
			Schemas: "/data/graphite/schemas",
			Enabled: true,
		},
		Udp: udpConfig{
			Listen:  ":2003",
			Enabled: true,
		},
		Tcp: tcpConfig{
			Listen:  ":2003",
			Enabled: true,
		},
		Carbonlink: carbonlinkConfig{
			Listen:  ":2004", //??
			Enabled: true,
			ReadTimeout: &Duration{
				Duration: 30 * time.Second,
			},
		},
	}

	return cfg
}

// PrintConfig ...
func PrintConfig(cfg interface{}) error {
	buf := new(bytes.Buffer)

	encoder := toml.NewEncoder(buf)
	encoder.Indent = ""

	if err := encoder.Encode(cfg); err != nil {
		return err
	}

	fmt.Print(buf.String())
	return nil
}

// ParseConfig ...
func ParseConfig(filename string, cfg interface{}) error {
	if filename != "" {
		if _, err := toml.DecodeFile(filename, cfg); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	/* CONFIG start */
	configFile := flag.String("config", "", "Filename of config")
	printDefaultConfig := flag.Bool("config-print-default", false, "Print default config")

	flag.Parse()

	cfg := newConfig()

	if *printDefaultConfig {
		if err := PrintConfig(cfg); err != nil {
			log.Fatal(err)
		}
		os.Exit(0)
	}

	if err := ParseConfig(*configFile, cfg); err != nil {
		log.Fatal(err)
	}

	// pp.Println(cfg)
	/* CONFIG end */

	cache := carbon.NewCache()
	cache.Start()
	defer cache.Stop()

	/* UDP start */
	udpCfg := cfg.Udp
	if udpCfg.Enabled {
		udpAddr, err := net.ResolveUDPAddr("udp", udpCfg.Listen)
		if err != nil {
			log.Fatal(err)
		}

		udpListener := carbon.NewUDPReceiver(cache.In())
		defer udpListener.Stop()
		if err = udpListener.Listen(udpAddr); err != nil {
			log.Fatal(err)
		}
	}
	/* UDP end */

	/* TCP start */
	tcpCfg := cfg.Tcp

	if tcpCfg.Enabled {
		tcpAddr, err := net.ResolveTCPAddr("tcp", tcpCfg.Listen)
		if err != nil {
			log.Fatal(err)
		}

		tcpListener := carbon.NewTCPReceiver(cache.In())
		defer tcpListener.Stop()
		if err = tcpListener.Listen(tcpAddr); err != nil {
			log.Fatal(err)
		}
	}
	/* TCP end */

	/* WHISPER start */
	if cfg.Whisper.Enabled {
		whisperSchemas, err := carbon.ReadWhisperSchemas(cfg.Whisper.Schemas)
		if err != nil {
			log.Fatal(err)
		}

		whisperPersister := carbon.NewWhisperPersister(cfg.Whisper.DataDir, whisperSchemas, cache.Out())

		whisperPersister.Start()
		defer whisperPersister.Stop()
	}
	/* WHISPER end */

	logrus.Info("started")
	select {}
}
<|endoftext|>


<commit_before>package go_koans

func aboutAllocation() {
	a := new(int)
	*a = 3
	assert(*a == __int__) // new() creates a pointer to the given type, like malloc() in C

	type person struct {
		name string
		age  int
	}
	bob := new(person)
	assert(bob.age == __int__) // it can allocate memory for custom types as well

	slice := make([]int, 3)
	assert(len(slice) == __int__) // make() creates slices of a given length

	slice = make([]int, 3, __positive_int__) // but can also take an optional capacity
	assert(cap(slice) == 20)

	m := make(map[int]string)
	assert(len(m) == __int__) // make() also creates maps
}
<commit_msg>Allocation Koan<commit_after>package go_koans

func aboutAllocation() {
	a := new(int)
	*a = 3
	assert(*a == 3) // new() creates a pointer to the given type, like malloc() in C

	type person struct {
		name string
		age  int
	}
	bob := new(person)
	assert(bob.age == 0) // it can allocate memory for custom types as well

	slice := make([]int, 3)
	assert(len(slice) == 3) // make() creates slices of a given length

	slice = make([]int, 3, 20) // but can also take an optional capacity
	assert(cap(slice) == 20)

	m := make(map[int]string)
	assert(len(m) == 0) // make() also creates maps
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/codegangsta/cli"
	"github.com/keybase/client/go/libcmdline"
	"github.com/keybase/client/go/libkb"
)

func NewCmdPGPEncrypt(cl *libcmdline.CommandLine) cli.Command {
	return cli.Command{
		Name:        "encrypt",
		Usage:       "keybase pgp encrypt [-r] [-l] [--batch] [--prompt-remote] [-s] [-m MESSAGE] [-b] [-o OUTPUT] [-i file] them",
		Description: "PGP encrypt messages or files for keybase users.",
		Action: func(c *cli.Context) {
			cl.ChooseCommand(&CmdPGPEncrypt{}, "encrypt", c)
		},
		Flags: []cli.Flag{
			cli.BoolFlag{
				Name:  "r, track-remote",
				Usage: "remotely track by default",
			},
			cli.BoolFlag{
				Name:  "l, track-local",
				Usage: "don't prompt for remote tracking",
			},
			cli.BoolFlag{
				Name:  "batch",
				Usage: "batch-mode without interactivity",
			},
			cli.BoolFlag{
				Name:  "prompt-remote",
				Usage: "prompt for remote tracking",
			},
			cli.BoolFlag{
				Name:  "s, sign",
				Usage: "sign in addition to encrypting",
			},
			cli.StringFlag{
				Name:  "m, message",
				Usage: "provide the message on the command line",
			},
			cli.BoolFlag{
				Name:  "b, binary",
				Usage: "output in binary (rather than ASCII/armored)",
			},
			cli.StringFlag{
				Name:  "o, outfile",
				Usage: "specify an outfile (stdout by default)",
			},
		},
	}

}

type CmdPGPEncrypt struct{}

func (c *CmdPGPEncrypt) Run() error {
	return nil
}

func (c *CmdPGPEncrypt) RunClient() error {
	return nil
}

func (c *CmdPGPEncrypt) ParseArgv(ctx *cli.Context) error {
	return nil
}

func (c *CmdPGPEncrypt) GetUsage() libkb.Usage {
	return libkb.Usage{
		Config:    true,
		API:       true,
		Terminal:  true,
		KbKeyring: true,
	}
}
<commit_msg>added -i, --no-self flags<commit_after>package main

import (
	"github.com/codegangsta/cli"
	"github.com/keybase/client/go/libcmdline"
	"github.com/keybase/client/go/libkb"
)

func NewCmdPGPEncrypt(cl *libcmdline.CommandLine) cli.Command {
	return cli.Command{
		Name:        "encrypt",
		Usage:       "keybase pgp encrypt [-r] [-l] [--no-self] [--batch] [--prompt-remote] [-s] [-m MESSAGE] [-b] [-o OUTPUT] [-i file] them",
		Description: "PGP encrypt messages or files for keybase users.",
		Action: func(c *cli.Context) {
			cl.ChooseCommand(&CmdPGPEncrypt{}, "encrypt", c)
		},
		Flags: []cli.Flag{
			cli.BoolFlag{
				Name:  "r, track-remote",
				Usage: "remotely track by default",
			},
			cli.BoolFlag{
				Name:  "l, track-local",
				Usage: "don't prompt for remote tracking",
			},
			cli.BoolFlag{
				Name:  "no-self",
				Usage: "don't encrypt for self",
			},
			cli.BoolFlag{
				Name:  "batch",
				Usage: "batch-mode without interactivity",
			},
			cli.BoolFlag{
				Name:  "prompt-remote",
				Usage: "prompt for remote tracking",
			},
			cli.BoolFlag{
				Name:  "s, sign",
				Usage: "sign in addition to encrypting",
			},
			cli.StringFlag{
				Name:  "m, message",
				Usage: "provide the message on the command line",
			},
			cli.BoolFlag{
				Name:  "b, binary",
				Usage: "output in binary (rather than ASCII/armored)",
			},
			cli.StringFlag{
				Name:  "i, infile",
				Usage: "specify an input file",
			},
			cli.StringFlag{
				Name:  "o, outfile",
				Usage: "specify an outfile (stdout by default)",
			},
		},
	}

}

type CmdPGPEncrypt struct{}

func (c *CmdPGPEncrypt) Run() error {
	return nil
}

func (c *CmdPGPEncrypt) RunClient() error {
	return nil
}

func (c *CmdPGPEncrypt) ParseArgv(ctx *cli.Context) error {
	return nil
}

func (c *CmdPGPEncrypt) GetUsage() libkb.Usage {
	return libkb.Usage{
		Config:    true,
		API:       true,
		Terminal:  true,
		KbKeyring: true,
	}
}
<|endoftext|>


<commit_before>// Copyright 2017 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

// BackgroundTask runs a function in the background once in a while.
// Note that this engine is long-lived and potentially has to deal with being
// logged out and logged in as a different user, etc.

package engine

import (
	"fmt"
	"sync"
	"time"

	"github.com/keybase/client/go/libkb"
	context "golang.org/x/net/context"
)

// Function to run periodically.
// The error is logged but otherwise ignored.
type TaskFunc func(g *libkb.GlobalContext, ectx *Context) error

type BackgroundTaskSettings struct {
	// Wait after starting the app
	Start time.Duration
	// When waking up on mobile lots of timers will go off at once. We wait an additional
	// delay so as not to add to that herd and slow down the mobile experience when opening the app.
	WakeUp time.Duration
	// Wait between runs
	Interval time.Duration
	// Time limit on each round
	Limit time.Duration
}

// BackgroundTask is an engine.
type BackgroundTask struct {
	libkb.Contextified
	sync.Mutex

	args *BackgroundTaskArgs

	shutdown bool
	// Function to cancel the background context.
	// Can be nil before RunEngine exits
	shutdownFunc context.CancelFunc
}

type BackgroundTaskArgs struct {
	Name     string
	F        TaskFunc
	Settings BackgroundTaskSettings

	// Channels used for testing. Normally nil.
	testingMetaCh     chan<- string
	testingRoundResCh chan<- error
}

// NewBackgroundTask creates a BackgroundTask engine.
func NewBackgroundTask(g *libkb.GlobalContext, args *BackgroundTaskArgs) *BackgroundTask {
	return &BackgroundTask{
		Contextified: libkb.NewContextified(g),
		args:         args,
		shutdownFunc: nil,
	}
}

// Name is the unique engine name.
func (e *BackgroundTask) Name() string {
	if e.args != nil {
		return fmt.Sprintf("BackgroundTask(%v)", e.args.Name)
	}
	return "BackgroundTask"
}

// GetPrereqs returns the engine prereqs.
func (e *BackgroundTask) Prereqs() Prereqs {
	return Prereqs{}
}

// RequiredUIs returns the required UIs.
func (e *BackgroundTask) RequiredUIs() []libkb.UIKind {
	return []libkb.UIKind{}
}

// SubConsumers returns the other UI consumers for this engine.
func (e *BackgroundTask) SubConsumers() []libkb.UIConsumer {
	return []libkb.UIConsumer{}
}

// Run starts the engine.
// Returns immediately, kicks off a background goroutine.
func (e *BackgroundTask) Run(ectx *Context) (err error) {
	defer e.G().CTrace(ectx.GetNetContext(), e.Name(), func() error { return err })()

	// use a new background context with a saved cancel function
	ectx = ectx.WithNetContext(context.Background())
	ectx, cancel := ectx.WithCancel()

	e.Lock()
	defer e.Unlock()

	e.shutdownFunc = cancel
	if e.shutdown {
		// Shutdown before started
		cancel()
		e.meta("early-shutdown")
		return nil
	}

	// start the loop and return
	go func() {
		err := e.loop(ectx)
		if err != nil {
			e.log(ectx.GetNetContext(), "loop error: %s", err)
		}
		cancel()
		e.meta("loop-exit")
	}()

	return nil
}

func (e *BackgroundTask) Shutdown() {
	e.Lock()
	defer e.Unlock()
	e.shutdown = true
	if e.shutdownFunc != nil {
		e.shutdownFunc()
	}
}

func (e *BackgroundTask) loop(ectx *Context) error {
	// wakeAt times are calculated before a meta before their corresponding sleep.
	// To avoid the race where the testing goroutine calls advance before
	// this routine decides when to wake up. That led to this routine never waking.
	wakeAt := e.G().Clock().Now().Add(e.args.Settings.Start)
	e.meta("loop-start")
	if err := libkb.SleepUntilWithContext(ectx.GetNetContext(), e.G().Clock(), wakeAt); err != nil {
		return err
	}
	e.meta("woke-start")
	var i int
	for {
		i++
		err := e.round(ectx)
		if err != nil {
			e.log(ectx.GetNetContext(), "round(%v) error: %s", i, err)
		} else {
			e.log(ectx.GetNetContext(), "round(%v) complete", i)
		}
		if e.args.testingRoundResCh != nil {
			e.args.testingRoundResCh <- err
		}
		wakeAt = e.G().Clock().Now().Add(e.args.Settings.Interval)
		e.meta("loop-round-complete")
		if err := libkb.SleepUntilWithContext(ectx.GetNetContext(), e.G().Clock(), wakeAt); err != nil {
			return err
		}
		wakeAt = e.G().Clock().Now().Add(e.args.Settings.WakeUp)
		e.meta("woke-interval")
		if err := libkb.SleepUntilWithContext(ectx.GetNetContext(), e.G().Clock(), wakeAt); err != nil {
			return err
		}
		e.meta("woke-wakeup")
	}
}

func (e *BackgroundTask) round(ectx *Context) error {
	ectx, cancel := ectx.WithTimeout(e.args.Settings.Limit)
	defer cancel()

	// Run the function.
	if e.args.F == nil {
		return fmt.Errorf("nil task function")
	}
	return e.args.F(e.G(), ectx)
}

func (e *BackgroundTask) meta(s string) {
	if e.args.testingMetaCh != nil {
		e.args.testingMetaCh <- s
	}
}

func (e *BackgroundTask) log(ctx context.Context, format string, args ...interface{}) {
	content := fmt.Sprintf(format, args)
	e.G().Log.CDebugf(ctx, "%s %s", e.Name(), content)
}
<commit_msg>add note<commit_after>// Copyright 2017 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

// BackgroundTask runs a function in the background once in a while.
// Note that this engine is long-lived and potentially has to deal with being
// logged out and logged in as a different user, etc.
// The timer uses the clock to sleep. So if there is a timezone change
// it will probably wake up early or sleep for the extra hours.

package engine

import (
	"fmt"
	"sync"
	"time"

	"github.com/keybase/client/go/libkb"
	context "golang.org/x/net/context"
)

// Function to run periodically.
// The error is logged but otherwise ignored.
type TaskFunc func(g *libkb.GlobalContext, ectx *Context) error

type BackgroundTaskSettings struct {
	// Wait after starting the app
	Start time.Duration
	// When waking up on mobile lots of timers will go off at once. We wait an additional
	// delay so as not to add to that herd and slow down the mobile experience when opening the app.
	WakeUp time.Duration
	// Wait between runs
	Interval time.Duration
	// Time limit on each round
	Limit time.Duration
}

// BackgroundTask is an engine.
type BackgroundTask struct {
	libkb.Contextified
	sync.Mutex

	args *BackgroundTaskArgs

	shutdown bool
	// Function to cancel the background context.
	// Can be nil before RunEngine exits
	shutdownFunc context.CancelFunc
}

type BackgroundTaskArgs struct {
	Name     string
	F        TaskFunc
	Settings BackgroundTaskSettings

	// Channels used for testing. Normally nil.
	testingMetaCh     chan<- string
	testingRoundResCh chan<- error
}

// NewBackgroundTask creates a BackgroundTask engine.
func NewBackgroundTask(g *libkb.GlobalContext, args *BackgroundTaskArgs) *BackgroundTask {
	return &BackgroundTask{
		Contextified: libkb.NewContextified(g),
		args:         args,
		shutdownFunc: nil,
	}
}

// Name is the unique engine name.
func (e *BackgroundTask) Name() string {
	if e.args != nil {
		return fmt.Sprintf("BackgroundTask(%v)", e.args.Name)
	}
	return "BackgroundTask"
}

// GetPrereqs returns the engine prereqs.
func (e *BackgroundTask) Prereqs() Prereqs {
	return Prereqs{}
}

// RequiredUIs returns the required UIs.
func (e *BackgroundTask) RequiredUIs() []libkb.UIKind {
	return []libkb.UIKind{}
}

// SubConsumers returns the other UI consumers for this engine.
func (e *BackgroundTask) SubConsumers() []libkb.UIConsumer {
	return []libkb.UIConsumer{}
}

// Run starts the engine.
// Returns immediately, kicks off a background goroutine.
func (e *BackgroundTask) Run(ectx *Context) (err error) {
	defer e.G().CTrace(ectx.GetNetContext(), e.Name(), func() error { return err })()

	// use a new background context with a saved cancel function
	ectx = ectx.WithNetContext(context.Background())
	ectx, cancel := ectx.WithCancel()

	e.Lock()
	defer e.Unlock()

	e.shutdownFunc = cancel
	if e.shutdown {
		// Shutdown before started
		cancel()
		e.meta("early-shutdown")
		return nil
	}

	// start the loop and return
	go func() {
		err := e.loop(ectx)
		if err != nil {
			e.log(ectx.GetNetContext(), "loop error: %s", err)
		}
		cancel()
		e.meta("loop-exit")
	}()

	return nil
}

func (e *BackgroundTask) Shutdown() {
	e.Lock()
	defer e.Unlock()
	e.shutdown = true
	if e.shutdownFunc != nil {
		e.shutdownFunc()
	}
}

func (e *BackgroundTask) loop(ectx *Context) error {
	// wakeAt times are calculated before a meta before their corresponding sleep.
	// To avoid the race where the testing goroutine calls advance before
	// this routine decides when to wake up. That led to this routine never waking.
	wakeAt := e.G().Clock().Now().Add(e.args.Settings.Start)
	e.meta("loop-start")
	if err := libkb.SleepUntilWithContext(ectx.GetNetContext(), e.G().Clock(), wakeAt); err != nil {
		return err
	}
	e.meta("woke-start")
	var i int
	for {
		i++
		err := e.round(ectx)
		if err != nil {
			e.log(ectx.GetNetContext(), "round(%v) error: %s", i, err)
		} else {
			e.log(ectx.GetNetContext(), "round(%v) complete", i)
		}
		if e.args.testingRoundResCh != nil {
			e.args.testingRoundResCh <- err
		}
		wakeAt = e.G().Clock().Now().Add(e.args.Settings.Interval)
		e.meta("loop-round-complete")
		if err := libkb.SleepUntilWithContext(ectx.GetNetContext(), e.G().Clock(), wakeAt); err != nil {
			return err
		}
		wakeAt = e.G().Clock().Now().Add(e.args.Settings.WakeUp)
		e.meta("woke-interval")
		if err := libkb.SleepUntilWithContext(ectx.GetNetContext(), e.G().Clock(), wakeAt); err != nil {
			return err
		}
		e.meta("woke-wakeup")
	}
}

func (e *BackgroundTask) round(ectx *Context) error {
	ectx, cancel := ectx.WithTimeout(e.args.Settings.Limit)
	defer cancel()

	// Run the function.
	if e.args.F == nil {
		return fmt.Errorf("nil task function")
	}
	return e.args.F(e.G(), ectx)
}

func (e *BackgroundTask) meta(s string) {
	if e.args.testingMetaCh != nil {
		e.args.testingMetaCh <- s
	}
}

func (e *BackgroundTask) log(ctx context.Context, format string, args ...interface{}) {
	content := fmt.Sprintf(format, args)
	e.G().Log.CDebugf(ctx, "%s %s", e.Name(), content)
}
<|endoftext|>


<commit_before>
package main

import (
    "fmt"
    "os"
)

func main() {

    fileName := "test.txt"

    //
    // we use the os Open function that returns a File pointer or an error
    //

    fileptr, err := os.Open(fileName)

    //
    // we make sure the file is closed, no matter of what happens in this
    // function. We defer immediately so we don't forget. Even if an error
    // occurs and fileptr is nil, the runtime will handle this situation
    // gracefully
    //

    defer fileptr.Close()

    if err != nil {
        fmt.Println("error", err)
        return
    }

    //
    // File implements Reader's Read() so we use that to read bytes
    //

    fileInfoPtr, err := fileptr.Stat()

    if err != nil {
        fmt.Println("error", err)
        return
    }

    fileSize := fileInfoPtr.Size()

    bs := make([]byte, fileSize)
    _, err = fileptr.Read(bs)

    if err != nil {
        fmt.Println("error", err)
        return
    }

    fileContent := string(bs)
    fmt.Print(fileContent)
}
<commit_msg>working read-file version, linked from https://kb.novaordis.com/index.php/Go_Package_os<commit_after>
package main

import (
    "fmt"
    "os"
)

func main() {

    fileName := "test.txt"

    //
    // os.Open() function returns a File pointer or an error
    //

    filePtr, err := os.Open(fileName)

    //
    // we make sure the file will be closed, no matter what happens in this
    // function. We defer immediately so we don't forget. Even if an error
    // occurs and filePtr is nil, the runtime will handle this situation
    // gracefully
    //

    defer filePtr.Close()

    if err != nil {

        //
        // exit on error
        //
        fmt.Println("error", err)
        return
    }

    //
    // os.File implements Reader.Read() so we use that to read bytes.
    // In order to read all bytes, we need to know how many bytes are
    // in the file.
    //

    fileInfoPtr, err := filePtr.Stat()

    if err != nil {

        //
        // exit on error
        //
        fmt.Println("error", err)
        return
    }

    fileSize := fileInfoPtr.Size()

    //
    // we make a slice large enough to accommodate all the bytes from the file
    //

    bs := make([]byte, fileSize)

    //
    // we do the reading
    //
    _, err = filePtr.Read(bs)

    if err != nil {

        //
        // exit on error
        //
        fmt.Println("error", err)
        return
    }

    //
    // we convert the bytes to a string
    //
    fileContent := string(bs)
    fmt.Print(fileContent)
}<|endoftext|>


<commit_before>// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package golist defines the "go list" implementation of the Packages metadata query.
package golist

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"golang.org/x/tools/go/packages/raw"
)

// A goTooOldError reports that the go command
// found by exec.LookPath is too old to use the new go list behavior.
type goTooOldError struct {
	error
}

// LoadRaw and returns the raw Go packages named by the given patterns.
// This is a low level API, in general you should be using the packages.Load
// unless you have a very strong need for the raw data, and you know that you
// are using conventional go layout as supported by `go list`
// It returns the packages identifiers that directly matched the patterns, the
// full set of packages requested (which may include the dependencies) and
// an error if the operation failed.
func LoadRaw(ctx context.Context, cfg *raw.Config, patterns ...string) ([]string, []*raw.Package, error) {
	if len(patterns) == 0 {
		return nil, nil, fmt.Errorf("no packages to load")
	}
	if cfg == nil {
		return nil, nil, fmt.Errorf("Load must be passed a valid Config")
	}
	if cfg.Dir == "" {
		return nil, nil, fmt.Errorf("Config does not have a working directory")
	}
	// Determine files requested in contains patterns
	var containFiles []string
	{
		restPatterns := patterns[:0]
		for _, pattern := range patterns {
			if containFile := strings.TrimPrefix(pattern, "contains:"); containFile != pattern {
				containFiles = append(containFiles, containFile)
			} else {
				restPatterns = append(restPatterns, pattern)
			}
		}
		containFiles = absJoin(cfg.Dir, containFiles)
		patterns = restPatterns
	}

	listfunc := golistPackages
	// TODO(matloob): Patterns may now be empty, if it was solely comprised of contains: patterns.
	// See if the extra process invocation can be avoided.
	roots, pkgs, err := listfunc(ctx, cfg, patterns...)
	if _, ok := err.(goTooOldError); ok {
		listfunc = golistPackagesFallback
		roots, pkgs, err = listfunc(ctx, cfg, patterns...)
	}
	if err != nil {
		return nil, nil, err
	}

	// Run go list for contains: patterns.
	seenPkgs := make(map[string]bool) // for deduplication. different containing queries could produce same packages
	if len(containFiles) > 0 {
		for _, pkg := range pkgs {
			seenPkgs[pkg.ID] = true
		}
	}
	for _, f := range containFiles {
		// TODO(matloob): Do only one query per directory.
		fdir := filepath.Dir(f)
		cfg.Dir = fdir
		_, cList, err := listfunc(ctx, cfg, ".")
		if err != nil {
			return nil, nil, err
		}
		// Deduplicate and set deplist to set of packages requested files.
		dedupedList := cList[:0] // invariant: only packages that haven't been seen before
		for _, pkg := range cList {
			if seenPkgs[pkg.ID] {
				continue
			}
			seenPkgs[pkg.ID] = true
			dedupedList = append(dedupedList, pkg)
			for _, pkgFile := range pkg.GoFiles {
				if filepath.Base(f) == filepath.Base(pkgFile) {
					roots = append(roots, pkg.ID)
					break
				}
			}
		}
		pkgs = append(pkgs, dedupedList...)
	}
	return roots, pkgs, nil
}

// Fields must match go list;
// see $GOROOT/src/cmd/go/internal/load/pkg.go.
type jsonPackage struct {
	ImportPath   string
	Dir          string
	Name         string
	Export       string
	GoFiles      []string
	CFiles       []string
	CgoFiles     []string
	SFiles       []string
	Imports      []string
	ImportMap    map[string]string
	Deps         []string
	TestGoFiles  []string
	TestImports  []string
	XTestGoFiles []string
	XTestImports []string
	ForTest      string // q in a "p [q.test]" package, else ""
	DepOnly      bool
}

// golistPackages uses the "go list" command to expand the
// pattern words and return metadata for the specified packages.
// dir may be "" and env may be nil, as per os/exec.Command.
func golistPackages(ctx context.Context, cfg *raw.Config, words ...string) ([]string, []*raw.Package, error) {
	// go list uses the following identifiers in ImportPath and Imports:
	//
	// 	"p"			-- importable package or main (command)
	//      "q.test"		-- q's test executable
	// 	"p [q.test]"		-- variant of p as built for q's test executable
	//	"q_test [q.test]"	-- q's external test package
	//
	// The packages p that are built differently for a test q.test
	// are q itself, plus any helpers used by the external test q_test,
	// typically including "testing" and all its dependencies.

	// Run "go list" for complete
	// information on the specified packages.

	buf, err := golist(ctx, cfg, golistargs(cfg, words))
	if err != nil {
		return nil, nil, err
	}
	// Decode the JSON and convert it to Package form.
	var roots []string
	var result []*raw.Package
	for dec := json.NewDecoder(buf); dec.More(); {
		p := new(jsonPackage)
		if err := dec.Decode(p); err != nil {
			return nil, nil, fmt.Errorf("JSON decoding failed: %v", err)
		}

		// Bad package?
		if p.Name == "" {
			// This could be due to:
			// - no such package
			// - package directory contains no Go source files
			// - all package declarations are mangled
			// - and possibly other things.
			//
			// For now, we throw it away and let later
			// stages rediscover the problem, but this
			// discards the error message computed by go list
			// and computes a new one---by different logic:
			// if only one of the package declarations is
			// bad, for example, should we report an error
			// in Metadata mode?
			// Unless we parse and typecheck, we might not
			// notice there's a problem.
			//
			// Perhaps we should save a map of PackageID to
			// errors for such cases.
			continue
		}

		id := p.ImportPath

		// Extract the PkgPath from the package's ID.
		pkgpath := id
		if i := strings.IndexByte(id, ' '); i >= 0 {
			pkgpath = id[:i]
		}

		if pkgpath == "unsafe" {
			p.GoFiles = nil // ignore fake unsafe.go file
		}

		// Assume go list emits only absolute paths for Dir.
		if !filepath.IsAbs(p.Dir) {
			log.Fatalf("internal error: go list returned non-absolute Package.Dir: %s", p.Dir)
		}

		export := p.Export
		if export != "" && !filepath.IsAbs(export) {
			export = filepath.Join(p.Dir, export)
		}

		// imports
		//
		// Imports contains the IDs of all imported packages.
		// ImportsMap records (path, ID) only where they differ.
		ids := make(map[string]bool)
		for _, id := range p.Imports {
			ids[id] = true
		}
		imports := make(map[string]string)
		for path, id := range p.ImportMap {
			imports[path] = id // non-identity import
			delete(ids, id)
		}
		for id := range ids {
			// Go issue 26136: go list omits imports in cgo-generated files.
			if id == "C" {
				imports["unsafe"] = "unsafe"
				imports["syscall"] = "syscall"
				if pkgpath != "runtime/cgo" {
					imports["runtime/cgo"] = "runtime/cgo"
				}
				continue
			}

			imports[id] = id // identity import
		}

		pkg := &raw.Package{
			ID:         id,
			Name:       p.Name,
			GoFiles:    absJoin(p.Dir, p.GoFiles, p.CgoFiles),
			OtherFiles: absJoin(p.Dir, p.SFiles, p.CFiles),
			PkgPath:    pkgpath,
			Imports:    imports,
			Export:     export,
		}
		if !p.DepOnly {
			roots = append(roots, pkg.ID)
		}
		result = append(result, pkg)
	}

	return roots, result, nil
}

// absJoin absolutizes and flattens the lists of files.
func absJoin(dir string, fileses ...[]string) (res []string) {
	for _, files := range fileses {
		for _, file := range files {
			if !filepath.IsAbs(file) {
				file = filepath.Join(dir, file)
			}
			res = append(res, file)
		}
	}
	return res
}

func golistargs(cfg *raw.Config, words []string) []string {
	fullargs := []string{
		"list", "-e", "-json", "-cgo=true",
		fmt.Sprintf("-test=%t", cfg.Tests),
		fmt.Sprintf("-export=%t", cfg.Export),
		fmt.Sprintf("-deps=%t", cfg.Deps),
	}
	fullargs = append(fullargs, cfg.Flags...)
	fullargs = append(fullargs, "--")
	fullargs = append(fullargs, words...)
	return fullargs
}

// golist returns the JSON-encoded result of a "go list args..." query.
func golist(ctx context.Context, cfg *raw.Config, args []string) (*bytes.Buffer, error) {
	out := new(bytes.Buffer)
	cmd := exec.CommandContext(ctx, "go", args...)
	cmd.Env = cfg.Env
	cmd.Dir = cfg.Dir
	cmd.Stdout = out
	cmd.Stderr = new(bytes.Buffer)
	if err := cmd.Run(); err != nil {
		exitErr, ok := err.(*exec.ExitError)
		if !ok {
			// Catastrophic error:
			// - executable not found
			// - context cancellation
			return nil, fmt.Errorf("couldn't exec 'go list': %s %T", err, err)
		}

		// Old go list?
		if strings.Contains(fmt.Sprint(cmd.Stderr), "flag provided but not defined") {
			return nil, goTooOldError{fmt.Errorf("unsupported version of go list: %s: %s", exitErr, cmd.Stderr)}
		}

		// Export mode entails a build.
		// If that build fails, errors appear on stderr
		// (despite the -e flag) and the Export field is blank.
		// Do not fail in that case.
		if !cfg.Export {
			return nil, fmt.Errorf("go list: %s: %s", exitErr, cmd.Stderr)
		}
	}

	// Print standard error output from "go list".
	// Due to the -e flag, this should be empty.
	// However, in -export mode it contains build errors.
	// Should go list save build errors in the Package.Error JSON field?
	// See https://github.com/golang/go/issues/26319.
	// If so, then we should continue to print stderr as go list
	// will be silent unless something unexpected happened.
	// If not, perhaps we should suppress it to reduce noise.
	if stderr := fmt.Sprint(cmd.Stderr); stderr != "" {
		fmt.Fprintf(os.Stderr, "go list stderr <<%s>>\n", stderr)
	}

	// debugging
	if false {
		fmt.Fprintln(os.Stderr, out)
	}

	return out, nil
}
<commit_msg>go/packages/golist: remove -cgo flag from go list invocation<commit_after>// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package golist defines the "go list" implementation of the Packages metadata query.
package golist

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"golang.org/x/tools/go/packages/raw"
)

// A goTooOldError reports that the go command
// found by exec.LookPath is too old to use the new go list behavior.
type goTooOldError struct {
	error
}

// LoadRaw and returns the raw Go packages named by the given patterns.
// This is a low level API, in general you should be using the packages.Load
// unless you have a very strong need for the raw data, and you know that you
// are using conventional go layout as supported by `go list`
// It returns the packages identifiers that directly matched the patterns, the
// full set of packages requested (which may include the dependencies) and
// an error if the operation failed.
func LoadRaw(ctx context.Context, cfg *raw.Config, patterns ...string) ([]string, []*raw.Package, error) {
	if len(patterns) == 0 {
		return nil, nil, fmt.Errorf("no packages to load")
	}
	if cfg == nil {
		return nil, nil, fmt.Errorf("Load must be passed a valid Config")
	}
	if cfg.Dir == "" {
		return nil, nil, fmt.Errorf("Config does not have a working directory")
	}
	// Determine files requested in contains patterns
	var containFiles []string
	{
		restPatterns := patterns[:0]
		for _, pattern := range patterns {
			if containFile := strings.TrimPrefix(pattern, "contains:"); containFile != pattern {
				containFiles = append(containFiles, containFile)
			} else {
				restPatterns = append(restPatterns, pattern)
			}
		}
		containFiles = absJoin(cfg.Dir, containFiles)
		patterns = restPatterns
	}

	listfunc := golistPackages
	// TODO(matloob): Patterns may now be empty, if it was solely comprised of contains: patterns.
	// See if the extra process invocation can be avoided.
	roots, pkgs, err := listfunc(ctx, cfg, patterns...)
	if _, ok := err.(goTooOldError); ok {
		listfunc = golistPackagesFallback
		roots, pkgs, err = listfunc(ctx, cfg, patterns...)
	}
	if err != nil {
		return nil, nil, err
	}

	// Run go list for contains: patterns.
	seenPkgs := make(map[string]bool) // for deduplication. different containing queries could produce same packages
	if len(containFiles) > 0 {
		for _, pkg := range pkgs {
			seenPkgs[pkg.ID] = true
		}
	}
	for _, f := range containFiles {
		// TODO(matloob): Do only one query per directory.
		fdir := filepath.Dir(f)
		cfg.Dir = fdir
		_, cList, err := listfunc(ctx, cfg, ".")
		if err != nil {
			return nil, nil, err
		}
		// Deduplicate and set deplist to set of packages requested files.
		dedupedList := cList[:0] // invariant: only packages that haven't been seen before
		for _, pkg := range cList {
			if seenPkgs[pkg.ID] {
				continue
			}
			seenPkgs[pkg.ID] = true
			dedupedList = append(dedupedList, pkg)
			for _, pkgFile := range pkg.GoFiles {
				if filepath.Base(f) == filepath.Base(pkgFile) {
					roots = append(roots, pkg.ID)
					break
				}
			}
		}
		pkgs = append(pkgs, dedupedList...)
	}
	return roots, pkgs, nil
}

// Fields must match go list;
// see $GOROOT/src/cmd/go/internal/load/pkg.go.
type jsonPackage struct {
	ImportPath   string
	Dir          string
	Name         string
	Export       string
	GoFiles      []string
	CFiles       []string
	CgoFiles     []string
	SFiles       []string
	Imports      []string
	ImportMap    map[string]string
	Deps         []string
	TestGoFiles  []string
	TestImports  []string
	XTestGoFiles []string
	XTestImports []string
	ForTest      string // q in a "p [q.test]" package, else ""
	DepOnly      bool
}

// golistPackages uses the "go list" command to expand the
// pattern words and return metadata for the specified packages.
// dir may be "" and env may be nil, as per os/exec.Command.
func golistPackages(ctx context.Context, cfg *raw.Config, words ...string) ([]string, []*raw.Package, error) {
	// go list uses the following identifiers in ImportPath and Imports:
	//
	// 	"p"			-- importable package or main (command)
	//      "q.test"		-- q's test executable
	// 	"p [q.test]"		-- variant of p as built for q's test executable
	//	"q_test [q.test]"	-- q's external test package
	//
	// The packages p that are built differently for a test q.test
	// are q itself, plus any helpers used by the external test q_test,
	// typically including "testing" and all its dependencies.

	// Run "go list" for complete
	// information on the specified packages.

	buf, err := golist(ctx, cfg, golistargs(cfg, words))
	if err != nil {
		return nil, nil, err
	}
	// Decode the JSON and convert it to Package form.
	var roots []string
	var result []*raw.Package
	for dec := json.NewDecoder(buf); dec.More(); {
		p := new(jsonPackage)
		if err := dec.Decode(p); err != nil {
			return nil, nil, fmt.Errorf("JSON decoding failed: %v", err)
		}

		// Bad package?
		if p.Name == "" {
			// This could be due to:
			// - no such package
			// - package directory contains no Go source files
			// - all package declarations are mangled
			// - and possibly other things.
			//
			// For now, we throw it away and let later
			// stages rediscover the problem, but this
			// discards the error message computed by go list
			// and computes a new one---by different logic:
			// if only one of the package declarations is
			// bad, for example, should we report an error
			// in Metadata mode?
			// Unless we parse and typecheck, we might not
			// notice there's a problem.
			//
			// Perhaps we should save a map of PackageID to
			// errors for such cases.
			continue
		}

		id := p.ImportPath

		// Extract the PkgPath from the package's ID.
		pkgpath := id
		if i := strings.IndexByte(id, ' '); i >= 0 {
			pkgpath = id[:i]
		}

		if pkgpath == "unsafe" {
			p.GoFiles = nil // ignore fake unsafe.go file
		}

		// Assume go list emits only absolute paths for Dir.
		if !filepath.IsAbs(p.Dir) {
			log.Fatalf("internal error: go list returned non-absolute Package.Dir: %s", p.Dir)
		}

		export := p.Export
		if export != "" && !filepath.IsAbs(export) {
			export = filepath.Join(p.Dir, export)
		}

		// imports
		//
		// Imports contains the IDs of all imported packages.
		// ImportsMap records (path, ID) only where they differ.
		ids := make(map[string]bool)
		for _, id := range p.Imports {
			ids[id] = true
		}
		imports := make(map[string]string)
		for path, id := range p.ImportMap {
			imports[path] = id // non-identity import
			delete(ids, id)
		}
		for id := range ids {
			// Go issue 26136: go list omits imports in cgo-generated files.
			if id == "C" {
				imports["unsafe"] = "unsafe"
				imports["syscall"] = "syscall"
				if pkgpath != "runtime/cgo" {
					imports["runtime/cgo"] = "runtime/cgo"
				}
				continue
			}

			imports[id] = id // identity import
		}

		pkg := &raw.Package{
			ID:         id,
			Name:       p.Name,
			GoFiles:    absJoin(p.Dir, p.GoFiles, p.CgoFiles),
			OtherFiles: absJoin(p.Dir, p.SFiles, p.CFiles),
			PkgPath:    pkgpath,
			Imports:    imports,
			Export:     export,
		}
		if !p.DepOnly {
			roots = append(roots, pkg.ID)
		}
		result = append(result, pkg)
	}

	return roots, result, nil
}

// absJoin absolutizes and flattens the lists of files.
func absJoin(dir string, fileses ...[]string) (res []string) {
	for _, files := range fileses {
		for _, file := range files {
			if !filepath.IsAbs(file) {
				file = filepath.Join(dir, file)
			}
			res = append(res, file)
		}
	}
	return res
}

func golistargs(cfg *raw.Config, words []string) []string {
	fullargs := []string{
		"list", "-e", "-json",
		fmt.Sprintf("-test=%t", cfg.Tests),
		fmt.Sprintf("-export=%t", cfg.Export),
		fmt.Sprintf("-deps=%t", cfg.Deps),
	}
	fullargs = append(fullargs, cfg.Flags...)
	fullargs = append(fullargs, "--")
	fullargs = append(fullargs, words...)
	return fullargs
}

// golist returns the JSON-encoded result of a "go list args..." query.
func golist(ctx context.Context, cfg *raw.Config, args []string) (*bytes.Buffer, error) {
	out := new(bytes.Buffer)
	cmd := exec.CommandContext(ctx, "go", args...)
	cmd.Env = cfg.Env
	cmd.Dir = cfg.Dir
	cmd.Stdout = out
	cmd.Stderr = new(bytes.Buffer)
	if err := cmd.Run(); err != nil {
		exitErr, ok := err.(*exec.ExitError)
		if !ok {
			// Catastrophic error:
			// - executable not found
			// - context cancellation
			return nil, fmt.Errorf("couldn't exec 'go list': %s %T", err, err)
		}

		// Old go list?
		if strings.Contains(fmt.Sprint(cmd.Stderr), "flag provided but not defined") {
			return nil, goTooOldError{fmt.Errorf("unsupported version of go list: %s: %s", exitErr, cmd.Stderr)}
		}

		// Export mode entails a build.
		// If that build fails, errors appear on stderr
		// (despite the -e flag) and the Export field is blank.
		// Do not fail in that case.
		if !cfg.Export {
			return nil, fmt.Errorf("go list: %s: %s", exitErr, cmd.Stderr)
		}
	}

	// Print standard error output from "go list".
	// Due to the -e flag, this should be empty.
	// However, in -export mode it contains build errors.
	// Should go list save build errors in the Package.Error JSON field?
	// See https://github.com/golang/go/issues/26319.
	// If so, then we should continue to print stderr as go list
	// will be silent unless something unexpected happened.
	// If not, perhaps we should suppress it to reduce noise.
	if stderr := fmt.Sprint(cmd.Stderr); stderr != "" {
		fmt.Fprintf(os.Stderr, "go list stderr <<%s>>\n", stderr)
	}

	// debugging
	if false {
		fmt.Fprintln(os.Stderr, out)
	}

	return out, nil
}
<|endoftext|>


<commit_before>// Go provides built-in support for [base64
// encoding/decoding](http://en.wikipedia.org/wiki/Base64).

package main

// This syntax imports the `encoding/base64` package with
// the `b64` name instead of the default `base64`. It'll
// save us some space below.
import (
	b64 "encoding/base64"
	//import "fmt"
	_ "github.com/tardisgo/tardisgo/golibruntime"
)

func main() {

	// Here's the `string` we'll encode/decode.
	data := "abc123!?$*&()'-=@~"

	// Go supports both standard and URL-compatible
	// base64. Here's how to encode using the standard
	// encoder. The encoder requires a `[]byte` so we
	// cast our `string` to that type.
	sEnc := b64.StdEncoding.EncodeToString([]byte(data))
	//fmt.Println(sEnc)
	println(sEnc)

	// Decoding may return an error, which you can check
	// if you don't already know the input to be
	// well-formed.
	sDec, _ := b64.StdEncoding.DecodeString(sEnc)
	//fmt.Println(string(sDec))
	println(string(sDec))
	//fmt.Println()
	println(" ") // TODO fix this bug - println() generates a haxe error : Unexpected )

	// This encodes/decodes using a URL-compatible base64
	// format.
	uEnc := b64.URLEncoding.EncodeToString([]byte(data))
	//fmt.Println(uEnc)
	println(uEnc)
	uDec, _ := b64.URLEncoding.DecodeString(uEnc)
	//fmt.Println(string(uDec))
	println(string(uDec))
}
<commit_msg>Fix to work on Win7<commit_after>// Go provides built-in support for [base64
// encoding/decoding](http://en.wikipedia.org/wiki/Base64).

package main

// This syntax imports the `encoding/base64` package with
// the `b64` name instead of the default `base64`. It'll
// save us some space below.
import (
	b64 "encoding/base64"
	//import "fmt"
	_ "github.com/tardisgo/tardisgo/golibruntime/bytes"
	_ "github.com/tardisgo/tardisgo/golibruntime/strings"
	_ "github.com/tardisgo/tardisgo/golibruntime/sync"
	_ "github.com/tardisgo/tardisgo/golibruntime/sync/atomic"
)

func main() {

	// Here's the `string` we'll encode/decode.
	data := "abc123!?$*&()'-=@~"

	// Go supports both standard and URL-compatible
	// base64. Here's how to encode using the standard
	// encoder. The encoder requires a `[]byte` so we
	// cast our `string` to that type.
	sEnc := b64.StdEncoding.EncodeToString([]byte(data))
	//fmt.Println(sEnc)
	println(sEnc)

	// Decoding may return an error, which you can check
	// if you don't already know the input to be
	// well-formed.
	sDec, _ := b64.StdEncoding.DecodeString(sEnc)
	//fmt.Println(string(sDec))
	println(string(sDec))
	//fmt.Println()
	println(" ") // TODO fix this bug - println() generates a haxe error : Unexpected )

	// This encodes/decodes using a URL-compatible base64
	// format.
	uEnc := b64.URLEncoding.EncodeToString([]byte(data))
	//fmt.Println(uEnc)
	println(uEnc)
	uDec, _ := b64.URLEncoding.DecodeString(uEnc)
	//fmt.Println(string(uDec))
	println(string(uDec))
}
<|endoftext|>


<commit_before>package middleware

import (
	"net"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// replacer is a type which can replace placeholder
// substrings in a string with actual values from a
// http.Request and responseRecorder. Always use
// NewReplacer to get one of these.
type replacer map[string]string

// NewReplacer makes a new replacer based on r and rr.
// Do not create a new replacer until r and rr have all
// the needed values, because this function copies those
// values into the replacer.
func NewReplacer(r *http.Request, rr *responseRecorder) replacer {
	rep := replacer{
		"{method}": r.Method,
		"{scheme}": func() string {
			if r.TLS != nil {
				return "https"
			}
			return "http"
		}(),
		"{host}":     r.Host,
		"{path}":     r.URL.Path,
		"{query}":    r.URL.RawQuery,
		"{fragment}": r.URL.Fragment,
		"{proto}":    r.Proto,
		"{remote}": func() string {
			if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" {
				return fwdFor
			}
			host, _, err := net.SplitHostPort(r.RemoteAddr)
			if err != nil {
				return r.RemoteAddr
			}
			return host
		}(),
		"{port}": func() string {
			_, port, err := net.SplitHostPort(r.RemoteAddr)
			if err != nil {
				return ""
			}
			return port
		}(),
		"{uri}": r.RequestURI,
		"{when}": func() string {
			return time.Now().Format(timeFormat)
		}(),
		"{status}":  strconv.Itoa(rr.status),
		"{size}":    strconv.Itoa(rr.size),
		"{latency}": time.Since(rr.start).String(),
	}

	// Header placeholders
	for header, val := range r.Header {
		rep[headerReplacer+header+"}"] = strings.Join(val, ",")
	}

	return rep
}

// Replace performs a replacement of values on s and returns
// the string with the replaced values.
func (r replacer) Replace(s string) string {
	for placeholder, replacement := range r {
		if replacement == "" {
			replacement = EmptyStringReplacer
		}
		s = strings.Replace(s, placeholder, replacement, -1)
	}

	// Replace any header placeholders that weren't found
	for strings.Contains(s, headerReplacer) {
		idxStart := strings.Index(s, headerReplacer)
		endOffset := idxStart + len(headerReplacer)
		idxEnd := strings.Index(s[endOffset:], "}")
		if idxEnd > -1 {
			s = s[:idxStart] + EmptyStringReplacer + s[endOffset+idxEnd+1:]
		} else {
			break
		}
	}
	return s
}

const (
	timeFormat          = "02/Jan/2006:15:04:05 -0700"
	headerReplacer      = "{>"
	EmptyStringReplacer = "-"
)
<commit_msg>Allow responseRecorder to be nil<commit_after>package middleware

import (
	"net"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// replacer is a type which can replace placeholder
// substrings in a string with actual values from a
// http.Request and responseRecorder. Always use
// NewReplacer to get one of these.
type replacer map[string]string

// NewReplacer makes a new replacer based on r and rr.
// Do not create a new replacer until r and rr have all
// the needed values, because this function copies those
// values into the replacer.
func NewReplacer(r *http.Request, rr *responseRecorder) replacer {
	rep := replacer{
		"{method}": r.Method,
		"{scheme}": func() string {
			if r.TLS != nil {
				return "https"
			}
			return "http"
		}(),
		"{host}":     r.Host,
		"{path}":     r.URL.Path,
		"{query}":    r.URL.RawQuery,
		"{fragment}": r.URL.Fragment,
		"{proto}":    r.Proto,
		"{remote}": func() string {
			if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" {
				return fwdFor
			}
			host, _, err := net.SplitHostPort(r.RemoteAddr)
			if err != nil {
				return r.RemoteAddr
			}
			return host
		}(),
		"{port}": func() string {
			_, port, err := net.SplitHostPort(r.RemoteAddr)
			if err != nil {
				return ""
			}
			return port
		}(),
		"{uri}": r.RequestURI,
		"{when}": func() string {
			return time.Now().Format(timeFormat)
		}(),
	}
	if rr != nil {
		rep["{status}"] = strconv.Itoa(rr.status)
		rep["{size}"] = strconv.Itoa(rr.size)
		rep["{latency}"] = time.Since(rr.start).String()
	}

	// Header placeholders
	for header, val := range r.Header {
		rep[headerReplacer+header+"}"] = strings.Join(val, ",")
	}

	return rep
}

// Replace performs a replacement of values on s and returns
// the string with the replaced values.
func (r replacer) Replace(s string) string {
	for placeholder, replacement := range r {
		if replacement == "" {
			replacement = EmptyStringReplacer
		}
		s = strings.Replace(s, placeholder, replacement, -1)
	}

	// Replace any header placeholders that weren't found
	for strings.Contains(s, headerReplacer) {
		idxStart := strings.Index(s, headerReplacer)
		endOffset := idxStart + len(headerReplacer)
		idxEnd := strings.Index(s[endOffset:], "}")
		if idxEnd > -1 {
			s = s[:idxStart] + EmptyStringReplacer + s[endOffset+idxEnd+1:]
		} else {
			break
		}
	}
	return s
}

const (
	timeFormat          = "02/Jan/2006:15:04:05 -0700"
	headerReplacer      = "{>"
	EmptyStringReplacer = "-"
)
<|endoftext|>


<commit_before>package lib

import (
    "fmt"
    "os"
    "strconv"
    "time"

    . "gopkg.in/check.v1"
)

func (s *OssutilCommandSuite) rawSetBucketACL(bucket, acl string, force bool) (bool, error) {
    args := []string{CloudURLToString(bucket, ""), acl}
    showElapse, err := s.rawSetACLWithArgs(args, false, true, force)
    return showElapse, err
}

func (s *OssutilCommandSuite) rawSetObjectACL(bucket, object, acl string, recursive, force bool) (bool, error) {
    args := []string{CloudURLToString(bucket, object), acl}
    showElapse, err := s.rawSetACLWithArgs(args, recursive, false, force)
    return showElapse, err
}

func (s *OssutilCommandSuite) rawSetACLWithArgs(args []string, recursive, bucket, force bool) (bool, error) {
    command := "set-acl"
    str := ""
    routines := strconv.Itoa(Routines)
    options := OptionMapType{
        "endpoint": &str,
        "accessKeyID": &str,
        "accessKeySecret": &str,
        "stsToken": &str,
        "configFile": &configFile,
        "routines": &routines,
        "recursive": &recursive,
        "bucket": &bucket,
        "force": &force,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    time.Sleep(sleepTime)
    return showElapse, err
}

func (s *OssutilCommandSuite) TestSetBucketACL(c *C) {
    bucket := bucketNameExist

    // set acl
    for _, acl := range []string{"private", "public-read", "public-read-write"} {
        s.setBucketACL(bucket, acl, c)
        bucketStat := s.getStat(bucket, "", c)
        c.Assert(bucketStat[StatACL], Equals, acl)
    }
}

func (s *OssutilCommandSuite) TestSetBucketErrorACL(c *C) {
    bucket := bucketNameDest

    for _, acl := range []string{"default", "def", "erracl", "私有"} {
        showElapse, err := s.rawSetBucketACL(bucket, acl, false)
        c.Assert(err, NotNil)
        c.Assert(showElapse, Equals, false)

        showElapse, err = s.rawSetBucketACL(bucket, acl, true)
        c.Assert(err, NotNil)
        c.Assert(showElapse, Equals, false)

        bucketStat := s.getStat(bucket, "", c)
        c.Assert(bucketStat[StatACL], Equals, "private")
    }
}

func (s *OssutilCommandSuite) TestSetNotExistBucketACL(c *C) {
    bucket := bucketNamePrefix + "noexistsetacl"

    showElapse, err := s.rawGetStat(bucket, "")
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // set acl and create bucket
    showElapse, err = s.rawSetBucketACL(bucket, "public-read", true)
    c.Assert(err, IsNil)
    c.Assert(showElapse, Equals, true)

    time.Sleep(sleepTime)
    bucketStat := s.getStat(bucket, "", c)
    c.Assert(bucketStat[StatACL], Equals, "public-read")

    s.removeBucket(bucket, true, c)
    time.Sleep(3*sleepTime)

    // invalid bucket name
    bucket = "a"
    showElapse, err = s.rawSetBucketACL(bucket, "public-read", true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    showElapse, err = s.rawGetStat(bucket, "")
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestSetBucketEmptyACL(c *C) {
    bucket := bucketNamePrefix + "acl3"
    s.putBucket(bucket, c)
    time.Sleep(sleepTime)

    object := "test"
    s.putObject(bucket, object, uploadFileName, c)

    showElapse, err := s.rawSetObjectACL(bucket, object, "", false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    s.removeBucket(bucket, true, c)
    time.Sleep(sleepTime)
}

func (s *OssutilCommandSuite) TestSetObjectACL(c *C) {
    bucket := bucketNameSetACL

    object := "TestSetObjectACL"

    // set acl to not exist object
    showElapse, err := s.rawSetObjectACL(bucket, object, "default", false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    object = "setacl-oldobject"
    s.putObject(bucket, object, uploadFileName, c)

    //get object acl
    objectStat := s.getStat(bucket, object, c)
    c.Assert(objectStat[StatACL], Equals, "default")

    object = "setacl-newobject"
    s.putObject(bucket, object, uploadFileName, c)

    // set acl
    for _, acl := range []string{"default", "private", "public-read", "public-read-write"} {
        s.setObjectACL(bucket, object, acl, false, true, c)
        objectStat = s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, acl)
    }

    s.setObjectACL(bucket, object, "private", false, true, c)

    // set error acl
    for _, acl := range []string{"public_read", "erracl", "私有"} {
        showElapse, err = s.rawSetObjectACL(bucket, object, acl, false, false)
        c.Assert(showElapse, Equals, false)
        c.Assert(err, NotNil)

        objectStat = s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "private")
    }
}

func (s *OssutilCommandSuite) TestBatchSetObjectACL(c *C) {
    bucket := bucketNameSetACL1

    // put objects
    num := 2
    objectNames := []string{}
    for i := 0; i < num; i++ {
        object := fmt.Sprintf("TestBatchSetObjectACL_setacl%d", i)
        s.putObject(bucket, object, uploadFileName, c)
        objectNames = append(objectNames, object)
    }
    time.Sleep(time.Second)

    for _, object := range objectNames {
        objectStat := s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "default")
    }

    // without --force option
    s.setObjectACL(bucket, "", "public-read-write", true, false, c)

    for _, object := range objectNames {
        objectStat := s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "default")
    }

    for _, acl := range []string{"private"} {
        s.setObjectACL(bucket, "TestBatchSetObjectACL_setacl1", acl, true, true, c)
        time.Sleep(sleepTime)

        objectStat := s.getStat(bucket, "TestBatchSetObjectACL_setacl1", c)
        c.Assert(objectStat[StatACL], Equals, acl)
    }

    showElapse, err := s.rawSetObjectACL(bucket, "TestBatchSetObjectACL_setacl", "erracl", true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestErrSetACL(c *C) {
    acl := "private"
    args := []string{"os://", acl}
    showElapse, err := s.rawSetACLWithArgs(args, false, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{"oss://", acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, false, true)

    // error set bucket acl
    bucket := bucketNamePrefix + "set-acl"
    object := "testobject"
    args = []string{CloudURLToString(bucket, object), acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, ""), acl}
    showElapse, err = s.rawSetACLWithArgs(args, true, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // miss acl
    args = []string{CloudURLToString(bucket, "")}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, object)}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, object)}
    showElapse, err = s.rawSetACLWithArgs(args, true, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // miss object
    args = []string{CloudURLToString(bucket, ""), acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // bad prefix
    showElapse, err = s.rawSetObjectACL(bucket, "/object", acl, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestErrBatchSetACL(c *C) {
    bucket := bucketNameExist

    // put objects
    num := 10
    objectNames := []string{}
    for i := 0; i < num; i++ {
        object := fmt.Sprintf("TestErrBatchSetACL_setacl:%d", i)
        s.putObject(bucket, object, uploadFileName, c)
        objectNames = append(objectNames, object)
    }

    command := "set-acl"
    str := ""
    str1 := "abc"
    args := []string{CloudURLToString(bucket, ""), "public-read-write"}
    routines := strconv.Itoa(Routines)
    ok := true
    options := OptionMapType{
        "endpoint": &str1,
        "accessKeyID": &str1,
        "accessKeySecret": &str1,
        "stsToken": &str,
        "routines": &routines,
        "recursive": &ok,
        "force": &ok,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    for _, object := range objectNames {
        objectStat := s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "default")
    }
}

func (s *OssutilCommandSuite) TestSetACLIDKey(c *C) {
    bucket := bucketNameExist

    cfile := "ossutil_test.config_boto"
    data := fmt.Sprintf("[Credentials]\nendpoint=%s\naccessKeyID=%s\naccessKeySecret=%s\n[Bucket-Endpoint]\n%s=%s[Bucket-Cname]\n%s=%s", "abc", "def", "ghi", bucket, "abc", bucket, "abc")
    s.createFile(cfile, data, c)

    command := "set-acl"
    str := ""
    args := []string{CloudURLToString(bucket, ""), "public-read"}
    routines := strconv.Itoa(Routines)
    ok := true
    options := OptionMapType{
        "endpoint": &str,
        "accessKeyID": &str,
        "accessKeySecret": &str,
        "stsToken": &str,
        "configFile": &cfile,
        "routines": &routines,
        "bucket": &ok,
        "force": &ok,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    c.Assert(err, NotNil)

    options = OptionMapType{
        "endpoint": &endpoint,
        "accessKeyID": &accessKeyID,
        "accessKeySecret": &accessKeySecret,
        "stsToken": &str,
        "configFile": &cfile,
        "routines": &routines,
        "bucket": &ok,
        "force": &ok,
    }
    showElapse, err = cm.RunCommand(command, args, options)
    c.Assert(err, IsNil)
    c.Assert(showElapse, Equals, true)

    _ = os.Remove(cfile)
}
<commit_msg>modify case<commit_after>package lib

import (
    "fmt"
    "os"
    "strconv"
    "time"

    . "gopkg.in/check.v1"
)

func (s *OssutilCommandSuite) rawSetBucketACL(bucket, acl string, force bool) (bool, error) {
    args := []string{CloudURLToString(bucket, ""), acl}
    showElapse, err := s.rawSetACLWithArgs(args, false, true, force)
    return showElapse, err
}

func (s *OssutilCommandSuite) rawSetObjectACL(bucket, object, acl string, recursive, force bool) (bool, error) {
    args := []string{CloudURLToString(bucket, object), acl}
    showElapse, err := s.rawSetACLWithArgs(args, recursive, false, force)
    return showElapse, err
}

func (s *OssutilCommandSuite) rawSetACLWithArgs(args []string, recursive, bucket, force bool) (bool, error) {
    command := "set-acl"
    str := ""
    routines := strconv.Itoa(Routines)
    options := OptionMapType{
        "endpoint": &str,
        "accessKeyID": &str,
        "accessKeySecret": &str,
        "stsToken": &str,
        "configFile": &configFile,
        "routines": &routines,
        "recursive": &recursive,
        "bucket": &bucket,
        "force": &force,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    time.Sleep(sleepTime)
    return showElapse, err
}

func (s *OssutilCommandSuite) TestSetBucketACL(c *C) {
    bucket := bucketNameExist

    // set acl
    for _, acl := range []string{"private", "public-read", "public-read-write"} {
        s.setBucketACL(bucket, acl, c)
        bucketStat := s.getStat(bucket, "", c)
        c.Assert(bucketStat[StatACL], Equals, acl)
    }
}

func (s *OssutilCommandSuite) TestSetBucketErrorACL(c *C) {
    bucket := bucketNameDest

    for _, acl := range []string{"default", "def", "erracl", "私有"} {
        showElapse, err := s.rawSetBucketACL(bucket, acl, false)
        c.Assert(err, NotNil)
        c.Assert(showElapse, Equals, false)

        showElapse, err = s.rawSetBucketACL(bucket, acl, true)
        c.Assert(err, NotNil)
        c.Assert(showElapse, Equals, false)

        bucketStat := s.getStat(bucket, "", c)
        c.Assert(bucketStat[StatACL], Equals, "private")
    }
}

func (s *OssutilCommandSuite) TestSetNotExistBucketACL(c *C) {
    bucket := bucketNamePrefix + "noexistsetacl"

    showElapse, err := s.rawGetStat(bucket, "")
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // set acl and create bucket
    showElapse, err = s.rawSetBucketACL(bucket, "public-read", true)
    c.Assert(err, IsNil)
    c.Assert(showElapse, Equals, true)

    time.Sleep(sleepTime)
    bucketStat := s.getStat(bucket, "", c)
    c.Assert(bucketStat[StatACL], Equals, "public-read")

    s.removeBucket(bucket, true, c)
    time.Sleep(3*sleepTime)

    // invalid bucket name
    bucket = "a"
    showElapse, err = s.rawSetBucketACL(bucket, "public-read", true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    showElapse, err = s.rawGetStat(bucket, "")
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestSetBucketEmptyACL(c *C) {
    bucket := bucketNamePrefix + "acl3"
    s.putBucket(bucket, c)
    time.Sleep(sleepTime)

    object := "test"
    s.putObject(bucket, object, uploadFileName, c)

    showElapse, err := s.rawSetObjectACL(bucket, object, "", false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    s.removeBucket(bucket, true, c)
    time.Sleep(sleepTime)
}

func (s *OssutilCommandSuite) TestSetObjectACL(c *C) {
    bucket := bucketNameSetACL

    object := "TestSetObjectACL"

    // set acl to not exist object
    showElapse, err := s.rawSetObjectACL(bucket, object, "default", false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    object = "setacl-oldobject"
    s.putObject(bucket, object, uploadFileName, c)

    //get object acl
    objectStat := s.getStat(bucket, object, c)
    c.Assert(objectStat[StatACL], Equals, "default")

    object = "setacl-newobject"
    s.putObject(bucket, object, uploadFileName, c)

    // set acl
    for _, acl := range []string{"default", "private", "public-read", "public-read-write"} {
        s.setObjectACL(bucket, object, acl, false, true, c)
        objectStat = s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, acl)
    }

    s.setObjectACL(bucket, object, "private", false, true, c)

    // set error acl
    for _, acl := range []string{"public_read", "erracl", "私有"} {
        showElapse, err = s.rawSetObjectACL(bucket, object, acl, false, false)
        c.Assert(showElapse, Equals, false)
        c.Assert(err, NotNil)

        objectStat = s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "private")
    }
}

func (s *OssutilCommandSuite) TestBatchSetObjectACL(c *C) {
    bucket := bucketNameSetACL1

    // put objects
    num := 2
    objectNames := []string{}
    for i := 0; i < num; i++ {
        object := fmt.Sprintf("TestBatchSetObjectACL_setacl%d", i)
        s.putObject(bucket, object, uploadFileName, c)
        objectNames = append(objectNames, object)
    }
    time.Sleep(time.Second)

    for _, object := range objectNames {
        objectStat := s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "default")
    }

    // without --force option
    s.setObjectACL(bucket, "", "public-read-write", true, false, c)

    /*for _, object := range objectNames {
        objectStat := s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "default")
    }*/

    for _, acl := range []string{"private"} {
        s.setObjectACL(bucket, "TestBatchSetObjectACL_setacl1", acl, true, true, c)
        time.Sleep(sleepTime)

        objectStat := s.getStat(bucket, "TestBatchSetObjectACL_setacl1", c)
        c.Assert(objectStat[StatACL], Equals, acl)
    }

    showElapse, err := s.rawSetObjectACL(bucket, "TestBatchSetObjectACL_setacl", "erracl", true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestErrSetACL(c *C) {
    acl := "private"
    args := []string{"os://", acl}
    showElapse, err := s.rawSetACLWithArgs(args, false, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{"oss://", acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, false, true)

    // error set bucket acl
    bucket := bucketNamePrefix + "set-acl"
    object := "testobject"
    args = []string{CloudURLToString(bucket, object), acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, ""), acl}
    showElapse, err = s.rawSetACLWithArgs(args, true, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // miss acl
    args = []string{CloudURLToString(bucket, "")}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, object)}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, object)}
    showElapse, err = s.rawSetACLWithArgs(args, true, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // miss object
    args = []string{CloudURLToString(bucket, ""), acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // bad prefix
    showElapse, err = s.rawSetObjectACL(bucket, "/object", acl, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestErrBatchSetACL(c *C) {
    bucket := bucketNameExist

    // put objects
    num := 10
    objectNames := []string{}
    for i := 0; i < num; i++ {
        object := fmt.Sprintf("TestErrBatchSetACL_setacl:%d", i)
        s.putObject(bucket, object, uploadFileName, c)
        objectNames = append(objectNames, object)
    }

    command := "set-acl"
    str := ""
    str1 := "abc"
    args := []string{CloudURLToString(bucket, ""), "public-read-write"}
    routines := strconv.Itoa(Routines)
    ok := true
    options := OptionMapType{
        "endpoint": &str1,
        "accessKeyID": &str1,
        "accessKeySecret": &str1,
        "stsToken": &str,
        "routines": &routines,
        "recursive": &ok,
        "force": &ok,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    for _, object := range objectNames {
        objectStat := s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "default")
    }
}

func (s *OssutilCommandSuite) TestSetACLIDKey(c *C) {
    bucket := bucketNameExist

    cfile := "ossutil_test.config_boto"
    data := fmt.Sprintf("[Credentials]\nendpoint=%s\naccessKeyID=%s\naccessKeySecret=%s\n[Bucket-Endpoint]\n%s=%s[Bucket-Cname]\n%s=%s", "abc", "def", "ghi", bucket, "abc", bucket, "abc")
    s.createFile(cfile, data, c)

    command := "set-acl"
    str := ""
    args := []string{CloudURLToString(bucket, ""), "public-read"}
    routines := strconv.Itoa(Routines)
    ok := true
    options := OptionMapType{
        "endpoint": &str,
        "accessKeyID": &str,
        "accessKeySecret": &str,
        "stsToken": &str,
        "configFile": &cfile,
        "routines": &routines,
        "bucket": &ok,
        "force": &ok,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    c.Assert(err, NotNil)

    options = OptionMapType{
        "endpoint": &endpoint,
        "accessKeyID": &accessKeyID,
        "accessKeySecret": &accessKeySecret,
        "stsToken": &str,
        "configFile": &cfile,
        "routines": &routines,
        "bucket": &ok,
        "force": &ok,
    }
    showElapse, err = cm.RunCommand(command, args, options)
    c.Assert(err, IsNil)
    c.Assert(showElapse, Equals, true)

    _ = os.Remove(cfile)
}
<|endoftext|>


<commit_before>package gpg

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"io"
	"strings"

	"golang.org/x/crypto/openpgp/packet"

	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
	"golang.org/x/crypto/openpgp"
	"golang.org/x/crypto/openpgp/armor"
)

func pathShowSessionKey(b *backend) *framework.Path {
	return &framework.Path{
		Pattern: "show-session-key/" + framework.GenericNameRegex("name"),
		Fields: map[string]*framework.FieldSchema{
			"name": {
				Type:        framework.TypeString,
				Description: "The key to use",
			},
			"ciphertext": {
				Type:        framework.TypeString,
				Description: "The ciphertext to decrypt",
			},
			"format": {
				Type:        framework.TypeString,
				Default:     "base64",
				Description: `Encoding format the ciphertext uses. Can be "base64" or "ascii-armor". Defaults to "base64".`,
			},
			"signer_key": {
				Type:        framework.TypeString,
				Description: "The ASCII-armored GPG key of the signer of the ciphertext. If present, the signature must be valid.",
			},
		},

		Callbacks: map[logical.Operation]framework.OperationFunc{
			logical.UpdateOperation: b.pathShowSessionKeyWrite,
		},

		HelpSynopsis:    pathDecryptSessionKeyHelpSyn,
		HelpDescription: pathDecryptSessionKeyHelpDesc,
	}
}

func (b *backend) pathShowSessionKeyWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	format := data.Get("format").(string)
	switch format {
	case "base64":
	case "ascii-armor":
	default:
		return logical.ErrorResponse(fmt.Sprintf("unsupported encoding format %s; must be \"base64\" or \"ascii-armor\"", format)), nil
	}

	keyEntry, err := b.key(ctx, req.Storage, data.Get("name").(string))
	if err != nil {
		return nil, err
	}
	if keyEntry == nil {
		return logical.ErrorResponse("key not found"), logical.ErrInvalidRequest
	}

	r := bytes.NewReader(keyEntry.SerializedKey)
	keyring, err := openpgp.ReadKeyRing(r)
	if err != nil {
		return nil, err
	}

	signerKey := data.Get("signer_key").(string)
	if signerKey != "" {
		el, err := openpgp.ReadArmoredKeyRing(strings.NewReader(signerKey))
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}
		keyring = append(keyring, el[0])
	}

	ciphertextEncoded := strings.NewReader(data.Get("ciphertext").(string))
	var ciphertextDecoder io.Reader
	switch format {
	case "base64":
		ciphertextDecoder = base64.NewDecoder(base64.StdEncoding, ciphertextEncoded)
	case "ascii-armor":
		block, err := armor.Decode(ciphertextEncoded)
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}
		ciphertextDecoder = block.Body
	}

	var p packet.Packet
	var sessionKey string
ParsePackets:
	for {
		p, err = packet.Read(ciphertextDecoder)
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}
		switch p := p.(type) {
		case *packet.EncryptedKey:
			encryptedKey := packet.EncryptedKey(*p)
			keys := keyring.KeysById(encryptedKey.KeyId)
			for _, key := range keys {
				encryptedKey.Decrypt(key.PrivateKey, nil)

				if encryptedKey.Key != nil && len(encryptedKey.Key) > 0 {
					sessionKey = fmt.Sprintf("%d:%s", encryptedKey.CipherFunc, strings.ToUpper(hex.EncodeToString(encryptedKey.Key)))
					break ParsePackets
				}
			}

			if encryptedKey.Key == nil || len(encryptedKey.Key) == 0 {
				return logical.ErrorResponse("Unable to decrypt session key"), nil
			}
		}
	}

	return &logical.Response{
		Data: map[string]interface{}{
			"session_key": sessionKey,
		},
	}, nil
}

const pathDecryptSessionKeyHelpSyn = "Decrypt a session key of a message using a named GPG key"

const pathDecryptSessionKeyHelpDesc = `
This path uses the named GPG key from the request path to decrypt the session key of a message.
`
<commit_msg>Session key can be encrypted with different keys<commit_after>package gpg

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"io"
	"strings"

	"golang.org/x/crypto/openpgp/packet"

	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
	"golang.org/x/crypto/openpgp"
	"golang.org/x/crypto/openpgp/armor"
)

func pathShowSessionKey(b *backend) *framework.Path {
	return &framework.Path{
		Pattern: "show-session-key/" + framework.GenericNameRegex("name"),
		Fields: map[string]*framework.FieldSchema{
			"name": {
				Type:        framework.TypeString,
				Description: "The key to use",
			},
			"ciphertext": {
				Type:        framework.TypeString,
				Description: "The ciphertext to decrypt",
			},
			"format": {
				Type:        framework.TypeString,
				Default:     "base64",
				Description: `Encoding format the ciphertext uses. Can be "base64" or "ascii-armor". Defaults to "base64".`,
			},
			"signer_key": {
				Type:        framework.TypeString,
				Description: "The ASCII-armored GPG key of the signer of the ciphertext. If present, the signature must be valid.",
			},
		},

		Callbacks: map[logical.Operation]framework.OperationFunc{
			logical.UpdateOperation: b.pathShowSessionKeyWrite,
		},

		HelpSynopsis:    pathDecryptSessionKeyHelpSyn,
		HelpDescription: pathDecryptSessionKeyHelpDesc,
	}
}

func (b *backend) pathShowSessionKeyWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	format := data.Get("format").(string)
	switch format {
	case "base64":
	case "ascii-armor":
	default:
		return logical.ErrorResponse(fmt.Sprintf("unsupported encoding format %s; must be \"base64\" or \"ascii-armor\"", format)), nil
	}

	keyEntry, err := b.key(ctx, req.Storage, data.Get("name").(string))
	if err != nil {
		return nil, err
	}
	if keyEntry == nil {
		return logical.ErrorResponse("key not found"), logical.ErrInvalidRequest
	}

	r := bytes.NewReader(keyEntry.SerializedKey)
	keyring, err := openpgp.ReadKeyRing(r)
	if err != nil {
		return nil, err
	}

	signerKey := data.Get("signer_key").(string)
	if signerKey != "" {
		el, err := openpgp.ReadArmoredKeyRing(strings.NewReader(signerKey))
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}
		keyring = append(keyring, el[0])
	}

	ciphertextEncoded := strings.NewReader(data.Get("ciphertext").(string))
	var ciphertextDecoder io.Reader
	switch format {
	case "base64":
		ciphertextDecoder = base64.NewDecoder(base64.StdEncoding, ciphertextEncoded)
	case "ascii-armor":
		block, err := armor.Decode(ciphertextEncoded)
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}
		ciphertextDecoder = block.Body
	}

	var p packet.Packet
	var sessionKey string
	for {
		p, err = packet.Read(ciphertextDecoder)
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}
		switch p := p.(type) {
		case *packet.EncryptedKey:
			encryptedKey := packet.EncryptedKey(*p)
			keys := keyring.KeysById(encryptedKey.KeyId)
			for _, key := range keys {
				encryptedKey.Decrypt(key.PrivateKey, nil)

				if encryptedKey.Key != nil && len(encryptedKey.Key) > 0 {
					sessionKey = fmt.Sprintf("%d:%s", encryptedKey.CipherFunc, strings.ToUpper(hex.EncodeToString(encryptedKey.Key)))
					return &logical.Response{
						Data: map[string]interface{}{
							"session_key": sessionKey,
						},
					}, nil
				}
			}
		}
	}

	return logical.ErrorResponse("Unable to decrypt session key"), nil
}

const pathDecryptSessionKeyHelpSyn = "Decrypt a session key of a message using a named GPG key"

const pathDecryptSessionKeyHelpDesc = `
This path uses the named GPG key from the request path to decrypt the session key of a message.
`
<|endoftext|>


<commit_before>// base36 supports Base36 encoding and decoding.
package base36

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"strings"

	"github.com/grokify/base36"
	"github.com/grokify/gotilla/math/bigint"
)

// Encode36 returns an encoded string given a byte array.
func Encode36(ba []byte) string {
	return Encode36HexString(hex.EncodeToString(ba))
}

// Encode36String returns an encoded string given a string.
func Encode36String(s string) string {
	return Encode36([]byte(s))
}

// Encode36HexString returns an encoded string given a string.
func Encode36HexString(s16 string) string {
	i := bigint.HexToInt(s16)
	return strings.ToLower(base36.EncodeBigInt(i))
}

// Decode36 returns a decoded byte array given an encoded byte array.
func Decode36(b36 []byte) ([]byte, error) {
	return Decode36String(string(b36))
}

// Decode36String returns a decoded byte array given an encoded string.
func Decode36String(s36 string) ([]byte, error) {
	bi := base36.DecodeBigInt(s36)
	return hex.DecodeString(bigint.IntToHex(bi))
}

// Md5Base36 returns a Base36 encoded MD5 hash of a string.
func Md5Base36(s string) string {
	return fmt.Sprintf("%025s",
		Encode36HexString(fmt.Sprintf("%x", md5.Sum([]byte(s)))))
}

/*
GMP Versions

import "github.com/grokify/gmp"

// Encode36String returns an encoded string given a byte array.
func Encode36(ba []byte) string {
	s16 := hex.EncodeToString(ba)
	bi := gmp.NewInt(0)
	bi.SetString(s16, 16)
	return bi.InBase(36)
}

// Decode36String returns a decoded byte array given an encoded string.
func Decode36String(s36 string) ([]byte, error) {
	bi := gmp.NewInt(0)
	bi.SetString(s36, 36)
	s16 := bi.InBase(16)
	return hex.DecodeString(s16)
}

// Md5Base36 returns a Base36 encoded MD5 hash of a string.
func Md5Base36(s string) string {
	h := md5.New()
	io.WriteString(h, s)
	s16 := fmt.Sprintf("%x", h.Sum(nil))
	bi := gmp.NewInt(0)
	bi.SetString(s16, 16)
	return fmt.Sprintf("%025s", bi.InBase(36))
}
*/
<commit_msg>extract constant<commit_after>// base36 supports Base36 encoding and decoding.
package base36

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"strconv"
	"strings"

	"github.com/grokify/base36"
	"github.com/grokify/gotilla/math/bigint"
)

// Md5Base36Length is the length for a MD5 Base36 string
const Md5Base36Length int = 25

// Encode36 returns an encoded string given a byte array.
func Encode36(ba []byte) string {
	return Encode36HexString(hex.EncodeToString(ba))
}

// Encode36String returns an encoded string given a string.
func Encode36String(s string) string {
	return Encode36([]byte(s))
}

// Encode36HexString returns an encoded string given a string.
func Encode36HexString(s16 string) string {
	i := bigint.HexToInt(s16)
	return strings.ToLower(base36.EncodeBigInt(i))
}

// Decode36 returns a decoded byte array given an encoded byte array.
func Decode36(b36 []byte) ([]byte, error) {
	return Decode36String(string(b36))
}

// Decode36String returns a decoded byte array given an encoded string.
func Decode36String(s36 string) ([]byte, error) {
	bi := base36.DecodeBigInt(s36)
	return hex.DecodeString(bigint.IntToHex(bi))
}

// Md5Base36 returns a Base36 encoded MD5 hash of a string.
func Md5Base36(s string) string {
	return fmt.Sprintf(`%0`+strconv.Itoa(Md5Base36Length)+`s`,
		Encode36HexString(fmt.Sprintf("%x", md5.Sum([]byte(s)))))
}

/*
GMP Versions

import "github.com/grokify/gmp"

// Encode36String returns an encoded string given a byte array.
func Encode36(ba []byte) string {
	s16 := hex.EncodeToString(ba)
	bi := gmp.NewInt(0)
	bi.SetString(s16, 16)
	return bi.InBase(36)
}

// Decode36String returns a decoded byte array given an encoded string.
func Decode36String(s36 string) ([]byte, error) {
	bi := gmp.NewInt(0)
	bi.SetString(s36, 36)
	s16 := bi.InBase(16)
	return hex.DecodeString(s16)
}

// Md5Base36 returns a Base36 encoded MD5 hash of a string.
func Md5Base36(s string) string {
	h := md5.New()
	io.WriteString(h, s)
	s16 := fmt.Sprintf("%x", h.Sum(nil))
	bi := gmp.NewInt(0)
	bi.SetString(s16, 16)
	return fmt.Sprintf("%025s", bi.InBase(36))
}
*/
<|endoftext|>