Skip to content

Add quote formatting to pylint config #186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ single-line-if-stmt = no
no-space-check = trailing-comma,dict-separator
max-module-lines = 1000
indent-string = ' '
string-quote=single-avoid-escape
triple-quote=single
docstring-quote=double

[MISCELLANEOUS]
notes = FIXME,XXX,TODO
Expand Down
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ python:
install:
- "pip install -r requirements.txt"
script:
- "pylint packet/routes packet"
- "pylint --load-plugins pylint_quotes packet/routes packet"
42 changes: 21 additions & 21 deletions packet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,57 +20,57 @@

# Load default configuration and any environment variable overrides
_root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
app.config.from_pyfile(os.path.join(_root_dir, "config.env.py"))
app.config.from_pyfile(os.path.join(_root_dir, 'config.env.py'))

# Load file based configuration overrides if present
_pyfile_config = os.path.join(_root_dir, "config.py")
_pyfile_config = os.path.join(_root_dir, 'config.py')
if os.path.exists(_pyfile_config):
app.config.from_pyfile(_pyfile_config)

# Fetch the version number from the npm package file
with open(os.path.join(_root_dir, "package.json")) as package_file:
app.config["VERSION"] = json.load(package_file)["version"]
with open(os.path.join(_root_dir, 'package.json')) as package_file:
app.config['VERSION'] = json.load(package_file)['version']

# Logger configuration
logging.getLogger().setLevel(app.config["LOG_LEVEL"])
app.logger.info("Launching packet v" + app.config["VERSION"])
app.logger.info("Using the {} realm".format(app.config["REALM"]))
logging.getLogger().setLevel(app.config['LOG_LEVEL'])
app.logger.info('Launching packet v' + app.config['VERSION'])
app.logger.info('Using the {} realm'.format(app.config['REALM']))

# Initialize the extensions
db = SQLAlchemy(app)
migrate = Migrate(app, db)
app.logger.info("SQLAlchemy pointed at " + repr(db.engine.url))
app.logger.info('SQLAlchemy pointed at ' + repr(db.engine.url))

APP_CONFIG = ProviderConfiguration(issuer=app.config["OIDC_ISSUER"],
client_metadata=ClientMetadata(app.config["OIDC_CLIENT_ID"],
app.config["OIDC_CLIENT_SECRET"]))
APP_CONFIG = ProviderConfiguration(issuer=app.config['OIDC_ISSUER'],
client_metadata=ClientMetadata(app.config['OIDC_CLIENT_ID'],
app.config['OIDC_CLIENT_SECRET']))

# Initialize Onesignal Notification apps
csh_onesignal_client = onesignal.Client(user_auth_key=app.config["ONESIGNAL_USER_AUTH_KEY"],
app_auth_key=app.config["ONESIGNAL_CSH_APP_AUTH_KEY"],
app_id=app.config["ONESIGNAL_CSH_APP_ID"])
csh_onesignal_client = onesignal.Client(user_auth_key=app.config['ONESIGNAL_USER_AUTH_KEY'],
app_auth_key=app.config['ONESIGNAL_CSH_APP_AUTH_KEY'],
app_id=app.config['ONESIGNAL_CSH_APP_ID'])

intro_onesignal_client = onesignal.Client(user_auth_key=app.config["ONESIGNAL_USER_AUTH_KEY"],
app_auth_key=app.config["ONESIGNAL_INTRO_APP_AUTH_KEY"],
app_id=app.config["ONESIGNAL_INTRO_APP_ID"])
intro_onesignal_client = onesignal.Client(user_auth_key=app.config['ONESIGNAL_USER_AUTH_KEY'],
app_auth_key=app.config['ONESIGNAL_INTRO_APP_AUTH_KEY'],
app_id=app.config['ONESIGNAL_INTRO_APP_ID'])

# OIDC Auth
auth = OIDCAuthentication({'app': APP_CONFIG}, app)

# LDAP
_ldap = csh_ldap.CSHLDAP(app.config["LDAP_BIND_DN"], app.config["LDAP_BIND_PASS"])
_ldap = csh_ldap.CSHLDAP(app.config['LDAP_BIND_DN'], app.config['LDAP_BIND_PASS'])

app.logger.info("OIDCAuth and LDAP configured")
app.logger.info('OIDCAuth and LDAP configured')

# pylint: disable=wrong-import-position
from . import models
from . import context_processors
from . import commands
from .routes import api, shared

if app.config["REALM"] == "csh":
if app.config['REALM'] == 'csh':
from .routes import upperclassmen
else:
from .routes import freshmen

