def run_dangerously() -> None: try: cmd = sys.argv[1].lower() args = sys.argv[2:] except IndexError: raise InvalidArgumentException('Please supply an argument.') if cmd == 'unit': unit(args) elif cmd == 'functional': runtests(args, 'functional', True) elif cmd == 'perf': runtests(args, 'perf', True) elif cmd in ('test', 'tests'): runtests(args, '', False) elif cmd in ('lint', 'pylint'): lint(args) elif cmd in ('types', 'mypy'): mypy(args) elif cmd == 'mypy-strict': mypy(args, strict=True) elif cmd == 'typeshed': mypy(args, typeshedding=True) elif cmd == 'jslint': jslint() elif cmd == 'jsfix': jsfix() elif cmd in ('nuke_db', 'reset_db'): reset_db() elif cmd in ('imports', 'isort', 'sort'): sort() elif cmd in ('fix-sorts', 'fix-imports', 'fiximports'): sort(True) elif cmd in ('pr', 'pull-request'): pull_request(args) elif cmd == 'build': build() elif cmd == 'buildjs': buildjs() elif cmd == 'popclean': popclean() elif cmd == 'readme': generate_readme() elif cmd == 'coverage': coverage() elif cmd == 'watch': watch() elif cmd == 'branch': branch(args) elif cmd == 'push': push() elif cmd == 'check': check(args) elif cmd in ('safe_push', 'safepush'): safe_push(args) elif cmd == 'release': release(args) else: raise InvalidArgumentException('Unrecognised command {cmd}.'.format(cmd=cmd))
def post_archetypes(): search_results = [] if request.form.get('deck_id') is not None: archetype_ids = request.form.getlist('archetype_id') # Adjust archetype_ids if we're assigning multiple decks to the same archetype. if len(archetype_ids) == 1 and len( request.form.getlist('deck_id')) > 1: archetype_ids = archetype_ids * len( request.form.getlist('deck_id')) for deck_id in request.form.getlist('deck_id'): archetype_id = archetype_ids.pop(0) if archetype_id: archs.assign(deck_id, archetype_id) elif request.form.get('q') is not None: search_results = ds.load_decks_by_cards( request.form.get('q').splitlines()) elif request.form.getlist('archetype_id') is not None and len( request.form.getlist('archetype_id')) == 2: archs.move( request.form.getlist('archetype_id')[0], request.form.getlist('archetype_id')[1]) elif request.form.get('parent') is not None: archs.add(request.form.get('name'), request.form.get('parent')) else: raise InvalidArgumentException( 'Did not find any of the expected keys in POST to /admin/archetypes: {f}' .format(f=request.form)) return edit_archetypes(search_results)
def post_archetypes() -> wrappers.Response: search_results: List[Deck] = [] if request.form.get('deck_id') is not None: archetype_ids = request.form.getlist('archetype_id') # Adjust archetype_ids if we're assigning multiple decks to the same archetype. if len(archetype_ids) == 1 and len(request.form.getlist('deck_id')) > 1: archetype_ids = archetype_ids * len(request.form.getlist('deck_id')) for deck_id in request.form.getlist('deck_id'): archetype_id = archetype_ids.pop(0) if archetype_id: archs.assign(deck_id, archetype_id, auth.person_id()) redis.clear(f'decksite:deck:{deck_id}') elif request.form.get('q') is not None and request.form.get('notq') is not None: search_results = ds.load_decks_by_cards(cast(str, request.form.get('q')).splitlines(), cast(str, request.form.get('notq')).splitlines()) elif request.form.get('find_conflicts') is not None: search_results = ds.load_conflicted_decks() elif request.form.get('rename_to') is not None: archs.rename(cast_int(request.form.get('archetype_id')), cast(str, request.form.get('rename_to'))) elif request.form.get('new_description') is not None: archs.update_description(cast_int(request.form.get('archetype_id')), cast(str, request.form.get('new_description'))) elif request.form.getlist('archetype_id') is not None and len(request.form.getlist('archetype_id')) == 2: archs.move(request.form.getlist('archetype_id')[0], request.form.getlist('archetype_id')[1]) elif request.form.get('parent') is not None: archs.add(cast(str, request.form.get('name')), cast_int(request.form.get('parent'))) else: raise InvalidArgumentException('Did not find any of the expected keys in POST to /admin/archetypes: {f}'.format(f=request.form)) return edit_archetypes(search_results, request.form.get('q', ''), request.form.get('notq', ''))
def insert_deck(competition_id: int, date: datetime.datetime, d: GatherlingDeck, fs: FinalStandings, players: List[Player]) -> deck.Deck: finish = fuzzy_get(fs, d.playername) if not finish: raise InvalidDataException( f"I don't have a finish for `{d.playername}`") mtgo_username = find_mtgo_username(d.playername, players) if not mtgo_username: raise InvalidDataException( f"I don't have an MTGO username for `{d.playername}`") raw: deck.RawDeckDescription = { 'name': d.name, 'source': 'Gatherling', 'competition_id': competition_id, 'created_date': dtutil.dt2ts(date), 'mtgo_username': mtgo_username, 'finish': finish, 'url': gatherling_url(f'/deck.php?mode=view&id={d.id}'), 'archetype': d.archetype.value, 'identifier': str(d.id), 'cards': { 'maindeck': d.maindeck, 'sideboard': d.sideboard }, } if len(raw['cards']['maindeck']) + len(raw['cards']['sideboard']) == 0: raise InvalidDataException( f'Unable to add deck with no cards `{d.id}`') decklist.vivify(raw['cards']) if deck.get_deck_id(raw['source'], raw['identifier']): raise InvalidArgumentException( "You asked me to insert a deck that already exists `{raw['source']}`, `{raw['identifier']}`" ) return deck.add_deck(raw)
def get(key: str) -> Optional[Union[str, List[str], int, float]]: if key in CONFIG: return CONFIG[key] try: cfg = json.load(open('config.json')) except FileNotFoundError: cfg = {} if key in cfg: CONFIG.update(cfg) return cfg[key] elif key in os.environ: cfg[key] = os.environ[key] elif key in DEFAULTS: # Lock in the default value if we use it. cfg[key] = DEFAULTS[key] if inspect.isfunction( cfg[key]): # If default value is a function, call it. cfg[key] = cfg[key]() else: raise InvalidArgumentException( 'No default or other configuration value available for {key}'. format(key=key)) print('CONFIG: {0}={1}'.format(key, cfg[key])) fh = open('config.json', 'w') fh.write(json.dumps(cfg, indent=4)) return cfg[key]
def season_query(season_id: Optional[Union[str, int]], column_name: str = 'season_id') -> str: if season_id is None or season_id == 'all' or season_id == 0: return 'TRUE' try: return '{column_name} = {season_id}'.format(column_name=column_name, season_id=int(season_id)) except ValueError as c: raise InvalidArgumentException('No season with id `{season_id}`'.format(season_id=season_id)) from c
def season_query(season_id: Optional[int]) -> str: if season_id is None or season_id == 'all': return 'TRUE' try: return 'season.id = {season_id}'.format(season_id=int(season_id)) except ValueError: raise InvalidArgumentException( 'No season with id `{season_id}`'.format(season_id=season_id))
def post_rules() -> str: if request.form.get('archetype_id') is not None: rs.add_rule(cast_int(request.form.get('archetype_id'))) else: raise InvalidArgumentException( 'Did not find any of the expected keys in POST to /admin/rules: {f}' .format(f=request.form)) return edit_rules()
def post_player_note() -> wrappers.Response: if not request.form.get('person_id') or not request.form.get('note'): raise InvalidArgumentException( f'Did not find any of the expected keys in POST to /admin/people/notes: {request.form}' ) creator = ps.load_person_by_discord_id(session['id']) ps.add_note(creator.id, request.form['person_id'], request.form['note']) return redirect(url_for('player_notes'))
async def gatherling_whois(name: Optional[str] = None, discord_id: Optional[str] = None) -> Container: if discord_id: url = f'https://gatherling.com/api.php?action=whois&discordid={discord_id}' elif name: url = f'https://gatherling.com/api.php?action=whois&name={name}' else: raise InvalidArgumentException('No identifier provided') data = await fetch_tools.fetch_json_async(url) return Container(data)
def medal2finish(m: Medal) -> int: if m == Medal.WINNER: return 1 if m == Medal.RUNNER_UP: return 2 if m == Medal.TOP_4: return 3 if m == Medal.TOP_8: return 5 raise InvalidArgumentException( f"I don't know what the finish is for `{m}`")
def sqlescape(s: ValidSqlArgumentDescription, force_string: bool = False, backslashed_escaped: bool = False) -> ValidSqlArgumentDescription: if str(s).isdecimal() and not force_string: return s if isinstance(s, str): encodable = s.encode('utf-8', 'strict').decode('utf-8') if encodable.find('\x00') >= 0: raise Exception('NUL not allowed in SQL string.') if not backslashed_escaped: encodable = encodable.replace('\\', '\\\\') return "'{escaped}'".format(escaped=encodable.replace("'", "''").replace('%', '%%')) raise InvalidArgumentException('Cannot sqlescape `{s}`'.format(s=s))
def get_format_id(name: str, allow_create: bool = False) -> int: if len(FORMAT_IDS) == 0: rs = db().select('SELECT id, name FROM format') for row in rs: FORMAT_IDS[row['name']] = row['id'] if name not in FORMAT_IDS.keys() and allow_create: db().execute('INSERT INTO format (name) VALUES (%s)', [name]) FORMAT_IDS[name] = db().last_insert_rowid() if name not in FORMAT_IDS.keys(): raise InvalidArgumentException( 'Unknown format: {name}'.format(name=name)) return FORMAT_IDS[name]
def insert_meld_result_faces(p: CardDescription, cards: Dict[str, int]) -> None: all_parts = p.get('all_parts') if all_parts is None: raise InvalidArgumentException( f'Tried to insert_meld_result_faces on a card without all_parts: {p}' ) front_face_names = [ part['name'] for part in all_parts if part['component'] == 'meld_part' ] card_ids = [cards[name] for name in front_face_names] for card_id in card_ids: insert_face(p, card_id, 2)
def insert_card_faces(p: CardDescription, card_id: int) -> None: card_faces = p.get('card_faces') if card_faces is None: raise InvalidArgumentException( f'Tried to insert_card_faces on a card without card_faces: {p} ({card_id})' ) first_face_cmc = mana.cmc(card_faces[0]['mana_cost']) position = 1 for face in card_faces: # Scryfall doesn't provide cmc on card_faces currently. See #5939. face['cmc'] = mana.cmc( face['mana_cost']) if face['mana_cost'] else first_face_cmc insert_face(face, card_id, position) position += 1
def meld_face_values(p: CardDescription, cards: Dict[str, int]) -> List[Dict[str, Any]]: values = [] all_parts = p.get('all_parts') if all_parts is None: raise InvalidArgumentException( f'Tried to insert_meld_result_faces on a card without all_parts: {p}' ) front_face_names = [ part['name'] for part in all_parts if part['component'] == 'meld_part' ] card_ids = [cards[name] for name in front_face_names] for card_id in card_ids: values.append(single_face_value(p, card_id, 2)) return values
def run() -> None: """Make a 'safe' (no personal info) copy of the current prod db for download by devs.""" host = configuration.get_str('mysql_host') port = configuration.get_int('mysql_port') usr = configuration.get_str('mysql_user') pwd = configuration.get_str('mysql_passwd') db = configuration.get_str('decksite_database') if not (host or port or usr or pwd or db): safe_pwd = 'PRESENT' if pwd else 'MISSING' raise InvalidArgumentException(f'Unable to dump dev db with {host} {port} {usr} pwd:{safe_pwd} {db}') base_command = ['mysqldump', '-h', host, '-P', str(port), '-u', usr, f'-p{pwd}'] structure = subprocess.check_output(base_command + ['--no-data', db]) data = subprocess.check_output(base_command + [f'--ignore-table={db}.person_note', db]) with gzip.open('shared_web/static/dev-db.sql.gz', 'wb') as f: f.write(structure) f.write(data)
def multiple_faces_values(p: CardDescription, card_id: int) -> List[Dict[str, Any]]: card_faces = p.get('card_faces') if card_faces is None: raise InvalidArgumentException( f'Tried to insert_card_faces on a card without card_faces: {p} ({card_id})' ) first_face_cmc = mana.cmc(card_faces[0]['mana_cost']) position = 1 face_values = [] for face in card_faces: # Scryfall doesn't provide cmc on card_faces currently. See #5939. face['cmc'] = mana.cmc( face['mana_cost']) if face['mana_cost'] else first_face_cmc face_values.append(single_face_value(face, card_id, position)) position += 1 return face_values