Send recursive dir listing
324867
function handleDir(fs, path, res) {
  var sh = new fs.Shell();

  sh.ls(path, {recursive: true}, function(err, listing) {
    if(err) {
      log.error(err, 'Unable to get listing for path `%s`', path);
      handle404(path, res);
      return;
    }
    write(listing, res);
  });
}
1084184
def dirs(self, *args, **kwargs):
        
        return [p for p in self.listdir(*args, **kwargs) if p.isdir()]
1345435
def dir(cls, label, children):
        """"""
        return FSEntry(label=label, children=children, type=u"Directory", use=None)
1203091
private void sendDirectory(final YokeRequest request, final String dir, final Handler<Object> next) {
        final FileSystem fileSystem = vertx().fileSystem();

        fileSystem.readDir(dir, new AsyncResultHandler<List<String>>() {
            @Override
            public void handle(AsyncResult<List<String>> asyncResult) {
                if (asyncResult.failed()) {
                    next.handle(asyncResult.cause());
                } else {
                    String accept = request.getHeader("accept", "text/plain");

                    if (accept.contains("html")) {
                        String normalizedDir = dir.substring(root.length());
                        if (!normalizedDir.endsWith("/")) {
                            normalizedDir += "/";
                        }

                        String file;
                        StringBuilder files = new StringBuilder("<ul id=\"files\">");

                        for (String s : asyncResult.result()) {
                            file = s.substring(s.lastIndexOf('/') + 1);
                            // skip dot files
                            if (!includeHidden && file.charAt(0) == '.') {
                                continue;
                            }
                            files.append("<li><a href=\"");
                            files.append(normalizedDir);
                            files.append(file);
                            files.append("\" title=\"");
                            files.append(file);
                            files.append("\">");
                            files.append(file);
                            files.append("</a></li>");
                        }

                        files.append("</ul>");

                        StringBuilder directory = new StringBuilder();
                        // define access to root
                        directory.append("<a href=\"/\">/</a> ");

                        StringBuilder expandingPath = new StringBuilder();
                        String[] dirParts = normalizedDir.split("/");
                        for (int i = 1; i < dirParts.length; i++) {
                            // dynamic expansion
                            expandingPath.append("/");
                            expandingPath.append(dirParts[i]);
                            // anchor building
                            if (i > 1) {
                                directory.append(" / ");
                            }
                            directory.append("<a href=\"");
                            directory.append(expandingPath.toString());
                            directory.append("\">");
                            directory.append(dirParts[i]);
                            directory.append("</a>");
                        }

                        request.response().setContentType("text/html");
                        request.response().end(
                                directoryTemplate.replace("{title}", (String) request.get("title")).replace("{directory}", normalizedDir)
                                        .replace("{linked-path}", directory.toString())
                                        .replace("{files}", files.toString()));
                    } else if (accept.contains("json")) {
                        String file;
                        JsonArray json = new JsonArray();

                        for (String s : asyncResult.result()) {
                            file = s.substring(s.lastIndexOf('/') + 1);
                            // skip dot files
                            if (!includeHidden && file.charAt(0) == '.') {
                                continue;
                            }
                            json.add(file);
                        }

                        request.response().end(json);
                    } else {
                        String file;
                        StringBuilder buffer = new StringBuilder();

                        for (String s : asyncResult.result()) {
                            file = s.substring(s.lastIndexOf('/') + 1);
                            // skip dot files
                            if (!includeHidden && file.charAt(0) == '.') {
                                continue;
                            }
                            buffer.append(file);
                            buffer.append('\n');
                        }

                        request.response().setContentType("text/plain");
                        request.response().end(buffer.toString());
                    }
                }
            }
        });
    }
1289263
def send_request(cls, sock, working_dir, command, *arguments, **environment):
    """"""
    for argument in arguments:
      cls.write_chunk(sock, ChunkType.ARGUMENT, argument)

    for item_tuple in environment.items():
      cls.write_chunk(sock,
                      ChunkType.ENVIRONMENT,
                      cls.ENVIRON_SEP.join(cls._decode_unicode_seq(item_tuple)))

    cls.write_chunk(sock, ChunkType.WORKING_DIR, working_dir)
    cls.write_chunk(sock, ChunkType.COMMAND, command)