app.logger.info("Routes registered")
app.logger.info('Routes registered')
96 changes: 48 additions & 48 deletions packet/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
ldap_is_on_coop


@app.cli.command("create-secret")
@app.cli.command('create-secret')
def create_secret():
"""
Generates a securely random token. Useful for creating a value for use in the "SECRET_KEY" config setting.
Expand All @@ -33,37 +33,37 @@ class CSVFreshman:
def __init__(self, row):
self.name = row[0]
self.rit_username = row[3]
self.onfloor = row[1] == "TRUE"
self.onfloor = row[1] == 'TRUE'


def parse_csv(freshmen_csv):
print("Parsing file...")
print('Parsing file...')
try:
with open(freshmen_csv, newline='') as freshmen_csv_file:
return {freshman.rit_username: freshman for freshman in map(CSVFreshman, csv.reader(freshmen_csv_file))}
except Exception as e:
print("Failure while parsing CSV")
print('Failure while parsing CSV')
raise e


def input_date(prompt):
while True:
try:
date_str = input(prompt + " (format: MM/DD/YYYY): ")
return datetime.strptime(date_str, "%m/%d/%Y").date()
date_str = input(prompt + ' (format: MM/DD/YYYY): ')
return datetime.strptime(date_str, '%m/%d/%Y').date()
except ValueError:
pass


@app.cli.command("sync-freshmen")
@click.argument("freshmen_csv")
@app.cli.command('sync-freshmen')
@click.argument('freshmen_csv')
def sync_freshmen(freshmen_csv):
"""
Updates the freshmen entries in the DB to match the given CSV.
"""
freshmen_in_csv = parse_csv(freshmen_csv)

print("Syncing contents with the DB...")
print('Syncing contents with the DB...')
freshmen_in_db = {freshman.rit_username: freshman for freshman in Freshman.query.all()}

for csv_freshman in freshmen_in_csv.values():
Expand Down Expand Up @@ -98,25 +98,25 @@ def sync_freshmen(freshmen_csv):
db.session.add(FreshSignature(packet=packet, freshman=freshmen_in_db[csv_freshman.rit_username]))

db.session.commit()
print("Done!")
print('Done!')


@app.cli.command("create-packets")
@click.argument("freshmen_csv")
@app.cli.command('create-packets')
@click.argument('freshmen_csv')
def create_packets(freshmen_csv):
"""
Creates a new packet season for each of the freshmen in the given CSV.
"""
print("WARNING: The 'sync-freshmen' command must be run first to ensure that the state of floor is up to date.")
if input("Continue? (y/N): ").lower() != "y":
if input('Continue? (y/N): ').lower() != 'y':
return

# Collect the necessary data
base_date = input_date("Input the first day of packet season")
base_date = input_date('Input the first day of packet season')
start = datetime.combine(base_date, packet_start_time)
end = datetime.combine(base_date, packet_end_time) + timedelta(days=14)

print("Fetching data from LDAP...")
print('Fetching data from LDAP...')
all_upper = list(filter(
lambda member: not ldap_is_intromember(member) and not ldap_is_on_coop(member), ldap_get_active_members()))

Expand All @@ -131,7 +131,7 @@ def create_packets(freshmen_csv):

# Create the new packets and the signatures for each freshman in the given CSV
freshmen_in_csv = parse_csv(freshmen_csv)
print("Creating DB entries and sending emails...")
print('Creating DB entries and sending emails...')
for freshman in Freshman.query.filter(Freshman.rit_username.in_(freshmen_in_csv)).all():
packet = Packet(freshman=freshman, start=start, end=end)
db.session.add(packet)
Expand All @@ -153,15 +153,15 @@ def create_packets(freshmen_csv):
db.session.add(FreshSignature(packet=packet, freshman=onfloor_freshman))

db.session.commit()
print("Done!")
print('Done!')


@app.cli.command("ldap-sync")
@app.cli.command('ldap-sync')
def ldap_sync():
"""
Updates the upper and misc sigs in the DB to match ldap.
"""
print("Fetching data from LDAP...")
print('Fetching data from LDAP...')
all_upper = {member.uid: member for member in filter(
lambda member: not ldap_is_intromember(member) and not ldap_is_on_coop(member), ldap_get_active_members())}

Expand All @@ -171,7 +171,7 @@ def ldap_sync():
c_m = ldap_get_constitutional_maintainers()
drink = ldap_get_drink_admins()

print("Applying updates to the DB...")
print('Applying updates to the DB...')
for packet in Packet.query.filter(Packet.end > datetime.now()).all():
# Update the role state of all UpperSignatures
for sig in filter(lambda sig: sig.member in all_upper, packet.upper_signatures):
Expand Down Expand Up @@ -215,89 +215,89 @@ def ldap_sync():
db.session.add(sig)

db.session.commit()
print("Done!")
print('Done!')


@app.cli.command("fetch-results")
@app.cli.command('fetch-results')
def fetch_results():
"""
Fetches and prints the results from a given packet season.
"""
end_date = datetime.combine(input_date("Enter the last day of the packet season you'd like to retrieve results "
"from"), packet_end_time)
'from'), packet_end_time)

for packet in Packet.query.filter_by(end=end_date).all():
print()

print("{} ({}):".format(packet.freshman.name, packet.freshman.rit_username))
print('{} ({}):'.format(packet.freshman.name, packet.freshman.rit_username))

received = packet.signatures_received()
required = packet.signatures_required()

print("\tUpperclassmen score: {:0.2f}%".format(received.member_total / required.member_total * 100))
print("\tTotal score: {:0.2f}%".format(received.total / required.total * 100))
print('\tUpperclassmen score: {:0.2f}%'.format(received.member_total / required.member_total * 100))
print('\tTotal score: {:0.2f}%'.format(received.total / required.total * 100))
print()

print("\tUpperclassmen: {}/{}".format(received.upper, required.upper))
print("\tFreshmen: {}/{}".format(received.fresh, required.fresh))
print("\tMiscellaneous: {}/{}".format(received.misc, required.misc))
print('\tUpperclassmen: {}/{}'.format(received.upper, required.upper))
print('\tFreshmen: {}/{}'.format(received.fresh, required.fresh))
print('\tMiscellaneous: {}/{}'.format(received.misc, required.misc))
print()

print("\tTotal missed:", required.total - received.total)
print('\tTotal missed:', required.total - received.total)


@app.cli.command("extend-packet")
@click.argument("packet_id")
@app.cli.command('extend-packet')
@click.argument('packet_id')
def extend_packet(packet_id):
"""
Extends the given packet by setting a new end date.
"""
packet = Packet.by_id(packet_id)

if not packet.is_open():
print("Packet is already closed so it cannot be extended")
print('Packet is already closed so it cannot be extended')
return
else:
print("Ready to extend packet #{} for {}".format(packet_id, packet.freshman_username))
print('Ready to extend packet #{} for {}'.format(packet_id, packet.freshman_username))

packet.end = datetime.combine(input_date("Enter the new end date for this packet"), packet_end_time)
packet.end = datetime.combine(input_date('Enter the new end date for this packet'), packet_end_time)
db.session.commit()

print("Packet successfully extended")
print('Packet successfully extended')


def remove_sig(packet_id, username, is_member):
packet = Packet.by_id(packet_id)

if not packet.is_open():
print("Packet is already closed so its signatures cannot be modified")
print('Packet is already closed so its signatures cannot be modified')
return
elif is_member:
sig = UpperSignature.query.filter_by(packet_id=packet_id, member=username).first()
if sig is not None:
sig.signed = False
db.session.commit()
print("Successfully unsigned packet")
print('Successfully unsigned packet')
else:
result = MiscSignature.query.filter_by(packet_id=packet_id, member=username).delete()
if result == 1:
db.session.commit()
print("Successfully unsigned packet")
print('Successfully unsigned packet')
else:
print("Failed to unsign packet; could not find signature")
print('Failed to unsign packet; could not find signature')
else:
sig = FreshSignature.query.filter_by(packet_id=packet_id, freshman_username=username).first()
if sig is not None:
sig.signed = False
db.session.commit()
print("Successfully unsigned packet")
print('Successfully unsigned packet')
else:
print("Failed to unsign packet; {} is not an onfloor".format(username))
print('Failed to unsign packet; {} is not an onfloor'.format(username))


@app.cli.command("remove-member-sig")
@click.argument("packet_id")
@click.argument("member")
@app.cli.command('remove-member-sig')
@click.argument('packet_id')
@click.argument('member')
def remove_member_sig(packet_id, member):
"""
Removes the given member's signature from the given packet.
Expand All @@ -306,9 +306,9 @@ def remove_member_sig(packet_id, member):
remove_sig(packet_id, member, True)


@app.cli.command("remove-freshman-sig")
@click.argument("packet_id")
@click.argument("freshman")
@app.cli.command('remove-freshman-sig')
@click.argument('packet_id')
@click.argument('freshman')
def remove_freshman_sig(packet_id, freshman):
"""
Removes the given freshman's signature from the given packet.
Expand Down
Loading