return criticalPromise.then(function (criticalCss) {
    var contents = fs.readFileSync(destFilename);
    var toReplace = new RegExp(options.htmlTagToReplace);
    var replacement = options.replacementHtmlHeader + criticalCss + options.replacementHtmlTrailer;
    var STRING_IS_NOT_PRESENT = -1;

    if (!toReplace.test(replacement)) {
      log.warn('The HTML tag hexo-critical-css is replacing is not put back by the replacement');
    }

    if (criticalCss === '') {
      log.warn('critical did not return any CSS. hexo-critical-css will not inject an empty style string into the file', htmlFile);
      return;
    }

    if (toReplace.test(contents)) {
      if (contents.indexOf(replacement) === STRING_IS_NOT_PRESENT) {

        contents = contents.replace(toReplace, replacement);

        fs.writeFileSync(destFilename, contents);

        log.log('Generated critical CSS for', htmlFile);

        return;
      }
      log.log('critical CSS was already present in the file', htmlFile);

      return;
    }

    log.error('The HTML expression hexo-critical-css is attempting to replace is not present in the HTML for file', htmlFile, ': the match was', options.htmlTagToReplace);

    return;
  })
    return criticalPromise.then(function (criticalCssHtml) {
      fs.writeFileSync(destFilename, criticalCssHtml);

      log.log('Generated critical CSS for', htmlFile);

      return;
    })
Пример #3
0
let logic = function(data) {
    var log = this.log;
    if (data.layout == 'post') {
        let abbrlink
        if (!/.*\.org/.test(data.source)){
            abbrlink = data.abbrlink
        }
        else
        {
            abbrlink = org_get_abbrlink(data).abbrlink
        }
        if (!abbrlink) {
			var opt_alg = ((this.config.abbrlink && this.config.abbrlink.alg) ? this.config.abbrlink.alg : 'crc16');
			var opt_rep = ((this.config.abbrlink && this.config.abbrlink.rep) ? this.config.abbrlink.rep : 'dec')
			
			let res = (opt_alg == 'crc32' ? crc32.str(data.title) >>> 0 : crc16(data.title) >>> 0);
			//check this abbrlink is already exist then get a different one
			abbrlink = model.check(res);
			//set abbrlink to hex or dec
			abbrlink = opt_rep == 'hex' ? abbrlink.toString(16) : abbrlink;
            data.abbrlink = abbrlink;
            let postStr;
            if (!/.*\.org/.test(data.source)){
            //re parse front matter
            var tmpPost = front.parse(data.raw);
            //add new generated link
            tmpPost.abbrlink = abbrlink;
            //process post
                postStr = front.stringify(tmpPost);
            postStr = '---\n' + postStr;
            fs.writeFileSync(data.full_source, postStr, 'utf-8');
            }
            else
            {
                postStr = data.raw.split("\n")
                postStr.splice(2,0,'#+ABBRLINK: ' + abbrlink)
                fs.writeFileSync(data.full_source, postStr.join('\n'), 'utf-8');
            }
            if(data.title.length==0)
                log.i("No title found for post [%s]", data.slug);
            log.i("Generate link %s for post [%s]", abbrlink, data.title);
        }
        model.add(abbrlink);
    }
    return data
}
function dir2categories(data){

    var config = this.config;

    //判断是否需要添加dir2categories依赖
    if(config.default_category === 'dir2categories') {
        //更新 categories 数组
        var segs = data.source.split('/');

        var tmpPost = front.parse(data.raw);

        tmpPost.categories = segs.splice(1,segs.length - 2);

        //更新标签
        tmpPost.tags = tmpPost.categories.map(function(cat){
            if(!!config.category_map[cat]){
                return config.category_map[cat];
            }
        });

        //判断是否存在标题
        if(!data.title){

            var anchor_start = data.raw.indexOf('# ') + 2;
            var anchor_end = data.raw.indexOf('\n\n',anchor_start);

            tmpPost.title = data.raw.substr(anchor_start, anchor_end - anchor_start);
        }

        //添加永久链接
        tmpPost.abbrlink = (checKCrc(crc32.str(tmpPost.title) >>> 0)).toString(16);

        let postStr = front.stringify(tmpPost);

        postStr = '---\n' + postStr;

        fs.writeFileSync(data.full_source, postStr, 'utf-8');
    }


}
Пример #5
0
 before(() => {
   fs.writeFileSync(base + 'test1.yml', testYaml1);
   fs.writeFileSync(base + 'test2.yml', testYaml2);
   fs.writeFileSync(base + 'test1.json', testJson1);
   fs.writeFileSync(base + 'test2.json', testJson2);
 });
