Add x-order to every property
The task: go-swagger reads a schema’s properties into a Go map, which loses
the order the author wrote them in. An x-order: N entry on each property
records that order, and the generator reads it back. The rewrite must leave
every other byte of the file as written: the comments, the blank line, the
flow mapping.
The file
const src = `# Pet store schemas
Pet:
type: object
properties:
name: # shown first in the UI
type: string
id: {type: integer, format: int64}
owner:
type: object
properties:
email:
type: string
address:
type: string
`Full source: docs/examples/documents/xorder/example_test.go
The transformer
// xOrder inserts "x-order: N" as the first entry of every property's schema, N counting the properties of each
// "properties" mapping from 0 in document order. Every other byte is copied.
type xOrder struct {
keyAt map[int]string // the last key seen at each depth
count map[int]int // the next order at the depth of a property name
pending int // the depth of the property whose schema opens next, or 0
order int // the order to write there
flow bool // the piece before was a "{"
}
func newXOrder() *xOrder {
return &xOrder{keyAt: map[int]string{}, count: map[int]int{}}
}
func (x *xOrder) Piece(w io.Writer, p transform.Piece) error {
defer func() { x.flow = p.Role == transform.RoleIndicator && string(p.Text) == "{" }()
if p.Role != transform.RoleKey {
return transform.Copy(w, p)
}
// The first key of the schema mapping: write the new entry in front of it.
if x.pending > 0 && p.Depth == x.pending+1 {
if err := x.insert(w, p); err != nil {
return err
}
p.Lead = nil // insert wrote it, ahead of the new entry
}
if p.Depth <= x.pending {
x.pending = 0 // the property held no mapping, so nothing was inserted
}
name := string(p.Trimmed())
x.keyAt[p.Depth] = name
if name == "properties" {
x.count[p.Depth+1] = 0 // a new run of properties starts one level down
}
if x.keyAt[p.Depth-1] == "properties" {
x.pending, x.order = p.Depth, x.count[p.Depth]
x.count[p.Depth]++
}
return transform.Copy(w, p)
}
// insert writes the key's Lead, then the new entry, then a line break and the key's indentation, which its column
// gives: the Lead can start with line breaks, so it cannot be written twice.
func (x *xOrder) insert(w io.Writer, p transform.Piece) error {
x.pending = 0
if _, err := w.Write(p.Lead); err != nil {
return err
}
entry := fmt.Sprintf("x-order: %d\n%s", x.order, strings.Repeat(" ", int(p.Token.Position.Column)-1))
if x.flow {
entry = fmt.Sprintf("x-order: %d, ", x.order)
}
_, err := io.WriteString(w, entry)
return err
}Full source: docs/examples/documents/xorder/example_test.go
transform.Walk calls Piece once for every
token of the document, in source order, and transform.Copy writes a piece as
the document wrote it. xOrder copies every piece, and writes one more entry
in front of the first key of each property’s schema.
The walk hands one piece at a time and nothing ahead of it, so xOrder keeps
its own state:
keyAtholds the last key seen at each depth. A key whose parent ispropertiesnames a property.pendingholds that property’s depth. The next key one level deeper is the first key of its schema, and the entry goes in front of it.countnumbers the properties of eachpropertiesmapping from 0.
The entry goes after the key’s Lead, which ends at the key’s column. The key
then moves to a line of its own, indented to Token.Position.Column. Writing
the Lead a second time would not do: it can start with line breaks, as the
blank line under owner: does. Inside a flow mapping, the entry is written as
x-order: N, after the {.
Run it
if err := transform.Walk(os.Stdout, []byte(src), newXOrder()); err != nil {
fmt.Println(err)
}Full source: docs/examples/documents/xorder/example_test.go
# Pet store schemas
Pet:
type: object
properties:
name: # shown first in the UI
x-order: 0
type: string
id: {x-order: 1, type: integer, format: int64}
owner:
x-order: 2
type: object
properties:
email:
x-order: 0
type: string
address:
x-order: 1
type: stringFull source: docs/examples/documents/xorder/example_test.go
Each properties mapping counts from 0. The comment on name:, the blank line
under owner: and the flow mapping of id stay as written.
Read it back
type schema struct {
Order *int `yaml:"x-order"`
Properties map[string]schema `yaml:"properties"`
}Full source: docs/examples/documents/xorder/example_test.go
var out bytes.Buffer
if err := transform.Walk(&out, []byte(src), newXOrder()); err != nil {
fmt.Println(err)
return
}
var doc map[string]schema
if err := codec.Unmarshal(out.Bytes(), &doc); err != nil {
fmt.Println(err)
return
}
pet := doc["Pet"]
owner := pet.Properties["owner"]
fmt.Println(*pet.Properties["name"].Order, *pet.Properties["id"].Order, *owner.Order)
fmt.Println(*owner.Properties["email"].Order, *owner.Properties["address"].Order)Full source: docs/examples/documents/xorder/example_test.go
0 1 2
0 1Full source: docs/examples/documents/xorder/example_test.go
The order now survives map[string]schema.
Limits
- A schema with no key gets no entry.
a: {}and an aliasa: *basehave no first key to write in front of. The count still moves past them, so the next property keeps its place. - An entry already there is not checked. Running the transformer twice
writes
x-ordertwice. Skip a property whose first key isx-order. - A rejected document leaves partial output.
Walkreturns the parse error and the pieces written so far stay written. Walk into abytes.Buffer, asExample_readBackdoes, and write the file only on success. - No
$refis followed. The transformer sees one document. A schema that references another file is rewritten where that file is.