11import json
22
3+ import yaml
4+
35from gendiff .cli import parse_args
46
57
@@ -8,13 +10,18 @@ def main() -> None:
810 print (generate_diff (args .first_file , args .second_file ))
911
1012
11- def read_file_json (path : str ):
13+ def read_file (path : str ):
14+ if path .endswith ('.json' ):
15+ load_data = json .load
16+ elif path .endswith (('.yaml' , '.yml' )):
17+ load_data = yaml .safe_load
18+ else :
19+ raise ValueError (f"ERROR: Unsupported format of file { path } ." )
1220 try :
1321 with open (path , mode = 'r' , encoding = 'utf-8' ) as file :
14- return json .load (file )
15- except Exception as error :
16- print ("Can't read_file_json\n " , error )
17- return None
22+ return load_data (file )
23+ except OSError as error :
24+ raise OSError (f"ERROR: Can't read file { path } . Reason: { error } " )
1825
1926
2027def get_list_of_dict_with_sign (data1 , data2 ) -> list :
@@ -33,15 +40,10 @@ def get_list_of_dict_with_sign(data1, data2) -> list:
3340
3441
3542def sort_list (items : list ):
36- def sort_by_rule (item : dict ) -> str :
37- """The sign is changed to correctly sort items with the same key."""
38- if item ['sign' ] == '+' :
39- sign = '-'
40- elif item ['sign' ] == '-' :
41- sign = '+'
42- else :
43- sign = ' '
44- return str ([item ['key' ], sign ])
43+ def sort_by_rule (item : dict ) -> tuple :
44+ """The sign -> digit for correctly sort items with the same key."""
45+ sign_order = {'-' : 0 , '+' : 1 , ' ' : 2 }
46+ return (item ['key' ], sign_order [item ['sign' ]])
4547 items .sort (key = sort_by_rule )
4648 return items
4749
@@ -50,6 +52,7 @@ def make_str_from_list(items: list) -> str:
5052 """
5153 Type checking for the output of strings without quotes,
5254 and for the correct output of True, False in the form of true, false.
55+ Doesn't matter for .yaml.
5356 """
5457 list_of_str = ['{' ]
5558 for item in items :
@@ -71,7 +74,8 @@ def make_str_from_list(items: list) -> str:
7174
7275
7376def generate_diff (path1 , path2 ) -> str :
74- data1 = read_file_json (path1 )
75- data2 = read_file_json (path2 )
76- sorted_list_of_dict = sort_list (get_list_of_dict_with_sign (data1 , data2 ))
77- return make_str_from_list (sorted_list_of_dict )
77+ dict_data1 = read_file (path1 )
78+ dict_data2 = read_file (path2 )
79+ list_of_dict = get_list_of_dict_with_sign (dict_data1 , dict_data2 )
80+ sorted_list = sort_list (list_of_dict )
81+ return make_str_from_list (sorted_list )
0 commit comments