YAML wrapper.
[python-bulletml.git] / bulletml / bulletyaml.py
diff --git a/bulletml/bulletyaml.py b/bulletml/bulletyaml.py
new file mode 100644 (file)
index 0000000..ea45436
--- /dev/null
@@ -0,0 +1,53 @@
+"""BulletYAML implementation.
+
+BulletYAML is a translation of BulletML into YAML. The structure is
+mostly the same as the XML version, except BulletRef/FireRef/ActionRef
+elements are only used if they contain parameters, as YAML has its own
+intra-document references. Parameterless references are turned into
+direct YAML references.
+
+If PyYAML is installed, importing this module automatically registers
+BulletYAML tags with the default loader and dumper.
+
+Example BulletYAML document:
+    !BulletML
+    type: vertical
+    actions:
+      top: !ActionDef
+        actions:
+        - !FireDef
+          bullet: !BulletDef {}
+
+"""
+
+from bulletml import parser
+
+def register(Loader=None, Dumper=None):
+    """Register BulletYAML types for a Loader and Dumper."""
+    for cls in [parser.Direction, parser.ChangeDirection,
+                parser.Speed, parser.ChangeSpeed, parser.Wait,
+                parser.Tag, parser.Untag, parser.Vanish,
+                parser.Repeat, parser.Accel, parser.BulletDef,
+                parser.BulletRef, parser.ActionDef, parser.ActionRef,
+                parser.FireDef, parser.FireRef, parser.Offset,
+                parser.BulletML]:
+
+        def add(cls, loader, dumper):
+            tag = "!" + cls.__name__
+            if loader:
+                def construct(loader, node):
+                    return loader.construct_yaml_object(node, cls)
+                loader.add_constructor(tag, construct)
+            if dumper:
+                def represent(dumper, obj):
+                    return dumper.represent_yaml_object(tag, obj, cls)
+                dumper.add_representer(cls, represent)
+
+        add(cls, Loader, Dumper)
+
+try:
+    import yaml
+except ImportError:
+    pass
+else:
+    register(yaml, yaml)