Write a file into the Toil jobstore.

    'existing' is a set of files retrieved as inputs from toil_get_file. This
    ensures they are mapped back as the same name if passed through.
487936
def write_file(writeFunc, index, existing, x):
    
    # Toil fileStore reference
    if x.startswith("toilfs:"):
        return x
    # File literal outputs with no path, we don't write these and will fail
    # with unsupportedRequirement when retrieving later with getFile
    elif x.startswith("_:"):
        return x
    else:
        x = existing.get(x, x)
        if x not in index:
            if not urlparse.urlparse(x).scheme:
                rp = os.path.realpath(x)
            else:
                rp = x
            try:
                index[x] = "toilfs:" + writeFunc(rp)
                existing[index[x]] = x
            except Exception as e:
                cwllogger.error("Got exception '%s' while copying '%s'", e, x)
                raise
        return index[x]
54186
def write_file(path, content, owner='root', group='root', perms=0o444):
    """"""
    uid = pwd.getpwnam(owner).pw_uid
    gid = grp.getgrnam(group).gr_gid
    # lets see if we can grab the file and compare the context, to avoid doing
    # a write.
    existing_content = None
    existing_uid, existing_gid, existing_perms = None, None, None
    try:
        with open(path, 'rb') as target:
            existing_content = target.read()
        stat = os.stat(path)
        existing_uid, existing_gid, existing_perms = (
            stat.st_uid, stat.st_gid, stat.st_mode
        )
    except Exception:
        pass
    if content != existing_content:
        log("Writing file {} {}:{} {:o}".format(path, owner, group, perms),
            level=DEBUG)
        with open(path, 'wb') as target:
            os.fchown(target.fileno(), uid, gid)
            os.fchmod(target.fileno(), perms)
            if six.PY3 and isinstance(content, six.string_types):
                content = content.encode('UTF-8')
            target.write(content)
        return
    # the contents were the same, but we might still need to change the
    # ownership or permissions.
    if existing_uid != uid:
        log("Changing uid on already existing content: {} -> {}"
            .format(existing_uid, uid), level=DEBUG)
        os.chown(path, uid, -1)
    if existing_gid != gid:
        log("Changing gid on already existing content: {} -> {}"
            .format(existing_gid, gid), level=DEBUG)
        os.chown(path, -1, gid)
    if existing_perms != perms:
        log("Changing permissions on existing content: {} -> {}"
            .format(existing_perms, perms), level=DEBUG)
        os.chmod(path, perms)
662232
def _list_existing(filesystem, glob, paths):
    
    globs = _constrain_glob(glob, paths)
    time_start = time.time()
    listing = []
    for g in sorted(globs):
        logger.debug('Listing %s', g)
        if filesystem.exists(g):
            listing.extend(filesystem.listdir(g))
    logger.debug('%d %s listings took %f s to return %d items',
                 len(globs), filesystem.__class__.__name__, time.time() - time_start, len(listing))
    return set(listing)
266579
public boolean exists() throws IOException {
        boolean exists = false;
        try {
            // force lookup again
            setFileHandle(null);
            exists = (getFileHandle() != null);
        } catch (FileNotFoundException e) {
            // do nothing
        }
        return exists;
    }
1366334
def uploadFile(uploadfunc, fileindex, existing, uf, skip_broken=False):
    

    if uf["location"].startswith("toilfs:") or uf["location"].startswith("_:"):
        return
    if uf["location"] in fileindex:
        uf["location"] = fileindex[uf["location"]]
        return
    if not uf["location"] and uf["path"]:
        uf["location"] = schema_salad.ref_resolver.file_uri(uf["path"])
    if uf["location"].startswith("file://") and not os.path.isfile(uf["location"][7:]):
        if skip_broken:
            return
        else:
            raise cwltool.errors.WorkflowException(
                "File is missing: %s" % uf["location"])
    uf["location"] = write_file(
        uploadfunc, fileindex, existing, uf["location"])
893087
def exists(self, record_key):
        
        ''' 
            
        '''
        
        title = '%s.exists' % self.__class__.__name__
    
    # validate inputs
        input_fields = {
            'record_key': record_key
        }
        for key, value in input_fields.items():
            object_title = '%s(%s=%s)' % (title, key, str(value))
            self.fields.validate(value, '.%s' % key, object_title)
    
    # construct path to file
        from os import path
        file_path = path.join(self.collection_folder, record_key)

    # validate existence of file
        if not path.exists(file_path):
            return False
        return True
