Exemplo n.º 1
0
/**
 * Overwrite file with sorted json
 * @param {String} path                  - absolutePath
 * @param {Object} [options = {}]        - optional params
 * @returns {*}
 */
function overwriteFile(path, options) {
  let fileContent = null;
  let newData = null;

  try {
    fileContent = fs.readFileSync(path, 'utf8');
    newData = visit(JSON.parse(fileContent), options);
  } catch (e) {
    console.error('Failed to retrieve json object from file');
    throw e;
  }

  let indent;

  if (options && options.indentSize) {
    indent = options.indentSize;
  } else {
    indent = detectIndent(fileContent).indent || DEFAULT_INDENT_SIZE;
  }

  const newLine = detectNewline(fileContent) || '\n';
  let newFileContent = JSON.stringify(newData, null, indent);

  if (!(options && options.noFinalNewLine)) {
    // Append a new line at EOF
    newFileContent += '\n';
  }

  if (newLine !== '\n') {
    newFileContent = newFileContent.replace(/\n/g, newLine);
  }

  fs.writeFileSync(path, newFileContent, 'utf8');
  return newData;
}
Exemplo n.º 2
0
 (shrinkwrap, lockfile) => {
   if (!shrinkwrap && !lockfile) {
     return cb(null, false, false)
   }
   const file = shrinkwrap ? SHRINKWRAP : PKGLOCK
   let data
   let indent
   let newline
   try {
     data = parseJSON(shrinkwrap || lockfile)
     indent = detectIndent(shrinkwrap || lockfile).indent
     newline = detectNewline(shrinkwrap || lockfile)
   } catch (err) {
     log.error('version', `Bad ${file} data.`)
     return cb(err)
   }
   data.version = newVersion
   write(data, file, indent, newline, (err) => {
     if (err) {
       log.error('version', `Failed to update version in ${file}`)
       return cb(err)
     } else {
       return cb(null, !!shrinkwrap, !!lockfile)
     }
   })
 }
Exemplo n.º 3
0
 ).then((data) => {
   return {
     path: file,
     raw: data,
     indent: detectIndent(data).indent,
     newline: detectNewline(data)
   }
 }).catch({code: 'ENOENT'}, () => {})
Exemplo n.º 4
0
 fs.readFile(packagePath, 'utf8', function (er, data) {
   if (er) return cb(new Error(er))
   var indent
   var newline
   try {
     indent = detectIndent(data).indent
     newline = detectNewline(data)
     data = JSON.parse(data)
   } catch (e) {
     er = e
     data = null
   }
   cb(er, data, indent, newline)
 })
Exemplo n.º 5
0
/**
 * Deserialize a text into a code block
 */
