gnunet-svn
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[GNUnet-SVN] [taler-bank] branch master updated (1669a8b -> 8ea1eda)


From: gnunet
Subject: [GNUnet-SVN] [taler-bank] branch master updated (1669a8b -> 8ea1eda)
Date: Wed, 22 Nov 2017 13:08:02 +0100

This is an automated email from the git hooks/post-receive script.

marcello pushed a change to branch master
in repository bank.

    from 1669a8b  readme
     new 4f80d3a  linting
     new 8ea1eda  linting talerconfig

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 talerbank/app/checks.py                            |   2 +-
 talerbank/app/management/commands/dump_talerdb.py  |  11 +-
 talerbank/app/management/commands/helpers.py       |  24 ++++
 .../app/management/commands/provide_accounts.py    |  26 ++--
 talerbank/app/models.py                            |   2 +-
 talerbank/app/schemas.py                           |   5 +-
 talerbank/app/tests.py                             |  58 ++++----
 talerbank/app/tests_alt.py                         |  21 +--
 talerbank/app/views.py                             |  25 ++--
 talerbank/talerconfig.py                           | 158 +++++++++++----------
 10 files changed, 171 insertions(+), 161 deletions(-)
 create mode 100644 talerbank/app/management/commands/helpers.py

diff --git a/talerbank/app/checks.py b/talerbank/app/checks.py
index 3b505bb..7865868 100644
--- a/talerbank/app/checks.py
+++ b/talerbank/app/checks.py
@@ -2,7 +2,7 @@ from django.core.checks import register, Warning
 from django.db.utils import OperationalError
 
 @register()
-def example_check(app_configs, **kwargs):
+def example_check():
     errors = []
     try:
         from .models import User
diff --git a/talerbank/app/management/commands/dump_talerdb.py 
b/talerbank/app/management/commands/dump_talerdb.py
index 5685da1..ba81444 100644
--- a/talerbank/app/management/commands/dump_talerdb.py
+++ b/talerbank/app/management/commands/dump_talerdb.py
@@ -19,6 +19,7 @@ import logging
 from django.core.management.base import BaseCommand
 from django.db.utils import OperationalError, ProgrammingError
 from ...models import BankAccount, BankTransaction
+from .helpers import hard_db_error_log
 
 LOGGER = logging.getLogger(__name__)
 
@@ -31,10 +32,7 @@ def dump_accounts():
         for acc in accounts:
             print(acc.user.username + " has account number " + 
str(acc.account_no))
     except (OperationalError, ProgrammingError):
-        LOGGER.error("likely causes: non existent DB or unmigrated project\n"
-                     "(try 'taler-bank-manage django migrate' in the latter 
case)",
-                     stack_info=False,
-                     exc_info=True)
+        hard_db_error_log()
         sys.exit(1)
 
 
@@ -51,10 +49,7 @@ def dump_history():
             msg.append(item.subject)
             print(''.join(msg))
     except (OperationalError, ProgrammingError):
-        LOGGER.error("likely causes: non existent DB or unmigrated project\n"
-                     "(try 'taler-bank-manage django migrate' in the latter 
case)",
-                     stack_info=False,
-                     exc_info=True)
+        hard_db_error_log()
         sys.exit(1)
 
 
diff --git a/talerbank/app/management/commands/helpers.py 
b/talerbank/app/management/commands/helpers.py
new file mode 100644
index 0000000..62137e9
--- /dev/null
+++ b/talerbank/app/management/commands/helpers.py
@@ -0,0 +1,24 @@
+#  This file is part of TALER
+#  (C) 2017 Taler Systems SA
+#
+#  TALER is free software; you can redistribute it and/or modify it under the
+#  terms of the GNU General Public License as published by the Free Software
+#  Foundation; either version 3, or (at your option) any later version.
+#
+#  TALER is distributed in the hope that it will be useful, but WITHOUT ANY
+#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
FOR
+#  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License along with
+#  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
+#
+#  @author Marcello Stanisci
+
+import logging
+LOGGER = logging.getLogger(__name__)
+
+def hard_db_error_log():
+    LOGGER.error("likely causes: non existent DB or unmigrated project\n"
+                 "(try 'taler-bank-manage django migrate' in the latter case)",
+                 stack_info=False,
+                 exc_info=True)
diff --git a/talerbank/app/management/commands/provide_accounts.py 
b/talerbank/app/management/commands/provide_accounts.py
index de5067d..c719296 100644
--- a/talerbank/app/management/commands/provide_accounts.py
+++ b/talerbank/app/management/commands/provide_accounts.py
@@ -18,12 +18,13 @@
 import sys
 import logging
 from django.contrib.auth.models import User
