TODO this should come from js-ipfs instead
192450
function buildConfig (_config) {
  _config.datastore = Object.assign({}, defaultDatastore, _get(_config, 'datastore', {}))

  return _config
}
124461
function FileCache(options){
  var self = this;
  // cordova-promise-fs
  this._fs = options.fs;
  if(!this._fs) {
    throw new Error('Missing required option "fs". Add an instance of cordova-promise-fs.');
  }
  // Use Promises from fs.
  Promise = this._fs.Promise;

  // 'mirror' mirrors files structure from "serverRoot" to "localRoot"
  // 'hash' creates a 1-deep filestructure, where the filenames are hashed server urls (with extension)
  this._mirrorMode = options.mode !== 'hash';
  this._retry = options.retry || [500,1500,8000];
  this._cacheBuster = !!options.cacheBuster;

  // normalize path
  this.localRoot = this._fs.normalize(options.localRoot || 'data');
  this.serverRoot = this._fs.normalize(options.serverRoot || '');

  // set internal variables
  this._downloading = [];    // download promises
  this._added = [];          // added files
  this._cached = {};         // cached files

  // list existing cache contents
  this.ready = this._fs.ensure(this.localRoot)
  .then(function(entry){
    self.localInternalURL = typeof entry.toInternalURL === 'function'? entry.toInternalURL(): entry.toURL();
    self.localUrl = entry.toURL();
    return self.list();
  });
}
513190
function (filePatterns, destination, options) {
  try {
    var fse = require('fs-extra')
  } catch (e) {
    console.error('This method can only be used in server applications.\n' +
      'Consider using the alternative method "i18nCompile.fromString()" instead.')
  }

  options = options || {};
  var matchedFiles = _.map(filePatterns, function (pattern) {
    return glob.sync(pattern);
  });

  var files = _.uniq(_.flatten(matchedFiles));

  var srcList = files.filter(function (filepath) {
    // Warn on and remove invalid source files (if nonull was set).
    try {
      fse.accessSync(filepath);
      return true;
    } catch (e) {
      console.warn('Source file "' + filepath + '" not found.');
      return false;
    }
  }).map(function (filepath) {
    // Read YAML file.
    var content = yaml.safeLoad(fse.readFileSync(filepath, 'utf8'), {
      filename: filepath,
      schema: yaml.JSON_SCHEMA
    });

    return new SrcItem(filepath, content);
  });

  var compiled = compileTranslations(srcList);

  // Handle options.
  if (options.merge) {
    // Write the destination file(with all languages merged in the same file).
    fse.outputFileSync(destination, JSON.stringify(compiled));

    // Print a success message.
    console.log('File "' + destination + '" created.');

    return;
  }

  // Write the destination files.
  for (var lang in compiled) {
    var fileDest = langFileDest(destination, lang, options.langPlace);
    fse.outputFileSync(fileDest, JSON.stringify(compiled[lang]));

    // Print a success message.
    console.log('File "' + fileDest + '" created.');
  }
}
640676
function sftpPut(inFilename, cb) {
    var fromFile, toFile, from, to;

    fromFile = localRoot + localSep + inFilename;
    toFile = remoteRoot + remoteSep + inFilename.split(localSep).join(remoteSep);

    if(localSep != remoteSep) {
      toFile = toFile.replace(new RegExp(localSep == '\\' ? '\\\\' : '\\/', 'g'), remoteSep);
    }

    grunt.verbose.write(fromFile + ' to ' + toFile);

    var f_size = fs.statSync(fromFile).size;

    var upload = function(fromFile, toFile, cb) {
      sftpConn.fastPut( fromFile, toFile, function(err){
        if (err){
          log.write((' Error uploading file: ' + err.message).red + '\n');
          cb(err);
        } else {
          grunt.verbose.write(' done'.green + '\n' );
          if( with_progress ) progressLogger.tick();
          transferred += parseInt(f_size/1024);
          cb(null);
        }
      });
    };

    if (cacheEnabled) {
      fs.stat(fromFile, function(err, fromFileData){
        if (cache[fromFile] && +new Date(cache[fromFile]) >= +new Date(fromFileData.mtime)) {
          cb(null);
        } else {
          cache[fromFile] = fromFileData.mtime;
          upload(fromFile, toFile, cb);
        }
      } );
    } else {
      upload(fromFile, toFile, cb);
    }

  }
