Giter Site home page Giter Site logo

hx-yaml's Introduction

Overview

A cross platform YAML 1.2 parser and renderer for Haxe 3+. Ported from the feature rich js-yaml. Currently supports JavaScript, Flash (as3), CPP and Neko 2.0+.

Installation

From haxelib:

haxelib install yaml

Or the latest directly from GitHub

haxelib git yaml https://github.com/mikestead/hx-yaml.git src

Example

invoice.yaml

invoice: 34843
date   : 2001-01-23
bill_to: &id001
  given  : Chris
  family : Dumars
  address:
    lines: |
      458 Walkman Dr.
      Suite #292
    city    : Royal Oak
    state   : MI
    postal  : 48046
ship_to: *id001
tax  : 251.42
457: true
total: 4443.52
comments: >
  Late afternoon is best.
  Backup contact is Nancy
  Billsmer @ 338-4338.

Example.hx

import yaml.Yaml;
import yaml.Parser;
import yaml.Renderer;
import yaml.util.ObjectMap;

class Example
{
	static function main()
	{
		parsingExample();
		renderingExample();
	}

	static function parsingExample()
	{
		#if sys
		// Load and parse our invoice document using yaml.util.ObjectMap for key => value containers.
		// Using this default option allows for complex key types and a slightly nicer api to 
		// iterate keys/values. 
		// Equivalent to Yaml.read("invoice.yaml", Parser.options().useMaps());
		var data:AnyObjectMap = Yaml.read("invoice.yaml"); 

		trace(data.get("tax")); // 251.42
		trace(data.get(457)); // true
		
		// Load and parse the same document this time using dynamic objects for key => value containers.
		// This option will stringify all keys but is useful for mapping to typedefs.
		var data = Yaml.read("invoice.yaml", Parser.options().useObjects());
		
		trace(data.invoice); // 3483
		trace(data.ship_to.given); // Chris
		trace(Reflect.field(data, "457")); // true
		#end
		
		// If you already have the yaml document in string form you can parse it directly
		var data = Yaml.parse("key: value");
		
		trace(data.get("key")); // value
	}

	static function renderingExample()
	{
		var receipt = {assistant:"Chris", items:[{rice:2.34}, {milk:1.22}]};

		// Render an object tree as a yaml document.
		var document = Yaml.render(receipt);
		trace(document);

		//  assistant: Chris
		//  items:
		//      - rice: 2.34
		//      - milk: 1.22

		#if sys
		// This time write that same document to disk and adjust the flow level giving 
		// a more compact result.
		Yaml.write("receipt.yaml", receipt, Renderer.options().setFlowLevel(1));
		#end
	}
}

receipt.yaml

assistant: Chris
items: [{rice: 2.34}, {milk: 1.22}]

API

Parsing

// Parse a single yaml document into object form
yaml.Yaml.parse(document:String, ?options:ParserOptions):Dynamic

// (sys only) Read a single yaml document from disk and parse it into object form
yaml.Yaml.read(filePath:String, ?options:ParserOptions):Dynamic

yaml.Parser.ParserOptions:
	- strict:Bool     - Parser will throw errors instead of tracing warnings. Default `false`.
    - validate:Bool   - Perform validation checks while parsing. Default is `true`.
    - schema:Schema   - The schema to use. Default is `yaml.schema.DefaultSchema`.
    - maps:Boolean    - True when using ObjectMaps, false when using Dynamic objects.

Rendering

// Render a yaml object graph as a yaml document
yaml.Yaml.render(data:Dynamic, ?options:RenderOptions):String

// (sys only) Render a yaml object graph as a yaml document and write it to disk
yaml.Yaml.write(filePath:String, data:Dynamic, ?options:RenderOptions):Void

yaml.Renderer.RendererOptions:
	- indent:Int        - The space indentation to use. Default `2`.
	- flowLevel:Int     - The level of nesting, when to switch from block to flow 
							style for collections. -1 means block style everywhere. Default `-1`.
	- styles:StringMap  - "tag" => "style" map. Each tag may have its own set of styles.
	- schema:Schema     - The schema to use. Default is `yaml.schema.DefaultSchema`.
Rendering Styles
!!null
  "canonical"   => "~"

!!int
  "binary"      => "0b1", "0b101010", "0b1110001111010"
  "octal"       => "01", "052", "016172"
  "decimal"     => "1", "42", "7290"
  "hexadecimal" => "0x1", "0x2A", "0x1C7A"

!!null, !!bool, !!float
  "lowercase"   => "null", "true", "false", ".nan", '.inf'
  "uppercase"   => "NULL", "TRUE", "FALSE", ".NAN", '.INF'
  "camelcase"   => "Null", "True", "False", ".NaN", '.Inf'

By default, !!int uses decimal, and !!null, !!bool, !!float use lowercase.

Supported YAML types

The list of standard YAML tags and corresponding Haxe types. See also YAML types.

!!null ''                   # null
!!bool 'yes'                # Bool
!!int '3...'                # Int
!!float '3.14...'           # Float
!!binary '...base64...'     # haxe.Binary
!!timestamp 'YYYY-...'      # Date
!!omap [ ... ]              # Array of yaml.util.ObjectMap
!!pairs [ ... ]             # Array of Array pairs
!!set { ... }               # yaml.util.ObjectMap of keys with null values
!!str '...'                 # String
!!seq [ ... ]               # Array
!!map { ... }               # yaml.util.ObjectMap