-from django.db.utils import ProgrammingError, DataError, OperationalError
+from django.db.utils import ProgrammingError, OperationalError
 from django.core.management.base import BaseCommand
-from ...models import BankAccount
 from django.conf import settings
+from ...models import BankAccount
+from .helpers import hard_db_error_log
 
-logger = logging.getLogger(__name__)
+LOGGER = logging.getLogger(__name__)
 
 
 def demo_accounts():
@@ -31,25 +32,21 @@ def demo_accounts():
         try:
             User.objects.get(username=name)
         except User.DoesNotExist:
-            u = User.objects.create_user(username=name, password='x')
-            b = BankAccount(user=u, is_public=True)
-            b.save()
-            logger.info("Creating account '%s' with number %s", name, 
b.account_no)
+            BankAccount(user=User.objects.create_user(username=name, 
password='x'),
+                        is_public=True).save()
+            LOGGER.info("Creating account for '%s'", name)
 
 
 def ensure_account(name):
-    logger.info("ensuring account '{}'".format(name))
+    LOGGER.info("ensuring account '%s'", name)
     user = None
     try:
         user = User.objects.get(username=name)
     except (OperationalError, ProgrammingError):
-        logger.error("likely causes: non existent DB or unmigrated project\n"
-                     "(try 'taler-bank-manage django migrate' in the latter 
case)",
-                     stack_info=False,
-                     exc_info=True)
+        hard_db_error_log()
         sys.exit(1)
     except User.DoesNotExist:
-        logger.info("Creating *user* account '{}'".format(name))
+        LOGGER.info("Creating *user* account '%s'", name)
         user = User.objects.create_user(username=name, password='x')
 
     try:
@@ -58,7 +55,8 @@ def ensure_account(name):
     except BankAccount.DoesNotExist:
         acc = BankAccount(user=user, is_public=True)
         acc.save()
