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

Rename some subcommands in line with tmc-cli #24

Merged
merged 4 commits into from
May 13, 2024
Merged

Conversation

madeddie
Copy link
Owner

@madeddie madeddie commented May 13, 2024

Prepare to add new subcommands

Summary by CodeRabbit

  • New Features
    • Added a function to parse specific task pages into Task objects.
  • Enhancements
    • Improved login command handling in the app.
  • Refactor
    • Updated logic for better user experience, including task list viewing and command handling.

Copy link
Contributor

coderabbitai bot commented May 13, 2024

Warning

Rate Limit Exceeded

@madeddie has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 56 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.

Commits Files that changed from the base of the PR and between 83a9c0e and 14faf25.

Walkthrough

The recent updates to the script have brought significant improvements, such as renaming functions for clarity, introducing subparsers for task management, and enhancing task list display by incorporating limits. The main function now supports a login command, and a new function facilitates the parsing of task details into structured objects.

Changes

File(s) Change Summary
moocfi_cses.py Renamed parser_config to parser_login, added subparsers parser_list and parser_show, updated main function to handle login command, and included limit parameter in print_task_list call.

🐇✨
In the land of code and night,
Changes come to bring new light.
Subparsers here, a function there,
Tailored tasks with utmost care.
Hop and leap with joy, alright! 🎉
🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@senior-dev-bot senior-dev-bot bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feedback from Senior Dev Bot

Comment on lines 332 to 338
datefmt="%Y-%m-%d %H:%M:%S",
)

if args.cmd == "configure":
if args.cmd == "login":
config = create_config()
write_config(args.config, config)
return

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE REVIEW

The change from "configure" to "login" in the conditional statement is clear. Ensure the rest of your application aligns with this new command naming to maintain consistency. Additionally, verify that all documentation and help messages reflect this change to avoid confusion for users.

Consider providing feedback or a success message to the user upon successful login or configuration update, enhancing the usability of your application.

if args.cmd == "login":
    config = create_config()
    write_config(args.config, config)
    print("Login successful. Configuration saved.")
    return

moocfi_cses.py Outdated
Comment on lines 368 to 374
if args.cmd == "list":
html = session.http_request(base_url)
task_list = parse_task_list(html)
print_task_list(task_list, filter=args.filter)
print_task_list(task_list, filter=args.filter, limit=args.limit)


if __name__ == "__main__":

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE REVIEW

The change properly extends the functionality of print_task_list by adding a limit parameter based on args.limit, maintaining readability and clear function usage. It's a practical update if print_task_list is already modified to handle this new limit parameter correctly. However, ensure args.limit is validated before use, especially for being a non-negative integer, to avoid runtime errors.

# Ensure args.limit is validated earlier in the code
if args.limit is not None and (not args.limit.isdigit() or int(args.limit) < 0):
    raise ValueError("Limit must be a non-negative integer.")

Comment on lines 323 to 328
...


# TODO: Implement function that parser the specific task page into Task object
def parse_task(html: str | bytes, task: Task) -> Task:
task = Task("a", "b", TaskState.COMPLETE)
return task


def main() -> None:
args = parse_args()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE REVIEW

The removed parse_task function was marked as a TODO, suggesting it was placeholder code. However, removing this function entirely without implementing or replacing its functionality might leave a gap in the application's capabilities, especially if other parts of the code depend on it. If the function's logic has been moved elsewhere or is no longer needed, ensure that this is documented or communicated to the team. If this function is to be implemented later, consider using clearer documentation or creating a ticket in your project tracking system to ensure it does not get forgotten.

# If the function is to be implemented later, consider keeping a placeholder or comment indicating future work
# TODO: Implement function that parses the specific task page into Task object
# Placeholder for future implementation

moocfi_cses.py Outdated
Comment on lines 298 to 319


# TODO: This should be part of a UI class or module
def print_task_list(task_list: list[Task], filter: Optional[str] = None) -> None:
def print_task_list(
task_list: list[Task], filter: Optional[str] = None, limit: Optional[int] = None
) -> None:
count: int = 0
for task in task_list:
if not filter or filter == task.state.value:
print(f"- {task.id}: {task.name} {TASK_STATE_ICON[task.state]}")
count += 1
if limit and count >= limit:
return


# TODO: Implement function that parser the specific task page into Task object
def parse_task(html: str | bytes, task: Task) -> Task:
task = Task("a", "b", TaskState.COMPLETE)
return task


