package protocol import ( "encoding/json" "errors" "fmt" "os" ) // Protocol structure type Protocol struct { Metadata Meta Structure []*Field DefaultValues []DefaultValues JavaScript string } // ToJSON conversion func (prot Protocol) ToJSON() string { data, err := json.MarshalIndent(prot, "", " ") if err != nil { return "" } return string(data) } // NewProtocolStructure which is empty func NewProtocolStructure() *Protocol { p := Protocol{} return &p } // AppendField to protocol func (prot *Protocol) AppendField(field Field) int { i := len(prot.Structure) prot.Structure = append(prot.Structure, &field) return i + 1 } // AppendFields to protocol func (prot *Protocol) AppendFields(fields ...Field) { for _, e := range fields { prot.AppendField(e) } } // AddField to protocol func (prot *Protocol) AddField(index int, field *Field) { if len(prot.Structure) == index { prot.AppendField(*field) return } ret := make([]*Field, 0) ret = append(ret, prot.Structure[:index]...) ret = append(ret, field) ret = append(ret, prot.Structure[index:]...) prot.Structure = ret } // UpdateFieldByName in the protocol func (prot *Protocol) UpdateFieldByName(name string, field *Field) { var fnd int = -1 for i, f := range prot.Structure { if f.Name == name { fnd = i } } if fnd != -1 { prot.Structure[fnd] = field } } // UpdateFieldByElement in the protocol func (prot *Protocol) UpdateFieldByElement(element int, field *Field) { prot.Structure[element] = field } // RemoveFieldByName from the protocol func (prot *Protocol) RemoveFieldByName(name string) error { element := -1 for i, f := range prot.Structure { if f.Name == name { element = i } } if element == -1 { return errors.New("Element not found") } prot.RemoveFieldByElement(element) return nil } // RemoveFieldByElement from the protocol func (prot *Protocol) RemoveFieldByElement(field int) { ret := make([]*Field, 0) for i, f := range prot.Structure { if i != field { fmt.Printf("appending %d, %s\n", i, f.ToJSON()) ret = append(ret, f) } } prot.Structure = ret } // Load a protocol from path into the current reference func (prot *Protocol) Load(path string) error { data, err := os.ReadFile(path) if err != nil { return err } err = json.Unmarshal(data, prot) return err } // Save a protocol at a path location func (prot *Protocol) Save(path string) error { data, err := json.MarshalIndent(*prot, "", " ") if err != nil { return err } err = os.WriteFile(path, data, 0644) return err } // LoadNew protocol from path func LoadNew(path string) (*Protocol, error) { prot := NewProtocolStructure() err := prot.Load(path) return prot, err }