-        logger.info("Creating *bank* account number '{}' for user 
'{}'".format(acc.account_no, name))
+        LOGGER.info("Creating *bank* account number \
+                    '%s' for user '%s'", acc.account_no, name)
 
 
 def basic_accounts():
diff --git a/talerbank/app/models.py b/talerbank/app/models.py
index d254cc4..fb86f41 100644
--- a/talerbank/app/models.py
+++ b/talerbank/app/models.py
@@ -42,7 +42,7 @@ class AmountField(models.Field):
             return "%s:0.0" % settings.TALER_CURRENCY
         return value.stringify(settings.TALER_DIGITS)
 
-    def from_db_value(self, value, expression, connection, context):
+    def from_db_value(self, value, *args):
         if None is value:
             return amount.Amount.parse(settings.TALER_CURRENCY)
         return amount.Amount.parse(value)
diff --git a/talerbank/app/schemas.py b/talerbank/app/schemas.py
index 73ce80c..b823595 100644
--- a/talerbank/app/schemas.py
+++ b/talerbank/app/schemas.py
@@ -19,9 +19,9 @@
 definitions of JSON schemas for validating data
 """
 
-from django.conf import settings
-import validictory
 import json
+import validictory
+from django.conf import settings
 
 AMOUNT_SCHEMA = {
     "type": "object",
@@ -125,4 +125,3 @@ def validate_incoming_request(incoming_request):
 
 def check_withdraw_session(session):
     validictory.validate(session, WITHDRAW_SESSION_SCHEMA)
-
diff --git a/talerbank/app/tests.py b/talerbank/app/tests.py
index 7e1ea26..5387fff 100644
--- a/talerbank/app/tests.py
+++ b/talerbank/app/tests.py
@@ -19,7 +19,7 @@ from django.test import TestCase, Client
 from django.core.urlresolvers import reverse
 from django.conf import settings
 from django.contrib.auth.models import User
-from mock import patch, MagicMock, Mock
+from mock import patch, MagicMock
 from .models import BankAccount, BankTransaction
 from . import urls
 from .views import wire_transfer
@@ -43,7 +43,7 @@ class WithdrawTestCase(TestCase):
                                           password=""),
             account_no=99)
         exchange_bankaccount.save()
-    
+
     @patch('hashlib.new') # Need to patch update() and hexdigest() methods.
     @patch('requests.post')
     @patch('time.time')
@@ -58,17 +58,17 @@ class WithdrawTestCase(TestCase):
             }
         }'''
         params = {
-          "amount_value": "0",
-          "amount_fraction": "1",
-          "amount_currency": settings.TALER_CURRENCY,
-          "exchange": "http://exchange.example/";,
-          "reserve_pub": "UVZ789",
-          "wire_details": wire_details.replace("\n", "").replace(" ", "")
+            "amount_value": "0",
+            "amount_fraction": "1",
+            "amount_currency": settings.TALER_CURRENCY,
+            "exchange": "http://exchange.example/";,
+            "reserve_pub": "UVZ789",
+            "wire_details": wire_details.replace("\n", "").replace(" ", "")
         }
         client.login(username="test_user", password="test_password")
 
-        response = client.get(reverse("pin-question", urlconf=urls),
-                              params)
+        client.get(reverse("pin-question", urlconf=urls),
+                   params)
         # We mock hashlib in order to fake the CAPTCHA.
         hasher = MagicMock()
         hasher.hexdigest = MagicMock()
@@ -78,21 +78,21 @@ class WithdrawTestCase(TestCase):
         post.status_code = 200
         mocked_post.return_value = post
         mocked_time.return_value = 0
-        response = client.post(reverse("pin-verify", urlconf=urls),
-                               {"pin_1": "0"})
+        client.post(reverse("pin-verify", urlconf=urls),
+                    {"pin_1": "0"})
         expected_json = {
             "reserve_pub": "UVZ789",
             "execution_date": "/Date(0)/",
             "sender_account_details": {
                 "type": "test",
                 "bank_uri": "http://testserver/";,
-                "account_number": 100 
+                "account_number": 100
                 },
             "transfer_details": {"timestamp": 0},
             "amount": {
                 "value": 0,
                 "fraction": 1,
-                "currency": settings.TALER_CURRENCY} 
+                "currency": settings.TALER_CURRENCY}
         }
         
mocked_post.assert_called_with("http://exchange.example/admin/add/incoming";,
                                        json=expected_json)
@@ -103,12 +103,10 @@ class WithdrawTestCase(TestCase):
 class InternalWireTransferTestCase(TestCase):
 
     def setUp(self):
-        gm = BankAccount(user=User.objects.create_user(username='give_money',
-                                                       password="gm"))
-        gm.save()
-        tm = BankAccount(user=User.objects.create_user(username='take_money'),
-                         account_no=88)
-        tm.save()
+        BankAccount(user=User.objects.create_user(username='give_money',
+                                                  password="gm")).save()
+        BankAccount(user=User.objects.create_user(username='take_money'),
+                    account_no=88).save()
 
     def test_internal_wire_transfer(self):
         client = Client()
@@ -117,8 +115,8 @@ class InternalWireTransferTestCase(TestCase):
                                {"amount": 3.0,
                                 "counterpart": 88,
                                 "subject": "charity"})
-        tm = BankAccount.objects.get(account_no=88)
-        self.assertEqual(0, Amount.cmp(Amount(settings.TALER_CURRENCY, 3), 
tm.amount))
+        self.assertEqual(0, Amount.cmp(Amount(settings.TALER_CURRENCY, 3),
+                                       
BankAccount.objects.get(account_no=88).amount))
         self.assertEqual(200, response.status_code)
 
     def tearDown(self):
@@ -203,14 +201,8 @@ class AmountTestCase(TestCase):
     def test_cmp_diff_curr(self):
         amount1 = Amount("X", 1)
         amount2 = Amount("Y", 2)
-        try:
+        with self.assertRaises(CurrencyMismatch):
             Amount.cmp(amount1, amount2)
-        except CurrencyMismatch:
-            self.assertTrue(True)
-            return
-        # Should never get here
-        self.assertTrue(False)
-
 
 class AddIncomingTestCase(TestCase):
     """Test money transfer's API"""
@@ -312,11 +304,11 @@ class HistoryTestCase(TestCase):
         for ctx in (HistoryContext(expected_resp={"status": 200},
                                    delta="4"),
                     HistoryContext(expected_resp={
-                                       "field": "row_id", "value": 6,
-                                       "status": 200}, delta="+1", start="5",),
+                        "field": "row_id", "value": 6,
+                        "status": 200}, delta="+1", start="5",),
                     HistoryContext(expected_resp={
-                                       "field": "wt_subject", "value": "h",
-                                       "status": 200}, delta="-1"),
+                        "field": "wt_subject", "value": "h",
+                        "status": 200}, delta="-1"),
                     HistoryContext(expected_resp={"status": 204},
                                    delta="1", start="11"),
                     HistoryContext(expected_resp={"status": 204},
diff --git a/talerbank/app/tests_alt.py b/talerbank/app/tests_alt.py
index 7d37586..33627ec 100644
--- a/talerbank/app/tests_alt.py
+++ b/talerbank/app/tests_alt.py
@@ -17,24 +17,17 @@ from django.test import TestCase
 from django.conf import settings
 from .amount import Amount, BadFormatAmount
 
-class BadDatabaseStringTestCase(TestCase):
-    def test_baddbstring(self):
-        pass
-
 class BadMaxDebtOptionTestCase(TestCase):
     def test_badmaxdebtoption(self):
-        try:
+        with self.assertRaises(BadFormatAmount):
             Amount.parse(settings.TALER_MAX_DEBT)
-        except BadFormatAmount:
-            self.assertTrue(True)
-            return
-        try:
             Amount.parse(settings.TALER_MAX_DEBT_BANK)
-        except BadFormatAmount:
-            self.assertTrue(True)
-            return
-        # Force to have at least one bad amount in config
-        self.assertTrue(False)
+
+# Note, the two following classes are used to check a faulty
+# _config_ file, so they are not supposed to have any logic.
+class BadDatabaseStringTestCase(TestCase):
+    def test_baddbstring(self):
+        pass
 
 class NoCurrencyOptionTestCase(TestCase):
     pass
diff --git a/talerbank/app/views.py b/talerbank/app/views.py
index 2723efa..40dcc01 100644
--- a/talerbank/app/views.py
+++ b/talerbank/app/views.py
@@ -26,8 +26,7 @@ import requests
 import django.contrib.auth
 import django.contrib.auth.views
 import django.contrib.auth.forms
-from decimal import Decimal
-from django.db import transaction, models
+from django.db import transaction
 from django import forms
 from django.conf import settings
 from django.contrib.auth.decorators import login_required
@@ -38,8 +37,7 @@ from django.contrib.auth.models import User
 from django.db.models import Q
 from simplemathcaptcha.fields import MathCaptchaField, MathCaptchaWidget
 from django.http import (JsonResponse, HttpResponse,
-                         HttpResponseBadRequest as HRBR,
-                         HttpResponseServerError)
+                         HttpResponseBadRequest as HRBR)
 from django.shortcuts import render, redirect
 from validictory.validator import (RequiredFieldValidationError as RFVE,
                                    FieldValidationError as FVE)