function deserializeCode(opts: Options, text: string): Block {
    const sep = detectNewline(text) || DEFAULT_NEWLINE;

    const lines = List(text.split(sep)).map(line =>
        Block.create({
            type: opts.lineType,
            nodes: [Text.create(line)]
        })
    );

    const code = Block.create({
        type: opts.containerType,
        nodes: lines
    });

    return code;
}
Exemplo n.º 6
0
const main = () => {
    if (fs.existsSync(`${projectRoot}/.gitignore`)) {
        var file = fs.readFileSync(`${projectRoot}/.gitignore`).toString();
        var newlineChar = detectNewline(file);
        if (!file.includes(".basic256rc.js")) fs.appendFileSync(`${projectRoot}/.gitignore`, `${newlineChar}.basic256rc.js${newlineChar}`);
    }

    if (fs.existsSync(`${projectRoot}/.basic256rc.js`)) {
        return exit("\n.basic256rc.js already exists, stopping setup.\n");
    }

    if (fs.existsSync("./config.js")) {
        try {
            var c = require("./config.js").k;
            if (c.key) fetchedKey = c.key;
            if (c.hmac_key) fetchedHMAC = c.hmac_key;
            convertedConfig = true;
        } catch (e) {
            fetchedKey = null,
            fetchedHMAC = null;
            console.warn(`\nThere is an old config.js file in package.\nHowever, reading of the keys have failed:\n\n${e.stack}\n`);
        }
    }

    const enduserconfig = {
        key: fetchedKey || randomValueHex(32), // create random hex val for enc key
        hmac_key: fetchedHMAC || randomValueHex(32) // create random hex val for hmac key
    };

    fs.appendFileSync(`${projectRoot}/.basic256rc.js`, `"use strict";

module.exports = ${JSON.stringify(enduserconfig, null, 4)}
`); // generate config file with necessary info

    if (convertedConfig) return exit("\nYour old configuration is saved to a file named .basic256rc.js has been created on the project root.\nDON'T FORGET TO BACK THIS UP.\n");
    return exit("\nA file named .basic256rc.js has been created on the project root. DON'T FORGET TO BACK THIS UP.\n");
};
Exemplo n.º 7
0
wiring.appendFiles = function appendFiles(htmlOrOptions, fileType, optimizedPath, sourceFileList, attrs, searchPath) {
  var blocks;
  var updatedContent;
  var html = htmlOrOptions;
  var files = '';
  var eolChar;

  if (typeof htmlOrOptions === 'object') {
    html = htmlOrOptions.html;
    fileType = htmlOrOptions.fileType;
    optimizedPath = htmlOrOptions.optimizedPath;
    sourceFileList = htmlOrOptions.sourceFileList;
    attrs = htmlOrOptions.attrs;
    searchPath = htmlOrOptions.searchPath;
  }

  attrs = this.attributes(attrs);

  eolChar = detectNewline(html);

  if (fileType === 'js') {
    sourceFileList.forEach(function (el) {
      files += wiring.appendIndent('<script ' + attrs + ' src="' + el + '"></script>' + eolChar);
    });
    blocks = this.generateBlock('js', optimizedPath, files, searchPath, eolChar);
    updatedContent = this.append(html, 'body', blocks);
  } else if (fileType === 'css') {
    sourceFileList.forEach(function (el) {
      files += wiring.appendIndent('<link ' + attrs + ' rel="stylesheet" href="' + el + '">' + eolChar);
    });
    blocks = this.generateBlock('css', optimizedPath, files, searchPath, eolChar);
    updatedContent = this.append(html, 'head', blocks);
  }

  // cleanup trailing whitespace
  return updatedContent.replace(/[\t ]+$/gm, '');
};
Exemplo n.º 8
0
function getProjectSync(pathOrSrcFile) {
    if (!fs.existsSync(pathOrSrcFile)) {
        throw new Error(exports.errors.GET_PROJECT_INVALID_PATH);
    }
    var dir = fs.lstatSync(pathOrSrcFile).isDirectory() ? pathOrSrcFile : path.dirname(pathOrSrcFile);
    var projectFile = tsconfig.resolveSync(dir);
    if (!projectFile) {
        throw errorWithDetails(new Error(exports.errors.GET_PROJECT_NO_PROJECT_FOUND), { projectFilePath: fsu.consistentPath(pathOrSrcFile), errorMessage: 'not found' });
    }
    var projectFileDirectory = path.dirname(projectFile) + path.sep;
    var projectSpec;
    var projectFileTextContent;
    try {
        projectFileTextContent = fs.readFileSync(projectFile, 'utf8');
    }
    catch (ex) {
        throw new Error(exports.errors.GET_PROJECT_FAILED_TO_OPEN_PROJECT_FILE);
    }
    try {
        projectSpec = tsconfig.parseFileSync(projectFileTextContent, projectFile, { resolvePaths: false });
    }
    catch (ex) {
        throw errorWithDetails(new Error(exports.errors.GET_PROJECT_JSON_PARSE_FAILED), { projectFilePath: fsu.consistentPath(projectFile), error: ex.message });
    }
    if (!projectSpec.atom) {
        projectSpec.atom = {
            rewriteTsconfig: false,
        };
    }
    if (projectSpec.filesGlob) {
        var prettyJSONProjectSpec = prettyJSON(projectSpec, detectIndent(projectFileTextContent).indent, detectNewline(projectFileTextContent));
        if (prettyJSONProjectSpec !== projectFileTextContent && projectSpec.atom.rewriteTsconfig) {
            fs.writeFileSync(projectFile, prettyJSONProjectSpec);
        }
    }
    var pkg = null;
    try {
        var packagePath = travelUpTheDirectoryTreeTillYouFind(projectFileDirectory, 'package.json');
        if (packagePath) {
            var packageJSONPath = getPotentiallyRelativeFile(projectFileDirectory, packagePath);
            var parsedPackage = JSON.parse(fs.readFileSync(packageJSONPath).toString());
            pkg = {
                main: parsedPackage.main,
                name: parsedPackage.name,
                directory: path.dirname(packageJSONPath),
                definition: parsedPackage.typescript && parsedPackage.typescript.definition
            };
        }
    }
    catch (ex) {
    }
    var project = {
        compilerOptions: {},
        files: projectSpec.files.map(function (x) { return path.resolve(projectFileDirectory, x); }),
        filesGlob: projectSpec.filesGlob,
        formatCodeOptions: formatting.makeFormatCodeOptions(projectSpec.formatCodeOptions),
        compileOnSave: projectSpec.compileOnSave == undefined ? true : projectSpec.compileOnSave,
        package: pkg,
        typings: [],
        externalTranspiler: projectSpec.externalTranspiler == undefined ? undefined : projectSpec.externalTranspiler,
        scripts: projectSpec.scripts || {},
        buildOnSave: !!projectSpec.buildOnSave,
        atom: { rewriteTsconfig: false, formatOnSave: !!projectSpec.atom.formatOnSave }
    };
    var validationResult = validator.validate(projectSpec.compilerOptions);
    if (validationResult.errorMessage) {
        throw errorWithDetails(new Error(exports.errors.GET_PROJECT_PROJECT_FILE_INVALID_OPTIONS), { projectFilePath: fsu.consistentPath(projectFile), errorMessage: validationResult.errorMessage });
    }
    project.compilerOptions = rawToTsCompilerOptions(projectSpec.compilerOptions, projectFileDirectory);
    project.files = increaseProjectForReferenceAndImports(project.files);
    var typings = getDefinitionsForNodeModules(dir, project.files);
    project.files = project.files.concat(typings.implicit);
    project.typings = typings.ours.concat(typings.implicit);
    project.files = project.files.concat(typings.packagejson);
    project.files = uniq(project.files.map(fsu.consistentPath));
    projectFileDirectory = removeTrailingSlash(fsu.consistentPath(projectFileDirectory));
    return {
        projectFileDirectory: projectFileDirectory,
        projectFilePath: projectFileDirectory + '/' + projectFileName,
        project: project,
        inMemory: false
    };
}
Exemplo n.º 9
0
/**
 * Detect the dominant newline character of a string
 * @param {String} text
 * @return {String}
 */
