Skip to content
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

Migrate to ruff format #41

Merged
merged 1 commit into from
Nov 28, 2023
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
13 changes: 8 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,23 @@ jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.11"
cache: "pip" # caching pip dependencies
- run: pip install -r requirements.txt

- name: Ruff linting
- run: pip install -e .

- name: Ruff format
uses: chartboost/ruff-action@v1
with:
args: format --check

- name: Black formatting
uses: psf/black@stable
- name: Ruff lint
uses: chartboost/ruff-action@v1

- name: Mypy
run: |
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4
Expand All @@ -20,7 +20,7 @@ jobs:
- name: Set up build tools
run: |
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip install -e .
python -m pip install setuptools build

- name: Build package
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:
asset_name: bitsrun-universal-macos.bin

steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4
Expand All @@ -34,7 +34,7 @@ jobs:
- name: Set up build tools
run: |
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip install -e .
python -m pip install pyinstaller

- name: Compile single executable for Windows/Linux
Expand Down
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "bitsrun"
version = "3.6.0"
version = "3.6.1"
description = "A headless login / logout script for 10.0.0.55"
authors = [{ name = "spencerwooo", email = "[email protected]" }]
dependencies = [
Expand Down Expand Up @@ -45,6 +45,10 @@ build-backend = "setuptools.build_meta"
line-length = 88
select = ["E", "F", "I", "N", "B", "SIM"]

[tool.ruff.format]
# Use single quotes rather than double quotes.
quote-style = "single"

[tool.mypy]
disallow_any_unimported = true
no_implicit_optional = true
Expand Down
5 changes: 0 additions & 5 deletions requirements.txt

This file was deleted.

46 changes: 23 additions & 23 deletions src/bitsrun/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
# A hacky way to specify shared options for multiple click commands:
# https://stackoverflow.com/questions/40182157/shared-options-and-flags-between-commands
_options = [
click.option("-u", "--username", help="Your username.", required=False),
click.option("-p", "--password", help="Your password.", required=False),
click.option("-v", "--verbose", is_flag=True, help="Verbosely echo API response."),
click.option('-u', '--username', help='Your username.', required=False),
click.option('-p', '--password', help='Your password.', required=False),
click.option('-v', '--verbose', is_flag=True, help='Verbosely echo API response.'),
]

# Replace the default implementation
Expand Down Expand Up @@ -46,11 +46,11 @@ def cli():
@cli.command()
def config_paths():
"""List possible paths of the configuration file."""
click.echo("\n".join(map(str, get_config_paths())))
click.echo('\n'.join(map(str, get_config_paths())))


@cli.command()
@click.option("--json/--no-json", default=False, help="Output in JSON format.")
@click.option('--json/--no-json', default=False, help='Output in JSON format.')
def status(json: bool):
"""Check current network login status."""
login_status = get_login_status()
Expand All @@ -61,15 +61,15 @@ def status(json: bool):
return

# Output in human-readable format
if login_status.get("user_name"):
if login_status.get('user_name'):
click.echo(
click.style("bitsrun: ", fg="green")
click.style('bitsrun: ', fg='green')
+ f"{login_status['user_name']} ({login_status['online_ip']}) is online"
)
print_status_table(login_status)
else:
click.echo(
click.style("bitsrun: ", fg="cyan")
click.style('bitsrun: ', fg='cyan')
+ f"{login_status['online_ip']} is offline"
)

Expand All @@ -78,20 +78,20 @@ def status(json: bool):
@add_options(_options)
def login(username, password, verbose):
"""Log into the BIT network."""
do_action("login", username, password, verbose)
do_action('login', username, password, verbose)


@cli.command()
@add_options(_options)
def logout(username, password, verbose):
"""Log out of the BIT network."""
do_action("logout", username, password, verbose)
do_action('logout', username, password, verbose)


def do_action(action, username, password, verbose):
# Support reading password from stdin when not passed via `--password`
if username and not password:
password = getpass(prompt="Please enter your password: ")
password = getpass(prompt='Please enter your password: ')

try:
# Try to read username and password from args provided. If none, look for config
Expand All @@ -101,25 +101,25 @@ def do_action(action, username, password, verbose):
elif conf := read_config():
if verbose:
click.echo(
click.style("bitsrun: ", fg="blue")
+ "Reading config from "
+ click.style(conf[1], fg="yellow", underline=True)
click.style('bitsrun: ', fg='blue')
+ 'Reading config from '
+ click.style(conf[1], fg='yellow', underline=True)
)
user = User(**conf[0])
else:
ctx = click.get_current_context()
ctx.fail("No username or password provided")
ctx.fail('No username or password provided')
sys.exit(1)

if action == "login":
if action == 'login':
resp = user.login()
message = f"{user.username} ({resp['online_ip']}) logged in"
elif action == "logout":
elif action == 'logout':
resp = user.logout()
message = f"{resp['online_ip']} logged out"
else:
# Should not reach here, but just in case
raise ValueError(f"Unknown action `{action}`")
raise ValueError(f'Unknown action `{action}`')

# Output direct result of the API response if verbose
if verbose:
Expand All @@ -128,11 +128,11 @@ def do_action(action, username, password, verbose):

# Handle error from API response. When field `error` is not `ok`, then the
# login/logout action has likely failed. Hints are provided in the `error_msg`.
if resp["error"] != "ok":
if resp['error'] != 'ok':
raise Exception(
resp["error_msg"]
if resp["error_msg"]
else "Action failed, use --verbose for more info"
resp['error_msg']
if resp['error_msg']
else 'Action failed, use --verbose for more info'
)

# Print success message
Expand All @@ -145,5 +145,5 @@ def do_action(action, username, password, verbose):
sys.exit(1)


if __name__ == "__main__":
if __name__ == '__main__':
cli()
14 changes: 7 additions & 7 deletions src/bitsrun/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from platformdirs import site_config_path, user_config_path

_APP_NAME = "bitsrun"
_APP_NAME = 'bitsrun'


def get_config_paths() -> map:
Expand Down Expand Up @@ -42,20 +42,20 @@ def get_config_paths() -> map:
]

# For backward compatibility
if not platform.startswith("win32"):
paths.insert(0, Path("/etc/"))
if not platform.startswith('win32'):
paths.insert(0, Path('/etc/'))

if platform.startswith("darwin"):
xdg_config_home = getenv("XDG_CONFIG_HOME", "")
if platform.startswith('darwin'):
xdg_config_home = getenv('XDG_CONFIG_HOME', '')
if xdg_config_home.strip():
paths.append(Path(xdg_config_home))
else:
paths.append(Path.home() / ".config")
paths.append(Path.home() / '.config')
paths.append(paths[-1] / _APP_NAME)
else:
paths.append(user_config_path())

return map(lambda path: path / "bit-user.json", paths)
return map(lambda path: path / 'bit-user.json', paths)


class ConfigType(TypedDict):
Expand Down
4 changes: 2 additions & 2 deletions src/bitsrun/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ class UserResponseType(TypedDict):
client_ip: str
online_ip: str
# Field `error` is also `login_error` when logout action fails
error: Union[Literal["login_error"], Literal["ok"]]
error: Union[Literal['login_error'], Literal['ok']]
error_msg: str
res: Union[Literal["login_error"], Literal["ok"]]
res: Union[Literal['login_error'], Literal['ok']]
# Field `username` is not present on login fails and all logout scenarios
username: Optional[str]

Expand Down
Loading