2016-11-04 3 views
0

Я пытался найти способ с глотком, чтобы выписывать только определенные файлы на основе данных ямля, которые я собираю в трубе. Я смог увидеть данные файла, но не смог получить ожидаемый результат.Выход управления Gulp основан на данных из более раннего канала

В этой задаче я собираю glob файлов разметки и передаю их в канал, который читает yaml, используя gulp-data, а затем добавляет к нему некоторые другие данные. Затем я прохожу через Swig.

Я пытаюсь добавить какой-то условный элемент, прежде чем я запишу в gulp.dest. Я нашел этот example, который доставил меня туда, где я сейчас.

Ближайший я получил ниже:

.pipe(tap(function(file) { 
    if (new Date(file.data.date) >= new Date(buildRange)) { 
     console.log(file.path); 
     gulp.src(file.path) 
     .pipe(gulp.dest(config.paths.dest + '/underreview/')); 
    } 
    })) 

Что я получил от console.log команды является правильным (он показывает 2 из 50 файлов). Но ничего не записывается в пункт назначения. Если я переведу gulp.dest за пределы этого канала, все файлы будут записаны.

Я пробовал использовать gulp-if или gulp-ignore, но не смог получить файл.data.date в любом из этих модулей.


Отредактировано: Вот полную задачу

module.exports = function(gulp, config, env) { 


var gulpSwig = require('gulp-swig'), 
    swig = require('swig'), 
    data = require('gulp-data'), 
    matter = require('gray-matter'), 
    runSequence = require('run-sequence'), 
    // BrowserSync 
    reload = config.browserSync.reload, 
    _ = require('lodash'), 
    Path = require('path'), 
    requireDir = require('require-dir'), 
    marked = require('marked'), 
    readingTime = require('reading-time'), 
    postsData = [], 
    postsTags = [], 
    pdate = null, 
    buildRange = new Date(new Date().setDate(new Date().getDate()-14)); 
    sitebuilddate = null, 
    through = require('through2'), 
    gutil = require('gulp-util'), 
    rename = require('gulp-rename'), 
    File = require('vinyl'), 
    $if = require('gulp-if'), 
    ignore = require('gulp-ignore'), 
    tap = require('gulp-tap'); 

    var opts = { 
    defaults: { 
     cache: false 
    }, 
    setup: function(Swig) { 
     Swig.setDefaults({ 
     loader: Swig.loaders.fs(config.paths.source + '/templates')}); 
    } 
    }; 

    // Full of the compiled HTML file 
    function targetPathFull(path, data) { 
    return Path.join(Path.dirname(path), targetPath(data)); 
    } 

gulp.task('templates2:under', function() { 
    return gulp.src(config.paths.source + '/content/**/*.md') 
     .pipe(data(function(file) { 
     postData = []; 
     var matterObject = matter(String(file.contents)), // extract front matter data 
      type = matterObject.data.type, // page type 
      body = matterObject.content, 
      postData = matterObject.data, 
      moreData = requireDir(config.paths.data), 
      data = {}, 
      bodySwig; 

     bodySwig = swig.compile(body, opts); 
     // Use swig to render partials first 
     body = bodySwig(data); 
     // Process markdown 
     if (Path.extname(file.path) === '.md') { 
      body = marked(body); 
     } 
     // Inherit the correct template based on type 
     if (type) { 
      var compiled = _.template(
      "{% extends 'pages/${type}.html' %}{% block body %}${body}{% endblock %}" 
      // Always use longform until a different template for different types is needed 
      //"{% extends 'pages/longform.html' %}{% block body %}${body}{% endblock %}" 
     ); 
      body = compiled({ 
      "type": type, 
      "body": body 
      }); 
     } 

     file.path = targetPathFull(file.path, postData); 
     moreData.path = targetPath(postData); 
     _.merge(data, postData, moreData); 

     data.url = data.site.domain + "/" + data.slug; 
     // Copy the processed body text back into the file object so Gulp can keep piping 
     file.contents = new Buffer(body); 

     return data; 
     })) 
     .pipe(gulpSwig(opts)) 
     .pipe(tap(function(file) { 
     if (new Date(file.data.date) >= new Date(buildRange)) { 
      console.log(file.path); 
      gulp.src(file.path) 
      .pipe(gulp.dest(config.paths.dest + '/underreview/')); 
     } 
     })) 
     .pipe(gulp.dest(config.paths.dest + '/underreview/')); 
    }); 
} 
+0

Возможно, вам будет легко ответить, если вы предоставили [mcve]. –

+0

@SvenSchoenung Я отправил свою полную задачу. Единственная часть, которая является новой, - это та часть, о которой я прошу. За последние 8 месяцев я строил ночной со всем другим кодом. – AGarrett

ответ

0

Таким образом, возможно, не самое лучшее решение, но после некоторого рефакторинга я пришел с этим:

.pipe(gulp.dest(config.paths.dest + '/underreview/')) 
     .pipe(tap(function(file) { 
     if (new Date(file.data.date) < new Date(buildRange)) { 
      console.log(file.data.path); 
      del(config.paths.dest + '/underreview/' + file.data.path) 
     } 
     })) 

я переехал gulp-tap после выхода, а затем я удаляю только что написанный файл.