function getNewLine(text) {
    return detectNewline(text) || DEFAULT;
}
Exemplo n.º 10
0
  fs.readFile(saveTarget, 'utf8', iferr(next, function (packagejson) {
    const indent = detectIndent(packagejson).indent
    const newline = detectNewline(packagejson)
    try {
      tree.package = parseJSON(packagejson)
    } catch (ex) {
      return next(ex)
    }

    // If we're saving bundled deps, normalize the key before we start
    if (saveBundle) {
      var bundle = tree.package.bundleDependencies || tree.package.bundledDependencies
      delete tree.package.bundledDependencies
      if (!Array.isArray(bundle)) bundle = []
    }

    var toSave = getThingsToSave(tree)
    var toRemove = getThingsToRemove(tree)
    var savingTo = {}
    toSave.forEach(function (pkg) { if (pkg.save) savingTo[pkg.save] = true })
    toRemove.forEach(function (pkg) { if (pkg.save) savingTo[pkg.save] = true })

    Object.keys(savingTo).forEach(function (save) {
      if (!tree.package[save]) tree.package[save] = {}
    })

    log.verbose('saving', toSave)
    const types = ['dependencies', 'devDependencies', 'optionalDependencies']
    toSave.forEach(function (pkg) {
      if (pkg.save) tree.package[pkg.save][pkg.name] = pkg.spec
      const movedFrom = []
      for (let saveType of types) {
        if (
          pkg.save !== saveType &&
          tree.package[saveType] &&
          tree.package[saveType][pkg.name]
        ) {
          movedFrom.push(saveType)
          delete tree.package[saveType][pkg.name]
        }
      }
      if (movedFrom.length) {
        log.notice('save', `${pkg.name} is being moved from ${movedFrom.join(' and ')} to ${pkg.save}`)
      }
      if (saveBundle) {
        var ii = bundle.indexOf(pkg.name)
        if (ii === -1) bundle.push(pkg.name)
      }
    })

    toRemove.forEach(function (pkg) {
      if (pkg.save) delete tree.package[pkg.save][pkg.name]
      if (saveBundle) {
        bundle = without(bundle, pkg.name)
      }
    })

    Object.keys(savingTo).forEach(function (key) {
      tree.package[key] = deepSortObject(tree.package[key])
    })
    if (saveBundle) {
      tree.package.bundleDependencies = deepSortObject(bundle)
    }

    var json = stringifyPackage(tree.package, indent, newline)
    if (json === packagejson) {
      log.verbose('shrinkwrap', 'skipping write for package.json because there were no changes.')
      next()
    } else {
      writeFileAtomic(saveTarget, json, next)
    }
  }))
