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 clean_artifacts(oss_fuzz_dir):
"""Clean build artifact from previous runs."""
build_dir = os.path.join(oss_fuzz_dir, 'build')
if os.path.exists(build_dir):
shutil.rmtree(build_dir, ignore_errors=True) | Clean build artifact from previous runs. | clean_artifacts | python | google/osv.dev | gcp/workers/worker/worker.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker.py | Apache-2.0 |
def fix_invalid_ghsa(vulnerability):
"""Attempt to fix an invalid GHSA entry.
Args:
vulnerability: a vulnerability object.
Returns:
whether the GHSA entry is valid.
"""
packages = {}
for affected in vulnerability.affected:
details = packages.setdefault(
(affected.package.ecosystem, aff... | Attempt to fix an invalid GHSA entry.
Args:
vulnerability: a vulnerability object.
Returns:
whether the GHSA entry is valid.
| fix_invalid_ghsa | python | google/osv.dev | gcp/workers/worker/worker.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker.py | Apache-2.0 |
def _handle_deleted(self, source_repo, vuln_path):
"""Handle existing bugs that have been subsequently deleted at their source.
Args:
source_repo: Source repository.
vuln_path: Path to vulnerability.
This marks the Bug as INVALID and as withdrawn.
"""
vuln_id = os.path.splitext(os.path... | Handle existing bugs that have been subsequently deleted at their source.
Args:
source_repo: Source repository.
vuln_path: Path to vulnerability.
This marks the Bug as INVALID and as withdrawn.
| _handle_deleted | python | google/osv.dev | gcp/workers/worker/worker.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker.py | Apache-2.0 |
def _analyze_vulnerability(self, source_repo, repo, vulnerability, path,
original_sha256):
"""Analyze vulnerability and push new changes."""
# Add OSS-Fuzz
added_fix_info = False
bug = osv.Bug.get_by_id(vulnerability.id)
if bug:
fix_result = osv.FixResult.get_by_id... | Analyze vulnerability and push new changes. | _analyze_vulnerability | python | google/osv.dev | gcp/workers/worker/worker.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker.py | Apache-2.0 |
def _maybe_remove_import_findings(self, vulnerability: osv.Bug):
"""Remove any stale import findings for a successfully processed Bug,"""
finding = osv.ImportFinding.get_by_id(vulnerability.id())
if finding:
logging.info('Removing stale import finding for %s', vulnerability.id())
finding.key.de... | Remove any stale import findings for a successfully processed Bug, | _maybe_remove_import_findings | python | google/osv.dev | gcp/workers/worker/worker.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker.py | Apache-2.0 |
def _log_task_latency(self, message):
"""Determine how long ago the task was requested.
Log how long it took to be serviced."""
request_time = message.attributes.get('req_timestamp')
if request_time:
request_time = int(request_time)
latency = int(time.time()) - request_time
task_type ... | Determine how long ago the task was requested.
Log how long it took to be serviced. | _log_task_latency | python | google/osv.dev | gcp/workers/worker/worker.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker.py | Apache-2.0 |
def test_no_issue(self):
"""Test generating details without an issue ID."""
crash_type = 'Heap-buffer-overflow'
crash_state = 'Foo\nBar\nBlah\n'
details = oss_fuzz.get_oss_fuzz_details('', crash_type, crash_state)
self.assertEqual(
'```\n'
'Crash type: Heap-buffer-overflow\n'
... | Test generating details without an issue ID. | test_no_issue | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_fixed_range_too_long(self):
"""Test fixed range that's too long."""
message = mock.Mock()
message.attributes = {
'source_id': 'oss-fuzz:123',
'allocated_id': 'OSV-2020-1337',
}
regress_result = osv.RegressResult(
id='oss-fuzz:123',
commit='eefe8ec3f1f90d0e68... | Test fixed range that's too long. | test_fixed_range_too_long | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_redhat_toobig(self):
"""Test failure handling of a too-large Red Hat record."""
solo_endpoint = 'RHSA-2018:3140' + '.json'
sha = 'a5cc068278ddad5f4c63d9b4f27baf59f296076306a24e850c5edde1b0232b0c'
self.source_repo.db_prefix.append('RHSA-')
self.source_repo.put()
task_runner = wo... | Test failure handling of a too-large Red Hat record. | test_update_redhat_toobig | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_new(self):
"""Test update with new vulnerability added."""
self.mock_repo.add_file(
'OSV-126.yaml',
self._load_test_data(os.path.join(TEST_DATA_DIR, 'OSV-126.yaml')),
)
self.mock_repo.commit('User', 'user@email')
task_runner = worker.TaskRunner(ndb_client, None, self... | Test update with new vulnerability added. | test_update_new | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_no_changes(self):
"""Test basic update (with no changes)."""
task_runner = worker.TaskRunner(ndb_client, None, self.tmp_dir.name, None,
None)
message = mock.Mock()
message.attributes = {
'source': 'source',
'path': 'OSV-125.yaml',
... | Test basic update (with no changes). | test_update_no_changes | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_conflict_while_pushing(self):
"""Test basic update with a conflict while pushing."""
original_push_source_changes = osv.push_source_changes
def mock_push_source_changes(*args, **kwargs):
self.mock_repo.add_file('OSV-123.yaml', 'changed')
self.mock_repo.commit('Another user', 'us... | Test basic update with a conflict while pushing. | test_update_conflict_while_pushing | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_normalize_pypi(self):
"""Test a PyPI entry normalizes as expected."""
self.source_repo.ignore_git = False
self.source_repo.versions_from_repo = False
self.source_repo.detect_cherrypicks = False
self.source_repo.db_prefix.append('PYSEC-')
self.source_repo.put()
self.mock_repo.add_fi... | Test a PyPI entry normalizes as expected. | test_normalize_pypi | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_android(self):
"""Test updating Android through bucket entries."""
self.source_repo.type = osv.SourceRepositoryType.BUCKET
self.source_repo.bucket = TEST_BUCKET
self.source_repo.editable = False
self.source_repo.db_prefix.append('ASB-A-')
self.source_repo.put()
task_runner =... | Test updating Android through bucket entries. | test_update_android | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_bad_ecosystem_new(self):
"""Test adding from an unsupported ecosystem."""
self.mock_repo.add_file(
'OSV-129.yaml',
self._load_test_data(os.path.join(TEST_DATA_DIR, 'OSV-129.yaml')),
)
self.mock_repo.commit('User', 'user@email')
task_runner = worker.TaskRunner(ndb_cli... | Test adding from an unsupported ecosystem. | test_update_bad_ecosystem_new | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_partly_bad_ecosystem_new(self):
"""Test adding vuln with both supported and unsupported ecosystem."""
self.mock_repo.add_file(
'OSV-130.yaml',
self._load_test_data(os.path.join(TEST_DATA_DIR, 'OSV-130.yaml')),
)
self.mock_repo.commit('User', 'user@email')
task_runner... | Test adding vuln with both supported and unsupported ecosystem. | test_update_partly_bad_ecosystem_new | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_partly_bad_ecosystem_delete(self):
"""Test removal of only supported ecosystem in vulnerability with
unsupported and supported ecosystems.
"""
task_runner = worker.TaskRunner(ndb_client, None, self.tmp_dir.name, None,
None)
message = mock.M... | Test removal of only supported ecosystem in vulnerability with
unsupported and supported ecosystems.
| test_update_partly_bad_ecosystem_delete | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_bucket_cve(self):
"""Test a bucket entry that is a converted CVE and doesn't have an ecosystem."""
self.source_repo.type = osv.SourceRepositoryType.BUCKET
self.source_repo.bucket = TEST_BUCKET
self.source_repo.editable = False
self.source_repo.db_prefix.append('CVE-')
self.source... | Test a bucket entry that is a converted CVE and doesn't have an ecosystem. | test_update_bucket_cve | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_invalid_prefix(self):
"""Test attempting to create a bug with a invalid db_prefix."""
with self.assertRaises(ValueError):
# Default db_prefix is `OSV-`
osv.Bug(
db_id='BLAH-131',
project=['blah.com/package'],
ecosystem=['ecosystem'],
source_id='source... | Test attempting to create a bug with a invalid db_prefix. | test_invalid_prefix | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_dont_index_too_many_git_versions(self):
"""Test that we don't index too many versions from Git."""
self.source_repo.ignore_git = False
self.source_repo.versions_from_repo = True
self.source_repo.detect_cherrypicks = True
self.source_repo.put()
# Use any valid OSV input test file here.
... | Test that we don't index too many versions from Git. | test_dont_index_too_many_git_versions | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_analysis_crash_handling(self):
"""Test that formerly crash-inducing GIT events are handled gracefully."""
self.source_repo.ignore_git = False
self.source_repo.versions_from_repo = True
self.source_repo.detect_cherrypicks = False
self.source_repo.db_prefix.append('CVE-')
self.source_repo... | Test that formerly crash-inducing GIT events are handled gracefully. | test_analysis_crash_handling | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def test_update_clears_stale_import_finding(self):
"""A subsequent successful update removes the now stale import finding."""
# Add a pre-existing record import finding.
osv.ImportFinding(
bug_id='OSV-123',
source='source',
findings=[osv.ImportFindings.INVALID_JSON],
first_... | A subsequent successful update removes the now stale import finding. | test_update_clears_stale_import_finding | python | google/osv.dev | gcp/workers/worker/worker_test.py | https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker_test.py | Apache-2.0 |
def populate_indices(bug):
"""Write search indices for the bug."""
bug['has_affected'] = bool(bug.get('affected'))
search_indices = []
project = bug.get('project')
if project:
search_indices.append(project)
search_indices.append(bug.key.id_or_name)
search_indices.extend(bug.key.id_or_name.split('-')... | Write search indices for the bug. | populate_indices | python | google/osv.dev | osv/bug.py | https://github.com/google/osv.dev/blob/master/osv/bug.py | Apache-2.0 |
def cached(cache: Cache, ttl: int = 60 * 60):
"""Function decorator to cache results.
Args:
cache: Cache object to store information, each function also has a unique
key for values cached, therefore you can safely share the same cache
object across different functions.
ttl: Time to live in seco... | Function decorator to cache results.
Args:
cache: Cache object to store information, each function also has a unique
key for values cached, therefore you can safely share the same cache
object across different functions.
ttl: Time to live in seconds (default 1 hour).
| cached | python | google/osv.dev | osv/cache.py | https://github.com/google/osv.dev/blob/master/osv/cache.py | Apache-2.0 |
def enumerate_versions(package, ecosystem, affected_range):
"""Enumerate versions from SEMVER and ECOSYSTEM input ranges."""
versions = set()
sorted_events = []
limits = []
# Remove any magic '0' values.
zero_event = None
for event in affected_range.events:
if event.introduced == '0':
zero_even... | Enumerate versions from SEMVER and ECOSYSTEM input ranges. | enumerate_versions | python | google/osv.dev | osv/impact.py | https://github.com/google/osv.dev/blob/master/osv/impact.py | Apache-2.0 |
def filter(self, record: logging.LogRecord) -> bool:
"""Add the error reporting fields to json_fields."""
if not hasattr(record, 'json_fields'):
record.json_fields = {}
if record.levelno >= logging.ERROR and not record.exc_info:
record.json_fields.update({
'@type':
'type... | Add the error reporting fields to json_fields. | filter | python | google/osv.dev | osv/logs.py | https://github.com/google/osv.dev/blob/master/osv/logs.py | Apache-2.0 |
def setup_gcp_logging(service_name):
"""Set up GCP logging and error reporting."""
logging_client = google_logging.Client()
logging_client.setup_logging()
logging.getLogger().addFilter(_ErrorReportingFilter(service_name))
logging.getLogger().setLevel(logging.INFO)
# Suppress noisy logs in some of our dep... | Set up GCP logging and error reporting. | setup_gcp_logging | python | google/osv.dev | osv/logs.py | https://github.com/google/osv.dev/blob/master/osv/logs.py | Apache-2.0 |
def _get_purl_indexes(affected_packages):
"""Get list of purls from affected packages, with and without qualifiers"""
resulting_set = set()
for pkg in affected_packages:
if pkg.package.purl:
resulting_set.add(pkg.package.purl)
if '?' in pkg.package.purl:
resulting_set.add(pkg.package.purl.... | Get list of purls from affected packages, with and without qualifiers | _get_purl_indexes | python | google/osv.dev | osv/models.py | https://github.com/google/osv.dev/blob/master/osv/models.py | Apache-2.0 |
def _maybe_strip_repo_prefixes(versions: list[str],
repo_urls: list[str]) -> str:
"""Try to strip the repo name from tags prior to normalizing.
There are some particularly regex-unfriendly tag names that prefix the
reponame that end in a number, like "openj9-0.8.0", resulting in an... | Try to strip the repo name from tags prior to normalizing.
There are some particularly regex-unfriendly tag names that prefix the
reponame that end in a number, like "openj9-0.8.0", resulting in an
incorrectly normalized version.
| _maybe_strip_repo_prefixes | python | google/osv.dev | osv/models.py | https://github.com/google/osv.dev/blob/master/osv/models.py | Apache-2.0 |
def repo_url(self):
"""Repo URL. Assumes there is only ever one repo URL per advisory."""
for affected_package in self.affected_packages:
for affected_range in affected_package.ranges:
if affected_range.repo_url:
return affected_range.repo_url
return None | Repo URL. Assumes there is only ever one repo URL per advisory. | repo_url | python | google/osv.dev | osv/models.py | https://github.com/google/osv.dev/blob/master/osv/models.py | Apache-2.0 |
def get_by_id(cls, vuln_id, *args, **kwargs) -> Self | None:
"""Overridden get_by_id to handle OSV allocated IDs."""
result = cls.query(cls.db_id == vuln_id).get()
if result:
return result
# TODO(ochang): Remove once all exsting bugs have IDs migrated.
if vuln_id.startswith(cls.OSV_ID_PREFIX)... | Overridden get_by_id to handle OSV allocated IDs. | get_by_id | python | google/osv.dev | osv/models.py | https://github.com/google/osv.dev/blob/master/osv/models.py | Apache-2.0 |
def _pre_put_hook(self): # pylint: disable=arguments-differ
"""Pre-put hook for populating search indices."""
search_indices = set()
search_indices.update(self._tokenize(self.id()))
for pkg in self.affected_packages:
# Set PURL if it wasn't provided.
if not pkg.package.purl:
pkg.p... | Pre-put hook for populating search indices. | _pre_put_hook | python | google/osv.dev | osv/models.py | https://github.com/google/osv.dev/blob/master/osv/models.py | Apache-2.0 |
def update_from_vulnerability(self, vulnerability):
"""Set fields from vulnerability. Does not set the ID."""
self.summary = vulnerability.summary
self.details = vulnerability.details
self.reference_url_types = {
ref.url: vulnerability_pb2.Reference.Type.Name(ref.type)
for ref in vulnera... | Set fields from vulnerability. Does not set the ID. | update_from_vulnerability | python | google/osv.dev | osv/models.py | https://github.com/google/osv.dev/blob/master/osv/models.py | Apache-2.0 |
def to_vulnerability_async(self,
include_source=False,
include_alias=False,
include_upstream=False):
"""Converts to Vulnerability proto and retrieves aliases asynchronously."""
vulnerability: vulnerability_pb2.Vulnerability =... | Converts to Vulnerability proto and retrieves aliases asynchronously. | to_vulnerability_async | python | google/osv.dev | osv/models.py | https://github.com/google/osv.dev/blob/master/osv/models.py | Apache-2.0 |
def ignore_file(self, file_path):
"""Return whether or not we should be ignoring a file."""
if not self.ignore_patterns:
return False
file_name = os.path.basename(file_path)
for pattern in self.ignore_patterns:
if re.match(pattern, file_name):
return True
return False | Return whether or not we should be ignoring a file. | ignore_file | python | google/osv.dev | osv/models.py | https://github.com/google/osv.dev/blob/master/osv/models.py | Apache-2.0 |
def _pre_put_hook(self): # pylint: disable=arguments-differ
"""Pre-put hook for setting key."""
if not self.key: # pylint: disable=access-member-before-definition
self.key = ndb.Key(ImportFinding, self.bug_id) | Pre-put hook for setting key. | _pre_put_hook | python | google/osv.dev | osv/models.py | https://github.com/google/osv.dev/blob/master/osv/models.py | Apache-2.0 |
def _url_encode(package_name):
"""URL encode a PURL `namespace/name` or `name`."""
parts = package_name.split('/')
return '/'.join(quote(p) for p in parts) | URL encode a PURL `namespace/name` or `name`. | _url_encode | python | google/osv.dev | osv/purl_helpers.py | https://github.com/google/osv.dev/blob/master/osv/purl_helpers.py | Apache-2.0 |
def package_to_purl(ecosystem: str, package_name: str) -> str | None:
"""Convert a ecosystem and package name to PURL."""
purl_data = ECOSYSTEM_PURL_DATA.get(ecosystem)
if not purl_data:
return None
purl_type, purl_namespace = purl_data
if purl_namespace:
purl_ecosystem = f'{purl_type}/{purl_namespac... | Convert a ecosystem and package name to PURL. | package_to_purl | python | google/osv.dev | osv/purl_helpers.py | https://github.com/google/osv.dev/blob/master/osv/purl_helpers.py | Apache-2.0 |
def parse_purl(purl_str: str) -> ParsedPURL | None:
"""Parses a PURL string and extracts
ecosystem, package, and version information.
Args:
purl_str: The Package URL string to parse.
Returns:
A tuple containing the ecosystem, package,
and version, or None if parsing fails.
"""
purl = PackageU... | Parses a PURL string and extracts
ecosystem, package, and version information.
Args:
purl_str: The Package URL string to parse.
Returns:
A tuple containing the ecosystem, package,
and version, or None if parsing fails.
| parse_purl | python | google/osv.dev | osv/purl_helpers.py | https://github.com/google/osv.dev/blob/master/osv/purl_helpers.py | Apache-2.0 |
def _git_mirror(git_url):
"""Get git mirror. If no mirror exists, return the git URL as is."""
mirror = _GIT_MIRRORS.get(git_url.rstrip('/'))
if mirror:
logging.info('Using mirror %s for git URL %s.', mirror, git_url)
return mirror
return git_url | Get git mirror. If no mirror exists, return the git URL as is. | _git_mirror | python | google/osv.dev | osv/repos.py | https://github.com/google/osv.dev/blob/master/osv/repos.py | Apache-2.0 |
def _set_git_callback_env(git_callbacks):
"""Set the environment variable to set git callbacks for cli git"""
env = {
# Prevent prompting for username if we don't have an ssh key
'GIT_TERMINAL_PROMPT': '0'
}
if git_callbacks:
env['GIT_SSH_COMMAND'] = (
f'ssh -i "{git_callbacks.ssh_key_pr... | Set the environment variable to set git callbacks for cli git | _set_git_callback_env | python | google/osv.dev | osv/repos.py | https://github.com/google/osv.dev/blob/master/osv/repos.py | Apache-2.0 |
def get(self, url):
"""Getter method.
Retrieves the text at the URL, using the cached result if available.
Args:
url: URL to retrieve
Returns:
the text at the URL.
Raises:
RequestError on a non-200 HTTP response.
"""
if self.cache:
cached_result = self.cache.get(... | Getter method.
Retrieves the text at the URL, using the cached result if available.
Args:
url: URL to retrieve
Returns:
the text at the URL.
Raises:
RequestError on a non-200 HTTP response.
| get | python | google/osv.dev | osv/request_helper.py | https://github.com/google/osv.dev/blob/master/osv/request_helper.py | Apache-2.0 |
def _strip_leading_v(version):
"""Strip leading v from the version, if any."""
# Versions starting with "v" aren't valid SemVer, but we handle them just in
# case.
if version.startswith('v'):
return version[1:]
return version | Strip leading v from the version, if any. | _strip_leading_v | python | google/osv.dev | osv/semver_index.py | https://github.com/google/osv.dev/blob/master/osv/semver_index.py | Apache-2.0 |
def _coerce_suffix(suffix):
"""Coerce a potentially invalid semver suffix into a valid semver suffix.
Removes leading zeros from the pre-release suffix and modifies empty
components to allow earlier SemVer specs (specifically 2.0.0-rc.1) to be
parsed.
Empty components are replaced with '-' (i.e 1.0.0-a..0 -... | Coerce a potentially invalid semver suffix into a valid semver suffix.
Removes leading zeros from the pre-release suffix and modifies empty
components to allow earlier SemVer specs (specifically 2.0.0-rc.1) to be
parsed.
Empty components are replaced with '-' (i.e 1.0.0-a..0 -> 1.0.0-a.-.0) which
mostly pre... | _coerce_suffix | python | google/osv.dev | osv/semver_index.py | https://github.com/google/osv.dev/blob/master/osv/semver_index.py | Apache-2.0 |
def coerce(version: str):
"""Coerce a potentially invalid semver into valid semver."""
version = _strip_leading_v(version)
version_pattern = re.compile(r'^(\d+)(\.\d+)?(\.\d+)?(.*)$')
match = version_pattern.match(version)
if not match:
return version
return (_remove_leading_zero(match.group(1)) +
... | Coerce a potentially invalid semver into valid semver. | coerce | python | google/osv.dev | osv/semver_index.py | https://github.com/google/osv.dev/blob/master/osv/semver_index.py | Apache-2.0 |
def normalize(version):
"""Normalize semver version for indexing (to allow for lexical
sorting/filtering)."""
version = parse(version)
# Precedence rules: https://semver.org/#spec-item-11
# 1. Precedence MUST be calculated by separating the version into major,
# minor, patch and pre-release identifiers in... | Normalize semver version for indexing (to allow for lexical
sorting/filtering). | normalize | python | google/osv.dev | osv/semver_index.py | https://github.com/google/osv.dev/blob/master/osv/semver_index.py | Apache-2.0 |
def normalize_prerelease(prerelease):
"""Normalize semver pre-release version suffix for indexing (to allow for
lexical sorting/filtering)."""
# 4. Precedence for two pre-release versions with the same major, minor, and
# patch version MUST be determined by comparing each dot separated identifier
# from left ... | Normalize semver pre-release version suffix for indexing (to allow for
lexical sorting/filtering). | normalize_prerelease | python | google/osv.dev | osv/semver_index.py | https://github.com/google/osv.dev/blob/master/osv/semver_index.py | Apache-2.0 |
def remove_implicit_resolver(cls, tag_to_remove):
"""
Remove implicit resolvers for a particular tag
Takes care not to modify resolvers in super classes.
"""
if 'yaml_implicit_resolvers' not in cls.__dict__:
cls.yaml_implicit_resolvers = cls.yaml_implicit_resolvers.copy()
for first_lette... |
Remove implicit resolvers for a particular tag
Takes care not to modify resolvers in super classes.
| remove_implicit_resolver | python | google/osv.dev | osv/sources.py | https://github.com/google/osv.dev/blob/master/osv/sources.py | Apache-2.0 |
def parse_vulnerabilities(path, key_path=None, strict=False):
"""Parse vulnerabilities (potentially multiple in a list)."""
return _parse_vulnerabilities(
_parse_vulnerability_dict(path), key_path, strict) | Parse vulnerabilities (potentially multiple in a list). | parse_vulnerabilities | python | google/osv.dev | osv/sources.py | https://github.com/google/osv.dev/blob/master/osv/sources.py | Apache-2.0 |
def source_path(source_repo, bug):
"""Get the source path for an osv.Bug."""
source_name, source_id = parse_source_id(bug.source_id)
if source_name == 'oss-fuzz' and len(bug.project) > 0:
path = os.path.join(bug.project[0], bug.id() + source_repo.extension)
if source_repo.directory_path:
path = os.p... | Get the source path for an osv.Bug. | source_path | python | google/osv.dev | osv/sources.py | https://github.com/google/osv.dev/blob/master/osv/sources.py | Apache-2.0 |
def ExpectationTest(test_data_dir): # pylint: disable=invalid-name
"""Mixin for test output generation/comparison."""
class Mixin:
"""Mixin."""
def _load_expected(self, expected_name, actual):
"""Load expected data."""
expected_path = os.path.join(
test_data_dir, f'{self.__class__._... | Mixin for test output generation/comparison. | ExpectationTest | python | google/osv.dev | osv/tests.py | https://github.com/google/osv.dev/blob/master/osv/tests.py | Apache-2.0 |
def expect_lines_equal(self, expected_name, actual_lines):
"""Check if the output lines is equal to the expected value,
printing a diff when it is different."""
expected_lines = self._load_expected(expected_name, actual_lines)
if expected_lines != actual_lines:
diff = difflib.unified_dif... | Check if the output lines is equal to the expected value,
printing a diff when it is different. | expect_lines_equal | python | google/osv.dev | osv/tests.py | https://github.com/google/osv.dev/blob/master/osv/tests.py | Apache-2.0 |
def _wait_for_emulator_ready(proc,
emulator,
indicator,
timeout=_EMULATOR_TIMEOUT):
"""Waits for emulator to be ready."""
global emulator_stdout_thread_output
emulator_stdout_thread_output = ''
def _read_thread(proc, ready_e... | Waits for emulator to be ready. | _wait_for_emulator_ready | python | google/osv.dev | osv/tests.py | https://github.com/google/osv.dev/blob/master/osv/tests.py | Apache-2.0 |
def analyze(path, checkout_path, key_path, analyze_git, detect_cherrypicks,
consider_all_branches):
"""Analyze and write changes to file."""
logging.info('Analyzing %s', path)
try:
vuln = sources.parse_vulnerability(path, key_path)
except Exception:
logging.error('Failed to parse %s', path)
... | Analyze and write changes to file. | analyze | python | google/osv.dev | osv/analyze_tool/__init__.py | https://github.com/google/osv.dev/blob/master/osv/analyze_tool/__init__.py | Apache-2.0 |
def _process_git_log(output: str) -> list:
"""
Takes git log diff output,
finds all changes to pkgver and pkgrel and outputs that in an unsorted list
"""
all_versions = set()
# Filter out the relevant lines
lines = [
x for x in output.splitlines()
if len(x) == 0 or x.startswi... |
Takes git log diff output,
finds all changes to pkgver and pkgrel and outputs that in an unsorted list
| _process_git_log | python | google/osv.dev | osv/ecosystems/alpine.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/alpine.py | Apache-2.0 |
def enumerate_versions(self,
package: str,
introduced,
fixed=None,
last_affected=None,
limits=None):
"""We use Alpines aports git repository history to do version enum"""
if config.work_... | We use Alpines aports git repository history to do version enum | enumerate_versions | python | google/osv.dev | osv/ecosystems/alpine.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/alpine.py | Apache-2.0 |
def _get_versions(branch: str, package: str) -> typing.List[str]:
"""Get all versions for a package from aports repo"""
# Checkout the repo at the alpine version branch
checkout_dir = os.path.join(config.work_dir, Alpine._GIT_REPO_PATH)
repos.ensure_updated_checkout(
Alpine._APORTS_GIT_URL, che... | Get all versions for a package from aports repo | _get_versions | python | google/osv.dev | osv/ecosystems/alpine.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/alpine.py | Apache-2.0 |
def test_alpine(self, ensure_updated_checkout_mock: mock.MagicMock):
"""Test Alpine ecosystem enumeration and caching behaviour"""
in_memory_cache = cache.InMemoryCache()
ecosystems.config.set_cache(in_memory_cache)
# Set work_dir to allow cloning/fetching
ecosystems.config.work_dir = self._TEST_DA... | Test Alpine ecosystem enumeration and caching behaviour | test_alpine | python | google/osv.dev | osv/ecosystems/alpine_test.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/alpine_test.py | Apache-2.0 |
def _enumerate_versions(self,
url,
bioc_versions,
package,
introduced,
fixed=None,
last_affected=None,
limits=None):
"""Helper method ... | Helper method to enumerate versions from a specific URL. | _enumerate_versions | python | google/osv.dev | osv/ecosystems/bioconductor.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/bioconductor.py | Apache-2.0 |
def set_cache(cache: typing.Optional[Cache]):
"""Configures and enables the redis caching layer"""
global shared_cache
shared_cache = cache | Configures and enables the redis caching layer | set_cache | python | google/osv.dev | osv/ecosystems/config.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/config.py | Apache-2.0 |
def _get_first_versions_for_release(release_number: str):
"""Gets the first version mapping for specific release number"""
response = requests.get(
CLOUD_API_CACHE_URL_TEMPLATE.format(version=release_number),
timeout=config.timeout)
if response.status_code == 404:
raise ReleaseNotFoundError(releas... | Gets the first version mapping for specific release number | _get_first_versions_for_release | python | google/osv.dev | osv/ecosystems/debian.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/debian.py | Apache-2.0 |
def test_debian(self, first_ver_requests_mock: mock.MagicMock,
general_requests_mock: mock.MagicMock):
"""Test Debian ecosystem enumeration and caching behaviour"""
in_memory_cache = cache.InMemoryCache()
ecosystems.config.set_cache(in_memory_cache)
ecosystem = ecosystems.get('Debian:9... | Test Debian ecosystem enumeration and caching behaviour | test_debian | python | google/osv.dev | osv/ecosystems/debian_test.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/debian_test.py | Apache-2.0 |
def test_debian_sort_key(self):
"""Tests Debian sort key across different releases."""
ecosystem = ecosystems.get('Debian')
# Compares base versions
self.assertGreater(ecosystem.sort_key('1.2.3'), ecosystem.sort_key('1.2'))
self.assertGreater(ecosystem.sort_key('1.3'), ecosystem.sort_key('1.2-3'))
... | Tests Debian sort key across different releases. | test_debian_sort_key | python | google/osv.dev | osv/ecosystems/debian_test.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/debian_test.py | Apache-2.0 |
def test_ecosystem_supported_by_schema(self):
"""Test ecosystems referenced exist in schema definition"""
for ecosystem in self.canonical_ecosystems:
self.assertIsNotNone(
self.schema_ecosystems.match(ecosystem),
msg=f'"{ecosystem}" not defined in schema')
for ecosystem in _ecosys... | Test ecosystems referenced exist in schema definition | test_ecosystem_supported_by_schema | python | google/osv.dev | osv/ecosystems/ecosystems_test.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/ecosystems_test.py | Apache-2.0 |
def sort_key(self, version):
"""Sort key.
The Haskell package version data type is defined at
https://hackage.haskell.org/package/Cabal-syntax/docs/Distribution-Types-Version.html
"""
# If version is not valid, it is most likely an invalid input version
# then sort it to the last/largest eleme... | Sort key.
The Haskell package version data type is defined at
https://hackage.haskell.org/package/Cabal-syntax/docs/Distribution-Types-Version.html
| sort_key | python | google/osv.dev | osv/ecosystems/haskell.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/haskell.py | Apache-2.0 |
def tag_to_version(cls, tag: str) -> typing.Optional[str]:
"""Convert a tag to a release version, or return None if invalid.
GHC release tags follow the scheme:
- ghc-<major>.<minor>.<patch>-alpha<n>
- ghc-<major>.<minor>.<patch>-rc<n>
- ghc-<major>.<minor>.<patch>-release
"""
parts = tag... | Convert a tag to a release version, or return None if invalid.
GHC release tags follow the scheme:
- ghc-<major>.<minor>.<patch>-alpha<n>
- ghc-<major>.<minor>.<patch>-rc<n>
- ghc-<major>.<minor>.<patch>-release
| tag_to_version | python | google/osv.dev | osv/ecosystems/haskell.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/haskell.py | Apache-2.0 |
def is_major_minor_patch(s: str) -> bool:
"""Check that string matches ``<int>.<int>.<int>``."""
parts = s.split('.')
return len(parts) == 3 and all(x.isdigit() for x in parts) | Check that string matches ``<int>.<int>.<int>``. | is_major_minor_patch | python | google/osv.dev | osv/ecosystems/haskell.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/haskell.py | Apache-2.0 |
def enumerate_versions(self,
package,
introduced,
fixed=None,
last_affected=None,
limits=None):
"""Enumerate versions.
Different components of GHC are part of the same software release.
... | Enumerate versions.
Different components of GHC are part of the same software release.
So we ignore the package (component) name.
| enumerate_versions | python | google/osv.dev | osv/ecosystems/haskell.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/haskell.py | Apache-2.0 |
def next_version(self, package, version):
"""Get the next version after the given version."""
versions = self.enumerate_versions(package, version, fixed=None)
# Check if the key used for sorting is equal as sometimes different
# strings could evaluate to the same version.
if versions and self.sort_k... | Get the next version after the given version. | next_version | python | google/osv.dev | osv/ecosystems/helper_base.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/helper_base.py | Apache-2.0 |
def _deps_dev_enumerate(self,
package,
introduced,
fixed=None,
last_affected=None,
limits=None):
"""Use deps.dev to get list of versions."""
ecosystem = self._DEPS_DEV_ECOSYSTEM_MAP[... | Use deps.dev to get list of versions. | _deps_dev_enumerate | python | google/osv.dev | osv/ecosystems/helper_base.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/helper_base.py | Apache-2.0 |
def qualifier_order(token):
"""Returns an integer representing a token's order."""
# ".qualifier" < "-qualifier" < "-number" < ".number"
if token.value.isdigit():
if token.prefix == '-':
return 2
assert token.prefix == '.'
return 3
if token.prefix == '-':
return 1
assert token.prefix ... | Returns an integer representing a token's order. | qualifier_order | python | google/osv.dev | osv/ecosystems/maven.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/maven.py | Apache-2.0 |
def check_versions_order(self, *versions):
"""Check that our precedence logic matches the expected order."""
parsed_versions = [maven.Version.from_string(v) for v in versions]
# pylint: disable=consider-using-enumerate
for i in range(len(parsed_versions)):
for j in range(i + 1, len(parsed_version... | Check that our precedence logic matches the expected order. | check_versions_order | python | google/osv.dev | osv/ecosystems/maven_test.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/maven_test.py | Apache-2.0 |
def check_versions_equal(self, *versions):
"""Check that the provided versions are equivalent."""
parsed_versions = [maven.Version.from_string(v) for v in versions]
# pylint: disable=consider-using-enumerate
for i in range(len(parsed_versions)):
for j in range(i + 1, len(parsed_versions)):
... | Check that the provided versions are equivalent. | check_versions_equal | python | google/osv.dev | osv/ecosystems/maven_test.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/maven_test.py | Apache-2.0 |
def test_versions_equal(self):
"""Test versions that should be considered equal."""
self.check_versions_equal('1', '1')
self.check_versions_equal('1', '1.0')
self.check_versions_equal('1', '1.0.0')
self.check_versions_equal('1.0', '1.0.0')
self.check_versions_equal('1', '1-0')
self.check_ver... | Test versions that should be considered equal. | test_versions_equal | python | google/osv.dev | osv/ecosystems/maven_test.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/maven_test.py | Apache-2.0 |
def test_version_zero(self):
"""Test comparison and equality with versions 0.0.0"""
self.check_versions_equal('0.0.0', '0.0', '0')
self.check_versions_equal('0.0.0-0.0.0', '0-final-ga', '0')
self.check_versions_order('0', '1')
# actual case from com.graphql-java:graphql-java
self.check_versions... | Test comparison and equality with versions 0.0.0 | test_version_zero | python | google/osv.dev | osv/ecosystems/maven_test.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/maven_test.py | Apache-2.0 |
def _extract_revision(str_version):
"""Extract revision (4th component) from version number (if any)."""
# e.g. '1.0.0.0-prerelease'
pattern = re.compile(r'^(\d+)(\.\d+)(\.\d+)(\.\d+)(.*)')
match = pattern.match(str_version)
if not match:
return str_version, 0
return (''.join(
(match.group(1), ma... | Extract revision (4th component) from version number (if any). | _extract_revision | python | google/osv.dev | osv/ecosystems/nuget.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/nuget.py | Apache-2.0 |
def php_slices_compare(a_split: List[str], b_split: List[str]):
"""
Compare php versions after being split by '.'
"""
for a, b in zip(a_split, b_split):
if a.isdigit() and b.isdigit():
compare = int(a) - int(b)
elif not a.isdigit() and not b.isdigit():
compare = PackagistVers... |
Compare php versions after being split by '.'
| php_slices_compare | python | google/osv.dev | osv/ecosystems/packagist.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/packagist.py | Apache-2.0 |
def php_version_compare(version_a: str, version_b: str) -> int:
"""
Given two php versions, compare which is newer
:return: 1 if a > b, -1 if b > a, 0 if a == b
"""
version_a = PackagistVersion.php_canonicalize_version(version_a)
version_b = PackagistVersion.php_canonicalize_version(version_b)
... |
Given two php versions, compare which is newer
:return: 1 if a > b, -1 if b > a, 0 if a == b
| php_version_compare | python | google/osv.dev | osv/ecosystems/packagist.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/packagist.py | Apache-2.0 |
def php_canonicalize_version(version: str) -> str:
"""
Replaces special separators (`-`,`_`,`+`) with `.`, and inserts `.`
between any digit and non-digit.
"""
if version.startswith('v'):
version = version[1:]
replaced = re.sub('[-_+]', '.', version)
replaced = re.sub(r'([^\d.])(\d)', ... |
Replaces special separators (`-`,`_`,`+`) with `.`, and inserts `.`
between any digit and non-digit.
| php_canonicalize_version | python | google/osv.dev | osv/ecosystems/packagist.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/packagist.py | Apache-2.0 |
def compare_special_versions(version_part_a: str, version_part_b: str) -> int:
# pylint: disable=line-too-long
"""
Compares the order of special characters against the order specified in php
docs.
any string not found in this list < dev < alpha = a < beta = b < RC = rc < # < pl = p.
:return: 1... |
Compares the order of special characters against the order specified in php
docs.
any string not found in this list < dev < alpha = a < beta = b < RC = rc < # < pl = p.
:return: 1 if a > b, -1 if b > a, 0 if a == b
| compare_special_versions | python | google/osv.dev | osv/ecosystems/packagist.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/packagist.py | Apache-2.0 |
def test_empty_identifier(self):
"""Test parsing versions with empty identifiers.
Although it's unlikely that it was intentional, SemVer 2.0.0-rc.1 does not
explicitly disallow this case. Not sure if Pub even allows it.
This test is probably unnecessary."""
pub.Version.from_string('1.0.0-a..b')
... | Test parsing versions with empty identifiers.
Although it's unlikely that it was intentional, SemVer 2.0.0-rc.1 does not
explicitly disallow this case. Not sure if Pub even allows it.
This test is probably unnecessary. | test_empty_identifier | python | google/osv.dev | osv/ecosystems/pub_test.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/pub_test.py | Apache-2.0 |
def get(name: str) -> Ecosystem:
"""Get ecosystem helpers for a given ecosystem."""
if name.startswith('Debian'):
return Debian(name.partition(':')[2])
if name.startswith('Alpine'):
return Alpine(name.partition(':')[2])
if name.startswith('AlmaLinux'):
return AlmaLinux()
if name.startswith('Ma... | Get ecosystem helpers for a given ecosystem. | get | python | google/osv.dev | osv/ecosystems/_ecosystems.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/_ecosystems.py | Apache-2.0 |
def add_matching_ecosystems(original_set: set[str]) -> set[str]:
"""
For Linux distributions, some release versions may have different variants.
For example, Ubuntu:22.04 is equivalent to Ubuntu:22.04:LTS.
This function adds all matching ecosystems
to the datastore to facilitate API queries.
For example:
... |
For Linux distributions, some release versions may have different variants.
For example, Ubuntu:22.04 is equivalent to Ubuntu:22.04:LTS.
This function adds all matching ecosystems
to the datastore to facilitate API queries.
For example:
- "Ubuntu:Pro:18.04:LTS" would also be "Ubuntu:18.04"
Args:
or... | add_matching_ecosystems | python | google/osv.dev | osv/ecosystems/_ecosystems.py | https://github.com/google/osv.dev/blob/master/osv/ecosystems/_ecosystems.py | Apache-2.0 |
def is_valid_alpine_version(s: str):
"""
Return True is the string `s` is a valid Alpine version.
We do not support yet version strings that start with
non-significant zeros.
For example:
>>> is_valid_alpine_version("006")
False
>>> is_valid_alpine_version("1.2.3")
True
>>> is_valid_alpine_version("... |
Return True is the string `s` is a valid Alpine version.
We do not support yet version strings that start with
non-significant zeros.
For example:
>>> is_valid_alpine_version("006")
False
>>> is_valid_alpine_version("1.2.3")
True
>>> is_valid_alpine_version("02-r1")
True
| is_valid_alpine_version | python | google/osv.dev | osv/third_party/univers/alpine.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/alpine.py | Apache-2.0 |
def normalize(cls, string):
"""
Return a normalized version string from ``string ``. Subclass can override.
"""
# FIXME: Is removing spaces and strip v the right thing to do?
return remove_spaces(string).rstrip("v ").strip() |
Return a normalized version string from ``string ``. Subclass can override.
| normalize | python | google/osv.dev | osv/third_party/univers/alpine.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/alpine.py | Apache-2.0 |
def eval_constraint(version1, operator, version2):
"""
Evaluate a versions constraint where two Debian package versions are
compared with an operator such as < or >. Return True if the constraint is
satisfied and False otherwise.
"""
version1 = coerce_version(version1)
version2 = coerce_ver... |
Evaluate a versions constraint where two Debian package versions are
compared with an operator such as < or >. Return True if the constraint is
satisfied and False otherwise.
| eval_constraint | python | google/osv.dev | osv/third_party/univers/debian.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/debian.py | Apache-2.0 |
def compare_strings(version1, version2):
"""
Compare two version strings (upstream or revision) using Debian semantics
and return one of the following integer numbers:
- -1 means version1 sorts before version2
- 0 means version1 and version2 are equal
- 1 means version1 sorts after v... |
Compare two version strings (upstream or revision) using Debian semantics
and return one of the following integer numbers:
- -1 means version1 sorts before version2
- 0 means version1 and version2 are equal
- 1 means version1 sorts after version2
| compare_strings | python | google/osv.dev | osv/third_party/univers/debian.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/debian.py | Apache-2.0 |
def compare_versions(version1, version2):
"""
Compare two Version objects or strings and return one of the following
integer numbers:
- -1 means version1 sorts before version2
- 0 means version1 and version2 are equal
- 1 means version1 sorts after version2
"""
version1 = coerce_v... |
Compare two Version objects or strings and return one of the following
integer numbers:
- -1 means version1 sorts before version2
- 0 means version1 and version2 are equal
- 1 means version1 sorts after version2
| compare_versions | python | google/osv.dev | osv/third_party/univers/debian.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/debian.py | Apache-2.0 |
def coerce_version(value):
"""
Return a Version object from value.
:param value: The value to coerce (a string or :class:`Version` object).
:returns: A :class:`Version` object.
"""
if not isinstance(value, Version):
value = Version.from_string(value)
return value |
Return a Version object from value.
:param value: The value to coerce (a string or :class:`Version` object).
:returns: A :class:`Version` object.
| coerce_version | python | google/osv.dev | osv/third_party/univers/debian.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/debian.py | Apache-2.0 |
def compare_version_objects(version1, version2):
"""
Compare two Version objects and return one of the following
integer numbers:
- -1 means version1 sorts before version2
- 0 means version1 and version2 are equal
- 1 means version1 sorts after version2
"""
if version1.epoch < ver... |
Compare two Version objects and return one of the following
integer numbers:
- -1 means version1 sorts before version2
- 0 means version1 and version2 are equal
- 1 means version1 sorts after version2
| compare_version_objects | python | google/osv.dev | osv/third_party/univers/debian.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/debian.py | Apache-2.0 |
def get_digit_prefix(characters):
"""
Return the digit prefix from a list of characters.
"""
value = 0
while characters and characters[0].isdigit():
value = value * 10 + int(characters.pop(0))
return value |
Return the digit prefix from a list of characters.
| get_digit_prefix | python | google/osv.dev | osv/third_party/univers/debian.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/debian.py | Apache-2.0 |
def get_non_digit_prefix(characters):
"""
Return the non-digit prefix from a list of characters.
"""
prefix = []
while characters and not characters[0].isdigit():
prefix.append(characters.pop(0))
return prefix |
Return the non-digit prefix from a list of characters.
| get_non_digit_prefix | python | google/osv.dev | osv/third_party/univers/debian.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/debian.py | Apache-2.0 |
def __init__(self, version):
"""
Construct a Version from the ``version`` string. A version string is a
series of digits or ASCII letters separated by dots and may contain dash
"-".
"""
if isinstance(version, (int, GemVersion)):
version = str(version)
... |
Construct a Version from the ``version`` string. A version string is a
series of digits or ASCII letters separated by dots and may contain dash
"-".
| __init__ | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def bump(self):
"""
Return a new version object where the next to the last revision number
is one greater (e.g., 5.3.1 => 5.4) i.e., incrementing this GemVersion
last numeric segment.
For example::
>>> assert GemVersion("5.3.1").bump() == GemVersion("5.4"), repr(GemVersi... |
Return a new version object where the next to the last revision number
is one greater (e.g., 5.3.1 => 5.4) i.e., incrementing this GemVersion
last numeric segment.
For example::
>>> assert GemVersion("5.3.1").bump() == GemVersion("5.4"), repr(GemVersion("5.3.1").bump())
... | bump | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def release(self):
"""
Return a new GemVersion which is the release for this version (e.g.,
1.2.0.a -> 1.2.0). Non-prerelease versions return themselves. A release
is composed only of numeric segments.
"""
if not self._release:
if self.prerelease():
... |
Return a new GemVersion which is the release for this version (e.g.,
1.2.0.a -> 1.2.0). Non-prerelease versions return themselves. A release
is composed only of numeric segments.
| release | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def segments(self):
"""
Return a new sequence of segments for this version where segments are
ints or strings parsed from the original version string.
"""
if not self._segments:
self._segments = self.get_segments()
return list(self._segments) |
Return a new sequence of segments for this version where segments are
ints or strings parsed from the original version string.
| segments | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def get_segments(self):
"""
Return a sequence of segments for this version where segments are ints
or strings parsed from the original version string.
"""
find_segments = re.compile(r"[0-9]+|[a-z]+", re.IGNORECASE).findall
segments = []
for seg in find_segments(se... |
Return a sequence of segments for this version where segments are ints
or strings parsed from the original version string.
| get_segments | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def get_canonical_segments(self):
"""
Return a new sequence of "canonical segments" for this version using
the Rubygems way.
"""
canonical_segments = []
for segments in self.split_segments():
segs = list(dropwhile(lambda s: s == 0, reversed(segments)))
... |
Return a new sequence of "canonical segments" for this version using
the Rubygems way.
| get_canonical_segments | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def split_segments(self):
"""
Return a two-tuple of segments:
- the first is a list of numeric-only segments starting from the left
- the second is a list of alpha or numericsegments starting with the
first alpha segment from the left.
"""
numeric_segments = []... |
Return a two-tuple of segments:
- the first is a list of numeric-only segments starting from the left
- the second is a list of alpha or numericsegments starting with the
first alpha segment from the left.
| split_segments | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def __cmp__(self, other, trace=False):
"""
Compare this version with ``other`` returning -1, 0, or 1 if the
other version is larger, the same, or smaller than this
one. Attempts to compare to something that's not a
``GemVersion raises an exception.
The comparison results... |
Compare this version with ``other`` returning -1, 0, or 1 if the
other version is larger, the same, or smaller than this
one. Attempts to compare to something that's not a
``GemVersion raises an exception.
The comparison results have the same semantics as the legacy "cmp()"
... | __cmp__ | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.