@@ -104,13 +102,15 @@ def profile_page(request):
     info_bar = None
     if request.method == "POST":
         wtf = WTForm(request.POST)
-        if wtf.is_valid(): 
+        if wtf.is_valid():
             amount_parts = (settings.TALER_CURRENCY,
                             wtf.cleaned_data.get("amount") + 0.0)
             try:
                 wire_transfer(Amount.parse("%s:%s" % amount_parts),
-                              BankAccount.objects.get(user=request.user),
-                              
BankAccount.objects.get(account_no=wtf.cleaned_data.get("counterpart")),
+                              BankAccount.objects.get(
+                                  user=request.user),
+                              BankAccount.objects.get(
+                                  
account_no=wtf.cleaned_data.get("counterpart")),
                               wtf.cleaned_data.get("subject"))
                 request.session["just_wire_transferred"] = True
             except BankAccount.DoesNotExist:
@@ -140,14 +140,14 @@ def profile_page(request):
         precision=settings.TALER_DIGITS,
         currency=user_account.amount.currency,
         account_no=user_account.account_no,
-        wt_form = wtf,
+        wt_form=wtf,
         history=history,
         just_withdrawn=just_withdrawn,
         just_registered=just_registered,
         no_initial_bonus=no_initial_bonus,
         just_wire_transferred=just_wire_transferred,
         wire_transfer_error=wire_transfer_error,
-        info_bar = info_bar
+        info_bar=info_bar
     )
     if settings.TALER_SUGGESTED_EXCHANGE:
         context["suggested_exchange"] = settings.TALER_SUGGESTED_EXCHANGE