When parsing into maps, yaml.util.ObjectMap is used. Under Haxe 3.0 haxe.ds.ObjectMap would be used but it doesn't support primitive keys on all targets and we need a map which can contain a mixture of key types.

Limitations

  • Under CPP and Neko UTC date translation is not yet possible so dates will be represented in local time instead.
  • Requires Neko 2.0+ when used under the Neko runtime due to its support for Unicode based regular expressions.
  • CPP support requires Haxe 3.1.2+ and hxcpp 3.0.2+

License

MIT - See LICENSE

hx-yaml's People

Contributors

brokenbeta avatar bubblebenj avatar cedx avatar fponticelli avatar gama11 avatar mikestead avatar mtribes-sdk-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hx-yaml's Issues

Yaml class: "#if sys" conditions should be "#if (sys || nodejs)"

Under Node.js, these errors are raised by the haxe compiler when using the Yaml class:

Class<yaml.Yaml> has no field read
Class<yaml.Yaml> has no field write

The hxnodejs package partially supports the sys target, notably the sys.io.File class:
https://github.com/HaxeFoundation/hxnodejs/blob/master/src/sys/io/File.hx

Currently, under Node.js you must use:

Yaml.parse(sys.io.File.getContent(filePath)); // read
sys.io.File.saveContent(filePath, Yaml.render(data)); // write

This is exactly what the Yaml.read and Yaml.write methods already do. So the compilation conditions #if sys could be relaxed and include the nodejs define: #if (sys || nodejs).

disallowed Unicode code point

thanks for writing the library.

I get this error when I include hx-yaml. It gets thrown before main starts. Any ideas?

Haxe Compiler 3.0.1 - (C)2005-2013 Haxe Foundation
NekoVM 2.0.0 (c)2005-2013 Haxe Foundation

stack trace:

Called from yaml/Parser.hx line 1998
Called from /usr/lib/haxe/std/neko/_std/EReg.hx line 22
Called from a C function
Called from /usr/lib/haxe/std/neko/_std/EReg.hx line 33
Uncaught exception - regexp.c(115) : Regexp compilation error : disallowed Unicode code point (>= 0xd800 && <= 0xdfff) in [\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}-\x{84}\x{86}-\x{9F}\x{D800}-\x{DFFF}\x{FFFE}\x{FFFF}]

Library orphaned?

With Haxe4 out there and lots of deprecation warnings and old haxelib release I would like to ask if is this library orphaned.

Yaml.render() and Yaml.write() does not work on iOS-target

Part of the error output:

Called from yaml.Yaml.render (yaml/Yaml.hx line 51)
Called from yaml.Renderer.render (yaml/Renderer.hx line 100)
Called from yaml.Renderer.writeNode (yaml/Renderer.hx line 475)
Called from yaml.Renderer.writeBlockMapping (yaml/Renderer.hx line 333)
Called from yaml.Renderer.writeMapBlockMapping (yaml/Renderer.hx line 376)
Called from *._Function_1_1 (openfl/display/Stage.hx line 120)

Renderer doesn't work?

This doesn't work:

trace(Yaml.render(Yaml.parse(Assets.getText('assets/images/custom_chars/custom_chars.yaml'))));

This is the fille

{
  template: !!map {
    like: bf,
    icons: !!seq [0,1,24]
  }
}

Is something wrong with the file or the renderer?

Stream delimiters breaks the Parser

Check out this test.

Crashing on:

...

This text should be ignored.

Parser error stack trace:

yaml.YamlException: can not read an implicit mapping pair; a colon is missed at yaml.Parser#generateError (269)
Called from yaml.Parser::throwError line 274
Called from yaml.Parser::readBlockMapping line 1489
Called from yaml.Parser::composeNode line 913
Called from yaml.Parser::readDocument line 1860
Called from yaml.Parser::parseAll line 263
Called from yaml.Parser::parse line 159
Called from yaml.Yaml::parse line 22

Php support?

Hey, nice project!

Is there any reason why php isn't supported?

[hl] Compilation target not supported due to lackof Unicode RegEx support

Hi I get this targeting HashLink on Haxe 4 RC 5

yaml/Parser.hx:2002: characters 9-81 : Compilation target not supported due to lackof Unicode RegEx support

Will HashLink be supported soon? (it would be a shame not to!)
Since this is likely the fault of HL API itself has there been an issue reported on github so I can follow the discussion?
(Or maybe there is some secret switch I can define so as to only support ASCII regex?)
Good job with this lib btw!

Anchors

I'm having problems accessing the "gameObjects" array at the end of this file:
http://pastebin.com/ULvM5g5i

I expected the array to contain the code of the anchors but it's just a string array.
I'm parsing the yaml to an Object.

I keep getting Class not found yaml.Yaml etc

Hello Mike,

I'd love to use this in my haxe project, but I always seem to get class not found errors...

I have tried installing it with:

haxelib yaml
haxelib local hx-yaml-master.zip
haxelib dec yaml /mydir/hx-yaml-master/src
haxelib git yaml https://github.com/mikestead/hx-yaml.git src

but when I simply import:

import yaml.Yaml;
import yaml.Parser;
etc

I always get a class not found yaml:Yaml etc

What am I doing wrong?

Kind regards,

Jaap

Support for Android?

I'm using this lib targeting HTML5 and it works like a charm, but I would like to be able to target iOS & Android.
Is it possible? (I guess not regarding the read.me).

Thx.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.