/*
recursively and synchronously visits the directory and all subdirectories and zips all files it finds
@param dir {String}: the path to the subdirectory
@param zipped_dir {JSZip}: the JSZip object with the new directory as root
346168
function zip_dir_sync(dir, zipped_dir) {

    var entries = fs.readdirSync(dir);
    var entries_count = entries.length;

    for(var i = 0; i < entries_count; i++) {
        var entry = entries[i];
        var entry_normalized_path = path.normalize(dir + path.sep + entry);
        var entry_stats = fs.statSync(entry_normalized_path);

        if(entry_stats.isDirectory()) {

            var new_zipped_dir = zipped_dir.folder(entry);

            // recursively zip the newly found dir
            zip_dir_sync(entry_normalized_path, new_zipped_dir);
        }
        else {

            var file = fs.readFileSync(entry_normalized_path);

            // zip the file within current subdir
            zipped_dir.file(entry, file);
        }
    }
}
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());
                    }
                }
            }
        });
    }
127951
public void processZips(File[] zipFiles, File destDir) throws IOException {
        for (int i = 0; i < zipFiles.length; i++) {
            processFile(zipFiles[i], destDir);
        }
    }
1030151
function createZip (targetZipPath, currentFolder, filesToInclude, done) {
  const args = ['-FS', targetZipPath].concat(filesToInclude)
  const startTime = Date.now()
  trace(`Calling: zip ${args.join(' ')}`)
  const child = childProcess.spawn('zip', args, {
    cwd: currentFolder,
    stdio: [ 'ignore', 'ignore', 'ignore' ]
  })
  child.on('error', (err) => {
    error(`Error: please verify that <zip> is installed on your system`)
    error(err.toString())
  })
  child.on('close', (code, signal) => {
    const elapsed = Math.floor(Date.now() - startTime)
    debug(`Zip exited with code ${code} in ${elapsed}ms`)
    done(code === 0 ? null : new Error(`Error creating ZIP file ${targetZipPath}`))
  })
}
76477
def write(inputDir, outputFile)
      entries = Dir.entries(inputDir); entries.delete("."); entries.delete("..")
      io = Zip::File.open(outputFile, Zip::File::CREATE);

      writeEntries(entries, "", io, inputDir)
      io.close();
    end
333448
function(dir) {
  var methods = [];

  var findConfigFiles = function(dir) {
    fs.readdirSync(dir).forEach(function(file) {
      file = path.join(dir, file);
      var stat = fs.statSync(file);
      if(stat && stat.isDirectory()) {
        findConfigFiles(file);
      } else if(/config.js$/.test(file)) {
        methods.push(file);
      }
    });
  };

  findConfigFiles(dir);

  return methods;
}
766130
private static void extractDirectory(ZipEntry entry, File dir) throws IOException {
		final String sourceMethod = "extractFile"; //$NON-NLS-1$
		final boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(sourceClass, sourceMethod, new Object[]{entry, dir});
		}

		dir.mkdir();	// May fail if the directory has already been created
		if (!dir.setLastModified(entry.getTime())) {
			throw new IOException("Failed to set last modified time for " + dir.getAbsolutePath()); //$NON-NLS-1$
		}

		if (isTraceLogging) {
			log.exiting(sourceClass, sourceMethod);
		}
	}
907476
function recursiveMkDir(dir) {
    if (!fs.existsSync(dir)) {
        recursiveMkDir(path.dirname(dir));
        fs.mkdirSync(dir);
    }
}
450581
private static void processZipStream(File dir, InputStream inputStream) throws IOException
   {
      ZipInputStream zip = new ZipInputStream(inputStream);
      while (true)
      {
         ZipEntry entry = zip.getNextEntry();
         if (entry == null)
         {
            break;
         }

         File file = new File(dir, entry.getName());
         if (entry.isDirectory())
         {
            FileHelper.mkdirsQuietly(file);
            continue;
         }

         File parent = file.getParentFile();
         if (parent != null)
         {
            FileHelper.mkdirsQuietly(parent);
         }

         FileOutputStream fos = new FileOutputStream(file);
         byte[] bytes = new byte[1024];
         int length;
         while ((length = zip.read(bytes)) >= 0)
         {
            fos.write(bytes, 0, length);
         }
         fos.close();
      }
   }
256667
def zip_dir(directory):
    """"""
    result = io.BytesIO()
    dlen = len(directory)
    with ZipFile(result, "w") as zf:
        for root, dirs, files in os.walk(directory):
            for name in files:
                full = os.path.join(root, name)
                rel = root[dlen:]
                dest = os.path.join(rel, name)
                zf.write(full, dest)
    return result
802499
function mkdirp(con, p, callback) {
  p = path.normalize(p);
  var dirs = p.split('/').slice(1); // remove empty string at the start.

  // console.log('dirs', dirs);

  var tasks = [];
  dirs.forEach(function(dir, i) {
    var subpath = '/' + dirs.slice(0, i).join('/') + '/' + dir;
    subpath = path.normalize(subpath); // remove extra `/` in first iteration
    tasks.push(async.apply(create, con, subpath));
  });
  async.waterfall(tasks, function(err, results) {
    if(err) return callback(err);
    // succeeded!
    return callback(null, true);
  });
}
302494
function addAllFilesAndSubdirectories(dir, doneCallback) {
            FileSystem.resolve(dir, function (err, directory) {
                function visitor(entry) {
                    if (entry.isFile) {
                        if (!isFileExcluded(entry)) { // ignore .dotfiles and non-.js files
                            addFilesToTern([entry.fullPath]);
                        }
                    } else {
                        return !isDirectoryExcluded(entry.fullPath) &&
                            entry.name.indexOf(".") !== 0 &&
                            !stopAddingFiles;
                    }
                }

                if (err) {
                    return;
                }

                if (dir === FileSystem.getDirectoryForPath(rootTernDir)) {
                    doneCallback();
                    return;
                }

                directory.visit(visitor, doneCallback);
            });
        }
574456
def pack(dir, zipfile)
      files = files_to_pack(dir)
      return false if files.empty?

      ::Zip::ZipFile.open(zipfile, true) do |zf|
        files.each do |f|
          zf.add(f.sub("#{dir}/",''), f)
        end
      end

      true
    end
197924
def zip(filename, paths, strip_prefix=''):
    
    if isinstance(paths, basestring):
        paths = [paths]

    filelist = set()
    for p in paths:
        if os.path.isfile(p):
            filelist.add(p)
        else:
            for root, dirs, files in os.walk(p):
                for f in files:
                    filelist.add(os.path.join(root, f))

    z = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED)
    for f in sorted(filelist):
        arcname = f
        if arcname.startswith(strip_prefix):
            arcname = arcname[len(strip_prefix):]
        if arcname.startswith(os.path.sep):
            arcname = arcname[1:]
        log.debug('Adding %s to %s[%s]', f, filename, arcname)
        z.write(f, arcname)

    z.close()
1162083
private void addDirectoryToZip(File topDirectory, File directory, ZipOutputStream out) throws IOException {
    Path top = Paths.get(topDirectory.getAbsolutePath());

    File[] files = directory.listFiles();
    byte[] buffer = new byte[BUFFER_SIZE];

    for (int i = 0; i < files.length; i++) {
      Path entry = Paths.get(files[i].getAbsolutePath());
      Path relative = top.relativize(entry);
      String entryName = relative.toString();
      if (files[i].isDirectory()) {
        entryName += FILE_SEPARATOR;
      }

      out.putNextEntry(new ZipEntry(entryName.replace("\\", "/")));

      if (!files[i].isDirectory()) {
        try (FileInputStream in = new FileInputStream(files[i])) {
          int bytesRead;
          while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
          }
        }
        out.closeEntry();
      }

      if (files[i].isDirectory()) {
        addDirectoryToZip(topDirectory, files[i], out);
      }
    }
  }
1266553
function dirParseSync(startDir, result) {
    var files;
    var i;
    var tmpPath;
    var currFile;

    // initialize the `result` object if it is the first iteration
    if (result === undefined) {
      result = {};
      result[localSep] = [];
    }

    // check if `startDir` is a valid location
    if (!fs.existsSync(startDir)) {
      grunt.warn(startDir + ' is not an existing location');
    }

    // iterate throught the contents of the `startDir` location of the current iteration
    files = fs.readdirSync(startDir);
    for (i = 0; i < files.length; i++) {
      currFile = startDir + localSep + files[i];
      if (!file.isMatch({matchBase: true}, exclusions, currFile)) {
        if (file.isDir(currFile)) {
          tmpPath = path.relative(localRoot, startDir + localSep + files[i]);
          if (!_.has(result, tmpPath)) {
            result[tmpPath] = [];
          }
          dirParseSync(currFile, result);
        } else {
          tmpPath = path.relative(localRoot, startDir);
          if (!tmpPath.length) {
            tmpPath = localSep;
          }
          result[tmpPath].push(files[i]);
        }
      }
    }

    return result;
  }
220390
public static void compress(File dir, File zipFile) throws IOException {

    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    recursiveAddZip(dir, zos, dir);

    zos.finish();
    zos.close();

  }