Skip to content

Commit

Permalink
Some simplifications and PEP related changes.
Browse files Browse the repository at this point in the history
  • Loading branch information
kelesi committed Nov 12, 2020
1 parent f609c81 commit d02f8a6
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 36 deletions.
41 changes: 23 additions & 18 deletions mtga-export.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@
from mtga_formats import MtgaFormats, normalize_set
import scryfall

__version__ = "0.4.3"
__version__ = "0.4.4"


def print_arrays_with_keys(data, prefix='', separator='|', last_separator='='):
"""Prints array branches on one line separated with a character.
Args:
prefix (string): Prefix to use at the begining of the line.
data: List, tuple or dictionary to print
prefix (str): Prefix to use at the begining of the line.
Defaults to empty string.
separator (string): Character or string to use as value/key separator.
separator (str): Character or string to use as value/key separator.
Defaults to pipe '|'.
last_separator (str): Last seperator used before printing final value
Examples:
>>> print_arrays_with_keys({'a': {'bb': {'ccc': 1}}})
Expand All @@ -36,16 +38,16 @@ def print_arrays_with_keys(data, prefix='', separator='|', last_separator='='):
prefix:a:bb=>2
prefix:b=>3
"""
if isinstance(data, (dict)):
if isinstance(data, dict):
if prefix:
prefix += separator
for key, value in iteritems(data):
print_arrays_with_keys(value, prefix + key, separator, last_separator)
return
if isinstance(data, (list, tuple)):
i=0
i = 0
for value in data:
i+=1
i += 1
print_arrays_with_keys(value, prefix + '['+str(i)+']', separator, last_separator)
return