480611
function listDir (path, originalPath) {
  if (!originalPath) {
    originalPath = path + separator;
  }

  // promises for sub listDir calls
  var dirs = [];

  return Promise.resolve(fs.readdir(path))
    // include only files
    .filter(function (item) {
      var absolutePath = join(path, item);

      return fs.stat(absolutePath).then(function (stat) {
        var isDirectory = stat.isDirectory();

        // if directory, read it
        if (isDirectory) {
          var list = listDir(absolutePath, originalPath);

          dirs.push(list);
        }

        return !isDirectory;
      });
    })
    // return relative paths
    .map(function (file) {
      var absolutePath = join(path, file);
      var relativePath = absolutePath.replace(originalPath, '');

      return relativePath;
    })
    // add files from sub-directories
    .then(function (files) {
      // wait for all listDir() to complete
      // and merge their results
      return Promise
        .all(dirs)
        .then(function () {
          dirs.forEach(function (promise) {
            var subFiles = promise.value();

            files = files.concat(subFiles);
          });

          return files;
        });
    });
}
1127455
function list(context, err, items, paths) {
    if (err) return fail(context, err);
    
    var long = context.options["l"];
    
    if (typeof long === "undefined") long = (context.command.slice(-3) === "dir");
    
    items.forEach(function (item) {
        if (item.filename == "." || item.filename == "..") return;
        
        if (paths) {
            shell.write(item.path);
        } else if (long) {
            shell.write(item.longname);
        } else {
            shell.write(item.filename);
        }
    });
    
    context.end();
}
188013
def ListDirectory(self, pathspec, depth=0):
    """"""
    # Limit recursion depth
    if depth >= self.request.max_depth:
      return

    try:
      fd = vfs.VFSOpen(pathspec, progress_callback=self.Progress)
      files = fd.ListFiles(ext_attrs=self.request.collect_ext_attrs)
    except (IOError, OSError) as e:
      if depth == 0:
        # We failed to open the directory the server asked for because dir
        # doesn't exist or some other reason. So we set status and return
        # back to the caller ending the Iterator.
        self.SetStatus(rdf_flows.GrrStatus.ReturnedStatus.IOERROR, e)
      else:
        # Can't open the directory we're searching, ignore the directory.
        logging.info("Find failed to ListDirectory for %s. Err: %s", pathspec,
                     e)
      return

    # If we are not supposed to cross devices, and don't know yet
    # which device we are on, we need to find out.
    if not self.request.cross_devs and self.filesystem_id is None:
      dir_stat = fd.Stat()
      self.filesystem_id = dir_stat.st_dev

    for file_stat in files:

      if stat.S_ISDIR(int(file_stat.st_mode)):
        # Do not traverse directories in a different filesystem.
        is_same_fs = self.filesystem_id == file_stat.st_dev
        if is_same_fs or self.request.cross_devs:
          for child_stat in self.ListDirectory(file_stat.pathspec, depth + 1):
            yield child_stat

      yield file_stat
894374
function recursiveReaddirSync(path) {
  var list = []
    , files = fs.readdirSync(path)
    , stats
    ;

  files.forEach(function (file) {
    stats = fs.lstatSync(p.join(path, file));
    if(stats.isDirectory()) {
      list = list.concat(recursiveReaddirSync(p.join(path, file)));
    } else {
      list.push(p.join(path, file));
    }
  });

  return list;
}
1368402
function sendDirectToUser(content, username) {
    return getDirectMessageRoomId(username)
        .then((rid) => sendToRoomId(content, rid));
}
306352
function directoryHTML( res, urldir, pathname, list ) {
    var ulist = [];
    function sendHTML( list ) {
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        res.send('<!DOCTYPE html>' +
        '<html>\n' +
        '<title>Directory listing for '+htmlsafe(urldir)+'</title>\n' +
        '<body>\n' +
        '<h2>Directory listing for '+htmlsafe(urldir)+'</h2>\n' +
        '<hr><ul>\n' +
        list.join('\n') +
        '</ul><hr>\n' +
        '</body>\n' +
        '</html>');
    }

    if ( !list.length ) {
        // Nothing to resolve
        return sendHTML( ulist );
    }

    // Check for each file if it's a directory or a file
    var q = async.queue(function(item, cb) {
        fs.stat(path.join(pathname, item), function(err, stat) {
            if ( !stat ) cb();
            var link = escape(item);
            item = htmlsafe(item);
            if ( stat.isDirectory() ) {
                ulist.push('<li><a href="'+link+'/">'+item+'/</a></li>')
            } else {
                ulist.push('<li><a href="'+link+'">'+item+'</a></li>')
            }
            cb();
        });
    }, 4);
    list.forEach(function(item) {
        q.push(item);
    });
    q.drain = function() {
        // Finished checking files, send the response
        sendHTML(ulist);
    };
}
182741
def listdir(self, path, **kwargs):
        """"""
        statuses = self.list_status(path, **kwargs)
        if len(statuses) == 1 and statuses[0].pathSuffix == '' and statuses[0].type == 'FILE':
            raise NotADirectoryError('Not a directory: {!r}'.format(path))
        return [f.pathSuffix for f in statuses]
180436
def rmdir(path, recursive=True, **kwargs):
    """"""
    if recursive:
        import shutil
        return shutil.rmtree(path, **kwargs)
    else:
        import os
        return os.remdir(path, **kwargs)
71604
def recursively_get_files_from_directory(directory):
    
    return [
        os.path.join(root, filename)
        for root, directories, filenames in os.walk(directory)
        for filename in filenames
    ]
1046949
def dir_list(self, saltenv='base', prefix=''):
        '''
        
        '''
        load = {'saltenv': saltenv,
                'prefix': prefix,
                'cmd': '_dir_list'}
        return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \
            else self.channel.send(load)
309876
public function rawlistDirectory($parameters, $recursive = false)
    {
        $result = @ftp_rawlist($this->connection, $parameters, $recursive);

        if ($result === false) {
            throw new Exception('Unable to list directory');
        }

        return $result;
    }
901427
def _serve_dir(self, abspath, params):
    """"""
    relpath = os.path.relpath(abspath, self._root)
    breadcrumbs = self._create_breadcrumbs(relpath)
    entries = [{'link_path': os.path.join(relpath, e), 'name': e} for e in os.listdir(abspath)]
    args = self._default_template_args('dir.html')
    args.update({'root_parent': os.path.dirname(self._root),
                 'breadcrumbs': breadcrumbs,
                 'entries': entries,
                 'params': params})
    content = self._renderer.render_name('base.html', args).encode("utf-8")
    self._send_content(content, 'text/html')