/* general functions for working with file system nodes
354224
function(promise, xhrResult) {
		var error = xhrResult;
		try {
			error = JSON.parse(xhrResult.responseText);
		} catch (e) {}
		if (error && error.DetailedMessage) {
			error = i18nUtil.formatMessage(messages["Err"], error.DetailedMessage);
		} else if (error && error.Message) {
			error = i18nUtil.formatMessage(messages["Err"], error.Message);
		} else if (typeof xhrResult.url === "string") {
			if (xhrResult.status === 0) {
				error = i18nUtil.formatMessage(messages["NoResponseFromServer"], xhrResult.url);
			} else {
				error = i18nUtil.formatMessage(messages["ServerError"], xhrResult.url, xhrResult.status, xhrResult.statusText);
			}
		}
		var errNode = document.createElement("span"); //$NON-NLS-0$
		errNode.textContent = error;
		promise.reject(errNode);
	}
954974
function FilesNode(src, raw, config) {
  utils.define(this, 'isFilesNode', true);
  this.options = utils.omit(raw.options, ['mapDest', 'flatten', 'rename', 'filter']);
  this.src = utils.arrayify(src);

  if (this.options.resolve) {
    var cwd = path.resolve(this.options.cwd || process.cwd());
    this.src = this.src.map(function(fp) {
      return path.resolve(cwd, fp);
    });
  }

  if (raw.options.mapDest) {
    this.dest = mapDest(raw.dest, src, raw);
  } else {
    this.dest = rewriteDest(raw.dest, src, raw.options);
  }

  // copy properties to the new node
  for (var key in raw) {
    if (key !== 'src' && key !== 'dest' && key !== 'options') {
      this[key] = raw[key];
    }
  }
  util.run(config, 'filesNode', this);
}
557835
function _filesToFile (files, target, separator, callback) {

			if ("undefined" === typeof files) {
				throw new ReferenceError("missing \"files\" argument");
			}
				else if ("object" !== typeof files || !(files instanceof Array)) {
					throw new TypeError("\"files\" argument is not an Array");
				}
			else if ("undefined" === typeof target) {
				throw new ReferenceError("missing \"target\" argument");
			}
				else if ("string" !== typeof target) {
					throw new TypeError("\"target\" argument is not a string");
				}
			else if ("undefined" === typeof callback && "undefined" === typeof separator) {
				throw new ReferenceError("missing \"callback\" argument");
			}
				else if ("function" !== typeof callback && "function" !== typeof separator) {
					throw new TypeError("\"callback\" argument is not a function");
				}
			else {

				const _target = target.trim();

				if ("" === _target) {
					throw new Error("\"target\" argument is empty");
				}
				else {

					const _callback = "undefined" === typeof callback ? separator : callback;

					Promise.resolve().then(() => {
						return isFileProm(_target);
					}).then((exists) => {

						return !exists ? Promise.resolve() : new Promise((resolve, reject) => {

							fs.unlink(_target, (err) => {
								return err ? reject(err) : resolve();
							});

						});

					}).then(() => {

						if (!files.length) {

							return new Promise((resolve, reject) => {

								fs.writeFile(_target, "", (err) => {
									return err ? reject(err) : resolve();
								});

							});

						}
						else {

							return filesToStreamProm(files, "string" === typeof separator ? separator : " ").then((readStream) => {

								return new Promise((resolve, reject) => {

									let error = false;
									readStream.once("error", (_err) => {
										error = true; reject(_err);
									}).pipe(fs.createWriteStream(_target, { "flags": "a" }).once("error", (_err) => {
										error = true; reject(_err);
									}).once("close", () => {

										if (!error) {
											resolve();
										}

									}));

								});

							});

						}

					}).then(() => {
						_callback(null);
					}).catch(_callback);

				}

			}

		}
1081903
function(callback) {
    //process first all directories and then all files.
    async.mapSeries(['getDirectories', 'getFiles'], (nodeSource, cbMap) => {
      syncDb[nodeSource]((err, nodes) => {
        async.eachSeries(nodes, (node, cb) => {
          if(node.localActions && node.localActions.create) {
            var nodePath = utility.joinPath(node.parent, node.name);

            syncDb.findByPath(nodePath, (err, syncedNode) => {
              try {
                var stat = fsWrap.lstatSync(nodePath);
              } catch(e) {
                logger.warning('resolveConflicts got lstat error on node', {category: 'sync-local-delta', nodePath, code: e.code});
                throw new BlnDeltaError(e.message);
              }

              //deleted and recreated at same path
              if(syncedNode.localActions && syncedNode.localActions.delete) {
                syncedNode.ino = stat.ino;

                delete syncedNode.localActions.delete;

                if(syncedNode.directory) {
                  syncedNode.ctime = stat.ctime;
                  syncedNode.mtime = stat.mtime;
                  syncedNode.size = stat.size;
                } else {
                  syncedNode.localActions.create = node.localActions.create;
                }

                async.parallel([
                  (cbParallel) => {
                    syncDb.update(syncedNode._id, syncedNode, cbParallel);
                  },
                  (cbParallel) => {
                    syncDb.remove(node._id, cbParallel);
                  }
                ], cb);
              } else {
                cb(null);
              }
            });
          } else {
            cb(null);
          }
        }, cbMap);
      });
    }, callback);
  }
504606
function(_root,_umi,_hanlder){
        var _node = _root,
            _hanlder = _hanlder||_f;
        if (_umi!='/'){
            _u._$forEach(
                _umi.split('/'),function(_name){
                    var _result = _hanlder(_node,_name);
                    if (!_result) 
                        return !0;
                    _node = _result;
                }
            );
        }
        return _node;
    }
646595
function fileSystem(context, settings, next) {
  var input = context.files

  if (input.length === 0) {
    next()
  } else {
    find(
      input,
      {
        cwd: settings.cwd,
        extensions: settings.extensions,
        silentlyIgnore: settings.silentlyIgnore,
        ignore: new Ignore({
          cwd: settings.cwd,
          detectIgnore: settings.detectIgnore,
          ignoreName: settings.ignoreName,
          ignorePath: settings.ignorePath
        })
      },
      onfound
    )
  }

  function onfound(error, result) {
    var output = result.files

    /* Sort alphabetically. Everything’s unique so we don’t care
     * about cases where left and right are equal. */
    output.sort(sortAlphabetically)

    /* Mark as given.  This allows outputting files,
     * which can be pretty dangerous, so it’s “hidden”. */
    output.forEach(markAsGiven)

    context.files = output

    /* If `out` wasn’t set, detect it based on
     * whether one file was given. */
    if (settings.out === null || settings.out === undefined) {
      settings.out = result.oneFileMode
    }

    next(error)
  }

  function markAsGiven(file) {
    file.data.unifiedEngineGiven = true
  }

  function sortAlphabetically(left, right) {
    return left.path < right.path ? -1 : 1
  }
}
843486
private void recursivels(FileSystem fs, Path p, List<FileStatus> out) 
  throws IOException {
    FileStatus fstatus = fs.getFileStatus(p);
    if (!fstatus.isDir()) {
      out.add(fstatus);
      return;
    }
    else {
      out.add(fstatus);
      FileStatus[] listStatus = fs.listStatus(p);
      for (FileStatus stat: listStatus) {
        recursivels(fs, stat.getPath(), out);
      }
    }
  }