Пример #6
0
//---------------------------------------
// Writing cache file
//---------------------------------------
function createCacheFile(inPath, hexoConfig, inPostPath , inDate , inEyeCatchImage , inTitleImageForAmp, inEyeCatchImageProperty , inXml , callback){
  
  var cacheData;
  var newObj = {
      "path"                  : "" ,
      "date_eyeCatch"         : "" ,
      "date_amp"              : "" ,
      "eyeCatchImage"         : "" ,
      "titleImageForAmp"      : "" ,
      "eyeCatchImageProperty" : "" ,
      "xml"                   : "" 
  };
  
  var addObj = getAddObj(inPath, inPostPath , inDate , inEyeCatchImage , inTitleImageForAmp, inEyeCatchImageProperty , inXml);
  
  if( !fs.existsSync(getCachePath(hexoConfig)) || hexoConfig.generator_amp.isCacheClear ){
    cacheData = {
      "hash": hexoConfig.generator_amp.hash ,
      "ampData":[
          assign(newObj,addObj)
      ]
    };
    hexoConfig.generator_amp.isCacheClear = false; 
  }else{
    var isAddedData = false;
    var cacheData   = fs.readFileSync(inPath);
    cacheData = JSON.parse(cacheData);
    for( var i=0; i<cacheData.ampData.length; i++){
      if( cacheData.ampData[i].path == inPostPath ){
        if( addObj.xml ){
          if( cacheData.ampData[i].date_amp != inDate ){
            cacheData.ampData[i] = assign(cacheData.ampData[i],addObj);
          }
        }else{
          if( cacheData.ampData[i].date_eyeCatch != inDate ){
            cacheData.ampData[i] = assign(cacheData.ampData[i],addObj);
          }
        }
        isAddedData = true;
        break;
      }
    }
    
    if(!isAddedData){
      cacheData.ampData.push( addObj );
    }
  }
  
  cacheData.hash = hexoConfig.generator_amp.hash
  
  mkdirp.sync( pathFn.dirname(inPath) );
  fs.writeFileSync(inPath , JSON.stringify(cacheData));
  read_cacheData = cacheData;
  
  // console.log("cached: "+inPostPath);
  
  newObj = null;
  addObj = null;
  
  if(callback)callback();
}
Пример #7
0
module.exports = ctx => function multiConfigPath(base, configPaths, outputDir) {
  const log = ctx.log;

  const defaultPath = pathFn.join(base, '_config.yml');
  let paths;

  if (!configPaths) {
    log.w('No config file entered.');
    return pathFn.join(base, '_config.yml');
  }

  // determine if comma or space separated
  if (configPaths.includes(',')) {
    paths = configPaths.replace(' ', '').split(',');
  } else {
    // only one config
    let configPath = pathFn.isAbsolute(configPaths) ? configPaths : pathFn.resolve(base, configPaths);

    if (!fs.existsSync(configPath)) {
      log.w(`Config file ${configPaths} not found, using default.`);
      configPath = defaultPath;
    }

    return configPath;
  }

  const numPaths = paths.length;

  // combine files
  const combinedConfig = {};
  let count = 0;
  for (let i = 0; i < numPaths; i++) {
    let configPath = '';

    if (pathFn.isAbsolute(paths[i])) {
      configPath = paths[i];
    } else {
      configPath = pathFn.join(base, paths[i]);
    }

    if (!fs.existsSync(configPath)) {
      log.w(`Config file ${paths[i]} not found.`);
      continue;
    }

    // files read synchronously to ensure proper overwrite order
    const file = fs.readFileSync(configPath);
    const ext = pathFn.extname(paths[i]).toLowerCase();

    if (ext === '.yml') {
      merge(combinedConfig, yml.load(file));
      count++;
    } else if (ext === '.json') {
      merge(combinedConfig, yml.safeLoad(file, {json: true}));
      count++;
    } else {
      log.w(`Config file ${paths[i]} not supported type.`);
    }
  }

  if (count === 0) {
    log.e('No config files found. Using _config.yml.');
    return defaultPath;
  }

  log.i('Config based on', count, 'files');

  const multiconfigRoot = outputDir || base;
  const outputPath = pathFn.join(multiconfigRoot, '_multiconfig.yml');

  log.d(`Writing _multiconfig.yml to ${outputPath}`);

  fs.writeFileSync(outputPath, yml.dump(combinedConfig));

  // write file and return path
  return outputPath;
};
  return function multiConfigPath(base, configPaths) {
    var log = ctx.log;

    var defaultPath = pathFn.join(base, '_config.yml');
    var paths;

    if (!configPaths) {
      log.w('No config file entered.');
      return pathFn.join(base, '_config.yml');
    }

    // determine if comma or space separated
    if (configPaths.indexOf(',') > -1) {
      paths = configPaths.replace(' ', '').split(',');

    } else {
      // only one config
      if (!fs.existsSync(pathFn.join(base, configPaths))) {
        log.w('Config file ' + configPaths + ' not found, using default.');
        return defaultPath;
      }

      return pathFn.resolve(base, configPaths);
    }

    var numPaths = paths.length;

    // combine files
    var combinedConfig = {};
    var count = 0;
    for (var i = 0; i < numPaths; i++) {
      if (!fs.existsSync(pathFn.join(base, paths[i]))) {
        log.w('Config file ' + paths[i] + ' not found.');
        continue;
      }

      // files read synchronously to ensure proper overwrite order
      var file = fs.readFileSync(pathFn.join(base, paths[i]));
      var ext = pathFn.extname(paths[i]).toLowerCase();

      if (ext === '.yml') {
        _.merge(combinedConfig, yml.load(file));
        count++;
      } else if (ext === '.json') {
        _.merge(combinedConfig, yml.safeLoad(file, {json: true}));
        count++;
      } else {
        log.w('Config file ' + paths[i] +
                                  ' not supported type.');
      }
    }

    if (count === 0) {
      log.e('No config files found. Using _config.yml.');
      return defaultPath;
    }

    log.i('Config based on', count, 'files');

    var outputPath = pathFn.join(base, '_multiconfig.yml');
    fs.writeFileSync(outputPath, yml.dump(combinedConfig));

    // write file and return path
    return outputPath;
  };