Instruction:
Can you create a Python 3 function that
downloads a file from the remote system to the local filesystem.

Response:
def get(self, remote, local=None, preserve_mode=True):
        """
        Download a file from the current connection to the local filesystem.

        :param str remote:
            Remote file to download.

            May be absolute, or relative to the remote working directory.

            .. note::
                Most SFTP servers set the remote working directory to the
                connecting user's home directory, and (unlike most shells) do
                *not* expand tildes (``~``).

                For example, instead of saying ``get("~/tmp/archive.tgz")``,
                say ``get("tmp/archive.tgz")``.

        :param local:
            Local path to store downloaded file in, or a file-like object.

            **If None or another 'falsey'/empty value is given** (the default),
            the remote file is downloaded to the current working directory (as
            seen by `os.getcwd`) using its remote filename.

            **If a string is given**, it should be a path to a local directory
            or file and is subject to similar behavior as that seen by common
            Unix utilities or OpenSSH's ``sftp`` or ``scp`` tools.

            For example, if the local path is a directory, the remote path's
            base filename will be added onto it (so ``get('foo/bar/file.txt',
            '/tmp/')`` would result in creation or overwriting of
            ``/tmp/file.txt``).

            .. note::
                When dealing with nonexistent file paths, normal Python file
                handling concerns come into play - for example, a ``local``
                path containing non-leaf directories which do not exist, will
                typically result in an `OSError`.

            **If a file-like object is given**, the contents of the remote file
            are simply written into it.

        :param bool preserve_mode:
            Whether to `os.chmod` the local file so it matches the remote
            file's mode (default: ``True``).

        :returns: A `.Result` object.

        .. versionadded:: 2.0
        """
        # TODO: how does this API change if we want to implement
        # remote-to-remote file transfer? (Is that even realistic?)
        # TODO: handle v1's string interpolation bits, especially the default
        # one, or at least think about how that would work re: split between
        # single and multiple server targets.
        # TODO: callback support
        # TODO: how best to allow changing the behavior/semantics of
        # remote/local (e.g. users might want 'safer' behavior that complains
        # instead of overwriting existing files) - this likely ties into the
        # "how to handle recursive/rsync" and "how to handle scp" questions

        # Massage remote path
        if not remote:
            raise ValueError("Remote path must not be empty!")
        orig_remote = remote
        remote = posixpath.join(
            self.sftp.getcwd() or self.sftp.normalize("."), remote
        )

        # Massage local path:
        # - handle file-ness
        # - if path, fill with remote name if empty, & make absolute
        orig_local = local
        is_file_like = hasattr(local, "write") and callable(local.write)
        if not local:
            local = posixpath.basename(remote)
        if not is_file_like:
            local = os.path.abspath(local)

        # Run Paramiko-level .get() (side-effects only. womp.)
        # TODO: push some of the path handling into Paramiko; it should be
        # responsible for dealing with path cleaning etc.
        # TODO: probably preserve warning message from v1 when overwriting
        # existing files. Use logging for that obviously.
        #
        # If local appears to be a file-like object, use sftp.getfo, not get
        if is_file_like:
            self.sftp.getfo(remotepath=remote, fl=local)
        else:
            self.sftp.get(remotepath=remote, localpath=local)
            # Set mode to same as remote end
            # TODO: Push this down into SFTPClient sometime (requires backwards
            # incompat release.)
            if preserve_mode:
                remote_mode = self.sftp.stat(remote).st_mode
                mode = stat.S_IMODE(remote_mode)
                os.chmod(local, mode)
        # Return something useful
        return Result(
            orig_remote=orig_remote,
            remote=remote,
            orig_local=orig_local,
            local=local,
            connection=self.connection,
        )


Instruction:
Can you tell what is the following Python 3 function doing
def put(self, local, remote=None, preserve_mode=True):
        if not local:
            raise ValueError("Local path must not be empty!")

        is_file_like = hasattr(local, "write") and callable(local.write)

        # Massage remote path
        orig_remote = remote
        if is_file_like:
            local_base = getattr(local, "name", None)
        else:
            local_base = os.path.basename(local)
        if not remote:
            if is_file_like:
                raise ValueError(
                    "Must give non-empty remote path when local is a file-like object!"  # noqa
                )
            else:
                remote = local_base
                debug("Massaged empty remote path into {!r}".format(remote))
        elif self.is_remote_dir(remote):
            # non-empty local_base implies a) text file path or b) FLO which
            # had a non-empty .name attribute. huzzah!
            if local_base:
                remote = posixpath.join(remote, local_base)
            else:
                if is_file_like:
                    raise ValueError(
                        "Can't put a file-like-object into a directory unless it has a non-empty .name attribute!"  # noqa
                    )
                else:
                    # TODO: can we ever really end up here? implies we want to
                    # reorganize all this logic so it has fewer potential holes
                    raise ValueError(
                        "Somehow got an empty local file basename ({!r}) when uploading to a directory ({!r})!".format(  # noqa
                            local_base, remote
                        )
                    )

        prejoined_remote = remote
        remote = posixpath.join(
            self.sftp.getcwd() or self.sftp.normalize("."), remote
        )
        if remote != prejoined_remote:
            msg = "Massaged relative remote path {!r} into {!r}"
            debug(msg.format(prejoined_remote, remote))

        # Massage local path
        orig_local = local
        if not is_file_like:
            local = os.path.abspath(local)
            if local != orig_local:
                debug(
                    "Massaged relative local path {!r} into {!r}".format(
                        orig_local, local
                    )
                )  # noqa

        # Run Paramiko-level .put() (side-effects only. womp.)
        # TODO: push some of the path handling into Paramiko; it should be
        # responsible for dealing with path cleaning etc.
        # TODO: probably preserve warning message from v1 when overwriting
        # existing files. Use logging for that obviously.
        #
        # If local appears to be a file-like object, use sftp.putfo, not put
        if is_file_like:
            msg = "Uploading file-like object {!r} to {!r}"
            debug(msg.format(local, remote))
            pointer = local.tell()
            try:
                local.seek(0)
                self.sftp.putfo(fl=local, remotepath=remote)
            finally:
                local.seek(pointer)
        else:
            debug("Uploading {!r} to {!r}".format(local, remote))
            self.sftp.put(localpath=local, remotepath=remote)
            # Set mode to same as local end
            # TODO: Push this down into SFTPClient sometime (requires backwards
            # incompat release.)
            if preserve_mode:
                local_mode = os.stat(local).st_mode
                mode = stat.S_IMODE(local_mode)
                self.sftp.chmod(remote, mode)
        # Return something useful
        return Result(
            orig_remote=orig_remote,
            remote=remote,
            orig_local=orig_local,
            local=local,
            connection=self.connection,
        )

