github.com/ipld/go-ipld-prime@v0.21.0/traversal/patch/parse.go (about)

     1  package patch
     2  
     3  import (
     4  	_ "embed"
     5  
     6  	"bytes"
     7  	"io"
     8  
     9  	"github.com/ipld/go-ipld-prime"
    10  	"github.com/ipld/go-ipld-prime/codec"
    11  	"github.com/ipld/go-ipld-prime/node/bindnode"
    12  	"github.com/ipld/go-ipld-prime/schema"
    13  
    14  	"github.com/ipld/go-ipld-prime/codec/json"
    15  	"github.com/ipld/go-ipld-prime/datamodel"
    16  )
    17  
    18  //go:embed patch.ipldsch
    19  var embedSchema []byte
    20  
    21  var ts = func() *schema.TypeSystem {
    22  	ts, err := ipld.LoadSchemaBytes(embedSchema)
    23  	if err != nil {
    24  		panic(err)
    25  	}
    26  	return ts
    27  }()
    28  
    29  func ParseBytes(b []byte, dec codec.Decoder) ([]Operation, error) {
    30  	return Parse(bytes.NewReader(b), dec)
    31  }
    32  
    33  func Parse(r io.Reader, dec codec.Decoder) ([]Operation, error) {
    34  	npt := bindnode.Prototype((*[]operationRaw)(nil), ts.TypeByName("OperationSequence"))
    35  	nb := npt.Representation().NewBuilder()
    36  	if err := json.Decode(nb, r); err != nil {
    37  		return nil, err
    38  	}
    39  	opsRaw := bindnode.Unwrap(nb.Build()).(*[]operationRaw)
    40  	var ops []Operation
    41  	for _, opRaw := range *opsRaw {
    42  		// TODO check the Op string
    43  		op := Operation{
    44  			Op:    Op(opRaw.Op),
    45  			Path:  datamodel.ParsePath(opRaw.Path),
    46  			Value: opRaw.Value,
    47  		}
    48  		if opRaw.From != nil {
    49  			op.From = datamodel.ParsePath(*opRaw.From)
    50  		}
    51  		ops = append(ops, op)
    52  	}
    53  	return ops, nil
    54  }
    55  
    56  // operationRaw is roughly the same structure as Operation, but more amenable to serialization
    57  // (it doesn't use high level library types that don't have a data model equivalent).
    58  type operationRaw struct {
    59  	Op    string
    60  	Path  string
    61  	Value datamodel.Node
    62  	From  *string
    63  }