Skip to content

Commit

Permalink
f-strings and docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
haliphax committed Mar 12, 2020
1 parent 5e31d6e commit 11a5118
Show file tree
Hide file tree
Showing 11 changed files with 166 additions and 50 deletions.
2 changes: 1 addition & 1 deletion userland/down.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"xthulu gosub example"

async def main(cx, arg1, arg2):
cx.echo('gosub example {} {}\r\n'.format(arg1, arg2))
cx.echo(f'gosub example {arg1} {arg2}\r\n')

with cx.lock('testing') as l:
if not l:
Expand Down
6 changes: 3 additions & 3 deletions userland/top.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async def main(cx):
value=['testing this thing'])

for k in cx.env.keys():
cx.echo('{} = {}\r\n'.format(k, cx.env[k]))
cx.echo(f'{k} = {cx.env[k]}\r\n')

dirty = True

Expand All @@ -35,7 +35,7 @@ async def main(cx):
ev = await cx.events.poll('resize')

if ev:
cx.echo('\r\n{}\r\n'.format(ev))
cx.echo(f'\r\n{ev}\r\n')
await cx.events.flush('resize')

ks = await cx.term.inkey(1)
Expand All @@ -58,7 +58,7 @@ async def main(cx):

elif ks.code == cx.term.KEY_ENTER:
dirty = True
cx.echo('\r\n{}\r\n'.format(led.value[0]))
cx.echo(f'\r\n{led.value[0]}\r\n')

else:
cx.echo(led.process_keystroke(ks) + cx.term.move_x(0) +
Expand Down
10 changes: 5 additions & 5 deletions xthulu/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@

@click.group()
def cli():
pass
"xthulu terminal server command line utility"


@cli.command()
def start():
'Start SSH server process'
"Start SSH server process"

try:
log.info('Starting SSH server')
loop.run_until_complete(start_server())
except (OSError, asyncssh.Error) as exc:
sys.exit('Error: {}'.format(exc))
sys.exit(f'Error: {exc}')

try:
log.info('SSH server is listening')
Expand All @@ -37,7 +37,7 @@ def start():

@cli.command()
def db_create():
'Create database tables'
"Create database tables"

from . import models

Expand All @@ -50,7 +50,7 @@ async def f():

@cli.command()
def db_init():
'Initialize database with starter data'
"Initialize database with starter data"

from .models.user import User, hash_password

Expand Down
66 changes: 56 additions & 10 deletions xthulu/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,46 +65,86 @@ async def _init(self):
self.log.debug(repr(self.user))

def echo(self, text):
"Echo text to the terminal"
"""
Echo text to the terminal
:param str text: The text to echo
"""

if text is None:
return

self.proc.stdout.write(text.encode(self.encoding))

async def gosub(self, script, *args, **kwargs):
"Execute script and return result"
"""
Execute script and return result
:param :class:`xthulu.structs.Script` script: The userland script to
execute
:returns: The return value from the script (if any)
:rtype: mixed
"""

script = Script(script, args, kwargs)

return await self.runscript(script)

def goto(self, script, *args, **kwargs):
"Switch to script and clear stack"
"""
Switch to script and clear stack
:param :class:`xthulu.structs.Script` script: The userland script to
execute
"""

raise Goto(script, *args, **kwargs)

@contextmanager
def lock(self, name):
"Session lock context manager"
"""
Session lock context manager
:param str name: The name of the lock to attempt
:returns: Whether or not the lock was granted
:rtype: bool
"""

try:
yield locks.get(self.sid, name)
finally:
locks.release(self.sid, name)

def get_lock(self, name):
"Acquire lock on behalf of session user"
"""
Acquire lock on behalf of session user
:param str name: The name of the lock to attempt
:returns: Whether or not the lock was granted
:rtype: bool
"""

return locks.get(self.sid, name)

def release_lock(self, name):
"Release lock on behalf of session user"
"""
Release lock on behalf of session user
:param str name: The name of the lock to attempt
:returns: Whether or not the lock was granted
:rtype: bool
"""

return locks.release(self.sid, name)

async def redirect(self, proc):
"Redirect context IO to other process"
"""
Redirect context IO to other process; convenience method which wraps
AsyncSSH's redirection routine
:param mixed proc: The process to redirect to; can be tuple, list,
str, or :class:`multiprocessing.Popen`
"""

@singledispatch
async def f(proc):
Expand All @@ -130,9 +170,15 @@ async def _(proc):
return await f(proc)

async def runscript(self, script):
"Run script and return result; used by :meth:`goto` and :meth:`gosub`"
"""
Run script and return result; used by :meth:`goto` and :meth:`gosub`
:param `xthulu.structs.Script` script: The userland script to run
:returns: The return value of the script (if any)
:rtype: mixed
"""

self.log.info('Running {}'.format(script))
self.log.info(f'Running {script}')
split = script.name.split('.')
found = None
mod = None
Expand All @@ -152,7 +198,7 @@ async def runscript(self, script):
except Exception as exc:
self.log.exception(exc)
self.echo(self.term.bold_red_on_black(
'\r\nException in {}\r\n'.format(script.name)))
'\r\nException in {script.name}\r\n'))
await aio.sleep(3)