Response: Uploads a file from the local filesystem to the remote system.


Instruction:
How would you explain what the following Python 3 function does
def load_ssh_config(self):
        # Update the runtime SSH config path (assumes enough regular config
        # levels have been loaded that anyone wanting to transmit this info
        # from a 'vanilla' Invoke config, has gotten it set.)
        if self.ssh_config_path:
            self._runtime_ssh_path = self.ssh_config_path
        # Load files from disk if we weren't given an explicit SSHConfig in
        # __init__
        if not self._given_explicit_object:
            self._load_ssh_files()

Response: Load the SSH config files from disk.


Instruction:
Can you generate the documentation for the following Python 3 function
def _load_ssh_files(self):
        # TODO: does this want to more closely ape the behavior of
        # InvokeConfig.load_files? re: having a _found attribute for each that
        # determines whether to load or skip
        if self._runtime_ssh_path is not None:
            path = self._runtime_ssh_path
            # Manually blow up like open() (_load_ssh_file normally doesn't)
            if not os.path.exists(path):
                msg = "No such file or directory: {!r}".format(path)
                raise IOError(errno.ENOENT, msg)
            self._load_ssh_file(os.path.expanduser(path))
        elif self.load_ssh_configs:
            for path in (self._user_ssh_path, self._system_ssh_path):
                self._load_ssh_file(os.path.expanduser(path))

Response: Loads the SSH config files for the current instance of an anatomical class.


Instruction:
Can you tell what is the following Python 3 function doing
def _load_ssh_file(self, path):
        if os.path.isfile(path):
            old_rules = len(self.base_ssh_config._config)
            with open(path) as fd:
                self.base_ssh_config.parse(fd)
            new_rules = len(self.base_ssh_config._config)
            msg = "Loaded {} new ssh_config rules from {!r}"
            debug(msg.format(new_rules - old_rules, path))
        else:
            debug("File not found, skipping")

Response: Attempts to open and parse an SSH config file at path.


Instruction:
Create a Python 3 function for
defaulting configuration values and behavior toggles. Fabric only extends this method in order to make minor adjustments and additions to Invoke's `~invoke.config.Config.global_defaults`; see its documentation for the base values, such as the config subtrees controlling behavior of ``run`` or how ``tasks`` behave. For Fabric-specific modifications and additions to the Invoke-level defaults, see our own config docs at :ref:`default-values`. .. versionadded:: 2.0

Response:
def global_defaults():
        """
        Default configuration values and behavior toggles.

        Fabric only extends this method in order to make minor adjustments and
        additions to Invoke's `~invoke.config.Config.global_defaults`; see its
        documentation for the base values, such as the config subtrees
        controlling behavior of ``run`` or how ``tasks`` behave.

        For Fabric-specific modifications and additions to the Invoke-level
        defaults, see our own config docs at :ref:`default-values`.

        .. versionadded:: 2.0
        """
        # TODO: hrm should the run-related things actually be derived from the
        # runner_class? E.g. Local defines local stuff, Remote defines remote
        # stuff? Doesn't help with the final config tree tho...
        # TODO: as to that, this is a core problem, Fabric wants split
        # local/remote stuff, eg replace_env wants to be False for local and
        # True remotely; shell wants to differ depending on target (and either
        # way, does not want to use local interrogation for remote)
        # TODO: is it worth moving all of our 'new' settings to a discrete
        # namespace for cleanliness' sake? e.g. ssh.port, ssh.user etc.
        # It wouldn't actually simplify this code any, but it would make it
        # easier for users to determine what came from which library/repo.
        defaults = InvokeConfig.global_defaults()
        ours = {
            # New settings
            "connect_kwargs": {},
            "forward_agent": False,
            "gateway": None,
            "load_ssh_configs": True,
            "port": 22,
            "run": {"replace_env": True},
            "runners": {"remote": Remote},
            "ssh_config_path": None,
            "tasks": {"collection_name": "fabfile"},
            # TODO: this becomes an override/extend once Invoke grows execution
            # timeouts (which should be timeouts.execute)
            "timeouts": {"connect": None},
            "user": get_local_user(),
        }
        merge_dicts(defaults, ours)
        return defaults