Exemplo n.º 1
0
func TestString(t *testing.T) {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	s := test.NewPopulatedNinOptStruct(r, false)
	data, err := proto.Marshal(s)
	if err != nil {
		panic(err)
	}
	buf := bytes.NewBuffer(nil)
	err = fieldpath.ToString("test", "NinOptStruct", test.ThetestDescription(), "", data, 0, os.Stdout)
	if err != nil {
		panic(err)
	}
	_ = buf
	t.Logf("%v", string(buf.Bytes()))
}
Exemplo n.º 2
0
func main() {
	if len(flag.Args()) == 0 {
		er("fieldpath needs to be provided")
	}
	var desc = &descriptor.FileDescriptorSet{}
	if len(descFilename) > 0 {
		data, err := ioutil.ReadFile(descFilename)
		if err != nil {
			er(err.Error())
		}
		if err := proto.Unmarshal(data, desc); err != nil {
			er(fmt.Sprintf("Reading descriptor_set_in filename (%v) : %v", descFilename, err))
		}
	}
	if len(protoFilename) > 0 {
		var err error
		desc, err = parser.ParseFile(protoFilename, strings.Split(protoPath, ":")...)
		if err != nil {
			er(fmt.Sprintf("Parsing proto filename (%v) with proto path (%v) : %v", protoFilename, protoPath, err))
		}
	}
	if desc == nil {
		er("either descriptor_set_in or proto_filename flag needs to be provided")
	}

	us := []*fieldpath.Unmarshaler{}
	printers := []func(v []byte){}
	for _, a := range flag.Args() {
		fieldpaths := strings.Split(a, ".")
		if len(fieldpaths) < 2 {
			er("fieldpath flag needs at least a package.message structure")
		}
		rootPkg := fieldpaths[0]
		rootMsg := fieldpaths[1]
		if len(fieldpaths) >= 3 {
			fpath := strings.Join(fieldpaths[2:], ".")
			if expandFlag {
				var err error
				fpath, err = fieldpath.Expand(rootPkg, rootMsg, fpath, desc)
				if err != nil {
					er(err.Error())
				}
			}
			field, err := fieldpath.NewGenericPath(rootPkg, rootMsg, desc, fpath)
			if err != nil {
				er(err.Error())
			}
			stdout := &ToStdout{}
			stdout.BytesFunc = func(v []byte) {
				os.Stdout.Write([]byte(fmt.Sprintf("%v\n", v)))
			}
			if field.IsMessage() {
				stdout.BytesFunc = func(v []byte) {
					err := fieldpath.ToString(rootPkg, rootMsg, desc, fpath, v, 0, os.Stdout)
					if err != nil {
						er(err.Error())
					}
				}
			}
			u := field.NewUnmarshaler(stdout)
			us = append(us, u)
		} else {
			printers = append(printers, func(v []byte) {
				err := fieldpath.ToString(rootPkg, rootMsg, desc, "", v, 0, os.Stdout)
				if err != nil {
					er(err.Error())
				}
			})
		}

	}

	var r reader
	if inputDelim == "varint" {
		r = newVarintReader(os.Stdin)
	} else if inputDelim == "big32" {
		r = newBig32Reader(os.Stdin)
	} else {
		r = newAllReader(os.Stdin)
	}

	c := fieldpath.Compile(us...)

	for {
		data := r.Read()
		if data == nil {
			return
		}
		for _, p := range printers {
			p(data)
		}
		err := c.Unmarshal(data)
		if err != nil {
			er(err.Error())
		}
		if inputDelim == "none" {
			return
		}
	}

}