jonschlinkert / gray-matter

Smarter YAML front matter parser, used by metalsmith, Gatsby, Netlify, Assemble, mapbox-gl, phenomic, vuejs vitepress, TinaCMS, Shopify Polaris, Ant Design, Astro, hashicorp, garden, slidev, saber, sourcegraph, and many others. Simple to use, and battle tested. Parses YAML by default but can also parse JSON Front Matter, Coffee Front Matter, TOML Front Matter, and has support for custom parsers. Please follow gray-matter's author: https://github.com/jonschlinkert
https://github.com/jonschlinkert
MIT License
3.91k stars 138 forks source link

matter() caches the content even when an error is thrown #121

Open hankei6km opened 3 years ago

hankei6km commented 3 years ago

It cancels throwing an error when processing the cached content.

Steps to reproduce

import matter from 'gray-matter';

const fixture = '---whatever\nABC: XYZ\n---';
console.log('=== start');
try {
  matter(fixture);
} catch (err) {
  console.log(`Error1: ${err}`);
}
console.log('===');
try {
  matter(fixture);
} catch (err) {
  console.log(`Error2: ${err}`);
}
console.log('=== done');

// === start
// Error1: Error: gray-matter engine "whatever" is not registered
// ===
// === done

Workaround

https://github.com/jonschlinkert/gray-matter/issues/43#issuecomment-318258919

  matter(fixture, {});

or

https://github.com/hankei6km/gray-matter/blob/cae943deb97562eed22c1ad4f29ac7e93527d864/index.js#L29

function matter(input, options) {
  if (input === '') {
    return { data: {}, content: input, excerpt: '', orig: input };
  }

  let file = toFile(input);
  const cached = matter.cache[file.content];

  if (!options) {
    if (cached) {
      file = Object.assign({}, cached);
      file.orig = cached.orig;
      return file;
    }

    const ret = parseMatter(file, options);

    // only cache if there are no options passed. if we cache when options
    // are passed, we would need to also cache options values, which would
    // negate any performance benefits of caching
    matter.cache[file.content] = file;

    return ret;
  }

  return parseMatter(file, options);
}