Expand All @@ -60,7 +62,8 @@ def get_argparse_parser():
"""
parser = argparse.ArgumentParser(description="Parse MTGA log file")
parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument("-l", "--log_file", help="MTGA/Unity log file [Win: %%AppData%%\\LocalLow\\Wizards Of The Coast\\MTGA\\Player.log]", nargs=1)
parser.add_argument("-l", "--log_file", nargs=1,
help="MTGA/Unity log file [Win: %%AppData%%\\LocalLow\\Wizards Of The Coast\\MTGA\\Player.log]")
parser.add_argument("-k", "--keyword", help="List json under keyword", nargs=1)
parser.add_argument("--collids", help="List collection ids", action="store_true")
parser.add_argument("-c", "--collection", help="List collection with card data", action="store_true")
Expand Down Expand Up @@ -128,7 +131,7 @@ def get_keyword_data(args, mlog):
return data


def get_collection(args, mlog):
def get_collection(mlog):
"""Get collection and print messages"""
from mtga.models.card import Card

Expand Down Expand Up @@ -158,11 +161,13 @@ def main(args_string=None):

if args.log_file:
log_file = args.log_file[0]
if not os.path.isfile(log_file):
print("Log file does not exist, provide proper logfile [%s]" % log_file)
sys.exit(1)

mlog = MtgaLog(log_file)
try:
mlog = MtgaLog(log_file)
except FileNotFoundError as exception:
print("Arena log file not found, please provide proper log file.")
print(str(exception))
sys.exit(1)

if not mlog.detailed_logs():
print('DETAILED LOGS (PLUGIN SUPPORT) ARE DISABLED.')
Expand All @@ -179,13 +184,13 @@ def main(args_string=None):
print(get_keyword_data(args, mlog))

if args.collection:
for card, count in get_collection(args, mlog):
for card, count in get_collection(mlog):
logging.debug(str(card))
print(card.mtga_id, card, count)

if args.export:
output.append(','.join(args.export))
for card, count in get_collection(args, mlog):
for card, count in get_collection(mlog):
fields = []
for key in args.export:
if key == "count":
Expand All @@ -198,7 +203,7 @@ def main(args_string=None):
sets_progression_output = {}
mformats = MtgaFormats(mtga_log=mlog)

for card, count in get_collection(args, mlog):
for card, count in get_collection(mlog):
if sets_progression_output.get(card.set, None) is None:
sets_progression_output[card.set] = {
'singlesOwned': 0,
Expand All @@ -215,13 +220,13 @@ def main(args_string=None):

if args.goldfish:
output.append('Card,Set ID,Set Name,Quantity,Foil')
for card, count in get_collection(args, mlog):
for card, count in get_collection(mlog):
card_set = normalize_set(card.set, {'ANA': 'ARENA'})
output.append('"%s",%s,%s,%s,%s' % (card.pretty_name, card_set, '', count, ''))

if args.deckstats:
output.append('card_name,amount,set_code,is_foil,is_pinned')
for card, count in get_collection(args, mlog):
for card, count in get_collection(mlog):
card_set = normalize_set(card.set, {'ANA': 'MTGA'})
output.append('"%s",%s,"%s",%s,%s' % (
card.pretty_name, count, card_set, 0, 0,
Expand Down Expand Up @@ -258,7 +263,7 @@ def main(args_string=None):
if deck.name == args.deckexport[0]:
output.append(deck.export_arena())

if output != []:
if output:
output_str = '\n'.join(output)
if args.file:
with open(args.file[0], "w") as out_file:
Expand Down
10 changes: 5 additions & 5 deletions mtga_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
MTGA_FORMATS_KEYWORD = "PlayerInventory.GetFormats"


def normalize_set(set_id, conversion={}):
def normalize_set(set_id, conversion=None):
"""Convert set id readable by goldfish/deckstats"""
conversion = {} if conversion is None else conversion
conversion.update({'DAR': 'DOM'})
return conversion.get(set_id.upper(), set_id.upper())

Expand All @@ -29,9 +30,8 @@ def _get_formats_json(self):
try:
with open(self.get_full_filename()) as formats_file:
return json.load(formats_file)
except FileNotFound:
return mtga_log.get_last_json_block(MTGA_FORMATS_KEYWORD)

except FileNotFoundError:
return self.mtga_log.get_last_json_block(MTGA_FORMATS_KEYWORD)

def get_format_sets(self, mtg_format):
"""Returns list of current sets in standard format"""
Expand All @@ -54,4 +54,4 @@ def get_set_info(self, mtga_set):

def get_set_card_count(self, mtga_set):
set_info = self.get_set_info(mtga_set)
return set_info.get('card_count', 0)
return set_info.get('card_count', 0)
24 changes: 13 additions & 11 deletions mtga_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,24 @@
MTGA_PRECON_DECK_LISTS_KEYWORD = "Deck.GetPreconDecksV3"
MTGA_LOG_FILENAME = "Player.log"


def _mtga_file_path(filename):
"""Get the full path to the specified MTGA file"""
appdata = os.path.dirname(os.getenv("APPDATA"))
appdata = os.getenv("APPDATA")

# If we don't have APPDATA, assume we're in the user's home directory
base = [appdata] if appdata else ["AppData"]
base = [os.path.dirname(appdata)] if appdata else ["AppData"]
components = base + ["LocalLow", "Wizards Of The Coast", "MTGA", filename]
return os.path.join(*components)


def get_mtga_file_path(filename):
filepath = _mtga_file_path(filename)
if not os.path.isfile(filepath):
raise FileNotFoundError('Could not find file %s' % filepath)
return filepath


def find_one_mtga_card(mtga_id):
from mtga.set_data import all_mtga_cards
return all_mtga_cards.find_one(mtga_id)
Expand All @@ -53,7 +57,7 @@ def __init__(self, log_filename=None):
def detailed_logs(self):
"""Are detailed logs enabled"""
with open(self.log_filename) as logfile:
head = ''.join([next(logfile) for x in range(100)])
head = ''.join([next(logfile) for _ in range(100)])

if re.search(r"DETAILED LOGS: ENABLED", head) is not None:
return True
Expand All @@ -77,7 +81,8 @@ def get_last_keyword_block(self, keyword):
with open(self.log_filename) as logfile:
for line in logfile:
if re.search(r"%s\b" % re.escape(keyword), line):
bucket = []
bucket, dict_levels, list_levels = [], 0, 0

if line.count('{') > 0 or line.count('[') > 0:
line = re.sub(r'.*' + re.escape(keyword), '', line)
else:
Expand All @@ -86,8 +91,6 @@ def get_last_keyword_block(self, keyword):

if copy and line:
bucket.append(line)

if copy:
dict_levels += line.count('{') - line.count('}')
list_levels += line.count('[') - line.count(']')

Expand All @@ -104,7 +107,7 @@ def get_last_json_block(self, keyword):
return self._list_to_json(block)
except ValueError as exception:
raise MtgaLogParsingError(exception)
#return False
# return False

def _list_to_json(self, json_list):
json_string = ''.join(json_list)
Expand All @@ -125,7 +128,7 @@ def lookup_cards(self, list_of_pairs):
card = find_one_mtga_card(mtga_id)
except ValueError as exception:
yield [mtga_id, MtgaUnknownCard(exception), count]
#Card not found, try to get it from scryfall
# Card not found, try to get it from scryfall
card = self._fetch_card_from_scryfall(mtga_id)

if card is not None:
Expand All @@ -134,7 +137,7 @@ def lookup_cards(self, list_of_pairs):
def lookup_card(self, mtga_id):
try:
return find_one_mtga_card(mtga_id)
except ValueError as exception:
except ValueError:
return self._fetch_card_from_scryfall(mtga_id)

def get_collection(self):
Expand Down Expand Up @@ -254,8 +257,7 @@ def deck(self):
}

def export_arena(self):
export = []
export.append("Deck")
export = ["Deck"]
for [mtga_id, card, count] in self.maindeck:
export.append("{} {} ({}) {}".format(count, card.pretty_name, card.set, card.set_number))
export.append("")
Expand Down
4 changes: 2 additions & 2 deletions tests/test_mtga_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def test_get_last_json_block_notpresent(self):
["123", MtgaUnknownCard],
["67688", "Ajani's Last Stand"],
["68369", "Firesong and Sunspeaker"],
#["64037", "Bomat Courier"],
["71132", "Reconnaissance Mission"],
["70192", "Faerie Vandal"],
["69108", "Angelic Reward"]
])
Expand Down Expand Up @@ -151,7 +151,7 @@ class Test_Scryfall(unittest.TestCase):
["123", scryfall.ScryfallError],
["67688", "Ajani's Last Stand"],
["68369", "Firesong and Sunspeaker"],
["64037", "Bomat Courier"],
["71132", "Reconnaissance Mission"],
["69108", "Angelic Reward"]
])
def test_get_mtga_card(self, mtga_id, expected_card_name):
Expand Down

0 comments on commit d02f8a6

Please sign in to comment.