@@ -204,10 +204,12 @@ def pin_tan_verify(request):
     hasher = hashlib.new("sha1")
     hasher.update(settings.SECRET_KEY.encode("utf-8"))
     # pin_0 is the answer given by the user
-    hasher.update(request.POST.get("pin_0" ,"").encode("utf-8"))
+    hasher.update(request.POST.get("pin_0", "").encode("utf-8"))
     hashed_attempt = hasher.hexdigest()
     if hashed_attempt != request.POST.get("pin_1"):
-        LOGGER.warning("Wrong CAPTCHA answer: %s vs %s" % 
(type(hashed_attempt), type(request.POST.get("pin_1"))))
+        LOGGER.warning("Wrong CAPTCHA answer: %s vs %s",
+                       type(hashed_attempt),
+                       type(request.POST.get("pin_1")))
         request.session["captcha_failed"] = True
         return redirect(request.POST.get("question_url", "profile"))
     # Check the session is a "pin tan" one
@@ -363,7 +365,6 @@ def serve_history(request, user_account):
     delta = request.GET.get("delta")
     if not delta:
         return HRBR()
-    #FIXME: make the '+' sign optional
     parsed_delta = re.search(r"([\+-])?([0-9]+)", delta)
     try:
         parsed_delta.group(0)
diff --git a/talerbank/talerconfig.py b/talerbank/talerconfig.py
index d72e15f..e27caeb 100644
--- a/talerbank/talerconfig.py
+++ b/talerbank/talerconfig.py
@@ -28,15 +28,15 @@ import weakref
 import sys
 import re
 
-logger = logging.getLogger(__name__)
+LOGGER = logging.getLogger(__name__)
 
 __all__ = ["TalerConfig"]
 
-taler_datadir = None
+TALER_DATADIR = None
 try:
     # not clear if this is a good idea ...
-    from talerpaths import taler_datadir as t
-    taler_datadir = t
+    from talerpaths import TALER_DATADIR as t
+    TALER_DATADIR = t
 except ImportError:
     pass
 
@@ -47,7 +47,7 @@ class ExpansionSyntaxError(Exception):
     pass
 
 
