Beispiel #1
2
func csv2String() string {
	buf := new(bytes.Buffer)
	for _, pub := range csv2.pubkeys {
		buf.WriteString(fmt.Sprintf("%s,\n", pub))
	}
	return string(buf.Bytes())
}
Beispiel #2
1
// Format implements the NodeFormatter interface.
func (node IndexElem) Format(buf *bytes.Buffer, f FmtFlags) {
	FormatNode(buf, f, node.Column)
	if node.Direction != DefaultDirection {
		buf.WriteByte(' ')
		buf.WriteString(node.Direction.String())
	}
}
Beispiel #3
0
func jsonToShort(images *[]Image) string {
	var buffer bytes.Buffer

	var byRepo = make(map[string][]string)

	for _, image := range *images {
		for _, repotag := range image.RepoTags {
			if repotag != "<none>:<none>" {

				// parse the repo name and tag name out
				// tag is after the last colon
				lastColonIndex := strings.LastIndex(repotag, ":")
				tagname := repotag[lastColonIndex+1:]
				reponame := repotag[0:lastColonIndex]

				if tags, exists := byRepo[reponame]; exists {
					byRepo[reponame] = append(tags, tagname)
				} else {
					byRepo[reponame] = []string{tagname}
				}
			}
		}
	}

	for repo, tags := range byRepo {
		buffer.WriteString(fmt.Sprintf("%s: %s\n", repo, strings.Join(tags, ", ")))
	}

	return buffer.String()
}
Beispiel #4
0
func (options *Html) TitleBlock(out *bytes.Buffer, text []byte) {
	text = bytes.TrimPrefix(text, []byte("% "))
	text = bytes.Replace(text, []byte("\n% "), []byte("\n"), -1)
	out.WriteString("<h1 class=\"title\">")
	out.Write(text)
	out.WriteString("\n</h1>")
}
Beispiel #5
0
// Format implements the NodeFormatter interface.
func (node *CreateDatabase) Format(buf *bytes.Buffer, f FmtFlags) {
	buf.WriteString("CREATE DATABASE ")
	if node.IfNotExists {
		buf.WriteString("IF NOT EXISTS ")
	}
	FormatNode(buf, f, node.Name)
}
Beispiel #6
0
Datei: load.go Projekt: Dreae/pwm
func saveDraw(w *draw.Window, statusCh chan string) {
	var buffer bytes.Buffer
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		panic(err)
	}
	buffer.WriteString(dir)

	statusCh <- fmt.Sprintf("Choose a Filename: %s", buffer.String())
	for {
		ev := termbox.PollEvent()
		switch ev.Key {
		case termbox.KeyEnter:
			statusCh <- "Saved"
			return
		case termbox.KeyBackspace:
			if buffer.Len() > 0 {
				buffer.Truncate(buffer.Len() - 1)
			}
		default:
			buffer.WriteRune(ev.Ch)
		}
		statusCh <- fmt.Sprintf("Choose a Filename: %s", buffer.String())
	}
}
Beispiel #7
0
// writeCloseScope writes a closing bracket to w.
func (enc *Encoder) writeCloseScopeStruct(structName string, level int) {
	closeScopeStructBuffer := bytes.Buffer{}
	closeScopeStructBuffer.WriteString("}")
	enc.writeTagsToByteBuffer(&closeScopeStructBuffer, structName)
	closeScopeStructBuffer.WriteString("\n")
	enc.writeString(closeScopeStructBuffer.String(), level)
}
Beispiel #8
0
func (pipeline *Pipeline) JSONFeed(since, limit int) ([]byte, error) {
	pipeline.mutex.RLock()
	var lineRaw []byte
	var line *PipelineFeedLine
	var buffer bytes.Buffer
	var err error
	data := pipeline.data[since:]
	count := 0
	for seq, msg := range data {
		line = &PipelineFeedLine{
			Seq: seq + since,
			Msg: msg.Outgoing,
		}
		lineRaw, err = json.Marshal(line)
		if err != nil {
			return nil, err
		}
		buffer.Write(lineRaw)
		buffer.WriteString("\n")

		count++
		if limit > 0 && count >= limit {
			break
		}
	}
	pipeline.mutex.RUnlock()

	return buffer.Bytes(), nil
}
Beispiel #9
0
// String gives a nice output to describe the tree.
func (t *Tree) String() string {
	var result bytes.Buffer
	path := strings.Join(t.path, ", ")
	if path != "" {
		path = fmt.Sprintf(" (path: %s)", path)
	}
	result.WriteString(t.Name() + path + "\n")

	cs := t.Children()
	if cs == nil {
		result.WriteString("  not loaded")
	} else {
		// Go through each child and get its string value, then indent it
		// by two.
		for _, c := range cs {
			r := strings.NewReader(c.String())
			scanner := bufio.NewScanner(r)
			for scanner.Scan() {
				result.WriteString("  ")
				result.WriteString(scanner.Text())
				result.WriteString("\n")
			}
		}
	}

	return result.String()
}
Beispiel #10
0
func (self *LogisticsService) GetHelpMessage() string {
	var buffer bytes.Buffer
	for command, helpMsg := range commandHelp {
		buffer.WriteString(fmt.Sprintf("[%s]: %s\n", command, helpMsg))
	}
	return buffer.String()
}
Beispiel #11
0
func newline(dst *bytes.Buffer, prefix, indent string, depth int) {
	dst.WriteByte('\n')
	dst.WriteString(prefix)
	for i := 0; i < depth; i++ {
		dst.WriteString(indent)
	}
}
Beispiel #12
0
// Fmt '%H': NodeList.
// Flags: all those of %N plus ',': separate with comma's instead of semicolons.
func Hconv(l *NodeList, flag int) string {
	if l == nil && fmtmode == FDbg {
		return "<nil>"
	}

	sf := flag
	sm, sb := setfmode(&flag)
	sep := "; "
	if fmtmode == FDbg {
		sep = "\n"
	} else if flag&obj.FmtComma != 0 {
		sep = ", "
	}

	var buf bytes.Buffer
	for ; l != nil; l = l.Next {
		buf.WriteString(Nconv(l.N, 0))
		if l.Next != nil {
			buf.WriteString(sep)
		}
	}

	flag = sf
	fmtbody = sb
	fmtmode = sm
	return buf.String()
}
func resourceComputeInstancePersonalityHash(v interface{}) int {
	var buf bytes.Buffer
	m := v.(map[string]interface{})
	buf.WriteString(fmt.Sprintf("%s-", m["file"].(string)))

	return hashcode.String(buf.String())
}
func resourceComputeVolumeAttachmentHash(v interface{}) int {
	var buf bytes.Buffer
	m := v.(map[string]interface{})
	buf.WriteString(fmt.Sprintf("%s-", m["volume_id"].(string)))

	return hashcode.String(buf.String())
}
func usageFor(fs *flag.FlagSet, usage string, extra string) func() {
	return func() {
		var b bytes.Buffer
		b.WriteString("Usage:\n  " + usage + "\n")

		var options [][]string
		fs.VisitAll(func(f *flag.Flag) {
			var opt = "  -" + f.Name

			if f.DefValue == "[]" {
				f.DefValue = ""
			}
			if f.DefValue != "false" {
				opt += "=" + fmt.Sprintf(`"%s"`, f.DefValue)
			}
			options = append(options, []string{opt, f.Usage})
		})

		if len(options) > 0 {
			b.WriteString("\nOptions:\n")
			optionTable(&b, options)
		}

		fmt.Println(b.String())

		if len(extra) > 0 {
			fmt.Println(extra)
		}
	}
}
Beispiel #16
0
func formatKeys(keys []engine.Key) string {
	var buf bytes.Buffer
	for i, key := range keys {
		buf.WriteString(fmt.Sprintf("%d: %s\n", i, key))
	}
	return buf.String()
}
Beispiel #17
0
// joinChart reads chart files and joins them with YAML delimiters
func joinChart(chartDir string, files []string) (bytes.Buffer, error) {

	var output bytes.Buffer

	for _, f := range files {
		contents, err := ioutil.ReadFile(f)
		if err != nil {
			return output, err
		}

		rf, err := filepath.Rel(chartDir, f)
		if err != nil {
			log.Warn("Could not find relative path: %s", err)
			return output, err
		}

		delimiter := fmt.Sprintf("--- # %s\n", rf)

		output.WriteString(delimiter)
		output.Write(contents)
		output.WriteString("--- # end\n")

	}

	return output, nil
}
Beispiel #18
0
//generateDartFunc returns a function that outputs text string for all the dart code
//in the system.
func generateDartFunc(desc []*ResourceDescription) func(http.ResponseWriter, *http.Request) {

	var text bytes.Buffer
	resourceStructs := []*FieldDescription{}
	supportStructs := []*FieldDescription{}

	//generate code for known resources
	for _, d := range desc {
		text.WriteString(generateDartForResource(d))
		resourceStructs = append(resourceStructs, d.Field)
	}
	//collect up supporting structs
	for _, d := range desc {
		candidates := collectStructs(d.Field)
		for _, s := range candidates {
			if !containsType(resourceStructs, s) && !containsType(supportStructs, s) {
				supportStructs = append(supportStructs, s)
			}
		}
	}
	for _, i := range supportStructs {
		text.WriteString(generateDartForSupportStruct(i))
	}
	return func(writer http.ResponseWriter, req *http.Request) {
		_, err := writer.Write(dartPrettyPrint(text.String()))
		if err != nil {
			fmt.Printf("error writing generated code: %s\n", err)
		}
	}
}
Beispiel #19
0
Datei: path.go Projekt: ssrl/go
// EvalSymlinks returns the path name after the evaluation of any symbolic
// links.
// If path is relative it will be evaluated relative to the current directory.
func EvalSymlinks(path string) (string, os.Error) {
	if runtime.GOOS == "windows" {
		// Symlinks are not supported under windows.
		_, err := os.Lstat(path)
		if err != nil {
			return "", err
		}
		return Clean(path), nil
	}
	const maxIter = 255
	originalPath := path
	// consume path by taking each frontmost path element,
	// expanding it if it's a symlink, and appending it to b
	var b bytes.Buffer
	for n := 0; path != ""; n++ {
		if n > maxIter {
			return "", os.NewError("EvalSymlinks: too many links in " + originalPath)
		}

		// find next path component, p
		i := strings.IndexRune(path, Separator)
		var p string
		if i == -1 {
			p, path = path, ""
		} else {
			p, path = path[:i], path[i+1:]
		}

		if p == "" {
			if b.Len() == 0 {
				// must be absolute path
				b.WriteRune(Separator)
			}
			continue
		}

		fi, err := os.Lstat(b.String() + p)
		if err != nil {
			return "", err
		}
		if !fi.IsSymlink() {
			b.WriteString(p)
			if path != "" {
				b.WriteRune(Separator)
			}
			continue
		}

		// it's a symlink, put it at the front of path
		dest, err := os.Readlink(b.String() + p)
		if err != nil {
			return "", err
		}
		if IsAbs(dest) {
			b.Reset()
		}
		path = dest + string(Separator) + path
	}
	return Clean(b.String()), nil
}
Beispiel #20
0
// TODO: This might now work
func (r *roffRenderer) Table(out *bytes.Buffer, header []byte, body []byte, columnData []int) {
	out.WriteString(".TS\nallbox;\n")

	out.Write(header)
	out.Write(body)
	out.WriteString("\n.TE\n")
}
Beispiel #21
0
// wrapDescription wraps the text in a cliflags.FlagInfo.Description.
func wrapDescription(s string) string {
	var result bytes.Buffer

	// split returns the parts of the string before and after the first occurrence
	// of the tag.
	split := func(str, tag string) (before, after string) {
		pieces := strings.SplitN(str, tag, 2)
		switch len(pieces) {
		case 0:
			return "", ""
		case 1:
			return pieces[0], ""
		default:
			return pieces[0], pieces[1]
		}
	}

	for len(s) > 0 {
		var toWrap, dontWrap string
		// Wrap everything up to the next stop wrap tag.
		toWrap, s = split(s, "<PRE>")
		result.WriteString(text.Wrap(toWrap, wrapWidth))
		// Copy everything up to the next start wrap tag.
		dontWrap, s = split(s, "</PRE>")
		result.WriteString(dontWrap)
	}
	return result.String()
}
Beispiel #22
0
func (r *roffRenderer) TableRow(out *bytes.Buffer, text []byte) {
	if out.Len() > 0 {
		out.WriteString("\n")
	}
	out.Write(text)
	out.WriteString("\n")
}
Beispiel #23
0
Datei: load.go Projekt: Dreae/pwm
func loadDraw(w *draw.Window, statusCh chan string) {
	var buffer bytes.Buffer
	buffer.WriteString("~/.pwm/database")

	statusCh <- fmt.Sprintf("Choose a Filename: %s", buffer.String())
	cb := make(chan string)
	go func() {
		for {
			buf, ok := <-cb
			if !ok {
				break
			}
			statusCh <- fmt.Sprintf("Choose a Filename: %s", buf)
		}
	}()
	draw.GetString(&buffer, cb)

	defer func() {
		if r := recover(); r != nil {
			switch r.(type) {
			case *os.PathError:
				statusCh <- fmt.Sprintf("No such file: %s", buffer.String())
			default:
				statusCh <- fmt.Sprintf("Could not load database: %s", buffer.String())
			}
		}
	}()
	root := LoadFile(buffer.String())
	ScreenList["Database"] = Database(w, root, statusCh)
}
Beispiel #24
0
// TODO: This is probably broken
func (r *roffRenderer) TableCell(out *bytes.Buffer, text []byte, align int) {
	if out.Len() > 0 {
		out.WriteString("\t")
	}
	out.Write(text)
	out.WriteString("\t")
}
Beispiel #25
0
func write(buf *bytes.Buffer, e Expr) {
	switch e := e.(type) {
	case literal:
		fmt.Fprintf(buf, "%g", e)

	case Var:
		fmt.Fprintf(buf, "%s", e)

	case unary:
		fmt.Fprintf(buf, "(%c", e.op)
		write(buf, e.x)
		buf.WriteByte(')')

	case binary:
		buf.WriteByte('(')
		write(buf, e.x)
		fmt.Fprintf(buf, " %c ", e.op)
		write(buf, e.y)
		buf.WriteByte(')')

	case call:
		fmt.Fprintf(buf, "%s(", e.fn)
		for i, arg := range e.args {
			if i > 0 {
				buf.WriteString(", ")
			}
			write(buf, arg)
		}
		buf.WriteByte(')')

	default:
		panic(fmt.Sprintf("unknown Expr: %T", e))
	}
}
Beispiel #26
0
func runCmdAddNote(cmd *cobra.Command, args []string) error {
	project, timestamp, value, err := helper.ArgsToEntryValues(args, flagAddTimeStamp, flagAddTimeStampRaw)
	if err != nil {
		return errgo.Notef(err, "can not convert args to entry usable values")
	}

	buffer := new(bytes.Buffer)

	if value != "-" {
		buffer.WriteString(value)
	}

	// If there is something piped in over stdin append it to the already set
	// value

	stat, _ := os.Stdin.Stat()
	if (stat.Mode() & os.ModeCharDevice) == 0 {
		io.Copy(buffer, os.Stdin)
	}

	note := data.Note{
		Value:     buffer.String(),
		TimeStamp: timestamp,
	}

	err = helper.RecordEntry(flagDataDir, project, note, flagAddAutoCommit)
	if err != nil {
		errgo.Notef(err, "can not record note to store")
	}

	return nil
}
Beispiel #27
0
func csv1String() string {
	buf := new(bytes.Buffer)
	for i, pub := range csv1.pubkeys {
		buf.WriteString(fmt.Sprintf("%s,%d,%s,%d,%d\n", pub, csv1.amts[i], csv1.names[i], csv1.perms[i], csv1.setbits[i]))
	}
	return string(buf.Bytes())
}
Beispiel #28
0
// decorate prefixes the string with the file and line of the call site
// and inserts the final newline if needed and indentation tabs for formatting.
func decorate(s string) string {
	_, file, line, ok := runtime.Caller(3) // decorate + log + public function.
	if ok {
		// Truncate file name at last file name separator.
		if index := strings.LastIndex(file, "/"); index >= 0 {
			file = file[index+1:]
		} else if index = strings.LastIndex(file, "\\"); index >= 0 {
			file = file[index+1:]
		}
	} else {
		file = "???"
		line = 1
	}
	buf := new(bytes.Buffer)
	// Every line is indented at least one tab.
	buf.WriteByte('\t')
	fmt.Fprintf(buf, "%s:%d: ", file, line)
	lines := strings.Split(s, "\n")
	if l := len(lines); l > 1 && lines[l-1] == "" {
		lines = lines[:l-1]
	}
	for i, line := range lines {
		if i > 0 {
			// Second and subsequent lines are indented an extra tab.
			buf.WriteString("\n\t\t")
		}
		buf.WriteString(line)
	}
	buf.WriteByte('\n')
	return buf.String()
}
func (slvgs *softLayer_Virtual_Guest_Service) SetTags(instanceId int, tags []string) (bool, error) {
	var tagStringBuffer bytes.Buffer
	for i, tag := range tags {
		tagStringBuffer.WriteString(tag)
		if i != len(tags)-1 {
			tagStringBuffer.WriteString(", ")
		}
	}

	setTagsParameters := datatypes.SoftLayer_Virtual_Guest_SetTags_Parameters{
		Parameters: []string{tagStringBuffer.String()},
	}

	requestBody, err := json.Marshal(setTagsParameters)
	if err != nil {
		return false, err
	}

	response, err := slvgs.client.DoRawHttpRequest(fmt.Sprintf("%s/%d/setTags.json", slvgs.GetName(), instanceId), "POST", bytes.NewBuffer(requestBody))
	if err != nil {
		return false, err
	}

	if res := string(response[:]); res != "true" {
		return false, errors.New(fmt.Sprintf("Failed to setTags for instance with id '%d', got '%s' as response from the API.", instanceId, res))
	}

	return true, nil
}
Beispiel #30
0
// TODO(c4milo): Legacy function, this is to be removed once we migrate
// the dependant code
func writeVmx(path string, vmx map[string]string) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}

	defer f.Close()

	keys := make([]string, len(vmx))
	i := 0
	for k := range vmx {
		keys[i] = k
		i++
	}

	sort.Strings(keys)

	var buf bytes.Buffer
	for _, key := range keys {
		buf.WriteString(key + " = " + `"` + vmx[key] + `"`)
		buf.WriteString("\n")
	}

	if _, err = io.Copy(f, &buf); err != nil {
		return err
	}

	return nil
}