Create a virtual file from a description.  If `options` is a string or a buffer, it’s used as the path.  In all other cases, the options are passed through to `vfile()`.
355373
function toVFile(options) {
  if (typeof options === 'string' || buffer(options)) {
    options = {path: String(options)}
  }

  return vfile(options)
}
880681
function mkfile(path, options, realCallback) {
        var meta = {};
        var called;
        var callback = function (err) {
            if (called) {
                if (err) {
                    if (meta.stream) meta.stream.emit("error", err);
                    else console.error(err.stack);
                }
                else if (meta.stream) meta.stream.emit("saved");
                return;
            }
            called = true;
            return realCallback(err, meta);
        };

        if (options.stream && !options.stream.readable) {
            return callback(new TypeError("options.stream must be readable."));
        }

        // Pause the input for now since we're not ready to write quite yet
        var readable = options.stream;
        if (readable) {
            if (readable.pause) readable.pause();
            var buffer = [];
            readable.on("data", onData);
            readable.on("end", onEnd);
        }

        function onData(chunk) {
            buffer.push(["data", chunk]);
        }
        function onEnd() {
            buffer.push(["end"]);
        }
        function error(err) {
            resume();
            if (tempPath) {
                fs.unlink(tempPath, callback.bind(null, err));
            }
            else
                return callback(err);
        }
        
        function resume() {
            if (readable) {
                // Stop buffering events and playback anything that happened.
                readable.removeListener("data", onData);
                readable.removeListener("end", onEnd);

                buffer.forEach(function (event) {
                    readable.emit.apply(readable, event);
                });
                // Resume the input stream if possible
                if (readable.resume) readable.resume();
            }
        }
        
        var tempPath;
        var resolvedPath = "";

        mkdir();

        function mkdir() {
            if (options.parents) {
                mkdirP(dirname(path), {}, function(err) {
                    if (err) return error(err);
                    resolve();
                });
            }
            else {
                resolve();
            }
        }

        // Make sure the user has access to the directory and get the real path.
        function resolve() {
            resolvePath(path, function (err, _resolvedPath) {
                if (err) {
                    if (err.code !== "ENOENT") {
                        return error(err);
                    }
                    // If checkSymlinks is on we'll get an ENOENT when creating a new file.
                    // In that case, just resolve the parent path and go from there.
                    resolvePath(dirname(path), function (err, dir) {
                        if (err) return error(err);
                        resolvedPath = join(dir, basename(path));
                        createTempFile();
                    });
                    return;
                }
                
                resolvedPath = _resolvedPath;
                createTempFile();
            });
        }
        
        
        function createTempFile() {
            tempPath = tmpFile(dirname(resolvedPath), "." + basename(resolvedPath) + "-", "~");
            
            var mode = options.mode || umask & 0666;
            fs.stat(resolvedPath, function(err, stat) {
                if (err && err.code !== "ENOENT") return error(err);
                
                var uid = process.getuid ? process.getuid() : 0;
                var gid = process.getgid ? process.getgid() : 0;
                
                if (stat) {
                    mode = stat.mode & 0777;
                    uid = stat.uid;
                    gid = stat.gid;
                }

                // node 0.8.x adds a "wx" shortcut, but since it's not in 0.6.x we use the
                // longhand here.
                var flags = constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL;
                fs.open(tempPath, flags, mode, function (err, fd) {
                    if (err) return error(err);
                    
                    fs.fchown(fd, uid, gid, function(err) {
                        fs.close(fd);
                        if (err) return error(err);
                        
                        pipe(fs.WriteStream(tempPath, {
                            encoding: options.encoding || null,
                            mode: mode
                        }));
                    });
                });
            });
        }

        function pipe(writable) {
            var hadError;
            
            if (readable) {
                readable.pipe(writable);
            }
            else {
                writable.on('open', function () {
                    if (hadError) return;
                    meta.stream = writable;
                    callback();
                });
            }
            writable.on('error', function (err) {
                hadError = true;
                error(err);
            });
            writable.on('close', function () {
                if (hadError) return;
                swap();
            });

            resume();
        }
        
        function swap() {
            fs.rename(tempPath, resolvedPath, function (err) {
                if (err) return error(err);
                callback();
            });
        }
    }