Expand Down
2 changes: 1 addition & 1 deletion xthulu/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ async def flush(self, event_name=None):
"""
Flush the event queue
:param str event_name: (Optional) The event name to filter
:param str event_name: The event name to filter (if any)
"""

popped = []
Expand Down
50 changes: 39 additions & 11 deletions xthulu/locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,27 @@


class Locks(object):

"Lock storage singleton"

locks = set([])
owned = {}


def get(owner, name):
"Acquire and hold lock on behalf of user/system"
"""
Acquire and hold lock on behalf of user/system
:param str owner: The name of the owner
:param str name: The name of the lock
:returns: Whether or not the lock was granted
:rtype: bool
"""

log.debug('{} getting lock {}'.format(owner, name))
log.debug(f'{owner} getting lock {name}')

if name in Locks.locks:
log.debug('{} lock already exists'.format(name))
log.debug(f'{name} lock already exists')

return False

Expand All @@ -34,17 +44,24 @@ def get(owner, name):


def release(owner, name):
"Release a lock owned by user/system"
"""
Release a lock owned by user/system
log.debug('{} releasing lock {}'.format(owner, name))
:param str owner: The name of the owner
:param str name: The name of the lock
:returns: Whether or not the lock was valid to begin with
:rtype: bool
"""

log.debug(f'{owner} releasing lock {name}')

if name not in Locks.locks:
log.debug('{} lock does not exist'.format(name))
log.debug(f'{name} lock does not exist')

return False

if owner not in Locks.owned or name not in Locks.owned[owner]:
log.debug('{} does not own lock {}'.format(owner, name))
log.debug(f'{owner} does not own lock {name}')

return False

Expand All @@ -58,7 +75,14 @@ def release(owner, name):

@contextmanager
def hold(owner, name):
"Session-agnostic lock context manager"
"""
Session-agnostic lock context manager
:param str owner: The name of the owner
:param str name: The name of the lock
:returns: Whether or not the lock was granted
:rtype: bool
"""

try:
yield get(owner, name)
Expand All @@ -67,9 +91,13 @@ def hold(owner, name):


def expire(owner):
"Remove all locks owned by user"
"""
Remove all locks owned by user
:param str owner: The name of the owner
"""

log.debug('Releasing locks owned by {}'.format(owner))
log.debug(f'Releasing locks owned by {owner}')
locks = 0
owned = None

Expand All @@ -78,7 +106,7 @@ def expire(owner):
locks = len(owned)

if locks == 0:
log.debug('No locks for {}'.format(owner))
log.debug(f'No locks for {owner}')
else:
for l in owned:
release(owner, l)
Expand Down
2 changes: 1 addition & 1 deletion xthulu/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class User(db.Model):
def __repr__(self):
'Represent as str'

return 'User({}#{})'.format(self.name, self.id)
return f'User({self.name}#{self.id})'


idx_name_lower = db.Index('idx_user_name_lower', func.lower(User.name))
Expand Down
24 changes: 11 additions & 13 deletions xthulu/ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def connection_made(self, conn):
self._peername = conn.get_extra_info('peername')
self._sid = '{}:{}'.format(*self._peername)
EventQueues.q[self._sid] = aio.Queue()
log.info('{} connecting'.format(self._peername[0]))
log.info(f'{self._peername[0]} connecting')

def connection_lost(self, exc):
"Connection closed"
Expand All @@ -41,10 +41,9 @@ def connection_lost(self, exc):
locks.expire(self._sid)

if exc:
log.error('Error: {}'.format(exc))
log.error(f'Error: {exc}')

log.info('{}@{} disconnected'.format(self._username,
self._peername[0]))
log.info(f'{self._username}@{self._peername[0]} disconnected')

def begin_auth(self, username):
"Check for auth bypass"
Expand All @@ -54,10 +53,10 @@ def begin_auth(self, username):

if ('no_password' in config['ssh']['auth'] and
username in config['ssh']['auth']['no_password']):
log.info('No password required for {}'.format(username))
log.info(f'No password required for {username}')
pwd_required = False

log.info('{}@{} connected'.format(username, self._peername[0]))
log.info(f'{username}@{self._peername[0]} connected')

return pwd_required

Expand All @@ -73,19 +72,18 @@ async def validate_password(self, username, password):
.gino.first())

if u is None:
log.warn('User {} does not exist'.format(username))
log.warn(f'User {username} does not exist')

return False

expected, _ = hash_password(password, u.salt)

if expected != u.password:
log.warn('Invalid credentials received for {}'
.format(username))
log.warn(f'Invalid credentials received for {username}')

return False

log.info('Valid credentials received for {}'.format(username))
log.info(f'Valid credentials received for {username}')

return True

Expand Down Expand Up @@ -140,18 +138,18 @@ def terminal_process():
return

if debug_term:
log.debug('proxy received: {}'.format(inp))
log.debug(f'proxy received: {inp}')

attr = getattr(term, inp[0])

if callable(attr) or len(inp[1]) or len(inp[2]):
if debug_term:
log.debug('{} callable'.format(inp[0]))
log.debug(f'{inp[0]} callable')

term_pipe.send(attr(*inp[1], **inp[2]))
else:
if debug_term:
log.debug('{} not callable'.format(inp[0]))
log.debug('{inp[0]} not callable')

term_pipe.send(attr)

Expand Down
Loading

0 comments on commit 11a5118

Please sign in to comment.