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

feat: add helper functions to parse input files #2918

Open
wants to merge 19 commits into
base: main
Choose a base branch
from

Conversation

fgvieira
Copy link
Contributor

@fgvieira fgvieira commented Jun 16, 2024

Add helper functions to parse input files. See example in snakemake/snakemake-wrappers#2725.

QC

  • The PR contains a test case for the changes or the changes are already covered by an existing test case.
  • The documentation (docs/) is updated to reflect the changes or this is not necessary (e.g. if the change does neither modify the language nor the behavior or functionalities of Snakemake).

Summary by CodeRabbit

Release Notes

  • New Features

    • Added advanced input parsing capabilities for Snakemake workflows
    • Introduced functions to extract checksums from input files
    • Enhanced input file handling with flexible parsing options
  • Documentation

    • Updated documentation with new input parsing and checksum extraction methods
  • Tests

    • Added test cases to validate new input parsing and checksum extraction functionality

Copy link

Quality Gate Passed Quality Gate passed

Issues
0 New issues
0 Accepted issues

Measures
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarCloud

docs/snakefiles/rules.rst Outdated Show resolved Hide resolved
docs/snakefiles/rules.rst Outdated Show resolved Hide resolved
Copy link

sonarqubecloud bot commented Aug 7, 2024

@johanneskoester
Copy link
Contributor

@fgvieira since PR #2927 is now merged and released, I think this PR can be revived and finalized?

@johanneskoester johanneskoester self-assigned this Jan 15, 2025
Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

📝 Walkthrough

Walkthrough

The pull request introduces two new utility functions, parse_input and extract_checksum, to enhance Snakemake's input handling capabilities. These functions are added to the documentation, implemented in the snakemake/ioutils/input.py module, and integrated into the global context. The changes include updating the initialization file, adding test cases, and providing example usage in the documentation. The new functions allow more flexible parsing of input files and extracting checksums from CSV-formatted files.

Changes

File Change Summary
docs/snakefiles/rules.rst Added documentation for two new functions: parse_input() and extract_checksum()
snakemake/ioutils/__init__.py Added imports for parse_input and extract_checksum to global context
snakemake/ioutils/input.py Implemented parse_input() and extract_checksum() functions for flexible input parsing
tests/test_ioutils/Snakefile Updated test Snakefile with new input handling and checksum extraction
tests/test_ioutils/samples.md5 Added new checksum entries for various TSV files
tests/test_ioutils/expected-results/* Updated expected result files to reflect new checksum handling

Sequence Diagram

sequenceDiagram
    participant User as Snakemake Workflow
    participant ParseInput as parse_input()
    participant ExtractChecksum as extract_checksum()
    participant InputFile as Input File

    User->>ParseInput: Call with input file and parser
    ParseInput->>InputFile: Open and read file
    alt No custom parser
        ParseInput-->>User: Return file content
    else Custom parser provided
        ParseInput->>ExtractChecksum: Apply parser function
        ExtractChecksum->>InputFile: Read specific data
        ExtractChecksum-->>ParseInput: Return parsed value
        ParseInput-->>User: Return parsed result
    end
Loading

The sequence diagram illustrates the workflow of the new parse_input() and extract_checksum() functions, showing how they can flexibly handle input file parsing with optional custom parsing logic.

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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
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

🧹 Nitpick comments (1)
snakemake/ioutils/input.py (1)

1-9: Add error handling for file operations.

The function should handle potential IOErrors when opening/reading the file and provide meaningful error messages.

 def parse_input(infile=None, parser=None, **kwargs):
     def inner(wildcards, input, output):
-        with open(infile, "r") as fh:
-            if parser is None:
-                return fh.read().strip()
-            else:
-                return parser(fh, **kwargs)
+        try:
+            with open(infile, "r") as fh:
+                if parser is None:
+                    return fh.read().strip()
+                else:
+                    return parser(fh, **kwargs)
+        except IOError as e:
+            raise WorkflowError(f"Error reading input file {infile}: {str(e)}")
     return inner
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7a75043 and 2e37b32.

📒 Files selected for processing (7)
  • docs/snakefiles/rules.rst (2 hunks)
  • snakemake/ioutils/__init__.py (2 hunks)
  • snakemake/ioutils/input.py (1 hunks)
  • tests/test_ioutils/Snakefile (4 hunks)
  • tests/test_ioutils/expected-results/c/1.txt (1 hunks)
  • tests/test_ioutils/expected-results/results/switch~someswitch.column~sample.txt (1 hunks)
  • tests/test_ioutils/samples.md5 (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • tests/test_ioutils/expected-results/c/1.txt
  • tests/test_ioutils/expected-results/results/switchsomeswitch.columnsample.txt
  • tests/test_ioutils/samples.md5
🧰 Additional context used
📓 Path-based instructions (2)
snakemake/ioutils/__init__.py (1)

Pattern **/*.py: Do not try to improve formatting.
Do not suggest type annotations for functions that are defined inside of functions or methods.
Do not suggest type annotation of the self argument of methods.
Do not suggest type annotation of the cls argument of classmethods.
Do not suggest return type annotation if a function or method does not contain a return statement.