859747
function createListener(virtualPath) {

  return function listener(req, res, next) {
    var paths = allPaths[virtualPath].slice();

    function processRequest(paths) {

      var physicalPath = paths.pop()
        , synchronizer = new Synchronizer()
        , uri = urlParser.parse(req.url).pathname
        , filename = "";

      if (virtualPath !== "/" && uri.indexOf(virtualPath) === 0) {
        uri = uri.substr(virtualPath.length, uri.length - virtualPath.length);
      }
      uri = (physicalPath || "") + uri;

      filename = fs.combine(process.cwd(), uri).replace(/\%20/gmi, ' ');

      if (cache[filename]) {
        console.log("\u001b[32mLoaded from Cache '" + filename + "\u001b[39m'");
        if (cache[filename] === 404) {
          res.writeHead(404, {"Content-Type": "text/plain"});
          res.write("Content not found");
          res.end();
        } else {
          if (req.headers["If-Modified-Since"] === cache[filename].since) {
            res.writeHead(304, {
              'Content-Type': mime.lookup(filename),
              'Last-Modified': cache[filename].since,
              //'If-Modified-Since': cache[filename].since,
              "Cache-Control": "max-age=31536000"
            });
            res.end();
          } else {
            res.writeHead(200, {
              'Content-Type': mime.lookup(filename),
              //'If-Modified-Since': cache[filename].since,
              'Last-Modified': cache[filename].since,
              "Cache-Control": "max-age=31536000"
            });
            res.write(cache[filename].data, "binary");
            res.end();
          }
        }
        return;
      }

      if (filename) {
        fs.readFile(filename, "binary", synchronizer.register("file"));
      }

      synchronizer.onfinish(function (err, data) {
        if (err) {
          if (paths.length > 0) {
            processRequest(paths);
          } else if (next) {
            next();
          } else {
            console.log("\u001b[31mStatic file not found '" + filename + "'\u001b[39m");
            cache[filename] = 404;
            res.writeHead(404, {"Content-Type": "text/plain"});
            res.write("Content not found");
            res.end();
          }
          return;
        }
        console.error("\u001b[31mLoaded static file '" + filename + "'\u001b[39m");
        cache[filename] = {
          data: data.file,
          since: new Date().toGMTString()
        };
        res.writeHead(200, {
          'Content-Type': mime.lookup(filename),
          //'If-Modified-Since': cache[filename].since,
          'Last-Modified': cache[filename].since,
          "Cache-Control": "max-age=31536000"
        });
        res.write(data.file, "binary");
        res.end();
        if (!settings.cacheEnabled) { cache[filename] = undefined; }
      });
    }

    processRequest(paths);
  };

}
107378
def from_project_path(cls, path):
        """"""
        path = vistir.compat.Path(path)
        if path.name == 'Pipfile':
            pipfile_path = path
            path = path.parent
        else:
            pipfile_path = path / 'Pipfile'
        pipfile_location = cls.normalize_path(pipfile_path)
        venv_path = path / '.venv'
        if venv_path.exists():
            if not venv_path.is_dir():
                possible_path = vistir.compat.Path(venv_path.read_text().strip())
                if possible_path.exists():
                    return cls(possible_path.as_posix())
            else:
                if venv_path.joinpath('lib').exists():
                    return cls(venv_path.as_posix())
        sanitized = re.sub(r'[ $`!*@"\\\r\n\t]', "_", path.name)[0:42]
        hash_ = hashlib.sha256(pipfile_location.encode()).digest()[:6]
        encoded_hash = base64.urlsafe_b64encode(hash_).decode()
        hash_fragment = encoded_hash[:8]
        venv_name = "{0}-{1}".format(sanitized, hash_fragment)
        return cls(cls.get_workon_home().joinpath(venv_name).as_posix())
