Skip to content

Commit f81a500

Browse files
committed
Added cascade settings loading from ~/.maigret/settings.json and ./settings.json
1 parent 4f5222d commit f81a500

File tree

8 files changed

+80
-39
lines changed

8 files changed

+80
-39
lines changed

.gitignore

+4-1
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,7 @@ src/
3030
.coverage
3131
dist/
3232
htmlcov/
33-
/test_*
33+
/test_*
34+
35+
# Maigret files
36+
settings.json

Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ lint:
1313
flake8 --count --select=E9,F63,F7,F82 --show-source --statistics ${LINT_FILES} maigret.py
1414

1515
@echo 'warning'
16-
flake8 --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics --ignore=E731,W503 ${LINT_FILES} maigret.py
16+
flake8 --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics --ignore=E731,W503,E501 ${LINT_FILES} maigret.py
1717

1818
@echo 'mypy'
1919
mypy ${LINT_FILES}

maigret/maigret.py

+20-16
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import platform
99
from argparse import ArgumentParser, RawDescriptionHelpFormatter
1010
from typing import List, Tuple
11+
import os.path as path
1112

1213
from socid_extractor import extract, parse
1314

@@ -111,7 +112,7 @@ def extract_ids_from_results(results: QueryResultWrapper, db: MaigretDatabase) -
111112
return ids_results
112113

113114

114-
def setup_arguments_parser():
115+
def setup_arguments_parser(settings: Settings):
115116
from aiohttp import __version__ as aiohttp_version
116117
from requests import __version__ as requests_version
117118
from socid_extractor import __version__ as socid_version
@@ -159,7 +160,7 @@ def setup_arguments_parser():
159160
action="store",
160161
type=int,
161162
metavar='RETRIES',
162-
default=1,
163+
default=settings.retries_count,
163164
help="Attempts to restart temporarily failed requests.",
164165
)
165166
parser.add_argument(
@@ -453,25 +454,34 @@ def setup_arguments_parser():
453454

454455

455456
async def main():
456-
arg_parser = setup_arguments_parser()
457-
args = arg_parser.parse_args()
458-
459457
# Logging
460458
log_level = logging.ERROR
461459
logging.basicConfig(
462460
format='[%(filename)s:%(lineno)d] %(levelname)-3s %(asctime)s %(message)s',
463461
datefmt='%H:%M:%S',
464462
level=log_level,
465463
)
464+
logger = logging.getLogger('maigret')
465+
logger.setLevel(log_level)
466466

467+
# Load settings
468+
settings = Settings()
469+
settings_loaded, err = settings.load()
470+
471+
if not settings_loaded:
472+
logger.error(err)
473+
sys.exit(3)
474+
475+
arg_parser = setup_arguments_parser(settings)
476+
args = arg_parser.parse_args()
477+
478+
# Re-set loggging level based on args
467479
if args.debug:
468480
log_level = logging.DEBUG
469481
elif args.info:
470482
log_level = logging.INFO
471483
elif args.verbose:
472484
log_level = logging.WARNING
473-
474-
logger = logging.getLogger('maigret')
475485
logger.setLevel(log_level)
476486

477487
# Usernames initial list
@@ -497,15 +507,9 @@ async def main():
497507
if args.tags:
498508
args.tags = list(set(str(args.tags).split(',')))
499509

500-
settings = Settings(
501-
os.path.join(
502-
os.path.dirname(os.path.realpath(__file__)), "resources/settings.json"
503-
)
504-
)
505-
506510
if args.db_file is None:
507-
args.db_file = os.path.join(
508-
os.path.dirname(os.path.realpath(__file__)), "resources/data.json"
511+
args.db_file = path.join(
512+
path.dirname(path.realpath(__file__)), "resources/data.json"
509513
)
510514

511515
if args.top_sites == 0 or args.all_sites:
@@ -568,7 +572,7 @@ async def main():
568572
os.makedirs(args.folderoutput, exist_ok=True)
569573

570574
# Define one report filename template
571-
report_filepath_tpl = os.path.join(args.folderoutput, 'report_{username}{postfix}')
575+
report_filepath_tpl = path.join(args.folderoutput, 'report_{username}{postfix}')
572576

573577
if usernames == {}:
574578
# magic params to exit after init

maigret/resources/data.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -13078,7 +13078,7 @@
1307813078
"us"
1307913079
],
1308013080
"headers": {
13081-
"authorization": "Bearer BQB8QPkkvz_PhWGy4sSY4ijssYjumEHJgJJBFu3VX2Sm4XIoT9jp0eFZrYL3TayY4QZGHmMiz3BCPLcAth4"
13081+
"authorization": "Bearer BQCJhizJUIWlnA6-hlMrHeTsb0jCi067H73LzQ1bWk8Iz1tQ6DIE6WyvbJ2x1bapJhZ_MLNiQbTp-dCxz7g"
1308213082
},
1308313083
"errors": {
1308413084
"Spotify is currently not available in your country.": "Access denied in your country, use proxy/vpn"
@@ -14913,7 +14913,7 @@
1491314913
"video"
1491414914
],
1491514915
"headers": {
14916-
"Authorization": "jwt eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MzU2OTI0NjAsInVzZXJfaWQiOm51bGwsImFwcF9pZCI6NTg0NzksInNjb3BlcyI6InB1YmxpYyIsInRlYW1fdXNlcl9pZCI6bnVsbH0.KZHo96wUe5__rTqZQqAWiJKPKOy2-sjyxRjhOuuhyEc"
14916+
"Authorization": "jwt eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MzYxMDg1NjAsInVzZXJfaWQiOm51bGwsImFwcF9pZCI6NTg0NzksInNjb3BlcyI6InB1YmxpYyIsInRlYW1fdXNlcl9pZCI6bnVsbH0.kqIzH7O99ov6IrTfeQoA7NNaSZe_7czUgrwKxHnBs3o"
1491714917
},
1491814918
"activation": {
1491914919
"url": "https://vimeo.com/_rv/viewer",

maigret/resources/settings.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,7 @@
1313
"e-mail"
1414
],
1515
"supposed_usernames": [
16-
"alex", "god", "admin", "red", "blue", "john"]
16+
"alex", "god", "admin", "red", "blue", "john"
17+
],
18+
"retries_count": 1
1719
}