# TODO: Implement function that posts the submit form with the correct file

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE REVIEW

  • For print_task_list, now that it has more responsibilities, consider refactoring it for single responsibility. Extract filtering and limiting logic into separate functions or within a class structure. For scalability and maintainability, this keeps functions more focused and simpler to manage.
def print_filtered_tasks(task_list: list[Task], filter: Optional[str] = None) -> list[Task]:
    ...
def print_limited_tasks(task_list: list[Task], limit: int) -> None:
    ...
  • The temporary default parameters ("a", "b") in parse_task should be replaced with actual logic for parsing HTML.

  • It's better to explicitly import or define what Task, TaskState, and TASK_STATE_ICON are to avoid confusion.

  • Consider adding type hints for the return type of parse_task.

  • Lastly, add more descriptive TODOs or implement the features to avoid ambiguity.

moocfi_cses.py Outdated
Comment on lines 130 to 155
)
subparsers = parser.add_subparsers(required=True)

parser_config = subparsers.add_parser("configure", help="Configure moocfi_cses")
parser_config.set_defaults(cmd="configure")
# login subparser
parser_login = subparsers.add_parser("login", help="Login to mooc.fi CSES")
parser_login.set_defaults(cmd="login")

# list exercises subparser
parser_list = subparsers.add_parser("list", help="List exercises")
parser_list.set_defaults(cmd="list")
parser_list.add_argument(
"--filter",
help="List complete, incomplete or all tasks (default: %(default)s)",
help="List only complete or incomplete tasks (default: all)",
choices=["complete", "incomplete"],
)
parser_list.add_argument(
"--limit", help="Maximum amount of items to list", type=int
)

# show exercise subparser
parser_show = subparsers.add_parser("show", help="Show details of an exercise")
parser_show.set_defaults(cmd="show")
parser_show.add_argument("task_id", help="Numerical task identifier or task name")

return parser.parse_args(args)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE REVIEW

Changes are well-directed towards enhancing the CLI tool's functionality by introducing new commands (login, list updates, show). However, for maintainability and scalability:

  1. Consistency in Help Messages:
    Ensure help messages maintain a consistent style in terms of sentence structure and capitalization. For example, "Login to mooc.fi CSES" starts with a capital letter, whereas others do not.

  2. Argument Choices for --filter:
    The update to --filter argument's help message is good but limiting choices to "complete" or "incomplete" and defaulting to "all" can be confusing since "all" is not a selectable option. Consider including "all" in the choices or adjust the implementation to handle its default behavior more intuitively.

  3. Extensibility of Argument Adding:
    For adding arguments to subparsers, consider creating a more modular approach if the subparsers and their arguments start to grow. This could involve defining a structure or configuration for commands and their arguments in a separate place and adding them in a loop, improving code readability and ease of updates.

    Example for a more consistent help message and including "all" in choices:

    parser_list.add_argument(
        "--filter",
        help="List only complete, incomplete, or all tasks (default: all)",
        choices=["complete", "incomplete", "all"],
    )

Copy link

============================= test session starts ==============================
platform linux -- Python 3.10.14, pytest-8.2.0, pluggy-1.5.0
rootdir: /home/runner/work/moocfi_cses/moocfi_cses
plugins: requests-mock-1.12.1, cov-5.0.0
collected 11 items

tests/test_moocfi_cses.py ...........                                    [100%]

---------- coverage: platform linux, python 3.10.14-final-0 ----------
Name                        Stmts   Miss  Cover
-----------------------------------------------
moocfi_cses.py                193     98    49%
tests/__init__.py               0      0   100%
tests/test_moocfi_cses.py      48      0   100%
-----------------------------------------------
TOTAL                         241     98    59%


============================== 11 passed in 0.11s ==============================

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between f3c0f00 and 760dcc9.
Files selected for processing (1)
  • moocfi_cses.py (5 hunks)
Additional comments not posted (2)
moocfi_cses.py (2)

133-152: The modifications to parse_args introduce new subparsers and arguments as intended. Ensure integration tests cover these changes.

Verification successful

The modifications to parse_args and the integration of new subparsers appear to be correctly implemented and are accompanied by tests. It is recommended to review the specific test cases in tests/test_moocfi_cses.py to ensure comprehensive coverage and correct behavior.

  • moocfi_cses.py: Implementation of parse_args with new subparsers.
  • tests/test_moocfi_cses.py: Contains tests for parse_args, including scenarios for missing arguments and specific commands like "list".
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration of new subparsers with the application.