182939
def Open(self):
    
    if not self._filename:
      raise ValueError('Missing filename.')

    if os.path.isfile(self._filename):
      raise IOError((
          'Unable to use an already existing file for output '
          '[{0:s}]').format(self._filename))

    options = {
        'constant_memory': True,
        'strings_to_urls': False,
        'strings_to_formulas': False,
        'default_date_format': self._timestamp_format}
    self._workbook = xlsxwriter.Workbook(self._filename, options)
    self._sheet = self._workbook.add_worksheet('Sheet')
    self._current_row = 0
393077
function exists(file) {
  try {
    fs.lstatSync(file);
    return true;
  } catch (e) {
    if (e.code === 'ENOENT' || e.code === 'ENOTDIR') {
      return false;
    } else {
      throw e;
    }
  }
}
989045
def _write(self, to_write):
        
        self._file.write(to_write.encode(self._encoding or
                                         self._default_encoding))
790974
function fileExists(file) {
    try {
        var targetStat = fs.statSync(file);
        if (targetStat.isDirectory() ) {
            throw new Error("File exists but it's a driectory: " + file);
        }
    }
    catch(err) {
        if (err.code == 'ENOENT') {         // No such file or directory
            return false;
        }
        else {
            throw err;
        }
    }
    return true;
}
769167
def write_to(filename)
      FileUtils.mkdir_p File.dirname(filename)

      PathUtils.atomic_write(filename) do |f|
        f.write source
      end

      nil
    end
485524
def check_existence(to_check, name, config_key=None, relative_to=None,
                    allow_undefined=False, allow_not_existing=False,
                    base_key='releaser'):
    """"""
    if allow_undefined and (to_check is None or to_check.lower() == 'none'):
        print("{: <14} -> {}UNDEFINED{}".format(name, WARNING_COLOR,
                                                RESET_COLOR))
        return
    else:
        if config_key is None:
            config_key = "{}.{}".format(base_key, name)
        my_check = Path(to_check).resolve()
        if my_check.exists() and relative_to is not None:
            printed_path = str(my_check.relative_to(relative_to))
            if printed_path != '.':
                printed_path = '.' + os.sep + printed_path
        else:
            printed_path = str(my_check)
        if my_check.exists() or allow_not_existing:
            print("{: <14} -> {}".format(name, printed_path))
            return
        else:
            raise FileNotFoundError("[{}ERROR{}] '{}', as given, doesn't "
                                    "exist. For configuration key '{}', was "
                                    "given: {}".format(ERROR_COLOR, RESET_COLOR,
                                                       name, config_key,
                                                       to_check))
733064
public function existingOnly()
    {
        $value = [
            'Filename' => $this->getFilename(),
            'Variant' => $this->getVariant(),
            'Hash' => $this->getHash()
        ];
        /** @var DBFile $file */
        $file = DBField::create_field('DBFile', $value);
        $file->setAllowGeneration(false);
        return $file;
    }
1323427
def existingDirectory(string):
    
    if not os.path.isdir(string):
        argparse.ArgumentTypeError('{} is not a valid directory.'.format(string))
    return string
177792
def ExistingFileOrNone(fname):
    """"""
    if os.path.isfile(fname):
        return fname
    elif fname.lower() == 'none':
        return None
    else:
        raise ValueError("%s must specify a valid file name or 'None'" % fname)
201215
def write(self, *a, **kw):
        
        fl = None
        try:
            self.file1.write(*a, **kw)
            self.file1.flush()
        except IOError:
            badFile, fl = 1, failure.Failure()

        try:
            self.file2.write(*a, **kw)
            self.file2.flush()
        except IOError:
            badFile, fl = 2, failure.Failure()

        if fl:
            out = self.file2 if badFile == 1 else self.file1
            out.write(str(fl) + '\n')
            out.flush()
            fl.raiseException()
963190
def new_file(self):
        

        file = self.get_untitled_file_name()
        LOGGER.debug("> Creating '{0}' file.".format(file))
        self.set_file(file, is_modified=False, is_untitled=True)
        self.__set_document_signals()
        return file