maigret/settings.py

+45-16
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,57 @@
1+
import os
2+
import os.path as path
13
import json
24

5+
SETTINGS_FILES_PATHS = [
6+
path.join(path.dirname(path.realpath(__file__)), "resources/settings.json"),
7+
'~/.maigret/settings.json',
8+
path.join(os.getcwd(), 'settings.json'),
9+
]
10+
311

412
class Settings:
13+
# main maigret setting
14+
retries_count: int
15+
16+
# submit mode settings
517
presence_strings: list
618
supposed_usernames: list
719

8-
def __init__(self, filename):
9-
data = {}
20+
def __init__(self):
21+
pass
22+
23+
def load(self, paths=None):
24+
was_inited = False
25+
26+
if not paths:
27+
paths = SETTINGS_FILES_PATHS
1028

11-
try:
12-
with open(filename, "r", encoding="utf-8") as file:
13-
try:
29+
for filename in paths:
30+
data = {}
31+
32+
try:
33+
with open(filename, "r", encoding="utf-8") as file:
1434
data = json.load(file)
15-
except Exception as error:
16-
raise ValueError(
17-
f"Problem with parsing json contents of "
18-
f"settings file '{filename}': {str(error)}."
19-
)
20-
except FileNotFoundError as error:
21-
raise FileNotFoundError(
22-
f"Problem while attempting to access settings file '{filename}'."
23-
) from error
24-
25-
self.__dict__.update(data)
35+
except FileNotFoundError:
36+
# treast as a normal situation
37+
pass
38+
except Exception as error:
39+
return False, ValueError(
40+
f"Problem with parsing json contents of "
41+
f"settings file '{filename}': {str(error)}."
42+
)
43+
44+
self.__dict__.update(data)
45+
import logging
46+
47+
logging.error(data)
48+
if data:
49+
was_inited = True
50+
51+
return (
52+
was_inited,
53+
f'None of the default settings files found: {", ".join(paths)}',
54+
)
2655

2756
@property
2857
def json(self):

tests/conftest.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@
77

88
from maigret.sites import MaigretDatabase
99
from maigret.maigret import setup_arguments_parser
10+
from maigret.settings import Settings
1011

1112

1213
CUR_PATH = os.path.dirname(os.path.realpath(__file__))
1314
JSON_FILE = os.path.join(CUR_PATH, '../maigret/resources/data.json')
15+
SETTINGS_FILE = os.path.join(CUR_PATH, '../maigret/resources/settings.json')
1416
TEST_JSON_FILE = os.path.join(CUR_PATH, 'db.json')
1517
LOCAL_TEST_JSON_FILE = os.path.join(CUR_PATH, 'local.json')
1618
empty_mark = Mark('', (), {})
@@ -59,7 +61,9 @@ def reports_autoclean():
5961

6062
@pytest.fixture(scope='session')
6163
def argparser():
62-
return setup_arguments_parser()
64+
settings = Settings()
65+
settings.load([SETTINGS_FILE])
66+
return setup_arguments_parser(settings)
6367

6468

6569
@pytest.fixture(scope="session")

tests/test_sites.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Maigret Database test functions"""
22
from maigret.sites import MaigretDatabase, MaigretSite
3-
from maigret.utils import URLMatcher
43

54
EXAMPLE_DB = {
65
'engines': {

0 commit comments

Comments
 (0)