Browse code

Refactor get_accounts() and get_history() into load_json().

Xavier G authored on 10/11/2017 18:12:05
Showing 3 changed files

... ...
@@ -22,7 +22,7 @@ def main():
22 22
     timestamps = {}
23 23
     filepaths = set(args.json_file)
24 24
     for filepath in filepaths:
25
-        accounts = get_accounts(filepath)
25
+        accounts = load_json(filepath)
26 26
         timestamp = accounts.get('timestamp', time.time())
27 27
         for account in accounts.get('data', []):
28 28
             add_account(table, account, timestamp)
... ...
@@ -33,13 +33,6 @@ def main():
33 33
     total_line += format_amount(total, DEFAULT_CURRENCY, COLORING_THRESHOLD)
34 34
     print(total_line)
35 35
 
36
-def get_accounts(accounts_json_path):
37
-    if accounts_json_path == '-':
38
-        return json.load(sys.stdin)
39
-    else:
40
-        with open(accounts_json_path, 'r') as filedesc:
41
-            return json.load(filedesc)
42
-
43 36
 def get_table():
44 37
     pt = PrettyTable()
45 38
     pt.field_names = ['Account ID', 'Account name', 'Balance', 'Data cached on']
... ...
@@ -20,7 +20,7 @@ def main():
20 20
     args = parse_args()
21 21
     filepath = args.json_file
22 22
     max_operations = args.count
23
-    history = get_history(filepath)
23
+    history = load_json(filepath)
24 24
     timestamp = history.get('timestamp', time.time())
25 25
     table = get_table(timestamp)
26 26
     i = 0
... ...
@@ -31,13 +31,6 @@ def main():
31 31
             break
32 32
     print(table)
33 33
 
34
-def get_history(history_json_path):
35
-    if history_json_path == '-':
36
-        return json.load(sys.stdin)
37
-    else:
38
-        with open(history_json_path, 'r') as filedesc:
39
-            return json.load(filedesc)
40
-
41 34
 def get_table(timestamp):
42 35
     pt = PrettyTable()
43 36
     field_names = ['Date', 'Label', 'Amount']
... ...
@@ -4,7 +4,9 @@ This module provides various functions and constants used by the boobank-utils
4 4
 tools.
5 5
 """
6 6
 import os
7
+import sys
7 8
 import time
9
+import json
8 10
 import errno
9 11
 from termcolor import colored
10 12
 
... ...
@@ -82,3 +84,13 @@ def mkdir(path, mode):
82 84
             pass
83 85
         else:
84 86
             raise
87
+
88
+def load_json(json_path):
89
+    """
90
+    Return the contents of a JSON file, given its path.
91
+    """
92
+    if json_path == '-':
93
+        return json.load(sys.stdin)
94
+    else:
95
+        with open(json_path, 'r') as filedesc:
96
+            return json.load(filedesc)