Пример #1
1
func TestMd5sum(t *testing.T) {
	r := NewRun(t)
	defer r.Finalise()
	file1 := r.WriteBoth("potato2", "------------------------------------------------------------", t1)
	file2 := r.WriteBoth("empty space", "", t2)

	fstest.CheckItems(t, r.fremote, file1, file2)

	var buf bytes.Buffer
	err := fs.Md5sum(r.fremote, &buf)
	if err != nil {
		t.Fatalf("List failed: %v", err)
	}
	res := buf.String()
	if !strings.Contains(res, "d41d8cd98f00b204e9800998ecf8427e  empty space\n") &&
		!strings.Contains(res, "                     UNSUPPORTED  empty space\n") &&
		!strings.Contains(res, "                                  empty space\n") {
		t.Errorf("empty space missing: %q", res)
	}
	if !strings.Contains(res, "6548b156ea68a4e003e786df99eee76  potato2\n") &&
		!strings.Contains(res, "                     UNSUPPORTED  potato2\n") &&
		!strings.Contains(res, "                                  potato2\n") {
		t.Errorf("potato2 missing: %q", res)
	}
}
Пример #2
1
Файл: etcd.go Проект: leobcn/gru
// Processes new tasks
func (m *etcdMinion) processTask(t *task.Task) error {
	var buf bytes.Buffer

	// Update state of task to indicate that we are now processing it
	t.State = task.TaskStateProcessing
	m.SaveTaskResult(t)

	cmd := exec.Command(t.Command, t.Args...)
	cmd.Stdout = &buf
	cmd.Stderr = &buf

	log.Printf("Processing task %s\n", t.TaskID)

	cmdError := cmd.Run()
	t.TimeProcessed = time.Now().Unix()
	t.Result = buf.String()

	if cmdError != nil {
		log.Printf("Failed to process task %s\n", t.TaskID)
		t.Error = cmdError.Error()
		t.State = task.TaskStateFailed
	} else {
		log.Printf("Finished processing task %s\n", t.TaskID)
		t.State = task.TaskStateSuccess
	}

	m.SaveTaskResult(t)

	return cmdError
}
Пример #3
1
Файл: task.go Проект: psev/atom
func (self *Task) Render() {
	for _, config := range self.Config.Templates {
		log.Printf("Render: %s", config.Dst)
		f, err := ioutil.ReadFile(self.Controller.Atom.Config.TmplDir + "/" + config.Src)
		if err != nil {
			log.Printf("Error:: Read - %s", err)
			continue
		}
		var output *bytes.Buffer
		if self.Controller.Atom.Config.Verbose {
			output = bytes.NewBuffer(nil)
		}
		src := bytes.NewBuffer(f)
		tmpl, err := template.New("").Funcs(self.Config.Store.FuncMap).Parse(src.String())
		if err != nil {
			log.Printf("Error:: Render - %s", err)
			continue
		}
		vars := map[string]interface{}{"cli": self.Controller.Atom.CLI}
		if self.Controller.Atom.Config.Verbose {
			if err := tmpl.Execute(output, vars); err != nil {
				log.Printf("Error:: Write - %s", err)
			}
			fmt.Print(output.String())
		}
		dst, err := os.Create(config.Dst)
		if err != nil {
			log.Printf("Error:: Open - %s", err)
			continue
		}
		if err := tmpl.Execute(dst, vars); err != nil {
			log.Printf("Error:: Write - %s", err)
		}
	}
}
Пример #4
0
// Helper function to test that a value is marshalled to JSON as expected.
func testJSONMarshal(t *testing.T, v interface{}, want string) {
	j, err := json.Marshal(v)
	if err != nil {
		t.Errorf("Unable to marshal JSON for %v", v)
	}

	w := new(bytes.Buffer)
	err = json.Compact(w, []byte(want))
	if err != nil {
		t.Errorf("String is not valid json: %s", want)
	}

	if w.String() != string(j) {
		t.Errorf("json.Marshal(%q) returned %s, want %s", v, j, w)
	}

	// now go the other direction and make sure things unmarshal as expected
	u := reflect.ValueOf(v).Interface()
	if err := json.Unmarshal([]byte(want), u); err != nil {
		t.Errorf("Unable to unmarshal JSON for %v", want)
	}

	if !reflect.DeepEqual(v, u) {
		t.Errorf("json.Unmarshal(%q) returned %s, want %s", want, u, v)
	}
}
Пример #5
0
Файл: load.go Проект: 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())
	}
}
Пример #6
0
// Ins composes, prepares and executes a sql INSERT statement returning a
// possible error.
//
// Ins offers convenience when specifying a long list of sql columns.
//
// Ins expects at least two column name-value pairs where the last pair will be
// a part of a sql RETURNING clause. The last column name is expected to be an
// identity column returning an Oracle-generated value. The last value specified
// to the variadic parameter 'columnPairs' is expected to be a pointer capable
// of receiving the identity value.
func (ses *Ses) Ins(tbl string, columnPairs ...interface{}) (err error) {
	ses.log(_drv.cfg.Log.Ses.Ins)
	err = ses.checkClosed()
	if err != nil {
		return errE(err)
	}
	if tbl == "" {
		return errF("tbl is empty.")
	}
	if len(columnPairs) < 2 {
		return errF("Parameter 'columnPairs' expects at least 2 column name-value pairs.")
	}
	if len(columnPairs)%2 != 0 {
		return errF("Variadic parameter 'columnPairs' received an odd number of elements. Parameter 'columnPairs' expects an even number of elements.")
	}
	// build INSERT statement, params slice
	params := make([]interface{}, len(columnPairs)/2)
	buf := new(bytes.Buffer)
	buf.WriteString("INSERT INTO ")
	buf.WriteString(tbl)
	buf.WriteString(" (")
	lastColName := ""
	for p := 0; p < len(params); p++ {
		n := p * 2
		columnName, ok := columnPairs[n].(string)
		if !ok {
			return errF("Variadic parameter 'columnPairs' expected an element at index %v to be of type string", n)
		}
		if p == len(params)-1 {
			lastColName = columnName
		} else {
			buf.WriteString(columnName)
			if p < len(params)-2 {
				buf.WriteString(", ")
			}
		}
		params[p] = columnPairs[n+1]
	}
	buf.WriteString(") VALUES (")
	for n := 1; n < len(params); n++ {
		buf.WriteString(fmt.Sprintf(":%v", n))
		if n < len(params)-1 {
			buf.WriteString(", ")
		}
	}
	buf.WriteString(")")
	buf.WriteString(" RETURNING ")
	buf.WriteString(lastColName)
	buf.WriteString(" INTO :RET_VAL")
	stmt, err := ses.Prep(buf.String()) // prep
	defer stmt.Close()
	if err != nil {
		return errE(err)
	}
	_, err = stmt.Exe(params...) // exe
	if err != nil {
		return errE(err)
	}
	return nil
}
Пример #7
0
func (location *GoogleLocationStruct) getGoogleLocation(requestURL string) {
	var buffer bytes.Buffer
	buffer.WriteString(googleURLPrefix)
	buffer.WriteString(requestURL)
	buffer.WriteString(googleURLPostfix)

	url := buffer.String()
	fmt.Println("Url is ", url)

	res, _ := http.Get(url)
	/*if err != nil {

		w.Write([]byte(`{    "error": "Unable to parse data from Google. Error at res, err := http.Get(url) -- line 75"}`))
		panic(err.Error())
	}*/

	body, _ := ioutil.ReadAll(res.Body)
	/*if err != nil {

		w.Write([]byte(`{    "error": "Unable to parse data from Google. body, err := ioutil.ReadAll(res.Body) -- line 84"}`))
		panic(err.Error())
	}*/

	_ = json.Unmarshal(body, &location)
	/*if err != nil {

		w.Write([]byte(`{    "error": "Unable to unmarshal Google data. body, 	err = json.Unmarshal(body, &googleLocation) -- line 94"}`))
		panic(err.Error())
	}*/
}
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
}
Пример #9
0
Файл: testing.go Проект: gmwu/go
// 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()
}
Пример #10
0
func Autobuild() {
	defer func() {
		if err := recover(); err != nil {
			str := ""
			for i := 1; ; i += 1 {
				_, file, line, ok := runtime.Caller(i)
				if !ok {
					break
				}
				str = str + fmt.Sprintf("%v,%v", file, line)
			}
			builderror <- str

		}
	}()
	fmt.Println("Autobuild")
	path, _ := os.Getwd()
	os.Chdir(path)
	bcmd := exec.Command("go", "build")
	var out bytes.Buffer
	var berr bytes.Buffer
	bcmd.Stdout = &out
	bcmd.Stderr = &berr
	err := bcmd.Run()
	if err != nil {
		fmt.Println("run error", err)
	}
	if out.String() == "" {
		Kill()
	} else {
		builderror <- berr.String()
	}
}
Пример #11
0
// Method Close encrypts and writes the encrypted data to the key file
func (k *KeyStore) Close(secret []byte) {
	// Encode a gob of the keystore
	var buff bytes.Buffer
	enc := gob.NewEncoder(&buff)
	enc.Encode(k)
	buffString := buff.String()

	// Encrypt the data
	block, err := aes.NewCipher(secret)
	if err != nil {
		panic(err)
	}
	ciphertext := make([]byte, aes.BlockSize+len(buffString))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}
	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(buffString))

	// Write the encrypted data to the file
	kFile, err := os.OpenFile(kf, os.O_WRONLY, 0644)
	if err != nil {
		panic(err)
	}
	bytesWritten, err := kFile.Write(ciphertext)
	if err != nil || bytesWritten == 0 {
		panic(err)
	}
}
func TestMultiWriter(t *testing.T) {
	sha1 := sha1.New()
	sink := new(bytes.Buffer)
	mw := MultiWriter(sha1, sink)

	sourceString := "My input text."
	source := strings.NewReader(sourceString)
	written, err := Copy(mw, source)

	if written != int64(len(sourceString)) {
		t.Errorf("short write of %d, not %d", written, len(sourceString))
	}

	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	sha1hex := fmt.Sprintf("%x", sha1.Sum())
	if sha1hex != "01cb303fa8c30a64123067c5aa6284ba7ec2d31b" {
		t.Error("incorrect sha1 value")
	}

	if sink.String() != sourceString {
		t.Errorf("expected %q; got %q", sourceString, sink.String())
	}
}
Пример #13
0
func (u *updateNode) ExplainPlan(v bool) (name, description string, children []planNode) {
	var buf bytes.Buffer
	if v {
		fmt.Fprintf(&buf, "set %s (", u.tableDesc.Name)
		for i, col := range u.tw.ru.updateCols {
			if i > 0 {
				fmt.Fprintf(&buf, ", ")
			}
			fmt.Fprintf(&buf, "%s", col.Name)
		}
		fmt.Fprintf(&buf, ") returning (")
		for i, col := range u.rh.columns {
			if i > 0 {
				fmt.Fprintf(&buf, ", ")
			}
			fmt.Fprintf(&buf, "%s", col.Name)
		}
		fmt.Fprintf(&buf, ")")
	}

	subplans := []planNode{u.run.rows}
	for _, e := range u.rh.exprs {
		subplans = u.p.collectSubqueryPlans(e, subplans)
	}

	return "update", buf.String(), subplans
}
Пример #14
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()
}
Пример #15
0
func init() {

	// find sqlite3 command
	sqlite3, err := exec.LookPath("sqlite3")
	if err != nil {
		log.Fatalf("error finding sqlite3 in system: %#v", err.Error())
	}
	log.Printf("sqlite3 path: %#v", sqlite3)

	// open the schema file
	file, err := os.Open("_test/schema.sqlite3.sql")
	if err != nil {
		log.Fatalf("error opening test schema: %#v", err.Error())
	}

	// initialize test database with sql file
	cmd := exec.Command(sqlite3, dbpath)
	var outstd bytes.Buffer
	var outerr bytes.Buffer

	cmd.Stdin = file
	cmd.Stdout = &outstd
	cmd.Stderr = &outerr

	if err := cmd.Run(); err != nil {
		log.Printf("output: %#v", outstd.String())
		log.Printf("error:  %#v", outerr.String())

		log.Fatalf("Failed to run sqlite command")
	}
}
Пример #16
0
func exec(t *testing.T, dir, cmd string, args []string, expect string) {
	r, w, err := Pipe()
	if err != nil {
		t.Fatalf("Pipe: %v", err)
	}
	defer r.Close()
	attr := &ProcAttr{Dir: dir, Files: []*File{nil, w, Stderr}}
	p, err := StartProcess(cmd, args, attr)
	if err != nil {
		t.Fatalf("StartProcess: %v", err)
	}
	w.Close()

	var b bytes.Buffer
	io.Copy(&b, r)
	output := b.String()

	fi1, _ := Stat(strings.TrimSpace(output))
	fi2, _ := Stat(expect)
	if !SameFile(fi1, fi2) {
		t.Errorf("exec %q returned %q wanted %q",
			strings.Join(append([]string{cmd}, args...), " "), output, expect)
	}
	p.Wait()
}
Пример #17
0
// parseMultivalueLine parses a line that includes several quoted values separated by whitespaces.
// Example: MachineMetadata="foo=bar" "baz=qux"
// If the provided line is not a multivalue string, the line is returned as the sole value.
func parseMultivalueLine(line string) (values []string) {
	if !strings.HasPrefix(line, `"`) || !strings.HasSuffix(line, `"`) {
		return []string{line}
	}

	var v bytes.Buffer
	w := false // check whether we're within quotes or not
	for _, e := range []byte(line) {
		// ignore quotes
		if e == '"' {
			w = !w
			continue
		}

		if e == ' ' {
			if !w { // between quoted values, keep the previous value and reset.
				values = append(values, v.String())
				v.Reset()
				continue
			}
		}

		v.WriteByte(e)
	}

	values = append(values, v.String())

	return
}
Пример #18
0
// TODO Make this private, since we should be able to test against BuildStatement()
func (c *Context) RenderCQL() (string, error) {

	var buf bytes.Buffer

	// TODO This should be a switch
	switch c.Operation {
	case ReadOperation:
		{
			renderSelect(c, &buf)
		}
	case WriteOperation:
		{
			if c.hasConditions() {
				renderUpdate(c, &buf, false)
			} else {
				renderInsert(c, &buf)
			}

			renderCAS(c, &buf)
		}
	case CounterOperation:
		{
			renderUpdate(c, &buf, true)
		}
	case DeleteOperation:
		{
			renderDelete(c, &buf)
		}
	default:
		return "", fmt.Errorf("Unknown operation type: %s", c.Operation)
	}

	return buf.String(), nil
}
Пример #19
0
func TestSha1sum(t *testing.T) {
	r := NewRun(t)
	defer r.Finalise()
	file1 := r.WriteBoth("potato2", "------------------------------------------------------------", t1)
	file2 := r.WriteBoth("empty space", "", t2)

	fstest.CheckItems(t, r.fremote, file1, file2)

	var buf bytes.Buffer
	err := fs.Sha1sum(r.fremote, &buf)
	if err != nil {
		t.Fatalf("List failed: %v", err)
	}
	res := buf.String()
	if !strings.Contains(res, "da39a3ee5e6b4b0d3255bfef95601890afd80709  empty space\n") &&
		!strings.Contains(res, "                             UNSUPPORTED  empty space\n") &&
		!strings.Contains(res, "                                          empty space\n") {
		t.Errorf("empty space missing: %q", res)
	}
	if !strings.Contains(res, "9dc7f7d3279715991a22853f5981df582b7f9f6d  potato2\n") &&
		!strings.Contains(res, "                             UNSUPPORTED  potato2\n") &&
		!strings.Contains(res, "                                          potato2\n") {
		t.Errorf("potato2 missing: %q", res)
	}
}
Пример #20
0
// Get retrieves the credentials for a given server url.
// The reader must contain the server URL to search.
// The writer is used to write the JSON serialization of the credentials.
func Get(helper Helper, reader io.Reader, writer io.Writer) error {
	scanner := bufio.NewScanner(reader)

	buffer := new(bytes.Buffer)
	for scanner.Scan() {
		buffer.Write(scanner.Bytes())
	}

	if err := scanner.Err(); err != nil && err != io.EOF {
		return err
	}

	serverURL := strings.TrimSpace(buffer.String())

	username, secret, err := helper.Get(serverURL)
	if err != nil {
		return err
	}

	resp := Credentials{
		Username: username,
		Secret:   secret,
	}

	buffer.Reset()
	if err := json.NewEncoder(buffer).Encode(resp); err != nil {
		return err
	}

	fmt.Fprint(writer, buffer.String())
	return nil
}
Пример #21
0
func (t *TableMap) bindInsert(elem reflect.Value) (bindInstance, error) {
	plan := t.insertPlan
	if plan.query == "" {
		plan.autoIncrIdx = -1

		s := bytes.Buffer{}
		s2 := bytes.Buffer{}
		s.WriteString(fmt.Sprintf("insert into %s (", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName)))

		x := 0
		first := true
		for y := range t.Columns {
			col := t.Columns[y]
			if !(col.isAutoIncr && t.dbmap.Dialect.AutoIncrBindValue() == "") {
				if !col.Transient {
					if !first {
						s.WriteString(",")
						s2.WriteString(",")
					}
					s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))

					if col.isAutoIncr {
						s2.WriteString(t.dbmap.Dialect.AutoIncrBindValue())
						plan.autoIncrIdx = y
						plan.autoIncrFieldName = col.fieldName
					} else {
						if col.DefaultValue == "" {
							s2.WriteString(t.dbmap.Dialect.BindVar(x))
							if col == t.version {
								plan.versField = col.fieldName
								plan.argFields = append(plan.argFields, versFieldConst)
							} else {
								plan.argFields = append(plan.argFields, col.fieldName)
							}
							x++
						} else {
							s2.WriteString(col.DefaultValue)
						}
					}
					first = false
				}
			} else {
				plan.autoIncrIdx = y
				plan.autoIncrFieldName = col.fieldName
			}
		}
		s.WriteString(") values (")
		s.WriteString(s2.String())
		s.WriteString(")")
		if plan.autoIncrIdx > -1 {
			s.WriteString(t.dbmap.Dialect.AutoIncrInsertSuffix(t.Columns[plan.autoIncrIdx]))
		}
		s.WriteString(t.dbmap.Dialect.QuerySuffix())

		plan.query = s.String()
		t.insertPlan = plan
	}

	return plan.createBindInstance(elem, t.dbmap.TypeConverter)
}
Пример #22
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
}
Пример #23
0
// String reassembles the URL into a valid URL string.
func (u *URL) String() string {
	var buf bytes.Buffer
	if u.Scheme != "" {
		buf.WriteString(u.Scheme)
		buf.WriteByte(':')
	}
	if u.Opaque != "" {
		buf.WriteString(u.Opaque)
	} else {
		if u.Scheme != "" || u.Host != "" || u.User != nil {
			buf.WriteString("//")
			if ui := u.User; ui != nil {
				buf.WriteString(ui.String())
				buf.WriteByte('@')
			}
			if h := u.Host; h != "" {
				buf.WriteString(h)
			}
		}
		if u.Path != "" && u.Path[0] != '/' && u.Host != "" {
			buf.WriteByte('/')
		}
		buf.WriteString(escape(u.Path, encodePath))
	}
	if u.RawQuery != "" {
		buf.WriteByte('?')
		buf.WriteString(u.RawQuery)
	}
	if u.Fragment != "" {
		buf.WriteByte('#')
		buf.WriteString(escape(u.Fragment, encodeFragment))
	}
	return buf.String()
}
Пример #24
0
func TestDecompressor(t *testing.T) {
	b := new(bytes.Buffer)
	for _, tt := range zlibTests {
		in := bytes.NewBuffer(tt.compressed)
		zlib, err := NewReaderDict(in, tt.dict)
		if err != nil {
			if err != tt.err {
				t.Errorf("%s: NewReader: %s", tt.desc, err)
			}
			continue
		}
		defer zlib.Close()
		b.Reset()
		n, err := io.Copy(b, zlib)
		if err != nil {
			if err != tt.err {
				t.Errorf("%s: io.Copy: %v want %v", tt.desc, err, tt.err)
			}
			continue
		}
		s := b.String()
		if s != tt.raw {
			t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.desc, n, s, len(tt.raw), tt.raw)
		}
	}
}
Пример #25
0
// InitComplexMessage initializes a complex structure of the
// type CustomComplexMessage which includes a xml, struct of type PubnubDemoMessage,
// strings, float and integer.
func InitComplexMessage() CustomComplexMessage {
	pubnubDemoMessage := PubnubDemoMessage{
		DefaultMessage: "~!@#$%^&*()_+ `1234567890-= qwertyuiop[]\\ {}| asdfghjkl;' :\" zxcvbnm,./ <>? ",
	}

	xmlDoc := &Data{Name: "Doe", Age: 42}

	//_, err := xml.MarshalIndent(xmlDoc, "  ", "    ")
	//output, err := xml.MarshalIndent(xmlDoc, "  ", "    ")
	output := new(bytes.Buffer)
	enc := xml.NewEncoder(output)

	err := enc.Encode(xmlDoc)
	if err != nil {
		fmt.Printf("error: %v\n", err)
		return CustomComplexMessage{}
	}
	//fmt.Printf("xmlDoc: %v\n", xmlDoc)
	customComplexMessage := CustomComplexMessage{
		VersionID:     3.4,
		TimeToken:     13601488652764619,
		OperationName: "Publish",
		Channels:      []string{"ch1", "ch 2"},
		DemoMessage:   pubnubDemoMessage,
		//SampleXml        : xmlDoc,
		SampleXML: output.String(),
	}
	return customComplexMessage
}
Пример #26
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)
}
Пример #27
0
func (plug *Autoban) Setup(write chan IRCMessage, conf PluginConf) {
	plug.user = conf.UserName
	plug.write = write
	plug.event = make(chan IRCMessage, 1000)

	var buffer bytes.Buffer
	buffer.WriteString(`(?i:`)
	// Because range copies the elements, which is totally idiotic
	matches := conf.Autoban.Matches
	for i := 0; i < len(matches); i++ {
		buffer.WriteString(matches[i].Regex)
		if i != len(matches)-1 {
			buffer.WriteString(`|`)
		}
		matches[i].Matcher = regexp.MustCompile(matches[i].Regex)
	}
	buffer.WriteString(`)`)

	plug.match = regexp.MustCompile(buffer.String())

	plug.autoBans = conf.Autoban.Matches

	go plug.Action()
	return
}
Пример #28
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()
}
Пример #29
0
func (g *GpgCLI) Sign(fp PGPFingerprint, payload []byte) (string, error) {
	g.outputVersion()
	arg := RunGpg2Arg{
		Arguments: []string{"--armor", "--sign", "-u", fp.String()},
		Stdout:    true,
		Stdin:     true,
	}

	res := g.Run2(arg)
	if res.Err != nil {
		return "", res.Err
	}

	res.Stdin.Write(payload)
	res.Stdin.Close()

	buf := new(bytes.Buffer)
	buf.ReadFrom(res.Stdout)
	armored := buf.String()

	// Convert to posix style on windows
	armored = PosixLineEndings(armored)

	if err := res.Wait(); err != nil {
		return "", err
	}

	return armored, nil
}
Пример #30
0
// resultTypeHelp generates and returns formatted help for the provided result
// type.
func resultTypeHelp(xT descLookupFunc, rt reflect.Type, fieldDescKey string) string {
	// Generate the JSON example for the result type.
	results, isComplex := reflectTypeToJSONExample(xT, rt, 0, fieldDescKey)

	// When this is a primitive type, add the associated JSON type and
	// result description into the final string, format it accordingly,
	// and return it.
	if !isComplex {
		return fmt.Sprintf("%s (%s) %s", results[0],
			reflectTypeToJSONType(xT, rt), xT(fieldDescKey))
	}

	// At this point, this is a complex type that already has the JSON types
	// and descriptions in the results.  Thus, use a tab writer to nicely
	// align the help text.
	var formatted bytes.Buffer
	w := new(tabwriter.Writer)
	w.Init(&formatted, 0, 4, 1, ' ', 0)
	for i, text := range results {
		if i == len(results)-1 {
			fmt.Fprintf(w, text)
		} else {
			fmt.Fprintln(w, text)
		}
	}
	w.Flush()
	return formatted.String()
}