예제 #1
1
//line fitted_type.got:17
func drawFittedTableQLetters(rSeq, qSeq alphabet.QLetters, index alphabet.Index, table []int, a [][]int) {
	tw := tabwriter.NewWriter(os.Stdout, 0, 0, 0, ' ', tabwriter.AlignRight|tabwriter.Debug)
	fmt.Printf("rSeq: %s\n", rSeq)
	fmt.Printf("qSeq: %s\n", qSeq)
	fmt.Fprint(tw, "\tqSeq\t")
	for _, l := range qSeq {
		fmt.Fprintf(tw, "%c\t", l)
	}
	fmt.Fprintln(tw)

	r, c := rSeq.Len()+1, qSeq.Len()+1
	fmt.Fprint(tw, "rSeq\t")
	for i := 0; i < r; i++ {
		if i != 0 {
			fmt.Fprintf(tw, "%c\t", rSeq[i-1].L)
		}

		for j := 0; j < c; j++ {
			p := pointerFittedQLetters(rSeq, qSeq, i, j, table, index, a, c)
			if p != "" {
				fmt.Fprintf(tw, "%s % 3v\t", p, table[i*c+j])
			} else {
				fmt.Fprintf(tw, "%v\t", table[i*c+j])
			}
		}
		fmt.Fprintln(tw)
	}
	tw.Flush()
}
예제 #2
0
// createCluster generates a new cluster using the provided stopper and the
// number of nodes supplied. Each node will have one store to start.
func createCluster(
	stopper *stop.Stopper,
	nodeCount int,
	epochWriter, actionWriter io.Writer,
	script Script,
	rand *rand.Rand,
) *Cluster {
	clock := hlc.NewClock(hlc.UnixNano)
	rpcContext := rpc.NewContext(nil, clock, stopper)
	g := gossip.New(rpcContext, nil, stopper)
	// NodeID is required for Gossip, so set it to -1 for the cluster Gossip
	// instance to prevent conflicts with real NodeIDs.
	g.SetNodeID(-1)
	storePool := storage.NewStorePool(g, clock, storage.TestTimeUntilStoreDeadOff, stopper)
	c := &Cluster{
		stopper:   stopper,
		clock:     clock,
		rpc:       rpcContext,
		gossip:    g,
		storePool: storePool,
		allocator: storage.MakeAllocator(storePool, storage.AllocatorOptions{
			AllowRebalance: true,
			Deterministic:  true,
		}),
		storeGossiper:   gossiputil.NewStoreGossiper(g),
		nodes:           make(map[roachpb.NodeID]*Node),
		stores:          make(map[roachpb.StoreID]*Store),
		ranges:          make(map[roachpb.RangeID]*Range),
		rangeIDsByStore: make(map[roachpb.StoreID]roachpb.RangeIDSlice),
		rand:            rand,
		epochWriter:     tabwriter.NewWriter(epochWriter, 8, 1, 2, ' ', 0),
		actionWriter:    tabwriter.NewWriter(actionWriter, 8, 1, 2, ' ', 0),
		script:          script,
		epoch:           -1,
	}

	// Add the nodes.
	for i := 0; i < nodeCount; i++ {
		c.addNewNodeWithStore()
	}

	// Add a single range and add to this first node's first store.
	firstRange := c.addRange()
	firstRange.addReplica(c.stores[0])

	c.calculateRangeIDsByStore()

	// Output the first epoch header.
	c.epoch = 0
	c.OutputEpochHeader()
	c.OutputEpoch()
	c.flush()

	return c
}
예제 #3
0
// createCluster generates a new cluster using the provided stopper and the
// number of nodes supplied. Each node will have one store to start.
func createCluster(stopper *stop.Stopper, nodeCount int, epochWriter, actionWriter io.Writer, script Script) *Cluster {
	rand, seed := randutil.NewPseudoRand()
	clock := hlc.NewClock(hlc.UnixNano)
	rpcContext := rpc.NewContext(&base.Context{}, clock, stopper)
	g := gossip.New(rpcContext, gossip.TestInterval, gossip.TestBootstrap)
	storePool := storage.NewStorePool(g, storage.TestTimeUntilStoreDeadOff, stopper)
	c := &Cluster{
		stopper:   stopper,
		clock:     clock,
		rpc:       rpcContext,
		gossip:    g,
		storePool: storePool,
		allocator: storage.MakeAllocator(storePool, storage.RebalancingOptions{
			AllowRebalance: true,
			Deterministic:  true,
		}),
		storeGossiper:   gossiputil.NewStoreGossiper(g),
		nodes:           make(map[roachpb.NodeID]*Node),
		stores:          make(map[roachpb.StoreID]*Store),
		ranges:          make(map[roachpb.RangeID]*Range),
		rangeIDsByStore: make(map[roachpb.StoreID]roachpb.RangeIDSlice),
		rand:            rand,
		seed:            seed,
		epochWriter:     tabwriter.NewWriter(epochWriter, 8, 1, 2, ' ', 0),
		actionWriter:    tabwriter.NewWriter(actionWriter, 8, 1, 2, ' ', 0),
		script:          script,
		epoch:           -1,
	}

	// Add the nodes.
	for i := 0; i < nodeCount; i++ {
		c.addNewNodeWithStore()
	}

	// Add a single range and add to this first node's first store.
	firstRange := c.addRange()
	firstRange.addReplica(c.stores[0])

	c.calculateRangeIDsByStore()

	// Output the first epoch header.
	c.epoch = 0
	c.OutputEpochHeader()
	c.OutputEpoch()
	c.flush()

	return c
}
예제 #4
0
func (s *Simulator) Help(args []string) {
	w := tabwriter.NewWriter(s.out, 0, 8, 0, '\t', 0)
	for _, c := range s.commands {
		fmt.Fprintf(w, "%s\t%s\t%s\n", c.Name, c.Args, c.Help)
	}
	w.Flush()
}
예제 #5
0
func listTask(ctx *cli.Context) {
	tasks := pClient.GetTasks()
	if tasks.Err != nil {
		fmt.Printf("Error getting tasks:\n%v\n", tasks.Err)
		os.Exit(1)
	}

	w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
	printFields(w, false, 0,
		"ID",
		"NAME",
		"STATE",
		"HIT",
		"MISS",
		"FAIL",
		"CREATED",
		"LAST FAILURE",
	)
	for _, task := range tasks.ScheduledTasks {
		printFields(w, false, 0,
			task.ID,
			task.Name,
			task.State,
			trunc(task.HitCount),
			trunc(task.MissCount),
			trunc(task.FailedCount),
			task.CreationTime().Format(unionParseFormat),
			task.LastFailureMessage,
		)
	}
	w.Flush()
}
예제 #6
0
파일: ls.go 프로젝트: kristinn/govmomi
func (cmd *ls) Run(f *flag.FlagSet) error {
	ctx := context.TODO()

	c, err := cmd.Client()
	if err != nil {
		return err
	}

	m, err := object.GetCustomFieldsManager(c)
	if err != nil {
		return err
	}

	field, err := m.Field(ctx)
	if err != nil {
		return err
	}

	tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)

	for _, def := range field {
		fmt.Fprintf(tw, "%d\t%s\n", def.Key, def.Name)
	}

	return tw.Flush()
}
예제 #7
0
파일: commands.go 프로젝트: scottjg/docker
func (srv *Server) CmdHistory(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
	cmd := rcli.Subcmd(stdout, "history", "IMAGE", "Show the history of an image")
	if err := cmd.Parse(args); err != nil {
		return nil
	}
	if cmd.NArg() != 1 {
		cmd.Usage()
		return nil
	}
	image, err := srv.runtime.repositories.LookupImage(cmd.Arg(0))
	if err != nil {
		return err
	}
	w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
	defer w.Flush()
	fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
	return image.WalkHistory(func(img *Image) error {
		fmt.Fprintf(w, "%s\t%s\t%s\n",
			srv.runtime.repositories.ImageName(img.ShortId()),
			HumanDuration(time.Now().Sub(img.Created))+" ago",
			strings.Join(img.ContainerConfig.Cmd, " "),
		)
		return nil
	})
}
예제 #8
0
파일: commands.go 프로젝트: jweede/docker
func (cli *DockerCli) CmdHistory(args ...string) error {
	cmd := Subcmd("history", "IMAGE", "Show the history of an image")
	if err := cmd.Parse(args); err != nil {
		return nil
	}
	if cmd.NArg() != 1 {
		cmd.Usage()
		return nil
	}

	body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
	if err != nil {
		return err
	}

	var outs []ApiHistory
	err = json.Unmarshal(body, &outs)
	if err != nil {
		return err
	}
	w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
	fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")

	for _, out := range outs {
		fmt.Fprintf(w, "%s\t%s ago\t%s\n", out.Id, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.CreatedBy)
	}
	w.Flush()
	return nil
}
예제 #9
0
func (cmd *esxcli) formatTable(res *Response) {
	fields := res.Info.Hints.Fields()

	tw := tabwriter.NewWriter(os.Stdout, len(fields), 0, 2, ' ', 0)

	var hr []string
	for _, name := range fields {
		hr = append(hr, strings.Repeat("-", len(name)))
	}

	fmt.Fprintln(tw, strings.Join(fields, "\t"))
	fmt.Fprintln(tw, strings.Join(hr, "\t"))

	for _, vals := range res.Values {
		var row []string

		for _, name := range fields {
			key := strings.Replace(name, " ", "", -1)
			if val, ok := vals[key]; ok {
				row = append(row, strings.Join(val, ", "))
			} else {
				row = append(row, "")
			}
		}

		fmt.Fprintln(tw, strings.Join(row, "\t"))
	}

	_ = tw.Flush()
}
예제 #10
0
// Print all the images based on SUSE. It will print in a format that is as
// close to the `docker` command as possible.
func printImages(imgs []*dockerclient.Image) {
	w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
	fmt.Fprintf(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE\n")

	cache := getCacheFile()
	for counter, img := range imgs {
		fmt.Printf("Inspecting image %d/%d\r", (counter + 1), len(imgs))
		if cache.isSUSE(img.Id) {
			if len(img.RepoTags) < 1 {
				continue
			}

			id := stringid.TruncateID(img.Id)
			size := units.HumanSize(float64(img.VirtualSize))
			for _, tag := range img.RepoTags {
				t := strings.SplitN(tag, ":", 2)
				fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\n", t[0], t[1], id,
					timeAgo(img.Created), size)
			}
		}
	}

	fmt.Printf("\n")

	_ = w.Flush()
	cache.flush()
}
예제 #11
0
// String formats headers by outputting headers and values in equal columns, sorted alphabetically by header. Repeated headers are marked with an asterisk.
func (h ResponseHeader) String() string {
	// Sort headers; get max header string length
	sortedHeaderKeys := make([]string, 0, len(h))
	for header := range h {
		sortedHeaderKeys = append(sortedHeaderKeys, header)
	}
	sort.Strings(sortedHeaderKeys)

	// Use a tabwriter to pretty print the output to a buffer
	var (
		buf bytes.Buffer
		tw  = tabwriter.NewWriter(&buf, 0, 0, 2, ' ', 0)
	)
	for _, headerKey := range sortedHeaderKeys {
		for i, headerValue := range h[headerKey] {
			// Flag repeated values with an asterisk
			asterisk := ""
			if i > 0 {
				asterisk = " *"
			}

			// Prevent long lines by breaking at "; "
			if len(headerValue) > 50 {
				headerValue = strings.Replace(headerValue, "; ", ";\n...\t", -1)
			}
			fmt.Fprintf(tw, "%s%s\t%s\n", headerKey, asterisk, headerValue)
		}
	}
	tw.Flush()
	return buf.String()
}
예제 #12
0
func cmdCreate(c *cli.Context) {
	utils.FlagsRequired(c, []string{"name", "domain_id", "ssh_profile_id", "firewall_profile_id"})
	webservice, err := webservice.NewWebService()
	utils.CheckError(err)

	v := make(map[string]string)

	v["name"] = c.String("name")
	v["domain_id"] = c.String("domain_id")
	v["ssh_profile_id"] = c.String("ssh_profile_id")
	v["firewall_profile_id"] = c.String("firewall_profile_id")

	jsonBytes, err := json.Marshal(v)
	utils.CheckError(err)
	err, res, code := webservice.Post("/v1/cloud/workspaces", jsonBytes)
	if res == nil {
		log.Fatal(err)
	}
	utils.CheckError(err)
	utils.CheckReturnCode(code, res)

	var workspace Workspace
	err = json.Unmarshal(res, &workspace)
	utils.CheckError(err)

	w := tabwriter.NewWriter(os.Stdout, 15, 1, 3, ' ', 0)
	fmt.Fprintln(w, "ID\tNAME\tDEFAULT\tDOMAIN ID\tSSH PROFILE ID\tFIREWALL PROFILE ID\r")
	fmt.Fprintf(w, "%s\t%s\t%t\t%s\t%s\t%s\n", workspace.Id, workspace.Name, workspace.Default, workspace.Domain_id, workspace.Ssh_profile_id, workspace.Firewall_profile_id)

	w.Flush()

}
예제 #13
0
파일: info.go 프로젝트: hmahmood/govmomi
func (r *infoResult) Write(w io.Writer) error {
	// Maintain order via r.objects as Property collector does not always return results in order.
	objects := make(map[types.ManagedObjectReference]mo.HostSystem, len(r.HostSystems))
	for _, o := range r.HostSystems {
		objects[o.Reference()] = o
	}

	tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)

	for _, o := range r.objects {
		host := objects[o.Reference()]
		s := host.Summary
		h := s.Hardware
		z := s.QuickStats
		ncpu := int32(h.NumCpuPkgs * h.NumCpuCores)
		cpuUsage := 100 * float64(z.OverallCpuUsage) / float64(ncpu*h.CpuMhz)
		memUsage := 100 * float64(z.OverallMemoryUsage<<20) / float64(h.MemorySize)

		fmt.Fprintf(tw, "Name:\t%s\n", s.Config.Name)
		fmt.Fprintf(tw, "  Path:\t%s\n", o.InventoryPath)
		fmt.Fprintf(tw, "  Manufacturer:\t%s\n", h.Vendor)
		fmt.Fprintf(tw, "  Logical CPUs:\t%d CPUs @ %dMHz\n", ncpu, h.CpuMhz)
		fmt.Fprintf(tw, "  Processor type:\t%s\n", h.CpuModel)
		fmt.Fprintf(tw, "  CPU usage:\t%d MHz (%.1f%%)\n", z.OverallCpuUsage, cpuUsage)
		fmt.Fprintf(tw, "  Memory:\t%dMB\n", h.MemorySize/(1024*1024))
		fmt.Fprintf(tw, "  Memory usage:\t%d MB (%.1f%%)\n", z.OverallMemoryUsage, memUsage)
		fmt.Fprintf(tw, "  Boot time:\t%s\n", s.Runtime.BootTime)
	}

	return tw.Flush()
}
예제 #14
0
func runReleaseShow(args *docopt.Args, client *controller.Client) error {
	var release *ct.Release
	var err error
	if args.String["<id>"] != "" {
		release, err = client.GetRelease(args.String["<id>"])
	} else {
		release, err = client.GetAppRelease(mustApp())
	}
	if err != nil {
		return err
	}
	var artifactDesc string
	if release.ArtifactID != "" {
		artifact, err := client.GetArtifact(release.ArtifactID)
		if err != nil {
			return err
		}
		artifactDesc = fmt.Sprintf("%s+%s", artifact.Type, artifact.URI)
	}
	types := make([]string, 0, len(release.Processes))
	for typ := range release.Processes {
		types = append(types, typ)
	}
	w := tabwriter.NewWriter(os.Stdout, 1, 2, 2, ' ', 0)
	defer w.Flush()
	listRec(w, "ID:", release.ID)
	listRec(w, "Artifact:", artifactDesc)
	listRec(w, "Process Types:", strings.Join(types, ", "))
	listRec(w, "Created At:", release.CreatedAt)
	for k, v := range release.Env {
		listRec(w, fmt.Sprintf("ENV[%s]", k), v)
	}
	return nil
}
예제 #15
0
파일: flag.go 프로젝트: yckrasnodar/docker
// PrintDefaults prints, to standard error unless configured
// otherwise, the default values of all defined flags in the set.
func (f *FlagSet) PrintDefaults() {
	writer := tabwriter.NewWriter(f.Out(), 20, 1, 3, ' ', 0)
	home := homedir.Get()

	// Don't substitute when HOME is /
	if runtime.GOOS != "windows" && home == "/" {
		home = ""
	}
	f.VisitAll(func(flag *Flag) {
		format := "  -%s=%s"
		names := []string{}
		for _, name := range flag.Names {
			if name[0] != '#' {
				names = append(names, name)
			}
		}
		if len(names) > 0 {
			val := flag.DefValue

			if home != "" && strings.HasPrefix(val, home) {
				val = homedir.GetShortcutString() + val[len(home):]
			}

			fmt.Fprintf(writer, format, strings.Join(names, ", -"), val)
			for i, line := range strings.Split(flag.Usage, "\n") {
				if i != 0 {
					line = "  " + line
				}
				fmt.Fprintln(writer, "\t", line)
			}
		}
	})
	writer.Flush()
}
예제 #16
0
func (cli *DockerCli) CmdTop(args ...string) error {
	cmd := Subcmd("top", "CONTAINER", "Lookup the running processes of a container")
	if err := cmd.Parse(args); err != nil {
		return nil
	}
	if cmd.NArg() != 1 {
		cmd.Usage()
		return nil
	}
	body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top", nil)
	if err != nil {
		return err
	}
	var procs []APITop
	err = json.Unmarshal(body, &procs)
	if err != nil {
		return err
	}
	w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
	fmt.Fprintln(w, "PID\tTTY\tTIME\tCMD")
	for _, proc := range procs {
		fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", proc.PID, proc.Tty, proc.Time, proc.Cmd)
	}
	w.Flush()
	return nil
}
예제 #17
0
// FormatMachineTabular returns a tabular summary of machine
func FormatMachineTabular(value interface{}) ([]byte, error) {
	fs, valueConverted := value.(formattedMachineStatus)
	if !valueConverted {
		return nil, errors.Errorf("expected value of type %T, got %T", fs, value)
	}
	var out bytes.Buffer
	// To format things into columns.
	tw := tabwriter.NewWriter(&out, 0, 1, 1, ' ', 0)
	p := func(values ...interface{}) {
		for _, v := range values {
			fmt.Fprintf(tw, "%s\t", v)
		}
		fmt.Fprintln(tw)
	}

	p("\n[Machines]")
	p("ID\tSTATE\tDNS\tINS-ID\tSERIES\tAZ")
	for _, name := range common.SortStringsNaturally(stringKeysFromMap(fs.Machines)) {
		m := fs.Machines[name]
		// We want to display availability zone so extract from hardware info".
		hw, err := instance.ParseHardware(m.Hardware)
		if err != nil {
			logger.Warningf("invalid hardware info %s for machine %v", m.Hardware, m)
		}
		az := ""
		if hw.AvailabilityZone != nil {
			az = *hw.AvailabilityZone
		}
		p(m.Id, m.AgentState, m.DNSName, m.InstanceId, m.Series, az)
	}
	tw.Flush()

	return out.Bytes(), nil
}
예제 #18
0
파일: flag.go 프로젝트: Bludge0n/docker
// PrintDefaults prints, to standard error unless configured
// otherwise, the default values of all defined flags in the set.
func (f *FlagSet) PrintDefaults() {
	writer := tabwriter.NewWriter(f.out(), 20, 1, 3, ' ', 0)
	f.VisitAll(func(flag *Flag) {
		format := "  -%s=%s"
		if _, ok := flag.Value.(*stringValue); ok {
			// put quotes on the value
			format = "  -%s=%q"
		}
		names := []string{}
		for _, name := range flag.Names {
			if name[0] != '#' {
				names = append(names, name)
			}
		}
		if len(names) > 0 {
			fmt.Fprintf(writer, format, strings.Join(names, ", -"), flag.DefValue)
			for i, line := range strings.Split(flag.Usage, "\n") {
				if i != 0 {
					line = "  " + line
				}
				fmt.Fprintln(writer, "\t", line)
			}
			//			start := fmt.Sprintf(format, strings.Join(names, ", -"), flag.DefValue)
			//			fmt.Fprintln(f.out(), start, strings.Replace(flag.Usage, "\n", "\n"+strings.Repeat(" ", len(start)+1), -1))
		}
	})
	writer.Flush()
}
예제 #19
0
파일: ls.go 프로젝트: 40a/cbfs
func lsCommand(u string, args []string) {
	client, err := cbfsclient.New(u)
	cbfstool.MaybeFatal(err, "Error creating client: %v", err)

	result, err := client.List(lsFlags.Arg(0))
	cbfstool.MaybeFatal(err, "Error listing directory: %v", err)

	dirnames := sort.StringSlice{}
	filenames := sort.StringSlice{}
	for k := range result.Dirs {
		dirnames = append(dirnames, k)
	}
	for k := range result.Files {
		filenames = append(filenames, k)
	}
	dirnames.Sort()
	filenames.Sort()

	if *lsDashL {
		totalFiles := 0
		totalSize := uint64(0)
		tw := tabwriter.NewWriter(os.Stdout, 2, 4, 2, ' ', 0)
		for i := range dirnames {
			dn := dirnames[i]
			di := result.Dirs[dn]
			fmt.Fprintf(tw, "d %8s\t%s\t(%s descendants)\n",
				humanize.Bytes(uint64(di.Size)), dn,
				humanize.Comma(int64(di.Descendants)))
			totalSize += uint64(di.Size)
			totalFiles += di.Descendants
		}
		for i := range filenames {
			fn := filenames[i]
			fi := result.Files[fn]
			fmt.Fprintf(tw, "f %8s\t%s\t%s\n",
				humanize.Bytes(uint64(fi.Length)), fn,
				fi.Headers.Get("Content-Type"))

			totalSize += uint64(fi.Length)
			totalFiles++
		}
		fmt.Fprintf(tw, "----------------------------------------\n")
		fmt.Fprintf(tw, "Tot: %s\t\t%s files\n",
			humanize.Bytes(totalSize),
			humanize.Comma(int64(totalFiles)))
		tw.Flush()
	} else {
		allnames := sort.StringSlice{}
		for i := range dirnames {
			allnames = append(allnames, dirnames[i])
		}
		for i := range filenames {
			allnames = append(allnames, filenames[i])
		}
		allnames.Sort()
		for _, a := range allnames {
			fmt.Println(a)
		}
	}
}
예제 #20
0
파일: ls.go 프로젝트: fdawg4l/govmomi
func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
	c, err := cmd.Client()
	if err != nil {
		return err
	}

	var host *object.HostSystem

	if c.IsVC() {
		host, err = cmd.HostSystemIfSpecified()
		if err != nil {
			return err
		}
	}

	m := object.NewDiagnosticManager(c)

	desc, err := m.QueryDescriptions(ctx, host)
	if err != nil {
		return err
	}

	tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)

	for _, d := range desc {
		fmt.Fprintf(tw, "%s\t%s\n", d.Key, d.FileName)
	}

	return tw.Flush()
}
예제 #21
0
파일: commands.go 프로젝트: jweede/docker
func (cli *DockerCli) CmdSearch(args ...string) error {
	cmd := Subcmd("search", "NAME", "Search the docker index for images")
	if err := cmd.Parse(args); err != nil {
		return nil
	}
	if cmd.NArg() != 1 {
		cmd.Usage()
		return nil
	}

	v := url.Values{}
	v.Set("term", cmd.Arg(0))
	body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
	if err != nil {
		return err
	}

	outs := []ApiSearch{}
	err = json.Unmarshal(body, &outs)
	if err != nil {
		return err
	}
	fmt.Printf("Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
	w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
	fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
	for _, out := range outs {
		fmt.Fprintf(w, "%s\t%s\n", out.Name, out.Description)
	}
	w.Flush()
	return nil
}
예제 #22
0
파일: env-vars.go 프로젝트: sgtpepper43/cx
func runEnvVars(c *cli.Context) {
	w := tabwriter.NewWriter(os.Stdout, 1, 2, 2, ' ', 0)
	defer w.Flush()
	var envVars []cloud66.StackEnvVar
	var err error
	stack := mustStack(c)
	envVars, err = client.StackEnvVars(stack.Uid)
	must(err)

	envVarKeys := c.Args()
	flagShowHistory := c.Bool("history")

	sort.Strings(envVarKeys)
	if len(envVarKeys) == 0 {
		printEnvVarsList(w, envVars, flagShowHistory)
	} else {
		// filter out the unwanted env_vars
		var filteredEnvVars []cloud66.StackEnvVar
		for _, i := range envVars {
			sorted := sort.SearchStrings(envVarKeys, i.Key)
			if sorted < len(envVarKeys) && envVarKeys[sorted] == i.Key {
				filteredEnvVars = append(filteredEnvVars, i)
			}
		}
		printEnvVarsList(w, filteredEnvVars, flagShowHistory)
	}
}
예제 #23
0
// updateCountString describes the update counts that were recorded by
// storeEventReader.  The formatting is appropriate to paste into this test if
// as a new expected value.
func (ser *storeEventReader) updateCountString() string {
	var buffer bytes.Buffer
	w := tabwriter.NewWriter(&buffer, 2, 1, 2, ' ', 0)

	var storeIDs sort.IntSlice
	for storeID := range ser.perStoreUpdateCount {
		storeIDs = append(storeIDs, int(storeID))
	}
	sort.Sort(storeIDs)

	for _, storeID := range storeIDs {
		if countset, ok := ser.perStoreUpdateCount[proto.StoreID(storeID)]; ok {
			fmt.Fprintf(w, "proto.StoreID(%d): {\n", storeID)

			var methodIDs sort.IntSlice
			for methodID := range countset {
				methodIDs = append(methodIDs, int(methodID))
			}
			sort.Sort(methodIDs)

			for _, methodID := range methodIDs {
				method := proto.Method(methodID)
				if count, okCount := countset[method]; okCount {
					fmt.Fprintf(w, "\tproto.%s:\t%d,\n", method, count)
				} else {
					panic("unreachable!")
				}
			}
		} else {
			panic("unreachable!")
		}
		fmt.Fprintf(w, "},\n")
	}
	return buffer.String()
}
예제 #24
0
파일: ps.go 프로젝트: snormore/flynn
func runPs(args *docopt.Args, client cluster.Host) error {
	all, err := client.ListJobs()
	if err != nil {
		return fmt.Errorf("could not get local jobs: %s", err)
	}

	jobs := make(sortJobs, 0, len(all))
	for _, job := range all {
		if !args.Bool["-a"] && !args.Bool["--all"] && job.Status != host.StatusStarting && job.Status != host.StatusRunning {
			continue
		}
		jobs = append(jobs, job)
	}
	sort.Sort(sort.Reverse(jobs))

	if args.Bool["-q"] || args.Bool["--quiet"] {
		for _, job := range jobs {
			fmt.Println(job.Job.ID)
		}
		return nil
	}
	w := tabwriter.NewWriter(os.Stdout, 1, 2, 2, ' ', 0)
	defer w.Flush()
	fmt.Fprintln(w, "JOB ID\tSTATE\tSTARTED\tCONTROLLER APP\tCONTROLLER TYPE")
	for _, job := range jobs {
		fmt.Fprintf(w, "%s\t%s\t%s ago\t%s\t%s\n", job.Job.ID, job.Status, units.HumanDuration(time.Now().UTC().Sub(job.StartedAt)), job.Job.Metadata["flynn-controller.app_name"], job.Job.Metadata["flynn-controller.type"])
	}
	return nil
}
예제 #25
0
func (s *CustomColumnsPrinter) PrintObj(obj runtime.Object, out io.Writer) error {
	w := tabwriter.NewWriter(out, columnwidth, tabwidth, padding, padding_character, flags)
	headers := make([]string, len(s.Columns))
	for ix := range s.Columns {
		headers[ix] = s.Columns[ix].Header
	}
	fmt.Fprintln(w, strings.Join(headers, "\t"))
	parsers := make([]*jsonpath.JSONPath, len(s.Columns))
	for ix := range s.Columns {
		parsers[ix] = jsonpath.New(fmt.Sprintf("column%d", ix))
		if err := parsers[ix].Parse(s.Columns[ix].FieldSpec); err != nil {
			return err
		}
	}

	if runtime.IsListType(obj) {
		objs, err := runtime.ExtractList(obj)
		if err != nil {
			return err
		}
		for ix := range objs {
			if err := s.printOneObject(objs[ix], parsers, w); err != nil {
				return err
			}
		}
	} else {
		if err := s.printOneObject(obj, parsers, w); err != nil {
			return err
		}
	}
	return w.Flush()
}
예제 #26
0
파일: rss.go 프로젝트: raphting/rss
func (i *Item) Format(indent int) string {
	buf := new(bytes.Buffer)
	single := strings.Repeat("\t", indent)
	double := single + "\t"
	if debug {
		w := tabwriter.NewWriter(buf, 0, 8, 0, '\t', tabwriter.StripEscape)
		fmt.Fprintf(w, "\xff%s\xffItem {\n", single)
		fmt.Fprintf(w, "\xff%s\xffTitle:\t%q\n", double, i.Title)
		fmt.Fprintf(w, "\xff%s\xffSummary:\t%q\n", double, i.Summary)
		fmt.Fprintf(w, "\xff%s\xffLink:\t%s\n", double, i.Link)
		fmt.Fprintf(w, "\xff%s\xffDate:\t%s\n", double, i.Date.Format(DATE))
		fmt.Fprintf(w, "\xff%s\xffID:\t%s\n", double, i.ID)
		fmt.Fprintf(w, "\xff%s\xffRead:\t%v\n", double, i.Read)
		fmt.Fprintf(w, "\xff%s\xffContent:\t%q\n", double, i.Content)
		fmt.Fprintf(w, "\xff%s\xff}\n", single)
		w.Flush()
	} else {
		w := buf
		fmt.Fprintf(w, "%sItem %q\n", single, i.Title)
		fmt.Fprintf(w, "%s%q\n", double, i.Link)
		fmt.Fprintf(w, "%s%s\n", double, i.Date.Format(DATE))
		fmt.Fprintf(w, "%s%q\n", double, i.ID)
		fmt.Fprintf(w, "%sRead: %v\n", double, i.Read)
		fmt.Fprintf(w, "%s%q\n", double, i.Content)
	}
	return buf.String()
}
예제 #27
0
func commandHelp(name string, cmd Command, f *flag.FlagSet) {
	type HasUsage interface {
		Usage() string
	}

	fmt.Fprintf(os.Stderr, "Usage: %s %s [OPTIONS]", os.Args[0], name)
	if u, ok := cmd.(HasUsage); ok {
		fmt.Fprintf(os.Stderr, " %s", u.Usage())
	}
	fmt.Fprintf(os.Stderr, "\n")

	type HasDescription interface {
		Description() string
	}

	if u, ok := cmd.(HasDescription); ok {
		fmt.Fprintf(os.Stderr, "%s\n", u.Description())
	}

	n := 0
	f.VisitAll(func(_ *flag.Flag) {
		n += 1
	})

	if n > 0 {
		fmt.Fprintf(os.Stderr, "\nOptions:\n")
		tw := tabwriter.NewWriter(os.Stderr, 2, 0, 2, ' ', 0)
		f.VisitAll(func(f *flag.Flag) {
			fmt.Fprintf(tw, "\t-%s=%s\t%s\n", f.Name, f.DefValue, f.Usage)
		})
		tw.Flush()
	}
}
예제 #28
0
파일: nsenter.go 프로젝트: beginnor/docker
// nsenterIp displays the network interfaces inside a container's net namespace
func nsenterIp(config *libcontainer.Config, args []string) {
	interfaces, err := net.Interfaces()
	if err != nil {
		log.Fatal(err)
	}

	w := tabwriter.NewWriter(os.Stdout, 10, 1, 3, ' ', 0)
	fmt.Fprint(w, "NAME\tMTU\tMAC\tFLAG\tADDRS\n")

	for _, iface := range interfaces {
		addrs, err := iface.Addrs()
		if err != nil {
			log.Fatal(err)
		}

		o := []string{}

		for _, a := range addrs {
			o = append(o, a.String())
		}

		fmt.Fprintf(w, "%s\t%d\t%s\t%s\t%s\n", iface.Name, iface.MTU, iface.HardwareAddr, iface.Flags, strings.Join(o, ","))
	}

	w.Flush()
}
예제 #29
0
// This example displays the results of Dec.Round with each of the Rounders.
//
func ExampleRounder() {
	var vals = []struct {
		x string
		s inf.Scale
	}{
		{"-0.18", 1}, {"-0.15", 1}, {"-0.12", 1}, {"-0.10", 1},
		{"-0.08", 1}, {"-0.05", 1}, {"-0.02", 1}, {"0.00", 1},
		{"0.02", 1}, {"0.05", 1}, {"0.08", 1}, {"0.10", 1},
		{"0.12", 1}, {"0.15", 1}, {"0.18", 1},
	}

	var rounders = []struct {
		name    string
		rounder inf.Rounder
	}{
		{"RoundDown", inf.RoundDown}, {"RoundUp", inf.RoundUp},
		{"RoundCeil", inf.RoundCeil}, {"RoundFloor", inf.RoundFloor},
		{"RoundHalfDown", inf.RoundHalfDown}, {"RoundHalfUp", inf.RoundHalfUp},
		{"RoundHalfEven", inf.RoundHalfEven}, {"RoundExact", inf.RoundExact},
	}

	fmt.Println("The results of new(inf.Dec).Round(x, s, inf.RoundXXX):\n")
	w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
	fmt.Fprint(w, "x\ts\t|\t")
	for _, r := range rounders {
		fmt.Fprintf(w, "%s\t", r.name[5:])
	}
	fmt.Fprintln(w)
	for _, v := range vals {
		fmt.Fprintf(w, "%s\t%d\t|\t", v.x, v.s)
		for _, r := range rounders {
			x, _ := new(inf.Dec).SetString(v.x)
			z := new(inf.Dec).Round(x, v.s, r.rounder)
			fmt.Fprintf(w, "%d\t", z)
		}
		fmt.Fprintln(w)
	}
	w.Flush()

	// Output:
	// The results of new(inf.Dec).Round(x, s, inf.RoundXXX):
	//
	//      x s | Down   Up Ceil Floor HalfDown HalfUp HalfEven Exact
	//  -0.18 1 | -0.1 -0.2 -0.1  -0.2     -0.2   -0.2     -0.2 <nil>
	//  -0.15 1 | -0.1 -0.2 -0.1  -0.2     -0.1   -0.2     -0.2 <nil>
	//  -0.12 1 | -0.1 -0.2 -0.1  -0.2     -0.1   -0.1     -0.1 <nil>
	//  -0.10 1 | -0.1 -0.1 -0.1  -0.1     -0.1   -0.1     -0.1  -0.1
	//  -0.08 1 |  0.0 -0.1  0.0  -0.1     -0.1   -0.1     -0.1 <nil>
	//  -0.05 1 |  0.0 -0.1  0.0  -0.1      0.0   -0.1      0.0 <nil>
	//  -0.02 1 |  0.0 -0.1  0.0  -0.1      0.0    0.0      0.0 <nil>
	//   0.00 1 |  0.0  0.0  0.0   0.0      0.0    0.0      0.0   0.0
	//   0.02 1 |  0.0  0.1  0.1   0.0      0.0    0.0      0.0 <nil>
	//   0.05 1 |  0.0  0.1  0.1   0.0      0.0    0.1      0.0 <nil>
	//   0.08 1 |  0.0  0.1  0.1   0.0      0.1    0.1      0.1 <nil>
	//   0.10 1 |  0.1  0.1  0.1   0.1      0.1    0.1      0.1   0.1
	//   0.12 1 |  0.1  0.2  0.2   0.1      0.1    0.1      0.1 <nil>
	//   0.15 1 |  0.1  0.2  0.2   0.1      0.1    0.2      0.2 <nil>
	//   0.18 1 |  0.1  0.2  0.2   0.1      0.2    0.2      0.2 <nil>

}
예제 #30
0
func (el *eventLog) Stack() string {
	buf := new(bytes.Buffer)
	tw := tabwriter.NewWriter(buf, 1, 8, 1, '\t', 0)
	printStackRecord(tw, el.stack)
	tw.Flush()
	return buf.String()
}