Skip to content

Commit

Permalink
internal/qmp-gen: generate implementations for events.
Browse files Browse the repository at this point in the history
  • Loading branch information
danderson committed Feb 1, 2017
1 parent b6cc630 commit 938d8f3
Show file tree
Hide file tree
Showing 5 changed files with 642 additions and 40 deletions.
30 changes: 30 additions & 0 deletions internal/qmp-gen/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,36 @@ type StatusInfo struct {
}
`),
},
{
name: "MEM_UNPLUG_ERROR",
in: []byte(`##
# @MEM_UNPLUG_ERROR
#
# Emitted when memory hot unplug error occurs.
#
# @device: device name
#
# @msg: Informative message
#
# Since: 2.4
##
{
"event": "MEM_UNPLUG_ERROR",
"data": {
"device": "str",
"msg": "str"
}
}`),
out: []byte(`// MEM_UNPLUG_ERROR -> MemUnplugError (event)
// MemUnplugError implements the "MEM_UNPLUG_ERROR" event.
type MemUnplugError struct {
Device string 'json:"device"'
Msg string 'json:"msg"'
}
func (MemUnplugError) isEvent() {}`),
},
}

for _, tt := range tests {
Expand Down
15 changes: 14 additions & 1 deletion internal/qmp-gen/templates/event
Original file line number Diff line number Diff line change
@@ -1 +1,14 @@
// EVENT {{ .Name }}
// {{ .Name }} -> {{ .Name.Go }} (event)

{{- if (.Data.Fields API).HasInterfaceField API }}
{{ abort "Events with union/alternate fields are not supported (to implement, steal from structtype's template)" }}
{{- end }}

// {{ .Name.Go }} implements the "{{ .Name }}" event.
type {{ .Name.Go }} struct {
{{- range .Data.Fields API }}
{{ render . }}
{{- end }}
}

func ({{ .Name.Go }}) isEvent() {}
27 changes: 25 additions & 2 deletions internal/qmp-gen/templates/main
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,33 @@ package raw
// Generated using `go generate`, do not edit by hand!

import (
"encoding/json"
"fmt"
"encoding/json"
"fmt"

"github.com/digitalocean/go-qemu/qmp"
)

{{ range . }}
{{ render . }}
{{ end }}

func UnmarshalEvent(evt qmp.Event) (Event, error) {
raw, err := json.Marshal(evt.Data)
if err != nil {
return nil, err
}
switch evt.Event {
{{- range . }}
{{- if eq (typeOf .) "event" }}
case "{{ .Name }}":
var ret {{ .Name.Go }}
if err = json.Unmarshal(raw, &ret); err != nil {
return nil, err
}
return ret, nil
{{- end }}
{{- end }}
default:
return nil, fmt.Errorf("unknown event kind %q", evt.Event)
}
}
Loading

0 comments on commit 938d8f3

Please sign in to comment.