snakemake/ioutils/input.py (1)

Pattern **/*.py: Do not try to improve formatting.
Do not suggest type annotations for functions that are defined inside of functions or methods.
Do not suggest type annotation of the self argument of methods.
Do not suggest type annotation of the cls argument of classmethods.
Do not suggest return type annotation if a function or method does not contain a return statement.

🪛 Ruff (0.8.2)
snakemake/ioutils/input.py

15-15: Do not assign a lambda expression, use a def

Rewrite fix_file_name as a def

(E731)

⏰ Context from checks skipped due to timeout of 90000ms (31)
  • GitHub Check: testing (10, 3.12)
  • GitHub Check: testing (10, 3.11)
  • GitHub Check: testing (9, 3.12)
  • GitHub Check: testing (9, 3.11)
  • GitHub Check: testing (8, 3.12)
  • GitHub Check: testing (8, 3.11)
  • GitHub Check: testing (7, 3.12)
  • GitHub Check: testing (7, 3.11)
  • GitHub Check: testing (6, 3.12)
  • GitHub Check: testing (6, 3.11)
  • GitHub Check: testing-windows (10)
  • GitHub Check: testing (5, 3.12)
  • GitHub Check: testing-windows (9)
  • GitHub Check: testing (5, 3.11)
  • GitHub Check: testing-windows (8)
  • GitHub Check: testing (4, 3.12)
  • GitHub Check: testing-windows (7)
  • GitHub Check: testing (4, 3.11)
  • GitHub Check: testing-windows (6)
  • GitHub Check: testing (3, 3.12)
  • GitHub Check: testing-windows (5)
  • GitHub Check: testing (3, 3.11)
  • GitHub Check: testing-windows (4)
  • GitHub Check: testing (2, 3.12)
  • GitHub Check: testing-windows (3)
  • GitHub Check: testing (2, 3.11)
  • GitHub Check: testing (1, 3.12)
  • GitHub Check: testing-windows (2)
  • GitHub Check: testing (1, 3.11)
  • GitHub Check: testing-windows (1)
  • GitHub Check: apidocs
🔇 Additional comments (3)
snakemake/ioutils/__init__.py (1)

8-8: LGTM!

The registration of new functions follows the established pattern correctly.

Also applies to: 25-26

tests/test_ioutils/Snakefile (1)

11-13: LGTM!

The test coverage is comprehensive and demonstrates proper usage of the new functionality.

Also applies to: 22-29

docs/snakefiles/rules.rst (1)

550-592: LGTM!

The documentation is clear, well-structured, and includes helpful examples.

Comment on lines +12 to +27
def extract_checksum(infile, **kwargs):
import pandas as pd

fix_file_name = lambda x: x.removeprefix("./")
return (
pd.read_csv(
infile,
sep=" ",
header=None,
engine="python",
converters={1: fix_file_name},
)
.set_index(1)
.loc[fix_file_name(kwargs.get("file"))]
.item()
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Multiple improvements needed for extract_checksum function.

  1. Replace lambda with a proper function per static analysis
  2. Add docstring and type hints
  3. Add error handling for pandas operations
+def fix_file_name(x: str) -> str:
+    """Remove ./ prefix from file names."""
+    return x.removeprefix("./")
+
+def extract_checksum(infile: str, **kwargs) -> str:
+    """Extract checksum from a CSV file.
+    
+    Args:
+        infile: Path to CSV file containing checksums
+        **kwargs: Additional arguments, must include 'file' key
+        
+    Returns:
+        str: The extracted checksum
+        
+    Raises:
+        WorkflowError: If file not found or checksum extraction fails
+    """
     import pandas as pd
-
-    fix_file_name = lambda x: x.removeprefix("./")
-    return (
-        pd.read_csv(
-            infile,
-            sep="  ",
-            header=None,
-            engine="python",
-            converters={1: fix_file_name},
-        )
-        .set_index(1)
-        .loc[fix_file_name(kwargs.get("file"))]
-        .item()
-    )
+    try:
+        df = pd.read_csv(
+                infile,
+                sep="  ",
+                header=None, 
+                engine="python",
+                converters={1: fix_file_name}
+            )
+        return df.set_index(1).loc[fix_file_name(kwargs["file"])].item()
+    except FileNotFoundError:
+        raise WorkflowError(f"Checksum file not found: {infile}")
+    except KeyError:
+        raise WorkflowError(f"File {kwargs['file']} not found in checksum file")
+    except Exception as e:
+        raise WorkflowError(f"Error extracting checksum: {str(e)}")

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

15-15: Do not assign a lambda expression, use a def

Rewrite fix_file_name as a def

(E731)

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.

2 participants