instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings that explain logic
import random import time from rich.markup import escape from textual.app import ComposeResult from textual.reactive import reactive from textual.widgets import Static, RichLog from textual.containers import Vertical, Container from ..helpers import classify_ec from .translator import T, TRANSLATOR class StatusPane...
--- +++ @@ -1,3 +1,6 @@+""" +Borg Cockpit - UI Widgets. +""" import random import time @@ -107,6 +110,7 @@ self.query_one("#status-elapsed").update(msg) def refresh_ui_labels(self): + """Update static UI labels with current translation.""" self.watch_elapsed_time(self.elapsed_time) ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/cockpit/widgets.py
Create documentation strings for testing functions
import os import time from pathlib import Path from xxhash import xxh64 from borgstore.store import Store from borgstore.store import ObjectNotFound as StoreObjectNotFound from borgstore.backends.errors import BackendError as StoreBackendError from borgstore.backends.errors import BackendDoesNotExist as StoreBackendD...
--- +++ @@ -35,32 +35,40 @@ class Repository: + """borgstore-based key/value store.""" class AlreadyExists(Error): + """A repository already exists at {}.""" exit_mcode = 10 class CheckNeeded(ErrorWithTraceback): + """Inconsistency detected. Please run "borg check {}".""" ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/repository.py
Write proper docstrings for these functions
import fnmatch import posixpath import re import sys import unicodedata from collections import namedtuple from enum import Enum from .helpers import clean_lines, shellpattern from .helpers.argparsing import Action, ArgumentTypeError from .helpers.errors import Error def parse_patternfile_line(line, roots, ie_comman...
--- +++ @@ -12,6 +12,7 @@ def parse_patternfile_line(line, roots, ie_commands, fallback): + """Parse a pattern-file line and act depending on which command it represents.""" ie_command = parse_inclexcl_command(line, fallback=fallback) if ie_command.cmd is IECommand.RootPath: roots.append(ie_co...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/patterns.py
Generate docstrings for each module
# borg cli interface / toplevel archiver code import sys import traceback # quickfix to disallow running borg with assertions switched off try: assert False except AssertionError: pass # OK else: print( "Borg requires working assertions. Please run Python without -O and/or unset PYTHONOPTIMIZE.",...
--- +++ @@ -179,14 +179,46 @@ return args class CommonOptions: + """ + Support class to allow specifying common options at multiple levels of the command hierarchy. + + Common options (e.g. --log-level, --repo) can be placed anywhere in the command line: + + borg --info cr...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/__init__.py
Write reusable docstrings
import logging import io import os import platform # python stdlib import - if this fails, check that cwd != src/borg/ import sys from collections import deque from itertools import islice from ..logger import create_logger logger = create_logger() from . import msgpack from .. import __version__ as borg_version fr...
--- +++ @@ -59,6 +59,11 @@ def log_multi(*msgs, level=logging.INFO, logger=logger): + """ + Log multiple lines of text, emitting each line via a separate logging call for cosmetic reasons. + + Each positional argument may be a single or multiple lines (separated by newlines) of text. + """ lines = ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/misc.py
Create docstrings for each class method
import errno import sys import logging import os import posixpath import stat import subprocess import time from io import TextIOWrapper from ._common import with_repository, Highlander from .. import helpers from ..archive import Archive, is_special from ..archive import BackupError, BackupOSError, BackupItemExcluded...
--- +++ @@ -42,6 +42,7 @@ class CreateMixIn: @with_repository(compatibility=(Manifest.Operation.WRITE,)) def do_create(self, args, repository, manifest): + """Creates a new archive.""" key = manifest.key matcher = PatternMatcher(fallback=True) matcher.add_inclexcl(args.patter...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/create_cmd.py
Add detailed docstrings explaining each function
from pathlib import Path from ._common import with_repository from ..archive import Archive from ..cache import write_chunkindex_to_repo_cache, build_chunkindex_from_repo from ..cache import files_cache_name, discover_files_cache_names from ..helpers import get_cache_dir from ..helpers.argparsing import ArgumentParser...
--- +++ @@ -38,6 +38,7 @@ return sum(entry.size for id, entry in self.chunks.iteritems()) # sum of stored sizes def garbage_collect(self): + """Removes unused chunks from a repository.""" logger.info("Starting compaction / garbage collection...") self.chunks = self.get_repositor...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/compact_cmd.py
Add docstrings that explain inputs and outputs
from collections import OrderedDict from collections.abc import Callable, ItemsView, Iterator, KeysView, MutableMapping, ValuesView from typing import TypeVar K = TypeVar("K") V = TypeVar("V") class LRUCache(MutableMapping[K, V]): _cache: OrderedDict[K, V] _capacity: int _dispose: Callable[[V], None] ...
--- +++ @@ -7,6 +7,11 @@ class LRUCache(MutableMapping[K, V]): + """ + Mapping which maintains a maximum size by removing the least recently used value. + Items are passed to dispose before being removed and setting an item which is + already in the cache has to be done using the replace method. + ""...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/lrucache.py
Please document this code using docstrings
import datetime import errno import hashlib import os import stat import time from collections import Counter from typing import TYPE_CHECKING from .constants import ROBJ_FILE_STREAM, zeros, ROBJ_DONTCARE if TYPE_CHECKING: # For type checking, assume mfusepy is available # This allows mypy to understand hlfus...
--- +++ @@ -39,6 +39,7 @@ def debug_log(msg): + """Append debug message to fuse_debug.log""" if DEBUG_LOG: timestamp = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3] with open(DEBUG_LOG, "a") as f: @@ -54,27 +55,32 @@ self.children = None # name (bytes) -> DirEntry, lazily a...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/hlfuse.py
Write documentation strings for class attributes
import os import errno from typing import BinaryIO, Iterator from ..constants import CH_DATA from .reader import Chunk class ChunkerFailing: def __init__(self, block_size: int, map: str) -> None: self.block_size = block_size # one char per block: r/R = successful read, e/E = I/O Error, e.g.: "rr...
--- +++ @@ -7,6 +7,13 @@ class ChunkerFailing: + """ + This is a very simple chunker for testing purposes. + + Reads block_size chunks. The map parameter controls behavior per block: + 'R' = successful read, 'E' = I/O Error. Blocks beyond the map length + will have the same behavior as the last map c...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/chunkers/failing.py
Write docstrings that follow conventions
import os from .datastruct import StableDict from ..constants import * # NOQA from msgpack import Packer as mp_Packer from msgpack import packb as mp_packb from msgpack import pack as mp_pack from msgpack import Unpacker as mp_Unpacker from msgpack import unpackb as mp_unpackb from msgpack import unpack as mp_unpac...
--- +++ @@ -1,3 +1,50 @@+""" +Wrapping msgpack +================ + +We wrap ``msgpack`` here as needed to avoid clutter in the calling code. + +Packing +------- +- use_bin_type = True (used by Borg since Borg 2.0) + This is used to generate output according to new msgpack 2.0 spec. + This cleanly keeps bytes and str ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/msgpack.py
Add docstrings to improve readability
import errno import hashlib import os import posixpath import re import stat import subprocess import sys import textwrap from pathlib import Path import platformdirs from .errors import Error from .process import prepare_subprocess_env from ..platformflags import is_win32 from ..constants import * # NOQA from .....
--- +++ @@ -24,6 +24,18 @@ def ensure_dir(path, mode=stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO, pretty_deadly=True): + """ + Ensure that the directory exists with the correct permissions. + + 1) Create the directory in a race-free manner. + 2) If mode is not None and the directory was created, set the ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/fs.py
Generate missing documentation strings
import errno import json import os import tempfile import time from pathlib import Path from . import platform from .helpers import Error, ErrorWithTraceback from .logger import create_logger ADD, REMOVE, REMOVE2 = "add", "remove", "remove2" SHARED, EXCLUSIVE = "shared", "exclusive" logger = create_logger(__name__) ...
--- +++ @@ -16,8 +16,21 @@ class TimeoutTimer: + """ + A timer for timeout checks (can also deal with "never time out"). + It can also compute and optionally execute a reasonable sleep time (e.g. to avoid + polling too often or to support thread/process rescheduling). + """ def __init__(self, ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/fslocking.py
Write reusable docstrings
import hashlib import io import json from hmac import compare_digest from collections.abc import Callable from pathlib import Path from xxhash import xxh64 from ..helpers import IntegrityError from ..logger import create_logger logger = create_logger() class FileLikeWrapper: def __init__(self, fd): sel...
--- +++ @@ -44,6 +44,20 @@ class FileHashingWrapper(FileLikeWrapper): + """ + Wrapper for file-like objects that computes a hash on-the-fly while reading/writing. + + WARNING: Seeks should only be used to query the size of the file, not + to skip data, because skipped data is not read and not hashed int...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/crypto/file_integrity.py
Document all public functions with docstrings
import json import textwrap from ..archive import Archive from ..constants import * # NOQA from ..helpers import msgpack from ..helpers import sysinfo from ..helpers import bin_to_hex, hex_to_bin, prepare_dump_dict from ..helpers import dash_open from ..helpers import StableDict from ..helpers import archivename_vali...
--- +++ @@ -22,11 +22,13 @@ class DebugMixIn: def do_debug_info(self, args): + """Displays system information for debugging and bug reports.""" print(sysinfo()) print("Process ID:", get_process_id()) @with_repository(compatibility=Manifest.NO_OPERATION_CHECK) def do_debug_dum...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/debug_cmd.py
Add documentation for all methods
import binascii import hmac import os import textwrap from hashlib import sha256, pbkdf2_hmac from pathlib import Path from typing import Literal, ClassVar from collections.abc import Callable from ..logger import create_logger logger = create_logger() import argon2.low_level from ..constants import * # NOQA from ...
--- +++ @@ -37,36 +37,43 @@ class UnsupportedPayloadError(Error): + """Unsupported payload type {}. A newer version is required to access this repository.""" exit_mcode = 48 class UnsupportedManifestError(Error): + """Unsupported manifest envelope. A newer version is required to access this reposi...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/crypto/key.py
Add return value explanations in docstrings
import abc import base64 import binascii import hashlib import json import os import os.path import re import shlex import stat import uuid from pathlib import Path from typing import ClassVar, Any, TYPE_CHECKING, Literal from collections import OrderedDict from datetime import datetime, timezone from functools import ...
--- +++ @@ -59,18 +59,21 @@ def safe_decode(s, coding="utf-8", errors="surrogateescape"): + """Decode bytes to str, with round-tripping of "invalid" bytes.""" if s is None: return None return s.decode(coding, errors) def safe_encode(s, coding="utf-8", errors="surrogateescape"): + """En...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/parseformat.py
Insert docstrings into my code
import re def parse_version(version): version_re = r""" (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+) # version, e.g. 1.2.33 (?P<prerelease>(?P<ptype>a|b|rc)(?P<pnum>\d+))? # optional prerelease, e.g. a1 or b2 or rc33 """ m = re.match(version_re, version, re.VERBOSE) if m is None: ...
--- +++ @@ -2,6 +2,19 @@ def parse_version(version): + """ + Simplistic parser for setuptools_scm versions. + + Supports final versions and alpha ('a'), beta ('b') and release candidate ('rc') versions. + It does not try to parse anything else than that, even if there is more in the version string. + + ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/version.py
Add docstrings for utility scripts
import subprocess from ._common import with_repository from ..cache import Cache from ..constants import * # NOQA from ..helpers import prepare_subprocess_env, set_ec, CommandError, ThreadRunner from ..helpers.argparsing import ArgumentParser, REMAINDER from ..logger import create_logger logger = create_logger() ...
--- +++ @@ -14,6 +14,7 @@ class LocksMixIn: @with_repository(manifest=False, exclusive=True) def do_with_lock(self, args, repository): + """Runs a user-specified command with the repository lock held.""" # the repository lock needs to get refreshed regularly, or it will be killed as stale. ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/lock_cmds.py
Can you add docstrings to this Python file?
from collections import defaultdict import os from ._common import with_repository, define_archive_filters_group from ..archive import Archive from ..constants import * # NOQA from ..helpers import bin_to_hex, Error from ..helpers import ProgressIndicatorPercent from ..helpers.argparsing import ArgumentParser from .....
--- +++ @@ -31,6 +31,7 @@ logger.info("Finished archives analysis.") def analyze_archives(self) -> None: + """Analyze all archives matching the given selection criteria.""" archive_infos = self.manifest.archives.list_considering(self.args) num_archives = len(archive_infos) ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/analyze_cmd.py
Add professional docstrings to my codebase
import errno import os import re import subprocess import sys import tempfile from packaging.version import parse as parse_version from .helpers import prepare_subprocess_env from .logger import create_logger logger = create_logger() from .platform import listxattr, getxattr, setxattr, ENOATTR # If we are runnin...
--- +++ @@ -1,3 +1,4 @@+"""A basic extended attributes (xattr) implementation for Linux, FreeBSD and macOS.""" import errno import os @@ -39,6 +40,7 @@ def is_enabled(path=None): + """Determines whether xattrs are enabled on the filesystem.""" with tempfile.NamedTemporaryFile(dir=path, prefix="borg-tmp"...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/xattr.py
Generate helpful docstrings for debugging
from typing import Any # here are the only imports from argparse and jsonargparse, # all other imports of these names import them from here: from argparse import Action, ArgumentError, ArgumentTypeError, RawDescriptionHelpFormatter # noqa: F401 from jsonargparse import ArgumentParser as _ArgumentParser # we subclas...
--- +++ @@ -1,3 +1,98 @@+""" +Borg argument-parsing layer +=========================== + +All imports of ``ArgumentParser``, ``Namespace``, ``SUPPRESS``, etc. come +from this module. It is the single seam between borg and the underlying +parser library (jsonargparse). + +Library choice +-------------- +Borg uses **jso...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/argparsing.py
Write docstrings for data processing functions
import asyncio import logging import os import sys from typing import Optional, Callable, List class BorgRunner: def __init__(self, command: List[str], log_callback: Callable[[dict], None]): self.command = command self.log_callback = log_callback self.process: Optional[asyncio.subprocess...
--- +++ @@ -1,3 +1,6 @@+""" +Borg Runner - Manages Borg subprocess execution and output parsing. +""" import asyncio import logging @@ -7,6 +10,9 @@ class BorgRunner: + """ + Manages the execution of the borg subprocess and parses its JSON output. + """ def __init__(self, command: List[str], log...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/cockpit/runner.py
Write docstrings describing functionality
import os from ..constants import * # NOQA from ..crypto.low_level import IntegrityError as IntegrityErrorBase modern_ec = os.environ.get("BORG_EXIT_CODES", "modern") == "modern" # "legacy" was used by borg < 2 class ErrorBase(Exception): # Error base class # if we raise such an Error and it is only c...
--- +++ @@ -9,6 +9,7 @@ class ErrorBase(Exception): + """ErrorBase: {}""" # Error base class @@ -37,38 +38,46 @@ class Error(ErrorBase): + """Error: {}""" class ErrorWithTraceback(Error): + """Error: {}""" # like Error, but show a traceback also traceback = True class Int...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/errors.py
Document my Python code with docstrings
import shtab from ._common import process_epilog from ..constants import * # NOQA from ..helpers import ( archivename_validator, SortBySpec, FilesCacheMode, PathSpec, ChunkerParams, CompressionSpec, tag_validator, relative_time_marker_validator, parse_file_size, ) from ..helpers.a...
--- +++ @@ -1,3 +1,54 @@+""" +Shell completion support for Borg commands. + +This module implements the `borg completion` command, which generates shell completion +scripts for bash and zsh. It uses the shtab library for basic completion generation +and extends it with custom dynamic completions for Borg-specific argum...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/completion_cmd.py
Document classes and their methods
import os from ..constants import * # NOQA from ..crypto.key import AESOCBRepoKey, CHPORepoKey, Blake2AESOCBRepoKey, Blake2CHPORepoKey from ..crypto.key import AESOCBKeyfileKey, CHPOKeyfileKey, Blake2AESOCBKeyfileKey, Blake2CHPOKeyfileKey from ..crypto.keymanager import KeyManager from ..helpers import PathSpec, Comm...
--- +++ @@ -18,6 +18,7 @@ class KeysMixIn: @with_repository(compatibility=(Manifest.Operation.CHECK,)) def do_key_change_passphrase(self, args, repository, manifest): + """Changes the repository key file passphrase.""" key = manifest.key if not hasattr(key, "change_passphrase"): ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/key_cmds.py
Create Google-style docstrings for my code
BORG_DICTIONARY = { # English -> Borg # UI Strings "**** You're welcome! ****": "You will be assimilated! ", "Files: ": "Drones: ", "Unchanged: ": "Unchanged: ", "Modified: ": "Modified: ", "Added: ": "Assimilated: ", "Other: ": "Other: ", "Errors: ": "Escaped: ", "RC: ": "Terminat...
--- +++ @@ -1,3 +1,6 @@+""" +Universal Translator - Converts standard English into Borg Speak. +""" BORG_DICTIONARY = { # English -> Borg # UI Strings @@ -14,6 +17,9 @@ class UniversalTranslator: + """ + Handles translation of log messages. + """ def __init__(self, enabled: bool = True): ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/cockpit/translator.py
Write Python docstrings for this snippet
import errno import functools import inspect import logging import os import select import shlex import shutil import socket import struct import sys import tempfile import textwrap import time from subprocess import Popen, PIPE from xxhash import xxh64 from . import __version__ from .compress import Compressor from ...
--- +++ @@ -46,31 +46,37 @@ class ConnectionClosed(Error): + """Connection closed by remote host.""" exit_mcode = 80 class ConnectionClosedWithHint(ConnectionClosed): + """Connection closed by remote host. {}""" exit_mcode = 81 class PathNotAllowed(Error): + """Repository path not a...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/legacyremote.py
Add docstrings for production code
import binascii import pkgutil import textwrap from hashlib import sha256 from ..helpers import Error, yes, bin_to_hex, hex_to_bin, dash_open from ..repoobj import RepoObj from .key import CHPOKeyfileKey, RepoKeyNotFoundError, KeyBlobStorage, identify_key class NotABorgKeyFile(Error): exit_mcode = 43 class ...
--- +++ @@ -11,21 +11,25 @@ class NotABorgKeyFile(Error): + """This file is not a Borg key backup, aborting.""" exit_mcode = 43 class RepoIdMismatch(Error): + """This key backup seems to be for a different backup repository, aborting.""" exit_mcode = 45 class UnencryptedRepo(Error): + ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/crypto/keymanager.py
Write docstrings for utility functions
import base64 import logging import os import stat import tarfile from ..archive import Archive, TarfileObjectProcessors, ChunksProcessor from ..constants import * # NOQA from ..helpers import HardLinkManager, IncludePatternNeverMatchedWarning from ..helpers import ProgressIndicatorPercent from ..helpers import dash_...
--- +++ @@ -55,6 +55,7 @@ @with_repository(compatibility=(Manifest.Operation.READ,)) @with_archive def do_export_tar(self, args, repository, manifest, archive): + """Export archive contents as a tarball""" self.output_list = args.output_list # A quick note about the general desi...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/tar_cmds.py
Add documentation for all methods
import enum import re from collections import namedtuple from datetime import datetime, timedelta, timezone from operator import attrgetter from collections.abc import Sequence from borgstore.store import ObjectNotFound, ItemInfo from .logger import create_logger logger = create_logger() from .constants import * #...
--- +++ @@ -22,11 +22,13 @@ class MandatoryFeatureUnsupported(Error): + """Unsupported repository feature(s) {}. A newer version of Borg is required to access this repository.""" exit_mcode = 25 class NoManifestError(Error): + """Repository has no manifest.""" exit_mcode = 26 @@ -68,6 +70...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/manifest.py
Add docstrings for internal functions
import errno import functools import io import os import stat import struct import sys import tempfile import time from collections import defaultdict, Counter from signal import SIGINT from typing import TYPE_CHECKING from .constants import ROBJ_FILE_STREAM, zeros if TYPE_CHECKING: # For type checking, assume l...
--- +++ @@ -1,3 +1,18 @@+""" +FUSE filesystem implementation for `borg mount`. + +IMPORTANT +========= + +This code is only safe for single-threaded and synchronous (non-async) usage. + +- llfuse is synchronous and used with workers=1, so there is only 1 thread, + and we are safe. +- pyfuse3 uses Trio, which only uses...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/fuse.py
Write Python docstrings for this snippet
import inspect import json import logging import logging.config import logging.handlers # needed for handlers defined there being configurable in logging.conf file import os import queue import sys import time import warnings from pathlib import Path logging_debugging_path: Path | None = None # if set, write borg.l...
--- +++ @@ -1,3 +1,52 @@+"""Logging facilities. + +Usage: + +- Each module declares its own logger using: + + from .logger import create_logger + logger = create_logger() + +- Then each module uses logger.info/warning/debug/etc. according to the + appropriate level: + + logger.debug('debugging info for ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/logger.py
Add docstrings to make code maintainable
from contextlib import contextmanager import json import logging import os import tempfile import time from ..constants import * # NOQA from ..crypto.key import FlexiKey from ..helpers import format_file_size, CompressionSpec from ..helpers import json_print from ..helpers import msgpack from ..helpers import get_res...
--- +++ @@ -18,6 +18,7 @@ class BenchmarkMixIn: def do_benchmark_crud(self, args): + """Benchmark Create, Read, Update, Delete for archives.""" def parse_args(args, cmd): # we need to inherit some essential options from the "borg benchmark crud" invocation @@ -160,6 +161,7 @@ ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/benchmark_cmd.py
Add standardized docstrings across the file
from .errors import Error class StableDict(dict): def items(self): return sorted(super().items()) class Buffer: class MemoryLimitExceeded(Error, OSError): def __init__(self, allocator, size=4096, limit=None): assert callable(allocator), "must give alloc(size) function as first param" ...
--- +++ @@ -2,16 +2,25 @@ class StableDict(dict): + """A dict subclass with stable items() ordering.""" def items(self): return sorted(super().items()) class Buffer: + """ + Provides a managed, resizable buffer. + """ class MemoryLimitExceeded(Error, OSError): + """Req...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/datastruct.py
Help me comply with documentation standards
import errno import io import os import socket import unicodedata import uuid from pathlib import Path from ..helpers import safe_unlink from ..platformflags import is_win32 """ platform base module ==================== Contains platform API implementations based on what Python itself provides. More specific APIs ar...
--- +++ @@ -33,22 +33,56 @@ def listxattr(path, *, follow_symlinks=False): + """ + Return xattr names of a file (list of bytes objects). + + *path* can either be a path (bytes) or an open file descriptor (int). + *follow_symlinks* indicates whether symlinks should be followed + and only applies when ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/platform/base.py
Add clean documentation to messy code
import io import sys from . import is_terminal class TextPecker: def __init__(self, s): self.str = s self.i = 0 def read(self, n): self.i += n return self.str[self.i - n : self.i] def peek(self, n): if n >= 0: return self.str[self.i : self.i + n] ...
--- +++ @@ -49,6 +49,13 @@ def rst_to_text(text, state_hook=None, references=None): + """ + Convert rST to a more human-friendly text form. + + This is a very loose conversion. No advanced rST features are supported. + The generated output depends directly on the input (for example, the + indentation...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/nanorst.py
Generate descriptive docstrings automatically
import getpass import os import shlex import subprocess import sys import textwrap from . import bin_to_hex from . import Error from . import yes from . import prepare_subprocess_env from ..logger import create_logger logger = create_logger() class NoPassphraseFailure(Error): exit_mcode = 50 class Passcomma...
--- +++ @@ -16,21 +16,25 @@ class NoPassphraseFailure(Error): + """Cannot acquire a passphrase: {}.""" exit_mcode = 50 class PasscommandFailure(Error): + """Passcommand supplied in BORG_PASSCOMMAND failed: {}.""" exit_mcode = 51 class PassphraseWrong(Error): + """Passphrase supplied...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/passphrase.py
Document helper functions with docstrings
import logging import json import time from ..logger import create_logger logger = create_logger() class ProgressIndicatorBase: LOGGER = "borg.output.progress" JSON_TYPE: str = None operation_id_counter = 0 @classmethod def operation_id(cls): cls.operation_id_counter += 1 retur...
--- +++ @@ -15,6 +15,7 @@ @classmethod def operation_id(cls): + """Unique number, can be used by receiving applications to distinguish different operations.""" cls.operation_id_counter += 1 return cls.operation_id_counter @@ -44,6 +45,14 @@ JSON_TYPE = "progress_percent" ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/progress.py
Write docstrings for this repository
from collections import defaultdict from ._common import with_repository, Highlander from ..constants import * # NOQA from ..compress import ObfuscateSize, Auto, COMPRESSOR_TABLE from ..hashindex import ChunkIndex from ..helpers import sig_int, ProgressIndicatorPercent, Error, CompressionSpec from ..helpers.argparsin...
--- +++ @@ -16,6 +16,7 @@ def find_chunks(repository, repo_objs, cache, stats, ctype, clevel, olevel): + """Find and flag chunks that need processing (usually: recompression).""" compr_keys = stats["compr_keys"] = set() compr_wanted = ctype, clevel, olevel recompress_count = 0 @@ -34,6 +35,7 @@ ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/repo_compress_cmd.py
Add docstrings to incomplete code
import datetime import json import random import time from xxhash import xxh64 from borgstore.store import ObjectNotFound from . import platform from .helpers import Error, ErrorWithTraceback from .logger import create_logger logger = create_logger(__name__) class LockError(Error): exit_mcode = 70 class Lo...
--- +++ @@ -15,36 +15,57 @@ class LockError(Error): + """Failed to acquire the lock {}.""" exit_mcode = 70 class LockErrorT(ErrorWithTraceback): + """Failed to acquire the lock {}.""" exit_mcode = 71 class LockFailed(LockErrorT): + """Failed to create/acquire the lock {} ({}).""" ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/storelocking.py
Help me add docstrings to my project
import contextlib import os import shlex import signal import subprocess import sys import time import threading import traceback from .. import __version__ from ..platformflags import is_win32 from ..logger import create_logger logger = create_logger() from ..helpers import EXIT_SUCCESS, EXIT_WARNING, EXIT_SIGNAL_...
--- +++ @@ -54,12 +54,28 @@ def daemonize(): + """Detach the process from the controlling terminal and run in the background. + + Returns: old and new get_process_id tuples. + """ with _daemonize() as (old_id, new_id): return old_id, new_id @contextlib.contextmanager def daemonizing(*, ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/process.py
Add verbose docstrings with examples
import errno import mmap import os import shutil import stat import struct import time from pathlib import Path from collections import defaultdict from configparser import ConfigParser from functools import partial from itertools import islice from collections.abc import Callable import xxhash from .constants import...
--- +++ @@ -66,32 +66,107 @@ class LegacyRepository: + """ + Filesystem-based transactional key-value store. + + Transactionality is achieved by using a log (aka journal) to record changes. The log is a series of numbered files + called segments. Each segment is a series of log entries. The segment numb...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/legacyrepository.py
Create docstrings for all classes and functions
import base64 import errno import json import os import posixpath import stat import sys import time from collections import OrderedDict, defaultdict from contextlib import contextmanager from datetime import timedelta from functools import partial from getpass import getuser from io import BytesIO from itertools impor...
--- +++ @@ -231,6 +231,19 @@ def stat_update_check(st_old, st_curr): + """ + this checks for some race conditions between the first filename-based stat() + we did before dispatching to the (hopefully correct) file type backup handler + and the (hopefully) fd-based fstat() we did in the handler. + + i...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archive.py
Generate NumPy-style docstrings
import configparser import io import os import shutil import stat from collections import namedtuple from datetime import datetime, timezone, timedelta from pathlib import Path from time import perf_counter from xxhash import xxh64 from borgstore.backends.errors import PermissionDenied from .logger import create_log...
--- +++ @@ -41,6 +41,13 @@ def files_cache_name(archive_name, files_cache_name="files"): + """ + Return the name of the files cache file for the given archive name. + + :param archive_name: name of the archive (ideally a series name) + :param files_cache_name: base name of the files cache file + :ret...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/cache.py
Create docstrings for all classes and functions
import errno import os from ..helpers import Buffer buffer = Buffer(bytearray, limit=2**24) def split_string0(buf): if isinstance(buf, bytearray): buf = bytes(buf) # Use a bytes object so we return a list of bytes objects. return buf.split(b"\0")[:-1] def split_lstring(buf): result = [] ...
--- +++ @@ -8,12 +8,14 @@ def split_string0(buf): + """Split a list of zero-terminated byte strings into Python bytes (without zero termination).""" if isinstance(buf, bytearray): buf = bytes(buf) # Use a bytes object so we return a list of bytes objects. return buf.split(b"\0")[:-1] def...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/platform/xattr.py
Generate docstrings for exported functions
import asyncio import time from textual.app import App, ComposeResult from textual.widgets import Header, Footer from textual.containers import Horizontal, Container from .theme import theme class BorgCockpitApp(App): from .. import __version__ as BORG_VERSION TITLE = f"Cockpit for BorgBackup {BORG_VERSI...
--- +++ @@ -1,3 +1,6 @@+""" +Borg Cockpit - Application Entry Point. +""" import asyncio import time @@ -10,6 +13,7 @@ class BorgCockpitApp(App): + """The main TUI Application class for Borg Cockpit.""" from .. import __version__ as BORG_VERSION @@ -18,6 +22,7 @@ BINDINGS = [("q", "quit", "Quit"...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/cockpit/app.py
Add docstrings for better understanding
import os import re from queue import LifoQueue def translate(pat, match_end=r"\Z"): pat = _translate_alternatives(pat) sep = os.path.sep n = len(pat) i = 0 res = "" while i < n: c = pat[i] i += 1 if c == "*": if i + 1 < n and pat[i] == "*" and pat[i + 1]...
--- +++ @@ -4,6 +4,20 @@ def translate(pat, match_end=r"\Z"): + """Translate a shell-style pattern to a regular expression. + + The pattern may include ``**<sep>`` (<sep> stands for the platform-specific path separator; "/" on POSIX systems) + for matching zero or more directory levels and "*" for matching...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/shellpattern.py
Write docstrings including parameters and return values
from typing import Iterator, BinaryIO import time from .reader import FileReader class ChunkerFixed: def __init__(self, block_size: int, header_size: int = 0, sparse: bool = False) -> None: self.block_size = block_size self.header_size = header_size self.chunking_time = 0.0 # likely w...
--- +++ @@ -7,6 +7,25 @@ class ChunkerFixed: + """ + This is a simple chunker for input data with data usually staying at the same + offset and/or with known block/record sizes: + + - raw disk images + - block devices + - database files with simple header + fixed-size records layout + + It opti...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/chunkers/fixed.py
Auto-generate documentation strings for this file
from ._common import with_repository, with_other_repository, Highlander from ..archive import Archive, cached_hash, DownloadPipeline from ..chunkers import get_chunker from ..constants import * # NOQA from ..crypto.key import uses_same_id_hash, uses_same_chunker_secret from ..helpers import Error from ..helpers import...
--- +++ @@ -30,6 +30,11 @@ dry_run, chunker_params=None, ): + """ + Transfer chunks from another repository to the current repository. + + If chunker_params is provided, the chunks will be re-chunked using the specified parameters. + """ transfer = 0 present = 0 chunks = [] @@ -126,...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/transfer_cmd.py
Add docstrings that explain logic
import os import re from datetime import datetime, timezone, timedelta def parse_timestamp(timestamp, tzinfo=timezone.utc): dt = datetime.fromisoformat(timestamp) if dt.tzinfo is None: dt = dt.replace(tzinfo=tzinfo) return dt def parse_local_timestamp(timestamp, tzinfo=None): dt = datetime.f...
--- +++ @@ -4,6 +4,10 @@ def parse_timestamp(timestamp, tzinfo=timezone.utc): + """Parse an ISO 8601 timestamp string. + + For naive/unaware datetime objects, assume they are in the tzinfo timezone (default: UTC). + """ dt = datetime.fromisoformat(timestamp) if dt.tzinfo is None: dt = dt...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/time.py
Help me comply with documentation standards
import os import logging from collections import namedtuple from ..constants import * # NOQA from .datastruct import StableDict, Buffer, EfficientCollectionQueue from .errors import Error, ErrorWithTraceback, IntegrityError, DecompressionError, CancelledByUser, CommandError from .errors import RTError, modern_ec fr...
--- +++ @@ -1,3 +1,9 @@+""" +This package contains helper and utility functionality that did not fit elsewhere. + +Code used to be in borg/helpers.py but was split into modules in this +package, which are imported here for compatibility. +""" import os import logging @@ -104,6 +110,7 @@ def max_ec(ec1, ec2): + ...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/helpers/__init__.py
Create docstrings for all classes and functions
import atexit import errno import functools import inspect import logging import os import queue import select import shlex import shutil import socket import struct import sys import tempfile import textwrap import time import traceback from subprocess import Popen, PIPE from xxhash import xxh64 import borg.logger f...
--- +++ @@ -53,31 +53,37 @@ class ConnectionClosed(Error): + """Connection closed by remote host""" exit_mcode = 80 class ConnectionClosedWithHint(ConnectionClosed): + """Connection closed by remote host. {}""" exit_mcode = 81 class PathNotAllowed(Error): + """Repository path not al...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/remote.py
Write clean docstrings for readability
import functools import os import textwrap import borg from ..archive import Archive from ..constants import * # NOQA from ..cache import Cache, assert_secure from ..helpers import Error from ..helpers import SortBySpec, location_validator, Location, relative_time_marker_validator from ..helpers import Highlander, oc...
--- +++ @@ -68,6 +68,19 @@ def with_repository( create=False, lock=True, exclusive=False, manifest=True, cache=False, secure=True, compatibility=None ): + """ + Method decorator for subcommand-handling methods: do_XYZ(self, args, repository, …) + + If a parameter (where allowed) is a str the attribute na...
https://raw.githubusercontent.com/borgbackup/borg/HEAD/src/borg/archiver/_common.py
Turn comments into proper docstrings
# Native python imports import json import os import pathlib import time from urllib import parse # Local imports from pytube import request # YouTube on TV client secrets _client_id = '861556708454-d6dlm3lh05idd8npek18k6be8ba3oc68.apps.googleusercontent.com' _client_secret = 'SboVhoG9s0rNafixCSGGKXAT' # Extracted A...
--- +++ @@ -1,3 +1,9 @@+"""This module is designed to interact with the innertube API. + +This module is NOT intended to be used directly by end users, as each of the +interfaces returns raw results. These should instead be parsed to extract +the useful information for the end user. +""" # Native python imports impor...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/innertube.py
Add docstrings explaining edge cases
from typing import Pattern, Union class PytubeError(Exception): class MaxRetriesExceeded(PytubeError): class HTMLParseError(PytubeError): class ExtractError(PytubeError): class RegexMatchError(ExtractError): def __init__(self, caller: str, pattern: Union[str, Pattern]): super().__init__(f"{caller...
--- +++ @@ -1,28 +1,50 @@+"""Library specific exception definitions.""" from typing import Pattern, Union class PytubeError(Exception): + """Base pytube exception that all others inherit. + + This is done to not pollute the built-in exceptions, which *could* result + in unintended errors being unexpected...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/exceptions.py
Generate consistent documentation across files
import logging from typing import Any, Callable, Dict, List, Optional import pytube import pytube.exceptions as exceptions from pytube import extract, request from pytube import Stream, StreamQuery from pytube.helpers import install_proxy from pytube.innertube import InnerTube from pytube.metadata import YouTubeMetada...
--- +++ @@ -1,3 +1,11 @@+""" +This module implements the core developer interface for pytube. + +The problem domain of the :class:`YouTube <YouTube> class focuses almost +exclusively on the developer interface. Pytube offloads the heavy lifting to +smaller peripheral modules and functions. + +""" import logging from ...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/__main__.py
Add docstrings explaining edge cases
import functools import gzip import json import logging import os import re import warnings from typing import Any, Callable, Dict, List, Optional, TypeVar from urllib import request from pytube.exceptions import RegexMatchError logger = logging.getLogger(__name__) class DeferredGeneratorList: def __init__(self...
--- +++ @@ -1,3 +1,4 @@+"""Various helper functions implemented by pytube.""" import functools import gzip import json @@ -14,14 +15,33 @@ class DeferredGeneratorList: + """A wrapper class for deferring list generation. + + Pytube has some continuation generators that create web calls, which means + tha...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/helpers.py
Provide docstrings following PEP 257
import logging import os from math import ceil from datetime import datetime from typing import BinaryIO, Dict, Optional, Tuple from urllib.error import HTTPError from urllib.parse import parse_qs from pytube import extract, request from pytube.helpers import safe_filename, target_directory from pytube.itags import g...
--- +++ @@ -1,3 +1,11 @@+""" +This module contains a container for stream manifest data. + +A container object for the media stream (video only / audio only / video+audio +combined). This was referred to as ``Video`` in the legacy pytube version, but +has been renamed to accommodate DASH (which serves the audio and vid...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/streams.py
Improve documentation using docstrings
import math import os import time import json import xml.etree.ElementTree as ElementTree from html import unescape from typing import Dict, Optional from pytube import request from pytube.helpers import safe_filename, target_directory class Caption: def __init__(self, caption_track: Dict): self.url = c...
--- +++ @@ -11,8 +11,14 @@ class Caption: + """Container for caption tracks.""" def __init__(self, caption_track: Dict): + """Construct a :class:`Caption <Caption>`. + + :param dict caption_track: + Caption track data extracted from ``watch_html``. + """ self.url =...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/captions.py
Document this module using docstrings
from collections.abc import Mapping, Sequence from typing import Callable, List, Optional, Union from pytube import Caption, Stream from pytube.helpers import deprecated class StreamQuery(Sequence): def __init__(self, fmt_streams): self.fmt_streams = fmt_streams self.itag_index = {int(s.itag): s...
--- +++ @@ -1,3 +1,4 @@+"""This module provides a query interface for media streams and captions.""" from collections.abc import Mapping, Sequence from typing import Callable, List, Optional, Union @@ -6,8 +7,14 @@ class StreamQuery(Sequence): + """Interface for querying the available media streams.""" ...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/query.py
Add well-formatted docstrings
from typing import Dict PROGRESSIVE_VIDEO = { 5: ("240p", "64kbps"), 6: ("270p", "64kbps"), 13: ("144p", None), 17: ("144p", "24kbps"), 18: ("360p", "96kbps"), 22: ("720p", "192kbps"), 34: ("360p", "128kbps"), 35: ("480p", "128kbps"), 36: ("240p", None), 37: ("1080p", "192kbps")...
--- +++ @@ -1,3 +1,4 @@+"""This module contains a lookup table of YouTube's itag values.""" from typing import Dict PROGRESSIVE_VIDEO = { @@ -129,6 +130,11 @@ def get_format_profile(itag: int) -> Dict: + """Get additional format information for a given itag. + + :param str itag: + YouTube format id...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/itags.py
Add documentation for all methods
import logging import urllib.parse import re from collections import OrderedDict from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from urllib.parse import parse_qs, quote, urlencode, urlparse from pytube.cipher import Cipher from pytube.exceptions import HTMLParseError, LiveStreamError...
--- +++ @@ -1,3 +1,4 @@+"""This module contains all non-cipher related data extraction logic.""" import logging import urllib.parse import re @@ -17,6 +18,13 @@ def publish_date(watch_html: str): + """Extract publish date + :param str watch_html: + The html contents of the watch page. + :rtype: s...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/extract.py
Add docstrings explaining edge cases
# -*- coding: utf-8 -*- import json import logging from typing import Dict, List, Optional, Tuple from pytube import extract, Playlist, request from pytube.helpers import uniqueify logger = logging.getLogger(__name__) class Channel(Playlist): def __init__(self, url: str, proxies: Optional[Dict[str, str]] = None...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Module for interacting with a user's youtube channel.""" import json import logging from typing import Dict, List, Optional, Tuple @@ -11,6 +12,13 @@ class Channel(Playlist): def __init__(self, url: str, proxies: Optional[Dict[str, str]] = None): + ""...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/contrib/channel.py
Add docstrings that explain purpose and usage
import ast import json import re from pytube.exceptions import HTMLParseError def parse_for_all_objects(html, preceding_regex): result = [] regex = re.compile(preceding_regex) match_iter = regex.finditer(html) for match in match_iter: if match: start_index = match.end() ...
--- +++ @@ -5,6 +5,16 @@ def parse_for_all_objects(html, preceding_regex): + """Parses input html to find all matches for the input starting point. + + :param str html: + HTML to be parsed for an object. + :param str preceding_regex: + Regex to find the string preceding the object. + :rtyp...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/parser.py
Add well-formatted docstrings
import json import logging from collections.abc import Sequence from datetime import date, datetime from typing import Dict, Iterable, List, Optional, Tuple, Union from pytube import extract, request, YouTube from pytube.helpers import cache, DeferredGeneratorList, install_proxy, uniqueify logger = logging.getLogger(...
--- +++ @@ -1,3 +1,4 @@+"""Module to download a complete playlist from a youtube channel.""" import json import logging from collections.abc import Sequence @@ -11,6 +12,7 @@ class Playlist(Sequence): + """Load a YouTube playlist with URL""" def __init__(self, url: str, proxies: Optional[Dict[str, str]...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/contrib/playlist.py
Add docstrings to improve code quality
import logging import re from itertools import chain from typing import Any, Callable, Dict, List, Optional, Tuple from pytube.exceptions import ExtractError, RegexMatchError from pytube.helpers import cache, regex_search from pytube.parser import find_object_from_startpoint, throttling_array_split logger = logging.g...
--- +++ @@ -1,3 +1,17 @@+""" +This module contains all logic necessary to decipher the signature. + +YouTube's strategy to restrict downloading videos is to send a ciphered version +of the signature to the client, along with the decryption algorithm obfuscated +in JavaScript. For the clients to play the videos, JavaScr...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/cipher.py
Add docstrings that explain purpose and usage
#!/usr/bin/env python3 import argparse import gzip import json import logging import os import shutil import sys import datetime as dt import subprocess # nosec from typing import List, Optional import pytube.exceptions as exceptions from pytube import __version__ from pytube import CaptionQuery, Playlist, Stream, Yo...
--- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +"""A simple command line application to download youtube videos.""" import argparse import gzip import json @@ -20,6 +21,7 @@ def main(): + """Command line application to download youtube videos.""" # noinspection PyTypeChecker parser = argparse.Argume...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/cli.py
Document all endpoints with docstrings
# Native python imports import logging # Local imports from pytube import YouTube from pytube.innertube import InnerTube logger = logging.getLogger(__name__) class Search: def __init__(self, query): self.query = query self._innertube_client = InnerTube(client='WEB') # The first search,...
--- +++ @@ -1,3 +1,4 @@+"""Module for interacting with YouTube search.""" # Native python imports import logging @@ -11,6 +12,11 @@ class Search: def __init__(self, query): + """Initialize Search object. + + :param str query: + Search query provided by the user. + """ ...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/contrib/search.py
Improve my code by adding docstrings
import http.client import json import logging import re import socket from functools import lru_cache from urllib import parse from urllib.error import URLError from urllib.request import Request, urlopen from pytube.exceptions import RegexMatchError, MaxRetriesExceeded from pytube.helpers import regex_search logger ...
--- +++ @@ -1,3 +1,4 @@+"""Implements a simple wrapper around urlopen.""" import http.client import json import logging @@ -37,6 +38,16 @@ def get(url, extra_headers=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): + """Send an http GET request. + + :param str url: + The URL to perform the GET request...
https://raw.githubusercontent.com/pytube/pytube/HEAD/pytube/request.py
Document this code for team use
#!/usr/bin/env python import io import re import subprocess import sys from optparse import OptionParser import click DEBUG = False CONFIRM_STEPS = False DRY_RUN = False def skip_step(): global CONFIRM_STEPS if CONFIRM_STEPS: return not click.confirm("--- Run this step?", default=True) return ...
--- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python +"""A script to publish a release of pgcli to PyPI.""" import io import re @@ -14,6 +15,10 @@ def skip_step(): + """ + Asks for user's response whether to run a step. Default is yes. + :return: boolean + """ global CONFIRM_STEPS if CONFIRM_ST...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/release.py
Write docstrings describing functionality
import click from textwrap import dedent keyring = None # keyring will be loaded later keyring_error_message = dedent( """\ {} {} To remove this message do one of the following: - prepare keyring as described at: https://keyring.readthedocs.io/en/stable/ - uninstall keyring: pip uninstall k...
--- +++ @@ -17,6 +17,7 @@ def keyring_initialize(keyring_enabled, *, logger): + """Initialize keyring only if explicitly enabled""" global keyring if keyring_enabled: @@ -30,6 +31,7 @@ def keyring_get_password(key): + """Attempt to get password from keyring""" # Find password from store ...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/auth.py
Fill in missing docstrings in my code
import re import sqlparse from sqlparse.sql import Identifier from sqlparse.tokens import Token, Error cleanup_regex = { # This matches only alphanumerics and underscores. "alphanum_underscore": re.compile(r"(\w+)$"), # This matches everything except spaces, parens, colon, and comma "many_punctuations"...
--- +++ @@ -16,6 +16,38 @@ def last_word(text, include="alphanum_underscore"): + r""" + Find the last word in a sentence. + + >>> last_word('abc') + 'abc' + >>> last_word(' abc') + 'abc' + >>> last_word('') + '' + >>> last_word(' ') + '' + >>> last_word('abc ') + '' + >>> last...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/packages/parseutils/utils.py
Add detailed docstrings explaining each function
import logging from prompt_toolkit.enums import EditingMode from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.filters import ( completion_is_selected, is_searching, has_completions, has_selection, vi_mode, ) from .pgbuffer import buffer_should_be_handled, safe_multi_line_mode ...
--- +++ @@ -15,33 +15,39 @@ def pgcli_bindings(pgcli): + """Custom key bindings for pgcli.""" kb = KeyBindings() tab_insert_text = " " * 4 @kb.add("f2") def _(event): + """Enable/Disable SmartCompletion Mode.""" _logger.debug("Detected F2 key.") pgcli.completer.sm...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/key_bindings.py
Write docstrings for utility functions
import sqlparse BASE_KEYWORDS = [ "drop", "shutdown", "delete", "truncate", "alter", "unconditional_update", ] ALL_KEYWORDS = BASE_KEYWORDS + ["update"] def query_starts_with(formatted_sql, prefixes): prefixes = [prefix.lower() for prefix in prefixes] return bool(formatted_sql) and f...
--- +++ @@ -13,16 +13,19 @@ def query_starts_with(formatted_sql, prefixes): + """Check if the query starts with any item from *prefixes*.""" prefixes = [prefix.lower() for prefix in prefixes] return bool(formatted_sql) and formatted_sql.split()[0] in prefixes def query_is_unconditional_update(form...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/packages/parseutils/__init__.py
Add structured docstrings to improve clarity
from collections import namedtuple _ColumnMetadata = namedtuple("ColumnMetadata", ["name", "datatype", "foreignkeys", "default", "has_default"]) def ColumnMetadata(name, datatype, foreignkeys=None, default=None, has_default=False): return _ColumnMetadata(name, datatype, foreignkeys or [], default, has_default) ...
--- +++ @@ -22,6 +22,8 @@ def parse_defaults(defaults_string): + """Yields default values for a function, given the string provided by + pg_get_expr(pg_catalog.pg_proc.proargdefaults, 0)""" if not defaults_string: return current = "" @@ -61,6 +63,7 @@ is_extension, arg_defa...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/packages/parseutils/meta.py
Write docstrings including parameters and return values
import threading import os from collections import OrderedDict from .pgcompleter import PGCompleter class CompletionRefresher: refreshers = OrderedDict() def __init__(self): self._completer_thread = None self._restart_refresh = threading.Event() def refresh(self, executor, special, call...
--- +++ @@ -13,6 +13,18 @@ self._restart_refresh = threading.Event() def refresh(self, executor, special, callbacks, history=None, settings=None): + """ + Creates a PGCompleter object and populates it with the relevant + completion suggestions in a background thread. + + execu...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/completion_refresher.py
Add docstrings to meet PEP guidelines
import ipaddress import logging import traceback from collections import namedtuple import re import pgspecial as special import psycopg import psycopg.sql from psycopg.conninfo import make_conninfo import sqlparse from .packages.parseutils.meta import FunctionMetadata, ForeignKey _logger = logging.getLogger(__name__...
--- +++ @@ -38,6 +38,8 @@ def register_typecasters(connection): + """Casts date and timestamp values to string, resolves issues with out-of-range + dates (e.g. BC) which psycopg can't handle""" for forced_text_type in [ "date", "time", @@ -52,6 +54,9 @@ # pg3: I don't know what is thi...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/pgexecute.py
Add inline docstrings for readability
import sqlparse from collections import namedtuple from sqlparse.sql import IdentifierList, Identifier, Function from sqlparse.tokens import Keyword, DML, Punctuation TableReference = namedtuple("TableReference", ["schema", "name", "alias", "is_function"]) TableReference.ref = property( lambda self: self.alias or ...
--- +++ @@ -70,6 +70,7 @@ def extract_table_identifiers(token_stream, allow_functions=True): + """yields tuples of TableReference namedtuples""" # We need to do some massaging of the names because postgres is case- # insensitive and '"Foo"' is not the same table as 'Foo' (while 'foo' is) @@ -123,6 +1...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/packages/parseutils/tables.py
Help me add docstrings to my project
from sqlparse import parse from sqlparse.tokens import Keyword, CTE, DML from sqlparse.sql import Identifier, IdentifierList, Parenthesis from collections import namedtuple from .meta import TableMetadata, ColumnMetadata # TableExpression is a namedtuple representing a CTE, used internally # name: cte alias assigned ...
--- +++ @@ -14,6 +14,7 @@ def isolate_query_ctes(full_text, text_before_cursor): + """Simplify a query by converting CTEs into table metadata objects""" if not full_text or not full_text.strip(): return full_text, text_before_cursor, () @@ -44,6 +45,14 @@ def extract_ctes(sql): + """Extrac...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/packages/parseutils/ctes.py
Please document this code using docstrings
import json import logging import re from itertools import count, chain import operator from collections import namedtuple, defaultdict, OrderedDict from cli_helpers.tabular_output import TabularOutputFormatter from pgspecial.namedqueries import NamedQueries from prompt_toolkit.completion import Completer, Completion, ...
--- +++ @@ -60,6 +60,18 @@ def generate_alias(tbl, alias_map=None): + """Generate a table alias. + + Given a table name will return an alias for that table using the first of + the following options there's a match for. + + 1. The predefined alias for table defined in the alias_map. + 2. All ...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/pgcompleter.py
Create docstrings for all classes and functions
import sys import click from .parseutils import is_destructive def confirm_destructive_query(queries, keywords, alias): info = "You're about to run a destructive command" if alias: info += f" in {click.style(alias, fg='red')}" prompt_text = f"{info}.\nDo you want to proceed?" if is_destructiv...
--- +++ @@ -4,6 +4,14 @@ def confirm_destructive_query(queries, keywords, alias): + """Check if the query is destructive and prompts the user to confirm. + + Returns: + * None if the query is non-destructive or we can't prompt the user. + * True if the query is destructive and the user wants to proceed....
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/packages/prompt_utils.py
Expand my code with proper documentation strings
from zoneinfo import ZoneInfoNotFoundError from configobj import ConfigObj, ParseError from pgspecial.namedqueries import NamedQueries from .config import skip_initial_comment import atexit import os import re import sys import traceback import logging import threading import shutil import functools import datetime as...
--- +++ @@ -309,12 +309,14 @@ raise PgCliQuitError def toggle_named_query_quiet(self): + """Toggle hiding of named query text""" self.hide_named_query_text = not self.hide_named_query_text status = "ON" if self.hide_named_query_text else "OFF" message = f"Named query qui...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/main.py
Fully document this Python code with docstrings
import re import sqlparse from collections import namedtuple from sqlparse.sql import Comparison, Identifier, Where from .parseutils.utils import last_word, find_prev_keyword, parse_partial_identifier from .parseutils.tables import extract_tables from .parseutils.ctes import isolate_query_ctes from pgspecial.main impor...
--- +++ @@ -85,6 +85,12 @@ return self.parsed.token_first().value.lower() == "insert" def get_tables(self, scope="full"): + """Gets the tables available in the statement. + param `scope:` possible values: 'full', 'insert', 'before' + If 'insert', only the first table is returned. + ...
https://raw.githubusercontent.com/dbcli/pgcli/HEAD/pgcli/packages/sqlcompletion.py
Write documentation strings for class attributes
import socket import paramiko import os import select import sys import threading import io from routersploit.core.exploit.exploit import Exploit from routersploit.core.exploit.exploit import Protocol from routersploit.core.exploit.option import OptBool from routersploit.core.exploit.printer import print_success from ...
--- +++ @@ -18,8 +18,16 @@ class SSHCli: + """ SSH Client provides methods to handle communication with SSH server """ def __init__(self, ssh_target: str, ssh_port: int, verbosity: bool = False) -> None: + """ SSH client constructor + + :param str ssh_target: SSH target ip address + :...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/ssh/ssh_client.py
Add docstrings for internal functions
import socket from routersploit.core.exploit.exploit import Exploit from routersploit.core.exploit.exploit import Protocol from routersploit.core.exploit.option import OptBool from routersploit.core.exploit.printer import print_status from routersploit.core.exploit.printer import print_error from routersploit.core.exp...
--- +++ @@ -13,8 +13,16 @@ class TCPCli: + """ TCP Client provides methods to handle communication with TCP server """ def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool = False) -> None: + """ TCP client constructor + + :param str tcp_target: target TCP server ip address + ...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/tcp/tcp_client.py
Create Google-style docstrings for my code
import atexit import itertools import pkgutil import os import sys import getopt import signal import traceback import threading, ctypes from collections import Counter from routersploit.core.exploit.exceptions import RoutersploitException from routersploit.core.exploit.utils import ( index_modules, pythonize_...
--- +++ @@ -50,6 +50,13 @@ self.banner = "" def setup(self): + """ Initialization of third-party libraries + + Setting interpreter history. + Setting appropriate completer function. + + :return: + """ if not os.path.exists(self.history_file): with ...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/interpreter.py
Add docstrings following best practices
############################################################## # Lempel-Ziv-Stac decompression # BitReader and RingList classes # # Copyright (C) 2011 Filippo Valsorda - FiloSottile # filosottile.wiki gmail.com - www.pytux.it # # This program is free software: you can redistribute it and/or modify # it under the terms...
--- +++ @@ -24,6 +24,11 @@ class BitReader: + """ + Gets a string or a iterable of chars (also mmap) + representing bytes (ord) and permits to extract + bits one by one like a stream + """ def __init__(self, data_bytes): self._bits = collections.deque() @@ -49,6 +54,10 @@ class Ri...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/libs/lzs/lzs.py
Create docstrings for all classes and functions
import asyncio from pysnmp.hlapi.v3arch.asyncio import * from routersploit.core.exploit.exploit import Exploit from routersploit.core.exploit.exploit import Protocol from routersploit.core.exploit.option import OptBool from routersploit.core.exploit.printer import print_success from routersploit.core.exploit.printer i...
--- +++ @@ -12,8 +12,16 @@ class SNMPCli: + """ SNMP Client provides methods to handle communication with SNMP server """ def __init__(self, snmp_target: str, snmp_port: int, verbosity: bool = False) -> None: + """ SNMP client constructor + + :param str snmp_target: target SNMP server ip add...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/snmp/snmp_client.py
Help me comply with documentation standards
import socket import requests import urllib3 from routersploit.core.exploit.exploit import Exploit from routersploit.core.exploit.exploit import Protocol from routersploit.core.exploit.option import OptBool from routersploit.core.exploit.printer import print_error urllib3.disable_warnings(urllib3.exceptions.Insecure...
--- +++ @@ -15,6 +15,7 @@ # pylint: disable=no-member class HTTPClient(Exploit): + """ HTTP Client provides methods to handle communication with HTTP server """ target_protocol = Protocol.HTTP @@ -22,6 +23,14 @@ ssl = OptBool(False, "SSL enabled: true/false") def http_request(self, method: str...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/http/http_client.py
Generate docstrings for exported functions
import ftplib import io from routersploit.core.exploit.exploit import Exploit from routersploit.core.exploit.exploit import Protocol from routersploit.core.exploit.option import OptBool from routersploit.core.exploit.printer import print_error from routersploit.core.exploit.printer import print_success FTP_TIMEOUT =...
--- +++ @@ -12,8 +12,17 @@ class FTPCli: + """ FTP Client provides methods to handle communication with FTP server """ def __init__(self, ftp_target: str, ftp_port: int, ssl: bool = False, verbosity: bool = False) -> None: + """ FTP client constructor + + :param str ftp_target: target FTP se...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/ftp/ftp_client.py
Add docstrings that explain purpose and usage
import re import os import importlib import string import random from functools import wraps import routersploit.modules as rsf_modules import routersploit.resources as resources import routersploit.resources.wordlists as wordlists from routersploit.core.exploit.printer import print_error, print_info from routersploi...
--- +++ @@ -18,11 +18,22 @@ def random_text(length: int, alph: str = string.ascii_letters + string.digits) -> str: + """ Generates random string text + + :param int length: length of text to generate + :param str alph: string of all possible characters to choose from + :return str: generated random stri...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/exploit/utils.py
Provide docstrings following PEP 257
import threading import sys import collections from weakref import WeakKeyDictionary try: import queue except ImportError: # Python 3.x import Queue as queue printer_queue = queue.Queue() thread_output_stream = WeakKeyDictionary() PrintResource = collections.namedtuple("PrintResource", ["content", "sep", "...
--- +++ @@ -28,6 +28,11 @@ def __cprint(*args, **kwargs): + """ Color print() + + Signature like Python 3 print() function + print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout]) + """ if not kwargs.pop("verbose", True): return @@ -43,26 +48,53 @@ def print_error(*args, **kw...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/exploit/printer.py
Document this module using docstrings
import os import threading import time from itertools import chain from functools import wraps from routersploit.core.exploit.printer import ( print_status, thread_output_stream, ) from routersploit.core.exploit.option import Option GLOBAL_OPTS = {} class Protocol: CUSTOM = "custom" TCP = "custom/tc...
--- +++ @@ -27,6 +27,11 @@ class ExploitOptionsAggregator(type): + """ Metaclass for exploit base class. + + Metaclass is aggregating all possible Attributes that user can set + for tab completion purposes. + """ def __new__(cls, name, bases, attrs): try: @@ -52,6 +57,13 @@ class BaseExp...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/exploit/exploit.py
Add docstrings for production code
from routersploit.core.exploit.exploit import Exploit from routersploit.core.exploit.option import OptInteger from routersploit.core.exploit.printer import ( print_error, print_status ) from routersploit.core.bluetooth.btle import ( ScanDelegate, BTLEScanner ) class Options: def __init__(self, bu...
--- +++ @@ -11,6 +11,7 @@ class Options: + """ Options used by the scanner """ def __init__(self, buffering, mac, enum_services): self.buffering = buffering @@ -19,12 +20,14 @@ class BTLEClient(Exploit): + """ Bluetooth Low Energy Client implementation """ scan_time = OptInteger(10,...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/bluetooth/btle_client.py
Add structured docstrings to improve clarity
import socket from routersploit.core.exploit.exploit import Exploit from routersploit.core.exploit.exploit import Protocol from routersploit.core.exploit.option import OptBool from routersploit.core.exploit.printer import print_error from routersploit.core.exploit.utils import is_ipv4 from routersploit.core.exploit.ut...
--- +++ @@ -12,8 +12,16 @@ class UDPCli: + """ UDP Client provides methods to handle communication with UDP server """ def __init__(self, udp_target: str, udp_port: int, verbosity: bool = False) -> None: + """ UDP client constructor + + :param str udp_target: target UDP server ip address + ...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/udp/udp_client.py
Create docstrings for all classes and functions
try: import telnetlib except ImportError: import telnetlib3 as telnetlib from routersploit.core.exploit.exploit import Exploit from routersploit.core.exploit.exploit import Protocol from routersploit.core.exploit.option import OptBool from routersploit.core.exploit.printer import print_success from routersploi...
--- +++ @@ -14,8 +14,16 @@ class TelnetCli: + """ Telnet Client provides methods to handle communication with Telnet server """ def __init__(self, telnet_target: str, telnet_port: int, verbosity: bool = False) -> None: + """ Telnet client constructor + + :param str telnet_target: target Teln...
https://raw.githubusercontent.com/threat9/routersploit/HEAD/routersploit/core/telnet/telnet_client.py
Add docstrings for better understanding
__all__ = [ "DataTable", "Dataset", ] import typing as t from pydantic import BaseModel if t.TYPE_CHECKING: from pandas import DataFrame as PandasDataFrame from ragas.backends import BaseBackend, get_registry from ragas.backends.inmemory import InMemoryBackend # For backwards compatibility, use typing...
--- +++ @@ -1,3 +1,4 @@+"""A python list like object that contains your evaluation data.""" __all__ = [ "DataTable", @@ -28,6 +29,11 @@ class DataTable(t.Generic[T]): + """A list-like interface for managing datatable entries with backend save and load. + + This class behaves like a Python list while s...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/dataset.py
Add docstrings for utility scripts
import typing as t from ragas.cache import CacheInterface from .base import BaseRagasEmbedding from .utils import batch_texts, get_optimal_batch_size, safe_import, validate_texts class LiteLLMEmbeddings(BaseRagasEmbedding): PROVIDER_NAME = "litellm" REQUIRES_MODEL = True def __init__( self, ...
--- +++ @@ -1,3 +1,4 @@+"""LiteLLM embeddings implementation for universal provider support.""" import typing as t @@ -8,6 +9,11 @@ class LiteLLMEmbeddings(BaseRagasEmbedding): + """Universal embedding interface using LiteLLM. + + Supports 100+ models across OpenAI, Azure, Google, Cohere, Anthropic, and ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/embeddings/litellm_provider.py
Generate docstrings for this script
import json import typing as t from datetime import date, datetime from pathlib import Path from pydantic import BaseModel from .base import BaseBackend class LocalJSONLBackend(BaseBackend): def __init__( self, root_dir: str, ): self.root_dir = Path(root_dir) def _get_data_dir...
--- +++ @@ -1,3 +1,4 @@+"""Local JSONL backend implementation for projects and datasets.""" import json import typing as t @@ -10,6 +11,38 @@ class LocalJSONLBackend(BaseBackend): + """File-based backend using JSONL format for local storage. + + Stores datasets and experiments as JSONL files (one JSON obj...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/backends/local_jsonl.py