-def expand(s, getter):
+def expand(var, getter):
     """
     Do shell-style parameter expansion.
     Supported syntax:
@@ -58,18 +58,18 @@ def expand(s, getter):
     pos = 0
     result = ""
     while pos != -1:
-        start = s.find("$", pos)
+        start = var.find("$", pos)
         if start == -1:
             break
-        if s[start:].startswith("${"):
+        if var[start:].startswith("${"):
             balance = 1
             end = start + 2
-            while balance > 0 and end < len(s):
-                balance += {"{": 1, "}": -1}.get(s[end], 0)
+            while balance > 0 and end < len(var):
+                balance += {"{": 1, "}": -1}.get(var[end], 0)
                 end += 1
             if balance != 0:
                 raise ExpansionSyntaxError("unbalanced parentheses")
-            piece = s[start+2:end-1]
+            piece = var[start+2:end-1]
             if piece.find(":-") > 0:
                 varname, alt = piece.split(":-", 1)
                 replace = getter(varname)
@@ -79,20 +79,20 @@ def expand(s, getter):
                 varname = piece
                 replace = getter(varname)
                 if replace is None:
-                    replace = s[start:end]
+                    replace = var[start:end]
         else:
             end = start + 2
-            while end < len(s) and s[start+1:end+1].isalnum():
+            while end < len(var) and var[start+1:end+1].isalnum():
                 end += 1
-            varname = s[start+1:end]
+            varname = var[start+1:end]
             replace = getter(varname)
             if replace is None:
-                replace = s[start:end]
+                replace = var[start:end]
         result = result + replace
         pos = end
 
 
-    return result + s[pos:]
+    return result + var[pos:]
 
 
 class OptionDict(collections.defaultdict):
@@ -101,9 +101,9 @@ class OptionDict(collections.defaultdict):
         self.section_name = section_name
         super().__init__()
     def __missing__(self, key):
-        e = Entry(self.config(), self.section_name, key)
-        self[key] = e
-        return e
+        entry = Entry(self.config(), self.section_name, key)
+        self[key] = entry
+        return entry
     def __getitem__(self, slice):
         return super().__getitem__(slice.lower())
     def __setitem__(self, slice, value):
@@ -114,9 +114,9 @@ class SectionDict(collections.defaultdict):
     def __init__(self):
         super().__init__()
     def __missing__(self, key):
-        v = OptionDict(self, key)
-        self[key] = v
-        return v
+        value = OptionDict(self, key)
+        self[key] = value
+        return value
     def __getitem__(self, slice):
         return super().__getitem__(slice.lower())
     def __setitem__(self, slice, value):
@@ -133,47 +133,51 @@ class Entry:
         self.config = weakref.ref(config)
 
     def __repr__(self):
-        return "<Entry section=%s, option=%s, value=%s>" % (self.section, 
self.option, repr(self.value),)
+        return "<Entry section=%s, option=%s, value=%s>" \
+               % (self.section, self.option, repr(self.value),)
 
     def __str__(self):
         return self.value
 
     def value_string(self, default=None, required=False, warn=False):
         if required and self.value is None:
-            raise ConfigurationError("Missing required option '%s' in section 
'%s'" % (self.option.upper(), self.section.upper()))
+            raise ConfigurationError("Missing required option '%s' in section 
'%s'" \
+                                     % (self.option.upper(), 
self.section.upper()))
         if self.value is None:
             if warn:
                 if default is not None:
-                    logger.warn("Configuration is missing option '%s' in 
section '%s', falling back to '%s'",
-                            self.option, self.section, default)
+                    LOGGER.warn("Configuration is missing option '%s' in 
section '%s',\
+                                falling back to '%s'", self.option, 
self.section, default)
                 else:
-                    logger.warn("Configuration ** is missing option '%s' in 
section '%s'", self.option.upper(), self.section.upper())
+                    LOGGER.warn("Configuration ** is missing option '%s' in 
section '%s'",
+                                self.option.upper(), self.section.upper())
             return default
         return self.value
 
     def value_int(self, default=None, required=False, warn=False):
-        v = self.value_string(default, warn, required)
-        if v is None:
+        value = self.value_string(default, warn, required)
+        if value is None:
             return None
         try:
-            return int(v)
+            return int(value)
         except ValueError:
-            raise ConfigurationError("Expected number for option '%s' in 
section '%s'" % (self.option.upper(), self.section.upper()))
+            raise ConfigurationError("Expected number for option '%s' in 
section '%s'" \
+                                     % (self.option.upper(), 
self.section.upper()))
 
     def _getsubst(self, key):
-        x = self.config()["paths"][key].value
-        if x is not None:
-            return x
-        x = os.environ.get(key)
-        if x is not None:
-            return x
+        value = self.config()["paths"][key].value
+        if value is not None:
+            return value
+        value = os.environ.get(key)
+        if value is not None:
+            return value
         return None
 
     def value_filename(self, default=None, required=False, warn=False):
-        v = self.value_string(default, warn, required)
-        if v is None:
+        value = self.value_string(default, warn, required)
+        if value is None:
             return None
-        return expand(v, lambda x: self._getsubst(x))
+        return expand(value, lambda x: self._getsubst(x))
 
     def location(self):
         if self.filename is None or self.lineno is None:
@@ -202,7 +206,7 @@ class TalerConfig:
             if xdg:
                 filename = os.path.join(xdg, "taler.conf")
             else:
-                filename = os.path.expanduser("~/.config/taler.conf") # <- 
what if you aren't there!?
+                filename = os.path.expanduser("~/.config/taler.conf")
         if load_defaults:
             cfg.load_defaults()
         cfg.load_file(filename)
@@ -229,10 +233,10 @@ class TalerConfig:
                 prefix = tmp[0]
             self.load_dir(os.path.join(prefix, "share/taler/config.d"))
             return
-        if taler_datadir:
-            self.load_dir(os.path.join(taler_datadir, "share/taler/config.d"))
+        if TALER_DATADIR:
+            self.load_dir(os.path.join(TALER_DATADIR, "share/taler/config.d"))
             return
-        logger.warn("no base directory found")
+        LOGGER.warn("no base directory found")
 
     @staticmethod
     def from_env(*args, **kwargs):
@@ -247,7 +251,7 @@ class TalerConfig:
         try:
             files = os.listdir(dirname)
         except FileNotFoundError:
-            logger.warn("can't read config directory '%s'", dirname)
+            LOGGER.warn("can't read config directory '%s'", dirname)
             return
         for file in files:
             if not file.endswith(".conf"):
@@ -263,7 +267,7 @@ class TalerConfig:
                 for line in file:
                     lineno += 1
                     line = line.strip()
-                    if len(line) == 0:
+                    if line == "":
                         # empty line
                         continue
                     if line.startswith("#"):
@@ -271,36 +275,37 @@ class TalerConfig:
                         continue
                     if line.startswith("["):
                         if not line.endswith("]"):
-                            logger.error("invalid section header in line %s: 
%s", lineno, repr(line))
+                            LOGGER.error("invalid section header in line %s: 
%s",
+                                         lineno, repr(line))
                         section_name = line.strip("[]").strip().strip('"')
                         current_section = section_name
                         continue
                     if current_section is None:
-                        logger.error("option outside of section in line %s: 
%s", lineno, repr(line))
+                        LOGGER.error("option outside of section in line %s: 
%s", lineno, repr(line))
                         continue
-                    kv = line.split("=", 1)
-                    if len(kv) != 2:
-                        logger.error("invalid option in line %s: %s", lineno, 
repr(line))
-                    key = kv[0].strip()
-                    value = kv[1].strip()
+                    pair = line.split("=", 1)
+                    if len(pair) != 2:
+                        LOGGER.error("invalid option in line %s: %s", lineno, 
repr(line))
+                    key = pair[0].strip()
+                    value = pair[1].strip()
                     if value.startswith('"'):
                         value = value[1:]
                         if not value.endswith('"'):
-                            logger.error("mismatched quotes in line %s: %s", 
lineno, repr(line))
+                            LOGGER.error("mismatched quotes in line %s: %s", 
lineno, repr(line))
                         else:
                             value = value[:-1]
-                    e = Entry(self.sections, current_section, key, value, 
filename, lineno)
-                    sections[current_section][key] = e
+                    entry = Entry(self.sections, current_section, key, value, 
filename, lineno)
+                    sections[current_section][key] = entry
         except FileNotFoundError:
-            logger.error("Configuration file (%s) not found", filename)
+            LOGGER.error("Configuration file (%s) not found", filename)
             sys.exit(3)
 
 
     def dump(self):
         for section_name, section in self.sections.items():
             print("[%s]" % (section.section_name,))
-            for option_name, e in section.items():
-                print("%s = %s # %s" % (e.option, e.value, e.location()))
+            for option_name, entry in section.items():
+                print("%s = %s # %s" % (entry.option, entry.value, 
entry.location()))
 
     def __getitem__(self, slice):
         if isinstance(slice, str):
@@ -309,24 +314,27 @@ class TalerConfig:
 
 
 if __name__ == "__main__":
-    import sys
     import argparse
 
-    parser = argparse.ArgumentParser()
-    parser.add_argument("--section", "-s", dest="section", default=None, 
metavar="SECTION")
-    parser.add_argument("--option", "-o", dest="option", default=None, 
metavar="OPTION")
-    parser.add_argument("--config", "-c", dest="config", default=None, 
metavar="FILE")
-    parser.add_argument("--filename", "-f", dest="expand_filename", 
default=False, action='store_true')
-    args = parser.parse_args()
-
-    tc = TalerConfig.from_file(args.config)
-
-    if args.section is not None and args.option is not None:
-        if args.expand_filename:
-            x = tc.value_filename(args.section, args.option)
+    PARSER = argparse.ArgumentParser()
+    PARSER.add_argument("--section", "-s", dest="section",
+                        default=None, metavar="SECTION")
+    PARSER.add_argument("--option", "-o", dest="option",
+                        default=None, metavar="OPTION")
+    PARSER.add_argument("--config", "-c", dest="config",
+                        default=None, metavar="FILE")
+    PARSER.add_argument("--filename", "-f", dest="expand_filename",
+                        default=False, action='store_true')
+    ARGS = PARSER.parse_args()
+
+    TC = TalerConfig.from_file(ARGS.config)
+
+    if ARGS.section is not None and ARGS.option is not None:
+        if ARGS.expand_filename:
+            X = TC.value_filename(ARGS.section, ARGS.option)
         else:
-            x = tc.value_string(args.section, args.option)
-        if x is not None:
-            print(x)
+            X = TC.value_string(ARGS.section, ARGS.option)
+        if X is not None:
+            print(X)
     else:
-        tc.dump()
+        TC.dump()

-- 
To stop receiving notification emails like this one, please contact
address@hidden



reply via email to

[Prev in Thread] Current Thread [Next in Thread]