716704
function writeExtensionFile(options) {
  return new Promise((resolve, reject) => {
    try {
      const {
        file,
        input,
        defaultContent,
        logNotFound,
        logEnd,
      } = options;
      const filePath = path.resolve(getExtensionsPath(), file);

      if (!input) {
        logger.warn(logNotFound);
        fs.writeFileSync(filePath, defaultContent, { flag: 'w+' });
        return resolve();
      }

      fs.writeFileSync(filePath, input, { flag: 'w+' });
      logger.log(logEnd);

      return resolve();
    } catch (e) {
      return reject(e);
    }
  });
}
167482
def save(self, path, verbose=False):
        
        path = os.path.realpath(path)
        if os.path.exists(path):
            if self.load_path and self.load_path == path:
                if verbose:
                    print "saving over previous suite..."
                for context_name in self.context_names:
                    self.context(context_name)  # load before dir deleted
                shutil.rmtree(path)
            else:
                raise SuiteError("Cannot save, path exists: %r" % path)

        contexts_path = os.path.join(path, "contexts")
        os.makedirs(contexts_path)

        # write suite data
        data = self.to_dict()
        filepath = os.path.join(path, "suite.yaml")
        with open(filepath, "w") as f:
            f.write(dump_yaml(data))

        # write contexts
        for context_name in self.context_names:
            context = self.context(context_name)
            context._set_parent_suite(path, context_name)
            filepath = self._context_path(context_name, path)
            if verbose:
                print "writing %r..." % filepath
            context.save(filepath)

        # create alias wrappers
        tools_path = os.path.join(path, "bin")
        os.makedirs(tools_path)
        if verbose:
            print "creating alias wrappers in %r..." % tools_path

        tools = self.get_tools()
        for tool_alias, d in tools.iteritems():
            tool_name = d["tool_name"]
            context_name = d["context_name"]

            data = self._context(context_name)
            prefix_char = data.get("prefix_char")

            if verbose:
                print ("creating %r -> %r (%s context)..."
                       % (tool_alias, tool_name, context_name))
            filepath = os.path.join(tools_path, tool_alias)

            create_forwarding_script(filepath,
                                     module="suite",
                                     func_name="_FWD__invoke_suite_tool_alias",
                                     context_name=context_name,
                                     tool_name=tool_name,
                                     prefix_char=prefix_char)
531603
function writeSync(description, options) {
  var file = vfile(description)
  fs.writeFileSync(
    path.resolve(file.cwd, file.path),
    file.contents || '',
    options
  )
}
801707
def create_with_virtualenv(self, interpreter, virtualenv_options):
        """"""
        args = ['virtualenv', '--python', interpreter, self.env_path]
        args.extend(virtualenv_options)
        if not self.pip_installed:
            args.insert(3, '--no-pip')
        try:
            helpers.logged_exec(args)
            self.env_bin_path = os.path.join(self.env_path, 'bin')
        except FileNotFoundError as error:
            logger.error('Virtualenv is not installed. It is needed to create a virtualenv with '
                         'a different python version than fades (got {})'.format(error))
            raise FadesError('virtualenv not found')
        except helpers.ExecutionError as error:
            error.dump_to_log(logger)
            raise FadesError('virtualenv could not be run')
        except Exception as error:
            logger.exception("Error creating virtualenv:  %s", error)
            raise FadesError('General error while running virtualenv')
407761
function startline(opt) {

  var options = opt || Object.create(null);

  // file
  var file;
  if (Boolean(options.file)) {
    file = require('path').resolve(String(options.file));
    if (!fs.existsSync(file)) {
      throw new Error('file does not exist');
    }
    if (!fs.statSync(file).isFile()) {
      throw new Error('path is not a file');
    }
  } else {
    throw new Error('"file" is required');
  }

  // clean
  var my = {
    file: file,
    encoding: options.encoding,
    flag: String(options.flag || 'r'),
    mode: Number(options.mode) || 444,
    autoClose: options.autoClose === false ? false : true,
    start: Number(options.start) || 0,
    end: Number(options.end),
    rc4: options.rc4,
    autokey: options.autokey,
    lodash: Boolean(options.autokey),
  };

  return new Startline(my);
}
409627
public static CreateObjectOptions objectOptionsFromFileOptions(CreateFileOptions options) {
    return new CreateObjectOptions(
        options.overwriteExisting(), options.getContentType(), options.getAttributes());
  }
1167533
def openSource(p, filetype=None):
    ''
    if not filetype:
        filetype = options.filetype
    if isinstance(p, str):
        if '://' in p:
            return openSource(UrlPath(p), filetype)  # convert to Path and recurse
        elif p == '-':
            return openSource(PathFd('-', vd().stdin), filetype)
        else:
            return openSource(Path(p), filetype)  # convert to Path and recurse
    elif isinstance(p, UrlPath):
        openfunc = 'openurl_' + p.scheme
        return getGlobals()[openfunc](p, filetype=filetype)
    elif isinstance(p, Path):
        if not filetype:
            filetype = p.suffix or 'txt'

        if os.path.isdir(p.resolve()):
            filetype = 'dir'

        openfunc = 'open_' + filetype.lower()
        if openfunc not in getGlobals():
            warning('no %s function' % openfunc)
            filetype = 'txt'
            openfunc = 'open_txt'
        vs = getGlobals()[openfunc](p)
    else:  # some other object
        status('unknown object type %s' % type(p))
        vs = None

    if vs:
        status('opening %s as %s' % (p.name, filetype))

    return vs