Exemplo n.º 11
0
  function sourceMapWrite(file, encoding, callback) {
    /*jshint validthis:true */

    if (file.isNull() || !file.sourceMap) {
      this.push(file);
      return callback();
    }

    if (file.isStream()) {
      return callback(new Error(PLUGIN_NAME + '-write: Streaming not supported'));
    }

    var sourceMap = file.sourceMap;
    // fix paths if Windows style paths
    sourceMap.file = unixStylePath(file.relative);

    if (options.mapSources && typeof options.mapSources === 'function') {
      sourceMap.sources = sourceMap.sources.map(function(filePath) {
        return options.mapSources(filePath);
      });
    }

    sourceMap.sources = sourceMap.sources.map(function(filePath) {
      return unixStylePath(filePath);
    });

    if (typeof options.sourceRoot === 'function') {
      sourceMap.sourceRoot = options.sourceRoot(file);
    } else {
      sourceMap.sourceRoot = options.sourceRoot;
    }
    if (sourceMap.sourceRoot === null) {
        sourceMap.sourceRoot = undefined;
    }

    if (options.includeContent) {
      sourceMap.sourcesContent = sourceMap.sourcesContent || [];

      // load missing source content
      for (var i = 0; i < file.sourceMap.sources.length; i++) {
        if (!sourceMap.sourcesContent[i]) {
          var sourcePath = path.resolve(sourceMap.sourceRoot || file.base, sourceMap.sources[i]);
          try {
            if (options.debug)
              console.log(PLUGIN_NAME + '-write: No source content for "' + sourceMap.sources[i] + '". Loading from file.');
            sourceMap.sourcesContent[i] = stripBom(fs.readFileSync(sourcePath, 'utf8'));
          } catch (e) {
            if (options.debug)
              console.warn(PLUGIN_NAME + '-write: source file not found: ' + sourcePath);
          }
        }
      }
    } else {
      delete sourceMap.sourcesContent;
    }

    var extension = file.relative.split('.').pop();
    var newline = detectNewline(file.contents.toString());
    var commentFormatter;

    switch (extension) {
      case 'css':
        commentFormatter = function(url) {
          return newline + "/*# sourceMappingURL=" + url + " */" + newline;
        };
        break;
      case 'js':
        commentFormatter = function(url) {
          return newline + "//# sourceMappingURL=" + url + newline;
        };
        break;
      default:
        commentFormatter = function(url) { return ""; };
    }

    var comment, sourceMappingURLPrefix;
    if (destPath === undefined || destPath === null) {
      // encode source map into comment
      var base64Map = new Buffer(JSON.stringify(sourceMap)).toString('base64');
      comment = commentFormatter('data:application/json;charset=' + options.charset + ';base64,' + base64Map);
    } else {
      var mapFile = path.join(destPath, file.relative) + '.map';
      // custom map file name
      if (options.mapFile && typeof options.mapFile === 'function') {
        mapFile = options.mapFile(mapFile);
      }

      var sourceMapPath = path.join(file.base, mapFile);

      // if explicit destination path is set
      if (options.destPath) {
        var destSourceMapPath = path.join(file.cwd, options.destPath, mapFile);
        var destFilePath = path.join(file.cwd, options.destPath, file.relative);
        sourceMap.file = unixStylePath(path.relative(path.dirname(destSourceMapPath), destFilePath));
        if (sourceMap.sourceRoot === undefined) {
          sourceMap.sourceRoot = unixStylePath(path.relative(path.dirname(destSourceMapPath), file.base));
        } else if (sourceMap.sourceRoot === '' || (sourceMap.sourceRoot && sourceMap.sourceRoot[0] === '.')) {
          sourceMap.sourceRoot = unixStylePath(path.join(path.relative(path.dirname(destSourceMapPath), file.base), sourceMap.sourceRoot));
        }
      } else {
        // best effort, can be incorrect if options.destPath not set
        sourceMap.file = unixStylePath(path.relative(path.dirname(sourceMapPath), file.path));
        if (sourceMap.sourceRoot === '' || (sourceMap.sourceRoot && sourceMap.sourceRoot[0] === '.')) {
          sourceMap.sourceRoot = unixStylePath(path.join(path.relative(path.dirname(sourceMapPath), file.base), sourceMap.sourceRoot));
        }
      }

      // add new source map file to stream
      var sourceMapFile = new File({
        cwd: file.cwd,
        base: file.base,
        path: sourceMapPath,
        contents: new Buffer(JSON.stringify(sourceMap)),
        stat: {
          isFile: function () { return true; },
          isDirectory: function () { return false; },
          isBlockDevice: function () { return false; },
          isCharacterDevice: function () { return false; },
          isSymbolicLink: function () { return false; },
          isFIFO: function () { return false; },
          isSocket: function () { return false; }
        }
      });
      this.push(sourceMapFile);

      var sourceMapPathRelative = path.relative(path.dirname(file.path), sourceMapPath);

      if (options.sourceMappingURLPrefix) {
        var prefix = '';
        if (typeof options.sourceMappingURLPrefix === 'function') {
          prefix = options.sourceMappingURLPrefix(file);
        } else {
          prefix = options.sourceMappingURLPrefix;
        }
        sourceMapPathRelative = prefix+path.join('/', sourceMapPathRelative);
      }
      comment = commentFormatter(unixStylePath(sourceMapPathRelative));

      if (options.sourceMappingURL && typeof options.sourceMappingURL === 'function') {
        comment = commentFormatter(options.sourceMappingURL(file));
      }
    }

    // append source map comment
    if (options.addComment)
      file.contents = Buffer.concat([file.contents, new Buffer(comment)]);

    this.push(file);
    callback();
  }