Files
obitools4/pkg/obiformats/fastseq_json_header.go
Eric Coissac d5e84ec676 rename goutils to obiutils
Former-commit-id: 2147f53db972bba571dfdae30c51b62d3e69cec5
2023-03-24 10:25:12 +07:00

85 lines
1.5 KiB
Go

package obiformats
import (
"math"
"strings"
log "github.com/sirupsen/logrus"
"git.metabarcoding.org/lecasofts/go/obitools/pkg/obiseq"
"git.metabarcoding.org/lecasofts/go/obitools/pkg/obiutils"
"github.com/goccy/go-json"
)
func _parse_json_header_(header string, annotations obiseq.Annotation) string {
start := -1
stop := -1
level := 0
lh := len(header)
for i := 0; (i < lh) && (stop < 0); i++ {
// fmt.Printf("[%d,%d-%d] : %d (%c) (%d,%c)\n", i, start, stop, header[i], header[i], '{', '{')
if level == 0 && header[i] == '{' {
start = i
}
if header[i] == '{' {
level++
}
if header[i] == '}' {
level--
}
if start >= 0 && level == 0 {
stop = i
}
}
if start < 0 || stop < 0 {
return header
}
stop++
err := json.Unmarshal([]byte(header)[start:stop], &annotations)
for k, v := range annotations {
switch vt := v.(type) {
case float64:
if vt == math.Floor(vt) {
annotations[k] = int(vt)
}
}
}
if err != nil {
log.Fatalf("annotation parsing error on %s : %v\n", header, err)
}
return strings.TrimSpace(header[stop:])
}
func ParseFastSeqJsonHeader(sequence *obiseq.BioSequence) {
sequence.SetDefinition(_parse_json_header_(sequence.Definition(),
sequence.Annotations()))
}
func FormatFastSeqJsonHeader(sequence *obiseq.BioSequence) string {
annotations := sequence.Annotations()
if len(annotations) > 0 {
text, err := obiutils.JsonMarshal(sequence.Annotations())
if err != nil {
panic(err)
}
return string(text)
}
return ""
}