1072674
function(inputFile, outputFile, content) {
                return Promise()
                .then(function() {
                    var outputFilePath = PathUtils.resolveInRoot(outputFolder, outputFile);

                    return fs.ensureFile(outputFilePath)
                    .then(function() {
                        return fs.copy(inputFile, outputFilePath);
                    });
                });
            }
2004
function FileClient(serviceRegistry, filter) {
		var _patterns;
		var _services;
		var _names;

		EventTarget.attach(this);
		/* @callback */
		function _noMatch(loc) {
			var d = new Deferred();
			d.reject(messages["No Matching FileService for location:"] + loc);
			return d;
		}

		var _fileSystemsRoots = [];
		var _allFileSystemsService = {
			/* @callback */
			fetchChildren: function() {
				var d = new Deferred();
				d.resolve(_fileSystemsRoots);
				return d;
			},
			/* @callback */
			createWorkspace: function() {
				var d = new Deferred();
				d.reject(messages["no file service"]);
				return d;
			},
			/* @callback */
			loadWorkspaces: function() {
				var d = new Deferred();
				d.reject(messages['no file service']);
				return d;
			},
			/* @callback */
			loadWorkspace: function(loc) {
				var d = new Deferred();
				window.setTimeout(function() {
					d.resolve({
						Directory: true,
						Length: 0,
						LocalTimeStamp: 0,
						Name: messages["File Servers"],
						Location: "/",
						Children: _fileSystemsRoots,
						ChildrenLocation: "/"
					});
				}, 100);
				return d;
			},
			/* @callback */
			read: function(loc) {
				if (loc === "/") {
					return this.loadWorkspace(loc);
				}
				return _noMatch(loc);
			},
			/**
			 * @description Computes the project context from the given location
			 * @param {String} context The resource context to find the project for
			 * @since 14.0
			 */
			getProject: _noMatch,
			search: _noMatch,
			createProject: _noMatch,
			createFolder: _noMatch,
			createFile: _noMatch,
			deleteFile: _noMatch,
			moveFile: _noMatch,
			copyFile: _noMatch,
			write: _noMatch
		};

		/**
		 * @description Initialize the service
		 * @private
		 */
		function init() {
			if (_services) { return; }
			_patterns = [];
			_services = [];
			_names = [];

			var allReferences = serviceRegistry.getServiceReferences("orion.core.file"); //$NON-NLS-1$
			var _references = allReferences;
			if (filter) {
				_references = [];
				for(var i = 0; i < allReferences.length; ++i) {
					if (filter(allReferences[i])) {
						_references.push(allReferences[i]);
					}
				}
			}
			_references.sort(function (ref1, ref2) {
				var ranking1 = ref1.getProperty("ranking") || 0; //$NON-NLS-1$
				var ranking2 = ref2.getProperty("ranking")  || 0; //$NON-NLS-1$
				return ranking1 - ranking2;
			});
			for(var j = 0; j < _references.length; ++j) {
				_fileSystemsRoots[j] = {
					Directory: true,
					Length: 0,
					LocalTimeStamp: 0,
					Location: _references[j].getProperty("top"), //$NON-NLS-1$
					ChildrenLocation: _references[j].getProperty("top"), //$NON-NLS-1$
					Name: _references[j].getProperty("Name") || _references[j].getProperty("NameKey") //$NON-NLS-1$ //$NON-NLS-2$
				};

				var filetop = _references[j].getProperty("top"); //$NON-NLS-1$
				var patternStringArray = _references[j].getProperty("pattern") || (filetop ? filetop.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1") : ""); //$NON-NLS-1$ //$NON-NLS-2$
				if (!Array.isArray(patternStringArray)) {
					patternStringArray = [patternStringArray];
				}
				var patterns = [];
				for (var k = 0; k < patternStringArray.length; k++) {
					var patternString = patternStringArray[k];
					if (patternString[0] !== "^") {
						patternString = "^" + patternString;
					}
					patterns.push(new RegExp(patternString));
				}
				_patterns[j] = patterns;
				_services[j] = serviceRegistry.getService(_references[j]);
				_names[j] = _references[j].getProperty("Name") || _references[j].getProperty("NameKey"); //$NON-NLS-1$ //$NON-NLS-2$
			}
		}

		/**
		 * @description Returns the index of the service for the given item location
		 * @function
		 * @private
		 * @param {String} itemLocation
		 * @returns returns
		 */
		this._getServiceIndex = function(itemLocation) {
			init();
			// client must specify via "/" when a multi file service tree is truly wanted
			if (itemLocation === "/") {
				return -1;
			} else if (!itemLocation || itemLocation.length && itemLocation.length === 0) {
				// TODO we could make the default file service a preference but for now we use the first one
				return _services[0] ? 0 : -1;
			}
			for(var i = 0; i < _patterns.length; ++i) {
				for (var j = 0; j < _patterns[i].length; j++) {
					if (_patterns[i][j].test(itemLocation)) {
						return i;
					}
				}
			}
			throw new Error(i18nUtil.formatMessage(messages['NoFileSrv'], itemLocation));
		};
		/**
		 * Returns the file service managing this location
		 * @param {String} itemLocation The location of the item
		 * @private
		 * @returns {FileClient} The service for the given item
		 */
		this._getService = function(itemLocation) {
			var i = this._getServiceIndex(itemLocation);
			return i === -1 ? _allFileSystemsService : _services[i];
		};
		/**
		 * Returns the name of the file service managing this location
		 * @param {String} itemLocation The location of the item
		 * @private
		 * @return {String} The name of this file service
		 */
		this._getServiceName = function(itemLocation) {
			var i = this._getServiceIndex(itemLocation);
			return i === -1 ? _allFileSystemsService.Name : _names[i];
		};
		/**
		 * Returns the root url of the file service managing this location
		 * @param {String} itemLocation The location of the item
		 * @private
		 * @return {String} The root URL of the given item
		 */
		this._getServiceRootURL = function(itemLocation) {
			var i = this._getServiceIndex(itemLocation);
			return i === -1 ? _allFileSystemsService.Location : _fileSystemsRoots[i].Location;
		};

		this._frozenEvent = {type: "Changed"};
		this._eventFrozenMode = false;

		serviceRegistry.registerService("orion.core.file.client", this); //$NON-NLS-1$
	}
766050
function createJsonFileDiscoverProvider(hostsFile) {
    var fs = require('fs');

    return function jsonFileProvider(callback) {
        fs.readFile(hostsFile, function onFileRead(err, data) {
            if (err) {
                callback(err);
                return;
            }

            var hosts;
            try {
                hosts = JSON.parse(data.toString());
            } catch (e) {
                callback(e);
                return;
            }
            callback(null, hosts);
            return;
        });
    };
}
349931
function(key, path, next) {
    this.fileSystem.get(key, function(err, data) {
      fs.writeFile(path, data, function(err) {
        if (err) {
          console.log(err);
        }
        next(err, data); 
      });
    });
  }
515605
function servePublicFile(file, type, maxAge) {
    const publicFileMiddleware = createPublicFileMiddleware(file, type, maxAge);

    return function servePublicFile(req, res, next) {
        if (req.path === '/' + file) {
            return publicFileMiddleware(req, res, next);
        } else {
            return next();
        }
    };
}
1293834
function Dbf(fileName) {

	this._fileName = fileName;
	var self = this;
	this._promise = new Promise(function(resolve, reject) {

		fs.open(fileName, 'r', function(err, fd) {
			if (err)
				reject(err);
			else {
				fs.read(fd, new Buffer(32), 0, 0x20, 0, function(err, bytes, buffer) {
					if (err)
						reject(err);
					else if (bytes === 0x20) {
						try {
							self._parse(fd, buffer, resolve, reject);
						} catch (e) {
							reject(e);
						}
					} else
						reject(new Error('Invalid file length'));
				});
			}
		});
	});

}
688568
function sendFile(params) {
    const p = params;
    
    checkParams(params);
    
    fs.lstat(p.name, (error, stat) => {
        if (error)
            return sendError(error, params);
        
        const isGzip = isGZIP(p.request) && p.gzip;
        const time = stat.mtime.toUTCString();
        const length = stat.size;
        const range = getRange(p.request, length);
        
        if (range)
            assign(p, {
                range,
                status: RANGE
            });
        
        assign(p, {
            time
        });
        
        if (!isGzip)
            p.length = length;
        
        setHeader(params);
        
        const options = {
            gzip    : isGzip,
            range,
        };
        
        files.pipe(p.name, p.response, options).catch((error) => {
            sendError(error, params);
        });
    });
}
713907
function ( srcs ) {
		return [
			/*
			 * Distribute foldernames and filenames in hashmaps.
			 */
			function step1 ( srcs ) {
				var map = Object.create ( null );
				function next ( source, parts, map ) {
					var part = parts.shift ();
					if ( !parts.length ) {
						map [ part ] = source;
					} else {
						map [ part ] = map [ part ] || Object.create ( null );
						next ( source, parts, map [ part ]);
					}
				}
				srcs.forEach ( function ( source ) {
					next ( source, source.split ( "/" ), map );
				});
				return map;
			},
			/*
			 * Transforming hashmaps into objects and arrays.
			 */
			function step2 ( map ) {
				var root = { name : "/", nodes : []};
				return ( function next ( map, parent, level ) {
					gui.Object.each ( map, function ( key, val ) {
						var node = { name : key };
						if ( typeof ( val ) === "object" ) {
							node.nodes = [];
							node.open = level < 1;
							next ( val, node, level + 1 );
						} else {
							node.src = val;
						}
						parent.nodes.push ( node );
					});
					return parent;
				}) ( map, root, 0 );
			},
			/*
			 * Split files from folders and sort them alphabetically.
			 */
			function step3 ( folder ) {
				var is, nodes = folder.nodes, alpha = function ( n1, n2 ) {
					return n1.name < n2.name ? -1 : n1.name > n2.name ? 1 : 0;
				};
				folder.nodes = nodes.filter ( function ( node ) {
					return (( is = node.nodes )) ? step3 ( node ) : false;
				}).sort ( alpha ).concat ( nodes.filter ( function ( node ) {
					return !node.nodes;
				}).sort ( alpha ));
				return folder;
			},
			/**
			 * Reduce to minimum viable root folder.
			 */
			function step4 ( folder ) {
				while ( folder.nodes.length === 1 && folder.nodes [ 0 ].nodes ) {
					//folder.hidden = true;
					folder = folder.nodes [ 0 ];
				}
				return folder;
			},
			/**
			 * Preoptimize search by stamping descendant filenames onto folders.
			 */
			function step5 ( folder ) {
				folder.filenames = folder.filenames || folder.nodes.map ( function ( node ) {
					return node.nodes ? step5 ( node ).filenames : node.name.toLowerCase ();
				}).join ( " " );
				return folder;
			}
		].reduce ( function ( input, nextstep ) { 
			return nextstep ( input ); 
		}, srcs );
	}
1275947
function streamFile(namespace, fileName) {
  return gfsPromise.then(function(gfs) {
    var deferred = q.defer();
    var options = {
      filename: fileName
    };
    if (namespace) {
      options.root = namespace;
    }
    var readstream = gfs.createReadStream(options);
    readstream.on('error', function(err) {
      console.log('An error occurred when reading file from gridfs!', err);
    });
    deferred.resolve(readstream);
    return deferred.promise;
  });
}
1142569
function jshintFileset(fileset) {
    var files = [];
    fileset.forEach(function (file) {
        if (isDirectory(file)) {
            files.push(file + '**/*.js');
        } else {
            files.push(file);
        }
    });

    return files;
}
1009941
function (src, dest, content, fileObject) {
						var files = {};

						_.each(content, function (v, k) {
							var file = fileObject.orig.dest + '/' + k + '.json';

							files[file] = JSON.stringify(v);
						});

						return files;
					}
1352886
function createSourceMapFile(opts) {
  return new File({
    cwd: opts.cwd,
    base: opts.base,
    path: opts.path,
    contents: new Buffer(JSON.stringify(opts.content)),
    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;
      },
    },
  });
}
659693
function local(rootFolder) {
    // Construct name to remote id map
    const remote = path.join(rootFolder, constants.META_DIR, constants.META_REMOTE);
    const remoteSource = fs.readJsonSync(remote, 'utf8');
    const destination = constants.META_LOCAL;
    return pack(rootFolder, destination);
}