crissdev / gulp-yaml

A Gulp plugin to convert YAML to JSON
MIT License
24 stars 7 forks source link

add a parseContents function #6

Closed lybo closed 7 years ago

lybo commented 7 years ago

Hi, Coin we add a parseContents function?

This function will be optional and it will manipulate the file contents.

The need of this manipulation of the content of an yaml file is for instance if you use https://www.npmjs.com/package/yaml-include-loader

I have cloned your repository and I have done this change. Then I did npm link to that one. It will be very handy for me if you include this option otherwise I can't use it with yaml-include-loader.

Example:


        function parseImports(content, filePath, options) {

            var oldLines = content.toString('utf8').split('\n');
            var newLines = [];
            var importKeyword = 'import';
            var importRawKeyword = 'import-raw';
            var regex = new RegExp("^(\\s+|)(\\w+):\\s(!(" + importKeyword + "|" + importRawKeyword + ")\\s+?(.*)(\\.ya?ml|\\.json)?)?\\s*$");
            var space = '';

            for (var i = 0; i < oldLines.length; i++) {
                var line = oldLines[i];
                var match = line.match(regex);
                if (!match) {
                    newLines.push(space + line);
                } else {
                    var fileName = match[3].substr(match[3].lastIndexOf('/')+1);
                    var fileNameArray = fileName.split('.');
                    newLines.push(line.replace(match[3], '"[!' + fileNameArray[0] + '!]"'));
                }
            }

            return new Buffer(newLines.join('\n'));
        }

        gulp
            .src([
                './configuration/*.yml'
            ])
            .pipe(yaml({
                parseContents: parseImports
            }))

Implementation:

             ' is empty. YAML loader cannot load empty content'));
         return callback();
       }
+      if (options.parseContents) {
+        file.contents = options.parseContents(file.contents, file.path, options);
+      }
       try {
         file.contents = yaml2json(file.contents, options);
         file.path = gutil.replaceExtension(file.path, '.json');
crissdev commented 7 years ago

@lybo You can achieve this using event-stream without having to change the implementation of this plugin.

gulp.src -pipe-> transform_using__es_map -pipe-> this_plugin

lybo commented 7 years ago

@crissdev Thanks!

A snippet for the next developer who has the same issue:

var yaml = require('gulp-yaml');
var es = require('event-stream');

function contentTransformation() {
      function transform(file, cb) {
          file.contents = parseImports(file.contents);
          cb(null, file);
      }
      return es.map(transform);
}
//snip....
        gulp
            .src([
                './configuration/*.yml'
            ])
            .pipe(contentTransformation())
            .pipe(yaml())
//snip....