# Test: Check if the new subparsers are correctly integrated and functioning.
rg --type python $'parse_args'

Length of output: 60



Script:

#!/bin/bash
# Description: Verify integration of new subparsers with the application.

# Test: Check if the new subparsers are correctly integrated and functioning.
rg --type py 'parse_args'

Length of output: 465


301-311: The addition of the limit parameter in print_task_list enhances functionality. Verify that the limit parameter is correctly handled in all scenarios.

Verification successful

The verification process confirms that the limit parameter in the print_task_list function is correctly handled. The function definition and its usage in the codebase both respect the limit on the number of tasks displayed, aligning with the intended functionality.

  • Function Definition: Located in moocfi_cses.py, the function correctly implements a check to stop printing tasks once the specified limit is reached.
  • Function Usage: Also in moocfi_cses.py, the function is called with limit being passed appropriately, ensuring that the functionality is integrated correctly with other parts of the application.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify correct handling of the `limit` parameter in `print_task_list`.

# Test: Check if the `limit` parameter correctly limits the number of tasks displayed.
rg --type python $'print_task_list'

Length of output: 65



Script:

#!/bin/bash
# Description: Verify correct handling of the `limit` parameter in `print_task_list`.

# Corrected Test: Check if the `limit` parameter correctly limits the number of tasks displayed.
# Using 'rg' without specifying file type to include all files, or could specify '--type py' for Python files specifically.
rg 'print_task_list' --type py

Length of output: 154

moocfi_cses.py Outdated
Comment on lines 314 to 316
def parse_task(html: str | bytes, task: Task) -> Task:
task = Task("a", "b", TaskState.COMPLETE)
return task
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function parse_task appears to be incomplete, returning a hardcoded Task object.

Would you like assistance in implementing this function, or should I open a GitHub issue to track this task?

Copy link

============================= test session starts ==============================
platform linux -- Python 3.10.14, pytest-8.2.0, pluggy-1.5.0
rootdir: /home/runner/work/moocfi_cses/moocfi_cses
plugins: requests-mock-1.12.1, cov-5.0.0
collected 11 items

tests/test_moocfi_cses.py .....FF....                                    [100%]

=================================== FAILURES ===================================
____________________________ test_login_successful _____________________________

mock_session = Session(username='[email protected]', password='test_password', base_url='https://example.com', cookies={})

    def test_login_successful(mock_session: moocfi_cses.Session) -> None:
        # Mocking the HTTP response for successful login
        with requests_mock.Mocker() as m:
            m.get(
                "https://example.com",
                text='<a class="account" href="/user/1234">[email protected] (mooc.fi)</a>',
            )
>           mock_session.login()

tests/test_moocfi_cses.py:70: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
moocfi_cses.py:55: in login
    if self.is_logged_in:
moocfi_cses.py:39: in is_logged_in
    html = self.http_request(urljoin(self.base_url, "list"))
moocfi_cses.py:105: in http_request
    res = self.http_session.get(url)
/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests/sessions.py:602: in get
    return self.request("GET", url, **kwargs)
/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests/sessions.py:589: in request
    resp = self.send(prep, **send_kwargs)
/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests_mock/mocker.py:185: in _fake_send
    return _original_send(session, request, **kwargs)