159623
async function (directory, filesInSassTree, exclusions) {
  const filesInDirectory = (await recursive(directory));

  const unusedFiles = filesInDirectory
    .filter((file) => isUnused(file, filesInSassTree, exclusions));

  return unusedFiles;
}
342630
private List<E> createBulkDirectoryNodes(List<E> nodes) {
    int minEntries = dirMinimum;
    int maxEntries = dirCapacity - 1;

    ArrayList<E> result = new ArrayList<>();
    List<List<E>> partitions = settings.bulkSplitter.partition(nodes, minEntries, maxEntries);

    for(List<E> partition : partitions) {
      // create node
      N dirNode = createNewDirectoryNode();
      // insert nodes
      for(E o : partition) {
        dirNode.addDirectoryEntry(o);
      }
      // write to file
      writeNode(dirNode);

      result.add(createNewDirectoryEntry(dirNode));
      if(getLogger().isDebuggingFiner()) {
        getLogger().debugFiner("Directory page no: "+dirNode.getPageID());
      }
    }

    return result;
  }
727665
async function mkfs(){

    // try to establish a connection to the module
    await getConnection();

    _mculogger.log('Formatting the file system...this will take around ~30s');

    try{
        const response = await _nodeMcuConnector.format();

        // just show complete message
        _mculogger.log('File System created | ' + response);
    }catch(e){
        _mculogger.error('Formatting failed');
        _logger.debug(e);
    }
}
897887
function(callback){
    var argFiles,
        filePath,
        i;

    if(!program.files || program.files.length === 0){
        return callback(null, true);
    }

    argFiles = program.files.split(',');

    output("Loading files...");

    for(i=0; i<argFiles.length; i++){
        filePath = path.resolve(__dirname, argFiles[i].toString());
        output("Reading file..." + filePath);
        if(fs.existsSync(filePath)){
            files.push(fs.readFileSync(filePath));
        }else{
            return callback("File does not exist, " + filePath, false);
        }
    }

    callback(null, true);
}
122801
function readFile(path, callback) {
  nodeFs.readFile(path, function (err, binary) {
    if (err) {
      if (err.code === "ENOENT") return callback();
      return callback(err);
    }
    return callback(null, binary);
  });
}
1095487
function createMockFS(files) {
    files = Immutable.fromJS(files);
    var mtime = new Date();

    function getFile(filePath) {
        var parts = path.normalize(filePath).split(path.sep);
        return parts.reduce(function(list, part, i) {
            if (!list) return null;

            var file;

            if (!part || part === '.') file = list;
            else file = list.get(part);

            if (!file) return null;

            if (is.string(file)) {
                if (i === (parts.length - 1)) return file;
                else return null;
            }

            return file;
        }, files);
    }

    function fsExists(filePath) {
        return Boolean(getFile(filePath) !== null);
    }

    function fsReadFile(filePath) {
        var file = getFile(filePath);
        if (!is.string(file)) {
            throw error.FileNotFoundError({
                filename: filePath
            });
        }

        return new Buffer(file, 'utf8');
    }

    function fsStatFile(filePath) {
        var file = getFile(filePath);
        if (!file) {
            throw error.FileNotFoundError({
                filename: filePath
            });
        }

        return {
            mtime: mtime
        };
    }

    function fsReadDir(filePath) {
        var dir = getFile(filePath);
        if (!dir || is.string(dir)) {
            throw error.FileNotFoundError({
                filename: filePath
            });
        }

        return dir
            .map(function(content, name) {
                if (!is.string(content)) {
                    name = name + '/';
                }

                return name;
            })
            .valueSeq();
    }

    return FS.create({
        root: '',
        fsExists: fsExists,
        fsReadFile: fsReadFile,
        fsStatFile: fsStatFile,
        fsReadDir: fsReadDir
    });
}
523847
function resolveNodeModules(pkgpath) {
  let dir = pkgpath;
  let dirs = [];
  let depth = maxFileSystemDepth;
  let parent;
  let nodeModulespath;

  while (true) {
    parent = path.dirname(dir);
    // Stop if we hit max file system depth or root
    // Convert to lowercase to fix problems on Windows
    if (!--depth || parent.toLowerCase() === dir.toLowerCase()) {
      break;
    }

    nodeModulespath = path.resolve(dir, 'node_modules');

    if (exists(nodeModulespath)) dirs.push(nodeModulespath);

    // Walk
    dir = parent;
  }

  return dirs;
}
1024809
function writeFile(filepath, data, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }

  if (!Buffer.isBuffer(data)) {
    return callback(new TypeError('Data must be a Buffer'));
  }

  if (!options) {
    options = {};
  }

  // Default the same as node
  var mode = options.mode || constants.DEFAULT_FILE_MODE;
  var flags = options.flags || 'w';
  var position = APPEND_MODE_REGEXP.test(flags) ? null : 0;

  fs.open(filepath, flags, mode, onOpen);

  function onOpen(openErr, fd) {
    if (openErr) {
      return onComplete(openErr);
    }

    fs.write(fd, data, 0, data.length, position, onComplete);

    function onComplete(writeErr) {
      callback(writeErr, fd);
    }
  }
}
155648
function parse_files(files, options) {
  let nodes = {
    // root section node
    '': {
      id: '',
      type: 'section',
      children: [],
      description: '',
      short_description: '',
      href: '#',
      root: true,
      file: '',
      line: 0
    }
  };

  files.forEach(file => {
    let fn = NDoc.parsers[path.extname(file)];

    if (!fn) return;

    /* eslint-disable no-console */
    console.info('Parsing file: ' + file);

    let file_nodes = fn(file, options);

    // TODO:  fail on name clash here as well -- as we might get name clash
    //        from different parsers, or even differnret files
    _.extend(nodes, file_nodes);
  });

  return nodes;
}
142298
function PersistOutNode(n) {
        RED.nodes.createNode(this,n);
        var node = this;

        node.name = n.name;
        node.storageNode = RED.nodes.getNode(n.storageNode);

        node.restore = function() {
            var msg = node.storageNode.getMessage(node.name);
            node.send(msg);
        };


        RED.events.on("nodes-started", node.restore);

        node.on("input", function(msg) {
            node.restore();
        });

        node.on('close', function(removed, done) {
            RED.events.removeListener("nodes-started", node.restore);
            done();
        });
    }