1200318
def create_default_file(cls, data=None, mode=None):
        """"""
        filepath = cls.get_default_filepath()
        if not filepath:
            return False

        filename = os.path.basename(filepath)
        config = read_file(get_data_path(), filename)

        # Find and replace data in default config
        data = data or {}
        for k, v in six.iteritems(data):
            v = v or ""
            config = re.sub(
                r"^(%(key)s) =[ ]*$" % {"key": k},
                "%(key)s = %(value)s" % {"key": k, "value": v},
                config,
                flags=re.MULTILINE,
            )

        dirpath = os.path.dirname(filepath)
        if not os.path.exists(dirpath):
            os.makedirs(dirpath)
        with click.open_file(filepath, "w+") as f:
            f.write(config)

        if mode is not None:
            os.chmod(filepath, mode)

        return True
473201
function (val, opts) {
    if (typeof val === 'function') {
      return new Snippet(val(this));
    }
    if (typeof val === 'string') {
      var str = utils.tryRead(val);
      var res = {content: null, options: opts || {}};
      if (str) {
        res.path = val;
        res.content = str.toString();
      } else {
        res.content = val;
      }
      return new Snippet(res);
    }
    if (val instanceof Snippet) {
      val.option(opts);
      return val;
    }
    if (typeof val === 'object') {
      val.options = extend({}, val.options, opts);
      return new Snippet(val);
    }
  }
1223276
def make_path_properties(file_or_path, prefix=''):
    """"""
    is_std = file_or_path in (sys.stdin, sys.stdout, sys.stderr)

    if is_std:
        path = '-'
    elif is_filelike(file_or_path):
        try:
            path = str(file_or_path.name)
        except AttributeError:
            path = None
    else:
        path = str(file_or_path)

    if is_std or not path:
        abspath = dirname = basename = stem = ext = None
        realpath = realdrive = realdir = realbase = realstem = realext = None
        numbers = num = None
    else:
        abspath = os.path.abspath(path)

        dirname, basename = os.path.split(path)
        stem, ext = os.path.splitext(basename)

        if not dirname:
            dirname = os.curdir

        realpath = os.path.realpath(path)
        realdrive, tail = os.path.splitdrive(realpath)
        realdir, realbase = os.path.split(tail)
        realstem, realext = os.path.splitext(realbase)

        numbers = [int(s) for s in re.findall(r'\d+', basename)]
        num = numbers[-1] if numbers else None

    return {
            prefix + 'path':      path,
            prefix + 'abspath':   abspath,
            prefix + 'dirname':   dirname,
            prefix + 'basename':  basename,
            prefix + 'stem':      stem,
            prefix + 'ext':       ext,
            prefix + 'realpath':  realpath,
            prefix + 'realdrive': realdrive,
            prefix + 'realdir':   realdir,
            prefix + 'realbase':  realbase,
            prefix + 'realstem':  realstem,
            prefix + 'realext':   realext,
            prefix + 'numbers':   numbers,
            prefix + 'num':       num,
        }
291846
def create_file(filename):
    

    expanded_filename = os.path.expanduser(os.path.expandvars(filename))
    if not os.path.exists(expanded_filename):
        open(expanded_filename, "a").close()
895643
def open(self, file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):
        
        urn = Urn(file)
        urn_path = urn.path()

        remote_file_exists = self.check(urn_path)

        if not remote_file_exists:
            if 'r' in mode:
                raise RemoteResourceNotFound(urn_path)
        elif self.is_dir(urn_path):
            raise OptionNotValid(name='file', value=file)

        with tempfile.TemporaryDirectory() as temp_dir:
            local_path = f'{temp_dir}{os.path.sep}{file}'

            if remote_file_exists:
                self.download_file(file, local_path)
            else:
                if ('w' in mode or 'a' in mode or 'x' in mode) and os.path.sep in local_path:
                    os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True)

            with open(file=local_path, mode=mode, buffering=buffering, encoding=encoding, errors=errors,
                      newline=newline, closefd=closefd, opener=opener) as f:
                yield f

            if 'w' in mode or 'a' in mode or 'x' in mode:
                self.upload_file(file, local_path)
999538
def make_file(abspath, text):
    
    try:
        with open(abspath, "wb") as f:
            f.write(text.encode("utf-8"))
        print("Made: %s" % abspath)
    except:  # pragma: no cover
        pass