partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
Library.contains_tracks
|
Check if one or more tracks is already saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
tracks : Union[Track, str]
A sequence of track objects or spotify IDs
|
spotify/models/library.py
|
async def contains_tracks(self, *tracks: Sequence[Union[str, Track]]) -> List[bool]:
"""Check if one or more tracks is already saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
tracks : Union[Track, str]
A sequence of track objects or spotify IDs
"""
_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]
return await self.user.http.is_saved_track(_tracks)
|
async def contains_tracks(self, *tracks: Sequence[Union[str, Track]]) -> List[bool]:
"""Check if one or more tracks is already saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
tracks : Union[Track, str]
A sequence of track objects or spotify IDs
"""
_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]
return await self.user.http.is_saved_track(_tracks)
|
[
"Check",
"if",
"one",
"or",
"more",
"tracks",
"is",
"already",
"saved",
"in",
"the",
"current",
"Spotify",
"user’s",
"‘Your",
"Music’",
"library",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/library.py#L40-L49
|
[
"async",
"def",
"contains_tracks",
"(",
"self",
",",
"*",
"tracks",
":",
"Sequence",
"[",
"Union",
"[",
"str",
",",
"Track",
"]",
"]",
")",
"->",
"List",
"[",
"bool",
"]",
":",
"_tracks",
"=",
"[",
"(",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
"else",
"obj",
".",
"id",
")",
"for",
"obj",
"in",
"tracks",
"]",
"return",
"await",
"self",
".",
"user",
".",
"http",
".",
"is_saved_track",
"(",
"_tracks",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Library.get_tracks
|
Get a list of the songs saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
limit : Optional[int]
The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
offset : Optional[int]
The index of the first item to return. Default: 0
|
spotify/models/library.py
|
async def get_tracks(self, *, limit=20, offset=0) -> List[Track]:
"""Get a list of the songs saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
limit : Optional[int]
The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
offset : Optional[int]
The index of the first item to return. Default: 0
"""
data = await self.user.http.saved_tracks(limit=limit, offset=offset)
return [Track(self.__client, item['track']) for item in data['items']]
|
async def get_tracks(self, *, limit=20, offset=0) -> List[Track]:
"""Get a list of the songs saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
limit : Optional[int]
The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
offset : Optional[int]
The index of the first item to return. Default: 0
"""
data = await self.user.http.saved_tracks(limit=limit, offset=offset)
return [Track(self.__client, item['track']) for item in data['items']]
|
[
"Get",
"a",
"list",
"of",
"the",
"songs",
"saved",
"in",
"the",
"current",
"Spotify",
"user’s",
"‘Your",
"Music’",
"library",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/library.py#L51-L63
|
[
"async",
"def",
"get_tracks",
"(",
"self",
",",
"*",
",",
"limit",
"=",
"20",
",",
"offset",
"=",
"0",
")",
"->",
"List",
"[",
"Track",
"]",
":",
"data",
"=",
"await",
"self",
".",
"user",
".",
"http",
".",
"saved_tracks",
"(",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")",
"return",
"[",
"Track",
"(",
"self",
".",
"__client",
",",
"item",
"[",
"'track'",
"]",
")",
"for",
"item",
"in",
"data",
"[",
"'items'",
"]",
"]"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Library.get_albums
|
Get a list of the albums saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
limit : Optional[int]
The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
offset : Optional[int]
The index of the first item to return. Default: 0
|
spotify/models/library.py
|
async def get_albums(self, *, limit=20, offset=0) -> List[Album]:
"""Get a list of the albums saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
limit : Optional[int]
The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
offset : Optional[int]
The index of the first item to return. Default: 0
"""
data = await self.user.http.saved_albums(limit=limit, offset=offset)
return [Album(self.__client, item['album']) for item in data['items']]
|
async def get_albums(self, *, limit=20, offset=0) -> List[Album]:
"""Get a list of the albums saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
limit : Optional[int]
The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
offset : Optional[int]
The index of the first item to return. Default: 0
"""
data = await self.user.http.saved_albums(limit=limit, offset=offset)
return [Album(self.__client, item['album']) for item in data['items']]
|
[
"Get",
"a",
"list",
"of",
"the",
"albums",
"saved",
"in",
"the",
"current",
"Spotify",
"user’s",
"‘Your",
"Music’",
"library",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/library.py#L65-L77
|
[
"async",
"def",
"get_albums",
"(",
"self",
",",
"*",
",",
"limit",
"=",
"20",
",",
"offset",
"=",
"0",
")",
"->",
"List",
"[",
"Album",
"]",
":",
"data",
"=",
"await",
"self",
".",
"user",
".",
"http",
".",
"saved_albums",
"(",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")",
"return",
"[",
"Album",
"(",
"self",
".",
"__client",
",",
"item",
"[",
"'album'",
"]",
")",
"for",
"item",
"in",
"data",
"[",
"'items'",
"]",
"]"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Library.remove_albums
|
Remove one or more albums from the current user’s ‘Your Music’ library.
Parameters
----------
albums : Sequence[Union[Album, str]]
A sequence of artist objects or spotify IDs
|
spotify/models/library.py
|
async def remove_albums(self, *albums):
"""Remove one or more albums from the current user’s ‘Your Music’ library.
Parameters
----------
albums : Sequence[Union[Album, str]]
A sequence of artist objects or spotify IDs
"""
_albums = [(obj if isinstance(obj, str) else obj.id) for obj in albums]
await self.user.http.delete_saved_albums(','.join(_albums))
|
async def remove_albums(self, *albums):
"""Remove one or more albums from the current user’s ‘Your Music’ library.
Parameters
----------
albums : Sequence[Union[Album, str]]
A sequence of artist objects or spotify IDs
"""
_albums = [(obj if isinstance(obj, str) else obj.id) for obj in albums]
await self.user.http.delete_saved_albums(','.join(_albums))
|
[
"Remove",
"one",
"or",
"more",
"albums",
"from",
"the",
"current",
"user’s",
"‘Your",
"Music’",
"library",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/library.py#L79-L88
|
[
"async",
"def",
"remove_albums",
"(",
"self",
",",
"*",
"albums",
")",
":",
"_albums",
"=",
"[",
"(",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
"else",
"obj",
".",
"id",
")",
"for",
"obj",
"in",
"albums",
"]",
"await",
"self",
".",
"user",
".",
"http",
".",
"delete_saved_albums",
"(",
"','",
".",
"join",
"(",
"_albums",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Library.remove_tracks
|
Remove one or more tracks from the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs
|
spotify/models/library.py
|
async def remove_tracks(self, *tracks):
"""Remove one or more tracks from the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs
"""
_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]
await self.user.http.delete_saved_tracks(','.join(_tracks))
|
async def remove_tracks(self, *tracks):
"""Remove one or more tracks from the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs
"""
_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]
await self.user.http.delete_saved_tracks(','.join(_tracks))
|
[
"Remove",
"one",
"or",
"more",
"tracks",
"from",
"the",
"current",
"user’s",
"‘Your",
"Music’",
"library",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/library.py#L90-L99
|
[
"async",
"def",
"remove_tracks",
"(",
"self",
",",
"*",
"tracks",
")",
":",
"_tracks",
"=",
"[",
"(",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
"else",
"obj",
".",
"id",
")",
"for",
"obj",
"in",
"tracks",
"]",
"await",
"self",
".",
"user",
".",
"http",
".",
"delete_saved_tracks",
"(",
"','",
".",
"join",
"(",
"_tracks",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Library.save_albums
|
Save one or more albums to the current user’s ‘Your Music’ library.
Parameters
----------
albums : Sequence[Union[Album, str]]
A sequence of artist objects or spotify IDs
|
spotify/models/library.py
|
async def save_albums(self, *albums):
"""Save one or more albums to the current user’s ‘Your Music’ library.
Parameters
----------
albums : Sequence[Union[Album, str]]
A sequence of artist objects or spotify IDs
"""
_albums = [(obj if isinstance(obj, str) else obj.id) for obj in albums]
await self.user.http.save_albums(','.join(_albums))
|
async def save_albums(self, *albums):
"""Save one or more albums to the current user’s ‘Your Music’ library.
Parameters
----------
albums : Sequence[Union[Album, str]]
A sequence of artist objects or spotify IDs
"""
_albums = [(obj if isinstance(obj, str) else obj.id) for obj in albums]
await self.user.http.save_albums(','.join(_albums))
|
[
"Save",
"one",
"or",
"more",
"albums",
"to",
"the",
"current",
"user’s",
"‘Your",
"Music’",
"library",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/library.py#L101-L110
|
[
"async",
"def",
"save_albums",
"(",
"self",
",",
"*",
"albums",
")",
":",
"_albums",
"=",
"[",
"(",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
"else",
"obj",
".",
"id",
")",
"for",
"obj",
"in",
"albums",
"]",
"await",
"self",
".",
"user",
".",
"http",
".",
"save_albums",
"(",
"','",
".",
"join",
"(",
"_albums",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Library.save_tracks
|
Save one or more tracks to the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs
|
spotify/models/library.py
|
async def save_tracks(self, *tracks):
"""Save one or more tracks to the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs
"""
_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]
await self.user.http.save_tracks(','.join(_tracks))
|
async def save_tracks(self, *tracks):
"""Save one or more tracks to the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs
"""
_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]
await self.user.http.save_tracks(','.join(_tracks))
|
[
"Save",
"one",
"or",
"more",
"tracks",
"to",
"the",
"current",
"user’s",
"‘Your",
"Music’",
"library",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/library.py#L112-L121
|
[
"async",
"def",
"save_tracks",
"(",
"self",
",",
"*",
"tracks",
")",
":",
"_tracks",
"=",
"[",
"(",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
"else",
"obj",
".",
"id",
")",
"for",
"obj",
"in",
"tracks",
"]",
"await",
"self",
".",
"user",
".",
"http",
".",
"save_tracks",
"(",
"','",
".",
"join",
"(",
"_tracks",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
to_id
|
Get a spotify ID from a URI or open.spotify URL.
Paramters
---------
string : str
The string to operate on.
Returns
-------
id : str
The Spotify ID from the string.
|
spotify/utils.py
|
def to_id(string: str) -> str:
"""Get a spotify ID from a URI or open.spotify URL.
Paramters
---------
string : str
The string to operate on.
Returns
-------
id : str
The Spotify ID from the string.
"""
string = string.strip()
match = _URI_RE.match(string)
if match is None:
match = _OPEN_RE.match(string)
if match is None:
return string
else:
return match.group(2)
else:
return match.group(1)
|
def to_id(string: str) -> str:
"""Get a spotify ID from a URI or open.spotify URL.
Paramters
---------
string : str
The string to operate on.
Returns
-------
id : str
The Spotify ID from the string.
"""
string = string.strip()
match = _URI_RE.match(string)
if match is None:
match = _OPEN_RE.match(string)
if match is None:
return string
else:
return match.group(2)
else:
return match.group(1)
|
[
"Get",
"a",
"spotify",
"ID",
"from",
"a",
"URI",
"or",
"open",
".",
"spotify",
"URL",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/utils.py#L21-L46
|
[
"def",
"to_id",
"(",
"string",
":",
"str",
")",
"->",
"str",
":",
"string",
"=",
"string",
".",
"strip",
"(",
")",
"match",
"=",
"_URI_RE",
".",
"match",
"(",
"string",
")",
"if",
"match",
"is",
"None",
":",
"match",
"=",
"_OPEN_RE",
".",
"match",
"(",
"string",
")",
"if",
"match",
"is",
"None",
":",
"return",
"string",
"else",
":",
"return",
"match",
".",
"group",
"(",
"2",
")",
"else",
":",
"return",
"match",
".",
"group",
"(",
"1",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
assert_hasattr
|
decorator to assert an object has an attribute when run.
|
spotify/utils.py
|
def assert_hasattr(attr: str, msg: str, tp: BaseException = SpotifyException) -> Callable:
"""decorator to assert an object has an attribute when run."""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def decorated(self, *args, **kwargs):
if not hasattr(self, attr):
raise tp(msg)
return func(self, *args, **kwargs)
if inspect.iscoroutinefunction(func):
@functools.wraps(func)
async def decorated(*args, **kwargs):
return await decorated(*args, **kwargs)
return decorated
return decorator
|
def assert_hasattr(attr: str, msg: str, tp: BaseException = SpotifyException) -> Callable:
"""decorator to assert an object has an attribute when run."""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def decorated(self, *args, **kwargs):
if not hasattr(self, attr):
raise tp(msg)
return func(self, *args, **kwargs)
if inspect.iscoroutinefunction(func):
@functools.wraps(func)
async def decorated(*args, **kwargs):
return await decorated(*args, **kwargs)
return decorated
return decorator
|
[
"decorator",
"to",
"assert",
"an",
"object",
"has",
"an",
"attribute",
"when",
"run",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/utils.py#L49-L64
|
[
"def",
"assert_hasattr",
"(",
"attr",
":",
"str",
",",
"msg",
":",
"str",
",",
"tp",
":",
"BaseException",
"=",
"SpotifyException",
")",
"->",
"Callable",
":",
"def",
"decorator",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"decorated",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"attr",
")",
":",
"raise",
"tp",
"(",
"msg",
")",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"inspect",
".",
"iscoroutinefunction",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"async",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"decorated",
"return",
"decorator"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
OAuth2.from_client
|
Construct a OAuth2 object from a `spotify.Client`.
|
spotify/utils.py
|
def from_client(cls, client, *args, **kwargs):
"""Construct a OAuth2 object from a `spotify.Client`."""
return cls(client.http.client_id, *args, **kwargs)
|
def from_client(cls, client, *args, **kwargs):
"""Construct a OAuth2 object from a `spotify.Client`."""
return cls(client.http.client_id, *args, **kwargs)
|
[
"Construct",
"a",
"OAuth2",
"object",
"from",
"a",
"spotify",
".",
"Client",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/utils.py#L106-L108
|
[
"def",
"from_client",
"(",
"cls",
",",
"client",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
"(",
"client",
".",
"http",
".",
"client_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
OAuth2.url_
|
Construct a OAuth2 URL instead of an OAuth2 object.
|
spotify/utils.py
|
def url_(client_id: str, redirect_uri: str, *, scope: str = None, state: str = None, secure: bool = True) -> str:
"""Construct a OAuth2 URL instead of an OAuth2 object."""
attrs = {
'client_id': client_id,
'redirect_uri': quote(redirect_uri)
}
if scope is not None:
attrs['scope'] = quote(scope)
if state is not None:
attrs['state'] = state
parameters = '&'.join('{0}={1}'.format(*item) for item in attrs.items())
return OAuth2._BASE.format(parameters=parameters)
|
def url_(client_id: str, redirect_uri: str, *, scope: str = None, state: str = None, secure: bool = True) -> str:
"""Construct a OAuth2 URL instead of an OAuth2 object."""
attrs = {
'client_id': client_id,
'redirect_uri': quote(redirect_uri)
}
if scope is not None:
attrs['scope'] = quote(scope)
if state is not None:
attrs['state'] = state
parameters = '&'.join('{0}={1}'.format(*item) for item in attrs.items())
return OAuth2._BASE.format(parameters=parameters)
|
[
"Construct",
"a",
"OAuth2",
"URL",
"instead",
"of",
"an",
"OAuth2",
"object",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/utils.py#L111-L126
|
[
"def",
"url_",
"(",
"client_id",
":",
"str",
",",
"redirect_uri",
":",
"str",
",",
"*",
",",
"scope",
":",
"str",
"=",
"None",
",",
"state",
":",
"str",
"=",
"None",
",",
"secure",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"attrs",
"=",
"{",
"'client_id'",
":",
"client_id",
",",
"'redirect_uri'",
":",
"quote",
"(",
"redirect_uri",
")",
"}",
"if",
"scope",
"is",
"not",
"None",
":",
"attrs",
"[",
"'scope'",
"]",
"=",
"quote",
"(",
"scope",
")",
"if",
"state",
"is",
"not",
"None",
":",
"attrs",
"[",
"'state'",
"]",
"=",
"state",
"parameters",
"=",
"'&'",
".",
"join",
"(",
"'{0}={1}'",
".",
"format",
"(",
"*",
"item",
")",
"for",
"item",
"in",
"attrs",
".",
"items",
"(",
")",
")",
"return",
"OAuth2",
".",
"_BASE",
".",
"format",
"(",
"parameters",
"=",
"parameters",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
OAuth2.attrs
|
Attributes used when constructing url parameters.
|
spotify/utils.py
|
def attrs(self):
"""Attributes used when constructing url parameters."""
data = {
'client_id': self.client_id,
'redirect_uri': quote(self.redirect_uri),
}
if self.scope is not None:
data['scope'] = quote(self.scope)
if self.state is not None:
data['state'] = self.state
return data
|
def attrs(self):
"""Attributes used when constructing url parameters."""
data = {
'client_id': self.client_id,
'redirect_uri': quote(self.redirect_uri),
}
if self.scope is not None:
data['scope'] = quote(self.scope)
if self.state is not None:
data['state'] = self.state
return data
|
[
"Attributes",
"used",
"when",
"constructing",
"url",
"parameters",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/utils.py#L134-L147
|
[
"def",
"attrs",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'redirect_uri'",
":",
"quote",
"(",
"self",
".",
"redirect_uri",
")",
",",
"}",
"if",
"self",
".",
"scope",
"is",
"not",
"None",
":",
"data",
"[",
"'scope'",
"]",
"=",
"quote",
"(",
"self",
".",
"scope",
")",
"if",
"self",
".",
"state",
"is",
"not",
"None",
":",
"data",
"[",
"'state'",
"]",
"=",
"self",
".",
"state",
"return",
"data"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
OAuth2.parameters
|
URL parameters used.
|
spotify/utils.py
|
def parameters(self) -> str:
"""URL parameters used."""
return '&'.join('{0}={1}'.format(*item) for item in self.attrs.items())
|
def parameters(self) -> str:
"""URL parameters used."""
return '&'.join('{0}={1}'.format(*item) for item in self.attrs.items())
|
[
"URL",
"parameters",
"used",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/utils.py#L150-L152
|
[
"def",
"parameters",
"(",
"self",
")",
"->",
"str",
":",
"return",
"'&'",
".",
"join",
"(",
"'{0}={1}'",
".",
"format",
"(",
"*",
"item",
")",
"for",
"item",
"in",
"self",
".",
"attrs",
".",
"items",
"(",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
PartialTracks.build
|
get the track object for each link in the partial tracks data
Returns
-------
tracks : List[Track]
The tracks
|
spotify/models/playlist.py
|
async def build(self):
"""get the track object for each link in the partial tracks data
Returns
-------
tracks : List[Track]
The tracks
"""
data = await self.__func()
return list(PlaylistTrack(self.__client, track) for track in data['items'])
|
async def build(self):
"""get the track object for each link in the partial tracks data
Returns
-------
tracks : List[Track]
The tracks
"""
data = await self.__func()
return list(PlaylistTrack(self.__client, track) for track in data['items'])
|
[
"get",
"the",
"track",
"object",
"for",
"each",
"link",
"in",
"the",
"partial",
"tracks",
"data"
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/playlist.py#L40-L49
|
[
"async",
"def",
"build",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"__func",
"(",
")",
"return",
"list",
"(",
"PlaylistTrack",
"(",
"self",
".",
"__client",
",",
"track",
")",
"for",
"track",
"in",
"data",
"[",
"'items'",
"]",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Playlist.get_all_tracks
|
Get all playlist tracks from the playlist.
Returns
-------
tracks : List[PlaylistTrack]
The playlists tracks.
|
spotify/models/playlist.py
|
async def get_all_tracks(self) -> List[PlaylistTrack]:
"""Get all playlist tracks from the playlist.
Returns
-------
tracks : List[PlaylistTrack]
The playlists tracks.
"""
if isinstance(self._tracks, PartialTracks):
return await self._tracks.build()
_tracks = []
offset = 0
while len(self.tracks) < self.total_tracks:
data = await self.__client.http.get_playlist_tracks(self.owner.id, self.id, limit=50, offset=offset)
_tracks += [PlaylistTrack(self.__client, item) for item in data['items']]
offset += 50
self.total_tracks = len(self._tracks)
return list(self._tracks)
|
async def get_all_tracks(self) -> List[PlaylistTrack]:
"""Get all playlist tracks from the playlist.
Returns
-------
tracks : List[PlaylistTrack]
The playlists tracks.
"""
if isinstance(self._tracks, PartialTracks):
return await self._tracks.build()
_tracks = []
offset = 0
while len(self.tracks) < self.total_tracks:
data = await self.__client.http.get_playlist_tracks(self.owner.id, self.id, limit=50, offset=offset)
_tracks += [PlaylistTrack(self.__client, item) for item in data['items']]
offset += 50
self.total_tracks = len(self._tracks)
return list(self._tracks)
|
[
"Get",
"all",
"playlist",
"tracks",
"from",
"the",
"playlist",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/playlist.py#L114-L134
|
[
"async",
"def",
"get_all_tracks",
"(",
"self",
")",
"->",
"List",
"[",
"PlaylistTrack",
"]",
":",
"if",
"isinstance",
"(",
"self",
".",
"_tracks",
",",
"PartialTracks",
")",
":",
"return",
"await",
"self",
".",
"_tracks",
".",
"build",
"(",
")",
"_tracks",
"=",
"[",
"]",
"offset",
"=",
"0",
"while",
"len",
"(",
"self",
".",
"tracks",
")",
"<",
"self",
".",
"total_tracks",
":",
"data",
"=",
"await",
"self",
".",
"__client",
".",
"http",
".",
"get_playlist_tracks",
"(",
"self",
".",
"owner",
".",
"id",
",",
"self",
".",
"id",
",",
"limit",
"=",
"50",
",",
"offset",
"=",
"offset",
")",
"_tracks",
"+=",
"[",
"PlaylistTrack",
"(",
"self",
".",
"__client",
",",
"item",
")",
"for",
"item",
"in",
"data",
"[",
"'items'",
"]",
"]",
"offset",
"+=",
"50",
"self",
".",
"total_tracks",
"=",
"len",
"(",
"self",
".",
"_tracks",
")",
"return",
"list",
"(",
"self",
".",
"_tracks",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.pause
|
Pause playback on the user’s account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
|
spotify/models/player.py
|
async def pause(self, *, device: Optional[SomeDevice] = None):
"""Pause playback on the user’s account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.pause_playback(device_id=str(device))
|
async def pause(self, *, device: Optional[SomeDevice] = None):
"""Pause playback on the user’s account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.pause_playback(device_id=str(device))
|
[
"Pause",
"playback",
"on",
"the",
"user’s",
"account",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L74-L83
|
[
"async",
"def",
"pause",
"(",
"self",
",",
"*",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"await",
"self",
".",
"_user",
".",
"http",
".",
"pause_playback",
"(",
"device_id",
"=",
"str",
"(",
"device",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.resume
|
Resume playback on the user's account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
|
spotify/models/player.py
|
async def resume(self, *, device: Optional[SomeDevice] = None):
"""Resume playback on the user's account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.play_playback(None, device_id=str(device))
|
async def resume(self, *, device: Optional[SomeDevice] = None):
"""Resume playback on the user's account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.play_playback(None, device_id=str(device))
|
[
"Resume",
"playback",
"on",
"the",
"user",
"s",
"account",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L85-L94
|
[
"async",
"def",
"resume",
"(",
"self",
",",
"*",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"await",
"self",
".",
"_user",
".",
"http",
".",
"play_playback",
"(",
"None",
",",
"device_id",
"=",
"str",
"(",
"device",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.seek
|
Seeks to the given position in the user’s currently playing track.
Parameters
----------
pos : int
The position in milliseconds to seek to.
Must be a positive number.
Passing in a position that is greater than the length of the track will cause the player to start playing the next song.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
|
spotify/models/player.py
|
async def seek(self, pos, *, device: Optional[SomeDevice] = None):
"""Seeks to the given position in the user’s currently playing track.
Parameters
----------
pos : int
The position in milliseconds to seek to.
Must be a positive number.
Passing in a position that is greater than the length of the track will cause the player to start playing the next song.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.seek_playback(pos, device_id=str(device))
|
async def seek(self, pos, *, device: Optional[SomeDevice] = None):
"""Seeks to the given position in the user’s currently playing track.
Parameters
----------
pos : int
The position in milliseconds to seek to.
Must be a positive number.
Passing in a position that is greater than the length of the track will cause the player to start playing the next song.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.seek_playback(pos, device_id=str(device))
|
[
"Seeks",
"to",
"the",
"given",
"position",
"in",
"the",
"user’s",
"currently",
"playing",
"track",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L96-L109
|
[
"async",
"def",
"seek",
"(",
"self",
",",
"pos",
",",
"*",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"await",
"self",
".",
"_user",
".",
"http",
".",
"seek_playback",
"(",
"pos",
",",
"device_id",
"=",
"str",
"(",
"device",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.set_repeat
|
Set the repeat mode for the user’s playback.
Parameters
----------
state : str
Options are repeat-track, repeat-context, and off
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
|
spotify/models/player.py
|
async def set_repeat(self, state, *, device: Optional[SomeDevice] = None):
"""Set the repeat mode for the user’s playback.
Parameters
----------
state : str
Options are repeat-track, repeat-context, and off
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.repeat_playback(state, device_id=str(device))
|
async def set_repeat(self, state, *, device: Optional[SomeDevice] = None):
"""Set the repeat mode for the user’s playback.
Parameters
----------
state : str
Options are repeat-track, repeat-context, and off
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.repeat_playback(state, device_id=str(device))
|
[
"Set",
"the",
"repeat",
"mode",
"for",
"the",
"user’s",
"playback",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L111-L122
|
[
"async",
"def",
"set_repeat",
"(",
"self",
",",
"state",
",",
"*",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"await",
"self",
".",
"_user",
".",
"http",
".",
"repeat_playback",
"(",
"state",
",",
"device_id",
"=",
"str",
"(",
"device",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.set_volume
|
Set the volume for the user’s current playback device.
Parameters
----------
volume : int
The volume to set. Must be a value from 0 to 100 inclusive.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
|
spotify/models/player.py
|
async def set_volume(self, volume: int, *, device: Optional[SomeDevice] = None):
"""Set the volume for the user’s current playback device.
Parameters
----------
volume : int
The volume to set. Must be a value from 0 to 100 inclusive.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.set_playback_volume(volume, device_id=str(device))
|
async def set_volume(self, volume: int, *, device: Optional[SomeDevice] = None):
"""Set the volume for the user’s current playback device.
Parameters
----------
volume : int
The volume to set. Must be a value from 0 to 100 inclusive.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.set_playback_volume(volume, device_id=str(device))
|
[
"Set",
"the",
"volume",
"for",
"the",
"user’s",
"current",
"playback",
"device",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L124-L135
|
[
"async",
"def",
"set_volume",
"(",
"self",
",",
"volume",
":",
"int",
",",
"*",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"await",
"self",
".",
"_user",
".",
"http",
".",
"set_playback_volume",
"(",
"volume",
",",
"device_id",
"=",
"str",
"(",
"device",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.next
|
Skips to next track in the user’s queue.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
|
spotify/models/player.py
|
async def next(self, *, device: Optional[SomeDevice] = None):
"""Skips to next track in the user’s queue.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.skip_next(device_id=str(device))
|
async def next(self, *, device: Optional[SomeDevice] = None):
"""Skips to next track in the user’s queue.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self._user.http.skip_next(device_id=str(device))
|
[
"Skips",
"to",
"next",
"track",
"in",
"the",
"user’s",
"queue",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L137-L146
|
[
"async",
"def",
"next",
"(",
"self",
",",
"*",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"await",
"self",
".",
"_user",
".",
"http",
".",
"skip_next",
"(",
"device_id",
"=",
"str",
"(",
"device",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.previous
|
Skips to previous track in the user’s queue.
Note that this will ALWAYS skip to the previous track, regardless of the current track’s progress.
Returning to the start of the current track should be performed using :meth:`seek`
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
|
spotify/models/player.py
|
async def previous(self, *, device: Optional[SomeDevice] = None):
"""Skips to previous track in the user’s queue.
Note that this will ALWAYS skip to the previous track, regardless of the current track’s progress.
Returning to the start of the current track should be performed using :meth:`seek`
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
return await self._user.http.skip_previous(device_id=str(device))
|
async def previous(self, *, device: Optional[SomeDevice] = None):
"""Skips to previous track in the user’s queue.
Note that this will ALWAYS skip to the previous track, regardless of the current track’s progress.
Returning to the start of the current track should be performed using :meth:`seek`
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
return await self._user.http.skip_previous(device_id=str(device))
|
[
"Skips",
"to",
"previous",
"track",
"in",
"the",
"user’s",
"queue",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L148-L160
|
[
"async",
"def",
"previous",
"(",
"self",
",",
"*",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"return",
"await",
"self",
".",
"_user",
".",
"http",
".",
"skip_previous",
"(",
"device_id",
"=",
"str",
"(",
"device",
")",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.play
|
Start a new context or resume current playback on the user’s active device.
The method treats a single argument as a Spotify context, such as a Artist, Album and playlist objects/URI.
When called with multiple positional arguments they are interpreted as a array of Spotify Track objects/URIs.
Parameters
----------
*uris : :obj:`SomeURIs`
When a single argument is passed in that argument is treated as a context.
Valid contexts are: albums, artists, playlists.
Album, Artist and Playlist objects are accepted too.
Otherwise when multiple arguments are passed in they,
A sequence of Spotify Tracks or Track URIs to play.
offset : Optional[:obj:`Offset`]
Indicates from where in the context playback should start.
Only available when `context` corresponds to an album or playlist object,
or when the `uris` parameter is used. when an integer offset is zero based and can’t be negative.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
|
spotify/models/player.py
|
async def play(self, *uris: SomeURIs, offset: Optional[Offset] = 0, device: Optional[SomeDevice] = None):
"""Start a new context or resume current playback on the user’s active device.
The method treats a single argument as a Spotify context, such as a Artist, Album and playlist objects/URI.
When called with multiple positional arguments they are interpreted as a array of Spotify Track objects/URIs.
Parameters
----------
*uris : :obj:`SomeURIs`
When a single argument is passed in that argument is treated as a context.
Valid contexts are: albums, artists, playlists.
Album, Artist and Playlist objects are accepted too.
Otherwise when multiple arguments are passed in they,
A sequence of Spotify Tracks or Track URIs to play.
offset : Optional[:obj:`Offset`]
Indicates from where in the context playback should start.
Only available when `context` corresponds to an album or playlist object,
or when the `uris` parameter is used. when an integer offset is zero based and can’t be negative.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
if len(uris) > 1:
# Regular uris paramter
context_uri = list(str(uri) for uri in uris)
else:
# Treat it as a context URI
context_uri = str(uris[0])
if device is not None:
if not isinstance(device, (Device, str)):
raise TypeError('Expected `device` to either be a spotify.Device or a string. got {type(0)!r}'.format(device))
else:
device = device.id
await self._user.http.play_playback(context_uri, offset=offset, device_id=device)
|
async def play(self, *uris: SomeURIs, offset: Optional[Offset] = 0, device: Optional[SomeDevice] = None):
"""Start a new context or resume current playback on the user’s active device.
The method treats a single argument as a Spotify context, such as a Artist, Album and playlist objects/URI.
When called with multiple positional arguments they are interpreted as a array of Spotify Track objects/URIs.
Parameters
----------
*uris : :obj:`SomeURIs`
When a single argument is passed in that argument is treated as a context.
Valid contexts are: albums, artists, playlists.
Album, Artist and Playlist objects are accepted too.
Otherwise when multiple arguments are passed in they,
A sequence of Spotify Tracks or Track URIs to play.
offset : Optional[:obj:`Offset`]
Indicates from where in the context playback should start.
Only available when `context` corresponds to an album or playlist object,
or when the `uris` parameter is used. when an integer offset is zero based and can’t be negative.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
if len(uris) > 1:
# Regular uris paramter
context_uri = list(str(uri) for uri in uris)
else:
# Treat it as a context URI
context_uri = str(uris[0])
if device is not None:
if not isinstance(device, (Device, str)):
raise TypeError('Expected `device` to either be a spotify.Device or a string. got {type(0)!r}'.format(device))
else:
device = device.id
await self._user.http.play_playback(context_uri, offset=offset, device_id=device)
|
[
"Start",
"a",
"new",
"context",
"or",
"resume",
"current",
"playback",
"on",
"the",
"user’s",
"active",
"device",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L162-L197
|
[
"async",
"def",
"play",
"(",
"self",
",",
"*",
"uris",
":",
"SomeURIs",
",",
"offset",
":",
"Optional",
"[",
"Offset",
"]",
"=",
"0",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"if",
"len",
"(",
"uris",
")",
">",
"1",
":",
"# Regular uris paramter",
"context_uri",
"=",
"list",
"(",
"str",
"(",
"uri",
")",
"for",
"uri",
"in",
"uris",
")",
"else",
":",
"# Treat it as a context URI",
"context_uri",
"=",
"str",
"(",
"uris",
"[",
"0",
"]",
")",
"if",
"device",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"device",
",",
"(",
"Device",
",",
"str",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Expected `device` to either be a spotify.Device or a string. got {type(0)!r}'",
".",
"format",
"(",
"device",
")",
")",
"else",
":",
"device",
"=",
"device",
".",
"id",
"await",
"self",
".",
"_user",
".",
"http",
".",
"play_playback",
"(",
"context_uri",
",",
"offset",
"=",
"offset",
",",
"device_id",
"=",
"device",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.shuffle
|
shuffle on or off for user’s playback.
Parameters
----------
state : Optional[bool]
if `True` then Shuffle user’s playback.
else if `False` do not shuffle user’s playback.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
|
spotify/models/player.py
|
async def shuffle(self, state: Optional[bool] = None, *, device: Optional[SomeDevice] = None):
"""shuffle on or off for user’s playback.
Parameters
----------
state : Optional[bool]
if `True` then Shuffle user’s playback.
else if `False` do not shuffle user’s playback.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self.__user.http.shuffle_playback(state)
|
async def shuffle(self, state: Optional[bool] = None, *, device: Optional[SomeDevice] = None):
"""shuffle on or off for user’s playback.
Parameters
----------
state : Optional[bool]
if `True` then Shuffle user’s playback.
else if `False` do not shuffle user’s playback.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target.
"""
await self.__user.http.shuffle_playback(state)
|
[
"shuffle",
"on",
"or",
"off",
"for",
"user’s",
"playback",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L199-L211
|
[
"async",
"def",
"shuffle",
"(",
"self",
",",
"state",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"*",
",",
"device",
":",
"Optional",
"[",
"SomeDevice",
"]",
"=",
"None",
")",
":",
"await",
"self",
".",
"__user",
".",
"http",
".",
"shuffle_playback",
"(",
"state",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
Player.transfer
|
Transfer playback to a new device and determine if it should start playing.
Parameters
----------
device : :obj:`SomeDevice`
The device on which playback should be started/transferred.
ensure_playback : bool
if `True` ensure playback happens on new device.
else keep the current playback state.
|
spotify/models/player.py
|
async def transfer(self, device: SomeDevice, ensure_playback: bool = False):
"""Transfer playback to a new device and determine if it should start playing.
Parameters
----------
device : :obj:`SomeDevice`
The device on which playback should be started/transferred.
ensure_playback : bool
if `True` ensure playback happens on new device.
else keep the current playback state.
"""
await self._user.http.transfer_player(str(device), play=ensure_playback)
|
async def transfer(self, device: SomeDevice, ensure_playback: bool = False):
"""Transfer playback to a new device and determine if it should start playing.
Parameters
----------
device : :obj:`SomeDevice`
The device on which playback should be started/transferred.
ensure_playback : bool
if `True` ensure playback happens on new device.
else keep the current playback state.
"""
await self._user.http.transfer_player(str(device), play=ensure_playback)
|
[
"Transfer",
"playback",
"to",
"a",
"new",
"device",
"and",
"determine",
"if",
"it",
"should",
"start",
"playing",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L213-L224
|
[
"async",
"def",
"transfer",
"(",
"self",
",",
"device",
":",
"SomeDevice",
",",
"ensure_playback",
":",
"bool",
"=",
"False",
")",
":",
"await",
"self",
".",
"_user",
".",
"http",
".",
"transfer_player",
"(",
"str",
"(",
"device",
")",
",",
"play",
"=",
"ensure_playback",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
SpotifyBase.from_href
|
Get the full object from spotify with a `href` attribute.
|
spotify/models/base.py
|
async def from_href(self):
"""Get the full object from spotify with a `href` attribute."""
if not hasattr(self, 'href'):
raise TypeError('Spotify object has no `href` attribute, therefore cannot be retrived')
elif hasattr(self, 'http'):
return await self.http.request(('GET', self.href))
else:
cls = type(self)
try:
client = getattr(self, '_{0}__client'.format(cls.__name__))
except AttributeError:
raise TypeError('Spotify object has no way to access a HTTPClient.')
else:
http = client.http
data = await http.request(('GET', self.href))
return cls(client, data)
|
async def from_href(self):
"""Get the full object from spotify with a `href` attribute."""
if not hasattr(self, 'href'):
raise TypeError('Spotify object has no `href` attribute, therefore cannot be retrived')
elif hasattr(self, 'http'):
return await self.http.request(('GET', self.href))
else:
cls = type(self)
try:
client = getattr(self, '_{0}__client'.format(cls.__name__))
except AttributeError:
raise TypeError('Spotify object has no way to access a HTTPClient.')
else:
http = client.http
data = await http.request(('GET', self.href))
return cls(client, data)
|
[
"Get",
"the",
"full",
"object",
"from",
"spotify",
"with",
"a",
"href",
"attribute",
"."
] |
mental32/spotify.py
|
python
|
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/base.py#L16-L36
|
[
"async",
"def",
"from_href",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'href'",
")",
":",
"raise",
"TypeError",
"(",
"'Spotify object has no `href` attribute, therefore cannot be retrived'",
")",
"elif",
"hasattr",
"(",
"self",
",",
"'http'",
")",
":",
"return",
"await",
"self",
".",
"http",
".",
"request",
"(",
"(",
"'GET'",
",",
"self",
".",
"href",
")",
")",
"else",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"try",
":",
"client",
"=",
"getattr",
"(",
"self",
",",
"'_{0}__client'",
".",
"format",
"(",
"cls",
".",
"__name__",
")",
")",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"'Spotify object has no way to access a HTTPClient.'",
")",
"else",
":",
"http",
"=",
"client",
".",
"http",
"data",
"=",
"await",
"http",
".",
"request",
"(",
"(",
"'GET'",
",",
"self",
".",
"href",
")",
")",
"return",
"cls",
"(",
"client",
",",
"data",
")"
] |
bb296cac7c3dd289908906b7069bd80f43950515
|
test
|
ExpirationDate.get
|
Execute the logic behind the meaning of ExpirationDate + return the matched status.
:return:
The status of the tested domain.
Can be one of the official status.
:rtype: str
|
PyFunceble/expiration_date.py
|
def get(self): # pragma: no cover
"""
Execute the logic behind the meaning of ExpirationDate + return the matched status.
:return:
The status of the tested domain.
Can be one of the official status.
:rtype: str
"""
# We get the status of the domain validation.
domain_validation = self.checker.is_domain_valid()
# We get the status of the IPv4 validation.
ip_validation = self.checker.is_ip_valid()
if "current_test_data" in PyFunceble.INTERN:
# The end-user want more information whith his test.
# We update some index.
PyFunceble.INTERN["current_test_data"].update(
{
"domain_syntax_validation": domain_validation,
"ip4_syntax_validation": ip_validation,
}
)
if (
domain_validation
and not ip_validation
or domain_validation
or PyFunceble.CONFIGURATION["local"]
):
# * The element is a valid domain.
# and
# * The element is not ahe valid IPv4.
# or
# * The element is a valid domain.
# * We get the HTTP status code of the currently tested element.
# and
# * We try to get the element status from the IANA database.
PyFunceble.INTERN.update(
{"http_code": HTTPCode().get(), "referer": Referer().get()}
)
if not PyFunceble.INTERN["referer"]:
# We could not get the referer.
# We parse the referer status into the upstream call.
return PyFunceble.INTERN["referer"]
# The WHOIS record status is not into our list of official status.
if PyFunceble.INTERN["referer"] and not self.checker.is_subdomain():
# * The iana database comparison status is not None.
# and
# * The domain we are testing is not a subdomain.
# We try to extract the expiration date from the WHOIS record.
# And we return the matched status.
return self._extract()
# The iana database comparison status is None.
# We log our whois record if the debug mode is activated.
Logs().whois(self.whois_record)
# And we return None, we could not extract the expiration date.
return None
if (
ip_validation
and not domain_validation
or ip_validation
or PyFunceble.CONFIGURATION["local"]
):
# * The element is a valid IPv4.
# and
# * The element is not a valid domain.
# or
# * The element is a valid IPv4.
# We get the HTTP status code.
PyFunceble.INTERN["http_code"] = HTTPCode().get()
# We log our whois record if the debug mode is activated.
Logs().whois(self.whois_record)
# And we return None, there is no expiration date to look for.
return None
# The validation was not passed.
# We log our whois record if the debug mode is activated.
Logs().whois(self.whois_record)
# And we return False, the domain could not pass the IP and domains syntax validation.
return False
|
def get(self): # pragma: no cover
"""
Execute the logic behind the meaning of ExpirationDate + return the matched status.
:return:
The status of the tested domain.
Can be one of the official status.
:rtype: str
"""
# We get the status of the domain validation.
domain_validation = self.checker.is_domain_valid()
# We get the status of the IPv4 validation.
ip_validation = self.checker.is_ip_valid()
if "current_test_data" in PyFunceble.INTERN:
# The end-user want more information whith his test.
# We update some index.
PyFunceble.INTERN["current_test_data"].update(
{
"domain_syntax_validation": domain_validation,
"ip4_syntax_validation": ip_validation,
}
)
if (
domain_validation
and not ip_validation
or domain_validation
or PyFunceble.CONFIGURATION["local"]
):
# * The element is a valid domain.
# and
# * The element is not ahe valid IPv4.
# or
# * The element is a valid domain.
# * We get the HTTP status code of the currently tested element.
# and
# * We try to get the element status from the IANA database.
PyFunceble.INTERN.update(
{"http_code": HTTPCode().get(), "referer": Referer().get()}
)
if not PyFunceble.INTERN["referer"]:
# We could not get the referer.
# We parse the referer status into the upstream call.
return PyFunceble.INTERN["referer"]
# The WHOIS record status is not into our list of official status.
if PyFunceble.INTERN["referer"] and not self.checker.is_subdomain():
# * The iana database comparison status is not None.
# and
# * The domain we are testing is not a subdomain.
# We try to extract the expiration date from the WHOIS record.
# And we return the matched status.
return self._extract()
# The iana database comparison status is None.
# We log our whois record if the debug mode is activated.
Logs().whois(self.whois_record)
# And we return None, we could not extract the expiration date.
return None
if (
ip_validation
and not domain_validation
or ip_validation
or PyFunceble.CONFIGURATION["local"]
):
# * The element is a valid IPv4.
# and
# * The element is not a valid domain.
# or
# * The element is a valid IPv4.
# We get the HTTP status code.
PyFunceble.INTERN["http_code"] = HTTPCode().get()
# We log our whois record if the debug mode is activated.
Logs().whois(self.whois_record)
# And we return None, there is no expiration date to look for.
return None
# The validation was not passed.
# We log our whois record if the debug mode is activated.
Logs().whois(self.whois_record)
# And we return False, the domain could not pass the IP and domains syntax validation.
return False
|
[
"Execute",
"the",
"logic",
"behind",
"the",
"meaning",
"of",
"ExpirationDate",
"+",
"return",
"the",
"matched",
"status",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/expiration_date.py#L94-L191
|
[
"def",
"get",
"(",
"self",
")",
":",
"# pragma: no cover",
"# We get the status of the domain validation.",
"domain_validation",
"=",
"self",
".",
"checker",
".",
"is_domain_valid",
"(",
")",
"# We get the status of the IPv4 validation.",
"ip_validation",
"=",
"self",
".",
"checker",
".",
"is_ip_valid",
"(",
")",
"if",
"\"current_test_data\"",
"in",
"PyFunceble",
".",
"INTERN",
":",
"# The end-user want more information whith his test.",
"# We update some index.",
"PyFunceble",
".",
"INTERN",
"[",
"\"current_test_data\"",
"]",
".",
"update",
"(",
"{",
"\"domain_syntax_validation\"",
":",
"domain_validation",
",",
"\"ip4_syntax_validation\"",
":",
"ip_validation",
",",
"}",
")",
"if",
"(",
"domain_validation",
"and",
"not",
"ip_validation",
"or",
"domain_validation",
"or",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"local\"",
"]",
")",
":",
"# * The element is a valid domain.",
"# and",
"# * The element is not ahe valid IPv4.",
"# or",
"# * The element is a valid domain.",
"# * We get the HTTP status code of the currently tested element.",
"# and",
"# * We try to get the element status from the IANA database.",
"PyFunceble",
".",
"INTERN",
".",
"update",
"(",
"{",
"\"http_code\"",
":",
"HTTPCode",
"(",
")",
".",
"get",
"(",
")",
",",
"\"referer\"",
":",
"Referer",
"(",
")",
".",
"get",
"(",
")",
"}",
")",
"if",
"not",
"PyFunceble",
".",
"INTERN",
"[",
"\"referer\"",
"]",
":",
"# We could not get the referer.",
"# We parse the referer status into the upstream call.",
"return",
"PyFunceble",
".",
"INTERN",
"[",
"\"referer\"",
"]",
"# The WHOIS record status is not into our list of official status.",
"if",
"PyFunceble",
".",
"INTERN",
"[",
"\"referer\"",
"]",
"and",
"not",
"self",
".",
"checker",
".",
"is_subdomain",
"(",
")",
":",
"# * The iana database comparison status is not None.",
"# and",
"# * The domain we are testing is not a subdomain.",
"# We try to extract the expiration date from the WHOIS record.",
"# And we return the matched status.",
"return",
"self",
".",
"_extract",
"(",
")",
"# The iana database comparison status is None.",
"# We log our whois record if the debug mode is activated.",
"Logs",
"(",
")",
".",
"whois",
"(",
"self",
".",
"whois_record",
")",
"# And we return None, we could not extract the expiration date.",
"return",
"None",
"if",
"(",
"ip_validation",
"and",
"not",
"domain_validation",
"or",
"ip_validation",
"or",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"local\"",
"]",
")",
":",
"# * The element is a valid IPv4.",
"# and",
"# * The element is not a valid domain.",
"# or",
"# * The element is a valid IPv4.",
"# We get the HTTP status code.",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
"=",
"HTTPCode",
"(",
")",
".",
"get",
"(",
")",
"# We log our whois record if the debug mode is activated.",
"Logs",
"(",
")",
".",
"whois",
"(",
"self",
".",
"whois_record",
")",
"# And we return None, there is no expiration date to look for.",
"return",
"None",
"# The validation was not passed.",
"# We log our whois record if the debug mode is activated.",
"Logs",
"(",
")",
".",
"whois",
"(",
"self",
".",
"whois_record",
")",
"# And we return False, the domain could not pass the IP and domains syntax validation.",
"return",
"False"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
ExpirationDate._convert_or_shorten_month
|
Convert a given month into our unified format.
:param data: The month to convert or shorten.
:type data: str
:return: The unified month name.
:rtype: str
|
PyFunceble/expiration_date.py
|
def _convert_or_shorten_month(cls, data):
"""
Convert a given month into our unified format.
:param data: The month to convert or shorten.
:type data: str
:return: The unified month name.
:rtype: str
"""
# We map the different month and their possible representation.
short_month = {
"jan": [str(1), "01", "Jan", "January"],
"feb": [str(2), "02", "Feb", "February"],
"mar": [str(3), "03", "Mar", "March"],
"apr": [str(4), "04", "Apr", "April"],
"may": [str(5), "05", "May"],
"jun": [str(6), "06", "Jun", "June"],
"jul": [str(7), "07", "Jul", "July"],
"aug": [str(8), "08", "Aug", "August"],
"sep": [str(9), "09", "Sep", "September"],
"oct": [str(10), "Oct", "October"],
"nov": [str(11), "Nov", "November"],
"dec": [str(12), "Dec", "December"],
}
for month in short_month:
# We loop through our map.
if data in short_month[month]:
# If the parsed data (or month if you prefer) is into our map.
# We return the element (or key if you prefer) assigned to
# the month.
return month
# The element is not into our map.
# We return the parsed element (or month if you prefer).
return data
|
def _convert_or_shorten_month(cls, data):
"""
Convert a given month into our unified format.
:param data: The month to convert or shorten.
:type data: str
:return: The unified month name.
:rtype: str
"""
# We map the different month and their possible representation.
short_month = {
"jan": [str(1), "01", "Jan", "January"],
"feb": [str(2), "02", "Feb", "February"],
"mar": [str(3), "03", "Mar", "March"],
"apr": [str(4), "04", "Apr", "April"],
"may": [str(5), "05", "May"],
"jun": [str(6), "06", "Jun", "June"],
"jul": [str(7), "07", "Jul", "July"],
"aug": [str(8), "08", "Aug", "August"],
"sep": [str(9), "09", "Sep", "September"],
"oct": [str(10), "Oct", "October"],
"nov": [str(11), "Nov", "November"],
"dec": [str(12), "Dec", "December"],
}
for month in short_month:
# We loop through our map.
if data in short_month[month]:
# If the parsed data (or month if you prefer) is into our map.
# We return the element (or key if you prefer) assigned to
# the month.
return month
# The element is not into our map.
# We return the parsed element (or month if you prefer).
return data
|
[
"Convert",
"a",
"given",
"month",
"into",
"our",
"unified",
"format",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/expiration_date.py#L208-L248
|
[
"def",
"_convert_or_shorten_month",
"(",
"cls",
",",
"data",
")",
":",
"# We map the different month and their possible representation.",
"short_month",
"=",
"{",
"\"jan\"",
":",
"[",
"str",
"(",
"1",
")",
",",
"\"01\"",
",",
"\"Jan\"",
",",
"\"January\"",
"]",
",",
"\"feb\"",
":",
"[",
"str",
"(",
"2",
")",
",",
"\"02\"",
",",
"\"Feb\"",
",",
"\"February\"",
"]",
",",
"\"mar\"",
":",
"[",
"str",
"(",
"3",
")",
",",
"\"03\"",
",",
"\"Mar\"",
",",
"\"March\"",
"]",
",",
"\"apr\"",
":",
"[",
"str",
"(",
"4",
")",
",",
"\"04\"",
",",
"\"Apr\"",
",",
"\"April\"",
"]",
",",
"\"may\"",
":",
"[",
"str",
"(",
"5",
")",
",",
"\"05\"",
",",
"\"May\"",
"]",
",",
"\"jun\"",
":",
"[",
"str",
"(",
"6",
")",
",",
"\"06\"",
",",
"\"Jun\"",
",",
"\"June\"",
"]",
",",
"\"jul\"",
":",
"[",
"str",
"(",
"7",
")",
",",
"\"07\"",
",",
"\"Jul\"",
",",
"\"July\"",
"]",
",",
"\"aug\"",
":",
"[",
"str",
"(",
"8",
")",
",",
"\"08\"",
",",
"\"Aug\"",
",",
"\"August\"",
"]",
",",
"\"sep\"",
":",
"[",
"str",
"(",
"9",
")",
",",
"\"09\"",
",",
"\"Sep\"",
",",
"\"September\"",
"]",
",",
"\"oct\"",
":",
"[",
"str",
"(",
"10",
")",
",",
"\"Oct\"",
",",
"\"October\"",
"]",
",",
"\"nov\"",
":",
"[",
"str",
"(",
"11",
")",
",",
"\"Nov\"",
",",
"\"November\"",
"]",
",",
"\"dec\"",
":",
"[",
"str",
"(",
"12",
")",
",",
"\"Dec\"",
",",
"\"December\"",
"]",
",",
"}",
"for",
"month",
"in",
"short_month",
":",
"# We loop through our map.",
"if",
"data",
"in",
"short_month",
"[",
"month",
"]",
":",
"# If the parsed data (or month if you prefer) is into our map.",
"# We return the element (or key if you prefer) assigned to",
"# the month.",
"return",
"month",
"# The element is not into our map.",
"# We return the parsed element (or month if you prefer).",
"return",
"data"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
ExpirationDate._cases_management
|
A little internal helper of self.format. (Avoiding of nested loops)
.. note::
Please note that the second value of the case represent the groups
in order :code:`[day,month,year]`.
This means that a :code:`[2,1,0]` will be for example for a date
in format :code:`2017-01-02` where
:code:`01` is the month.
:param regex_number: The identifiant of the regex.
:type regex_number: int
:param matched_result: The matched result to format.
:type matched_result: list
:return:
A list representing the expiration date.
The list can be "decoded" like :code:`[day, month, year]`
:rtype: list|None
|
PyFunceble/expiration_date.py
|
def _cases_management(self, regex_number, matched_result):
"""
A little internal helper of self.format. (Avoiding of nested loops)
.. note::
Please note that the second value of the case represent the groups
in order :code:`[day,month,year]`.
This means that a :code:`[2,1,0]` will be for example for a date
in format :code:`2017-01-02` where
:code:`01` is the month.
:param regex_number: The identifiant of the regex.
:type regex_number: int
:param matched_result: The matched result to format.
:type matched_result: list
:return:
A list representing the expiration date.
The list can be "decoded" like :code:`[day, month, year]`
:rtype: list|None
"""
# We map our regex numbers with with the right group order.
# Note: please report to the method note for more information about the mapping.
cases = {
"first": [[1, 2, 3, 10, 11, 22, 26, 27, 28, 29, 32, 34, 38], [0, 1, 2]],
"second": [[14, 15, 31, 33, 36, 37], [1, 0, 2]],
"third": [
[4, 5, 6, 7, 8, 9, 12, 13, 16, 17, 18, 19, 20, 21, 23, 24, 25, 30, 35],
[2, 1, 0],
],
}
for case in cases:
# We loop through the cases.
# We get the case data.
case_data = cases[case]
if int(regex_number) in case_data[0]:
# The regex number is into the currently read case data.
# We return a list with the formatted elements.
# 1. We convert the day to 2 digits.
# 2. We convert the month to the unified format.
# 3. We return the year.
return [
self._convert_1_to_2_digits(matched_result[case_data[1][0]]),
self._convert_or_shorten_month(matched_result[case_data[1][1]]),
str(matched_result[case_data[1][2]]),
]
# The regex number is not already mapped.
# We return the parsed data.
return matched_result
|
def _cases_management(self, regex_number, matched_result):
"""
A little internal helper of self.format. (Avoiding of nested loops)
.. note::
Please note that the second value of the case represent the groups
in order :code:`[day,month,year]`.
This means that a :code:`[2,1,0]` will be for example for a date
in format :code:`2017-01-02` where
:code:`01` is the month.
:param regex_number: The identifiant of the regex.
:type regex_number: int
:param matched_result: The matched result to format.
:type matched_result: list
:return:
A list representing the expiration date.
The list can be "decoded" like :code:`[day, month, year]`
:rtype: list|None
"""
# We map our regex numbers with with the right group order.
# Note: please report to the method note for more information about the mapping.
cases = {
"first": [[1, 2, 3, 10, 11, 22, 26, 27, 28, 29, 32, 34, 38], [0, 1, 2]],
"second": [[14, 15, 31, 33, 36, 37], [1, 0, 2]],
"third": [
[4, 5, 6, 7, 8, 9, 12, 13, 16, 17, 18, 19, 20, 21, 23, 24, 25, 30, 35],
[2, 1, 0],
],
}
for case in cases:
# We loop through the cases.
# We get the case data.
case_data = cases[case]
if int(regex_number) in case_data[0]:
# The regex number is into the currently read case data.
# We return a list with the formatted elements.
# 1. We convert the day to 2 digits.
# 2. We convert the month to the unified format.
# 3. We return the year.
return [
self._convert_1_to_2_digits(matched_result[case_data[1][0]]),
self._convert_or_shorten_month(matched_result[case_data[1][1]]),
str(matched_result[case_data[1][2]]),
]
# The regex number is not already mapped.
# We return the parsed data.
return matched_result
|
[
"A",
"little",
"internal",
"helper",
"of",
"self",
".",
"format",
".",
"(",
"Avoiding",
"of",
"nested",
"loops",
")"
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/expiration_date.py#L250-L307
|
[
"def",
"_cases_management",
"(",
"self",
",",
"regex_number",
",",
"matched_result",
")",
":",
"# We map our regex numbers with with the right group order.",
"# Note: please report to the method note for more information about the mapping.",
"cases",
"=",
"{",
"\"first\"",
":",
"[",
"[",
"1",
",",
"2",
",",
"3",
",",
"10",
",",
"11",
",",
"22",
",",
"26",
",",
"27",
",",
"28",
",",
"29",
",",
"32",
",",
"34",
",",
"38",
"]",
",",
"[",
"0",
",",
"1",
",",
"2",
"]",
"]",
",",
"\"second\"",
":",
"[",
"[",
"14",
",",
"15",
",",
"31",
",",
"33",
",",
"36",
",",
"37",
"]",
",",
"[",
"1",
",",
"0",
",",
"2",
"]",
"]",
",",
"\"third\"",
":",
"[",
"[",
"4",
",",
"5",
",",
"6",
",",
"7",
",",
"8",
",",
"9",
",",
"12",
",",
"13",
",",
"16",
",",
"17",
",",
"18",
",",
"19",
",",
"20",
",",
"21",
",",
"23",
",",
"24",
",",
"25",
",",
"30",
",",
"35",
"]",
",",
"[",
"2",
",",
"1",
",",
"0",
"]",
",",
"]",
",",
"}",
"for",
"case",
"in",
"cases",
":",
"# We loop through the cases.",
"# We get the case data.",
"case_data",
"=",
"cases",
"[",
"case",
"]",
"if",
"int",
"(",
"regex_number",
")",
"in",
"case_data",
"[",
"0",
"]",
":",
"# The regex number is into the currently read case data.",
"# We return a list with the formatted elements.",
"# 1. We convert the day to 2 digits.",
"# 2. We convert the month to the unified format.",
"# 3. We return the year.",
"return",
"[",
"self",
".",
"_convert_1_to_2_digits",
"(",
"matched_result",
"[",
"case_data",
"[",
"1",
"]",
"[",
"0",
"]",
"]",
")",
",",
"self",
".",
"_convert_or_shorten_month",
"(",
"matched_result",
"[",
"case_data",
"[",
"1",
"]",
"[",
"1",
"]",
"]",
")",
",",
"str",
"(",
"matched_result",
"[",
"case_data",
"[",
"1",
"]",
"[",
"2",
"]",
"]",
")",
",",
"]",
"# The regex number is not already mapped.",
"# We return the parsed data.",
"return",
"matched_result"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
ExpirationDate._format
|
Format the expiration date into an unified format (01-jan-1970).
:param date_to_convert:
The date to convert. In other words, the extracted date.
:type date_to_convert: str
:return: The formatted expiration date.
:rtype: str
|
PyFunceble/expiration_date.py
|
def _format(self, date_to_convert=None):
"""
Format the expiration date into an unified format (01-jan-1970).
:param date_to_convert:
The date to convert. In other words, the extracted date.
:type date_to_convert: str
:return: The formatted expiration date.
:rtype: str
"""
if not date_to_convert: # pragma: no cover
# The date to conver is given.
# We initiate the date we are working with.
date_to_convert = self.expiration_date
# We map the different possible regex.
# The regex index represent a unique number which have to be reported
# to the self._case_management() method.
regex_dates = {
# Date in format: 02-jan-2017
"1": r"([0-9]{2})-([a-z]{3})-([0-9]{4})",
# Date in format: 02.01.2017 // Month: jan
"2": r"([0-9]{2})\.([0-9]{2})\.([0-9]{4})$",
# Date in format: 02/01/2017 // Month: jan
"3": r"([0-3][0-9])\/(0[1-9]|1[012])\/([0-9]{4})",
# Date in format: 2017-01-02 // Month: jan
"4": r"([0-9]{4})-([0-9]{2})-([0-9]{2})$",
# Date in format: 2017.01.02 // Month: jan
"5": r"([0-9]{4})\.([0-9]{2})\.([0-9]{2})$",
# Date in format: 2017/01/02 // Month: jan
"6": r"([0-9]{4})\/([0-9]{2})\/([0-9]{2})$",
# Date in format: 2017.01.02 15:00:00
"7": r"([0-9]{4})\.([0-9]{2})\.([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 20170102 15:00:00 // Month: jan
"8": r"([0-9]{4})([0-9]{2})([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 2017-01-02 15:00:00 // Month: jan
"9": r"([0-9]{4})-([0-9]{2})-([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 02.01.2017 15:00:00 // Month: jan
"10": r"([0-9]{2})\.([0-9]{2})\.([0-9]{4})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 02-Jan-2017 15:00:00 UTC
"11": r"([0-9]{2})-([A-Z]{1}[a-z]{2})-([0-9]{4})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{1}.*", # pylint: disable=line-too-long
# Date in format: 2017/01/02 01:00:00 (+0900) // Month: jan
"12": r"([0-9]{4})\/([0-9]{2})\/([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s\(.*\)",
# Date in format: 2017/01/02 01:00:00 // Month: jan
"13": r"([0-9]{4})\/([0-9]{2})\/([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}$",
# Date in format: Mon Jan 02 15:00:00 GMT 2017
"14": r"[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{3}\s([0-9]{4})", # pylint: disable=line-too-long
# Date in format: Mon Jan 02 2017
"15": r"[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{2})\s([0-9]{4})",
# Date in format: 2017-01-02T15:00:00 // Month: jan
"16": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}$",
# Date in format: 2017-01-02T15:00:00Z // Month: jan${'7}
"17": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[A-Z].*",
# Date in format: 2017-01-02T15:00:00+0200 // Month: jan
"18": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{4}",
# Date in format: 2017-01-02T15:00:00+0200.622265+03:00 //
# Month: jan
"19": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9].*[+-][0-9]{2}:[0-9]{2}", # pylint: disable=line-too-long
# Date in format: 2017-01-02T15:00:00+0200.622265 // Month: jan
"20": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}$",
# Date in format: 2017-01-02T23:59:59.0Z // Month: jan
"21": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9].*[A-Z]",
# Date in format: 02-01-2017 // Month: jan
"22": r"([0-9]{2})-([0-9]{2})-([0-9]{4})",
# Date in format: 2017. 01. 02. // Month: jan
"23": r"([0-9]{4})\.\s([0-9]{2})\.\s([0-9]{2})\.",
# Date in format: 2017-01-02T00:00:00+13:00 // Month: jan
"24": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{2}:[0-9]{2}", # pylint: disable=line-too-long
# Date in format: 20170102 // Month: jan
"25": r"(?=[0-9]{8})(?=([0-9]{4})([0-9]{2})([0-9]{2}))",
# Date in format: 02-Jan-2017
"26": r"([0-9]{2})-([A-Z]{1}[a-z]{2})-([0-9]{4})$",
# Date in format: 02.1.2017 // Month: jan
"27": r"([0-9]{2})\.([0-9]{1})\.([0-9]{4})",
# Date in format: 02 Jan 2017
"28": r"([0-9]{1,2})\s([A-Z]{1}[a-z]{2})\s([0-9]{4})",
# Date in format: 02-January-2017
"29": r"([0-9]{2})-([A-Z]{1}[a-z]*)-([0-9]{4})",
# Date in format: 2017-Jan-02.
"30": r"([0-9]{4})-([A-Z]{1}[a-z]{2})-([0-9]{2})\.",
# Date in format: Mon Jan 02 15:00:00 2017
"31": r"[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{1,2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s([0-9]{4})", # pylint: disable=line-too-long
# Date in format: Mon Jan 2017 15:00:00
"32": r"()[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{4})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: January 02 2017-Jan-02
"33": r"([A-Z]{1}[a-z]*)\s([0-9]{1,2})\s([0-9]{4})",
# Date in format: 2.1.2017 // Month: jan
"34": r"([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{4})",
# Date in format: 20170102000000 // Month: jan
"35": r"([0-9]{4})([0-9]{2})([0-9]{2})[0-9]+",
# Date in format: 01/02/2017 // Month: jan
"36": r"(0[1-9]|1[012])\/([0-3][0-9])\/([0-9]{4})",
# Date in format: January 2 2017
"37": r"([A-Z]{1}[a-z].*)\s\s([0-9]{1,2})\s([0-9]{4})",
# Date in format: 2nd January 2017
"38": r"([0-9]{1,})[a-z]{1,}\s([A-Z].*)\s(2[0-9]{3})",
}
for regx in regex_dates:
# We loop through our map.
# We try to get the matched groups if the date to convert match the currently
# read regex.
matched_result = Regex(
date_to_convert, regex_dates[regx], return_data=True, rematch=True
).match()
if matched_result:
# The matched result is not None or an empty list.
# We get the date.
date = self._cases_management(regx, matched_result)
if date:
# The date is given.
# We return the formatted date.
return "-".join(date)
# We return an empty string as we were not eable to match the date format.
return ""
|
def _format(self, date_to_convert=None):
"""
Format the expiration date into an unified format (01-jan-1970).
:param date_to_convert:
The date to convert. In other words, the extracted date.
:type date_to_convert: str
:return: The formatted expiration date.
:rtype: str
"""
if not date_to_convert: # pragma: no cover
# The date to conver is given.
# We initiate the date we are working with.
date_to_convert = self.expiration_date
# We map the different possible regex.
# The regex index represent a unique number which have to be reported
# to the self._case_management() method.
regex_dates = {
# Date in format: 02-jan-2017
"1": r"([0-9]{2})-([a-z]{3})-([0-9]{4})",
# Date in format: 02.01.2017 // Month: jan
"2": r"([0-9]{2})\.([0-9]{2})\.([0-9]{4})$",
# Date in format: 02/01/2017 // Month: jan
"3": r"([0-3][0-9])\/(0[1-9]|1[012])\/([0-9]{4})",
# Date in format: 2017-01-02 // Month: jan
"4": r"([0-9]{4})-([0-9]{2})-([0-9]{2})$",
# Date in format: 2017.01.02 // Month: jan
"5": r"([0-9]{4})\.([0-9]{2})\.([0-9]{2})$",
# Date in format: 2017/01/02 // Month: jan
"6": r"([0-9]{4})\/([0-9]{2})\/([0-9]{2})$",
# Date in format: 2017.01.02 15:00:00
"7": r"([0-9]{4})\.([0-9]{2})\.([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 20170102 15:00:00 // Month: jan
"8": r"([0-9]{4})([0-9]{2})([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 2017-01-02 15:00:00 // Month: jan
"9": r"([0-9]{4})-([0-9]{2})-([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 02.01.2017 15:00:00 // Month: jan
"10": r"([0-9]{2})\.([0-9]{2})\.([0-9]{4})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 02-Jan-2017 15:00:00 UTC
"11": r"([0-9]{2})-([A-Z]{1}[a-z]{2})-([0-9]{4})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{1}.*", # pylint: disable=line-too-long
# Date in format: 2017/01/02 01:00:00 (+0900) // Month: jan
"12": r"([0-9]{4})\/([0-9]{2})\/([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s\(.*\)",
# Date in format: 2017/01/02 01:00:00 // Month: jan
"13": r"([0-9]{4})\/([0-9]{2})\/([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}$",
# Date in format: Mon Jan 02 15:00:00 GMT 2017
"14": r"[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{3}\s([0-9]{4})", # pylint: disable=line-too-long
# Date in format: Mon Jan 02 2017
"15": r"[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{2})\s([0-9]{4})",
# Date in format: 2017-01-02T15:00:00 // Month: jan
"16": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}$",
# Date in format: 2017-01-02T15:00:00Z // Month: jan${'7}
"17": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[A-Z].*",
# Date in format: 2017-01-02T15:00:00+0200 // Month: jan
"18": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{4}",
# Date in format: 2017-01-02T15:00:00+0200.622265+03:00 //
# Month: jan
"19": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9].*[+-][0-9]{2}:[0-9]{2}", # pylint: disable=line-too-long
# Date in format: 2017-01-02T15:00:00+0200.622265 // Month: jan
"20": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}$",
# Date in format: 2017-01-02T23:59:59.0Z // Month: jan
"21": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9].*[A-Z]",
# Date in format: 02-01-2017 // Month: jan
"22": r"([0-9]{2})-([0-9]{2})-([0-9]{4})",
# Date in format: 2017. 01. 02. // Month: jan
"23": r"([0-9]{4})\.\s([0-9]{2})\.\s([0-9]{2})\.",
# Date in format: 2017-01-02T00:00:00+13:00 // Month: jan
"24": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{2}:[0-9]{2}", # pylint: disable=line-too-long
# Date in format: 20170102 // Month: jan
"25": r"(?=[0-9]{8})(?=([0-9]{4})([0-9]{2})([0-9]{2}))",
# Date in format: 02-Jan-2017
"26": r"([0-9]{2})-([A-Z]{1}[a-z]{2})-([0-9]{4})$",
# Date in format: 02.1.2017 // Month: jan
"27": r"([0-9]{2})\.([0-9]{1})\.([0-9]{4})",
# Date in format: 02 Jan 2017
"28": r"([0-9]{1,2})\s([A-Z]{1}[a-z]{2})\s([0-9]{4})",
# Date in format: 02-January-2017
"29": r"([0-9]{2})-([A-Z]{1}[a-z]*)-([0-9]{4})",
# Date in format: 2017-Jan-02.
"30": r"([0-9]{4})-([A-Z]{1}[a-z]{2})-([0-9]{2})\.",
# Date in format: Mon Jan 02 15:00:00 2017
"31": r"[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{1,2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s([0-9]{4})", # pylint: disable=line-too-long
# Date in format: Mon Jan 2017 15:00:00
"32": r"()[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{4})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: January 02 2017-Jan-02
"33": r"([A-Z]{1}[a-z]*)\s([0-9]{1,2})\s([0-9]{4})",
# Date in format: 2.1.2017 // Month: jan
"34": r"([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{4})",
# Date in format: 20170102000000 // Month: jan
"35": r"([0-9]{4})([0-9]{2})([0-9]{2})[0-9]+",
# Date in format: 01/02/2017 // Month: jan
"36": r"(0[1-9]|1[012])\/([0-3][0-9])\/([0-9]{4})",
# Date in format: January 2 2017
"37": r"([A-Z]{1}[a-z].*)\s\s([0-9]{1,2})\s([0-9]{4})",
# Date in format: 2nd January 2017
"38": r"([0-9]{1,})[a-z]{1,}\s([A-Z].*)\s(2[0-9]{3})",
}
for regx in regex_dates:
# We loop through our map.
# We try to get the matched groups if the date to convert match the currently
# read regex.
matched_result = Regex(
date_to_convert, regex_dates[regx], return_data=True, rematch=True
).match()
if matched_result:
# The matched result is not None or an empty list.
# We get the date.
date = self._cases_management(regx, matched_result)
if date:
# The date is given.
# We return the formatted date.
return "-".join(date)
# We return an empty string as we were not eable to match the date format.
return ""
|
[
"Format",
"the",
"expiration",
"date",
"into",
"an",
"unified",
"format",
"(",
"01",
"-",
"jan",
"-",
"1970",
")",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/expiration_date.py#L309-L432
|
[
"def",
"_format",
"(",
"self",
",",
"date_to_convert",
"=",
"None",
")",
":",
"if",
"not",
"date_to_convert",
":",
"# pragma: no cover",
"# The date to conver is given.",
"# We initiate the date we are working with.",
"date_to_convert",
"=",
"self",
".",
"expiration_date",
"# We map the different possible regex.",
"# The regex index represent a unique number which have to be reported",
"# to the self._case_management() method.",
"regex_dates",
"=",
"{",
"# Date in format: 02-jan-2017",
"\"1\"",
":",
"r\"([0-9]{2})-([a-z]{3})-([0-9]{4})\"",
",",
"# Date in format: 02.01.2017 // Month: jan",
"\"2\"",
":",
"r\"([0-9]{2})\\.([0-9]{2})\\.([0-9]{4})$\"",
",",
"# Date in format: 02/01/2017 // Month: jan",
"\"3\"",
":",
"r\"([0-3][0-9])\\/(0[1-9]|1[012])\\/([0-9]{4})\"",
",",
"# Date in format: 2017-01-02 // Month: jan",
"\"4\"",
":",
"r\"([0-9]{4})-([0-9]{2})-([0-9]{2})$\"",
",",
"# Date in format: 2017.01.02 // Month: jan",
"\"5\"",
":",
"r\"([0-9]{4})\\.([0-9]{2})\\.([0-9]{2})$\"",
",",
"# Date in format: 2017/01/02 // Month: jan",
"\"6\"",
":",
"r\"([0-9]{4})\\/([0-9]{2})\\/([0-9]{2})$\"",
",",
"# Date in format: 2017.01.02 15:00:00",
"\"7\"",
":",
"r\"([0-9]{4})\\.([0-9]{2})\\.([0-9]{2})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\"",
",",
"# Date in format: 20170102 15:00:00 // Month: jan",
"\"8\"",
":",
"r\"([0-9]{4})([0-9]{2})([0-9]{2})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\"",
",",
"# Date in format: 2017-01-02 15:00:00 // Month: jan",
"\"9\"",
":",
"r\"([0-9]{4})-([0-9]{2})-([0-9]{2})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\"",
",",
"# Date in format: 02.01.2017 15:00:00 // Month: jan",
"\"10\"",
":",
"r\"([0-9]{2})\\.([0-9]{2})\\.([0-9]{4})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\"",
",",
"# Date in format: 02-Jan-2017 15:00:00 UTC",
"\"11\"",
":",
"r\"([0-9]{2})-([A-Z]{1}[a-z]{2})-([0-9]{4})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\s[A-Z]{1}.*\"",
",",
"# pylint: disable=line-too-long",
"# Date in format: 2017/01/02 01:00:00 (+0900) // Month: jan",
"\"12\"",
":",
"r\"([0-9]{4})\\/([0-9]{2})\\/([0-9]{2})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\s\\(.*\\)\"",
",",
"# Date in format: 2017/01/02 01:00:00 // Month: jan",
"\"13\"",
":",
"r\"([0-9]{4})\\/([0-9]{2})\\/([0-9]{2})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}$\"",
",",
"# Date in format: Mon Jan 02 15:00:00 GMT 2017",
"\"14\"",
":",
"r\"[a-zA-Z]{3}\\s([a-zA-Z]{3})\\s([0-9]{2})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\s[A-Z]{3}\\s([0-9]{4})\"",
",",
"# pylint: disable=line-too-long",
"# Date in format: Mon Jan 02 2017",
"\"15\"",
":",
"r\"[a-zA-Z]{3}\\s([a-zA-Z]{3})\\s([0-9]{2})\\s([0-9]{4})\"",
",",
"# Date in format: 2017-01-02T15:00:00 // Month: jan",
"\"16\"",
":",
"r\"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}$\"",
",",
"# Date in format: 2017-01-02T15:00:00Z // Month: jan${'7}",
"\"17\"",
":",
"r\"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[A-Z].*\"",
",",
"# Date in format: 2017-01-02T15:00:00+0200 // Month: jan",
"\"18\"",
":",
"r\"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{4}\"",
",",
"# Date in format: 2017-01-02T15:00:00+0200.622265+03:00 //",
"# Month: jan",
"\"19\"",
":",
"r\"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9].*[+-][0-9]{2}:[0-9]{2}\"",
",",
"# pylint: disable=line-too-long",
"# Date in format: 2017-01-02T15:00:00+0200.622265 // Month: jan",
"\"20\"",
":",
"r\"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{6}$\"",
",",
"# Date in format: 2017-01-02T23:59:59.0Z // Month: jan",
"\"21\"",
":",
"r\"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9].*[A-Z]\"",
",",
"# Date in format: 02-01-2017 // Month: jan",
"\"22\"",
":",
"r\"([0-9]{2})-([0-9]{2})-([0-9]{4})\"",
",",
"# Date in format: 2017. 01. 02. // Month: jan",
"\"23\"",
":",
"r\"([0-9]{4})\\.\\s([0-9]{2})\\.\\s([0-9]{2})\\.\"",
",",
"# Date in format: 2017-01-02T00:00:00+13:00 // Month: jan",
"\"24\"",
":",
"r\"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{2}:[0-9]{2}\"",
",",
"# pylint: disable=line-too-long",
"# Date in format: 20170102 // Month: jan",
"\"25\"",
":",
"r\"(?=[0-9]{8})(?=([0-9]{4})([0-9]{2})([0-9]{2}))\"",
",",
"# Date in format: 02-Jan-2017",
"\"26\"",
":",
"r\"([0-9]{2})-([A-Z]{1}[a-z]{2})-([0-9]{4})$\"",
",",
"# Date in format: 02.1.2017 // Month: jan",
"\"27\"",
":",
"r\"([0-9]{2})\\.([0-9]{1})\\.([0-9]{4})\"",
",",
"# Date in format: 02 Jan 2017",
"\"28\"",
":",
"r\"([0-9]{1,2})\\s([A-Z]{1}[a-z]{2})\\s([0-9]{4})\"",
",",
"# Date in format: 02-January-2017",
"\"29\"",
":",
"r\"([0-9]{2})-([A-Z]{1}[a-z]*)-([0-9]{4})\"",
",",
"# Date in format: 2017-Jan-02.",
"\"30\"",
":",
"r\"([0-9]{4})-([A-Z]{1}[a-z]{2})-([0-9]{2})\\.\"",
",",
"# Date in format: Mon Jan 02 15:00:00 2017",
"\"31\"",
":",
"r\"[a-zA-Z]{3}\\s([a-zA-Z]{3})\\s([0-9]{1,2})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\s([0-9]{4})\"",
",",
"# pylint: disable=line-too-long",
"# Date in format: Mon Jan 2017 15:00:00",
"\"32\"",
":",
"r\"()[a-zA-Z]{3}\\s([a-zA-Z]{3})\\s([0-9]{4})\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\"",
",",
"# Date in format: January 02 2017-Jan-02",
"\"33\"",
":",
"r\"([A-Z]{1}[a-z]*)\\s([0-9]{1,2})\\s([0-9]{4})\"",
",",
"# Date in format: 2.1.2017 // Month: jan",
"\"34\"",
":",
"r\"([0-9]{1,2})\\.([0-9]{1,2})\\.([0-9]{4})\"",
",",
"# Date in format: 20170102000000 // Month: jan",
"\"35\"",
":",
"r\"([0-9]{4})([0-9]{2})([0-9]{2})[0-9]+\"",
",",
"# Date in format: 01/02/2017 // Month: jan",
"\"36\"",
":",
"r\"(0[1-9]|1[012])\\/([0-3][0-9])\\/([0-9]{4})\"",
",",
"# Date in format: January 2 2017",
"\"37\"",
":",
"r\"([A-Z]{1}[a-z].*)\\s\\s([0-9]{1,2})\\s([0-9]{4})\"",
",",
"# Date in format: 2nd January 2017",
"\"38\"",
":",
"r\"([0-9]{1,})[a-z]{1,}\\s([A-Z].*)\\s(2[0-9]{3})\"",
",",
"}",
"for",
"regx",
"in",
"regex_dates",
":",
"# We loop through our map.",
"# We try to get the matched groups if the date to convert match the currently",
"# read regex.",
"matched_result",
"=",
"Regex",
"(",
"date_to_convert",
",",
"regex_dates",
"[",
"regx",
"]",
",",
"return_data",
"=",
"True",
",",
"rematch",
"=",
"True",
")",
".",
"match",
"(",
")",
"if",
"matched_result",
":",
"# The matched result is not None or an empty list.",
"# We get the date.",
"date",
"=",
"self",
".",
"_cases_management",
"(",
"regx",
",",
"matched_result",
")",
"if",
"date",
":",
"# The date is given.",
"# We return the formatted date.",
"return",
"\"-\"",
".",
"join",
"(",
"date",
")",
"# We return an empty string as we were not eable to match the date format.",
"return",
"\"\""
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
ExpirationDate._extract
|
Extract the expiration date from the whois record.
:return: The status of the domain.
:rtype: str
|
PyFunceble/expiration_date.py
|
def _extract(self): # pragma: no cover
"""
Extract the expiration date from the whois record.
:return: The status of the domain.
:rtype: str
"""
# We try to get the expiration date from the database.
expiration_date_from_database = Whois().get_expiration_date()
if expiration_date_from_database:
# The hash of the current whois record did not changed and the
# expiration date from the database is not empty not equal to
# None or False.
# We generate the files and print the status.
# It's an active element!
Generate(
PyFunceble.STATUS["official"]["up"],
"WHOIS",
expiration_date_from_database,
).status_file()
# We handle und return the official up status.
return PyFunceble.STATUS["official"]["up"]
# We get the whois record.
self.whois_record = Lookup().whois(PyFunceble.INTERN["referer"])
# We list the list of regex which will help us get an unformatted expiration date.
to_match = [
r"expire:(.*)",
r"expire on:(.*)",
r"Expiry Date:(.*)",
r"free-date(.*)",
r"expires:(.*)",
r"Expiration date:(.*)",
r"Expiry date:(.*)",
r"Expire Date:(.*)",
r"renewal date:(.*)",
r"Expires:(.*)",
r"validity:(.*)",
r"Expiration Date :(.*)",
r"Expiry :(.*)",
r"expires at:(.*)",
r"domain_datebilleduntil:(.*)",
r"Data de expiração \/ Expiration Date \(dd\/mm\/yyyy\):(.*)",
r"Fecha de expiración \(Expiration date\):(.*)",
r"\[Expires on\](.*)",
r"Record expires on(.*)(\(YYYY-MM-DD\))",
r"status: OK-UNTIL(.*)",
r"renewal:(.*)",
r"expires............:(.*)",
r"expire-date:(.*)",
r"Exp date:(.*)",
r"Valid-date(.*)",
r"Expires On:(.*)",
r"Fecha de vencimiento:(.*)",
r"Expiration:.........(.*)",
r"Fecha de Vencimiento:(.*)",
r"Registry Expiry Date:(.*)",
r"Expires on..............:(.*)",
r"Expiration Time:(.*)",
r"Expiration Date:(.*)",
r"Expired:(.*)",
r"Date d'expiration:(.*)",
r"expiration date:(.*)",
]
if self.whois_record:
# The whois record is not empty.
if "current_test_data" in PyFunceble.INTERN:
# The end-user want more information whith his test.
# We update the whois_record index.
PyFunceble.INTERN["current_test_data"][
"whois_record"
] = self.whois_record
for string in to_match:
# We loop through the list of regex.
# We try tro extract the expiration date from the WHOIS record.
expiration_date = Regex(
self.whois_record, string, return_data=True, rematch=True, group=0
).match()
if expiration_date:
# The expiration date could be extracted.
# We get the extracted expiration date.
self.expiration_date = expiration_date[0].strip()
# We initate a regex which will help us know if a number
# is present into the extracted expiration date.
regex_rumbers = r"[0-9]"
if Regex(
self.expiration_date, regex_rumbers, return_data=False
).match():
# The extracted expiration date has a number.
# We format the extracted expiration date.
self.expiration_date = self._format()
if (
self.expiration_date
and not Regex(
self.expiration_date,
r"[0-9]{2}\-[a-z]{3}\-2[0-9]{3}",
return_data=False,
).match()
):
# The formatted expiration date does not match our unified format.
# We log the problem.
Logs().expiration_date(self.expiration_date)
# We log the whois record.
Logs().whois(self.whois_record)
if "current_test_data" in PyFunceble.INTERN:
# The end-user want more information whith his test.
# We update the expiration_date index.
PyFunceble.INTERN["current_test_data"][
"expiration_date"
] = self.expiration_date
# We generate the files and print the status.
# It's an active element!
Generate(
PyFunceble.STATUS["official"]["up"],
"WHOIS",
self.expiration_date,
).status_file()
# We log the whois record.
Logs().whois(self.whois_record)
# We save the whois record into the database.
Whois(expiration_date=self.expiration_date).add()
# We handle und return the official up status.
return PyFunceble.STATUS["official"]["up"]
# The extracted expiration date does not have a number.
# We log the whois record.
Logs().whois(self.whois_record)
# We return None, we could not get the expiration date.
return None
# The whois record is empty.
# We return None, we could not get the whois record.
return None
|
def _extract(self): # pragma: no cover
"""
Extract the expiration date from the whois record.
:return: The status of the domain.
:rtype: str
"""
# We try to get the expiration date from the database.
expiration_date_from_database = Whois().get_expiration_date()
if expiration_date_from_database:
# The hash of the current whois record did not changed and the
# expiration date from the database is not empty not equal to
# None or False.
# We generate the files and print the status.
# It's an active element!
Generate(
PyFunceble.STATUS["official"]["up"],
"WHOIS",
expiration_date_from_database,
).status_file()
# We handle und return the official up status.
return PyFunceble.STATUS["official"]["up"]
# We get the whois record.
self.whois_record = Lookup().whois(PyFunceble.INTERN["referer"])
# We list the list of regex which will help us get an unformatted expiration date.
to_match = [
r"expire:(.*)",
r"expire on:(.*)",
r"Expiry Date:(.*)",
r"free-date(.*)",
r"expires:(.*)",
r"Expiration date:(.*)",
r"Expiry date:(.*)",
r"Expire Date:(.*)",
r"renewal date:(.*)",
r"Expires:(.*)",
r"validity:(.*)",
r"Expiration Date :(.*)",
r"Expiry :(.*)",
r"expires at:(.*)",
r"domain_datebilleduntil:(.*)",
r"Data de expiração \/ Expiration Date \(dd\/mm\/yyyy\):(.*)",
r"Fecha de expiración \(Expiration date\):(.*)",
r"\[Expires on\](.*)",
r"Record expires on(.*)(\(YYYY-MM-DD\))",
r"status: OK-UNTIL(.*)",
r"renewal:(.*)",
r"expires............:(.*)",
r"expire-date:(.*)",
r"Exp date:(.*)",
r"Valid-date(.*)",
r"Expires On:(.*)",
r"Fecha de vencimiento:(.*)",
r"Expiration:.........(.*)",
r"Fecha de Vencimiento:(.*)",
r"Registry Expiry Date:(.*)",
r"Expires on..............:(.*)",
r"Expiration Time:(.*)",
r"Expiration Date:(.*)",
r"Expired:(.*)",
r"Date d'expiration:(.*)",
r"expiration date:(.*)",
]
if self.whois_record:
# The whois record is not empty.
if "current_test_data" in PyFunceble.INTERN:
# The end-user want more information whith his test.
# We update the whois_record index.
PyFunceble.INTERN["current_test_data"][
"whois_record"
] = self.whois_record
for string in to_match:
# We loop through the list of regex.
# We try tro extract the expiration date from the WHOIS record.
expiration_date = Regex(
self.whois_record, string, return_data=True, rematch=True, group=0
).match()
if expiration_date:
# The expiration date could be extracted.
# We get the extracted expiration date.
self.expiration_date = expiration_date[0].strip()
# We initate a regex which will help us know if a number
# is present into the extracted expiration date.
regex_rumbers = r"[0-9]"
if Regex(
self.expiration_date, regex_rumbers, return_data=False
).match():
# The extracted expiration date has a number.
# We format the extracted expiration date.
self.expiration_date = self._format()
if (
self.expiration_date
and not Regex(
self.expiration_date,
r"[0-9]{2}\-[a-z]{3}\-2[0-9]{3}",
return_data=False,
).match()
):
# The formatted expiration date does not match our unified format.
# We log the problem.
Logs().expiration_date(self.expiration_date)
# We log the whois record.
Logs().whois(self.whois_record)
if "current_test_data" in PyFunceble.INTERN:
# The end-user want more information whith his test.
# We update the expiration_date index.
PyFunceble.INTERN["current_test_data"][
"expiration_date"
] = self.expiration_date
# We generate the files and print the status.
# It's an active element!
Generate(
PyFunceble.STATUS["official"]["up"],
"WHOIS",
self.expiration_date,
).status_file()
# We log the whois record.
Logs().whois(self.whois_record)
# We save the whois record into the database.
Whois(expiration_date=self.expiration_date).add()
# We handle und return the official up status.
return PyFunceble.STATUS["official"]["up"]
# The extracted expiration date does not have a number.
# We log the whois record.
Logs().whois(self.whois_record)
# We return None, we could not get the expiration date.
return None
# The whois record is empty.
# We return None, we could not get the whois record.
return None
|
[
"Extract",
"the",
"expiration",
"date",
"from",
"the",
"whois",
"record",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/expiration_date.py#L434-L593
|
[
"def",
"_extract",
"(",
"self",
")",
":",
"# pragma: no cover",
"# We try to get the expiration date from the database.",
"expiration_date_from_database",
"=",
"Whois",
"(",
")",
".",
"get_expiration_date",
"(",
")",
"if",
"expiration_date_from_database",
":",
"# The hash of the current whois record did not changed and the",
"# expiration date from the database is not empty not equal to",
"# None or False.",
"# We generate the files and print the status.",
"# It's an active element!",
"Generate",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
",",
"\"WHOIS\"",
",",
"expiration_date_from_database",
",",
")",
".",
"status_file",
"(",
")",
"# We handle und return the official up status.",
"return",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
"# We get the whois record.",
"self",
".",
"whois_record",
"=",
"Lookup",
"(",
")",
".",
"whois",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"referer\"",
"]",
")",
"# We list the list of regex which will help us get an unformatted expiration date.",
"to_match",
"=",
"[",
"r\"expire:(.*)\"",
",",
"r\"expire on:(.*)\"",
",",
"r\"Expiry Date:(.*)\"",
",",
"r\"free-date(.*)\"",
",",
"r\"expires:(.*)\"",
",",
"r\"Expiration date:(.*)\"",
",",
"r\"Expiry date:(.*)\"",
",",
"r\"Expire Date:(.*)\"",
",",
"r\"renewal date:(.*)\"",
",",
"r\"Expires:(.*)\"",
",",
"r\"validity:(.*)\"",
",",
"r\"Expiration Date :(.*)\"",
",",
"r\"Expiry :(.*)\"",
",",
"r\"expires at:(.*)\"",
",",
"r\"domain_datebilleduntil:(.*)\"",
",",
"r\"Data de expiração \\/ Expiration Date \\(dd\\/mm\\/yyyy\\):(.*)\",",
"",
"r\"Fecha de expiración \\(Expiration date\\):(.*)\",",
"",
"r\"\\[Expires on\\](.*)\"",
",",
"r\"Record expires on(.*)(\\(YYYY-MM-DD\\))\"",
",",
"r\"status: OK-UNTIL(.*)\"",
",",
"r\"renewal:(.*)\"",
",",
"r\"expires............:(.*)\"",
",",
"r\"expire-date:(.*)\"",
",",
"r\"Exp date:(.*)\"",
",",
"r\"Valid-date(.*)\"",
",",
"r\"Expires On:(.*)\"",
",",
"r\"Fecha de vencimiento:(.*)\"",
",",
"r\"Expiration:.........(.*)\"",
",",
"r\"Fecha de Vencimiento:(.*)\"",
",",
"r\"Registry Expiry Date:(.*)\"",
",",
"r\"Expires on..............:(.*)\"",
",",
"r\"Expiration Time:(.*)\"",
",",
"r\"Expiration Date:(.*)\"",
",",
"r\"Expired:(.*)\"",
",",
"r\"Date d'expiration:(.*)\"",
",",
"r\"expiration date:(.*)\"",
",",
"]",
"if",
"self",
".",
"whois_record",
":",
"# The whois record is not empty.",
"if",
"\"current_test_data\"",
"in",
"PyFunceble",
".",
"INTERN",
":",
"# The end-user want more information whith his test.",
"# We update the whois_record index.",
"PyFunceble",
".",
"INTERN",
"[",
"\"current_test_data\"",
"]",
"[",
"\"whois_record\"",
"]",
"=",
"self",
".",
"whois_record",
"for",
"string",
"in",
"to_match",
":",
"# We loop through the list of regex.",
"# We try tro extract the expiration date from the WHOIS record.",
"expiration_date",
"=",
"Regex",
"(",
"self",
".",
"whois_record",
",",
"string",
",",
"return_data",
"=",
"True",
",",
"rematch",
"=",
"True",
",",
"group",
"=",
"0",
")",
".",
"match",
"(",
")",
"if",
"expiration_date",
":",
"# The expiration date could be extracted.",
"# We get the extracted expiration date.",
"self",
".",
"expiration_date",
"=",
"expiration_date",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"# We initate a regex which will help us know if a number",
"# is present into the extracted expiration date.",
"regex_rumbers",
"=",
"r\"[0-9]\"",
"if",
"Regex",
"(",
"self",
".",
"expiration_date",
",",
"regex_rumbers",
",",
"return_data",
"=",
"False",
")",
".",
"match",
"(",
")",
":",
"# The extracted expiration date has a number.",
"# We format the extracted expiration date.",
"self",
".",
"expiration_date",
"=",
"self",
".",
"_format",
"(",
")",
"if",
"(",
"self",
".",
"expiration_date",
"and",
"not",
"Regex",
"(",
"self",
".",
"expiration_date",
",",
"r\"[0-9]{2}\\-[a-z]{3}\\-2[0-9]{3}\"",
",",
"return_data",
"=",
"False",
",",
")",
".",
"match",
"(",
")",
")",
":",
"# The formatted expiration date does not match our unified format.",
"# We log the problem.",
"Logs",
"(",
")",
".",
"expiration_date",
"(",
"self",
".",
"expiration_date",
")",
"# We log the whois record.",
"Logs",
"(",
")",
".",
"whois",
"(",
"self",
".",
"whois_record",
")",
"if",
"\"current_test_data\"",
"in",
"PyFunceble",
".",
"INTERN",
":",
"# The end-user want more information whith his test.",
"# We update the expiration_date index.",
"PyFunceble",
".",
"INTERN",
"[",
"\"current_test_data\"",
"]",
"[",
"\"expiration_date\"",
"]",
"=",
"self",
".",
"expiration_date",
"# We generate the files and print the status.",
"# It's an active element!",
"Generate",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
",",
"\"WHOIS\"",
",",
"self",
".",
"expiration_date",
",",
")",
".",
"status_file",
"(",
")",
"# We log the whois record.",
"Logs",
"(",
")",
".",
"whois",
"(",
"self",
".",
"whois_record",
")",
"# We save the whois record into the database.",
"Whois",
"(",
"expiration_date",
"=",
"self",
".",
"expiration_date",
")",
".",
"add",
"(",
")",
"# We handle und return the official up status.",
"return",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
"# The extracted expiration date does not have a number.",
"# We log the whois record.",
"Logs",
"(",
")",
".",
"whois",
"(",
"self",
".",
"whois_record",
")",
"# We return None, we could not get the expiration date.",
"return",
"None",
"# The whois record is empty.",
"# We return None, we could not get the whois record.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Production._update_code_urls
|
Read the code and update all links.
|
PyFunceble/production.py
|
def _update_code_urls(self):
"""
Read the code and update all links.
"""
to_ignore = [".gitignore", ".keep"]
for root, _, files in PyFunceble.walk(
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.directory_separator
+ "PyFunceble"
+ PyFunceble.directory_separator
):
# We loop through every directories and files in the `PyFunceble` directory.
for file in files:
# We loop through the list of files of the currently read directory.
if file not in to_ignore and "__pycache__" not in root:
# * The filename is not into the list of file to ignore.
# and
# * The directory we are reading is not `__pycache__`.
if root.endswith(PyFunceble.directory_separator):
# The root directory ends with the directory separator.
# We fix the path in the currently read file.
self._update_docs(root + file)
else:
# The root directory does not ends with the directory separator.
# We fix the path in the currently read file.
# (after appending the directory separator between the root and file)
self._update_docs(root + PyFunceble.directory_separator + file)
for root, _, files in PyFunceble.walk(
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.directory_separator
+ "tests"
+ PyFunceble.directory_separator
):
# We loop through every directories and files in the `tests` directory.
for file in files:
# We loop through the list of files of the currently read directory.
if file not in to_ignore and "__pycache__" not in root:
# * The filename is not into the list of file to ignore.
# and
# * The directory we are reading is not `__pycache__`.
if root.endswith(PyFunceble.directory_separator):
# The root directory ends with the directory separator.
# We fix the path in the currently read file.
self._update_docs(root + file)
else:
# The root directory does not ends with the directory separator.
# We fix the path in the currently read file.
# (after appending the directory separator between the root and file)
self._update_docs(root + PyFunceble.directory_separator + file)
|
def _update_code_urls(self):
"""
Read the code and update all links.
"""
to_ignore = [".gitignore", ".keep"]
for root, _, files in PyFunceble.walk(
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.directory_separator
+ "PyFunceble"
+ PyFunceble.directory_separator
):
# We loop through every directories and files in the `PyFunceble` directory.
for file in files:
# We loop through the list of files of the currently read directory.
if file not in to_ignore and "__pycache__" not in root:
# * The filename is not into the list of file to ignore.
# and
# * The directory we are reading is not `__pycache__`.
if root.endswith(PyFunceble.directory_separator):
# The root directory ends with the directory separator.
# We fix the path in the currently read file.
self._update_docs(root + file)
else:
# The root directory does not ends with the directory separator.
# We fix the path in the currently read file.
# (after appending the directory separator between the root and file)
self._update_docs(root + PyFunceble.directory_separator + file)
for root, _, files in PyFunceble.walk(
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.directory_separator
+ "tests"
+ PyFunceble.directory_separator
):
# We loop through every directories and files in the `tests` directory.
for file in files:
# We loop through the list of files of the currently read directory.
if file not in to_ignore and "__pycache__" not in root:
# * The filename is not into the list of file to ignore.
# and
# * The directory we are reading is not `__pycache__`.
if root.endswith(PyFunceble.directory_separator):
# The root directory ends with the directory separator.
# We fix the path in the currently read file.
self._update_docs(root + file)
else:
# The root directory does not ends with the directory separator.
# We fix the path in the currently read file.
# (after appending the directory separator between the root and file)
self._update_docs(root + PyFunceble.directory_separator + file)
|
[
"Read",
"the",
"code",
"and",
"update",
"all",
"links",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/production.py#L248-L308
|
[
"def",
"_update_code_urls",
"(",
"self",
")",
":",
"to_ignore",
"=",
"[",
"\".gitignore\"",
",",
"\".keep\"",
"]",
"for",
"root",
",",
"_",
",",
"files",
"in",
"PyFunceble",
".",
"walk",
"(",
"PyFunceble",
".",
"CURRENT_DIRECTORY",
"+",
"PyFunceble",
".",
"directory_separator",
"+",
"\"PyFunceble\"",
"+",
"PyFunceble",
".",
"directory_separator",
")",
":",
"# We loop through every directories and files in the `PyFunceble` directory.",
"for",
"file",
"in",
"files",
":",
"# We loop through the list of files of the currently read directory.",
"if",
"file",
"not",
"in",
"to_ignore",
"and",
"\"__pycache__\"",
"not",
"in",
"root",
":",
"# * The filename is not into the list of file to ignore.",
"# and",
"# * The directory we are reading is not `__pycache__`.",
"if",
"root",
".",
"endswith",
"(",
"PyFunceble",
".",
"directory_separator",
")",
":",
"# The root directory ends with the directory separator.",
"# We fix the path in the currently read file.",
"self",
".",
"_update_docs",
"(",
"root",
"+",
"file",
")",
"else",
":",
"# The root directory does not ends with the directory separator.",
"# We fix the path in the currently read file.",
"# (after appending the directory separator between the root and file)",
"self",
".",
"_update_docs",
"(",
"root",
"+",
"PyFunceble",
".",
"directory_separator",
"+",
"file",
")",
"for",
"root",
",",
"_",
",",
"files",
"in",
"PyFunceble",
".",
"walk",
"(",
"PyFunceble",
".",
"CURRENT_DIRECTORY",
"+",
"PyFunceble",
".",
"directory_separator",
"+",
"\"tests\"",
"+",
"PyFunceble",
".",
"directory_separator",
")",
":",
"# We loop through every directories and files in the `tests` directory.",
"for",
"file",
"in",
"files",
":",
"# We loop through the list of files of the currently read directory.",
"if",
"file",
"not",
"in",
"to_ignore",
"and",
"\"__pycache__\"",
"not",
"in",
"root",
":",
"# * The filename is not into the list of file to ignore.",
"# and",
"# * The directory we are reading is not `__pycache__`.",
"if",
"root",
".",
"endswith",
"(",
"PyFunceble",
".",
"directory_separator",
")",
":",
"# The root directory ends with the directory separator.",
"# We fix the path in the currently read file.",
"self",
".",
"_update_docs",
"(",
"root",
"+",
"file",
")",
"else",
":",
"# The root directory does not ends with the directory separator.",
"# We fix the path in the currently read file.",
"# (after appending the directory separator between the root and file)",
"self",
".",
"_update_docs",
"(",
"root",
"+",
"PyFunceble",
".",
"directory_separator",
"+",
"file",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Production._is_version_greater
|
Check if the current version is greater as the older older one.
|
PyFunceble/production.py
|
def _is_version_greater(self):
"""
Check if the current version is greater as the older older one.
"""
# we compare the 2 versions.
checked = Version(True).check_versions(
self.current_version[0], self.version_yaml
)
if checked is not None and not checked:
# The current version is greater as the older one.
# We return True.
return True
# We return False
return False
|
def _is_version_greater(self):
"""
Check if the current version is greater as the older older one.
"""
# we compare the 2 versions.
checked = Version(True).check_versions(
self.current_version[0], self.version_yaml
)
if checked is not None and not checked:
# The current version is greater as the older one.
# We return True.
return True
# We return False
return False
|
[
"Check",
"if",
"the",
"current",
"version",
"is",
"greater",
"as",
"the",
"older",
"older",
"one",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/production.py#L320-L337
|
[
"def",
"_is_version_greater",
"(",
"self",
")",
":",
"# we compare the 2 versions.",
"checked",
"=",
"Version",
"(",
"True",
")",
".",
"check_versions",
"(",
"self",
".",
"current_version",
"[",
"0",
"]",
",",
"self",
".",
"version_yaml",
")",
"if",
"checked",
"is",
"not",
"None",
"and",
"not",
"checked",
":",
"# The current version is greater as the older one.",
"# We return True.",
"return",
"True",
"# We return False",
"return",
"False"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Production.is_dev_version
|
Check if the current branch is `dev`.
|
PyFunceble/production.py
|
def is_dev_version(cls):
"""
Check if the current branch is `dev`.
"""
# We initiate the command we have to run in order to
# get the branch we are currently working with.
command = "git branch"
# We execute and get the command output.
command_result = Command(command).execute()
for branch in command_result.split("\n"):
# We loop through each line of the command output.
if branch.startswith("*") and "dev" in branch:
# The current branch is `dev`.
# We return True.
return True
# The current branch is not `dev`.
# We return False.
return False
|
def is_dev_version(cls):
"""
Check if the current branch is `dev`.
"""
# We initiate the command we have to run in order to
# get the branch we are currently working with.
command = "git branch"
# We execute and get the command output.
command_result = Command(command).execute()
for branch in command_result.split("\n"):
# We loop through each line of the command output.
if branch.startswith("*") and "dev" in branch:
# The current branch is `dev`.
# We return True.
return True
# The current branch is not `dev`.
# We return False.
return False
|
[
"Check",
"if",
"the",
"current",
"branch",
"is",
"dev",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/production.py#L340-L364
|
[
"def",
"is_dev_version",
"(",
"cls",
")",
":",
"# We initiate the command we have to run in order to",
"# get the branch we are currently working with.",
"command",
"=",
"\"git branch\"",
"# We execute and get the command output.",
"command_result",
"=",
"Command",
"(",
"command",
")",
".",
"execute",
"(",
")",
"for",
"branch",
"in",
"command_result",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"# We loop through each line of the command output.",
"if",
"branch",
".",
"startswith",
"(",
"\"*\"",
")",
"and",
"\"dev\"",
"in",
"branch",
":",
"# The current branch is `dev`.",
"# We return True.",
"return",
"True",
"# The current branch is not `dev`.",
"# We return False.",
"return",
"False"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Production._does_require_deprecation
|
Check if we have to put the previous version into the deprecated list.
|
PyFunceble/production.py
|
def _does_require_deprecation(self):
"""
Check if we have to put the previous version into the deprecated list.
"""
for index, version_number in enumerate(self.current_version[0][:2]):
# We loop through the 2 last elements of the version.
if version_number > self.version_yaml[index]:
# The currently read version number is greater than the one we have in
# the version.yaml.
# We return True.
return True
# We return False, we do not need to deprecate anything.
return False
|
def _does_require_deprecation(self):
"""
Check if we have to put the previous version into the deprecated list.
"""
for index, version_number in enumerate(self.current_version[0][:2]):
# We loop through the 2 last elements of the version.
if version_number > self.version_yaml[index]:
# The currently read version number is greater than the one we have in
# the version.yaml.
# We return True.
return True
# We return False, we do not need to deprecate anything.
return False
|
[
"Check",
"if",
"we",
"have",
"to",
"put",
"the",
"previous",
"version",
"into",
"the",
"deprecated",
"list",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/production.py#L393-L409
|
[
"def",
"_does_require_deprecation",
"(",
"self",
")",
":",
"for",
"index",
",",
"version_number",
"in",
"enumerate",
"(",
"self",
".",
"current_version",
"[",
"0",
"]",
"[",
":",
"2",
"]",
")",
":",
"# We loop through the 2 last elements of the version.",
"if",
"version_number",
">",
"self",
".",
"version_yaml",
"[",
"index",
"]",
":",
"# The currently read version number is greater than the one we have in",
"# the version.yaml.",
"# We return True.",
"return",
"True",
"# We return False, we do not need to deprecate anything.",
"return",
"False"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Production._update_docs
|
Update the given documentation file or :code:`README.rst` so that
it always gives branch related URL and informations.
.. note::
This only apply to :code:`dev` and :code:`master` branch.
:param file_to_update: The file to update.
:type file_to_update: str
|
PyFunceble/production.py
|
def _update_docs(self, file_to_update):
"""
Update the given documentation file or :code:`README.rst` so that
it always gives branch related URL and informations.
.. note::
This only apply to :code:`dev` and :code:`master` branch.
:param file_to_update: The file to update.
:type file_to_update: str
"""
if self.is_dev_version():
# The current version is the dev version.
# We map what we have to replace.
# Format: {match:replacement}
regexes = {
"/%s/" % "dev": r"\/%s\/" % "master",
"=%s" % "dev": "=%s" % "master",
}
elif self.is_master_version():
# The current version is the master version.
# We map what we have to replace.
regexes = {
"/%s/" % "master": r"\/%s\/" % "dev",
"=%s" % "master": "=%s" % "dev",
}
else:
# The current version is not the master nor the dev version.
# We raise an exception as the branch we are currently is not meaned
# for production.
raise Exception("Please switch to `dev` or `master` branch.")
# We get the content of the file to fix.
to_update = File(file_to_update).read()
for replacement, regex in regexes.items():
# We loop through reach element of the map.
# We process the replacement.
to_update = Regex(to_update, regex, replace_with=replacement).replace()
# We finally overwrite the file to fix with the filtered.
# content.
File(file_to_update).write(to_update, overwrite=True)
|
def _update_docs(self, file_to_update):
"""
Update the given documentation file or :code:`README.rst` so that
it always gives branch related URL and informations.
.. note::
This only apply to :code:`dev` and :code:`master` branch.
:param file_to_update: The file to update.
:type file_to_update: str
"""
if self.is_dev_version():
# The current version is the dev version.
# We map what we have to replace.
# Format: {match:replacement}
regexes = {
"/%s/" % "dev": r"\/%s\/" % "master",
"=%s" % "dev": "=%s" % "master",
}
elif self.is_master_version():
# The current version is the master version.
# We map what we have to replace.
regexes = {
"/%s/" % "master": r"\/%s\/" % "dev",
"=%s" % "master": "=%s" % "dev",
}
else:
# The current version is not the master nor the dev version.
# We raise an exception as the branch we are currently is not meaned
# for production.
raise Exception("Please switch to `dev` or `master` branch.")
# We get the content of the file to fix.
to_update = File(file_to_update).read()
for replacement, regex in regexes.items():
# We loop through reach element of the map.
# We process the replacement.
to_update = Regex(to_update, regex, replace_with=replacement).replace()
# We finally overwrite the file to fix with the filtered.
# content.
File(file_to_update).write(to_update, overwrite=True)
|
[
"Update",
"the",
"given",
"documentation",
"file",
"or",
":",
"code",
":",
"README",
".",
"rst",
"so",
"that",
"it",
"always",
"gives",
"branch",
"related",
"URL",
"and",
"informations",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/production.py#L428-L475
|
[
"def",
"_update_docs",
"(",
"self",
",",
"file_to_update",
")",
":",
"if",
"self",
".",
"is_dev_version",
"(",
")",
":",
"# The current version is the dev version.",
"# We map what we have to replace.",
"# Format: {match:replacement}",
"regexes",
"=",
"{",
"\"/%s/\"",
"%",
"\"dev\"",
":",
"r\"\\/%s\\/\"",
"%",
"\"master\"",
",",
"\"=%s\"",
"%",
"\"dev\"",
":",
"\"=%s\"",
"%",
"\"master\"",
",",
"}",
"elif",
"self",
".",
"is_master_version",
"(",
")",
":",
"# The current version is the master version.",
"# We map what we have to replace.",
"regexes",
"=",
"{",
"\"/%s/\"",
"%",
"\"master\"",
":",
"r\"\\/%s\\/\"",
"%",
"\"dev\"",
",",
"\"=%s\"",
"%",
"\"master\"",
":",
"\"=%s\"",
"%",
"\"dev\"",
",",
"}",
"else",
":",
"# The current version is not the master nor the dev version.",
"# We raise an exception as the branch we are currently is not meaned",
"# for production.",
"raise",
"Exception",
"(",
"\"Please switch to `dev` or `master` branch.\"",
")",
"# We get the content of the file to fix.",
"to_update",
"=",
"File",
"(",
"file_to_update",
")",
".",
"read",
"(",
")",
"for",
"replacement",
",",
"regex",
"in",
"regexes",
".",
"items",
"(",
")",
":",
"# We loop through reach element of the map.",
"# We process the replacement.",
"to_update",
"=",
"Regex",
"(",
"to_update",
",",
"regex",
",",
"replace_with",
"=",
"replacement",
")",
".",
"replace",
"(",
")",
"# We finally overwrite the file to fix with the filtered.",
"# content.",
"File",
"(",
"file_to_update",
")",
".",
"write",
"(",
"to_update",
",",
"overwrite",
"=",
"True",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Production._update_setup_py
|
Update :code:`setup.py` so that it always have the right name.
|
PyFunceble/production.py
|
def _update_setup_py(self):
"""
Update :code:`setup.py` so that it always have the right name.
"""
# We initiate the path to the file we have to filter.
setup_py_path = PyFunceble.CURRENT_DIRECTORY + "setup.py"
if self.is_dev_version():
# The current version is the `dev` version.
# We map what we have to replace.
# Format: {match:replacement}
regexes = {
'name="PyFunceble-dev"': r'name=".*"',
'"Development Status :: 4 - Beta"': r'"Development\sStatus\s::.*"',
}
elif self.is_master_version():
# The current version is the `dev` version.
# We map what we have to replace.
regexes = {
'name="PyFunceble"': r'name=".*"',
'"Development Status :: 5 - Production/Stable"': r'"Development\sStatus\s::.*"',
}
else:
# The current version is not the `dev` nor the `master` version.
# We raise an exception to the user, the current branch is not meant for
# production.
raise Exception("Please switch to `dev` or `master` branch.")
# We get the file content.
to_update = File(setup_py_path).read()
for replacement, regex in regexes.items():
# We loop through our map.
# And we process the replacement.
to_update = Regex(to_update, regex, replace_with=replacement).replace()
# We finally replace the content of the file with the filtered
# version.
File(setup_py_path).write(to_update, overwrite=True)
|
def _update_setup_py(self):
"""
Update :code:`setup.py` so that it always have the right name.
"""
# We initiate the path to the file we have to filter.
setup_py_path = PyFunceble.CURRENT_DIRECTORY + "setup.py"
if self.is_dev_version():
# The current version is the `dev` version.
# We map what we have to replace.
# Format: {match:replacement}
regexes = {
'name="PyFunceble-dev"': r'name=".*"',
'"Development Status :: 4 - Beta"': r'"Development\sStatus\s::.*"',
}
elif self.is_master_version():
# The current version is the `dev` version.
# We map what we have to replace.
regexes = {
'name="PyFunceble"': r'name=".*"',
'"Development Status :: 5 - Production/Stable"': r'"Development\sStatus\s::.*"',
}
else:
# The current version is not the `dev` nor the `master` version.
# We raise an exception to the user, the current branch is not meant for
# production.
raise Exception("Please switch to `dev` or `master` branch.")
# We get the file content.
to_update = File(setup_py_path).read()
for replacement, regex in regexes.items():
# We loop through our map.
# And we process the replacement.
to_update = Regex(to_update, regex, replace_with=replacement).replace()
# We finally replace the content of the file with the filtered
# version.
File(setup_py_path).write(to_update, overwrite=True)
|
[
"Update",
":",
"code",
":",
"setup",
".",
"py",
"so",
"that",
"it",
"always",
"have",
"the",
"right",
"name",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/production.py#L477-L520
|
[
"def",
"_update_setup_py",
"(",
"self",
")",
":",
"# We initiate the path to the file we have to filter.",
"setup_py_path",
"=",
"PyFunceble",
".",
"CURRENT_DIRECTORY",
"+",
"\"setup.py\"",
"if",
"self",
".",
"is_dev_version",
"(",
")",
":",
"# The current version is the `dev` version.",
"# We map what we have to replace.",
"# Format: {match:replacement}",
"regexes",
"=",
"{",
"'name=\"PyFunceble-dev\"'",
":",
"r'name=\".*\"'",
",",
"'\"Development Status :: 4 - Beta\"'",
":",
"r'\"Development\\sStatus\\s::.*\"'",
",",
"}",
"elif",
"self",
".",
"is_master_version",
"(",
")",
":",
"# The current version is the `dev` version.",
"# We map what we have to replace.",
"regexes",
"=",
"{",
"'name=\"PyFunceble\"'",
":",
"r'name=\".*\"'",
",",
"'\"Development Status :: 5 - Production/Stable\"'",
":",
"r'\"Development\\sStatus\\s::.*\"'",
",",
"}",
"else",
":",
"# The current version is not the `dev` nor the `master` version.",
"# We raise an exception to the user, the current branch is not meant for",
"# production.",
"raise",
"Exception",
"(",
"\"Please switch to `dev` or `master` branch.\"",
")",
"# We get the file content.",
"to_update",
"=",
"File",
"(",
"setup_py_path",
")",
".",
"read",
"(",
")",
"for",
"replacement",
",",
"regex",
"in",
"regexes",
".",
"items",
"(",
")",
":",
"# We loop through our map.",
"# And we process the replacement.",
"to_update",
"=",
"Regex",
"(",
"to_update",
",",
"regex",
",",
"replace_with",
"=",
"replacement",
")",
".",
"replace",
"(",
")",
"# We finally replace the content of the file with the filtered",
"# version.",
"File",
"(",
"setup_py_path",
")",
".",
"write",
"(",
"to_update",
",",
"overwrite",
"=",
"True",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Production._update_travis_yml
|
Update :code:`.travis.yml` according to current branch.
|
PyFunceble/production.py
|
def _update_travis_yml(self):
"""
Update :code:`.travis.yml` according to current branch.
"""
# We initiate the file we have to filter/update.
travis_yml_path = PyFunceble.CURRENT_DIRECTORY + ".travis.yml"
if self.is_dev_version():
# The current version is the `dev` version.
# We map what we have to replace.
# Format: {match:replacement}
regexes = {
"pip3 install pyfunceble-dev": r"pip3\sinstall\spyfunceble.*",
"pip-autoremove pyfunceble-dev ": r"pip-autoremove\spyfunceble\s",
}
elif self.is_master_version():
# The current version is the `master` version.
# We map what we have to replace.
regexes = {
"pip3 install pyfunceble": r"pip3\sinstall\spyfunceble.*",
"pip-autoremove pyfunceble ": r"pip-autoremove\spyfunceble[a-z-_]+\s",
}
else:
# The current version is not the `master` nor the `dev` version.
# We raise an exception, the current branch is not meant for production.
raise Exception("Please switch to `dev` or `master` branch.")
# We get the file content.
to_update = File(travis_yml_path).read()
for replacement, regex in regexes.items():
# We loop through the map.
# And we process the replacement.
to_update = Regex(to_update, regex, replace_with=replacement).replace()
# We finaly replace the file content with the filtered
# content.
File(travis_yml_path).write(to_update, overwrite=True)
|
def _update_travis_yml(self):
"""
Update :code:`.travis.yml` according to current branch.
"""
# We initiate the file we have to filter/update.
travis_yml_path = PyFunceble.CURRENT_DIRECTORY + ".travis.yml"
if self.is_dev_version():
# The current version is the `dev` version.
# We map what we have to replace.
# Format: {match:replacement}
regexes = {
"pip3 install pyfunceble-dev": r"pip3\sinstall\spyfunceble.*",
"pip-autoremove pyfunceble-dev ": r"pip-autoremove\spyfunceble\s",
}
elif self.is_master_version():
# The current version is the `master` version.
# We map what we have to replace.
regexes = {
"pip3 install pyfunceble": r"pip3\sinstall\spyfunceble.*",
"pip-autoremove pyfunceble ": r"pip-autoremove\spyfunceble[a-z-_]+\s",
}
else:
# The current version is not the `master` nor the `dev` version.
# We raise an exception, the current branch is not meant for production.
raise Exception("Please switch to `dev` or `master` branch.")
# We get the file content.
to_update = File(travis_yml_path).read()
for replacement, regex in regexes.items():
# We loop through the map.
# And we process the replacement.
to_update = Regex(to_update, regex, replace_with=replacement).replace()
# We finaly replace the file content with the filtered
# content.
File(travis_yml_path).write(to_update, overwrite=True)
|
[
"Update",
":",
"code",
":",
".",
"travis",
".",
"yml",
"according",
"to",
"current",
"branch",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/production.py#L522-L564
|
[
"def",
"_update_travis_yml",
"(",
"self",
")",
":",
"# We initiate the file we have to filter/update.",
"travis_yml_path",
"=",
"PyFunceble",
".",
"CURRENT_DIRECTORY",
"+",
"\".travis.yml\"",
"if",
"self",
".",
"is_dev_version",
"(",
")",
":",
"# The current version is the `dev` version.",
"# We map what we have to replace.",
"# Format: {match:replacement}",
"regexes",
"=",
"{",
"\"pip3 install pyfunceble-dev\"",
":",
"r\"pip3\\sinstall\\spyfunceble.*\"",
",",
"\"pip-autoremove pyfunceble-dev \"",
":",
"r\"pip-autoremove\\spyfunceble\\s\"",
",",
"}",
"elif",
"self",
".",
"is_master_version",
"(",
")",
":",
"# The current version is the `master` version.",
"# We map what we have to replace.",
"regexes",
"=",
"{",
"\"pip3 install pyfunceble\"",
":",
"r\"pip3\\sinstall\\spyfunceble.*\"",
",",
"\"pip-autoremove pyfunceble \"",
":",
"r\"pip-autoremove\\spyfunceble[a-z-_]+\\s\"",
",",
"}",
"else",
":",
"# The current version is not the `master` nor the `dev` version.",
"# We raise an exception, the current branch is not meant for production.",
"raise",
"Exception",
"(",
"\"Please switch to `dev` or `master` branch.\"",
")",
"# We get the file content.",
"to_update",
"=",
"File",
"(",
"travis_yml_path",
")",
".",
"read",
"(",
")",
"for",
"replacement",
",",
"regex",
"in",
"regexes",
".",
"items",
"(",
")",
":",
"# We loop through the map.",
"# And we process the replacement.",
"to_update",
"=",
"Regex",
"(",
"to_update",
",",
"regex",
",",
"replace_with",
"=",
"replacement",
")",
".",
"replace",
"(",
")",
"# We finaly replace the file content with the filtered",
"# content.",
"File",
"(",
"travis_yml_path",
")",
".",
"write",
"(",
"to_update",
",",
"overwrite",
"=",
"True",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
AutoContinue.backup
|
Backup the current execution state.
|
PyFunceble/auto_continue.py
|
def backup(self):
"""
Backup the current execution state.
"""
if PyFunceble.CONFIGURATION["auto_continue"]:
# The auto_continue subsystem is activated.
# We initiate the location where we are going to save the data to backup.
data_to_backup = {}
# We get the current counter states.
configuration_counter = PyFunceble.INTERN["counter"]["number"]
# We initiate the data we have to backup.
data_to_backup[PyFunceble.INTERN["file_to_test"]] = {
# We backup the number of tested.
"tested": configuration_counter["tested"],
# We backup the number of up.
"up": configuration_counter["up"],
# We backup the number of down.
"down": configuration_counter["down"],
# We backup the number of invalid.
"invalid": configuration_counter["invalid"],
}
# We initiate the final data we have to save.
# We initiate this variable instead of updating backup_content because
# we do not want to touch the backup_content.
to_save = {}
# We add the backup_content into to_save.
to_save.update(self.backup_content)
# And we overwrite with the newly data to backup.
to_save.update(data_to_backup)
# Finaly, we save our informations into the log file.
Dict(to_save).to_json(self.autocontinue_log_file)
|
def backup(self):
"""
Backup the current execution state.
"""
if PyFunceble.CONFIGURATION["auto_continue"]:
# The auto_continue subsystem is activated.
# We initiate the location where we are going to save the data to backup.
data_to_backup = {}
# We get the current counter states.
configuration_counter = PyFunceble.INTERN["counter"]["number"]
# We initiate the data we have to backup.
data_to_backup[PyFunceble.INTERN["file_to_test"]] = {
# We backup the number of tested.
"tested": configuration_counter["tested"],
# We backup the number of up.
"up": configuration_counter["up"],
# We backup the number of down.
"down": configuration_counter["down"],
# We backup the number of invalid.
"invalid": configuration_counter["invalid"],
}
# We initiate the final data we have to save.
# We initiate this variable instead of updating backup_content because
# we do not want to touch the backup_content.
to_save = {}
# We add the backup_content into to_save.
to_save.update(self.backup_content)
# And we overwrite with the newly data to backup.
to_save.update(data_to_backup)
# Finaly, we save our informations into the log file.
Dict(to_save).to_json(self.autocontinue_log_file)
|
[
"Backup",
"the",
"current",
"execution",
"state",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/auto_continue.py#L105-L141
|
[
"def",
"backup",
"(",
"self",
")",
":",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"auto_continue\"",
"]",
":",
"# The auto_continue subsystem is activated.",
"# We initiate the location where we are going to save the data to backup.",
"data_to_backup",
"=",
"{",
"}",
"# We get the current counter states.",
"configuration_counter",
"=",
"PyFunceble",
".",
"INTERN",
"[",
"\"counter\"",
"]",
"[",
"\"number\"",
"]",
"# We initiate the data we have to backup.",
"data_to_backup",
"[",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
"]",
"=",
"{",
"# We backup the number of tested.",
"\"tested\"",
":",
"configuration_counter",
"[",
"\"tested\"",
"]",
",",
"# We backup the number of up.",
"\"up\"",
":",
"configuration_counter",
"[",
"\"up\"",
"]",
",",
"# We backup the number of down.",
"\"down\"",
":",
"configuration_counter",
"[",
"\"down\"",
"]",
",",
"# We backup the number of invalid.",
"\"invalid\"",
":",
"configuration_counter",
"[",
"\"invalid\"",
"]",
",",
"}",
"# We initiate the final data we have to save.",
"# We initiate this variable instead of updating backup_content because",
"# we do not want to touch the backup_content.",
"to_save",
"=",
"{",
"}",
"# We add the backup_content into to_save.",
"to_save",
".",
"update",
"(",
"self",
".",
"backup_content",
")",
"# And we overwrite with the newly data to backup.",
"to_save",
".",
"update",
"(",
"data_to_backup",
")",
"# Finaly, we save our informations into the log file.",
"Dict",
"(",
"to_save",
")",
".",
"to_json",
"(",
"self",
".",
"autocontinue_log_file",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
AutoContinue.restore
|
Restore data from the given path.
|
PyFunceble/auto_continue.py
|
def restore(self):
"""
Restore data from the given path.
"""
if PyFunceble.CONFIGURATION["auto_continue"] and self.backup_content:
# The auto_continue subsystem is activated and the backup_content
# is not empty.
# We get the file we have to restore.
file_to_restore = PyFunceble.INTERN["file_to_test"]
if file_to_restore in self.backup_content:
# The file we are working with is already into the backup content.
# We initiate the different status to set.
to_initiate = ["up", "down", "invalid", "tested"]
# Because at some time it was not the current status, we have to map
# the new with the old. This way, if someone is running the latest
# version but with old data, we still continue like nothing happend.
alternatives = {
"up": "number_of_up",
"down": "number_of_down",
"invalid": "number_of_invalid",
"tested": "number_of_tested",
}
for string in to_initiate:
# We loop over the status we have to initiate.
try:
# We try to update the counters by using the currently read status.
PyFunceble.INTERN["counter"]["number"].update(
{string: self.backup_content[file_to_restore][string]}
)
except KeyError:
# But if the status is not present, we try with the older index
# we mapped previously.
PyFunceble.INTERN["counter"]["number"].update(
{
string: self.backup_content[file_to_restore][
alternatives[string]
]
}
)
|
def restore(self):
"""
Restore data from the given path.
"""
if PyFunceble.CONFIGURATION["auto_continue"] and self.backup_content:
# The auto_continue subsystem is activated and the backup_content
# is not empty.
# We get the file we have to restore.
file_to_restore = PyFunceble.INTERN["file_to_test"]
if file_to_restore in self.backup_content:
# The file we are working with is already into the backup content.
# We initiate the different status to set.
to_initiate = ["up", "down", "invalid", "tested"]
# Because at some time it was not the current status, we have to map
# the new with the old. This way, if someone is running the latest
# version but with old data, we still continue like nothing happend.
alternatives = {
"up": "number_of_up",
"down": "number_of_down",
"invalid": "number_of_invalid",
"tested": "number_of_tested",
}
for string in to_initiate:
# We loop over the status we have to initiate.
try:
# We try to update the counters by using the currently read status.
PyFunceble.INTERN["counter"]["number"].update(
{string: self.backup_content[file_to_restore][string]}
)
except KeyError:
# But if the status is not present, we try with the older index
# we mapped previously.
PyFunceble.INTERN["counter"]["number"].update(
{
string: self.backup_content[file_to_restore][
alternatives[string]
]
}
)
|
[
"Restore",
"data",
"from",
"the",
"given",
"path",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/auto_continue.py#L143-L188
|
[
"def",
"restore",
"(",
"self",
")",
":",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"auto_continue\"",
"]",
"and",
"self",
".",
"backup_content",
":",
"# The auto_continue subsystem is activated and the backup_content",
"# is not empty.",
"# We get the file we have to restore.",
"file_to_restore",
"=",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
"if",
"file_to_restore",
"in",
"self",
".",
"backup_content",
":",
"# The file we are working with is already into the backup content.",
"# We initiate the different status to set.",
"to_initiate",
"=",
"[",
"\"up\"",
",",
"\"down\"",
",",
"\"invalid\"",
",",
"\"tested\"",
"]",
"# Because at some time it was not the current status, we have to map",
"# the new with the old. This way, if someone is running the latest",
"# version but with old data, we still continue like nothing happend.",
"alternatives",
"=",
"{",
"\"up\"",
":",
"\"number_of_up\"",
",",
"\"down\"",
":",
"\"number_of_down\"",
",",
"\"invalid\"",
":",
"\"number_of_invalid\"",
",",
"\"tested\"",
":",
"\"number_of_tested\"",
",",
"}",
"for",
"string",
"in",
"to_initiate",
":",
"# We loop over the status we have to initiate.",
"try",
":",
"# We try to update the counters by using the currently read status.",
"PyFunceble",
".",
"INTERN",
"[",
"\"counter\"",
"]",
"[",
"\"number\"",
"]",
".",
"update",
"(",
"{",
"string",
":",
"self",
".",
"backup_content",
"[",
"file_to_restore",
"]",
"[",
"string",
"]",
"}",
")",
"except",
"KeyError",
":",
"# But if the status is not present, we try with the older index",
"# we mapped previously.",
"PyFunceble",
".",
"INTERN",
"[",
"\"counter\"",
"]",
"[",
"\"number\"",
"]",
".",
"update",
"(",
"{",
"string",
":",
"self",
".",
"backup_content",
"[",
"file_to_restore",
"]",
"[",
"alternatives",
"[",
"string",
"]",
"]",
"}",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
AdBlock._is_to_ignore
|
Check if we have to ignore the given line.
:param line: The line from the file.
:type line: str
|
PyFunceble/adblock.py
|
def _is_to_ignore(cls, line):
"""
Check if we have to ignore the given line.
:param line: The line from the file.
:type line: str
"""
# We set the list of regex to match to be
# considered as ignored.
to_ignore = [r"(^!|^@@|^\/|^\[|^\.|^-|^_|^\?|^&)"] # , r"(\$|,)(image)"]
for element in to_ignore:
# We loop through the list of regex.
if Regex(line, element, return_data=False).match():
# The currently read line match the currently read
# regex.
# We return true, it has to be ignored.
return True
# Wer return False, it does not has to be ignored.
return False
|
def _is_to_ignore(cls, line):
"""
Check if we have to ignore the given line.
:param line: The line from the file.
:type line: str
"""
# We set the list of regex to match to be
# considered as ignored.
to_ignore = [r"(^!|^@@|^\/|^\[|^\.|^-|^_|^\?|^&)"] # , r"(\$|,)(image)"]
for element in to_ignore:
# We loop through the list of regex.
if Regex(line, element, return_data=False).match():
# The currently read line match the currently read
# regex.
# We return true, it has to be ignored.
return True
# Wer return False, it does not has to be ignored.
return False
|
[
"Check",
"if",
"we",
"have",
"to",
"ignore",
"the",
"given",
"line",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/adblock.py#L106-L129
|
[
"def",
"_is_to_ignore",
"(",
"cls",
",",
"line",
")",
":",
"# We set the list of regex to match to be",
"# considered as ignored.",
"to_ignore",
"=",
"[",
"r\"(^!|^@@|^\\/|^\\[|^\\.|^-|^_|^\\?|^&)\"",
"]",
"# , r\"(\\$|,)(image)\"]",
"for",
"element",
"in",
"to_ignore",
":",
"# We loop through the list of regex.",
"if",
"Regex",
"(",
"line",
",",
"element",
",",
"return_data",
"=",
"False",
")",
".",
"match",
"(",
")",
":",
"# The currently read line match the currently read",
"# regex.",
"# We return true, it has to be ignored.",
"return",
"True",
"# Wer return False, it does not has to be ignored.",
"return",
"False"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
AdBlock._handle_options
|
Handle the data from the options.
:param options: The list of options from the rule.
:type options: list
:return: The list of domains to return globally.
:rtype: list
|
PyFunceble/adblock.py
|
def _handle_options(self, options):
"""
Handle the data from the options.
:param options: The list of options from the rule.
:type options: list
:return: The list of domains to return globally.
:rtype: list
"""
# We initiate a variable which will save our result
result = []
# We initiate the regex which will be used to extract the domain listed
# under the option domain=
regex_domain_option = r"domain=(.*)"
for option in options:
# We loop through the list of option.
try:
# We try to extract the list of domains from the currently read
# option.
domains = Regex(
option, regex_domain_option, return_data=True, rematch=True, group=0
).match()[-1]
if domains:
# We could extract something.
if self.aggressive: # pragma: no cover
result.extend(
[
x
for x in domains.split("|")
if x and not x.startswith("~")
]
)
else:
# We return True.
return True
except TypeError:
pass
# We return the result.
return result
|
def _handle_options(self, options):
"""
Handle the data from the options.
:param options: The list of options from the rule.
:type options: list
:return: The list of domains to return globally.
:rtype: list
"""
# We initiate a variable which will save our result
result = []
# We initiate the regex which will be used to extract the domain listed
# under the option domain=
regex_domain_option = r"domain=(.*)"
for option in options:
# We loop through the list of option.
try:
# We try to extract the list of domains from the currently read
# option.
domains = Regex(
option, regex_domain_option, return_data=True, rematch=True, group=0
).match()[-1]
if domains:
# We could extract something.
if self.aggressive: # pragma: no cover
result.extend(
[
x
for x in domains.split("|")
if x and not x.startswith("~")
]
)
else:
# We return True.
return True
except TypeError:
pass
# We return the result.
return result
|
[
"Handle",
"the",
"data",
"from",
"the",
"options",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/adblock.py#L131-L176
|
[
"def",
"_handle_options",
"(",
"self",
",",
"options",
")",
":",
"# We initiate a variable which will save our result",
"result",
"=",
"[",
"]",
"# We initiate the regex which will be used to extract the domain listed",
"# under the option domain=",
"regex_domain_option",
"=",
"r\"domain=(.*)\"",
"for",
"option",
"in",
"options",
":",
"# We loop through the list of option.",
"try",
":",
"# We try to extract the list of domains from the currently read",
"# option.",
"domains",
"=",
"Regex",
"(",
"option",
",",
"regex_domain_option",
",",
"return_data",
"=",
"True",
",",
"rematch",
"=",
"True",
",",
"group",
"=",
"0",
")",
".",
"match",
"(",
")",
"[",
"-",
"1",
"]",
"if",
"domains",
":",
"# We could extract something.",
"if",
"self",
".",
"aggressive",
":",
"# pragma: no cover",
"result",
".",
"extend",
"(",
"[",
"x",
"for",
"x",
"in",
"domains",
".",
"split",
"(",
"\"|\"",
")",
"if",
"x",
"and",
"not",
"x",
".",
"startswith",
"(",
"\"~\"",
")",
"]",
")",
"else",
":",
"# We return True.",
"return",
"True",
"except",
"TypeError",
":",
"pass",
"# We return the result.",
"return",
"result"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
AdBlock._extract_base
|
Extract the base of the given element.
.. example:
given "hello/world?world=beautiful" return "hello"
:param element: The element we are working with.
:type element: str|list
|
PyFunceble/adblock.py
|
def _extract_base(self, element):
"""
Extract the base of the given element.
.. example:
given "hello/world?world=beautiful" return "hello"
:param element: The element we are working with.
:type element: str|list
"""
if isinstance(element, list):
# The given element is a list.
# We get the base of each element of the list.
return [self._extract_base(x) for x in element]
# We get the base if it is an URL.
base = self.checker.is_url_valid(url=element, return_base=True)
if base:
# It is an URL.
# We return the extracted base.
return base
if "/" in element:
# / is in the given element.
# We return the first element before the
# first /
return element.split("/")[0]
# / is not in the given element.
# We return the given element.
return element
|
def _extract_base(self, element):
"""
Extract the base of the given element.
.. example:
given "hello/world?world=beautiful" return "hello"
:param element: The element we are working with.
:type element: str|list
"""
if isinstance(element, list):
# The given element is a list.
# We get the base of each element of the list.
return [self._extract_base(x) for x in element]
# We get the base if it is an URL.
base = self.checker.is_url_valid(url=element, return_base=True)
if base:
# It is an URL.
# We return the extracted base.
return base
if "/" in element:
# / is in the given element.
# We return the first element before the
# first /
return element.split("/")[0]
# / is not in the given element.
# We return the given element.
return element
|
[
"Extract",
"the",
"base",
"of",
"the",
"given",
"element",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/adblock.py#L178-L214
|
[
"def",
"_extract_base",
"(",
"self",
",",
"element",
")",
":",
"if",
"isinstance",
"(",
"element",
",",
"list",
")",
":",
"# The given element is a list.",
"# We get the base of each element of the list.",
"return",
"[",
"self",
".",
"_extract_base",
"(",
"x",
")",
"for",
"x",
"in",
"element",
"]",
"# We get the base if it is an URL.",
"base",
"=",
"self",
".",
"checker",
".",
"is_url_valid",
"(",
"url",
"=",
"element",
",",
"return_base",
"=",
"True",
")",
"if",
"base",
":",
"# It is an URL.",
"# We return the extracted base.",
"return",
"base",
"if",
"\"/\"",
"in",
"element",
":",
"# / is in the given element.",
"# We return the first element before the",
"# first /",
"return",
"element",
".",
"split",
"(",
"\"/\"",
")",
"[",
"0",
"]",
"# / is not in the given element.",
"# We return the given element.",
"return",
"element"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
AdBlock.decode
|
Decode/extract the domains to test from the adblock formated file.
:return: The list of domains to test.
:rtype: list
|
PyFunceble/adblock.py
|
def decode(self):
"""
Decode/extract the domains to test from the adblock formated file.
:return: The list of domains to test.
:rtype: list
"""
# We initiate a variable which will save what we are going to return.
result = []
# We initiate the first regex we are going to use to get
# the element to format.
regex = r"^(?:.*\|\|)([^\/\$\^]{1,}).*$"
# We initiate the third regex we are going to use to get
# the element to format.
regex_v3 = (
r"(?:#+(?:[a-z]+?)?\[[a-z]+(?:\^|\*)\=(?:\'|\"))(.*\..*)(?:(?:\'|\")\])"
)
# We initiate the fourth regex we are going to use to get
# the element to format.
regex_v4 = r"^\|(.*\..*)\|$"
for line in self.to_format:
# We loop through the different line.
rematch = rematch_v3 = rematch_v4 = None
# We extract the different group from our first regex.
rematch = Regex(
line, regex, return_data=True, rematch=True, group=0
).match()
# We extract the different group from our fourth regex.
#
# Note: We execute the following in second because it is more
# specific that others.
rematch_v4 = Regex(
line, regex_v4, return_data=True, rematch=True, group=0
).match()
# We extract the different group from our third regex.
rematch_v3 = Regex(
line, regex_v3, return_data=True, rematch=True, group=0
).match()
if rematch:
# The first extraction was successfull.
if self.options_separator in line:
options = line.split(self.options_separator)[-1].split(
self.option_separator
)
if (
not options[-1]
or "third-party" in options
or "script" in options
or "popup" in options
or "xmlhttprequest" in options
):
# We extend the result with the extracted elements.
result.extend(self._extract_base(rematch))
extra = self._handle_options(options)
if extra and isinstance(extra, list): # pragma: no cover
extra.extend(self._extract_base(rematch))
result.extend(self._extract_base(extra))
elif extra:
result.extend(self._extract_base(rematch))
else:
# We extend the result with the extracted elements.
result.extend(self._extract_base(rematch))
if rematch_v4:
# The fourth extraction was successfull.
# We extend the formatted elements from the extracted elements.
result.extend(List(self._format_decoded(rematch_v4)).format())
if rematch_v3:
# The second extraction was successfull.
# We extend the formatted elements from the extracted elements.
result.extend(List(self._format_decoded(rematch_v3)).format())
# We return the result.
return List(result).format()
|
def decode(self):
"""
Decode/extract the domains to test from the adblock formated file.
:return: The list of domains to test.
:rtype: list
"""
# We initiate a variable which will save what we are going to return.
result = []
# We initiate the first regex we are going to use to get
# the element to format.
regex = r"^(?:.*\|\|)([^\/\$\^]{1,}).*$"
# We initiate the third regex we are going to use to get
# the element to format.
regex_v3 = (
r"(?:#+(?:[a-z]+?)?\[[a-z]+(?:\^|\*)\=(?:\'|\"))(.*\..*)(?:(?:\'|\")\])"
)
# We initiate the fourth regex we are going to use to get
# the element to format.
regex_v4 = r"^\|(.*\..*)\|$"
for line in self.to_format:
# We loop through the different line.
rematch = rematch_v3 = rematch_v4 = None
# We extract the different group from our first regex.
rematch = Regex(
line, regex, return_data=True, rematch=True, group=0
).match()
# We extract the different group from our fourth regex.
#
# Note: We execute the following in second because it is more
# specific that others.
rematch_v4 = Regex(
line, regex_v4, return_data=True, rematch=True, group=0
).match()
# We extract the different group from our third regex.
rematch_v3 = Regex(
line, regex_v3, return_data=True, rematch=True, group=0
).match()
if rematch:
# The first extraction was successfull.
if self.options_separator in line:
options = line.split(self.options_separator)[-1].split(
self.option_separator
)
if (
not options[-1]
or "third-party" in options
or "script" in options
or "popup" in options
or "xmlhttprequest" in options
):
# We extend the result with the extracted elements.
result.extend(self._extract_base(rematch))
extra = self._handle_options(options)
if extra and isinstance(extra, list): # pragma: no cover
extra.extend(self._extract_base(rematch))
result.extend(self._extract_base(extra))
elif extra:
result.extend(self._extract_base(rematch))
else:
# We extend the result with the extracted elements.
result.extend(self._extract_base(rematch))
if rematch_v4:
# The fourth extraction was successfull.
# We extend the formatted elements from the extracted elements.
result.extend(List(self._format_decoded(rematch_v4)).format())
if rematch_v3:
# The second extraction was successfull.
# We extend the formatted elements from the extracted elements.
result.extend(List(self._format_decoded(rematch_v3)).format())
# We return the result.
return List(result).format()
|
[
"Decode",
"/",
"extract",
"the",
"domains",
"to",
"test",
"from",
"the",
"adblock",
"formated",
"file",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/adblock.py#L216-L307
|
[
"def",
"decode",
"(",
"self",
")",
":",
"# We initiate a variable which will save what we are going to return.",
"result",
"=",
"[",
"]",
"# We initiate the first regex we are going to use to get",
"# the element to format.",
"regex",
"=",
"r\"^(?:.*\\|\\|)([^\\/\\$\\^]{1,}).*$\"",
"# We initiate the third regex we are going to use to get",
"# the element to format.",
"regex_v3",
"=",
"(",
"r\"(?:#+(?:[a-z]+?)?\\[[a-z]+(?:\\^|\\*)\\=(?:\\'|\\\"))(.*\\..*)(?:(?:\\'|\\\")\\])\"",
")",
"# We initiate the fourth regex we are going to use to get",
"# the element to format.",
"regex_v4",
"=",
"r\"^\\|(.*\\..*)\\|$\"",
"for",
"line",
"in",
"self",
".",
"to_format",
":",
"# We loop through the different line.",
"rematch",
"=",
"rematch_v3",
"=",
"rematch_v4",
"=",
"None",
"# We extract the different group from our first regex.",
"rematch",
"=",
"Regex",
"(",
"line",
",",
"regex",
",",
"return_data",
"=",
"True",
",",
"rematch",
"=",
"True",
",",
"group",
"=",
"0",
")",
".",
"match",
"(",
")",
"# We extract the different group from our fourth regex.",
"#",
"# Note: We execute the following in second because it is more",
"# specific that others.",
"rematch_v4",
"=",
"Regex",
"(",
"line",
",",
"regex_v4",
",",
"return_data",
"=",
"True",
",",
"rematch",
"=",
"True",
",",
"group",
"=",
"0",
")",
".",
"match",
"(",
")",
"# We extract the different group from our third regex.",
"rematch_v3",
"=",
"Regex",
"(",
"line",
",",
"regex_v3",
",",
"return_data",
"=",
"True",
",",
"rematch",
"=",
"True",
",",
"group",
"=",
"0",
")",
".",
"match",
"(",
")",
"if",
"rematch",
":",
"# The first extraction was successfull.",
"if",
"self",
".",
"options_separator",
"in",
"line",
":",
"options",
"=",
"line",
".",
"split",
"(",
"self",
".",
"options_separator",
")",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"self",
".",
"option_separator",
")",
"if",
"(",
"not",
"options",
"[",
"-",
"1",
"]",
"or",
"\"third-party\"",
"in",
"options",
"or",
"\"script\"",
"in",
"options",
"or",
"\"popup\"",
"in",
"options",
"or",
"\"xmlhttprequest\"",
"in",
"options",
")",
":",
"# We extend the result with the extracted elements.",
"result",
".",
"extend",
"(",
"self",
".",
"_extract_base",
"(",
"rematch",
")",
")",
"extra",
"=",
"self",
".",
"_handle_options",
"(",
"options",
")",
"if",
"extra",
"and",
"isinstance",
"(",
"extra",
",",
"list",
")",
":",
"# pragma: no cover",
"extra",
".",
"extend",
"(",
"self",
".",
"_extract_base",
"(",
"rematch",
")",
")",
"result",
".",
"extend",
"(",
"self",
".",
"_extract_base",
"(",
"extra",
")",
")",
"elif",
"extra",
":",
"result",
".",
"extend",
"(",
"self",
".",
"_extract_base",
"(",
"rematch",
")",
")",
"else",
":",
"# We extend the result with the extracted elements.",
"result",
".",
"extend",
"(",
"self",
".",
"_extract_base",
"(",
"rematch",
")",
")",
"if",
"rematch_v4",
":",
"# The fourth extraction was successfull.",
"# We extend the formatted elements from the extracted elements.",
"result",
".",
"extend",
"(",
"List",
"(",
"self",
".",
"_format_decoded",
"(",
"rematch_v4",
")",
")",
".",
"format",
"(",
")",
")",
"if",
"rematch_v3",
":",
"# The second extraction was successfull.",
"# We extend the formatted elements from the extracted elements.",
"result",
".",
"extend",
"(",
"List",
"(",
"self",
".",
"_format_decoded",
"(",
"rematch_v3",
")",
")",
".",
"format",
"(",
")",
")",
"# We return the result.",
"return",
"List",
"(",
"result",
")",
".",
"format",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
AdBlock._format_decoded
|
Format the exctracted adblock line before passing it to the system.
:param to_format: The extracted line from the file.
:type to_format: str
:param result: A list of the result of this method.
:type result: list
:return: The list of domains or IP to test.
:rtype: list
|
PyFunceble/adblock.py
|
def _format_decoded(self, to_format, result=None): # pragma: no cover
"""
Format the exctracted adblock line before passing it to the system.
:param to_format: The extracted line from the file.
:type to_format: str
:param result: A list of the result of this method.
:type result: list
:return: The list of domains or IP to test.
:rtype: list
"""
if not result:
# The result is not given.
# We set the result as an empty list.
result = []
for data in List(to_format).format():
# We loop through the different lines to format.
if data:
# The currently read line is not empty.
if "^" in data:
# There is an accent in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("^"), result)
if "#" in data:
# There is a dash in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("#"), result)
if "," in data:
# There is a comma in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split(","), result)
if "!" in data:
# There is an exclamation mark in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("!"), result)
if "|" in data:
# There is a vertival bar in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("|"), result)
if data:
# The currently read line is not empty.
data = self._extract_base(data)
if data and (
self.checker.is_domain_valid(data)
or self.checker.is_ip_valid(data)
):
# The extraced base is not empty.
# and
# * The currently read line is a valid domain.
# or
# * The currently read line is a valid IP.
# We append the currently read line to the result.
result.append(data)
elif data:
# * The currently read line is not a valid domain.
# or
# * The currently read line is not a valid IP.
# We try to get the url base.
url_base = self.checker.is_url_valid(data, return_base=True)
if url_base:
# The url_base is not empty or equal to False or None.
# We append the url base to the result.
result.append(url_base)
# We return the result element.
return result
|
def _format_decoded(self, to_format, result=None): # pragma: no cover
"""
Format the exctracted adblock line before passing it to the system.
:param to_format: The extracted line from the file.
:type to_format: str
:param result: A list of the result of this method.
:type result: list
:return: The list of domains or IP to test.
:rtype: list
"""
if not result:
# The result is not given.
# We set the result as an empty list.
result = []
for data in List(to_format).format():
# We loop through the different lines to format.
if data:
# The currently read line is not empty.
if "^" in data:
# There is an accent in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("^"), result)
if "#" in data:
# There is a dash in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("#"), result)
if "," in data:
# There is a comma in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split(","), result)
if "!" in data:
# There is an exclamation mark in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("!"), result)
if "|" in data:
# There is a vertival bar in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("|"), result)
if data:
# The currently read line is not empty.
data = self._extract_base(data)
if data and (
self.checker.is_domain_valid(data)
or self.checker.is_ip_valid(data)
):
# The extraced base is not empty.
# and
# * The currently read line is a valid domain.
# or
# * The currently read line is a valid IP.
# We append the currently read line to the result.
result.append(data)
elif data:
# * The currently read line is not a valid domain.
# or
# * The currently read line is not a valid IP.
# We try to get the url base.
url_base = self.checker.is_url_valid(data, return_base=True)
if url_base:
# The url_base is not empty or equal to False or None.
# We append the url base to the result.
result.append(url_base)
# We return the result element.
return result
|
[
"Format",
"the",
"exctracted",
"adblock",
"line",
"before",
"passing",
"it",
"to",
"the",
"system",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/adblock.py#L309-L402
|
[
"def",
"_format_decoded",
"(",
"self",
",",
"to_format",
",",
"result",
"=",
"None",
")",
":",
"# pragma: no cover",
"if",
"not",
"result",
":",
"# The result is not given.",
"# We set the result as an empty list.",
"result",
"=",
"[",
"]",
"for",
"data",
"in",
"List",
"(",
"to_format",
")",
".",
"format",
"(",
")",
":",
"# We loop through the different lines to format.",
"if",
"data",
":",
"# The currently read line is not empty.",
"if",
"\"^\"",
"in",
"data",
":",
"# There is an accent in the currently read line.",
"# We recall this method but with the current result state",
"# and splited data.",
"return",
"self",
".",
"_format_decoded",
"(",
"data",
".",
"split",
"(",
"\"^\"",
")",
",",
"result",
")",
"if",
"\"#\"",
"in",
"data",
":",
"# There is a dash in the currently read line.",
"# We recall this method but with the current result state",
"# and splited data.",
"return",
"self",
".",
"_format_decoded",
"(",
"data",
".",
"split",
"(",
"\"#\"",
")",
",",
"result",
")",
"if",
"\",\"",
"in",
"data",
":",
"# There is a comma in the currently read line.",
"# We recall this method but with the current result state",
"# and splited data.",
"return",
"self",
".",
"_format_decoded",
"(",
"data",
".",
"split",
"(",
"\",\"",
")",
",",
"result",
")",
"if",
"\"!\"",
"in",
"data",
":",
"# There is an exclamation mark in the currently read line.",
"# We recall this method but with the current result state",
"# and splited data.",
"return",
"self",
".",
"_format_decoded",
"(",
"data",
".",
"split",
"(",
"\"!\"",
")",
",",
"result",
")",
"if",
"\"|\"",
"in",
"data",
":",
"# There is a vertival bar in the currently read line.",
"# We recall this method but with the current result state",
"# and splited data.",
"return",
"self",
".",
"_format_decoded",
"(",
"data",
".",
"split",
"(",
"\"|\"",
")",
",",
"result",
")",
"if",
"data",
":",
"# The currently read line is not empty.",
"data",
"=",
"self",
".",
"_extract_base",
"(",
"data",
")",
"if",
"data",
"and",
"(",
"self",
".",
"checker",
".",
"is_domain_valid",
"(",
"data",
")",
"or",
"self",
".",
"checker",
".",
"is_ip_valid",
"(",
"data",
")",
")",
":",
"# The extraced base is not empty.",
"# and",
"# * The currently read line is a valid domain.",
"# or",
"# * The currently read line is a valid IP.",
"# We append the currently read line to the result.",
"result",
".",
"append",
"(",
"data",
")",
"elif",
"data",
":",
"# * The currently read line is not a valid domain.",
"# or",
"# * The currently read line is not a valid IP.",
"# We try to get the url base.",
"url_base",
"=",
"self",
".",
"checker",
".",
"is_url_valid",
"(",
"data",
",",
"return_base",
"=",
"True",
")",
"if",
"url_base",
":",
"# The url_base is not empty or equal to False or None.",
"# We append the url base to the result.",
"result",
".",
"append",
"(",
"url_base",
")",
"# We return the result element.",
"return",
"result"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
HTTPCode._access
|
Get the HTTP code status.
:return: The matched HTTP status code.
:rtype: int|None
|
PyFunceble/http_code.py
|
def _access(self): # pragma: no cover
"""
Get the HTTP code status.
:return: The matched HTTP status code.
:rtype: int|None
"""
try:
# We try to get the HTTP status code.
if PyFunceble.INTERN["to_test_type"] == "url":
# We are globally testing a URL.
# We get the head of the URL.
req = PyFunceble.requests.head(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
headers=self.headers,
verify=PyFunceble.CONFIGURATION["verify_ssl_certificate"],
)
else:
# We are not globally testing a URL.
# We get the head of the constructed URL.
req = PyFunceble.requests.head(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
headers=self.headers,
)
# And we try to get the status code.
return req.status_code
except (
PyFunceble.requests.exceptions.InvalidURL,
PyFunceble.socket.timeout,
PyFunceble.requests.exceptions.Timeout,
PyFunceble.requests.ConnectionError,
urllib3_exceptions.InvalidHeader,
UnicodeDecodeError, # The probability that this happend in production is minimal.
):
# If one of the listed exception is matched, that means that something
# went wrong and we were unable to extract the status code.
# We return None.
return None
|
def _access(self): # pragma: no cover
"""
Get the HTTP code status.
:return: The matched HTTP status code.
:rtype: int|None
"""
try:
# We try to get the HTTP status code.
if PyFunceble.INTERN["to_test_type"] == "url":
# We are globally testing a URL.
# We get the head of the URL.
req = PyFunceble.requests.head(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
headers=self.headers,
verify=PyFunceble.CONFIGURATION["verify_ssl_certificate"],
)
else:
# We are not globally testing a URL.
# We get the head of the constructed URL.
req = PyFunceble.requests.head(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
headers=self.headers,
)
# And we try to get the status code.
return req.status_code
except (
PyFunceble.requests.exceptions.InvalidURL,
PyFunceble.socket.timeout,
PyFunceble.requests.exceptions.Timeout,
PyFunceble.requests.ConnectionError,
urllib3_exceptions.InvalidHeader,
UnicodeDecodeError, # The probability that this happend in production is minimal.
):
# If one of the listed exception is matched, that means that something
# went wrong and we were unable to extract the status code.
# We return None.
return None
|
[
"Get",
"the",
"HTTP",
"code",
"status",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/http_code.py#L109-L155
|
[
"def",
"_access",
"(",
"self",
")",
":",
"# pragma: no cover",
"try",
":",
"# We try to get the HTTP status code.",
"if",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test_type\"",
"]",
"==",
"\"url\"",
":",
"# We are globally testing a URL.",
"# We get the head of the URL.",
"req",
"=",
"PyFunceble",
".",
"requests",
".",
"head",
"(",
"self",
".",
"to_get",
",",
"timeout",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"seconds_before_http_timeout\"",
"]",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"verify",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"verify_ssl_certificate\"",
"]",
",",
")",
"else",
":",
"# We are not globally testing a URL.",
"# We get the head of the constructed URL.",
"req",
"=",
"PyFunceble",
".",
"requests",
".",
"head",
"(",
"self",
".",
"to_get",
",",
"timeout",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"seconds_before_http_timeout\"",
"]",
",",
"headers",
"=",
"self",
".",
"headers",
",",
")",
"# And we try to get the status code.",
"return",
"req",
".",
"status_code",
"except",
"(",
"PyFunceble",
".",
"requests",
".",
"exceptions",
".",
"InvalidURL",
",",
"PyFunceble",
".",
"socket",
".",
"timeout",
",",
"PyFunceble",
".",
"requests",
".",
"exceptions",
".",
"Timeout",
",",
"PyFunceble",
".",
"requests",
".",
"ConnectionError",
",",
"urllib3_exceptions",
".",
"InvalidHeader",
",",
"UnicodeDecodeError",
",",
"# The probability that this happend in production is minimal.",
")",
":",
"# If one of the listed exception is matched, that means that something",
"# went wrong and we were unable to extract the status code.",
"# We return None.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
HTTPCode.get
|
Return the HTTP code status.
:return: The matched and formatted status code.
:rtype: str|int|None
|
PyFunceble/http_code.py
|
def get(self):
"""
Return the HTTP code status.
:return: The matched and formatted status code.
:rtype: str|int|None
"""
if PyFunceble.HTTP_CODE["active"]:
# The http status code extraction is activated.
# We get the http status code.
http_code = self._access()
# We initiate a variable which will save the list of allowed
# http status code.
list_of_valid_http_code = []
for codes in [
PyFunceble.HTTP_CODE["list"]["up"],
PyFunceble.HTTP_CODE["list"]["potentially_down"],
PyFunceble.HTTP_CODE["list"]["potentially_up"],
]:
# We loop throught the list of http status code.
# We extend the list of valid with the currently read
# codes.
list_of_valid_http_code.extend(codes)
if http_code not in list_of_valid_http_code or http_code is None:
# * The extracted http code is not in the list of valid http code.
# or
# * The extracted http code is equal to `None`.
# We return 3 star in order to mention that we were not eable to extract
# the http status code.
return "*" * 3
# * The extracted http code is in the list of valid http code.
# or
# * The extracted http code is not equal to `None`.
# We return the extracted http status code.
return http_code
# The http status code extraction is activated.
# We return None.
return None
|
def get(self):
"""
Return the HTTP code status.
:return: The matched and formatted status code.
:rtype: str|int|None
"""
if PyFunceble.HTTP_CODE["active"]:
# The http status code extraction is activated.
# We get the http status code.
http_code = self._access()
# We initiate a variable which will save the list of allowed
# http status code.
list_of_valid_http_code = []
for codes in [
PyFunceble.HTTP_CODE["list"]["up"],
PyFunceble.HTTP_CODE["list"]["potentially_down"],
PyFunceble.HTTP_CODE["list"]["potentially_up"],
]:
# We loop throught the list of http status code.
# We extend the list of valid with the currently read
# codes.
list_of_valid_http_code.extend(codes)
if http_code not in list_of_valid_http_code or http_code is None:
# * The extracted http code is not in the list of valid http code.
# or
# * The extracted http code is equal to `None`.
# We return 3 star in order to mention that we were not eable to extract
# the http status code.
return "*" * 3
# * The extracted http code is in the list of valid http code.
# or
# * The extracted http code is not equal to `None`.
# We return the extracted http status code.
return http_code
# The http status code extraction is activated.
# We return None.
return None
|
[
"Return",
"the",
"HTTP",
"code",
"status",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/http_code.py#L157-L204
|
[
"def",
"get",
"(",
"self",
")",
":",
"if",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"active\"",
"]",
":",
"# The http status code extraction is activated.",
"# We get the http status code.",
"http_code",
"=",
"self",
".",
"_access",
"(",
")",
"# We initiate a variable which will save the list of allowed",
"# http status code.",
"list_of_valid_http_code",
"=",
"[",
"]",
"for",
"codes",
"in",
"[",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"list\"",
"]",
"[",
"\"up\"",
"]",
",",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"list\"",
"]",
"[",
"\"potentially_down\"",
"]",
",",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"list\"",
"]",
"[",
"\"potentially_up\"",
"]",
",",
"]",
":",
"# We loop throught the list of http status code.",
"# We extend the list of valid with the currently read",
"# codes.",
"list_of_valid_http_code",
".",
"extend",
"(",
"codes",
")",
"if",
"http_code",
"not",
"in",
"list_of_valid_http_code",
"or",
"http_code",
"is",
"None",
":",
"# * The extracted http code is not in the list of valid http code.",
"# or",
"# * The extracted http code is equal to `None`.",
"# We return 3 star in order to mention that we were not eable to extract",
"# the http status code.",
"return",
"\"*\"",
"*",
"3",
"# * The extracted http code is in the list of valid http code.",
"# or",
"# * The extracted http code is not equal to `None`.",
"# We return the extracted http status code.",
"return",
"http_code",
"# The http status code extraction is activated.",
"# We return None.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
syntax_check
|
Check the syntax of the given domain.
:param domain: The domain to check the syntax for.
:type domain: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
|
PyFunceble/__init__.py
|
def syntax_check(domain): # pragma: no cover
"""
Check the syntax of the given domain.
:param domain: The domain to check the syntax for.
:type domain: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
"""
if domain and isinstance(domain, str):
# * The given domain is not empty nor None.
# and
# * The given domain is a string.
# We silently load the configuration.
load_config(True)
return Check(domain).is_domain_valid()
# We return None, there is nothing to check.
return None
|
def syntax_check(domain): # pragma: no cover
"""
Check the syntax of the given domain.
:param domain: The domain to check the syntax for.
:type domain: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
"""
if domain and isinstance(domain, str):
# * The given domain is not empty nor None.
# and
# * The given domain is a string.
# We silently load the configuration.
load_config(True)
return Check(domain).is_domain_valid()
# We return None, there is nothing to check.
return None
|
[
"Check",
"the",
"syntax",
"of",
"the",
"given",
"domain",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L284-L309
|
[
"def",
"syntax_check",
"(",
"domain",
")",
":",
"# pragma: no cover",
"if",
"domain",
"and",
"isinstance",
"(",
"domain",
",",
"str",
")",
":",
"# * The given domain is not empty nor None.",
"# and",
"# * The given domain is a string.",
"# We silently load the configuration.",
"load_config",
"(",
"True",
")",
"return",
"Check",
"(",
"domain",
")",
".",
"is_domain_valid",
"(",
")",
"# We return None, there is nothing to check.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
is_subdomain
|
Check if the given domain is a subdomain.
:param domain: The domain we are checking.
:type domain: str
:return: The subdomain state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
|
PyFunceble/__init__.py
|
def is_subdomain(domain): # pragma: no cover
"""
Check if the given domain is a subdomain.
:param domain: The domain we are checking.
:type domain: str
:return: The subdomain state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
"""
if domain and isinstance(domain, str):
# * The given domain is not empty nor None.
# and
# * The given domain is a string.
# We silently load the configuration.
load_config(True)
return Check(domain).is_subdomain()
# We return None, there is nothing to check.
return None
|
def is_subdomain(domain): # pragma: no cover
"""
Check if the given domain is a subdomain.
:param domain: The domain we are checking.
:type domain: str
:return: The subdomain state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
"""
if domain and isinstance(domain, str):
# * The given domain is not empty nor None.
# and
# * The given domain is a string.
# We silently load the configuration.
load_config(True)
return Check(domain).is_subdomain()
# We return None, there is nothing to check.
return None
|
[
"Check",
"if",
"the",
"given",
"domain",
"is",
"a",
"subdomain",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L312-L337
|
[
"def",
"is_subdomain",
"(",
"domain",
")",
":",
"# pragma: no cover",
"if",
"domain",
"and",
"isinstance",
"(",
"domain",
",",
"str",
")",
":",
"# * The given domain is not empty nor None.",
"# and",
"# * The given domain is a string.",
"# We silently load the configuration.",
"load_config",
"(",
"True",
")",
"return",
"Check",
"(",
"domain",
")",
".",
"is_subdomain",
"(",
")",
"# We return None, there is nothing to check.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
ipv4_syntax_check
|
Check the syntax of the given IPv4.
:param ip: The IPv4 to check the syntax for.
:type ip: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`.
|
PyFunceble/__init__.py
|
def ipv4_syntax_check(ip): # pragma: no cover
"""
Check the syntax of the given IPv4.
:param ip: The IPv4 to check the syntax for.
:type ip: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`.
"""
if ip and isinstance(ip, str):
# The given IP is not empty nor None.
# and
# * The given IP is a string.
# We silently load the configuration.
load_config(True)
return Check(ip).is_ip_valid()
# We return None, there is nothing to check.
return None
|
def ipv4_syntax_check(ip): # pragma: no cover
"""
Check the syntax of the given IPv4.
:param ip: The IPv4 to check the syntax for.
:type ip: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`.
"""
if ip and isinstance(ip, str):
# The given IP is not empty nor None.
# and
# * The given IP is a string.
# We silently load the configuration.
load_config(True)
return Check(ip).is_ip_valid()
# We return None, there is nothing to check.
return None
|
[
"Check",
"the",
"syntax",
"of",
"the",
"given",
"IPv4",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L340-L365
|
[
"def",
"ipv4_syntax_check",
"(",
"ip",
")",
":",
"# pragma: no cover",
"if",
"ip",
"and",
"isinstance",
"(",
"ip",
",",
"str",
")",
":",
"# The given IP is not empty nor None.",
"# and",
"# * The given IP is a string.",
"# We silently load the configuration.",
"load_config",
"(",
"True",
")",
"return",
"Check",
"(",
"ip",
")",
".",
"is_ip_valid",
"(",
")",
"# We return None, there is nothing to check.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
is_ipv4_range
|
Check if the given IP is an IP range.
:param ip: The IP we are checking.
:type ip: str
:return: The IPv4 range state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`.
|
PyFunceble/__init__.py
|
def is_ipv4_range(ip): # pragma: no cover
"""
Check if the given IP is an IP range.
:param ip: The IP we are checking.
:type ip: str
:return: The IPv4 range state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`.
"""
if ip and isinstance(ip, str):
# The given IP is not empty nor None.
# and
# * The given IP is a string.
# We silently load the configuration.
load_config(True)
return Check(ip).is_ip_range()
# We return None, there is nothing to check.
return None
|
def is_ipv4_range(ip): # pragma: no cover
"""
Check if the given IP is an IP range.
:param ip: The IP we are checking.
:type ip: str
:return: The IPv4 range state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we return :code:`None`.
"""
if ip and isinstance(ip, str):
# The given IP is not empty nor None.
# and
# * The given IP is a string.
# We silently load the configuration.
load_config(True)
return Check(ip).is_ip_range()
# We return None, there is nothing to check.
return None
|
[
"Check",
"if",
"the",
"given",
"IP",
"is",
"an",
"IP",
"range",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L368-L393
|
[
"def",
"is_ipv4_range",
"(",
"ip",
")",
":",
"# pragma: no cover",
"if",
"ip",
"and",
"isinstance",
"(",
"ip",
",",
"str",
")",
":",
"# The given IP is not empty nor None.",
"# and",
"# * The given IP is a string.",
"# We silently load the configuration.",
"load_config",
"(",
"True",
")",
"return",
"Check",
"(",
"ip",
")",
".",
"is_ip_range",
"(",
")",
"# We return None, there is nothing to check.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
url_syntax_check
|
Check the syntax of the given URL.
:param url: The URL to check the syntax for.
:type url: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`url` is given, we return :code:`None`.
|
PyFunceble/__init__.py
|
def url_syntax_check(url): # pragma: no cover
"""
Check the syntax of the given URL.
:param url: The URL to check the syntax for.
:type url: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`url` is given, we return :code:`None`.
"""
if url and isinstance(url, str):
# The given URL is not empty nor None.
# and
# * The given URL is a string.
# We silently load the configuration.
load_config(True)
return Check(url).is_url_valid()
# We return None, there is nothing to check.
return None
|
def url_syntax_check(url): # pragma: no cover
"""
Check the syntax of the given URL.
:param url: The URL to check the syntax for.
:type url: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`url` is given, we return :code:`None`.
"""
if url and isinstance(url, str):
# The given URL is not empty nor None.
# and
# * The given URL is a string.
# We silently load the configuration.
load_config(True)
return Check(url).is_url_valid()
# We return None, there is nothing to check.
return None
|
[
"Check",
"the",
"syntax",
"of",
"the",
"given",
"URL",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L396-L421
|
[
"def",
"url_syntax_check",
"(",
"url",
")",
":",
"# pragma: no cover",
"if",
"url",
"and",
"isinstance",
"(",
"url",
",",
"str",
")",
":",
"# The given URL is not empty nor None.",
"# and",
"# * The given URL is a string.",
"# We silently load the configuration.",
"load_config",
"(",
"True",
")",
"return",
"Check",
"(",
"url",
")",
".",
"is_url_valid",
"(",
")",
"# We return None, there is nothing to check.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
load_config
|
Load the configuration.
:param under_test:
Tell us if we only have to load the configuration file (True)
or load the configuration file and initate the output directory
if it does not exist (False).
:type under_test: bool
:param custom:
A dict with the configuration index (from .PyFunceble.yaml) to update.
:type custom: dict
.. warning::
If :code:`custom` is given, the given :code:`dict` overwrite
the last value of the given configuration indexes.
|
PyFunceble/__init__.py
|
def load_config(under_test=False, custom=None): # pragma: no cover
"""
Load the configuration.
:param under_test:
Tell us if we only have to load the configuration file (True)
or load the configuration file and initate the output directory
if it does not exist (False).
:type under_test: bool
:param custom:
A dict with the configuration index (from .PyFunceble.yaml) to update.
:type custom: dict
.. warning::
If :code:`custom` is given, the given :code:`dict` overwrite
the last value of the given configuration indexes.
"""
if "config_loaded" not in INTERN:
# The configuration was not already loaded.
# We load and download the different configuration file if they are non
# existant.
Load(CURRENT_DIRECTORY)
if not under_test:
# If we are not under test which means that we want to save informations,
# we initiate the directory structure.
DirectoryStructure()
# We save that the configuration was loaded.
INTERN.update({"config_loaded": True})
if custom and isinstance(custom, dict):
# The given configuration is not None or empty.
# and
# It is a dict.
# We update the configuration index.
CONFIGURATION.update(custom)
|
def load_config(under_test=False, custom=None): # pragma: no cover
"""
Load the configuration.
:param under_test:
Tell us if we only have to load the configuration file (True)
or load the configuration file and initate the output directory
if it does not exist (False).
:type under_test: bool
:param custom:
A dict with the configuration index (from .PyFunceble.yaml) to update.
:type custom: dict
.. warning::
If :code:`custom` is given, the given :code:`dict` overwrite
the last value of the given configuration indexes.
"""
if "config_loaded" not in INTERN:
# The configuration was not already loaded.
# We load and download the different configuration file if they are non
# existant.
Load(CURRENT_DIRECTORY)
if not under_test:
# If we are not under test which means that we want to save informations,
# we initiate the directory structure.
DirectoryStructure()
# We save that the configuration was loaded.
INTERN.update({"config_loaded": True})
if custom and isinstance(custom, dict):
# The given configuration is not None or empty.
# and
# It is a dict.
# We update the configuration index.
CONFIGURATION.update(custom)
|
[
"Load",
"the",
"configuration",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L475-L515
|
[
"def",
"load_config",
"(",
"under_test",
"=",
"False",
",",
"custom",
"=",
"None",
")",
":",
"# pragma: no cover",
"if",
"\"config_loaded\"",
"not",
"in",
"INTERN",
":",
"# The configuration was not already loaded.",
"# We load and download the different configuration file if they are non",
"# existant.",
"Load",
"(",
"CURRENT_DIRECTORY",
")",
"if",
"not",
"under_test",
":",
"# If we are not under test which means that we want to save informations,",
"# we initiate the directory structure.",
"DirectoryStructure",
"(",
")",
"# We save that the configuration was loaded.",
"INTERN",
".",
"update",
"(",
"{",
"\"config_loaded\"",
":",
"True",
"}",
")",
"if",
"custom",
"and",
"isinstance",
"(",
"custom",
",",
"dict",
")",
":",
"# The given configuration is not None or empty.",
"# and",
"# It is a dict.",
"# We update the configuration index.",
"CONFIGURATION",
".",
"update",
"(",
"custom",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
stay_safe
|
Print a friendly message.
|
PyFunceble/__init__.py
|
def stay_safe(): # pragma: no cover
"""
Print a friendly message.
"""
random = int(choice(str(int(time()))))
if not CONFIGURATION["quiet"] and random % 3 == 0:
print("\n" + Fore.GREEN + Style.BRIGHT + "Thanks for using PyFunceble!")
print(
Fore.YELLOW
+ Style.BRIGHT
+ "Share your experience on "
+ Fore.CYAN
+ "Twitter"
+ Fore.YELLOW
+ " with "
+ Fore.CYAN
+ "#PyFunceble"
+ Fore.YELLOW
+ "!"
)
print(
Fore.GREEN
+ Style.BRIGHT
+ "Have a feedback, an issue or an improvement idea ?"
)
print(
Fore.YELLOW
+ Style.BRIGHT
+ "Let us know on "
+ Fore.CYAN
+ "GitHub"
+ Fore.YELLOW
+ "!"
)
|
def stay_safe(): # pragma: no cover
"""
Print a friendly message.
"""
random = int(choice(str(int(time()))))
if not CONFIGURATION["quiet"] and random % 3 == 0:
print("\n" + Fore.GREEN + Style.BRIGHT + "Thanks for using PyFunceble!")
print(
Fore.YELLOW
+ Style.BRIGHT
+ "Share your experience on "
+ Fore.CYAN
+ "Twitter"
+ Fore.YELLOW
+ " with "
+ Fore.CYAN
+ "#PyFunceble"
+ Fore.YELLOW
+ "!"
)
print(
Fore.GREEN
+ Style.BRIGHT
+ "Have a feedback, an issue or an improvement idea ?"
)
print(
Fore.YELLOW
+ Style.BRIGHT
+ "Let us know on "
+ Fore.CYAN
+ "GitHub"
+ Fore.YELLOW
+ "!"
)
|
[
"Print",
"a",
"friendly",
"message",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L518-L553
|
[
"def",
"stay_safe",
"(",
")",
":",
"# pragma: no cover",
"random",
"=",
"int",
"(",
"choice",
"(",
"str",
"(",
"int",
"(",
"time",
"(",
")",
")",
")",
")",
")",
"if",
"not",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
"and",
"random",
"%",
"3",
"==",
"0",
":",
"print",
"(",
"\"\\n\"",
"+",
"Fore",
".",
"GREEN",
"+",
"Style",
".",
"BRIGHT",
"+",
"\"Thanks for using PyFunceble!\"",
")",
"print",
"(",
"Fore",
".",
"YELLOW",
"+",
"Style",
".",
"BRIGHT",
"+",
"\"Share your experience on \"",
"+",
"Fore",
".",
"CYAN",
"+",
"\"Twitter\"",
"+",
"Fore",
".",
"YELLOW",
"+",
"\" with \"",
"+",
"Fore",
".",
"CYAN",
"+",
"\"#PyFunceble\"",
"+",
"Fore",
".",
"YELLOW",
"+",
"\"!\"",
")",
"print",
"(",
"Fore",
".",
"GREEN",
"+",
"Style",
".",
"BRIGHT",
"+",
"\"Have a feedback, an issue or an improvement idea ?\"",
")",
"print",
"(",
"Fore",
".",
"YELLOW",
"+",
"Style",
".",
"BRIGHT",
"+",
"\"Let us know on \"",
"+",
"Fore",
".",
"CYAN",
"+",
"\"GitHub\"",
"+",
"Fore",
".",
"YELLOW",
"+",
"\"!\"",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
_command_line
|
Provide the command line interface.
|
PyFunceble/__init__.py
|
def _command_line(): # pragma: no cover pylint: disable=too-many-branches,too-many-statements
"""
Provide the command line interface.
"""
if __name__ == "PyFunceble":
# We initiate the end of the coloration at the end of each line.
initiate(autoreset=True)
# We load the configuration and the directory structure.
load_config(True)
try:
# The following handle the command line argument.
try:
PARSER = argparse.ArgumentParser(
epilog="Crafted with %s by %s"
% (
Fore.RED + "♥" + Fore.RESET,
Style.BRIGHT
+ Fore.CYAN
+ "Nissar Chababy (Funilrys) "
+ Style.RESET_ALL
+ "with the help of "
+ Style.BRIGHT
+ Fore.GREEN
+ "https://pyfunceble.rtfd.io/en/master/contributors.html "
+ Style.RESET_ALL
+ "&& "
+ Style.BRIGHT
+ Fore.GREEN
+ "https://pyfunceble.rtfd.io/en/master/special-thanks.html",
),
add_help=False,
)
CURRENT_VALUE_FORMAT = (
Fore.YELLOW + Style.BRIGHT + "Configured value: " + Fore.BLUE
)
PARSER.add_argument(
"-ad",
"--adblock",
action="store_true",
help="Switch the decoding of the adblock format. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["adblock"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-a",
"--all",
action="store_false",
help="Output all available information on the screen. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["less"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"" "-c",
"--auto-continue",
"--continue",
action="store_true",
help="Switch the value of the auto continue mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["auto_continue"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--autosave-minutes",
type=int,
help="Update the minimum of minutes before we start "
"committing to upstream under Travis CI. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis_autosave_minutes"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--clean", action="store_true", help="Clean all files under output."
)
PARSER.add_argument(
"--clean-all",
action="store_true",
help="Clean all files under output and all file generated by PyFunceble.",
)
PARSER.add_argument(
"--cmd",
type=str,
help="Pass a command to run before each commit "
"(except the final one) under the Travis mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["command_before_end"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--cmd-before-end",
type=str,
help="Pass a command to run before the results "
"(final) commit under the Travis mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["command_before_end"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--commit-autosave-message",
type=str,
help="Replace the default autosave commit message. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis_autosave_commit"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--commit-results-message",
type=str,
help="Replace the default results (final) commit message. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis_autosave_final_commit"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-d", "--domain", type=str, help="Set and test the given domain."
)
PARSER.add_argument(
"-db",
"--database",
action="store_true",
help="Switch the value of the usage of a database to store "
"inactive domains of the currently tested list. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["inactive_database"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-dbr",
"--days-between-db-retest",
type=int,
help="Set the numbers of days between each retest of domains present "
"into inactive-db.json. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["days_between_db_retest"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--debug",
action="store_true",
help="Switch the value of the debug mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["debug"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--directory-structure",
action="store_true",
help="Generate the directory and files that are needed and which does "
"not exist in the current directory.",
)
PARSER.add_argument(
"-ex",
"--execution",
action="store_true",
help="Switch the default value of the execution time showing. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["show_execution_time"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-f",
"--file",
type=str,
help="Read the given file and test all domains inside it. "
"If a URL is given we download and test the content of the given URL.", # pylint: disable=line-too-long
)
PARSER.add_argument(
"--filter", type=str, help="Domain to filter (regex)."
)
PARSER.add_argument(
"--help",
action="help",
default=argparse.SUPPRESS,
help="Show this help message and exit.",
)
PARSER.add_argument(
"--hierarchical",
action="store_true",
help="Switch the value of the hierarchical sorting of the tested file. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["hierarchical_sorting"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-h",
"--host",
action="store_true",
help="Switch the value of the generation of hosts file. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["generate_hosts"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--http",
action="store_true",
help="Switch the value of the usage of HTTP code. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(HTTP_CODE["active"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--iana",
action="store_true",
help="Update/Generate `iana-domains-db.json`.",
)
PARSER.add_argument(
"--idna",
action="store_true",
help="Switch the value of the IDNA conversion. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["idna_conversion"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-ip",
type=str,
help="Change the IP to print in the hosts files with the given one. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["custom_ip"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--json",
action="store_true",
help="Switch the value of the generation "
"of the JSON formatted list of domains. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["generate_json"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--less",
action="store_true",
help="Output less informations on screen. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(Core.switch("less"))
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--local",
action="store_true",
help="Switch the value of the local network testing. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(Core.switch("local"))
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--link", type=str, help="Download and test the given file."
)
PARSER.add_argument(
"-m",
"--mining",
action="store_true",
help="Switch the value of the mining subsystem usage. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["mining"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-n",
"--no-files",
action="store_true",
help="Switch the value of the production of output files. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["no_files"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-nl",
"--no-logs",
action="store_true",
help="Switch the value of the production of logs files "
"in the case we encounter some errors. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(not CONFIGURATION["logs"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-ns",
"--no-special",
action="store_true",
help="Switch the value of the usage of the SPECIAL rules. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["no_special"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-nu",
"--no-unified",
action="store_true",
help="Switch the value of the production unified logs "
"under the output directory. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["unified"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-nw",
"--no-whois",
action="store_true",
help="Switch the value the usage of whois to test domain's status. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["no_whois"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-p",
"--percentage",
action="store_true",
help="Switch the value of the percentage output mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["show_percentage"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--plain",
action="store_true",
help="Switch the value of the generation "
"of the plain list of domains. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["plain_list_domain"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--production",
action="store_true",
help="Prepare the repository for production.",
)
PARSER.add_argument(
"-psl",
"--public-suffix",
action="store_true",
help="Update/Generate `public-suffix.json`.",
)
PARSER.add_argument(
"-q",
"--quiet",
action="store_true",
help="Run the script in quiet mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["quiet"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--share-logs",
action="store_true",
help="Switch the value of the sharing of logs. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["share_logs"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-s",
"--simple",
action="store_true",
help="Switch the value of the simple output mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["simple"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--split",
action="store_true",
help="Switch the value of the split of the generated output files. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["inactive_database"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--syntax",
action="store_true",
help="Switch the value of the syntax test mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["syntax"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-t",
"--timeout",
type=int,
default=3,
help="Switch the value of the timeout. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["seconds_before_http_timeout"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--travis",
action="store_true",
help="Switch the value of the Travis mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--travis-branch",
type=str,
default="master",
help="Switch the branch name where we are going to push. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis_branch"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-u", "--url", type=str, help="Analyze the given URL."
)
PARSER.add_argument(
"-uf",
"--url-file",
type=str,
help="Read and test the list of URL of the given file. "
"If a URL is given we download and test the content of the given URL.", # pylint: disable=line-too-long
)
PARSER.add_argument(
"-ua",
"--user-agent",
type=str,
help="Set the user-agent to use and set every time we "
"interact with everything which is not our logs sharing system.", # pylint: disable=line-too-long
)
PARSER.add_argument(
"-v",
"--version",
help="Show the version of PyFunceble and exit.",
action="version",
version="%(prog)s " + VERSION,
)
PARSER.add_argument(
"-vsc",
"--verify-ssl-certificate",
action="store_true",
help="Switch the value of the verification of the "
"SSL/TLS certificate when testing for URL. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["verify_ssl_certificate"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-wdb",
"--whois-database",
action="store_true",
help="Switch the value of the usage of a database to store "
"whois data in order to avoid whois servers rate limit. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["whois_database"])
+ Style.RESET_ALL
),
)
ARGS = PARSER.parse_args()
if ARGS.less:
CONFIGURATION.update({"less": ARGS.less})
elif not ARGS.all:
CONFIGURATION.update({"less": ARGS.all})
if ARGS.adblock:
CONFIGURATION.update({"adblock": Core.switch("adblock")})
if ARGS.auto_continue:
CONFIGURATION.update(
{"auto_continue": Core.switch("auto_continue")}
)
if ARGS.autosave_minutes:
CONFIGURATION.update(
{"travis_autosave_minutes": ARGS.autosave_minutes}
)
if ARGS.clean:
Clean(None)
if ARGS.clean_all:
Clean(None, ARGS.clean_all)
if ARGS.cmd:
CONFIGURATION.update({"command": ARGS.cmd})
if ARGS.cmd_before_end:
CONFIGURATION.update({"command_before_end": ARGS.cmd_before_end})
if ARGS.commit_autosave_message:
CONFIGURATION.update(
{"travis_autosave_commit": ARGS.commit_autosave_message}
)
if ARGS.commit_results_message:
CONFIGURATION.update(
{"travis_autosave_final_commit": ARGS.commit_results_message}
)
if ARGS.database:
CONFIGURATION.update(
{"inactive_database": Core.switch("inactive_database")}
)
if ARGS.days_between_db_retest:
CONFIGURATION.update(
{"days_between_db_retest": ARGS.days_between_db_retest}
)
if ARGS.debug:
CONFIGURATION.update({"debug": Core.switch("debug")})
if ARGS.directory_structure:
DirectoryStructure()
if ARGS.execution:
CONFIGURATION.update(
{"show_execution_time": Core.switch("show_execution_time")}
)
if ARGS.filter:
CONFIGURATION.update({"filter": ARGS.filter})
if ARGS.hierarchical:
CONFIGURATION.update(
{"hierarchical_sorting": Core.switch("hierarchical_sorting")}
)
if ARGS.host:
CONFIGURATION.update(
{"generate_hosts": Core.switch("generate_hosts")}
)
if ARGS.http:
HTTP_CODE.update({"active": Core.switch(HTTP_CODE["active"], True)})
if ARGS.iana:
IANA().update()
if ARGS.idna:
CONFIGURATION.update(
{"idna_conversion": Core.switch("idna_conversion")}
)
if ARGS.ip:
CONFIGURATION.update({"custom_ip": ARGS.ip})
if ARGS.json:
CONFIGURATION.update(
{"generate_json": Core.switch("generate_json")}
)
if ARGS.local:
CONFIGURATION.update({"local": Core.switch("local")})
if ARGS.mining:
CONFIGURATION.update({"mining": Core.switch("mining")})
if ARGS.no_files:
CONFIGURATION.update({"no_files": Core.switch("no_files")})
if ARGS.no_logs:
CONFIGURATION.update({"logs": Core.switch("logs")})
if ARGS.no_special:
CONFIGURATION.update({"no_special": Core.switch("no_special")})
if ARGS.no_unified:
CONFIGURATION.update({"unified": Core.switch("unified")})
if ARGS.no_whois:
CONFIGURATION.update({"no_whois": Core.switch("no_whois")})
if ARGS.percentage:
CONFIGURATION.update(
{"show_percentage": Core.switch("show_percentage")}
)
if ARGS.plain:
CONFIGURATION.update(
{"plain_list_domain": Core.switch("plain_list_domain")}
)
if ARGS.production:
Production()
if ARGS.public_suffix:
PublicSuffix().update()
if ARGS.quiet:
CONFIGURATION.update({"quiet": Core.switch("quiet")})
if ARGS.share_logs:
CONFIGURATION.update({"share_logs": Core.switch("share_logs")})
if ARGS.simple:
CONFIGURATION.update(
{"simple": Core.switch("simple"), "quiet": Core.switch("quiet")}
)
if ARGS.split:
CONFIGURATION.update({"split": Core.switch("split")})
if ARGS.syntax:
CONFIGURATION.update({"syntax": Core.switch("syntax")})
if ARGS.timeout and ARGS.timeout % 3 == 0:
CONFIGURATION.update({"seconds_before_http_timeout": ARGS.timeout})
if ARGS.travis:
CONFIGURATION.update({"travis": Core.switch("travis")})
if ARGS.travis_branch:
CONFIGURATION.update({"travis_branch": ARGS.travis_branch})
if ARGS.user_agent:
CONFIGURATION.update({"user_agent": ARGS.user_agent})
if ARGS.verify_ssl_certificate:
CONFIGURATION.update(
{"verify_ssl_certificate": ARGS.verify_ssl_certificate}
)
if ARGS.whois_database:
CONFIGURATION.update(
{"whois_database": Core.switch("whois_database")}
)
if not CONFIGURATION["quiet"]:
Core.colorify_logo(home=True)
# We compare the versions (upstream and local) and in between.
Version().compare()
# We call our Core which will handle all case depending of the configuration or
# the used command line arguments.
Core(
domain_or_ip_to_test=ARGS.domain,
file_path=ARGS.file,
url_to_test=ARGS.url,
url_file=ARGS.url_file,
link_to_test=ARGS.link,
)
except KeyError as e:
if not Version(True).is_cloned():
# We are not into the cloned version.
# We merge the local with the upstream configuration.
Merge(CURRENT_DIRECTORY)
else:
# We are in the cloned version.
# We raise the exception.
#
# Note: The purpose of this is to avoid having
# to search for a mistake while developing.
raise e
except KeyboardInterrupt:
stay_safe()
|
def _command_line(): # pragma: no cover pylint: disable=too-many-branches,too-many-statements
"""
Provide the command line interface.
"""
if __name__ == "PyFunceble":
# We initiate the end of the coloration at the end of each line.
initiate(autoreset=True)
# We load the configuration and the directory structure.
load_config(True)
try:
# The following handle the command line argument.
try:
PARSER = argparse.ArgumentParser(
epilog="Crafted with %s by %s"
% (
Fore.RED + "♥" + Fore.RESET,
Style.BRIGHT
+ Fore.CYAN
+ "Nissar Chababy (Funilrys) "
+ Style.RESET_ALL
+ "with the help of "
+ Style.BRIGHT
+ Fore.GREEN
+ "https://pyfunceble.rtfd.io/en/master/contributors.html "
+ Style.RESET_ALL
+ "&& "
+ Style.BRIGHT
+ Fore.GREEN
+ "https://pyfunceble.rtfd.io/en/master/special-thanks.html",
),
add_help=False,
)
CURRENT_VALUE_FORMAT = (
Fore.YELLOW + Style.BRIGHT + "Configured value: " + Fore.BLUE
)
PARSER.add_argument(
"-ad",
"--adblock",
action="store_true",
help="Switch the decoding of the adblock format. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["adblock"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-a",
"--all",
action="store_false",
help="Output all available information on the screen. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["less"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"" "-c",
"--auto-continue",
"--continue",
action="store_true",
help="Switch the value of the auto continue mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["auto_continue"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--autosave-minutes",
type=int,
help="Update the minimum of minutes before we start "
"committing to upstream under Travis CI. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis_autosave_minutes"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--clean", action="store_true", help="Clean all files under output."
)
PARSER.add_argument(
"--clean-all",
action="store_true",
help="Clean all files under output and all file generated by PyFunceble.",
)
PARSER.add_argument(
"--cmd",
type=str,
help="Pass a command to run before each commit "
"(except the final one) under the Travis mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["command_before_end"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--cmd-before-end",
type=str,
help="Pass a command to run before the results "
"(final) commit under the Travis mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["command_before_end"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--commit-autosave-message",
type=str,
help="Replace the default autosave commit message. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis_autosave_commit"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--commit-results-message",
type=str,
help="Replace the default results (final) commit message. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis_autosave_final_commit"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-d", "--domain", type=str, help="Set and test the given domain."
)
PARSER.add_argument(
"-db",
"--database",
action="store_true",
help="Switch the value of the usage of a database to store "
"inactive domains of the currently tested list. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["inactive_database"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-dbr",
"--days-between-db-retest",
type=int,
help="Set the numbers of days between each retest of domains present "
"into inactive-db.json. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["days_between_db_retest"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--debug",
action="store_true",
help="Switch the value of the debug mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["debug"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--directory-structure",
action="store_true",
help="Generate the directory and files that are needed and which does "
"not exist in the current directory.",
)
PARSER.add_argument(
"-ex",
"--execution",
action="store_true",
help="Switch the default value of the execution time showing. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["show_execution_time"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-f",
"--file",
type=str,
help="Read the given file and test all domains inside it. "
"If a URL is given we download and test the content of the given URL.", # pylint: disable=line-too-long
)
PARSER.add_argument(
"--filter", type=str, help="Domain to filter (regex)."
)
PARSER.add_argument(
"--help",
action="help",
default=argparse.SUPPRESS,
help="Show this help message and exit.",
)
PARSER.add_argument(
"--hierarchical",
action="store_true",
help="Switch the value of the hierarchical sorting of the tested file. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["hierarchical_sorting"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-h",
"--host",
action="store_true",
help="Switch the value of the generation of hosts file. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["generate_hosts"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--http",
action="store_true",
help="Switch the value of the usage of HTTP code. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(HTTP_CODE["active"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--iana",
action="store_true",
help="Update/Generate `iana-domains-db.json`.",
)
PARSER.add_argument(
"--idna",
action="store_true",
help="Switch the value of the IDNA conversion. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["idna_conversion"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-ip",
type=str,
help="Change the IP to print in the hosts files with the given one. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["custom_ip"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--json",
action="store_true",
help="Switch the value of the generation "
"of the JSON formatted list of domains. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["generate_json"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--less",
action="store_true",
help="Output less informations on screen. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(Core.switch("less"))
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--local",
action="store_true",
help="Switch the value of the local network testing. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(Core.switch("local"))
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--link", type=str, help="Download and test the given file."
)
PARSER.add_argument(
"-m",
"--mining",
action="store_true",
help="Switch the value of the mining subsystem usage. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["mining"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-n",
"--no-files",
action="store_true",
help="Switch the value of the production of output files. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["no_files"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-nl",
"--no-logs",
action="store_true",
help="Switch the value of the production of logs files "
"in the case we encounter some errors. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(not CONFIGURATION["logs"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-ns",
"--no-special",
action="store_true",
help="Switch the value of the usage of the SPECIAL rules. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["no_special"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-nu",
"--no-unified",
action="store_true",
help="Switch the value of the production unified logs "
"under the output directory. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["unified"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-nw",
"--no-whois",
action="store_true",
help="Switch the value the usage of whois to test domain's status. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["no_whois"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-p",
"--percentage",
action="store_true",
help="Switch the value of the percentage output mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["show_percentage"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--plain",
action="store_true",
help="Switch the value of the generation "
"of the plain list of domains. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["plain_list_domain"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--production",
action="store_true",
help="Prepare the repository for production.",
)
PARSER.add_argument(
"-psl",
"--public-suffix",
action="store_true",
help="Update/Generate `public-suffix.json`.",
)
PARSER.add_argument(
"-q",
"--quiet",
action="store_true",
help="Run the script in quiet mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["quiet"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--share-logs",
action="store_true",
help="Switch the value of the sharing of logs. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["share_logs"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-s",
"--simple",
action="store_true",
help="Switch the value of the simple output mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["simple"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--split",
action="store_true",
help="Switch the value of the split of the generated output files. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["inactive_database"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--syntax",
action="store_true",
help="Switch the value of the syntax test mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["syntax"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-t",
"--timeout",
type=int,
default=3,
help="Switch the value of the timeout. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["seconds_before_http_timeout"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--travis",
action="store_true",
help="Switch the value of the Travis mode. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"--travis-branch",
type=str,
default="master",
help="Switch the branch name where we are going to push. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["travis_branch"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-u", "--url", type=str, help="Analyze the given URL."
)
PARSER.add_argument(
"-uf",
"--url-file",
type=str,
help="Read and test the list of URL of the given file. "
"If a URL is given we download and test the content of the given URL.", # pylint: disable=line-too-long
)
PARSER.add_argument(
"-ua",
"--user-agent",
type=str,
help="Set the user-agent to use and set every time we "
"interact with everything which is not our logs sharing system.", # pylint: disable=line-too-long
)
PARSER.add_argument(
"-v",
"--version",
help="Show the version of PyFunceble and exit.",
action="version",
version="%(prog)s " + VERSION,
)
PARSER.add_argument(
"-vsc",
"--verify-ssl-certificate",
action="store_true",
help="Switch the value of the verification of the "
"SSL/TLS certificate when testing for URL. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["verify_ssl_certificate"])
+ Style.RESET_ALL
),
)
PARSER.add_argument(
"-wdb",
"--whois-database",
action="store_true",
help="Switch the value of the usage of a database to store "
"whois data in order to avoid whois servers rate limit. %s"
% (
CURRENT_VALUE_FORMAT
+ repr(CONFIGURATION["whois_database"])
+ Style.RESET_ALL
),
)
ARGS = PARSER.parse_args()
if ARGS.less:
CONFIGURATION.update({"less": ARGS.less})
elif not ARGS.all:
CONFIGURATION.update({"less": ARGS.all})
if ARGS.adblock:
CONFIGURATION.update({"adblock": Core.switch("adblock")})
if ARGS.auto_continue:
CONFIGURATION.update(
{"auto_continue": Core.switch("auto_continue")}
)
if ARGS.autosave_minutes:
CONFIGURATION.update(
{"travis_autosave_minutes": ARGS.autosave_minutes}
)
if ARGS.clean:
Clean(None)
if ARGS.clean_all:
Clean(None, ARGS.clean_all)
if ARGS.cmd:
CONFIGURATION.update({"command": ARGS.cmd})
if ARGS.cmd_before_end:
CONFIGURATION.update({"command_before_end": ARGS.cmd_before_end})
if ARGS.commit_autosave_message:
CONFIGURATION.update(
{"travis_autosave_commit": ARGS.commit_autosave_message}
)
if ARGS.commit_results_message:
CONFIGURATION.update(
{"travis_autosave_final_commit": ARGS.commit_results_message}
)
if ARGS.database:
CONFIGURATION.update(
{"inactive_database": Core.switch("inactive_database")}
)
if ARGS.days_between_db_retest:
CONFIGURATION.update(
{"days_between_db_retest": ARGS.days_between_db_retest}
)
if ARGS.debug:
CONFIGURATION.update({"debug": Core.switch("debug")})
if ARGS.directory_structure:
DirectoryStructure()
if ARGS.execution:
CONFIGURATION.update(
{"show_execution_time": Core.switch("show_execution_time")}
)
if ARGS.filter:
CONFIGURATION.update({"filter": ARGS.filter})
if ARGS.hierarchical:
CONFIGURATION.update(
{"hierarchical_sorting": Core.switch("hierarchical_sorting")}
)
if ARGS.host:
CONFIGURATION.update(
{"generate_hosts": Core.switch("generate_hosts")}
)
if ARGS.http:
HTTP_CODE.update({"active": Core.switch(HTTP_CODE["active"], True)})
if ARGS.iana:
IANA().update()
if ARGS.idna:
CONFIGURATION.update(
{"idna_conversion": Core.switch("idna_conversion")}
)
if ARGS.ip:
CONFIGURATION.update({"custom_ip": ARGS.ip})
if ARGS.json:
CONFIGURATION.update(
{"generate_json": Core.switch("generate_json")}
)
if ARGS.local:
CONFIGURATION.update({"local": Core.switch("local")})
if ARGS.mining:
CONFIGURATION.update({"mining": Core.switch("mining")})
if ARGS.no_files:
CONFIGURATION.update({"no_files": Core.switch("no_files")})
if ARGS.no_logs:
CONFIGURATION.update({"logs": Core.switch("logs")})
if ARGS.no_special:
CONFIGURATION.update({"no_special": Core.switch("no_special")})
if ARGS.no_unified:
CONFIGURATION.update({"unified": Core.switch("unified")})
if ARGS.no_whois:
CONFIGURATION.update({"no_whois": Core.switch("no_whois")})
if ARGS.percentage:
CONFIGURATION.update(
{"show_percentage": Core.switch("show_percentage")}
)
if ARGS.plain:
CONFIGURATION.update(
{"plain_list_domain": Core.switch("plain_list_domain")}
)
if ARGS.production:
Production()
if ARGS.public_suffix:
PublicSuffix().update()
if ARGS.quiet:
CONFIGURATION.update({"quiet": Core.switch("quiet")})
if ARGS.share_logs:
CONFIGURATION.update({"share_logs": Core.switch("share_logs")})
if ARGS.simple:
CONFIGURATION.update(
{"simple": Core.switch("simple"), "quiet": Core.switch("quiet")}
)
if ARGS.split:
CONFIGURATION.update({"split": Core.switch("split")})
if ARGS.syntax:
CONFIGURATION.update({"syntax": Core.switch("syntax")})
if ARGS.timeout and ARGS.timeout % 3 == 0:
CONFIGURATION.update({"seconds_before_http_timeout": ARGS.timeout})
if ARGS.travis:
CONFIGURATION.update({"travis": Core.switch("travis")})
if ARGS.travis_branch:
CONFIGURATION.update({"travis_branch": ARGS.travis_branch})
if ARGS.user_agent:
CONFIGURATION.update({"user_agent": ARGS.user_agent})
if ARGS.verify_ssl_certificate:
CONFIGURATION.update(
{"verify_ssl_certificate": ARGS.verify_ssl_certificate}
)
if ARGS.whois_database:
CONFIGURATION.update(
{"whois_database": Core.switch("whois_database")}
)
if not CONFIGURATION["quiet"]:
Core.colorify_logo(home=True)
# We compare the versions (upstream and local) and in between.
Version().compare()
# We call our Core which will handle all case depending of the configuration or
# the used command line arguments.
Core(
domain_or_ip_to_test=ARGS.domain,
file_path=ARGS.file,
url_to_test=ARGS.url,
url_file=ARGS.url_file,
link_to_test=ARGS.link,
)
except KeyError as e:
if not Version(True).is_cloned():
# We are not into the cloned version.
# We merge the local with the upstream configuration.
Merge(CURRENT_DIRECTORY)
else:
# We are in the cloned version.
# We raise the exception.
#
# Note: The purpose of this is to avoid having
# to search for a mistake while developing.
raise e
except KeyboardInterrupt:
stay_safe()
|
[
"Provide",
"the",
"command",
"line",
"interface",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L556-L1339
|
[
"def",
"_command_line",
"(",
")",
":",
"# pragma: no cover pylint: disable=too-many-branches,too-many-statements",
"if",
"__name__",
"==",
"\"PyFunceble\"",
":",
"# We initiate the end of the coloration at the end of each line.",
"initiate",
"(",
"autoreset",
"=",
"True",
")",
"# We load the configuration and the directory structure.",
"load_config",
"(",
"True",
")",
"try",
":",
"# The following handle the command line argument.",
"try",
":",
"PARSER",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"epilog",
"=",
"\"Crafted with %s by %s\"",
"%",
"(",
"Fore",
".",
"RED",
"+",
"\"♥\" +",
"F",
"re.R",
"E",
"SET,",
"",
"Style",
".",
"BRIGHT",
"+",
"Fore",
".",
"CYAN",
"+",
"\"Nissar Chababy (Funilrys) \"",
"+",
"Style",
".",
"RESET_ALL",
"+",
"\"with the help of \"",
"+",
"Style",
".",
"BRIGHT",
"+",
"Fore",
".",
"GREEN",
"+",
"\"https://pyfunceble.rtfd.io/en/master/contributors.html \"",
"+",
"Style",
".",
"RESET_ALL",
"+",
"\"&& \"",
"+",
"Style",
".",
"BRIGHT",
"+",
"Fore",
".",
"GREEN",
"+",
"\"https://pyfunceble.rtfd.io/en/master/special-thanks.html\"",
",",
")",
",",
"add_help",
"=",
"False",
",",
")",
"CURRENT_VALUE_FORMAT",
"=",
"(",
"Fore",
".",
"YELLOW",
"+",
"Style",
".",
"BRIGHT",
"+",
"\"Configured value: \"",
"+",
"Fore",
".",
"BLUE",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-ad\"",
",",
"\"--adblock\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the decoding of the adblock format. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"adblock\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-a\"",
",",
"\"--all\"",
",",
"action",
"=",
"\"store_false\"",
",",
"help",
"=",
"\"Output all available information on the screen. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"less\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"\"",
"\"-c\"",
",",
"\"--auto-continue\"",
",",
"\"--continue\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the auto continue mode. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"auto_continue\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--autosave-minutes\"",
",",
"type",
"=",
"int",
",",
"help",
"=",
"\"Update the minimum of minutes before we start \"",
"\"committing to upstream under Travis CI. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"travis_autosave_minutes\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--clean\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Clean all files under output.\"",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--clean-all\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Clean all files under output and all file generated by PyFunceble.\"",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--cmd\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Pass a command to run before each commit \"",
"\"(except the final one) under the Travis mode. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"command_before_end\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--cmd-before-end\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Pass a command to run before the results \"",
"\"(final) commit under the Travis mode. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"command_before_end\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--commit-autosave-message\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Replace the default autosave commit message. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"travis_autosave_commit\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--commit-results-message\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Replace the default results (final) commit message. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"travis_autosave_final_commit\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-d\"",
",",
"\"--domain\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Set and test the given domain.\"",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-db\"",
",",
"\"--database\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the usage of a database to store \"",
"\"inactive domains of the currently tested list. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"inactive_database\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-dbr\"",
",",
"\"--days-between-db-retest\"",
",",
"type",
"=",
"int",
",",
"help",
"=",
"\"Set the numbers of days between each retest of domains present \"",
"\"into inactive-db.json. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"days_between_db_retest\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--debug\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the debug mode. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"debug\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--directory-structure\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Generate the directory and files that are needed and which does \"",
"\"not exist in the current directory.\"",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-ex\"",
",",
"\"--execution\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the default value of the execution time showing. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"show_execution_time\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-f\"",
",",
"\"--file\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Read the given file and test all domains inside it. \"",
"\"If a URL is given we download and test the content of the given URL.\"",
",",
"# pylint: disable=line-too-long",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--filter\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Domain to filter (regex).\"",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--help\"",
",",
"action",
"=",
"\"help\"",
",",
"default",
"=",
"argparse",
".",
"SUPPRESS",
",",
"help",
"=",
"\"Show this help message and exit.\"",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--hierarchical\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the hierarchical sorting of the tested file. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"hierarchical_sorting\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-h\"",
",",
"\"--host\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the generation of hosts file. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"generate_hosts\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--http\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the usage of HTTP code. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"HTTP_CODE",
"[",
"\"active\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--iana\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Update/Generate `iana-domains-db.json`.\"",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--idna\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the IDNA conversion. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"idna_conversion\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-ip\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Change the IP to print in the hosts files with the given one. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"custom_ip\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--json\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the generation \"",
"\"of the JSON formatted list of domains. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"generate_json\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--less\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Output less informations on screen. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"Core",
".",
"switch",
"(",
"\"less\"",
")",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--local\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the local network testing. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"Core",
".",
"switch",
"(",
"\"local\"",
")",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--link\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Download and test the given file.\"",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-m\"",
",",
"\"--mining\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the mining subsystem usage. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"mining\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-n\"",
",",
"\"--no-files\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the production of output files. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"no_files\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-nl\"",
",",
"\"--no-logs\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the production of logs files \"",
"\"in the case we encounter some errors. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"not",
"CONFIGURATION",
"[",
"\"logs\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-ns\"",
",",
"\"--no-special\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the usage of the SPECIAL rules. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"no_special\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-nu\"",
",",
"\"--no-unified\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the production unified logs \"",
"\"under the output directory. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"unified\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-nw\"",
",",
"\"--no-whois\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value the usage of whois to test domain's status. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"no_whois\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-p\"",
",",
"\"--percentage\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the percentage output mode. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"show_percentage\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--plain\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the generation \"",
"\"of the plain list of domains. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"plain_list_domain\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--production\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Prepare the repository for production.\"",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-psl\"",
",",
"\"--public-suffix\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Update/Generate `public-suffix.json`.\"",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-q\"",
",",
"\"--quiet\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Run the script in quiet mode. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--share-logs\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the sharing of logs. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"share_logs\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-s\"",
",",
"\"--simple\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the simple output mode. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"simple\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--split\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the split of the generated output files. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"inactive_database\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--syntax\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the syntax test mode. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"syntax\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-t\"",
",",
"\"--timeout\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"3",
",",
"help",
"=",
"\"Switch the value of the timeout. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"seconds_before_http_timeout\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--travis\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the Travis mode. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"travis\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"--travis-branch\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"\"master\"",
",",
"help",
"=",
"\"Switch the branch name where we are going to push. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"travis_branch\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-u\"",
",",
"\"--url\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Analyze the given URL.\"",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-uf\"",
",",
"\"--url-file\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Read and test the list of URL of the given file. \"",
"\"If a URL is given we download and test the content of the given URL.\"",
",",
"# pylint: disable=line-too-long",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-ua\"",
",",
"\"--user-agent\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Set the user-agent to use and set every time we \"",
"\"interact with everything which is not our logs sharing system.\"",
",",
"# pylint: disable=line-too-long",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-v\"",
",",
"\"--version\"",
",",
"help",
"=",
"\"Show the version of PyFunceble and exit.\"",
",",
"action",
"=",
"\"version\"",
",",
"version",
"=",
"\"%(prog)s \"",
"+",
"VERSION",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-vsc\"",
",",
"\"--verify-ssl-certificate\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the verification of the \"",
"\"SSL/TLS certificate when testing for URL. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"verify_ssl_certificate\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"PARSER",
".",
"add_argument",
"(",
"\"-wdb\"",
",",
"\"--whois-database\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Switch the value of the usage of a database to store \"",
"\"whois data in order to avoid whois servers rate limit. %s\"",
"%",
"(",
"CURRENT_VALUE_FORMAT",
"+",
"repr",
"(",
"CONFIGURATION",
"[",
"\"whois_database\"",
"]",
")",
"+",
"Style",
".",
"RESET_ALL",
")",
",",
")",
"ARGS",
"=",
"PARSER",
".",
"parse_args",
"(",
")",
"if",
"ARGS",
".",
"less",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"less\"",
":",
"ARGS",
".",
"less",
"}",
")",
"elif",
"not",
"ARGS",
".",
"all",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"less\"",
":",
"ARGS",
".",
"all",
"}",
")",
"if",
"ARGS",
".",
"adblock",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"adblock\"",
":",
"Core",
".",
"switch",
"(",
"\"adblock\"",
")",
"}",
")",
"if",
"ARGS",
".",
"auto_continue",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"auto_continue\"",
":",
"Core",
".",
"switch",
"(",
"\"auto_continue\"",
")",
"}",
")",
"if",
"ARGS",
".",
"autosave_minutes",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"travis_autosave_minutes\"",
":",
"ARGS",
".",
"autosave_minutes",
"}",
")",
"if",
"ARGS",
".",
"clean",
":",
"Clean",
"(",
"None",
")",
"if",
"ARGS",
".",
"clean_all",
":",
"Clean",
"(",
"None",
",",
"ARGS",
".",
"clean_all",
")",
"if",
"ARGS",
".",
"cmd",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"command\"",
":",
"ARGS",
".",
"cmd",
"}",
")",
"if",
"ARGS",
".",
"cmd_before_end",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"command_before_end\"",
":",
"ARGS",
".",
"cmd_before_end",
"}",
")",
"if",
"ARGS",
".",
"commit_autosave_message",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"travis_autosave_commit\"",
":",
"ARGS",
".",
"commit_autosave_message",
"}",
")",
"if",
"ARGS",
".",
"commit_results_message",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"travis_autosave_final_commit\"",
":",
"ARGS",
".",
"commit_results_message",
"}",
")",
"if",
"ARGS",
".",
"database",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"inactive_database\"",
":",
"Core",
".",
"switch",
"(",
"\"inactive_database\"",
")",
"}",
")",
"if",
"ARGS",
".",
"days_between_db_retest",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"days_between_db_retest\"",
":",
"ARGS",
".",
"days_between_db_retest",
"}",
")",
"if",
"ARGS",
".",
"debug",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"debug\"",
":",
"Core",
".",
"switch",
"(",
"\"debug\"",
")",
"}",
")",
"if",
"ARGS",
".",
"directory_structure",
":",
"DirectoryStructure",
"(",
")",
"if",
"ARGS",
".",
"execution",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"show_execution_time\"",
":",
"Core",
".",
"switch",
"(",
"\"show_execution_time\"",
")",
"}",
")",
"if",
"ARGS",
".",
"filter",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"filter\"",
":",
"ARGS",
".",
"filter",
"}",
")",
"if",
"ARGS",
".",
"hierarchical",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"hierarchical_sorting\"",
":",
"Core",
".",
"switch",
"(",
"\"hierarchical_sorting\"",
")",
"}",
")",
"if",
"ARGS",
".",
"host",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"generate_hosts\"",
":",
"Core",
".",
"switch",
"(",
"\"generate_hosts\"",
")",
"}",
")",
"if",
"ARGS",
".",
"http",
":",
"HTTP_CODE",
".",
"update",
"(",
"{",
"\"active\"",
":",
"Core",
".",
"switch",
"(",
"HTTP_CODE",
"[",
"\"active\"",
"]",
",",
"True",
")",
"}",
")",
"if",
"ARGS",
".",
"iana",
":",
"IANA",
"(",
")",
".",
"update",
"(",
")",
"if",
"ARGS",
".",
"idna",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"idna_conversion\"",
":",
"Core",
".",
"switch",
"(",
"\"idna_conversion\"",
")",
"}",
")",
"if",
"ARGS",
".",
"ip",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"custom_ip\"",
":",
"ARGS",
".",
"ip",
"}",
")",
"if",
"ARGS",
".",
"json",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"generate_json\"",
":",
"Core",
".",
"switch",
"(",
"\"generate_json\"",
")",
"}",
")",
"if",
"ARGS",
".",
"local",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"local\"",
":",
"Core",
".",
"switch",
"(",
"\"local\"",
")",
"}",
")",
"if",
"ARGS",
".",
"mining",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"mining\"",
":",
"Core",
".",
"switch",
"(",
"\"mining\"",
")",
"}",
")",
"if",
"ARGS",
".",
"no_files",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"no_files\"",
":",
"Core",
".",
"switch",
"(",
"\"no_files\"",
")",
"}",
")",
"if",
"ARGS",
".",
"no_logs",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"logs\"",
":",
"Core",
".",
"switch",
"(",
"\"logs\"",
")",
"}",
")",
"if",
"ARGS",
".",
"no_special",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"no_special\"",
":",
"Core",
".",
"switch",
"(",
"\"no_special\"",
")",
"}",
")",
"if",
"ARGS",
".",
"no_unified",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"unified\"",
":",
"Core",
".",
"switch",
"(",
"\"unified\"",
")",
"}",
")",
"if",
"ARGS",
".",
"no_whois",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"no_whois\"",
":",
"Core",
".",
"switch",
"(",
"\"no_whois\"",
")",
"}",
")",
"if",
"ARGS",
".",
"percentage",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"show_percentage\"",
":",
"Core",
".",
"switch",
"(",
"\"show_percentage\"",
")",
"}",
")",
"if",
"ARGS",
".",
"plain",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"plain_list_domain\"",
":",
"Core",
".",
"switch",
"(",
"\"plain_list_domain\"",
")",
"}",
")",
"if",
"ARGS",
".",
"production",
":",
"Production",
"(",
")",
"if",
"ARGS",
".",
"public_suffix",
":",
"PublicSuffix",
"(",
")",
".",
"update",
"(",
")",
"if",
"ARGS",
".",
"quiet",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"quiet\"",
":",
"Core",
".",
"switch",
"(",
"\"quiet\"",
")",
"}",
")",
"if",
"ARGS",
".",
"share_logs",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"share_logs\"",
":",
"Core",
".",
"switch",
"(",
"\"share_logs\"",
")",
"}",
")",
"if",
"ARGS",
".",
"simple",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"simple\"",
":",
"Core",
".",
"switch",
"(",
"\"simple\"",
")",
",",
"\"quiet\"",
":",
"Core",
".",
"switch",
"(",
"\"quiet\"",
")",
"}",
")",
"if",
"ARGS",
".",
"split",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"split\"",
":",
"Core",
".",
"switch",
"(",
"\"split\"",
")",
"}",
")",
"if",
"ARGS",
".",
"syntax",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"syntax\"",
":",
"Core",
".",
"switch",
"(",
"\"syntax\"",
")",
"}",
")",
"if",
"ARGS",
".",
"timeout",
"and",
"ARGS",
".",
"timeout",
"%",
"3",
"==",
"0",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"seconds_before_http_timeout\"",
":",
"ARGS",
".",
"timeout",
"}",
")",
"if",
"ARGS",
".",
"travis",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"travis\"",
":",
"Core",
".",
"switch",
"(",
"\"travis\"",
")",
"}",
")",
"if",
"ARGS",
".",
"travis_branch",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"travis_branch\"",
":",
"ARGS",
".",
"travis_branch",
"}",
")",
"if",
"ARGS",
".",
"user_agent",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"user_agent\"",
":",
"ARGS",
".",
"user_agent",
"}",
")",
"if",
"ARGS",
".",
"verify_ssl_certificate",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"verify_ssl_certificate\"",
":",
"ARGS",
".",
"verify_ssl_certificate",
"}",
")",
"if",
"ARGS",
".",
"whois_database",
":",
"CONFIGURATION",
".",
"update",
"(",
"{",
"\"whois_database\"",
":",
"Core",
".",
"switch",
"(",
"\"whois_database\"",
")",
"}",
")",
"if",
"not",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
":",
"Core",
".",
"colorify_logo",
"(",
"home",
"=",
"True",
")",
"# We compare the versions (upstream and local) and in between.",
"Version",
"(",
")",
".",
"compare",
"(",
")",
"# We call our Core which will handle all case depending of the configuration or",
"# the used command line arguments.",
"Core",
"(",
"domain_or_ip_to_test",
"=",
"ARGS",
".",
"domain",
",",
"file_path",
"=",
"ARGS",
".",
"file",
",",
"url_to_test",
"=",
"ARGS",
".",
"url",
",",
"url_file",
"=",
"ARGS",
".",
"url_file",
",",
"link_to_test",
"=",
"ARGS",
".",
"link",
",",
")",
"except",
"KeyError",
"as",
"e",
":",
"if",
"not",
"Version",
"(",
"True",
")",
".",
"is_cloned",
"(",
")",
":",
"# We are not into the cloned version.",
"# We merge the local with the upstream configuration.",
"Merge",
"(",
"CURRENT_DIRECTORY",
")",
"else",
":",
"# We are in the cloned version.",
"# We raise the exception.",
"#",
"# Note: The purpose of this is to avoid having",
"# to search for a mistake while developing.",
"raise",
"e",
"except",
"KeyboardInterrupt",
":",
"stay_safe",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core._entry_management_url_download
|
Check if the given information is a URL.
If it is the case, it download and update the location of file to test.
:param passed: The url passed to the system.
:type passed: str
:return: The state of the check.
:rtype: bool
|
PyFunceble/core.py
|
def _entry_management_url_download(self, passed):
"""
Check if the given information is a URL.
If it is the case, it download and update the location of file to test.
:param passed: The url passed to the system.
:type passed: str
:return: The state of the check.
:rtype: bool
"""
if passed and self.checker.is_url_valid(passed):
# The passed string is an URL.
# We get the file name based on the URL.
# We actually just get the string after the last `/` in the URL.
file_to_test = passed.split("/")[-1]
if (
not PyFunceble.path.isfile(file_to_test)
or PyFunceble.INTERN["counter"]["number"]["tested"] == 0
):
# The filename does not exist in the current directory
# or the currently number of tested is equal to 0.
# We download the content of the link.
Download(passed, file_to_test).text()
# The files does exist or the currently number of tested is greater than
# 0.
# We initiate the file we have to test.
PyFunceble.INTERN["file_to_test"] = file_to_test
# We return true to say that everything goes right.
return True
# The passed string is not an URL.
# We do not need to do anything else.
return False
|
def _entry_management_url_download(self, passed):
"""
Check if the given information is a URL.
If it is the case, it download and update the location of file to test.
:param passed: The url passed to the system.
:type passed: str
:return: The state of the check.
:rtype: bool
"""
if passed and self.checker.is_url_valid(passed):
# The passed string is an URL.
# We get the file name based on the URL.
# We actually just get the string after the last `/` in the URL.
file_to_test = passed.split("/")[-1]
if (
not PyFunceble.path.isfile(file_to_test)
or PyFunceble.INTERN["counter"]["number"]["tested"] == 0
):
# The filename does not exist in the current directory
# or the currently number of tested is equal to 0.
# We download the content of the link.
Download(passed, file_to_test).text()
# The files does exist or the currently number of tested is greater than
# 0.
# We initiate the file we have to test.
PyFunceble.INTERN["file_to_test"] = file_to_test
# We return true to say that everything goes right.
return True
# The passed string is not an URL.
# We do not need to do anything else.
return False
|
[
"Check",
"if",
"the",
"given",
"information",
"is",
"a",
"URL",
".",
"If",
"it",
"is",
"the",
"case",
"it",
"download",
"and",
"update",
"the",
"location",
"of",
"file",
"to",
"test",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L156-L197
|
[
"def",
"_entry_management_url_download",
"(",
"self",
",",
"passed",
")",
":",
"if",
"passed",
"and",
"self",
".",
"checker",
".",
"is_url_valid",
"(",
"passed",
")",
":",
"# The passed string is an URL.",
"# We get the file name based on the URL.",
"# We actually just get the string after the last `/` in the URL.",
"file_to_test",
"=",
"passed",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"if",
"(",
"not",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"file_to_test",
")",
"or",
"PyFunceble",
".",
"INTERN",
"[",
"\"counter\"",
"]",
"[",
"\"number\"",
"]",
"[",
"\"tested\"",
"]",
"==",
"0",
")",
":",
"# The filename does not exist in the current directory",
"# or the currently number of tested is equal to 0.",
"# We download the content of the link.",
"Download",
"(",
"passed",
",",
"file_to_test",
")",
".",
"text",
"(",
")",
"# The files does exist or the currently number of tested is greater than",
"# 0.",
"# We initiate the file we have to test.",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
"=",
"file_to_test",
"# We return true to say that everything goes right.",
"return",
"True",
"# The passed string is not an URL.",
"# We do not need to do anything else.",
"return",
"False"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core._entry_management_url
|
Manage the loading of the url system.
|
PyFunceble/core.py
|
def _entry_management_url(self):
"""
Manage the loading of the url system.
"""
if (
self.url_file # pylint: disable=no-member
and not self._entry_management_url_download(
self.url_file # pylint: disable=no-member
)
): # pylint: disable=no-member
# The current url_file is not a URL.
# We initiate the filename as the file we have to test.
PyFunceble.INTERN[
"file_to_test"
] = self.url_file
|
def _entry_management_url(self):
"""
Manage the loading of the url system.
"""
if (
self.url_file # pylint: disable=no-member
and not self._entry_management_url_download(
self.url_file # pylint: disable=no-member
)
): # pylint: disable=no-member
# The current url_file is not a URL.
# We initiate the filename as the file we have to test.
PyFunceble.INTERN[
"file_to_test"
] = self.url_file
|
[
"Manage",
"the",
"loading",
"of",
"the",
"url",
"system",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L199-L215
|
[
"def",
"_entry_management_url",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"url_file",
"# pylint: disable=no-member",
"and",
"not",
"self",
".",
"_entry_management_url_download",
"(",
"self",
".",
"url_file",
"# pylint: disable=no-member",
")",
")",
":",
"# pylint: disable=no-member",
"# The current url_file is not a URL.",
"# We initiate the filename as the file we have to test.",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
"=",
"self",
".",
"url_file"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core._entry_management
|
Avoid to have 1 millions line into self.__init__()
|
PyFunceble/core.py
|
def _entry_management(self): # pylint: disable=too-many-branches
"""
Avoid to have 1 millions line into self.__init__()
"""
if not self.modulo_test: # pylint: disable=no-member
# We are not in a module usage.
# We set the file_path as the file we have to test.
PyFunceble.INTERN[
"file_to_test"
] = self.file_path # pylint: disable=no-member
# We check if the given file_path is an url.
# If it is an URL we update the file to test and download
# the given URL.
self._entry_management_url()
# We fix the environnement permissions.
AutoSave().travis_permissions()
# We check if we need to bypass the execution of PyFunceble.
self.bypass()
# We set the start time.
ExecutionTime("start")
if PyFunceble.CONFIGURATION["syntax"]:
# We are checking for syntax.
# We deactivate the http status code.
PyFunceble.HTTP_CODE["active"] = False
if self.domain_or_ip_to_test: # pylint: disable=no-member
# The given domain is not empty or None.
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "domain"
# We set the start time.
ExecutionTime("start")
# We deactivate the showing of percentage as we are in a single
# test run.
PyFunceble.CONFIGURATION["show_percentage"] = False
# We deactivate the whois database as it is not needed.
PyFunceble.CONFIGURATION["whois_database"] = False
if PyFunceble.CONFIGURATION["idna_conversion"]:
domain_or_ip_to_test = domain2idna(
self.domain_or_ip_to_test.lower() # pylint: disable=no-member
)
else:
domain_or_ip_to_test = (
self.domain_or_ip_to_test.lower() # pylint: disable=no-member
) # pylint: disable=no-member
# We test the domain after converting it to lower case.
self.domain(domain_or_ip_to_test)
elif self.url_to_test and not self.file_path: # pylint: disable=no-member
# An url to test is given and the file path is empty.
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "url"
# We set the start time.
ExecutionTime("start")
# We deactivate the showing of percentage as we are in a single
# test run.
PyFunceble.CONFIGURATION["show_percentage"] = False
# We test the url to test after converting it if needed (IDNA).
self.url(
self.checker.is_url_valid(
self.url_to_test, # pylint: disable=no-member
return_formatted=True,
)
)
elif (
self._entry_management_url_download(
self.url_file # pylint: disable=no-member
)
or self.url_file # pylint: disable=no-member
):
# * A file full of URL is given.
# or
# * the given file full of URL is a URL.
# * We deactivate the whois subsystem as it is not needed for url testing.
# * We activate the generation of plain list element.
# * We activate the generation of splited data instead of unified data.
PyFunceble.CONFIGURATION["no_whois"] = PyFunceble.CONFIGURATION[
"plain_list_domain"
] = PyFunceble.CONFIGURATION["split"] = True
# We deactivate the generation of hosts file as it is not relevant for
# url testing.
PyFunceble.CONFIGURATION["generate_hosts"] = False
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "url"
# And we test the given or the downloaded file.
self.file_url()
elif (
self._entry_management_url_download(
self.link_to_test # pylint: disable=no-member
)
or self._entry_management_url_download(
self.file_path # pylint: disable=no-member
) # pylint: disable=no-member
or self.file_path # pylint: disable=no-member
):
# * A file path is given.
# or
# * The given file path is an URL.
# or
# * A link to test is given.
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "domain"
# We test the given or the downloaded file.
self.file()
else:
# No file, domain, single url or file or url is given.
# We print a message on screen.
print(
PyFunceble.Fore.CYAN + PyFunceble.Style.BRIGHT + "Nothing to test."
)
if (
self.domain_or_ip_to_test # pylint: disable=no-member
or self.url_to_test # pylint: disable=no-member
):
# We are testing a domain.
# We stop and log the execution time.
ExecutionTime("stop", last=True)
# We log the current percentage state.
self.percentage.log()
# We show the colored logo.
self.colorify_logo()
# We print our friendly message :)
PyFunceble.stay_safe()
else:
# We are used as an imported module.
# * We activate the simple mode as the table or any full
# details on screen are irrelevant.
# * We activate the quiet mode.
# And we deactivate the generation of files.
PyFunceble.CONFIGURATION["simple"] = PyFunceble.CONFIGURATION[
"quiet"
] = PyFunceble.CONFIGURATION["no_files"] = True
# * We deactivate the whois database as it is not needed.
# * We deactivate the database as it is not needed.
# * We deactivate the autocontinue subsystem as it is not needed.
# * We deactivate the execution time subsystem as it is not needed.
PyFunceble.CONFIGURATION["whois_database"] = PyFunceble.CONFIGURATION[
"inactive_database"
] = PyFunceble.CONFIGURATION["auto_continue"] = PyFunceble.CONFIGURATION[
"show_execution_time"
] = False
if self.domain_or_ip_to_test: # pylint: disable=no-member
# A domain is given.
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "domain"
# We set the domain to test.
PyFunceble.INTERN[
"to_test"
] = self.domain_or_ip_to_test.lower() # pylint: disable=no-member
elif self.url_to_test: # pylint: disable=no-member
# A url is given,
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "url"
# We set the url to test.
PyFunceble.INTERN[
"to_test"
] = self.url_to_test
|
def _entry_management(self): # pylint: disable=too-many-branches
"""
Avoid to have 1 millions line into self.__init__()
"""
if not self.modulo_test: # pylint: disable=no-member
# We are not in a module usage.
# We set the file_path as the file we have to test.
PyFunceble.INTERN[
"file_to_test"
] = self.file_path # pylint: disable=no-member
# We check if the given file_path is an url.
# If it is an URL we update the file to test and download
# the given URL.
self._entry_management_url()
# We fix the environnement permissions.
AutoSave().travis_permissions()
# We check if we need to bypass the execution of PyFunceble.
self.bypass()
# We set the start time.
ExecutionTime("start")
if PyFunceble.CONFIGURATION["syntax"]:
# We are checking for syntax.
# We deactivate the http status code.
PyFunceble.HTTP_CODE["active"] = False
if self.domain_or_ip_to_test: # pylint: disable=no-member
# The given domain is not empty or None.
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "domain"
# We set the start time.
ExecutionTime("start")
# We deactivate the showing of percentage as we are in a single
# test run.
PyFunceble.CONFIGURATION["show_percentage"] = False
# We deactivate the whois database as it is not needed.
PyFunceble.CONFIGURATION["whois_database"] = False
if PyFunceble.CONFIGURATION["idna_conversion"]:
domain_or_ip_to_test = domain2idna(
self.domain_or_ip_to_test.lower() # pylint: disable=no-member
)
else:
domain_or_ip_to_test = (
self.domain_or_ip_to_test.lower() # pylint: disable=no-member
) # pylint: disable=no-member
# We test the domain after converting it to lower case.
self.domain(domain_or_ip_to_test)
elif self.url_to_test and not self.file_path: # pylint: disable=no-member
# An url to test is given and the file path is empty.
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "url"
# We set the start time.
ExecutionTime("start")
# We deactivate the showing of percentage as we are in a single
# test run.
PyFunceble.CONFIGURATION["show_percentage"] = False
# We test the url to test after converting it if needed (IDNA).
self.url(
self.checker.is_url_valid(
self.url_to_test, # pylint: disable=no-member
return_formatted=True,
)
)
elif (
self._entry_management_url_download(
self.url_file # pylint: disable=no-member
)
or self.url_file # pylint: disable=no-member
):
# * A file full of URL is given.
# or
# * the given file full of URL is a URL.
# * We deactivate the whois subsystem as it is not needed for url testing.
# * We activate the generation of plain list element.
# * We activate the generation of splited data instead of unified data.
PyFunceble.CONFIGURATION["no_whois"] = PyFunceble.CONFIGURATION[
"plain_list_domain"
] = PyFunceble.CONFIGURATION["split"] = True
# We deactivate the generation of hosts file as it is not relevant for
# url testing.
PyFunceble.CONFIGURATION["generate_hosts"] = False
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "url"
# And we test the given or the downloaded file.
self.file_url()
elif (
self._entry_management_url_download(
self.link_to_test # pylint: disable=no-member
)
or self._entry_management_url_download(
self.file_path # pylint: disable=no-member
) # pylint: disable=no-member
or self.file_path # pylint: disable=no-member
):
# * A file path is given.
# or
# * The given file path is an URL.
# or
# * A link to test is given.
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "domain"
# We test the given or the downloaded file.
self.file()
else:
# No file, domain, single url or file or url is given.
# We print a message on screen.
print(
PyFunceble.Fore.CYAN + PyFunceble.Style.BRIGHT + "Nothing to test."
)
if (
self.domain_or_ip_to_test # pylint: disable=no-member
or self.url_to_test # pylint: disable=no-member
):
# We are testing a domain.
# We stop and log the execution time.
ExecutionTime("stop", last=True)
# We log the current percentage state.
self.percentage.log()
# We show the colored logo.
self.colorify_logo()
# We print our friendly message :)
PyFunceble.stay_safe()
else:
# We are used as an imported module.
# * We activate the simple mode as the table or any full
# details on screen are irrelevant.
# * We activate the quiet mode.
# And we deactivate the generation of files.
PyFunceble.CONFIGURATION["simple"] = PyFunceble.CONFIGURATION[
"quiet"
] = PyFunceble.CONFIGURATION["no_files"] = True
# * We deactivate the whois database as it is not needed.
# * We deactivate the database as it is not needed.
# * We deactivate the autocontinue subsystem as it is not needed.
# * We deactivate the execution time subsystem as it is not needed.
PyFunceble.CONFIGURATION["whois_database"] = PyFunceble.CONFIGURATION[
"inactive_database"
] = PyFunceble.CONFIGURATION["auto_continue"] = PyFunceble.CONFIGURATION[
"show_execution_time"
] = False
if self.domain_or_ip_to_test: # pylint: disable=no-member
# A domain is given.
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "domain"
# We set the domain to test.
PyFunceble.INTERN[
"to_test"
] = self.domain_or_ip_to_test.lower() # pylint: disable=no-member
elif self.url_to_test: # pylint: disable=no-member
# A url is given,
# We initiate a variable which will tell the system the type
# of the tested element.
PyFunceble.INTERN["to_test_type"] = "url"
# We set the url to test.
PyFunceble.INTERN[
"to_test"
] = self.url_to_test
|
[
"Avoid",
"to",
"have",
"1",
"millions",
"line",
"into",
"self",
".",
"__init__",
"()"
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L217-L414
|
[
"def",
"_entry_management",
"(",
"self",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"not",
"self",
".",
"modulo_test",
":",
"# pylint: disable=no-member",
"# We are not in a module usage.",
"# We set the file_path as the file we have to test.",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
"=",
"self",
".",
"file_path",
"# pylint: disable=no-member",
"# We check if the given file_path is an url.",
"# If it is an URL we update the file to test and download",
"# the given URL.",
"self",
".",
"_entry_management_url",
"(",
")",
"# We fix the environnement permissions.",
"AutoSave",
"(",
")",
".",
"travis_permissions",
"(",
")",
"# We check if we need to bypass the execution of PyFunceble.",
"self",
".",
"bypass",
"(",
")",
"# We set the start time.",
"ExecutionTime",
"(",
"\"start\"",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"syntax\"",
"]",
":",
"# We are checking for syntax.",
"# We deactivate the http status code.",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"active\"",
"]",
"=",
"False",
"if",
"self",
".",
"domain_or_ip_to_test",
":",
"# pylint: disable=no-member",
"# The given domain is not empty or None.",
"# We initiate a variable which will tell the system the type",
"# of the tested element.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test_type\"",
"]",
"=",
"\"domain\"",
"# We set the start time.",
"ExecutionTime",
"(",
"\"start\"",
")",
"# We deactivate the showing of percentage as we are in a single",
"# test run.",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"show_percentage\"",
"]",
"=",
"False",
"# We deactivate the whois database as it is not needed.",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"whois_database\"",
"]",
"=",
"False",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"idna_conversion\"",
"]",
":",
"domain_or_ip_to_test",
"=",
"domain2idna",
"(",
"self",
".",
"domain_or_ip_to_test",
".",
"lower",
"(",
")",
"# pylint: disable=no-member",
")",
"else",
":",
"domain_or_ip_to_test",
"=",
"(",
"self",
".",
"domain_or_ip_to_test",
".",
"lower",
"(",
")",
"# pylint: disable=no-member",
")",
"# pylint: disable=no-member",
"# We test the domain after converting it to lower case.",
"self",
".",
"domain",
"(",
"domain_or_ip_to_test",
")",
"elif",
"self",
".",
"url_to_test",
"and",
"not",
"self",
".",
"file_path",
":",
"# pylint: disable=no-member",
"# An url to test is given and the file path is empty.",
"# We initiate a variable which will tell the system the type",
"# of the tested element.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test_type\"",
"]",
"=",
"\"url\"",
"# We set the start time.",
"ExecutionTime",
"(",
"\"start\"",
")",
"# We deactivate the showing of percentage as we are in a single",
"# test run.",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"show_percentage\"",
"]",
"=",
"False",
"# We test the url to test after converting it if needed (IDNA).",
"self",
".",
"url",
"(",
"self",
".",
"checker",
".",
"is_url_valid",
"(",
"self",
".",
"url_to_test",
",",
"# pylint: disable=no-member",
"return_formatted",
"=",
"True",
",",
")",
")",
"elif",
"(",
"self",
".",
"_entry_management_url_download",
"(",
"self",
".",
"url_file",
"# pylint: disable=no-member",
")",
"or",
"self",
".",
"url_file",
"# pylint: disable=no-member",
")",
":",
"# * A file full of URL is given.",
"# or",
"# * the given file full of URL is a URL.",
"# * We deactivate the whois subsystem as it is not needed for url testing.",
"# * We activate the generation of plain list element.",
"# * We activate the generation of splited data instead of unified data.",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"no_whois\"",
"]",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"plain_list_domain\"",
"]",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"split\"",
"]",
"=",
"True",
"# We deactivate the generation of hosts file as it is not relevant for",
"# url testing.",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"generate_hosts\"",
"]",
"=",
"False",
"# We initiate a variable which will tell the system the type",
"# of the tested element.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test_type\"",
"]",
"=",
"\"url\"",
"# And we test the given or the downloaded file.",
"self",
".",
"file_url",
"(",
")",
"elif",
"(",
"self",
".",
"_entry_management_url_download",
"(",
"self",
".",
"link_to_test",
"# pylint: disable=no-member",
")",
"or",
"self",
".",
"_entry_management_url_download",
"(",
"self",
".",
"file_path",
"# pylint: disable=no-member",
")",
"# pylint: disable=no-member",
"or",
"self",
".",
"file_path",
"# pylint: disable=no-member",
")",
":",
"# * A file path is given.",
"# or",
"# * The given file path is an URL.",
"# or",
"# * A link to test is given.",
"# We initiate a variable which will tell the system the type",
"# of the tested element.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test_type\"",
"]",
"=",
"\"domain\"",
"# We test the given or the downloaded file.",
"self",
".",
"file",
"(",
")",
"else",
":",
"# No file, domain, single url or file or url is given.",
"# We print a message on screen.",
"print",
"(",
"PyFunceble",
".",
"Fore",
".",
"CYAN",
"+",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"\"Nothing to test.\"",
")",
"if",
"(",
"self",
".",
"domain_or_ip_to_test",
"# pylint: disable=no-member",
"or",
"self",
".",
"url_to_test",
"# pylint: disable=no-member",
")",
":",
"# We are testing a domain.",
"# We stop and log the execution time.",
"ExecutionTime",
"(",
"\"stop\"",
",",
"last",
"=",
"True",
")",
"# We log the current percentage state.",
"self",
".",
"percentage",
".",
"log",
"(",
")",
"# We show the colored logo.",
"self",
".",
"colorify_logo",
"(",
")",
"# We print our friendly message :)",
"PyFunceble",
".",
"stay_safe",
"(",
")",
"else",
":",
"# We are used as an imported module.",
"# * We activate the simple mode as the table or any full",
"# details on screen are irrelevant.",
"# * We activate the quiet mode.",
"# And we deactivate the generation of files.",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"simple\"",
"]",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"no_files\"",
"]",
"=",
"True",
"# * We deactivate the whois database as it is not needed.",
"# * We deactivate the database as it is not needed.",
"# * We deactivate the autocontinue subsystem as it is not needed.",
"# * We deactivate the execution time subsystem as it is not needed.",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"whois_database\"",
"]",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"inactive_database\"",
"]",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"auto_continue\"",
"]",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"show_execution_time\"",
"]",
"=",
"False",
"if",
"self",
".",
"domain_or_ip_to_test",
":",
"# pylint: disable=no-member",
"# A domain is given.",
"# We initiate a variable which will tell the system the type",
"# of the tested element.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test_type\"",
"]",
"=",
"\"domain\"",
"# We set the domain to test.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
"=",
"self",
".",
"domain_or_ip_to_test",
".",
"lower",
"(",
")",
"# pylint: disable=no-member",
"elif",
"self",
".",
"url_to_test",
":",
"# pylint: disable=no-member",
"# A url is given,",
"# We initiate a variable which will tell the system the type",
"# of the tested element.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test_type\"",
"]",
"=",
"\"url\"",
"# We set the url to test.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
"=",
"self",
".",
"url_to_test"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core.bypass
|
Exit the script if :code:`[PyFunceble skip]` is matched into the latest
commit message.
|
PyFunceble/core.py
|
def bypass(cls):
"""
Exit the script if :code:`[PyFunceble skip]` is matched into the latest
commit message.
"""
# We set the regex to match in order to bypass the execution of
# PyFunceble.
regex_bypass = r"\[PyFunceble\sskip\]"
if (
PyFunceble.CONFIGURATION["travis"]
and Regex(
Command("git log -1").execute(), regex_bypass, return_data=False
).match()
):
# * We are under Travis CI.
# and
# * The bypass marker is matched into the latest commit.
# We save everything and stop PyFunceble.
AutoSave(True, is_bypass=True)
|
def bypass(cls):
"""
Exit the script if :code:`[PyFunceble skip]` is matched into the latest
commit message.
"""
# We set the regex to match in order to bypass the execution of
# PyFunceble.
regex_bypass = r"\[PyFunceble\sskip\]"
if (
PyFunceble.CONFIGURATION["travis"]
and Regex(
Command("git log -1").execute(), regex_bypass, return_data=False
).match()
):
# * We are under Travis CI.
# and
# * The bypass marker is matched into the latest commit.
# We save everything and stop PyFunceble.
AutoSave(True, is_bypass=True)
|
[
"Exit",
"the",
"script",
"if",
":",
"code",
":",
"[",
"PyFunceble",
"skip",
"]",
"is",
"matched",
"into",
"the",
"latest",
"commit",
"message",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L561-L582
|
[
"def",
"bypass",
"(",
"cls",
")",
":",
"# We set the regex to match in order to bypass the execution of",
"# PyFunceble.",
"regex_bypass",
"=",
"r\"\\[PyFunceble\\sskip\\]\"",
"if",
"(",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"travis\"",
"]",
"and",
"Regex",
"(",
"Command",
"(",
"\"git log -1\"",
")",
".",
"execute",
"(",
")",
",",
"regex_bypass",
",",
"return_data",
"=",
"False",
")",
".",
"match",
"(",
")",
")",
":",
"# * We are under Travis CI.",
"# and",
"# * The bypass marker is matched into the latest commit.",
"# We save everything and stop PyFunceble.",
"AutoSave",
"(",
"True",
",",
"is_bypass",
"=",
"True",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core._print_header
|
Decide if we print or not the header.
|
PyFunceble/core.py
|
def _print_header(cls):
"""
Decide if we print or not the header.
"""
if (
not PyFunceble.CONFIGURATION["quiet"]
and not PyFunceble.CONFIGURATION["header_printed"]
):
# * The quiet mode is not activated.
# and
# * The header has not been already printed.
# We print a new line.
print("\n")
if PyFunceble.CONFIGURATION["less"]:
# We have to show less informations on screen.
# We print the `Less` header.
Prints(None, "Less").header()
else:
# We have to show every informations on screen.
# We print the `Generic` header.
Prints(None, "Generic").header()
# The header was printed.
# We initiate the variable which say that the header has been printed to True.
PyFunceble.CONFIGURATION["header_printed"] = True
|
def _print_header(cls):
"""
Decide if we print or not the header.
"""
if (
not PyFunceble.CONFIGURATION["quiet"]
and not PyFunceble.CONFIGURATION["header_printed"]
):
# * The quiet mode is not activated.
# and
# * The header has not been already printed.
# We print a new line.
print("\n")
if PyFunceble.CONFIGURATION["less"]:
# We have to show less informations on screen.
# We print the `Less` header.
Prints(None, "Less").header()
else:
# We have to show every informations on screen.
# We print the `Generic` header.
Prints(None, "Generic").header()
# The header was printed.
# We initiate the variable which say that the header has been printed to True.
PyFunceble.CONFIGURATION["header_printed"] = True
|
[
"Decide",
"if",
"we",
"print",
"or",
"not",
"the",
"header",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L585-L615
|
[
"def",
"_print_header",
"(",
"cls",
")",
":",
"if",
"(",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
"and",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"header_printed\"",
"]",
")",
":",
"# * The quiet mode is not activated.",
"# and",
"# * The header has not been already printed.",
"# We print a new line.",
"print",
"(",
"\"\\n\"",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"less\"",
"]",
":",
"# We have to show less informations on screen.",
"# We print the `Less` header.",
"Prints",
"(",
"None",
",",
"\"Less\"",
")",
".",
"header",
"(",
")",
"else",
":",
"# We have to show every informations on screen.",
"# We print the `Generic` header.",
"Prints",
"(",
"None",
",",
"\"Generic\"",
")",
".",
"header",
"(",
")",
"# The header was printed.",
"# We initiate the variable which say that the header has been printed to True.",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"header_printed\"",
"]",
"=",
"True"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core._file_decision
|
Manage the database, autosave and autocontinue systems for the case that we are reading
a file.
:param current: The currently tested element.
:type current: str
:param last: The last element of the list.
:type last: str
:param status: The status of the currently tested element.
:type status: str
|
PyFunceble/core.py
|
def _file_decision(self, current, last, status=None):
"""
Manage the database, autosave and autocontinue systems for the case that we are reading
a file.
:param current: The currently tested element.
:type current: str
:param last: The last element of the list.
:type last: str
:param status: The status of the currently tested element.
:type status: str
"""
if (
status
and not PyFunceble.CONFIGURATION["simple"]
and PyFunceble.INTERN["file_to_test"]
):
# * The status is given.
# and
# * The simple mode is deactivated.
# and
# * A file to test is set.
# We run the mining logic.
self.mining.process()
# We delete the currently tested element from the mining
# database.
# Indeed, as it is tested, it is already in our
# testing process which means that we don't need it into
# the mining database.
self.mining.remove()
if (
status.lower() in PyFunceble.STATUS["list"]["up"]
or status.lower() in PyFunceble.STATUS["list"]["valid"]
):
# The status is in the list of up status.
if self.inactive_database.is_present():
# The currently tested element is in the database.
# We generate the suspicious file(s).
Generate(PyFunceble.STATUS["official"]["up"]).analytic_file(
"suspicious"
)
# We remove the currently tested element from the
# database.
self.inactive_database.remove()
else:
# The status is not in the list of up status.
# We add the currently tested element to the
# database.
self.inactive_database.add()
# We backup the current state of the file reading
# for the case that we need to continue later.
self.auto_continue.backup()
if current != last:
# The current element is not the last one.
# We run the autosave logic.
AutoSave()
else:
# The current element is the last one.
# We stop and log the execution time.
ExecutionTime("stop", last=True)
# We show/log the percentage.
self.percentage.log()
# We reset the counters as we end the process.
self.reset_counters()
# We backup the current state of the file reading
# for the case that we need to continue later.
self.auto_continue.backup()
# We show the colored logo.
self.colorify_logo()
# We save and stop the script if we are under
# Travis CI.
AutoSave(True)
for index in ["http_code", "referer"]:
# We loop through some configuration index we have to empty.
if index in PyFunceble.INTERN:
# The index is in the configuration.
# We empty the configuration index.
PyFunceble.INTERN[index] = ""
|
def _file_decision(self, current, last, status=None):
"""
Manage the database, autosave and autocontinue systems for the case that we are reading
a file.
:param current: The currently tested element.
:type current: str
:param last: The last element of the list.
:type last: str
:param status: The status of the currently tested element.
:type status: str
"""
if (
status
and not PyFunceble.CONFIGURATION["simple"]
and PyFunceble.INTERN["file_to_test"]
):
# * The status is given.
# and
# * The simple mode is deactivated.
# and
# * A file to test is set.
# We run the mining logic.
self.mining.process()
# We delete the currently tested element from the mining
# database.
# Indeed, as it is tested, it is already in our
# testing process which means that we don't need it into
# the mining database.
self.mining.remove()
if (
status.lower() in PyFunceble.STATUS["list"]["up"]
or status.lower() in PyFunceble.STATUS["list"]["valid"]
):
# The status is in the list of up status.
if self.inactive_database.is_present():
# The currently tested element is in the database.
# We generate the suspicious file(s).
Generate(PyFunceble.STATUS["official"]["up"]).analytic_file(
"suspicious"
)
# We remove the currently tested element from the
# database.
self.inactive_database.remove()
else:
# The status is not in the list of up status.
# We add the currently tested element to the
# database.
self.inactive_database.add()
# We backup the current state of the file reading
# for the case that we need to continue later.
self.auto_continue.backup()
if current != last:
# The current element is not the last one.
# We run the autosave logic.
AutoSave()
else:
# The current element is the last one.
# We stop and log the execution time.
ExecutionTime("stop", last=True)
# We show/log the percentage.
self.percentage.log()
# We reset the counters as we end the process.
self.reset_counters()
# We backup the current state of the file reading
# for the case that we need to continue later.
self.auto_continue.backup()
# We show the colored logo.
self.colorify_logo()
# We save and stop the script if we are under
# Travis CI.
AutoSave(True)
for index in ["http_code", "referer"]:
# We loop through some configuration index we have to empty.
if index in PyFunceble.INTERN:
# The index is in the configuration.
# We empty the configuration index.
PyFunceble.INTERN[index] = ""
|
[
"Manage",
"the",
"database",
"autosave",
"and",
"autocontinue",
"systems",
"for",
"the",
"case",
"that",
"we",
"are",
"reading",
"a",
"file",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L617-L717
|
[
"def",
"_file_decision",
"(",
"self",
",",
"current",
",",
"last",
",",
"status",
"=",
"None",
")",
":",
"if",
"(",
"status",
"and",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"simple\"",
"]",
"and",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
")",
":",
"# * The status is given.",
"# and",
"# * The simple mode is deactivated.",
"# and",
"# * A file to test is set.",
"# We run the mining logic.",
"self",
".",
"mining",
".",
"process",
"(",
")",
"# We delete the currently tested element from the mining",
"# database.",
"# Indeed, as it is tested, it is already in our",
"# testing process which means that we don't need it into",
"# the mining database.",
"self",
".",
"mining",
".",
"remove",
"(",
")",
"if",
"(",
"status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"up\"",
"]",
"or",
"status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"valid\"",
"]",
")",
":",
"# The status is in the list of up status.",
"if",
"self",
".",
"inactive_database",
".",
"is_present",
"(",
")",
":",
"# The currently tested element is in the database.",
"# We generate the suspicious file(s).",
"Generate",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
")",
".",
"analytic_file",
"(",
"\"suspicious\"",
")",
"# We remove the currently tested element from the",
"# database.",
"self",
".",
"inactive_database",
".",
"remove",
"(",
")",
"else",
":",
"# The status is not in the list of up status.",
"# We add the currently tested element to the",
"# database.",
"self",
".",
"inactive_database",
".",
"add",
"(",
")",
"# We backup the current state of the file reading",
"# for the case that we need to continue later.",
"self",
".",
"auto_continue",
".",
"backup",
"(",
")",
"if",
"current",
"!=",
"last",
":",
"# The current element is not the last one.",
"# We run the autosave logic.",
"AutoSave",
"(",
")",
"else",
":",
"# The current element is the last one.",
"# We stop and log the execution time.",
"ExecutionTime",
"(",
"\"stop\"",
",",
"last",
"=",
"True",
")",
"# We show/log the percentage.",
"self",
".",
"percentage",
".",
"log",
"(",
")",
"# We reset the counters as we end the process.",
"self",
".",
"reset_counters",
"(",
")",
"# We backup the current state of the file reading",
"# for the case that we need to continue later.",
"self",
".",
"auto_continue",
".",
"backup",
"(",
")",
"# We show the colored logo.",
"self",
".",
"colorify_logo",
"(",
")",
"# We save and stop the script if we are under",
"# Travis CI.",
"AutoSave",
"(",
"True",
")",
"for",
"index",
"in",
"[",
"\"http_code\"",
",",
"\"referer\"",
"]",
":",
"# We loop through some configuration index we have to empty.",
"if",
"index",
"in",
"PyFunceble",
".",
"INTERN",
":",
"# The index is in the configuration.",
"# We empty the configuration index.",
"PyFunceble",
".",
"INTERN",
"[",
"index",
"]",
"=",
"\"\""
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core.domain
|
Manage the case that we want to test only a domain.
:param domain: The domain or IP to test.
:type domain: str
:param last_domain:
The last domain to test if we are testing a file.
:type last_domain: str
:param return_status: Tell us if we need to return the status.
:type return_status: bool
|
PyFunceble/core.py
|
def domain(self, domain=None, last_domain=None):
"""
Manage the case that we want to test only a domain.
:param domain: The domain or IP to test.
:type domain: str
:param last_domain:
The last domain to test if we are testing a file.
:type last_domain: str
:param return_status: Tell us if we need to return the status.
:type return_status: bool
"""
# We print the header.
self._print_header()
if domain:
# A domain is given.
# We format and set the domain we are testing and treating.
PyFunceble.INTERN["to_test"] = self._format_domain(domain)
else:
# A domain is not given.
# We set the domain we are testing and treating to None.
PyFunceble.INTERN["to_test"] = None
if PyFunceble.INTERN["to_test"]:
# The domain is given (Not None).
if PyFunceble.CONFIGURATION["syntax"]:
# The syntax mode is activated.
# We get the status from Syntax.
status = self.syntax_status.get()
else:
# We test and get the status of the domain.
status, _ = self.status.get()
# We run the file decision logic.
self._file_decision(PyFunceble.INTERN["to_test"], last_domain, status)
if PyFunceble.CONFIGURATION["simple"]:
# The simple mode is activated.
# We print the domain and the status.
print(PyFunceble.INTERN["to_test"], status)
# We return the tested domain and its status.
return PyFunceble.INTERN["to_test"], status
# We return None, there is nothing to test.
return None
|
def domain(self, domain=None, last_domain=None):
"""
Manage the case that we want to test only a domain.
:param domain: The domain or IP to test.
:type domain: str
:param last_domain:
The last domain to test if we are testing a file.
:type last_domain: str
:param return_status: Tell us if we need to return the status.
:type return_status: bool
"""
# We print the header.
self._print_header()
if domain:
# A domain is given.
# We format and set the domain we are testing and treating.
PyFunceble.INTERN["to_test"] = self._format_domain(domain)
else:
# A domain is not given.
# We set the domain we are testing and treating to None.
PyFunceble.INTERN["to_test"] = None
if PyFunceble.INTERN["to_test"]:
# The domain is given (Not None).
if PyFunceble.CONFIGURATION["syntax"]:
# The syntax mode is activated.
# We get the status from Syntax.
status = self.syntax_status.get()
else:
# We test and get the status of the domain.
status, _ = self.status.get()
# We run the file decision logic.
self._file_decision(PyFunceble.INTERN["to_test"], last_domain, status)
if PyFunceble.CONFIGURATION["simple"]:
# The simple mode is activated.
# We print the domain and the status.
print(PyFunceble.INTERN["to_test"], status)
# We return the tested domain and its status.
return PyFunceble.INTERN["to_test"], status
# We return None, there is nothing to test.
return None
|
[
"Manage",
"the",
"case",
"that",
"we",
"want",
"to",
"test",
"only",
"a",
"domain",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L719-L773
|
[
"def",
"domain",
"(",
"self",
",",
"domain",
"=",
"None",
",",
"last_domain",
"=",
"None",
")",
":",
"# We print the header.",
"self",
".",
"_print_header",
"(",
")",
"if",
"domain",
":",
"# A domain is given.",
"# We format and set the domain we are testing and treating.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
"=",
"self",
".",
"_format_domain",
"(",
"domain",
")",
"else",
":",
"# A domain is not given.",
"# We set the domain we are testing and treating to None.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
"=",
"None",
"if",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
":",
"# The domain is given (Not None).",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"syntax\"",
"]",
":",
"# The syntax mode is activated.",
"# We get the status from Syntax.",
"status",
"=",
"self",
".",
"syntax_status",
".",
"get",
"(",
")",
"else",
":",
"# We test and get the status of the domain.",
"status",
",",
"_",
"=",
"self",
".",
"status",
".",
"get",
"(",
")",
"# We run the file decision logic.",
"self",
".",
"_file_decision",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
",",
"last_domain",
",",
"status",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"simple\"",
"]",
":",
"# The simple mode is activated.",
"# We print the domain and the status.",
"print",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
",",
"status",
")",
"# We return the tested domain and its status.",
"return",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
",",
"status",
"# We return None, there is nothing to test.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core.url
|
Manage the case that we want to test only a given url.
:param url_to_test: The url to test.
:type url_to_test: str
:param last_url:
The last url of the file we are testing
(if exist)
:type last_url: str
|
PyFunceble/core.py
|
def url(self, url_to_test=None, last_url=None):
"""
Manage the case that we want to test only a given url.
:param url_to_test: The url to test.
:type url_to_test: str
:param last_url:
The last url of the file we are testing
(if exist)
:type last_url: str
"""
# We print the header.
self._print_header()
if url_to_test:
# An url to test is given.
# We set the url we are going to test.
PyFunceble.INTERN["to_test"] = url_to_test
else:
# An URL to test is not given.
# We set the url we are going to test to None.
PyFunceble.INTERN["to_test"] = None
if PyFunceble.INTERN["to_test"]:
# An URL to test is given.
if PyFunceble.CONFIGURATION["syntax"]:
# The syntax mode is activated.
# We get the status from Syntax.
status = self.syntax_status.get()
else:
# The syntax mode is not activated.
# We get the status from URL.
status = self.url_status.get()
# We run the file decision logic.
self._file_decision(PyFunceble.INTERN["to_test"], last_url, status)
if PyFunceble.CONFIGURATION["simple"]:
# The simple mode is activated.
# We print the URL informations.
print(PyFunceble.INTERN["to_test"], status)
# We return the URL we tested and its status.
return PyFunceble.INTERN["to_test"], status
# We return None, there is nothing to test.
return None
|
def url(self, url_to_test=None, last_url=None):
"""
Manage the case that we want to test only a given url.
:param url_to_test: The url to test.
:type url_to_test: str
:param last_url:
The last url of the file we are testing
(if exist)
:type last_url: str
"""
# We print the header.
self._print_header()
if url_to_test:
# An url to test is given.
# We set the url we are going to test.
PyFunceble.INTERN["to_test"] = url_to_test
else:
# An URL to test is not given.
# We set the url we are going to test to None.
PyFunceble.INTERN["to_test"] = None
if PyFunceble.INTERN["to_test"]:
# An URL to test is given.
if PyFunceble.CONFIGURATION["syntax"]:
# The syntax mode is activated.
# We get the status from Syntax.
status = self.syntax_status.get()
else:
# The syntax mode is not activated.
# We get the status from URL.
status = self.url_status.get()
# We run the file decision logic.
self._file_decision(PyFunceble.INTERN["to_test"], last_url, status)
if PyFunceble.CONFIGURATION["simple"]:
# The simple mode is activated.
# We print the URL informations.
print(PyFunceble.INTERN["to_test"], status)
# We return the URL we tested and its status.
return PyFunceble.INTERN["to_test"], status
# We return None, there is nothing to test.
return None
|
[
"Manage",
"the",
"case",
"that",
"we",
"want",
"to",
"test",
"only",
"a",
"given",
"url",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L775-L829
|
[
"def",
"url",
"(",
"self",
",",
"url_to_test",
"=",
"None",
",",
"last_url",
"=",
"None",
")",
":",
"# We print the header.",
"self",
".",
"_print_header",
"(",
")",
"if",
"url_to_test",
":",
"# An url to test is given.",
"# We set the url we are going to test.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
"=",
"url_to_test",
"else",
":",
"# An URL to test is not given.",
"# We set the url we are going to test to None.",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
"=",
"None",
"if",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
":",
"# An URL to test is given.",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"syntax\"",
"]",
":",
"# The syntax mode is activated.",
"# We get the status from Syntax.",
"status",
"=",
"self",
".",
"syntax_status",
".",
"get",
"(",
")",
"else",
":",
"# The syntax mode is not activated.",
"# We get the status from URL.",
"status",
"=",
"self",
".",
"url_status",
".",
"get",
"(",
")",
"# We run the file decision logic.",
"self",
".",
"_file_decision",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
",",
"last_url",
",",
"status",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"simple\"",
"]",
":",
"# The simple mode is activated.",
"# We print the URL informations.",
"print",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
",",
"status",
")",
"# We return the URL we tested and its status.",
"return",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
",",
"status",
"# We return None, there is nothing to test.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core.colorify_logo
|
Print the colored logo based on global results.
:param home: Tell us if we have to print the initial coloration.
:type home: bool
|
PyFunceble/core.py
|
def colorify_logo(cls, home=False):
"""
Print the colored logo based on global results.
:param home: Tell us if we have to print the initial coloration.
:type home: bool
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
to_print = []
if home:
# We have to print the initial logo.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(
PyFunceble.Fore.YELLOW + line + PyFunceble.Fore.RESET
)
elif PyFunceble.INTERN["counter"]["percentage"]["up"] >= 50:
# The percentage of up is greater or equal to 50%.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(
PyFunceble.Fore.GREEN + line + PyFunceble.Fore.RESET
)
else:
# The percentage of up is less than 50%.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(PyFunceble.Fore.RED + line + PyFunceble.Fore.RESET)
print("\n".join(to_print))
|
def colorify_logo(cls, home=False):
"""
Print the colored logo based on global results.
:param home: Tell us if we have to print the initial coloration.
:type home: bool
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
to_print = []
if home:
# We have to print the initial logo.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(
PyFunceble.Fore.YELLOW + line + PyFunceble.Fore.RESET
)
elif PyFunceble.INTERN["counter"]["percentage"]["up"] >= 50:
# The percentage of up is greater or equal to 50%.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(
PyFunceble.Fore.GREEN + line + PyFunceble.Fore.RESET
)
else:
# The percentage of up is less than 50%.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(PyFunceble.Fore.RED + line + PyFunceble.Fore.RESET)
print("\n".join(to_print))
|
[
"Print",
"the",
"colored",
"logo",
"based",
"on",
"global",
"results",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L844-L893
|
[
"def",
"colorify_logo",
"(",
"cls",
",",
"home",
"=",
"False",
")",
":",
"if",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
":",
"# The quiet mode is not activated.",
"to_print",
"=",
"[",
"]",
"if",
"home",
":",
"# We have to print the initial logo.",
"for",
"line",
"in",
"PyFunceble",
".",
"ASCII_PYFUNCEBLE",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"# We loop through each lines of the ASCII representation",
"# of PyFunceble.",
"# And we append to the data to print the currently read",
"# line with the right coloration.",
"to_print",
".",
"append",
"(",
"PyFunceble",
".",
"Fore",
".",
"YELLOW",
"+",
"line",
"+",
"PyFunceble",
".",
"Fore",
".",
"RESET",
")",
"elif",
"PyFunceble",
".",
"INTERN",
"[",
"\"counter\"",
"]",
"[",
"\"percentage\"",
"]",
"[",
"\"up\"",
"]",
">=",
"50",
":",
"# The percentage of up is greater or equal to 50%.",
"for",
"line",
"in",
"PyFunceble",
".",
"ASCII_PYFUNCEBLE",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"# We loop through each lines of the ASCII representation",
"# of PyFunceble.",
"# And we append to the data to print the currently read",
"# line with the right coloration.",
"to_print",
".",
"append",
"(",
"PyFunceble",
".",
"Fore",
".",
"GREEN",
"+",
"line",
"+",
"PyFunceble",
".",
"Fore",
".",
"RESET",
")",
"else",
":",
"# The percentage of up is less than 50%.",
"for",
"line",
"in",
"PyFunceble",
".",
"ASCII_PYFUNCEBLE",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"# We loop through each lines of the ASCII representation",
"# of PyFunceble.",
"# And we append to the data to print the currently read",
"# line with the right coloration.",
"to_print",
".",
"append",
"(",
"PyFunceble",
".",
"Fore",
".",
"RED",
"+",
"line",
"+",
"PyFunceble",
".",
"Fore",
".",
"RESET",
")",
"print",
"(",
"\"\\n\"",
".",
"join",
"(",
"to_print",
")",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core._format_domain
|
Format the extracted domain before passing it to the system.
:param extracted_domain: The extracted domain.
:type extracted_domain: str
:return: The formatted domain or IP to test.
:rtype: str
.. note:
Understand by formating the fact that we get rid
of all the noises around the domain we want to test.
|
PyFunceble/core.py
|
def _format_domain(cls, extracted_domain):
"""
Format the extracted domain before passing it to the system.
:param extracted_domain: The extracted domain.
:type extracted_domain: str
:return: The formatted domain or IP to test.
:rtype: str
.. note:
Understand by formating the fact that we get rid
of all the noises around the domain we want to test.
"""
if not extracted_domain.startswith("#"):
# The line is not a commented line.
if "#" in extracted_domain:
# There is a comment at the end of the line.
# We delete the comment from the line.
extracted_domain = extracted_domain[
: extracted_domain.find("#")
].strip()
if " " in extracted_domain or "\t" in extracted_domain:
# A space or a tabs is in the line.
# We remove all whitestring from the extracted line.
splited_line = extracted_domain.split()
# As there was a space or a tab in the string, we consider
# that we are working with the hosts file format which means
# that the domain we have to test is after the first string.
# So we set the index to 1.
index = 1
while index < len(splited_line):
# We loop until the index is greater than the length of
# the splited line.
if splited_line[index]:
# The element at the current index is not an empty string.
# We break the loop.
break
# The element at the current index is an empty string.
# We increase the index number.
index += 1
# We return the last read element.
return splited_line[index]
# We return the extracted line.
return extracted_domain
# The extracted line is a comment line.
# We return an empty string as we do not want to work with commented line.
return ""
|
def _format_domain(cls, extracted_domain):
"""
Format the extracted domain before passing it to the system.
:param extracted_domain: The extracted domain.
:type extracted_domain: str
:return: The formatted domain or IP to test.
:rtype: str
.. note:
Understand by formating the fact that we get rid
of all the noises around the domain we want to test.
"""
if not extracted_domain.startswith("#"):
# The line is not a commented line.
if "#" in extracted_domain:
# There is a comment at the end of the line.
# We delete the comment from the line.
extracted_domain = extracted_domain[
: extracted_domain.find("#")
].strip()
if " " in extracted_domain or "\t" in extracted_domain:
# A space or a tabs is in the line.
# We remove all whitestring from the extracted line.
splited_line = extracted_domain.split()
# As there was a space or a tab in the string, we consider
# that we are working with the hosts file format which means
# that the domain we have to test is after the first string.
# So we set the index to 1.
index = 1
while index < len(splited_line):
# We loop until the index is greater than the length of
# the splited line.
if splited_line[index]:
# The element at the current index is not an empty string.
# We break the loop.
break
# The element at the current index is an empty string.
# We increase the index number.
index += 1
# We return the last read element.
return splited_line[index]
# We return the extracted line.
return extracted_domain
# The extracted line is a comment line.
# We return an empty string as we do not want to work with commented line.
return ""
|
[
"Format",
"the",
"extracted",
"domain",
"before",
"passing",
"it",
"to",
"the",
"system",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L896-L958
|
[
"def",
"_format_domain",
"(",
"cls",
",",
"extracted_domain",
")",
":",
"if",
"not",
"extracted_domain",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"# The line is not a commented line.",
"if",
"\"#\"",
"in",
"extracted_domain",
":",
"# There is a comment at the end of the line.",
"# We delete the comment from the line.",
"extracted_domain",
"=",
"extracted_domain",
"[",
":",
"extracted_domain",
".",
"find",
"(",
"\"#\"",
")",
"]",
".",
"strip",
"(",
")",
"if",
"\" \"",
"in",
"extracted_domain",
"or",
"\"\\t\"",
"in",
"extracted_domain",
":",
"# A space or a tabs is in the line.",
"# We remove all whitestring from the extracted line.",
"splited_line",
"=",
"extracted_domain",
".",
"split",
"(",
")",
"# As there was a space or a tab in the string, we consider",
"# that we are working with the hosts file format which means",
"# that the domain we have to test is after the first string.",
"# So we set the index to 1.",
"index",
"=",
"1",
"while",
"index",
"<",
"len",
"(",
"splited_line",
")",
":",
"# We loop until the index is greater than the length of",
"# the splited line.",
"if",
"splited_line",
"[",
"index",
"]",
":",
"# The element at the current index is not an empty string.",
"# We break the loop.",
"break",
"# The element at the current index is an empty string.",
"# We increase the index number.",
"index",
"+=",
"1",
"# We return the last read element.",
"return",
"splited_line",
"[",
"index",
"]",
"# We return the extracted line.",
"return",
"extracted_domain",
"# The extracted line is a comment line.",
"# We return an empty string as we do not want to work with commented line.",
"return",
"\"\""
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core._extract_domain_from_file
|
Extract all non commented lines from the file we are testing.
:return: The elements to test.
:rtype: list
|
PyFunceble/core.py
|
def _extract_domain_from_file(cls):
"""
Extract all non commented lines from the file we are testing.
:return: The elements to test.
:rtype: list
"""
# We initiate the variable which will save what we are going to return.
result = []
if PyFunceble.path.isfile(PyFunceble.INTERN["file_to_test"]):
# The give file to test exist.
try:
with open(PyFunceble.INTERN["file_to_test"]) as file:
# We open and read the file.
for line in file:
# We loop through each lines.
if not line.startswith("#"):
# The currently read line is not a commented line.
# We append the current read line to the result.
result.append(line.rstrip("\n").strip())
except UnicodeDecodeError:
with open(PyFunceble.INTERN["file_to_test"], encoding="utf-8") as file:
# We open and read the file.
for line in file:
# We loop through each lines.
if not line.startswith("#"):
# The currently read line is not a commented line.
# We append the current read line to the result.
result.append(line.rstrip("\n").strip())
else:
# The given file to test does not exist.
# We raise a FileNotFoundError exception.
raise FileNotFoundError(PyFunceble.INTERN["file_to_test"])
# We return the result.
return result
|
def _extract_domain_from_file(cls):
"""
Extract all non commented lines from the file we are testing.
:return: The elements to test.
:rtype: list
"""
# We initiate the variable which will save what we are going to return.
result = []
if PyFunceble.path.isfile(PyFunceble.INTERN["file_to_test"]):
# The give file to test exist.
try:
with open(PyFunceble.INTERN["file_to_test"]) as file:
# We open and read the file.
for line in file:
# We loop through each lines.
if not line.startswith("#"):
# The currently read line is not a commented line.
# We append the current read line to the result.
result.append(line.rstrip("\n").strip())
except UnicodeDecodeError:
with open(PyFunceble.INTERN["file_to_test"], encoding="utf-8") as file:
# We open and read the file.
for line in file:
# We loop through each lines.
if not line.startswith("#"):
# The currently read line is not a commented line.
# We append the current read line to the result.
result.append(line.rstrip("\n").strip())
else:
# The given file to test does not exist.
# We raise a FileNotFoundError exception.
raise FileNotFoundError(PyFunceble.INTERN["file_to_test"])
# We return the result.
return result
|
[
"Extract",
"all",
"non",
"commented",
"lines",
"from",
"the",
"file",
"we",
"are",
"testing",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L961-L1007
|
[
"def",
"_extract_domain_from_file",
"(",
"cls",
")",
":",
"# We initiate the variable which will save what we are going to return.",
"result",
"=",
"[",
"]",
"if",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
")",
":",
"# The give file to test exist.",
"try",
":",
"with",
"open",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
")",
"as",
"file",
":",
"# We open and read the file.",
"for",
"line",
"in",
"file",
":",
"# We loop through each lines.",
"if",
"not",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"# The currently read line is not a commented line.",
"# We append the current read line to the result.",
"result",
".",
"append",
"(",
"line",
".",
"rstrip",
"(",
"\"\\n\"",
")",
".",
"strip",
"(",
")",
")",
"except",
"UnicodeDecodeError",
":",
"with",
"open",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"file",
":",
"# We open and read the file.",
"for",
"line",
"in",
"file",
":",
"# We loop through each lines.",
"if",
"not",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"# The currently read line is not a commented line.",
"# We append the current read line to the result.",
"result",
".",
"append",
"(",
"line",
".",
"rstrip",
"(",
"\"\\n\"",
")",
".",
"strip",
"(",
")",
")",
"else",
":",
"# The given file to test does not exist.",
"# We raise a FileNotFoundError exception.",
"raise",
"FileNotFoundError",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
")",
"# We return the result.",
"return",
"result"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core.file
|
Manage the case that need to test each domain of a given file path.
.. note::
1 domain per line.
|
PyFunceble/core.py
|
def file(self):
"""
Manage the case that need to test each domain of a given file path.
.. note::
1 domain per line.
"""
# We get, format, filter, clean the list to test.
list_to_test = self._file_list_to_test_filtering()
if PyFunceble.CONFIGURATION["idna_conversion"]:
# We have to convert domains to idna.
# We convert if we need to convert.
list_to_test = domain2idna(list_to_test)
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list_to_test).custom_format(Sort.hierarchical)
else:
# The hierarchical sorting is not desired by the user.
# We format the list.
list_to_test = List(list_to_test).custom_format(Sort.standard)
# We initiate a local variable which will save the current state of the list.
not_filtered = list_to_test
try:
# We remove the element which are in the database from the
# current list to test.
list_to_test = List(
list(
set(
list_to_test[PyFunceble.INTERN["counter"]["number"]["tested"] :]
)
- set(PyFunceble.INTERN["flatten_inactive_db"])
)
).format()
_ = list_to_test[-1]
except IndexError:
# Our list to test is the one with the element from the database.
list_to_test = not_filtered[
PyFunceble.INTERN["counter"]["number"]["tested"] :
]
# We delete the undesired variable.
del not_filtered
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list(list_to_test)).custom_format(Sort.hierarchical)
try:
# We test each element of the list to test.
return [self.domain(x, list_to_test[-1]) for x in list_to_test if x]
except IndexError:
# We print a message on screen.
print(PyFunceble.Fore.CYAN + PyFunceble.Style.BRIGHT + "Nothing to test.")
|
def file(self):
"""
Manage the case that need to test each domain of a given file path.
.. note::
1 domain per line.
"""
# We get, format, filter, clean the list to test.
list_to_test = self._file_list_to_test_filtering()
if PyFunceble.CONFIGURATION["idna_conversion"]:
# We have to convert domains to idna.
# We convert if we need to convert.
list_to_test = domain2idna(list_to_test)
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list_to_test).custom_format(Sort.hierarchical)
else:
# The hierarchical sorting is not desired by the user.
# We format the list.
list_to_test = List(list_to_test).custom_format(Sort.standard)
# We initiate a local variable which will save the current state of the list.
not_filtered = list_to_test
try:
# We remove the element which are in the database from the
# current list to test.
list_to_test = List(
list(
set(
list_to_test[PyFunceble.INTERN["counter"]["number"]["tested"] :]
)
- set(PyFunceble.INTERN["flatten_inactive_db"])
)
).format()
_ = list_to_test[-1]
except IndexError:
# Our list to test is the one with the element from the database.
list_to_test = not_filtered[
PyFunceble.INTERN["counter"]["number"]["tested"] :
]
# We delete the undesired variable.
del not_filtered
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list(list_to_test)).custom_format(Sort.hierarchical)
try:
# We test each element of the list to test.
return [self.domain(x, list_to_test[-1]) for x in list_to_test if x]
except IndexError:
# We print a message on screen.
print(PyFunceble.Fore.CYAN + PyFunceble.Style.BRIGHT + "Nothing to test.")
|
[
"Manage",
"the",
"case",
"that",
"need",
"to",
"test",
"each",
"domain",
"of",
"a",
"given",
"file",
"path",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L1111-L1174
|
[
"def",
"file",
"(",
"self",
")",
":",
"# We get, format, filter, clean the list to test.",
"list_to_test",
"=",
"self",
".",
"_file_list_to_test_filtering",
"(",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"idna_conversion\"",
"]",
":",
"# We have to convert domains to idna.",
"# We convert if we need to convert.",
"list_to_test",
"=",
"domain2idna",
"(",
"list_to_test",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"hierarchical_sorting\"",
"]",
":",
"# The hierarchical sorting is desired by the user.",
"# We format the list.",
"list_to_test",
"=",
"List",
"(",
"list_to_test",
")",
".",
"custom_format",
"(",
"Sort",
".",
"hierarchical",
")",
"else",
":",
"# The hierarchical sorting is not desired by the user.",
"# We format the list.",
"list_to_test",
"=",
"List",
"(",
"list_to_test",
")",
".",
"custom_format",
"(",
"Sort",
".",
"standard",
")",
"# We initiate a local variable which will save the current state of the list.",
"not_filtered",
"=",
"list_to_test",
"try",
":",
"# We remove the element which are in the database from the",
"# current list to test.",
"list_to_test",
"=",
"List",
"(",
"list",
"(",
"set",
"(",
"list_to_test",
"[",
"PyFunceble",
".",
"INTERN",
"[",
"\"counter\"",
"]",
"[",
"\"number\"",
"]",
"[",
"\"tested\"",
"]",
":",
"]",
")",
"-",
"set",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"flatten_inactive_db\"",
"]",
")",
")",
")",
".",
"format",
"(",
")",
"_",
"=",
"list_to_test",
"[",
"-",
"1",
"]",
"except",
"IndexError",
":",
"# Our list to test is the one with the element from the database.",
"list_to_test",
"=",
"not_filtered",
"[",
"PyFunceble",
".",
"INTERN",
"[",
"\"counter\"",
"]",
"[",
"\"number\"",
"]",
"[",
"\"tested\"",
"]",
":",
"]",
"# We delete the undesired variable.",
"del",
"not_filtered",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"hierarchical_sorting\"",
"]",
":",
"# The hierarchical sorting is desired by the user.",
"# We format the list.",
"list_to_test",
"=",
"List",
"(",
"list",
"(",
"list_to_test",
")",
")",
".",
"custom_format",
"(",
"Sort",
".",
"hierarchical",
")",
"try",
":",
"# We test each element of the list to test.",
"return",
"[",
"self",
".",
"domain",
"(",
"x",
",",
"list_to_test",
"[",
"-",
"1",
"]",
")",
"for",
"x",
"in",
"list_to_test",
"if",
"x",
"]",
"except",
"IndexError",
":",
"# We print a message on screen.",
"print",
"(",
"PyFunceble",
".",
"Fore",
".",
"CYAN",
"+",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"\"Nothing to test.\"",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core.file_url
|
Manage the case that we have to test a file
.. note::
1 URL per line.
|
PyFunceble/core.py
|
def file_url(self):
"""
Manage the case that we have to test a file
.. note::
1 URL per line.
"""
# We get, format, clean the list of URL to test.
list_to_test = self._file_list_to_test_filtering()
# We initiate a local variable which will save the current state of the list.
not_filtered = list_to_test
try:
# We remove the element which are in the database from the
# current list to test.
list_to_test = List(
list(
set(
list_to_test[PyFunceble.INTERN["counter"]["number"]["tested"] :]
)
- set(PyFunceble.INTERN["flatten_inactive_db"])
)
).format()
_ = list_to_test[-1]
except IndexError:
# Our list to test is the one with the element from the database.
list_to_test = not_filtered[
PyFunceble.INTERN["counter"]["number"]["tested"] :
]
# We delete the undesired variable.
del not_filtered
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list(list_to_test)).custom_format(Sort.hierarchical)
try:
# We test each URL from the list to test.
return [self.url(x, list_to_test[-1]) for x in list_to_test if x]
except IndexError:
# We print a message on screen.
print(PyFunceble.Fore.CYAN + PyFunceble.Style.BRIGHT + "Nothing to test.")
|
def file_url(self):
"""
Manage the case that we have to test a file
.. note::
1 URL per line.
"""
# We get, format, clean the list of URL to test.
list_to_test = self._file_list_to_test_filtering()
# We initiate a local variable which will save the current state of the list.
not_filtered = list_to_test
try:
# We remove the element which are in the database from the
# current list to test.
list_to_test = List(
list(
set(
list_to_test[PyFunceble.INTERN["counter"]["number"]["tested"] :]
)
- set(PyFunceble.INTERN["flatten_inactive_db"])
)
).format()
_ = list_to_test[-1]
except IndexError:
# Our list to test is the one with the element from the database.
list_to_test = not_filtered[
PyFunceble.INTERN["counter"]["number"]["tested"] :
]
# We delete the undesired variable.
del not_filtered
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list(list_to_test)).custom_format(Sort.hierarchical)
try:
# We test each URL from the list to test.
return [self.url(x, list_to_test[-1]) for x in list_to_test if x]
except IndexError:
# We print a message on screen.
print(PyFunceble.Fore.CYAN + PyFunceble.Style.BRIGHT + "Nothing to test.")
|
[
"Manage",
"the",
"case",
"that",
"we",
"have",
"to",
"test",
"a",
"file"
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L1176-L1222
|
[
"def",
"file_url",
"(",
"self",
")",
":",
"# We get, format, clean the list of URL to test.",
"list_to_test",
"=",
"self",
".",
"_file_list_to_test_filtering",
"(",
")",
"# We initiate a local variable which will save the current state of the list.",
"not_filtered",
"=",
"list_to_test",
"try",
":",
"# We remove the element which are in the database from the",
"# current list to test.",
"list_to_test",
"=",
"List",
"(",
"list",
"(",
"set",
"(",
"list_to_test",
"[",
"PyFunceble",
".",
"INTERN",
"[",
"\"counter\"",
"]",
"[",
"\"number\"",
"]",
"[",
"\"tested\"",
"]",
":",
"]",
")",
"-",
"set",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"flatten_inactive_db\"",
"]",
")",
")",
")",
".",
"format",
"(",
")",
"_",
"=",
"list_to_test",
"[",
"-",
"1",
"]",
"except",
"IndexError",
":",
"# Our list to test is the one with the element from the database.",
"list_to_test",
"=",
"not_filtered",
"[",
"PyFunceble",
".",
"INTERN",
"[",
"\"counter\"",
"]",
"[",
"\"number\"",
"]",
"[",
"\"tested\"",
"]",
":",
"]",
"# We delete the undesired variable.",
"del",
"not_filtered",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"hierarchical_sorting\"",
"]",
":",
"# The hierarchical sorting is desired by the user.",
"# We format the list.",
"list_to_test",
"=",
"List",
"(",
"list",
"(",
"list_to_test",
")",
")",
".",
"custom_format",
"(",
"Sort",
".",
"hierarchical",
")",
"try",
":",
"# We test each URL from the list to test.",
"return",
"[",
"self",
".",
"url",
"(",
"x",
",",
"list_to_test",
"[",
"-",
"1",
"]",
")",
"for",
"x",
"in",
"list_to_test",
"if",
"x",
"]",
"except",
"IndexError",
":",
"# We print a message on screen.",
"print",
"(",
"PyFunceble",
".",
"Fore",
".",
"CYAN",
"+",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"\"Nothing to test.\"",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Core.switch
|
Switch PyFunceble.CONFIGURATION variables to their opposite.
:param variable:
The variable name to switch.
The variable should be an index our configuration system.
If we want to switch a bool variable, we should parse
it here.
:type variable: str|bool
:param custom:
Let us know if have to switch the parsed variable instead
of our configuration index.
:type custom: bool
:return:
The opposite of the configuration index or the given variable.
:rtype: bool
:raises:
:code:`Exception`
When the configuration is not valid. In other words,
if the PyFunceble.CONFIGURATION[variable_name] is not a bool.
|
PyFunceble/core.py
|
def switch(
cls, variable, custom=False
): # pylint: disable=inconsistent-return-statements
"""
Switch PyFunceble.CONFIGURATION variables to their opposite.
:param variable:
The variable name to switch.
The variable should be an index our configuration system.
If we want to switch a bool variable, we should parse
it here.
:type variable: str|bool
:param custom:
Let us know if have to switch the parsed variable instead
of our configuration index.
:type custom: bool
:return:
The opposite of the configuration index or the given variable.
:rtype: bool
:raises:
:code:`Exception`
When the configuration is not valid. In other words,
if the PyFunceble.CONFIGURATION[variable_name] is not a bool.
"""
if not custom:
# We are not working with custom variable which is not into
# the configuration.
# We get the current state.
current_state = dict.get(PyFunceble.CONFIGURATION, variable)
else:
# We are working with a custom variable which is not into the
# configuration
current_state = variable
if isinstance(current_state, bool):
# The current state is a boolean.
if current_state:
# The current state is equal to True.
# We return False.
return False
# The current state is equal to False.
# We return True.
return True
# The current state is not a boolean.
# We set the message to raise.
to_print = "Impossible to switch %s. Please post an issue to %s"
# We raise an exception inviting the user to report an issue.
raise Exception(
to_print % (repr(variable), PyFunceble.LINKS["repo"] + "/issues.")
)
|
def switch(
cls, variable, custom=False
): # pylint: disable=inconsistent-return-statements
"""
Switch PyFunceble.CONFIGURATION variables to their opposite.
:param variable:
The variable name to switch.
The variable should be an index our configuration system.
If we want to switch a bool variable, we should parse
it here.
:type variable: str|bool
:param custom:
Let us know if have to switch the parsed variable instead
of our configuration index.
:type custom: bool
:return:
The opposite of the configuration index or the given variable.
:rtype: bool
:raises:
:code:`Exception`
When the configuration is not valid. In other words,
if the PyFunceble.CONFIGURATION[variable_name] is not a bool.
"""
if not custom:
# We are not working with custom variable which is not into
# the configuration.
# We get the current state.
current_state = dict.get(PyFunceble.CONFIGURATION, variable)
else:
# We are working with a custom variable which is not into the
# configuration
current_state = variable
if isinstance(current_state, bool):
# The current state is a boolean.
if current_state:
# The current state is equal to True.
# We return False.
return False
# The current state is equal to False.
# We return True.
return True
# The current state is not a boolean.
# We set the message to raise.
to_print = "Impossible to switch %s. Please post an issue to %s"
# We raise an exception inviting the user to report an issue.
raise Exception(
to_print % (repr(variable), PyFunceble.LINKS["repo"] + "/issues.")
)
|
[
"Switch",
"PyFunceble",
".",
"CONFIGURATION",
"variables",
"to",
"their",
"opposite",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/core.py#L1225-L1286
|
[
"def",
"switch",
"(",
"cls",
",",
"variable",
",",
"custom",
"=",
"False",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"if",
"not",
"custom",
":",
"# We are not working with custom variable which is not into",
"# the configuration.",
"# We get the current state.",
"current_state",
"=",
"dict",
".",
"get",
"(",
"PyFunceble",
".",
"CONFIGURATION",
",",
"variable",
")",
"else",
":",
"# We are working with a custom variable which is not into the",
"# configuration",
"current_state",
"=",
"variable",
"if",
"isinstance",
"(",
"current_state",
",",
"bool",
")",
":",
"# The current state is a boolean.",
"if",
"current_state",
":",
"# The current state is equal to True.",
"# We return False.",
"return",
"False",
"# The current state is equal to False.",
"# We return True.",
"return",
"True",
"# The current state is not a boolean.",
"# We set the message to raise.",
"to_print",
"=",
"\"Impossible to switch %s. Please post an issue to %s\"",
"# We raise an exception inviting the user to report an issue.",
"raise",
"Exception",
"(",
"to_print",
"%",
"(",
"repr",
"(",
"variable",
")",
",",
"PyFunceble",
".",
"LINKS",
"[",
"\"repo\"",
"]",
"+",
"\"/issues.\"",
")",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Status.get
|
Get the status while testing for an IP or domain.
.. note::
We consider that the domain or IP we are currently testing
is into :code:`PyFunceble.INTERN["to_test"]`.
|
PyFunceble/status.py
|
def get(cls):
"""
Get the status while testing for an IP or domain.
.. note::
We consider that the domain or IP we are currently testing
is into :code:`PyFunceble.INTERN["to_test"]`.
"""
if "to_test" in PyFunceble.INTERN and PyFunceble.INTERN["to_test"]:
expiration_date = ExpirationDate().get()
if expiration_date is False:
return cls.handle(status="invalid")
if expiration_date == PyFunceble.STATUS["official"]["up"]:
return expiration_date, "WHOIS"
return cls.handle(status="inactive")
raise NotImplementedError("We expect `INTERN['to_test']` to be set.")
|
def get(cls):
"""
Get the status while testing for an IP or domain.
.. note::
We consider that the domain or IP we are currently testing
is into :code:`PyFunceble.INTERN["to_test"]`.
"""
if "to_test" in PyFunceble.INTERN and PyFunceble.INTERN["to_test"]:
expiration_date = ExpirationDate().get()
if expiration_date is False:
return cls.handle(status="invalid")
if expiration_date == PyFunceble.STATUS["official"]["up"]:
return expiration_date, "WHOIS"
return cls.handle(status="inactive")
raise NotImplementedError("We expect `INTERN['to_test']` to be set.")
|
[
"Get",
"the",
"status",
"while",
"testing",
"for",
"an",
"IP",
"or",
"domain",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/status.py#L89-L109
|
[
"def",
"get",
"(",
"cls",
")",
":",
"if",
"\"to_test\"",
"in",
"PyFunceble",
".",
"INTERN",
"and",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
":",
"expiration_date",
"=",
"ExpirationDate",
"(",
")",
".",
"get",
"(",
")",
"if",
"expiration_date",
"is",
"False",
":",
"return",
"cls",
".",
"handle",
"(",
"status",
"=",
"\"invalid\"",
")",
"if",
"expiration_date",
"==",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
":",
"return",
"expiration_date",
",",
"\"WHOIS\"",
"return",
"cls",
".",
"handle",
"(",
"status",
"=",
"\"inactive\"",
")",
"raise",
"NotImplementedError",
"(",
"\"We expect `INTERN['to_test']` to be set.\"",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Status.handle
|
Handle the lack of WHOIS and expiration date. :smile_cat:
:param matched_status: The status that we have to handle.
:type status: str
:param invalid_source:
The source to set when we handle INVALID element.
:type invalid_source: str
:return:
The strus of the domain after generating the files desired
by the user.
:rtype: str
|
PyFunceble/status.py
|
def handle(cls, status, invalid_source="IANA"):
"""
Handle the lack of WHOIS and expiration date. :smile_cat:
:param matched_status: The status that we have to handle.
:type status: str
:param invalid_source:
The source to set when we handle INVALID element.
:type invalid_source: str
:return:
The strus of the domain after generating the files desired
by the user.
:rtype: str
"""
if status.lower() not in PyFunceble.STATUS["list"]["invalid"]:
# The matched status is not in the list of invalid status.
# We initiate the source we are going to parse to the Generate class.
source = "NSLOOKUP"
if Lookup().nslookup():
# We could execute the nslookup logic.
# We get the status and source after extra rules check.
status, source = cls.extra_rules.handle(
PyFunceble.STATUS["official"]["up"], source
)
# We generate the status files with the up status.
Generate(status, source).status_file()
# We return the up status.
return status, source
# We could not execute the nslookup logic.
# We get the status and source after extra rules check.
status, source = cls.extra_rules.handle(
PyFunceble.STATUS["official"]["down"], source
)
# We generate the status file with the down status.
Generate(status, source).status_file()
# We return the down status.
return status, source
# The matched status is in the list of invalid status.
# We get the status and source after extra rules check.
status, source = cls.extra_rules.handle(
PyFunceble.STATUS["official"]["invalid"], invalid_source
)
# We generate the status file with the invalid status.
Generate(status, source).status_file()
# We return the status.
return status, source
|
def handle(cls, status, invalid_source="IANA"):
"""
Handle the lack of WHOIS and expiration date. :smile_cat:
:param matched_status: The status that we have to handle.
:type status: str
:param invalid_source:
The source to set when we handle INVALID element.
:type invalid_source: str
:return:
The strus of the domain after generating the files desired
by the user.
:rtype: str
"""
if status.lower() not in PyFunceble.STATUS["list"]["invalid"]:
# The matched status is not in the list of invalid status.
# We initiate the source we are going to parse to the Generate class.
source = "NSLOOKUP"
if Lookup().nslookup():
# We could execute the nslookup logic.
# We get the status and source after extra rules check.
status, source = cls.extra_rules.handle(
PyFunceble.STATUS["official"]["up"], source
)
# We generate the status files with the up status.
Generate(status, source).status_file()
# We return the up status.
return status, source
# We could not execute the nslookup logic.
# We get the status and source after extra rules check.
status, source = cls.extra_rules.handle(
PyFunceble.STATUS["official"]["down"], source
)
# We generate the status file with the down status.
Generate(status, source).status_file()
# We return the down status.
return status, source
# The matched status is in the list of invalid status.
# We get the status and source after extra rules check.
status, source = cls.extra_rules.handle(
PyFunceble.STATUS["official"]["invalid"], invalid_source
)
# We generate the status file with the invalid status.
Generate(status, source).status_file()
# We return the status.
return status, source
|
[
"Handle",
"the",
"lack",
"of",
"WHOIS",
"and",
"expiration",
"date",
".",
":",
"smile_cat",
":"
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/status.py#L112-L173
|
[
"def",
"handle",
"(",
"cls",
",",
"status",
",",
"invalid_source",
"=",
"\"IANA\"",
")",
":",
"if",
"status",
".",
"lower",
"(",
")",
"not",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"invalid\"",
"]",
":",
"# The matched status is not in the list of invalid status.",
"# We initiate the source we are going to parse to the Generate class.",
"source",
"=",
"\"NSLOOKUP\"",
"if",
"Lookup",
"(",
")",
".",
"nslookup",
"(",
")",
":",
"# We could execute the nslookup logic.",
"# We get the status and source after extra rules check.",
"status",
",",
"source",
"=",
"cls",
".",
"extra_rules",
".",
"handle",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
",",
"source",
")",
"# We generate the status files with the up status.",
"Generate",
"(",
"status",
",",
"source",
")",
".",
"status_file",
"(",
")",
"# We return the up status.",
"return",
"status",
",",
"source",
"# We could not execute the nslookup logic.",
"# We get the status and source after extra rules check.",
"status",
",",
"source",
"=",
"cls",
".",
"extra_rules",
".",
"handle",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"down\"",
"]",
",",
"source",
")",
"# We generate the status file with the down status.",
"Generate",
"(",
"status",
",",
"source",
")",
".",
"status_file",
"(",
")",
"# We return the down status.",
"return",
"status",
",",
"source",
"# The matched status is in the list of invalid status.",
"# We get the status and source after extra rules check.",
"status",
",",
"source",
"=",
"cls",
".",
"extra_rules",
".",
"handle",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"invalid\"",
"]",
",",
"invalid_source",
")",
"# We generate the status file with the invalid status.",
"Generate",
"(",
"status",
",",
"source",
")",
".",
"status_file",
"(",
")",
"# We return the status.",
"return",
"status",
",",
"source"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
URLStatus.handle
|
Handle the backend of the given status.
|
PyFunceble/status.py
|
def handle(self):
"""
Handle the backend of the given status.
"""
# We initiate the source we are going to parse to the Generate class.
source = "URL"
if self.catched.lower() not in PyFunceble.STATUS["list"]["invalid"]:
# The parsed status is not in the list of invalid.
# We generate the status file with the catched status.
Generate(self.catched, source).status_file()
else:
# The parsed status is in the list of invalid.
# We generate the status file with the parsed status.
Generate(self.catched, "SYNTAX").status_file()
# We return the parsed status.
return self.catched
|
def handle(self):
"""
Handle the backend of the given status.
"""
# We initiate the source we are going to parse to the Generate class.
source = "URL"
if self.catched.lower() not in PyFunceble.STATUS["list"]["invalid"]:
# The parsed status is not in the list of invalid.
# We generate the status file with the catched status.
Generate(self.catched, source).status_file()
else:
# The parsed status is in the list of invalid.
# We generate the status file with the parsed status.
Generate(self.catched, "SYNTAX").status_file()
# We return the parsed status.
return self.catched
|
[
"Handle",
"the",
"backend",
"of",
"the",
"given",
"status",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/status.py#L603-L623
|
[
"def",
"handle",
"(",
"self",
")",
":",
"# We initiate the source we are going to parse to the Generate class.",
"source",
"=",
"\"URL\"",
"if",
"self",
".",
"catched",
".",
"lower",
"(",
")",
"not",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"invalid\"",
"]",
":",
"# The parsed status is not in the list of invalid.",
"# We generate the status file with the catched status.",
"Generate",
"(",
"self",
".",
"catched",
",",
"source",
")",
".",
"status_file",
"(",
")",
"else",
":",
"# The parsed status is in the list of invalid.",
"# We generate the status file with the parsed status.",
"Generate",
"(",
"self",
".",
"catched",
",",
"\"SYNTAX\"",
")",
".",
"status_file",
"(",
")",
"# We return the parsed status.",
"return",
"self",
".",
"catched"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
DirectoryStructure.backup
|
Backup the developer state of `output/` in order to make it restorable
and portable for user.
|
PyFunceble/directory_structure.py
|
def backup(self):
"""
Backup the developer state of `output/` in order to make it restorable
and portable for user.
"""
# We set the current output directory path.
output_path = self.base + PyFunceble.OUTPUTS["parent_directory"]
# We initiate the structure base.
result = {PyFunceble.OUTPUTS["parent_directory"]: {}}
for root, _, files in PyFunceble.walk(output_path):
# We loop through the current output directory structure.
# We get the currently read directory name.
directories = Directory(root.split(output_path)[1]).fix_path()
# We initiate a local variable which will get the structure of the subdirectory.
local_result = result[PyFunceble.OUTPUTS["parent_directory"]]
for file in files:
# We loop through the list of files.
# We construct the file path.
file_path = root + PyFunceble.directory_separator + file
# We get the hash of the file.
file_hash = Hash(file_path, "sha512", True).get()
# We convert the file content to a list.
lines_in_list = [line.rstrip("\n") for line in open(file_path)]
# We convert the file content into a more flat format.
# We use `@@@` as glue and implicitly replacement for `\n`.
formatted_content = "@@@".join(lines_in_list)
# We update the local result (and implicitly the global result)
# with the files and directory informations/structure.
local_result = local_result.setdefault(
directories,
{file: {"sha512": file_hash, "content": formatted_content}},
)
# We finally save the directory structure into the production file.
Dict(result).to_json(self.base + "dir_structure_production.json")
|
def backup(self):
"""
Backup the developer state of `output/` in order to make it restorable
and portable for user.
"""
# We set the current output directory path.
output_path = self.base + PyFunceble.OUTPUTS["parent_directory"]
# We initiate the structure base.
result = {PyFunceble.OUTPUTS["parent_directory"]: {}}
for root, _, files in PyFunceble.walk(output_path):
# We loop through the current output directory structure.
# We get the currently read directory name.
directories = Directory(root.split(output_path)[1]).fix_path()
# We initiate a local variable which will get the structure of the subdirectory.
local_result = result[PyFunceble.OUTPUTS["parent_directory"]]
for file in files:
# We loop through the list of files.
# We construct the file path.
file_path = root + PyFunceble.directory_separator + file
# We get the hash of the file.
file_hash = Hash(file_path, "sha512", True).get()
# We convert the file content to a list.
lines_in_list = [line.rstrip("\n") for line in open(file_path)]
# We convert the file content into a more flat format.
# We use `@@@` as glue and implicitly replacement for `\n`.
formatted_content = "@@@".join(lines_in_list)
# We update the local result (and implicitly the global result)
# with the files and directory informations/structure.
local_result = local_result.setdefault(
directories,
{file: {"sha512": file_hash, "content": formatted_content}},
)
# We finally save the directory structure into the production file.
Dict(result).to_json(self.base + "dir_structure_production.json")
|
[
"Backup",
"the",
"developer",
"state",
"of",
"output",
"/",
"in",
"order",
"to",
"make",
"it",
"restorable",
"and",
"portable",
"for",
"user",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/directory_structure.py#L109-L154
|
[
"def",
"backup",
"(",
"self",
")",
":",
"# We set the current output directory path.",
"output_path",
"=",
"self",
".",
"base",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"parent_directory\"",
"]",
"# We initiate the structure base.",
"result",
"=",
"{",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"parent_directory\"",
"]",
":",
"{",
"}",
"}",
"for",
"root",
",",
"_",
",",
"files",
"in",
"PyFunceble",
".",
"walk",
"(",
"output_path",
")",
":",
"# We loop through the current output directory structure.",
"# We get the currently read directory name.",
"directories",
"=",
"Directory",
"(",
"root",
".",
"split",
"(",
"output_path",
")",
"[",
"1",
"]",
")",
".",
"fix_path",
"(",
")",
"# We initiate a local variable which will get the structure of the subdirectory.",
"local_result",
"=",
"result",
"[",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"parent_directory\"",
"]",
"]",
"for",
"file",
"in",
"files",
":",
"# We loop through the list of files.",
"# We construct the file path.",
"file_path",
"=",
"root",
"+",
"PyFunceble",
".",
"directory_separator",
"+",
"file",
"# We get the hash of the file.",
"file_hash",
"=",
"Hash",
"(",
"file_path",
",",
"\"sha512\"",
",",
"True",
")",
".",
"get",
"(",
")",
"# We convert the file content to a list.",
"lines_in_list",
"=",
"[",
"line",
".",
"rstrip",
"(",
"\"\\n\"",
")",
"for",
"line",
"in",
"open",
"(",
"file_path",
")",
"]",
"# We convert the file content into a more flat format.",
"# We use `@@@` as glue and implicitly replacement for `\\n`.",
"formatted_content",
"=",
"\"@@@\"",
".",
"join",
"(",
"lines_in_list",
")",
"# We update the local result (and implicitly the global result)",
"# with the files and directory informations/structure.",
"local_result",
"=",
"local_result",
".",
"setdefault",
"(",
"directories",
",",
"{",
"file",
":",
"{",
"\"sha512\"",
":",
"file_hash",
",",
"\"content\"",
":",
"formatted_content",
"}",
"}",
",",
")",
"# We finally save the directory structure into the production file.",
"Dict",
"(",
"result",
")",
".",
"to_json",
"(",
"self",
".",
"base",
"+",
"\"dir_structure_production.json\"",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
DirectoryStructure._restore_replace
|
Check if we need to replace ".gitignore" to ".keep".
:return: The replacement status.
:rtype: bool
|
PyFunceble/directory_structure.py
|
def _restore_replace(self):
"""
Check if we need to replace ".gitignore" to ".keep".
:return: The replacement status.
:rtype: bool
"""
if PyFunceble.path.isdir(self.base + ".git"):
# The `.git` directory exist.
if "PyFunceble" not in Command("git remote show origin").execute():
# PyFunceble is not in the origin.
# We return True.
return True
# We return False.
return False
# The `.git` directory does not exist.
# We return True.
return True
|
def _restore_replace(self):
"""
Check if we need to replace ".gitignore" to ".keep".
:return: The replacement status.
:rtype: bool
"""
if PyFunceble.path.isdir(self.base + ".git"):
# The `.git` directory exist.
if "PyFunceble" not in Command("git remote show origin").execute():
# PyFunceble is not in the origin.
# We return True.
return True
# We return False.
return False
# The `.git` directory does not exist.
# We return True.
return True
|
[
"Check",
"if",
"we",
"need",
"to",
"replace",
".",
"gitignore",
"to",
".",
"keep",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/directory_structure.py#L156-L179
|
[
"def",
"_restore_replace",
"(",
"self",
")",
":",
"if",
"PyFunceble",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"base",
"+",
"\".git\"",
")",
":",
"# The `.git` directory exist.",
"if",
"\"PyFunceble\"",
"not",
"in",
"Command",
"(",
"\"git remote show origin\"",
")",
".",
"execute",
"(",
")",
":",
"# PyFunceble is not in the origin.",
"# We return True.",
"return",
"True",
"# We return False.",
"return",
"False",
"# The `.git` directory does not exist.",
"# We return True.",
"return",
"True"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
DirectoryStructure._update_structure_from_config
|
Update the paths according to configs.
:param structure: The read structure.
:type structure: dict
|
PyFunceble/directory_structure.py
|
def _update_structure_from_config(self, structure):
"""
Update the paths according to configs.
:param structure: The read structure.
:type structure: dict
"""
# We initiate a variable which will map what we have to replace `ouput` to.
# Indeed, as we allow the user to change directory names directly from the
# configuration, here we initiate what we have to replace `output/` with.
to_replace_base_map = {"output/": PyFunceble.OUTPUTS["parent_directory"]}
# We map the replacement of other directories.
to_replace_map = {
#########################################################################
# The following part is there for historical reason. #
#########################################################################
# We get the replacement of the HTTP_Analytic directory from the
# configuration file.
"HTTP_Analytic/": PyFunceble.OUTPUTS["analytic"]["directories"]["parent"],
# We get the replacement of the HTTP_Analytic/ACTIVE directory from the
# configuration file.
"HTTP_Analytic/ACTIVE/": PyFunceble.OUTPUTS["analytic"]["directories"][
"parent"
]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["up"],
"HTTP_Analytic/POTENTIALLY_ACTIVE/": PyFunceble.OUTPUTS["analytic"][
"directories"
]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_up"],
# We get the replacement of the HTTP_Analytic/POTENTIALLY_INACTIVE directory
# from the configuration file.
"HTTP_Analytic/POTENTIALLY_INACTIVE/": PyFunceble.OUTPUTS["analytic"][
"directories"
]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_down"],
#########################################################################
# The previous part is there for historical reason. #
#########################################################################
# We get the replacement of the Analytic directory from the
# configuration file.
"Analytic/": PyFunceble.OUTPUTS["analytic"]["directories"]["parent"],
# We get the replacement of the Analytic/ACTIVE directory from the
# configuration file.
"Analytic/ACTIVE/": PyFunceble.OUTPUTS["analytic"]["directories"]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["up"],
"Analytic/POTENTIALLY_ACTIVE/": PyFunceble.OUTPUTS["analytic"][
"directories"
]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_up"],
# We get the replacement of the Analytic/POTENTIALLY_INACTIVE directory
# from the configuration file.
"Analytic/POTENTIALLY_INACTIVE/": PyFunceble.OUTPUTS["analytic"][
"directories"
]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_down"],
# We get the replacement of the Analytic/SUSPICIOUS directory
# from the configuration file.
"Analytic/SUSPICIOUS/": PyFunceble.OUTPUTS["analytic"]["directories"][
"parent"
]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["suspicious"],
# We get the replacement of the domains directory from the
# configuration file.
"domains/": PyFunceble.OUTPUTS["domains"]["directory"],
# We get the replacement of the domains/ACTIVE directory from the
# configuration file.
"domains/ACTIVE/": PyFunceble.OUTPUTS["domains"]["directory"]
+ PyFunceble.STATUS["official"]["up"],
# We get the replacement of the domains/INACTIVE directory from the
# configuration file.
"domains/INACTIVE/": PyFunceble.OUTPUTS["domains"]["directory"]
+ PyFunceble.STATUS["official"]["down"],
# We get the replacement of the domains/INVALID directory from the
# configuration file.
"domains/INVALID/": PyFunceble.OUTPUTS["domains"]["directory"]
+ PyFunceble.STATUS["official"]["invalid"],
# We get the replacement of the domains/VALID directory from the
# configuration file.
"domains/VALID/": PyFunceble.OUTPUTS["domains"]["directory"]
+ PyFunceble.STATUS["official"]["valid"],
# We get the replacement of the hosts directory from the
# configuration file.
"hosts/": PyFunceble.OUTPUTS["hosts"]["directory"],
# We get the replacement of the hosts/ACTIVE directory from the
# configuration file.
"hosts/ACTIVE/": PyFunceble.OUTPUTS["hosts"]["directory"]
+ PyFunceble.STATUS["official"]["up"],
# We get the replacement of the hosts/INACTIVE directory from the
# configuration file.
"hosts/INACTIVE/": PyFunceble.OUTPUTS["hosts"]["directory"]
+ PyFunceble.STATUS["official"]["down"],
# We get the replacement of the hosts/INVALID directory from the
# configuration file.
"hosts/INVALID/": PyFunceble.OUTPUTS["hosts"]["directory"]
+ PyFunceble.STATUS["official"]["invalid"],
# We get the replacement of the hosts/VALID directory from the
# configuration file.
"hosts/VALID/": PyFunceble.OUTPUTS["hosts"]["directory"]
+ PyFunceble.STATUS["official"]["valid"],
# We get the replacement of the json directory from the
# configuration file.
"json/": PyFunceble.OUTPUTS["json"]["directory"],
# We get the replacement of the json/ACTIVE directory from the
# configuration file.
"json/ACTIVE/": PyFunceble.OUTPUTS["json"]["directory"]
+ PyFunceble.STATUS["official"]["up"],
# We get the replacement of the json/INACTIVE directory from the
# configuration file.
"json/INACTIVE/": PyFunceble.OUTPUTS["json"]["directory"]
+ PyFunceble.STATUS["official"]["down"],
# We get the replacement of the json/INVALID directory from the
# configuration file.
"json/INVALID/": PyFunceble.OUTPUTS["json"]["directory"]
+ PyFunceble.STATUS["official"]["invalid"],
# We get the replacement of the json/VALID directory from the
# configuration file.
"json/VALID/": PyFunceble.OUTPUTS["json"]["directory"]
+ PyFunceble.STATUS["official"]["valid"],
# We get the replacement of the logs directory from the
# configuration file.
"logs/": PyFunceble.OUTPUTS["logs"]["directories"]["parent"],
# We get the replacement of the logs/percentage directory from the
# configuration file.
"logs/percentage/": PyFunceble.OUTPUTS["logs"]["directories"]["parent"]
+ PyFunceble.OUTPUTS["logs"]["directories"]["percentage"],
# We get the replacement of the splited directory from the
# configuration file.
"splited/": PyFunceble.OUTPUTS["splited"]["directory"],
}
# We initiate the variable which will be used for the structure
# update.
to_replace = {}
for mapped, declared in to_replace_map.items():
# We loop through the declared mad.
# We fix the path of the declared.
declared = Directory(declared).fix_path()
# print('dec', declared, 'map', mapped)
# And we update our data.
to_replace.update({mapped: declared})
to_replace_base = {}
for mapped, declared in to_replace_base_map.items():
# We loop through the declared mad.
# We fix the path of the declared.
declared = Directory(declared).fix_path()
# And we update our data.
to_replace_base.update({mapped: declared})
# We perform the replacement of the base directory.
structure = Dict(structure).rename_key(to_replace_base)
# We perform the replacement of every subdirectories.
structure[PyFunceble.OUTPUTS["parent_directory"]] = Dict(
structure[PyFunceble.OUTPUTS["parent_directory"]]
).rename_key(to_replace)
try:
# We try to save the structure into the right path.
Dict(structure).to_json(self.structure)
except FileNotFoundError:
# But if we get a FileNotFoundError exception,
# We create the directory where the directory structure should be saved.
PyFunceble.mkdir(
PyFunceble.directory_separator.join(
self.structure.split(PyFunceble.directory_separator)[:-1]
)
)
# And we retry to save the structure into the right path.
Dict(structure).to_json(self.structure)
# We finaly return the new structure in case it's needed for other logic.
return structure
|
def _update_structure_from_config(self, structure):
"""
Update the paths according to configs.
:param structure: The read structure.
:type structure: dict
"""
# We initiate a variable which will map what we have to replace `ouput` to.
# Indeed, as we allow the user to change directory names directly from the
# configuration, here we initiate what we have to replace `output/` with.
to_replace_base_map = {"output/": PyFunceble.OUTPUTS["parent_directory"]}
# We map the replacement of other directories.
to_replace_map = {
#########################################################################
# The following part is there for historical reason. #
#########################################################################
# We get the replacement of the HTTP_Analytic directory from the
# configuration file.
"HTTP_Analytic/": PyFunceble.OUTPUTS["analytic"]["directories"]["parent"],
# We get the replacement of the HTTP_Analytic/ACTIVE directory from the
# configuration file.
"HTTP_Analytic/ACTIVE/": PyFunceble.OUTPUTS["analytic"]["directories"][
"parent"
]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["up"],
"HTTP_Analytic/POTENTIALLY_ACTIVE/": PyFunceble.OUTPUTS["analytic"][
"directories"
]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_up"],
# We get the replacement of the HTTP_Analytic/POTENTIALLY_INACTIVE directory
# from the configuration file.
"HTTP_Analytic/POTENTIALLY_INACTIVE/": PyFunceble.OUTPUTS["analytic"][
"directories"
]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_down"],
#########################################################################
# The previous part is there for historical reason. #
#########################################################################
# We get the replacement of the Analytic directory from the
# configuration file.
"Analytic/": PyFunceble.OUTPUTS["analytic"]["directories"]["parent"],
# We get the replacement of the Analytic/ACTIVE directory from the
# configuration file.
"Analytic/ACTIVE/": PyFunceble.OUTPUTS["analytic"]["directories"]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["up"],
"Analytic/POTENTIALLY_ACTIVE/": PyFunceble.OUTPUTS["analytic"][
"directories"
]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_up"],
# We get the replacement of the Analytic/POTENTIALLY_INACTIVE directory
# from the configuration file.
"Analytic/POTENTIALLY_INACTIVE/": PyFunceble.OUTPUTS["analytic"][
"directories"
]["parent"]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_down"],
# We get the replacement of the Analytic/SUSPICIOUS directory
# from the configuration file.
"Analytic/SUSPICIOUS/": PyFunceble.OUTPUTS["analytic"]["directories"][
"parent"
]
+ PyFunceble.OUTPUTS["analytic"]["directories"]["suspicious"],
# We get the replacement of the domains directory from the
# configuration file.
"domains/": PyFunceble.OUTPUTS["domains"]["directory"],
# We get the replacement of the domains/ACTIVE directory from the
# configuration file.
"domains/ACTIVE/": PyFunceble.OUTPUTS["domains"]["directory"]
+ PyFunceble.STATUS["official"]["up"],
# We get the replacement of the domains/INACTIVE directory from the
# configuration file.
"domains/INACTIVE/": PyFunceble.OUTPUTS["domains"]["directory"]
+ PyFunceble.STATUS["official"]["down"],
# We get the replacement of the domains/INVALID directory from the
# configuration file.
"domains/INVALID/": PyFunceble.OUTPUTS["domains"]["directory"]
+ PyFunceble.STATUS["official"]["invalid"],
# We get the replacement of the domains/VALID directory from the
# configuration file.
"domains/VALID/": PyFunceble.OUTPUTS["domains"]["directory"]
+ PyFunceble.STATUS["official"]["valid"],
# We get the replacement of the hosts directory from the
# configuration file.
"hosts/": PyFunceble.OUTPUTS["hosts"]["directory"],
# We get the replacement of the hosts/ACTIVE directory from the
# configuration file.
"hosts/ACTIVE/": PyFunceble.OUTPUTS["hosts"]["directory"]
+ PyFunceble.STATUS["official"]["up"],
# We get the replacement of the hosts/INACTIVE directory from the
# configuration file.
"hosts/INACTIVE/": PyFunceble.OUTPUTS["hosts"]["directory"]
+ PyFunceble.STATUS["official"]["down"],
# We get the replacement of the hosts/INVALID directory from the
# configuration file.
"hosts/INVALID/": PyFunceble.OUTPUTS["hosts"]["directory"]
+ PyFunceble.STATUS["official"]["invalid"],
# We get the replacement of the hosts/VALID directory from the
# configuration file.
"hosts/VALID/": PyFunceble.OUTPUTS["hosts"]["directory"]
+ PyFunceble.STATUS["official"]["valid"],
# We get the replacement of the json directory from the
# configuration file.
"json/": PyFunceble.OUTPUTS["json"]["directory"],
# We get the replacement of the json/ACTIVE directory from the
# configuration file.
"json/ACTIVE/": PyFunceble.OUTPUTS["json"]["directory"]
+ PyFunceble.STATUS["official"]["up"],
# We get the replacement of the json/INACTIVE directory from the
# configuration file.
"json/INACTIVE/": PyFunceble.OUTPUTS["json"]["directory"]
+ PyFunceble.STATUS["official"]["down"],
# We get the replacement of the json/INVALID directory from the
# configuration file.
"json/INVALID/": PyFunceble.OUTPUTS["json"]["directory"]
+ PyFunceble.STATUS["official"]["invalid"],
# We get the replacement of the json/VALID directory from the
# configuration file.
"json/VALID/": PyFunceble.OUTPUTS["json"]["directory"]
+ PyFunceble.STATUS["official"]["valid"],
# We get the replacement of the logs directory from the
# configuration file.
"logs/": PyFunceble.OUTPUTS["logs"]["directories"]["parent"],
# We get the replacement of the logs/percentage directory from the
# configuration file.
"logs/percentage/": PyFunceble.OUTPUTS["logs"]["directories"]["parent"]
+ PyFunceble.OUTPUTS["logs"]["directories"]["percentage"],
# We get the replacement of the splited directory from the
# configuration file.
"splited/": PyFunceble.OUTPUTS["splited"]["directory"],
}
# We initiate the variable which will be used for the structure
# update.
to_replace = {}
for mapped, declared in to_replace_map.items():
# We loop through the declared mad.
# We fix the path of the declared.
declared = Directory(declared).fix_path()
# print('dec', declared, 'map', mapped)
# And we update our data.
to_replace.update({mapped: declared})
to_replace_base = {}
for mapped, declared in to_replace_base_map.items():
# We loop through the declared mad.
# We fix the path of the declared.
declared = Directory(declared).fix_path()
# And we update our data.
to_replace_base.update({mapped: declared})
# We perform the replacement of the base directory.
structure = Dict(structure).rename_key(to_replace_base)
# We perform the replacement of every subdirectories.
structure[PyFunceble.OUTPUTS["parent_directory"]] = Dict(
structure[PyFunceble.OUTPUTS["parent_directory"]]
).rename_key(to_replace)
try:
# We try to save the structure into the right path.
Dict(structure).to_json(self.structure)
except FileNotFoundError:
# But if we get a FileNotFoundError exception,
# We create the directory where the directory structure should be saved.
PyFunceble.mkdir(
PyFunceble.directory_separator.join(
self.structure.split(PyFunceble.directory_separator)[:-1]
)
)
# And we retry to save the structure into the right path.
Dict(structure).to_json(self.structure)
# We finaly return the new structure in case it's needed for other logic.
return structure
|
[
"Update",
"the",
"paths",
"according",
"to",
"configs",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/directory_structure.py#L181-L363
|
[
"def",
"_update_structure_from_config",
"(",
"self",
",",
"structure",
")",
":",
"# We initiate a variable which will map what we have to replace `ouput` to.",
"# Indeed, as we allow the user to change directory names directly from the",
"# configuration, here we initiate what we have to replace `output/` with.",
"to_replace_base_map",
"=",
"{",
"\"output/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"parent_directory\"",
"]",
"}",
"# We map the replacement of other directories.",
"to_replace_map",
"=",
"{",
"#########################################################################",
"# The following part is there for historical reason. #",
"#########################################################################",
"# We get the replacement of the HTTP_Analytic directory from the",
"# configuration file.",
"\"HTTP_Analytic/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
",",
"# We get the replacement of the HTTP_Analytic/ACTIVE directory from the",
"# configuration file.",
"\"HTTP_Analytic/ACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"up\"",
"]",
",",
"\"HTTP_Analytic/POTENTIALLY_ACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"potentially_up\"",
"]",
",",
"# We get the replacement of the HTTP_Analytic/POTENTIALLY_INACTIVE directory",
"# from the configuration file.",
"\"HTTP_Analytic/POTENTIALLY_INACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"potentially_down\"",
"]",
",",
"#########################################################################",
"# The previous part is there for historical reason. #",
"#########################################################################",
"# We get the replacement of the Analytic directory from the",
"# configuration file.",
"\"Analytic/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
",",
"# We get the replacement of the Analytic/ACTIVE directory from the",
"# configuration file.",
"\"Analytic/ACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"up\"",
"]",
",",
"\"Analytic/POTENTIALLY_ACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"potentially_up\"",
"]",
",",
"# We get the replacement of the Analytic/POTENTIALLY_INACTIVE directory",
"# from the configuration file.",
"\"Analytic/POTENTIALLY_INACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"potentially_down\"",
"]",
",",
"# We get the replacement of the Analytic/SUSPICIOUS directory",
"# from the configuration file.",
"\"Analytic/SUSPICIOUS/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"suspicious\"",
"]",
",",
"# We get the replacement of the domains directory from the",
"# configuration file.",
"\"domains/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"domains\"",
"]",
"[",
"\"directory\"",
"]",
",",
"# We get the replacement of the domains/ACTIVE directory from the",
"# configuration file.",
"\"domains/ACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"domains\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
",",
"# We get the replacement of the domains/INACTIVE directory from the",
"# configuration file.",
"\"domains/INACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"domains\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"down\"",
"]",
",",
"# We get the replacement of the domains/INVALID directory from the",
"# configuration file.",
"\"domains/INVALID/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"domains\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"invalid\"",
"]",
",",
"# We get the replacement of the domains/VALID directory from the",
"# configuration file.",
"\"domains/VALID/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"domains\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"valid\"",
"]",
",",
"# We get the replacement of the hosts directory from the",
"# configuration file.",
"\"hosts/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"hosts\"",
"]",
"[",
"\"directory\"",
"]",
",",
"# We get the replacement of the hosts/ACTIVE directory from the",
"# configuration file.",
"\"hosts/ACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"hosts\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
",",
"# We get the replacement of the hosts/INACTIVE directory from the",
"# configuration file.",
"\"hosts/INACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"hosts\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"down\"",
"]",
",",
"# We get the replacement of the hosts/INVALID directory from the",
"# configuration file.",
"\"hosts/INVALID/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"hosts\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"invalid\"",
"]",
",",
"# We get the replacement of the hosts/VALID directory from the",
"# configuration file.",
"\"hosts/VALID/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"hosts\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"valid\"",
"]",
",",
"# We get the replacement of the json directory from the",
"# configuration file.",
"\"json/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"json\"",
"]",
"[",
"\"directory\"",
"]",
",",
"# We get the replacement of the json/ACTIVE directory from the",
"# configuration file.",
"\"json/ACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"json\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
",",
"# We get the replacement of the json/INACTIVE directory from the",
"# configuration file.",
"\"json/INACTIVE/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"json\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"down\"",
"]",
",",
"# We get the replacement of the json/INVALID directory from the",
"# configuration file.",
"\"json/INVALID/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"json\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"invalid\"",
"]",
",",
"# We get the replacement of the json/VALID directory from the",
"# configuration file.",
"\"json/VALID/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"json\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"valid\"",
"]",
",",
"# We get the replacement of the logs directory from the",
"# configuration file.",
"\"logs/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"logs\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
",",
"# We get the replacement of the logs/percentage directory from the",
"# configuration file.",
"\"logs/percentage/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"logs\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"logs\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"percentage\"",
"]",
",",
"# We get the replacement of the splited directory from the",
"# configuration file.",
"\"splited/\"",
":",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"splited\"",
"]",
"[",
"\"directory\"",
"]",
",",
"}",
"# We initiate the variable which will be used for the structure",
"# update.",
"to_replace",
"=",
"{",
"}",
"for",
"mapped",
",",
"declared",
"in",
"to_replace_map",
".",
"items",
"(",
")",
":",
"# We loop through the declared mad.",
"# We fix the path of the declared.",
"declared",
"=",
"Directory",
"(",
"declared",
")",
".",
"fix_path",
"(",
")",
"# print('dec', declared, 'map', mapped)",
"# And we update our data.",
"to_replace",
".",
"update",
"(",
"{",
"mapped",
":",
"declared",
"}",
")",
"to_replace_base",
"=",
"{",
"}",
"for",
"mapped",
",",
"declared",
"in",
"to_replace_base_map",
".",
"items",
"(",
")",
":",
"# We loop through the declared mad.",
"# We fix the path of the declared.",
"declared",
"=",
"Directory",
"(",
"declared",
")",
".",
"fix_path",
"(",
")",
"# And we update our data.",
"to_replace_base",
".",
"update",
"(",
"{",
"mapped",
":",
"declared",
"}",
")",
"# We perform the replacement of the base directory.",
"structure",
"=",
"Dict",
"(",
"structure",
")",
".",
"rename_key",
"(",
"to_replace_base",
")",
"# We perform the replacement of every subdirectories.",
"structure",
"[",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"parent_directory\"",
"]",
"]",
"=",
"Dict",
"(",
"structure",
"[",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"parent_directory\"",
"]",
"]",
")",
".",
"rename_key",
"(",
"to_replace",
")",
"try",
":",
"# We try to save the structure into the right path.",
"Dict",
"(",
"structure",
")",
".",
"to_json",
"(",
"self",
".",
"structure",
")",
"except",
"FileNotFoundError",
":",
"# But if we get a FileNotFoundError exception,",
"# We create the directory where the directory structure should be saved.",
"PyFunceble",
".",
"mkdir",
"(",
"PyFunceble",
".",
"directory_separator",
".",
"join",
"(",
"self",
".",
"structure",
".",
"split",
"(",
"PyFunceble",
".",
"directory_separator",
")",
"[",
":",
"-",
"1",
"]",
")",
")",
"# And we retry to save the structure into the right path.",
"Dict",
"(",
"structure",
")",
".",
"to_json",
"(",
"self",
".",
"structure",
")",
"# We finaly return the new structure in case it's needed for other logic.",
"return",
"structure"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
DirectoryStructure._get_structure
|
Get the structure we are going to work with.
:return: The structure we have to work with.
:rtype: dict
|
PyFunceble/directory_structure.py
|
def _get_structure(self):
"""
Get the structure we are going to work with.
:return: The structure we have to work with.
:rtype: dict
"""
# We initiate an empty variable which is going to save the location of
# file we are going to download.
structure_file = ""
# We initiate the variable which will save the request instance.
req = ""
if PyFunceble.path.isfile(self.structure):
# The structure path file exist.
# We set it as the destination file.
structure_file = self.structure
elif PyFunceble.path.isfile(self.base + "dir_structure_production.json"):
# * The structure path file does not exist.
# but
# * The production structure path file exist.
# We set it as the destination file
structure_file = self.base + "dir_structure_production.json"
else:
# * The structure path file does not exist.
# and
# * The production structure path file does not exist.
if "dev" not in PyFunceble.VERSION:
# `dev` is not into the local version name.
# We get the production file from the master branch.
req = PyFunceble.requests.get(
PyFunceble.LINKS["dir_structure"].replace("dev", "master")
)
else:
# `dev` is into the local version name.
# We get the production file from the dev branch.
req = PyFunceble.requests.get(
PyFunceble.LINKS["dir_structure"].replace("master", "dev")
)
if structure_file.endswith("_production.json"):
# The destination is the production file.
# And we return the updated the structure from the last read file.
# (with the names from the configuration file).
return self._update_structure_from_config(
Dict().from_json(File(structure_file).read())
)
# The destination is not the production file.
if structure_file.endswith(".json"):
# The destination ends with `.json`.
# And we return the updated the structure from the given file.
# (with the names from the configuration file).
return self._update_structure_from_config(
Dict().from_json(File(structure_file).read())
)
# The destination does not ends with `.json`.
# We return the updated the structure from the link we previously got.
# (with the names from the configuration file).
return self._update_structure_from_config(Dict().from_json(req.text))
|
def _get_structure(self):
"""
Get the structure we are going to work with.
:return: The structure we have to work with.
:rtype: dict
"""
# We initiate an empty variable which is going to save the location of
# file we are going to download.
structure_file = ""
# We initiate the variable which will save the request instance.
req = ""
if PyFunceble.path.isfile(self.structure):
# The structure path file exist.
# We set it as the destination file.
structure_file = self.structure
elif PyFunceble.path.isfile(self.base + "dir_structure_production.json"):
# * The structure path file does not exist.
# but
# * The production structure path file exist.
# We set it as the destination file
structure_file = self.base + "dir_structure_production.json"
else:
# * The structure path file does not exist.
# and
# * The production structure path file does not exist.
if "dev" not in PyFunceble.VERSION:
# `dev` is not into the local version name.
# We get the production file from the master branch.
req = PyFunceble.requests.get(
PyFunceble.LINKS["dir_structure"].replace("dev", "master")
)
else:
# `dev` is into the local version name.
# We get the production file from the dev branch.
req = PyFunceble.requests.get(
PyFunceble.LINKS["dir_structure"].replace("master", "dev")
)
if structure_file.endswith("_production.json"):
# The destination is the production file.
# And we return the updated the structure from the last read file.
# (with the names from the configuration file).
return self._update_structure_from_config(
Dict().from_json(File(structure_file).read())
)
# The destination is not the production file.
if structure_file.endswith(".json"):
# The destination ends with `.json`.
# And we return the updated the structure from the given file.
# (with the names from the configuration file).
return self._update_structure_from_config(
Dict().from_json(File(structure_file).read())
)
# The destination does not ends with `.json`.
# We return the updated the structure from the link we previously got.
# (with the names from the configuration file).
return self._update_structure_from_config(Dict().from_json(req.text))
|
[
"Get",
"the",
"structure",
"we",
"are",
"going",
"to",
"work",
"with",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/directory_structure.py#L365-L436
|
[
"def",
"_get_structure",
"(",
"self",
")",
":",
"# We initiate an empty variable which is going to save the location of",
"# file we are going to download.",
"structure_file",
"=",
"\"\"",
"# We initiate the variable which will save the request instance.",
"req",
"=",
"\"\"",
"if",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"structure",
")",
":",
"# The structure path file exist.",
"# We set it as the destination file.",
"structure_file",
"=",
"self",
".",
"structure",
"elif",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"base",
"+",
"\"dir_structure_production.json\"",
")",
":",
"# * The structure path file does not exist.",
"# but",
"# * The production structure path file exist.",
"# We set it as the destination file",
"structure_file",
"=",
"self",
".",
"base",
"+",
"\"dir_structure_production.json\"",
"else",
":",
"# * The structure path file does not exist.",
"# and",
"# * The production structure path file does not exist.",
"if",
"\"dev\"",
"not",
"in",
"PyFunceble",
".",
"VERSION",
":",
"# `dev` is not into the local version name.",
"# We get the production file from the master branch.",
"req",
"=",
"PyFunceble",
".",
"requests",
".",
"get",
"(",
"PyFunceble",
".",
"LINKS",
"[",
"\"dir_structure\"",
"]",
".",
"replace",
"(",
"\"dev\"",
",",
"\"master\"",
")",
")",
"else",
":",
"# `dev` is into the local version name.",
"# We get the production file from the dev branch.",
"req",
"=",
"PyFunceble",
".",
"requests",
".",
"get",
"(",
"PyFunceble",
".",
"LINKS",
"[",
"\"dir_structure\"",
"]",
".",
"replace",
"(",
"\"master\"",
",",
"\"dev\"",
")",
")",
"if",
"structure_file",
".",
"endswith",
"(",
"\"_production.json\"",
")",
":",
"# The destination is the production file.",
"# And we return the updated the structure from the last read file.",
"# (with the names from the configuration file).",
"return",
"self",
".",
"_update_structure_from_config",
"(",
"Dict",
"(",
")",
".",
"from_json",
"(",
"File",
"(",
"structure_file",
")",
".",
"read",
"(",
")",
")",
")",
"# The destination is not the production file.",
"if",
"structure_file",
".",
"endswith",
"(",
"\".json\"",
")",
":",
"# The destination ends with `.json`.",
"# And we return the updated the structure from the given file.",
"# (with the names from the configuration file).",
"return",
"self",
".",
"_update_structure_from_config",
"(",
"Dict",
"(",
")",
".",
"from_json",
"(",
"File",
"(",
"structure_file",
")",
".",
"read",
"(",
")",
")",
")",
"# The destination does not ends with `.json`.",
"# We return the updated the structure from the link we previously got.",
"# (with the names from the configuration file).",
"return",
"self",
".",
"_update_structure_from_config",
"(",
"Dict",
"(",
")",
".",
"from_json",
"(",
"req",
".",
"text",
")",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
DirectoryStructure._create_directory
|
Creates the given directory if it does not exists.
:param directory: The directory to create.
:type directory: str
:param loop: Tell us if we are in the creation loop or not.
:type loop: bool
|
PyFunceble/directory_structure.py
|
def _create_directory(cls, directory, loop=False):
"""
Creates the given directory if it does not exists.
:param directory: The directory to create.
:type directory: str
:param loop: Tell us if we are in the creation loop or not.
:type loop: bool
"""
if not loop and PyFunceble.directory_separator in directory:
# * We are not in the loop.
# and
# * The directory separator in the given directory.
# We split the directories separator.
splited_directory = directory.split(PyFunceble.directory_separator)
# We initiate a variable which will save the full path to create.
full_path_to_create = ""
for single_directory in splited_directory:
# We loop through each directory.
# We append the currently read directory to the full path.
full_path_to_create += single_directory + PyFunceble.directory_separator
# And we create the directory if it does not exist.
cls._create_directory(full_path_to_create, True)
if not PyFunceble.path.isdir(directory):
# The given directory does not exist.
# We update the permission.
# (Only if we are under Travis CI.)
AutoSave.travis_permissions()
# We create the directory.
PyFunceble.mkdir(directory)
# We update the permission.
# (Only if we are under Travis CI.)
AutoSave.travis_permissions()
|
def _create_directory(cls, directory, loop=False):
"""
Creates the given directory if it does not exists.
:param directory: The directory to create.
:type directory: str
:param loop: Tell us if we are in the creation loop or not.
:type loop: bool
"""
if not loop and PyFunceble.directory_separator in directory:
# * We are not in the loop.
# and
# * The directory separator in the given directory.
# We split the directories separator.
splited_directory = directory.split(PyFunceble.directory_separator)
# We initiate a variable which will save the full path to create.
full_path_to_create = ""
for single_directory in splited_directory:
# We loop through each directory.
# We append the currently read directory to the full path.
full_path_to_create += single_directory + PyFunceble.directory_separator
# And we create the directory if it does not exist.
cls._create_directory(full_path_to_create, True)
if not PyFunceble.path.isdir(directory):
# The given directory does not exist.
# We update the permission.
# (Only if we are under Travis CI.)
AutoSave.travis_permissions()
# We create the directory.
PyFunceble.mkdir(directory)
# We update the permission.
# (Only if we are under Travis CI.)
AutoSave.travis_permissions()
|
[
"Creates",
"the",
"given",
"directory",
"if",
"it",
"does",
"not",
"exists",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/directory_structure.py#L439-L482
|
[
"def",
"_create_directory",
"(",
"cls",
",",
"directory",
",",
"loop",
"=",
"False",
")",
":",
"if",
"not",
"loop",
"and",
"PyFunceble",
".",
"directory_separator",
"in",
"directory",
":",
"# * We are not in the loop.",
"# and",
"# * The directory separator in the given directory.",
"# We split the directories separator.",
"splited_directory",
"=",
"directory",
".",
"split",
"(",
"PyFunceble",
".",
"directory_separator",
")",
"# We initiate a variable which will save the full path to create.",
"full_path_to_create",
"=",
"\"\"",
"for",
"single_directory",
"in",
"splited_directory",
":",
"# We loop through each directory.",
"# We append the currently read directory to the full path.",
"full_path_to_create",
"+=",
"single_directory",
"+",
"PyFunceble",
".",
"directory_separator",
"# And we create the directory if it does not exist.",
"cls",
".",
"_create_directory",
"(",
"full_path_to_create",
",",
"True",
")",
"if",
"not",
"PyFunceble",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"# The given directory does not exist.",
"# We update the permission.",
"# (Only if we are under Travis CI.)",
"AutoSave",
".",
"travis_permissions",
"(",
")",
"# We create the directory.",
"PyFunceble",
".",
"mkdir",
"(",
"directory",
")",
"# We update the permission.",
"# (Only if we are under Travis CI.)",
"AutoSave",
".",
"travis_permissions",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
DirectoryStructure.restore
|
Restore the 'output/' directory structure based on the `dir_structure.json` file.
|
PyFunceble/directory_structure.py
|
def restore(self):
"""
Restore the 'output/' directory structure based on the `dir_structure.json` file.
"""
# We get the structure we have to create/apply.
structure = self._get_structure()
# We get the list of key which is implicitly the list of directory to recreate.
list_of_key = list(structure.keys())
# We move to the content of the parent as we know that we are creating only one directory.
# Note: if one day we will have to create multiple directory, we will have to change
# the following.
structure = structure[list_of_key[0]]
# We also set the parent directory as we are going to construct its childen.
parent_path = list_of_key[0]
if not parent_path.endswith(PyFunceble.directory_separator):
parent_path += PyFunceble.directory_separator
# We get if we have to replace `.gitignore` to `.keep` and versa.
replacement_status = self._restore_replace()
for directory in structure:
# We loop through the list of directory to create.
# We construct the full path.
base = self.base + parent_path + directory
if not base.endswith(PyFunceble.directory_separator):
base += PyFunceble.directory_separator
# We create the constructed path if it does not exist.
self._create_directory(base)
for file in structure[directory]:
# We loop through the list of files in the currently read directory.
# We construct the full file path.s
file_path = base + file
# We get the file content.
content_to_write = structure[directory][file]["content"]
# And its sha512 checksum.
online_sha = structure[directory][file]["sha512"]
# We update the content to write by replacing our glue with `\n`.
content_to_write = Regex(
content_to_write, "@@@", escape=True, replace_with="\\n"
).replace()
# We get the file path as .keep.
git_to_keep = file_path.replace("gitignore", "keep")
# We get the file path as .gitignore.
keep_to_git = file_path.replace("keep", "gitignore")
if replacement_status:
# We have to replace every .gitignore to .keep.
if (
PyFunceble.path.isfile(file_path)
and Hash(file_path, "sha512", True).get() == online_sha
):
# * The currently read file exist.
# and
# * Its sha512sum is equal to the one we have in our structure.
# We rename the file.
PyFunceble.rename(file_path, git_to_keep)
# And we disallow the file writing.
write = False
else:
# * The currently read file does not exist.
# or
# * Its sha512sum is not equal to the one we have in our structure.
# We delere the file if it does exist.
File(file_path).delete()
# We update the file path.
file_path = git_to_keep
# And we allow the file writing.
write = True
else:
# We have to replace every .keep to .gitignore.
if (
PyFunceble.path.isfile(keep_to_git)
and Hash(file_path, "sha512", True).get() == online_sha
):
# * The .keep file exist.
# and
# * Its sha512sum is equal to the one we have in our structure.
# We rename the file.
PyFunceble.rename(file_path, keep_to_git)
# And we disallow the file writing.
write = False
else:
# * The .keep file does not exist.
# or
# * Its sha512sum is not equal to the one we have in our structure.
# We delete the file if it exist.
File(keep_to_git).delete()
# We update the file path
file_path = keep_to_git
# And we allow the file writing.
write = True
if write:
# The file writing is allowed.
# We write our file content into the file path.
File(file_path).write(content_to_write + "\n", True)
self.delete_uneeded()
|
def restore(self):
"""
Restore the 'output/' directory structure based on the `dir_structure.json` file.
"""
# We get the structure we have to create/apply.
structure = self._get_structure()
# We get the list of key which is implicitly the list of directory to recreate.
list_of_key = list(structure.keys())
# We move to the content of the parent as we know that we are creating only one directory.
# Note: if one day we will have to create multiple directory, we will have to change
# the following.
structure = structure[list_of_key[0]]
# We also set the parent directory as we are going to construct its childen.
parent_path = list_of_key[0]
if not parent_path.endswith(PyFunceble.directory_separator):
parent_path += PyFunceble.directory_separator
# We get if we have to replace `.gitignore` to `.keep` and versa.
replacement_status = self._restore_replace()
for directory in structure:
# We loop through the list of directory to create.
# We construct the full path.
base = self.base + parent_path + directory
if not base.endswith(PyFunceble.directory_separator):
base += PyFunceble.directory_separator
# We create the constructed path if it does not exist.
self._create_directory(base)
for file in structure[directory]:
# We loop through the list of files in the currently read directory.
# We construct the full file path.s
file_path = base + file
# We get the file content.
content_to_write = structure[directory][file]["content"]
# And its sha512 checksum.
online_sha = structure[directory][file]["sha512"]
# We update the content to write by replacing our glue with `\n`.
content_to_write = Regex(
content_to_write, "@@@", escape=True, replace_with="\\n"
).replace()
# We get the file path as .keep.
git_to_keep = file_path.replace("gitignore", "keep")
# We get the file path as .gitignore.
keep_to_git = file_path.replace("keep", "gitignore")
if replacement_status:
# We have to replace every .gitignore to .keep.
if (
PyFunceble.path.isfile(file_path)
and Hash(file_path, "sha512", True).get() == online_sha
):
# * The currently read file exist.
# and
# * Its sha512sum is equal to the one we have in our structure.
# We rename the file.
PyFunceble.rename(file_path, git_to_keep)
# And we disallow the file writing.
write = False
else:
# * The currently read file does not exist.
# or
# * Its sha512sum is not equal to the one we have in our structure.
# We delere the file if it does exist.
File(file_path).delete()
# We update the file path.
file_path = git_to_keep
# And we allow the file writing.
write = True
else:
# We have to replace every .keep to .gitignore.
if (
PyFunceble.path.isfile(keep_to_git)
and Hash(file_path, "sha512", True).get() == online_sha
):
# * The .keep file exist.
# and
# * Its sha512sum is equal to the one we have in our structure.
# We rename the file.
PyFunceble.rename(file_path, keep_to_git)
# And we disallow the file writing.
write = False
else:
# * The .keep file does not exist.
# or
# * Its sha512sum is not equal to the one we have in our structure.
# We delete the file if it exist.
File(keep_to_git).delete()
# We update the file path
file_path = keep_to_git
# And we allow the file writing.
write = True
if write:
# The file writing is allowed.
# We write our file content into the file path.
File(file_path).write(content_to_write + "\n", True)
self.delete_uneeded()
|
[
"Restore",
"the",
"output",
"/",
"directory",
"structure",
"based",
"on",
"the",
"dir_structure",
".",
"json",
"file",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/directory_structure.py#L484-L607
|
[
"def",
"restore",
"(",
"self",
")",
":",
"# We get the structure we have to create/apply.",
"structure",
"=",
"self",
".",
"_get_structure",
"(",
")",
"# We get the list of key which is implicitly the list of directory to recreate.",
"list_of_key",
"=",
"list",
"(",
"structure",
".",
"keys",
"(",
")",
")",
"# We move to the content of the parent as we know that we are creating only one directory.",
"# Note: if one day we will have to create multiple directory, we will have to change",
"# the following.",
"structure",
"=",
"structure",
"[",
"list_of_key",
"[",
"0",
"]",
"]",
"# We also set the parent directory as we are going to construct its childen.",
"parent_path",
"=",
"list_of_key",
"[",
"0",
"]",
"if",
"not",
"parent_path",
".",
"endswith",
"(",
"PyFunceble",
".",
"directory_separator",
")",
":",
"parent_path",
"+=",
"PyFunceble",
".",
"directory_separator",
"# We get if we have to replace `.gitignore` to `.keep` and versa.",
"replacement_status",
"=",
"self",
".",
"_restore_replace",
"(",
")",
"for",
"directory",
"in",
"structure",
":",
"# We loop through the list of directory to create.",
"# We construct the full path.",
"base",
"=",
"self",
".",
"base",
"+",
"parent_path",
"+",
"directory",
"if",
"not",
"base",
".",
"endswith",
"(",
"PyFunceble",
".",
"directory_separator",
")",
":",
"base",
"+=",
"PyFunceble",
".",
"directory_separator",
"# We create the constructed path if it does not exist.",
"self",
".",
"_create_directory",
"(",
"base",
")",
"for",
"file",
"in",
"structure",
"[",
"directory",
"]",
":",
"# We loop through the list of files in the currently read directory.",
"# We construct the full file path.s",
"file_path",
"=",
"base",
"+",
"file",
"# We get the file content.",
"content_to_write",
"=",
"structure",
"[",
"directory",
"]",
"[",
"file",
"]",
"[",
"\"content\"",
"]",
"# And its sha512 checksum.",
"online_sha",
"=",
"structure",
"[",
"directory",
"]",
"[",
"file",
"]",
"[",
"\"sha512\"",
"]",
"# We update the content to write by replacing our glue with `\\n`.",
"content_to_write",
"=",
"Regex",
"(",
"content_to_write",
",",
"\"@@@\"",
",",
"escape",
"=",
"True",
",",
"replace_with",
"=",
"\"\\\\n\"",
")",
".",
"replace",
"(",
")",
"# We get the file path as .keep.",
"git_to_keep",
"=",
"file_path",
".",
"replace",
"(",
"\"gitignore\"",
",",
"\"keep\"",
")",
"# We get the file path as .gitignore.",
"keep_to_git",
"=",
"file_path",
".",
"replace",
"(",
"\"keep\"",
",",
"\"gitignore\"",
")",
"if",
"replacement_status",
":",
"# We have to replace every .gitignore to .keep.",
"if",
"(",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
"and",
"Hash",
"(",
"file_path",
",",
"\"sha512\"",
",",
"True",
")",
".",
"get",
"(",
")",
"==",
"online_sha",
")",
":",
"# * The currently read file exist.",
"# and",
"# * Its sha512sum is equal to the one we have in our structure.",
"# We rename the file.",
"PyFunceble",
".",
"rename",
"(",
"file_path",
",",
"git_to_keep",
")",
"# And we disallow the file writing.",
"write",
"=",
"False",
"else",
":",
"# * The currently read file does not exist.",
"# or",
"# * Its sha512sum is not equal to the one we have in our structure.",
"# We delere the file if it does exist.",
"File",
"(",
"file_path",
")",
".",
"delete",
"(",
")",
"# We update the file path.",
"file_path",
"=",
"git_to_keep",
"# And we allow the file writing.",
"write",
"=",
"True",
"else",
":",
"# We have to replace every .keep to .gitignore.",
"if",
"(",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"keep_to_git",
")",
"and",
"Hash",
"(",
"file_path",
",",
"\"sha512\"",
",",
"True",
")",
".",
"get",
"(",
")",
"==",
"online_sha",
")",
":",
"# * The .keep file exist.",
"# and",
"# * Its sha512sum is equal to the one we have in our structure.",
"# We rename the file.",
"PyFunceble",
".",
"rename",
"(",
"file_path",
",",
"keep_to_git",
")",
"# And we disallow the file writing.",
"write",
"=",
"False",
"else",
":",
"# * The .keep file does not exist.",
"# or",
"# * Its sha512sum is not equal to the one we have in our structure.",
"# We delete the file if it exist.",
"File",
"(",
"keep_to_git",
")",
".",
"delete",
"(",
")",
"# We update the file path",
"file_path",
"=",
"keep_to_git",
"# And we allow the file writing.",
"write",
"=",
"True",
"if",
"write",
":",
"# The file writing is allowed.",
"# We write our file content into the file path.",
"File",
"(",
"file_path",
")",
".",
"write",
"(",
"content_to_write",
"+",
"\"\\n\"",
",",
"True",
")",
"self",
".",
"delete_uneeded",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
DirectoryStructure.delete_uneeded
|
Delete the directory which are not registered into our structure.
|
PyFunceble/directory_structure.py
|
def delete_uneeded(self):
"""
Delete the directory which are not registered into our structure.
"""
# We get the structure we have to apply.
structure = self._get_structure()
# We get the list of key which is implicitly the list of directory we do not bave to delete.
list_of_key = list(structure.keys())
# We move to the content of the parent as we know that we are creating only one directory.
# Note: if one day we will have to create multiple directory, we will have to change
# the following.
structure = structure[list_of_key[0]]
# We also set the parent directory as we are going to construct its childen.
parent_path = list_of_key[0]
if not parent_path.endswith(PyFunceble.directory_separator):
parent_path += PyFunceble.directory_separator
for root, _, _ in PyFunceble.walk(parent_path):
# We loop through each directories of the parent path.
# We fix the path in order to avoid issues.
root = Directory(root).fix_path()
if root.replace(parent_path, "") not in structure:
# The currently read directory is not in our structure.
# We delete it.
PyFunceble.rmtree(root)
|
def delete_uneeded(self):
"""
Delete the directory which are not registered into our structure.
"""
# We get the structure we have to apply.
structure = self._get_structure()
# We get the list of key which is implicitly the list of directory we do not bave to delete.
list_of_key = list(structure.keys())
# We move to the content of the parent as we know that we are creating only one directory.
# Note: if one day we will have to create multiple directory, we will have to change
# the following.
structure = structure[list_of_key[0]]
# We also set the parent directory as we are going to construct its childen.
parent_path = list_of_key[0]
if not parent_path.endswith(PyFunceble.directory_separator):
parent_path += PyFunceble.directory_separator
for root, _, _ in PyFunceble.walk(parent_path):
# We loop through each directories of the parent path.
# We fix the path in order to avoid issues.
root = Directory(root).fix_path()
if root.replace(parent_path, "") not in structure:
# The currently read directory is not in our structure.
# We delete it.
PyFunceble.rmtree(root)
|
[
"Delete",
"the",
"directory",
"which",
"are",
"not",
"registered",
"into",
"our",
"structure",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/directory_structure.py#L609-L641
|
[
"def",
"delete_uneeded",
"(",
"self",
")",
":",
"# We get the structure we have to apply.",
"structure",
"=",
"self",
".",
"_get_structure",
"(",
")",
"# We get the list of key which is implicitly the list of directory we do not bave to delete.",
"list_of_key",
"=",
"list",
"(",
"structure",
".",
"keys",
"(",
")",
")",
"# We move to the content of the parent as we know that we are creating only one directory.",
"# Note: if one day we will have to create multiple directory, we will have to change",
"# the following.",
"structure",
"=",
"structure",
"[",
"list_of_key",
"[",
"0",
"]",
"]",
"# We also set the parent directory as we are going to construct its childen.",
"parent_path",
"=",
"list_of_key",
"[",
"0",
"]",
"if",
"not",
"parent_path",
".",
"endswith",
"(",
"PyFunceble",
".",
"directory_separator",
")",
":",
"parent_path",
"+=",
"PyFunceble",
".",
"directory_separator",
"for",
"root",
",",
"_",
",",
"_",
"in",
"PyFunceble",
".",
"walk",
"(",
"parent_path",
")",
":",
"# We loop through each directories of the parent path.",
"# We fix the path in order to avoid issues.",
"root",
"=",
"Directory",
"(",
"root",
")",
".",
"fix_path",
"(",
")",
"if",
"root",
".",
"replace",
"(",
"parent_path",
",",
"\"\"",
")",
"not",
"in",
"structure",
":",
"# The currently read directory is not in our structure.",
"# We delete it.",
"PyFunceble",
".",
"rmtree",
"(",
"root",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Load._set_path_to_configs
|
Set the paths to the configuration files.
:param path_to_config: The possible path to the config to load.
:type path_to_config: str
:return:
The path to the config to read (0), the path to the default
configuration to read as fallback.(1)
:rtype: tuple
|
PyFunceble/config.py
|
def _set_path_to_configs(cls, path_to_config):
"""
Set the paths to the configuration files.
:param path_to_config: The possible path to the config to load.
:type path_to_config: str
:return:
The path to the config to read (0), the path to the default
configuration to read as fallback.(1)
:rtype: tuple
"""
if not path_to_config.endswith(PyFunceble.directory_separator):
# The path to the config does not ends with the directory separator.
# We initiate the default and the parsed variable with the directory separator.
default = parsed = path_to_config + PyFunceble.directory_separator
else:
# The path to the config does ends with the directory separator.
# We initiate the default and the parsed variable.
default = parsed = path_to_config
# We append the `CONFIGURATION_FILENAME` to the parsed variable.
parsed += PyFunceble.CONFIGURATION_FILENAME
# And we append the `DEFAULT_CONFIGURATION_FILENAME` to the default variable.
default += PyFunceble.DEFAULT_CONFIGURATION_FILENAME
# We finaly return a tuple which contain both informations.
return (parsed, default)
|
def _set_path_to_configs(cls, path_to_config):
"""
Set the paths to the configuration files.
:param path_to_config: The possible path to the config to load.
:type path_to_config: str
:return:
The path to the config to read (0), the path to the default
configuration to read as fallback.(1)
:rtype: tuple
"""
if not path_to_config.endswith(PyFunceble.directory_separator):
# The path to the config does not ends with the directory separator.
# We initiate the default and the parsed variable with the directory separator.
default = parsed = path_to_config + PyFunceble.directory_separator
else:
# The path to the config does ends with the directory separator.
# We initiate the default and the parsed variable.
default = parsed = path_to_config
# We append the `CONFIGURATION_FILENAME` to the parsed variable.
parsed += PyFunceble.CONFIGURATION_FILENAME
# And we append the `DEFAULT_CONFIGURATION_FILENAME` to the default variable.
default += PyFunceble.DEFAULT_CONFIGURATION_FILENAME
# We finaly return a tuple which contain both informations.
return (parsed, default)
|
[
"Set",
"the",
"paths",
"to",
"the",
"configuration",
"files",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L195-L225
|
[
"def",
"_set_path_to_configs",
"(",
"cls",
",",
"path_to_config",
")",
":",
"if",
"not",
"path_to_config",
".",
"endswith",
"(",
"PyFunceble",
".",
"directory_separator",
")",
":",
"# The path to the config does not ends with the directory separator.",
"# We initiate the default and the parsed variable with the directory separator.",
"default",
"=",
"parsed",
"=",
"path_to_config",
"+",
"PyFunceble",
".",
"directory_separator",
"else",
":",
"# The path to the config does ends with the directory separator.",
"# We initiate the default and the parsed variable.",
"default",
"=",
"parsed",
"=",
"path_to_config",
"# We append the `CONFIGURATION_FILENAME` to the parsed variable.",
"parsed",
"+=",
"PyFunceble",
".",
"CONFIGURATION_FILENAME",
"# And we append the `DEFAULT_CONFIGURATION_FILENAME` to the default variable.",
"default",
"+=",
"PyFunceble",
".",
"DEFAULT_CONFIGURATION_FILENAME",
"# We finaly return a tuple which contain both informations.",
"return",
"(",
"parsed",
",",
"default",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Load._load_config_file
|
Load .PyFunceble.yaml into the system.
|
PyFunceble/config.py
|
def _load_config_file(self):
"""
Load .PyFunceble.yaml into the system.
"""
try:
# We try to load the configuration file.
PyFunceble.CONFIGURATION.update(
Dict.from_yaml(File(self.path_to_config).read())
)
# We install the latest iana configuration file.
self._install_iana_config()
# We install the latest public suffix configuration file.
self._install_psl_config()
# We install the latest directory structure file.
self._install_directory_structure_file()
except FileNotFoundError as exception:
# But if the configuration file is not found.
if PyFunceble.path.isfile(self.path_to_default_config):
# The `DEFAULT_CONFIGURATION_FILENAME` file exists.
# We copy it as the configuration file.
File(self.path_to_default_config).copy(self.path_to_config)
# And we load the configuration file as it does exist (yet).
self._load_config_file()
else:
# The `DEFAULT_CONFIGURATION_FILENAME` file does not exists.
# We raise the exception we were handling.
raise exception
|
def _load_config_file(self):
"""
Load .PyFunceble.yaml into the system.
"""
try:
# We try to load the configuration file.
PyFunceble.CONFIGURATION.update(
Dict.from_yaml(File(self.path_to_config).read())
)
# We install the latest iana configuration file.
self._install_iana_config()
# We install the latest public suffix configuration file.
self._install_psl_config()
# We install the latest directory structure file.
self._install_directory_structure_file()
except FileNotFoundError as exception:
# But if the configuration file is not found.
if PyFunceble.path.isfile(self.path_to_default_config):
# The `DEFAULT_CONFIGURATION_FILENAME` file exists.
# We copy it as the configuration file.
File(self.path_to_default_config).copy(self.path_to_config)
# And we load the configuration file as it does exist (yet).
self._load_config_file()
else:
# The `DEFAULT_CONFIGURATION_FILENAME` file does not exists.
# We raise the exception we were handling.
raise exception
|
[
"Load",
".",
"PyFunceble",
".",
"yaml",
"into",
"the",
"system",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L227-L262
|
[
"def",
"_load_config_file",
"(",
"self",
")",
":",
"try",
":",
"# We try to load the configuration file.",
"PyFunceble",
".",
"CONFIGURATION",
".",
"update",
"(",
"Dict",
".",
"from_yaml",
"(",
"File",
"(",
"self",
".",
"path_to_config",
")",
".",
"read",
"(",
")",
")",
")",
"# We install the latest iana configuration file.",
"self",
".",
"_install_iana_config",
"(",
")",
"# We install the latest public suffix configuration file.",
"self",
".",
"_install_psl_config",
"(",
")",
"# We install the latest directory structure file.",
"self",
".",
"_install_directory_structure_file",
"(",
")",
"except",
"FileNotFoundError",
"as",
"exception",
":",
"# But if the configuration file is not found.",
"if",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"path_to_default_config",
")",
":",
"# The `DEFAULT_CONFIGURATION_FILENAME` file exists.",
"# We copy it as the configuration file.",
"File",
"(",
"self",
".",
"path_to_default_config",
")",
".",
"copy",
"(",
"self",
".",
"path_to_config",
")",
"# And we load the configuration file as it does exist (yet).",
"self",
".",
"_load_config_file",
"(",
")",
"else",
":",
"# The `DEFAULT_CONFIGURATION_FILENAME` file does not exists.",
"# We raise the exception we were handling.",
"raise",
"exception"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Load._install_production_config
|
Download the production configuration and install it in the
current directory.
|
PyFunceble/config.py
|
def _install_production_config(self):
"""
Download the production configuration and install it in the
current directory.
"""
# We initiate the link to the production configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
production_config_link = "https://raw.githubusercontent.com/funilrys/PyFunceble/master/.PyFunceble_production.yaml" # pylint: disable=line-too-long
# We update the link according to our current version.
production_config_link = Version(True).right_url_from_version(
production_config_link
)
if not Version(True).is_cloned():
# The current version is not the cloned one.
# We download the link content and save it inside the default location.
#
# Note: We add this one in order to allow the enduser to always have
# a copy of our upstream configuration file.
Download(production_config_link, self.path_to_default_config).text()
# And we download the link content and return the download status.
return Download(production_config_link, self.path_to_config).text()
|
def _install_production_config(self):
"""
Download the production configuration and install it in the
current directory.
"""
# We initiate the link to the production configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
production_config_link = "https://raw.githubusercontent.com/funilrys/PyFunceble/master/.PyFunceble_production.yaml" # pylint: disable=line-too-long
# We update the link according to our current version.
production_config_link = Version(True).right_url_from_version(
production_config_link
)
if not Version(True).is_cloned():
# The current version is not the cloned one.
# We download the link content and save it inside the default location.
#
# Note: We add this one in order to allow the enduser to always have
# a copy of our upstream configuration file.
Download(production_config_link, self.path_to_default_config).text()
# And we download the link content and return the download status.
return Download(production_config_link, self.path_to_config).text()
|
[
"Download",
"the",
"production",
"configuration",
"and",
"install",
"it",
"in",
"the",
"current",
"directory",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L264-L290
|
[
"def",
"_install_production_config",
"(",
"self",
")",
":",
"# We initiate the link to the production configuration.",
"# It is not hard coded because this method is called only if we",
"# are sure that the configuration file exist.",
"production_config_link",
"=",
"\"https://raw.githubusercontent.com/funilrys/PyFunceble/master/.PyFunceble_production.yaml\"",
"# pylint: disable=line-too-long",
"# We update the link according to our current version.",
"production_config_link",
"=",
"Version",
"(",
"True",
")",
".",
"right_url_from_version",
"(",
"production_config_link",
")",
"if",
"not",
"Version",
"(",
"True",
")",
".",
"is_cloned",
"(",
")",
":",
"# The current version is not the cloned one.",
"# We download the link content and save it inside the default location.",
"#",
"# Note: We add this one in order to allow the enduser to always have",
"# a copy of our upstream configuration file.",
"Download",
"(",
"production_config_link",
",",
"self",
".",
"path_to_default_config",
")",
".",
"text",
"(",
")",
"# And we download the link content and return the download status.",
"return",
"Download",
"(",
"production_config_link",
",",
"self",
".",
"path_to_config",
")",
".",
"text",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Load._install_iana_config
|
Download `iana-domains-db.json` if not present.
|
PyFunceble/config.py
|
def _install_iana_config(cls):
"""
Download `iana-domains-db.json` if not present.
"""
# We initiate the link to the iana configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
iana_link = PyFunceble.CONFIGURATION["links"]["iana"]
# We update the link according to our current version.
iana_link = Version(True).right_url_from_version(iana_link)
# We set the destination of the downloaded file.
destination = PyFunceble.CURRENT_DIRECTORY + "iana-domains-db.json"
if not Version(True).is_cloned() or not PyFunceble.path.isfile(destination):
# The current version is not the cloned version.
# We Download the link content and return the download status.
return Download(iana_link, destination).text()
# We are in the cloned version.
# We do not need to download the file, so we are returning None.
return None
|
def _install_iana_config(cls):
"""
Download `iana-domains-db.json` if not present.
"""
# We initiate the link to the iana configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
iana_link = PyFunceble.CONFIGURATION["links"]["iana"]
# We update the link according to our current version.
iana_link = Version(True).right_url_from_version(iana_link)
# We set the destination of the downloaded file.
destination = PyFunceble.CURRENT_DIRECTORY + "iana-domains-db.json"
if not Version(True).is_cloned() or not PyFunceble.path.isfile(destination):
# The current version is not the cloned version.
# We Download the link content and return the download status.
return Download(iana_link, destination).text()
# We are in the cloned version.
# We do not need to download the file, so we are returning None.
return None
|
[
"Download",
"iana",
"-",
"domains",
"-",
"db",
".",
"json",
"if",
"not",
"present",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L293-L318
|
[
"def",
"_install_iana_config",
"(",
"cls",
")",
":",
"# We initiate the link to the iana configuration.",
"# It is not hard coded because this method is called only if we",
"# are sure that the configuration file exist.",
"iana_link",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"links\"",
"]",
"[",
"\"iana\"",
"]",
"# We update the link according to our current version.",
"iana_link",
"=",
"Version",
"(",
"True",
")",
".",
"right_url_from_version",
"(",
"iana_link",
")",
"# We set the destination of the downloaded file.",
"destination",
"=",
"PyFunceble",
".",
"CURRENT_DIRECTORY",
"+",
"\"iana-domains-db.json\"",
"if",
"not",
"Version",
"(",
"True",
")",
".",
"is_cloned",
"(",
")",
"or",
"not",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"destination",
")",
":",
"# The current version is not the cloned version.",
"# We Download the link content and return the download status.",
"return",
"Download",
"(",
"iana_link",
",",
"destination",
")",
".",
"text",
"(",
")",
"# We are in the cloned version.",
"# We do not need to download the file, so we are returning None.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Load._install_psl_config
|
Download `public-suffix.json` if not present.
|
PyFunceble/config.py
|
def _install_psl_config(cls):
"""
Download `public-suffix.json` if not present.
"""
# We initiate the link to the public suffix configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
psl_link = PyFunceble.CONFIGURATION["links"]["psl"]
# We update the link according to our current version.
psl_link = Version(True).right_url_from_version(psl_link)
# We set the destination of the downloaded file.
destination = (
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["public_suffix"]
)
if not Version(True).is_cloned() or not PyFunceble.path.isfile(destination):
# The current version is not the cloned version.
# We Download the link content and return the download status.
return Download(psl_link, destination).text()
# We are in the cloned version.
# We do not need to download the file, so we are returning None.
return None
|
def _install_psl_config(cls):
"""
Download `public-suffix.json` if not present.
"""
# We initiate the link to the public suffix configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
psl_link = PyFunceble.CONFIGURATION["links"]["psl"]
# We update the link according to our current version.
psl_link = Version(True).right_url_from_version(psl_link)
# We set the destination of the downloaded file.
destination = (
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["public_suffix"]
)
if not Version(True).is_cloned() or not PyFunceble.path.isfile(destination):
# The current version is not the cloned version.
# We Download the link content and return the download status.
return Download(psl_link, destination).text()
# We are in the cloned version.
# We do not need to download the file, so we are returning None.
return None
|
[
"Download",
"public",
"-",
"suffix",
".",
"json",
"if",
"not",
"present",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L321-L349
|
[
"def",
"_install_psl_config",
"(",
"cls",
")",
":",
"# We initiate the link to the public suffix configuration.",
"# It is not hard coded because this method is called only if we",
"# are sure that the configuration file exist.",
"psl_link",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"links\"",
"]",
"[",
"\"psl\"",
"]",
"# We update the link according to our current version.",
"psl_link",
"=",
"Version",
"(",
"True",
")",
".",
"right_url_from_version",
"(",
"psl_link",
")",
"# We set the destination of the downloaded file.",
"destination",
"=",
"(",
"PyFunceble",
".",
"CURRENT_DIRECTORY",
"+",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"outputs\"",
"]",
"[",
"\"default_files\"",
"]",
"[",
"\"public_suffix\"",
"]",
")",
"if",
"not",
"Version",
"(",
"True",
")",
".",
"is_cloned",
"(",
")",
"or",
"not",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"destination",
")",
":",
"# The current version is not the cloned version.",
"# We Download the link content and return the download status.",
"return",
"Download",
"(",
"psl_link",
",",
"destination",
")",
".",
"text",
"(",
")",
"# We are in the cloned version.",
"# We do not need to download the file, so we are returning None.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Load._install_directory_structure_file
|
Download the latest version of `dir_structure_production.json`.
|
PyFunceble/config.py
|
def _install_directory_structure_file(cls):
"""
Download the latest version of `dir_structure_production.json`.
"""
# We initiate the link to the public suffix configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
dir_structure_link = PyFunceble.CONFIGURATION["links"]["dir_structure"]
# We update the link according to our current version.
dir_structure_link = Version(True).right_url_from_version(dir_structure_link)
# We set the destination of the downloaded file.
destination = (
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["dir_structure"]
)
if not Version(True).is_cloned() or not PyFunceble.path.isfile(destination):
# The current version is not the cloned version.
# We Download the link content and return the download status.
data = Download(dir_structure_link, destination, return_data=True).text()
File(destination).write(data, overwrite=True)
return True
# We are in the cloned version.
# We do not need to download the file, so we are returning None.
return None
|
def _install_directory_structure_file(cls):
"""
Download the latest version of `dir_structure_production.json`.
"""
# We initiate the link to the public suffix configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
dir_structure_link = PyFunceble.CONFIGURATION["links"]["dir_structure"]
# We update the link according to our current version.
dir_structure_link = Version(True).right_url_from_version(dir_structure_link)
# We set the destination of the downloaded file.
destination = (
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["dir_structure"]
)
if not Version(True).is_cloned() or not PyFunceble.path.isfile(destination):
# The current version is not the cloned version.
# We Download the link content and return the download status.
data = Download(dir_structure_link, destination, return_data=True).text()
File(destination).write(data, overwrite=True)
return True
# We are in the cloned version.
# We do not need to download the file, so we are returning None.
return None
|
[
"Download",
"the",
"latest",
"version",
"of",
"dir_structure_production",
".",
"json",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L352-L383
|
[
"def",
"_install_directory_structure_file",
"(",
"cls",
")",
":",
"# We initiate the link to the public suffix configuration.",
"# It is not hard coded because this method is called only if we",
"# are sure that the configuration file exist.",
"dir_structure_link",
"=",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"links\"",
"]",
"[",
"\"dir_structure\"",
"]",
"# We update the link according to our current version.",
"dir_structure_link",
"=",
"Version",
"(",
"True",
")",
".",
"right_url_from_version",
"(",
"dir_structure_link",
")",
"# We set the destination of the downloaded file.",
"destination",
"=",
"(",
"PyFunceble",
".",
"CURRENT_DIRECTORY",
"+",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"outputs\"",
"]",
"[",
"\"default_files\"",
"]",
"[",
"\"dir_structure\"",
"]",
")",
"if",
"not",
"Version",
"(",
"True",
")",
".",
"is_cloned",
"(",
")",
"or",
"not",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"destination",
")",
":",
"# The current version is not the cloned version.",
"# We Download the link content and return the download status.",
"data",
"=",
"Download",
"(",
"dir_structure_link",
",",
"destination",
",",
"return_data",
"=",
"True",
")",
".",
"text",
"(",
")",
"File",
"(",
"destination",
")",
".",
"write",
"(",
"data",
",",
"overwrite",
"=",
"True",
")",
"return",
"True",
"# We are in the cloned version.",
"# We do not need to download the file, so we are returning None.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Merge._merge_values
|
Simply merge the older into the new one.
|
PyFunceble/config.py
|
def _merge_values(self):
"""
Simply merge the older into the new one.
"""
to_remove = []
self.new_config = Dict(
Dict(self.upstream_config).merge(PyFunceble.CONFIGURATION)
).remove_key(to_remove)
|
def _merge_values(self):
"""
Simply merge the older into the new one.
"""
to_remove = []
self.new_config = Dict(
Dict(self.upstream_config).merge(PyFunceble.CONFIGURATION)
).remove_key(to_remove)
|
[
"Simply",
"merge",
"the",
"older",
"into",
"the",
"new",
"one",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L415-L424
|
[
"def",
"_merge_values",
"(",
"self",
")",
":",
"to_remove",
"=",
"[",
"]",
"self",
".",
"new_config",
"=",
"Dict",
"(",
"Dict",
"(",
"self",
".",
"upstream_config",
")",
".",
"merge",
"(",
"PyFunceble",
".",
"CONFIGURATION",
")",
")",
".",
"remove_key",
"(",
"to_remove",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Merge._load
|
Execute the logic behind the merging.
|
PyFunceble/config.py
|
def _load(self):
"""
Execute the logic behind the merging.
"""
if "PYFUNCEBLE_AUTO_CONFIGURATION" not in PyFunceble.environ:
# The auto configuration environment variable is not set.
while True:
# We infinitly loop until we get a reponse which is `y|Y` or `n|N`.
# We ask the user if we should install and load the default configuration.
response = input(
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.RED
+ "A configuration key is missing.\n"
+ PyFunceble.Fore.RESET
+ "Try to merge upstream configuration file into %s ? [y/n] "
% (
PyFunceble.Style.BRIGHT
+ self.path_to_config
+ PyFunceble.Style.RESET_ALL
)
)
if isinstance(response, str):
# The response is a string
if response.lower() == "y":
# The response is a `y` or `Y`.
# We merge the old values inside the new one.
self._merge_values()
# And we save.
self._save()
print(
PyFunceble.Style.BRIGHT + PyFunceble.Fore.GREEN + "Done!\n"
"Please try again, if it happens again,"
" please fill a new issue."
)
# And we break the loop as we got a satisfied response.
break
elif response.lower() == "n":
# The response is a `n` or `N`.
# We inform the user that something went wrong.
raise Exception("Configuration key still missing.")
else:
# The auto configuration environment variable is set.
# We merge the old values inside the new one.
self._merge_values()
# And we save.
self._save()
|
def _load(self):
"""
Execute the logic behind the merging.
"""
if "PYFUNCEBLE_AUTO_CONFIGURATION" not in PyFunceble.environ:
# The auto configuration environment variable is not set.
while True:
# We infinitly loop until we get a reponse which is `y|Y` or `n|N`.
# We ask the user if we should install and load the default configuration.
response = input(
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.RED
+ "A configuration key is missing.\n"
+ PyFunceble.Fore.RESET
+ "Try to merge upstream configuration file into %s ? [y/n] "
% (
PyFunceble.Style.BRIGHT
+ self.path_to_config
+ PyFunceble.Style.RESET_ALL
)
)
if isinstance(response, str):
# The response is a string
if response.lower() == "y":
# The response is a `y` or `Y`.
# We merge the old values inside the new one.
self._merge_values()
# And we save.
self._save()
print(
PyFunceble.Style.BRIGHT + PyFunceble.Fore.GREEN + "Done!\n"
"Please try again, if it happens again,"
" please fill a new issue."
)
# And we break the loop as we got a satisfied response.
break
elif response.lower() == "n":
# The response is a `n` or `N`.
# We inform the user that something went wrong.
raise Exception("Configuration key still missing.")
else:
# The auto configuration environment variable is set.
# We merge the old values inside the new one.
self._merge_values()
# And we save.
self._save()
|
[
"Execute",
"the",
"logic",
"behind",
"the",
"merging",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L433-L491
|
[
"def",
"_load",
"(",
"self",
")",
":",
"if",
"\"PYFUNCEBLE_AUTO_CONFIGURATION\"",
"not",
"in",
"PyFunceble",
".",
"environ",
":",
"# The auto configuration environment variable is not set.",
"while",
"True",
":",
"# We infinitly loop until we get a reponse which is `y|Y` or `n|N`.",
"# We ask the user if we should install and load the default configuration.",
"response",
"=",
"input",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"PyFunceble",
".",
"Fore",
".",
"RED",
"+",
"\"A configuration key is missing.\\n\"",
"+",
"PyFunceble",
".",
"Fore",
".",
"RESET",
"+",
"\"Try to merge upstream configuration file into %s ? [y/n] \"",
"%",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"self",
".",
"path_to_config",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
")",
")",
"if",
"isinstance",
"(",
"response",
",",
"str",
")",
":",
"# The response is a string",
"if",
"response",
".",
"lower",
"(",
")",
"==",
"\"y\"",
":",
"# The response is a `y` or `Y`.",
"# We merge the old values inside the new one.",
"self",
".",
"_merge_values",
"(",
")",
"# And we save.",
"self",
".",
"_save",
"(",
")",
"print",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"PyFunceble",
".",
"Fore",
".",
"GREEN",
"+",
"\"Done!\\n\"",
"\"Please try again, if it happens again,\"",
"\" please fill a new issue.\"",
")",
"# And we break the loop as we got a satisfied response.",
"break",
"elif",
"response",
".",
"lower",
"(",
")",
"==",
"\"n\"",
":",
"# The response is a `n` or `N`.",
"# We inform the user that something went wrong.",
"raise",
"Exception",
"(",
"\"Configuration key still missing.\"",
")",
"else",
":",
"# The auto configuration environment variable is set.",
"# We merge the old values inside the new one.",
"self",
".",
"_merge_values",
"(",
")",
"# And we save.",
"self",
".",
"_save",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Version.split_versions
|
Convert the versions to a shorter one.
:param version: The version to split.
:type version: str
:param return_non_digits:
Activate the return of the non-digits parts of the splitted
version.
:type return_non_digits: bool
:return: The splitted version name/numbers.
:rtype: list
|
PyFunceble/config.py
|
def split_versions(cls, version, return_non_digits=False):
"""
Convert the versions to a shorter one.
:param version: The version to split.
:type version: str
:param return_non_digits:
Activate the return of the non-digits parts of the splitted
version.
:type return_non_digits: bool
:return: The splitted version name/numbers.
:rtype: list
"""
# We split the version.
splited_version = version.split(".")
# We split the parsed version and keep the digits.
digits = [x for x in splited_version if x.isdigit()]
if not return_non_digits:
# We do not have to return the non digits part of the version.
# We return the digits part of the version.
return digits
# We have to return the non digit parts of the version.
# We split the parsed version and keep the non digits.
non_digits = [x for x in splited_version if not x.isdigit()]
# We return a tuple with first the digits part and finally the non digit parts.
return (digits, non_digits[0])
|
def split_versions(cls, version, return_non_digits=False):
"""
Convert the versions to a shorter one.
:param version: The version to split.
:type version: str
:param return_non_digits:
Activate the return of the non-digits parts of the splitted
version.
:type return_non_digits: bool
:return: The splitted version name/numbers.
:rtype: list
"""
# We split the version.
splited_version = version.split(".")
# We split the parsed version and keep the digits.
digits = [x for x in splited_version if x.isdigit()]
if not return_non_digits:
# We do not have to return the non digits part of the version.
# We return the digits part of the version.
return digits
# We have to return the non digit parts of the version.
# We split the parsed version and keep the non digits.
non_digits = [x for x in splited_version if not x.isdigit()]
# We return a tuple with first the digits part and finally the non digit parts.
return (digits, non_digits[0])
|
[
"Convert",
"the",
"versions",
"to",
"a",
"shorter",
"one",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L528-L562
|
[
"def",
"split_versions",
"(",
"cls",
",",
"version",
",",
"return_non_digits",
"=",
"False",
")",
":",
"# We split the version.",
"splited_version",
"=",
"version",
".",
"split",
"(",
"\".\"",
")",
"# We split the parsed version and keep the digits.",
"digits",
"=",
"[",
"x",
"for",
"x",
"in",
"splited_version",
"if",
"x",
".",
"isdigit",
"(",
")",
"]",
"if",
"not",
"return_non_digits",
":",
"# We do not have to return the non digits part of the version.",
"# We return the digits part of the version.",
"return",
"digits",
"# We have to return the non digit parts of the version.",
"# We split the parsed version and keep the non digits.",
"non_digits",
"=",
"[",
"x",
"for",
"x",
"in",
"splited_version",
"if",
"not",
"x",
".",
"isdigit",
"(",
")",
"]",
"# We return a tuple with first the digits part and finally the non digit parts.",
"return",
"(",
"digits",
",",
"non_digits",
"[",
"0",
"]",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Version.check_versions
|
Compare the given versions.
:param local: The local version converted by split_versions().
:type local: list
:param upstream: The upstream version converted by split_versions().
:type upstream: list
:return:
- True: local < upstream
- None: local == upstream
- False: local > upstream
:rtype: bool|None
|
PyFunceble/config.py
|
def check_versions(cls, local, upstream):
"""
Compare the given versions.
:param local: The local version converted by split_versions().
:type local: list
:param upstream: The upstream version converted by split_versions().
:type upstream: list
:return:
- True: local < upstream
- None: local == upstream
- False: local > upstream
:rtype: bool|None
"""
# A version should be in format [1,2,3] which is actually the version `1.2.3`
# So as we only have 3 elements in the versioning,
# we initiate the following variable in order to get the status of each parts.
status = [None, None, None]
for index, version_number in enumerate(local):
# We loop through the local version.
if int(version_number) < int(upstream[index]):
# The local version is less than the upstream version.
# We initiate its status to True which means that we are in
# an old version (for the current version part).
status[index] = True
elif int(version_number) > int(upstream[index]):
# The local version is greater then the upstream version.
# We initiate its status to False which means that we are in
# a more recent version (for the current version part).
status[index] = False
# Otherwise the status stay None which means that there is no change
# between both local and upstream.
if False in status:
# There is a False in the status.
# We return False which means that we are in a more recent version.
return False
if True in status:
# There is a True in the status.
# We return True which means that we are in a older version.
return True
# There is no True or False in the status.
# We return None which means that we are in the same version as upstream.
return None
|
def check_versions(cls, local, upstream):
"""
Compare the given versions.
:param local: The local version converted by split_versions().
:type local: list
:param upstream: The upstream version converted by split_versions().
:type upstream: list
:return:
- True: local < upstream
- None: local == upstream
- False: local > upstream
:rtype: bool|None
"""
# A version should be in format [1,2,3] which is actually the version `1.2.3`
# So as we only have 3 elements in the versioning,
# we initiate the following variable in order to get the status of each parts.
status = [None, None, None]
for index, version_number in enumerate(local):
# We loop through the local version.
if int(version_number) < int(upstream[index]):
# The local version is less than the upstream version.
# We initiate its status to True which means that we are in
# an old version (for the current version part).
status[index] = True
elif int(version_number) > int(upstream[index]):
# The local version is greater then the upstream version.
# We initiate its status to False which means that we are in
# a more recent version (for the current version part).
status[index] = False
# Otherwise the status stay None which means that there is no change
# between both local and upstream.
if False in status:
# There is a False in the status.
# We return False which means that we are in a more recent version.
return False
if True in status:
# There is a True in the status.
# We return True which means that we are in a older version.
return True
# There is no True or False in the status.
# We return None which means that we are in the same version as upstream.
return None
|
[
"Compare",
"the",
"given",
"versions",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L584-L640
|
[
"def",
"check_versions",
"(",
"cls",
",",
"local",
",",
"upstream",
")",
":",
"# A version should be in format [1,2,3] which is actually the version `1.2.3`",
"# So as we only have 3 elements in the versioning,",
"# we initiate the following variable in order to get the status of each parts.",
"status",
"=",
"[",
"None",
",",
"None",
",",
"None",
"]",
"for",
"index",
",",
"version_number",
"in",
"enumerate",
"(",
"local",
")",
":",
"# We loop through the local version.",
"if",
"int",
"(",
"version_number",
")",
"<",
"int",
"(",
"upstream",
"[",
"index",
"]",
")",
":",
"# The local version is less than the upstream version.",
"# We initiate its status to True which means that we are in",
"# an old version (for the current version part).",
"status",
"[",
"index",
"]",
"=",
"True",
"elif",
"int",
"(",
"version_number",
")",
">",
"int",
"(",
"upstream",
"[",
"index",
"]",
")",
":",
"# The local version is greater then the upstream version.",
"# We initiate its status to False which means that we are in",
"# a more recent version (for the current version part).",
"status",
"[",
"index",
"]",
"=",
"False",
"# Otherwise the status stay None which means that there is no change",
"# between both local and upstream.",
"if",
"False",
"in",
"status",
":",
"# There is a False in the status.",
"# We return False which means that we are in a more recent version.",
"return",
"False",
"if",
"True",
"in",
"status",
":",
"# There is a True in the status.",
"# We return True which means that we are in a older version.",
"return",
"True",
"# There is no True or False in the status.",
"# We return None which means that we are in the same version as upstream.",
"return",
"None"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Version.compare
|
Compare the current version with the upstream saved version.
|
PyFunceble/config.py
|
def compare(self):
"""
Compare the current version with the upstream saved version.
"""
if self.upstream_data["force_update"]["status"]:
# The force_update status is set to True.
for minimal in self.upstream_data["force_update"]["minimal_version"]:
# We loop through the list of minimal version which trigger the
# the force update message.
# We compare the local with the currently read minimal version.
checked = self.check_versions(
self.local_splited, self.split_versions(minimal)
)
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
if checked or checked is not False and not checked:
# The current version is less or equal to
# the minimal version.
# We initiate the message we are going to return to
# the user.
message = (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.RED
+ "A critical issue has been fixed.\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
message += (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.GREEN
+ "Please take the time to update PyFunceble!\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
# We print the message on screen.
print(message)
# We exit PyFunceble with the code 1.
exit(1)
elif checked or checked is not False and not checked:
# The quiet mode is activated and the current version
# is less or equal to the minimal version.
# We raise an exception telling the user to update their
# instance of PyFunceble.
raise Exception(
"A critical issue has been fixed. Please take the time to update PyFunceble!" # pylint:disable=line-too-long
)
for version in self.upstream_data["deprecated"]:
# We loop through the list of deprecated versions.
# We compare the local with the currently read deprecated version.
checked = self.check_versions(
self.local_splited, self.split_versions(version)
)
if (
not PyFunceble.CONFIGURATION["quiet"]
and checked
or checked is not False
and not checked
):
# The quiet mode is not activated and the local version is
# less or equal to the currently read deprecated version.
# We initiate the message we are going to return to the user.
message = (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.RED
+ "Your current version is considered as deprecated.\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
message += (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.GREEN
+ "Please take the time to update PyFunceble!\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
# We print the message.
print(message)
# And we continue to the next logic. There is no need to
# shutdown PyFunceble as it's just for information.
return
# The quiet mode is activated.
if checked or checked is not False and not checked:
# The local version is less or equal to the currently
# read deprecated version.
print("Version deprecated.")
# And we continue to the next logic. There is no need to
# shutdown PyFunceble as it's just for information.
return
# We compare the local version with the upstream version.
status = self.check_versions(
self.local_splited,
self.split_versions(self.upstream_data["current_version"]),
)
if status is not None and not status and not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activate and the current version is greater than
# the upstream version.
# We initiate the message we are going to return to the user.
message = (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.CYAN
+ "Your version is more recent!\nYou should really think about sharing your changes with the community!\n" # pylint:disable=line-too-long
+ PyFunceble.Style.RESET_ALL
)
message += (
PyFunceble.Style.BRIGHT
+ "Your version: "
+ PyFunceble.Style.RESET_ALL
+ PyFunceble.VERSION
+ "\n"
)
message += (
PyFunceble.Style.BRIGHT
+ "Upstream version: "
+ PyFunceble.Style.RESET_ALL
+ self.upstream_data["current_version"]
+ "\n"
)
# We print the message.
print(message)
elif status:
# The current version is less that the upstream version.
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
# We initiate the message we are going to return to the user.
message = (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.YELLOW
+ "Please take the time to update PyFunceble!\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
message += (
PyFunceble.Style.BRIGHT
+ "Your version: "
+ PyFunceble.Style.RESET_ALL
+ PyFunceble.VERSION
+ "\n"
) # pylint:disable=line-too-long
message += (
PyFunceble.Style.BRIGHT
+ "Upstream version: "
+ PyFunceble.Style.RESET_ALL
+ self.upstream_data[ # pylint:disable=line-too-long
"current_version"
]
+ "\n"
)
# We print the message.
print(message)
else:
# The quiet mode is activated.
# We print the message.
print("New version available.")
# And we continue to the next app logic. There is no need to
# shutdown PyFunceble as it's just for information.
return
|
def compare(self):
"""
Compare the current version with the upstream saved version.
"""
if self.upstream_data["force_update"]["status"]:
# The force_update status is set to True.
for minimal in self.upstream_data["force_update"]["minimal_version"]:
# We loop through the list of minimal version which trigger the
# the force update message.
# We compare the local with the currently read minimal version.
checked = self.check_versions(
self.local_splited, self.split_versions(minimal)
)
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
if checked or checked is not False and not checked:
# The current version is less or equal to
# the minimal version.
# We initiate the message we are going to return to
# the user.
message = (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.RED
+ "A critical issue has been fixed.\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
message += (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.GREEN
+ "Please take the time to update PyFunceble!\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
# We print the message on screen.
print(message)
# We exit PyFunceble with the code 1.
exit(1)
elif checked or checked is not False and not checked:
# The quiet mode is activated and the current version
# is less or equal to the minimal version.
# We raise an exception telling the user to update their
# instance of PyFunceble.
raise Exception(
"A critical issue has been fixed. Please take the time to update PyFunceble!" # pylint:disable=line-too-long
)
for version in self.upstream_data["deprecated"]:
# We loop through the list of deprecated versions.
# We compare the local with the currently read deprecated version.
checked = self.check_versions(
self.local_splited, self.split_versions(version)
)
if (
not PyFunceble.CONFIGURATION["quiet"]
and checked
or checked is not False
and not checked
):
# The quiet mode is not activated and the local version is
# less or equal to the currently read deprecated version.
# We initiate the message we are going to return to the user.
message = (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.RED
+ "Your current version is considered as deprecated.\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
message += (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.GREEN
+ "Please take the time to update PyFunceble!\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
# We print the message.
print(message)
# And we continue to the next logic. There is no need to
# shutdown PyFunceble as it's just for information.
return
# The quiet mode is activated.
if checked or checked is not False and not checked:
# The local version is less or equal to the currently
# read deprecated version.
print("Version deprecated.")
# And we continue to the next logic. There is no need to
# shutdown PyFunceble as it's just for information.
return
# We compare the local version with the upstream version.
status = self.check_versions(
self.local_splited,
self.split_versions(self.upstream_data["current_version"]),
)
if status is not None and not status and not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activate and the current version is greater than
# the upstream version.
# We initiate the message we are going to return to the user.
message = (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.CYAN
+ "Your version is more recent!\nYou should really think about sharing your changes with the community!\n" # pylint:disable=line-too-long
+ PyFunceble.Style.RESET_ALL
)
message += (
PyFunceble.Style.BRIGHT
+ "Your version: "
+ PyFunceble.Style.RESET_ALL
+ PyFunceble.VERSION
+ "\n"
)
message += (
PyFunceble.Style.BRIGHT
+ "Upstream version: "
+ PyFunceble.Style.RESET_ALL
+ self.upstream_data["current_version"]
+ "\n"
)
# We print the message.
print(message)
elif status:
# The current version is less that the upstream version.
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
# We initiate the message we are going to return to the user.
message = (
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.YELLOW
+ "Please take the time to update PyFunceble!\n"
+ PyFunceble.Style.RESET_ALL
) # pylint:disable=line-too-long
message += (
PyFunceble.Style.BRIGHT
+ "Your version: "
+ PyFunceble.Style.RESET_ALL
+ PyFunceble.VERSION
+ "\n"
) # pylint:disable=line-too-long
message += (
PyFunceble.Style.BRIGHT
+ "Upstream version: "
+ PyFunceble.Style.RESET_ALL
+ self.upstream_data[ # pylint:disable=line-too-long
"current_version"
]
+ "\n"
)
# We print the message.
print(message)
else:
# The quiet mode is activated.
# We print the message.
print("New version available.")
# And we continue to the next app logic. There is no need to
# shutdown PyFunceble as it's just for information.
return
|
[
"Compare",
"the",
"current",
"version",
"with",
"the",
"upstream",
"saved",
"version",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L642-L819
|
[
"def",
"compare",
"(",
"self",
")",
":",
"if",
"self",
".",
"upstream_data",
"[",
"\"force_update\"",
"]",
"[",
"\"status\"",
"]",
":",
"# The force_update status is set to True.",
"for",
"minimal",
"in",
"self",
".",
"upstream_data",
"[",
"\"force_update\"",
"]",
"[",
"\"minimal_version\"",
"]",
":",
"# We loop through the list of minimal version which trigger the",
"# the force update message.",
"# We compare the local with the currently read minimal version.",
"checked",
"=",
"self",
".",
"check_versions",
"(",
"self",
".",
"local_splited",
",",
"self",
".",
"split_versions",
"(",
"minimal",
")",
")",
"if",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
":",
"# The quiet mode is not activated.",
"if",
"checked",
"or",
"checked",
"is",
"not",
"False",
"and",
"not",
"checked",
":",
"# The current version is less or equal to",
"# the minimal version.",
"# We initiate the message we are going to return to",
"# the user.",
"message",
"=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"PyFunceble",
".",
"Fore",
".",
"RED",
"+",
"\"A critical issue has been fixed.\\n\"",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
")",
"# pylint:disable=line-too-long",
"message",
"+=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"PyFunceble",
".",
"Fore",
".",
"GREEN",
"+",
"\"Please take the time to update PyFunceble!\\n\"",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
")",
"# pylint:disable=line-too-long",
"# We print the message on screen.",
"print",
"(",
"message",
")",
"# We exit PyFunceble with the code 1.",
"exit",
"(",
"1",
")",
"elif",
"checked",
"or",
"checked",
"is",
"not",
"False",
"and",
"not",
"checked",
":",
"# The quiet mode is activated and the current version",
"# is less or equal to the minimal version.",
"# We raise an exception telling the user to update their",
"# instance of PyFunceble.",
"raise",
"Exception",
"(",
"\"A critical issue has been fixed. Please take the time to update PyFunceble!\"",
"# pylint:disable=line-too-long",
")",
"for",
"version",
"in",
"self",
".",
"upstream_data",
"[",
"\"deprecated\"",
"]",
":",
"# We loop through the list of deprecated versions.",
"# We compare the local with the currently read deprecated version.",
"checked",
"=",
"self",
".",
"check_versions",
"(",
"self",
".",
"local_splited",
",",
"self",
".",
"split_versions",
"(",
"version",
")",
")",
"if",
"(",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
"and",
"checked",
"or",
"checked",
"is",
"not",
"False",
"and",
"not",
"checked",
")",
":",
"# The quiet mode is not activated and the local version is",
"# less or equal to the currently read deprecated version.",
"# We initiate the message we are going to return to the user.",
"message",
"=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"PyFunceble",
".",
"Fore",
".",
"RED",
"+",
"\"Your current version is considered as deprecated.\\n\"",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
")",
"# pylint:disable=line-too-long",
"message",
"+=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"PyFunceble",
".",
"Fore",
".",
"GREEN",
"+",
"\"Please take the time to update PyFunceble!\\n\"",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
")",
"# pylint:disable=line-too-long",
"# We print the message.",
"print",
"(",
"message",
")",
"# And we continue to the next logic. There is no need to",
"# shutdown PyFunceble as it's just for information.",
"return",
"# The quiet mode is activated.",
"if",
"checked",
"or",
"checked",
"is",
"not",
"False",
"and",
"not",
"checked",
":",
"# The local version is less or equal to the currently",
"# read deprecated version.",
"print",
"(",
"\"Version deprecated.\"",
")",
"# And we continue to the next logic. There is no need to",
"# shutdown PyFunceble as it's just for information.",
"return",
"# We compare the local version with the upstream version.",
"status",
"=",
"self",
".",
"check_versions",
"(",
"self",
".",
"local_splited",
",",
"self",
".",
"split_versions",
"(",
"self",
".",
"upstream_data",
"[",
"\"current_version\"",
"]",
")",
",",
")",
"if",
"status",
"is",
"not",
"None",
"and",
"not",
"status",
"and",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
":",
"# The quiet mode is not activate and the current version is greater than",
"# the upstream version.",
"# We initiate the message we are going to return to the user.",
"message",
"=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"PyFunceble",
".",
"Fore",
".",
"CYAN",
"+",
"\"Your version is more recent!\\nYou should really think about sharing your changes with the community!\\n\"",
"# pylint:disable=line-too-long",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
")",
"message",
"+=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"\"Your version: \"",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
"+",
"PyFunceble",
".",
"VERSION",
"+",
"\"\\n\"",
")",
"message",
"+=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"\"Upstream version: \"",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
"+",
"self",
".",
"upstream_data",
"[",
"\"current_version\"",
"]",
"+",
"\"\\n\"",
")",
"# We print the message.",
"print",
"(",
"message",
")",
"elif",
"status",
":",
"# The current version is less that the upstream version.",
"if",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
":",
"# The quiet mode is not activated.",
"# We initiate the message we are going to return to the user.",
"message",
"=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"PyFunceble",
".",
"Fore",
".",
"YELLOW",
"+",
"\"Please take the time to update PyFunceble!\\n\"",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
")",
"# pylint:disable=line-too-long",
"message",
"+=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"\"Your version: \"",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
"+",
"PyFunceble",
".",
"VERSION",
"+",
"\"\\n\"",
")",
"# pylint:disable=line-too-long",
"message",
"+=",
"(",
"PyFunceble",
".",
"Style",
".",
"BRIGHT",
"+",
"\"Upstream version: \"",
"+",
"PyFunceble",
".",
"Style",
".",
"RESET_ALL",
"+",
"self",
".",
"upstream_data",
"[",
"# pylint:disable=line-too-long",
"\"current_version\"",
"]",
"+",
"\"\\n\"",
")",
"# We print the message.",
"print",
"(",
"message",
")",
"else",
":",
"# The quiet mode is activated.",
"# We print the message.",
"print",
"(",
"\"New version available.\"",
")",
"# And we continue to the next app logic. There is no need to",
"# shutdown PyFunceble as it's just for information.",
"return"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Version.is_cloned
|
Let us know if we are currently in the cloned version of
PyFunceble which implicitly mean that we are in developement mode.
|
PyFunceble/config.py
|
def is_cloned(cls):
"""
Let us know if we are currently in the cloned version of
PyFunceble which implicitly mean that we are in developement mode.
"""
if not PyFunceble.path.isdir(".git"):
# The git directory does not exist.
# We return False, the current version is not the cloned version.
return False
# We list the list of file which can be found only in a cloned version.
list_of_file = [
".coveragerc",
".coveralls.yml",
".gitignore",
".PyFunceble_production.yaml",
".travis.yml",
"CODE_OF_CONDUCT.md",
"CONTRIBUTING.md",
"dir_structure_production.json",
"MANIFEST.in",
"README.rst",
"requirements.txt",
"setup.py",
"version.yaml",
]
# We list the list of directory which can be found only in a cloned
# version.
list_of_dir = ["docs", "PyFunceble", "tests"]
for file in list_of_file:
# We loop through the list of file.
if not PyFunceble.path.isfile(file):
# The file does not exist in the current directory.
# We return False, the current version is not the cloned version.
return False
# All required files exist in the current directory.
for directory in list_of_dir:
# We loop through the list of directory.
if not PyFunceble.path.isdir(directory):
# The directory does not exist in the current directory.
# We return False, the current version is not the cloned version.
return False
# All required directories exist in the current directory.
# We return True, the current version is a cloned version.
return True
|
def is_cloned(cls):
"""
Let us know if we are currently in the cloned version of
PyFunceble which implicitly mean that we are in developement mode.
"""
if not PyFunceble.path.isdir(".git"):
# The git directory does not exist.
# We return False, the current version is not the cloned version.
return False
# We list the list of file which can be found only in a cloned version.
list_of_file = [
".coveragerc",
".coveralls.yml",
".gitignore",
".PyFunceble_production.yaml",
".travis.yml",
"CODE_OF_CONDUCT.md",
"CONTRIBUTING.md",
"dir_structure_production.json",
"MANIFEST.in",
"README.rst",
"requirements.txt",
"setup.py",
"version.yaml",
]
# We list the list of directory which can be found only in a cloned
# version.
list_of_dir = ["docs", "PyFunceble", "tests"]
for file in list_of_file:
# We loop through the list of file.
if not PyFunceble.path.isfile(file):
# The file does not exist in the current directory.
# We return False, the current version is not the cloned version.
return False
# All required files exist in the current directory.
for directory in list_of_dir:
# We loop through the list of directory.
if not PyFunceble.path.isdir(directory):
# The directory does not exist in the current directory.
# We return False, the current version is not the cloned version.
return False
# All required directories exist in the current directory.
# We return True, the current version is a cloned version.
return True
|
[
"Let",
"us",
"know",
"if",
"we",
"are",
"currently",
"in",
"the",
"cloned",
"version",
"of",
"PyFunceble",
"which",
"implicitly",
"mean",
"that",
"we",
"are",
"in",
"developement",
"mode",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/config.py#L822-L878
|
[
"def",
"is_cloned",
"(",
"cls",
")",
":",
"if",
"not",
"PyFunceble",
".",
"path",
".",
"isdir",
"(",
"\".git\"",
")",
":",
"# The git directory does not exist.",
"# We return False, the current version is not the cloned version.",
"return",
"False",
"# We list the list of file which can be found only in a cloned version.",
"list_of_file",
"=",
"[",
"\".coveragerc\"",
",",
"\".coveralls.yml\"",
",",
"\".gitignore\"",
",",
"\".PyFunceble_production.yaml\"",
",",
"\".travis.yml\"",
",",
"\"CODE_OF_CONDUCT.md\"",
",",
"\"CONTRIBUTING.md\"",
",",
"\"dir_structure_production.json\"",
",",
"\"MANIFEST.in\"",
",",
"\"README.rst\"",
",",
"\"requirements.txt\"",
",",
"\"setup.py\"",
",",
"\"version.yaml\"",
",",
"]",
"# We list the list of directory which can be found only in a cloned",
"# version.",
"list_of_dir",
"=",
"[",
"\"docs\"",
",",
"\"PyFunceble\"",
",",
"\"tests\"",
"]",
"for",
"file",
"in",
"list_of_file",
":",
"# We loop through the list of file.",
"if",
"not",
"PyFunceble",
".",
"path",
".",
"isfile",
"(",
"file",
")",
":",
"# The file does not exist in the current directory.",
"# We return False, the current version is not the cloned version.",
"return",
"False",
"# All required files exist in the current directory.",
"for",
"directory",
"in",
"list_of_dir",
":",
"# We loop through the list of directory.",
"if",
"not",
"PyFunceble",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"# The directory does not exist in the current directory.",
"# We return False, the current version is not the cloned version.",
"return",
"False",
"# All required directories exist in the current directory.",
"# We return True, the current version is a cloned version.",
"return",
"True"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Generate._handle_non_existant_index
|
Handle and check that some configuration index exists.
|
PyFunceble/generate.py
|
def _handle_non_existant_index(cls):
"""
Handle and check that some configuration index exists.
"""
try:
# We try to call the http code.
PyFunceble.INTERN["http_code"]
except KeyError:
# If it is not found.
# We initiate an empty http code.
PyFunceble.INTERN["http_code"] = "*" * 3
try:
# We try to call the referer.
PyFunceble.INTERN["referer"]
except KeyError:
# If it is not found.
# We initate an `Unknown` referer.
PyFunceble.INTERN["referer"] = "Unknown"
|
def _handle_non_existant_index(cls):
"""
Handle and check that some configuration index exists.
"""
try:
# We try to call the http code.
PyFunceble.INTERN["http_code"]
except KeyError:
# If it is not found.
# We initiate an empty http code.
PyFunceble.INTERN["http_code"] = "*" * 3
try:
# We try to call the referer.
PyFunceble.INTERN["referer"]
except KeyError:
# If it is not found.
# We initate an `Unknown` referer.
PyFunceble.INTERN["referer"] = "Unknown"
|
[
"Handle",
"and",
"check",
"that",
"some",
"configuration",
"index",
"exists",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L130-L151
|
[
"def",
"_handle_non_existant_index",
"(",
"cls",
")",
":",
"try",
":",
"# We try to call the http code.",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
"except",
"KeyError",
":",
"# If it is not found.",
"# We initiate an empty http code.",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
"=",
"\"*\"",
"*",
"3",
"try",
":",
"# We try to call the referer.",
"PyFunceble",
".",
"INTERN",
"[",
"\"referer\"",
"]",
"except",
"KeyError",
":",
"# If it is not found.",
"# We initate an `Unknown` referer.",
"PyFunceble",
".",
"INTERN",
"[",
"\"referer\"",
"]",
"=",
"\"Unknown\""
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Generate._analytic_host_file_directory
|
Return the analytic directory to write depending of the matched
status.
|
PyFunceble/generate.py
|
def _analytic_host_file_directory(self):
"""
Return the analytic directory to write depending of the matched
status.
"""
# We construct the path to the analytic directory.
output_dir = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["analytic"]["directories"]["parent"]
)
if self.domain_status.lower() in PyFunceble.STATUS["list"]["potentially_up"]:
# The status is in the list of analytic up status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"][
"potentially_up"
]
elif (
self.domain_status.lower() in PyFunceble.STATUS["list"]["potentially_down"]
):
# The status is in the list of analytic down status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"][
"potentially_down"
]
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["suspicious"]:
# The status is in the list of analytic suspicious status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"]["suspicious"]
else:
# The status is not in the list of analytic down or up status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"]["up"]
return output_dir
|
def _analytic_host_file_directory(self):
"""
Return the analytic directory to write depending of the matched
status.
"""
# We construct the path to the analytic directory.
output_dir = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["analytic"]["directories"]["parent"]
)
if self.domain_status.lower() in PyFunceble.STATUS["list"]["potentially_up"]:
# The status is in the list of analytic up status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"][
"potentially_up"
]
elif (
self.domain_status.lower() in PyFunceble.STATUS["list"]["potentially_down"]
):
# The status is in the list of analytic down status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"][
"potentially_down"
]
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["suspicious"]:
# The status is in the list of analytic suspicious status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"]["suspicious"]
else:
# The status is not in the list of analytic down or up status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"]["up"]
return output_dir
|
[
"Return",
"the",
"analytic",
"directory",
"to",
"write",
"depending",
"of",
"the",
"matched",
"status",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L153-L192
|
[
"def",
"_analytic_host_file_directory",
"(",
"self",
")",
":",
"# We construct the path to the analytic directory.",
"output_dir",
"=",
"(",
"self",
".",
"output_parent_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
")",
"if",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"potentially_up\"",
"]",
":",
"# The status is in the list of analytic up status.",
"# We complete the output directory.",
"output_dir",
"+=",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"potentially_up\"",
"]",
"elif",
"(",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"potentially_down\"",
"]",
")",
":",
"# The status is in the list of analytic down status.",
"# We complete the output directory.",
"output_dir",
"+=",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"potentially_down\"",
"]",
"elif",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"suspicious\"",
"]",
":",
"# The status is in the list of analytic suspicious status.",
"# We complete the output directory.",
"output_dir",
"+=",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"suspicious\"",
"]",
"else",
":",
"# The status is not in the list of analytic down or up status.",
"# We complete the output directory.",
"output_dir",
"+=",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"up\"",
"]",
"return",
"output_dir"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Generate.info_files
|
Generate the hosts file, the plain list and the splitted lists.
|
PyFunceble/generate.py
|
def info_files(self): # pylint: disable=inconsistent-return-statements
"""
Generate the hosts file, the plain list and the splitted lists.
"""
if self._do_not_produce_file():
# We do not have to produce file.
# We return false.
return False
if (
"file_to_test" in PyFunceble.INTERN
and PyFunceble.INTERN["file_to_test"]
and (
PyFunceble.CONFIGURATION["generate_hosts"]
or PyFunceble.CONFIGURATION["plain_list_domain"]
or PyFunceble.CONFIGURATION["generate_json"]
)
):
# * We are not testing as an imported module.
# and
# * The hosts file generation is activated.
# or
# * The plain list generation is activated.
# We initiate a variable which whill save the splited testination.
splited_destination = ""
# We initiate the list of all analytic related statuses.
http_list = []
http_list.extend(PyFunceble.STATUS["list"]["potentially_up"])
http_list.extend(PyFunceble.STATUS["list"]["potentially_down"])
http_list.extend(PyFunceble.STATUS["list"]["http_active"])
http_list.extend(PyFunceble.STATUS["list"]["suspicious"])
# We partially initiate the path to the hosts file.
output_hosts = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["hosts"]["directory"]
+ "%s"
+ directory_separator
+ PyFunceble.OUTPUTS["hosts"]["filename"]
)
# We partially initiate the path to the plain list file.
output_domains = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["domains"]["directory"]
+ "%s"
+ directory_separator
+ PyFunceble.OUTPUTS["domains"]["filename"]
)
# We partially intiate the path to the json list file.
output_json = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["json"]["directory"]
+ "%s"
+ directory_separator
+ PyFunceble.OUTPUTS["json"]["filename"]
)
if self.domain_status.lower() in PyFunceble.STATUS["list"]["up"]:
# The status is in the list of up list.
# We complete the path to the hosts file.
hosts_destination = output_hosts % PyFunceble.STATUS["official"]["up"]
# We complete the path to the plain list file.
plain_destination = output_domains % PyFunceble.STATUS["official"]["up"]
# We complete the path to the json list file.
json_destination = output_json % PyFunceble.STATUS["official"]["up"]
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["valid"]:
# The status is in the list of valid list.
# We complete the path to the hosts file.
hosts_destination = (
output_hosts % PyFunceble.STATUS["official"]["valid"]
)
# We complete the path to the plain list file.
plain_destination = (
output_domains % PyFunceble.STATUS["official"]["valid"]
)
# We complete the path to the json list file.
json_destination = output_json % PyFunceble.STATUS["official"]["valid"]
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["down"]:
# The status is in the list of down list.
# We complete the path to the hosts file.
hosts_destination = output_hosts % PyFunceble.STATUS["official"]["down"]
# We complete the path to the plain list file.
plain_destination = (
output_domains % PyFunceble.STATUS["official"]["down"]
)
# We complete the path to the json list file.
json_destination = output_json % PyFunceble.STATUS["official"]["down"]
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["invalid"]:
# The status is in the list of invalid list.
# We complete the path to the hosts file.
hosts_destination = (
output_hosts % PyFunceble.STATUS["official"]["invalid"]
)
# We complete the path to the plain list file.
plain_destination = (
output_domains % PyFunceble.STATUS["official"]["invalid"]
)
# We complete the path to the json list file.
json_destination = (
output_json % PyFunceble.STATUS["official"]["invalid"]
)
elif self.domain_status.lower() in http_list:
# The status is in the list of analytic status.
# We construct the path to the analytic directory.
output_dir = self._analytic_host_file_directory()
if not output_dir.endswith(directory_separator):
# The output directory does not ends with the directory separator.
# We append the directory separator at the end of the output directory.
output_dir += directory_separator
# We initiate the hosts file path.
hosts_destination = output_dir + PyFunceble.OUTPUTS["hosts"]["filename"]
# We initiate the plain list file path.
plain_destination = (
output_dir + PyFunceble.OUTPUTS["domains"]["filename"]
)
# We complete the path to the json list file.
json_destination = output_dir + PyFunceble.OUTPUTS["json"]["filename"]
# We initiate the path to the http code file.
# Note: We generate the http code file so that
# we can have each domain in a file which is the
# extracted http code.
splited_destination = output_dir + str(PyFunceble.INTERN["http_code"])
if PyFunceble.CONFIGURATION["generate_hosts"]:
# The hosts file generation is activated.
# We generate/append the currently tested element in its
# final location. (hosts file format)
# We print on screen and on file.
Prints(
[PyFunceble.CONFIGURATION["custom_ip"], self.tested],
"FullHosts",
hosts_destination,
).data()
if PyFunceble.CONFIGURATION["plain_list_domain"]:
# The plain list generation is activated.
# We generate/append the currently tested element in its
# final location. (the plain list format)
# We print on file.
Prints([self.tested], "PlainDomain", plain_destination).data()
if PyFunceble.CONFIGURATION["split"] and splited_destination:
# The splited list generation is activated.
# We generate/append the currently tested element in its
# final location. (the split list format)
# We print on file.
Prints([self.tested], "PlainDomain", splited_destination).data()
if PyFunceble.CONFIGURATION["generate_json"]:
# The jsaon list generation is activated.
# We generate/append the currently tested element in its
# final location. (the json format)
# We print on file.
Prints([self.tested], "JSON", json_destination).data()
|
def info_files(self): # pylint: disable=inconsistent-return-statements
"""
Generate the hosts file, the plain list and the splitted lists.
"""
if self._do_not_produce_file():
# We do not have to produce file.
# We return false.
return False
if (
"file_to_test" in PyFunceble.INTERN
and PyFunceble.INTERN["file_to_test"]
and (
PyFunceble.CONFIGURATION["generate_hosts"]
or PyFunceble.CONFIGURATION["plain_list_domain"]
or PyFunceble.CONFIGURATION["generate_json"]
)
):
# * We are not testing as an imported module.
# and
# * The hosts file generation is activated.
# or
# * The plain list generation is activated.
# We initiate a variable which whill save the splited testination.
splited_destination = ""
# We initiate the list of all analytic related statuses.
http_list = []
http_list.extend(PyFunceble.STATUS["list"]["potentially_up"])
http_list.extend(PyFunceble.STATUS["list"]["potentially_down"])
http_list.extend(PyFunceble.STATUS["list"]["http_active"])
http_list.extend(PyFunceble.STATUS["list"]["suspicious"])
# We partially initiate the path to the hosts file.
output_hosts = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["hosts"]["directory"]
+ "%s"
+ directory_separator
+ PyFunceble.OUTPUTS["hosts"]["filename"]
)
# We partially initiate the path to the plain list file.
output_domains = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["domains"]["directory"]
+ "%s"
+ directory_separator
+ PyFunceble.OUTPUTS["domains"]["filename"]
)
# We partially intiate the path to the json list file.
output_json = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["json"]["directory"]
+ "%s"
+ directory_separator
+ PyFunceble.OUTPUTS["json"]["filename"]
)
if self.domain_status.lower() in PyFunceble.STATUS["list"]["up"]:
# The status is in the list of up list.
# We complete the path to the hosts file.
hosts_destination = output_hosts % PyFunceble.STATUS["official"]["up"]
# We complete the path to the plain list file.
plain_destination = output_domains % PyFunceble.STATUS["official"]["up"]
# We complete the path to the json list file.
json_destination = output_json % PyFunceble.STATUS["official"]["up"]
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["valid"]:
# The status is in the list of valid list.
# We complete the path to the hosts file.
hosts_destination = (
output_hosts % PyFunceble.STATUS["official"]["valid"]
)
# We complete the path to the plain list file.
plain_destination = (
output_domains % PyFunceble.STATUS["official"]["valid"]
)
# We complete the path to the json list file.
json_destination = output_json % PyFunceble.STATUS["official"]["valid"]
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["down"]:
# The status is in the list of down list.
# We complete the path to the hosts file.
hosts_destination = output_hosts % PyFunceble.STATUS["official"]["down"]
# We complete the path to the plain list file.
plain_destination = (
output_domains % PyFunceble.STATUS["official"]["down"]
)
# We complete the path to the json list file.
json_destination = output_json % PyFunceble.STATUS["official"]["down"]
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["invalid"]:
# The status is in the list of invalid list.
# We complete the path to the hosts file.
hosts_destination = (
output_hosts % PyFunceble.STATUS["official"]["invalid"]
)
# We complete the path to the plain list file.
plain_destination = (
output_domains % PyFunceble.STATUS["official"]["invalid"]
)
# We complete the path to the json list file.
json_destination = (
output_json % PyFunceble.STATUS["official"]["invalid"]
)
elif self.domain_status.lower() in http_list:
# The status is in the list of analytic status.
# We construct the path to the analytic directory.
output_dir = self._analytic_host_file_directory()
if not output_dir.endswith(directory_separator):
# The output directory does not ends with the directory separator.
# We append the directory separator at the end of the output directory.
output_dir += directory_separator
# We initiate the hosts file path.
hosts_destination = output_dir + PyFunceble.OUTPUTS["hosts"]["filename"]
# We initiate the plain list file path.
plain_destination = (
output_dir + PyFunceble.OUTPUTS["domains"]["filename"]
)
# We complete the path to the json list file.
json_destination = output_dir + PyFunceble.OUTPUTS["json"]["filename"]
# We initiate the path to the http code file.
# Note: We generate the http code file so that
# we can have each domain in a file which is the
# extracted http code.
splited_destination = output_dir + str(PyFunceble.INTERN["http_code"])
if PyFunceble.CONFIGURATION["generate_hosts"]:
# The hosts file generation is activated.
# We generate/append the currently tested element in its
# final location. (hosts file format)
# We print on screen and on file.
Prints(
[PyFunceble.CONFIGURATION["custom_ip"], self.tested],
"FullHosts",
hosts_destination,
).data()
if PyFunceble.CONFIGURATION["plain_list_domain"]:
# The plain list generation is activated.
# We generate/append the currently tested element in its
# final location. (the plain list format)
# We print on file.
Prints([self.tested], "PlainDomain", plain_destination).data()
if PyFunceble.CONFIGURATION["split"] and splited_destination:
# The splited list generation is activated.
# We generate/append the currently tested element in its
# final location. (the split list format)
# We print on file.
Prints([self.tested], "PlainDomain", splited_destination).data()
if PyFunceble.CONFIGURATION["generate_json"]:
# The jsaon list generation is activated.
# We generate/append the currently tested element in its
# final location. (the json format)
# We print on file.
Prints([self.tested], "JSON", json_destination).data()
|
[
"Generate",
"the",
"hosts",
"file",
"the",
"plain",
"list",
"and",
"the",
"splitted",
"lists",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L194-L376
|
[
"def",
"info_files",
"(",
"self",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"if",
"self",
".",
"_do_not_produce_file",
"(",
")",
":",
"# We do not have to produce file.",
"# We return false.",
"return",
"False",
"if",
"(",
"\"file_to_test\"",
"in",
"PyFunceble",
".",
"INTERN",
"and",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
"and",
"(",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"generate_hosts\"",
"]",
"or",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"plain_list_domain\"",
"]",
"or",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"generate_json\"",
"]",
")",
")",
":",
"# * We are not testing as an imported module.",
"# and",
"# * The hosts file generation is activated.",
"# or",
"# * The plain list generation is activated.",
"# We initiate a variable which whill save the splited testination.",
"splited_destination",
"=",
"\"\"",
"# We initiate the list of all analytic related statuses.",
"http_list",
"=",
"[",
"]",
"http_list",
".",
"extend",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"potentially_up\"",
"]",
")",
"http_list",
".",
"extend",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"potentially_down\"",
"]",
")",
"http_list",
".",
"extend",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"http_active\"",
"]",
")",
"http_list",
".",
"extend",
"(",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"suspicious\"",
"]",
")",
"# We partially initiate the path to the hosts file.",
"output_hosts",
"=",
"(",
"self",
".",
"output_parent_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"hosts\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"\"%s\"",
"+",
"directory_separator",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"hosts\"",
"]",
"[",
"\"filename\"",
"]",
")",
"# We partially initiate the path to the plain list file.",
"output_domains",
"=",
"(",
"self",
".",
"output_parent_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"domains\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"\"%s\"",
"+",
"directory_separator",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"domains\"",
"]",
"[",
"\"filename\"",
"]",
")",
"# We partially intiate the path to the json list file.",
"output_json",
"=",
"(",
"self",
".",
"output_parent_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"json\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"\"%s\"",
"+",
"directory_separator",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"json\"",
"]",
"[",
"\"filename\"",
"]",
")",
"if",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"up\"",
"]",
":",
"# The status is in the list of up list.",
"# We complete the path to the hosts file.",
"hosts_destination",
"=",
"output_hosts",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
"# We complete the path to the plain list file.",
"plain_destination",
"=",
"output_domains",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
"# We complete the path to the json list file.",
"json_destination",
"=",
"output_json",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
"elif",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"valid\"",
"]",
":",
"# The status is in the list of valid list.",
"# We complete the path to the hosts file.",
"hosts_destination",
"=",
"(",
"output_hosts",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"valid\"",
"]",
")",
"# We complete the path to the plain list file.",
"plain_destination",
"=",
"(",
"output_domains",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"valid\"",
"]",
")",
"# We complete the path to the json list file.",
"json_destination",
"=",
"output_json",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"valid\"",
"]",
"elif",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"down\"",
"]",
":",
"# The status is in the list of down list.",
"# We complete the path to the hosts file.",
"hosts_destination",
"=",
"output_hosts",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"down\"",
"]",
"# We complete the path to the plain list file.",
"plain_destination",
"=",
"(",
"output_domains",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"down\"",
"]",
")",
"# We complete the path to the json list file.",
"json_destination",
"=",
"output_json",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"down\"",
"]",
"elif",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"invalid\"",
"]",
":",
"# The status is in the list of invalid list.",
"# We complete the path to the hosts file.",
"hosts_destination",
"=",
"(",
"output_hosts",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"invalid\"",
"]",
")",
"# We complete the path to the plain list file.",
"plain_destination",
"=",
"(",
"output_domains",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"invalid\"",
"]",
")",
"# We complete the path to the json list file.",
"json_destination",
"=",
"(",
"output_json",
"%",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"invalid\"",
"]",
")",
"elif",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"http_list",
":",
"# The status is in the list of analytic status.",
"# We construct the path to the analytic directory.",
"output_dir",
"=",
"self",
".",
"_analytic_host_file_directory",
"(",
")",
"if",
"not",
"output_dir",
".",
"endswith",
"(",
"directory_separator",
")",
":",
"# The output directory does not ends with the directory separator.",
"# We append the directory separator at the end of the output directory.",
"output_dir",
"+=",
"directory_separator",
"# We initiate the hosts file path.",
"hosts_destination",
"=",
"output_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"hosts\"",
"]",
"[",
"\"filename\"",
"]",
"# We initiate the plain list file path.",
"plain_destination",
"=",
"(",
"output_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"domains\"",
"]",
"[",
"\"filename\"",
"]",
")",
"# We complete the path to the json list file.",
"json_destination",
"=",
"output_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"json\"",
"]",
"[",
"\"filename\"",
"]",
"# We initiate the path to the http code file.",
"# Note: We generate the http code file so that",
"# we can have each domain in a file which is the",
"# extracted http code.",
"splited_destination",
"=",
"output_dir",
"+",
"str",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"generate_hosts\"",
"]",
":",
"# The hosts file generation is activated.",
"# We generate/append the currently tested element in its",
"# final location. (hosts file format)",
"# We print on screen and on file.",
"Prints",
"(",
"[",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"custom_ip\"",
"]",
",",
"self",
".",
"tested",
"]",
",",
"\"FullHosts\"",
",",
"hosts_destination",
",",
")",
".",
"data",
"(",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"plain_list_domain\"",
"]",
":",
"# The plain list generation is activated.",
"# We generate/append the currently tested element in its",
"# final location. (the plain list format)",
"# We print on file.",
"Prints",
"(",
"[",
"self",
".",
"tested",
"]",
",",
"\"PlainDomain\"",
",",
"plain_destination",
")",
".",
"data",
"(",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"split\"",
"]",
"and",
"splited_destination",
":",
"# The splited list generation is activated.",
"# We generate/append the currently tested element in its",
"# final location. (the split list format)",
"# We print on file.",
"Prints",
"(",
"[",
"self",
".",
"tested",
"]",
",",
"\"PlainDomain\"",
",",
"splited_destination",
")",
".",
"data",
"(",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"generate_json\"",
"]",
":",
"# The jsaon list generation is activated.",
"# We generate/append the currently tested element in its",
"# final location. (the json format)",
"# We print on file.",
"Prints",
"(",
"[",
"self",
".",
"tested",
"]",
",",
"\"JSON\"",
",",
"json_destination",
")",
".",
"data",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Generate.unified_file
|
Generate unified file. Understand by that that we use an unified table
instead of a separate table for each status which could result into a
misunderstanding.
|
PyFunceble/generate.py
|
def unified_file(self):
"""
Generate unified file. Understand by that that we use an unified table
instead of a separate table for each status which could result into a
misunderstanding.
"""
if (
"file_to_test" in PyFunceble.INTERN
and PyFunceble.INTERN["file_to_test"]
and PyFunceble.CONFIGURATION["unified"]
):
# * We are not testing as an imported module.
# and
# * The unified file generation is activated.
# We construct the path of the unified file.
output = (
self.output_parent_dir + PyFunceble.OUTPUTS["default_files"]["results"]
)
if PyFunceble.CONFIGURATION["less"]:
# We have to print less information.
if PyFunceble.HTTP_CODE["active"]:
# The http status code request is activated.
# We construct what we have to print.
to_print = [
self.tested,
self.domain_status,
PyFunceble.INTERN["http_code"],
]
else:
# The http status code request is not activated.
# We construct what we have to print.
to_print = [self.tested, self.domain_status, self.source]
# And we print the informations on file.
Prints(to_print, "Less", output, True).data()
else:
# The unified file generation is not activated.
# We construct what we have to print.
to_print = [
self.tested,
self.domain_status,
self.expiration_date,
self.source,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
]
# And we print the information on file.
Prints(to_print, "Generic_File", output, True).data()
|
def unified_file(self):
"""
Generate unified file. Understand by that that we use an unified table
instead of a separate table for each status which could result into a
misunderstanding.
"""
if (
"file_to_test" in PyFunceble.INTERN
and PyFunceble.INTERN["file_to_test"]
and PyFunceble.CONFIGURATION["unified"]
):
# * We are not testing as an imported module.
# and
# * The unified file generation is activated.
# We construct the path of the unified file.
output = (
self.output_parent_dir + PyFunceble.OUTPUTS["default_files"]["results"]
)
if PyFunceble.CONFIGURATION["less"]:
# We have to print less information.
if PyFunceble.HTTP_CODE["active"]:
# The http status code request is activated.
# We construct what we have to print.
to_print = [
self.tested,
self.domain_status,
PyFunceble.INTERN["http_code"],
]
else:
# The http status code request is not activated.
# We construct what we have to print.
to_print = [self.tested, self.domain_status, self.source]
# And we print the informations on file.
Prints(to_print, "Less", output, True).data()
else:
# The unified file generation is not activated.
# We construct what we have to print.
to_print = [
self.tested,
self.domain_status,
self.expiration_date,
self.source,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
]
# And we print the information on file.
Prints(to_print, "Generic_File", output, True).data()
|
[
"Generate",
"unified",
"file",
".",
"Understand",
"by",
"that",
"that",
"we",
"use",
"an",
"unified",
"table",
"instead",
"of",
"a",
"separate",
"table",
"for",
"each",
"status",
"which",
"could",
"result",
"into",
"a",
"misunderstanding",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L378-L433
|
[
"def",
"unified_file",
"(",
"self",
")",
":",
"if",
"(",
"\"file_to_test\"",
"in",
"PyFunceble",
".",
"INTERN",
"and",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
"and",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"unified\"",
"]",
")",
":",
"# * We are not testing as an imported module.",
"# and",
"# * The unified file generation is activated.",
"# We construct the path of the unified file.",
"output",
"=",
"(",
"self",
".",
"output_parent_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"default_files\"",
"]",
"[",
"\"results\"",
"]",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"less\"",
"]",
":",
"# We have to print less information.",
"if",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"active\"",
"]",
":",
"# The http status code request is activated.",
"# We construct what we have to print.",
"to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"domain_status",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
",",
"]",
"else",
":",
"# The http status code request is not activated.",
"# We construct what we have to print.",
"to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"domain_status",
",",
"self",
".",
"source",
"]",
"# And we print the informations on file.",
"Prints",
"(",
"to_print",
",",
"\"Less\"",
",",
"output",
",",
"True",
")",
".",
"data",
"(",
")",
"else",
":",
"# The unified file generation is not activated.",
"# We construct what we have to print.",
"to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"domain_status",
",",
"self",
".",
"expiration_date",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
",",
"PyFunceble",
".",
"CURRENT_TIME",
",",
"]",
"# And we print the information on file.",
"Prints",
"(",
"to_print",
",",
"\"Generic_File\"",
",",
"output",
",",
"True",
")",
".",
"data",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Generate.analytic_file
|
Generate :code:`Analytic/*` files based on the given old and
new statuses.
:param new_status: The new status of the domain.
:type new_status: str
:param old_status: The old status of the domain.
:type old_status: str
|
PyFunceble/generate.py
|
def analytic_file(self, new_status, old_status=None):
"""
Generate :code:`Analytic/*` files based on the given old and
new statuses.
:param new_status: The new status of the domain.
:type new_status: str
:param old_status: The old status of the domain.
:type old_status: str
"""
if not old_status:
# The old status is not given.
# We set the old status as the one given globally.
old_status = self.domain_status
if "file_to_test" in PyFunceble.INTERN and PyFunceble.INTERN["file_to_test"]:
# We are not testing as an imported module.
# We partially construct the path to the file to write/print.
output = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["analytic"]["directories"]["parent"]
+ "%s%s"
)
if new_status.lower() in PyFunceble.STATUS["list"]["up"]:
# The new status is in the list of up status.
# We complete the output directory.
output = output % (
PyFunceble.OUTPUTS["analytic"]["directories"]["up"],
PyFunceble.OUTPUTS["analytic"]["filenames"]["up"],
)
# We generate the hosts file.
Generate("HTTP_Active").info_files()
elif new_status.lower() in PyFunceble.STATUS["list"]["potentially_up"]:
# The new status is in the list of down status.
# We complete the output directory.
output = output % (
PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_up"],
PyFunceble.OUTPUTS["analytic"]["filenames"]["potentially_up"],
)
# We generate the hosts file.
Generate("potentially_up").info_files()
elif new_status.lower() in PyFunceble.STATUS["list"]["suspicious"]:
# The new status is in the list of suspicious status.
# We complete the output directory.
output = output % (
PyFunceble.OUTPUTS["analytic"]["directories"]["suspicious"],
PyFunceble.OUTPUTS["analytic"]["filenames"]["suspicious"],
)
# We generate the hosts file.
Generate("suspicious").info_files()
else:
# The new status is in the list of up and down status.
# We complete the output directory.
output = output % (
PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_down"],
PyFunceble.OUTPUTS["analytic"]["filenames"]["potentially_down"],
)
# We generate the hosts files.
Generate("potentially_down").info_files()
# We print the information on file.
Prints(
[
self.tested,
old_status,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
],
"HTTP",
output,
True,
).data()
|
def analytic_file(self, new_status, old_status=None):
"""
Generate :code:`Analytic/*` files based on the given old and
new statuses.
:param new_status: The new status of the domain.
:type new_status: str
:param old_status: The old status of the domain.
:type old_status: str
"""
if not old_status:
# The old status is not given.
# We set the old status as the one given globally.
old_status = self.domain_status
if "file_to_test" in PyFunceble.INTERN and PyFunceble.INTERN["file_to_test"]:
# We are not testing as an imported module.
# We partially construct the path to the file to write/print.
output = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["analytic"]["directories"]["parent"]
+ "%s%s"
)
if new_status.lower() in PyFunceble.STATUS["list"]["up"]:
# The new status is in the list of up status.
# We complete the output directory.
output = output % (
PyFunceble.OUTPUTS["analytic"]["directories"]["up"],
PyFunceble.OUTPUTS["analytic"]["filenames"]["up"],
)
# We generate the hosts file.
Generate("HTTP_Active").info_files()
elif new_status.lower() in PyFunceble.STATUS["list"]["potentially_up"]:
# The new status is in the list of down status.
# We complete the output directory.
output = output % (
PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_up"],
PyFunceble.OUTPUTS["analytic"]["filenames"]["potentially_up"],
)
# We generate the hosts file.
Generate("potentially_up").info_files()
elif new_status.lower() in PyFunceble.STATUS["list"]["suspicious"]:
# The new status is in the list of suspicious status.
# We complete the output directory.
output = output % (
PyFunceble.OUTPUTS["analytic"]["directories"]["suspicious"],
PyFunceble.OUTPUTS["analytic"]["filenames"]["suspicious"],
)
# We generate the hosts file.
Generate("suspicious").info_files()
else:
# The new status is in the list of up and down status.
# We complete the output directory.
output = output % (
PyFunceble.OUTPUTS["analytic"]["directories"]["potentially_down"],
PyFunceble.OUTPUTS["analytic"]["filenames"]["potentially_down"],
)
# We generate the hosts files.
Generate("potentially_down").info_files()
# We print the information on file.
Prints(
[
self.tested,
old_status,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
],
"HTTP",
output,
True,
).data()
|
[
"Generate",
":",
"code",
":",
"Analytic",
"/",
"*",
"files",
"based",
"on",
"the",
"given",
"old",
"and",
"new",
"statuses",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L435-L519
|
[
"def",
"analytic_file",
"(",
"self",
",",
"new_status",
",",
"old_status",
"=",
"None",
")",
":",
"if",
"not",
"old_status",
":",
"# The old status is not given.",
"# We set the old status as the one given globally.",
"old_status",
"=",
"self",
".",
"domain_status",
"if",
"\"file_to_test\"",
"in",
"PyFunceble",
".",
"INTERN",
"and",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
":",
"# We are not testing as an imported module.",
"# We partially construct the path to the file to write/print.",
"output",
"=",
"(",
"self",
".",
"output_parent_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"parent\"",
"]",
"+",
"\"%s%s\"",
")",
"if",
"new_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"up\"",
"]",
":",
"# The new status is in the list of up status.",
"# We complete the output directory.",
"output",
"=",
"output",
"%",
"(",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"up\"",
"]",
",",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"filenames\"",
"]",
"[",
"\"up\"",
"]",
",",
")",
"# We generate the hosts file.",
"Generate",
"(",
"\"HTTP_Active\"",
")",
".",
"info_files",
"(",
")",
"elif",
"new_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"potentially_up\"",
"]",
":",
"# The new status is in the list of down status.",
"# We complete the output directory.",
"output",
"=",
"output",
"%",
"(",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"potentially_up\"",
"]",
",",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"filenames\"",
"]",
"[",
"\"potentially_up\"",
"]",
",",
")",
"# We generate the hosts file.",
"Generate",
"(",
"\"potentially_up\"",
")",
".",
"info_files",
"(",
")",
"elif",
"new_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"suspicious\"",
"]",
":",
"# The new status is in the list of suspicious status.",
"# We complete the output directory.",
"output",
"=",
"output",
"%",
"(",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"suspicious\"",
"]",
",",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"filenames\"",
"]",
"[",
"\"suspicious\"",
"]",
",",
")",
"# We generate the hosts file.",
"Generate",
"(",
"\"suspicious\"",
")",
".",
"info_files",
"(",
")",
"else",
":",
"# The new status is in the list of up and down status.",
"# We complete the output directory.",
"output",
"=",
"output",
"%",
"(",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"directories\"",
"]",
"[",
"\"potentially_down\"",
"]",
",",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"analytic\"",
"]",
"[",
"\"filenames\"",
"]",
"[",
"\"potentially_down\"",
"]",
",",
")",
"# We generate the hosts files.",
"Generate",
"(",
"\"potentially_down\"",
")",
".",
"info_files",
"(",
")",
"# We print the information on file.",
"Prints",
"(",
"[",
"self",
".",
"tested",
",",
"old_status",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
",",
"PyFunceble",
".",
"CURRENT_TIME",
",",
"]",
",",
"\"HTTP\"",
",",
"output",
",",
"True",
",",
")",
".",
"data",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Generate._prints_status_file
|
Logic behind the printing (in file) when generating status file.
|
PyFunceble/generate.py
|
def _prints_status_file(self): # pylint: disable=too-many-branches
"""
Logic behind the printing (in file) when generating status file.
"""
if PyFunceble.INTERN["file_to_test"]:
# We are testing a file.
output = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["splited"]["directory"]
+ self.domain_status
)
if PyFunceble.CONFIGURATION["less"]:
# We have to print less information.
# We print the information on file.
Prints(
[self.tested, self.domain_status, self.source], "Less", output, True
).data()
elif PyFunceble.CONFIGURATION["split"]:
# We have to split the information we print on file.
if self.domain_status.lower() in PyFunceble.STATUS["list"]["up"]:
# The status is in the list of up status.
if PyFunceble.HTTP_CODE["active"]:
# The http code extraction is activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.expiration_date,
self.source,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
]
else:
# The http code extraction is not activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.expiration_date,
self.source,
PyFunceble.CURRENT_TIME,
]
# We print the informations to print on file.
Prints(
data_to_print, PyFunceble.STATUS["official"]["up"], output, True
).data()
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["valid"]:
# The status is in the list of valid status.
# We initiate the data to print.
data_to_print = [self.tested, self.source, PyFunceble.CURRENT_TIME]
# We print the informations to print on file.
Prints(
data_to_print,
PyFunceble.STATUS["official"]["valid"],
output,
True,
).data()
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["down"]:
# The status is in the list of down status.
if PyFunceble.HTTP_CODE["active"]:
# The http statuc code extraction is activated.
# We initiate the data to print.
data_to_print = [
self.tested,
PyFunceble.INTERN["referer"],
self.domain_status,
self.source,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
]
else:
# The http status code extraction is not activated.
# We initate the data to print.
data_to_print = [
self.tested,
PyFunceble.INTERN["referer"],
self.domain_status,
self.source,
PyFunceble.CURRENT_TIME,
]
# We print the information on file.
Prints(
data_to_print,
PyFunceble.STATUS["official"]["down"],
output,
True,
).data()
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["invalid"]:
# The status is in the list of invalid status.
if PyFunceble.HTTP_CODE["active"]:
# The http status code extraction is activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.source,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
]
else:
# The http status code extraction is not activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.source,
PyFunceble.CURRENT_TIME,
]
# We print the information to print on file.
Prints(
data_to_print,
PyFunceble.STATUS["official"]["invalid"],
output,
True,
).data()
|
def _prints_status_file(self): # pylint: disable=too-many-branches
"""
Logic behind the printing (in file) when generating status file.
"""
if PyFunceble.INTERN["file_to_test"]:
# We are testing a file.
output = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["splited"]["directory"]
+ self.domain_status
)
if PyFunceble.CONFIGURATION["less"]:
# We have to print less information.
# We print the information on file.
Prints(
[self.tested, self.domain_status, self.source], "Less", output, True
).data()
elif PyFunceble.CONFIGURATION["split"]:
# We have to split the information we print on file.
if self.domain_status.lower() in PyFunceble.STATUS["list"]["up"]:
# The status is in the list of up status.
if PyFunceble.HTTP_CODE["active"]:
# The http code extraction is activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.expiration_date,
self.source,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
]
else:
# The http code extraction is not activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.expiration_date,
self.source,
PyFunceble.CURRENT_TIME,
]
# We print the informations to print on file.
Prints(
data_to_print, PyFunceble.STATUS["official"]["up"], output, True
).data()
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["valid"]:
# The status is in the list of valid status.
# We initiate the data to print.
data_to_print = [self.tested, self.source, PyFunceble.CURRENT_TIME]
# We print the informations to print on file.
Prints(
data_to_print,
PyFunceble.STATUS["official"]["valid"],
output,
True,
).data()
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["down"]:
# The status is in the list of down status.
if PyFunceble.HTTP_CODE["active"]:
# The http statuc code extraction is activated.
# We initiate the data to print.
data_to_print = [
self.tested,
PyFunceble.INTERN["referer"],
self.domain_status,
self.source,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
]
else:
# The http status code extraction is not activated.
# We initate the data to print.
data_to_print = [
self.tested,
PyFunceble.INTERN["referer"],
self.domain_status,
self.source,
PyFunceble.CURRENT_TIME,
]
# We print the information on file.
Prints(
data_to_print,
PyFunceble.STATUS["official"]["down"],
output,
True,
).data()
elif self.domain_status.lower() in PyFunceble.STATUS["list"]["invalid"]:
# The status is in the list of invalid status.
if PyFunceble.HTTP_CODE["active"]:
# The http status code extraction is activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.source,
PyFunceble.INTERN["http_code"],
PyFunceble.CURRENT_TIME,
]
else:
# The http status code extraction is not activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.source,
PyFunceble.CURRENT_TIME,
]
# We print the information to print on file.
Prints(
data_to_print,
PyFunceble.STATUS["official"]["invalid"],
output,
True,
).data()
|
[
"Logic",
"behind",
"the",
"printing",
"(",
"in",
"file",
")",
"when",
"generating",
"status",
"file",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L521-L650
|
[
"def",
"_prints_status_file",
"(",
"self",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
":",
"# We are testing a file.",
"output",
"=",
"(",
"self",
".",
"output_parent_dir",
"+",
"PyFunceble",
".",
"OUTPUTS",
"[",
"\"splited\"",
"]",
"[",
"\"directory\"",
"]",
"+",
"self",
".",
"domain_status",
")",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"less\"",
"]",
":",
"# We have to print less information.",
"# We print the information on file.",
"Prints",
"(",
"[",
"self",
".",
"tested",
",",
"self",
".",
"domain_status",
",",
"self",
".",
"source",
"]",
",",
"\"Less\"",
",",
"output",
",",
"True",
")",
".",
"data",
"(",
")",
"elif",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"split\"",
"]",
":",
"# We have to split the information we print on file.",
"if",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"up\"",
"]",
":",
"# The status is in the list of up status.",
"if",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"active\"",
"]",
":",
"# The http code extraction is activated.",
"# We initiate the data to print.",
"data_to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"expiration_date",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
",",
"PyFunceble",
".",
"CURRENT_TIME",
",",
"]",
"else",
":",
"# The http code extraction is not activated.",
"# We initiate the data to print.",
"data_to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"expiration_date",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"CURRENT_TIME",
",",
"]",
"# We print the informations to print on file.",
"Prints",
"(",
"data_to_print",
",",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"up\"",
"]",
",",
"output",
",",
"True",
")",
".",
"data",
"(",
")",
"elif",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"valid\"",
"]",
":",
"# The status is in the list of valid status.",
"# We initiate the data to print.",
"data_to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"CURRENT_TIME",
"]",
"# We print the informations to print on file.",
"Prints",
"(",
"data_to_print",
",",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"valid\"",
"]",
",",
"output",
",",
"True",
",",
")",
".",
"data",
"(",
")",
"elif",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"down\"",
"]",
":",
"# The status is in the list of down status.",
"if",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"active\"",
"]",
":",
"# The http statuc code extraction is activated.",
"# We initiate the data to print.",
"data_to_print",
"=",
"[",
"self",
".",
"tested",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"referer\"",
"]",
",",
"self",
".",
"domain_status",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
",",
"PyFunceble",
".",
"CURRENT_TIME",
",",
"]",
"else",
":",
"# The http status code extraction is not activated.",
"# We initate the data to print.",
"data_to_print",
"=",
"[",
"self",
".",
"tested",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"referer\"",
"]",
",",
"self",
".",
"domain_status",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"CURRENT_TIME",
",",
"]",
"# We print the information on file.",
"Prints",
"(",
"data_to_print",
",",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"down\"",
"]",
",",
"output",
",",
"True",
",",
")",
".",
"data",
"(",
")",
"elif",
"self",
".",
"domain_status",
".",
"lower",
"(",
")",
"in",
"PyFunceble",
".",
"STATUS",
"[",
"\"list\"",
"]",
"[",
"\"invalid\"",
"]",
":",
"# The status is in the list of invalid status.",
"if",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"active\"",
"]",
":",
"# The http status code extraction is activated.",
"# We initiate the data to print.",
"data_to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
",",
"PyFunceble",
".",
"CURRENT_TIME",
",",
"]",
"else",
":",
"# The http status code extraction is not activated.",
"# We initiate the data to print.",
"data_to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"CURRENT_TIME",
",",
"]",
"# We print the information to print on file.",
"Prints",
"(",
"data_to_print",
",",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"invalid\"",
"]",
",",
"output",
",",
"True",
",",
")",
".",
"data",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Generate._prints_status_screen
|
Logic behind the printing (on screen) when generating status file.
|
PyFunceble/generate.py
|
def _prints_status_screen(self):
"""
Logic behind the printing (on screen) when generating status file.
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
if PyFunceble.CONFIGURATION["less"]:
# We have to print less information.
# We initiate the data to print.
to_print = [
self.tested,
self.domain_status,
PyFunceble.INTERN["http_code"],
]
if not PyFunceble.HTTP_CODE["active"]:
# The http status code is not activated.
# We replace the last element to print with
# the source.
to_print[-1] = self.source
# We print the informations on screen.
Prints(to_print, "Less").data()
else:
# We have to print all informations on screen.
if PyFunceble.HTTP_CODE["active"]:
# The http status code extraction is activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.domain_status,
self.expiration_date,
self.source,
PyFunceble.INTERN["http_code"],
]
else:
# The http status code extraction is not activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.domain_status,
self.expiration_date,
self.source,
PyFunceble.CURRENT_TIME,
]
# We print the information on screen.
Prints(data_to_print, "Generic").data()
|
def _prints_status_screen(self):
"""
Logic behind the printing (on screen) when generating status file.
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
if PyFunceble.CONFIGURATION["less"]:
# We have to print less information.
# We initiate the data to print.
to_print = [
self.tested,
self.domain_status,
PyFunceble.INTERN["http_code"],
]
if not PyFunceble.HTTP_CODE["active"]:
# The http status code is not activated.
# We replace the last element to print with
# the source.
to_print[-1] = self.source
# We print the informations on screen.
Prints(to_print, "Less").data()
else:
# We have to print all informations on screen.
if PyFunceble.HTTP_CODE["active"]:
# The http status code extraction is activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.domain_status,
self.expiration_date,
self.source,
PyFunceble.INTERN["http_code"],
]
else:
# The http status code extraction is not activated.
# We initiate the data to print.
data_to_print = [
self.tested,
self.domain_status,
self.expiration_date,
self.source,
PyFunceble.CURRENT_TIME,
]
# We print the information on screen.
Prints(data_to_print, "Generic").data()
|
[
"Logic",
"behind",
"the",
"printing",
"(",
"on",
"screen",
")",
"when",
"generating",
"status",
"file",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L652-L706
|
[
"def",
"_prints_status_screen",
"(",
"self",
")",
":",
"if",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"quiet\"",
"]",
":",
"# The quiet mode is not activated.",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"less\"",
"]",
":",
"# We have to print less information.",
"# We initiate the data to print.",
"to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"domain_status",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
",",
"]",
"if",
"not",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"active\"",
"]",
":",
"# The http status code is not activated.",
"# We replace the last element to print with",
"# the source.",
"to_print",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"source",
"# We print the informations on screen.",
"Prints",
"(",
"to_print",
",",
"\"Less\"",
")",
".",
"data",
"(",
")",
"else",
":",
"# We have to print all informations on screen.",
"if",
"PyFunceble",
".",
"HTTP_CODE",
"[",
"\"active\"",
"]",
":",
"# The http status code extraction is activated.",
"# We initiate the data to print.",
"data_to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"domain_status",
",",
"self",
".",
"expiration_date",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"INTERN",
"[",
"\"http_code\"",
"]",
",",
"]",
"else",
":",
"# The http status code extraction is not activated.",
"# We initiate the data to print.",
"data_to_print",
"=",
"[",
"self",
".",
"tested",
",",
"self",
".",
"domain_status",
",",
"self",
".",
"expiration_date",
",",
"self",
".",
"source",
",",
"PyFunceble",
".",
"CURRENT_TIME",
",",
"]",
"# We print the information on screen.",
"Prints",
"(",
"data_to_print",
",",
"\"Generic\"",
")",
".",
"data",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Generate.status_file
|
Generate a file according to the domain status.
|
PyFunceble/generate.py
|
def status_file(self): # pylint: disable=inconsistent-return-statements
"""
Generate a file according to the domain status.
"""
if "file_to_test" in PyFunceble.INTERN:
# We are not testing as an imported module.
# We generate the hosts file.
Generate(self.domain_status, self.source, self.expiration_date).info_files()
# We are testing a file content.
# We increase the percentage count.
Percentage(self.domain_status).count()
# We print on screen if needed.
self._prints_status_screen()
if self._do_not_produce_file():
return None
if (
not PyFunceble.CONFIGURATION["no_files"]
and PyFunceble.CONFIGURATION["split"]
):
# * The file non-generation of file is globaly deactivated.
# and
# * We have to split the outputs.
# We print or generate the files.
self._prints_status_file()
else:
# * The file non-generation of file is globaly activated.
# or
# * We do not have to split the outputs.
# We print or generate the unified files.
self.unified_file()
|
def status_file(self): # pylint: disable=inconsistent-return-statements
"""
Generate a file according to the domain status.
"""
if "file_to_test" in PyFunceble.INTERN:
# We are not testing as an imported module.
# We generate the hosts file.
Generate(self.domain_status, self.source, self.expiration_date).info_files()
# We are testing a file content.
# We increase the percentage count.
Percentage(self.domain_status).count()
# We print on screen if needed.
self._prints_status_screen()
if self._do_not_produce_file():
return None
if (
not PyFunceble.CONFIGURATION["no_files"]
and PyFunceble.CONFIGURATION["split"]
):
# * The file non-generation of file is globaly deactivated.
# and
# * We have to split the outputs.
# We print or generate the files.
self._prints_status_file()
else:
# * The file non-generation of file is globaly activated.
# or
# * We do not have to split the outputs.
# We print or generate the unified files.
self.unified_file()
|
[
"Generate",
"a",
"file",
"according",
"to",
"the",
"domain",
"status",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L708-L746
|
[
"def",
"status_file",
"(",
"self",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"if",
"\"file_to_test\"",
"in",
"PyFunceble",
".",
"INTERN",
":",
"# We are not testing as an imported module.",
"# We generate the hosts file.",
"Generate",
"(",
"self",
".",
"domain_status",
",",
"self",
".",
"source",
",",
"self",
".",
"expiration_date",
")",
".",
"info_files",
"(",
")",
"# We are testing a file content.",
"# We increase the percentage count.",
"Percentage",
"(",
"self",
".",
"domain_status",
")",
".",
"count",
"(",
")",
"# We print on screen if needed.",
"self",
".",
"_prints_status_screen",
"(",
")",
"if",
"self",
".",
"_do_not_produce_file",
"(",
")",
":",
"return",
"None",
"if",
"(",
"not",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"no_files\"",
"]",
"and",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"split\"",
"]",
")",
":",
"# * The file non-generation of file is globaly deactivated.",
"# and",
"# * We have to split the outputs.",
"# We print or generate the files.",
"self",
".",
"_prints_status_file",
"(",
")",
"else",
":",
"# * The file non-generation of file is globaly activated.",
"# or",
"# * We do not have to split the outputs.",
"# We print or generate the unified files.",
"self",
".",
"unified_file",
"(",
")"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
test
|
Generate._do_not_produce_file
|
Check if we are allowed to produce a file based from the given
information.
:return:
The state of the production.
True: We do not produce file.
False: We do produce file.
:rtype: bool
|
PyFunceble/generate.py
|
def _do_not_produce_file(self):
"""
Check if we are allowed to produce a file based from the given
information.
:return:
The state of the production.
True: We do not produce file.
False: We do produce file.
:rtype: bool
"""
if (
Inactive().is_present()
and self.domain_status
in [
PyFunceble.STATUS["official"]["down"],
PyFunceble.STATUS["official"]["invalid"],
]
and PyFunceble.INTERN["to_test"]
not in PyFunceble.INTERN["extracted_list_to_test"]
):
return True
return False
|
def _do_not_produce_file(self):
"""
Check if we are allowed to produce a file based from the given
information.
:return:
The state of the production.
True: We do not produce file.
False: We do produce file.
:rtype: bool
"""
if (
Inactive().is_present()
and self.domain_status
in [
PyFunceble.STATUS["official"]["down"],
PyFunceble.STATUS["official"]["invalid"],
]
and PyFunceble.INTERN["to_test"]
not in PyFunceble.INTERN["extracted_list_to_test"]
):
return True
return False
|
[
"Check",
"if",
"we",
"are",
"allowed",
"to",
"produce",
"a",
"file",
"based",
"from",
"the",
"given",
"information",
"."
] |
funilrys/PyFunceble
|
python
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/generate.py#L748-L771
|
[
"def",
"_do_not_produce_file",
"(",
"self",
")",
":",
"if",
"(",
"Inactive",
"(",
")",
".",
"is_present",
"(",
")",
"and",
"self",
".",
"domain_status",
"in",
"[",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"down\"",
"]",
",",
"PyFunceble",
".",
"STATUS",
"[",
"\"official\"",
"]",
"[",
"\"invalid\"",
"]",
",",
"]",
"and",
"PyFunceble",
".",
"INTERN",
"[",
"\"to_test\"",
"]",
"not",
"in",
"PyFunceble",
".",
"INTERN",
"[",
"\"extracted_list_to_test\"",
"]",
")",
":",
"return",
"True",
"return",
"False"
] |
cdf69cbde120199171f7158e1c33635753e6e2f5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.