/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests/sessions.py:703: in send
    r = adapter.send(request, **kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <requests_mock.adapter.Adapter object at 0x7f3eb53b30d0>
request = <requests_mock.request._RequestObjectProxy object at 0x7f3eb53b11b0>
kwargs = {'cert': None, 'proxies': OrderedDict(), 'stream': False, 'timeout': None, ...}
matcher = <requests_mock.adapter._Matcher object at 0x7f3eb53b2dd0>, resp = None

    def send(self, request, **kwargs):
        request = _RequestObjectProxy(request,
                                      case_sensitive=self._case_sensitive,
                                      **kwargs)
        self._add_to_history(request)
    
        for matcher in reversed(self._matchers):
            try:
                resp = matcher(request)
            except Exception:
                request._matcher = weakref.ref(matcher)
                raise
    
            if resp is not None:
                request._matcher = weakref.ref(matcher)
                resp.connection = self
                logger.debug('{} {} {}'.format(request._request.method,
                                               request._request.url,
                                               resp.status_code))
                return resp
    
>       raise exceptions.NoMockAddress(request)
E       requests_mock.exceptions.NoMockAddress: No mock address: GET https://example.com/list

/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests_mock/adapter.py:261: NoMockAddress
______________________________ test_login_failed _______________________________

mock_session = Session(username='[email protected]', password='test_password', base_url='https://example.com', cookies={})

    def test_login_failed(mock_session: moocfi_cses.Session) -> None:
        # Mocking the HTTP response for failed login
        with requests_mock.Mocker() as m:
            m.get(
                "https://example.com",
                text='<a class="account" href="/login/oauth-redirect?site=mooc.fi">Login using mooc.fi</a>',
            )
            m.get("https://example.com/account", text="Login required")
            m.get("https://example.com/login/oauth-redirect?site=mooc.fi", text="")
            with pytest.raises(ValueError):
>               mock_session.login()

tests/test_moocfi_cses.py:84: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
moocfi_cses.py:55: in login
    if self.is_logged_in:
moocfi_cses.py:39: in is_logged_in
    html = self.http_request(urljoin(self.base_url, "list"))
moocfi_cses.py:105: in http_request
    res = self.http_session.get(url)
/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests/sessions.py:602: in get
    return self.request("GET", url, **kwargs)
/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests/sessions.py:589: in request
    resp = self.send(prep, **send_kwargs)
/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests_mock/mocker.py:185: in _fake_send
    return _original_send(session, request, **kwargs)
/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests/sessions.py:703: in send
    r = adapter.send(request, **kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <requests_mock.adapter.Adapter object at 0x7f3eb59b70d0>
request = <requests_mock.request._RequestObjectProxy object at 0x7f3eb59b5780>
kwargs = {'cert': None, 'proxies': OrderedDict(), 'stream': False, 'timeout': None, ...}
matcher = <requests_mock.adapter._Matcher object at 0x7f3eb59b58d0>, resp = None

    def send(self, request, **kwargs):
        request = _RequestObjectProxy(request,
                                      case_sensitive=self._case_sensitive,
                                      **kwargs)
        self._add_to_history(request)
    
        for matcher in reversed(self._matchers):
            try:
                resp = matcher(request)
            except Exception:
                request._matcher = weakref.ref(matcher)
                raise
    
            if resp is not None:
                request._matcher = weakref.ref(matcher)
                resp.connection = self
                logger.debug('{} {} {}'.format(request._request.method,
                                               request._request.url,
                                               resp.status_code))
                return resp
    
>       raise exceptions.NoMockAddress(request)
E       requests_mock.exceptions.NoMockAddress: No mock address: GET https://example.com/list

/opt/hostedtoolcache/Python/3.10.14/x64/lib/python3.10/site-packages/requests_mock/adapter.py:261: NoMockAddress

---------- coverage: platform linux, python 3.10.14-final-0 ----------
Name                        Stmts   Miss  Cover
-----------------------------------------------
moocfi_cses.py                219    136    38%
tests/__init__.py               0      0   100%
tests/test_moocfi_cses.py      48      1    98%
-----------------------------------------------
TOTAL                         267    137    49%

=========================== short test summary info ============================
FAILED tests/test_moocfi_cses.py::test_login_successful - requests_mock.exceptions.NoMockAddress: No mock address: GET https://example.com/list
FAILED tests/test_moocfi_cses.py::test_login_failed - requests_mock.exceptions.NoMockAddress: No mock address: GET https://example.com/list
========================= 2 failed, 9 passed in 0.23s ==========================

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Out of diff range and nitpick comments (1)
moocfi_cses.py (1)

Line range hint 58-83: Refactor the login method to reduce complexity and improve error handling.

def login(self) -> None:
    """Logs into the site using webscraping."""
    if self.is_logged_in:
        return

    res = self.http_session.get(urljoin(self.base_url, "list"))
    login_link = find_link(res.text, './/a[@class="account"]')
    if not login_link:
        logging.debug(f"url: {res.url}, status: {res.status_code}\nhtml:\n{res.text}")
        raise ValueError("Failed to find login url")

    login_url = urljoin(res.url, login_link.get("href"))
    res = self.http_session.get(login_url, headers={"referer": res.url})
    login_form = parse_form(res.text, ".//form")
    if not login_form:
        logging.debug(f"url: {res.url}, status: {res.status_code}\nhtml:\n{res.text}")
        raise ValueError("Failed to find login form")

    login_form["session[login]"] = self.username
    login_form["session[password]"] = self.password
    self.http_session.post(url=urljoin(res.url, login_form.pop("_action")), headers={"referer": res.url}, data=login_form)

    if not self.is_logged_in:
        logging.debug(f"url: {res.url}, status: {res.status_code}\nhtml:\n{res.text}")
        raise ValueError("Login failed")
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 760dcc9 and 106003e.
Files selected for processing (1)
  • moocfi_cses.py (11 hunks)
Additional comments not posted (1)
moocfi_cses.py (1)

39-39: Ensure that the login check is robust against changes in the webpage structure.

Comment on lines +13 to +16
from urllib.parse import urljoin
from pathlib import Path
from typing import AnyStr, Optional
from xml.etree.ElementTree import Element, tostring
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider consolidating imports from the same module.

- from urllib.parse import urljoin
- from pathlib import Path
- from typing import AnyStr, Optional
+ from urllib.parse import urljoin
+ from pathlib import Path
+ from typing import AnyStr, Optional

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
from urllib.parse import urljoin
from pathlib import Path
from typing import AnyStr, Optional
from xml.etree.ElementTree import Element, tostring
from urllib.parse import urljoin
from pathlib import Path
from typing import AnyStr, Optional
from xml.etree.ElementTree import Element, tostring

Comment on lines +135 to +154
# login subparser
parser_login = subparsers.add_parser("login", help="Login to mooc.fi CSES")
parser_login.set_defaults(cmd="login")

# list exercises subparser
parser_list = subparsers.add_parser("list", help="List exercises")
parser_list.set_defaults(cmd="list")
parser_list.add_argument(
"--filter",
help="List complete, incomplete or all tasks (default: %(default)s)",
help="List only complete or incomplete tasks (default: all)",
choices=["complete", "incomplete"],
)
parser_list.add_argument(
"--limit", help="Maximum amount of items to list", type=int
)

# show exercise subparser
parser_show = subparsers.add_parser("show", help="Show details of an exercise")
parser_show.set_defaults(cmd="show")
parser_show.add_argument("task_id", help="Numerical task identifier")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure consistency in the help messages and argument choices for subparsers.

parser_login = subparsers.add_parser("login", help="Login to mooc.fi CSES")
parser_list = subparsers.add_parser("list", help="List exercises")
parser_show = subparsers.add_parser("show", help="Show details of an exercise")

Comment on lines +306 to +316
def print_task_list(
task_list: list[Task], filter: Optional[str] = None, limit: Optional[int] = None
) -> None:
count: int = 0
for task in task_list:
if not filter or filter == task.state.value:
print(f"- {task.id}: {task.name} {TASK_STATE_ICON[task.state]}")
count += 1
if limit and count >= limit:
return

Copy link
Contributor

@coderabbitai coderabbitai bot May 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider refactoring print_task_list to separate filtering and limiting logic into different functions.

def print_filtered_tasks(task_list: list[Task], filter: Optional[str] = None) -> list[Task]:
    return [task for task in task_list if not filter or filter == task.state.value]

def print_limited_tasks(filtered_tasks: list[Task], limit: Optional[int] = None) -> None:
    for count, task in enumerate(filtered_tasks, 1):
        print(f"- {task.id}: {task.name} {TASK_STATE_ICON[task.state]}")
        if limit and count >= limit:
            break

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai make a github issue for this please

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@madeddie, the GitHub issue has been successfully created for refactoring the print_task_list function to separate the filtering and limiting logic. You can view and track the issue here.

Analysis chain
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Create a GitHub issue for refactoring the print_task_list function
gh issue create \
  --title "Refactor print_task_list to separate filtering and limiting logic" \
  --body "It's suggested to refactor the `print_task_list` function to separate the filtering and limiting logic into different functions for better readability and maintainability. This change can help in managing the tasks more efficiently and make the codebase cleaner.

Related PR: https://github.com/madeddie/moocfi_cses/pull/24
Comment: https://github.com/madeddie/moocfi_cses/pull/24#discussion_r1598756440" \
  --repo madeddie/moocfi_cses

Length of output: 672

moocfi_cses.py Outdated
Comment on lines 320 to 352
def parse_task(html: str | bytes) -> Task:
root = htmlement.fromstring(html)
task_link_element = root.find('.//div[@class="nav sidebar"]/a')
task_link = task_link_element if task_link_element is not None else Element("a")
task_id = task_link.get("href", "").split("/")[-1]
task_name = task_link.text or "N/A"
task_span_element = task_link.find("span")
task_span = task_span_element if task_span_element is not None else Element("span")
task_span_class = task_span.get("class", "")
desc_div_element = root.find('.//div[@class="md"]')
desc_div = desc_div_element if desc_div_element is not None else Element("div")
description = html2text(tostring(desc_div).decode("utf8"))
code = root.findtext(".//pre", "N/A")
submit_file = next(
iter(
[
code_element.text
for code_element in root.findall(".//code")
if code_element.text is not None and ".py" in code_element.text
]
),
"N/A",
)
task = Task(
id=task_id,
name=task_name,
state=TaskState.COMPLETE if "full" in task_span_class else TaskState.INCOMPLETE,
description=description.strip(),
code=code,
submit_file=submit_file,
)

return task
Copy link
Contributor

@coderabbitai coderabbitai bot May 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

The parse_task function in moocfi_cses.py does not include exception handling mechanisms. This could lead to unhandled errors if unexpected input or conditions are encountered during its execution. It is recommended to implement try-except blocks to manage potential exceptions effectively, especially given the function's interaction with external data (HTML parsing and attribute access).

  • Consider wrapping sections of the code that parse HTML and access attributes in try-except blocks to handle possible exceptions like AttributeError or parsing errors.
  • It may also be beneficial to validate the existence and correctness of the HTML structure before attempting to parse it.
Analysis chain

Ensure that parse_task handles exceptions and edge cases effectively.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that `parse_task` handles exceptions and edge cases effectively.

# Test: Search for exception handling in `parse_task`.
rg --type python $'try:|except'

Length of output: 63



Script:

#!/bin/bash
# Description: Verify that `parse_task` handles exceptions and edge cases effectively.

# Corrected Test: Search for exception handling in `parse_task`.
rg --type py $'try:|except'

Length of output: 276

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai make a github issue for this please

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@madeddie, the GitHub issue has been successfully created to address the lack of exception handling in the parse_task function of the moocfi_cses.py file. You can view and track the issue here. If there's anything else you need, feel free to ask!

Analysis chain
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Create a GitHub issue regarding the lack of exception handling in the `parse_task` function.

gh issue create \
  --title "Add Exception Handling to parse_task Function" \
  --body "The `parse_task` function in `moocfi_cses.py` currently lacks proper exception handling mechanisms. This could lead to unhandled errors if unexpected input or conditions are encountered during its execution, especially given the function's interaction with external data (HTML parsing and attribute access). It is recommended to implement try-except blocks to manage potential exceptions effectively, and to validate the existence and correctness of the HTML structure before attempting to parse it. This issue was identified in the context of PR https://github.com/madeddie/moocfi_cses/pull/24." \
  --repo madeddie/moocfi_cses

Length of output: 923

Copy link

============================= test session starts ==============================
platform linux -- Python 3.10.14, pytest-8.2.0, pluggy-1.5.0
rootdir: /home/runner/work/moocfi_cses/moocfi_cses
plugins: requests-mock-1.12.1, cov-5.0.0
collected 11 items

tests/test_moocfi_cses.py ...........                                    [100%]

---------- coverage: platform linux, python 3.10.14-final-0 ----------
Name                        Stmts   Miss  Cover
-----------------------------------------------
moocfi_cses.py                219    118    46%
tests/__init__.py               0      0   100%
tests/test_moocfi_cses.py      48      0   100%
-----------------------------------------------
TOTAL                         267    118    56%


============================== 11 passed in 0.10s ==============================

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 106003e and 83a9c0e.
Files selected for processing (1)
  • tests/test_moocfi_cses.py (3 hunks)
Files skipped from review due to trivial changes (1)
  • tests/test_moocfi_cses.py

Copy link

============================= test session starts ==============================
platform linux -- Python 3.10.14, pytest-8.2.0, pluggy-1.5.0
rootdir: /home/runner/work/moocfi_cses/moocfi_cses
plugins: requests-mock-1.12.1, cov-5.0.0
collected 11 items

tests/test_moocfi_cses.py ...........                                    [100%]

---------- coverage: platform linux, python 3.10.14-final-0 ----------
Name                        Stmts   Miss  Cover
-----------------------------------------------
moocfi_cses.py                219    118    46%
tests/__init__.py               0      0   100%
tests/test_moocfi_cses.py      48      0   100%
-----------------------------------------------
TOTAL                         267    118    56%


============================== 11 passed in 0.10s ==============================

@madeddie madeddie merged commit b5bf07c into main May 13, 2024
1 check passed
@madeddie madeddie deleted the add_subcommands branch May 13, 2024 16:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant