code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def num_tokens_from_messages(self, messages: List[Message]) -> int:
"""
Get the total number of tokens used by a list of messages, accounting for text and base64 encoded images.
Parameters
----------
messages : List[Message]
The list of messages to count the tokens i... |
Get the total number of tokens used by a list of messages, accounting for text and base64 encoded images.
Parameters
----------
messages : List[Message]
The list of messages to count the tokens in.
Returns
-------
int
The total number of... | num_tokens_from_messages | python | AntonOsika/gpt-engineer | gpt_engineer/core/token_usage.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/token_usage.py | MIT |
def update_log(self, messages: List[Message], answer: str, step_name: str) -> None:
"""
Update the token usage log with the number of tokens used in the current step.
Parameters
----------
messages : List[Message]
The list of messages in the conversation.
ans... |
Update the token usage log with the number of tokens used in the current step.
Parameters
----------
messages : List[Message]
The list of messages in the conversation.
answer : str
The answer from the AI.
step_name : str
The name of t... | update_log | python | AntonOsika/gpt-engineer | gpt_engineer/core/token_usage.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/token_usage.py | MIT |
def format_log(self) -> str:
"""
Format the token usage log as a CSV string.
Returns
-------
str
The token usage log formatted as a CSV string.
"""
result = "step_name,prompt_tokens_in_step,completion_tokens_in_step,total_tokens_in_step,total_prompt_t... |
Format the token usage log as a CSV string.
Returns
-------
str
The token usage log formatted as a CSV string.
| format_log | python | AntonOsika/gpt-engineer | gpt_engineer/core/token_usage.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/token_usage.py | MIT |
def usage_cost(self) -> float | None:
"""
Return the total cost in USD of the API usage.
Returns
-------
float
Cost in USD.
"""
if not self.is_openai_model():
return None
try:
result = 0
for log in self.log... |
Return the total cost in USD of the API usage.
Returns
-------
float
Cost in USD.
| usage_cost | python | AntonOsika/gpt-engineer | gpt_engineer/core/token_usage.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/token_usage.py | MIT |
def __getitem__(self, key: str) -> str:
"""
Retrieve the content of a file in the database corresponding to the given key.
If the file is an image with a .png or .jpeg extension, it returns the content
in Base64-encoded string format.
Parameters
----------
key : ... |
Retrieve the content of a file in the database corresponding to the given key.
If the file is an image with a .png or .jpeg extension, it returns the content
in Base64-encoded string format.
Parameters
----------
key : str
The key (filename) whose content is... | __getitem__ | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/disk_memory.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/disk_memory.py | MIT |
def get(self, key: str, default: Optional[Any] = None) -> Any:
"""
Retrieve the content of a file in the database, or return a default value if not found.
Parameters
----------
key : str
The key (filename) whose content is to be retrieved.
default : Any, opti... |
Retrieve the content of a file in the database, or return a default value if not found.
Parameters
----------
key : str
The key (filename) whose content is to be retrieved.
default : Any, optional
The default value to return if the file does not exist. D... | get | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/disk_memory.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/disk_memory.py | MIT |
def __setitem__(self, key: Union[str, Path], val: str) -> None:
"""
Set or update the content of a file in the database corresponding to the given key.
Parameters
----------
key : str or Path
The key (filename) where the content is to be set.
val : str
... |
Set or update the content of a file in the database corresponding to the given key.
Parameters
----------
key : str or Path
The key (filename) where the content is to be set.
val : str
The content to be written to the file.
Raises
------... | __setitem__ | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/disk_memory.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/disk_memory.py | MIT |
def __delitem__(self, key: Union[str, Path]) -> None:
"""
Delete a file or directory from the database corresponding to the given key.
Parameters
----------
key : str or Path
The key (filename or directory name) to be deleted.
Raises
------
K... |
Delete a file or directory from the database corresponding to the given key.
Parameters
----------
key : str or Path
The key (filename or directory name) to be deleted.
Raises
------
KeyError
If the file or directory corresponding to the... | __delitem__ | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/disk_memory.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/disk_memory.py | MIT |
def __iter__(self) -> Iterator[str]:
"""
Iterate over the keys (filenames) in the database.
Yields
------
Iterator[str]
An iterator over the sorted list of keys (filenames) in the database.
"""
return iter(
sorted(
str(ite... |
Iterate over the keys (filenames) in the database.
Yields
------
Iterator[str]
An iterator over the sorted list of keys (filenames) in the database.
| __iter__ | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/disk_memory.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/disk_memory.py | MIT |
def to_path_list_string(self, supported_code_files_only: bool = False) -> str:
"""
Generate a string representation of the file paths in the database.
Parameters
----------
supported_code_files_only : bool, optional
If True, filter the list to include only supported ... |
Generate a string representation of the file paths in the database.
Parameters
----------
supported_code_files_only : bool, optional
If True, filter the list to include only supported code file extensions.
Default is False.
Returns
-------
... | to_path_list_string | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/disk_memory.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/disk_memory.py | MIT |
def log(self, key: Union[str, Path], val: str) -> None:
"""
Append to a file or create and write to it if it doesn't exist.
Parameters
----------
key : str or Path
The key (filename) where the content is to be appended.
val : str
The content to be... |
Append to a file or create and write to it if it doesn't exist.
Parameters
----------
key : str or Path
The key (filename) where the content is to be appended.
val : str
The content to be appended to the file.
| log | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/disk_memory.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/disk_memory.py | MIT |
def archive_logs(self):
"""
Moves all logs to archive directory based on current timestamp
"""
if "logs" in self:
archive_dir = (
self.path / f"logs_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}"
)
shutil.move(self.path / "logs", archi... |
Moves all logs to archive directory based on current timestamp
| archive_logs | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/disk_memory.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/disk_memory.py | MIT |
def setup_sys_prompt(preprompts: MutableMapping[Union[str, Path], str]) -> str:
"""
Sets up the system prompt for generating code.
Parameters
----------
preprompts : MutableMapping[Union[str, Path], str]
A mapping of preprompt messages to guide the AI model.
Returns
-------
str... |
Sets up the system prompt for generating code.
Parameters
----------
preprompts : MutableMapping[Union[str, Path], str]
A mapping of preprompt messages to guide the AI model.
Returns
-------
str
The system prompt message for the AI model.
| setup_sys_prompt | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/steps.py | MIT |
def setup_sys_prompt_existing_code(
preprompts: MutableMapping[Union[str, Path], str]
) -> str:
"""
Sets up the system prompt for improving existing code.
Parameters
----------
preprompts : MutableMapping[Union[str, Path], str]
A mapping of preprompt messages to guide the AI model.
... |
Sets up the system prompt for improving existing code.
Parameters
----------
preprompts : MutableMapping[Union[str, Path], str]
A mapping of preprompt messages to guide the AI model.
Returns
-------
str
The system prompt message for the AI model to improve existing code.
... | setup_sys_prompt_existing_code | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/steps.py | MIT |
def gen_code(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
"""
Generates code from a prompt using AI and returns the generated files.
Parameters
----------
ai : AI
The AI model used for generating code.
prompt : str
The user... |
Generates code from a prompt using AI and returns the generated files.
Parameters
----------
ai : AI
The AI model used for generating code.
prompt : str
The user prompt to generate code from.
memory : BaseMemory
The memory interface where the code and related data are s... | gen_code | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/steps.py | MIT |
def gen_entrypoint(
ai: AI,
prompt: Prompt,
files_dict: FilesDict,
memory: BaseMemory,
preprompts_holder: PrepromptsHolder,
) -> FilesDict:
"""
Generates an entrypoint for the codebase and returns the entrypoint files.
Parameters
----------
ai : AI
The AI model used for ... |
Generates an entrypoint for the codebase and returns the entrypoint files.
Parameters
----------
ai : AI
The AI model used for generating the entrypoint.
files_dict : FilesDict
The dictionary of file names to their respective source code content.
memory : BaseMemory
The... | gen_entrypoint | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/steps.py | MIT |
def execute_entrypoint(
ai: AI,
execution_env: BaseExecutionEnv,
files_dict: FilesDict,
prompt: Prompt = None,
preprompts_holder: PrepromptsHolder = None,
memory: BaseMemory = None,
) -> FilesDict:
"""
Executes the entrypoint of the codebase.
Parameters
----------
ai : AI
... |
Executes the entrypoint of the codebase.
Parameters
----------
ai : AI
The AI model used for generating the entrypoint.
execution_env : BaseExecutionEnv
The execution environment in which the code is executed.
files_dict : FilesDict
The dictionary of file names to their... | execute_entrypoint | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/steps.py | MIT |
def improve_fn(
ai: AI,
prompt: Prompt,
files_dict: FilesDict,
memory: BaseMemory,
preprompts_holder: PrepromptsHolder,
diff_timeout=3,
) -> FilesDict:
"""
Improves the code based on user input and returns the updated files.
Parameters
----------
ai : AI
The AI model... |
Improves the code based on user input and returns the updated files.
Parameters
----------
ai : AI
The AI model used for improving code.
prompt :str
The user prompt to improve the code.
files_dict : FilesDict
The dictionary of file names to their respective source code ... | improve_fn | python | AntonOsika/gpt-engineer | gpt_engineer/core/default/steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/default/steps.py | MIT |
def get_platform_info() -> str:
"""
Returns a string containing the OS and Python version information.
This function is used for self-healing by providing information about the current
operating system and Python version. It assumes that the Python version in the
virtual environment is the one bein... |
Returns a string containing the OS and Python version information.
This function is used for self-healing by providing information about the current
operating system and Python version. It assumes that the Python version in the
virtual environment is the one being used.
Returns:
str: A st... | get_platform_info | python | AntonOsika/gpt-engineer | gpt_engineer/tools/custom_steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/tools/custom_steps.py | MIT |
def self_heal(
ai: AI,
execution_env: BaseExecutionEnv,
files_dict: FilesDict,
prompt: Prompt = None,
preprompts_holder: PrepromptsHolder = None,
memory: BaseMemory = None,
diff_timeout=3,
) -> FilesDict:
"""
Attempts to execute the code from the entrypoint and if it fails, sends the... |
Attempts to execute the code from the entrypoint and if it fails, sends the error output back to the AI with instructions to fix.
Parameters
----------
ai : AI
An instance of the AI model.
execution_env : BaseExecutionEnv
The execution environment where the code is run.
files_d... | self_heal | python | AntonOsika/gpt-engineer | gpt_engineer/tools/custom_steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/tools/custom_steps.py | MIT |
def clarified_gen(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
"""
Generates code based on clarifications obtained from the user and saves it to a specified workspace.
Parameters
----------
ai : AI
An instance of the AI model, responsi... |
Generates code based on clarifications obtained from the user and saves it to a specified workspace.
Parameters
----------
ai : AI
An instance of the AI model, responsible for processing and generating the code.
prompt : str
The user's clarification prompt.
memory : BaseMemory
... | clarified_gen | python | AntonOsika/gpt-engineer | gpt_engineer/tools/custom_steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/tools/custom_steps.py | MIT |
def lite_gen(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
"""
Executes the AI model using the main prompt and saves the generated results to the specified workspace.
Parameters
----------
ai : AI
An instance of the AI model.
prompt... |
Executes the AI model using the main prompt and saves the generated results to the specified workspace.
Parameters
----------
ai : AI
An instance of the AI model.
prompt : str
The main prompt to feed to the AI model.
memory : BaseMemory
The memory instance where the gen... | lite_gen | python | AntonOsika/gpt-engineer | gpt_engineer/tools/custom_steps.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/tools/custom_steps.py | MIT |
def main():
"""
Main function that iterates through all directories in the 'benchmark' folder
and cleans them by removing all files and directories except for 'prompt' and
'main_prompt'.
"""
benchmarks = Path("benchmark")
for benchmark in benchmarks.iterdir():
if benchmark.is_dir()... |
Main function that iterates through all directories in the 'benchmark' folder
and cleans them by removing all files and directories except for 'prompt' and
'main_prompt'.
| main | python | AntonOsika/gpt-engineer | scripts/clean_benchmarks.py | https://github.com/AntonOsika/gpt-engineer/blob/master/scripts/clean_benchmarks.py | MIT |
def main(
n_benchmarks: Union[int, None] = None,
):
"""
Main function that runs benchmarks on folders within the 'benchmark' directory.
Parameters
----------
n_benchmarks : Union[int, None], optional
The number of benchmarks to run. If None, all benchmarks are run.
"""
path = ... |
Main function that runs benchmarks on folders within the 'benchmark' directory.
Parameters
----------
n_benchmarks : Union[int, None], optional
The number of benchmarks to run. If None, all benchmarks are run.
| main | python | AntonOsika/gpt-engineer | scripts/legacy_benchmark.py | https://github.com/AntonOsika/gpt-engineer/blob/master/scripts/legacy_benchmark.py | MIT |
def generate_report(benchmarks, benchmark_path):
"""
Generates a report of the benchmark results and optionally appends it to a markdown file.
Parameters
----------
benchmarks : list
A list of benchmark folder paths that have been processed.
benchmark_path : Path
The path to the... |
Generates a report of the benchmark results and optionally appends it to a markdown file.
Parameters
----------
benchmarks : list
A list of benchmark folder paths that have been processed.
benchmark_path : Path
The path to the benchmark directory.
| generate_report | python | AntonOsika/gpt-engineer | scripts/legacy_benchmark.py | https://github.com/AntonOsika/gpt-engineer/blob/master/scripts/legacy_benchmark.py | MIT |
def insert_markdown_section(file_path, section_title, section_text, level):
"""
Inserts a new section into a markdown file at the specified level.
Parameters
----------
file_path : Path
The path to the markdown file.
section_title : str
The title of the section to insert.
se... |
Inserts a new section into a markdown file at the specified level.
Parameters
----------
file_path : Path
The path to the markdown file.
section_title : str
The title of the section to insert.
section_text : str
The text content of the section to insert.
level : int... | insert_markdown_section | python | AntonOsika/gpt-engineer | scripts/legacy_benchmark.py | https://github.com/AntonOsika/gpt-engineer/blob/master/scripts/legacy_benchmark.py | MIT |
def ask_yes_no(question: str) -> bool:
"""
Asks a yes/no question and returns the response as a boolean value.
Parameters
----------
question : str
The yes/no question to ask.
Returns
-------
bool
True if the answer is 'yes', False if 'no'.
"""
while True:
... |
Asks a yes/no question and returns the response as a boolean value.
Parameters
----------
question : str
The yes/no question to ask.
Returns
-------
bool
True if the answer is 'yes', False if 'no'.
| ask_yes_no | python | AntonOsika/gpt-engineer | scripts/legacy_benchmark.py | https://github.com/AntonOsika/gpt-engineer/blob/master/scripts/legacy_benchmark.py | MIT |
def pretty_print_conversation(messages):
"""
Prints a conversation with messages formatted and colored by role.
Parameters
----------
messages : list
A list of message dictionaries, each containing 'role', 'name', and 'content' keys.
"""
role_to_color = {
"system": "red",
... |
Prints a conversation with messages formatted and colored by role.
Parameters
----------
messages : list
A list of message dictionaries, each containing 'role', 'name', and 'content' keys.
| pretty_print_conversation | python | AntonOsika/gpt-engineer | scripts/print_chat.py | https://github.com/AntonOsika/gpt-engineer/blob/master/scripts/print_chat.py | MIT |
def main(
messages_path: str,
):
"""
Main function that loads messages from a JSON file and prints them using pretty formatting.
Parameters
----------
messages_path : str
The file path to the JSON file containing the messages.
"""
with open(messages_path) as f:
messages... |
Main function that loads messages from a JSON file and prints them using pretty formatting.
Parameters
----------
messages_path : str
The file path to the JSON file containing the messages.
| main | python | AntonOsika/gpt-engineer | scripts/print_chat.py | https://github.com/AntonOsika/gpt-engineer/blob/master/scripts/print_chat.py | MIT |
def venv_setup_teardown():
"""
A pytest fixture that sets up and tears down a virtual environment for testing.
This fixture is automatically used for all tests in this module.
The fixture:
- Creates a virtual environment.
- Installs Poetry in the virtual environment.
- Installs dependencies... |
A pytest fixture that sets up and tears down a virtual environment for testing.
This fixture is automatically used for all tests in this module.
The fixture:
- Creates a virtual environment.
- Installs Poetry in the virtual environment.
- Installs dependencies using Poetry.
- Cleans up by ... | venv_setup_teardown | python | AntonOsika/gpt-engineer | tests/test_install.py | https://github.com/AntonOsika/gpt-engineer/blob/master/tests/test_install.py | MIT |
def test_installation():
"""
Test to ensure that the package can be installed using Poetry in the virtual environment.
"""
# Determine the correct Poetry executable path based on the operating system.
poetry_executable = (
f"{VENV_DIR}/bin/poetry"
if sys.platform != "win32"
e... |
Test to ensure that the package can be installed using Poetry in the virtual environment.
| test_installation | python | AntonOsika/gpt-engineer | tests/test_install.py | https://github.com/AntonOsika/gpt-engineer/blob/master/tests/test_install.py | MIT |
def test_cli_execution():
"""
Test to verify that the command-line interface (CLI) of the package works as expected.
This test assumes that the 'gpt-engineer' command is available and operational after installation.
"""
# Run the 'gpt-engineer' command with the '--help' option and capture its output... |
Test to verify that the command-line interface (CLI) of the package works as expected.
This test assumes that the 'gpt-engineer' command is available and operational after installation.
| test_cli_execution | python | AntonOsika/gpt-engineer | tests/test_install.py | https://github.com/AntonOsika/gpt-engineer/blob/master/tests/test_install.py | MIT |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 after 150 and 225 epochs"""
lr = args.lr * (0.1 ** (epoch // 150)) * (0.1 ** (epoch // 225))
# log to TensorBoard
if args.tensorboard:
log_value('learning_rate', lr, epoch)
for param_group i... | Sets the learning rate to the initial LR decayed by 10 after 150 and 225 epochs | adjust_learning_rate | python | andreasveit/densenet-pytorch | train.py | https://github.com/andreasveit/densenet-pytorch/blob/master/train.py | BSD-3-Clause |
def from_page_token(cls, page_token: str | None) -> Self:
"""Generate a query cursor from a url safe page token."""
qc = cls()
if not page_token:
qc._cursor_state = _QueryCursorState.STARTED
qc._ndb_cursor = None
return qc
split_values = page_token.split(_METADATA_SEPARATOR, 1)
i... | Generate a query cursor from a url safe page token. | from_page_token | python | google/osv.dev | gcp/api/cursor.py | https://github.com/google/osv.dev/blob/master/gcp/api/cursor.py | Apache-2.0 |
def update_from_iterator(self, it: ndb.QueryIterator) -> None:
"""
Update the current cursor from the value of the ndb.iterator passed in.
Args:
it: the iterator to take the cursor position from.
"""
try:
self._ndb_cursor = typing.cast(ndb.Cursor, it.cursor_after())
self._cursor_s... |
Update the current cursor from the value of the ndb.iterator passed in.
Args:
it: the iterator to take the cursor position from.
| update_from_iterator | python | google/osv.dev | gcp/api/cursor.py | https://github.com/google/osv.dev/blob/master/gcp/api/cursor.py | Apache-2.0 |
def ndb_cursor(self) -> ndb.Cursor | None:
"""The inner ndb cursor, could be None"""
if self._cursor_state == _QueryCursorState.IN_PROGRESS:
return self._ndb_cursor
return None | The inner ndb cursor, could be None | ndb_cursor | python | google/osv.dev | gcp/api/cursor.py | https://github.com/google/osv.dev/blob/master/gcp/api/cursor.py | Apache-2.0 |
def url_safe_encode(self) -> str | None:
"""
Create a url safe page token to pass back to the API caller.
"""
cursor_part: str = ''
match self._cursor_state:
case _QueryCursorState.STARTED:
cursor_part = _FIRST_PAGE_TOKEN
case _QueryCursorState.IN_PROGRESS:
# Assume that ... |
Create a url safe page token to pass back to the API caller.
| url_safe_encode | python | google/osv.dev | gcp/api/cursor.py | https://github.com/google/osv.dev/blob/master/gcp/api/cursor.py | Apache-2.0 |
def assert_vuln_equal(self, expected, actual):
"""Assert that the vulnerability is equal."""
self.remove_modified(expected)
self.remove_modified(actual)
self.assertDictEqual(expected, actual) | Assert that the vulnerability is equal. | assert_vuln_equal | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def assert_results_equal(self, expected, actual):
"""Assert that results are equal.
Args:
expected: dictionary representation of the expected vulnerability.
actual: dictionary representation of the actual vulnerability.
"""
# Single query results.
for vuln in expected.get('vulns', []):
... | Assert that results are equal.
Args:
expected: dictionary representation of the expected vulnerability.
actual: dictionary representation of the actual vulnerability.
| assert_results_equal | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_get_with_multiple(self):
"""Test getting a vulnerability with multiple packages."""
go_2020_0015 = self._get('GO-2020-0015')
response = requests.get(_api() + '/v1/vulns/GO-2020-0015', timeout=_TIMEOUT)
self.assert_vuln_equal(go_2020_0015, response.json()) | Test getting a vulnerability with multiple packages. | test_get_with_multiple | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_debian(self):
"""Test querying Debian with sub ecosystem versions"""
dsa_2665_1 = self._get('DSA-710-1')
response = requests.post(
_api() + _BASE_QUERY,
data=json.dumps({
'version': '1.0.2-1',
'package': {
'name': 'gtkhtml',
... | Test querying Debian with sub ecosystem versions | test_query_debian | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_invalid_ecosystem(self):
"""Test a query with an invalid ecosystem fails validation."""
response = requests.post(
_api() + _BASE_QUERY,
data=json.dumps({
'version': '1.0.0',
'package': {
'name': 'a_package_name_of_no_consequence',
... | Test a query with an invalid ecosystem fails validation. | test_query_invalid_ecosystem | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_unknown_purl_invalid_semver(self):
"""Test an unknown purl query with an invalid semver"""
response = requests.post(
_api() + _BASE_QUERY,
data=json.dumps({
'package': {
'purl':
'pkg:golang/github.com/' +
'tianon/... | Test an unknown purl query with an invalid semver | test_query_unknown_purl_invalid_semver | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_semver_no_vulns(self):
"""Test queries by SemVer with no vulnerabilities."""
package = 'github.com/justinas/nosurf'
ecosystem = 'Go'
# Test that a SemVer with a (believed to be non-vulnerable) version and an
# ecosystem returns no vulnerabilities.
# (This version does not exist)
... | Test queries by SemVer with no vulnerabilities. | test_query_semver_no_vulns | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_semver_multiple_package(self):
"""Test query by SemVer (with multiple packages)."""
response = requests.post(
_api() + _BASE_QUERY,
data=json.dumps({
'version': '2.4.0',
'package': {
'name': 'gopkg.in/yaml.v2',
'ecosystem': '... | Test query by SemVer (with multiple packages). | test_query_semver_multiple_package | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_purl_with_version_trailing_zeroes(self):
"""Test purl with trailing zeroes in version."""
expected = requests.post(
_api() + _BASE_QUERY,
data=json.dumps({'package': {
'purl': 'pkg:pypi/cryptography@3.1',
}}),
timeout=_TIMEOUT)
response = requests.... | Test purl with trailing zeroes in version. | test_query_purl_with_version_trailing_zeroes | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_with_redundant_ecosystem(self):
"""Test purl with redundant ecosystem raises error"""
response = requests.post(
_api() + _BASE_QUERY,
data=json.dumps({
"package": {
"ecosystem": "PyPI",
"purl": "pkg:pypi/mlflow@0.4.0",
}
... | Test purl with redundant ecosystem raises error | test_query_with_redundant_ecosystem | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_with_redundant_version(self):
"""Test purl with redundant version raises error"""
response = requests.post(
_api() + _BASE_QUERY,
data=json.dumps({
"version": "0.4.0",
"package": {
"purl": "pkg:pypi/mlflow@0.4.0",
}
}),
... | Test purl with redundant version raises error | test_query_with_redundant_version | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_with_redundant_package_name(self):
"""Test purl with redundant name raises error"""
response = requests.post(
_api() + _BASE_QUERY,
data=json.dumps(
{"package": {
"name": "mlflow",
"purl": "pkg:pypi/mlflow@0.4.0",
}}),
... | Test purl with redundant name raises error | test_query_with_redundant_package_name | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_get_vuln_by_alias_not_in_db(self):
""" Test search by ID for a vuln not in db, but alias is"""
response = requests.get(
_api() + '/v1/vulns/CVE-2024-40120', timeout=_TIMEOUT)
self.assert_results_equal(
{
'code': 5,
'message': 'Bug not found, but the following... | Test search by ID for a vuln not in db, but alias is | test_get_vuln_by_alias_not_in_db | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_pagination(self):
"""Test query by package with pagination."""
response = requests.post(
_api() + _BASE_QUERY,
data=json.dumps(
{'package': {
'ecosystem': 'PyPI',
'name': 'tensorflow',
}}),
timeout=_TIMEOUT)
resu... | Test query by package with pagination. | test_query_pagination | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_query_pagination_no_ecosystem(self):
"""Test query with pagination but no ecosystem."""
response = requests.post(
_api() + _BASE_QUERY,
data=json.dumps({
'package': {
'name': 'django',
},
# Test with a version that is ambiguous whether... | Test query with pagination but no ecosystem. | test_query_pagination_no_ecosystem | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def test_all_possible_queries(self):
"""Test all combinations of valid and invalid queries"""
semver_package = {'package': {'purl': 'pkg:cargo/crossbeam-utils'}}
semver_package_with_version = {
'package': {
'purl': 'pkg:cargo/crossbeam-utils@0.8.5'
}
}
nonsemver_package... | Test all combinations of valid and invalid queries | test_all_possible_queries | python | google/osv.dev | gcp/api/integration_tests.py | https://github.com/google/osv.dev/blob/master/gcp/api/integration_tests.py | Apache-2.0 |
def GetVulnById(self, request, context):
"""Return a `Vulnerability` object for a given OSV ID.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Return a `Vulnerability` object for a given OSV ID.
| GetVulnById | python | google/osv.dev | gcp/api/osv_service_v1_pb2_grpc.py | https://github.com/google/osv.dev/blob/master/gcp/api/osv_service_v1_pb2_grpc.py | Apache-2.0 |
def DetermineVersion(self, request, context):
"""Determine the version of the provided hash values.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Determine the version of the provided hash values.
| DetermineVersion | python | google/osv.dev | gcp/api/osv_service_v1_pb2_grpc.py | https://github.com/google/osv.dev/blob/master/gcp/api/osv_service_v1_pb2_grpc.py | Apache-2.0 |
def ndb_context(func):
"""Wrapper to create an NDB context."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
with _ndb_client.context():
return func(*args, **kwargs)
return wrapper | Wrapper to create an NDB context. | ndb_context | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def log_trace(self, func):
"""Wrapper for grpc method to capture trace from header metadata"""
@functools.wraps(func)
def wrapper(s, r, context: grpc.ServicerContext):
self.thread_local.trace = dict(
context.invocation_metadata()).get('x-cloud-trace-context')
return func(s, r, context... | Wrapper for grpc method to capture trace from header metadata | log_trace | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def filter(self, record: logging.LogRecord) -> bool:
"""logging.Filter method to add trace into log data."""
trace = getattr(self.thread_local, 'trace', None)
if not trace:
return True
# Trace context header example:
# "X-Cloud-Trace-Context: TRACE_ID/SPAN_ID;o=TRACE_TRUE"
parts = trace.s... | logging.Filter method to add trace into log data. | filter | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def GetVulnById(self, request, context: grpc.ServicerContext):
"""Return a `Vulnerability` object for a given OSV ID."""
bug = osv.Bug.get_by_id(request.id)
if not bug:
# Check for aliases
alias_group = osv.AliasGroup.query(
osv.AliasGroup.bug_ids == request.id).get()
if alias_g... | Return a `Vulnerability` object for a given OSV ID. | GetVulnById | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def ImportFindings(self, request, context: grpc.ServicerContext):
"""Return a list of `ImportFinding` for a given source."""
source = request.source
# TODO(gongh@): add source check,
# check if the source name exists in the source repository.
if not source:
context.abort(grpc.StatusCode.INVALI... | Return a list of `ImportFinding` for a given source. | ImportFindings | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def Check(self, request, context: grpc.ServicerContext):
"""Health check per the gRPC health check protocol."""
del request # Unused.
del context # Unused.
# Read up to a single Bug entity from the DB. This should not cause an
# exception or time out.
osv.Bug.query().fetch(1)
return healt... | Health check per the gRPC health check protocol. | Check | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def cursor_at_current(self) -> ndb.Cursor | None:
"""
Return the cursor if the stored cursor is for the current query.
"""
if self.input_cursor.query_number == self.query_counter:
return self.input_cursor.ndb_cursor
return None |
Return the cursor if the stored cursor is for the current query.
| cursor_at_current | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def save_cursor_at_page_break(self, it: ndb.QueryIterator):
"""
Saves the cursor at the current page break position
"""
self.output_cursor.update_from_iterator(it)
self.output_cursor.query_number = self.query_counter |
Saves the cursor at the current page break position
| save_cursor_at_page_break | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def should_skip_bucket(path: str) -> bool:
"""Returns whether or not the given file path should be skipped for the
determineversions bucket computation."""
if not path:
return False
# Check for a nested vendored directory, as this could mess with results. The
# API expects the file path passed to be rela... | Returns whether or not the given file path should be skipped for the
determineversions bucket computation. | should_skip_bucket | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def process_buckets(
file_results: list[osv.FileResult]) -> list[osv.RepoIndexBucket]:
"""
Create buckets in the same process as
indexer to generate the same bucket hashes
"""
buckets: list[list[bytes]] = [[] for _ in range(_BUCKET_SIZE)]
for fr in file_results:
if should_skip_bucket(fr.path):
... |
Create buckets in the same process as
indexer to generate the same bucket hashes
| process_buckets | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def build_determine_version_result(
file_matches_by_proj: dict[ndb.Key, int],
bucket_matches_by_proj: dict[ndb.Key, int],
num_skipped_buckets: int,
# 1 means has items, 0 means empty
empty_bucket_bitmap: int,
query_file_count: int) -> osv_service_v1_pb2.VersionMatchList:
"""Build sorted determ... | Build sorted determine version result from the input | build_determine_version_result | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def estimate_diff(num_bucket_change: int, file_count_diff: int) -> int:
"""
Estimates the number of files that have changed based on
the number of buckets that changed.
"""
estimate = _BUCKET_SIZE * math.log(
(_BUCKET_SIZE + 1) / (_BUCKET_SIZE - num_bucket_change + 1))
return file_count_diff + round... |
Estimates the number of files that have changed based on
the number of buckets that changed.
| estimate_diff | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def bug_to_response(bug: osv.Bug,
include_details=True,
include_alias=False) -> vulnerability_pb2.Vulnerability:
"""Convert a Bug entity to a response object."""
if include_details:
return bug.to_vulnerability(
include_source=True, include_alias=include_alias)
... | Convert a Bug entity to a response object. | bug_to_response | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def _is_semver_affected(affected_packages: list[osv.AffectedPackage],
package_name: str | None, ecosystem: str | None,
version_str: str):
"""Returns whether or not the given version is within an affected SEMVER
range.
"""
version = semver_index.parse(version_str)... | Returns whether or not the given version is within an affected SEMVER
range.
| _is_semver_affected | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def _is_version_affected(affected_packages,
package_name,
ecosystem,
version,
normalize=False):
"""
Returns whether or not the given version is within an affected ECOSYSTEM
range.
"""
for affected_package in af... |
Returns whether or not the given version is within an affected ECOSYSTEM
range.
| _is_version_affected | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def _query_by_semver(context: QueryContext, query: ndb.Query,
package_name: str | None, ecosystem: str | None,
version: str) -> list[osv.Bug]:
"""
Perform a query by semver version.
This is a ndb.tasklet, so will return a future that will need to be yielded.
Args:
... |
Perform a query by semver version.
This is a ndb.tasklet, so will return a future that will need to be yielded.
Args:
context: QueryContext for the current query.
query: A partially completed ndb.Query object which only needs
semver filters to be added before query is performed.
package_name... | _query_by_semver | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def _query_by_generic_version(
context: QueryContext,
base_query: ndb.Query,
package_name: str | None,
ecosystem: str | None,
version: str,
) -> list[osv.Bug]:
"""
Query by generic version.
This is a ndb.tasklet, so will return a future that will need to be yielded.
Args:
context: Q... |
Query by generic version.
This is a ndb.tasklet, so will return a future that will need to be yielded.
Args:
context: QueryContext for the current query.
base_query: A partially completed ndb.Query object which only needs
version filters to be added before query is performed.
package_name... | _query_by_generic_version | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def query_by_generic_helper(context: QueryContext, base_query: ndb.Query,
package_name: str | None, ecosystem: str | None,
version: str, is_normalized: bool) -> list[osv.Bug]:
"""
Helper function for query_by_generic.
This function can be called multiple ti... |
Helper function for query_by_generic.
This function can be called multiple times.
| query_by_generic_helper | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def query_by_version(
context: QueryContext,
package_name: str | None,
ecosystem: str | None,
version: str,
to_response: ToResponseCallable = bug_to_response
) -> list[vulnerability_pb2.Vulnerability]:
"""
Query by (fuzzy) version.
This is a ndb.tasklet, so will return a future that will need... |
Query by (fuzzy) version.
This is a ndb.tasklet, so will return a future that will need to be yielded.
Args:
context: QueryContext for the current query.
package_name: Optional name of the package to query.
ecosystem: Optional ecosystem of the package to query.
version: The version str to query... | query_by_version | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def _query_by_comparing_versions(context: QueryContext, query: ndb.Query,
package_name: str, ecosystem: str,
version: str) -> list[osv.Bug]:
"""
Query by comparing versions.
Args:
context: QueryContext for the current query.
query: A parti... |
Query by comparing versions.
Args:
context: QueryContext for the current query.
query: A partially completed ndb.Query object which only needs
version filters to be added before query is performed.
package_name: Required name of the package to query.
ecosystem: Required ecosystem of the pac... | _query_by_comparing_versions | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def query_by_package(
context: QueryContext, package_name: str | None, ecosystem: str | None,
to_response: ToResponseCallable) -> list[vulnerability_pb2.Vulnerability]:
"""
Query by package.
This is a ndb.tasklet, so will return a future that will need to be yielded.
Args:
context: QueryContext ... |
Query by package.
This is a ndb.tasklet, so will return a future that will need to be yielded.
Args:
context: QueryContext for the current query.
package_name: Optional name of the package to query.
ecosystem: Optional ecosystem of the package to query.
to_response: Function to convert osv.Bu... | query_by_package | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def serve(port: int, local: bool):
"""Configures and runs the OSV API server."""
server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=5))
servicer = OSVServicer()
osv_service_v1_pb2_grpc.add_OSVServicer_to_server(servicer, server)
health_pb2_grpc.add_HealthServicer_to_server(servicer, server... | Configures and runs the OSV API server. | serve | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def is_cloud_run() -> bool:
"""Check if we are running in Cloud Run."""
# https://cloud.google.com/run/docs/container-contract#env-vars
return os.getenv('K_SERVICE') is not None | Check if we are running in Cloud Run. | is_cloud_run | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def is_matching_package_ecosystem(package_ecosystem: str,
ecosystem: str) -> bool:
"""Checks if the queried ecosystem matches the affected package's ecosystem,
considering potential variations in the package's ecosystem.
"""
# Special case for GIT queries,
# for which osv en... | Checks if the queried ecosystem matches the affected package's ecosystem,
considering potential variations in the package's ecosystem.
| is_matching_package_ecosystem | python | google/osv.dev | gcp/api/server.py | https://github.com/google/osv.dev/blob/master/gcp/api/server.py | Apache-2.0 |
def check(self):
"""Check that the server is still up."""
if self.backend and self.backend.poll():
raise RuntimeError('Backend process died.')
if self.esp.poll():
raise RuntimeError('ESP process died.') | Check that the server is still up. | check | python | google/osv.dev | gcp/api/test_server.py | https://github.com/google/osv.dev/blob/master/gcp/api/test_server.py | Apache-2.0 |
def _get_private_key():
"""Get the private key for signing the request."""
client = secretmanager.SecretManagerServiceClient()
response = client.access_secret_version(request={'name': _SECRET_NAME})
return json.loads(response.payload.data) | Get the private key for signing the request. | _get_private_key | python | google/osv.dev | gcp/functions/pypi/main.py | https://github.com/google/osv.dev/blob/master/gcp/functions/pypi/main.py | Apache-2.0 |
def smart_cache(
key: str,
hard_timeout: int,
soft_timeout: int,
) -> Callable:
"""
The decorated function will be cached with the given key.
If the decorated function is called any time after the `soft_timeout`
of the cache, the cached value will still be returned, but the cache
will be refre... |
The decorated function will be cached with the given key.
If the decorated function is called any time after the `soft_timeout`
of the cache, the cached value will still be returned, but the cache
will be refreshed in an asynchronous background thread.
Currently this decorator does not support differing... | smart_cache | python | google/osv.dev | gcp/website/cache.py | https://github.com/google/osv.dev/blob/master/gcp/website/cache.py | Apache-2.0 |
def setUp():
""" Set Up a series of bugs and UpstreamGroups to put in the emulator
for testing purposes."""
tests.reset_emulator()
osv.Bug(
id='ALIAS-CVE-1',
db_id='ALIAS-CVE-1',
aliases=['CVE-1', 'ALIAS'],
status=1,
upstream_raw=['CVE-1', 'CVE-2'],
source='test',
publi... | Set Up a series of bugs and UpstreamGroups to put in the emulator
for testing purposes. | setUp | python | google/osv.dev | gcp/website/frontend_emulator.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_emulator.py | Apache-2.0 |
def blog_post_static_files(blog_name: str, file_name: str):
"""Return static files under blog post directories"""
if not _VALID_BLOG_NAME.match(blog_name):
abort(404)
path = safe_join(current_app.static_folder, _BLOG_CONTENTS_DIR, 'posts',
blog_name)
if not path:
abort(404)
return... | Return static files under blog post directories | blog_post_static_files | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def vulnerability_redirector(potential_vuln_id: str):
"""Convenience redirector for /VULN-ID to /vulnerability/VULN-ID."""
# AlmaLinux have colons in their identifiers, which gets URL encoded.
potential_vuln_id = parse.unquote(potential_vuln_id)
if not _VALID_VULN_ID.match(potential_vuln_id):
abort(400)
... | Convenience redirector for /VULN-ID to /vulnerability/VULN-ID. | vulnerability_redirector | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def vulnerability_json_redirector(potential_vuln_id):
"""Convenience redirector for /VULN-ID.json and /vulnerability/VULN-ID.json to
https://api.osv.dev/v1/vulns/VULN-ID.
"""
if not _VALID_VULN_ID.match(potential_vuln_id):
abort(400)
return None
# This calls abort() on failed retrievals.
try:
b... | Convenience redirector for /VULN-ID.json and /vulnerability/VULN-ID.json to
https://api.osv.dev/v1/vulns/VULN-ID.
| vulnerability_json_redirector | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def add_stream_info(bug, response):
"""Add upstream hierarchy information to `response`."""
# Check whether there are upstreams
if bug.upstream_raw and 'upstream' in response:
upstream_hierarchy_string = get_upstreams_of_vulnerability(bug)
response['upstream_hierarchy'] = upstream_hierarchy_string
# Che... | Add upstream hierarchy information to `response`. | add_stream_info | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def calculate_severity_details(
severity: dict) -> tuple[float | None, str | None]:
"""Calculate score and rating of severity"""
cvss_calculator = {
'CVSS_V2': CVSS2,
'CVSS_V3': CVSS3,
'CVSS_V4': CVSS4,
}
type_ = severity.get('type')
score = severity.get('score')
if not (type_ and sc... | Calculate score and rating of severity | calculate_severity_details | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def add_source_info(bug, response):
"""Add upstream provenance information to `response`."""
if bug.source_of_truth == osv.SourceOfTruth.INTERNAL:
response['source'] = 'INTERNAL'
return
source_repo = osv.get_source_repository(bug.source)
if not source_repo or not source_repo.link:
logging.error(
... | Add upstream provenance information to `response`. | add_source_info | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def osv_get_ecosystem_counts_cached():
"""Get count of vulnerabilities per ecosystem, cached"""
# Check if we're already in ndb context, if not, put us in one
# We can sometimes not be in ndb context because caching
# runs in a separate thread
if ndb.get_context(raise_context_error=False) is None:
# IMPOR... | Get count of vulnerabilities per ecosystem, cached | osv_get_ecosystem_counts_cached | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def osv_get_ecosystem_counts() -> dict[str, int]:
"""Get count of vulnerabilities per ecosystem."""
counts = {}
ecosystem_names = osv_get_ecosystems()
for ecosystem in ecosystem_names:
if ':' in ecosystem or ecosystem == '[EMPTY]':
# Count by the base ecosystem index. Otherwise we'll overcount as a
... | Get count of vulnerabilities per ecosystem. | osv_get_ecosystem_counts | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def osv_get_by_id(vuln_id: str) -> dict:
"""Gets bug details from its id. If invalid, aborts the request."""
if not vuln_id:
abort(400)
bug = osv.Bug.get_by_id(vuln_id)
if not bug:
alias = check_for_aliases(vuln_id)
if not alias:
if osv.ImportFinding.get_by_id(vuln_id):
raise Vulnerab... | Gets bug details from its id. If invalid, aborts the request. | osv_get_by_id | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def check_for_aliases(vuln_id: str) -> osv.Bug | None:
""" Search for aliases of a vuln if only one exists """
alias_group = osv.AliasGroup.query(osv.AliasGroup.bug_ids == vuln_id).get()
if alias_group and len(alias_group.bug_ids) == 2:
# Assume if current ID doesn't exist, but an alias does, bug must exist.
... | Search for aliases of a vuln if only one exists | check_for_aliases | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def event_type(event):
"""Get the type from an event."""
if event.get('introduced'):
return 'Introduced'
if event.get('fixed'):
return 'Fixed'
if event.get('limit'):
return 'Limit'
if event.get('last_affected'):
return 'Last affected'
return None | Get the type from an event. | event_type | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def event_link(event):
"""Get the link from an event."""
if event.get('introduced_link'):
return event['introduced_link']
if event.get('fixed_link'):
return event['fixed_link']
if event.get('limit_link'):
return event['limit_link']
if event.get('last_affected_link'):
return event['last_affecte... | Get the link from an event. | event_link | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def event_value(event):
"""Get the value from an event."""
if event.get('introduced'):
return event['introduced']
if event.get('fixed'):
return event['fixed']
if event.get('limit'):
return event['limit']
if event.get('last_affected'):
return event['last_affected']
return None | Get the value from an event. | event_value | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def should_collapse(affected):
"""Whether if we should collapse the package tab bar."""
total_package_length = sum(
len(entry.get('package', {}).get('name', '')) for entry in affected)
return total_package_length > 70 or len(affected) > 5 | Whether if we should collapse the package tab bar. | should_collapse | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def sort_versions(versions: list[str], ecosystem: str) -> list[str]:
"""Sorts a list of version numbers in the given ecosystem's sorting order."""
try:
return sorted(versions, key=osv.ecosystems.get(ecosystem).sort_key)
except (NotImplementedError, AttributeError):
# If the ecosystem doesn't support order... | Sorts a list of version numbers in the given ecosystem's sorting order. | sort_versions | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def list_packages(vuln_affected: list[dict]):
"""Lists all affected package names without duplicates,
remaining in the original order."""
packages = []
for affected in vuln_affected:
if 'package' in affected:
package_entry = affected['package']['ecosystem'] + '/' + affected[
'package']['nam... | Lists all affected package names without duplicates,
remaining in the original order. | list_packages | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
def link_to_deps_dev(package, ecosystem):
"""
Generate a link to the deps.dev page for a given package in the specified
ecosystem.
Args:
package (str): The name of the package.
ecosystem (str): The ecosystem name.
Returns:
str or None: The URL to the deps.dev page for the package if the
... |
Generate a link to the deps.dev page for a given package in the specified
ecosystem.
Args:
package (str): The name of the package.
ecosystem (str): The ecosystem name.
Returns:
str or None: The URL to the deps.dev page for the package if the
ecosystem is supported, None otherwise.
| link_to_deps_dev | python | google/osv.dev | gcp/website/frontend_handlers.py | https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.