diff --git "a/oracle_context_cache_v3/GitGuardian__ggshield.json" "b/oracle_context_cache_v3/GitGuardian__ggshield.json" new file mode 100644--- /dev/null +++ "b/oracle_context_cache_v3/GitGuardian__ggshield.json" @@ -0,0 +1 @@ +{"repo": "GitGuardian/ggshield", "n_pairs": 200, "version": "v3_compressed", "max_tokens": 6000, "contexts": {"tests/unit/cmd/honeytoken/test_honeytoken_with_context.py::70": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["CliRunner", "cli", "my_vcr"], "enclosing_function": "test_honeytoken_create_with_context_bad_language", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_check.py::23": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli", "my_vcr", "uuid4"], "enclosing_function": "test_hmsl_check_random_secret", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/test_install.py::32": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/install.py", "ggshield/core/errors.py"], "used_names": ["ExitCode", "Path", "assert_invoke_exited_with", "cli", "os"], "enclosing_function": "test_local_exist_is_dir", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_docker.py::198": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/secret_scan_common_options.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/scannable.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/docker.py"], "used_names": ["DOCKER_EXAMPLE_PATH", "DOCKER__INCOMPLETE_MANIFEST_EXAMPLE_PATH", "DockerImage", "ExitCode", "IGNORED_DEFAULT_WILDCARDS", "LayerInfo", "Mock", "Path", "StringScannable", "UNCHECKED_SECRET_PATCH", "assert_invoke_exited_with", "cli", "click", "init_exclusion_regexes", "json", "my_vcr", "patch", "pytest", "write_text"], "enclosing_function": "test_docker_scan_archive", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/cmd/secret/scan/secret_scan_common_options.py\nIGNORED_DEFAULT_WILDCARDS = [\n \"**/.git/*/**/*\", # only keep files in .git/ but not in subdirectories\n \"**/.pytest_cache/**/*\",\n \"**/.mypy_cache/**/*\",\n \"**/.venv/**/*\",\n \"**/.eggs/**/*\",\n \"**/.eggs-info/**/*\",\n \"**/vendor/**/*\",\n \"**/vendors/**/*\",\n \"**/node_modules/**/*\",\n \"top-1000.txt*\",\n \"**/*.storyboard*\",\n \"**/*.xib\",\n \"**/*.mdx*\",\n \"**/*.sops\",\n]\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/filter.py\ndef init_exclusion_regexes(paths_ignore: Iterable[str]) -> Set[Pattern[str]]:\n \"\"\"\n filter_set creates a set of paths of the ignored\n entries from 3 sources:\n .gitguardian.yaml\n files in .git\n files ignore in .gitignore\n \"\"\"\n res = set()\n for path in paths_ignore:\n if not is_pattern_valid(path):\n raise UsageError(f\"{path} is not a valid exclude pattern.\")\n res.add(re.compile(translate_user_pattern(path)))\n return res\n\n\n# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n\n# Source: ggshield/verticals/secret/docker.py\nclass LayerInfo:\n filename: str\n command: str\n diff_id: str\n\n def should_scan(self) -> bool:\n \"\"\"\n Returns True if a layer should be scanned, False otherwise.\n Only COPY and ADD layers should be scanned.\n \"\"\"\n if self.command == \"\":\n # Some images contain layers with no commands. Since we don't know how they have\n # been created, we must scan them.\n # Examples of such images from Docker Hub:\n # - aevea/release-notary:0.9.7\n # - redhat/ubi8:8.6-754\n return True\n else:\n return LAYER_TO_SCAN_PATTERN.search(self.command) is not None\n\nclass DockerImage:\n # The manifest.json file\n manifest: Dict[str, Any]\n\n # The Image JSON file\n # (see https://github.com/moby/moby/blob/master/image/spec/v1.2.md#terminology)\n image: Dict[str, Any]\n\n layer_infos: List[LayerInfo]\n\n @staticmethod\n @contextmanager\n def open(archive_path: Path) -> Generator[\"DockerImage\", None, None]:\n \"\"\"ContextManager to create a DockerImage instance.\"\"\"\n with tarfile.open(archive_path) as tar_file:\n yield DockerImage(archive_path, tar_file)\n\n def __init__(self, archive_path: Path, tar_file: tarfile.TarFile):\n \"\"\"Creates a DockerImage instance. Internal. Prefer using DockerImage.open().\"\"\"\n self.archive_path = archive_path\n self.tar_file = tar_file\n self._load_manifest()\n self._load_image()\n self.config_scannable = StringScannable(\n \"Dockerfile or build-args\", json.dumps(self.image, indent=2)\n )\n\n self._load_layer_infos()\n\n def _load_manifest(self) -> None:\n \"\"\"\n Reads \"manifest.json\", stores result in self.manifest\n \"\"\"\n manifest_file = self.tar_file.extractfile(\"manifest.json\")\n if manifest_file is None:\n raise InvalidDockerArchiveException(\"No manifest file found.\")\n\n self.manifest = json.load(manifest_file)[0]\n\n def _load_image(self) -> None:\n \"\"\"\n Reads the image JSON file, stores result in self.image\n \"\"\"\n try:\n config_file_path = self.manifest[\"Config\"]\n except KeyError:\n raise InvalidDockerArchiveException(\"No Config key in manifest.\")\n\n config_file_info = self.tar_file.getmember(config_file_path)\n if config_file_info is None:\n raise InvalidDockerArchiveException(\"No config file found.\")\n\n config_file = self.tar_file.extractfile(config_file_info)\n if config_file is None:\n raise InvalidDockerArchiveException(\"Config file could not be extracted.\")\n\n self.image = json.load(config_file)\n\n def _load_layer_infos(self) -> None:\n \"\"\"\n Fill self.layer_infos with LayerInfo instances for all non-empty layers\n \"\"\"\n\n #\n # manifest[\"Layers\"] contains a list of non-empty layers like this:\n #\n # \"/layer.tar\"\n layer_filenames = self.manifest[\"Layers\"]\n\n # image[\"history\"] contains a list of entries like this:\n # {\n # \"created\": ISO8601 timestamp,\n # \"created_by\": command to build the layer\n # \"empty_layer\": if present, equals true\n # }\n non_empty_history_entries = [\n x for x in self.image[\"history\"] if not x.get(\"empty_layer\")\n ]\n\n #\n # image[\"rootfs\"][\"diff_ids\"] contains the list of layer IDs\n diff_ids = self.image[\"rootfs\"][\"diff_ids\"]\n\n layer_infos = [\n LayerInfo(\n filename=filename,\n command=history.get(\"created_by\", \"\"),\n diff_id=diff_id,\n )\n for filename, history, diff_id in zip(\n layer_filenames, non_empty_history_entries, diff_ids\n )\n ]\n self.layer_infos = [x for x in layer_infos if x.should_scan()]\n\n def get_layer_scannables(\n self, layer_info: LayerInfo, exclusion_regexes: Set[re.Pattern[str]]\n ) -> Iterable[Scannable]:\n \"\"\"\n Extracts Scannable to be scanned for given layer.\n \"\"\"\n layer_filename = layer_info.filename\n layer_archive = tarfile.open(\n name=self.archive_path / layer_filename,\n fileobj=self.tar_file.extractfile(layer_filename),\n )\n\n layer_id = layer_info.diff_id\n\n for file_info in layer_archive:\n if not file_info.isfile():\n continue\n\n if file_info.size == 0:\n continue\n\n if not _validate_filepath(\n filepath=file_info.path, exclusion_regexes=exclusion_regexes\n ):\n continue\n\n yield DockerContentScannable(layer_id, layer_archive, file_info)", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 8998, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/cmd/secret/scan/secret_scan_common_options.py\nIGNORED_DEFAULT_WILDCARDS = [\n \"**/.git/*/**/*\", # only keep files in .git/ but not in subdirectories\n \"**/.pytest_cache/**/*\",\n \"**/.mypy_cache/**/*\",\n \"**/.venv/**/*\",\n \"**/.eggs/**/*\",\n \"**/.eggs-info/**/*\",\n \"**/vendor/**/*\",\n \"**/vendors/**/*\",\n \"**/node_modules/**/*\",\n \"top-1000.txt*\",\n \"**/*.storyboard*\",\n \"**/*.xib\",\n \"**/*.mdx*\",\n \"**/*.sops\",\n]\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/filter.py\ndef init_exclusion_regexes(paths_ignore: Iterable[str]) -> Set[Pattern[str]]:\n \"\"\"\n filter_set creates a set of paths of the ignored\n entries from 3 sources:\n .gitguardian.yaml\n files in .git\n files ignore in .gitignore\n \"\"\"\n res = set()\n for path in paths_ignore:\n if not is_pattern_valid(path):\n raise UsageError(f\"{path} is not a valid exclude pattern.\")\n res.add(re.compile(translate_user_pattern(path)))\n return res\n\n\n# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n\n# Source: ggshield/verticals/secret/docker.py\nclass LayerInfo:\n filename: str\n command: str\n diff_id: str\n\n def should_scan(self) -> bool:\n \"\"\"\n Returns True if a layer should be scanned, False otherwise.\n Only COPY and ADD layers should be scanned.\n \"\"\"\n if self.command == \"\":\n # Some images contain layers with no commands. Since we don't know how they have\n # been created, we must scan them.\n # Examples of such images from Docker Hub:\n # - aevea/release-notary:0.9.7\n # - redhat/ubi8:8.6-754\n return True\n else:\n return LAYER_TO_SCAN_PATTERN.search(self.command) is not None\n\nclass DockerImage:\n # The manifest.json file\n manifest: Dict[str, Any]\n\n # The Image JSON file\n # (see https://github.com/moby/moby/blob/master/image/spec/v1.2.md#terminology)\n image: Dict[str, Any]\n\n layer_infos: List[LayerInfo]\n\n @staticmethod\n @contextmanager\n def open(archive_path: Path) -> Generator[\"DockerImage\", None, None]:\n \"\"\"ContextManager to create a DockerImage instance.\"\"\"\n with tarfile.open(archive_path) as tar_file:\n yield DockerImage(archive_path, tar_file)\n\n def __init__(self, archive_path: Path, tar_file: tarfile.TarFile):\n \"\"\"Creates a DockerImage instance. Internal. Prefer using DockerImage.open().\"\"\"\n self.archive_path = archive_path\n self.tar_file = tar_file\n self._load_manifest()\n self._load_image()\n self.config_scannable = StringScannable(\n \"Dockerfile or build-args\", json.dumps(self.image, indent=2)\n )\n\n self._load_layer_infos()\n\n def _load_manifest(self) -> None:\n \"\"\"\n Reads \"manifest.json\", stores result in self.manifest\n \"\"\"\n manifest_file = self.tar_file.extractfile(\"manifest.json\")\n if manifest_file is None:\n raise InvalidDockerArchiveException(\"No manifest file found.\")\n\n self.manifest = json.load(manifest_file)[0]\n\n def _load_image(self) -> None:\n \"\"\"\n Reads the image JSON file, stores result in self.image\n \"\"\"\n try:\n config_file_path = self.manifest[\"Config\"]\n except KeyError:\n raise InvalidDockerArchiveException(\"No Config key in manifest.\")\n\n config_file_info = self.tar_file.getmember(config_file_path)\n if config_file_info is None:\n raise InvalidDockerArchiveException(\"No config file found.\")\n\n config_file = self.tar_file.extractfile(config_file_info)\n if config_file is None:\n raise InvalidDockerArchiveException(\"Config file could not be extracted.\")\n\n self.image = json.load(config_file)\n\n def _load_layer_infos(self) -> None:\n \"\"\"\n Fill self.layer_infos with LayerInfo instances for all non-empty layers\n \"\"\"\n\n #\n # manifest[\"Layers\"] contains a list of non-empty layers like this:\n #\n # \"/layer.tar\"\n layer_filenames = self.manifest[\"Layers\"]\n\n # image[\"history\"] contains a list of entries like this:\n # {\n # \"created\": ISO8601 timestamp,\n # \"created_by\": command to build the layer\n # \"empty_layer\": if present, equals true\n # }\n non_empty_history_entries = [\n x for x in self.image[\"history\"] if not x.get(\"empty_layer\")\n ]\n\n #\n # image[\"rootfs\"][\"diff_ids\"] contains the list of layer IDs\n diff_ids = self.image[\"rootfs\"][\"diff_ids\"]\n\n layer_infos = [\n LayerInfo(\n filename=filename,\n command=history.get(\"created_by\", \"\"),\n diff_id=diff_id,\n )\n for filename, history, diff_id in zip(\n layer_filenames, non_empty_history_entries, diff_ids\n )\n ]\n self.layer_infos = [x for x in layer_infos if x.should_scan()]\n\n def get_layer_scannables(\n self, layer_info: LayerInfo, exclusion_regexes: Set[re.Pattern[str]]\n ) -> Iterable[Scannable]:\n \"\"\"\n Extracts Scannable to be scanned for given layer.\n \"\"\"\n layer_filename = layer_info.filename\n layer_archive = tarfile.open(\n name=self.archive_path / layer_filename,\n fileobj=self.tar_file.extractfile(layer_filename),\n )\n\n layer_id = layer_info.diff_id\n\n for file_info in layer_archive:\n if not file_info.isfile():\n continue\n\n if file_info.size == 0:\n continue\n\n if not _validate_filepath(\n filepath=file_info.path, exclusion_regexes=exclusion_regexes\n ):\n continue\n\n yield DockerContentScannable(layer_id, layer_archive, file_info)", "n_chars_compressed": 8998, "compression_ratio": 1.0}, "tests/unit/cmd/auth/test_logout.py::155": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/constants.py", "ggshield/core/errors.py"], "used_names": ["Config", "DEFAULT_INSTANCE_URL", "ExitCode", "Mock", "add_instance_config"], "enclosing_function": "test_logout_all", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/constants.py\nDEFAULT_INSTANCE_URL = \"https://dashboard.gitguardian.com\"\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 8798, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/constants.py\nDEFAULT_INSTANCE_URL = \"https://dashboard.gitguardian.com\"\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 8798, "compression_ratio": 1.0}, "tests/unit/cmd/test_config.py::223": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/config/user_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py", "ggshield/utils/os.py"], "used_names": ["Config", "ExitCode"], "enclosing_function": "test_set_lifetime_invalid_value", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 15, "n_files_resolved": 6, "n_chars_extracted": 8700, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 8700, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_commit_range.py::42": {"resolved_imports": [], "used_names": ["GG_VALID_TOKEN", "Path", "Repository", "recreate_censored_content", "run_ggshield_scan"], "enclosing_function": "test_scan_commit_range_finds_old_leak", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/cmd/test_config_migrate.py::92": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["Path", "assert_invoke_ok", "cli", "yaml"], "enclosing_function": "test_config_migrate_cmd", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/plugin/test_update.py::26": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py", "ggshield/core/plugin/client.py", "ggshield/core/plugin/loader.py"], "used_names": ["ExitCode", "cli"], "enclosing_function": "test_update_requires_plugin_or_all_or_check", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_loader.py::113": {"resolved_imports": ["ggshield/core/config/enterprise_config.py", "ggshield/core/plugin/base.py", "ggshield/core/plugin/loader.py", "ggshield/core/plugin/registry.py"], "used_names": ["EnterpriseConfig", "Path", "PluginLoader", "patch"], "enclosing_function": "test_load_enabled_plugins_empty", "extracted_code": "# Source: ggshield/core/config/enterprise_config.py\nclass EnterpriseConfig:\n \"\"\"Enterprise configuration stored in ~/.config/ggshield/enterprise_config.yaml\"\"\"\n\n plugins: Dict[str, PluginConfig] = field(default_factory=dict)\n\n @classmethod\n def load(cls) -> \"EnterpriseConfig\":\n \"\"\"Load enterprise config from file.\"\"\"\n config_path = get_enterprise_config_filepath()\n data = load_yaml_dict(config_path)\n\n if data is None:\n return cls()\n\n # Convert plugin configs from dict\n plugins: Dict[str, PluginConfig] = {}\n for name, plugin_data in data.get(\"plugins\", {}).items():\n if isinstance(plugin_data, dict):\n plugins[name] = PluginConfig(\n enabled=plugin_data.get(\"enabled\", True),\n version=plugin_data.get(\"version\"),\n auto_update=plugin_data.get(\"auto_update\", True),\n )\n elif isinstance(plugin_data, bool):\n # Simple format: just enabled/disabled\n plugins[name] = PluginConfig(enabled=plugin_data)\n else:\n plugins[name] = PluginConfig(enabled=True)\n\n return cls(plugins=plugins)\n\n def save(self) -> None:\n \"\"\"Save enterprise config to file.\"\"\"\n config_path = get_enterprise_config_filepath()\n\n # Convert to dict for saving\n data: Dict[str, Any] = {\n \"plugins\": {\n name: {\n \"enabled\": cfg.enabled,\n \"version\": cfg.version,\n \"auto_update\": cfg.auto_update,\n }\n for name, cfg in self.plugins.items()\n }\n }\n\n # Remove None values for cleaner YAML\n for plugin_data in data[\"plugins\"].values():\n if plugin_data[\"version\"] is None:\n del plugin_data[\"version\"]\n\n save_yaml_dict(data, config_path)\n\n def enable_plugin(self, plugin_name: str, version: Optional[str] = None) -> None:\n \"\"\"Enable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n self.plugins[plugin_name] = PluginConfig()\n\n self.plugins[plugin_name].enabled = True\n if version:\n self.plugins[plugin_name].version = version\n\n def disable_plugin(self, plugin_name: str) -> None:\n \"\"\"Disable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n raise ValueError(f\"Plugin '{plugin_name}' is not configured\")\n\n self.plugins[plugin_name].enabled = False\n\n def is_plugin_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n # Default: disabled if not explicitly configured\n return plugin_config.enabled if plugin_config else False\n\n def get_plugin_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the configured version of a plugin.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n return plugin_config.version if plugin_config else None\n\n def remove_plugin(self, plugin_name: str) -> bool:\n \"\"\"Remove a plugin from configuration.\"\"\"\n if plugin_name in self.plugins:\n del self.plugins[plugin_name]\n return True\n return False\n\n\n# Source: ggshield/core/plugin/loader.py\nclass PluginLoader:\n \"\"\"Discovers and loads ggshield plugins from entry points and local wheels.\"\"\"\n\n def __init__(self, enterprise_config: EnterpriseConfig) -> None:\n self.enterprise_config = enterprise_config\n self.plugins_dir = get_plugins_dir()\n\n def discover_plugins(self) -> List[DiscoveredPlugin]:\n \"\"\"Discover all available plugins from entry points and local wheels.\"\"\"\n discovered: Dict[str, DiscoveredPlugin] = {}\n\n # 1. Discover from local wheels first and track their entry point names\n local_entry_point_names: set[str] = set()\n for wheel_info in self._scan_local_wheels():\n plugin_name: str = wheel_info[\"name\"]\n wheel_path: Path = wheel_info[\"path\"]\n wheel_version: str = wheel_info[\"version\"]\n entry_point_name: Optional[str] = wheel_info[\"entry_point_name\"]\n\n # Use entry point name as key if available, otherwise package name\n key = entry_point_name if entry_point_name else plugin_name\n if entry_point_name:\n local_entry_point_names.add(entry_point_name)\n\n discovered[key] = DiscoveredPlugin(\n name=key,\n entry_point=None,\n wheel_path=wheel_path,\n is_installed=True,\n is_enabled=self._is_enabled(key),\n version=wheel_version,\n )\n\n # 2. Discover from entry points (skip if already found in local wheels)\n for ep in self._get_entry_points():\n plugin_name = ep.name\n # Skip if this entry point is provided by a local wheel\n if plugin_name in local_entry_point_names:\n continue\n discovered[plugin_name] = DiscoveredPlugin(\n name=plugin_name,\n entry_point=ep,\n wheel_path=None,\n is_installed=True,\n is_enabled=self._is_enabled(plugin_name),\n version=self._get_entry_point_version(ep),\n )\n\n return list(discovered.values())\n\n def load_enabled_plugins(self) -> PluginRegistry:\n \"\"\"Load all enabled plugins and return a populated registry.\"\"\"\n registry = PluginRegistry()\n\n for discovered in self.discover_plugins():\n if not discovered.is_enabled:\n logger.debug(\"Skipping disabled plugin: %s\", discovered.name)\n continue\n\n try:\n plugin = self._load_plugin(discovered)\n if plugin is None:\n continue\n\n if not self._check_version_compatibility(plugin.metadata):\n logger.warning(\n \"Plugin %s requires ggshield >= %s, skipping\",\n plugin.metadata.name,\n plugin.metadata.min_ggshield_version,\n )\n continue\n\n plugin.on_load()\n plugin.register(registry)\n registry.register_plugin(plugin)\n\n logger.info(\n \"Loaded plugin: %s v%s\",\n plugin.metadata.name,\n plugin.metadata.version,\n )\n\n except Exception as e:\n logger.warning(\"Failed to load plugin %s: %s\", discovered.name, e)\n\n return registry\n\n def _load_plugin(self, discovered: DiscoveredPlugin) -> Optional[GGShieldPlugin]:\n \"\"\"Load a single plugin from discovery info.\"\"\"\n if discovered.wheel_path:\n return self._load_from_wheel(discovered.wheel_path)\n elif discovered.entry_point:\n return self._load_from_entry_point(discovered.entry_point)\n return None\n\n def _load_from_entry_point(\n self, ep: importlib.metadata.EntryPoint\n ) -> GGShieldPlugin:\n \"\"\"Load a plugin from an entry point.\"\"\"\n plugin_class = ep.load()\n return plugin_class()\n\n def _load_from_wheel(self, wheel_path: Path) -> Optional[GGShieldPlugin]:\n \"\"\"Load a plugin from a local wheel file.\n\n Wheels are extracted to a directory before loading because Python\n cannot import native extensions (.so/.pyd) directly from zip files.\n \"\"\"\n # Extract wheel to a directory alongside the wheel file\n extract_dir = wheel_path.parent / f\".{wheel_path.stem}_extracted\"\n\n try:\n # Extract if not already extracted or wheel is newer\n if not extract_dir.exists() or (\n wheel_path.stat().st_mtime > extract_dir.stat().st_mtime\n ):\n import shutil\n\n if extract_dir.exists():\n shutil.rmtree(extract_dir)\n\n from ggshield.utils.archive import safe_unpack\n\n safe_unpack(wheel_path, extract_dir)\n\n # Add extracted directory to sys.path\n extract_str = str(extract_dir)\n if extract_str not in sys.path:\n sys.path.append(extract_str)\n\n entry_point_str = self._read_wheel_entry_point(wheel_path)\n if not entry_point_str:\n logger.warning(\"No entry point found in wheel: %s\", wheel_path)\n return None\n\n module_name, class_name = entry_point_str.split(\":\")\n module = importlib.import_module(module_name)\n plugin_class = getattr(module, class_name)\n return plugin_class()\n except Exception as e:\n logger.warning(\"Failed to load wheel %s: %s\", wheel_path, e)\n return None\n\n def _read_wheel_entry_point(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the ggshield.plugins entry point value from a wheel's metadata.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[1] if result else None\n\n def _read_wheel_entry_point_name(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the entry point name from a wheel's entry_points.txt.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[0] if result else None\n\n def _get_entry_points(self) -> Iterator[importlib.metadata.EntryPoint]:\n \"\"\"Get all entry points in the ggshield.plugins group.\"\"\"\n try:\n eps = importlib.metadata.entry_points(group=PLUGIN_ENTRY_POINT_GROUP)\n yield from eps\n except TypeError:\n all_eps = importlib.metadata.entry_points()\n yield from all_eps.get(PLUGIN_ENTRY_POINT_GROUP, [])\n\n def _scan_local_wheels(self) -> Iterator[WheelInfo]:\n \"\"\"Scan the plugins directory for installed wheels.\"\"\"\n import json\n\n if not self.plugins_dir.exists():\n return\n\n for plugin_dir in self.plugins_dir.iterdir():\n if not plugin_dir.is_dir():\n continue\n\n manifest_path = plugin_dir / \"manifest.json\"\n if manifest_path.exists():\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\", \"\")\n wheel_path = plugin_dir / wheel_filename\n\n if wheel_path.exists():\n # Extract entry point name from wheel for deduplication\n entry_point_name = self._read_wheel_entry_point_name(wheel_path)\n yield WheelInfo(\n name=manifest[\"plugin_name\"],\n version=manifest[\"version\"],\n path=wheel_path,\n entry_point_name=entry_point_name,\n )\n except (json.JSONDecodeError, KeyError) as e:\n logger.warning(\"Invalid manifest in %s: %s\", plugin_dir, e)\n\n def _is_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled in config.\"\"\"\n plugin_config = self.enterprise_config.plugins.get(plugin_name)\n if plugin_config is None:\n return False\n return plugin_config.enabled\n\n def _get_entry_point_version(\n self, ep: importlib.metadata.EntryPoint\n ) -> Optional[str]:\n \"\"\"Get the version of a package providing an entry point.\"\"\"\n try:\n module_path = ep.value.split(\":\")[0]\n package_name = module_path.split(\".\")[0]\n dist = importlib.metadata.distribution(package_name)\n return dist.version\n except (importlib.metadata.PackageNotFoundError, IndexError):\n return None\n\n def _check_version_compatibility(self, metadata: PluginMetadata) -> bool:\n \"\"\"Check if plugin is compatible with current ggshield version.\"\"\"\n try:\n current = packaging_version.parse(ggshield_version)\n required = packaging_version.parse(metadata.min_ggshield_version)\n return current >= required\n except Exception as e:\n logger.error(\n \"Failed to parse version for plugin %s (requires %s): %s\",\n metadata.name,\n metadata.min_ggshield_version,\n e,\n )\n return False", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 12506, "extracted_code_full": "# Source: ggshield/core/config/enterprise_config.py\nclass EnterpriseConfig:\n \"\"\"Enterprise configuration stored in ~/.config/ggshield/enterprise_config.yaml\"\"\"\n\n plugins: Dict[str, PluginConfig] = field(default_factory=dict)\n\n @classmethod\n def load(cls) -> \"EnterpriseConfig\":\n \"\"\"Load enterprise config from file.\"\"\"\n config_path = get_enterprise_config_filepath()\n data = load_yaml_dict(config_path)\n\n if data is None:\n return cls()\n\n # Convert plugin configs from dict\n plugins: Dict[str, PluginConfig] = {}\n for name, plugin_data in data.get(\"plugins\", {}).items():\n if isinstance(plugin_data, dict):\n plugins[name] = PluginConfig(\n enabled=plugin_data.get(\"enabled\", True),\n version=plugin_data.get(\"version\"),\n auto_update=plugin_data.get(\"auto_update\", True),\n )\n elif isinstance(plugin_data, bool):\n # Simple format: just enabled/disabled\n plugins[name] = PluginConfig(enabled=plugin_data)\n else:\n plugins[name] = PluginConfig(enabled=True)\n\n return cls(plugins=plugins)\n\n def save(self) -> None:\n \"\"\"Save enterprise config to file.\"\"\"\n config_path = get_enterprise_config_filepath()\n\n # Convert to dict for saving\n data: Dict[str, Any] = {\n \"plugins\": {\n name: {\n \"enabled\": cfg.enabled,\n \"version\": cfg.version,\n \"auto_update\": cfg.auto_update,\n }\n for name, cfg in self.plugins.items()\n }\n }\n\n # Remove None values for cleaner YAML\n for plugin_data in data[\"plugins\"].values():\n if plugin_data[\"version\"] is None:\n del plugin_data[\"version\"]\n\n save_yaml_dict(data, config_path)\n\n def enable_plugin(self, plugin_name: str, version: Optional[str] = None) -> None:\n \"\"\"Enable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n self.plugins[plugin_name] = PluginConfig()\n\n self.plugins[plugin_name].enabled = True\n if version:\n self.plugins[plugin_name].version = version\n\n def disable_plugin(self, plugin_name: str) -> None:\n \"\"\"Disable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n raise ValueError(f\"Plugin '{plugin_name}' is not configured\")\n\n self.plugins[plugin_name].enabled = False\n\n def is_plugin_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n # Default: disabled if not explicitly configured\n return plugin_config.enabled if plugin_config else False\n\n def get_plugin_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the configured version of a plugin.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n return plugin_config.version if plugin_config else None\n\n def remove_plugin(self, plugin_name: str) -> bool:\n \"\"\"Remove a plugin from configuration.\"\"\"\n if plugin_name in self.plugins:\n del self.plugins[plugin_name]\n return True\n return False\n\n\n# Source: ggshield/core/plugin/loader.py\nclass PluginLoader:\n \"\"\"Discovers and loads ggshield plugins from entry points and local wheels.\"\"\"\n\n def __init__(self, enterprise_config: EnterpriseConfig) -> None:\n self.enterprise_config = enterprise_config\n self.plugins_dir = get_plugins_dir()\n\n def discover_plugins(self) -> List[DiscoveredPlugin]:\n \"\"\"Discover all available plugins from entry points and local wheels.\"\"\"\n discovered: Dict[str, DiscoveredPlugin] = {}\n\n # 1. Discover from local wheels first and track their entry point names\n local_entry_point_names: set[str] = set()\n for wheel_info in self._scan_local_wheels():\n plugin_name: str = wheel_info[\"name\"]\n wheel_path: Path = wheel_info[\"path\"]\n wheel_version: str = wheel_info[\"version\"]\n entry_point_name: Optional[str] = wheel_info[\"entry_point_name\"]\n\n # Use entry point name as key if available, otherwise package name\n key = entry_point_name if entry_point_name else plugin_name\n if entry_point_name:\n local_entry_point_names.add(entry_point_name)\n\n discovered[key] = DiscoveredPlugin(\n name=key,\n entry_point=None,\n wheel_path=wheel_path,\n is_installed=True,\n is_enabled=self._is_enabled(key),\n version=wheel_version,\n )\n\n # 2. Discover from entry points (skip if already found in local wheels)\n for ep in self._get_entry_points():\n plugin_name = ep.name\n # Skip if this entry point is provided by a local wheel\n if plugin_name in local_entry_point_names:\n continue\n discovered[plugin_name] = DiscoveredPlugin(\n name=plugin_name,\n entry_point=ep,\n wheel_path=None,\n is_installed=True,\n is_enabled=self._is_enabled(plugin_name),\n version=self._get_entry_point_version(ep),\n )\n\n return list(discovered.values())\n\n def load_enabled_plugins(self) -> PluginRegistry:\n \"\"\"Load all enabled plugins and return a populated registry.\"\"\"\n registry = PluginRegistry()\n\n for discovered in self.discover_plugins():\n if not discovered.is_enabled:\n logger.debug(\"Skipping disabled plugin: %s\", discovered.name)\n continue\n\n try:\n plugin = self._load_plugin(discovered)\n if plugin is None:\n continue\n\n if not self._check_version_compatibility(plugin.metadata):\n logger.warning(\n \"Plugin %s requires ggshield >= %s, skipping\",\n plugin.metadata.name,\n plugin.metadata.min_ggshield_version,\n )\n continue\n\n plugin.on_load()\n plugin.register(registry)\n registry.register_plugin(plugin)\n\n logger.info(\n \"Loaded plugin: %s v%s\",\n plugin.metadata.name,\n plugin.metadata.version,\n )\n\n except Exception as e:\n logger.warning(\"Failed to load plugin %s: %s\", discovered.name, e)\n\n return registry\n\n def _load_plugin(self, discovered: DiscoveredPlugin) -> Optional[GGShieldPlugin]:\n \"\"\"Load a single plugin from discovery info.\"\"\"\n if discovered.wheel_path:\n return self._load_from_wheel(discovered.wheel_path)\n elif discovered.entry_point:\n return self._load_from_entry_point(discovered.entry_point)\n return None\n\n def _load_from_entry_point(\n self, ep: importlib.metadata.EntryPoint\n ) -> GGShieldPlugin:\n \"\"\"Load a plugin from an entry point.\"\"\"\n plugin_class = ep.load()\n return plugin_class()\n\n def _load_from_wheel(self, wheel_path: Path) -> Optional[GGShieldPlugin]:\n \"\"\"Load a plugin from a local wheel file.\n\n Wheels are extracted to a directory before loading because Python\n cannot import native extensions (.so/.pyd) directly from zip files.\n \"\"\"\n # Extract wheel to a directory alongside the wheel file\n extract_dir = wheel_path.parent / f\".{wheel_path.stem}_extracted\"\n\n try:\n # Extract if not already extracted or wheel is newer\n if not extract_dir.exists() or (\n wheel_path.stat().st_mtime > extract_dir.stat().st_mtime\n ):\n import shutil\n\n if extract_dir.exists():\n shutil.rmtree(extract_dir)\n\n from ggshield.utils.archive import safe_unpack\n\n safe_unpack(wheel_path, extract_dir)\n\n # Add extracted directory to sys.path\n extract_str = str(extract_dir)\n if extract_str not in sys.path:\n sys.path.append(extract_str)\n\n entry_point_str = self._read_wheel_entry_point(wheel_path)\n if not entry_point_str:\n logger.warning(\"No entry point found in wheel: %s\", wheel_path)\n return None\n\n module_name, class_name = entry_point_str.split(\":\")\n module = importlib.import_module(module_name)\n plugin_class = getattr(module, class_name)\n return plugin_class()\n except Exception as e:\n logger.warning(\"Failed to load wheel %s: %s\", wheel_path, e)\n return None\n\n def _read_wheel_entry_point(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the ggshield.plugins entry point value from a wheel's metadata.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[1] if result else None\n\n def _read_wheel_entry_point_name(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the entry point name from a wheel's entry_points.txt.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[0] if result else None\n\n def _get_entry_points(self) -> Iterator[importlib.metadata.EntryPoint]:\n \"\"\"Get all entry points in the ggshield.plugins group.\"\"\"\n try:\n eps = importlib.metadata.entry_points(group=PLUGIN_ENTRY_POINT_GROUP)\n yield from eps\n except TypeError:\n all_eps = importlib.metadata.entry_points()\n yield from all_eps.get(PLUGIN_ENTRY_POINT_GROUP, [])\n\n def _scan_local_wheels(self) -> Iterator[WheelInfo]:\n \"\"\"Scan the plugins directory for installed wheels.\"\"\"\n import json\n\n if not self.plugins_dir.exists():\n return\n\n for plugin_dir in self.plugins_dir.iterdir():\n if not plugin_dir.is_dir():\n continue\n\n manifest_path = plugin_dir / \"manifest.json\"\n if manifest_path.exists():\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\", \"\")\n wheel_path = plugin_dir / wheel_filename\n\n if wheel_path.exists():\n # Extract entry point name from wheel for deduplication\n entry_point_name = self._read_wheel_entry_point_name(wheel_path)\n yield WheelInfo(\n name=manifest[\"plugin_name\"],\n version=manifest[\"version\"],\n path=wheel_path,\n entry_point_name=entry_point_name,\n )\n except (json.JSONDecodeError, KeyError) as e:\n logger.warning(\"Invalid manifest in %s: %s\", plugin_dir, e)\n\n def _is_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled in config.\"\"\"\n plugin_config = self.enterprise_config.plugins.get(plugin_name)\n if plugin_config is None:\n return False\n return plugin_config.enabled\n\n def _get_entry_point_version(\n self, ep: importlib.metadata.EntryPoint\n ) -> Optional[str]:\n \"\"\"Get the version of a package providing an entry point.\"\"\"\n try:\n module_path = ep.value.split(\":\")[0]\n package_name = module_path.split(\".\")[0]\n dist = importlib.metadata.distribution(package_name)\n return dist.version\n except (importlib.metadata.PackageNotFoundError, IndexError):\n return None\n\n def _check_version_compatibility(self, metadata: PluginMetadata) -> bool:\n \"\"\"Check if plugin is compatible with current ggshield version.\"\"\"\n try:\n current = packaging_version.parse(ggshield_version)\n required = packaging_version.parse(metadata.min_ggshield_version)\n return current >= required\n except Exception as e:\n logger.error(\n \"Failed to parse version for plugin %s (requires %s): %s\",\n metadata.name,\n metadata.min_ggshield_version,\n e,\n )\n return False", "n_chars_compressed": 12506, "compression_ratio": 1.0}, "tests/unit/cmd/plugin/test_status.py::54": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py", "ggshield/core/plugin/client.py"], "used_names": ["ExitCode", "PluginCatalog", "cli", "mock"], "enclosing_function": "test_status_shows_plan", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/plugin/client.py\nclass PluginCatalog:\n \"\"\"Catalog of available plugins for the account.\"\"\"\n\n plan: str\n features: Dict[str, bool]\n plugins: List[PluginInfo]", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 2238, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/plugin/client.py\nclass PluginCatalog:\n \"\"\"Catalog of available plugins for the account.\"\"\"\n\n plan: str\n features: Dict[str, bool]\n plugins: List[PluginInfo]", "n_chars_compressed": 2238, "compression_ratio": 1.0}, "tests/unit/utils/test_git_shell.py::640": {"resolved_imports": ["ggshield/core/tar_utils.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["Repository", "get_default_branch", "git"], "enclosing_function": "test_get_default_branch_without_remote", "extracted_code": "# Source: ggshield/utils/git_shell.py\ndef git(\n command: List[str],\n timeout: int = COMMAND_TIMEOUT,\n check: bool = True,\n cwd: Optional[Union[str, Path]] = None,\n log_stderr: bool = True,\n ignore_git_config: bool = True,\n) -> str:\n \"\"\"Calls git with the given arguments, returns stdout as a string\"\"\"\n env = os.environ.copy()\n # Ensure git messages are in English\n env[\"LANG\"] = \"C\"\n # Ensure git behavior is not affected by the user git configuration, but give us a\n # way to set some configuration (useful for safe.directory)\n if ignore_git_config:\n env[\"GIT_CONFIG_GLOBAL\"] = os.getenv(\"GG_GIT_CONFIG\", \"\")\n env[\"GIT_CONFIG_SYSTEM\"] = \"\"\n\n if cwd is None:\n cwd = Path.cwd()\n\n try:\n logger.debug(\"command=%s timeout=%d\", command, timeout)\n result = subprocess.run(\n (\n [\n _get_git_path(),\n \"-c\",\n \"core.quotePath=false\",\n \"-c\",\n \"safe.directory=*\",\n ]\n + (\n [\"-c\", \"core.longpaths=true\"]\n if platform.system() == \"Windows\"\n else []\n )\n + command\n ),\n check=check,\n capture_output=True,\n timeout=timeout,\n env=env,\n cwd=str(cwd),\n )\n if result.stderr and log_stderr:\n logger.warning(\n \"command=%s, stderr=%s\",\n command,\n result.stderr.decode(\"utf-8\", errors=\"ignore\"),\n )\n return result.stdout.decode(\"utf-8\", errors=\"ignore\").rstrip()\n except subprocess.CalledProcessError as exc:\n stderr = exc.stderr.decode(\"utf-8\", errors=\"ignore\")\n if log_stderr:\n logger.error(\"command=%s, stderr=%s\", command, stderr)\n if \"detected dubious ownership in repository\" in stderr:\n raise GitError(\n \"Git command failed because of a dubious ownership in repository.\\n\"\n \"If you still want to run ggshield, make sure you mark \"\n \"the current repository as safe for git with:\\n\"\n \" git config --global --add safe.directory \"\n )\n raise exc\n except subprocess.TimeoutExpired:\n raise GitCommandTimeoutExpired(\n 'Command \"{}\" timed out'.format(\" \".join(command))\n )\n\ndef get_default_branch(wd: Optional[Union[str, Path]] = None) -> str:\n \"\"\"\n Return the default branch of the repository.\n\n Try to get the default branch from a remote, either origin or the first remote,\n otherwise return the config init.defaultBranch.\n \"\"\"\n if not wd:\n wd = Path.cwd()\n\n remotes = get_remotes(wd)\n remote = None\n if \"origin\" in remotes:\n remote = \"origin\"\n elif len(remotes) > 0:\n remote = remotes[0]\n\n default_branch = None\n if remote is not None:\n for line in git([\"remote\", \"show\", remote], cwd=wd).splitlines():\n line = line.strip()\n if line.startswith(\"HEAD branch: \"):\n default_branch = remote + \"/\" + line[len(\"HEAD branch: \") :]\n break\n\n if default_branch is None:\n return git([\"config\", \"init.defaultBranch\"], cwd=wd).strip()\n\n return default_branch", "n_imports_parsed": 14, "n_files_resolved": 3, "n_chars_extracted": 3388, "extracted_code_full": "# Source: ggshield/utils/git_shell.py\ndef git(\n command: List[str],\n timeout: int = COMMAND_TIMEOUT,\n check: bool = True,\n cwd: Optional[Union[str, Path]] = None,\n log_stderr: bool = True,\n ignore_git_config: bool = True,\n) -> str:\n \"\"\"Calls git with the given arguments, returns stdout as a string\"\"\"\n env = os.environ.copy()\n # Ensure git messages are in English\n env[\"LANG\"] = \"C\"\n # Ensure git behavior is not affected by the user git configuration, but give us a\n # way to set some configuration (useful for safe.directory)\n if ignore_git_config:\n env[\"GIT_CONFIG_GLOBAL\"] = os.getenv(\"GG_GIT_CONFIG\", \"\")\n env[\"GIT_CONFIG_SYSTEM\"] = \"\"\n\n if cwd is None:\n cwd = Path.cwd()\n\n try:\n logger.debug(\"command=%s timeout=%d\", command, timeout)\n result = subprocess.run(\n (\n [\n _get_git_path(),\n \"-c\",\n \"core.quotePath=false\",\n \"-c\",\n \"safe.directory=*\",\n ]\n + (\n [\"-c\", \"core.longpaths=true\"]\n if platform.system() == \"Windows\"\n else []\n )\n + command\n ),\n check=check,\n capture_output=True,\n timeout=timeout,\n env=env,\n cwd=str(cwd),\n )\n if result.stderr and log_stderr:\n logger.warning(\n \"command=%s, stderr=%s\",\n command,\n result.stderr.decode(\"utf-8\", errors=\"ignore\"),\n )\n return result.stdout.decode(\"utf-8\", errors=\"ignore\").rstrip()\n except subprocess.CalledProcessError as exc:\n stderr = exc.stderr.decode(\"utf-8\", errors=\"ignore\")\n if log_stderr:\n logger.error(\"command=%s, stderr=%s\", command, stderr)\n if \"detected dubious ownership in repository\" in stderr:\n raise GitError(\n \"Git command failed because of a dubious ownership in repository.\\n\"\n \"If you still want to run ggshield, make sure you mark \"\n \"the current repository as safe for git with:\\n\"\n \" git config --global --add safe.directory \"\n )\n raise exc\n except subprocess.TimeoutExpired:\n raise GitCommandTimeoutExpired(\n 'Command \"{}\" timed out'.format(\" \".join(command))\n )\n\ndef get_default_branch(wd: Optional[Union[str, Path]] = None) -> str:\n \"\"\"\n Return the default branch of the repository.\n\n Try to get the default branch from a remote, either origin or the first remote,\n otherwise return the config init.defaultBranch.\n \"\"\"\n if not wd:\n wd = Path.cwd()\n\n remotes = get_remotes(wd)\n remote = None\n if \"origin\" in remotes:\n remote = \"origin\"\n elif len(remotes) > 0:\n remote = remotes[0]\n\n default_branch = None\n if remote is not None:\n for line in git([\"remote\", \"show\", remote], cwd=wd).splitlines():\n line = line.strip()\n if line.startswith(\"HEAD branch: \"):\n default_branch = remote + \"/\" + line[len(\"HEAD branch: \") :]\n break\n\n if default_branch is None:\n return git([\"config\", \"init.defaultBranch\"], cwd=wd).strip()\n\n return default_branch", "n_chars_compressed": 3388, "compression_ratio": 1.0}, "tests/unit/core/scan/test_file.py::105": {"resolved_imports": ["ggshield/core/scan/file.py", "ggshield/core/scan/scannable.py"], "used_names": ["File"], "enclosing_function": "test_file_is_longer_than_does_not_read_utf8_file", "extracted_code": "# Source: ggshield/core/scan/file.py\nclass File(Scannable):\n \"\"\"Implementation of Scannable for files from the disk.\"\"\"\n\n def __init__(self, path: Union[str, Path]):\n super().__init__()\n self._path = Path(path)\n\n @property\n def url(self) -> str:\n return url_for_path(self._path)\n\n @property\n def filename(self) -> str:\n return str(self._path)\n\n @property\n def path(self) -> Path:\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n if self._utf8_encoded_size is not None:\n # We already have the encoded size, easy\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n with self.path.open(\"rb\") as fp:\n (\n result,\n self._content,\n self._utf8_encoded_size,\n ) = Scannable._is_file_longer_than(fp, max_utf8_encoded_size)\n return result\n\n def _read_content(self) -> None:\n if self._content is None:\n with self.path.open(\"rb\") as f:\n self._content, self._utf8_encoded_size = Scannable._decode_bytes(\n f.read()\n )", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 1185, "extracted_code_full": "# Source: ggshield/core/scan/file.py\nclass File(Scannable):\n \"\"\"Implementation of Scannable for files from the disk.\"\"\"\n\n def __init__(self, path: Union[str, Path]):\n super().__init__()\n self._path = Path(path)\n\n @property\n def url(self) -> str:\n return url_for_path(self._path)\n\n @property\n def filename(self) -> str:\n return str(self._path)\n\n @property\n def path(self) -> Path:\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n if self._utf8_encoded_size is not None:\n # We already have the encoded size, easy\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n with self.path.open(\"rb\") as fp:\n (\n result,\n self._content,\n self._utf8_encoded_size,\n ) = Scannable._is_file_longer_than(fp, max_utf8_encoded_size)\n return result\n\n def _read_content(self) -> None:\n if self._content is None:\n with self.path.open(\"rb\") as f:\n self._content, self._utf8_encoded_size = Scannable._decode_bytes(\n f.read()\n )", "n_chars_compressed": 1185, "compression_ratio": 1.0}, "tests/unit/core/ui/test_client_callbacks.py::25": {"resolved_imports": ["ggshield/core/ui/client_callbacks.py"], "used_names": ["ClientCallbacks", "patch"], "enclosing_function": "test_on_rate_limited_debouncing", "extracted_code": "# Source: ggshield/core/ui/client_callbacks.py\nclass ClientCallbacks(GGClientCallbacks):\n \"\"\"Implementation of GGClientCallbacks using GGShieldUI to show messages\"\"\"\n\n def __init__(self):\n self._last_rate_limit_message_at = 0.0\n\n def on_rate_limited(self, delay: int) -> None:\n # When we are rate-limited, all scanning threads report the rate limit. To avoid\n # spamming the console, only show a message if the previous rate limit message\n # was more than RATE_LIMIT_MESSAGE_MINIMUM_INTERVAL seconds ago\n now = time.time()\n if now - self._last_rate_limit_message_at < RATE_LIMIT_MESSAGE_MINIMUM_INTERVAL:\n return\n ui.display_warning(f\"Rate-limit hit, retrying in {delay} seconds\")\n self._last_rate_limit_message_at = now", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 796, "extracted_code_full": "# Source: ggshield/core/ui/client_callbacks.py\nclass ClientCallbacks(GGClientCallbacks):\n \"\"\"Implementation of GGClientCallbacks using GGShieldUI to show messages\"\"\"\n\n def __init__(self):\n self._last_rate_limit_message_at = 0.0\n\n def on_rate_limited(self, delay: int) -> None:\n # When we are rate-limited, all scanning threads report the rate limit. To avoid\n # spamming the console, only show a message if the previous rate limit message\n # was more than RATE_LIMIT_MESSAGE_MINIMUM_INTERVAL seconds ago\n now = time.time()\n if now - self._last_rate_limit_message_at < RATE_LIMIT_MESSAGE_MINIMUM_INTERVAL:\n return\n ui.display_warning(f\"Rate-limit hit, retrying in {delay} seconds\")\n self._last_rate_limit_message_at = now", "n_chars_compressed": 796, "compression_ratio": 1.0}, "tests/unit/cmd/honeytoken/test_honeytoken.py::176": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["Any", "CliRunner", "Dict", "ExitCode", "List", "RequestMock", "Union", "assert_invoke_exited_with", "cli", "create_json_response", "pytest"], "enclosing_function": "test_honeytoken_create_error_403", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/cmd/auth/test_login.py::129": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/constants.py", "ggshield/core/errors.py", "ggshield/utils/datetime.py", "ggshield/verticals/auth/oauth.py"], "used_names": ["Config", "assert_invoke_ok", "cli"], "enclosing_function": "test_auth_login_token_default_instance", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_imports_parsed": 16, "n_files_resolved": 6, "n_chars_extracted": 9420, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_chars_compressed": 9420, "compression_ratio": 1.0}, "tests/unit/cmd/auth/test_login.py::139": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/constants.py", "ggshield/core/errors.py", "ggshield/utils/datetime.py", "ggshield/verticals/auth/oauth.py"], "used_names": ["Config", "assert_invoke_ok", "cli"], "enclosing_function": "test_auth_login_token_default_instance", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_imports_parsed": 16, "n_files_resolved": 6, "n_chars_extracted": 9420, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_chars_compressed": 9420, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_client.py::32": {"resolved_imports": ["ggshield/core/plugin/client.py", "ggshield/core/plugin/platform.py"], "used_names": ["PluginInfo"], "enclosing_function": "test_is_platform_supported_no_restrictions", "extracted_code": "# Source: ggshield/core/plugin/client.py\nclass PluginInfo:\n \"\"\"Information about an available plugin.\"\"\"\n\n name: str\n display_name: str\n description: str\n available: bool\n latest_version: Optional[str]\n supported_platforms: List[str] = field(default_factory=list)\n reason: Optional[str] = None\n\n def is_platform_supported(self, platform: str, arch: str) -> bool:\n \"\"\"Check if this plugin supports the given platform/arch.\"\"\"\n if not self.supported_platforms:\n return True\n return (\n f\"{platform}-{arch}\" in self.supported_platforms\n or \"any-any\" in self.supported_platforms\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 664, "extracted_code_full": "# Source: ggshield/core/plugin/client.py\nclass PluginInfo:\n \"\"\"Information about an available plugin.\"\"\"\n\n name: str\n display_name: str\n description: str\n available: bool\n latest_version: Optional[str]\n supported_platforms: List[str] = field(default_factory=list)\n reason: Optional[str] = None\n\n def is_platform_supported(self, platform: str, arch: str) -> bool:\n \"\"\"Check if this plugin supports the given platform/arch.\"\"\"\n if not self.supported_platforms:\n return True\n return (\n f\"{platform}-{arch}\" in self.supported_platforms\n or \"any-any\" in self.supported_platforms\n )", "n_chars_compressed": 664, "compression_ratio": 1.0}, "tests/unit/cmd/test_config.py::149": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/config/user_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py", "ggshield/utils/os.py"], "used_names": ["Config", "ExitCode", "add_instance_config", "pytest"], "enclosing_function": "test_set_lifetime_default_config_value", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 15, "n_files_resolved": 6, "n_chars_extracted": 8700, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 8700, "compression_ratio": 1.0}, "tests/unit/cmd/auth/test_login.py::261": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/constants.py", "ggshield/core/errors.py", "ggshield/utils/datetime.py", "ggshield/verticals/auth/oauth.py"], "used_names": ["Config", "assert_invoke_ok", "cli"], "enclosing_function": "test_auth_login_token_update_existing_config", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_imports_parsed": 16, "n_files_resolved": 6, "n_chars_extracted": 9420, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_chars_compressed": 9420, "compression_ratio": 1.0}, "tests/unit/core/test_client.py::279": {"resolved_imports": ["ggshield/core/client.py", "ggshield/core/config/config.py", "ggshield/core/errors.py"], "used_names": ["create_session", "pytest"], "enclosing_function": "test_create_session_with_self_signed_option", "extracted_code": "# Source: ggshield/core/client.py\ndef create_session(allow_self_signed: bool = False) -> Session:\n session = Session()\n if allow_self_signed:\n ui.display_warning(\n \"SSL verification is disabled. Your connection to the GitGuardian API is NOT encrypted \"\n \"and is vulnerable to man-in-the-middle attacks. Traffic, including API keys and scan results, \"\n \"can be intercepted and modified.\"\n )\n ui.display_warning(\n \"To securely use self-signed certificates with Python >= 3.10, disable this option and \"\n \"install your certificate in your system's trust store. \"\n \"See: https://docs.gitguardian.com/ggshield-docs/configuration#support-for-self-signed-certificates\"\n )\n urllib3.disable_warnings()\n session.verify = False\n # Mount HTTPAdapter with larger pool sizes for better concurrency\n adapter = HTTPAdapter(\n pool_maxsize=100, # default 10\n )\n session.mount(\"http://\", adapter)\n session.mount(\"https://\", adapter)\n return session", "n_imports_parsed": 12, "n_files_resolved": 3, "n_chars_extracted": 1069, "extracted_code_full": "# Source: ggshield/core/client.py\ndef create_session(allow_self_signed: bool = False) -> Session:\n session = Session()\n if allow_self_signed:\n ui.display_warning(\n \"SSL verification is disabled. Your connection to the GitGuardian API is NOT encrypted \"\n \"and is vulnerable to man-in-the-middle attacks. Traffic, including API keys and scan results, \"\n \"can be intercepted and modified.\"\n )\n ui.display_warning(\n \"To securely use self-signed certificates with Python >= 3.10, disable this option and \"\n \"install your certificate in your system's trust store. \"\n \"See: https://docs.gitguardian.com/ggshield-docs/configuration#support-for-self-signed-certificates\"\n )\n urllib3.disable_warnings()\n session.verify = False\n # Mount HTTPAdapter with larger pool sizes for better concurrency\n adapter = HTTPAdapter(\n pool_maxsize=100, # default 10\n )\n session.mount(\"http://\", adapter)\n session.mount(\"https://\", adapter)\n return session", "n_chars_compressed": 1069, "compression_ratio": 1.0}, "tests/unit/core/config/test_config.py::243": {"resolved_imports": ["ggshield/core/config/auth_config.py", "ggshield/core/config/config.py", "ggshield/core/config/utils.py", "ggshield/core/constants.py", "ggshield/core/errors.py", "ggshield/core/url_utils.py"], "used_names": ["Config", "os", "sys"], "enclosing_function": "test_v1_in_api_url_env", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_imports_parsed": 15, "n_files_resolved": 6, "n_chars_extracted": 8037, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_chars_compressed": 8037, "compression_ratio": 1.0}, "tests/unit/core/scan/test_commit.py::495": {"resolved_imports": ["ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/utils/git_shell.py"], "used_names": ["Commit", "Filemode", "Path", "Repository", "pytest", "subprocess"], "enclosing_function": "test_from_merge", "extracted_code": "# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/utils/git_shell.py\nclass Filemode(Enum):\n \"\"\"\n Enum class for git filemode.\n \"\"\"\n\n MODIFY = \"modified file\"\n DELETE = \"deleted file\"\n NEW = \"new file\"\n RENAME = \"renamed file\"\n FILE = \"file\"\n UNMERGED = \"unmerged file\"\n UNKNOWN = \"unknown\"", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 4557, "extracted_code_full": "# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/utils/git_shell.py\nclass Filemode(Enum):\n \"\"\"\n Enum class for git filemode.\n \"\"\"\n\n MODIFY = \"modified file\"\n DELETE = \"deleted file\"\n NEW = \"new file\"\n RENAME = \"renamed file\"\n FILE = \"file\"\n UNMERGED = \"unmerged file\"\n UNKNOWN = \"unknown\"", "n_chars_compressed": 4557, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_precommit.py::31": {"resolved_imports": [], "used_names": ["CalledProcessError", "GG_VALID_TOKEN", "Path", "Repository", "pytest", "recreate_censored_content", "run_ggshield"], "enclosing_function": "test_scan_precommit", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/cmd/auth/test_login.py::140": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/constants.py", "ggshield/core/errors.py", "ggshield/utils/datetime.py", "ggshield/verticals/auth/oauth.py"], "used_names": ["Config", "assert_invoke_ok", "cli"], "enclosing_function": "test_auth_login_token_default_instance", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_imports_parsed": 16, "n_files_resolved": 6, "n_chars_extracted": 9420, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_chars_compressed": 9420, "compression_ratio": 1.0}, "tests/unit/cmd/auth/test_login.py::145": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/constants.py", "ggshield/core/errors.py", "ggshield/utils/datetime.py", "ggshield/verticals/auth/oauth.py"], "used_names": ["Config", "assert_invoke_ok", "cli"], "enclosing_function": "test_auth_login_token_default_instance", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_imports_parsed": 16, "n_files_resolved": 6, "n_chars_extracted": 9420, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_chars_compressed": 9420, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_precommit.py::103": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/precommit.py", "ggshield/utils/os.py"], "used_names": ["check_is_merge_without_conflict", "get_merge_branch_from_reflog"], "enclosing_function": "test_get_merge_branch_from_reflog", "extracted_code": "# Source: ggshield/cmd/secret/scan/precommit.py\ndef check_is_merge_without_conflict() -> bool:\n \"\"\"Check if the reflog action is a merge without conflict\"\"\"\n return os.getenv(\"GIT_REFLOG_ACTION\", \"\").split(\" \")[0] == \"merge\"\n\ndef get_merge_branch_from_reflog() -> str:\n \"\"\"Get the branch that was merged from the reflog\"\"\"\n return os.getenv(\"GIT_REFLOG_ACTION\", \"\").split(\" \")[-1]", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 392, "extracted_code_full": "# Source: ggshield/cmd/secret/scan/precommit.py\ndef check_is_merge_without_conflict() -> bool:\n \"\"\"Check if the reflog action is a merge without conflict\"\"\"\n return os.getenv(\"GIT_REFLOG_ACTION\", \"\").split(\" \")[0] == \"merge\"\n\ndef get_merge_branch_from_reflog() -> str:\n \"\"\"Get the branch that was merged from the reflog\"\"\"\n return os.getenv(\"GIT_REFLOG_ACTION\", \"\").split(\" \")[-1]", "n_chars_compressed": 392, "compression_ratio": 1.0}, "tests/unit/core/test_cache.py::20": {"resolved_imports": ["ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/types.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["Cache"], "enclosing_function": "test_defaults", "extracted_code": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )", "n_imports_parsed": 11, "n_files_resolved": 5, "n_chars_extracted": 2587, "extracted_code_full": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )", "n_chars_compressed": 2587, "compression_ratio": 1.0}, "tests/unit/core/test_env_utils.py::101": {"resolved_imports": ["ggshield/core/env_utils.py", "ggshield/utils/os.py"], "used_names": ["TRACKED_ENV_VARS", "cd", "load_dot_env", "pytest"], "enclosing_function": "test_load_dot_env_returns_set_vars", "extracted_code": "# Source: ggshield/core/env_utils.py\nTRACKED_ENV_VARS = {\n \"GITGUARDIAN_INSTANCE\",\n \"GITGUARDIAN_API_URL\",\n \"GITGUARDIAN_API_KEY\",\n \"GITGUARDIAN_GIT_REMOTE_FALLBACK_URL\",\n}\n\ndef load_dot_env() -> Set[str]:\n \"\"\"\n Loads .env file into os.environ.\n Return the list of env vars that were set by the dotenv file\n among env vars in TRACKED_ENV_VARS\n \"\"\"\n dont_load_env = getenv_bool(\"GITGUARDIAN_DONT_LOAD_ENV\")\n if dont_load_env:\n logger.debug(\"Not loading .env, GITGUARDIAN_DONT_LOAD_ENV is set\")\n return set()\n\n dot_env_path = _find_dot_env()\n if dot_env_path:\n dot_env_path = dot_env_path.absolute()\n logger.debug(\"Loading environment file %s\", dot_env_path)\n load_dotenv(dot_env_path, override=True)\n\n return dotenv_values(dot_env_path).keys() & TRACKED_ENV_VARS\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1152, "extracted_code_full": "# Source: ggshield/core/env_utils.py\nTRACKED_ENV_VARS = {\n \"GITGUARDIAN_INSTANCE\",\n \"GITGUARDIAN_API_URL\",\n \"GITGUARDIAN_API_KEY\",\n \"GITGUARDIAN_GIT_REMOTE_FALLBACK_URL\",\n}\n\ndef load_dot_env() -> Set[str]:\n \"\"\"\n Loads .env file into os.environ.\n Return the list of env vars that were set by the dotenv file\n among env vars in TRACKED_ENV_VARS\n \"\"\"\n dont_load_env = getenv_bool(\"GITGUARDIAN_DONT_LOAD_ENV\")\n if dont_load_env:\n logger.debug(\"Not loading .env, GITGUARDIAN_DONT_LOAD_ENV is set\")\n return set()\n\n dot_env_path = _find_dot_env()\n if dot_env_path:\n dot_env_path = dot_env_path.absolute()\n logger.debug(\"Loading environment file %s\", dot_env_path)\n load_dotenv(dot_env_path, override=True)\n\n return dotenv_values(dot_env_path).keys() & TRACKED_ENV_VARS\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_chars_compressed": 1152, "compression_ratio": 1.0}, "tests/unit/cmd/test_ignore.py::257": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/ignore.py", "ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Cache", "Config", "IgnoredMatch", "ignore_last_found"], "enclosing_function": "test_ignore_last_found_preserve_previous_config", "extracted_code": "# Source: ggshield/cmd/secret/ignore.py\ndef ignore_last_found(config: Config, cache: Cache) -> int:\n \"\"\"\n Add last found secrets from .cache_ggshield into ignored_matches\n in the local .gitguardian.yaml config file so that they are ignored on next run\n Secrets are added as `hash`\n \"\"\"\n for secret in cache.last_found_secrets:\n config.add_ignored_match(secret)\n return len(cache.last_found_secrets)\n\n\n# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/types.py\nclass IgnoredMatch(FilteredConfig):\n match: str\n name: Optional[str] = None\n\n def __post_init__(self) -> None:\n if self.name is None:\n self.name = \"\"", "n_imports_parsed": 14, "n_files_resolved": 11, "n_chars_extracted": 11268, "extracted_code_full": "# Source: ggshield/cmd/secret/ignore.py\ndef ignore_last_found(config: Config, cache: Cache) -> int:\n \"\"\"\n Add last found secrets from .cache_ggshield into ignored_matches\n in the local .gitguardian.yaml config file so that they are ignored on next run\n Secrets are added as `hash`\n \"\"\"\n for secret in cache.last_found_secrets:\n config.add_ignored_match(secret)\n return len(cache.last_found_secrets)\n\n\n# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/types.py\nclass IgnoredMatch(FilteredConfig):\n match: str\n name: Optional[str] = None\n\n def __post_init__(self) -> None:\n if self.name is None:\n self.name = \"\"", "n_chars_compressed": 11268, "compression_ratio": 1.0}, "tests/functional/secret/test_merge_commit.py::78": {"resolved_imports": [], "used_names": ["CalledProcessError", "Path", "SecretLocation", "generate_repo_with_merge_commit", "pytest"], "enclosing_function": "test_merge_commit_with_conflict_and_secret_in_conflict", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/cmd/test_ignore.py::226": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/ignore.py", "ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Cache", "Match", "PolicyBreak", "get_ignore_sha"], "enclosing_function": "test_do_not_duplicate_last_found_secrets", "extracted_code": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/filter.py\ndef get_ignore_sha(policy_break: PolicyBreak) -> str:\n hashable = \"\".join(\n [\n f\"{match.match},{match.match_type}\"\n for match in sorted(\n policy_break.matches, key=operator.attrgetter(\"match_type\")\n )\n ]\n )\n\n return hashlib.sha256(hashable.encode(\"UTF-8\")).hexdigest()", "n_imports_parsed": 14, "n_files_resolved": 11, "n_chars_extracted": 2963, "extracted_code_full": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/filter.py\ndef get_ignore_sha(policy_break: PolicyBreak) -> str:\n hashable = \"\".join(\n [\n f\"{match.match},{match.match_type}\"\n for match in sorted(\n policy_break.matches, key=operator.attrgetter(\"match_type\")\n )\n ]\n )\n\n return hashlib.sha256(hashable.encode(\"UTF-8\")).hexdigest()", "n_chars_compressed": 2963, "compression_ratio": 1.0}, "tests/unit/cmd/test_ignore.py::71": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/ignore.py", "ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["ExitCode", "assert_invoke_exited_with", "cli"], "enclosing_function": "test_error_sha_last_found", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 14, "n_files_resolved": 11, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_client.py::183": {"resolved_imports": ["ggshield/core/plugin/client.py", "ggshield/core/plugin/platform.py"], "used_names": ["MagicMock", "PlatformInfo", "PluginAPIClient", "PluginDownloadInfo", "patch"], "enclosing_function": "test_get_download_info_success", "extracted_code": "# Source: ggshield/core/plugin/client.py\nclass PluginDownloadInfo:\n \"\"\"Information needed to download a plugin.\"\"\"\n\n download_url: str\n filename: str\n sha256: str\n version: str\n expires_at: str\n\nclass PluginAPIClient:\n \"\"\"Client for GitGuardian plugin API.\"\"\"\n\n API_VERSION = \"v1\"\n\n def __init__(self, client: GGClient):\n self.client = client\n self.base_url = client.base_uri.rstrip(\"/\")\n\n def get_available_plugins(self) -> PluginCatalog:\n \"\"\"Fetch available plugins for the authenticated account.\"\"\"\n platform_info = get_platform_info()\n\n try:\n response = self.client.session.get(\n f\"{self.base_url}/{self.API_VERSION}/plugins\",\n params={\n \"platform\": platform_info.os,\n \"arch\": platform_info.arch,\n },\n headers=self._get_headers(),\n )\n response.raise_for_status()\n except requests.RequestException as e:\n raise PluginAPIError(f\"Failed to fetch plugins: {e}\") from e\n\n data = response.json()\n\n account_data = data.get(\"account\", {})\n current_platform = f\"{platform_info.os}-{platform_info.arch}\"\n\n return PluginCatalog(\n plan=account_data.get(\"plan\", data.get(\"plan\", \"unknown\")),\n features=account_data.get(\"features\", data.get(\"features\", {})),\n plugins=[\n PluginInfo(\n name=p.get(\"name\", \"unknown\"),\n display_name=p.get(\"display_name\", p.get(\"name\", \"Unknown\")),\n description=p.get(\"description\", \"\"),\n available=self._is_plugin_available(p, current_platform),\n latest_version=p.get(\"latest_version\"),\n supported_platforms=p.get(\"supported_platforms\", []),\n reason=self._get_unavailable_reason(p, current_platform),\n )\n for p in data.get(\"plugins\", [])\n ],\n )\n\n def get_download_info(\n self,\n plugin_name: str,\n version: Optional[str] = None,\n platform_info: Optional[PlatformInfo] = None,\n ) -> PluginDownloadInfo:\n \"\"\"Get download URL for a plugin wheel.\"\"\"\n resolved_platform_info: PlatformInfo\n if platform_info is None:\n resolved_platform_info = get_platform_info()\n else:\n resolved_platform_info = platform_info\n\n params: Dict[str, str] = {\n \"platform\": resolved_platform_info.os,\n \"arch\": resolved_platform_info.arch,\n \"python_abi\": resolved_platform_info.python_abi,\n }\n if version:\n params[\"version\"] = version\n\n try:\n response = self.client.session.get(\n f\"{self.base_url}/{self.API_VERSION}/plugins/{plugin_name}/download\",\n params=params,\n headers=self._get_headers(),\n )\n\n if response.status_code == 403:\n raise PluginNotAvailableError(plugin_name)\n elif response.status_code == 404:\n raise PluginNotAvailableError(\n plugin_name, \"Plugin or version not found\"\n )\n\n response.raise_for_status()\n\n except PluginNotAvailableError:\n raise\n except requests.RequestException as e:\n raise PluginAPIError(f\"Failed to get download info: {e}\") from e\n\n data = response.json()\n\n return PluginDownloadInfo(\n download_url=data[\"download_url\"],\n filename=data[\"filename\"],\n sha256=data[\"sha256\"],\n version=data[\"version\"],\n expires_at=data[\"expires_at\"],\n )\n\n def _is_plugin_available(\n self, plugin_data: Dict[str, Any], current_platform: str\n ) -> bool:\n if not plugin_data.get(\"available\", True):\n return False\n supported = plugin_data.get(\"supported_platforms\", [])\n if not supported:\n return True\n return current_platform in supported or \"any-any\" in supported\n\n def _get_unavailable_reason(\n self, plugin_data: Dict[str, Any], current_platform: str\n ) -> Optional[str]:\n if plugin_data.get(\"reason\"):\n return plugin_data[\"reason\"]\n supported = plugin_data.get(\"supported_platforms\", [])\n if (\n supported\n and current_platform not in supported\n and \"any-any\" not in supported\n ):\n return f\"Not available for {current_platform}. Supported: {', '.join(supported)}\"\n return None\n\n def _get_headers(self) -> Dict[str, str]:\n return {\n \"Authorization\": f\"Token {self.client.api_key}\",\n \"Content-Type\": \"application/json\",\n }\n\n\n# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4997, "extracted_code_full": "# Source: ggshield/core/plugin/client.py\nclass PluginDownloadInfo:\n \"\"\"Information needed to download a plugin.\"\"\"\n\n download_url: str\n filename: str\n sha256: str\n version: str\n expires_at: str\n\nclass PluginAPIClient:\n \"\"\"Client for GitGuardian plugin API.\"\"\"\n\n API_VERSION = \"v1\"\n\n def __init__(self, client: GGClient):\n self.client = client\n self.base_url = client.base_uri.rstrip(\"/\")\n\n def get_available_plugins(self) -> PluginCatalog:\n \"\"\"Fetch available plugins for the authenticated account.\"\"\"\n platform_info = get_platform_info()\n\n try:\n response = self.client.session.get(\n f\"{self.base_url}/{self.API_VERSION}/plugins\",\n params={\n \"platform\": platform_info.os,\n \"arch\": platform_info.arch,\n },\n headers=self._get_headers(),\n )\n response.raise_for_status()\n except requests.RequestException as e:\n raise PluginAPIError(f\"Failed to fetch plugins: {e}\") from e\n\n data = response.json()\n\n account_data = data.get(\"account\", {})\n current_platform = f\"{platform_info.os}-{platform_info.arch}\"\n\n return PluginCatalog(\n plan=account_data.get(\"plan\", data.get(\"plan\", \"unknown\")),\n features=account_data.get(\"features\", data.get(\"features\", {})),\n plugins=[\n PluginInfo(\n name=p.get(\"name\", \"unknown\"),\n display_name=p.get(\"display_name\", p.get(\"name\", \"Unknown\")),\n description=p.get(\"description\", \"\"),\n available=self._is_plugin_available(p, current_platform),\n latest_version=p.get(\"latest_version\"),\n supported_platforms=p.get(\"supported_platforms\", []),\n reason=self._get_unavailable_reason(p, current_platform),\n )\n for p in data.get(\"plugins\", [])\n ],\n )\n\n def get_download_info(\n self,\n plugin_name: str,\n version: Optional[str] = None,\n platform_info: Optional[PlatformInfo] = None,\n ) -> PluginDownloadInfo:\n \"\"\"Get download URL for a plugin wheel.\"\"\"\n resolved_platform_info: PlatformInfo\n if platform_info is None:\n resolved_platform_info = get_platform_info()\n else:\n resolved_platform_info = platform_info\n\n params: Dict[str, str] = {\n \"platform\": resolved_platform_info.os,\n \"arch\": resolved_platform_info.arch,\n \"python_abi\": resolved_platform_info.python_abi,\n }\n if version:\n params[\"version\"] = version\n\n try:\n response = self.client.session.get(\n f\"{self.base_url}/{self.API_VERSION}/plugins/{plugin_name}/download\",\n params=params,\n headers=self._get_headers(),\n )\n\n if response.status_code == 403:\n raise PluginNotAvailableError(plugin_name)\n elif response.status_code == 404:\n raise PluginNotAvailableError(\n plugin_name, \"Plugin or version not found\"\n )\n\n response.raise_for_status()\n\n except PluginNotAvailableError:\n raise\n except requests.RequestException as e:\n raise PluginAPIError(f\"Failed to get download info: {e}\") from e\n\n data = response.json()\n\n return PluginDownloadInfo(\n download_url=data[\"download_url\"],\n filename=data[\"filename\"],\n sha256=data[\"sha256\"],\n version=data[\"version\"],\n expires_at=data[\"expires_at\"],\n )\n\n def _is_plugin_available(\n self, plugin_data: Dict[str, Any], current_platform: str\n ) -> bool:\n if not plugin_data.get(\"available\", True):\n return False\n supported = plugin_data.get(\"supported_platforms\", [])\n if not supported:\n return True\n return current_platform in supported or \"any-any\" in supported\n\n def _get_unavailable_reason(\n self, plugin_data: Dict[str, Any], current_platform: str\n ) -> Optional[str]:\n if plugin_data.get(\"reason\"):\n return plugin_data[\"reason\"]\n supported = plugin_data.get(\"supported_platforms\", [])\n if (\n supported\n and current_platform not in supported\n and \"any-any\" not in supported\n ):\n return f\"Not available for {current_platform}. Supported: {', '.join(supported)}\"\n return None\n\n def _get_headers(self) -> Dict[str, str]:\n return {\n \"Authorization\": f\"Token {self.client.api_key}\",\n \"Content-Type\": \"application/json\",\n }\n\n\n# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str", "n_chars_compressed": 4997, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_decrypt.py::116": {"resolved_imports": ["ggshield/__main__.py", "ggshield/verticals/hmsl/crypto.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli"], "enclosing_function": "test_hmsl_decrypt_default_behavior", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/test_check_updates.py::158": {"resolved_imports": ["ggshield/core/__init__.py", "ggshield/core/check_updates.py"], "used_names": ["CACHE_FILE", "FakeFilesystem", "Path", "load_last_check_time", "pytest"], "enclosing_function": "test_load_last_check_time_swallows_errors", "extracted_code": "# Source: ggshield/core/check_updates.py\nCACHE_FILE = get_cache_dir() / \"update_check.yaml\"\n\ndef load_last_check_time() -> Optional[float]:\n \"\"\"Returns the last time we checked, or None if not available\"\"\"\n try:\n cached_data = load_yaml_dict(CACHE_FILE)\n if cached_data is None:\n # File does not exist, do not log any warning\n return None\n return float(cached_data[CHECK_AT_KEY])\n except Exception as e:\n logger.warning(\"Could not load cached latest version: %s\", repr(e))\n return None", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 551, "extracted_code_full": "# Source: ggshield/core/check_updates.py\nCACHE_FILE = get_cache_dir() / \"update_check.yaml\"\n\ndef load_last_check_time() -> Optional[float]:\n \"\"\"Returns the last time we checked, or None if not available\"\"\"\n try:\n cached_data = load_yaml_dict(CACHE_FILE)\n if cached_data is None:\n # File does not exist, do not log any warning\n return None\n return float(cached_data[CHECK_AT_KEY])\n except Exception as e:\n logger.warning(\"Could not load cached latest version: %s\", repr(e))\n return None", "n_chars_compressed": 551, "compression_ratio": 1.0}, "tests/unit/cmd/test_status.py::26": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/utils/os.py"], "used_names": ["assert_invoke_ok", "cli", "json", "jsonschema", "my_vcr"], "enclosing_function": "test_quota", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 11, "n_files_resolved": 3, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/plugin/test_manage.py::40": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["ExitCode", "cli", "mock"], "enclosing_function": "test_enable_installed_plugin", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_path.py::174": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["CliRunner", "assert_invoke_ok", "cli", "my_vcr"], "enclosing_function": "test_files_verbose", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 12, "n_files_resolved": 2, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/test_text_utils.py::19": {"resolved_imports": ["ggshield/core/text_utils.py"], "used_names": ["Optional", "pytest", "translate_validity"], "enclosing_function": "test_translate_validity", "extracted_code": "# Source: ggshield/core/text_utils.py\ndef translate_validity(validity_id: Optional[str]) -> str:\n if validity_id is None:\n validity_id = \"unknown\"\n # If we don't have a text for the validity_id, return it as is. We assume the text\n # of the ID is more valuable than a generic \"Unknown\" string\n return _VALIDITY_TEXT_FOR_ID.get(validity_id, validity_id)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 371, "extracted_code_full": "# Source: ggshield/core/text_utils.py\ndef translate_validity(validity_id: Optional[str]) -> str:\n if validity_id is None:\n validity_id = \"unknown\"\n # If we don't have a text for the validity_id, return it as is. We assume the text\n # of the ID is more valuable than a generic \"Unknown\" string\n return _VALIDITY_TEXT_FOR_ID.get(validity_id, validity_id)", "n_chars_compressed": 371, "compression_ratio": 1.0}, "tests/unit/core/test_check_updates.py::121": {"resolved_imports": ["ggshield/core/__init__.py", "ggshield/core/check_updates.py"], "used_names": ["CACHE_FILE", "FakeFilesystem", "Path", "load_last_check_time"], "enclosing_function": "test_load_last_check_time_ok", "extracted_code": "# Source: ggshield/core/check_updates.py\nCACHE_FILE = get_cache_dir() / \"update_check.yaml\"\n\ndef load_last_check_time() -> Optional[float]:\n \"\"\"Returns the last time we checked, or None if not available\"\"\"\n try:\n cached_data = load_yaml_dict(CACHE_FILE)\n if cached_data is None:\n # File does not exist, do not log any warning\n return None\n return float(cached_data[CHECK_AT_KEY])\n except Exception as e:\n logger.warning(\"Could not load cached latest version: %s\", repr(e))\n return None", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 551, "extracted_code_full": "# Source: ggshield/core/check_updates.py\nCACHE_FILE = get_cache_dir() / \"update_check.yaml\"\n\ndef load_last_check_time() -> Optional[float]:\n \"\"\"Returns the last time we checked, or None if not available\"\"\"\n try:\n cached_data = load_yaml_dict(CACHE_FILE)\n if cached_data is None:\n # File does not exist, do not log any warning\n return None\n return float(cached_data[CHECK_AT_KEY])\n except Exception as e:\n logger.warning(\"Could not load cached latest version: %s\", repr(e))\n return None", "n_chars_compressed": 551, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_docker.py::71": {"resolved_imports": ["ggshield/core/dirs.py"], "used_names": ["GG_VALID_TOKEN", "Path", "pytest", "recreate_censored_content", "run_ggshield_scan"], "enclosing_function": "test_scan_docker_find_secret", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/unit/cmd/honeytoken/test_honeytoken.py::58": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["Any", "Dict", "List", "S", "Union"], "enclosing_function": "payload_checker", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/core/plugin/test_registry.py::40": {"resolved_imports": ["ggshield/core/plugin/base.py", "ggshield/core/plugin/registry.py"], "used_names": ["PluginRegistry"], "enclosing_function": "test_empty_registry", "extracted_code": "# Source: ggshield/core/plugin/registry.py\nclass PluginRegistry:\n \"\"\"Central registry for all loaded plugins and their capabilities.\"\"\"\n\n _plugins: Dict[str, GGShieldPlugin] = field(default_factory=dict)\n _commands: List[click.Command] = field(default_factory=list)\n\n def register_plugin(self, plugin: GGShieldPlugin) -> None:\n \"\"\"Register a loaded plugin.\"\"\"\n self._plugins[plugin.metadata.name] = plugin\n\n def register_command(self, command: click.Command) -> None:\n \"\"\"Register a CLI command provided by a plugin.\"\"\"\n self._commands.append(command)\n\n def get_plugin(self, name: str) -> Optional[GGShieldPlugin]:\n \"\"\"Get a loaded plugin by name.\"\"\"\n return self._plugins.get(name)\n\n def get_all_plugins(self) -> Dict[str, GGShieldPlugin]:\n \"\"\"Get all loaded plugins.\"\"\"\n return self._plugins.copy()\n\n def get_commands(self) -> List[click.Command]:\n \"\"\"Get all plugin-provided commands.\"\"\"\n return self._commands.copy()", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1014, "extracted_code_full": "# Source: ggshield/core/plugin/registry.py\nclass PluginRegistry:\n \"\"\"Central registry for all loaded plugins and their capabilities.\"\"\"\n\n _plugins: Dict[str, GGShieldPlugin] = field(default_factory=dict)\n _commands: List[click.Command] = field(default_factory=list)\n\n def register_plugin(self, plugin: GGShieldPlugin) -> None:\n \"\"\"Register a loaded plugin.\"\"\"\n self._plugins[plugin.metadata.name] = plugin\n\n def register_command(self, command: click.Command) -> None:\n \"\"\"Register a CLI command provided by a plugin.\"\"\"\n self._commands.append(command)\n\n def get_plugin(self, name: str) -> Optional[GGShieldPlugin]:\n \"\"\"Get a loaded plugin by name.\"\"\"\n return self._plugins.get(name)\n\n def get_all_plugins(self) -> Dict[str, GGShieldPlugin]:\n \"\"\"Get all loaded plugins.\"\"\"\n return self._plugins.copy()\n\n def get_commands(self) -> List[click.Command]:\n \"\"\"Get all plugin-provided commands.\"\"\"\n return self._commands.copy()", "n_chars_compressed": 1014, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_ci.py::115": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/__init__.py", "ggshield/core/ui/__init__.py", "ggshield/core/errors.py", "ggshield/core/git_hooks/ci/commit_range.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["Dict", "EMPTY_SHA", "Mock", "click", "collect_commit_range_from_ci_env", "patch", "pytest", "ui"], "enclosing_function": "test_gitlab_ci_range", "extracted_code": "# Source: ggshield/core/git_hooks/ci/commit_range.py\ndef collect_commit_range_from_ci_env() -> Tuple[List[str], SupportedCI]:\n ci_mode = SupportedCI.from_ci_env()\n\n base_commit_var = CI_COMMIT_VAR.get(ci_mode)\n base_commit = os.getenv(base_commit_var, \"HEAD\") if base_commit_var else \"HEAD\"\n\n ui.display_verbose(f\"\\tIdentified base commit as {base_commit}\")\n\n target_branch_var = CI_TARGET_BRANCH_ASSOC.get(ci_mode)\n target_branch = None\n if target_branch_var:\n target_branch = os.getenv(target_branch_var)\n if target_branch and target_branch != EMPTY_SHA:\n ui.display_verbose(f\"\\tIdentified target branch as {target_branch}\")\n remote_prefix = get_remote_prefix()\n if remote_prefix:\n _fetch_target_branch(remote_prefix.rstrip(\"/\"), target_branch)\n commit_list = get_list_commit_SHA(\n f\"{remote_prefix}{target_branch}..{base_commit}\"\n )\n if commit_list:\n return commit_list, ci_mode\n\n previous_commit = None\n previous_commit_var = CI_PREVIOUS_COMMIT_VAR.get(ci_mode)\n if previous_commit_var:\n previous_commit = os.getenv(previous_commit_var)\n if (\n previous_commit is None or previous_commit == EMPTY_SHA\n ) and ci_mode == SupportedCI.GITHUB:\n previous_commit = os.getenv(\"GITHUB_DEFAULT_BRANCH\")\n if (\n previous_commit is not None\n and previous_commit != EMPTY_SHA\n and not previous_commit.startswith(\"...\")\n ):\n ui.display_verbose(\n f\"\\tIdentified previous commit or commit range as {previous_commit}\"\n )\n if ci_mode in [SupportedCI.CIRCLECI, SupportedCI.TRAVIS]:\n # for these ci envs, previous_commit is a range of commits\n commit_range = previous_commit\n elif ci_mode == SupportedCI.GITLAB:\n commit_range = f\"{previous_commit}~1..{base_commit}\"\n else:\n commit_range = f\"{previous_commit}..{base_commit}\"\n commit_list = get_list_commit_SHA(commit_range)\n if commit_list:\n return commit_list, ci_mode\n\n commit_list = get_list_commit_SHA(f\"{base_commit}~1...\")\n if commit_list:\n return commit_list, ci_mode\n\n raise UnexpectedError(\n \"Unable to get commit range. Please submit an issue with the following info:\\n\"\n \" Repository URL: \\n\"\n f\" CI_TYPE: {ci_mode.value}\\n\"\n f\" TARGET_BRANCH: {target_branch}\\n\"\n f\" PREVIOUS_COMMIT: {previous_commit}\\n\"\n f\" BASE_COMMIT: {base_commit}\"\n )\n\n\n# Source: ggshield/utils/git_shell.py\nEMPTY_SHA = \"0000000000000000000000000000000000000000\"", "n_imports_parsed": 16, "n_files_resolved": 7, "n_chars_extracted": 2771, "extracted_code_full": "# Source: ggshield/core/git_hooks/ci/commit_range.py\ndef collect_commit_range_from_ci_env() -> Tuple[List[str], SupportedCI]:\n ci_mode = SupportedCI.from_ci_env()\n\n base_commit_var = CI_COMMIT_VAR.get(ci_mode)\n base_commit = os.getenv(base_commit_var, \"HEAD\") if base_commit_var else \"HEAD\"\n\n ui.display_verbose(f\"\\tIdentified base commit as {base_commit}\")\n\n target_branch_var = CI_TARGET_BRANCH_ASSOC.get(ci_mode)\n target_branch = None\n if target_branch_var:\n target_branch = os.getenv(target_branch_var)\n if target_branch and target_branch != EMPTY_SHA:\n ui.display_verbose(f\"\\tIdentified target branch as {target_branch}\")\n remote_prefix = get_remote_prefix()\n if remote_prefix:\n _fetch_target_branch(remote_prefix.rstrip(\"/\"), target_branch)\n commit_list = get_list_commit_SHA(\n f\"{remote_prefix}{target_branch}..{base_commit}\"\n )\n if commit_list:\n return commit_list, ci_mode\n\n previous_commit = None\n previous_commit_var = CI_PREVIOUS_COMMIT_VAR.get(ci_mode)\n if previous_commit_var:\n previous_commit = os.getenv(previous_commit_var)\n if (\n previous_commit is None or previous_commit == EMPTY_SHA\n ) and ci_mode == SupportedCI.GITHUB:\n previous_commit = os.getenv(\"GITHUB_DEFAULT_BRANCH\")\n if (\n previous_commit is not None\n and previous_commit != EMPTY_SHA\n and not previous_commit.startswith(\"...\")\n ):\n ui.display_verbose(\n f\"\\tIdentified previous commit or commit range as {previous_commit}\"\n )\n if ci_mode in [SupportedCI.CIRCLECI, SupportedCI.TRAVIS]:\n # for these ci envs, previous_commit is a range of commits\n commit_range = previous_commit\n elif ci_mode == SupportedCI.GITLAB:\n commit_range = f\"{previous_commit}~1..{base_commit}\"\n else:\n commit_range = f\"{previous_commit}..{base_commit}\"\n commit_list = get_list_commit_SHA(commit_range)\n if commit_list:\n return commit_list, ci_mode\n\n commit_list = get_list_commit_SHA(f\"{base_commit}~1...\")\n if commit_list:\n return commit_list, ci_mode\n\n raise UnexpectedError(\n \"Unable to get commit range. Please submit an issue with the following info:\\n\"\n \" Repository URL: \\n\"\n f\" CI_TYPE: {ci_mode.value}\\n\"\n f\" TARGET_BRANCH: {target_branch}\\n\"\n f\" PREVIOUS_COMMIT: {previous_commit}\\n\"\n f\" BASE_COMMIT: {base_commit}\"\n )\n\n\n# Source: ggshield/utils/git_shell.py\nEMPTY_SHA = \"0000000000000000000000000000000000000000\"", "n_chars_compressed": 2771, "compression_ratio": 1.0}, "tests/unit/cmd/test_install.py::50": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/install.py", "ggshield/core/errors.py"], "used_names": ["Path", "assert_invoke_ok", "cli", "os"], "enclosing_function": "test_local_exist_force", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_api_status.py::17": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli", "my_vcr"], "enclosing_function": "test_hmsl_api_status", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/config/test_auth_config.py::38": {"resolved_imports": ["ggshield/core/config/config.py", "ggshield/core/config/auth_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py"], "used_names": ["Config", "TEST_AUTH_CONFIG", "get_auth_config_filepath", "prepare_auth_config_dict_for_save", "write_yaml"], "enclosing_function": "test_load", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/auth_config.py\ndef prepare_auth_config_dict_for_save(data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Does the opposite of `prepare_auth_config_dict_for_parse`: turn the\n instances[].account key into instances[].accounts keys.\n \"\"\"\n data = deepcopy(data)\n try:\n instances = data[\"instances\"]\n except KeyError:\n return data\n\n for instance in instances:\n account = instance.pop(\"account\")\n instance[\"accounts\"] = [account]\n\n return data\n\n\n# Source: ggshield/core/config/utils.py\ndef get_auth_config_filepath() -> Path:\n return get_config_dir() / AUTH_CONFIG_FILENAME", "n_imports_parsed": 11, "n_files_resolved": 4, "n_chars_extracted": 8691, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/auth_config.py\ndef prepare_auth_config_dict_for_save(data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Does the opposite of `prepare_auth_config_dict_for_parse`: turn the\n instances[].account key into instances[].accounts keys.\n \"\"\"\n data = deepcopy(data)\n try:\n instances = data[\"instances\"]\n except KeyError:\n return data\n\n for instance in instances:\n account = instance.pop(\"account\")\n instance[\"accounts\"] = [account]\n\n return data\n\n\n# Source: ggshield/core/config/utils.py\ndef get_auth_config_filepath() -> Path:\n return get_config_dir() / AUTH_CONFIG_FILENAME", "n_chars_compressed": 8691, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_downloader.py::65": {"resolved_imports": ["ggshield/core/plugin/client.py", "ggshield/core/plugin/downloader.py"], "used_names": ["Path", "PluginDownloader", "json", "patch"], "enclosing_function": "test_is_installed_true", "extracted_code": "# Source: ggshield/core/plugin/downloader.py\nclass PluginDownloader:\n \"\"\"Downloads and installs plugin wheels.\"\"\"\n\n def __init__(self) -> None:\n self.plugins_dir = get_plugins_dir(create=True)\n\n def download_and_install(\n self,\n download_info: PluginDownloadInfo,\n plugin_name: str,\n source: Optional[PluginSource] = None,\n ) -> Path:\n \"\"\"Download a plugin wheel and install it locally.\"\"\"\n self._validate_plugin_name(plugin_name)\n\n plugin_dir = self.plugins_dir / plugin_name\n plugin_dir.mkdir(parents=True, exist_ok=True)\n\n wheel_path = plugin_dir / download_info.filename\n temp_path = plugin_dir / f\"{download_info.filename}.tmp\"\n\n try:\n logger.info(\"Downloading %s...\", download_info.filename)\n response = requests.get(download_info.download_url, stream=True)\n response.raise_for_status()\n\n sha256_hash = hashlib.sha256()\n with open(temp_path, \"wb\") as f:\n for chunk in response.iter_content(chunk_size=8192):\n f.write(chunk)\n sha256_hash.update(chunk)\n\n computed_hash = sha256_hash.hexdigest()\n if computed_hash.lower() != download_info.sha256.lower():\n raise ChecksumMismatchError(download_info.sha256, computed_hash)\n\n # Use GitGuardian API as default source if not provided\n if source is None:\n source = PluginSource(type=PluginSourceType.GITGUARDIAN_API)\n\n self._write_manifest(\n plugin_dir=plugin_dir,\n plugin_name=plugin_name,\n version=download_info.version,\n wheel_filename=download_info.filename,\n sha256=download_info.sha256,\n source=source,\n )\n\n temp_path.rename(wheel_path)\n\n logger.info(\"Installed %s v%s\", plugin_name, download_info.version)\n\n return wheel_path\n\n except requests.RequestException as e:\n raise DownloadError(f\"Failed to download plugin: {e}\") from e\n finally:\n if temp_path.exists():\n temp_path.unlink()\n\n def install_from_wheel(\n self,\n wheel_path: Path,\n force: bool = False,\n ) -> Tuple[str, str, Path]:\n \"\"\"\n Install a plugin from a local wheel file.\n\n Args:\n wheel_path: Path to the wheel file.\n force: Skip security warnings if True.\n\n Returns:\n Tuple of (plugin_name, version, installed_wheel_path).\n\n Raises:\n WheelError: If the wheel file is invalid.\n DownloadError: If installation fails.\n \"\"\"\n # Extract metadata from wheel\n try:\n metadata = extract_wheel_metadata(wheel_path)\n except WheelError as e:\n raise DownloadError(f\"Invalid wheel file: {e}\") from e\n\n plugin_name = metadata.name\n version = metadata.version\n self._validate_plugin_name(plugin_name)\n\n # Create plugin directory\n plugin_dir = self.plugins_dir / plugin_name\n plugin_dir.mkdir(parents=True, exist_ok=True)\n\n # Copy wheel to plugin directory\n dest_wheel_path = plugin_dir / wheel_path.name\n shutil.copy2(wheel_path, dest_wheel_path)\n\n # Compute SHA256\n sha256 = self._compute_sha256(dest_wheel_path)\n\n # Create source tracking\n source = PluginSource(\n type=PluginSourceType.LOCAL_FILE,\n local_path=str(wheel_path.resolve()),\n sha256=sha256,\n )\n\n self._write_manifest(\n plugin_dir=plugin_dir,\n plugin_name=plugin_name,\n version=version,\n wheel_filename=wheel_path.name,\n sha256=sha256,\n source=source,\n )\n\n logger.info(\"Installed %s v%s from local wheel\", plugin_name, version)\n\n return plugin_name, version, dest_wheel_path\n\n def download_from_url(\n self,\n url: str,\n sha256: Optional[str] = None,\n force: bool = False,\n ) -> Tuple[str, str, Path]:\n \"\"\"\n Download and install a plugin from a URL.\n\n Args:\n url: URL to download the wheel from.\n sha256: Expected SHA256 checksum (optional but recommended).\n force: Skip security warnings if True.\n\n Returns:\n Tuple of (plugin_name, version, installed_wheel_path).\n\n Raises:\n InsecureSourceError: If URL uses HTTP instead of HTTPS.\n ChecksumMismatchError: If checksum doesn't match.\n DownloadError: If download or installation fails.\n \"\"\"\n # Security check: require HTTPS\n if url.startswith(\"http://\"):\n raise InsecureSourceError(\n \"HTTP URLs are not allowed for security reasons. Use HTTPS instead.\"\n )\n\n if not url.startswith(\"https://\"):\n raise DownloadError(f\"Invalid URL scheme: {url}\")\n\n # Download to temp file\n with tempfile.TemporaryDirectory() as temp_dir:\n # Extract filename from URL\n filename = url.split(\"/\")[-1].split(\"?\")[0]\n if not filename.endswith(\".whl\"):\n filename = \"plugin.whl\"\n\n temp_wheel_path = Path(temp_dir) / filename\n\n try:\n logger.info(\"Downloading from %s...\", url)\n response = requests.get(url, stream=True)\n response.raise_for_status()\n\n sha256_hash = hashlib.sha256()\n with open(temp_wheel_path, \"wb\") as f:\n for chunk in response.iter_content(chunk_size=8192):\n f.write(chunk)\n sha256_hash.update(chunk)\n\n computed_hash = sha256_hash.hexdigest()\n\n # Verify checksum if provided\n if sha256 and computed_hash.lower() != sha256.lower():\n raise ChecksumMismatchError(sha256, computed_hash)\n\n except requests.RequestException as e:\n raise DownloadError(f\"Failed to download from URL: {e}\") from e\n\n # Extract metadata\n try:\n metadata = extract_wheel_metadata(temp_wheel_path)\n except WheelError as e:\n raise DownloadError(f\"Downloaded file is not a valid wheel: {e}\") from e\n\n plugin_name = metadata.name\n version = metadata.version\n self._validate_plugin_name(plugin_name)\n\n # Create plugin directory and copy wheel\n plugin_dir = self.plugins_dir / plugin_name\n plugin_dir.mkdir(parents=True, exist_ok=True)\n\n dest_wheel_path = plugin_dir / temp_wheel_path.name\n shutil.copy2(temp_wheel_path, dest_wheel_path)\n\n # Create source tracking\n source = PluginSource(\n type=PluginSourceType.URL,\n url=url,\n sha256=computed_hash,\n )\n\n self._write_manifest(\n plugin_dir=plugin_dir,\n plugin_name=plugin_name,\n version=version,\n wheel_filename=dest_wheel_path.name,\n sha256=computed_hash,\n source=source,\n )\n\n logger.info(\"Installed %s v%s from URL\", plugin_name, version)\n\n return plugin_name, version, dest_wheel_path\n\n def download_from_github_release(\n self,\n url: str,\n sha256: Optional[str] = None,\n force: bool = False,\n ) -> Tuple[str, str, Path]:\n \"\"\"\n Download and install a plugin from a GitHub release asset.\n\n Args:\n url: GitHub release asset URL.\n sha256: Expected SHA256 checksum (optional).\n force: Skip security warnings if True.\n\n Returns:\n Tuple of (plugin_name, version, installed_wheel_path).\n \"\"\"\n # Extract repo info from URL for source tracking\n github_repo = self._extract_github_repo(url)\n\n # Download using standard URL method\n plugin_name, version, wheel_path = self.download_from_url(url, sha256, force)\n\n # Update source to track GitHub release\n manifest_path = self.plugins_dir / plugin_name / \"manifest.json\"\n manifest = json.loads(manifest_path.read_text())\n\n source = PluginSource(\n type=PluginSourceType.GITHUB_RELEASE,\n url=url,\n github_repo=github_repo,\n sha256=manifest.get(\"sha256\"),\n )\n manifest[\"source\"] = source.to_dict()\n manifest_path.write_text(json.dumps(manifest, indent=2))\n\n return plugin_name, version, wheel_path\n\n def download_from_github_artifact(\n self,\n url: str,\n force: bool = False,\n ) -> Tuple[str, str, Path]:\n \"\"\"\n Download and install a plugin from a GitHub Actions artifact.\n\n GitHub artifacts are ZIP files containing wheel(s). This method:\n 1. Downloads the artifact ZIP\n 2. Extracts the wheel file\n 3. Installs the wheel\n\n Args:\n url: GitHub artifact URL (browser URL or API URL).\n force: Skip security warnings if True.\n\n Returns:\n Tuple of (plugin_name, version, installed_wheel_path).\n\n Raises:\n GitHubArtifactError: If artifact cannot be downloaded or processed.\n DownloadError: If installation fails.\n \"\"\"\n # Parse artifact URL to get API endpoint\n artifact_info = self._parse_github_artifact_url(url)\n if not artifact_info:\n raise GitHubArtifactError(f\"Invalid GitHub artifact URL: {url}\")\n\n owner, repo, artifact_id = artifact_info\n\n # Get GitHub token from environment\n github_token = os.environ.get(\"GITHUB_TOKEN\")\n if not github_token:\n # Try gh CLI as fallback\n github_token = self._get_gh_token()\n\n if not github_token:\n raise GitHubArtifactError(\n \"GitHub authentication required. Set GITHUB_TOKEN environment variable \"\n \"or install and authenticate with GitHub CLI (gh auth login).\"\n )\n\n # Download artifact ZIP\n api_url = f\"https://api.github.com/repos/{owner}/{repo}/actions/artifacts/{artifact_id}/zip\"\n\n with tempfile.TemporaryDirectory() as temp_dir:\n temp_dir_path = Path(temp_dir)\n artifact_zip_path = temp_dir_path / \"artifact.zip\"\n\n try:\n logger.info(\"Downloading GitHub artifact...\")\n response = requests.get(\n api_url,\n headers={\n \"Authorization\": f\"Bearer {github_token}\",\n \"Accept\": \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n stream=True,\n )\n response.raise_for_status()\n\n with open(artifact_zip_path, \"wb\") as f:\n for chunk in response.iter_content(chunk_size=8192):\n f.write(chunk)\n\n except requests.RequestException as e:\n raise GitHubArtifactError(f\"Failed to download artifact: {e}\") from e\n\n # Extract ZIP and find wheel\n extract_dir = temp_dir_path / \"extracted\"\n\n try:\n from ggshield.utils.archive import safe_unpack\n\n safe_unpack(artifact_zip_path, extract_dir)\n except Exception as e:\n raise GitHubArtifactError(f\"Failed to extract artifact: {e}\") from e\n\n # Find wheel file in extracted contents\n wheel_files = list(extract_dir.glob(\"**/*.whl\"))\n if not wheel_files:\n raise GitHubArtifactError(\"No wheel file found in artifact\")\n\n if len(wheel_files) > 1:\n logger.warning(\n \"Multiple wheel files found in artifact, using first: %s\",\n wheel_files[0].name,\n )\n\n temp_wheel_path = wheel_files[0]\n\n # Extract metadata\n try:\n metadata = extract_wheel_metadata(temp_wheel_path)\n except WheelError as e:\n raise DownloadError(f\"Invalid wheel in artifact: {e}\") from e\n\n plugin_name = metadata.name\n version = metadata.version\n self._validate_plugin_name(plugin_name)\n\n # Create plugin directory and copy wheel\n plugin_dir = self.plugins_dir / plugin_name\n plugin_dir.mkdir(parents=True, exist_ok=True)\n\n dest_wheel_path = plugin_dir / temp_wheel_path.name\n shutil.copy2(temp_wheel_path, dest_wheel_path)\n\n # Compute SHA256\n sha256 = self._compute_sha256(dest_wheel_path)\n\n # Create source tracking\n source = PluginSource(\n type=PluginSourceType.GITHUB_ARTIFACT,\n url=url,\n github_repo=f\"{owner}/{repo}\",\n sha256=sha256,\n )\n\n self._write_manifest(\n plugin_dir=plugin_dir,\n plugin_name=plugin_name,\n version=version,\n wheel_filename=dest_wheel_path.name,\n sha256=sha256,\n source=source,\n )\n\n logger.info(\"Installed %s v%s from GitHub artifact\", plugin_name, version)\n\n return plugin_name, version, dest_wheel_path\n\n def uninstall(self, plugin_name: str) -> bool:\n \"\"\"Uninstall a plugin (by package name or entry point name).\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n logger.warning(\"Invalid plugin name: %s\", plugin_name)\n return False\n\n plugin_dir = self.plugins_dir / plugin_name\n if not plugin_dir.exists():\n # Try finding by entry point name\n plugin_dir = self._find_plugin_dir_by_entry_point(plugin_name)\n if plugin_dir is None:\n return False\n\n shutil.rmtree(plugin_dir)\n\n logger.info(\"Uninstalled plugin: %s\", plugin_name)\n return True\n\n def get_installed_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the installed version of a plugin (by package name or entry point name).\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n logger.warning(\"Invalid plugin name: %s\", plugin_name)\n return None\n\n manifest_path = self.plugins_dir / plugin_name / \"manifest.json\"\n if not manifest_path.exists():\n # Try finding by entry point name\n plugin_dir = self._find_plugin_dir_by_entry_point(plugin_name)\n if plugin_dir is None:\n return None\n manifest_path = plugin_dir / \"manifest.json\"\n\n try:\n manifest = json.loads(manifest_path.read_text())\n return manifest.get(\"version\")\n except (json.JSONDecodeError, KeyError):\n return None\n\n def is_installed(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is installed (by package name or entry point name).\"\"\"\n return self.get_installed_version(plugin_name) is not None\n\n def _find_plugin_dir_by_entry_point(self, entry_point_name: str) -> Optional[Path]:\n \"\"\"Find a plugin directory by its entry point name.\"\"\"\n if not self.plugins_dir.exists():\n return None\n\n for plugin_dir in self.plugins_dir.iterdir():\n if not plugin_dir.is_dir():\n continue\n\n manifest_path = plugin_dir / \"manifest.json\"\n if not manifest_path.exists():\n continue\n\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\", \"\")\n wheel_path = plugin_dir / wheel_filename\n\n if wheel_path.exists():\n # Read entry point name from wheel\n ep_name = self._read_entry_point_name_from_wheel(wheel_path)\n if ep_name == entry_point_name:\n return plugin_dir\n except (json.JSONDecodeError, KeyError):\n continue\n\n return None\n\n def _read_entry_point_name_from_wheel(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the entry point name from a wheel file.\"\"\"\n from ggshield.core.plugin.loader import read_entry_point_from_wheel\n\n result = read_entry_point_from_wheel(wheel_path)\n return result[0] if result else None\n\n def get_wheel_path(self, plugin_name: str) -> Optional[Path]:\n \"\"\"Get the path to an installed plugin's wheel file.\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n logger.warning(\"Invalid plugin name: %s\", plugin_name)\n return None\n\n manifest_path = self.plugins_dir / plugin_name / \"manifest.json\"\n if not manifest_path.exists():\n return None\n\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\")\n if wheel_filename:\n wheel_path = self.plugins_dir / plugin_name / wheel_filename\n if wheel_path.exists():\n return wheel_path\n except (json.JSONDecodeError, KeyError):\n pass\n\n return None\n\n def get_manifest(self, plugin_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get the full manifest for an installed plugin.\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n logger.warning(\"Invalid plugin name: %s\", plugin_name)\n return None\n\n manifest_path = self.plugins_dir / plugin_name / \"manifest.json\"\n if not manifest_path.exists():\n return None\n\n try:\n return json.loads(manifest_path.read_text())\n except json.JSONDecodeError:\n return None\n\n def get_plugin_source(self, plugin_name: str) -> Optional[PluginSource]:\n \"\"\"Get the source information for an installed plugin.\"\"\"\n manifest = self.get_manifest(plugin_name)\n if not manifest:\n return None\n\n source_data = manifest.get(\"source\")\n if not source_data:\n # Legacy manifest without source tracking - assume GitGuardian API\n return PluginSource(type=PluginSourceType.GITGUARDIAN_API)\n\n try:\n return PluginSource.from_dict(source_data)\n except (KeyError, ValueError):\n return None\n\n @staticmethod\n def _is_valid_plugin_name(plugin_name: str) -> bool:\n \"\"\"Check if plugin name is safe to use as a path segment.\"\"\"\n if not plugin_name or plugin_name in {\".\", \"..\"}:\n return False\n if \"/\" in plugin_name or \"\\\\\" in plugin_name:\n return False\n if \"\\x00\" in plugin_name:\n return False\n return True\n\n def _validate_plugin_name(self, plugin_name: str) -> None:\n \"\"\"Validate plugin name and raise on unsafe values.\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n raise DownloadError(f\"Invalid plugin name: {plugin_name!r}\")\n\n def _write_manifest(\n self,\n plugin_dir: Path,\n plugin_name: str,\n version: str,\n wheel_filename: str,\n sha256: str,\n source: PluginSource,\n ) -> None:\n \"\"\"Write the plugin manifest file.\"\"\"\n manifest = {\n \"plugin_name\": plugin_name,\n \"version\": version,\n \"wheel_filename\": wheel_filename,\n \"sha256\": sha256,\n \"source\": source.to_dict(),\n \"installed_at\": datetime.now(timezone.utc).isoformat(),\n }\n manifest_path = plugin_dir / \"manifest.json\"\n manifest_path.write_text(json.dumps(manifest, indent=2))\n\n def _compute_sha256(self, file_path: Path) -> str:\n \"\"\"Compute SHA256 hash of a file.\"\"\"\n sha256_hash = hashlib.sha256()\n with open(file_path, \"rb\") as f:\n for chunk in iter(lambda: f.read(8192), b\"\"):\n sha256_hash.update(chunk)\n return sha256_hash.hexdigest()\n\n def _extract_github_repo(self, url: str) -> Optional[str]:\n \"\"\"Extract owner/repo from a GitHub URL.\"\"\"\n # Pattern: github.com/{owner}/{repo}/...\n match = re.match(r\"https://github\\.com/([^/]+)/([^/]+)\", url)\n if match:\n return f\"{match.group(1)}/{match.group(2)}\"\n return None\n\n def _parse_github_artifact_url(self, url: str) -> Optional[Tuple[str, str, str]]:\n \"\"\"\n Parse GitHub artifact URL to extract owner, repo, and artifact ID.\n\n Supports URLs like:\n - https://github.com/{owner}/{repo}/actions/runs/{run_id}/artifacts/{artifact_id}\n \"\"\"\n pattern = (\n r\"https://github\\.com/([^/]+)/([^/]+)/actions/runs/\\d+/artifacts/(\\d+)\"\n )\n match = re.match(pattern, url)\n if match:\n return match.group(1), match.group(2), match.group(3)\n return None\n\n def _get_gh_token(self) -> Optional[str]:\n \"\"\"Try to get GitHub token from gh CLI.\"\"\"\n import subprocess\n\n try:\n result = subprocess.run(\n [\"gh\", \"auth\", \"token\"],\n capture_output=True,\n text=True,\n timeout=5,\n )\n if result.returncode == 0:\n return result.stdout.strip()\n except (subprocess.SubprocessError, FileNotFoundError):\n pass\n return None", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 21541, "extracted_code_full": "# Source: ggshield/core/plugin/downloader.py\nclass PluginDownloader:\n \"\"\"Downloads and installs plugin wheels.\"\"\"\n\n def __init__(self) -> None:\n self.plugins_dir = get_plugins_dir(create=True)\n\n def download_and_install(\n self,\n download_info: PluginDownloadInfo,\n plugin_name: str,\n source: Optional[PluginSource] = None,\n ) -> Path:\n \"\"\"Download a plugin wheel and install it locally.\"\"\"\n self._validate_plugin_name(plugin_name)\n\n plugin_dir = self.plugins_dir / plugin_name\n plugin_dir.mkdir(parents=True, exist_ok=True)\n\n wheel_path = plugin_dir / download_info.filename\n temp_path = plugin_dir / f\"{download_info.filename}.tmp\"\n\n try:\n logger.info(\"Downloading %s...\", download_info.filename)\n response = requests.get(download_info.download_url, stream=True)\n response.raise_for_status()\n\n sha256_hash = hashlib.sha256()\n with open(temp_path, \"wb\") as f:\n for chunk in response.iter_content(chunk_size=8192):\n f.write(chunk)\n sha256_hash.update(chunk)\n\n computed_hash = sha256_hash.hexdigest()\n if computed_hash.lower() != download_info.sha256.lower():\n raise ChecksumMismatchError(download_info.sha256, computed_hash)\n\n # Use GitGuardian API as default source if not provided\n if source is None:\n source = PluginSource(type=PluginSourceType.GITGUARDIAN_API)\n\n self._write_manifest(\n plugin_dir=plugin_dir,\n plugin_name=plugin_name,\n version=download_info.version,\n wheel_filename=download_info.filename,\n sha256=download_info.sha256,\n source=source,\n )\n\n temp_path.rename(wheel_path)\n\n logger.info(\"Installed %s v%s\", plugin_name, download_info.version)\n\n return wheel_path\n\n except requests.RequestException as e:\n raise DownloadError(f\"Failed to download plugin: {e}\") from e\n finally:\n if temp_path.exists():\n temp_path.unlink()\n\n def install_from_wheel(\n self,\n wheel_path: Path,\n force: bool = False,\n ) -> Tuple[str, str, Path]:\n \"\"\"\n Install a plugin from a local wheel file.\n\n Args:\n wheel_path: Path to the wheel file.\n force: Skip security warnings if True.\n\n Returns:\n Tuple of (plugin_name, version, installed_wheel_path).\n\n Raises:\n WheelError: If the wheel file is invalid.\n DownloadError: If installation fails.\n \"\"\"\n # Extract metadata from wheel\n try:\n metadata = extract_wheel_metadata(wheel_path)\n except WheelError as e:\n raise DownloadError(f\"Invalid wheel file: {e}\") from e\n\n plugin_name = metadata.name\n version = metadata.version\n self._validate_plugin_name(plugin_name)\n\n # Create plugin directory\n plugin_dir = self.plugins_dir / plugin_name\n plugin_dir.mkdir(parents=True, exist_ok=True)\n\n # Copy wheel to plugin directory\n dest_wheel_path = plugin_dir / wheel_path.name\n shutil.copy2(wheel_path, dest_wheel_path)\n\n # Compute SHA256\n sha256 = self._compute_sha256(dest_wheel_path)\n\n # Create source tracking\n source = PluginSource(\n type=PluginSourceType.LOCAL_FILE,\n local_path=str(wheel_path.resolve()),\n sha256=sha256,\n )\n\n self._write_manifest(\n plugin_dir=plugin_dir,\n plugin_name=plugin_name,\n version=version,\n wheel_filename=wheel_path.name,\n sha256=sha256,\n source=source,\n )\n\n logger.info(\"Installed %s v%s from local wheel\", plugin_name, version)\n\n return plugin_name, version, dest_wheel_path\n\n def download_from_url(\n self,\n url: str,\n sha256: Optional[str] = None,\n force: bool = False,\n ) -> Tuple[str, str, Path]:\n \"\"\"\n Download and install a plugin from a URL.\n\n Args:\n url: URL to download the wheel from.\n sha256: Expected SHA256 checksum (optional but recommended).\n force: Skip security warnings if True.\n\n Returns:\n Tuple of (plugin_name, version, installed_wheel_path).\n\n Raises:\n InsecureSourceError: If URL uses HTTP instead of HTTPS.\n ChecksumMismatchError: If checksum doesn't match.\n DownloadError: If download or installation fails.\n \"\"\"\n # Security check: require HTTPS\n if url.startswith(\"http://\"):\n raise InsecureSourceError(\n \"HTTP URLs are not allowed for security reasons. Use HTTPS instead.\"\n )\n\n if not url.startswith(\"https://\"):\n raise DownloadError(f\"Invalid URL scheme: {url}\")\n\n # Download to temp file\n with tempfile.TemporaryDirectory() as temp_dir:\n # Extract filename from URL\n filename = url.split(\"/\")[-1].split(\"?\")[0]\n if not filename.endswith(\".whl\"):\n filename = \"plugin.whl\"\n\n temp_wheel_path = Path(temp_dir) / filename\n\n try:\n logger.info(\"Downloading from %s...\", url)\n response = requests.get(url, stream=True)\n response.raise_for_status()\n\n sha256_hash = hashlib.sha256()\n with open(temp_wheel_path, \"wb\") as f:\n for chunk in response.iter_content(chunk_size=8192):\n f.write(chunk)\n sha256_hash.update(chunk)\n\n computed_hash = sha256_hash.hexdigest()\n\n # Verify checksum if provided\n if sha256 and computed_hash.lower() != sha256.lower():\n raise ChecksumMismatchError(sha256, computed_hash)\n\n except requests.RequestException as e:\n raise DownloadError(f\"Failed to download from URL: {e}\") from e\n\n # Extract metadata\n try:\n metadata = extract_wheel_metadata(temp_wheel_path)\n except WheelError as e:\n raise DownloadError(f\"Downloaded file is not a valid wheel: {e}\") from e\n\n plugin_name = metadata.name\n version = metadata.version\n self._validate_plugin_name(plugin_name)\n\n # Create plugin directory and copy wheel\n plugin_dir = self.plugins_dir / plugin_name\n plugin_dir.mkdir(parents=True, exist_ok=True)\n\n dest_wheel_path = plugin_dir / temp_wheel_path.name\n shutil.copy2(temp_wheel_path, dest_wheel_path)\n\n # Create source tracking\n source = PluginSource(\n type=PluginSourceType.URL,\n url=url,\n sha256=computed_hash,\n )\n\n self._write_manifest(\n plugin_dir=plugin_dir,\n plugin_name=plugin_name,\n version=version,\n wheel_filename=dest_wheel_path.name,\n sha256=computed_hash,\n source=source,\n )\n\n logger.info(\"Installed %s v%s from URL\", plugin_name, version)\n\n return plugin_name, version, dest_wheel_path\n\n def download_from_github_release(\n self,\n url: str,\n sha256: Optional[str] = None,\n force: bool = False,\n ) -> Tuple[str, str, Path]:\n \"\"\"\n Download and install a plugin from a GitHub release asset.\n\n Args:\n url: GitHub release asset URL.\n sha256: Expected SHA256 checksum (optional).\n force: Skip security warnings if True.\n\n Returns:\n Tuple of (plugin_name, version, installed_wheel_path).\n \"\"\"\n # Extract repo info from URL for source tracking\n github_repo = self._extract_github_repo(url)\n\n # Download using standard URL method\n plugin_name, version, wheel_path = self.download_from_url(url, sha256, force)\n\n # Update source to track GitHub release\n manifest_path = self.plugins_dir / plugin_name / \"manifest.json\"\n manifest = json.loads(manifest_path.read_text())\n\n source = PluginSource(\n type=PluginSourceType.GITHUB_RELEASE,\n url=url,\n github_repo=github_repo,\n sha256=manifest.get(\"sha256\"),\n )\n manifest[\"source\"] = source.to_dict()\n manifest_path.write_text(json.dumps(manifest, indent=2))\n\n return plugin_name, version, wheel_path\n\n def download_from_github_artifact(\n self,\n url: str,\n force: bool = False,\n ) -> Tuple[str, str, Path]:\n \"\"\"\n Download and install a plugin from a GitHub Actions artifact.\n\n GitHub artifacts are ZIP files containing wheel(s). This method:\n 1. Downloads the artifact ZIP\n 2. Extracts the wheel file\n 3. Installs the wheel\n\n Args:\n url: GitHub artifact URL (browser URL or API URL).\n force: Skip security warnings if True.\n\n Returns:\n Tuple of (plugin_name, version, installed_wheel_path).\n\n Raises:\n GitHubArtifactError: If artifact cannot be downloaded or processed.\n DownloadError: If installation fails.\n \"\"\"\n # Parse artifact URL to get API endpoint\n artifact_info = self._parse_github_artifact_url(url)\n if not artifact_info:\n raise GitHubArtifactError(f\"Invalid GitHub artifact URL: {url}\")\n\n owner, repo, artifact_id = artifact_info\n\n # Get GitHub token from environment\n github_token = os.environ.get(\"GITHUB_TOKEN\")\n if not github_token:\n # Try gh CLI as fallback\n github_token = self._get_gh_token()\n\n if not github_token:\n raise GitHubArtifactError(\n \"GitHub authentication required. Set GITHUB_TOKEN environment variable \"\n \"or install and authenticate with GitHub CLI (gh auth login).\"\n )\n\n # Download artifact ZIP\n api_url = f\"https://api.github.com/repos/{owner}/{repo}/actions/artifacts/{artifact_id}/zip\"\n\n with tempfile.TemporaryDirectory() as temp_dir:\n temp_dir_path = Path(temp_dir)\n artifact_zip_path = temp_dir_path / \"artifact.zip\"\n\n try:\n logger.info(\"Downloading GitHub artifact...\")\n response = requests.get(\n api_url,\n headers={\n \"Authorization\": f\"Bearer {github_token}\",\n \"Accept\": \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n stream=True,\n )\n response.raise_for_status()\n\n with open(artifact_zip_path, \"wb\") as f:\n for chunk in response.iter_content(chunk_size=8192):\n f.write(chunk)\n\n except requests.RequestException as e:\n raise GitHubArtifactError(f\"Failed to download artifact: {e}\") from e\n\n # Extract ZIP and find wheel\n extract_dir = temp_dir_path / \"extracted\"\n\n try:\n from ggshield.utils.archive import safe_unpack\n\n safe_unpack(artifact_zip_path, extract_dir)\n except Exception as e:\n raise GitHubArtifactError(f\"Failed to extract artifact: {e}\") from e\n\n # Find wheel file in extracted contents\n wheel_files = list(extract_dir.glob(\"**/*.whl\"))\n if not wheel_files:\n raise GitHubArtifactError(\"No wheel file found in artifact\")\n\n if len(wheel_files) > 1:\n logger.warning(\n \"Multiple wheel files found in artifact, using first: %s\",\n wheel_files[0].name,\n )\n\n temp_wheel_path = wheel_files[0]\n\n # Extract metadata\n try:\n metadata = extract_wheel_metadata(temp_wheel_path)\n except WheelError as e:\n raise DownloadError(f\"Invalid wheel in artifact: {e}\") from e\n\n plugin_name = metadata.name\n version = metadata.version\n self._validate_plugin_name(plugin_name)\n\n # Create plugin directory and copy wheel\n plugin_dir = self.plugins_dir / plugin_name\n plugin_dir.mkdir(parents=True, exist_ok=True)\n\n dest_wheel_path = plugin_dir / temp_wheel_path.name\n shutil.copy2(temp_wheel_path, dest_wheel_path)\n\n # Compute SHA256\n sha256 = self._compute_sha256(dest_wheel_path)\n\n # Create source tracking\n source = PluginSource(\n type=PluginSourceType.GITHUB_ARTIFACT,\n url=url,\n github_repo=f\"{owner}/{repo}\",\n sha256=sha256,\n )\n\n self._write_manifest(\n plugin_dir=plugin_dir,\n plugin_name=plugin_name,\n version=version,\n wheel_filename=dest_wheel_path.name,\n sha256=sha256,\n source=source,\n )\n\n logger.info(\"Installed %s v%s from GitHub artifact\", plugin_name, version)\n\n return plugin_name, version, dest_wheel_path\n\n def uninstall(self, plugin_name: str) -> bool:\n \"\"\"Uninstall a plugin (by package name or entry point name).\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n logger.warning(\"Invalid plugin name: %s\", plugin_name)\n return False\n\n plugin_dir = self.plugins_dir / plugin_name\n if not plugin_dir.exists():\n # Try finding by entry point name\n plugin_dir = self._find_plugin_dir_by_entry_point(plugin_name)\n if plugin_dir is None:\n return False\n\n shutil.rmtree(plugin_dir)\n\n logger.info(\"Uninstalled plugin: %s\", plugin_name)\n return True\n\n def get_installed_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the installed version of a plugin (by package name or entry point name).\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n logger.warning(\"Invalid plugin name: %s\", plugin_name)\n return None\n\n manifest_path = self.plugins_dir / plugin_name / \"manifest.json\"\n if not manifest_path.exists():\n # Try finding by entry point name\n plugin_dir = self._find_plugin_dir_by_entry_point(plugin_name)\n if plugin_dir is None:\n return None\n manifest_path = plugin_dir / \"manifest.json\"\n\n try:\n manifest = json.loads(manifest_path.read_text())\n return manifest.get(\"version\")\n except (json.JSONDecodeError, KeyError):\n return None\n\n def is_installed(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is installed (by package name or entry point name).\"\"\"\n return self.get_installed_version(plugin_name) is not None\n\n def _find_plugin_dir_by_entry_point(self, entry_point_name: str) -> Optional[Path]:\n \"\"\"Find a plugin directory by its entry point name.\"\"\"\n if not self.plugins_dir.exists():\n return None\n\n for plugin_dir in self.plugins_dir.iterdir():\n if not plugin_dir.is_dir():\n continue\n\n manifest_path = plugin_dir / \"manifest.json\"\n if not manifest_path.exists():\n continue\n\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\", \"\")\n wheel_path = plugin_dir / wheel_filename\n\n if wheel_path.exists():\n # Read entry point name from wheel\n ep_name = self._read_entry_point_name_from_wheel(wheel_path)\n if ep_name == entry_point_name:\n return plugin_dir\n except (json.JSONDecodeError, KeyError):\n continue\n\n return None\n\n def _read_entry_point_name_from_wheel(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the entry point name from a wheel file.\"\"\"\n from ggshield.core.plugin.loader import read_entry_point_from_wheel\n\n result = read_entry_point_from_wheel(wheel_path)\n return result[0] if result else None\n\n def get_wheel_path(self, plugin_name: str) -> Optional[Path]:\n \"\"\"Get the path to an installed plugin's wheel file.\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n logger.warning(\"Invalid plugin name: %s\", plugin_name)\n return None\n\n manifest_path = self.plugins_dir / plugin_name / \"manifest.json\"\n if not manifest_path.exists():\n return None\n\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\")\n if wheel_filename:\n wheel_path = self.plugins_dir / plugin_name / wheel_filename\n if wheel_path.exists():\n return wheel_path\n except (json.JSONDecodeError, KeyError):\n pass\n\n return None\n\n def get_manifest(self, plugin_name: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get the full manifest for an installed plugin.\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n logger.warning(\"Invalid plugin name: %s\", plugin_name)\n return None\n\n manifest_path = self.plugins_dir / plugin_name / \"manifest.json\"\n if not manifest_path.exists():\n return None\n\n try:\n return json.loads(manifest_path.read_text())\n except json.JSONDecodeError:\n return None\n\n def get_plugin_source(self, plugin_name: str) -> Optional[PluginSource]:\n \"\"\"Get the source information for an installed plugin.\"\"\"\n manifest = self.get_manifest(plugin_name)\n if not manifest:\n return None\n\n source_data = manifest.get(\"source\")\n if not source_data:\n # Legacy manifest without source tracking - assume GitGuardian API\n return PluginSource(type=PluginSourceType.GITGUARDIAN_API)\n\n try:\n return PluginSource.from_dict(source_data)\n except (KeyError, ValueError):\n return None\n\n @staticmethod\n def _is_valid_plugin_name(plugin_name: str) -> bool:\n \"\"\"Check if plugin name is safe to use as a path segment.\"\"\"\n if not plugin_name or plugin_name in {\".\", \"..\"}:\n return False\n if \"/\" in plugin_name or \"\\\\\" in plugin_name:\n return False\n if \"\\x00\" in plugin_name:\n return False\n return True\n\n def _validate_plugin_name(self, plugin_name: str) -> None:\n \"\"\"Validate plugin name and raise on unsafe values.\"\"\"\n if not self._is_valid_plugin_name(plugin_name):\n raise DownloadError(f\"Invalid plugin name: {plugin_name!r}\")\n\n def _write_manifest(\n self,\n plugin_dir: Path,\n plugin_name: str,\n version: str,\n wheel_filename: str,\n sha256: str,\n source: PluginSource,\n ) -> None:\n \"\"\"Write the plugin manifest file.\"\"\"\n manifest = {\n \"plugin_name\": plugin_name,\n \"version\": version,\n \"wheel_filename\": wheel_filename,\n \"sha256\": sha256,\n \"source\": source.to_dict(),\n \"installed_at\": datetime.now(timezone.utc).isoformat(),\n }\n manifest_path = plugin_dir / \"manifest.json\"\n manifest_path.write_text(json.dumps(manifest, indent=2))\n\n def _compute_sha256(self, file_path: Path) -> str:\n \"\"\"Compute SHA256 hash of a file.\"\"\"\n sha256_hash = hashlib.sha256()\n with open(file_path, \"rb\") as f:\n for chunk in iter(lambda: f.read(8192), b\"\"):\n sha256_hash.update(chunk)\n return sha256_hash.hexdigest()\n\n def _extract_github_repo(self, url: str) -> Optional[str]:\n \"\"\"Extract owner/repo from a GitHub URL.\"\"\"\n # Pattern: github.com/{owner}/{repo}/...\n match = re.match(r\"https://github\\.com/([^/]+)/([^/]+)\", url)\n if match:\n return f\"{match.group(1)}/{match.group(2)}\"\n return None\n\n def _parse_github_artifact_url(self, url: str) -> Optional[Tuple[str, str, str]]:\n \"\"\"\n Parse GitHub artifact URL to extract owner, repo, and artifact ID.\n\n Supports URLs like:\n - https://github.com/{owner}/{repo}/actions/runs/{run_id}/artifacts/{artifact_id}\n \"\"\"\n pattern = (\n r\"https://github\\.com/([^/]+)/([^/]+)/actions/runs/\\d+/artifacts/(\\d+)\"\n )\n match = re.match(pattern, url)\n if match:\n return match.group(1), match.group(2), match.group(3)\n return None\n\n def _get_gh_token(self) -> Optional[str]:\n \"\"\"Try to get GitHub token from gh CLI.\"\"\"\n import subprocess\n\n try:\n result = subprocess.run(\n [\"gh\", \"auth\", \"token\"],\n capture_output=True,\n text=True,\n timeout=5,\n )\n if result.returncode == 0:\n return result.stdout.strip()\n except (subprocess.SubprocessError, FileNotFoundError):\n pass\n return None", "n_chars_compressed": 21541, "compression_ratio": 1.0}, "tests/unit/verticals/hmsl/secret_manager/hashicorp_vault/test_api_client.py::281": {"resolved_imports": ["ggshield/verticals/hmsl/secret_manager/hashicorp_vault/api_client.py", "ggshield/verticals/hmsl/secret_manager/hashicorp_vault/exceptions.py", "ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py"], "used_names": ["VaultAPIClient", "VaultKvMount", "patch"], "enclosing_function": "test_get_secrets_or_empty_success", "extracted_code": "# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/api_client.py\nclass VaultAPIClient:\n \"\"\"Client to interact with Vault API.\"\"\"\n\n def __init__(self, vault_url: str, api_token: str) -> None:\n self.session = requests.Session()\n self.session.headers[\"X-Vault-Token\"] = api_token\n\n if not vault_url.startswith(\"http://\") and not vault_url.startswith(\"https://\"):\n vault_url = f\"https://{vault_url}\"\n try:\n self.vault_url = urlparse(vault_url).geturl()\n except ValueError:\n raise VaultInvalidUrlError(\n f\"cannot parse the Vault URL '{vault_url}'. Are you sure it is valid?\"\n )\n\n def _make_request(\n self, endpoint: str, method: str = \"GET\", api_version: str = \"v1\"\n ) -> Dict[str, Any]:\n \"\"\" \"\n Make request to the API.\n \"\"\"\n api_res = self.session.request(\n method, f\"{self.vault_url}/{api_version}/{endpoint}\"\n )\n api_res.raise_for_status()\n\n return api_res.json()\n\n def get_kv_mounts(self) -> Generator[VaultKvMount, None, None]:\n \"\"\"\n Get all kv mounts for the Vault instance.\n\n Will try the /sys/mounts endpoint first, and if there is a forbidden error\n fallback to the /sys/internal/ui internal endpoint.\n \"\"\"\n\n try:\n api_res = self._make_request(\"sys/mounts\")[\"data\"]\n except requests.HTTPError:\n api_res = self._make_request(\"sys/internal/ui/mounts\")[\"data\"][\"secret\"]\n\n for key, value in api_res.items():\n if value[\"type\"] != \"kv\":\n continue\n\n yield VaultKvMount(\n name=key.rstrip(\"/\"), # remove trailing slash\n version=value[\"options\"][\"version\"],\n )\n\n def list_kv_items(self, mount: VaultKvMount, path: str) -> List[str]:\n logger.debug(f\"Listing kv items for mount {mount.name} at {path}\")\n\n api_endpoint = (\n f\"{mount.name}/metadata/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n\n try:\n api_res = self._make_request(api_endpoint, method=\"LIST\")\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n # The API return 404 when trying to list items when the path is a file\n # and not a directory\n if exc.response.status_code == 404:\n raise VaultPathIsNotADirectoryError()\n\n raise exc\n\n return [item.rstrip(\"/\") for item in api_res[\"data\"][\"keys\"]]\n\n def get_kv_secrets(self, mount: VaultKvMount, path: str) -> List[Tuple[str, str]]:\n \"\"\"\n Get secrets from the specified mount at the specified path.\n\n Returns a list of tuples containing secret key and secret value\n \"\"\"\n\n logger.debug(f\"Getting secrets at {path}\")\n api_endpoint = (\n f\"{mount.name}/data/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n try:\n api_res = self._make_request(api_endpoint)\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n if exc.response.status_code == 404:\n raise VaultNotFoundItemError(\n f\"{path} was not found: it's either not a file, \"\n \"was deleted or cannot be accessed with the current token\"\n )\n\n raise exc\n\n data = api_res[\"data\"][\"data\"] if mount.version == \"2\" else api_res[\"data\"]\n return [\n (f\"{path}/{secret_name}\", secret_value)\n for secret_name, secret_value in data.items()\n ]\n\n def _get_secrets_or_empty(\n self, mount: VaultKvMount, folder_path: str\n ) -> VaultSecrets:\n \"\"\"\n Call get_kv_secrets on the given mount and folder path.\n\n Return the secrets or an empty list if VaultNotFoundItemError was raised.\n \"\"\"\n try:\n return VaultSecrets(\n secrets=self.get_kv_secrets(mount, folder_path),\n not_fetched_paths=[],\n )\n except VaultNotFoundItemError as exc:\n logger.debug(f\"Not found error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n def _get_secrets_from_path(\n self, mount: VaultKvMount, folder_path: str, recursive: bool\n ) -> VaultSecrets:\n \"\"\"\n Get the secrets on the given mount and folder path.\n If recursive is True, iterate recursively on subfolders.\n\n Return the secrets or an empty list if errors were raised.\n \"\"\"\n # Get current directory secret\n try:\n subfolders = self.list_kv_items(mount, folder_path)\n except VaultPathIsNotADirectoryError:\n return self._get_secrets_or_empty(mount, folder_path)\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n if not recursive:\n return VaultSecrets(secrets=[], not_fetched_paths=[])\n\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for subfolder in subfolders:\n subfolder_result = self._get_secrets_from_path(\n mount, f\"{folder_path}/{subfolder}\", True\n )\n result.secrets += subfolder_result.secrets\n result.not_fetched_paths += subfolder_result.not_fetched_paths\n\n return result\n\n def get_secrets(\n self, mount: VaultKvMount, path: str, recursive: bool\n ) -> VaultSecrets:\n # Check first if it's a directory\n try:\n keys = self.list_kv_items(mount, path)\n except VaultPathIsNotADirectoryError:\n # If it's a file, return directly\n return self._get_secrets_or_empty(mount, path)\n\n # If it's a folder, get secrets of the folder\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for folder in keys:\n folder_path = f\"{path}/{folder}\".strip(\"/\")\n folder_result = self._get_secrets_from_path(mount, folder_path, recursive)\n result.secrets += folder_result.secrets\n result.not_fetched_paths += folder_result.not_fetched_paths\n\n return result\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py\nclass VaultKvMount(VaultMount):\n \"\"\"\n Model to represent a Vault KV mount.\n \"\"\"\n\n version: str", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 7009, "extracted_code_full": "# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/api_client.py\nclass VaultAPIClient:\n \"\"\"Client to interact with Vault API.\"\"\"\n\n def __init__(self, vault_url: str, api_token: str) -> None:\n self.session = requests.Session()\n self.session.headers[\"X-Vault-Token\"] = api_token\n\n if not vault_url.startswith(\"http://\") and not vault_url.startswith(\"https://\"):\n vault_url = f\"https://{vault_url}\"\n try:\n self.vault_url = urlparse(vault_url).geturl()\n except ValueError:\n raise VaultInvalidUrlError(\n f\"cannot parse the Vault URL '{vault_url}'. Are you sure it is valid?\"\n )\n\n def _make_request(\n self, endpoint: str, method: str = \"GET\", api_version: str = \"v1\"\n ) -> Dict[str, Any]:\n \"\"\" \"\n Make request to the API.\n \"\"\"\n api_res = self.session.request(\n method, f\"{self.vault_url}/{api_version}/{endpoint}\"\n )\n api_res.raise_for_status()\n\n return api_res.json()\n\n def get_kv_mounts(self) -> Generator[VaultKvMount, None, None]:\n \"\"\"\n Get all kv mounts for the Vault instance.\n\n Will try the /sys/mounts endpoint first, and if there is a forbidden error\n fallback to the /sys/internal/ui internal endpoint.\n \"\"\"\n\n try:\n api_res = self._make_request(\"sys/mounts\")[\"data\"]\n except requests.HTTPError:\n api_res = self._make_request(\"sys/internal/ui/mounts\")[\"data\"][\"secret\"]\n\n for key, value in api_res.items():\n if value[\"type\"] != \"kv\":\n continue\n\n yield VaultKvMount(\n name=key.rstrip(\"/\"), # remove trailing slash\n version=value[\"options\"][\"version\"],\n )\n\n def list_kv_items(self, mount: VaultKvMount, path: str) -> List[str]:\n logger.debug(f\"Listing kv items for mount {mount.name} at {path}\")\n\n api_endpoint = (\n f\"{mount.name}/metadata/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n\n try:\n api_res = self._make_request(api_endpoint, method=\"LIST\")\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n # The API return 404 when trying to list items when the path is a file\n # and not a directory\n if exc.response.status_code == 404:\n raise VaultPathIsNotADirectoryError()\n\n raise exc\n\n return [item.rstrip(\"/\") for item in api_res[\"data\"][\"keys\"]]\n\n def get_kv_secrets(self, mount: VaultKvMount, path: str) -> List[Tuple[str, str]]:\n \"\"\"\n Get secrets from the specified mount at the specified path.\n\n Returns a list of tuples containing secret key and secret value\n \"\"\"\n\n logger.debug(f\"Getting secrets at {path}\")\n api_endpoint = (\n f\"{mount.name}/data/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n try:\n api_res = self._make_request(api_endpoint)\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n if exc.response.status_code == 404:\n raise VaultNotFoundItemError(\n f\"{path} was not found: it's either not a file, \"\n \"was deleted or cannot be accessed with the current token\"\n )\n\n raise exc\n\n data = api_res[\"data\"][\"data\"] if mount.version == \"2\" else api_res[\"data\"]\n return [\n (f\"{path}/{secret_name}\", secret_value)\n for secret_name, secret_value in data.items()\n ]\n\n def _get_secrets_or_empty(\n self, mount: VaultKvMount, folder_path: str\n ) -> VaultSecrets:\n \"\"\"\n Call get_kv_secrets on the given mount and folder path.\n\n Return the secrets or an empty list if VaultNotFoundItemError was raised.\n \"\"\"\n try:\n return VaultSecrets(\n secrets=self.get_kv_secrets(mount, folder_path),\n not_fetched_paths=[],\n )\n except VaultNotFoundItemError as exc:\n logger.debug(f\"Not found error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n def _get_secrets_from_path(\n self, mount: VaultKvMount, folder_path: str, recursive: bool\n ) -> VaultSecrets:\n \"\"\"\n Get the secrets on the given mount and folder path.\n If recursive is True, iterate recursively on subfolders.\n\n Return the secrets or an empty list if errors were raised.\n \"\"\"\n # Get current directory secret\n try:\n subfolders = self.list_kv_items(mount, folder_path)\n except VaultPathIsNotADirectoryError:\n return self._get_secrets_or_empty(mount, folder_path)\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n if not recursive:\n return VaultSecrets(secrets=[], not_fetched_paths=[])\n\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for subfolder in subfolders:\n subfolder_result = self._get_secrets_from_path(\n mount, f\"{folder_path}/{subfolder}\", True\n )\n result.secrets += subfolder_result.secrets\n result.not_fetched_paths += subfolder_result.not_fetched_paths\n\n return result\n\n def get_secrets(\n self, mount: VaultKvMount, path: str, recursive: bool\n ) -> VaultSecrets:\n # Check first if it's a directory\n try:\n keys = self.list_kv_items(mount, path)\n except VaultPathIsNotADirectoryError:\n # If it's a file, return directly\n return self._get_secrets_or_empty(mount, path)\n\n # If it's a folder, get secrets of the folder\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for folder in keys:\n folder_path = f\"{path}/{folder}\".strip(\"/\")\n folder_result = self._get_secrets_from_path(mount, folder_path, recursive)\n result.secrets += folder_result.secrets\n result.not_fetched_paths += folder_result.not_fetched_paths\n\n return result\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py\nclass VaultKvMount(VaultMount):\n \"\"\"\n Model to represent a Vault KV mount.\n \"\"\"\n\n version: str", "n_chars_compressed": 7009, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_path.py::404": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["ExitCode", "Path", "cli", "os", "write_text"], "enclosing_function": "test_scan_path_should_detect_non_git_files", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 12, "n_files_resolved": 2, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/cmd/test_install.py::202": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/install.py", "ggshield/core/errors.py"], "used_names": ["CliRunner", "Mock", "Path", "install_local", "patch"], "enclosing_function": "test_install_local_detects_husky", "extracted_code": "# Source: ggshield/cmd/install.py\ndef install_local(hook_type: str, force: bool, append: bool) -> int:\n \"\"\"Local pre-commit/pre-push hook installation.\"\"\"\n check_git_dir()\n hook_dir_path = get_local_hook_dir_path()\n return create_hook(\n hook_dir_path=hook_dir_path,\n force=force,\n local_hook_support=False,\n hook_type=hook_type,\n append=append,\n )", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 397, "extracted_code_full": "# Source: ggshield/cmd/install.py\ndef install_local(hook_type: str, force: bool, append: bool) -> int:\n \"\"\"Local pre-commit/pre-push hook installation.\"\"\"\n check_git_dir()\n hook_dir_path = get_local_hook_dir_path()\n return create_hook(\n hook_dir_path=hook_dir_path,\n force=force,\n local_hook_support=False,\n hook_type=hook_type,\n append=append,\n )", "n_chars_compressed": 397, "compression_ratio": 1.0}, "tests/functional/hmsl/test_hmsl_check.py::28": {"resolved_imports": [], "used_names": ["Path", "run_ggshield"], "enclosing_function": "test_check_short_circuits_when_all_filtered", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/verticals/secret/test_secret_scanner.py::419": {"resolved_imports": ["ggshield/__init__.py", "ggshield/core/cache.py", "ggshield/core/config/user_config.py", "ggshield/core/errors.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/scan/scannable.py", "ggshield/core/scanner_ui/scanner_ui.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Cache", "Match", "Mock", "MultiScanResult", "PolicyBreak", "ScanContext", "ScanMode", "ScanResult", "SecretConfig", "SecretScanner", "StringScannable", "patch", "pytest"], "enclosing_function": "test_scan_ignore_known_secrets", "extracted_code": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_imports_parsed": 18, "n_files_resolved": 12, "n_chars_extracted": 14742, "extracted_code_full": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_chars_compressed": 14742, "compression_ratio": 1.0}, "tests/unit/core/scan/test_commit.py::118": {"resolved_imports": ["ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/utils/git_shell.py"], "used_names": ["Commit", "Path"], "enclosing_function": "test_patch_separation", "extracted_code": "# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 4266, "extracted_code_full": "# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"", "n_chars_compressed": 4266, "compression_ratio": 1.0}, "tests/unit/core/scan/test_commit.py::117": {"resolved_imports": ["ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/utils/git_shell.py"], "used_names": ["Commit", "Path"], "enclosing_function": "test_patch_separation", "extracted_code": "# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 4266, "extracted_code_full": "# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"", "n_chars_compressed": 4266, "compression_ratio": 1.0}, "tests/unit/core/config/test_user_config.py::31": {"resolved_imports": ["ggshield/core/config/config.py", "ggshield/core/config/user_config.py", "ggshield/core/errors.py", "ggshield/core/types.py"], "used_names": ["Config", "write_yaml"], "enclosing_function": "test_display_options", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 8037, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_chars_compressed": 8037, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_docker.py::196": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/secret_scan_common_options.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/scannable.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/docker.py"], "used_names": ["DOCKER_EXAMPLE_PATH", "DOCKER__INCOMPLETE_MANIFEST_EXAMPLE_PATH", "DockerImage", "ExitCode", "IGNORED_DEFAULT_WILDCARDS", "LayerInfo", "Mock", "Path", "StringScannable", "UNCHECKED_SECRET_PATCH", "assert_invoke_exited_with", "cli", "click", "init_exclusion_regexes", "json", "my_vcr", "patch", "pytest", "write_text"], "enclosing_function": "test_docker_scan_archive", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/cmd/secret/scan/secret_scan_common_options.py\nIGNORED_DEFAULT_WILDCARDS = [\n \"**/.git/*/**/*\", # only keep files in .git/ but not in subdirectories\n \"**/.pytest_cache/**/*\",\n \"**/.mypy_cache/**/*\",\n \"**/.venv/**/*\",\n \"**/.eggs/**/*\",\n \"**/.eggs-info/**/*\",\n \"**/vendor/**/*\",\n \"**/vendors/**/*\",\n \"**/node_modules/**/*\",\n \"top-1000.txt*\",\n \"**/*.storyboard*\",\n \"**/*.xib\",\n \"**/*.mdx*\",\n \"**/*.sops\",\n]\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/filter.py\ndef init_exclusion_regexes(paths_ignore: Iterable[str]) -> Set[Pattern[str]]:\n \"\"\"\n filter_set creates a set of paths of the ignored\n entries from 3 sources:\n .gitguardian.yaml\n files in .git\n files ignore in .gitignore\n \"\"\"\n res = set()\n for path in paths_ignore:\n if not is_pattern_valid(path):\n raise UsageError(f\"{path} is not a valid exclude pattern.\")\n res.add(re.compile(translate_user_pattern(path)))\n return res\n\n\n# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n\n# Source: ggshield/verticals/secret/docker.py\nclass LayerInfo:\n filename: str\n command: str\n diff_id: str\n\n def should_scan(self) -> bool:\n \"\"\"\n Returns True if a layer should be scanned, False otherwise.\n Only COPY and ADD layers should be scanned.\n \"\"\"\n if self.command == \"\":\n # Some images contain layers with no commands. Since we don't know how they have\n # been created, we must scan them.\n # Examples of such images from Docker Hub:\n # - aevea/release-notary:0.9.7\n # - redhat/ubi8:8.6-754\n return True\n else:\n return LAYER_TO_SCAN_PATTERN.search(self.command) is not None\n\nclass DockerImage:\n # The manifest.json file\n manifest: Dict[str, Any]\n\n # The Image JSON file\n # (see https://github.com/moby/moby/blob/master/image/spec/v1.2.md#terminology)\n image: Dict[str, Any]\n\n layer_infos: List[LayerInfo]\n\n @staticmethod\n @contextmanager\n def open(archive_path: Path) -> Generator[\"DockerImage\", None, None]:\n \"\"\"ContextManager to create a DockerImage instance.\"\"\"\n with tarfile.open(archive_path) as tar_file:\n yield DockerImage(archive_path, tar_file)\n\n def __init__(self, archive_path: Path, tar_file: tarfile.TarFile):\n \"\"\"Creates a DockerImage instance. Internal. Prefer using DockerImage.open().\"\"\"\n self.archive_path = archive_path\n self.tar_file = tar_file\n self._load_manifest()\n self._load_image()\n self.config_scannable = StringScannable(\n \"Dockerfile or build-args\", json.dumps(self.image, indent=2)\n )\n\n self._load_layer_infos()\n\n def _load_manifest(self) -> None:\n \"\"\"\n Reads \"manifest.json\", stores result in self.manifest\n \"\"\"\n manifest_file = self.tar_file.extractfile(\"manifest.json\")\n if manifest_file is None:\n raise InvalidDockerArchiveException(\"No manifest file found.\")\n\n self.manifest = json.load(manifest_file)[0]\n\n def _load_image(self) -> None:\n \"\"\"\n Reads the image JSON file, stores result in self.image\n \"\"\"\n try:\n config_file_path = self.manifest[\"Config\"]\n except KeyError:\n raise InvalidDockerArchiveException(\"No Config key in manifest.\")\n\n config_file_info = self.tar_file.getmember(config_file_path)\n if config_file_info is None:\n raise InvalidDockerArchiveException(\"No config file found.\")\n\n config_file = self.tar_file.extractfile(config_file_info)\n if config_file is None:\n raise InvalidDockerArchiveException(\"Config file could not be extracted.\")\n\n self.image = json.load(config_file)\n\n def _load_layer_infos(self) -> None:\n \"\"\"\n Fill self.layer_infos with LayerInfo instances for all non-empty layers\n \"\"\"\n\n #\n # manifest[\"Layers\"] contains a list of non-empty layers like this:\n #\n # \"/layer.tar\"\n layer_filenames = self.manifest[\"Layers\"]\n\n # image[\"history\"] contains a list of entries like this:\n # {\n # \"created\": ISO8601 timestamp,\n # \"created_by\": command to build the layer\n # \"empty_layer\": if present, equals true\n # }\n non_empty_history_entries = [\n x for x in self.image[\"history\"] if not x.get(\"empty_layer\")\n ]\n\n #\n # image[\"rootfs\"][\"diff_ids\"] contains the list of layer IDs\n diff_ids = self.image[\"rootfs\"][\"diff_ids\"]\n\n layer_infos = [\n LayerInfo(\n filename=filename,\n command=history.get(\"created_by\", \"\"),\n diff_id=diff_id,\n )\n for filename, history, diff_id in zip(\n layer_filenames, non_empty_history_entries, diff_ids\n )\n ]\n self.layer_infos = [x for x in layer_infos if x.should_scan()]\n\n def get_layer_scannables(\n self, layer_info: LayerInfo, exclusion_regexes: Set[re.Pattern[str]]\n ) -> Iterable[Scannable]:\n \"\"\"\n Extracts Scannable to be scanned for given layer.\n \"\"\"\n layer_filename = layer_info.filename\n layer_archive = tarfile.open(\n name=self.archive_path / layer_filename,\n fileobj=self.tar_file.extractfile(layer_filename),\n )\n\n layer_id = layer_info.diff_id\n\n for file_info in layer_archive:\n if not file_info.isfile():\n continue\n\n if file_info.size == 0:\n continue\n\n if not _validate_filepath(\n filepath=file_info.path, exclusion_regexes=exclusion_regexes\n ):\n continue\n\n yield DockerContentScannable(layer_id, layer_archive, file_info)", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 8998, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/cmd/secret/scan/secret_scan_common_options.py\nIGNORED_DEFAULT_WILDCARDS = [\n \"**/.git/*/**/*\", # only keep files in .git/ but not in subdirectories\n \"**/.pytest_cache/**/*\",\n \"**/.mypy_cache/**/*\",\n \"**/.venv/**/*\",\n \"**/.eggs/**/*\",\n \"**/.eggs-info/**/*\",\n \"**/vendor/**/*\",\n \"**/vendors/**/*\",\n \"**/node_modules/**/*\",\n \"top-1000.txt*\",\n \"**/*.storyboard*\",\n \"**/*.xib\",\n \"**/*.mdx*\",\n \"**/*.sops\",\n]\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/filter.py\ndef init_exclusion_regexes(paths_ignore: Iterable[str]) -> Set[Pattern[str]]:\n \"\"\"\n filter_set creates a set of paths of the ignored\n entries from 3 sources:\n .gitguardian.yaml\n files in .git\n files ignore in .gitignore\n \"\"\"\n res = set()\n for path in paths_ignore:\n if not is_pattern_valid(path):\n raise UsageError(f\"{path} is not a valid exclude pattern.\")\n res.add(re.compile(translate_user_pattern(path)))\n return res\n\n\n# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n\n# Source: ggshield/verticals/secret/docker.py\nclass LayerInfo:\n filename: str\n command: str\n diff_id: str\n\n def should_scan(self) -> bool:\n \"\"\"\n Returns True if a layer should be scanned, False otherwise.\n Only COPY and ADD layers should be scanned.\n \"\"\"\n if self.command == \"\":\n # Some images contain layers with no commands. Since we don't know how they have\n # been created, we must scan them.\n # Examples of such images from Docker Hub:\n # - aevea/release-notary:0.9.7\n # - redhat/ubi8:8.6-754\n return True\n else:\n return LAYER_TO_SCAN_PATTERN.search(self.command) is not None\n\nclass DockerImage:\n # The manifest.json file\n manifest: Dict[str, Any]\n\n # The Image JSON file\n # (see https://github.com/moby/moby/blob/master/image/spec/v1.2.md#terminology)\n image: Dict[str, Any]\n\n layer_infos: List[LayerInfo]\n\n @staticmethod\n @contextmanager\n def open(archive_path: Path) -> Generator[\"DockerImage\", None, None]:\n \"\"\"ContextManager to create a DockerImage instance.\"\"\"\n with tarfile.open(archive_path) as tar_file:\n yield DockerImage(archive_path, tar_file)\n\n def __init__(self, archive_path: Path, tar_file: tarfile.TarFile):\n \"\"\"Creates a DockerImage instance. Internal. Prefer using DockerImage.open().\"\"\"\n self.archive_path = archive_path\n self.tar_file = tar_file\n self._load_manifest()\n self._load_image()\n self.config_scannable = StringScannable(\n \"Dockerfile or build-args\", json.dumps(self.image, indent=2)\n )\n\n self._load_layer_infos()\n\n def _load_manifest(self) -> None:\n \"\"\"\n Reads \"manifest.json\", stores result in self.manifest\n \"\"\"\n manifest_file = self.tar_file.extractfile(\"manifest.json\")\n if manifest_file is None:\n raise InvalidDockerArchiveException(\"No manifest file found.\")\n\n self.manifest = json.load(manifest_file)[0]\n\n def _load_image(self) -> None:\n \"\"\"\n Reads the image JSON file, stores result in self.image\n \"\"\"\n try:\n config_file_path = self.manifest[\"Config\"]\n except KeyError:\n raise InvalidDockerArchiveException(\"No Config key in manifest.\")\n\n config_file_info = self.tar_file.getmember(config_file_path)\n if config_file_info is None:\n raise InvalidDockerArchiveException(\"No config file found.\")\n\n config_file = self.tar_file.extractfile(config_file_info)\n if config_file is None:\n raise InvalidDockerArchiveException(\"Config file could not be extracted.\")\n\n self.image = json.load(config_file)\n\n def _load_layer_infos(self) -> None:\n \"\"\"\n Fill self.layer_infos with LayerInfo instances for all non-empty layers\n \"\"\"\n\n #\n # manifest[\"Layers\"] contains a list of non-empty layers like this:\n #\n # \"/layer.tar\"\n layer_filenames = self.manifest[\"Layers\"]\n\n # image[\"history\"] contains a list of entries like this:\n # {\n # \"created\": ISO8601 timestamp,\n # \"created_by\": command to build the layer\n # \"empty_layer\": if present, equals true\n # }\n non_empty_history_entries = [\n x for x in self.image[\"history\"] if not x.get(\"empty_layer\")\n ]\n\n #\n # image[\"rootfs\"][\"diff_ids\"] contains the list of layer IDs\n diff_ids = self.image[\"rootfs\"][\"diff_ids\"]\n\n layer_infos = [\n LayerInfo(\n filename=filename,\n command=history.get(\"created_by\", \"\"),\n diff_id=diff_id,\n )\n for filename, history, diff_id in zip(\n layer_filenames, non_empty_history_entries, diff_ids\n )\n ]\n self.layer_infos = [x for x in layer_infos if x.should_scan()]\n\n def get_layer_scannables(\n self, layer_info: LayerInfo, exclusion_regexes: Set[re.Pattern[str]]\n ) -> Iterable[Scannable]:\n \"\"\"\n Extracts Scannable to be scanned for given layer.\n \"\"\"\n layer_filename = layer_info.filename\n layer_archive = tarfile.open(\n name=self.archive_path / layer_filename,\n fileobj=self.tar_file.extractfile(layer_filename),\n )\n\n layer_id = layer_info.diff_id\n\n for file_info in layer_archive:\n if not file_info.isfile():\n continue\n\n if file_info.size == 0:\n continue\n\n if not _validate_filepath(\n filepath=file_info.path, exclusion_regexes=exclusion_regexes\n ):\n continue\n\n yield DockerContentScannable(layer_id, layer_archive, file_info)", "n_chars_compressed": 8998, "compression_ratio": 1.0}, "tests/unit/verticals/secret/test_secret_scanner.py::268": {"resolved_imports": ["ggshield/__init__.py", "ggshield/core/cache.py", "ggshield/core/config/user_config.py", "ggshield/core/errors.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/scan/scannable.py", "ggshield/core/scanner_ui/scanner_ui.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Commit", "Mock", "ScanContext", "ScanMode", "SecretConfig", "SecretScanner", "_SIMPLE_SECRET_TOKEN", "my_vcr"], "enclosing_function": "test_scan_merge_commit", "extracted_code": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_imports_parsed": 18, "n_files_resolved": 12, "n_chars_extracted": 15296, "extracted_code_full": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_chars_compressed": 15296, "compression_ratio": 1.0}, "tests/unit/verticals/secret/output/test_sarif_output.py::135": {"resolved_imports": ["ggshield/core/config/user_config.py", "ggshield/core/scan/commit.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/output/secret_sarif_output_handler.py"], "used_names": ["Results", "SecretConfig", "SecretSARIFOutputHandler", "SecretScanCollection", "json"], "enclosing_function": "test_sarif_output_no_secrets", "extracted_code": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)\n\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details\n\n\n# Source: ggshield/verticals/secret/output/secret_sarif_output_handler.py\nclass SecretSARIFOutputHandler(SecretOutputHandler):\n\n def _process_scan_impl(self, scan: SecretScanCollection) -> str:\n incident_details = (\n scan.get_incident_details(self.client)\n if self.with_incident_details and self.client\n else {}\n )\n dct = {\n \"version\": \"2.1.0\",\n \"$schema\": SCHEMA_URL,\n \"runs\": [\n {\n \"tool\": {\n \"driver\": {\n \"organization\": \"GitGuardian\",\n \"name\": \"ggshield\",\n \"informationUri\": \"https://github.com/GitGuardian/ggshield\",\n \"version\": ggshield_version,\n },\n \"extensions\": [\n {\n \"name\": \"secret\",\n \"version\": VERSIONS.secrets_engine_version,\n }\n ],\n },\n \"results\": list(\n _create_sarif_results(scan.get_all_results(), incident_details)\n ),\n }\n ],\n }\n return json.dumps(dct)", "n_imports_parsed": 18, "n_files_resolved": 4, "n_chars_extracted": 6408, "extracted_code_full": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)\n\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details\n\n\n# Source: ggshield/verticals/secret/output/secret_sarif_output_handler.py\nclass SecretSARIFOutputHandler(SecretOutputHandler):\n\n def _process_scan_impl(self, scan: SecretScanCollection) -> str:\n incident_details = (\n scan.get_incident_details(self.client)\n if self.with_incident_details and self.client\n else {}\n )\n dct = {\n \"version\": \"2.1.0\",\n \"$schema\": SCHEMA_URL,\n \"runs\": [\n {\n \"tool\": {\n \"driver\": {\n \"organization\": \"GitGuardian\",\n \"name\": \"ggshield\",\n \"informationUri\": \"https://github.com/GitGuardian/ggshield\",\n \"version\": ggshield_version,\n },\n \"extensions\": [\n {\n \"name\": \"secret\",\n \"version\": VERSIONS.secrets_engine_version,\n }\n ],\n },\n \"results\": list(\n _create_sarif_results(scan.get_all_results(), incident_details)\n ),\n }\n ],\n }\n return json.dumps(dct)", "n_chars_compressed": 6408, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_repo.py::44": {"resolved_imports": [], "used_names": ["GG_VALID_TOKEN", "Repository", "recreate_censored_content", "run_ggshield_scan"], "enclosing_function": "test_scan_repo", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/core/config/test_auth_config.py::37": {"resolved_imports": ["ggshield/core/config/config.py", "ggshield/core/config/auth_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py"], "used_names": ["Config", "TEST_AUTH_CONFIG", "get_auth_config_filepath", "prepare_auth_config_dict_for_save", "write_yaml"], "enclosing_function": "test_load", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/auth_config.py\ndef prepare_auth_config_dict_for_save(data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Does the opposite of `prepare_auth_config_dict_for_parse`: turn the\n instances[].account key into instances[].accounts keys.\n \"\"\"\n data = deepcopy(data)\n try:\n instances = data[\"instances\"]\n except KeyError:\n return data\n\n for instance in instances:\n account = instance.pop(\"account\")\n instance[\"accounts\"] = [account]\n\n return data\n\n\n# Source: ggshield/core/config/utils.py\ndef get_auth_config_filepath() -> Path:\n return get_config_dir() / AUTH_CONFIG_FILENAME", "n_imports_parsed": 11, "n_files_resolved": 4, "n_chars_extracted": 8691, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/auth_config.py\ndef prepare_auth_config_dict_for_save(data: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Does the opposite of `prepare_auth_config_dict_for_parse`: turn the\n instances[].account key into instances[].accounts keys.\n \"\"\"\n data = deepcopy(data)\n try:\n instances = data[\"instances\"]\n except KeyError:\n return data\n\n for instance in instances:\n account = instance.pop(\"account\")\n instance[\"accounts\"] = [account]\n\n return data\n\n\n# Source: ggshield/core/config/utils.py\ndef get_auth_config_filepath() -> Path:\n return get_config_dir() / AUTH_CONFIG_FILENAME", "n_chars_compressed": 8691, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_platform.py::23": {"resolved_imports": ["ggshield/core/plugin/platform.py"], "used_names": ["PlatformInfo"], "enclosing_function": "test_platform_info_creation", "extracted_code": "# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 159, "extracted_code_full": "# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str", "n_chars_compressed": 159, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_base.py::42": {"resolved_imports": ["ggshield/core/plugin/base.py", "ggshield/core/plugin/registry.py"], "used_names": ["PluginMetadata"], "enclosing_function": "test_metadata_fields", "extracted_code": "# Source: ggshield/core/plugin/base.py\nclass PluginMetadata:\n \"\"\"Metadata about a plugin.\"\"\"\n\n name: str\n version: str\n display_name: str\n description: str\n min_ggshield_version: str", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 200, "extracted_code_full": "# Source: ggshield/core/plugin/base.py\nclass PluginMetadata:\n \"\"\"Metadata about a plugin.\"\"\"\n\n name: str\n version: str\n display_name: str\n description: str\n min_ggshield_version: str", "n_chars_compressed": 200, "compression_ratio": 1.0}, "tests/unit/core/ui/test_ui.py::10": {"resolved_imports": ["ggshield/core/__init__.py", "ggshield/core/ui/__init__.py", "ggshield/core/ui/ggshield_ui.py"], "used_names": ["Level", "ui"], "enclosing_function": "test_level", "extracted_code": "# Source: ggshield/core/ui/ggshield_ui.py\nclass Level(IntEnum):\n ERROR = auto()\n WARNING = auto()\n INFO = auto()\n VERBOSE = auto()\n DEBUG = auto()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 161, "extracted_code_full": "# Source: ggshield/core/ui/ggshield_ui.py\nclass Level(IntEnum):\n ERROR = auto()\n WARNING = auto()\n INFO = auto()\n VERBOSE = auto()\n DEBUG = auto()", "n_chars_compressed": 161, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_base.py::41": {"resolved_imports": ["ggshield/core/plugin/base.py", "ggshield/core/plugin/registry.py"], "used_names": ["PluginMetadata"], "enclosing_function": "test_metadata_fields", "extracted_code": "# Source: ggshield/core/plugin/base.py\nclass PluginMetadata:\n \"\"\"Metadata about a plugin.\"\"\"\n\n name: str\n version: str\n display_name: str\n description: str\n min_ggshield_version: str", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 200, "extracted_code_full": "# Source: ggshield/core/plugin/base.py\nclass PluginMetadata:\n \"\"\"Metadata about a plugin.\"\"\"\n\n name: str\n version: str\n display_name: str\n description: str\n min_ggshield_version: str", "n_chars_compressed": 200, "compression_ratio": 1.0}, "tests/unit/cmd/auth/test_logout.py::63": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/constants.py", "ggshield/core/errors.py"], "used_names": ["Config", "DEFAULT_INSTANCE_URL", "ExitCode", "Mock", "add_instance_config", "pytest"], "enclosing_function": "test_valid_logout", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/constants.py\nDEFAULT_INSTANCE_URL = \"https://dashboard.gitguardian.com\"\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 8798, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/constants.py\nDEFAULT_INSTANCE_URL = \"https://dashboard.gitguardian.com\"\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 8798, "compression_ratio": 1.0}, "tests/unit/verticals/secret/test_secret_scanner.py::124": {"resolved_imports": ["ggshield/__init__.py", "ggshield/core/cache.py", "ggshield/core/config/user_config.py", "ggshield/core/errors.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/scan/scannable.py", "ggshield/core/scanner_ui/scanner_ui.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Commit", "ExitCode", "GG_TEST_TOKEN", "Mock", "ScanContext", "ScanMode", "SecretConfig", "SecretScanner", "UNCHECKED_SECRET_PATCH", "_MULTIPLE_SECRETS_PATCH", "_NO_SECRET_PATCH", "_ONE_LINE_AND_MULTILINE_PATCH", "my_vcr", "pytest"], "enclosing_function": "test_scan_patch", "extracted_code": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_imports_parsed": 18, "n_files_resolved": 12, "n_chars_extracted": 15959, "extracted_code_full": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_chars_compressed": 15959, "compression_ratio": 1.0}, "tests/unit/core/test_cache.py::37": {"resolved_imports": ["ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/types.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["Cache", "json"], "enclosing_function": "test_load_invalid_cache", "extracted_code": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )", "n_imports_parsed": 11, "n_files_resolved": 5, "n_chars_extracted": 2587, "extracted_code_full": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )", "n_chars_compressed": 2587, "compression_ratio": 1.0}, "tests/unit/cmd/test_install.py::151": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/install.py", "ggshield/core/errors.py"], "used_names": ["CliRunner", "Mock", "Path", "assert_invoke_ok", "cli", "patch", "pytest"], "enclosing_function": "test_install_exists_append", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_enterprise_config.py::18": {"resolved_imports": ["ggshield/core/config/enterprise_config.py"], "used_names": ["PluginConfig"], "enclosing_function": "test_default_values", "extracted_code": "# Source: ggshield/core/config/enterprise_config.py\nclass PluginConfig:\n \"\"\"Configuration for a single plugin.\"\"\"\n\n enabled: bool = True\n version: Optional[str] = None\n auto_update: bool = True", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 205, "extracted_code_full": "# Source: ggshield/core/config/enterprise_config.py\nclass PluginConfig:\n \"\"\"Configuration for a single plugin.\"\"\"\n\n enabled: bool = True\n version: Optional[str] = None\n auto_update: bool = True", "n_chars_compressed": 205, "compression_ratio": 1.0}, "tests/unit/cmd/test_ignore.py::56": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/ignore.py", "ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Config", "IgnoredMatch", "assert_invoke_ok", "cli", "patch"], "enclosing_function": "test_ignore_sha", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/types.py\nclass IgnoredMatch(FilteredConfig):\n match: str\n name: Optional[str] = None\n\n def __post_init__(self) -> None:\n if self.name is None:\n self.name = \"\"", "n_imports_parsed": 14, "n_files_resolved": 11, "n_chars_extracted": 9632, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/types.py\nclass IgnoredMatch(FilteredConfig):\n match: str\n name: Optional[str] = None\n\n def __post_init__(self) -> None:\n if self.name is None:\n self.name = \"\"", "n_chars_compressed": 9632, "compression_ratio": 1.0}, "tests/unit/cmd/plugin/test_update.py::1111": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py", "ggshield/core/plugin/client.py", "ggshield/core/plugin/loader.py", "ggshield/cmd/plugin/update.py"], "used_names": ["_check_github_release_update", "mock"], "enclosing_function": "test_check_github_release_update_success", "extracted_code": "# Source: ggshield/cmd/plugin/update.py\ndef _check_github_release_update(github_repo: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Check for the latest release of a GitHub repository.\n\n Args:\n github_repo: Repository in \"owner/repo\" format.\n\n Returns:\n Release data dict or None if check fails.\n \"\"\"\n # Get GitHub token if available\n github_token = os.environ.get(\"GITHUB_TOKEN\")\n\n headers: Dict[str, str] = {\n \"Accept\": \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n }\n if github_token:\n headers[\"Authorization\"] = f\"Bearer {github_token}\"\n\n try:\n response = requests.get(\n f\"https://api.github.com/repos/{github_repo}/releases/latest\",\n headers=headers,\n timeout=10,\n )\n if response.status_code == 200:\n return response.json()\n except requests.RequestException:\n pass\n\n return None", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 948, "extracted_code_full": "# Source: ggshield/cmd/plugin/update.py\ndef _check_github_release_update(github_repo: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Check for the latest release of a GitHub repository.\n\n Args:\n github_repo: Repository in \"owner/repo\" format.\n\n Returns:\n Release data dict or None if check fails.\n \"\"\"\n # Get GitHub token if available\n github_token = os.environ.get(\"GITHUB_TOKEN\")\n\n headers: Dict[str, str] = {\n \"Accept\": \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n }\n if github_token:\n headers[\"Authorization\"] = f\"Bearer {github_token}\"\n\n try:\n response = requests.get(\n f\"https://api.github.com/repos/{github_repo}/releases/latest\",\n headers=headers,\n timeout=10,\n )\n if response.status_code == 200:\n return response.json()\n except requests.RequestException:\n pass\n\n return None", "n_chars_compressed": 948, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_fingerprint.py::126": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/hmsl/decrypt.py", "ggshield/verticals/hmsl/client.py", "ggshield/verticals/hmsl/crypto.py"], "used_names": ["CliRunner", "PREFIX_LENGTH", "assert_invoke_ok", "cli", "hash_string"], "enclosing_function": "test_hmsl_fingerprint_default_behavior", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/hmsl/client.py\nPREFIX_LENGTH = 5\n\n\n# Source: ggshield/verticals/hmsl/crypto.py\ndef hash_string(text: str) -> str:\n return (\n Scrypt(salt=_PEPPER, n=2048, r=8, p=1, length=32)\n .derive(text.encode(\"utf-8\"))\n .hex()\n )", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 1655, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/hmsl/client.py\nPREFIX_LENGTH = 5\n\n\n# Source: ggshield/verticals/hmsl/crypto.py\ndef hash_string(text: str) -> str:\n return (\n Scrypt(salt=_PEPPER, n=2048, r=8, p=1, length=32)\n .derive(text.encode(\"utf-8\"))\n .hex()\n )", "n_chars_compressed": 1655, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_platform.py::22": {"resolved_imports": ["ggshield/core/plugin/platform.py"], "used_names": ["PlatformInfo"], "enclosing_function": "test_platform_info_creation", "extracted_code": "# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 159, "extracted_code_full": "# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str", "n_chars_compressed": 159, "compression_ratio": 1.0}, "tests/unit/cmd/honeytoken/test_honeytoken.py::154": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["Any", "Dict", "List", "Union"], "enclosing_function": "payload_checker", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/request_mock.py::112": {"resolved_imports": [], "used_names": [], "enclosing_function": "assert_all_requests_happened", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/core/plugin/test_registry.py::39": {"resolved_imports": ["ggshield/core/plugin/base.py", "ggshield/core/plugin/registry.py"], "used_names": ["PluginRegistry"], "enclosing_function": "test_empty_registry", "extracted_code": "# Source: ggshield/core/plugin/registry.py\nclass PluginRegistry:\n \"\"\"Central registry for all loaded plugins and their capabilities.\"\"\"\n\n _plugins: Dict[str, GGShieldPlugin] = field(default_factory=dict)\n _commands: List[click.Command] = field(default_factory=list)\n\n def register_plugin(self, plugin: GGShieldPlugin) -> None:\n \"\"\"Register a loaded plugin.\"\"\"\n self._plugins[plugin.metadata.name] = plugin\n\n def register_command(self, command: click.Command) -> None:\n \"\"\"Register a CLI command provided by a plugin.\"\"\"\n self._commands.append(command)\n\n def get_plugin(self, name: str) -> Optional[GGShieldPlugin]:\n \"\"\"Get a loaded plugin by name.\"\"\"\n return self._plugins.get(name)\n\n def get_all_plugins(self) -> Dict[str, GGShieldPlugin]:\n \"\"\"Get all loaded plugins.\"\"\"\n return self._plugins.copy()\n\n def get_commands(self) -> List[click.Command]:\n \"\"\"Get all plugin-provided commands.\"\"\"\n return self._commands.copy()", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1014, "extracted_code_full": "# Source: ggshield/core/plugin/registry.py\nclass PluginRegistry:\n \"\"\"Central registry for all loaded plugins and their capabilities.\"\"\"\n\n _plugins: Dict[str, GGShieldPlugin] = field(default_factory=dict)\n _commands: List[click.Command] = field(default_factory=list)\n\n def register_plugin(self, plugin: GGShieldPlugin) -> None:\n \"\"\"Register a loaded plugin.\"\"\"\n self._plugins[plugin.metadata.name] = plugin\n\n def register_command(self, command: click.Command) -> None:\n \"\"\"Register a CLI command provided by a plugin.\"\"\"\n self._commands.append(command)\n\n def get_plugin(self, name: str) -> Optional[GGShieldPlugin]:\n \"\"\"Get a loaded plugin by name.\"\"\"\n return self._plugins.get(name)\n\n def get_all_plugins(self) -> Dict[str, GGShieldPlugin]:\n \"\"\"Get all loaded plugins.\"\"\"\n return self._plugins.copy()\n\n def get_commands(self) -> List[click.Command]:\n \"\"\"Get all plugin-provided commands.\"\"\"\n return self._commands.copy()", "n_chars_compressed": 1014, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_path.py::152": {"resolved_imports": [], "used_names": ["Path", "run_ggshield_scan", "shutil", "sys"], "enclosing_function": "test_scan_path_works_if_git_not_found", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/cmd/test_crash_log.py::16": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["main", "pytest"], "enclosing_function": "test_syntax_error_no_crash_log", "extracted_code": "# Source: ggshield/__main__.py\ndef main(args: Optional[List[str]] = None) -> Any:\n \"\"\"\n Wrapper around cli.main() to handle the GITGUARDIAN_CRASH_LOG variable.\n\n `args` is only used by unit-tests.\n \"\"\"\n _register_plugin_commands()\n\n # Required by pyinstaller when forking.\n # See https://pyinstaller.org/en/latest/common-issues-and-pitfalls.html#multi-processing\n multiprocessing.freeze_support()\n\n log_utils.disable_logs()\n\n if not os.getenv(\"GG_PLAINTEXT_OUTPUT\", False) and sys.stderr.isatty():\n ui.set_ui(RichGGShieldUI())\n\n force_utf8_output()\n setup_truststore()\n\n show_crash_log = getenv_bool(\"GITGUARDIAN_CRASH_LOG\")\n return cli.main(args, prog_name=\"ggshield\", standalone_mode=not show_crash_log)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 754, "extracted_code_full": "# Source: ggshield/__main__.py\ndef main(args: Optional[List[str]] = None) -> Any:\n \"\"\"\n Wrapper around cli.main() to handle the GITGUARDIAN_CRASH_LOG variable.\n\n `args` is only used by unit-tests.\n \"\"\"\n _register_plugin_commands()\n\n # Required by pyinstaller when forking.\n # See https://pyinstaller.org/en/latest/common-issues-and-pitfalls.html#multi-processing\n multiprocessing.freeze_support()\n\n log_utils.disable_logs()\n\n if not os.getenv(\"GG_PLAINTEXT_OUTPUT\", False) and sys.stderr.isatty():\n ui.set_ui(RichGGShieldUI())\n\n force_utf8_output()\n setup_truststore()\n\n show_crash_log = getenv_bool(\"GITGUARDIAN_CRASH_LOG\")\n return cli.main(args, prog_name=\"ggshield\", standalone_mode=not show_crash_log)", "n_chars_compressed": 754, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_fingerprint.py::169": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/hmsl/decrypt.py", "ggshield/verticals/hmsl/client.py", "ggshield/verticals/hmsl/crypto.py"], "used_names": ["CliRunner", "assert_invoke_ok", "cli"], "enclosing_function": "test_hmsl_fingerprint_cleartext", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_client.py::302": {"resolved_imports": ["ggshield/core/plugin/client.py", "ggshield/core/plugin/platform.py"], "used_names": ["MagicMock", "PluginAPIClient"], "enclosing_function": "test_get_unavailable_reason_platform_mismatch", "extracted_code": "# Source: ggshield/core/plugin/client.py\nclass PluginAPIClient:\n \"\"\"Client for GitGuardian plugin API.\"\"\"\n\n API_VERSION = \"v1\"\n\n def __init__(self, client: GGClient):\n self.client = client\n self.base_url = client.base_uri.rstrip(\"/\")\n\n def get_available_plugins(self) -> PluginCatalog:\n \"\"\"Fetch available plugins for the authenticated account.\"\"\"\n platform_info = get_platform_info()\n\n try:\n response = self.client.session.get(\n f\"{self.base_url}/{self.API_VERSION}/plugins\",\n params={\n \"platform\": platform_info.os,\n \"arch\": platform_info.arch,\n },\n headers=self._get_headers(),\n )\n response.raise_for_status()\n except requests.RequestException as e:\n raise PluginAPIError(f\"Failed to fetch plugins: {e}\") from e\n\n data = response.json()\n\n account_data = data.get(\"account\", {})\n current_platform = f\"{platform_info.os}-{platform_info.arch}\"\n\n return PluginCatalog(\n plan=account_data.get(\"plan\", data.get(\"plan\", \"unknown\")),\n features=account_data.get(\"features\", data.get(\"features\", {})),\n plugins=[\n PluginInfo(\n name=p.get(\"name\", \"unknown\"),\n display_name=p.get(\"display_name\", p.get(\"name\", \"Unknown\")),\n description=p.get(\"description\", \"\"),\n available=self._is_plugin_available(p, current_platform),\n latest_version=p.get(\"latest_version\"),\n supported_platforms=p.get(\"supported_platforms\", []),\n reason=self._get_unavailable_reason(p, current_platform),\n )\n for p in data.get(\"plugins\", [])\n ],\n )\n\n def get_download_info(\n self,\n plugin_name: str,\n version: Optional[str] = None,\n platform_info: Optional[PlatformInfo] = None,\n ) -> PluginDownloadInfo:\n \"\"\"Get download URL for a plugin wheel.\"\"\"\n resolved_platform_info: PlatformInfo\n if platform_info is None:\n resolved_platform_info = get_platform_info()\n else:\n resolved_platform_info = platform_info\n\n params: Dict[str, str] = {\n \"platform\": resolved_platform_info.os,\n \"arch\": resolved_platform_info.arch,\n \"python_abi\": resolved_platform_info.python_abi,\n }\n if version:\n params[\"version\"] = version\n\n try:\n response = self.client.session.get(\n f\"{self.base_url}/{self.API_VERSION}/plugins/{plugin_name}/download\",\n params=params,\n headers=self._get_headers(),\n )\n\n if response.status_code == 403:\n raise PluginNotAvailableError(plugin_name)\n elif response.status_code == 404:\n raise PluginNotAvailableError(\n plugin_name, \"Plugin or version not found\"\n )\n\n response.raise_for_status()\n\n except PluginNotAvailableError:\n raise\n except requests.RequestException as e:\n raise PluginAPIError(f\"Failed to get download info: {e}\") from e\n\n data = response.json()\n\n return PluginDownloadInfo(\n download_url=data[\"download_url\"],\n filename=data[\"filename\"],\n sha256=data[\"sha256\"],\n version=data[\"version\"],\n expires_at=data[\"expires_at\"],\n )\n\n def _is_plugin_available(\n self, plugin_data: Dict[str, Any], current_platform: str\n ) -> bool:\n if not plugin_data.get(\"available\", True):\n return False\n supported = plugin_data.get(\"supported_platforms\", [])\n if not supported:\n return True\n return current_platform in supported or \"any-any\" in supported\n\n def _get_unavailable_reason(\n self, plugin_data: Dict[str, Any], current_platform: str\n ) -> Optional[str]:\n if plugin_data.get(\"reason\"):\n return plugin_data[\"reason\"]\n supported = plugin_data.get(\"supported_platforms\", [])\n if (\n supported\n and current_platform not in supported\n and \"any-any\" not in supported\n ):\n return f\"Not available for {current_platform}. Supported: {', '.join(supported)}\"\n return None\n\n def _get_headers(self) -> Dict[str, str]:\n return {\n \"Authorization\": f\"Token {self.client.api_key}\",\n \"Content-Type\": \"application/json\",\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4663, "extracted_code_full": "# Source: ggshield/core/plugin/client.py\nclass PluginAPIClient:\n \"\"\"Client for GitGuardian plugin API.\"\"\"\n\n API_VERSION = \"v1\"\n\n def __init__(self, client: GGClient):\n self.client = client\n self.base_url = client.base_uri.rstrip(\"/\")\n\n def get_available_plugins(self) -> PluginCatalog:\n \"\"\"Fetch available plugins for the authenticated account.\"\"\"\n platform_info = get_platform_info()\n\n try:\n response = self.client.session.get(\n f\"{self.base_url}/{self.API_VERSION}/plugins\",\n params={\n \"platform\": platform_info.os,\n \"arch\": platform_info.arch,\n },\n headers=self._get_headers(),\n )\n response.raise_for_status()\n except requests.RequestException as e:\n raise PluginAPIError(f\"Failed to fetch plugins: {e}\") from e\n\n data = response.json()\n\n account_data = data.get(\"account\", {})\n current_platform = f\"{platform_info.os}-{platform_info.arch}\"\n\n return PluginCatalog(\n plan=account_data.get(\"plan\", data.get(\"plan\", \"unknown\")),\n features=account_data.get(\"features\", data.get(\"features\", {})),\n plugins=[\n PluginInfo(\n name=p.get(\"name\", \"unknown\"),\n display_name=p.get(\"display_name\", p.get(\"name\", \"Unknown\")),\n description=p.get(\"description\", \"\"),\n available=self._is_plugin_available(p, current_platform),\n latest_version=p.get(\"latest_version\"),\n supported_platforms=p.get(\"supported_platforms\", []),\n reason=self._get_unavailable_reason(p, current_platform),\n )\n for p in data.get(\"plugins\", [])\n ],\n )\n\n def get_download_info(\n self,\n plugin_name: str,\n version: Optional[str] = None,\n platform_info: Optional[PlatformInfo] = None,\n ) -> PluginDownloadInfo:\n \"\"\"Get download URL for a plugin wheel.\"\"\"\n resolved_platform_info: PlatformInfo\n if platform_info is None:\n resolved_platform_info = get_platform_info()\n else:\n resolved_platform_info = platform_info\n\n params: Dict[str, str] = {\n \"platform\": resolved_platform_info.os,\n \"arch\": resolved_platform_info.arch,\n \"python_abi\": resolved_platform_info.python_abi,\n }\n if version:\n params[\"version\"] = version\n\n try:\n response = self.client.session.get(\n f\"{self.base_url}/{self.API_VERSION}/plugins/{plugin_name}/download\",\n params=params,\n headers=self._get_headers(),\n )\n\n if response.status_code == 403:\n raise PluginNotAvailableError(plugin_name)\n elif response.status_code == 404:\n raise PluginNotAvailableError(\n plugin_name, \"Plugin or version not found\"\n )\n\n response.raise_for_status()\n\n except PluginNotAvailableError:\n raise\n except requests.RequestException as e:\n raise PluginAPIError(f\"Failed to get download info: {e}\") from e\n\n data = response.json()\n\n return PluginDownloadInfo(\n download_url=data[\"download_url\"],\n filename=data[\"filename\"],\n sha256=data[\"sha256\"],\n version=data[\"version\"],\n expires_at=data[\"expires_at\"],\n )\n\n def _is_plugin_available(\n self, plugin_data: Dict[str, Any], current_platform: str\n ) -> bool:\n if not plugin_data.get(\"available\", True):\n return False\n supported = plugin_data.get(\"supported_platforms\", [])\n if not supported:\n return True\n return current_platform in supported or \"any-any\" in supported\n\n def _get_unavailable_reason(\n self, plugin_data: Dict[str, Any], current_platform: str\n ) -> Optional[str]:\n if plugin_data.get(\"reason\"):\n return plugin_data[\"reason\"]\n supported = plugin_data.get(\"supported_platforms\", [])\n if (\n supported\n and current_platform not in supported\n and \"any-any\" not in supported\n ):\n return f\"Not available for {current_platform}. Supported: {', '.join(supported)}\"\n return None\n\n def _get_headers(self) -> Dict[str, str]:\n return {\n \"Authorization\": f\"Token {self.client.api_key}\",\n \"Content-Type\": \"application/json\",\n }", "n_chars_compressed": 4663, "compression_ratio": 1.0}, "tests/unit/cmd/honeytoken/test_honeytoken.py::42": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["CliRunner", "assert_invoke_ok", "cli", "my_vcr"], "enclosing_function": "test_honeytoken_create_ok_no_name", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/plugin/test_list.py::31": {"resolved_imports": ["ggshield/cmd/plugin/plugin_list.py", "ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["ExitCode", "cli", "mock"], "enclosing_function": "test_list_no_plugins", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_precommit.py::179": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/precommit.py", "ggshield/utils/os.py"], "used_names": ["Repository", "assert_invoke_ok", "cd", "cli", "my_vcr", "pytest", "subprocess"], "enclosing_function": "test_precommit_with_unmerged_files", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1694, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_chars_compressed": 1694, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_wheel_utils.py::194": {"resolved_imports": ["ggshield/core/plugin/wheel_utils.py"], "used_names": ["WheelMetadata"], "enclosing_function": "test_dataclass_fields", "extracted_code": "# Source: ggshield/core/plugin/wheel_utils.py\nclass WheelMetadata:\n \"\"\"Metadata extracted from a wheel file.\"\"\"\n\n name: str\n version: str\n summary: Optional[str] = None\n author: Optional[str] = None\n license: Optional[str] = None", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 247, "extracted_code_full": "# Source: ggshield/core/plugin/wheel_utils.py\nclass WheelMetadata:\n \"\"\"Metadata extracted from a wheel file.\"\"\"\n\n name: str\n version: str\n summary: Optional[str] = None\n author: Optional[str] = None\n license: Optional[str] = None", "n_chars_compressed": 247, "compression_ratio": 1.0}, "tests/unit/verticals/secret/test_secret_scan_collection.py::43": {"resolved_imports": ["ggshield/core/config/user_config.py", "ggshield/core/filter.py", "ggshield/core/scan/scannable.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scan_collection.py"], "used_names": ["Results"], "enclosing_function": "test_results_from_exception", "extracted_code": "# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)", "n_imports_parsed": 11, "n_files_resolved": 5, "n_chars_extracted": 1037, "extracted_code_full": "# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)", "n_chars_compressed": 1037, "compression_ratio": 1.0}, "tests/unit/cmd/test_ignore.py::101": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/ignore.py", "ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Cache", "Commit", "Config", "Mock", "ScanContext", "ScanMode", "SecretScanner", "_MULTIPLE_SECRETS_PATCH", "ignore_last_found", "my_vcr"], "enclosing_function": "test_cache_catches_last_found_secrets", "extracted_code": "# Source: ggshield/cmd/secret/ignore.py\ndef ignore_last_found(config: Config, cache: Cache) -> int:\n \"\"\"\n Add last found secrets from .cache_ggshield into ignored_matches\n in the local .gitguardian.yaml config file so that they are ignored on next run\n Secrets are added as `hash`\n \"\"\"\n for secret in cache.last_found_secrets:\n config.add_ignored_match(secret)\n return len(cache.last_found_secrets)\n\n\n# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_imports_parsed": 14, "n_files_resolved": 11, "n_chars_extracted": 24546, "extracted_code_full": "# Source: ggshield/cmd/secret/ignore.py\ndef ignore_last_found(config: Config, cache: Cache) -> int:\n \"\"\"\n Add last found secrets from .cache_ggshield into ignored_matches\n in the local .gitguardian.yaml config file so that they are ignored on next run\n Secrets are added as `hash`\n \"\"\"\n for secret in cache.last_found_secrets:\n config.add_ignored_match(secret)\n return len(cache.last_found_secrets)\n\n\n# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_chars_compressed": 24546, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_precommit.py::87": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/precommit.py", "ggshield/utils/os.py"], "used_names": ["Path", "Repository", "check_is_merge_with_conflict", "check_is_merge_without_conflict", "pytest", "subprocess"], "enclosing_function": "test_is_merge_with_conflict", "extracted_code": "# Source: ggshield/cmd/secret/scan/precommit.py\ndef check_is_merge_without_conflict() -> bool:\n \"\"\"Check if the reflog action is a merge without conflict\"\"\"\n return os.getenv(\"GIT_REFLOG_ACTION\", \"\").split(\" \")[0] == \"merge\"\n\ndef check_is_merge_with_conflict(cwd: Path) -> bool:\n \"\"\"Check if MERGE_HEAD exists (meaning we are in a merge with conflict)\"\"\"\n try:\n git([\"rev-parse\", \"--verify\", \"-q\", \"MERGE_HEAD\"], cwd=cwd)\n # MERGE_HEAD exists\n return True\n except subprocess.CalledProcessError:\n # MERGE_HEAD does not exist\n return False", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 588, "extracted_code_full": "# Source: ggshield/cmd/secret/scan/precommit.py\ndef check_is_merge_without_conflict() -> bool:\n \"\"\"Check if the reflog action is a merge without conflict\"\"\"\n return os.getenv(\"GIT_REFLOG_ACTION\", \"\").split(\" \")[0] == \"merge\"\n\ndef check_is_merge_with_conflict(cwd: Path) -> bool:\n \"\"\"Check if MERGE_HEAD exists (meaning we are in a merge with conflict)\"\"\"\n try:\n git([\"rev-parse\", \"--verify\", \"-q\", \"MERGE_HEAD\"], cwd=cwd)\n # MERGE_HEAD exists\n return True\n except subprocess.CalledProcessError:\n # MERGE_HEAD does not exist\n return False", "n_chars_compressed": 588, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_docker.py::104": {"resolved_imports": ["ggshield/core/dirs.py"], "used_names": ["Path", "run_ggshield_scan", "skipwindows"], "enclosing_function": "test_scan_docker_uses_cache", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/unit/cmd/test_ignore.py::152": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/ignore.py", "ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Cache", "Commit", "Config", "Mock", "ScanContext", "ScanMode", "SecretScanner", "_MULTIPLE_SECRETS_PATCH", "my_vcr"], "enclosing_function": "test_cache_catches_nothing", "extracted_code": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_imports_parsed": 14, "n_files_resolved": 11, "n_chars_extracted": 24117, "extracted_code_full": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_chars_compressed": 24117, "compression_ratio": 1.0}, "tests/unit/cmd/test_log_options.py::24": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["Path", "assert_invoke_ok", "cli", "pytest"], "enclosing_function": "test_log_to_stderr_option", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/scan/test_file.py::128": {"resolved_imports": ["ggshield/core/scan/file.py", "ggshield/core/scan/scannable.py"], "used_names": ["File"], "enclosing_function": "test_file_is_longer_than_if_file_has_been_read", "extracted_code": "# Source: ggshield/core/scan/file.py\nclass File(Scannable):\n \"\"\"Implementation of Scannable for files from the disk.\"\"\"\n\n def __init__(self, path: Union[str, Path]):\n super().__init__()\n self._path = Path(path)\n\n @property\n def url(self) -> str:\n return url_for_path(self._path)\n\n @property\n def filename(self) -> str:\n return str(self._path)\n\n @property\n def path(self) -> Path:\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n if self._utf8_encoded_size is not None:\n # We already have the encoded size, easy\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n with self.path.open(\"rb\") as fp:\n (\n result,\n self._content,\n self._utf8_encoded_size,\n ) = Scannable._is_file_longer_than(fp, max_utf8_encoded_size)\n return result\n\n def _read_content(self) -> None:\n if self._content is None:\n with self.path.open(\"rb\") as f:\n self._content, self._utf8_encoded_size = Scannable._decode_bytes(\n f.read()\n )", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 1185, "extracted_code_full": "# Source: ggshield/core/scan/file.py\nclass File(Scannable):\n \"\"\"Implementation of Scannable for files from the disk.\"\"\"\n\n def __init__(self, path: Union[str, Path]):\n super().__init__()\n self._path = Path(path)\n\n @property\n def url(self) -> str:\n return url_for_path(self._path)\n\n @property\n def filename(self) -> str:\n return str(self._path)\n\n @property\n def path(self) -> Path:\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n if self._utf8_encoded_size is not None:\n # We already have the encoded size, easy\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n with self.path.open(\"rb\") as fp:\n (\n result,\n self._content,\n self._utf8_encoded_size,\n ) = Scannable._is_file_longer_than(fp, max_utf8_encoded_size)\n return result\n\n def _read_content(self) -> None:\n if self._content is None:\n with self.path.open(\"rb\") as f:\n self._content, self._utf8_encoded_size = Scannable._decode_bytes(\n f.read()\n )", "n_chars_compressed": 1185, "compression_ratio": 1.0}, "tests/unit/verticals/secret/output/test_text_output.py::183": {"resolved_imports": ["ggshield/core/config/user_config.py", "ggshield/core/scan/scannable.py", "ggshield/utils/git_shell.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/output/secret_text_output_handler.py"], "used_names": [], "enclosing_function": "assert_policies_displayed", "extracted_code": "", "n_imports_parsed": 13, "n_files_resolved": 5, "n_chars_extracted": 0}, "tests/unit/cmd/scan/test_prepush.py::45": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/secret_scan_common_options.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["CliRunner", "Mock", "assert_invoke_ok", "cli", "patch"], "enclosing_function": "test_prepush_no_commits", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 13, "n_files_resolved": 8, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_fingerprint.py::129": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/hmsl/decrypt.py", "ggshield/verticals/hmsl/client.py", "ggshield/verticals/hmsl/crypto.py"], "used_names": ["CliRunner", "PREFIX_LENGTH", "assert_invoke_ok", "cli", "hash_string"], "enclosing_function": "test_hmsl_fingerprint_default_behavior", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/hmsl/client.py\nPREFIX_LENGTH = 5\n\n\n# Source: ggshield/verticals/hmsl/crypto.py\ndef hash_string(text: str) -> str:\n return (\n Scrypt(salt=_PEPPER, n=2048, r=8, p=1, length=32)\n .derive(text.encode(\"utf-8\"))\n .hex()\n )", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 1655, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/hmsl/client.py\nPREFIX_LENGTH = 5\n\n\n# Source: ggshield/verticals/hmsl/crypto.py\ndef hash_string(text: str) -> str:\n return (\n Scrypt(salt=_PEPPER, n=2048, r=8, p=1, length=32)\n .derive(text.encode(\"utf-8\"))\n .hex()\n )", "n_chars_compressed": 1655, "compression_ratio": 1.0}, "tests/functional/hmsl/test_hmsl_fingerprint.py::29": {"resolved_imports": [], "used_names": ["Path", "run_ggshield"], "enclosing_function": "test_fingerprint_filters_short_secrets", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/cmd/hmsl/test_query.py::21": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli", "my_vcr"], "enclosing_function": "test_hmsl_query_prefix", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_loader.py::50": {"resolved_imports": ["ggshield/core/config/enterprise_config.py", "ggshield/core/plugin/base.py", "ggshield/core/plugin/loader.py", "ggshield/core/plugin/registry.py"], "used_names": ["EnterpriseConfig", "Path", "PluginLoader", "patch"], "enclosing_function": "test_discover_plugins_empty", "extracted_code": "# Source: ggshield/core/config/enterprise_config.py\nclass EnterpriseConfig:\n \"\"\"Enterprise configuration stored in ~/.config/ggshield/enterprise_config.yaml\"\"\"\n\n plugins: Dict[str, PluginConfig] = field(default_factory=dict)\n\n @classmethod\n def load(cls) -> \"EnterpriseConfig\":\n \"\"\"Load enterprise config from file.\"\"\"\n config_path = get_enterprise_config_filepath()\n data = load_yaml_dict(config_path)\n\n if data is None:\n return cls()\n\n # Convert plugin configs from dict\n plugins: Dict[str, PluginConfig] = {}\n for name, plugin_data in data.get(\"plugins\", {}).items():\n if isinstance(plugin_data, dict):\n plugins[name] = PluginConfig(\n enabled=plugin_data.get(\"enabled\", True),\n version=plugin_data.get(\"version\"),\n auto_update=plugin_data.get(\"auto_update\", True),\n )\n elif isinstance(plugin_data, bool):\n # Simple format: just enabled/disabled\n plugins[name] = PluginConfig(enabled=plugin_data)\n else:\n plugins[name] = PluginConfig(enabled=True)\n\n return cls(plugins=plugins)\n\n def save(self) -> None:\n \"\"\"Save enterprise config to file.\"\"\"\n config_path = get_enterprise_config_filepath()\n\n # Convert to dict for saving\n data: Dict[str, Any] = {\n \"plugins\": {\n name: {\n \"enabled\": cfg.enabled,\n \"version\": cfg.version,\n \"auto_update\": cfg.auto_update,\n }\n for name, cfg in self.plugins.items()\n }\n }\n\n # Remove None values for cleaner YAML\n for plugin_data in data[\"plugins\"].values():\n if plugin_data[\"version\"] is None:\n del plugin_data[\"version\"]\n\n save_yaml_dict(data, config_path)\n\n def enable_plugin(self, plugin_name: str, version: Optional[str] = None) -> None:\n \"\"\"Enable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n self.plugins[plugin_name] = PluginConfig()\n\n self.plugins[plugin_name].enabled = True\n if version:\n self.plugins[plugin_name].version = version\n\n def disable_plugin(self, plugin_name: str) -> None:\n \"\"\"Disable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n raise ValueError(f\"Plugin '{plugin_name}' is not configured\")\n\n self.plugins[plugin_name].enabled = False\n\n def is_plugin_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n # Default: disabled if not explicitly configured\n return plugin_config.enabled if plugin_config else False\n\n def get_plugin_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the configured version of a plugin.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n return plugin_config.version if plugin_config else None\n\n def remove_plugin(self, plugin_name: str) -> bool:\n \"\"\"Remove a plugin from configuration.\"\"\"\n if plugin_name in self.plugins:\n del self.plugins[plugin_name]\n return True\n return False\n\n\n# Source: ggshield/core/plugin/loader.py\nclass PluginLoader:\n \"\"\"Discovers and loads ggshield plugins from entry points and local wheels.\"\"\"\n\n def __init__(self, enterprise_config: EnterpriseConfig) -> None:\n self.enterprise_config = enterprise_config\n self.plugins_dir = get_plugins_dir()\n\n def discover_plugins(self) -> List[DiscoveredPlugin]:\n \"\"\"Discover all available plugins from entry points and local wheels.\"\"\"\n discovered: Dict[str, DiscoveredPlugin] = {}\n\n # 1. Discover from local wheels first and track their entry point names\n local_entry_point_names: set[str] = set()\n for wheel_info in self._scan_local_wheels():\n plugin_name: str = wheel_info[\"name\"]\n wheel_path: Path = wheel_info[\"path\"]\n wheel_version: str = wheel_info[\"version\"]\n entry_point_name: Optional[str] = wheel_info[\"entry_point_name\"]\n\n # Use entry point name as key if available, otherwise package name\n key = entry_point_name if entry_point_name else plugin_name\n if entry_point_name:\n local_entry_point_names.add(entry_point_name)\n\n discovered[key] = DiscoveredPlugin(\n name=key,\n entry_point=None,\n wheel_path=wheel_path,\n is_installed=True,\n is_enabled=self._is_enabled(key),\n version=wheel_version,\n )\n\n # 2. Discover from entry points (skip if already found in local wheels)\n for ep in self._get_entry_points():\n plugin_name = ep.name\n # Skip if this entry point is provided by a local wheel\n if plugin_name in local_entry_point_names:\n continue\n discovered[plugin_name] = DiscoveredPlugin(\n name=plugin_name,\n entry_point=ep,\n wheel_path=None,\n is_installed=True,\n is_enabled=self._is_enabled(plugin_name),\n version=self._get_entry_point_version(ep),\n )\n\n return list(discovered.values())\n\n def load_enabled_plugins(self) -> PluginRegistry:\n \"\"\"Load all enabled plugins and return a populated registry.\"\"\"\n registry = PluginRegistry()\n\n for discovered in self.discover_plugins():\n if not discovered.is_enabled:\n logger.debug(\"Skipping disabled plugin: %s\", discovered.name)\n continue\n\n try:\n plugin = self._load_plugin(discovered)\n if plugin is None:\n continue\n\n if not self._check_version_compatibility(plugin.metadata):\n logger.warning(\n \"Plugin %s requires ggshield >= %s, skipping\",\n plugin.metadata.name,\n plugin.metadata.min_ggshield_version,\n )\n continue\n\n plugin.on_load()\n plugin.register(registry)\n registry.register_plugin(plugin)\n\n logger.info(\n \"Loaded plugin: %s v%s\",\n plugin.metadata.name,\n plugin.metadata.version,\n )\n\n except Exception as e:\n logger.warning(\"Failed to load plugin %s: %s\", discovered.name, e)\n\n return registry\n\n def _load_plugin(self, discovered: DiscoveredPlugin) -> Optional[GGShieldPlugin]:\n \"\"\"Load a single plugin from discovery info.\"\"\"\n if discovered.wheel_path:\n return self._load_from_wheel(discovered.wheel_path)\n elif discovered.entry_point:\n return self._load_from_entry_point(discovered.entry_point)\n return None\n\n def _load_from_entry_point(\n self, ep: importlib.metadata.EntryPoint\n ) -> GGShieldPlugin:\n \"\"\"Load a plugin from an entry point.\"\"\"\n plugin_class = ep.load()\n return plugin_class()\n\n def _load_from_wheel(self, wheel_path: Path) -> Optional[GGShieldPlugin]:\n \"\"\"Load a plugin from a local wheel file.\n\n Wheels are extracted to a directory before loading because Python\n cannot import native extensions (.so/.pyd) directly from zip files.\n \"\"\"\n # Extract wheel to a directory alongside the wheel file\n extract_dir = wheel_path.parent / f\".{wheel_path.stem}_extracted\"\n\n try:\n # Extract if not already extracted or wheel is newer\n if not extract_dir.exists() or (\n wheel_path.stat().st_mtime > extract_dir.stat().st_mtime\n ):\n import shutil\n\n if extract_dir.exists():\n shutil.rmtree(extract_dir)\n\n from ggshield.utils.archive import safe_unpack\n\n safe_unpack(wheel_path, extract_dir)\n\n # Add extracted directory to sys.path\n extract_str = str(extract_dir)\n if extract_str not in sys.path:\n sys.path.append(extract_str)\n\n entry_point_str = self._read_wheel_entry_point(wheel_path)\n if not entry_point_str:\n logger.warning(\"No entry point found in wheel: %s\", wheel_path)\n return None\n\n module_name, class_name = entry_point_str.split(\":\")\n module = importlib.import_module(module_name)\n plugin_class = getattr(module, class_name)\n return plugin_class()\n except Exception as e:\n logger.warning(\"Failed to load wheel %s: %s\", wheel_path, e)\n return None\n\n def _read_wheel_entry_point(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the ggshield.plugins entry point value from a wheel's metadata.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[1] if result else None\n\n def _read_wheel_entry_point_name(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the entry point name from a wheel's entry_points.txt.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[0] if result else None\n\n def _get_entry_points(self) -> Iterator[importlib.metadata.EntryPoint]:\n \"\"\"Get all entry points in the ggshield.plugins group.\"\"\"\n try:\n eps = importlib.metadata.entry_points(group=PLUGIN_ENTRY_POINT_GROUP)\n yield from eps\n except TypeError:\n all_eps = importlib.metadata.entry_points()\n yield from all_eps.get(PLUGIN_ENTRY_POINT_GROUP, [])\n\n def _scan_local_wheels(self) -> Iterator[WheelInfo]:\n \"\"\"Scan the plugins directory for installed wheels.\"\"\"\n import json\n\n if not self.plugins_dir.exists():\n return\n\n for plugin_dir in self.plugins_dir.iterdir():\n if not plugin_dir.is_dir():\n continue\n\n manifest_path = plugin_dir / \"manifest.json\"\n if manifest_path.exists():\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\", \"\")\n wheel_path = plugin_dir / wheel_filename\n\n if wheel_path.exists():\n # Extract entry point name from wheel for deduplication\n entry_point_name = self._read_wheel_entry_point_name(wheel_path)\n yield WheelInfo(\n name=manifest[\"plugin_name\"],\n version=manifest[\"version\"],\n path=wheel_path,\n entry_point_name=entry_point_name,\n )\n except (json.JSONDecodeError, KeyError) as e:\n logger.warning(\"Invalid manifest in %s: %s\", plugin_dir, e)\n\n def _is_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled in config.\"\"\"\n plugin_config = self.enterprise_config.plugins.get(plugin_name)\n if plugin_config is None:\n return False\n return plugin_config.enabled\n\n def _get_entry_point_version(\n self, ep: importlib.metadata.EntryPoint\n ) -> Optional[str]:\n \"\"\"Get the version of a package providing an entry point.\"\"\"\n try:\n module_path = ep.value.split(\":\")[0]\n package_name = module_path.split(\".\")[0]\n dist = importlib.metadata.distribution(package_name)\n return dist.version\n except (importlib.metadata.PackageNotFoundError, IndexError):\n return None\n\n def _check_version_compatibility(self, metadata: PluginMetadata) -> bool:\n \"\"\"Check if plugin is compatible with current ggshield version.\"\"\"\n try:\n current = packaging_version.parse(ggshield_version)\n required = packaging_version.parse(metadata.min_ggshield_version)\n return current >= required\n except Exception as e:\n logger.error(\n \"Failed to parse version for plugin %s (requires %s): %s\",\n metadata.name,\n metadata.min_ggshield_version,\n e,\n )\n return False", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 12506, "extracted_code_full": "# Source: ggshield/core/config/enterprise_config.py\nclass EnterpriseConfig:\n \"\"\"Enterprise configuration stored in ~/.config/ggshield/enterprise_config.yaml\"\"\"\n\n plugins: Dict[str, PluginConfig] = field(default_factory=dict)\n\n @classmethod\n def load(cls) -> \"EnterpriseConfig\":\n \"\"\"Load enterprise config from file.\"\"\"\n config_path = get_enterprise_config_filepath()\n data = load_yaml_dict(config_path)\n\n if data is None:\n return cls()\n\n # Convert plugin configs from dict\n plugins: Dict[str, PluginConfig] = {}\n for name, plugin_data in data.get(\"plugins\", {}).items():\n if isinstance(plugin_data, dict):\n plugins[name] = PluginConfig(\n enabled=plugin_data.get(\"enabled\", True),\n version=plugin_data.get(\"version\"),\n auto_update=plugin_data.get(\"auto_update\", True),\n )\n elif isinstance(plugin_data, bool):\n # Simple format: just enabled/disabled\n plugins[name] = PluginConfig(enabled=plugin_data)\n else:\n plugins[name] = PluginConfig(enabled=True)\n\n return cls(plugins=plugins)\n\n def save(self) -> None:\n \"\"\"Save enterprise config to file.\"\"\"\n config_path = get_enterprise_config_filepath()\n\n # Convert to dict for saving\n data: Dict[str, Any] = {\n \"plugins\": {\n name: {\n \"enabled\": cfg.enabled,\n \"version\": cfg.version,\n \"auto_update\": cfg.auto_update,\n }\n for name, cfg in self.plugins.items()\n }\n }\n\n # Remove None values for cleaner YAML\n for plugin_data in data[\"plugins\"].values():\n if plugin_data[\"version\"] is None:\n del plugin_data[\"version\"]\n\n save_yaml_dict(data, config_path)\n\n def enable_plugin(self, plugin_name: str, version: Optional[str] = None) -> None:\n \"\"\"Enable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n self.plugins[plugin_name] = PluginConfig()\n\n self.plugins[plugin_name].enabled = True\n if version:\n self.plugins[plugin_name].version = version\n\n def disable_plugin(self, plugin_name: str) -> None:\n \"\"\"Disable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n raise ValueError(f\"Plugin '{plugin_name}' is not configured\")\n\n self.plugins[plugin_name].enabled = False\n\n def is_plugin_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n # Default: disabled if not explicitly configured\n return plugin_config.enabled if plugin_config else False\n\n def get_plugin_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the configured version of a plugin.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n return plugin_config.version if plugin_config else None\n\n def remove_plugin(self, plugin_name: str) -> bool:\n \"\"\"Remove a plugin from configuration.\"\"\"\n if plugin_name in self.plugins:\n del self.plugins[plugin_name]\n return True\n return False\n\n\n# Source: ggshield/core/plugin/loader.py\nclass PluginLoader:\n \"\"\"Discovers and loads ggshield plugins from entry points and local wheels.\"\"\"\n\n def __init__(self, enterprise_config: EnterpriseConfig) -> None:\n self.enterprise_config = enterprise_config\n self.plugins_dir = get_plugins_dir()\n\n def discover_plugins(self) -> List[DiscoveredPlugin]:\n \"\"\"Discover all available plugins from entry points and local wheels.\"\"\"\n discovered: Dict[str, DiscoveredPlugin] = {}\n\n # 1. Discover from local wheels first and track their entry point names\n local_entry_point_names: set[str] = set()\n for wheel_info in self._scan_local_wheels():\n plugin_name: str = wheel_info[\"name\"]\n wheel_path: Path = wheel_info[\"path\"]\n wheel_version: str = wheel_info[\"version\"]\n entry_point_name: Optional[str] = wheel_info[\"entry_point_name\"]\n\n # Use entry point name as key if available, otherwise package name\n key = entry_point_name if entry_point_name else plugin_name\n if entry_point_name:\n local_entry_point_names.add(entry_point_name)\n\n discovered[key] = DiscoveredPlugin(\n name=key,\n entry_point=None,\n wheel_path=wheel_path,\n is_installed=True,\n is_enabled=self._is_enabled(key),\n version=wheel_version,\n )\n\n # 2. Discover from entry points (skip if already found in local wheels)\n for ep in self._get_entry_points():\n plugin_name = ep.name\n # Skip if this entry point is provided by a local wheel\n if plugin_name in local_entry_point_names:\n continue\n discovered[plugin_name] = DiscoveredPlugin(\n name=plugin_name,\n entry_point=ep,\n wheel_path=None,\n is_installed=True,\n is_enabled=self._is_enabled(plugin_name),\n version=self._get_entry_point_version(ep),\n )\n\n return list(discovered.values())\n\n def load_enabled_plugins(self) -> PluginRegistry:\n \"\"\"Load all enabled plugins and return a populated registry.\"\"\"\n registry = PluginRegistry()\n\n for discovered in self.discover_plugins():\n if not discovered.is_enabled:\n logger.debug(\"Skipping disabled plugin: %s\", discovered.name)\n continue\n\n try:\n plugin = self._load_plugin(discovered)\n if plugin is None:\n continue\n\n if not self._check_version_compatibility(plugin.metadata):\n logger.warning(\n \"Plugin %s requires ggshield >= %s, skipping\",\n plugin.metadata.name,\n plugin.metadata.min_ggshield_version,\n )\n continue\n\n plugin.on_load()\n plugin.register(registry)\n registry.register_plugin(plugin)\n\n logger.info(\n \"Loaded plugin: %s v%s\",\n plugin.metadata.name,\n plugin.metadata.version,\n )\n\n except Exception as e:\n logger.warning(\"Failed to load plugin %s: %s\", discovered.name, e)\n\n return registry\n\n def _load_plugin(self, discovered: DiscoveredPlugin) -> Optional[GGShieldPlugin]:\n \"\"\"Load a single plugin from discovery info.\"\"\"\n if discovered.wheel_path:\n return self._load_from_wheel(discovered.wheel_path)\n elif discovered.entry_point:\n return self._load_from_entry_point(discovered.entry_point)\n return None\n\n def _load_from_entry_point(\n self, ep: importlib.metadata.EntryPoint\n ) -> GGShieldPlugin:\n \"\"\"Load a plugin from an entry point.\"\"\"\n plugin_class = ep.load()\n return plugin_class()\n\n def _load_from_wheel(self, wheel_path: Path) -> Optional[GGShieldPlugin]:\n \"\"\"Load a plugin from a local wheel file.\n\n Wheels are extracted to a directory before loading because Python\n cannot import native extensions (.so/.pyd) directly from zip files.\n \"\"\"\n # Extract wheel to a directory alongside the wheel file\n extract_dir = wheel_path.parent / f\".{wheel_path.stem}_extracted\"\n\n try:\n # Extract if not already extracted or wheel is newer\n if not extract_dir.exists() or (\n wheel_path.stat().st_mtime > extract_dir.stat().st_mtime\n ):\n import shutil\n\n if extract_dir.exists():\n shutil.rmtree(extract_dir)\n\n from ggshield.utils.archive import safe_unpack\n\n safe_unpack(wheel_path, extract_dir)\n\n # Add extracted directory to sys.path\n extract_str = str(extract_dir)\n if extract_str not in sys.path:\n sys.path.append(extract_str)\n\n entry_point_str = self._read_wheel_entry_point(wheel_path)\n if not entry_point_str:\n logger.warning(\"No entry point found in wheel: %s\", wheel_path)\n return None\n\n module_name, class_name = entry_point_str.split(\":\")\n module = importlib.import_module(module_name)\n plugin_class = getattr(module, class_name)\n return plugin_class()\n except Exception as e:\n logger.warning(\"Failed to load wheel %s: %s\", wheel_path, e)\n return None\n\n def _read_wheel_entry_point(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the ggshield.plugins entry point value from a wheel's metadata.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[1] if result else None\n\n def _read_wheel_entry_point_name(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the entry point name from a wheel's entry_points.txt.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[0] if result else None\n\n def _get_entry_points(self) -> Iterator[importlib.metadata.EntryPoint]:\n \"\"\"Get all entry points in the ggshield.plugins group.\"\"\"\n try:\n eps = importlib.metadata.entry_points(group=PLUGIN_ENTRY_POINT_GROUP)\n yield from eps\n except TypeError:\n all_eps = importlib.metadata.entry_points()\n yield from all_eps.get(PLUGIN_ENTRY_POINT_GROUP, [])\n\n def _scan_local_wheels(self) -> Iterator[WheelInfo]:\n \"\"\"Scan the plugins directory for installed wheels.\"\"\"\n import json\n\n if not self.plugins_dir.exists():\n return\n\n for plugin_dir in self.plugins_dir.iterdir():\n if not plugin_dir.is_dir():\n continue\n\n manifest_path = plugin_dir / \"manifest.json\"\n if manifest_path.exists():\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\", \"\")\n wheel_path = plugin_dir / wheel_filename\n\n if wheel_path.exists():\n # Extract entry point name from wheel for deduplication\n entry_point_name = self._read_wheel_entry_point_name(wheel_path)\n yield WheelInfo(\n name=manifest[\"plugin_name\"],\n version=manifest[\"version\"],\n path=wheel_path,\n entry_point_name=entry_point_name,\n )\n except (json.JSONDecodeError, KeyError) as e:\n logger.warning(\"Invalid manifest in %s: %s\", plugin_dir, e)\n\n def _is_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled in config.\"\"\"\n plugin_config = self.enterprise_config.plugins.get(plugin_name)\n if plugin_config is None:\n return False\n return plugin_config.enabled\n\n def _get_entry_point_version(\n self, ep: importlib.metadata.EntryPoint\n ) -> Optional[str]:\n \"\"\"Get the version of a package providing an entry point.\"\"\"\n try:\n module_path = ep.value.split(\":\")[0]\n package_name = module_path.split(\".\")[0]\n dist = importlib.metadata.distribution(package_name)\n return dist.version\n except (importlib.metadata.PackageNotFoundError, IndexError):\n return None\n\n def _check_version_compatibility(self, metadata: PluginMetadata) -> bool:\n \"\"\"Check if plugin is compatible with current ggshield version.\"\"\"\n try:\n current = packaging_version.parse(ggshield_version)\n required = packaging_version.parse(metadata.min_ggshield_version)\n return current >= required\n except Exception as e:\n logger.error(\n \"Failed to parse version for plugin %s (requires %s): %s\",\n metadata.name,\n metadata.min_ggshield_version,\n e,\n )\n return False", "n_chars_compressed": 12506, "compression_ratio": 1.0}, "tests/unit/core/scan/test_scannable.py::17": {"resolved_imports": ["ggshield/core/scan/file.py", "ggshield/core/scan/scannable.py"], "used_names": ["Path", "StringScannable"], "enclosing_function": "test_string_scannable_path", "extracted_code": "# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1122, "extracted_code_full": "# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size", "n_chars_compressed": 1122, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_check.py::22": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli", "my_vcr", "uuid4"], "enclosing_function": "test_hmsl_check_random_secret", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_path.py::53": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["ExitCode", "Path", "cli", "my_vcr", "os", "pytest", "write_text"], "enclosing_function": "test_scan_file", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 12, "n_files_resolved": 2, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/core/config/test_auth_config.py::109": {"resolved_imports": ["ggshield/core/config/config.py", "ggshield/core/config/auth_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py"], "used_names": ["Config", "UnknownInstanceError", "pytest"], "enclosing_function": "test_update", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/errors.py\nclass UnknownInstanceError(AuthError):\n \"\"\"\n Raised when the requested instance does not exist\n \"\"\"\n\n def __init__(self, instance: str):\n super().__init__(instance, f\"Unknown instance: '{instance}'\")", "n_imports_parsed": 11, "n_files_resolved": 4, "n_chars_extracted": 8292, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/errors.py\nclass UnknownInstanceError(AuthError):\n \"\"\"\n Raised when the requested instance does not exist\n \"\"\"\n\n def __init__(self, instance: str):\n super().__init__(instance, f\"Unknown instance: '{instance}'\")", "n_chars_compressed": 8292, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_docker.py::98": {"resolved_imports": ["ggshield/core/dirs.py"], "used_names": ["Path", "run_ggshield_scan", "skipwindows"], "enclosing_function": "test_scan_docker_uses_cache", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/functional/secret/test_scan_path.py::79": {"resolved_imports": [], "used_names": ["GG_VALID_TOKEN", "GG_VALID_TOKEN_IGNORE_SHA", "Path", "json", "jsonschema", "pytest", "recreate_censored_string", "run_ggshield_scan"], "enclosing_function": "test_scan_path_json_output", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/cmd/auth/test_login.py::829": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/constants.py", "ggshield/core/errors.py", "ggshield/utils/datetime.py", "ggshield/verticals/auth/oauth.py"], "used_names": ["Optional", "Set"], "enclosing_function": "_assert_open_url", "extracted_code": "", "n_imports_parsed": 16, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/unit/core/scan/test_file.py::235": {"resolved_imports": ["ggshield/core/scan/file.py", "ggshield/core/scan/scannable.py"], "used_names": ["create_files_from_paths", "pytest"], "enclosing_function": "test_create_files_from_paths", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/utils/test_git_shell.py::63": {"resolved_imports": ["ggshield/core/tar_utils.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["git"], "enclosing_function": "test_git_shell", "extracted_code": "# Source: ggshield/utils/git_shell.py\ndef git(\n command: List[str],\n timeout: int = COMMAND_TIMEOUT,\n check: bool = True,\n cwd: Optional[Union[str, Path]] = None,\n log_stderr: bool = True,\n ignore_git_config: bool = True,\n) -> str:\n \"\"\"Calls git with the given arguments, returns stdout as a string\"\"\"\n env = os.environ.copy()\n # Ensure git messages are in English\n env[\"LANG\"] = \"C\"\n # Ensure git behavior is not affected by the user git configuration, but give us a\n # way to set some configuration (useful for safe.directory)\n if ignore_git_config:\n env[\"GIT_CONFIG_GLOBAL\"] = os.getenv(\"GG_GIT_CONFIG\", \"\")\n env[\"GIT_CONFIG_SYSTEM\"] = \"\"\n\n if cwd is None:\n cwd = Path.cwd()\n\n try:\n logger.debug(\"command=%s timeout=%d\", command, timeout)\n result = subprocess.run(\n (\n [\n _get_git_path(),\n \"-c\",\n \"core.quotePath=false\",\n \"-c\",\n \"safe.directory=*\",\n ]\n + (\n [\"-c\", \"core.longpaths=true\"]\n if platform.system() == \"Windows\"\n else []\n )\n + command\n ),\n check=check,\n capture_output=True,\n timeout=timeout,\n env=env,\n cwd=str(cwd),\n )\n if result.stderr and log_stderr:\n logger.warning(\n \"command=%s, stderr=%s\",\n command,\n result.stderr.decode(\"utf-8\", errors=\"ignore\"),\n )\n return result.stdout.decode(\"utf-8\", errors=\"ignore\").rstrip()\n except subprocess.CalledProcessError as exc:\n stderr = exc.stderr.decode(\"utf-8\", errors=\"ignore\")\n if log_stderr:\n logger.error(\"command=%s, stderr=%s\", command, stderr)\n if \"detected dubious ownership in repository\" in stderr:\n raise GitError(\n \"Git command failed because of a dubious ownership in repository.\\n\"\n \"If you still want to run ggshield, make sure you mark \"\n \"the current repository as safe for git with:\\n\"\n \" git config --global --add safe.directory \"\n )\n raise exc\n except subprocess.TimeoutExpired:\n raise GitCommandTimeoutExpired(\n 'Command \"{}\" timed out'.format(\" \".join(command))\n )", "n_imports_parsed": 14, "n_files_resolved": 3, "n_chars_extracted": 2482, "extracted_code_full": "# Source: ggshield/utils/git_shell.py\ndef git(\n command: List[str],\n timeout: int = COMMAND_TIMEOUT,\n check: bool = True,\n cwd: Optional[Union[str, Path]] = None,\n log_stderr: bool = True,\n ignore_git_config: bool = True,\n) -> str:\n \"\"\"Calls git with the given arguments, returns stdout as a string\"\"\"\n env = os.environ.copy()\n # Ensure git messages are in English\n env[\"LANG\"] = \"C\"\n # Ensure git behavior is not affected by the user git configuration, but give us a\n # way to set some configuration (useful for safe.directory)\n if ignore_git_config:\n env[\"GIT_CONFIG_GLOBAL\"] = os.getenv(\"GG_GIT_CONFIG\", \"\")\n env[\"GIT_CONFIG_SYSTEM\"] = \"\"\n\n if cwd is None:\n cwd = Path.cwd()\n\n try:\n logger.debug(\"command=%s timeout=%d\", command, timeout)\n result = subprocess.run(\n (\n [\n _get_git_path(),\n \"-c\",\n \"core.quotePath=false\",\n \"-c\",\n \"safe.directory=*\",\n ]\n + (\n [\"-c\", \"core.longpaths=true\"]\n if platform.system() == \"Windows\"\n else []\n )\n + command\n ),\n check=check,\n capture_output=True,\n timeout=timeout,\n env=env,\n cwd=str(cwd),\n )\n if result.stderr and log_stderr:\n logger.warning(\n \"command=%s, stderr=%s\",\n command,\n result.stderr.decode(\"utf-8\", errors=\"ignore\"),\n )\n return result.stdout.decode(\"utf-8\", errors=\"ignore\").rstrip()\n except subprocess.CalledProcessError as exc:\n stderr = exc.stderr.decode(\"utf-8\", errors=\"ignore\")\n if log_stderr:\n logger.error(\"command=%s, stderr=%s\", command, stderr)\n if \"detected dubious ownership in repository\" in stderr:\n raise GitError(\n \"Git command failed because of a dubious ownership in repository.\\n\"\n \"If you still want to run ggshield, make sure you mark \"\n \"the current repository as safe for git with:\\n\"\n \" git config --global --add safe.directory \"\n )\n raise exc\n except subprocess.TimeoutExpired:\n raise GitCommandTimeoutExpired(\n 'Command \"{}\" timed out'.format(\" \".join(command))\n )", "n_chars_compressed": 2482, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_wheel_utils.py::61": {"resolved_imports": ["ggshield/core/plugin/wheel_utils.py"], "used_names": ["Path", "extract_wheel_metadata"], "enclosing_function": "test_extract_valid_wheel", "extracted_code": "# Source: ggshield/core/plugin/wheel_utils.py\ndef extract_wheel_metadata(wheel_path: Path) -> WheelMetadata:\n \"\"\"\n Extract metadata from a wheel file.\n\n Reads the METADATA file from the wheel's dist-info directory.\n\n Args:\n wheel_path: Path to the wheel file.\n\n Returns:\n WheelMetadata with name, version, and optional fields.\n\n Raises:\n InvalidWheelError: If the wheel is not a valid ZIP file.\n MetadataNotFoundError: If METADATA file is not found.\n WheelError: For other parsing errors.\n \"\"\"\n if not wheel_path.exists():\n raise InvalidWheelError(f\"Wheel file not found: {wheel_path}\")\n\n if not wheel_path.suffix == \".whl\":\n raise InvalidWheelError(f\"Not a wheel file: {wheel_path}\")\n\n try:\n with ZipFile(wheel_path, \"r\") as zf:\n metadata_path = _find_metadata_file(zf)\n if metadata_path is None:\n raise MetadataNotFoundError(\n f\"METADATA file not found in wheel: {wheel_path}\"\n )\n\n metadata_content = zf.read(metadata_path).decode(\"utf-8\")\n return _parse_metadata(metadata_content)\n\n except BadZipFile as e:\n raise InvalidWheelError(f\"Invalid wheel file (not a valid ZIP): {e}\") from e", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1276, "extracted_code_full": "# Source: ggshield/core/plugin/wheel_utils.py\ndef extract_wheel_metadata(wheel_path: Path) -> WheelMetadata:\n \"\"\"\n Extract metadata from a wheel file.\n\n Reads the METADATA file from the wheel's dist-info directory.\n\n Args:\n wheel_path: Path to the wheel file.\n\n Returns:\n WheelMetadata with name, version, and optional fields.\n\n Raises:\n InvalidWheelError: If the wheel is not a valid ZIP file.\n MetadataNotFoundError: If METADATA file is not found.\n WheelError: For other parsing errors.\n \"\"\"\n if not wheel_path.exists():\n raise InvalidWheelError(f\"Wheel file not found: {wheel_path}\")\n\n if not wheel_path.suffix == \".whl\":\n raise InvalidWheelError(f\"Not a wheel file: {wheel_path}\")\n\n try:\n with ZipFile(wheel_path, \"r\") as zf:\n metadata_path = _find_metadata_file(zf)\n if metadata_path is None:\n raise MetadataNotFoundError(\n f\"METADATA file not found in wheel: {wheel_path}\"\n )\n\n metadata_content = zf.read(metadata_path).decode(\"utf-8\")\n return _parse_metadata(metadata_content)\n\n except BadZipFile as e:\n raise InvalidWheelError(f\"Invalid wheel file (not a valid ZIP): {e}\") from e", "n_chars_compressed": 1276, "compression_ratio": 1.0}, "tests/unit/core/config/test_utils.py::69": {"resolved_imports": ["ggshield/core/config/utils.py", "ggshield/utils/os.py"], "used_names": ["update_dict_from_other"], "enclosing_function": "test_update_dict_from_other", "extracted_code": "# Source: ggshield/core/config/utils.py\ndef update_dict_from_other(dct: Dict[str, Any], other: Dict[str, Any]) -> None:\n \"\"\"\n Merge values from `other` dict into `dct`. List entries are appended, sets are\n updated, dicts are merged.\n\n The merge happens in-place: `dct` is modified.\n \"\"\"\n for key, value in other.items():\n try:\n if value is None:\n continue\n if isinstance(value, list):\n dct.setdefault(key, []).extend(value)\n elif isinstance(value, set):\n dct.setdefault(key, set()).update(value)\n elif isinstance(value, dict):\n update_dict_from_other(dct.setdefault(key, {}), value)\n else:\n dct[key] = value\n except AttributeError:\n raise UnexpectedError(f\"Failed to load configuration on key '{key}'\")", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 875, "extracted_code_full": "# Source: ggshield/core/config/utils.py\ndef update_dict_from_other(dct: Dict[str, Any], other: Dict[str, Any]) -> None:\n \"\"\"\n Merge values from `other` dict into `dct`. List entries are appended, sets are\n updated, dicts are merged.\n\n The merge happens in-place: `dct` is modified.\n \"\"\"\n for key, value in other.items():\n try:\n if value is None:\n continue\n if isinstance(value, list):\n dct.setdefault(key, []).extend(value)\n elif isinstance(value, set):\n dct.setdefault(key, set()).update(value)\n elif isinstance(value, dict):\n update_dict_from_other(dct.setdefault(key, {}), value)\n else:\n dct[key] = value\n except AttributeError:\n raise UnexpectedError(f\"Failed to load configuration on key '{key}'\")", "n_chars_compressed": 875, "compression_ratio": 1.0}, "tests/unit/core/test_url_utils.py::59": {"resolved_imports": ["ggshield/core/url_utils.py"], "used_names": ["dashboard_to_api_url", "pytest"], "enclosing_function": "test_dashboard_to_api_url", "extracted_code": "# Source: ggshield/core/url_utils.py\ndef dashboard_to_api_url(dashboard_url: str, warn: bool = False) -> str:\n \"\"\"\n Convert a dashboard URL to an API URL.\n handles the SaaS edge case where the host changes instead of the path\n \"\"\"\n parsed_url = validate_instance_url(dashboard_url, warn=warn)\n\n if any(parsed_url.netloc.endswith(\".\" + domain) for domain in GITGUARDIAN_DOMAINS):\n parsed_url = parsed_url._replace(\n netloc=parsed_url.netloc.replace(\"dashboard\", \"api\")\n )\n else:\n parsed_url = parsed_url._replace(\n path=f\"{parsed_url.path}{ON_PREMISE_API_URL_PATH_PREFIX}\"\n )\n return parsed_url.geturl()", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 676, "extracted_code_full": "# Source: ggshield/core/url_utils.py\ndef dashboard_to_api_url(dashboard_url: str, warn: bool = False) -> str:\n \"\"\"\n Convert a dashboard URL to an API URL.\n handles the SaaS edge case where the host changes instead of the path\n \"\"\"\n parsed_url = validate_instance_url(dashboard_url, warn=warn)\n\n if any(parsed_url.netloc.endswith(\".\" + domain) for domain in GITGUARDIAN_DOMAINS):\n parsed_url = parsed_url._replace(\n netloc=parsed_url.netloc.replace(\"dashboard\", \"api\")\n )\n else:\n parsed_url = parsed_url._replace(\n path=f\"{parsed_url.path}{ON_PREMISE_API_URL_PATH_PREFIX}\"\n )\n return parsed_url.geturl()", "n_chars_compressed": 676, "compression_ratio": 1.0}, "tests/unit/core/scan/test_id_cache.py::41": {"resolved_imports": ["ggshield/core/scan/id_cache.py"], "used_names": ["FakeFilesystem", "IDCache", "Path"], "enclosing_function": "test_contains", "extracted_code": "# Source: ggshield/core/scan/id_cache.py\nclass IDCache:\n \"\"\"\n Stores a list of IDs as JSON in self.cache_path.\n \"\"\"\n\n def __init__(self, cache_path: Path):\n self.cache_path = cache_path\n self._ids: Set[str] = set()\n if self.cache_path.exists():\n self._load()\n\n def __contains__(self, id: str) -> bool:\n return id in self._ids\n\n def add(self, layer_id: str) -> None:\n self._ids.add(layer_id)\n self._save()\n\n def _load(self) -> None:\n try:\n ids = json.loads(self.cache_path.read_text())\n except Exception as exc:\n logger.warning(\"Failed to load cache from %s: %s\", self.cache_path, exc)\n return\n self._ids = set(ids)\n\n def _save(self) -> None:\n text = json.dumps(list(self._ids))\n try:\n self.cache_path.parent.mkdir(parents=True, exist_ok=True)\n self.cache_path.write_text(text)\n except Exception as exc:\n logger.warning(\"Failed to save cache to %s: %s\", self.cache_path, exc)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1059, "extracted_code_full": "# Source: ggshield/core/scan/id_cache.py\nclass IDCache:\n \"\"\"\n Stores a list of IDs as JSON in self.cache_path.\n \"\"\"\n\n def __init__(self, cache_path: Path):\n self.cache_path = cache_path\n self._ids: Set[str] = set()\n if self.cache_path.exists():\n self._load()\n\n def __contains__(self, id: str) -> bool:\n return id in self._ids\n\n def add(self, layer_id: str) -> None:\n self._ids.add(layer_id)\n self._save()\n\n def _load(self) -> None:\n try:\n ids = json.loads(self.cache_path.read_text())\n except Exception as exc:\n logger.warning(\"Failed to load cache from %s: %s\", self.cache_path, exc)\n return\n self._ids = set(ids)\n\n def _save(self) -> None:\n text = json.dumps(list(self._ids))\n try:\n self.cache_path.parent.mkdir(parents=True, exist_ok=True)\n self.cache_path.write_text(text)\n except Exception as exc:\n logger.warning(\"Failed to save cache to %s: %s\", self.cache_path, exc)", "n_chars_compressed": 1059, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_wheel_utils.py::165": {"resolved_imports": ["ggshield/core/plugin/wheel_utils.py"], "used_names": ["Path", "validate_wheel_file"], "enclosing_function": "test_valid_wheel", "extracted_code": "# Source: ggshield/core/plugin/wheel_utils.py\ndef validate_wheel_file(wheel_path: Path) -> bool:\n \"\"\"\n Validate that a file is a valid wheel.\n\n Returns True if the file is a valid wheel, False otherwise.\n Does not raise exceptions.\n \"\"\"\n try:\n extract_wheel_metadata(wheel_path)\n return True\n except WheelError:\n return False", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 367, "extracted_code_full": "# Source: ggshield/core/plugin/wheel_utils.py\ndef validate_wheel_file(wheel_path: Path) -> bool:\n \"\"\"\n Validate that a file is a valid wheel.\n\n Returns True if the file is a valid wheel, False otherwise.\n Does not raise exceptions.\n \"\"\"\n try:\n extract_wheel_metadata(wheel_path)\n return True\n except WheelError:\n return False", "n_chars_compressed": 367, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_loader.py::79": {"resolved_imports": ["ggshield/core/config/enterprise_config.py", "ggshield/core/plugin/base.py", "ggshield/core/plugin/loader.py", "ggshield/core/plugin/registry.py"], "used_names": ["EnterpriseConfig", "Path", "PluginLoader", "json", "patch"], "enclosing_function": "test_discover_plugins_from_local_wheel", "extracted_code": "# Source: ggshield/core/config/enterprise_config.py\nclass EnterpriseConfig:\n \"\"\"Enterprise configuration stored in ~/.config/ggshield/enterprise_config.yaml\"\"\"\n\n plugins: Dict[str, PluginConfig] = field(default_factory=dict)\n\n @classmethod\n def load(cls) -> \"EnterpriseConfig\":\n \"\"\"Load enterprise config from file.\"\"\"\n config_path = get_enterprise_config_filepath()\n data = load_yaml_dict(config_path)\n\n if data is None:\n return cls()\n\n # Convert plugin configs from dict\n plugins: Dict[str, PluginConfig] = {}\n for name, plugin_data in data.get(\"plugins\", {}).items():\n if isinstance(plugin_data, dict):\n plugins[name] = PluginConfig(\n enabled=plugin_data.get(\"enabled\", True),\n version=plugin_data.get(\"version\"),\n auto_update=plugin_data.get(\"auto_update\", True),\n )\n elif isinstance(plugin_data, bool):\n # Simple format: just enabled/disabled\n plugins[name] = PluginConfig(enabled=plugin_data)\n else:\n plugins[name] = PluginConfig(enabled=True)\n\n return cls(plugins=plugins)\n\n def save(self) -> None:\n \"\"\"Save enterprise config to file.\"\"\"\n config_path = get_enterprise_config_filepath()\n\n # Convert to dict for saving\n data: Dict[str, Any] = {\n \"plugins\": {\n name: {\n \"enabled\": cfg.enabled,\n \"version\": cfg.version,\n \"auto_update\": cfg.auto_update,\n }\n for name, cfg in self.plugins.items()\n }\n }\n\n # Remove None values for cleaner YAML\n for plugin_data in data[\"plugins\"].values():\n if plugin_data[\"version\"] is None:\n del plugin_data[\"version\"]\n\n save_yaml_dict(data, config_path)\n\n def enable_plugin(self, plugin_name: str, version: Optional[str] = None) -> None:\n \"\"\"Enable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n self.plugins[plugin_name] = PluginConfig()\n\n self.plugins[plugin_name].enabled = True\n if version:\n self.plugins[plugin_name].version = version\n\n def disable_plugin(self, plugin_name: str) -> None:\n \"\"\"Disable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n raise ValueError(f\"Plugin '{plugin_name}' is not configured\")\n\n self.plugins[plugin_name].enabled = False\n\n def is_plugin_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n # Default: disabled if not explicitly configured\n return plugin_config.enabled if plugin_config else False\n\n def get_plugin_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the configured version of a plugin.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n return plugin_config.version if plugin_config else None\n\n def remove_plugin(self, plugin_name: str) -> bool:\n \"\"\"Remove a plugin from configuration.\"\"\"\n if plugin_name in self.plugins:\n del self.plugins[plugin_name]\n return True\n return False\n\n\n# Source: ggshield/core/plugin/loader.py\nclass PluginLoader:\n \"\"\"Discovers and loads ggshield plugins from entry points and local wheels.\"\"\"\n\n def __init__(self, enterprise_config: EnterpriseConfig) -> None:\n self.enterprise_config = enterprise_config\n self.plugins_dir = get_plugins_dir()\n\n def discover_plugins(self) -> List[DiscoveredPlugin]:\n \"\"\"Discover all available plugins from entry points and local wheels.\"\"\"\n discovered: Dict[str, DiscoveredPlugin] = {}\n\n # 1. Discover from local wheels first and track their entry point names\n local_entry_point_names: set[str] = set()\n for wheel_info in self._scan_local_wheels():\n plugin_name: str = wheel_info[\"name\"]\n wheel_path: Path = wheel_info[\"path\"]\n wheel_version: str = wheel_info[\"version\"]\n entry_point_name: Optional[str] = wheel_info[\"entry_point_name\"]\n\n # Use entry point name as key if available, otherwise package name\n key = entry_point_name if entry_point_name else plugin_name\n if entry_point_name:\n local_entry_point_names.add(entry_point_name)\n\n discovered[key] = DiscoveredPlugin(\n name=key,\n entry_point=None,\n wheel_path=wheel_path,\n is_installed=True,\n is_enabled=self._is_enabled(key),\n version=wheel_version,\n )\n\n # 2. Discover from entry points (skip if already found in local wheels)\n for ep in self._get_entry_points():\n plugin_name = ep.name\n # Skip if this entry point is provided by a local wheel\n if plugin_name in local_entry_point_names:\n continue\n discovered[plugin_name] = DiscoveredPlugin(\n name=plugin_name,\n entry_point=ep,\n wheel_path=None,\n is_installed=True,\n is_enabled=self._is_enabled(plugin_name),\n version=self._get_entry_point_version(ep),\n )\n\n return list(discovered.values())\n\n def load_enabled_plugins(self) -> PluginRegistry:\n \"\"\"Load all enabled plugins and return a populated registry.\"\"\"\n registry = PluginRegistry()\n\n for discovered in self.discover_plugins():\n if not discovered.is_enabled:\n logger.debug(\"Skipping disabled plugin: %s\", discovered.name)\n continue\n\n try:\n plugin = self._load_plugin(discovered)\n if plugin is None:\n continue\n\n if not self._check_version_compatibility(plugin.metadata):\n logger.warning(\n \"Plugin %s requires ggshield >= %s, skipping\",\n plugin.metadata.name,\n plugin.metadata.min_ggshield_version,\n )\n continue\n\n plugin.on_load()\n plugin.register(registry)\n registry.register_plugin(plugin)\n\n logger.info(\n \"Loaded plugin: %s v%s\",\n plugin.metadata.name,\n plugin.metadata.version,\n )\n\n except Exception as e:\n logger.warning(\"Failed to load plugin %s: %s\", discovered.name, e)\n\n return registry\n\n def _load_plugin(self, discovered: DiscoveredPlugin) -> Optional[GGShieldPlugin]:\n \"\"\"Load a single plugin from discovery info.\"\"\"\n if discovered.wheel_path:\n return self._load_from_wheel(discovered.wheel_path)\n elif discovered.entry_point:\n return self._load_from_entry_point(discovered.entry_point)\n return None\n\n def _load_from_entry_point(\n self, ep: importlib.metadata.EntryPoint\n ) -> GGShieldPlugin:\n \"\"\"Load a plugin from an entry point.\"\"\"\n plugin_class = ep.load()\n return plugin_class()\n\n def _load_from_wheel(self, wheel_path: Path) -> Optional[GGShieldPlugin]:\n \"\"\"Load a plugin from a local wheel file.\n\n Wheels are extracted to a directory before loading because Python\n cannot import native extensions (.so/.pyd) directly from zip files.\n \"\"\"\n # Extract wheel to a directory alongside the wheel file\n extract_dir = wheel_path.parent / f\".{wheel_path.stem}_extracted\"\n\n try:\n # Extract if not already extracted or wheel is newer\n if not extract_dir.exists() or (\n wheel_path.stat().st_mtime > extract_dir.stat().st_mtime\n ):\n import shutil\n\n if extract_dir.exists():\n shutil.rmtree(extract_dir)\n\n from ggshield.utils.archive import safe_unpack\n\n safe_unpack(wheel_path, extract_dir)\n\n # Add extracted directory to sys.path\n extract_str = str(extract_dir)\n if extract_str not in sys.path:\n sys.path.append(extract_str)\n\n entry_point_str = self._read_wheel_entry_point(wheel_path)\n if not entry_point_str:\n logger.warning(\"No entry point found in wheel: %s\", wheel_path)\n return None\n\n module_name, class_name = entry_point_str.split(\":\")\n module = importlib.import_module(module_name)\n plugin_class = getattr(module, class_name)\n return plugin_class()\n except Exception as e:\n logger.warning(\"Failed to load wheel %s: %s\", wheel_path, e)\n return None\n\n def _read_wheel_entry_point(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the ggshield.plugins entry point value from a wheel's metadata.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[1] if result else None\n\n def _read_wheel_entry_point_name(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the entry point name from a wheel's entry_points.txt.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[0] if result else None\n\n def _get_entry_points(self) -> Iterator[importlib.metadata.EntryPoint]:\n \"\"\"Get all entry points in the ggshield.plugins group.\"\"\"\n try:\n eps = importlib.metadata.entry_points(group=PLUGIN_ENTRY_POINT_GROUP)\n yield from eps\n except TypeError:\n all_eps = importlib.metadata.entry_points()\n yield from all_eps.get(PLUGIN_ENTRY_POINT_GROUP, [])\n\n def _scan_local_wheels(self) -> Iterator[WheelInfo]:\n \"\"\"Scan the plugins directory for installed wheels.\"\"\"\n import json\n\n if not self.plugins_dir.exists():\n return\n\n for plugin_dir in self.plugins_dir.iterdir():\n if not plugin_dir.is_dir():\n continue\n\n manifest_path = plugin_dir / \"manifest.json\"\n if manifest_path.exists():\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\", \"\")\n wheel_path = plugin_dir / wheel_filename\n\n if wheel_path.exists():\n # Extract entry point name from wheel for deduplication\n entry_point_name = self._read_wheel_entry_point_name(wheel_path)\n yield WheelInfo(\n name=manifest[\"plugin_name\"],\n version=manifest[\"version\"],\n path=wheel_path,\n entry_point_name=entry_point_name,\n )\n except (json.JSONDecodeError, KeyError) as e:\n logger.warning(\"Invalid manifest in %s: %s\", plugin_dir, e)\n\n def _is_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled in config.\"\"\"\n plugin_config = self.enterprise_config.plugins.get(plugin_name)\n if plugin_config is None:\n return False\n return plugin_config.enabled\n\n def _get_entry_point_version(\n self, ep: importlib.metadata.EntryPoint\n ) -> Optional[str]:\n \"\"\"Get the version of a package providing an entry point.\"\"\"\n try:\n module_path = ep.value.split(\":\")[0]\n package_name = module_path.split(\".\")[0]\n dist = importlib.metadata.distribution(package_name)\n return dist.version\n except (importlib.metadata.PackageNotFoundError, IndexError):\n return None\n\n def _check_version_compatibility(self, metadata: PluginMetadata) -> bool:\n \"\"\"Check if plugin is compatible with current ggshield version.\"\"\"\n try:\n current = packaging_version.parse(ggshield_version)\n required = packaging_version.parse(metadata.min_ggshield_version)\n return current >= required\n except Exception as e:\n logger.error(\n \"Failed to parse version for plugin %s (requires %s): %s\",\n metadata.name,\n metadata.min_ggshield_version,\n e,\n )\n return False", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 12506, "extracted_code_full": "# Source: ggshield/core/config/enterprise_config.py\nclass EnterpriseConfig:\n \"\"\"Enterprise configuration stored in ~/.config/ggshield/enterprise_config.yaml\"\"\"\n\n plugins: Dict[str, PluginConfig] = field(default_factory=dict)\n\n @classmethod\n def load(cls) -> \"EnterpriseConfig\":\n \"\"\"Load enterprise config from file.\"\"\"\n config_path = get_enterprise_config_filepath()\n data = load_yaml_dict(config_path)\n\n if data is None:\n return cls()\n\n # Convert plugin configs from dict\n plugins: Dict[str, PluginConfig] = {}\n for name, plugin_data in data.get(\"plugins\", {}).items():\n if isinstance(plugin_data, dict):\n plugins[name] = PluginConfig(\n enabled=plugin_data.get(\"enabled\", True),\n version=plugin_data.get(\"version\"),\n auto_update=plugin_data.get(\"auto_update\", True),\n )\n elif isinstance(plugin_data, bool):\n # Simple format: just enabled/disabled\n plugins[name] = PluginConfig(enabled=plugin_data)\n else:\n plugins[name] = PluginConfig(enabled=True)\n\n return cls(plugins=plugins)\n\n def save(self) -> None:\n \"\"\"Save enterprise config to file.\"\"\"\n config_path = get_enterprise_config_filepath()\n\n # Convert to dict for saving\n data: Dict[str, Any] = {\n \"plugins\": {\n name: {\n \"enabled\": cfg.enabled,\n \"version\": cfg.version,\n \"auto_update\": cfg.auto_update,\n }\n for name, cfg in self.plugins.items()\n }\n }\n\n # Remove None values for cleaner YAML\n for plugin_data in data[\"plugins\"].values():\n if plugin_data[\"version\"] is None:\n del plugin_data[\"version\"]\n\n save_yaml_dict(data, config_path)\n\n def enable_plugin(self, plugin_name: str, version: Optional[str] = None) -> None:\n \"\"\"Enable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n self.plugins[plugin_name] = PluginConfig()\n\n self.plugins[plugin_name].enabled = True\n if version:\n self.plugins[plugin_name].version = version\n\n def disable_plugin(self, plugin_name: str) -> None:\n \"\"\"Disable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n raise ValueError(f\"Plugin '{plugin_name}' is not configured\")\n\n self.plugins[plugin_name].enabled = False\n\n def is_plugin_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n # Default: disabled if not explicitly configured\n return plugin_config.enabled if plugin_config else False\n\n def get_plugin_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the configured version of a plugin.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n return plugin_config.version if plugin_config else None\n\n def remove_plugin(self, plugin_name: str) -> bool:\n \"\"\"Remove a plugin from configuration.\"\"\"\n if plugin_name in self.plugins:\n del self.plugins[plugin_name]\n return True\n return False\n\n\n# Source: ggshield/core/plugin/loader.py\nclass PluginLoader:\n \"\"\"Discovers and loads ggshield plugins from entry points and local wheels.\"\"\"\n\n def __init__(self, enterprise_config: EnterpriseConfig) -> None:\n self.enterprise_config = enterprise_config\n self.plugins_dir = get_plugins_dir()\n\n def discover_plugins(self) -> List[DiscoveredPlugin]:\n \"\"\"Discover all available plugins from entry points and local wheels.\"\"\"\n discovered: Dict[str, DiscoveredPlugin] = {}\n\n # 1. Discover from local wheels first and track their entry point names\n local_entry_point_names: set[str] = set()\n for wheel_info in self._scan_local_wheels():\n plugin_name: str = wheel_info[\"name\"]\n wheel_path: Path = wheel_info[\"path\"]\n wheel_version: str = wheel_info[\"version\"]\n entry_point_name: Optional[str] = wheel_info[\"entry_point_name\"]\n\n # Use entry point name as key if available, otherwise package name\n key = entry_point_name if entry_point_name else plugin_name\n if entry_point_name:\n local_entry_point_names.add(entry_point_name)\n\n discovered[key] = DiscoveredPlugin(\n name=key,\n entry_point=None,\n wheel_path=wheel_path,\n is_installed=True,\n is_enabled=self._is_enabled(key),\n version=wheel_version,\n )\n\n # 2. Discover from entry points (skip if already found in local wheels)\n for ep in self._get_entry_points():\n plugin_name = ep.name\n # Skip if this entry point is provided by a local wheel\n if plugin_name in local_entry_point_names:\n continue\n discovered[plugin_name] = DiscoveredPlugin(\n name=plugin_name,\n entry_point=ep,\n wheel_path=None,\n is_installed=True,\n is_enabled=self._is_enabled(plugin_name),\n version=self._get_entry_point_version(ep),\n )\n\n return list(discovered.values())\n\n def load_enabled_plugins(self) -> PluginRegistry:\n \"\"\"Load all enabled plugins and return a populated registry.\"\"\"\n registry = PluginRegistry()\n\n for discovered in self.discover_plugins():\n if not discovered.is_enabled:\n logger.debug(\"Skipping disabled plugin: %s\", discovered.name)\n continue\n\n try:\n plugin = self._load_plugin(discovered)\n if plugin is None:\n continue\n\n if not self._check_version_compatibility(plugin.metadata):\n logger.warning(\n \"Plugin %s requires ggshield >= %s, skipping\",\n plugin.metadata.name,\n plugin.metadata.min_ggshield_version,\n )\n continue\n\n plugin.on_load()\n plugin.register(registry)\n registry.register_plugin(plugin)\n\n logger.info(\n \"Loaded plugin: %s v%s\",\n plugin.metadata.name,\n plugin.metadata.version,\n )\n\n except Exception as e:\n logger.warning(\"Failed to load plugin %s: %s\", discovered.name, e)\n\n return registry\n\n def _load_plugin(self, discovered: DiscoveredPlugin) -> Optional[GGShieldPlugin]:\n \"\"\"Load a single plugin from discovery info.\"\"\"\n if discovered.wheel_path:\n return self._load_from_wheel(discovered.wheel_path)\n elif discovered.entry_point:\n return self._load_from_entry_point(discovered.entry_point)\n return None\n\n def _load_from_entry_point(\n self, ep: importlib.metadata.EntryPoint\n ) -> GGShieldPlugin:\n \"\"\"Load a plugin from an entry point.\"\"\"\n plugin_class = ep.load()\n return plugin_class()\n\n def _load_from_wheel(self, wheel_path: Path) -> Optional[GGShieldPlugin]:\n \"\"\"Load a plugin from a local wheel file.\n\n Wheels are extracted to a directory before loading because Python\n cannot import native extensions (.so/.pyd) directly from zip files.\n \"\"\"\n # Extract wheel to a directory alongside the wheel file\n extract_dir = wheel_path.parent / f\".{wheel_path.stem}_extracted\"\n\n try:\n # Extract if not already extracted or wheel is newer\n if not extract_dir.exists() or (\n wheel_path.stat().st_mtime > extract_dir.stat().st_mtime\n ):\n import shutil\n\n if extract_dir.exists():\n shutil.rmtree(extract_dir)\n\n from ggshield.utils.archive import safe_unpack\n\n safe_unpack(wheel_path, extract_dir)\n\n # Add extracted directory to sys.path\n extract_str = str(extract_dir)\n if extract_str not in sys.path:\n sys.path.append(extract_str)\n\n entry_point_str = self._read_wheel_entry_point(wheel_path)\n if not entry_point_str:\n logger.warning(\"No entry point found in wheel: %s\", wheel_path)\n return None\n\n module_name, class_name = entry_point_str.split(\":\")\n module = importlib.import_module(module_name)\n plugin_class = getattr(module, class_name)\n return plugin_class()\n except Exception as e:\n logger.warning(\"Failed to load wheel %s: %s\", wheel_path, e)\n return None\n\n def _read_wheel_entry_point(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the ggshield.plugins entry point value from a wheel's metadata.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[1] if result else None\n\n def _read_wheel_entry_point_name(self, wheel_path: Path) -> Optional[str]:\n \"\"\"Read the entry point name from a wheel's entry_points.txt.\"\"\"\n result = read_entry_point_from_wheel(wheel_path)\n return result[0] if result else None\n\n def _get_entry_points(self) -> Iterator[importlib.metadata.EntryPoint]:\n \"\"\"Get all entry points in the ggshield.plugins group.\"\"\"\n try:\n eps = importlib.metadata.entry_points(group=PLUGIN_ENTRY_POINT_GROUP)\n yield from eps\n except TypeError:\n all_eps = importlib.metadata.entry_points()\n yield from all_eps.get(PLUGIN_ENTRY_POINT_GROUP, [])\n\n def _scan_local_wheels(self) -> Iterator[WheelInfo]:\n \"\"\"Scan the plugins directory for installed wheels.\"\"\"\n import json\n\n if not self.plugins_dir.exists():\n return\n\n for plugin_dir in self.plugins_dir.iterdir():\n if not plugin_dir.is_dir():\n continue\n\n manifest_path = plugin_dir / \"manifest.json\"\n if manifest_path.exists():\n try:\n manifest = json.loads(manifest_path.read_text())\n wheel_filename = manifest.get(\"wheel_filename\", \"\")\n wheel_path = plugin_dir / wheel_filename\n\n if wheel_path.exists():\n # Extract entry point name from wheel for deduplication\n entry_point_name = self._read_wheel_entry_point_name(wheel_path)\n yield WheelInfo(\n name=manifest[\"plugin_name\"],\n version=manifest[\"version\"],\n path=wheel_path,\n entry_point_name=entry_point_name,\n )\n except (json.JSONDecodeError, KeyError) as e:\n logger.warning(\"Invalid manifest in %s: %s\", plugin_dir, e)\n\n def _is_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled in config.\"\"\"\n plugin_config = self.enterprise_config.plugins.get(plugin_name)\n if plugin_config is None:\n return False\n return plugin_config.enabled\n\n def _get_entry_point_version(\n self, ep: importlib.metadata.EntryPoint\n ) -> Optional[str]:\n \"\"\"Get the version of a package providing an entry point.\"\"\"\n try:\n module_path = ep.value.split(\":\")[0]\n package_name = module_path.split(\".\")[0]\n dist = importlib.metadata.distribution(package_name)\n return dist.version\n except (importlib.metadata.PackageNotFoundError, IndexError):\n return None\n\n def _check_version_compatibility(self, metadata: PluginMetadata) -> bool:\n \"\"\"Check if plugin is compatible with current ggshield version.\"\"\"\n try:\n current = packaging_version.parse(ggshield_version)\n required = packaging_version.parse(metadata.min_ggshield_version)\n return current >= required\n except Exception as e:\n logger.error(\n \"Failed to parse version for plugin %s (requires %s): %s\",\n metadata.name,\n metadata.min_ggshield_version,\n e,\n )\n return False", "n_chars_compressed": 12506, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_decrypt.py::118": {"resolved_imports": ["ggshield/__main__.py", "ggshield/verticals/hmsl/crypto.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli"], "enclosing_function": "test_hmsl_decrypt_default_behavior", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/utils/test_os.py::105": {"resolved_imports": ["ggshield/utils/os.py"], "used_names": ["cd", "os"], "enclosing_function": "test_cd_context_manager", "extracted_code": "# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 311, "extracted_code_full": "# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_chars_compressed": 311, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_docker.py::90": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/secret_scan_common_options.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/scannable.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/docker.py"], "used_names": ["Mock", "SecretScanCollection", "assert_invoke_ok", "cli", "click", "patch"], "enclosing_function": "test_docker_scan_abort", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 3671, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details", "n_chars_compressed": 3671, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_quota.py::18": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli", "my_vcr"], "enclosing_function": "test_hmsl_quota", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/auth/test_login.py::423": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/constants.py", "ggshield/core/errors.py", "ggshield/utils/datetime.py", "ggshield/verticals/auth/oauth.py"], "used_names": ["ExitCode", "add_instance_config"], "enclosing_function": "test_auth_login_recreates_token_if_deleted_server_side", "extracted_code": "# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 16, "n_files_resolved": 6, "n_chars_extracted": 660, "extracted_code_full": "# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 660, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_enterprise_config.py::27": {"resolved_imports": ["ggshield/core/config/enterprise_config.py"], "used_names": ["PluginConfig"], "enclosing_function": "test_custom_values", "extracted_code": "# Source: ggshield/core/config/enterprise_config.py\nclass PluginConfig:\n \"\"\"Configuration for a single plugin.\"\"\"\n\n enabled: bool = True\n version: Optional[str] = None\n auto_update: bool = True", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 205, "extracted_code_full": "# Source: ggshield/core/config/enterprise_config.py\nclass PluginConfig:\n \"\"\"Configuration for a single plugin.\"\"\"\n\n enabled: bool = True\n version: Optional[str] = None\n auto_update: bool = True", "n_chars_compressed": 205, "compression_ratio": 1.0}, "tests/unit/core/scan/test_id_cache.py::24": {"resolved_imports": ["ggshield/core/scan/id_cache.py"], "used_names": ["FakeFilesystem", "IDCache", "Path", "json"], "enclosing_function": "test_add", "extracted_code": "# Source: ggshield/core/scan/id_cache.py\nclass IDCache:\n \"\"\"\n Stores a list of IDs as JSON in self.cache_path.\n \"\"\"\n\n def __init__(self, cache_path: Path):\n self.cache_path = cache_path\n self._ids: Set[str] = set()\n if self.cache_path.exists():\n self._load()\n\n def __contains__(self, id: str) -> bool:\n return id in self._ids\n\n def add(self, layer_id: str) -> None:\n self._ids.add(layer_id)\n self._save()\n\n def _load(self) -> None:\n try:\n ids = json.loads(self.cache_path.read_text())\n except Exception as exc:\n logger.warning(\"Failed to load cache from %s: %s\", self.cache_path, exc)\n return\n self._ids = set(ids)\n\n def _save(self) -> None:\n text = json.dumps(list(self._ids))\n try:\n self.cache_path.parent.mkdir(parents=True, exist_ok=True)\n self.cache_path.write_text(text)\n except Exception as exc:\n logger.warning(\"Failed to save cache to %s: %s\", self.cache_path, exc)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1059, "extracted_code_full": "# Source: ggshield/core/scan/id_cache.py\nclass IDCache:\n \"\"\"\n Stores a list of IDs as JSON in self.cache_path.\n \"\"\"\n\n def __init__(self, cache_path: Path):\n self.cache_path = cache_path\n self._ids: Set[str] = set()\n if self.cache_path.exists():\n self._load()\n\n def __contains__(self, id: str) -> bool:\n return id in self._ids\n\n def add(self, layer_id: str) -> None:\n self._ids.add(layer_id)\n self._save()\n\n def _load(self) -> None:\n try:\n ids = json.loads(self.cache_path.read_text())\n except Exception as exc:\n logger.warning(\"Failed to load cache from %s: %s\", self.cache_path, exc)\n return\n self._ids = set(ids)\n\n def _save(self) -> None:\n text = json.dumps(list(self._ids))\n try:\n self.cache_path.parent.mkdir(parents=True, exist_ok=True)\n self.cache_path.write_text(text)\n except Exception as exc:\n logger.warning(\"Failed to save cache to %s: %s\", self.cache_path, exc)", "n_chars_compressed": 1059, "compression_ratio": 1.0}, "tests/unit/verticals/secret/output/test_sarif_output.py::277": {"resolved_imports": ["ggshield/core/config/user_config.py", "ggshield/core/scan/commit.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/output/secret_sarif_output_handler.py"], "used_names": ["Commit", "Result", "Results", "SecretConfig", "SecretSARIFOutputHandler", "SecretScanCollection", "json"], "enclosing_function": "test_sarif_output_for_nested_scan", "extracted_code": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Result:\n \"\"\"\n Return model for a scan which zips the information\n between the Scan result and its input file.\n \"\"\"\n\n filename: str # Name of the file/patch scanned\n filemode: Filemode\n path: Path\n url: str\n secrets: List[Secret]\n ignored_secrets_count_by_kind: Counter[IgnoreKind]\n\n @property\n def is_on_patch(self) -> bool:\n return self.filemode != Filemode.FILE\n\n def censor(self) -> None:\n for secret in self.secrets:\n for extended_match in secret.matches:\n cast(ExtendedMatch, extended_match).censor()\n\n @property\n def has_secrets(self) -> bool:\n return len(self.secrets) > 0\n\n @classmethod\n def from_scan_result(\n cls, file: Scannable, scan_result: ScanResult, secret_config: SecretConfig\n ) -> \"Result\":\n \"\"\"Creates a Result from a Scannable and a ScanResult.\n - Removes ignored policy breaks\n - replace matches by ExtendedMatches\n \"\"\"\n\n to_keep: List[Tuple[PolicyBreak, Optional[IgnoreReason]]] = []\n ignored_secrets_count_by_kind = Counter()\n for policy_break in scan_result.policy_breaks:\n ignore_reason = compute_ignore_reason(policy_break, secret_config)\n if ignore_reason is not None:\n if secret_config.all_secrets:\n to_keep.append((policy_break, ignore_reason))\n else:\n ignored_secrets_count_by_kind[ignore_reason.kind] += 1\n else:\n to_keep.append((policy_break, None))\n\n result = Result(\n filename=file.filename,\n filemode=file.filemode,\n path=file.path,\n url=file.url,\n secrets=[],\n ignored_secrets_count_by_kind=ignored_secrets_count_by_kind,\n )\n\n lines = get_lines_from_content(file.content, file.filemode)\n secrets = [\n Secret(\n validity=policy_break.validity,\n known_secret=policy_break.known_secret,\n incident_url=policy_break.incident_url,\n detector_display_name=policy_break.break_type,\n detector_name=policy_break.detector_name,\n detector_group_name=policy_break.detector_group_name,\n documentation_url=policy_break.documentation_url,\n matches=[\n ExtendedMatch.from_match(match, lines, result.is_on_patch)\n for match in policy_break.matches\n ],\n ignore_reason=ignore_reason,\n diff_kind=policy_break.diff_kind,\n is_vaulted=policy_break.is_vaulted,\n vault_type=getattr(policy_break, \"vault_type\", None),\n vault_name=getattr(policy_break, \"vault_name\", None),\n vault_path=getattr(policy_break, \"vault_path\", None),\n vault_path_count=getattr(policy_break, \"vault_path_count\", None),\n )\n for policy_break, ignore_reason in to_keep\n ]\n\n result.secrets = secrets\n return result\n\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)\n\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details\n\n\n# Source: ggshield/verticals/secret/output/secret_sarif_output_handler.py\nclass SecretSARIFOutputHandler(SecretOutputHandler):\n\n def _process_scan_impl(self, scan: SecretScanCollection) -> str:\n incident_details = (\n scan.get_incident_details(self.client)\n if self.with_incident_details and self.client\n else {}\n )\n dct = {\n \"version\": \"2.1.0\",\n \"$schema\": SCHEMA_URL,\n \"runs\": [\n {\n \"tool\": {\n \"driver\": {\n \"organization\": \"GitGuardian\",\n \"name\": \"ggshield\",\n \"informationUri\": \"https://github.com/GitGuardian/ggshield\",\n \"version\": ggshield_version,\n },\n \"extensions\": [\n {\n \"name\": \"secret\",\n \"version\": VERSIONS.secrets_engine_version,\n }\n ],\n },\n \"results\": list(\n _create_sarif_results(scan.get_all_results(), incident_details)\n ),\n }\n ],\n }\n return json.dumps(dct)", "n_imports_parsed": 18, "n_files_resolved": 4, "n_chars_extracted": 13778, "extracted_code_full": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Result:\n \"\"\"\n Return model for a scan which zips the information\n between the Scan result and its input file.\n \"\"\"\n\n filename: str # Name of the file/patch scanned\n filemode: Filemode\n path: Path\n url: str\n secrets: List[Secret]\n ignored_secrets_count_by_kind: Counter[IgnoreKind]\n\n @property\n def is_on_patch(self) -> bool:\n return self.filemode != Filemode.FILE\n\n def censor(self) -> None:\n for secret in self.secrets:\n for extended_match in secret.matches:\n cast(ExtendedMatch, extended_match).censor()\n\n @property\n def has_secrets(self) -> bool:\n return len(self.secrets) > 0\n\n @classmethod\n def from_scan_result(\n cls, file: Scannable, scan_result: ScanResult, secret_config: SecretConfig\n ) -> \"Result\":\n \"\"\"Creates a Result from a Scannable and a ScanResult.\n - Removes ignored policy breaks\n - replace matches by ExtendedMatches\n \"\"\"\n\n to_keep: List[Tuple[PolicyBreak, Optional[IgnoreReason]]] = []\n ignored_secrets_count_by_kind = Counter()\n for policy_break in scan_result.policy_breaks:\n ignore_reason = compute_ignore_reason(policy_break, secret_config)\n if ignore_reason is not None:\n if secret_config.all_secrets:\n to_keep.append((policy_break, ignore_reason))\n else:\n ignored_secrets_count_by_kind[ignore_reason.kind] += 1\n else:\n to_keep.append((policy_break, None))\n\n result = Result(\n filename=file.filename,\n filemode=file.filemode,\n path=file.path,\n url=file.url,\n secrets=[],\n ignored_secrets_count_by_kind=ignored_secrets_count_by_kind,\n )\n\n lines = get_lines_from_content(file.content, file.filemode)\n secrets = [\n Secret(\n validity=policy_break.validity,\n known_secret=policy_break.known_secret,\n incident_url=policy_break.incident_url,\n detector_display_name=policy_break.break_type,\n detector_name=policy_break.detector_name,\n detector_group_name=policy_break.detector_group_name,\n documentation_url=policy_break.documentation_url,\n matches=[\n ExtendedMatch.from_match(match, lines, result.is_on_patch)\n for match in policy_break.matches\n ],\n ignore_reason=ignore_reason,\n diff_kind=policy_break.diff_kind,\n is_vaulted=policy_break.is_vaulted,\n vault_type=getattr(policy_break, \"vault_type\", None),\n vault_name=getattr(policy_break, \"vault_name\", None),\n vault_path=getattr(policy_break, \"vault_path\", None),\n vault_path_count=getattr(policy_break, \"vault_path_count\", None),\n )\n for policy_break, ignore_reason in to_keep\n ]\n\n result.secrets = secrets\n return result\n\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)\n\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details\n\n\n# Source: ggshield/verticals/secret/output/secret_sarif_output_handler.py\nclass SecretSARIFOutputHandler(SecretOutputHandler):\n\n def _process_scan_impl(self, scan: SecretScanCollection) -> str:\n incident_details = (\n scan.get_incident_details(self.client)\n if self.with_incident_details and self.client\n else {}\n )\n dct = {\n \"version\": \"2.1.0\",\n \"$schema\": SCHEMA_URL,\n \"runs\": [\n {\n \"tool\": {\n \"driver\": {\n \"organization\": \"GitGuardian\",\n \"name\": \"ggshield\",\n \"informationUri\": \"https://github.com/GitGuardian/ggshield\",\n \"version\": ggshield_version,\n },\n \"extensions\": [\n {\n \"name\": \"secret\",\n \"version\": VERSIONS.secrets_engine_version,\n }\n ],\n },\n \"results\": list(\n _create_sarif_results(scan.get_all_results(), incident_details)\n ),\n }\n ],\n }\n return json.dumps(dct)", "n_chars_compressed": 13778, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_prepush.py::35": {"resolved_imports": [], "used_names": ["CalledProcessError", "GG_VALID_TOKEN", "Path", "Repository", "pytest", "recreate_censored_content", "run_ggshield"], "enclosing_function": "test_scan_prepush", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/core/scan/test_file.py::131": {"resolved_imports": ["ggshield/core/scan/file.py", "ggshield/core/scan/scannable.py"], "used_names": ["File"], "enclosing_function": "test_file_is_longer_than_if_file_has_been_read", "extracted_code": "# Source: ggshield/core/scan/file.py\nclass File(Scannable):\n \"\"\"Implementation of Scannable for files from the disk.\"\"\"\n\n def __init__(self, path: Union[str, Path]):\n super().__init__()\n self._path = Path(path)\n\n @property\n def url(self) -> str:\n return url_for_path(self._path)\n\n @property\n def filename(self) -> str:\n return str(self._path)\n\n @property\n def path(self) -> Path:\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n if self._utf8_encoded_size is not None:\n # We already have the encoded size, easy\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n with self.path.open(\"rb\") as fp:\n (\n result,\n self._content,\n self._utf8_encoded_size,\n ) = Scannable._is_file_longer_than(fp, max_utf8_encoded_size)\n return result\n\n def _read_content(self) -> None:\n if self._content is None:\n with self.path.open(\"rb\") as f:\n self._content, self._utf8_encoded_size = Scannable._decode_bytes(\n f.read()\n )", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 1185, "extracted_code_full": "# Source: ggshield/core/scan/file.py\nclass File(Scannable):\n \"\"\"Implementation of Scannable for files from the disk.\"\"\"\n\n def __init__(self, path: Union[str, Path]):\n super().__init__()\n self._path = Path(path)\n\n @property\n def url(self) -> str:\n return url_for_path(self._path)\n\n @property\n def filename(self) -> str:\n return str(self._path)\n\n @property\n def path(self) -> Path:\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n if self._utf8_encoded_size is not None:\n # We already have the encoded size, easy\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n with self.path.open(\"rb\") as fp:\n (\n result,\n self._content,\n self._utf8_encoded_size,\n ) = Scannable._is_file_longer_than(fp, max_utf8_encoded_size)\n return result\n\n def _read_content(self) -> None:\n if self._content is None:\n with self.path.open(\"rb\") as f:\n self._content, self._utf8_encoded_size = Scannable._decode_bytes(\n f.read()\n )", "n_chars_compressed": 1185, "compression_ratio": 1.0}, "tests/unit/cmd/honeytoken/test_honeytoken_with_context.py::47": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py"], "used_names": ["CliRunner", "assert_invoke_ok", "cli", "my_vcr"], "enclosing_function": "test_honeytoken_create_with_context_ok_no_name", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/verticals/hmsl/secret_manager/hashicorp_vault/test_api_client.py::302": {"resolved_imports": ["ggshield/verticals/hmsl/secret_manager/hashicorp_vault/api_client.py", "ggshield/verticals/hmsl/secret_manager/hashicorp_vault/exceptions.py", "ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py"], "used_names": ["VaultAPIClient", "VaultKvMount", "VaultNotFoundItemError", "patch"], "enclosing_function": "test_get_secrets_or_empty_vault_not_found_item_error", "extracted_code": "# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/api_client.py\nclass VaultAPIClient:\n \"\"\"Client to interact with Vault API.\"\"\"\n\n def __init__(self, vault_url: str, api_token: str) -> None:\n self.session = requests.Session()\n self.session.headers[\"X-Vault-Token\"] = api_token\n\n if not vault_url.startswith(\"http://\") and not vault_url.startswith(\"https://\"):\n vault_url = f\"https://{vault_url}\"\n try:\n self.vault_url = urlparse(vault_url).geturl()\n except ValueError:\n raise VaultInvalidUrlError(\n f\"cannot parse the Vault URL '{vault_url}'. Are you sure it is valid?\"\n )\n\n def _make_request(\n self, endpoint: str, method: str = \"GET\", api_version: str = \"v1\"\n ) -> Dict[str, Any]:\n \"\"\" \"\n Make request to the API.\n \"\"\"\n api_res = self.session.request(\n method, f\"{self.vault_url}/{api_version}/{endpoint}\"\n )\n api_res.raise_for_status()\n\n return api_res.json()\n\n def get_kv_mounts(self) -> Generator[VaultKvMount, None, None]:\n \"\"\"\n Get all kv mounts for the Vault instance.\n\n Will try the /sys/mounts endpoint first, and if there is a forbidden error\n fallback to the /sys/internal/ui internal endpoint.\n \"\"\"\n\n try:\n api_res = self._make_request(\"sys/mounts\")[\"data\"]\n except requests.HTTPError:\n api_res = self._make_request(\"sys/internal/ui/mounts\")[\"data\"][\"secret\"]\n\n for key, value in api_res.items():\n if value[\"type\"] != \"kv\":\n continue\n\n yield VaultKvMount(\n name=key.rstrip(\"/\"), # remove trailing slash\n version=value[\"options\"][\"version\"],\n )\n\n def list_kv_items(self, mount: VaultKvMount, path: str) -> List[str]:\n logger.debug(f\"Listing kv items for mount {mount.name} at {path}\")\n\n api_endpoint = (\n f\"{mount.name}/metadata/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n\n try:\n api_res = self._make_request(api_endpoint, method=\"LIST\")\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n # The API return 404 when trying to list items when the path is a file\n # and not a directory\n if exc.response.status_code == 404:\n raise VaultPathIsNotADirectoryError()\n\n raise exc\n\n return [item.rstrip(\"/\") for item in api_res[\"data\"][\"keys\"]]\n\n def get_kv_secrets(self, mount: VaultKvMount, path: str) -> List[Tuple[str, str]]:\n \"\"\"\n Get secrets from the specified mount at the specified path.\n\n Returns a list of tuples containing secret key and secret value\n \"\"\"\n\n logger.debug(f\"Getting secrets at {path}\")\n api_endpoint = (\n f\"{mount.name}/data/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n try:\n api_res = self._make_request(api_endpoint)\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n if exc.response.status_code == 404:\n raise VaultNotFoundItemError(\n f\"{path} was not found: it's either not a file, \"\n \"was deleted or cannot be accessed with the current token\"\n )\n\n raise exc\n\n data = api_res[\"data\"][\"data\"] if mount.version == \"2\" else api_res[\"data\"]\n return [\n (f\"{path}/{secret_name}\", secret_value)\n for secret_name, secret_value in data.items()\n ]\n\n def _get_secrets_or_empty(\n self, mount: VaultKvMount, folder_path: str\n ) -> VaultSecrets:\n \"\"\"\n Call get_kv_secrets on the given mount and folder path.\n\n Return the secrets or an empty list if VaultNotFoundItemError was raised.\n \"\"\"\n try:\n return VaultSecrets(\n secrets=self.get_kv_secrets(mount, folder_path),\n not_fetched_paths=[],\n )\n except VaultNotFoundItemError as exc:\n logger.debug(f\"Not found error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n def _get_secrets_from_path(\n self, mount: VaultKvMount, folder_path: str, recursive: bool\n ) -> VaultSecrets:\n \"\"\"\n Get the secrets on the given mount and folder path.\n If recursive is True, iterate recursively on subfolders.\n\n Return the secrets or an empty list if errors were raised.\n \"\"\"\n # Get current directory secret\n try:\n subfolders = self.list_kv_items(mount, folder_path)\n except VaultPathIsNotADirectoryError:\n return self._get_secrets_or_empty(mount, folder_path)\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n if not recursive:\n return VaultSecrets(secrets=[], not_fetched_paths=[])\n\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for subfolder in subfolders:\n subfolder_result = self._get_secrets_from_path(\n mount, f\"{folder_path}/{subfolder}\", True\n )\n result.secrets += subfolder_result.secrets\n result.not_fetched_paths += subfolder_result.not_fetched_paths\n\n return result\n\n def get_secrets(\n self, mount: VaultKvMount, path: str, recursive: bool\n ) -> VaultSecrets:\n # Check first if it's a directory\n try:\n keys = self.list_kv_items(mount, path)\n except VaultPathIsNotADirectoryError:\n # If it's a file, return directly\n return self._get_secrets_or_empty(mount, path)\n\n # If it's a folder, get secrets of the folder\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for folder in keys:\n folder_path = f\"{path}/{folder}\".strip(\"/\")\n folder_result = self._get_secrets_from_path(mount, folder_path, recursive)\n result.secrets += folder_result.secrets\n result.not_fetched_paths += folder_result.not_fetched_paths\n\n return result\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/exceptions.py\nclass VaultNotFoundItemError(Exception):\n \"\"\"Raised when list_kv_items was called on a directory and not a file.\"\"\"\n\n pass\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py\nclass VaultKvMount(VaultMount):\n \"\"\"\n Model to represent a Vault KV mount.\n \"\"\"\n\n version: str", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 7219, "extracted_code_full": "# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/api_client.py\nclass VaultAPIClient:\n \"\"\"Client to interact with Vault API.\"\"\"\n\n def __init__(self, vault_url: str, api_token: str) -> None:\n self.session = requests.Session()\n self.session.headers[\"X-Vault-Token\"] = api_token\n\n if not vault_url.startswith(\"http://\") and not vault_url.startswith(\"https://\"):\n vault_url = f\"https://{vault_url}\"\n try:\n self.vault_url = urlparse(vault_url).geturl()\n except ValueError:\n raise VaultInvalidUrlError(\n f\"cannot parse the Vault URL '{vault_url}'. Are you sure it is valid?\"\n )\n\n def _make_request(\n self, endpoint: str, method: str = \"GET\", api_version: str = \"v1\"\n ) -> Dict[str, Any]:\n \"\"\" \"\n Make request to the API.\n \"\"\"\n api_res = self.session.request(\n method, f\"{self.vault_url}/{api_version}/{endpoint}\"\n )\n api_res.raise_for_status()\n\n return api_res.json()\n\n def get_kv_mounts(self) -> Generator[VaultKvMount, None, None]:\n \"\"\"\n Get all kv mounts for the Vault instance.\n\n Will try the /sys/mounts endpoint first, and if there is a forbidden error\n fallback to the /sys/internal/ui internal endpoint.\n \"\"\"\n\n try:\n api_res = self._make_request(\"sys/mounts\")[\"data\"]\n except requests.HTTPError:\n api_res = self._make_request(\"sys/internal/ui/mounts\")[\"data\"][\"secret\"]\n\n for key, value in api_res.items():\n if value[\"type\"] != \"kv\":\n continue\n\n yield VaultKvMount(\n name=key.rstrip(\"/\"), # remove trailing slash\n version=value[\"options\"][\"version\"],\n )\n\n def list_kv_items(self, mount: VaultKvMount, path: str) -> List[str]:\n logger.debug(f\"Listing kv items for mount {mount.name} at {path}\")\n\n api_endpoint = (\n f\"{mount.name}/metadata/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n\n try:\n api_res = self._make_request(api_endpoint, method=\"LIST\")\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n # The API return 404 when trying to list items when the path is a file\n # and not a directory\n if exc.response.status_code == 404:\n raise VaultPathIsNotADirectoryError()\n\n raise exc\n\n return [item.rstrip(\"/\") for item in api_res[\"data\"][\"keys\"]]\n\n def get_kv_secrets(self, mount: VaultKvMount, path: str) -> List[Tuple[str, str]]:\n \"\"\"\n Get secrets from the specified mount at the specified path.\n\n Returns a list of tuples containing secret key and secret value\n \"\"\"\n\n logger.debug(f\"Getting secrets at {path}\")\n api_endpoint = (\n f\"{mount.name}/data/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n try:\n api_res = self._make_request(api_endpoint)\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n if exc.response.status_code == 404:\n raise VaultNotFoundItemError(\n f\"{path} was not found: it's either not a file, \"\n \"was deleted or cannot be accessed with the current token\"\n )\n\n raise exc\n\n data = api_res[\"data\"][\"data\"] if mount.version == \"2\" else api_res[\"data\"]\n return [\n (f\"{path}/{secret_name}\", secret_value)\n for secret_name, secret_value in data.items()\n ]\n\n def _get_secrets_or_empty(\n self, mount: VaultKvMount, folder_path: str\n ) -> VaultSecrets:\n \"\"\"\n Call get_kv_secrets on the given mount and folder path.\n\n Return the secrets or an empty list if VaultNotFoundItemError was raised.\n \"\"\"\n try:\n return VaultSecrets(\n secrets=self.get_kv_secrets(mount, folder_path),\n not_fetched_paths=[],\n )\n except VaultNotFoundItemError as exc:\n logger.debug(f\"Not found error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n def _get_secrets_from_path(\n self, mount: VaultKvMount, folder_path: str, recursive: bool\n ) -> VaultSecrets:\n \"\"\"\n Get the secrets on the given mount and folder path.\n If recursive is True, iterate recursively on subfolders.\n\n Return the secrets or an empty list if errors were raised.\n \"\"\"\n # Get current directory secret\n try:\n subfolders = self.list_kv_items(mount, folder_path)\n except VaultPathIsNotADirectoryError:\n return self._get_secrets_or_empty(mount, folder_path)\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n if not recursive:\n return VaultSecrets(secrets=[], not_fetched_paths=[])\n\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for subfolder in subfolders:\n subfolder_result = self._get_secrets_from_path(\n mount, f\"{folder_path}/{subfolder}\", True\n )\n result.secrets += subfolder_result.secrets\n result.not_fetched_paths += subfolder_result.not_fetched_paths\n\n return result\n\n def get_secrets(\n self, mount: VaultKvMount, path: str, recursive: bool\n ) -> VaultSecrets:\n # Check first if it's a directory\n try:\n keys = self.list_kv_items(mount, path)\n except VaultPathIsNotADirectoryError:\n # If it's a file, return directly\n return self._get_secrets_or_empty(mount, path)\n\n # If it's a folder, get secrets of the folder\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for folder in keys:\n folder_path = f\"{path}/{folder}\".strip(\"/\")\n folder_result = self._get_secrets_from_path(mount, folder_path, recursive)\n result.secrets += folder_result.secrets\n result.not_fetched_paths += folder_result.not_fetched_paths\n\n return result\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/exceptions.py\nclass VaultNotFoundItemError(Exception):\n \"\"\"Raised when list_kv_items was called on a directory and not a file.\"\"\"\n\n pass\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py\nclass VaultKvMount(VaultMount):\n \"\"\"\n Model to represent a Vault KV mount.\n \"\"\"\n\n version: str", "n_chars_compressed": 7219, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_fingerprint.py::133": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/hmsl/decrypt.py", "ggshield/verticals/hmsl/client.py", "ggshield/verticals/hmsl/crypto.py"], "used_names": ["CliRunner", "PREFIX_LENGTH", "assert_invoke_ok", "cli", "hash_string"], "enclosing_function": "test_hmsl_fingerprint_default_behavior", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/hmsl/client.py\nPREFIX_LENGTH = 5\n\n\n# Source: ggshield/verticals/hmsl/crypto.py\ndef hash_string(text: str) -> str:\n return (\n Scrypt(salt=_PEPPER, n=2048, r=8, p=1, length=32)\n .derive(text.encode(\"utf-8\"))\n .hex()\n )", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 1655, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/hmsl/client.py\nPREFIX_LENGTH = 5\n\n\n# Source: ggshield/verticals/hmsl/crypto.py\ndef hash_string(text: str) -> str:\n return (\n Scrypt(salt=_PEPPER, n=2048, r=8, p=1, length=32)\n .derive(text.encode(\"utf-8\"))\n .hex()\n )", "n_chars_compressed": 1655, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/check_secret_manager/test_hashicorp_vault.py::183": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/hmsl/check_secret_manager/hashicorp_vault.py", "ggshield/verticals/hmsl/collection.py", "ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py"], "used_names": ["Mock", "NAMING_STRATEGIES", "PreparedSecrets", "SecretWithKey", "VaultKvMount", "VaultSecrets", "cli", "patch", "pytest"], "enclosing_function": "test_check_hashicorp_vault_cmd", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/hmsl/collection.py\nclass PreparedSecrets:\n payload: Set[str]\n mapping: Dict[str, str]\n\nclass SecretWithKey:\n key: Optional[str]\n value: str\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py\nclass VaultKvMount(VaultMount):\n \"\"\"\n Model to represent a Vault KV mount.\n \"\"\"\n\n version: str\n\nclass VaultSecrets:\n \"\"\"\n Model to hold secrets fetched from the vault.\n\n The aim is to include the secrets themselves and the not_fetched_paths\n list to communicate the paths that could not be fetched\n (permission denied, errors etc.).\n \"\"\"\n\n secrets: List[Tuple[str, str]]\n not_fetched_paths: List[str]", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2077, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/verticals/hmsl/collection.py\nclass PreparedSecrets:\n payload: Set[str]\n mapping: Dict[str, str]\n\nclass SecretWithKey:\n key: Optional[str]\n value: str\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py\nclass VaultKvMount(VaultMount):\n \"\"\"\n Model to represent a Vault KV mount.\n \"\"\"\n\n version: str\n\nclass VaultSecrets:\n \"\"\"\n Model to hold secrets fetched from the vault.\n\n The aim is to include the secrets themselves and the not_fetched_paths\n list to communicate the paths that could not be fetched\n (permission denied, errors etc.).\n \"\"\"\n\n secrets: List[Tuple[str, str]]\n not_fetched_paths: List[str]", "n_chars_compressed": 2077, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_prereceive.py::44": {"resolved_imports": [], "used_names": ["CalledProcessError", "GG_VALID_TOKEN", "Path", "Repository", "pytest", "recreate_censored_content"], "enclosing_function": "test_scan_prereceive", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/core/plugin/test_platform.py::21": {"resolved_imports": ["ggshield/core/plugin/platform.py"], "used_names": ["PlatformInfo"], "enclosing_function": "test_platform_info_creation", "extracted_code": "# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 159, "extracted_code_full": "# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str", "n_chars_compressed": 159, "compression_ratio": 1.0}, "tests/unit/cmd/test_config.py::101": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/config/user_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py", "ggshield/utils/os.py"], "used_names": ["All", "Any", "ExitCode", "In", "Match", "S", "json", "jsonschema"], "enclosing_function": "test_list_json_output", "extracted_code": "# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 15, "n_files_resolved": 6, "n_chars_extracted": 660, "extracted_code_full": "# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 660, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_registry.py::49": {"resolved_imports": ["ggshield/core/plugin/base.py", "ggshield/core/plugin/registry.py"], "used_names": ["PluginRegistry"], "enclosing_function": "test_register_plugin", "extracted_code": "# Source: ggshield/core/plugin/registry.py\nclass PluginRegistry:\n \"\"\"Central registry for all loaded plugins and their capabilities.\"\"\"\n\n _plugins: Dict[str, GGShieldPlugin] = field(default_factory=dict)\n _commands: List[click.Command] = field(default_factory=list)\n\n def register_plugin(self, plugin: GGShieldPlugin) -> None:\n \"\"\"Register a loaded plugin.\"\"\"\n self._plugins[plugin.metadata.name] = plugin\n\n def register_command(self, command: click.Command) -> None:\n \"\"\"Register a CLI command provided by a plugin.\"\"\"\n self._commands.append(command)\n\n def get_plugin(self, name: str) -> Optional[GGShieldPlugin]:\n \"\"\"Get a loaded plugin by name.\"\"\"\n return self._plugins.get(name)\n\n def get_all_plugins(self) -> Dict[str, GGShieldPlugin]:\n \"\"\"Get all loaded plugins.\"\"\"\n return self._plugins.copy()\n\n def get_commands(self) -> List[click.Command]:\n \"\"\"Get all plugin-provided commands.\"\"\"\n return self._commands.copy()", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1014, "extracted_code_full": "# Source: ggshield/core/plugin/registry.py\nclass PluginRegistry:\n \"\"\"Central registry for all loaded plugins and their capabilities.\"\"\"\n\n _plugins: Dict[str, GGShieldPlugin] = field(default_factory=dict)\n _commands: List[click.Command] = field(default_factory=list)\n\n def register_plugin(self, plugin: GGShieldPlugin) -> None:\n \"\"\"Register a loaded plugin.\"\"\"\n self._plugins[plugin.metadata.name] = plugin\n\n def register_command(self, command: click.Command) -> None:\n \"\"\"Register a CLI command provided by a plugin.\"\"\"\n self._commands.append(command)\n\n def get_plugin(self, name: str) -> Optional[GGShieldPlugin]:\n \"\"\"Get a loaded plugin by name.\"\"\"\n return self._plugins.get(name)\n\n def get_all_plugins(self) -> Dict[str, GGShieldPlugin]:\n \"\"\"Get all loaded plugins.\"\"\"\n return self._plugins.copy()\n\n def get_commands(self) -> List[click.Command]:\n \"\"\"Get all plugin-provided commands.\"\"\"\n return self._commands.copy()", "n_chars_compressed": 1014, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_wheel_utils.py::195": {"resolved_imports": ["ggshield/core/plugin/wheel_utils.py"], "used_names": ["WheelMetadata"], "enclosing_function": "test_dataclass_fields", "extracted_code": "# Source: ggshield/core/plugin/wheel_utils.py\nclass WheelMetadata:\n \"\"\"Metadata extracted from a wheel file.\"\"\"\n\n name: str\n version: str\n summary: Optional[str] = None\n author: Optional[str] = None\n license: Optional[str] = None", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 247, "extracted_code_full": "# Source: ggshield/core/plugin/wheel_utils.py\nclass WheelMetadata:\n \"\"\"Metadata extracted from a wheel file.\"\"\"\n\n name: str\n version: str\n summary: Optional[str] = None\n author: Optional[str] = None\n license: Optional[str] = None", "n_chars_compressed": 247, "compression_ratio": 1.0}, "tests/unit/core/config/test_utils.py::71": {"resolved_imports": ["ggshield/core/config/utils.py", "ggshield/utils/os.py"], "used_names": ["update_dict_from_other"], "enclosing_function": "test_update_dict_from_other", "extracted_code": "# Source: ggshield/core/config/utils.py\ndef update_dict_from_other(dct: Dict[str, Any], other: Dict[str, Any]) -> None:\n \"\"\"\n Merge values from `other` dict into `dct`. List entries are appended, sets are\n updated, dicts are merged.\n\n The merge happens in-place: `dct` is modified.\n \"\"\"\n for key, value in other.items():\n try:\n if value is None:\n continue\n if isinstance(value, list):\n dct.setdefault(key, []).extend(value)\n elif isinstance(value, set):\n dct.setdefault(key, set()).update(value)\n elif isinstance(value, dict):\n update_dict_from_other(dct.setdefault(key, {}), value)\n else:\n dct[key] = value\n except AttributeError:\n raise UnexpectedError(f\"Failed to load configuration on key '{key}'\")", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 875, "extracted_code_full": "# Source: ggshield/core/config/utils.py\ndef update_dict_from_other(dct: Dict[str, Any], other: Dict[str, Any]) -> None:\n \"\"\"\n Merge values from `other` dict into `dct`. List entries are appended, sets are\n updated, dicts are merged.\n\n The merge happens in-place: `dct` is modified.\n \"\"\"\n for key, value in other.items():\n try:\n if value is None:\n continue\n if isinstance(value, list):\n dct.setdefault(key, []).extend(value)\n elif isinstance(value, set):\n dct.setdefault(key, set()).update(value)\n elif isinstance(value, dict):\n update_dict_from_other(dct.setdefault(key, {}), value)\n else:\n dct[key] = value\n except AttributeError:\n raise UnexpectedError(f\"Failed to load configuration on key '{key}'\")", "n_chars_compressed": 875, "compression_ratio": 1.0}, "tests/unit/core/test_check_updates.py::73": {"resolved_imports": ["ggshield/core/__init__.py", "ggshield/core/check_updates.py"], "used_names": ["FakeFilesystem", "Mock", "MonkeyPatch", "check_for_updates", "core", "patch"], "enclosing_function": "test_check_for_updates_twice_only_notifies_once", "extracted_code": "# Source: ggshield/core/check_updates.py\ndef check_for_updates() -> Optional[str]:\n \"\"\"\n Check for ggshield updates on GitHub. Return the latest version if available.\n Query GitHub API at most once per day and save locally the latest version in a file.\n \"\"\"\n check_at = load_last_check_time()\n\n if check_at is not None and (time.time() - check_at < 24 * 60 * 60):\n # We checked today, no need to check again\n return None\n\n logger.debug(\"Checking the latest released version of ggshield...\")\n\n # Save check time now so that it is saved even if the check fails. This ensures we\n # don't try for every command if the user does not have network access.\n try:\n save_last_check_time(time.time())\n except Exception as e:\n logger.warning(\"Could not save time of version check to cache: %s\", repr(e))\n # Do not continue if we can't save check time. If we continue we are going to\n # send requests to api.github.com every time ggshield is called.\n return None\n\n try:\n resp = requests.get(\n \"https://api.github.com/repos/GitGuardian/GGShield/releases/latest\",\n headers={\n \"Accept\": \"application/vnd.github+json\",\n \"User-Agent\": f\"GGShield {__version__}\",\n \"X-Github-Api-Version\": \"2022-11-28\",\n },\n timeout=CHECK_TIMEOUT,\n )\n except Exception as e:\n logger.warning(\"Failed to connect to api.github.com: %s\", repr(e))\n return None\n\n if resp.status_code != 200:\n # Handle GitHub rate limit responses gracefully\n # https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#rate-limiting\n if int(resp.headers.get(\"X-RateLimit-Remaining\", -1)) == 0:\n logger.warning(\"GitHub rate limit exceeded - rescheduling update check\")\n\n # Reset the next update check based on when the GH API quota resets\n check_at = int(resp.headers.get(\"X-RateLimit-Reset\", -1)) - 24 * 60 * 60\n if check_at < 0:\n # Somehow we've hit the rate limit and the reset header is missing\n # This can only happen if GH changes their responses\n logger.warning(\"Failed rescheduling update check\")\n return None\n\n try:\n save_last_check_time(check_at)\n except Exception as e:\n logger.warning(\n \"Could not save time of version check to cache: %s\", repr(e)\n )\n\n return None\n\n logger.warning(\"Failed to check: %s\", resp.text)\n return None\n\n try:\n data = resp.json()\n latest_version: str = data[\"tag_name\"][1:]\n\n current_version_split = _split_version(__version__)\n latest_version_split = _split_version(latest_version)\n except Exception as e:\n logger.warning(\"Failed to parse response: %s\", repr(e))\n return None\n\n if current_version_split < latest_version_split:\n return latest_version\n return None", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 3076, "extracted_code_full": "# Source: ggshield/core/check_updates.py\ndef check_for_updates() -> Optional[str]:\n \"\"\"\n Check for ggshield updates on GitHub. Return the latest version if available.\n Query GitHub API at most once per day and save locally the latest version in a file.\n \"\"\"\n check_at = load_last_check_time()\n\n if check_at is not None and (time.time() - check_at < 24 * 60 * 60):\n # We checked today, no need to check again\n return None\n\n logger.debug(\"Checking the latest released version of ggshield...\")\n\n # Save check time now so that it is saved even if the check fails. This ensures we\n # don't try for every command if the user does not have network access.\n try:\n save_last_check_time(time.time())\n except Exception as e:\n logger.warning(\"Could not save time of version check to cache: %s\", repr(e))\n # Do not continue if we can't save check time. If we continue we are going to\n # send requests to api.github.com every time ggshield is called.\n return None\n\n try:\n resp = requests.get(\n \"https://api.github.com/repos/GitGuardian/GGShield/releases/latest\",\n headers={\n \"Accept\": \"application/vnd.github+json\",\n \"User-Agent\": f\"GGShield {__version__}\",\n \"X-Github-Api-Version\": \"2022-11-28\",\n },\n timeout=CHECK_TIMEOUT,\n )\n except Exception as e:\n logger.warning(\"Failed to connect to api.github.com: %s\", repr(e))\n return None\n\n if resp.status_code != 200:\n # Handle GitHub rate limit responses gracefully\n # https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#rate-limiting\n if int(resp.headers.get(\"X-RateLimit-Remaining\", -1)) == 0:\n logger.warning(\"GitHub rate limit exceeded - rescheduling update check\")\n\n # Reset the next update check based on when the GH API quota resets\n check_at = int(resp.headers.get(\"X-RateLimit-Reset\", -1)) - 24 * 60 * 60\n if check_at < 0:\n # Somehow we've hit the rate limit and the reset header is missing\n # This can only happen if GH changes their responses\n logger.warning(\"Failed rescheduling update check\")\n return None\n\n try:\n save_last_check_time(check_at)\n except Exception as e:\n logger.warning(\n \"Could not save time of version check to cache: %s\", repr(e)\n )\n\n return None\n\n logger.warning(\"Failed to check: %s\", resp.text)\n return None\n\n try:\n data = resp.json()\n latest_version: str = data[\"tag_name\"][1:]\n\n current_version_split = _split_version(__version__)\n latest_version_split = _split_version(latest_version)\n except Exception as e:\n logger.warning(\"Failed to parse response: %s\", repr(e))\n return None\n\n if current_version_split < latest_version_split:\n return latest_version\n return None", "n_chars_compressed": 3076, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_platform.py::72": {"resolved_imports": ["ggshield/core/plugin/platform.py"], "used_names": ["get_platform_info", "patch"], "enclosing_function": "test_detect_arm64", "extracted_code": "# Source: ggshield/core/plugin/platform.py\ndef get_platform_info() -> PlatformInfo:\n \"\"\"Detect current platform for wheel selection.\"\"\"\n system = platform.system().lower()\n if system == \"darwin\":\n os_name = \"macosx\"\n elif system == \"linux\":\n os_name = \"linux\"\n elif system == \"windows\":\n os_name = \"win\"\n else:\n os_name = system\n\n # Detect architecture\n machine = platform.machine().lower()\n if machine in (\"arm64\", \"aarch64\"):\n arch = \"arm64\"\n elif machine in (\"x86_64\", \"amd64\"):\n arch = \"x86_64\"\n else:\n arch = machine\n\n # Detect Python version for ABI\n python_abi = f\"cp{sys.version_info.major}{sys.version_info.minor}\"\n\n return PlatformInfo(os=os_name, arch=arch, python_abi=python_abi)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 782, "extracted_code_full": "# Source: ggshield/core/plugin/platform.py\ndef get_platform_info() -> PlatformInfo:\n \"\"\"Detect current platform for wheel selection.\"\"\"\n system = platform.system().lower()\n if system == \"darwin\":\n os_name = \"macosx\"\n elif system == \"linux\":\n os_name = \"linux\"\n elif system == \"windows\":\n os_name = \"win\"\n else:\n os_name = system\n\n # Detect architecture\n machine = platform.machine().lower()\n if machine in (\"arm64\", \"aarch64\"):\n arch = \"arm64\"\n elif machine in (\"x86_64\", \"amd64\"):\n arch = \"x86_64\"\n else:\n arch = machine\n\n # Detect Python version for ABI\n python_abi = f\"cp{sys.version_info.major}{sys.version_info.minor}\"\n\n return PlatformInfo(os=os_name, arch=arch, python_abi=python_abi)", "n_chars_compressed": 782, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_ci.py::158": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/__init__.py", "ggshield/core/ui/__init__.py", "ggshield/core/errors.py", "ggshield/core/git_hooks/ci/commit_range.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["Dict", "Mock", "assert_invoke_ok", "cli", "click", "patch", "pytest"], "enclosing_function": "test_ci_cmd_uses_right_mode_header", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 16, "n_files_resolved": 7, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_query.py::23": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli", "my_vcr"], "enclosing_function": "test_hmsl_query_prefix", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/test_ignore.py::124": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/ignore.py", "ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Cache", "Commit", "Config", "Mock", "ScanContext", "ScanMode", "SecretScanner", "_MULTIPLE_SECRETS_PATCH", "ignore_last_found", "my_vcr"], "enclosing_function": "test_cache_catches_last_found_secrets", "extracted_code": "# Source: ggshield/cmd/secret/ignore.py\ndef ignore_last_found(config: Config, cache: Cache) -> int:\n \"\"\"\n Add last found secrets from .cache_ggshield into ignored_matches\n in the local .gitguardian.yaml config file so that they are ignored on next run\n Secrets are added as `hash`\n \"\"\"\n for secret in cache.last_found_secrets:\n config.add_ignored_match(secret)\n return len(cache.last_found_secrets)\n\n\n# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_imports_parsed": 14, "n_files_resolved": 11, "n_chars_extracted": 24546, "extracted_code_full": "# Source: ggshield/cmd/secret/ignore.py\ndef ignore_last_found(config: Config, cache: Cache) -> int:\n \"\"\"\n Add last found secrets from .cache_ggshield into ignored_matches\n in the local .gitguardian.yaml config file so that they are ignored on next run\n Secrets are added as `hash`\n \"\"\"\n for secret in cache.last_found_secrets:\n config.add_ignored_match(secret)\n return len(cache.last_found_secrets)\n\n\n# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_chars_compressed": 24546, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_platform.py::134": {"resolved_imports": ["ggshield/core/plugin/platform.py"], "used_names": ["PlatformInfo", "get_wheel_platform_tags", "patch"], "enclosing_function": "test_returns_list_of_tags", "extracted_code": "# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str\n\ndef get_wheel_platform_tags() -> List[str]:\n \"\"\"Get list of compatible wheel platform tags for current system.\"\"\"\n info = get_platform_info()\n tags = [format_platform_tag(info)]\n\n if info.arch == \"arm64\":\n tags.append(f\"{info.os}-aarch64\")\n elif info.arch == \"x86_64\":\n tags.append(f\"{info.os}-amd64\")\n\n return tags", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 508, "extracted_code_full": "# Source: ggshield/core/plugin/platform.py\nclass PlatformInfo:\n \"\"\"Information about the current platform.\"\"\"\n\n os: str\n arch: str\n python_abi: str\n\ndef get_wheel_platform_tags() -> List[str]:\n \"\"\"Get list of compatible wheel platform tags for current system.\"\"\"\n info = get_platform_info()\n tags = [format_platform_tag(info)]\n\n if info.arch == \"arm64\":\n tags.append(f\"{info.os}-aarch64\")\n elif info.arch == \"x86_64\":\n tags.append(f\"{info.os}-amd64\")\n\n return tags", "n_chars_compressed": 508, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_wheel_utils.py::64": {"resolved_imports": ["ggshield/core/plugin/wheel_utils.py"], "used_names": ["Path", "extract_wheel_metadata"], "enclosing_function": "test_extract_valid_wheel", "extracted_code": "# Source: ggshield/core/plugin/wheel_utils.py\ndef extract_wheel_metadata(wheel_path: Path) -> WheelMetadata:\n \"\"\"\n Extract metadata from a wheel file.\n\n Reads the METADATA file from the wheel's dist-info directory.\n\n Args:\n wheel_path: Path to the wheel file.\n\n Returns:\n WheelMetadata with name, version, and optional fields.\n\n Raises:\n InvalidWheelError: If the wheel is not a valid ZIP file.\n MetadataNotFoundError: If METADATA file is not found.\n WheelError: For other parsing errors.\n \"\"\"\n if not wheel_path.exists():\n raise InvalidWheelError(f\"Wheel file not found: {wheel_path}\")\n\n if not wheel_path.suffix == \".whl\":\n raise InvalidWheelError(f\"Not a wheel file: {wheel_path}\")\n\n try:\n with ZipFile(wheel_path, \"r\") as zf:\n metadata_path = _find_metadata_file(zf)\n if metadata_path is None:\n raise MetadataNotFoundError(\n f\"METADATA file not found in wheel: {wheel_path}\"\n )\n\n metadata_content = zf.read(metadata_path).decode(\"utf-8\")\n return _parse_metadata(metadata_content)\n\n except BadZipFile as e:\n raise InvalidWheelError(f\"Invalid wheel file (not a valid ZIP): {e}\") from e", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1276, "extracted_code_full": "# Source: ggshield/core/plugin/wheel_utils.py\ndef extract_wheel_metadata(wheel_path: Path) -> WheelMetadata:\n \"\"\"\n Extract metadata from a wheel file.\n\n Reads the METADATA file from the wheel's dist-info directory.\n\n Args:\n wheel_path: Path to the wheel file.\n\n Returns:\n WheelMetadata with name, version, and optional fields.\n\n Raises:\n InvalidWheelError: If the wheel is not a valid ZIP file.\n MetadataNotFoundError: If METADATA file is not found.\n WheelError: For other parsing errors.\n \"\"\"\n if not wheel_path.exists():\n raise InvalidWheelError(f\"Wheel file not found: {wheel_path}\")\n\n if not wheel_path.suffix == \".whl\":\n raise InvalidWheelError(f\"Not a wheel file: {wheel_path}\")\n\n try:\n with ZipFile(wheel_path, \"r\") as zf:\n metadata_path = _find_metadata_file(zf)\n if metadata_path is None:\n raise MetadataNotFoundError(\n f\"METADATA file not found in wheel: {wheel_path}\"\n )\n\n metadata_content = zf.read(metadata_path).decode(\"utf-8\")\n return _parse_metadata(metadata_content)\n\n except BadZipFile as e:\n raise InvalidWheelError(f\"Invalid wheel file (not a valid ZIP): {e}\") from e", "n_chars_compressed": 1276, "compression_ratio": 1.0}, "tests/unit/cmd/test_status.py::39": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/utils/os.py"], "used_names": ["All", "ConfigSource", "In", "Match", "S", "assert_invoke_ok", "cli", "json", "jsonschema", "my_vcr"], "enclosing_function": "test_api_status", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass ConfigSource(Enum):\n \"\"\"\n Enum of the different sources of configuration\n where an API key or instance URL can come from\n \"\"\"\n\n CMD_OPTION = \"command line option\"\n DOTENV = \".env file\"\n ENV_VAR = \"environment variable\"\n USER_CONFIG = \"user config\"\n DEFAULT = \"default\"", "n_imports_parsed": 11, "n_files_resolved": 3, "n_chars_extracted": 1725, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass ConfigSource(Enum):\n \"\"\"\n Enum of the different sources of configuration\n where an API key or instance URL can come from\n \"\"\"\n\n CMD_OPTION = \"command line option\"\n DOTENV = \".env file\"\n ENV_VAR = \"environment variable\"\n USER_CONFIG = \"user config\"\n DEFAULT = \"default\"", "n_chars_compressed": 1725, "compression_ratio": 1.0}, "tests/unit/core/config/test_config.py::221": {"resolved_imports": ["ggshield/core/config/auth_config.py", "ggshield/core/config/config.py", "ggshield/core/config/utils.py", "ggshield/core/constants.py", "ggshield/core/errors.py", "ggshield/core/url_utils.py"], "used_names": ["Config"], "enclosing_function": "test_user_config_url_no_configured_instance", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_imports_parsed": 15, "n_files_resolved": 6, "n_chars_extracted": 8037, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_chars_compressed": 8037, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_prepush.py::46": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/secret_scan_common_options.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["CliRunner", "Mock", "assert_invoke_ok", "cli", "patch"], "enclosing_function": "test_prepush_no_commits", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 13, "n_files_resolved": 8, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/test_ignore.py::57": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/ignore.py", "ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Config", "IgnoredMatch", "assert_invoke_ok", "cli", "patch"], "enclosing_function": "test_ignore_sha", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/types.py\nclass IgnoredMatch(FilteredConfig):\n match: str\n name: Optional[str] = None\n\n def __post_init__(self) -> None:\n if self.name is None:\n self.name = \"\"", "n_imports_parsed": 14, "n_files_resolved": 11, "n_chars_extracted": 9632, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/types.py\nclass IgnoredMatch(FilteredConfig):\n match: str\n name: Optional[str] = None\n\n def __post_init__(self) -> None:\n if self.name is None:\n self.name = \"\"", "n_chars_compressed": 9632, "compression_ratio": 1.0}, "tests/unit/cmd/test_status.py::135": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/utils/os.py"], "used_names": ["cli", "mock", "pytest"], "enclosing_function": "test_ssl_verify", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 11, "n_files_resolved": 3, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_repo.py::103": {"resolved_imports": [], "used_names": ["Repository", "run_ggshield_scan"], "enclosing_function": "test_scan_repo_exclude_patterns", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/cmd/test_config.py::261": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/config/user_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py", "ggshield/utils/os.py"], "used_names": ["Config", "ExitCode", "UserConfig", "cd", "find_global_config_path"], "enclosing_function": "test_set_instance", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/user_config.py\nclass UserConfig(FilteredConfig):\n \"\"\"\n Holds all ggshield settings defined by the user in the .gitguardian.yaml files\n (local and global).\n \"\"\"\n\n instance: Optional[str] = None\n exit_zero: bool = False\n verbose: bool = False\n insecure: bool = False\n max_commits_for_hook: int = 50\n secret: SecretConfig = field(default_factory=SecretConfig)\n debug: bool = False\n\n # If we hit any deprecated syntax when loading a configuration file, we do not\n # display them directly, otherwise the messages would also be shown when running\n # `ggshield config migrate`, which would be odd.\n # Instead, we store them in this list and a result_callback() function displays\n # them when we quit. When `config migrate` runs, it clears this list, so nothing\n # gets displayed.\n deprecation_messages: List[str] = field(default_factory=list)\n\n def save(self, config_path: Path) -> None:\n \"\"\"\n Save config to config_path\n \"\"\"\n dct = self.to_config_dict()\n save_yaml_dict(dct, config_path)\n\n def to_config_dict(self) -> Dict[str, Any]:\n dct = self.to_dict()\n default_dct = UserConfig.from_dict({}).to_dict()\n\n dct = remove_common_dict_items(dct, default_dct)\n\n dct[\"version\"] = CURRENT_CONFIG_VERSION\n\n return dct\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> Tuple[\"UserConfig\", Path]:\n \"\"\"\n Load the various user configs files to create a UserConfig object:\n - global user configuration file (in the home)\n - local user configuration file (in the repository)\n\n Returns a UserConfig instance, and the path where updates should be saved\n \"\"\"\n deprecation_messages: List[str] = []\n if config_path:\n logger.debug(\"Loading custom config from %s\", config_path)\n dct = _load_config_dict(config_path, deprecation_messages)\n user_config = UserConfig.from_config_dict(dct)\n user_config.deprecation_messages = deprecation_messages\n return user_config, config_path\n\n user_config_dict: Dict[str, Any] = {}\n global_config_path = find_global_config_path()\n if global_config_path:\n dct = _load_config_dict(global_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n logger.debug(\"Loaded global config from %s\", global_config_path)\n else:\n logger.debug(\"No global config\")\n\n local_config_path = find_local_config_path()\n if local_config_path:\n dct = _load_config_dict(local_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n config_path = local_config_path\n logger.debug(\"Loaded local config from %s\", local_config_path)\n else:\n logger.debug(\"No local config\")\n\n user_config = UserConfig.from_config_dict(user_config_dict)\n user_config.deprecation_messages = deprecation_messages\n\n if config_path is None:\n config_path = Path(DEFAULT_LOCAL_CONFIG_PATH)\n return user_config, config_path\n\n @staticmethod\n def from_config_dict(data: Dict[str, Any]) -> \"UserConfig\":\n \"\"\"Create a UserConfig instance. In case of error, format it and raise\n ParseError.\"\"\"\n try:\n return UserConfig.from_dict(data)\n except ValidationError as exc:\n message = format_validation_error(exc)\n raise ParseError(message) from exc\n\n\n# Source: ggshield/core/config/utils.py\ndef find_global_config_path(*, to_write: Literal[False] = False) -> Optional[Path]: ...\n\ndef find_global_config_path(*, to_write: Literal[True]) -> Path: ...\n\ndef find_global_config_path(*, to_write: bool = False) -> Optional[Path]:\n \"\"\"\n Returns the path to the user global config file (the file in the user home\n directory).\n If there is no such file:\n - If `to_write` is False, returns None.\n - If `to_write` is True, returns the path to the default file.\n\n This means the function never returns None if `to_write` is True.\n \"\"\"\n for filename in USER_CONFIG_FILENAMES:\n path = get_global_path(filename)\n if path.exists():\n return path\n return get_global_path(DEFAULT_CONFIG_FILENAME) if to_write else None\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_imports_parsed": 15, "n_files_resolved": 6, "n_chars_extracted": 13416, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/user_config.py\nclass UserConfig(FilteredConfig):\n \"\"\"\n Holds all ggshield settings defined by the user in the .gitguardian.yaml files\n (local and global).\n \"\"\"\n\n instance: Optional[str] = None\n exit_zero: bool = False\n verbose: bool = False\n insecure: bool = False\n max_commits_for_hook: int = 50\n secret: SecretConfig = field(default_factory=SecretConfig)\n debug: bool = False\n\n # If we hit any deprecated syntax when loading a configuration file, we do not\n # display them directly, otherwise the messages would also be shown when running\n # `ggshield config migrate`, which would be odd.\n # Instead, we store them in this list and a result_callback() function displays\n # them when we quit. When `config migrate` runs, it clears this list, so nothing\n # gets displayed.\n deprecation_messages: List[str] = field(default_factory=list)\n\n def save(self, config_path: Path) -> None:\n \"\"\"\n Save config to config_path\n \"\"\"\n dct = self.to_config_dict()\n save_yaml_dict(dct, config_path)\n\n def to_config_dict(self) -> Dict[str, Any]:\n dct = self.to_dict()\n default_dct = UserConfig.from_dict({}).to_dict()\n\n dct = remove_common_dict_items(dct, default_dct)\n\n dct[\"version\"] = CURRENT_CONFIG_VERSION\n\n return dct\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> Tuple[\"UserConfig\", Path]:\n \"\"\"\n Load the various user configs files to create a UserConfig object:\n - global user configuration file (in the home)\n - local user configuration file (in the repository)\n\n Returns a UserConfig instance, and the path where updates should be saved\n \"\"\"\n deprecation_messages: List[str] = []\n if config_path:\n logger.debug(\"Loading custom config from %s\", config_path)\n dct = _load_config_dict(config_path, deprecation_messages)\n user_config = UserConfig.from_config_dict(dct)\n user_config.deprecation_messages = deprecation_messages\n return user_config, config_path\n\n user_config_dict: Dict[str, Any] = {}\n global_config_path = find_global_config_path()\n if global_config_path:\n dct = _load_config_dict(global_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n logger.debug(\"Loaded global config from %s\", global_config_path)\n else:\n logger.debug(\"No global config\")\n\n local_config_path = find_local_config_path()\n if local_config_path:\n dct = _load_config_dict(local_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n config_path = local_config_path\n logger.debug(\"Loaded local config from %s\", local_config_path)\n else:\n logger.debug(\"No local config\")\n\n user_config = UserConfig.from_config_dict(user_config_dict)\n user_config.deprecation_messages = deprecation_messages\n\n if config_path is None:\n config_path = Path(DEFAULT_LOCAL_CONFIG_PATH)\n return user_config, config_path\n\n @staticmethod\n def from_config_dict(data: Dict[str, Any]) -> \"UserConfig\":\n \"\"\"Create a UserConfig instance. In case of error, format it and raise\n ParseError.\"\"\"\n try:\n return UserConfig.from_dict(data)\n except ValidationError as exc:\n message = format_validation_error(exc)\n raise ParseError(message) from exc\n\n\n# Source: ggshield/core/config/utils.py\ndef find_global_config_path(*, to_write: Literal[False] = False) -> Optional[Path]: ...\n\ndef find_global_config_path(*, to_write: Literal[True]) -> Path: ...\n\ndef find_global_config_path(*, to_write: bool = False) -> Optional[Path]:\n \"\"\"\n Returns the path to the user global config file (the file in the user home\n directory).\n If there is no such file:\n - If `to_write` is False, returns None.\n - If `to_write` is True, returns the path to the default file.\n\n This means the function never returns None if `to_write` is True.\n \"\"\"\n for filename in USER_CONFIG_FILENAMES:\n path = get_global_path(filename)\n if path.exists():\n return path\n return get_global_path(DEFAULT_CONFIG_FILENAME) if to_write else None\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_chars_compressed": 13416, "compression_ratio": 1.0}, "tests/unit/core/config/test_user_config.py::132": {"resolved_imports": ["ggshield/core/config/config.py", "ggshield/core/config/user_config.py", "ggshield/core/errors.py", "ggshield/core/types.py"], "used_names": ["IgnoredMatch", "UserConfig", "write_yaml"], "enclosing_function": "test_load_v1", "extracted_code": "# Source: ggshield/core/config/user_config.py\nclass UserConfig(FilteredConfig):\n \"\"\"\n Holds all ggshield settings defined by the user in the .gitguardian.yaml files\n (local and global).\n \"\"\"\n\n instance: Optional[str] = None\n exit_zero: bool = False\n verbose: bool = False\n insecure: bool = False\n max_commits_for_hook: int = 50\n secret: SecretConfig = field(default_factory=SecretConfig)\n debug: bool = False\n\n # If we hit any deprecated syntax when loading a configuration file, we do not\n # display them directly, otherwise the messages would also be shown when running\n # `ggshield config migrate`, which would be odd.\n # Instead, we store them in this list and a result_callback() function displays\n # them when we quit. When `config migrate` runs, it clears this list, so nothing\n # gets displayed.\n deprecation_messages: List[str] = field(default_factory=list)\n\n def save(self, config_path: Path) -> None:\n \"\"\"\n Save config to config_path\n \"\"\"\n dct = self.to_config_dict()\n save_yaml_dict(dct, config_path)\n\n def to_config_dict(self) -> Dict[str, Any]:\n dct = self.to_dict()\n default_dct = UserConfig.from_dict({}).to_dict()\n\n dct = remove_common_dict_items(dct, default_dct)\n\n dct[\"version\"] = CURRENT_CONFIG_VERSION\n\n return dct\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> Tuple[\"UserConfig\", Path]:\n \"\"\"\n Load the various user configs files to create a UserConfig object:\n - global user configuration file (in the home)\n - local user configuration file (in the repository)\n\n Returns a UserConfig instance, and the path where updates should be saved\n \"\"\"\n deprecation_messages: List[str] = []\n if config_path:\n logger.debug(\"Loading custom config from %s\", config_path)\n dct = _load_config_dict(config_path, deprecation_messages)\n user_config = UserConfig.from_config_dict(dct)\n user_config.deprecation_messages = deprecation_messages\n return user_config, config_path\n\n user_config_dict: Dict[str, Any] = {}\n global_config_path = find_global_config_path()\n if global_config_path:\n dct = _load_config_dict(global_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n logger.debug(\"Loaded global config from %s\", global_config_path)\n else:\n logger.debug(\"No global config\")\n\n local_config_path = find_local_config_path()\n if local_config_path:\n dct = _load_config_dict(local_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n config_path = local_config_path\n logger.debug(\"Loaded local config from %s\", local_config_path)\n else:\n logger.debug(\"No local config\")\n\n user_config = UserConfig.from_config_dict(user_config_dict)\n user_config.deprecation_messages = deprecation_messages\n\n if config_path is None:\n config_path = Path(DEFAULT_LOCAL_CONFIG_PATH)\n return user_config, config_path\n\n @staticmethod\n def from_config_dict(data: Dict[str, Any]) -> \"UserConfig\":\n \"\"\"Create a UserConfig instance. In case of error, format it and raise\n ParseError.\"\"\"\n try:\n return UserConfig.from_dict(data)\n except ValidationError as exc:\n message = format_validation_error(exc)\n raise ParseError(message) from exc\n\n\n# Source: ggshield/core/types.py\nclass IgnoredMatch(FilteredConfig):\n match: str\n name: Optional[str] = None\n\n def __post_init__(self) -> None:\n if self.name is None:\n self.name = \"\"", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 3805, "extracted_code_full": "# Source: ggshield/core/config/user_config.py\nclass UserConfig(FilteredConfig):\n \"\"\"\n Holds all ggshield settings defined by the user in the .gitguardian.yaml files\n (local and global).\n \"\"\"\n\n instance: Optional[str] = None\n exit_zero: bool = False\n verbose: bool = False\n insecure: bool = False\n max_commits_for_hook: int = 50\n secret: SecretConfig = field(default_factory=SecretConfig)\n debug: bool = False\n\n # If we hit any deprecated syntax when loading a configuration file, we do not\n # display them directly, otherwise the messages would also be shown when running\n # `ggshield config migrate`, which would be odd.\n # Instead, we store them in this list and a result_callback() function displays\n # them when we quit. When `config migrate` runs, it clears this list, so nothing\n # gets displayed.\n deprecation_messages: List[str] = field(default_factory=list)\n\n def save(self, config_path: Path) -> None:\n \"\"\"\n Save config to config_path\n \"\"\"\n dct = self.to_config_dict()\n save_yaml_dict(dct, config_path)\n\n def to_config_dict(self) -> Dict[str, Any]:\n dct = self.to_dict()\n default_dct = UserConfig.from_dict({}).to_dict()\n\n dct = remove_common_dict_items(dct, default_dct)\n\n dct[\"version\"] = CURRENT_CONFIG_VERSION\n\n return dct\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> Tuple[\"UserConfig\", Path]:\n \"\"\"\n Load the various user configs files to create a UserConfig object:\n - global user configuration file (in the home)\n - local user configuration file (in the repository)\n\n Returns a UserConfig instance, and the path where updates should be saved\n \"\"\"\n deprecation_messages: List[str] = []\n if config_path:\n logger.debug(\"Loading custom config from %s\", config_path)\n dct = _load_config_dict(config_path, deprecation_messages)\n user_config = UserConfig.from_config_dict(dct)\n user_config.deprecation_messages = deprecation_messages\n return user_config, config_path\n\n user_config_dict: Dict[str, Any] = {}\n global_config_path = find_global_config_path()\n if global_config_path:\n dct = _load_config_dict(global_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n logger.debug(\"Loaded global config from %s\", global_config_path)\n else:\n logger.debug(\"No global config\")\n\n local_config_path = find_local_config_path()\n if local_config_path:\n dct = _load_config_dict(local_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n config_path = local_config_path\n logger.debug(\"Loaded local config from %s\", local_config_path)\n else:\n logger.debug(\"No local config\")\n\n user_config = UserConfig.from_config_dict(user_config_dict)\n user_config.deprecation_messages = deprecation_messages\n\n if config_path is None:\n config_path = Path(DEFAULT_LOCAL_CONFIG_PATH)\n return user_config, config_path\n\n @staticmethod\n def from_config_dict(data: Dict[str, Any]) -> \"UserConfig\":\n \"\"\"Create a UserConfig instance. In case of error, format it and raise\n ParseError.\"\"\"\n try:\n return UserConfig.from_dict(data)\n except ValidationError as exc:\n message = format_validation_error(exc)\n raise ParseError(message) from exc\n\n\n# Source: ggshield/core/types.py\nclass IgnoredMatch(FilteredConfig):\n match: str\n name: Optional[str] = None\n\n def __post_init__(self) -> None:\n if self.name is None:\n self.name = \"\"", "n_chars_compressed": 3805, "compression_ratio": 1.0}, "tests/unit/cmd/plugin/test_install.py::31": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/plugin/install.py", "ggshield/core/errors.py", "ggshield/core/plugin/client.py"], "used_names": ["ExitCode", "cli"], "enclosing_function": "test_install_requires_plugin_source", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/verticals/secret/output/test_gitlab_webui_output.py::21": {"resolved_imports": ["ggshield/core/config/user_config.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/output/secret_gitlab_webui_output_handler.py"], "used_names": ["Match", "SecretFactory", "format_secret"], "enclosing_function": "test_format_secret", "extracted_code": "# Source: ggshield/verticals/secret/output/secret_gitlab_webui_output_handler.py\ndef format_secret(secret: Secret) -> str:\n \"\"\"Returns a string with the policy name, validity and a comma-separated,\n double-quoted, censored version of all `secret` matches.\n\n Looks like this:\n\n PayPal OAuth2 Keys (Validity: Valid, id=\"aa*******bb\", secret=\"cc******dd\")\n \"\"\"\n match_str = \", \".join(\n f'{x.match_type}: \"{censor_match(x)}\"' for x in secret.matches\n )\n validity = translate_validity(secret.validity)\n return f\"{secret.detector_display_name} (Validity: {validity}, {match_str})\"", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 608, "extracted_code_full": "# Source: ggshield/verticals/secret/output/secret_gitlab_webui_output_handler.py\ndef format_secret(secret: Secret) -> str:\n \"\"\"Returns a string with the policy name, validity and a comma-separated,\n double-quoted, censored version of all `secret` matches.\n\n Looks like this:\n\n PayPal OAuth2 Keys (Validity: Valid, id=\"aa*******bb\", secret=\"cc******dd\")\n \"\"\"\n match_str = \", \".join(\n f'{x.match_type}: \"{censor_match(x)}\"' for x in secret.matches\n )\n validity = translate_validity(secret.validity)\n return f\"{secret.detector_display_name} (Validity: {validity}, {match_str})\"", "n_chars_compressed": 608, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_decrypt.py::117": {"resolved_imports": ["ggshield/__main__.py", "ggshield/verticals/hmsl/crypto.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli"], "enclosing_function": "test_hmsl_decrypt_default_behavior", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/verticals/secret/test_scan_repo.py::81": {"resolved_imports": ["ggshield/core/config/user_config.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/commit_information.py", "ggshield/core/scan/commit_utils.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/repo.py"], "used_names": ["Commit", "CommitInformation", "List", "MagicMock", "Path", "get_commits_by_batch", "pytest"], "enclosing_function": "test_get_commits_content_by_batch", "extracted_code": "# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/commit_information.py\nclass CommitInformation:\n author: str\n email: str\n date: str\n paths: List[Path]\n renames: Dict[Path, Path] = field(default_factory=dict)\n\n @staticmethod\n def from_patch_header(header_str: str) -> \"CommitInformation\":\n \"\"\"\n Parse a patch header generated with `git show` or `git diff` using\n HEADER_COMMON_ARGS.\n\n Output format looks like this:\n\n ```\n commit $SHA\n Author: $NAME <$EMAIL>\n Date: $DATE\n\n $SUBJECT\n\n $BODY\n $RAW_FILE_LINES\n ```\n\n If the commit is empty the last line is absent and the header ends with `\\n`.\n \"\"\"\n header = PatchHeader.from_string(header_str)\n match = _INFO_HEADER_REGEX.search(header.info)\n assert match is not None, f\"Failed to extract commit info from `{header.info}`\"\n\n if header.files:\n # Usual commit, with files in it\n paths: List[Path] = []\n renames: Dict[Path, Path] = {}\n for file_info in header.files:\n paths.append(file_info.path)\n if file_info.old_path is not None:\n renames[file_info.path] = file_info.old_path\n else:\n # Empty commit\n paths = []\n renames = {}\n\n return CommitInformation(**match.groupdict(), paths=paths, renames=renames)\n\n @staticmethod\n def from_staged(cwd: Optional[Path] = None) -> \"CommitInformation\":\n output = git([\"diff\", \"--staged\"] + HEADER_COMMON_ARGS, cwd=cwd)\n if not output:\n # This happens when there are no changes\n return CommitInformation(\"\", \"\", \"\", [])\n\n return CommitInformation.from_patch_header(\n DIFF_EMPTY_COMMIT_INFO_BLOCK + output\n )\n\n @staticmethod\n def from_sha(sha: str, cwd: Optional[Path] = None) -> \"CommitInformation\":\n header = git([\"show\", sha] + HEADER_COMMON_ARGS, cwd=cwd)\n return CommitInformation.from_patch_header(header)\n\n\n# Source: ggshield/verticals/secret/repo.py\ndef get_commits_by_batch(\n commits: Iterable[Commit],\n batch_max_size: int,\n) -> Iterator[List[Commit]]:\n \"\"\"\n Given a list of commit shas yield the commit files\n by biggest batches possible of length at most `batch_max_size`\n \"\"\"\n current_count = 0\n batch = []\n for commit in commits:\n num_files = len(commit.urls)\n if current_count + num_files < batch_max_size:\n batch.append(commit)\n current_count += num_files\n else:\n # The first batch can remain empty if it has too many files\n if batch:\n yield batch\n current_count = num_files\n batch = [commit]\n # Send the last batch that remains\n yield batch", "n_imports_parsed": 12, "n_files_resolved": 6, "n_chars_extracted": 7107, "extracted_code_full": "# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/commit_information.py\nclass CommitInformation:\n author: str\n email: str\n date: str\n paths: List[Path]\n renames: Dict[Path, Path] = field(default_factory=dict)\n\n @staticmethod\n def from_patch_header(header_str: str) -> \"CommitInformation\":\n \"\"\"\n Parse a patch header generated with `git show` or `git diff` using\n HEADER_COMMON_ARGS.\n\n Output format looks like this:\n\n ```\n commit $SHA\n Author: $NAME <$EMAIL>\n Date: $DATE\n\n $SUBJECT\n\n $BODY\n $RAW_FILE_LINES\n ```\n\n If the commit is empty the last line is absent and the header ends with `\\n`.\n \"\"\"\n header = PatchHeader.from_string(header_str)\n match = _INFO_HEADER_REGEX.search(header.info)\n assert match is not None, f\"Failed to extract commit info from `{header.info}`\"\n\n if header.files:\n # Usual commit, with files in it\n paths: List[Path] = []\n renames: Dict[Path, Path] = {}\n for file_info in header.files:\n paths.append(file_info.path)\n if file_info.old_path is not None:\n renames[file_info.path] = file_info.old_path\n else:\n # Empty commit\n paths = []\n renames = {}\n\n return CommitInformation(**match.groupdict(), paths=paths, renames=renames)\n\n @staticmethod\n def from_staged(cwd: Optional[Path] = None) -> \"CommitInformation\":\n output = git([\"diff\", \"--staged\"] + HEADER_COMMON_ARGS, cwd=cwd)\n if not output:\n # This happens when there are no changes\n return CommitInformation(\"\", \"\", \"\", [])\n\n return CommitInformation.from_patch_header(\n DIFF_EMPTY_COMMIT_INFO_BLOCK + output\n )\n\n @staticmethod\n def from_sha(sha: str, cwd: Optional[Path] = None) -> \"CommitInformation\":\n header = git([\"show\", sha] + HEADER_COMMON_ARGS, cwd=cwd)\n return CommitInformation.from_patch_header(header)\n\n\n# Source: ggshield/verticals/secret/repo.py\ndef get_commits_by_batch(\n commits: Iterable[Commit],\n batch_max_size: int,\n) -> Iterator[List[Commit]]:\n \"\"\"\n Given a list of commit shas yield the commit files\n by biggest batches possible of length at most `batch_max_size`\n \"\"\"\n current_count = 0\n batch = []\n for commit in commits:\n num_files = len(commit.urls)\n if current_count + num_files < batch_max_size:\n batch.append(commit)\n current_count += num_files\n else:\n # The first batch can remain empty if it has too many files\n if batch:\n yield batch\n current_count = num_files\n batch = [commit]\n # Send the last batch that remains\n yield batch", "n_chars_compressed": 7107, "compression_ratio": 1.0}, "tests/unit/verticals/secret/output/test_gitlab_webui_output.py::55": {"resolved_imports": ["ggshield/core/config/user_config.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/output/secret_gitlab_webui_output_handler.py"], "used_names": ["Results", "SecretConfig", "SecretGitLabWebUIOutputHandler", "SecretScanCollection"], "enclosing_function": "test_gitlab_web_ui_output_no_secrets", "extracted_code": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)\n\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details\n\n\n# Source: ggshield/verticals/secret/output/secret_gitlab_webui_output_handler.py\nclass SecretGitLabWebUIOutputHandler(SecretOutputHandler):\n \"\"\"\n Terse OutputHandler optimized for GitLab Web UI, because GitLab Web UI only shows\n lines starting with GL-HOOK-ERR.\n\n See https://docs.gitlab.com/ee/administration/server_hooks.html#custom-error-messages\n \"\"\"\n\n use_stderr = True\n\n def _process_scan_impl(self, scan: SecretScanCollection) -> str:\n results = scan.get_all_results()\n\n secrets_to_report = [secret for result in results for secret in result.secrets]\n\n # If no secrets or no new secrets were found\n if len(secrets_to_report) == 0:\n return \"\"\n\n # Use a set to ensure we do not report duplicate incidents.\n # (can happen when the secret is present in both the old and the new version of\n # the document)\n formatted_secrets = {format_secret(x) for x in secrets_to_report}\n break_count = len(formatted_secrets)\n\n if self.ignore_known_secrets:\n summary_str = f\"{break_count} new {pluralize('incident', break_count)}\"\n else:\n summary_str = f\"{break_count} {pluralize('incident', break_count)}\"\n\n # Putting each policy break on its own line would be more readable, but we can't\n # do this because of a bug in GitLab Web IDE which causes newline characters to\n # be shown as \"
\"\n # https://gitlab.com/gitlab-org/gitlab/-/issues/350349\n breaks_str = \", \".join(formatted_secrets)\n\n return (\n f\"GL-HOOK-ERR: ggshield found {summary_str} in these changes: {breaks_str}.\"\n \" The commit has been rejected.\"\n )", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 6784, "extracted_code_full": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)\n\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details\n\n\n# Source: ggshield/verticals/secret/output/secret_gitlab_webui_output_handler.py\nclass SecretGitLabWebUIOutputHandler(SecretOutputHandler):\n \"\"\"\n Terse OutputHandler optimized for GitLab Web UI, because GitLab Web UI only shows\n lines starting with GL-HOOK-ERR.\n\n See https://docs.gitlab.com/ee/administration/server_hooks.html#custom-error-messages\n \"\"\"\n\n use_stderr = True\n\n def _process_scan_impl(self, scan: SecretScanCollection) -> str:\n results = scan.get_all_results()\n\n secrets_to_report = [secret for result in results for secret in result.secrets]\n\n # If no secrets or no new secrets were found\n if len(secrets_to_report) == 0:\n return \"\"\n\n # Use a set to ensure we do not report duplicate incidents.\n # (can happen when the secret is present in both the old and the new version of\n # the document)\n formatted_secrets = {format_secret(x) for x in secrets_to_report}\n break_count = len(formatted_secrets)\n\n if self.ignore_known_secrets:\n summary_str = f\"{break_count} new {pluralize('incident', break_count)}\"\n else:\n summary_str = f\"{break_count} {pluralize('incident', break_count)}\"\n\n # Putting each policy break on its own line would be more readable, but we can't\n # do this because of a bug in GitLab Web IDE which causes newline characters to\n # be shown as \"
\"\n # https://gitlab.com/gitlab-org/gitlab/-/issues/350349\n breaks_str = \", \".join(formatted_secrets)\n\n return (\n f\"GL-HOOK-ERR: ggshield found {summary_str} in these changes: {breaks_str}.\"\n \" The commit has been rejected.\"\n )", "n_chars_compressed": 6784, "compression_ratio": 1.0}, "tests/unit/core/config/test_auth_config.py::120": {"resolved_imports": ["ggshield/core/config/config.py", "ggshield/core/config/auth_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py"], "used_names": ["Config"], "enclosing_function": "test_load_file_not_existing", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_imports_parsed": 11, "n_files_resolved": 4, "n_chars_extracted": 8037, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience", "n_chars_compressed": 8037, "compression_ratio": 1.0}, "tests/unit/core/test_lines.py::125": {"resolved_imports": ["ggshield/core/lines.py", "ggshield/utils/git_shell.py"], "used_names": ["Filemode", "get_lines_from_patch"], "enclosing_function": "test_get_lines_set_indices_for_line_on_hunk_header", "extracted_code": "# Source: ggshield/core/lines.py\ndef get_lines_from_patch(content: str, filemode: Filemode) -> Iterable[Line]:\n \"\"\"Return the lines with line number from a git patch.\"\"\"\n content += \"\\n\"\n pre_index = 0\n post_index = 0\n\n for line in content.split(\"\\n\"):\n if not line:\n continue\n line_type = line[0]\n line_content = line\n line_pre_index = None\n line_post_index = None\n\n if line_type == \" \":\n pre_index += 1\n post_index += 1\n line_pre_index = pre_index\n line_post_index = post_index\n elif line_type == \"@\":\n m = REGEX_HUNK_HEADER.search(line)\n if m is None:\n continue\n pre_index = int(m.groupdict()[\"pre_index\"])\n post_index = int(m.groupdict()[\"post_index\"])\n trailing_content = m.groupdict()[\"trailing_content\"]\n\n if filemode == Filemode.NEW or filemode == Filemode.DELETE:\n pre_index = 1\n post_index = 1\n\n pre_index -= 1\n post_index -= 1\n if trailing_content:\n # If the hunk header has trailing content, it might contain a secret\n # match, so give it a line number.\n #\n # That trailing content is generated by Git (see [1]), so the number\n # might not be correct, but the rest of ggshield requires it.\n #\n # [1]: https://git-scm.com/docs/gitattributes#_defining_a_custom_hunk_header\n line_pre_index = pre_index\n line_post_index = pre_index\n elif line_type == \"+\":\n post_index += 1\n line_post_index = post_index\n elif line_type == \"-\":\n pre_index += 1\n line_pre_index = pre_index\n elif line_type == \"\\\\\":\n # This type of line shouldn't contain any secret; no need to set indices\n pass\n else:\n raise ParseError(\n f'Failed to parse patch line. Unexpected first character in \"{line}\"'\n )\n\n yield Line(\n content=line_content,\n is_patch=True,\n pre_index=line_pre_index,\n post_index=line_post_index,\n )\n\n\n# Source: ggshield/utils/git_shell.py\nclass Filemode(Enum):\n \"\"\"\n Enum class for git filemode.\n \"\"\"\n\n MODIFY = \"modified file\"\n DELETE = \"deleted file\"\n NEW = \"new file\"\n RENAME = \"renamed file\"\n FILE = \"file\"\n UNMERGED = \"unmerged file\"\n UNKNOWN = \"unknown\"", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2573, "extracted_code_full": "# Source: ggshield/core/lines.py\ndef get_lines_from_patch(content: str, filemode: Filemode) -> Iterable[Line]:\n \"\"\"Return the lines with line number from a git patch.\"\"\"\n content += \"\\n\"\n pre_index = 0\n post_index = 0\n\n for line in content.split(\"\\n\"):\n if not line:\n continue\n line_type = line[0]\n line_content = line\n line_pre_index = None\n line_post_index = None\n\n if line_type == \" \":\n pre_index += 1\n post_index += 1\n line_pre_index = pre_index\n line_post_index = post_index\n elif line_type == \"@\":\n m = REGEX_HUNK_HEADER.search(line)\n if m is None:\n continue\n pre_index = int(m.groupdict()[\"pre_index\"])\n post_index = int(m.groupdict()[\"post_index\"])\n trailing_content = m.groupdict()[\"trailing_content\"]\n\n if filemode == Filemode.NEW or filemode == Filemode.DELETE:\n pre_index = 1\n post_index = 1\n\n pre_index -= 1\n post_index -= 1\n if trailing_content:\n # If the hunk header has trailing content, it might contain a secret\n # match, so give it a line number.\n #\n # That trailing content is generated by Git (see [1]), so the number\n # might not be correct, but the rest of ggshield requires it.\n #\n # [1]: https://git-scm.com/docs/gitattributes#_defining_a_custom_hunk_header\n line_pre_index = pre_index\n line_post_index = pre_index\n elif line_type == \"+\":\n post_index += 1\n line_post_index = post_index\n elif line_type == \"-\":\n pre_index += 1\n line_pre_index = pre_index\n elif line_type == \"\\\\\":\n # This type of line shouldn't contain any secret; no need to set indices\n pass\n else:\n raise ParseError(\n f'Failed to parse patch line. Unexpected first character in \"{line}\"'\n )\n\n yield Line(\n content=line_content,\n is_patch=True,\n pre_index=line_pre_index,\n post_index=line_post_index,\n )\n\n\n# Source: ggshield/utils/git_shell.py\nclass Filemode(Enum):\n \"\"\"\n Enum class for git filemode.\n \"\"\"\n\n MODIFY = \"modified file\"\n DELETE = \"deleted file\"\n NEW = \"new file\"\n RENAME = \"renamed file\"\n FILE = \"file\"\n UNMERGED = \"unmerged file\"\n UNKNOWN = \"unknown\"", "n_chars_compressed": 2573, "compression_ratio": 1.0}, "tests/unit/utils/test_archive.py::61": {"resolved_imports": ["ggshield/utils/archive.py"], "used_names": ["Path", "UnsafeArchive", "check_archive_content", "pytest"], "enclosing_function": "test_check_archive_content_raises_exception", "extracted_code": "# Source: ggshield/utils/archive.py\nclass UnsafeArchive(Exception):\n \"\"\"\n Raised when an archive is considered unsafe.\n\n An archive is considered unsafe if it contains paths outside the extract directory\n or symbolic links pointing outside the extract directory.\n \"\"\"\n\n def __init__(self):\n self.bad_paths: List[Path] = []\n self.bad_links: List[Tuple[Path, Path]] = []\n\n def __str__(self) -> str:\n lines: List[str] = [\"Archive contains unsafe files.\"]\n if self.bad_paths:\n lines.append(\"Paths outside the archive root:\")\n lines.extend(f\"- {p}\" for p in self.bad_paths)\n if self.bad_links:\n lines.append(\"Links pointing outside the archive root:\")\n lines.extend(f\"- {src} -> {target}\" for src, target in self.bad_links)\n return \"\\n\".join(lines)\n\n def add_bad_path(self, path: Path) -> None:\n self.bad_paths.append(path)\n\n def add_bad_link(self, path: Path, target: Path) -> None:\n self.bad_links.append((path, target))\n\n def has_fails(self) -> bool:\n return bool(self.bad_paths) or bool(self.bad_links)\n\ndef check_archive_content(archive: Path) -> None:\n \"\"\"\n Check `archive` safety, raise `UnsafeArchive` if it is unsafe.\n \"\"\"\n if archive.suffix in {\".zip\", \".whl\", \".jar\"}:\n _check_zip_content(archive)\n else:\n _check_tar_content(archive)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 1405, "extracted_code_full": "# Source: ggshield/utils/archive.py\nclass UnsafeArchive(Exception):\n \"\"\"\n Raised when an archive is considered unsafe.\n\n An archive is considered unsafe if it contains paths outside the extract directory\n or symbolic links pointing outside the extract directory.\n \"\"\"\n\n def __init__(self):\n self.bad_paths: List[Path] = []\n self.bad_links: List[Tuple[Path, Path]] = []\n\n def __str__(self) -> str:\n lines: List[str] = [\"Archive contains unsafe files.\"]\n if self.bad_paths:\n lines.append(\"Paths outside the archive root:\")\n lines.extend(f\"- {p}\" for p in self.bad_paths)\n if self.bad_links:\n lines.append(\"Links pointing outside the archive root:\")\n lines.extend(f\"- {src} -> {target}\" for src, target in self.bad_links)\n return \"\\n\".join(lines)\n\n def add_bad_path(self, path: Path) -> None:\n self.bad_paths.append(path)\n\n def add_bad_link(self, path: Path, target: Path) -> None:\n self.bad_links.append((path, target))\n\n def has_fails(self) -> bool:\n return bool(self.bad_paths) or bool(self.bad_links)\n\ndef check_archive_content(archive: Path) -> None:\n \"\"\"\n Check `archive` safety, raise `UnsafeArchive` if it is unsafe.\n \"\"\"\n if archive.suffix in {\".zip\", \".whl\", \".jar\"}:\n _check_zip_content(archive)\n else:\n _check_tar_content(archive)", "n_chars_compressed": 1405, "compression_ratio": 1.0}, "tests/unit/cmd/test_status.py::21": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/utils/os.py"], "used_names": ["assert_invoke_ok", "cli", "json", "jsonschema", "my_vcr"], "enclosing_function": "test_quota", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 11, "n_files_resolved": 3, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/test_match_span.py::93": {"resolved_imports": ["ggshield/core/lines.py", "ggshield/core/match_span.py", "ggshield/utils/git_shell.py"], "used_names": ["Filemode", "List", "MatchSpan", "ScanResult", "_MULTI_SECRET_ONE_LINE_PATCH", "_MULTI_SECRET_ONE_LINE_PATCH_SCAN_RESULT", "_MULTI_SECRET_TWO_LINES_PATCH", "_MULTI_SECRET_TWO_LINES_PATCH_SCAN_RESULT", "_ONE_LINE_AND_MULTILINE_PATCH_CONTENT", "_ONE_LINE_AND_MULTILINE_PATCH_SCAN_RESULT", "_SIMPLE_SECRET_MULTILINE_PATCH", "_SIMPLE_SECRET_MULTILINE_PATCH_SCAN_RESULT", "_SIMPLE_SECRET_PATCH", "_SIMPLE_SECRET_PATCH_SCAN_RESULT", "get_lines_from_content", "pytest"], "enclosing_function": "test_from_match", "extracted_code": "# Source: ggshield/core/lines.py\ndef get_lines_from_content(content: str, filemode: Filemode) -> List[Line]:\n \"\"\"\n Return the secrets and the lines with line number.\n\n :param content: Content to scan\n :param filemode: Filemode of the content\n \"\"\"\n\n # Patch\n if filemode != Filemode.FILE:\n return list(get_lines_from_patch(content, filemode))\n\n # File\n return list(get_lines_from_file(content))\n\n\n# Source: ggshield/core/match_span.py\nclass MatchSpan(NamedTuple):\n \"\"\"Represents the start and end of a match in a text.\n\n line_index_start and line_index_end are line numbers.\n column_index_start and column_index_end are positions within the line.\n\n All indices are 0-based.\n\n Contrary to Match, column_index_end points to the character *after* the last\n character of the match.\n \"\"\"\n\n line_index_start: int\n line_index_end: int\n column_index_start: int\n column_index_end: int\n\n @staticmethod\n def from_match(match: Match, lines: List[Line]) -> \"MatchSpan\":\n \"\"\"\n Create a MatchSpan from a Match and a list of lines.\n\n :param match: a Match where index_{start,end} are not None\n :param lines: List of lines with indices (post_index and pre_index)\n \"\"\"\n index = 0\n line_index = 0\n len_line = len(lines[line_index].content) + 1\n # Update line_index until we find the secret start\n assert match.index_start is not None\n while match.index_start >= index + len_line:\n index += len_line\n line_index += 1\n len_line = len(lines[line_index].content) + 1\n\n line_index_start = line_index\n column_index_start = match.index_start - index\n\n # Update line_index until we find the secret end\n assert match.index_end is not None\n while match.index_end > index + len_line:\n index += len_line\n line_index += 1\n len_line = len(lines[line_index].content) + 1\n\n line_index_end = line_index\n column_index_end = match.index_end - index + 1\n return MatchSpan(\n line_index_start,\n line_index_end,\n column_index_start,\n column_index_end,\n )\n\n\n# Source: ggshield/utils/git_shell.py\nclass Filemode(Enum):\n \"\"\"\n Enum class for git filemode.\n \"\"\"\n\n MODIFY = \"modified file\"\n DELETE = \"deleted file\"\n NEW = \"new file\"\n RENAME = \"renamed file\"\n FILE = \"file\"\n UNMERGED = \"unmerged file\"\n UNKNOWN = \"unknown\"", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 2525, "extracted_code_full": "# Source: ggshield/core/lines.py\ndef get_lines_from_content(content: str, filemode: Filemode) -> List[Line]:\n \"\"\"\n Return the secrets and the lines with line number.\n\n :param content: Content to scan\n :param filemode: Filemode of the content\n \"\"\"\n\n # Patch\n if filemode != Filemode.FILE:\n return list(get_lines_from_patch(content, filemode))\n\n # File\n return list(get_lines_from_file(content))\n\n\n# Source: ggshield/core/match_span.py\nclass MatchSpan(NamedTuple):\n \"\"\"Represents the start and end of a match in a text.\n\n line_index_start and line_index_end are line numbers.\n column_index_start and column_index_end are positions within the line.\n\n All indices are 0-based.\n\n Contrary to Match, column_index_end points to the character *after* the last\n character of the match.\n \"\"\"\n\n line_index_start: int\n line_index_end: int\n column_index_start: int\n column_index_end: int\n\n @staticmethod\n def from_match(match: Match, lines: List[Line]) -> \"MatchSpan\":\n \"\"\"\n Create a MatchSpan from a Match and a list of lines.\n\n :param match: a Match where index_{start,end} are not None\n :param lines: List of lines with indices (post_index and pre_index)\n \"\"\"\n index = 0\n line_index = 0\n len_line = len(lines[line_index].content) + 1\n # Update line_index until we find the secret start\n assert match.index_start is not None\n while match.index_start >= index + len_line:\n index += len_line\n line_index += 1\n len_line = len(lines[line_index].content) + 1\n\n line_index_start = line_index\n column_index_start = match.index_start - index\n\n # Update line_index until we find the secret end\n assert match.index_end is not None\n while match.index_end > index + len_line:\n index += len_line\n line_index += 1\n len_line = len(lines[line_index].content) + 1\n\n line_index_end = line_index\n column_index_end = match.index_end - index + 1\n return MatchSpan(\n line_index_start,\n line_index_end,\n column_index_start,\n column_index_end,\n )\n\n\n# Source: ggshield/utils/git_shell.py\nclass Filemode(Enum):\n \"\"\"\n Enum class for git filemode.\n \"\"\"\n\n MODIFY = \"modified file\"\n DELETE = \"deleted file\"\n NEW = \"new file\"\n RENAME = \"renamed file\"\n FILE = \"file\"\n UNMERGED = \"unmerged file\"\n UNKNOWN = \"unknown\"", "n_chars_compressed": 2525, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_repo.py::78": {"resolved_imports": [], "used_names": ["Repository", "os", "patch", "run_ggshield_scan"], "enclosing_function": "test_scan_repo_quota_limit_reached", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/core/scan/test_file.py::209": {"resolved_imports": ["ggshield/core/scan/file.py", "ggshield/core/scan/scannable.py"], "used_names": ["File", "Path", "is_windows"], "enclosing_function": "test_file_path", "extracted_code": "# Source: ggshield/core/scan/file.py\nclass File(Scannable):\n \"\"\"Implementation of Scannable for files from the disk.\"\"\"\n\n def __init__(self, path: Union[str, Path]):\n super().__init__()\n self._path = Path(path)\n\n @property\n def url(self) -> str:\n return url_for_path(self._path)\n\n @property\n def filename(self) -> str:\n return str(self._path)\n\n @property\n def path(self) -> Path:\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n if self._utf8_encoded_size is not None:\n # We already have the encoded size, easy\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n with self.path.open(\"rb\") as fp:\n (\n result,\n self._content,\n self._utf8_encoded_size,\n ) = Scannable._is_file_longer_than(fp, max_utf8_encoded_size)\n return result\n\n def _read_content(self) -> None:\n if self._content is None:\n with self.path.open(\"rb\") as f:\n self._content, self._utf8_encoded_size = Scannable._decode_bytes(\n f.read()\n )", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 1185, "extracted_code_full": "# Source: ggshield/core/scan/file.py\nclass File(Scannable):\n \"\"\"Implementation of Scannable for files from the disk.\"\"\"\n\n def __init__(self, path: Union[str, Path]):\n super().__init__()\n self._path = Path(path)\n\n @property\n def url(self) -> str:\n return url_for_path(self._path)\n\n @property\n def filename(self) -> str:\n return str(self._path)\n\n @property\n def path(self) -> Path:\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n if self._utf8_encoded_size is not None:\n # We already have the encoded size, easy\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n with self.path.open(\"rb\") as fp:\n (\n result,\n self._content,\n self._utf8_encoded_size,\n ) = Scannable._is_file_longer_than(fp, max_utf8_encoded_size)\n return result\n\n def _read_content(self) -> None:\n if self._content is None:\n with self.path.open(\"rb\") as f:\n self._content, self._utf8_encoded_size = Scannable._decode_bytes(\n f.read()\n )", "n_chars_compressed": 1185, "compression_ratio": 1.0}, "tests/unit/core/test_check_updates.py::132": {"resolved_imports": ["ggshield/core/__init__.py", "ggshield/core/check_updates.py"], "used_names": ["FakeFilesystem", "load_last_check_time"], "enclosing_function": "test_load_last_check_time_no_cache_ok", "extracted_code": "# Source: ggshield/core/check_updates.py\ndef load_last_check_time() -> Optional[float]:\n \"\"\"Returns the last time we checked, or None if not available\"\"\"\n try:\n cached_data = load_yaml_dict(CACHE_FILE)\n if cached_data is None:\n # File does not exist, do not log any warning\n return None\n return float(cached_data[CHECK_AT_KEY])\n except Exception as e:\n logger.warning(\"Could not load cached latest version: %s\", repr(e))\n return None", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 499, "extracted_code_full": "# Source: ggshield/core/check_updates.py\ndef load_last_check_time() -> Optional[float]:\n \"\"\"Returns the last time we checked, or None if not available\"\"\"\n try:\n cached_data = load_yaml_dict(CACHE_FILE)\n if cached_data is None:\n # File does not exist, do not log any warning\n return None\n return float(cached_data[CHECK_AT_KEY])\n except Exception as e:\n logger.warning(\"Could not load cached latest version: %s\", repr(e))\n return None", "n_chars_compressed": 499, "compression_ratio": 1.0}, "tests/unit/core/test_filter.py::131": {"resolved_imports": ["ggshield/core/filter.py"], "used_names": ["censor_string", "pytest"], "enclosing_function": "test_censor_string", "extracted_code": "# Source: ggshield/core/filter.py\ndef censor_string(text: str) -> str:\n \"\"\"\n Censor a string (usually a secret), revealing only the first and last\n 1/6th of the match up to a maximum of MAXIMUM_CENSOR_LENGTH.\n\n :return: the text censored\n \"\"\"\n len_match = len(text)\n\n # Special cases for short lengths\n if len_match <= 2:\n return \"*\" * len_match\n if len_match == 3:\n return f\"**{text[2]}\"\n\n censor_start = min(math.ceil(len_match / 6), MAXIMUM_CENSOR_LENGTH)\n censor_end = len_match - censor_start\n\n censored = REGEX_MATCH_HIDE.sub(\"*\", text)\n\n return text[:censor_start] + censored[censor_start:censor_end] + text[censor_end:]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 680, "extracted_code_full": "# Source: ggshield/core/filter.py\ndef censor_string(text: str) -> str:\n \"\"\"\n Censor a string (usually a secret), revealing only the first and last\n 1/6th of the match up to a maximum of MAXIMUM_CENSOR_LENGTH.\n\n :return: the text censored\n \"\"\"\n len_match = len(text)\n\n # Special cases for short lengths\n if len_match <= 2:\n return \"*\" * len_match\n if len_match == 3:\n return f\"**{text[2]}\"\n\n censor_start = min(math.ceil(len_match / 6), MAXIMUM_CENSOR_LENGTH)\n censor_end = len_match - censor_start\n\n censored = REGEX_MATCH_HIDE.sub(\"*\", text)\n\n return text[:censor_start] + censored[censor_start:censor_end] + text[censor_end:]", "n_chars_compressed": 680, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_parameters.py::23": {"resolved_imports": ["ggshield/cmd/secret/scan/secret_scan_common_options.py"], "used_names": ["Mock", "_source_uuid_callback", "click", "pytest"], "enclosing_function": "test_invalid_uuid_raises_bad_parameter", "extracted_code": "# Source: ggshield/cmd/secret/scan/secret_scan_common_options.py\ndef _source_uuid_callback(\n ctx: click.Context, param: click.Parameter, value: Optional[str]\n) -> Optional[str]:\n if value is not None:\n try:\n uuid.UUID(value)\n except ValueError:\n raise click.BadParameter(\"source-uuid must be a valid UUID\")\n return create_config_callback(\"secret\", \"source_uuid\")(ctx, param, value)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 426, "extracted_code_full": "# Source: ggshield/cmd/secret/scan/secret_scan_common_options.py\ndef _source_uuid_callback(\n ctx: click.Context, param: click.Parameter, value: Optional[str]\n) -> Optional[str]:\n if value is not None:\n try:\n uuid.UUID(value)\n except ValueError:\n raise click.BadParameter(\"source-uuid must be a valid UUID\")\n return create_config_callback(\"secret\", \"source_uuid\")(ctx, param, value)", "n_chars_compressed": 426, "compression_ratio": 1.0}, "tests/unit/cmd/hmsl/test_quota.py::17": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli", "my_vcr"], "enclosing_function": "test_hmsl_quota", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/test_lines.py::46": {"resolved_imports": ["ggshield/core/lines.py", "ggshield/utils/git_shell.py"], "used_names": ["Line", "pytest"], "enclosing_function": "test_build_line_count", "extracted_code": "# Source: ggshield/core/lines.py\nclass Line:\n \"\"\"\n Represent a line in a document.\n\n - content: Content of the line\n - pre_index: Line index (deletion for patches, line index for files)\n - post_index: Line index (addition for patches)\n\n pre_index and post_index are 1-based.\n\n For files: pre_index is the line number, post_index is None.\n\n For patches: pre_index and post_index are line numbers relative to the *document\n modified by the patch*, not to the patch itself. This means that for a patch like\n this:\n\n ```\n diff --git a/foo.py b/foo.py\n index c53e550a..7ed9d026 100644\n --- a/foo.py\n +++ b/foo.py\n @@ -56,8 +56,8 @@\n Hello\n -world\n +beautiful\n +WORLD\n ```\n\n The values of content, pre_index, and post_index are:\n\n content pre_index post_index\n \"@@ -56,8 +56,8 @@\" None None\n \" Hello\" 56 56\n \"-world\" 57 None\n \"+beautiful\" None 57\n \"+WORLD\" None 58\n \"\"\"\n\n content: str\n is_patch: bool = False\n pre_index: Optional[int] = None\n post_index: Optional[int] = None\n\n def __hash__(self) -> int:\n return hash(\n (\n self.content,\n self.is_patch,\n self.pre_index,\n self.post_index,\n )\n )\n\n def build_line_count(self, padding: int, is_secret: bool = False) -> str:\n \"\"\"Return the formatted line count.\"\"\"\n line_count_style = (\n STYLE[\"line_count_secret\"] if is_secret else STYLE[\"line_count\"]\n )\n\n # File\n if not self.is_patch:\n return FILE_LINE_PREFIX.format(\n format_text(\n format_line_count(self.pre_index, padding), line_count_style\n )\n )\n\n # Patch\n pre_index = format_line_count(self.pre_index, padding)\n post_index = format_line_count(self.post_index, padding)\n\n return PATCH_LINE_PREFIX.format(\n format_text(pre_index, line_count_style),\n format_text(post_index, line_count_style),\n )", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2182, "extracted_code_full": "# Source: ggshield/core/lines.py\nclass Line:\n \"\"\"\n Represent a line in a document.\n\n - content: Content of the line\n - pre_index: Line index (deletion for patches, line index for files)\n - post_index: Line index (addition for patches)\n\n pre_index and post_index are 1-based.\n\n For files: pre_index is the line number, post_index is None.\n\n For patches: pre_index and post_index are line numbers relative to the *document\n modified by the patch*, not to the patch itself. This means that for a patch like\n this:\n\n ```\n diff --git a/foo.py b/foo.py\n index c53e550a..7ed9d026 100644\n --- a/foo.py\n +++ b/foo.py\n @@ -56,8 +56,8 @@\n Hello\n -world\n +beautiful\n +WORLD\n ```\n\n The values of content, pre_index, and post_index are:\n\n content pre_index post_index\n \"@@ -56,8 +56,8 @@\" None None\n \" Hello\" 56 56\n \"-world\" 57 None\n \"+beautiful\" None 57\n \"+WORLD\" None 58\n \"\"\"\n\n content: str\n is_patch: bool = False\n pre_index: Optional[int] = None\n post_index: Optional[int] = None\n\n def __hash__(self) -> int:\n return hash(\n (\n self.content,\n self.is_patch,\n self.pre_index,\n self.post_index,\n )\n )\n\n def build_line_count(self, padding: int, is_secret: bool = False) -> str:\n \"\"\"Return the formatted line count.\"\"\"\n line_count_style = (\n STYLE[\"line_count_secret\"] if is_secret else STYLE[\"line_count\"]\n )\n\n # File\n if not self.is_patch:\n return FILE_LINE_PREFIX.format(\n format_text(\n format_line_count(self.pre_index, padding), line_count_style\n )\n )\n\n # Patch\n pre_index = format_line_count(self.pre_index, padding)\n post_index = format_line_count(self.post_index, padding)\n\n return PATCH_LINE_PREFIX.format(\n format_text(pre_index, line_count_style),\n format_text(post_index, line_count_style),\n )", "n_chars_compressed": 2182, "compression_ratio": 1.0}, "tests/unit/verticals/secret/test_scan_docker.py::63": {"resolved_imports": ["ggshield/core/errors.py", "ggshield/core/scan/file.py", "ggshield/verticals/secret/docker.py"], "used_names": ["LayerInfo", "pytest"], "enclosing_function": "test_should_scan_layer", "extracted_code": "# Source: ggshield/verticals/secret/docker.py\nclass LayerInfo:\n filename: str\n command: str\n diff_id: str\n\n def should_scan(self) -> bool:\n \"\"\"\n Returns True if a layer should be scanned, False otherwise.\n Only COPY and ADD layers should be scanned.\n \"\"\"\n if self.command == \"\":\n # Some images contain layers with no commands. Since we don't know how they have\n # been created, we must scan them.\n # Examples of such images from Docker Hub:\n # - aevea/release-notary:0.9.7\n # - redhat/ubi8:8.6-754\n return True\n else:\n return LAYER_TO_SCAN_PATTERN.search(self.command) is not None", "n_imports_parsed": 12, "n_files_resolved": 3, "n_chars_extracted": 711, "extracted_code_full": "# Source: ggshield/verticals/secret/docker.py\nclass LayerInfo:\n filename: str\n command: str\n diff_id: str\n\n def should_scan(self) -> bool:\n \"\"\"\n Returns True if a layer should be scanned, False otherwise.\n Only COPY and ADD layers should be scanned.\n \"\"\"\n if self.command == \"\":\n # Some images contain layers with no commands. Since we don't know how they have\n # been created, we must scan them.\n # Examples of such images from Docker Hub:\n # - aevea/release-notary:0.9.7\n # - redhat/ubi8:8.6-754\n return True\n else:\n return LAYER_TO_SCAN_PATTERN.search(self.command) is not None", "n_chars_compressed": 711, "compression_ratio": 1.0}, "tests/unit/verticals/secret/output/test_json_output.py::597": {"resolved_imports": ["ggshield/core/config/user_config.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/scan/scannable.py", "ggshield/core/scan/file.py", "ggshield/utils/git_shell.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/secret_scanner.py", "ggshield/verticals/secret/output/secret_json_output_handler.py", "ggshield/verticals/secret/output/secret_output_handler.py"], "used_names": ["Filemode", "GGClient", "Mock", "Result", "Results", "SECRET_INCIDENT_MOCK", "SecretConfig", "SecretIncident", "SecretJSONOutputHandler", "SecretScanCollection", "StringScannable", "TWO_POLICY_BREAKS", "_ONE_LINE_AND_MULTILINE_PATCH_CONTENT", "deepcopy", "json", "pytest"], "enclosing_function": "test_with_incident_details", "extracted_code": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n\n# Source: ggshield/utils/git_shell.py\nclass Filemode(Enum):\n \"\"\"\n Enum class for git filemode.\n \"\"\"\n\n MODIFY = \"modified file\"\n DELETE = \"deleted file\"\n NEW = \"new file\"\n RENAME = \"renamed file\"\n FILE = \"file\"\n UNMERGED = \"unmerged file\"\n UNKNOWN = \"unknown\"\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Result:\n \"\"\"\n Return model for a scan which zips the information\n between the Scan result and its input file.\n \"\"\"\n\n filename: str # Name of the file/patch scanned\n filemode: Filemode\n path: Path\n url: str\n secrets: List[Secret]\n ignored_secrets_count_by_kind: Counter[IgnoreKind]\n\n @property\n def is_on_patch(self) -> bool:\n return self.filemode != Filemode.FILE\n\n def censor(self) -> None:\n for secret in self.secrets:\n for extended_match in secret.matches:\n cast(ExtendedMatch, extended_match).censor()\n\n @property\n def has_secrets(self) -> bool:\n return len(self.secrets) > 0\n\n @classmethod\n def from_scan_result(\n cls, file: Scannable, scan_result: ScanResult, secret_config: SecretConfig\n ) -> \"Result\":\n \"\"\"Creates a Result from a Scannable and a ScanResult.\n - Removes ignored policy breaks\n - replace matches by ExtendedMatches\n \"\"\"\n\n to_keep: List[Tuple[PolicyBreak, Optional[IgnoreReason]]] = []\n ignored_secrets_count_by_kind = Counter()\n for policy_break in scan_result.policy_breaks:\n ignore_reason = compute_ignore_reason(policy_break, secret_config)\n if ignore_reason is not None:\n if secret_config.all_secrets:\n to_keep.append((policy_break, ignore_reason))\n else:\n ignored_secrets_count_by_kind[ignore_reason.kind] += 1\n else:\n to_keep.append((policy_break, None))\n\n result = Result(\n filename=file.filename,\n filemode=file.filemode,\n path=file.path,\n url=file.url,\n secrets=[],\n ignored_secrets_count_by_kind=ignored_secrets_count_by_kind,\n )\n\n lines = get_lines_from_content(file.content, file.filemode)\n secrets = [\n Secret(\n validity=policy_break.validity,\n known_secret=policy_break.known_secret,\n incident_url=policy_break.incident_url,\n detector_display_name=policy_break.break_type,\n detector_name=policy_break.detector_name,\n detector_group_name=policy_break.detector_group_name,\n documentation_url=policy_break.documentation_url,\n matches=[\n ExtendedMatch.from_match(match, lines, result.is_on_patch)\n for match in policy_break.matches\n ],\n ignore_reason=ignore_reason,\n diff_kind=policy_break.diff_kind,\n is_vaulted=policy_break.is_vaulted,\n vault_type=getattr(policy_break, \"vault_type\", None),\n vault_name=getattr(policy_break, \"vault_name\", None),\n vault_path=getattr(policy_break, \"vault_path\", None),\n vault_path_count=getattr(policy_break, \"vault_path_count\", None),\n )\n for policy_break, ignore_reason in to_keep\n ]\n\n result.secrets = secrets\n return result\n\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)\n\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details\n\n\n# Source: ggshield/verticals/secret/output/secret_json_output_handler.py\nclass SecretJSONOutputHandler(SecretOutputHandler):\n def create_scan_dict(\n self,\n scan: SecretScanCollection,\n incident_details: Dict[str, SecretIncident],\n top: bool = True,\n ) -> Dict[str, Any]:\n scan_dict: Dict[str, Any] = {\n \"id\": scan.id,\n \"type\": scan.type,\n \"total_incidents\": 0,\n \"total_occurrences\": 0,\n }\n if scan.extra_info:\n scan_dict[\"extra_info\"] = scan.extra_info\n\n if top:\n scan_dict[\"secrets_engine_version\"] = VERSIONS.secrets_engine_version\n\n if scan.results:\n for result in scan.results.results:\n result_dict = self.process_result(result, incident_details)\n scan_dict.setdefault(\"results\", []).append(result_dict)\n scan_dict[\"total_incidents\"] += result_dict[\"total_incidents\"]\n scan_dict[\"total_occurrences\"] += result_dict[\"total_occurrences\"]\n\n for error in scan.results.errors:\n error_dict = self.process_error(error)\n scan_dict.setdefault(\"errors\", []).append(error_dict)\n\n if scan.scans:\n for inner_scan in scan.scans_with_results:\n inner_scan_dict = self.create_scan_dict(\n inner_scan, top=False, incident_details=incident_details\n )\n scan_dict.setdefault(\"scans\", []).append(inner_scan_dict)\n scan_dict[\"total_incidents\"] += inner_scan_dict[\"total_incidents\"]\n scan_dict[\"total_occurrences\"] += inner_scan_dict[\"total_occurrences\"]\n return scan_dict\n\n def _process_scan_impl(self, scan: SecretScanCollection) -> str:\n if self.with_incident_details:\n assert self.client\n incident_details = scan.get_incident_details(self.client)\n else:\n incident_details = {}\n scan_dict = self.create_scan_dict(\n scan, top=True, incident_details=incident_details\n )\n text = JSONScanCollectionSchema().dumps(scan_dict)\n # dumps() return type is not defined, so cast `text`, otherwise mypy complains\n return cast(str, text)\n\n def process_result(\n self, result: Result, incident_details: Dict[str, SecretIncident]\n ) -> Dict[str, Any]:\n result_dict: Dict[str, Any] = {\n \"filename\": result.path,\n \"mode\": result.filemode.name,\n \"incidents\": [],\n \"total_occurrences\": 0,\n \"total_incidents\": 0,\n }\n sha_dict = group_secrets_by_ignore_sha(result.secrets)\n result_dict[\"total_incidents\"] = len(sha_dict)\n\n if not self.show_secrets:\n result.censor()\n\n for ignore_sha, secrets in sha_dict.items():\n flattened_dict = self.serialized_secret(\n ignore_sha, secrets, incident_details\n )\n result_dict[\"incidents\"].append(flattened_dict)\n result_dict[\"total_occurrences\"] += flattened_dict[\"total_occurrences\"]\n return result_dict\n\n @staticmethod\n def process_error(error: Error) -> Dict[str, Any]:\n error_dict: Dict[str, Any] = {\n \"files\": [\n {\n \"filename\": filename,\n \"mode\": filemode.name,\n }\n for filename, filemode in error.files\n ],\n \"description\": error.description,\n }\n return error_dict\n\n def serialized_secret(\n self,\n ignore_sha: str,\n secrets: List[Secret],\n incident_details: Dict[str, SecretIncident],\n ) -> Dict[str, Any]:\n flattened_dict: Dict[str, Any] = {\n \"occurrences\": [],\n \"ignore_sha\": ignore_sha,\n \"policy\": secrets[0].policy,\n \"detector\": secrets[0].detector_display_name,\n \"total_occurrences\": len(secrets),\n }\n\n if secrets[0].documentation_url:\n flattened_dict[\"detector_documentation\"] = secrets[0].documentation_url\n\n if secrets[0].validity:\n flattened_dict[\"validity\"] = secrets[0].validity\n\n if secrets[0].known_secret:\n flattened_dict[\"known_secret\"] = secrets[0].known_secret\n flattened_dict[\"incident_url\"] = secrets[0].incident_url\n assert secrets[0].incident_url\n details = incident_details.get(secrets[0].incident_url)\n if details is not None:\n flattened_dict[\"incident_details\"] = details\n\n if secrets[0].ignore_reason is not None:\n flattened_dict[\"ignore_reason\"] = dataclasses.asdict(\n secrets[0].ignore_reason\n )\n\n if secrets[0].is_vaulted:\n flattened_dict[\"secret_vaulted\"] = secrets[0].is_vaulted\n\n # Add vault information if available\n if secrets[0].vault_path is not None:\n flattened_dict[\"vault_type\"] = secrets[0].vault_type\n flattened_dict[\"vault_name\"] = secrets[0].vault_name\n flattened_dict[\"vault_path\"] = secrets[0].vault_path\n flattened_dict[\"vault_path_count\"] = secrets[0].vault_path_count\n\n for secret in secrets:\n flattened_dict[\"occurrences\"].extend(self.serialize_secret_matches(secret))\n\n return flattened_dict\n\n def serialize_secret_matches(\n self,\n secret: Secret,\n ) -> List[Dict[str, Any]]:\n \"\"\"\n Serialize secret matches. The method uses MatchSpan to get the start and\n end index of the match.\n Returns a list of matches.\n \"\"\"\n matches_list: List[Dict[str, Any]] = []\n for match in secret.matches:\n assert isinstance(match, ExtendedMatch)\n\n match_dict: Dict[str, Any] = {\n \"match\": match.match,\n \"match_type\": match.match_type,\n \"line_start\": match.line_start,\n \"line_end\": match.line_end,\n \"index_start\": match.span.column_index_start,\n \"index_end\": match.span.column_index_end,\n }\n if match.pre_line_start is not None and match.pre_line_end is not None:\n match_dict[\"pre_line_start\"] = match.pre_line_start\n match_dict[\"pre_line_end\"] = match.pre_line_end\n if match.post_line_start is not None and match.post_line_end is not None:\n match_dict[\"post_line_start\"] = match.post_line_start\n match_dict[\"post_line_end\"] = match.post_line_end\n matches_list.append(match_dict)\n return matches_list", "n_imports_parsed": 21, "n_files_resolved": 11, "n_chars_extracted": 16264, "extracted_code_full": "# Source: ggshield/core/config/user_config.py\nclass SecretConfig(FilteredConfig):\n \"\"\"\n Holds all user-defined secret-specific settings\n \"\"\"\n\n show_secrets: bool = False\n ignored_detectors: Set[str] = field(default_factory=set)\n ignored_matches: List[IgnoredMatch] = field(default_factory=list)\n ignored_paths: Set[str] = field(default_factory=set)\n ignore_known_secrets: bool = False\n with_incident_details: bool = False\n # if configuration key is left unset the dashboard's remediation message is used.\n all_secrets: bool = False\n prereceive_remediation_message: str = \"\"\n source_uuid: Optional[UUID] = None\n\n def add_ignored_match(self, secret: IgnoredMatch) -> None:\n \"\"\"\n Add secret to ignored_matches.\n \"\"\"\n for match in self.ignored_matches:\n if match.match == secret.match:\n # take the opportunity to name the ignored match\n if not match.name:\n match.name = secret.name\n return\n self.ignored_matches.append(secret)\n\n def dump_for_monitoring(self) -> str:\n return json.dumps(\n {\n \"show_secrets\": self.show_secrets,\n \"ignored_detectors_count\": len(self.ignored_detectors),\n \"ignored_matches_count\": len(self.ignored_matches),\n \"ignored_paths_count\": len(self.ignored_paths),\n \"ignore_known_secrets\": self.ignore_known_secrets,\n \"with_incident_details\": self.with_incident_details,\n \"has_prereceive_remediation_message\": bool(\n self.prereceive_remediation_message\n ),\n \"all_secrets\": self.all_secrets,\n \"source_uuid\": self.source_uuid,\n }\n )\n\n\n# Source: ggshield/core/scan/scannable.py\nclass StringScannable(Scannable):\n \"\"\"Implementation of Scannable for content already loaded in memory\"\"\"\n\n def __init__(self, url: str, content: str, filemode: Filemode = Filemode.FILE):\n super().__init__(filemode)\n self._url = url\n self._path: Optional[Path] = None\n self._content = content\n\n def _read_content(self) -> None:\n assert self._content is not None\n if self._utf8_encoded_size is None:\n self._utf8_encoded_size = len(self._content.encode(errors=\"replace\"))\n\n @property\n def url(self) -> str:\n return self._url\n\n @property\n def filename(self) -> str:\n return str(self._url)\n\n @property\n def path(self) -> Path:\n if self._path is None:\n result = urllib.parse.urlparse(self._url)\n self._path = Path(result.path)\n return self._path\n\n def is_longer_than(self, max_utf8_encoded_size: int) -> bool:\n self._read_content()\n assert self._utf8_encoded_size is not None\n return self._utf8_encoded_size > max_utf8_encoded_size\n\n\n# Source: ggshield/utils/git_shell.py\nclass Filemode(Enum):\n \"\"\"\n Enum class for git filemode.\n \"\"\"\n\n MODIFY = \"modified file\"\n DELETE = \"deleted file\"\n NEW = \"new file\"\n RENAME = \"renamed file\"\n FILE = \"file\"\n UNMERGED = \"unmerged file\"\n UNKNOWN = \"unknown\"\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass Result:\n \"\"\"\n Return model for a scan which zips the information\n between the Scan result and its input file.\n \"\"\"\n\n filename: str # Name of the file/patch scanned\n filemode: Filemode\n path: Path\n url: str\n secrets: List[Secret]\n ignored_secrets_count_by_kind: Counter[IgnoreKind]\n\n @property\n def is_on_patch(self) -> bool:\n return self.filemode != Filemode.FILE\n\n def censor(self) -> None:\n for secret in self.secrets:\n for extended_match in secret.matches:\n cast(ExtendedMatch, extended_match).censor()\n\n @property\n def has_secrets(self) -> bool:\n return len(self.secrets) > 0\n\n @classmethod\n def from_scan_result(\n cls, file: Scannable, scan_result: ScanResult, secret_config: SecretConfig\n ) -> \"Result\":\n \"\"\"Creates a Result from a Scannable and a ScanResult.\n - Removes ignored policy breaks\n - replace matches by ExtendedMatches\n \"\"\"\n\n to_keep: List[Tuple[PolicyBreak, Optional[IgnoreReason]]] = []\n ignored_secrets_count_by_kind = Counter()\n for policy_break in scan_result.policy_breaks:\n ignore_reason = compute_ignore_reason(policy_break, secret_config)\n if ignore_reason is not None:\n if secret_config.all_secrets:\n to_keep.append((policy_break, ignore_reason))\n else:\n ignored_secrets_count_by_kind[ignore_reason.kind] += 1\n else:\n to_keep.append((policy_break, None))\n\n result = Result(\n filename=file.filename,\n filemode=file.filemode,\n path=file.path,\n url=file.url,\n secrets=[],\n ignored_secrets_count_by_kind=ignored_secrets_count_by_kind,\n )\n\n lines = get_lines_from_content(file.content, file.filemode)\n secrets = [\n Secret(\n validity=policy_break.validity,\n known_secret=policy_break.known_secret,\n incident_url=policy_break.incident_url,\n detector_display_name=policy_break.break_type,\n detector_name=policy_break.detector_name,\n detector_group_name=policy_break.detector_group_name,\n documentation_url=policy_break.documentation_url,\n matches=[\n ExtendedMatch.from_match(match, lines, result.is_on_patch)\n for match in policy_break.matches\n ],\n ignore_reason=ignore_reason,\n diff_kind=policy_break.diff_kind,\n is_vaulted=policy_break.is_vaulted,\n vault_type=getattr(policy_break, \"vault_type\", None),\n vault_name=getattr(policy_break, \"vault_name\", None),\n vault_path=getattr(policy_break, \"vault_path\", None),\n vault_path_count=getattr(policy_break, \"vault_path_count\", None),\n )\n for policy_break, ignore_reason in to_keep\n ]\n\n result.secrets = secrets\n return result\n\nclass Results:\n \"\"\"\n Return model for a scan with the results and errors of the scan\n\n Not a NamedTuple like the others because it causes mypy 0.961 to crash on the\n `from_exception()` method (!)\n\n Similar crash: https://github.com/python/mypy/issues/12629\n \"\"\"\n\n results: List[Result] = field(default_factory=list)\n errors: List[Error] = field(default_factory=list)\n\n @staticmethod\n def from_exception(exc: Exception) -> \"Results\":\n \"\"\"Create a Results representing a failure\"\"\"\n exc_class_name = exc.__class__.__name__\n description = f\"{exc_class_name}: {str(exc) or '-'}\"\n error = Error(files=[], description=description)\n return Results(results=[], errors=[error])\n\n def extend(self, others: \"Results\") -> None:\n self.results.extend(others.results)\n self.errors.extend(others.errors)\n\n @property\n def has_secrets(self) -> bool:\n return any(x.has_secrets for x in self.results)\n\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details\n\n\n# Source: ggshield/verticals/secret/output/secret_json_output_handler.py\nclass SecretJSONOutputHandler(SecretOutputHandler):\n def create_scan_dict(\n self,\n scan: SecretScanCollection,\n incident_details: Dict[str, SecretIncident],\n top: bool = True,\n ) -> Dict[str, Any]:\n scan_dict: Dict[str, Any] = {\n \"id\": scan.id,\n \"type\": scan.type,\n \"total_incidents\": 0,\n \"total_occurrences\": 0,\n }\n if scan.extra_info:\n scan_dict[\"extra_info\"] = scan.extra_info\n\n if top:\n scan_dict[\"secrets_engine_version\"] = VERSIONS.secrets_engine_version\n\n if scan.results:\n for result in scan.results.results:\n result_dict = self.process_result(result, incident_details)\n scan_dict.setdefault(\"results\", []).append(result_dict)\n scan_dict[\"total_incidents\"] += result_dict[\"total_incidents\"]\n scan_dict[\"total_occurrences\"] += result_dict[\"total_occurrences\"]\n\n for error in scan.results.errors:\n error_dict = self.process_error(error)\n scan_dict.setdefault(\"errors\", []).append(error_dict)\n\n if scan.scans:\n for inner_scan in scan.scans_with_results:\n inner_scan_dict = self.create_scan_dict(\n inner_scan, top=False, incident_details=incident_details\n )\n scan_dict.setdefault(\"scans\", []).append(inner_scan_dict)\n scan_dict[\"total_incidents\"] += inner_scan_dict[\"total_incidents\"]\n scan_dict[\"total_occurrences\"] += inner_scan_dict[\"total_occurrences\"]\n return scan_dict\n\n def _process_scan_impl(self, scan: SecretScanCollection) -> str:\n if self.with_incident_details:\n assert self.client\n incident_details = scan.get_incident_details(self.client)\n else:\n incident_details = {}\n scan_dict = self.create_scan_dict(\n scan, top=True, incident_details=incident_details\n )\n text = JSONScanCollectionSchema().dumps(scan_dict)\n # dumps() return type is not defined, so cast `text`, otherwise mypy complains\n return cast(str, text)\n\n def process_result(\n self, result: Result, incident_details: Dict[str, SecretIncident]\n ) -> Dict[str, Any]:\n result_dict: Dict[str, Any] = {\n \"filename\": result.path,\n \"mode\": result.filemode.name,\n \"incidents\": [],\n \"total_occurrences\": 0,\n \"total_incidents\": 0,\n }\n sha_dict = group_secrets_by_ignore_sha(result.secrets)\n result_dict[\"total_incidents\"] = len(sha_dict)\n\n if not self.show_secrets:\n result.censor()\n\n for ignore_sha, secrets in sha_dict.items():\n flattened_dict = self.serialized_secret(\n ignore_sha, secrets, incident_details\n )\n result_dict[\"incidents\"].append(flattened_dict)\n result_dict[\"total_occurrences\"] += flattened_dict[\"total_occurrences\"]\n return result_dict\n\n @staticmethod\n def process_error(error: Error) -> Dict[str, Any]:\n error_dict: Dict[str, Any] = {\n \"files\": [\n {\n \"filename\": filename,\n \"mode\": filemode.name,\n }\n for filename, filemode in error.files\n ],\n \"description\": error.description,\n }\n return error_dict\n\n def serialized_secret(\n self,\n ignore_sha: str,\n secrets: List[Secret],\n incident_details: Dict[str, SecretIncident],\n ) -> Dict[str, Any]:\n flattened_dict: Dict[str, Any] = {\n \"occurrences\": [],\n \"ignore_sha\": ignore_sha,\n \"policy\": secrets[0].policy,\n \"detector\": secrets[0].detector_display_name,\n \"total_occurrences\": len(secrets),\n }\n\n if secrets[0].documentation_url:\n flattened_dict[\"detector_documentation\"] = secrets[0].documentation_url\n\n if secrets[0].validity:\n flattened_dict[\"validity\"] = secrets[0].validity\n\n if secrets[0].known_secret:\n flattened_dict[\"known_secret\"] = secrets[0].known_secret\n flattened_dict[\"incident_url\"] = secrets[0].incident_url\n assert secrets[0].incident_url\n details = incident_details.get(secrets[0].incident_url)\n if details is not None:\n flattened_dict[\"incident_details\"] = details\n\n if secrets[0].ignore_reason is not None:\n flattened_dict[\"ignore_reason\"] = dataclasses.asdict(\n secrets[0].ignore_reason\n )\n\n if secrets[0].is_vaulted:\n flattened_dict[\"secret_vaulted\"] = secrets[0].is_vaulted\n\n # Add vault information if available\n if secrets[0].vault_path is not None:\n flattened_dict[\"vault_type\"] = secrets[0].vault_type\n flattened_dict[\"vault_name\"] = secrets[0].vault_name\n flattened_dict[\"vault_path\"] = secrets[0].vault_path\n flattened_dict[\"vault_path_count\"] = secrets[0].vault_path_count\n\n for secret in secrets:\n flattened_dict[\"occurrences\"].extend(self.serialize_secret_matches(secret))\n\n return flattened_dict\n\n def serialize_secret_matches(\n self,\n secret: Secret,\n ) -> List[Dict[str, Any]]:\n \"\"\"\n Serialize secret matches. The method uses MatchSpan to get the start and\n end index of the match.\n Returns a list of matches.\n \"\"\"\n matches_list: List[Dict[str, Any]] = []\n for match in secret.matches:\n assert isinstance(match, ExtendedMatch)\n\n match_dict: Dict[str, Any] = {\n \"match\": match.match,\n \"match_type\": match.match_type,\n \"line_start\": match.line_start,\n \"line_end\": match.line_end,\n \"index_start\": match.span.column_index_start,\n \"index_end\": match.span.column_index_end,\n }\n if match.pre_line_start is not None and match.pre_line_end is not None:\n match_dict[\"pre_line_start\"] = match.pre_line_start\n match_dict[\"pre_line_end\"] = match.pre_line_end\n if match.post_line_start is not None and match.post_line_end is not None:\n match_dict[\"post_line_start\"] = match.post_line_start\n match_dict[\"post_line_end\"] = match.post_line_end\n matches_list.append(match_dict)\n return matches_list", "n_chars_compressed": 16264, "compression_ratio": 1.0}, "tests/unit/verticals/hmsl/test_hmsl_client.py::120": {"resolved_imports": ["ggshield/__init__.py", "ggshield/verticals/hmsl/client.py", "ggshield/verticals/hmsl/crypto.py"], "used_names": ["mock"], "enclosing_function": "test_hmsl_client_decode_response", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/unit/core/plugin/test_enterprise_config.py::38": {"resolved_imports": ["ggshield/core/config/enterprise_config.py"], "used_names": ["EnterpriseConfig"], "enclosing_function": "test_empty_config", "extracted_code": "# Source: ggshield/core/config/enterprise_config.py\nclass EnterpriseConfig:\n \"\"\"Enterprise configuration stored in ~/.config/ggshield/enterprise_config.yaml\"\"\"\n\n plugins: Dict[str, PluginConfig] = field(default_factory=dict)\n\n @classmethod\n def load(cls) -> \"EnterpriseConfig\":\n \"\"\"Load enterprise config from file.\"\"\"\n config_path = get_enterprise_config_filepath()\n data = load_yaml_dict(config_path)\n\n if data is None:\n return cls()\n\n # Convert plugin configs from dict\n plugins: Dict[str, PluginConfig] = {}\n for name, plugin_data in data.get(\"plugins\", {}).items():\n if isinstance(plugin_data, dict):\n plugins[name] = PluginConfig(\n enabled=plugin_data.get(\"enabled\", True),\n version=plugin_data.get(\"version\"),\n auto_update=plugin_data.get(\"auto_update\", True),\n )\n elif isinstance(plugin_data, bool):\n # Simple format: just enabled/disabled\n plugins[name] = PluginConfig(enabled=plugin_data)\n else:\n plugins[name] = PluginConfig(enabled=True)\n\n return cls(plugins=plugins)\n\n def save(self) -> None:\n \"\"\"Save enterprise config to file.\"\"\"\n config_path = get_enterprise_config_filepath()\n\n # Convert to dict for saving\n data: Dict[str, Any] = {\n \"plugins\": {\n name: {\n \"enabled\": cfg.enabled,\n \"version\": cfg.version,\n \"auto_update\": cfg.auto_update,\n }\n for name, cfg in self.plugins.items()\n }\n }\n\n # Remove None values for cleaner YAML\n for plugin_data in data[\"plugins\"].values():\n if plugin_data[\"version\"] is None:\n del plugin_data[\"version\"]\n\n save_yaml_dict(data, config_path)\n\n def enable_plugin(self, plugin_name: str, version: Optional[str] = None) -> None:\n \"\"\"Enable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n self.plugins[plugin_name] = PluginConfig()\n\n self.plugins[plugin_name].enabled = True\n if version:\n self.plugins[plugin_name].version = version\n\n def disable_plugin(self, plugin_name: str) -> None:\n \"\"\"Disable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n raise ValueError(f\"Plugin '{plugin_name}' is not configured\")\n\n self.plugins[plugin_name].enabled = False\n\n def is_plugin_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n # Default: disabled if not explicitly configured\n return plugin_config.enabled if plugin_config else False\n\n def get_plugin_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the configured version of a plugin.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n return plugin_config.version if plugin_config else None\n\n def remove_plugin(self, plugin_name: str) -> bool:\n \"\"\"Remove a plugin from configuration.\"\"\"\n if plugin_name in self.plugins:\n del self.plugins[plugin_name]\n return True\n return False", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 3298, "extracted_code_full": "# Source: ggshield/core/config/enterprise_config.py\nclass EnterpriseConfig:\n \"\"\"Enterprise configuration stored in ~/.config/ggshield/enterprise_config.yaml\"\"\"\n\n plugins: Dict[str, PluginConfig] = field(default_factory=dict)\n\n @classmethod\n def load(cls) -> \"EnterpriseConfig\":\n \"\"\"Load enterprise config from file.\"\"\"\n config_path = get_enterprise_config_filepath()\n data = load_yaml_dict(config_path)\n\n if data is None:\n return cls()\n\n # Convert plugin configs from dict\n plugins: Dict[str, PluginConfig] = {}\n for name, plugin_data in data.get(\"plugins\", {}).items():\n if isinstance(plugin_data, dict):\n plugins[name] = PluginConfig(\n enabled=plugin_data.get(\"enabled\", True),\n version=plugin_data.get(\"version\"),\n auto_update=plugin_data.get(\"auto_update\", True),\n )\n elif isinstance(plugin_data, bool):\n # Simple format: just enabled/disabled\n plugins[name] = PluginConfig(enabled=plugin_data)\n else:\n plugins[name] = PluginConfig(enabled=True)\n\n return cls(plugins=plugins)\n\n def save(self) -> None:\n \"\"\"Save enterprise config to file.\"\"\"\n config_path = get_enterprise_config_filepath()\n\n # Convert to dict for saving\n data: Dict[str, Any] = {\n \"plugins\": {\n name: {\n \"enabled\": cfg.enabled,\n \"version\": cfg.version,\n \"auto_update\": cfg.auto_update,\n }\n for name, cfg in self.plugins.items()\n }\n }\n\n # Remove None values for cleaner YAML\n for plugin_data in data[\"plugins\"].values():\n if plugin_data[\"version\"] is None:\n del plugin_data[\"version\"]\n\n save_yaml_dict(data, config_path)\n\n def enable_plugin(self, plugin_name: str, version: Optional[str] = None) -> None:\n \"\"\"Enable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n self.plugins[plugin_name] = PluginConfig()\n\n self.plugins[plugin_name].enabled = True\n if version:\n self.plugins[plugin_name].version = version\n\n def disable_plugin(self, plugin_name: str) -> None:\n \"\"\"Disable a plugin.\"\"\"\n if plugin_name not in self.plugins:\n raise ValueError(f\"Plugin '{plugin_name}' is not configured\")\n\n self.plugins[plugin_name].enabled = False\n\n def is_plugin_enabled(self, plugin_name: str) -> bool:\n \"\"\"Check if a plugin is enabled.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n # Default: disabled if not explicitly configured\n return plugin_config.enabled if plugin_config else False\n\n def get_plugin_version(self, plugin_name: str) -> Optional[str]:\n \"\"\"Get the configured version of a plugin.\"\"\"\n plugin_config = self.plugins.get(plugin_name)\n return plugin_config.version if plugin_config else None\n\n def remove_plugin(self, plugin_name: str) -> bool:\n \"\"\"Remove a plugin from configuration.\"\"\"\n if plugin_name in self.plugins:\n del self.plugins[plugin_name]\n return True\n return False", "n_chars_compressed": 3298, "compression_ratio": 1.0}, "tests/unit/core/test_text_utils.py::46": {"resolved_imports": ["ggshield/core/text_utils.py"], "used_names": ["clip_long_line", "pytest"], "enclosing_function": "test_clip_long_line", "extracted_code": "# Source: ggshield/core/text_utils.py\ndef clip_long_line(\n content: str,\n max_length: int,\n before: bool = False,\n after: bool = False,\n min_length: int = 10,\n is_patch: bool = False,\n) -> str:\n \"\"\"\n Add a \"…\" character before and/or after the given string\n if it exceeds a maximum length.\n \"\"\"\n ellipsis = \"…\"\n\n if is_patch:\n # If we are clipping a patch, move the first character out of `content` so that\n # we can keep it visible. It's important because this character is the patch\n # symbol.\n prefix = content[:1]\n content = content[1:]\n max_length -= 1\n else:\n prefix = \"\"\n\n content_length = len(content)\n if content_length > max_length:\n if before and after and content_length > max_length + 1:\n content = (\n ellipsis\n + content[\n (content_length - max(max_length, min_length)) // 2\n + 1 : (content_length + max(max_length, min_length)) // 2\n - 1\n ]\n + ellipsis\n )\n elif after:\n content = content[: max(max_length - 1, min_length)] + ellipsis\n elif before:\n content = ellipsis + content[min(-max_length + 1, -min_length) :]\n return prefix + content", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1333, "extracted_code_full": "# Source: ggshield/core/text_utils.py\ndef clip_long_line(\n content: str,\n max_length: int,\n before: bool = False,\n after: bool = False,\n min_length: int = 10,\n is_patch: bool = False,\n) -> str:\n \"\"\"\n Add a \"…\" character before and/or after the given string\n if it exceeds a maximum length.\n \"\"\"\n ellipsis = \"…\"\n\n if is_patch:\n # If we are clipping a patch, move the first character out of `content` so that\n # we can keep it visible. It's important because this character is the patch\n # symbol.\n prefix = content[:1]\n content = content[1:]\n max_length -= 1\n else:\n prefix = \"\"\n\n content_length = len(content)\n if content_length > max_length:\n if before and after and content_length > max_length + 1:\n content = (\n ellipsis\n + content[\n (content_length - max(max_length, min_length)) // 2\n + 1 : (content_length + max(max_length, min_length)) // 2\n - 1\n ]\n + ellipsis\n )\n elif after:\n content = content[: max(max_length - 1, min_length)] + ellipsis\n elif before:\n content = ellipsis + content[min(-max_length + 1, -min_length) :]\n return prefix + content", "n_chars_compressed": 1333, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_path.py::37": {"resolved_imports": [], "used_names": ["GG_VALID_TOKEN", "GG_VALID_TOKEN_IGNORE_SHA", "Path", "pytest", "recreate_censored_string", "run_ggshield_scan"], "enclosing_function": "test_scan_path", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/verticals/hmsl/secret_manager/hashicorp_vault/test_api_client.py::280": {"resolved_imports": ["ggshield/verticals/hmsl/secret_manager/hashicorp_vault/api_client.py", "ggshield/verticals/hmsl/secret_manager/hashicorp_vault/exceptions.py", "ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py"], "used_names": ["VaultAPIClient", "VaultKvMount", "patch"], "enclosing_function": "test_get_secrets_or_empty_success", "extracted_code": "# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/api_client.py\nclass VaultAPIClient:\n \"\"\"Client to interact with Vault API.\"\"\"\n\n def __init__(self, vault_url: str, api_token: str) -> None:\n self.session = requests.Session()\n self.session.headers[\"X-Vault-Token\"] = api_token\n\n if not vault_url.startswith(\"http://\") and not vault_url.startswith(\"https://\"):\n vault_url = f\"https://{vault_url}\"\n try:\n self.vault_url = urlparse(vault_url).geturl()\n except ValueError:\n raise VaultInvalidUrlError(\n f\"cannot parse the Vault URL '{vault_url}'. Are you sure it is valid?\"\n )\n\n def _make_request(\n self, endpoint: str, method: str = \"GET\", api_version: str = \"v1\"\n ) -> Dict[str, Any]:\n \"\"\" \"\n Make request to the API.\n \"\"\"\n api_res = self.session.request(\n method, f\"{self.vault_url}/{api_version}/{endpoint}\"\n )\n api_res.raise_for_status()\n\n return api_res.json()\n\n def get_kv_mounts(self) -> Generator[VaultKvMount, None, None]:\n \"\"\"\n Get all kv mounts for the Vault instance.\n\n Will try the /sys/mounts endpoint first, and if there is a forbidden error\n fallback to the /sys/internal/ui internal endpoint.\n \"\"\"\n\n try:\n api_res = self._make_request(\"sys/mounts\")[\"data\"]\n except requests.HTTPError:\n api_res = self._make_request(\"sys/internal/ui/mounts\")[\"data\"][\"secret\"]\n\n for key, value in api_res.items():\n if value[\"type\"] != \"kv\":\n continue\n\n yield VaultKvMount(\n name=key.rstrip(\"/\"), # remove trailing slash\n version=value[\"options\"][\"version\"],\n )\n\n def list_kv_items(self, mount: VaultKvMount, path: str) -> List[str]:\n logger.debug(f\"Listing kv items for mount {mount.name} at {path}\")\n\n api_endpoint = (\n f\"{mount.name}/metadata/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n\n try:\n api_res = self._make_request(api_endpoint, method=\"LIST\")\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n # The API return 404 when trying to list items when the path is a file\n # and not a directory\n if exc.response.status_code == 404:\n raise VaultPathIsNotADirectoryError()\n\n raise exc\n\n return [item.rstrip(\"/\") for item in api_res[\"data\"][\"keys\"]]\n\n def get_kv_secrets(self, mount: VaultKvMount, path: str) -> List[Tuple[str, str]]:\n \"\"\"\n Get secrets from the specified mount at the specified path.\n\n Returns a list of tuples containing secret key and secret value\n \"\"\"\n\n logger.debug(f\"Getting secrets at {path}\")\n api_endpoint = (\n f\"{mount.name}/data/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n try:\n api_res = self._make_request(api_endpoint)\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n if exc.response.status_code == 404:\n raise VaultNotFoundItemError(\n f\"{path} was not found: it's either not a file, \"\n \"was deleted or cannot be accessed with the current token\"\n )\n\n raise exc\n\n data = api_res[\"data\"][\"data\"] if mount.version == \"2\" else api_res[\"data\"]\n return [\n (f\"{path}/{secret_name}\", secret_value)\n for secret_name, secret_value in data.items()\n ]\n\n def _get_secrets_or_empty(\n self, mount: VaultKvMount, folder_path: str\n ) -> VaultSecrets:\n \"\"\"\n Call get_kv_secrets on the given mount and folder path.\n\n Return the secrets or an empty list if VaultNotFoundItemError was raised.\n \"\"\"\n try:\n return VaultSecrets(\n secrets=self.get_kv_secrets(mount, folder_path),\n not_fetched_paths=[],\n )\n except VaultNotFoundItemError as exc:\n logger.debug(f\"Not found error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n def _get_secrets_from_path(\n self, mount: VaultKvMount, folder_path: str, recursive: bool\n ) -> VaultSecrets:\n \"\"\"\n Get the secrets on the given mount and folder path.\n If recursive is True, iterate recursively on subfolders.\n\n Return the secrets or an empty list if errors were raised.\n \"\"\"\n # Get current directory secret\n try:\n subfolders = self.list_kv_items(mount, folder_path)\n except VaultPathIsNotADirectoryError:\n return self._get_secrets_or_empty(mount, folder_path)\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n if not recursive:\n return VaultSecrets(secrets=[], not_fetched_paths=[])\n\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for subfolder in subfolders:\n subfolder_result = self._get_secrets_from_path(\n mount, f\"{folder_path}/{subfolder}\", True\n )\n result.secrets += subfolder_result.secrets\n result.not_fetched_paths += subfolder_result.not_fetched_paths\n\n return result\n\n def get_secrets(\n self, mount: VaultKvMount, path: str, recursive: bool\n ) -> VaultSecrets:\n # Check first if it's a directory\n try:\n keys = self.list_kv_items(mount, path)\n except VaultPathIsNotADirectoryError:\n # If it's a file, return directly\n return self._get_secrets_or_empty(mount, path)\n\n # If it's a folder, get secrets of the folder\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for folder in keys:\n folder_path = f\"{path}/{folder}\".strip(\"/\")\n folder_result = self._get_secrets_from_path(mount, folder_path, recursive)\n result.secrets += folder_result.secrets\n result.not_fetched_paths += folder_result.not_fetched_paths\n\n return result\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py\nclass VaultKvMount(VaultMount):\n \"\"\"\n Model to represent a Vault KV mount.\n \"\"\"\n\n version: str", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 7009, "extracted_code_full": "# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/api_client.py\nclass VaultAPIClient:\n \"\"\"Client to interact with Vault API.\"\"\"\n\n def __init__(self, vault_url: str, api_token: str) -> None:\n self.session = requests.Session()\n self.session.headers[\"X-Vault-Token\"] = api_token\n\n if not vault_url.startswith(\"http://\") and not vault_url.startswith(\"https://\"):\n vault_url = f\"https://{vault_url}\"\n try:\n self.vault_url = urlparse(vault_url).geturl()\n except ValueError:\n raise VaultInvalidUrlError(\n f\"cannot parse the Vault URL '{vault_url}'. Are you sure it is valid?\"\n )\n\n def _make_request(\n self, endpoint: str, method: str = \"GET\", api_version: str = \"v1\"\n ) -> Dict[str, Any]:\n \"\"\" \"\n Make request to the API.\n \"\"\"\n api_res = self.session.request(\n method, f\"{self.vault_url}/{api_version}/{endpoint}\"\n )\n api_res.raise_for_status()\n\n return api_res.json()\n\n def get_kv_mounts(self) -> Generator[VaultKvMount, None, None]:\n \"\"\"\n Get all kv mounts for the Vault instance.\n\n Will try the /sys/mounts endpoint first, and if there is a forbidden error\n fallback to the /sys/internal/ui internal endpoint.\n \"\"\"\n\n try:\n api_res = self._make_request(\"sys/mounts\")[\"data\"]\n except requests.HTTPError:\n api_res = self._make_request(\"sys/internal/ui/mounts\")[\"data\"][\"secret\"]\n\n for key, value in api_res.items():\n if value[\"type\"] != \"kv\":\n continue\n\n yield VaultKvMount(\n name=key.rstrip(\"/\"), # remove trailing slash\n version=value[\"options\"][\"version\"],\n )\n\n def list_kv_items(self, mount: VaultKvMount, path: str) -> List[str]:\n logger.debug(f\"Listing kv items for mount {mount.name} at {path}\")\n\n api_endpoint = (\n f\"{mount.name}/metadata/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n\n try:\n api_res = self._make_request(api_endpoint, method=\"LIST\")\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n # The API return 404 when trying to list items when the path is a file\n # and not a directory\n if exc.response.status_code == 404:\n raise VaultPathIsNotADirectoryError()\n\n raise exc\n\n return [item.rstrip(\"/\") for item in api_res[\"data\"][\"keys\"]]\n\n def get_kv_secrets(self, mount: VaultKvMount, path: str) -> List[Tuple[str, str]]:\n \"\"\"\n Get secrets from the specified mount at the specified path.\n\n Returns a list of tuples containing secret key and secret value\n \"\"\"\n\n logger.debug(f\"Getting secrets at {path}\")\n api_endpoint = (\n f\"{mount.name}/data/{path}\"\n if mount.version == \"2\"\n else f\"{mount.name}/{path}\"\n )\n try:\n api_res = self._make_request(api_endpoint)\n except requests.HTTPError as exc:\n if exc.response.status_code == 403:\n raise VaultForbiddenItemError(\n f\"cannot access item on mount {mount.name} at path {path}\"\n )\n\n if exc.response.status_code == 404:\n raise VaultNotFoundItemError(\n f\"{path} was not found: it's either not a file, \"\n \"was deleted or cannot be accessed with the current token\"\n )\n\n raise exc\n\n data = api_res[\"data\"][\"data\"] if mount.version == \"2\" else api_res[\"data\"]\n return [\n (f\"{path}/{secret_name}\", secret_value)\n for secret_name, secret_value in data.items()\n ]\n\n def _get_secrets_or_empty(\n self, mount: VaultKvMount, folder_path: str\n ) -> VaultSecrets:\n \"\"\"\n Call get_kv_secrets on the given mount and folder path.\n\n Return the secrets or an empty list if VaultNotFoundItemError was raised.\n \"\"\"\n try:\n return VaultSecrets(\n secrets=self.get_kv_secrets(mount, folder_path),\n not_fetched_paths=[],\n )\n except VaultNotFoundItemError as exc:\n logger.debug(f\"Not found error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n def _get_secrets_from_path(\n self, mount: VaultKvMount, folder_path: str, recursive: bool\n ) -> VaultSecrets:\n \"\"\"\n Get the secrets on the given mount and folder path.\n If recursive is True, iterate recursively on subfolders.\n\n Return the secrets or an empty list if errors were raised.\n \"\"\"\n # Get current directory secret\n try:\n subfolders = self.list_kv_items(mount, folder_path)\n except VaultPathIsNotADirectoryError:\n return self._get_secrets_or_empty(mount, folder_path)\n except VaultForbiddenItemError as exc:\n logger.debug(f\"Forbidden error: {exc}\")\n return VaultSecrets(secrets=[], not_fetched_paths=[folder_path])\n\n if not recursive:\n return VaultSecrets(secrets=[], not_fetched_paths=[])\n\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for subfolder in subfolders:\n subfolder_result = self._get_secrets_from_path(\n mount, f\"{folder_path}/{subfolder}\", True\n )\n result.secrets += subfolder_result.secrets\n result.not_fetched_paths += subfolder_result.not_fetched_paths\n\n return result\n\n def get_secrets(\n self, mount: VaultKvMount, path: str, recursive: bool\n ) -> VaultSecrets:\n # Check first if it's a directory\n try:\n keys = self.list_kv_items(mount, path)\n except VaultPathIsNotADirectoryError:\n # If it's a file, return directly\n return self._get_secrets_or_empty(mount, path)\n\n # If it's a folder, get secrets of the folder\n result = VaultSecrets(secrets=[], not_fetched_paths=[])\n for folder in keys:\n folder_path = f\"{path}/{folder}\".strip(\"/\")\n folder_result = self._get_secrets_from_path(mount, folder_path, recursive)\n result.secrets += folder_result.secrets\n result.not_fetched_paths += folder_result.not_fetched_paths\n\n return result\n\n\n# Source: ggshield/verticals/hmsl/secret_manager/hashicorp_vault/models.py\nclass VaultKvMount(VaultMount):\n \"\"\"\n Model to represent a Vault KV mount.\n \"\"\"\n\n version: str", "n_chars_compressed": 7009, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_wheel_utils.py::82": {"resolved_imports": ["ggshield/core/plugin/wheel_utils.py"], "used_names": ["Path", "extract_wheel_metadata"], "enclosing_function": "test_extract_minimal_metadata", "extracted_code": "# Source: ggshield/core/plugin/wheel_utils.py\ndef extract_wheel_metadata(wheel_path: Path) -> WheelMetadata:\n \"\"\"\n Extract metadata from a wheel file.\n\n Reads the METADATA file from the wheel's dist-info directory.\n\n Args:\n wheel_path: Path to the wheel file.\n\n Returns:\n WheelMetadata with name, version, and optional fields.\n\n Raises:\n InvalidWheelError: If the wheel is not a valid ZIP file.\n MetadataNotFoundError: If METADATA file is not found.\n WheelError: For other parsing errors.\n \"\"\"\n if not wheel_path.exists():\n raise InvalidWheelError(f\"Wheel file not found: {wheel_path}\")\n\n if not wheel_path.suffix == \".whl\":\n raise InvalidWheelError(f\"Not a wheel file: {wheel_path}\")\n\n try:\n with ZipFile(wheel_path, \"r\") as zf:\n metadata_path = _find_metadata_file(zf)\n if metadata_path is None:\n raise MetadataNotFoundError(\n f\"METADATA file not found in wheel: {wheel_path}\"\n )\n\n metadata_content = zf.read(metadata_path).decode(\"utf-8\")\n return _parse_metadata(metadata_content)\n\n except BadZipFile as e:\n raise InvalidWheelError(f\"Invalid wheel file (not a valid ZIP): {e}\") from e", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1276, "extracted_code_full": "# Source: ggshield/core/plugin/wheel_utils.py\ndef extract_wheel_metadata(wheel_path: Path) -> WheelMetadata:\n \"\"\"\n Extract metadata from a wheel file.\n\n Reads the METADATA file from the wheel's dist-info directory.\n\n Args:\n wheel_path: Path to the wheel file.\n\n Returns:\n WheelMetadata with name, version, and optional fields.\n\n Raises:\n InvalidWheelError: If the wheel is not a valid ZIP file.\n MetadataNotFoundError: If METADATA file is not found.\n WheelError: For other parsing errors.\n \"\"\"\n if not wheel_path.exists():\n raise InvalidWheelError(f\"Wheel file not found: {wheel_path}\")\n\n if not wheel_path.suffix == \".whl\":\n raise InvalidWheelError(f\"Not a wheel file: {wheel_path}\")\n\n try:\n with ZipFile(wheel_path, \"r\") as zf:\n metadata_path = _find_metadata_file(zf)\n if metadata_path is None:\n raise MetadataNotFoundError(\n f\"METADATA file not found in wheel: {wheel_path}\"\n )\n\n metadata_content = zf.read(metadata_path).decode(\"utf-8\")\n return _parse_metadata(metadata_content)\n\n except BadZipFile as e:\n raise InvalidWheelError(f\"Invalid wheel file (not a valid ZIP): {e}\") from e", "n_chars_compressed": 1276, "compression_ratio": 1.0}, "tests/unit/core/plugin/test_platform.py::63": {"resolved_imports": ["ggshield/core/plugin/platform.py"], "used_names": ["get_platform_info", "patch"], "enclosing_function": "test_detect_windows", "extracted_code": "# Source: ggshield/core/plugin/platform.py\ndef get_platform_info() -> PlatformInfo:\n \"\"\"Detect current platform for wheel selection.\"\"\"\n system = platform.system().lower()\n if system == \"darwin\":\n os_name = \"macosx\"\n elif system == \"linux\":\n os_name = \"linux\"\n elif system == \"windows\":\n os_name = \"win\"\n else:\n os_name = system\n\n # Detect architecture\n machine = platform.machine().lower()\n if machine in (\"arm64\", \"aarch64\"):\n arch = \"arm64\"\n elif machine in (\"x86_64\", \"amd64\"):\n arch = \"x86_64\"\n else:\n arch = machine\n\n # Detect Python version for ABI\n python_abi = f\"cp{sys.version_info.major}{sys.version_info.minor}\"\n\n return PlatformInfo(os=os_name, arch=arch, python_abi=python_abi)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 782, "extracted_code_full": "# Source: ggshield/core/plugin/platform.py\ndef get_platform_info() -> PlatformInfo:\n \"\"\"Detect current platform for wheel selection.\"\"\"\n system = platform.system().lower()\n if system == \"darwin\":\n os_name = \"macosx\"\n elif system == \"linux\":\n os_name = \"linux\"\n elif system == \"windows\":\n os_name = \"win\"\n else:\n os_name = system\n\n # Detect architecture\n machine = platform.machine().lower()\n if machine in (\"arm64\", \"aarch64\"):\n arch = \"arm64\"\n elif machine in (\"x86_64\", \"amd64\"):\n arch = \"x86_64\"\n else:\n arch = machine\n\n # Detect Python version for ABI\n python_abi = f\"cp{sys.version_info.major}{sys.version_info.minor}\"\n\n return PlatformInfo(os=os_name, arch=arch, python_abi=python_abi)", "n_chars_compressed": 782, "compression_ratio": 1.0}, "tests/unit/cmd/test_config_migrate.py::84": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["Path", "assert_invoke_ok", "cli", "yaml"], "enclosing_function": "test_config_migrate_cmd", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/utils/test_os.py::102": {"resolved_imports": ["ggshield/utils/os.py"], "used_names": ["cd", "os"], "enclosing_function": "test_cd_context_manager", "extracted_code": "# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 311, "extracted_code_full": "# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_chars_compressed": 311, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_repo.py::83": {"resolved_imports": [], "used_names": ["Repository", "os", "patch", "run_ggshield_scan"], "enclosing_function": "test_scan_repo_quota_limit_reached", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/core/config/test_user_config.py::233": {"resolved_imports": ["ggshield/core/config/config.py", "ggshield/core/config/user_config.py", "ggshield/core/errors.py", "ggshield/core/types.py"], "used_names": ["UserConfig", "write_yaml"], "enclosing_function": "test_user_config_unknown_keys", "extracted_code": "# Source: ggshield/core/config/user_config.py\nclass UserConfig(FilteredConfig):\n \"\"\"\n Holds all ggshield settings defined by the user in the .gitguardian.yaml files\n (local and global).\n \"\"\"\n\n instance: Optional[str] = None\n exit_zero: bool = False\n verbose: bool = False\n insecure: bool = False\n max_commits_for_hook: int = 50\n secret: SecretConfig = field(default_factory=SecretConfig)\n debug: bool = False\n\n # If we hit any deprecated syntax when loading a configuration file, we do not\n # display them directly, otherwise the messages would also be shown when running\n # `ggshield config migrate`, which would be odd.\n # Instead, we store them in this list and a result_callback() function displays\n # them when we quit. When `config migrate` runs, it clears this list, so nothing\n # gets displayed.\n deprecation_messages: List[str] = field(default_factory=list)\n\n def save(self, config_path: Path) -> None:\n \"\"\"\n Save config to config_path\n \"\"\"\n dct = self.to_config_dict()\n save_yaml_dict(dct, config_path)\n\n def to_config_dict(self) -> Dict[str, Any]:\n dct = self.to_dict()\n default_dct = UserConfig.from_dict({}).to_dict()\n\n dct = remove_common_dict_items(dct, default_dct)\n\n dct[\"version\"] = CURRENT_CONFIG_VERSION\n\n return dct\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> Tuple[\"UserConfig\", Path]:\n \"\"\"\n Load the various user configs files to create a UserConfig object:\n - global user configuration file (in the home)\n - local user configuration file (in the repository)\n\n Returns a UserConfig instance, and the path where updates should be saved\n \"\"\"\n deprecation_messages: List[str] = []\n if config_path:\n logger.debug(\"Loading custom config from %s\", config_path)\n dct = _load_config_dict(config_path, deprecation_messages)\n user_config = UserConfig.from_config_dict(dct)\n user_config.deprecation_messages = deprecation_messages\n return user_config, config_path\n\n user_config_dict: Dict[str, Any] = {}\n global_config_path = find_global_config_path()\n if global_config_path:\n dct = _load_config_dict(global_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n logger.debug(\"Loaded global config from %s\", global_config_path)\n else:\n logger.debug(\"No global config\")\n\n local_config_path = find_local_config_path()\n if local_config_path:\n dct = _load_config_dict(local_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n config_path = local_config_path\n logger.debug(\"Loaded local config from %s\", local_config_path)\n else:\n logger.debug(\"No local config\")\n\n user_config = UserConfig.from_config_dict(user_config_dict)\n user_config.deprecation_messages = deprecation_messages\n\n if config_path is None:\n config_path = Path(DEFAULT_LOCAL_CONFIG_PATH)\n return user_config, config_path\n\n @staticmethod\n def from_config_dict(data: Dict[str, Any]) -> \"UserConfig\":\n \"\"\"Create a UserConfig instance. In case of error, format it and raise\n ParseError.\"\"\"\n try:\n return UserConfig.from_dict(data)\n except ValidationError as exc:\n message = format_validation_error(exc)\n raise ParseError(message) from exc", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 3593, "extracted_code_full": "# Source: ggshield/core/config/user_config.py\nclass UserConfig(FilteredConfig):\n \"\"\"\n Holds all ggshield settings defined by the user in the .gitguardian.yaml files\n (local and global).\n \"\"\"\n\n instance: Optional[str] = None\n exit_zero: bool = False\n verbose: bool = False\n insecure: bool = False\n max_commits_for_hook: int = 50\n secret: SecretConfig = field(default_factory=SecretConfig)\n debug: bool = False\n\n # If we hit any deprecated syntax when loading a configuration file, we do not\n # display them directly, otherwise the messages would also be shown when running\n # `ggshield config migrate`, which would be odd.\n # Instead, we store them in this list and a result_callback() function displays\n # them when we quit. When `config migrate` runs, it clears this list, so nothing\n # gets displayed.\n deprecation_messages: List[str] = field(default_factory=list)\n\n def save(self, config_path: Path) -> None:\n \"\"\"\n Save config to config_path\n \"\"\"\n dct = self.to_config_dict()\n save_yaml_dict(dct, config_path)\n\n def to_config_dict(self) -> Dict[str, Any]:\n dct = self.to_dict()\n default_dct = UserConfig.from_dict({}).to_dict()\n\n dct = remove_common_dict_items(dct, default_dct)\n\n dct[\"version\"] = CURRENT_CONFIG_VERSION\n\n return dct\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> Tuple[\"UserConfig\", Path]:\n \"\"\"\n Load the various user configs files to create a UserConfig object:\n - global user configuration file (in the home)\n - local user configuration file (in the repository)\n\n Returns a UserConfig instance, and the path where updates should be saved\n \"\"\"\n deprecation_messages: List[str] = []\n if config_path:\n logger.debug(\"Loading custom config from %s\", config_path)\n dct = _load_config_dict(config_path, deprecation_messages)\n user_config = UserConfig.from_config_dict(dct)\n user_config.deprecation_messages = deprecation_messages\n return user_config, config_path\n\n user_config_dict: Dict[str, Any] = {}\n global_config_path = find_global_config_path()\n if global_config_path:\n dct = _load_config_dict(global_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n logger.debug(\"Loaded global config from %s\", global_config_path)\n else:\n logger.debug(\"No global config\")\n\n local_config_path = find_local_config_path()\n if local_config_path:\n dct = _load_config_dict(local_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n config_path = local_config_path\n logger.debug(\"Loaded local config from %s\", local_config_path)\n else:\n logger.debug(\"No local config\")\n\n user_config = UserConfig.from_config_dict(user_config_dict)\n user_config.deprecation_messages = deprecation_messages\n\n if config_path is None:\n config_path = Path(DEFAULT_LOCAL_CONFIG_PATH)\n return user_config, config_path\n\n @staticmethod\n def from_config_dict(data: Dict[str, Any]) -> \"UserConfig\":\n \"\"\"Create a UserConfig instance. In case of error, format it and raise\n ParseError.\"\"\"\n try:\n return UserConfig.from_dict(data)\n except ValidationError as exc:\n message = format_validation_error(exc)\n raise ParseError(message) from exc", "n_chars_compressed": 3593, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_prereceive.py::87": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/user_config.py", "ggshield/core/errors.py", "ggshield/core/scan/scannable.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py", "ggshield/verticals/secret/secret_scan_collection.py"], "used_names": ["CliRunner", "ExitCode", "Mock", "assert_invoke_ok", "cd", "cli", "create_pre_receive_repo", "patch"], "enclosing_function": "test_stdin_input", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_imports_parsed": 13, "n_files_resolved": 7, "n_chars_extracted": 2357, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_chars_compressed": 2357, "compression_ratio": 1.0}, "tests/unit/utils/test_git_shell.py::769": {"resolved_imports": ["ggshield/core/tar_utils.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["Path", "Repository", "cd", "gitignore", "logging"], "enclosing_function": "test_gitignore_write_error", "extracted_code": "# Source: ggshield/utils/git_shell.py\ndef gitignore(path: Path):\n \"\"\"\n Tries to add a path to the gitignore file.\n :param path: path to the file or directory to add to .gitignore\n \"\"\"\n working_dir = Path.cwd()\n\n if not is_git_available() or not is_git_dir(working_dir):\n return\n\n repo_root = _git_rev_parse(option=\"--show-toplevel\", wd=working_dir)\n if repo_root is not None:\n try:\n with open(Path(repo_root) / \".gitignore\", \"a\") as f:\n f.write(\"\\n# Added by ggshield\\n\")\n f.write(path.as_posix() + \"\\n\")\n except OSError:\n logger.debug(\n \"Failed to add %s to .gitignore in %s\",\n path,\n working_dir,\n )\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_imports_parsed": 14, "n_files_resolved": 3, "n_chars_extracted": 1068, "extracted_code_full": "# Source: ggshield/utils/git_shell.py\ndef gitignore(path: Path):\n \"\"\"\n Tries to add a path to the gitignore file.\n :param path: path to the file or directory to add to .gitignore\n \"\"\"\n working_dir = Path.cwd()\n\n if not is_git_available() or not is_git_dir(working_dir):\n return\n\n repo_root = _git_rev_parse(option=\"--show-toplevel\", wd=working_dir)\n if repo_root is not None:\n try:\n with open(Path(repo_root) / \".gitignore\", \"a\") as f:\n f.write(\"\\n# Added by ggshield\\n\")\n f.write(path.as_posix() + \"\\n\")\n except OSError:\n logger.debug(\n \"Failed to add %s to .gitignore in %s\",\n path,\n working_dir,\n )\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_chars_compressed": 1068, "compression_ratio": 1.0}, "tests/unit/utils/test_archive.py::96": {"resolved_imports": ["ggshield/utils/archive.py"], "used_names": ["Optional", "Path", "ZipFile", "_zip_get_symlink_target", "pytest"], "enclosing_function": "test_zip_get_symlink_target", "extracted_code": "# Source: ggshield/utils/archive.py\ndef _zip_get_symlink_target(zip: ZipFile, info: ZipInfo) -> Optional[Path]:\n \"\"\"\n If `info` points to a symbolic link inside `zip`, then return the link target.\n If it's a regular file, return None.\n \"\"\"\n if not stat.S_ISLNK(info.external_attr >> 16):\n return None\n target = zip.open(info).read().decode()\n return Path(target)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 390, "extracted_code_full": "# Source: ggshield/utils/archive.py\ndef _zip_get_symlink_target(zip: ZipFile, info: ZipInfo) -> Optional[Path]:\n \"\"\"\n If `info` points to a symbolic link inside `zip`, then return the link target.\n If it's a regular file, return None.\n \"\"\"\n if not stat.S_ISLNK(info.external_attr >> 16):\n return None\n target = zip.open(info).read().decode()\n return Path(target)", "n_chars_compressed": 390, "compression_ratio": 1.0}, "tests/unit/cmd/test_config.py::277": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/config.py", "ggshield/core/config/user_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py", "ggshield/utils/os.py"], "used_names": ["Config", "ExitCode", "UserConfig", "cd", "find_global_config_path"], "enclosing_function": "test_set_instance", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/user_config.py\nclass UserConfig(FilteredConfig):\n \"\"\"\n Holds all ggshield settings defined by the user in the .gitguardian.yaml files\n (local and global).\n \"\"\"\n\n instance: Optional[str] = None\n exit_zero: bool = False\n verbose: bool = False\n insecure: bool = False\n max_commits_for_hook: int = 50\n secret: SecretConfig = field(default_factory=SecretConfig)\n debug: bool = False\n\n # If we hit any deprecated syntax when loading a configuration file, we do not\n # display them directly, otherwise the messages would also be shown when running\n # `ggshield config migrate`, which would be odd.\n # Instead, we store them in this list and a result_callback() function displays\n # them when we quit. When `config migrate` runs, it clears this list, so nothing\n # gets displayed.\n deprecation_messages: List[str] = field(default_factory=list)\n\n def save(self, config_path: Path) -> None:\n \"\"\"\n Save config to config_path\n \"\"\"\n dct = self.to_config_dict()\n save_yaml_dict(dct, config_path)\n\n def to_config_dict(self) -> Dict[str, Any]:\n dct = self.to_dict()\n default_dct = UserConfig.from_dict({}).to_dict()\n\n dct = remove_common_dict_items(dct, default_dct)\n\n dct[\"version\"] = CURRENT_CONFIG_VERSION\n\n return dct\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> Tuple[\"UserConfig\", Path]:\n \"\"\"\n Load the various user configs files to create a UserConfig object:\n - global user configuration file (in the home)\n - local user configuration file (in the repository)\n\n Returns a UserConfig instance, and the path where updates should be saved\n \"\"\"\n deprecation_messages: List[str] = []\n if config_path:\n logger.debug(\"Loading custom config from %s\", config_path)\n dct = _load_config_dict(config_path, deprecation_messages)\n user_config = UserConfig.from_config_dict(dct)\n user_config.deprecation_messages = deprecation_messages\n return user_config, config_path\n\n user_config_dict: Dict[str, Any] = {}\n global_config_path = find_global_config_path()\n if global_config_path:\n dct = _load_config_dict(global_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n logger.debug(\"Loaded global config from %s\", global_config_path)\n else:\n logger.debug(\"No global config\")\n\n local_config_path = find_local_config_path()\n if local_config_path:\n dct = _load_config_dict(local_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n config_path = local_config_path\n logger.debug(\"Loaded local config from %s\", local_config_path)\n else:\n logger.debug(\"No local config\")\n\n user_config = UserConfig.from_config_dict(user_config_dict)\n user_config.deprecation_messages = deprecation_messages\n\n if config_path is None:\n config_path = Path(DEFAULT_LOCAL_CONFIG_PATH)\n return user_config, config_path\n\n @staticmethod\n def from_config_dict(data: Dict[str, Any]) -> \"UserConfig\":\n \"\"\"Create a UserConfig instance. In case of error, format it and raise\n ParseError.\"\"\"\n try:\n return UserConfig.from_dict(data)\n except ValidationError as exc:\n message = format_validation_error(exc)\n raise ParseError(message) from exc\n\n\n# Source: ggshield/core/config/utils.py\ndef find_global_config_path(*, to_write: Literal[False] = False) -> Optional[Path]: ...\n\ndef find_global_config_path(*, to_write: Literal[True]) -> Path: ...\n\ndef find_global_config_path(*, to_write: bool = False) -> Optional[Path]:\n \"\"\"\n Returns the path to the user global config file (the file in the user home\n directory).\n If there is no such file:\n - If `to_write` is False, returns None.\n - If `to_write` is True, returns the path to the default file.\n\n This means the function never returns None if `to_write` is True.\n \"\"\"\n for filename in USER_CONFIG_FILENAMES:\n path = get_global_path(filename)\n if path.exists():\n return path\n return get_global_path(DEFAULT_CONFIG_FILENAME) if to_write else None\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_imports_parsed": 15, "n_files_resolved": 6, "n_chars_extracted": 13416, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/user_config.py\nclass UserConfig(FilteredConfig):\n \"\"\"\n Holds all ggshield settings defined by the user in the .gitguardian.yaml files\n (local and global).\n \"\"\"\n\n instance: Optional[str] = None\n exit_zero: bool = False\n verbose: bool = False\n insecure: bool = False\n max_commits_for_hook: int = 50\n secret: SecretConfig = field(default_factory=SecretConfig)\n debug: bool = False\n\n # If we hit any deprecated syntax when loading a configuration file, we do not\n # display them directly, otherwise the messages would also be shown when running\n # `ggshield config migrate`, which would be odd.\n # Instead, we store them in this list and a result_callback() function displays\n # them when we quit. When `config migrate` runs, it clears this list, so nothing\n # gets displayed.\n deprecation_messages: List[str] = field(default_factory=list)\n\n def save(self, config_path: Path) -> None:\n \"\"\"\n Save config to config_path\n \"\"\"\n dct = self.to_config_dict()\n save_yaml_dict(dct, config_path)\n\n def to_config_dict(self) -> Dict[str, Any]:\n dct = self.to_dict()\n default_dct = UserConfig.from_dict({}).to_dict()\n\n dct = remove_common_dict_items(dct, default_dct)\n\n dct[\"version\"] = CURRENT_CONFIG_VERSION\n\n return dct\n\n @classmethod\n def load(cls, config_path: Optional[Path] = None) -> Tuple[\"UserConfig\", Path]:\n \"\"\"\n Load the various user configs files to create a UserConfig object:\n - global user configuration file (in the home)\n - local user configuration file (in the repository)\n\n Returns a UserConfig instance, and the path where updates should be saved\n \"\"\"\n deprecation_messages: List[str] = []\n if config_path:\n logger.debug(\"Loading custom config from %s\", config_path)\n dct = _load_config_dict(config_path, deprecation_messages)\n user_config = UserConfig.from_config_dict(dct)\n user_config.deprecation_messages = deprecation_messages\n return user_config, config_path\n\n user_config_dict: Dict[str, Any] = {}\n global_config_path = find_global_config_path()\n if global_config_path:\n dct = _load_config_dict(global_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n logger.debug(\"Loaded global config from %s\", global_config_path)\n else:\n logger.debug(\"No global config\")\n\n local_config_path = find_local_config_path()\n if local_config_path:\n dct = _load_config_dict(local_config_path, deprecation_messages)\n update_dict_from_other(user_config_dict, dct)\n config_path = local_config_path\n logger.debug(\"Loaded local config from %s\", local_config_path)\n else:\n logger.debug(\"No local config\")\n\n user_config = UserConfig.from_config_dict(user_config_dict)\n user_config.deprecation_messages = deprecation_messages\n\n if config_path is None:\n config_path = Path(DEFAULT_LOCAL_CONFIG_PATH)\n return user_config, config_path\n\n @staticmethod\n def from_config_dict(data: Dict[str, Any]) -> \"UserConfig\":\n \"\"\"Create a UserConfig instance. In case of error, format it and raise\n ParseError.\"\"\"\n try:\n return UserConfig.from_dict(data)\n except ValidationError as exc:\n message = format_validation_error(exc)\n raise ParseError(message) from exc\n\n\n# Source: ggshield/core/config/utils.py\ndef find_global_config_path(*, to_write: Literal[False] = False) -> Optional[Path]: ...\n\ndef find_global_config_path(*, to_write: Literal[True]) -> Path: ...\n\ndef find_global_config_path(*, to_write: bool = False) -> Optional[Path]:\n \"\"\"\n Returns the path to the user global config file (the file in the user home\n directory).\n If there is no such file:\n - If `to_write` is False, returns None.\n - If `to_write` is True, returns the path to the default file.\n\n This means the function never returns None if `to_write` is True.\n \"\"\"\n for filename in USER_CONFIG_FILENAMES:\n path = get_global_path(filename)\n if path.exists():\n return path\n return get_global_path(DEFAULT_CONFIG_FILENAME) if to_write else None\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_chars_compressed": 13416, "compression_ratio": 1.0}, "tests/unit/core/config/test_auth_config.py::92": {"resolved_imports": ["ggshield/core/config/config.py", "ggshield/core/config/auth_config.py", "ggshield/core/config/utils.py", "ggshield/core/errors.py"], "used_names": ["Config", "TEST_AUTH_CONFIG", "deepcopy", "get_auth_config_filepath", "write_yaml"], "enclosing_function": "test_token_not_expiring", "extracted_code": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/utils.py\ndef get_auth_config_filepath() -> Path:\n return get_config_dir() / AUTH_CONFIG_FILENAME", "n_imports_parsed": 11, "n_files_resolved": 4, "n_chars_extracted": 8170, "extracted_code_full": "# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/config/utils.py\ndef get_auth_config_filepath() -> Path:\n return get_config_dir() / AUTH_CONFIG_FILENAME", "n_chars_compressed": 8170, "compression_ratio": 1.0}, "tests/unit/cmd/plugin/test_update.py::1110": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py", "ggshield/core/plugin/client.py", "ggshield/core/plugin/loader.py", "ggshield/cmd/plugin/update.py"], "used_names": ["_check_github_release_update", "mock"], "enclosing_function": "test_check_github_release_update_success", "extracted_code": "# Source: ggshield/cmd/plugin/update.py\ndef _check_github_release_update(github_repo: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Check for the latest release of a GitHub repository.\n\n Args:\n github_repo: Repository in \"owner/repo\" format.\n\n Returns:\n Release data dict or None if check fails.\n \"\"\"\n # Get GitHub token if available\n github_token = os.environ.get(\"GITHUB_TOKEN\")\n\n headers: Dict[str, str] = {\n \"Accept\": \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n }\n if github_token:\n headers[\"Authorization\"] = f\"Bearer {github_token}\"\n\n try:\n response = requests.get(\n f\"https://api.github.com/repos/{github_repo}/releases/latest\",\n headers=headers,\n timeout=10,\n )\n if response.status_code == 200:\n return response.json()\n except requests.RequestException:\n pass\n\n return None", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 948, "extracted_code_full": "# Source: ggshield/cmd/plugin/update.py\ndef _check_github_release_update(github_repo: str) -> Optional[Dict[str, Any]]:\n \"\"\"\n Check for the latest release of a GitHub repository.\n\n Args:\n github_repo: Repository in \"owner/repo\" format.\n\n Returns:\n Release data dict or None if check fails.\n \"\"\"\n # Get GitHub token if available\n github_token = os.environ.get(\"GITHUB_TOKEN\")\n\n headers: Dict[str, str] = {\n \"Accept\": \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n }\n if github_token:\n headers[\"Authorization\"] = f\"Bearer {github_token}\"\n\n try:\n response = requests.get(\n f\"https://api.github.com/repos/{github_repo}/releases/latest\",\n headers=headers,\n timeout=10,\n )\n if response.status_code == 200:\n return response.json()\n except requests.RequestException:\n pass\n\n return None", "n_chars_compressed": 948, "compression_ratio": 1.0}, "tests/unit/cmd/test_ignore.py::154": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/ignore.py", "ggshield/core/cache.py", "ggshield/core/config/config.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/commit.py", "ggshield/core/scan/scan_context.py", "ggshield/core/scan/scan_mode.py", "ggshield/core/types.py", "ggshield/verticals/secret/secret_scanner.py"], "used_names": ["Cache", "Commit", "Config", "Mock", "ScanContext", "ScanMode", "SecretScanner", "_MULTIPLE_SECRETS_PATCH", "my_vcr"], "enclosing_function": "test_cache_catches_nothing", "extracted_code": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_imports_parsed": 14, "n_files_resolved": 11, "n_chars_extracted": 24117, "extracted_code_full": "# Source: ggshield/core/cache.py\nclass Cache:\n def __init__(self) -> None:\n self.cache_path = Path(CACHE_PATH)\n self.last_found_secrets: List[IgnoredMatch] = []\n self.purge()\n self.load_cache()\n\n def load_cache(self) -> None:\n if self.cache_path.is_file() and is_gitignored(self.cache_path) is False:\n gitignore(self.cache_path)\n\n if not self.cache_path.is_file() or self.cache_path.stat().st_size == 0:\n return\n\n try:\n f = self.cache_path.open()\n except PermissionError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n _cache: Dict[str, Any] = json.load(f)\n except Exception as e:\n raise UnexpectedError(\n f\"Parsing error while reading {self.cache_path}:\\n{str(e)}\"\n )\n self.update_cache(**_cache)\n\n def update_cache(self, **kwargs: Any) -> None:\n if SECRETS_CACHE_KEY in kwargs:\n self.last_found_secrets = [\n IgnoredMatch.from_dict(secret)\n for secret in kwargs.pop(SECRETS_CACHE_KEY)\n ]\n if kwargs:\n for key in kwargs.keys():\n ui.display_warning(f'Unrecognized key in cache \"{key}\"')\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n SECRETS_CACHE_KEY: [secret.to_dict() for secret in self.last_found_secrets]\n }\n\n def save(self) -> None:\n if not self.last_found_secrets:\n # if there are no found secrets, don't modify the cache file\n return\n try:\n f = self.cache_path.open(\"w\")\n except OSError:\n # Hotfix: for the time being we skip cache handling if permission denied\n return\n with f:\n try:\n json.dump(self.to_dict(), f)\n except Exception as e:\n raise UnexpectedError(\n f\"Failed to save cache in {self.cache_path}:\\n{str(e)}\"\n )\n\n def purge(self) -> None:\n self.last_found_secrets = []\n\n def add_found_policy_break(\n self, break_type: str, ignore_sha: str, filename: str\n ) -> None:\n if not any(\n last_found.match == ignore_sha for last_found in self.last_found_secrets\n ):\n self.last_found_secrets.append(\n IgnoredMatch(\n name=f\"{break_type} - {filename}\",\n match=ignore_sha,\n )\n )\n\n\n# Source: ggshield/core/config/config.py\nclass Config:\n \"\"\"\n Top-level config class. Contains an instance of UserConfig and an instance of\n AuthConfig.\n \"\"\"\n\n __slots__ = [\n \"user_config\",\n \"auth_config\",\n \"_cmdline_instance_name\",\n \"_config_path\",\n \"_dotenv_vars\",\n ]\n\n user_config: UserConfig\n auth_config: AuthConfig\n\n # The instance name, if ggshield is invoked with `--instance`\n _cmdline_instance_name: Optional[str]\n\n _config_path: Path\n\n # This environment variable helps us knowing whether environment variables\n # were set by the dotenv file or not\n # It is used in the `api-status` command to return the API key and instance sources\n _dotenv_vars: Set[str]\n\n def __init__(self, config_path: Optional[Path] = None):\n self.user_config, self._config_path = UserConfig.load(config_path=config_path)\n self.auth_config = AuthConfig.load()\n self._cmdline_instance_name = None\n self._dotenv_vars = set()\n\n def save(self) -> None:\n self.user_config.save(self._config_path)\n self.auth_config.save()\n\n @property\n def config_path(self) -> Path:\n return self._config_path\n\n @property\n def instance_name(self) -> str:\n return self.get_instance_name_and_source()[0]\n\n def get_instance_name_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the instance name and source of the selected instance.\n\n The instance name (defaulting to URL) of the selected instance\n priority order is:\n - set from the command line (by setting cmdline_instance_name)\n - in case the user set the api url instead of dashboard url, we replace it\n - GITGUARDIAN_INSTANCE env var\n - GITGUARDIAN_API_URL env var\n - in local user config (in user_config.dashboard_url)\n - in global user config (in user_config.dashboard_url)\n - the default instance\n \"\"\"\n if self._cmdline_instance_name:\n if re.match(\n r\"^https:\\/\\/api(\\.[a-z0-9]+)?\\.gitguardian\\.com\",\n self._cmdline_instance_name,\n ) or re.match(r\"/exposed/?$\", self._cmdline_instance_name):\n return (\n api_to_dashboard_url(self._cmdline_instance_name),\n ConfigSource.CMD_OPTION,\n )\n return self._cmdline_instance_name, ConfigSource.CMD_OPTION\n\n try:\n url = os.environ[\"GITGUARDIAN_INSTANCE\"]\n logger.debug(\"Using instance URL from $GITGUARDIAN_INSTANCE\")\n except KeyError:\n pass\n else:\n validate_instance_url(url)\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_INSTANCE\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return remove_url_trailing_slash(url), source\n\n try:\n name = os.environ[\"GITGUARDIAN_API_URL\"]\n logger.debug(\"Using API URL from $GITGUARDIAN_API_URL\")\n except KeyError:\n pass\n else:\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_URL\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n return api_to_dashboard_url(name, warn=True), source\n\n if self.user_config.instance:\n return self.user_config.instance, ConfigSource.USER_CONFIG\n\n return DEFAULT_INSTANCE_URL, ConfigSource.DEFAULT\n\n @property\n def cmdline_instance_name(self) -> Optional[str]:\n return self._cmdline_instance_name\n\n @cmdline_instance_name.setter\n def cmdline_instance_name(self, name: str) -> None:\n \"\"\"\n Override the current instance name. To be called by commands supporting the\n `--instance` option.\n \"\"\"\n parsed_url = clean_url(name)\n if not parsed_url.scheme or not parsed_url.netloc:\n raise click.BadParameter(\n \"Please provide a valid URL.\",\n param_hint=\"instance\",\n )\n self._cmdline_instance_name = f\"{parsed_url.scheme}://{parsed_url.netloc}\"\n\n @property\n def api_url(self) -> str:\n \"\"\"\n The API URL to use the API\n It's the API URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return dashboard_to_api_url(self.instance_name)\n\n @property\n def dashboard_url(self) -> str:\n \"\"\"\n The dashboard URL to use the dashboard\n It's the dashboard URL from the configured instance\n \"\"\"\n # TODO change when instance_name can be a name instead of just a URL\n return self.instance_name\n\n @property\n def api_key(self) -> str:\n return self.get_api_key_and_source()[0]\n\n def get_api_key_and_source(self) -> Tuple[str, ConfigSource]:\n \"\"\"\n Return the selected API key and its source\n\n The API key to use\n priority order is\n - env var\n - the api key from the selected instance\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_API_KEY\")\n source = (\n ConfigSource.DOTENV\n if \"GITGUARDIAN_API_KEY\" in self._dotenv_vars\n else ConfigSource.ENV_VAR\n )\n except KeyError:\n key = self.auth_config.get_instance_token(self.instance_name)\n source = ConfigSource.USER_CONFIG\n return key, source\n\n def add_ignored_match(self, *args: Any, **kwargs: Any) -> None:\n return self.user_config.secret.add_ignored_match(*args, **kwargs)\n\n @property\n def saas_api_url(self) -> str:\n \"\"\"\n The GIM SaaS instance used to get JWT tokens.\n This can be overridden with the GITGUARDIAN_SAAS_URL environment variable.\n If the HMSL URL is different from the default, we derive the SaaS API from it.\n Otherwise the SaaS API URL is actually the one derived from the dashboard\n \"\"\"\n if self.hmsl_url != DEFAULT_HMSL_URL and \"api\" in self.hmsl_url:\n default_value = self.hmsl_url.replace(\"hasmysecretleaked\", \"gitguardian\")\n else:\n default_value = self.api_url\n\n return os.environ.get(\n \"GITGUARDIAN_SAAS_URL\",\n default_value,\n )\n\n @property\n def saas_api_key(self) -> str:\n \"\"\"\n The API key associated with the SaaS GIM instance.\n For testing purposes, it can be overridden with the\n GITGUARDIAN_SAAS_API_KEY environment variable.\n \"\"\"\n try:\n key = os.environ[\"GITGUARDIAN_SAAS_API_KEY\"]\n logger.debug(\"Using API key from $GITGUARDIAN_SAAS_API_KEY\")\n except KeyError:\n pass\n else:\n return key\n logger.debug(\"Using API key for SaaS instance from config\")\n return self.api_key\n\n # Properties for HasMySecretLeaked\n # We can't rely on the instance selected by the user,\n # as JWT creation is only available in SaaS.\n @property\n def hmsl_url(self) -> str:\n \"\"\"\n The url of the HasMySecretLeaked service\n \"\"\"\n try:\n url = os.environ[\"GITGUARDIAN_HMSL_URL\"]\n logger.debug(\"Using HasMySecretLeaked URL from $GITGUARDIAN_HMSL_URL\")\n except KeyError:\n url = DEFAULT_HMSL_URL\n logger.debug(\"Using default HasMySecretLeaked URL\")\n return remove_url_trailing_slash(url)\n\n @property\n def hmsl_audience(self) -> str:\n \"\"\"\n The audience of our JWT tokens for HasMySecretLeaked.\n \"\"\"\n try:\n audience = os.environ[\"GITGUARDIAN_HMSL_AUDIENCE\"]\n logger.debug(\"Using audience from $GITGUARDIAN_HMSL_AUDIENCE\")\n except KeyError:\n audience = self.hmsl_url\n logger.debug(\"Using HasMySecretLeaked URL as audience\")\n return audience\n\n\n# Source: ggshield/core/scan/commit.py\nclass Commit:\n \"\"\"\n Commit represents a commit which is a list of commit files.\n \"\"\"\n\n def __init__(\n self,\n sha: Optional[str],\n patch_parser: PatchParserFunction,\n info: CommitInformation,\n ):\n \"\"\"\n Internal constructor. Used by the `from_*` static methods and by some tests.\n Real code should use the `from_*` methods.\n \"\"\"\n self.sha = sha\n self._patch_parser = patch_parser\n self.info = info\n\n @property\n def urls(self) -> Sequence[str]:\n return [CommitScannable.create_url(self.sha, x) for x in self.info.paths]\n\n @staticmethod\n def from_sha(\n sha: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n info = CommitInformation.from_sha(sha, cwd=cwd)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n for paths in batched(commit.info.paths, _MAX_DOCS_PER_COMMIT):\n cmd = [\"show\", sha, *PATCH_COMMON_ARGS, \"--\"]\n\n # Append paths to the command-line. If the file has been renamed, append\n # both old and new paths. If we only append the new path then `git\n # show` returns the new path as an added file.\n for path in paths:\n if old_path := commit.info.renames.get(path):\n cmd.append(str(old_path))\n cmd.append(str(path))\n\n patch = git(cmd, cwd=cwd)\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha, parser, info)\n\n @staticmethod\n def from_merge(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n merge_branch: str = \"MERGE_HEAD\",\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n\n diff_files = get_diff_files(cwd=cwd)\n\n shas_in_merge_branch = dict(\n get_file_sha_in_ref(merge_branch, diff_files, cwd=cwd)\n )\n shas_in_head = dict(get_file_sha_in_ref(\"HEAD\", diff_files, cwd=cwd))\n\n files_to_scan = set()\n for path, sha in get_file_sha_stage(diff_files, cwd=cwd):\n # The file is either new or different from both HEAD and MERGE_HEAD\n if sha not in {shas_in_head.get(path), shas_in_merge_branch.get(path)}:\n files_to_scan.add(path)\n\n def parser_merge(commit: \"Commit\") -> Iterable[Scannable]:\n for files in batched(files_to_scan, MAX_FILES_PER_GIT_COMMAND):\n patch = git([\"diff\", \"--staged\", *PATCH_COMMON_ARGS, *files], cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n return Commit(sha=None, patch_parser=parser_merge, info=info)\n\n @staticmethod\n def from_staged(\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n cwd: Optional[Path] = None,\n ) -> \"Commit\":\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n patch = git([\"diff\", \"--staged\"] + PATCH_COMMON_ARGS, cwd=cwd)\n yield from parse_patch(\n STAGED_PREFIX,\n DIFF_EMPTY_COMMIT_INFO_BLOCK + patch,\n exclusion_regexes,\n )\n\n info = CommitInformation.from_staged(cwd)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n @staticmethod\n def from_patch(\n patch: str,\n exclusion_regexes: Optional[Set[Pattern[str]]] = None,\n sha: str = PATCH_PREFIX,\n ) -> \"Commit\":\n \"\"\"This one is for tests\"\"\"\n info = CommitInformation.from_patch_header(patch)\n\n def parser(commit: \"Commit\") -> Iterable[Scannable]:\n yield from parse_patch(sha, patch, exclusion_regexes)\n\n return Commit(sha=None, patch_parser=parser, info=info)\n\n def get_files(self) -> Iterable[Scannable]:\n \"\"\"\n Parse the patch into files and extract the changes for each one of them.\n \"\"\"\n yield from self._patch_parser(self)\n\n def __repr__(self) -> str:\n return f\"\"\n\n\n# Source: ggshield/core/scan/scan_context.py\nclass ScanContext:\n scan_mode: Union[ScanMode, str]\n command_path: str\n extra_headers: Optional[Dict[str, str]] = None\n target_path: Optional[Path] = None\n\n def __post_init__(self) -> None:\n self.command_id = str(uuid.uuid4())\n self.os_name, self.os_version = get_os_info()\n self.python_version = platform.python_version()\n\n def _get_repository_url(\n self,\n ) -> Optional[str]:\n repo_url = None\n if self.scan_mode == ScanMode.CI:\n repo_url = get_repository_url_from_ci()\n if repo_url is None and self.target_path is not None:\n repo_url = get_repository_url_from_path(self.target_path)\n return repo_url\n\n def get_http_headers(self) -> Dict[str, str]:\n \"\"\"\n Returns the extra headers to send in HTTP requests.\n If `command_id` is not None, a `GGShield-Command-Id` header will be sent.\n Adds the \"GGShield-\" prefix to the header's names.\n \"\"\"\n headers = {\n \"Version\": __version__,\n \"Command-Path\": self.command_path,\n \"Command-Id\": self.command_id,\n \"OS-Name\": self.os_name,\n \"OS-Version\": self.os_version,\n \"Python-Version\": self.python_version,\n }\n repo_url = self._get_repository_url()\n if repo_url is not None:\n headers[\"Repository-URL\"] = repo_url\n if self.extra_headers:\n headers = {**headers, **self.extra_headers}\n\n return {\n **{f\"GGShield-{key}\": str(value) for key, value in headers.items()},\n \"mode\": (\n self.scan_mode.value\n if isinstance(self.scan_mode, ScanMode)\n else self.scan_mode\n ),\n }\n\n\n# Source: ggshield/core/scan/scan_mode.py\nclass ScanMode(Enum):\n REPO = \"repo\"\n PATH = \"path\"\n COMMIT_RANGE = \"commit_range\"\n PRE_COMMIT = \"pre_commit\"\n PRE_PUSH = \"pre_push\"\n PRE_RECEIVE = \"pre_receive\"\n CI = \"ci\"\n DOCKER = \"docker\"\n PYPI = \"pypi\"\n ARCHIVE = \"archive\"\n DOCSET = \"docset\"\n CHANGE = \"change\"\n\n\n# Source: ggshield/verticals/secret/secret_scanner.py\nclass SecretScanner:\n \"\"\"\n A SecretScanner scans a list of Scannable, using multiple threads\n \"\"\"\n\n def __init__(\n self,\n client: GGClient,\n cache: Cache,\n scan_context: ScanContext,\n secret_config: SecretConfig,\n check_api_key: Optional[bool] = True,\n ):\n if check_api_key:\n scopes = get_required_token_scopes_from_config(secret_config)\n check_client_api_key(client, scopes)\n\n self.client = client\n self.cache = cache\n self.secret_config = secret_config\n self.headers = scan_context.get_http_headers()\n self.headers.update({\"scan_options\": secret_config.dump_for_monitoring()})\n\n self.command_id = scan_context.command_id\n\n def scan(\n self,\n files: Iterable[Scannable],\n scanner_ui: ScannerUI,\n scan_threads: Optional[int] = None,\n ) -> Results:\n \"\"\"\n Starts the scan, using at most `scan_threads`. If `scan_threads` is not set,\n defaults to MAX_WORKERS.\n Reports progress through `scanner_ui`.\n Returns a Results instance.\n \"\"\"\n if scan_threads is None:\n scan_threads = MAX_WORKERS\n logger.debug(\"command_id=%s scan_threads=%d\", self.command_id, scan_threads)\n\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=scan_threads, thread_name_prefix=\"content_scan\"\n ) as executor:\n chunks_for_futures = self._start_scans(\n executor,\n files,\n scanner_ui,\n )\n\n return self._collect_results(scanner_ui, chunks_for_futures)\n\n def _scan_chunk(\n self, executor: concurrent.futures.ThreadPoolExecutor, chunk: List[Scannable]\n ) -> ScanFuture:\n \"\"\"\n Sends a chunk of files to scan to the API\n \"\"\"\n # `documents` is a version of `chunk` suitable for `GGClient.multi_content_scan()`\n documents = [\n {\"document\": x.content, \"filename\": x.filename[-_API_PATH_MAX_LENGTH:]}\n for x in chunk\n ]\n\n # Use scan_and_create_incidents if source_uuid is provided, otherwise use multi_content_scan\n if self.secret_config.source_uuid:\n return executor.submit(\n self.client.scan_and_create_incidents,\n documents,\n self.secret_config.source_uuid,\n extra_headers=self.headers,\n )\n else:\n return executor.submit(\n self.client.multi_content_scan,\n documents,\n self.headers,\n all_secrets=True,\n )\n\n def _start_scans(\n self,\n executor: concurrent.futures.ThreadPoolExecutor,\n scannables: Iterable[Scannable],\n scanner_ui: ScannerUI,\n ) -> Dict[ScanFuture, List[Scannable]]:\n \"\"\"\n Start all scans, return a tuple containing:\n - a mapping of future to the list of files it is scanning\n - a list of files which we did not send to scan because we could not decode them\n \"\"\"\n chunks_for_futures = {}\n\n chunk: List[Scannable] = []\n max_payload_size = self.client.maximum_payload_size - _SIZE_METADATA_OVERHEAD\n utf8_encoded_chunk_size = 0\n maximum_document_size = int(\n os.getenv(\n \"GG_MAX_DOC_SIZE\",\n self.client.secret_scan_preferences.maximum_document_size,\n )\n )\n maximum_documents_per_scan = int(\n os.getenv(\n \"GG_MAX_DOCS\",\n self.client.secret_scan_preferences.maximum_documents_per_scan,\n )\n )\n logging.debug(\"max_doc_size=%d\", maximum_document_size)\n logging.debug(\"max_docs=%d\", maximum_documents_per_scan)\n for scannable in scannables:\n try:\n if scannable.is_longer_than(maximum_document_size):\n scanner_ui.on_skipped(\n scannable, f\"content is over {maximum_document_size:,} bytes\"\n )\n continue\n content = scannable.content\n except DecodeError:\n scanner_ui.on_skipped(scannable, \"can't detect encoding\")\n continue\n except NonSeekableFileError:\n scanner_ui.on_skipped(scannable, \"file cannot be seeked\")\n continue\n except FileNotFoundError:\n scanner_ui.on_skipped(scannable, \"file not found\")\n continue\n\n if content:\n if (\n len(chunk) == maximum_documents_per_scan\n or utf8_encoded_chunk_size + scannable.utf8_encoded_size\n > max_payload_size\n ):\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n chunk = []\n utf8_encoded_chunk_size = 0\n chunk.append(scannable)\n utf8_encoded_chunk_size += scannable.utf8_encoded_size\n else:\n scanner_ui.on_skipped(scannable, \"\")\n if chunk:\n future = self._scan_chunk(executor, chunk)\n chunks_for_futures[future] = chunk\n return chunks_for_futures\n\n def _collect_results(\n self,\n scanner_ui: ScannerUI,\n chunks_for_futures: Dict[ScanFuture, List[Scannable]],\n ) -> Results:\n \"\"\"\n Receive scans as they complete, report progress and collect them and return\n a Results.\n \"\"\"\n self.cache.purge()\n\n results = []\n errors = []\n for future in concurrent.futures.as_completed(chunks_for_futures):\n chunk = chunks_for_futures[future]\n scanner_ui.on_scanned(chunk)\n\n exception = future.exception()\n if exception is None:\n scan = future.result()\n else:\n scan = Detail(detail=str(exception))\n errors.append(\n Error(\n files=[(x.filename, x.filemode) for x in chunk],\n description=scan.detail,\n )\n )\n\n if not scan.success:\n assert isinstance(scan, Detail)\n handle_scan_chunk_error(scan, chunk)\n continue\n\n assert isinstance(scan, MultiScanResult)\n for file, scan_result in zip(chunk, scan.scan_results):\n result = Result.from_scan_result(file, scan_result, self.secret_config)\n for secret in result.secrets:\n self.cache.add_found_policy_break(\n secret.detector_display_name,\n secret.get_ignore_sha(),\n file.filename,\n )\n results.append(result)\n\n self.cache.save()\n return Results(results=results, errors=errors)", "n_chars_compressed": 24117, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_docker.py::111": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/secret_scan_common_options.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/scannable.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/docker.py"], "used_names": ["ExitCode", "Mock", "SecretScanCollection", "assert_invoke_exited_with", "cli", "click", "patch"], "enclosing_function": "test_docker_scan_failed_to_save", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 4334, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/verticals/secret/secret_scan_collection.py\nclass SecretScanCollection:\n id: str\n type: str\n results: Optional[Results] = None\n scans: Optional[List[\"SecretScanCollection\"]] = None\n optional_header: Optional[str] = None # To be printed in Text Output\n extra_info: Optional[Dict[str, str]] = None # To be included in JSON Output\n\n def __init__(\n self,\n id: Union[str, Path],\n type: str,\n results: Optional[Results] = None,\n scans: Optional[List[\"SecretScanCollection\"]] = None,\n optional_header: Optional[str] = None,\n extra_info: Optional[Dict[str, str]] = None,\n ):\n self.id = str(id)\n self.type = type\n self.results = results\n self.scans = scans\n self.optional_header = optional_header\n self.extra_info = extra_info\n\n self.total_secrets_count = sum(\n len(result.secrets) for result in self.get_all_results()\n )\n\n @property\n def scans_with_results(self) -> List[\"SecretScanCollection\"]:\n if self.scans:\n return [scan for scan in self.scans if scan.results]\n return []\n\n def get_all_results(self) -> Iterable[Result]:\n \"\"\"Returns an iterable on all results and sub-scan results\"\"\"\n if self.results:\n yield from self.results.results\n if self.scans:\n for scan in self.scans:\n if scan.results:\n yield from scan.results.results\n\n def get_incident_details(self, client: GGClient) -> Dict[str, SecretIncident]:\n incident_details: dict[str, SecretIncident] = {}\n for result in self.get_all_results():\n for secret in result.secrets:\n url = secret.incident_url\n if url and url not in incident_details:\n incident_id = int(url.split(\"/\")[-1])\n resp = client.retrieve_secret_incident(\n incident_id, with_occurrences=0\n )\n if isinstance(resp, SecretIncident):\n incident_details[url] = resp\n else:\n assert isinstance(resp, Detail)\n handle_api_error(resp)\n return incident_details", "n_chars_compressed": 4334, "compression_ratio": 1.0}, "tests/unit/utils/test_files.py::162": {"resolved_imports": ["ggshield/core/tar_utils.py", "ggshield/utils/files.py"], "used_names": ["ListFilesMode", "Repository", "list_files", "write_text"], "enclosing_function": "test_get_gitignored_files", "extracted_code": "# Source: ggshield/utils/files.py\nclass ListFilesMode(Enum):\n \"\"\"\n Control `get_filepaths()` behavior:\n\n - ALL: list all specified paths. If one of the path is a directory, list all its paths recursively.\n - ALL_BUT_GITIGNORED: like ALL, except those ignored by git (listed in .gitignore).\n - GIT_COMMITTED_OR_STAGED: list all committed files and all staged files.\n - GIT_COMMITTED: list only committed files.\n \"\"\"\n\n GIT_COMMITTED = auto()\n GIT_COMMITTED_OR_STAGED = auto()\n ALL_BUT_GITIGNORED = auto()\n ALL = auto()\n\ndef list_files(\n paths: List[Path],\n exclusion_regexes: Set[Pattern[str]],\n list_files_mode: ListFilesMode,\n) -> Set[Path]:\n \"\"\"\n Retrieve a set of the files inside `paths`.\n\n Note: only plain files are returned, not directories.\n \"\"\"\n targets: Set[Path] = set()\n for path in paths:\n if path.is_file():\n if (\n list_files_mode == ListFilesMode.ALL_BUT_GITIGNORED\n and is_git_dir(path.parent)\n and path.name not in git_ls_unstaged(path.parent) + git_ls(path.parent)\n ):\n continue\n targets.add(path)\n elif path.is_dir():\n _targets = set()\n if list_files_mode != ListFilesMode.ALL and is_git_dir(path):\n target_filepaths = (\n get_filepaths_from_ref(\"HEAD\", wd=path)\n if list_files_mode == ListFilesMode.GIT_COMMITTED\n else git_ls(path)\n )\n _targets = {path / x for x in target_filepaths}\n if list_files_mode == ListFilesMode.ALL_BUT_GITIGNORED:\n _targets.update({path / x for x in git_ls_unstaged(path)})\n else:\n _targets = path.rglob(r\"*\")\n\n for file_path in _targets:\n if not file_path.is_dir() and not is_path_excluded(\n file_path, exclusion_regexes\n ):\n targets.add(file_path)\n return targets", "n_imports_parsed": 10, "n_files_resolved": 2, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/utils/files.py\nclass ListFilesMode(Enum):\n \"\"\"\n Control `get_filepaths()` behavior:\n\n - ALL: list all specified paths. If one of the path is a directory, list all its paths recursively.\n - ALL_BUT_GITIGNORED: like ALL, except those ignored by git (listed in .gitignore).\n - GIT_COMMITTED_OR_STAGED: list all committed files and all staged files.\n - GIT_COMMITTED: list only committed files.\n \"\"\"\n\n GIT_COMMITTED = auto()\n GIT_COMMITTED_OR_STAGED = auto()\n ALL_BUT_GITIGNORED = auto()\n ALL = auto()\n\ndef list_files(\n paths: List[Path],\n exclusion_regexes: Set[Pattern[str]],\n list_files_mode: ListFilesMode,\n) -> Set[Path]:\n \"\"\"\n Retrieve a set of the files inside `paths`.\n\n Note: only plain files are returned, not directories.\n \"\"\"\n targets: Set[Path] = set()\n for path in paths:\n if path.is_file():\n if (\n list_files_mode == ListFilesMode.ALL_BUT_GITIGNORED\n and is_git_dir(path.parent)\n and path.name not in git_ls_unstaged(path.parent) + git_ls(path.parent)\n ):\n continue\n targets.add(path)\n elif path.is_dir():\n _targets = set()\n if list_files_mode != ListFilesMode.ALL and is_git_dir(path):\n target_filepaths = (\n get_filepaths_from_ref(\"HEAD\", wd=path)\n if list_files_mode == ListFilesMode.GIT_COMMITTED\n else git_ls(path)\n )\n _targets = {path / x for x in target_filepaths}\n if list_files_mode == ListFilesMode.ALL_BUT_GITIGNORED:\n _targets.update({path / x for x in git_ls_unstaged(path)})\n else:\n _targets = path.rglob(r\"*\")\n\n for file_path in _targets:\n if not file_path.is_dir() and not is_path_excluded(\n file_path, exclusion_regexes\n ):\n targets.add(file_path)\n return targets", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/core/scan/test_commit_information.py::96": {"resolved_imports": ["ggshield/core/scan/commit_information.py"], "used_names": ["CommitInformation", "Repository"], "enclosing_function": "test_from_staged_without_changes", "extracted_code": "# Source: ggshield/core/scan/commit_information.py\nclass CommitInformation:\n author: str\n email: str\n date: str\n paths: List[Path]\n renames: Dict[Path, Path] = field(default_factory=dict)\n\n @staticmethod\n def from_patch_header(header_str: str) -> \"CommitInformation\":\n \"\"\"\n Parse a patch header generated with `git show` or `git diff` using\n HEADER_COMMON_ARGS.\n\n Output format looks like this:\n\n ```\n commit $SHA\n Author: $NAME <$EMAIL>\n Date: $DATE\n\n $SUBJECT\n\n $BODY\n $RAW_FILE_LINES\n ```\n\n If the commit is empty the last line is absent and the header ends with `\\n`.\n \"\"\"\n header = PatchHeader.from_string(header_str)\n match = _INFO_HEADER_REGEX.search(header.info)\n assert match is not None, f\"Failed to extract commit info from `{header.info}`\"\n\n if header.files:\n # Usual commit, with files in it\n paths: List[Path] = []\n renames: Dict[Path, Path] = {}\n for file_info in header.files:\n paths.append(file_info.path)\n if file_info.old_path is not None:\n renames[file_info.path] = file_info.old_path\n else:\n # Empty commit\n paths = []\n renames = {}\n\n return CommitInformation(**match.groupdict(), paths=paths, renames=renames)\n\n @staticmethod\n def from_staged(cwd: Optional[Path] = None) -> \"CommitInformation\":\n output = git([\"diff\", \"--staged\"] + HEADER_COMMON_ARGS, cwd=cwd)\n if not output:\n # This happens when there are no changes\n return CommitInformation(\"\", \"\", \"\", [])\n\n return CommitInformation.from_patch_header(\n DIFF_EMPTY_COMMIT_INFO_BLOCK + output\n )\n\n @staticmethod\n def from_sha(sha: str, cwd: Optional[Path] = None) -> \"CommitInformation\":\n header = git([\"show\", sha] + HEADER_COMMON_ARGS, cwd=cwd)\n return CommitInformation.from_patch_header(header)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2057, "extracted_code_full": "# Source: ggshield/core/scan/commit_information.py\nclass CommitInformation:\n author: str\n email: str\n date: str\n paths: List[Path]\n renames: Dict[Path, Path] = field(default_factory=dict)\n\n @staticmethod\n def from_patch_header(header_str: str) -> \"CommitInformation\":\n \"\"\"\n Parse a patch header generated with `git show` or `git diff` using\n HEADER_COMMON_ARGS.\n\n Output format looks like this:\n\n ```\n commit $SHA\n Author: $NAME <$EMAIL>\n Date: $DATE\n\n $SUBJECT\n\n $BODY\n $RAW_FILE_LINES\n ```\n\n If the commit is empty the last line is absent and the header ends with `\\n`.\n \"\"\"\n header = PatchHeader.from_string(header_str)\n match = _INFO_HEADER_REGEX.search(header.info)\n assert match is not None, f\"Failed to extract commit info from `{header.info}`\"\n\n if header.files:\n # Usual commit, with files in it\n paths: List[Path] = []\n renames: Dict[Path, Path] = {}\n for file_info in header.files:\n paths.append(file_info.path)\n if file_info.old_path is not None:\n renames[file_info.path] = file_info.old_path\n else:\n # Empty commit\n paths = []\n renames = {}\n\n return CommitInformation(**match.groupdict(), paths=paths, renames=renames)\n\n @staticmethod\n def from_staged(cwd: Optional[Path] = None) -> \"CommitInformation\":\n output = git([\"diff\", \"--staged\"] + HEADER_COMMON_ARGS, cwd=cwd)\n if not output:\n # This happens when there are no changes\n return CommitInformation(\"\", \"\", \"\", [])\n\n return CommitInformation.from_patch_header(\n DIFF_EMPTY_COMMIT_INFO_BLOCK + output\n )\n\n @staticmethod\n def from_sha(sha: str, cwd: Optional[Path] = None) -> \"CommitInformation\":\n header = git([\"show\", sha] + HEADER_COMMON_ARGS, cwd=cwd)\n return CommitInformation.from_patch_header(header)", "n_chars_compressed": 2057, "compression_ratio": 1.0}, "tests/unit/cmd/plugin/test_update.py::420": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/errors.py", "ggshield/core/plugin/client.py", "ggshield/core/plugin/loader.py"], "used_names": ["DiscoveredPlugin", "ExitCode", "Path", "PluginCatalog", "PluginDownloadInfo", "PluginInfo", "cli", "mock"], "enclosing_function": "test_update_all", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/plugin/client.py\nclass PluginInfo:\n \"\"\"Information about an available plugin.\"\"\"\n\n name: str\n display_name: str\n description: str\n available: bool\n latest_version: Optional[str]\n supported_platforms: List[str] = field(default_factory=list)\n reason: Optional[str] = None\n\n def is_platform_supported(self, platform: str, arch: str) -> bool:\n \"\"\"Check if this plugin supports the given platform/arch.\"\"\"\n if not self.supported_platforms:\n return True\n return (\n f\"{platform}-{arch}\" in self.supported_platforms\n or \"any-any\" in self.supported_platforms\n )\n\nclass PluginCatalog:\n \"\"\"Catalog of available plugins for the account.\"\"\"\n\n plan: str\n features: Dict[str, bool]\n plugins: List[PluginInfo]\n\nclass PluginDownloadInfo:\n \"\"\"Information needed to download a plugin.\"\"\"\n\n download_url: str\n filename: str\n sha256: str\n version: str\n expires_at: str\n\n\n# Source: ggshield/core/plugin/loader.py\nclass DiscoveredPlugin:\n \"\"\"Information about a discovered plugin.\"\"\"\n\n name: str\n entry_point: Optional[importlib.metadata.EntryPoint]\n wheel_path: Optional[Path]\n is_installed: bool\n is_enabled: bool\n version: Optional[str]", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 3325, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/core/plugin/client.py\nclass PluginInfo:\n \"\"\"Information about an available plugin.\"\"\"\n\n name: str\n display_name: str\n description: str\n available: bool\n latest_version: Optional[str]\n supported_platforms: List[str] = field(default_factory=list)\n reason: Optional[str] = None\n\n def is_platform_supported(self, platform: str, arch: str) -> bool:\n \"\"\"Check if this plugin supports the given platform/arch.\"\"\"\n if not self.supported_platforms:\n return True\n return (\n f\"{platform}-{arch}\" in self.supported_platforms\n or \"any-any\" in self.supported_platforms\n )\n\nclass PluginCatalog:\n \"\"\"Catalog of available plugins for the account.\"\"\"\n\n plan: str\n features: Dict[str, bool]\n plugins: List[PluginInfo]\n\nclass PluginDownloadInfo:\n \"\"\"Information needed to download a plugin.\"\"\"\n\n download_url: str\n filename: str\n sha256: str\n version: str\n expires_at: str\n\n\n# Source: ggshield/core/plugin/loader.py\nclass DiscoveredPlugin:\n \"\"\"Information about a discovered plugin.\"\"\"\n\n name: str\n entry_point: Optional[importlib.metadata.EntryPoint]\n wheel_path: Optional[Path]\n is_installed: bool\n is_enabled: bool\n version: Optional[str]", "n_chars_compressed": 3325, "compression_ratio": 1.0}, "tests/functional/utils.py::24": {"resolved_imports": ["ggshield/core/filter.py"], "used_names": ["Dict", "GGSHIELD_PATH", "Optional", "os", "subprocess"], "enclosing_function": "run_ggshield", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/unit/cmd/hmsl/test_api_status.py::18": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["CliRunner", "Path", "assert_invoke_ok", "cli", "my_vcr"], "enclosing_function": "test_hmsl_api_status", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/core/test_check_updates.py::67": {"resolved_imports": ["ggshield/core/__init__.py", "ggshield/core/check_updates.py"], "used_names": ["FakeFilesystem", "Mock", "MonkeyPatch", "check_for_updates", "core", "patch"], "enclosing_function": "test_check_for_updates_twice_only_notifies_once", "extracted_code": "# Source: ggshield/core/check_updates.py\ndef check_for_updates() -> Optional[str]:\n \"\"\"\n Check for ggshield updates on GitHub. Return the latest version if available.\n Query GitHub API at most once per day and save locally the latest version in a file.\n \"\"\"\n check_at = load_last_check_time()\n\n if check_at is not None and (time.time() - check_at < 24 * 60 * 60):\n # We checked today, no need to check again\n return None\n\n logger.debug(\"Checking the latest released version of ggshield...\")\n\n # Save check time now so that it is saved even if the check fails. This ensures we\n # don't try for every command if the user does not have network access.\n try:\n save_last_check_time(time.time())\n except Exception as e:\n logger.warning(\"Could not save time of version check to cache: %s\", repr(e))\n # Do not continue if we can't save check time. If we continue we are going to\n # send requests to api.github.com every time ggshield is called.\n return None\n\n try:\n resp = requests.get(\n \"https://api.github.com/repos/GitGuardian/GGShield/releases/latest\",\n headers={\n \"Accept\": \"application/vnd.github+json\",\n \"User-Agent\": f\"GGShield {__version__}\",\n \"X-Github-Api-Version\": \"2022-11-28\",\n },\n timeout=CHECK_TIMEOUT,\n )\n except Exception as e:\n logger.warning(\"Failed to connect to api.github.com: %s\", repr(e))\n return None\n\n if resp.status_code != 200:\n # Handle GitHub rate limit responses gracefully\n # https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#rate-limiting\n if int(resp.headers.get(\"X-RateLimit-Remaining\", -1)) == 0:\n logger.warning(\"GitHub rate limit exceeded - rescheduling update check\")\n\n # Reset the next update check based on when the GH API quota resets\n check_at = int(resp.headers.get(\"X-RateLimit-Reset\", -1)) - 24 * 60 * 60\n if check_at < 0:\n # Somehow we've hit the rate limit and the reset header is missing\n # This can only happen if GH changes their responses\n logger.warning(\"Failed rescheduling update check\")\n return None\n\n try:\n save_last_check_time(check_at)\n except Exception as e:\n logger.warning(\n \"Could not save time of version check to cache: %s\", repr(e)\n )\n\n return None\n\n logger.warning(\"Failed to check: %s\", resp.text)\n return None\n\n try:\n data = resp.json()\n latest_version: str = data[\"tag_name\"][1:]\n\n current_version_split = _split_version(__version__)\n latest_version_split = _split_version(latest_version)\n except Exception as e:\n logger.warning(\"Failed to parse response: %s\", repr(e))\n return None\n\n if current_version_split < latest_version_split:\n return latest_version\n return None", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 3076, "extracted_code_full": "# Source: ggshield/core/check_updates.py\ndef check_for_updates() -> Optional[str]:\n \"\"\"\n Check for ggshield updates on GitHub. Return the latest version if available.\n Query GitHub API at most once per day and save locally the latest version in a file.\n \"\"\"\n check_at = load_last_check_time()\n\n if check_at is not None and (time.time() - check_at < 24 * 60 * 60):\n # We checked today, no need to check again\n return None\n\n logger.debug(\"Checking the latest released version of ggshield...\")\n\n # Save check time now so that it is saved even if the check fails. This ensures we\n # don't try for every command if the user does not have network access.\n try:\n save_last_check_time(time.time())\n except Exception as e:\n logger.warning(\"Could not save time of version check to cache: %s\", repr(e))\n # Do not continue if we can't save check time. If we continue we are going to\n # send requests to api.github.com every time ggshield is called.\n return None\n\n try:\n resp = requests.get(\n \"https://api.github.com/repos/GitGuardian/GGShield/releases/latest\",\n headers={\n \"Accept\": \"application/vnd.github+json\",\n \"User-Agent\": f\"GGShield {__version__}\",\n \"X-Github-Api-Version\": \"2022-11-28\",\n },\n timeout=CHECK_TIMEOUT,\n )\n except Exception as e:\n logger.warning(\"Failed to connect to api.github.com: %s\", repr(e))\n return None\n\n if resp.status_code != 200:\n # Handle GitHub rate limit responses gracefully\n # https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#rate-limiting\n if int(resp.headers.get(\"X-RateLimit-Remaining\", -1)) == 0:\n logger.warning(\"GitHub rate limit exceeded - rescheduling update check\")\n\n # Reset the next update check based on when the GH API quota resets\n check_at = int(resp.headers.get(\"X-RateLimit-Reset\", -1)) - 24 * 60 * 60\n if check_at < 0:\n # Somehow we've hit the rate limit and the reset header is missing\n # This can only happen if GH changes their responses\n logger.warning(\"Failed rescheduling update check\")\n return None\n\n try:\n save_last_check_time(check_at)\n except Exception as e:\n logger.warning(\n \"Could not save time of version check to cache: %s\", repr(e)\n )\n\n return None\n\n logger.warning(\"Failed to check: %s\", resp.text)\n return None\n\n try:\n data = resp.json()\n latest_version: str = data[\"tag_name\"][1:]\n\n current_version_split = _split_version(__version__)\n latest_version_split = _split_version(latest_version)\n except Exception as e:\n logger.warning(\"Failed to parse response: %s\", repr(e))\n return None\n\n if current_version_split < latest_version_split:\n return latest_version\n return None", "n_chars_compressed": 3076, "compression_ratio": 1.0}, "tests/functional/secret/test_merge_commit.py::57": {"resolved_imports": [], "used_names": ["CalledProcessError", "Path", "SecretLocation", "generate_repo_with_merge_commit", "pytest"], "enclosing_function": "test_merge_commit_no_conflict", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/cmd/scan/test_ci.py::177": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/__init__.py", "ggshield/core/ui/__init__.py", "ggshield/core/errors.py", "ggshield/core/git_hooks/ci/commit_range.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py"], "used_names": ["ExitCode", "assert_invoke_exited_with", "cli", "click", "patch"], "enclosing_function": "test_ci_cmd_does_not_work_outside_ci", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_imports_parsed": 16, "n_files_resolved": 7, "n_chars_extracted": 2043, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128", "n_chars_compressed": 2043, "compression_ratio": 1.0}, "tests/unit/verticals/hmsl/test_hmsl_crypto.py::28": {"resolved_imports": ["ggshield/verticals/hmsl/crypto.py"], "used_names": ["decrypt", "encrypt"], "enclosing_function": "test_encrypt_decrypt", "extracted_code": "# Source: ggshield/verticals/hmsl/crypto.py\ndef encrypt(message: str, key: bytes) -> bytes:\n \"\"\"Encrypt a message using AES-GCM with a random nonce.\n\n Key must be 32 bytes long.\n \"\"\"\n nonce = secrets.token_bytes(12)\n return nonce + AESGCM(key).encrypt(\n nonce=nonce, data=message.encode(\"utf-8\"), associated_data=None\n )\n\ndef decrypt(payload: bytes, key: bytes) -> str:\n \"\"\"Decrypt a message using AES-GCM. Key must be 32 bytes long.\"\"\"\n try:\n cleartext = AESGCM(key).decrypt(\n nonce=payload[:12], data=payload[12:], associated_data=None\n )\n return cleartext.decode()\n except InvalidTag as exc:\n raise DecryptionError from exc", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 699, "extracted_code_full": "# Source: ggshield/verticals/hmsl/crypto.py\ndef encrypt(message: str, key: bytes) -> bytes:\n \"\"\"Encrypt a message using AES-GCM with a random nonce.\n\n Key must be 32 bytes long.\n \"\"\"\n nonce = secrets.token_bytes(12)\n return nonce + AESGCM(key).encrypt(\n nonce=nonce, data=message.encode(\"utf-8\"), associated_data=None\n )\n\ndef decrypt(payload: bytes, key: bytes) -> str:\n \"\"\"Decrypt a message using AES-GCM. Key must be 32 bytes long.\"\"\"\n try:\n cleartext = AESGCM(key).decrypt(\n nonce=payload[:12], data=payload[12:], associated_data=None\n )\n return cleartext.decode()\n except InvalidTag as exc:\n raise DecryptionError from exc", "n_chars_compressed": 699, "compression_ratio": 1.0}, "tests/functional/secret/test_scan_docset.py::21": {"resolved_imports": [], "used_names": ["GG_VALID_TOKEN", "Path", "run_ggshield_scan"], "enclosing_function": "test_scan_docset_positive", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/cmd/test_log_options.py::23": {"resolved_imports": ["ggshield/__main__.py"], "used_names": ["Path", "assert_invoke_ok", "cli", "pytest"], "enclosing_function": "test_log_to_stderr_option", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 1380, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)", "n_chars_compressed": 1380, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_prereceive.py::89": {"resolved_imports": ["ggshield/__main__.py", "ggshield/core/config/user_config.py", "ggshield/core/errors.py", "ggshield/core/scan/scannable.py", "ggshield/utils/git_shell.py", "ggshield/utils/os.py", "ggshield/verticals/secret/secret_scan_collection.py"], "used_names": ["CliRunner", "ExitCode", "Mock", "assert_invoke_ok", "cd", "cli", "create_pre_receive_repo", "patch"], "enclosing_function": "test_stdin_input", "extracted_code": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_imports_parsed": 13, "n_files_resolved": 7, "n_chars_extracted": 2357, "extracted_code_full": "# Source: ggshield/__main__.py\ndef cli(\n ctx: click.Context,\n *,\n allow_self_signed: Optional[bool],\n insecure: Optional[bool],\n config_path: Optional[Path],\n instance: Optional[str],\n **kwargs: Any,\n) -> None:\n # Create ContextObj, load config\n ctx.obj = ctx_obj = ContextObj()\n ctx_obj.cache = Cache()\n ctx_obj.config = Config(config_path)\n user_config = ctx_obj.config.user_config\n\n # If the config wants a higher UI level, set it now\n if user_config.debug and ui.get_level() < ui.Level.DEBUG:\n setup_debug_mode()\n elif user_config.verbose and ui.get_level() < ui.Level.VERBOSE:\n ensure_level(ui.Level.VERBOSE)\n\n # Update SSL verification settings in the config\n # TODO: this should be reworked: if a command which writes the config is called with\n # --insecure, the config will contain `insecure: true`.\n if insecure or allow_self_signed:\n user_config.insecure = True\n\n ctx_obj.config._dotenv_vars = load_dot_env()\n\n # Apply instance from command line\n if instance:\n ctx_obj.config.cmdline_instance_name = instance\n\n # Use pre-loaded plugin registry\n ctx_obj.plugin_registry = _load_plugins()\n\n # Flush deferred plugin warnings now that logging is configured\n for msg in _deferred_warnings:\n logger.warning(msg)\n _deferred_warnings.clear()\n\n _set_color(ctx)\n\n\n# Source: ggshield/core/errors.py\nclass ExitCode(IntEnum):\n \"\"\"\n Define constant exit codes based on their type\n \"\"\"\n\n # Everything went well\n SUCCESS = 0\n # Scan was successful, and found problems (e.g. leaked secrets)\n SCAN_FOUND_PROBLEMS = 1\n # Error on the command-line, like a missing parameter\n USAGE_ERROR = 2\n # auth subcommand failed\n AUTHENTICATION_ERROR = 3\n # GitGuardian server is not responding\n GITGUARDIAN_SERVER_UNAVAILABLE = 4\n\n # Add new exit codes here.\n # If you add a new exit code, make sure you also add it to the documentation.\n\n # Catch all for other failures\n UNEXPECTED_ERROR = 128\n\n\n# Source: ggshield/utils/os.py\ndef cd(newdir: Union[str, Path]) -> Iterator[None]:\n \"\"\"\n A context manager to temporarily change the current directory\n \"\"\"\n prevdir = Path.cwd()\n newdir = Path(newdir).expanduser()\n os.chdir(newdir)\n try:\n yield\n finally:\n os.chdir(prevdir)", "n_chars_compressed": 2357, "compression_ratio": 1.0}, "tests/unit/cmd/scan/test_docker.py::53": {"resolved_imports": ["ggshield/__main__.py", "ggshield/cmd/secret/scan/secret_scan_common_options.py", "ggshield/core/errors.py", "ggshield/core/filter.py", "ggshield/core/scan/scannable.py", "ggshield/verticals/secret/secret_scan_collection.py", "ggshield/verticals/secret/docker.py"], "used_names": ["_validate_filepath", "pytest", "re"], "enclosing_function": "test_docker_filepath_validation", "extracted_code": "# Source: ggshield/verticals/secret/docker.py\ndef _validate_filepath(\n filepath: str,\n exclusion_regexes: Set[re.Pattern[str]],\n) -> bool:\n if any(\n banned_pattern.search(filepath)\n for banned_pattern in FILEPATH_BANLIST_PATTERNS | exclusion_regexes\n ):\n return False\n\n if is_path_binary(filepath):\n return False\n return True", "n_imports_parsed": 14, "n_files_resolved": 7, "n_chars_extracted": 371, "extracted_code_full": "# Source: ggshield/verticals/secret/docker.py\ndef _validate_filepath(\n filepath: str,\n exclusion_regexes: Set[re.Pattern[str]],\n) -> bool:\n if any(\n banned_pattern.search(filepath)\n for banned_pattern in FILEPATH_BANLIST_PATTERNS | exclusion_regexes\n ):\n return False\n\n if is_path_binary(filepath):\n return False\n return True", "n_chars_compressed": 371, "compression_ratio": 1.0}}} \ No newline at end of file