Skip to content

Instantly share code, notes, and snippets.

@vincicat
Created October 24, 2021 20:24
Show Gist options
  • Save vincicat/8273db9c06f57155b780f8e89f72a435 to your computer and use it in GitHub Desktop.
Save vincicat/8273db9c06f57155b780f8e89f72a435 to your computer and use it in GitHub Desktop.
parsing Unity YAML
// for js-yaml 4.0, to avoid unity "YAML unknown tag" error: schema is required
import yaml from "js-yaml";
import path from "path";
import fs, { readFileSync } from "fs";
function parseAssetFile(p, assetsPath) {
// Read the File
let file = fs.readFileSync(path.resolve(assetsPath, p), { encoding: "utf-8" });
// From github: https://github.com/nodeca/js-yaml/issues/100
let types = {};
// remove the unity tag line
file = file.replace(/%TAG.+\r?\n?/, "");
// replace each subsequent tag with the full line + map any types
file = file.replace(/!u!([0-9]+).+/g, (match, p1) => {
// create our mapping for this type
if (!(p1 in types)) {
const type = new yaml.Type(`tag:unity3d.com,2011:${p1}`, {
kind: "mapping",
construct: function (data) {
return data || {}; // in case of empty node
},
instanceOf: Object,
});
types[p1] = type;
}
return `!<tag:unity3d.com,2011:${p1}>`;
});
// create our schema (migrate to 4.x sytnax)
const schema = yaml.DEFAULT_SCHEMA.extend(Object.values(types));
let doc = {};
try {
//using loadAll as it is a multi-file YAML, but the result will be in an Array
doc = yaml.loadAll(file, null, { schema });
} catch (e) {
// handle the parsing error in your way, but doc will be empty if error occur.
}
return doc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment