Changeset View
Changeset View
Standalone View
Standalone View
swh/search/utils.py
# Copyright (C) 2021 The Software Heritage developers | # Copyright (C) 2021 The Software Heritage developers | ||||
# See the AUTHORS file at the top-level directory of this distribution | # See the AUTHORS file at the top-level directory of this distribution | ||||
# License: GNU General Public License version 3, or any later version | # License: GNU General Public License version 3, or any later version | ||||
# See top-level LICENSE file for more information | # See top-level LICENSE file for more information | ||||
import codecs | import codecs | ||||
from datetime import datetime | from datetime import datetime | ||||
from typing import Optional | |||||
import iso8601 # type: ignore | import iso8601 # type: ignore | ||||
def get_expansion(field, sep=None): | def get_expansion(field, sep=None): | ||||
METADATA_FIELDS = { | METADATA_FIELDS = { | ||||
"licenses": ["intrinsic_metadata", "http://schema.org/license", "@id"], | "licenses": ["intrinsic_metadata", "http://schema.org/license", "@id"], | ||||
"programming_languages": [ | "programming_languages": [ | ||||
Show All 25 Lines | def get_expansion(field, sep=None): | ||||
} | } | ||||
if sep: | if sep: | ||||
return sep.join(METADATA_FIELDS[field]) | return sep.join(METADATA_FIELDS[field]) | ||||
return METADATA_FIELDS[field] | return METADATA_FIELDS[field] | ||||
def is_date_parsable(date_str): | def parse_and_format_date(date_str: str) -> Optional[str]: | ||||
""" | """ | ||||
Return True if date_str is in the format | Parses a string date in the format %Y-%m-%d or ISO8601 and returns | ||||
%Y-%m-%d or the standard ISO format. | a new string date in the format YYYY-mm-dd if the parsing succeeded | ||||
Otherwise return False. | otherwise None. | ||||
""" | """ | ||||
try: | try: | ||||
datetime.strptime(date_str, "%Y-%m-%d") | return datetime.strptime(date_str, "%Y-%m-%d").strftime("%Y-%m-%d") | ||||
return True | |||||
except Exception: | except Exception: | ||||
try: | try: | ||||
iso8601.parse_date(date_str) | return iso8601.parse_date(date_str).strftime("%Y-%m-%d") | ||||
return True | |||||
except Exception: | except Exception: | ||||
return False | return None | ||||
def escape(obj): | def escape(obj): | ||||
r"""Makes the object directly injectable into the | r"""Makes the object directly injectable into the | ||||
query language by converting the escapable parts of | query language by converting the escapable parts of | ||||
the object into escape sequences. | the object into escape sequences. | ||||
For strings, appends \ before special characters like ', ", and \ | For strings, appends \ before special characters like ', ", and \ | ||||
▲ Show 20 Lines • Show All 41 Lines • Show Last 20 Lines |