example_name
stringlengths 10
28
| python_file
stringlengths 9
32
| python_code
stringlengths 490
18.2k
| rust_code
stringlengths 0
434
| has_rust
bool 2
classes | category
stringlengths 2
20
| python_lines
int32 13
586
| rust_lines
int32 0
6
| blocking_features
listlengths 0
7
| suspiciousness
float32 0
0.95
| error
stringlengths 33
500
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|
example_abs
|
abs_tool.py
|
#!/usr/bin/env python3
"""Abs Example - Absolute value operations CLI.
Examples:
>>> compute_abs_int(-5)
5
>>> compute_abs_int(5)
5
>>> compute_abs_float(-3.14)
3.14
>>> compute_abs_float(2.71)
2.71
"""
import argparse
def compute_abs_int(x: int) -> int:
"""Compute absolute value of integer.
>>> compute_abs_int(-10)
10
>>> compute_abs_int(0)
0
>>> compute_abs_int(42)
42
"""
if x < 0:
return -x
return x
def compute_abs_float(x: float) -> float:
"""Compute absolute value of float.
>>> compute_abs_float(-2.5)
2.5
>>> compute_abs_float(0.0)
0.0
>>> compute_abs_float(1.5)
1.5
"""
if x < 0:
return -x
return x
def main():
parser = argparse.ArgumentParser(description="Absolute value tool")
subs = parser.add_subparsers(dest="cmd", required=True)
i = subs.add_parser("int")
i.add_argument("x", type=int)
f = subs.add_parser("float")
f.add_argument("x", type=float)
args = parser.parse_args()
if args.cmd == "int":
print(compute_abs_int(args.x))
elif args.cmd == "float":
print(compute_abs_float(args.x))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_abs/abs_tool.py (1236 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_abs/abs_tool.rs (2536 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_abs/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 25.1 KB/s
⏱️ Total time: 48ms
| true
|
abs
| 65
| 6
|
[] | 0
| null |
example_abs
|
test_abs_tool.py
|
"""Tests for abs_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "abs_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_int_positive():
r = run("int 5")
assert r.returncode == 0
assert r.stdout.strip() == "5"
def test_int_negative():
r = run("int -42")
assert r.returncode == 0
assert r.stdout.strip() == "42"
def test_float_positive():
r = run("float 3.14")
assert r.returncode == 0
assert r.stdout.strip() == "3.14"
def test_float_negative():
r = run("float -2.5")
assert r.returncode == 0
assert r.stdout.strip() == "2.5"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_abs/test_abs_tool.py (747 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_abs/test_abs_tool.rs (2077 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_abs/Cargo.toml (2 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 14.7 KB/s
⏱️ Total time: 49ms
| true
|
abs
| 38
| 6
|
[] | 0
| null |
example_age_calculator
|
age_cli.py
|
#!/usr/bin/env python3
"""Age calculator CLI.
Calculate age and related date information.
"""
import argparse
import sys
from datetime import date, datetime
def parse_date(date_str: str) -> date | None:
"""Parse date string into date object."""
formats = [
"%Y-%m-%d",
"%d/%m/%Y",
"%m/%d/%Y",
"%Y/%m/%d",
"%d-%m-%Y",
]
for fmt in formats:
try:
return datetime.strptime(date_str, fmt).date()
except ValueError:
continue
return None
def calculate_age(birth_date: date, as_of: date | None = None) -> dict:
"""Calculate age in years, months, days."""
if as_of is None:
as_of = date.today()
# Calculate years
years = as_of.year - birth_date.year
# Adjust if birthday hasn't occurred this year
if (as_of.month, as_of.day) < (birth_date.month, birth_date.day):
years -= 1
# Calculate months
months = as_of.month - birth_date.month
if as_of.day < birth_date.day:
months -= 1
if months < 0:
months += 12
# Calculate days
days = as_of.day - birth_date.day
if days < 0:
# Get days in previous month
prev_month = as_of.month - 1 if as_of.month > 1 else 12
prev_year = as_of.year if as_of.month > 1 else as_of.year - 1
days_in_prev = days_in_month(prev_year, prev_month)
days += days_in_prev
return {
"years": years,
"months": months,
"days": days,
}
def days_in_month(year: int, month: int) -> int:
"""Get number of days in a month."""
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
if month in [4, 6, 9, 11]:
return 30
# February
if is_leap_year(year):
return 29
return 28
def is_leap_year(year: int) -> bool:
"""Check if year is a leap year."""
if year % 400 == 0:
return True
if year % 100 == 0:
return False
if year % 4 == 0:
return True
return False
def total_days(birth_date: date, as_of: date | None = None) -> int:
"""Calculate total days lived."""
if as_of is None:
as_of = date.today()
return (as_of - birth_date).days
def next_birthday(birth_date: date, as_of: date | None = None) -> date:
"""Calculate next birthday."""
if as_of is None:
as_of = date.today()
# Try this year
try:
this_year = date(as_of.year, birth_date.month, birth_date.day)
except ValueError:
# Feb 29 in non-leap year
this_year = date(as_of.year, 3, 1)
if this_year > as_of:
return this_year
# Next year
try:
return date(as_of.year + 1, birth_date.month, birth_date.day)
except ValueError:
return date(as_of.year + 1, 3, 1)
def days_until_birthday(birth_date: date, as_of: date | None = None) -> int:
"""Days until next birthday."""
if as_of is None:
as_of = date.today()
return (next_birthday(birth_date, as_of) - as_of).days
def zodiac_sign(birth_date: date) -> str:
"""Get zodiac sign for birth date."""
month = birth_date.month
day = birth_date.day
signs = [
(1, 20, "Capricorn"),
(2, 19, "Aquarius"),
(3, 20, "Pisces"),
(4, 20, "Aries"),
(5, 21, "Taurus"),
(6, 21, "Gemini"),
(7, 22, "Cancer"),
(8, 23, "Leo"),
(9, 23, "Virgo"),
(10, 23, "Libra"),
(11, 22, "Scorpio"),
(12, 22, "Sagittarius"),
]
for end_month, end_day, sign in signs:
if month == end_month and day <= end_day:
return sign
if month < end_month:
# Return previous sign
idx = signs.index((end_month, end_day, sign))
return signs[idx - 1][2]
return "Capricorn"
def day_of_week(d: date) -> str:
"""Get day of week name."""
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
return days[d.weekday()]
def format_age(age: dict) -> str:
"""Format age dict for display."""
parts = []
if age["years"] > 0:
parts.append(f"{age['years']} year{'s' if age['years'] != 1 else ''}")
if age["months"] > 0:
parts.append(f"{age['months']} month{'s' if age['months'] != 1 else ''}")
if age["days"] > 0 or not parts:
parts.append(f"{age['days']} day{'s' if age['days'] != 1 else ''}")
return ", ".join(parts)
def main() -> int:
parser = argparse.ArgumentParser(description="Calculate age and date information")
parser.add_argument("birthdate", help="Birth date (YYYY-MM-DD)")
parser.add_argument("--as-of", metavar="DATE", help="Calculate as of date (default: today)")
parser.add_argument("--days", action="store_true", help="Show total days")
parser.add_argument("--next", action="store_true", help="Show next birthday")
parser.add_argument("--zodiac", action="store_true", help="Show zodiac sign")
parser.add_argument("--json", action="store_true", help="Output as JSON")
args = parser.parse_args()
birth = parse_date(args.birthdate)
if not birth:
print(f"Invalid date format: {args.birthdate}", file=sys.stderr)
return 1
as_of = None
if args.as_of:
as_of = parse_date(args.as_of)
if not as_of:
print(f"Invalid date format: {args.as_of}", file=sys.stderr)
return 1
age = calculate_age(birth, as_of)
if args.json:
import json
result = {
"birth_date": str(birth),
"age": age,
"total_days": total_days(birth, as_of),
"next_birthday": str(next_birthday(birth, as_of)),
"days_until_birthday": days_until_birthday(birth, as_of),
"zodiac": zodiac_sign(birth),
"birth_day": day_of_week(birth),
}
print(json.dumps(result, indent=2))
return 0
if args.days:
print(total_days(birth, as_of))
return 0
if args.next:
nb = next_birthday(birth, as_of)
days = days_until_birthday(birth, as_of)
print(f"Next birthday: {nb} ({days} days)")
return 0
if args.zodiac:
print(zodiac_sign(birth))
return 0
# Default: show full info
print(f"Birth date: {birth} ({day_of_week(birth)})")
print(f"Age: {format_age(age)}")
print(f"Total days: {total_days(birth, as_of):,}")
print(f"Zodiac: {zodiac_sign(birth)}")
nb = next_birthday(birth, as_of)
days = days_until_birthday(birth, as_of)
print(f"Next birthday: {nb} ({days} days away)")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_age_calculator/age_cli.py (6645 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_age_calculator/age_cli.rs (14113 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_age_calculator/Cargo.toml (4 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 117.4 KB/s
⏱️ Total time: 55ms
| true
|
age_calculator
| 241
| 6
|
[
"exception_handling"
] | 0.577
| null |
example_age_calculator
|
test_age_cli.py
|
"""Tests for age_cli.py"""
from datetime import date
from age_cli import (
calculate_age,
day_of_week,
days_in_month,
days_until_birthday,
format_age,
is_leap_year,
next_birthday,
parse_date,
total_days,
zodiac_sign,
)
class TestParseDate:
def test_iso_format(self):
result = parse_date("2000-01-15")
assert result == date(2000, 1, 15)
def test_slash_dmy(self):
result = parse_date("15/01/2000")
assert result == date(2000, 1, 15)
def test_slash_mdy(self):
result = parse_date("01/15/2000")
assert result == date(2000, 1, 15)
def test_invalid(self):
assert parse_date("not a date") is None
assert parse_date("2000-13-01") is None
class TestIsLeapYear:
def test_leap_year_divisible_by_4(self):
assert is_leap_year(2020) is True
def test_not_leap_divisible_by_100(self):
assert is_leap_year(1900) is False
def test_leap_divisible_by_400(self):
assert is_leap_year(2000) is True
def test_not_leap(self):
assert is_leap_year(2023) is False
class TestDaysInMonth:
def test_january(self):
assert days_in_month(2023, 1) == 31
def test_april(self):
assert days_in_month(2023, 4) == 30
def test_february_normal(self):
assert days_in_month(2023, 2) == 28
def test_february_leap(self):
assert days_in_month(2024, 2) == 29
class TestCalculateAge:
def test_exact_years(self):
birth = date(2000, 6, 15)
as_of = date(2023, 6, 15)
result = calculate_age(birth, as_of)
assert result["years"] == 23
assert result["months"] == 0
assert result["days"] == 0
def test_before_birthday(self):
birth = date(2000, 6, 15)
as_of = date(2023, 6, 10)
result = calculate_age(birth, as_of)
assert result["years"] == 22
def test_after_birthday(self):
birth = date(2000, 6, 15)
as_of = date(2023, 6, 20)
result = calculate_age(birth, as_of)
assert result["years"] == 23
assert result["days"] == 5
def test_months_calculation(self):
birth = date(2000, 1, 15)
as_of = date(2000, 4, 15)
result = calculate_age(birth, as_of)
assert result["years"] == 0
assert result["months"] == 3
assert result["days"] == 0
class TestTotalDays:
def test_simple(self):
birth = date(2000, 1, 1)
as_of = date(2000, 1, 11)
assert total_days(birth, as_of) == 10
def test_year(self):
birth = date(2000, 1, 1)
as_of = date(2001, 1, 1)
assert total_days(birth, as_of) == 366 # 2000 is leap year
class TestNextBirthday:
def test_this_year(self):
birth = date(2000, 12, 25)
as_of = date(2023, 6, 1)
result = next_birthday(birth, as_of)
assert result == date(2023, 12, 25)
def test_next_year(self):
birth = date(2000, 1, 15)
as_of = date(2023, 6, 1)
result = next_birthday(birth, as_of)
assert result == date(2024, 1, 15)
def test_today(self):
birth = date(2000, 6, 15)
as_of = date(2023, 6, 15)
result = next_birthday(birth, as_of)
# Birthday is today, so next is next year
assert result == date(2024, 6, 15)
class TestDaysUntilBirthday:
def test_same_month(self):
birth = date(2000, 6, 20)
as_of = date(2023, 6, 15)
result = days_until_birthday(birth, as_of)
assert result == 5
class TestZodiacSign:
def test_aries(self):
assert zodiac_sign(date(2000, 4, 10)) == "Aries"
def test_taurus(self):
assert zodiac_sign(date(2000, 5, 5)) == "Taurus"
def test_cancer(self):
assert zodiac_sign(date(2000, 7, 15)) == "Cancer"
def test_capricorn_december(self):
assert zodiac_sign(date(2000, 12, 25)) == "Capricorn"
def test_capricorn_january(self):
assert zodiac_sign(date(2000, 1, 10)) == "Capricorn"
class TestDayOfWeek:
def test_monday(self):
assert day_of_week(date(2023, 12, 25)) == "Monday"
def test_friday(self):
assert day_of_week(date(2023, 12, 29)) == "Friday"
class TestFormatAge:
def test_full(self):
age = {"years": 25, "months": 3, "days": 10}
result = format_age(age)
assert "25 years" in result
assert "3 months" in result
assert "10 days" in result
def test_singular(self):
age = {"years": 1, "months": 1, "days": 1}
result = format_age(age)
assert "1 year" in result
assert "1 month" in result
assert "1 day" in result
def test_zero_years(self):
age = {"years": 0, "months": 6, "days": 15}
result = format_age(age)
assert "year" not in result
assert "6 months" in result
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_age_calculator/test_age_cli.py (4878 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_age_calculator/test_age_cli.rs (10133 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_age_calculator/Cargo.toml (1 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 89.2 KB/s
⏱️ Total time: 53ms
| true
|
age_calculator
| 181
| 6
|
[
"class_definition"
] | 0.612
| null |
example_any_all
|
any_all_tool.py
|
#!/usr/bin/env python3
"""Any All Example - Any/all operations CLI.
Examples:
>>> check_any(0, 0, 1, 0)
True
>>> check_all(1, 1, 1, 1)
True
"""
import argparse
def check_any(a: int, b: int, c: int, d: int) -> bool:
"""Check if any value is truthy.
>>> check_any(0, 0, 0, 0)
False
>>> check_any(1, 0, 0, 0)
True
>>> check_any(0, 0, 0, 1)
True
"""
return a != 0 or b != 0 or c != 0 or d != 0
def check_all(a: int, b: int, c: int, d: int) -> bool:
"""Check if all values are truthy.
>>> check_all(1, 1, 1, 1)
True
>>> check_all(1, 1, 1, 0)
False
>>> check_all(0, 0, 0, 0)
False
"""
return a != 0 and b != 0 and c != 0 and d != 0
def main():
parser = argparse.ArgumentParser(description="Any/all operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
a = subs.add_parser("any")
a.add_argument("a", type=int)
a.add_argument("b", type=int)
a.add_argument("c", type=int)
a.add_argument("d", type=int)
al = subs.add_parser("all")
al.add_argument("a", type=int)
al.add_argument("b", type=int)
al.add_argument("c", type=int)
al.add_argument("d", type=int)
args = parser.parse_args()
if args.cmd == "any":
print("true" if check_any(args.a, args.b, args.c, args.d) else "false")
elif args.cmd == "all":
print("true" if check_all(args.a, args.b, args.c, args.d) else "false")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_any_all/any_all_tool.py (1498 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_any_all/any_all_tool.rs (2238 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_any_all/Cargo.toml (1 dependencies)
⏱️ Parse time: 58ms
📊 Throughput: 24.8 KB/s
⏱️ Total time: 59ms
| true
|
any_all
| 63
| 6
|
[] | 0
| null |
example_any_all
|
test_any_all_tool.py
|
"""Tests for any_all_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "any_all_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_any_true():
r = run("any 0 0 1 0")
assert r.returncode == 0
assert r.stdout.strip() == "true"
def test_any_false():
r = run("any 0 0 0 0")
assert r.returncode == 0
assert r.stdout.strip() == "false"
def test_all_true():
r = run("all 1 1 1 1")
assert r.returncode == 0
assert r.stdout.strip() == "true"
def test_all_false():
r = run("all 1 0 1 1")
assert r.returncode == 0
assert r.stdout.strip() == "false"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_any_all/test_any_all_tool.py (757 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_any_all/test_any_all_tool.rs (2083 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_any_all/Cargo.toml (2 dependencies)
⏱️ Parse time: 52ms
📊 Throughput: 14.1 KB/s
⏱️ Total time: 52ms
| true
|
any_all
| 38
| 6
|
[] | 0
| null |
example_argparse_minimal
|
minimal_cli.py
|
#!/usr/bin/env python3
"""
Minimal Argparse CLI - Baseline example that must compile
This is the absolute minimum argparse example:
- Single positional argument
- Single optional argument
- No subcommands
- Minimal handler
Purpose: Baseline CLI that depyler must handle correctly.
"""
import argparse
def main():
"""Main entry point with minimal argparse."""
parser = argparse.ArgumentParser(
description="Minimal CLI example",
prog="minimal_cli.py",
)
# Single positional argument
parser.add_argument(
"input",
help="Input value",
)
# Single optional argument
parser.add_argument(
"-u",
"--upper",
action="store_true",
help="Convert to uppercase",
)
args = parser.parse_args()
# Minimal handler
if args.upper:
print(args.input.upper())
else:
print(args.input)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_argparse_minimal/minimal_cli.py (942 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_argparse_minimal/minimal_cli.rs (582 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_argparse_minimal/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 19.0 KB/s
⏱️ Total time: 48ms
| true
|
argparse_minimal
| 48
| 6
|
[
"context_manager"
] | 0.652
| null |
example_argparse_minimal
|
test_minimal_cli.py
|
"""
Test suite for minimal_cli.py
Baseline CLI that must work with depyler
Following extreme TDD methodology.
"""
import subprocess
from pathlib import Path
import pytest
SCRIPT = Path(__file__).parent / "minimal_cli.py"
def run_cli(*args):
"""Helper to run CLI and capture output."""
result = subprocess.run(
["python3", str(SCRIPT), *args],
capture_output=True,
text=True,
)
return result
class TestMinimalCLI:
"""Test suite for minimal CLI."""
def test_help_flag(self):
"""Test --help displays usage."""
result = run_cli("--help")
assert result.returncode == 0
assert "usage:" in result.stdout.lower()
assert "input" in result.stdout.lower()
assert "--upper" in result.stdout
def test_basic_execution(self):
"""Test basic execution with input."""
result = run_cli("hello")
assert result.returncode == 0
assert "hello" in result.stdout
def test_uppercase_short_flag(self):
"""Test -u flag for uppercase."""
result = run_cli("-u", "hello")
assert result.returncode == 0
assert "HELLO" in result.stdout
def test_uppercase_long_flag(self):
"""Test --upper flag for uppercase."""
result = run_cli("--upper", "hello")
assert result.returncode == 0
assert "HELLO" in result.stdout
def test_missing_input(self):
"""Test error when input is missing."""
result = run_cli()
assert result.returncode != 0
assert "required" in result.stderr.lower() or "argument" in result.stderr.lower()
@pytest.mark.parametrize(
"input_val,expected",
[
("hello", "hello"),
("WORLD", "WORLD"),
("MixedCase", "MixedCase"),
("123", "123"),
("", ""),
],
)
def test_various_inputs(self, input_val, expected):
"""Test various input values."""
result = run_cli(input_val)
assert result.returncode == 0
assert expected in result.stdout
@pytest.mark.parametrize(
"input_val,expected",
[
("hello", "HELLO"),
("world", "WORLD"),
("MixedCase", "MIXEDCASE"),
("123", "123"),
],
)
def test_uppercase_various(self, input_val, expected):
"""Test uppercase with various inputs."""
result = run_cli("-u", input_val)
assert result.returncode == 0
assert expected in result.stdout
def test_special_characters(self):
"""Test with special characters."""
result = run_cli("hello world!")
assert result.returncode == 0
assert "hello world!" in result.stdout
def test_unicode(self):
"""Test with unicode input."""
result = run_cli("hello 世界")
assert result.returncode == 0
assert "hello 世界" in result.stdout
def test_output_ends_newline(self):
"""Test output ends with newline."""
result = run_cli("test")
assert result.returncode == 0
assert result.stdout.endswith("\n")
def test_stderr_empty_on_success(self):
"""Test stderr empty on success."""
result = run_cli("test")
assert result.returncode == 0
assert result.stderr == ""
def test_deterministic(self):
"""Test deterministic output."""
results = [run_cli("test") for _ in range(3)]
assert all(r.returncode == 0 for r in results)
assert all(r.stdout == results[0].stdout for r in results)
def test_flag_before_input(self):
"""Test flag can come before input."""
result = run_cli("-u", "hello")
assert result.returncode == 0
assert "HELLO" in result.stdout
def test_flag_after_input(self):
"""Test flag can come after input."""
result = run_cli("hello", "-u")
assert result.returncode == 0
assert "HELLO" in result.stdout
def test_invalid_flag(self):
"""Test error with invalid flag."""
result = run_cli("--invalid", "test")
assert result.returncode != 0
assert "unrecognized" in result.stderr.lower() or "invalid" in result.stderr.lower()
| false
|
argparse_minimal
| 138
| 0
|
[
"context_manager",
"class_definition",
"stdin_usage",
"decorator"
] | 0.652
|
Performance Warnings
══════════════════════════════════════════════════
[1] [Medium] Large value 'args' passed by copy
Location: run_cli, line 0
Impact: Complexity: O(n), Scales: Yes, Hot path: No
Why: Passing large values by copy is inefficient
Fix: Consider passing by reference (&) or using Box/Arc for large types
Summary: Found 1 warnings (0 critical, 0 high severity)
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions:
|
|
example_array
|
array_tool.py
|
#!/usr/bin/env python3
"""Array Example - Aggregate operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Array operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
s = subs.add_parser("sum")
s.add_argument("a", type=int)
s.add_argument("b", type=int)
s.add_argument("c", type=int)
p = subs.add_parser("product")
p.add_argument("a", type=int)
p.add_argument("b", type=int)
p.add_argument("c", type=int)
args = parser.parse_args()
if args.cmd == "sum":
print(args.a + args.b + args.c)
elif args.cmd == "product":
print(args.a * args.b * args.c)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_array/array_tool.py (718 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_array/array_tool.rs (1043 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_array/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 14.5 KB/s
⏱️ Total time: 48ms
| true
|
array
| 29
| 6
|
[] | 0
| null |
example_array
|
test_array_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for array CLI."""
import subprocess
SCRIPT = "array_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestSum:
def test_sum(self): r = run(["sum", "1", "2", "3"]); assert r.returncode == 0 and "6" in r.stdout
class TestProduct:
def test_product(self): r = run(["product", "2", "3", "4"]); assert r.returncode == 0 and "24" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_array/test_array_tool.py (566 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_array/test_array_tool.rs (2004 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 11.1 KB/s
⏱️ Total time: 49ms
| true
|
array
| 15
| 5
|
[
"class_definition"
] | 0.612
| null |
example_ascii
|
ascii_tool.py
|
#!/usr/bin/env python3
"""Ascii Example - ASCII operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="ASCII operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
u = subs.add_parser("upper")
u.add_argument("code", type=int)
lo = subs.add_parser("lower")
lo.add_argument("code", type=int)
d = subs.add_parser("digit")
d.add_argument("n", type=int)
args = parser.parse_args()
if args.cmd == "upper":
print(chr(args.code))
elif args.cmd == "lower":
print(chr(args.code))
elif args.cmd == "digit":
print(ord("0") + args.n)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_ascii/ascii_tool.py (695 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_ascii/ascii_tool.rs (1046 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_ascii/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 13.7 KB/s
⏱️ Total time: 49ms
| true
|
ascii
| 28
| 6
|
[] | 0
| null |
example_ascii
|
test_ascii_tool.py
|
"""Tests for ascii_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "ascii_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_upper():
r = run("upper 65")
assert r.returncode == 0
assert r.stdout.strip() == "A"
def test_lower():
r = run("lower 97")
assert r.returncode == 0
assert r.stdout.strip() == "a"
def test_digit():
r = run("digit 5")
assert r.returncode == 0
assert r.stdout.strip() == "53"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_ascii/test_ascii_tool.py (605 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_ascii/test_ascii_tool.rs (1813 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_ascii/Cargo.toml (2 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 12.2 KB/s
⏱️ Total time: 48ms
| true
|
ascii
| 32
| 6
|
[] | 0
| null |
example_async_basic
|
async_basic_cli.py
|
#!/usr/bin/env python3
"""Async Basic CLI.
Basic async/await patterns and coroutine functions.
"""
import argparse
import asyncio
import sys
async def async_identity(value: int) -> int:
"""Simple async identity function."""
return value
async def async_add(a: int, b: int) -> int:
"""Async addition."""
return a + b
async def async_multiply(a: int, b: int) -> int:
"""Async multiplication."""
return a * b
async def async_delay(delay_ms: int) -> int:
"""Async function with delay."""
await asyncio.sleep(delay_ms / 1000.0)
return delay_ms
async def async_chain(value: int) -> int:
"""Chain multiple async operations."""
v1 = await async_identity(value)
v2 = await async_add(v1, 10)
v3 = await async_multiply(v2, 2)
return v3
async def async_conditional(value: int) -> str:
"""Async with conditional logic."""
result = await async_identity(value)
if result > 0:
return "positive"
elif result < 0:
return "negative"
else:
return "zero"
async def async_loop(count: int) -> int:
"""Async loop accumulator."""
total = 0
for i in range(count):
total = await async_add(total, i)
return total
async def async_early_return(values: list[int]) -> int:
"""Async with early return."""
for value in values:
result = await async_identity(value)
if result < 0:
return result
return 0
async def async_try_operation(value: int) -> int:
"""Async operation that may fail."""
if value < 0:
raise ValueError(f"Negative value: {value}")
return await async_identity(value * 2)
async def async_safe_operation(value: int) -> tuple[bool, int]:
"""Async operation with error handling."""
try:
result = await async_try_operation(value)
return (True, result)
except ValueError:
return (False, 0)
async def async_map(values: list[int], transform: int) -> list[int]:
"""Async map operation."""
results: list[int] = []
for v in values:
result = await async_add(v, transform)
results.append(result)
return results
async def async_filter_positive(values: list[int]) -> list[int]:
"""Async filter for positive values."""
results: list[int] = []
for v in values:
val = await async_identity(v)
if val > 0:
results.append(val)
return results
async def async_reduce(values: list[int], initial: int) -> int:
"""Async reduce/fold operation."""
accumulator = initial
for v in values:
accumulator = await async_add(accumulator, v)
return accumulator
async def async_find_first(values: list[int], target: int) -> int:
"""Async find first matching value."""
for i, v in enumerate(values):
val = await async_identity(v)
if val == target:
return i
return -1
async def async_any_match(values: list[int], target: int) -> bool:
"""Async check if any value matches."""
for v in values:
val = await async_identity(v)
if val == target:
return True
return False
async def async_all_positive(values: list[int]) -> bool:
"""Async check if all values are positive."""
for v in values:
val = await async_identity(v)
if val <= 0:
return False
return True
async def async_count_matching(values: list[int], predicate_value: int) -> int:
"""Async count values greater than predicate."""
count = 0
for v in values:
val = await async_identity(v)
if val > predicate_value:
count += 1
return count
async def async_partition(values: list[int], pivot: int) -> tuple[list[int], list[int]]:
"""Async partition values around pivot."""
less: list[int] = []
greater_or_equal: list[int] = []
for v in values:
val = await async_identity(v)
if val < pivot:
less.append(val)
else:
greater_or_equal.append(val)
return (less, greater_or_equal)
async def async_sum_squares(values: list[int]) -> int:
"""Async sum of squares."""
total = 0
for v in values:
squared = await async_multiply(v, v)
total = await async_add(total, squared)
return total
async def async_fibonacci(n: int) -> int:
"""Async fibonacci calculation."""
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, await async_add(a, b)
return b
async def async_factorial(n: int) -> int:
"""Async factorial calculation."""
if n <= 1:
return 1
result = 1
for i in range(2, n + 1):
result = await async_multiply(result, i)
return result
def run_async(coro: object) -> object:
"""Run async function synchronously."""
return asyncio.run(coro) # type: ignore
def main() -> int:
parser = argparse.ArgumentParser(description="Async basic CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# chain
chain_p = subparsers.add_parser("chain", help="Chain async operations")
chain_p.add_argument("value", type=int)
# sum
sum_p = subparsers.add_parser("sum", help="Async sum")
sum_p.add_argument("values", type=int, nargs="+")
# fibonacci
fib_p = subparsers.add_parser("fibonacci", help="Async fibonacci")
fib_p.add_argument("n", type=int)
# factorial
fact_p = subparsers.add_parser("factorial", help="Async factorial")
fact_p.add_argument("n", type=int)
args = parser.parse_args()
if args.command == "chain":
result = run_async(async_chain(args.value))
print(f"Result: {result}")
elif args.command == "sum":
result = run_async(async_reduce(args.values, 0))
print(f"Sum: {result}")
elif args.command == "fibonacci":
result = run_async(async_fibonacci(args.n))
print(f"Fibonacci({args.n}): {result}")
elif args.command == "factorial":
result = run_async(async_factorial(args.n))
print(f"Factorial({args.n}): {result}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_async_basic/async_basic_cli.py (6186 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_async_basic/async_basic_cli.rs (11954 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_async_basic/Cargo.toml (1 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 109.1 KB/s
⏱️ Total time: 55ms
| true
|
async_basic
| 241
| 6
|
[
"async_await",
"context_manager",
"exception_handling",
"functools"
] | 0.946
| null |
example_async_basic
|
test_async_basic_cli.py
|
"""Tests for async_basic_cli.py"""
import pytest
from async_basic_cli import (
async_add,
async_all_positive,
async_any_match,
async_chain,
async_conditional,
async_count_matching,
async_delay,
async_early_return,
async_factorial,
async_fibonacci,
async_filter_positive,
async_find_first,
async_identity,
async_loop,
async_map,
async_multiply,
async_partition,
async_reduce,
async_safe_operation,
async_sum_squares,
async_try_operation,
run_async,
)
class TestBasicAsync:
def test_identity(self):
result = run_async(async_identity(42))
assert result == 42
def test_add(self):
result = run_async(async_add(3, 4))
assert result == 7
def test_multiply(self):
result = run_async(async_multiply(3, 4))
assert result == 12
class TestAsyncDelay:
def test_delay_returns_value(self):
result = run_async(async_delay(10))
assert result == 10
class TestAsyncChain:
def test_chain(self):
# Chain: identity(5) = 5, add(5, 10) = 15, multiply(15, 2) = 30
result = run_async(async_chain(5))
assert result == 30
class TestAsyncConditional:
def test_positive(self):
result = run_async(async_conditional(5))
assert result == "positive"
def test_negative(self):
result = run_async(async_conditional(-5))
assert result == "negative"
def test_zero(self):
result = run_async(async_conditional(0))
assert result == "zero"
class TestAsyncLoop:
def test_loop_sum(self):
# 0 + 1 + 2 + 3 + 4 = 10
result = run_async(async_loop(5))
assert result == 10
def test_empty_loop(self):
result = run_async(async_loop(0))
assert result == 0
class TestAsyncEarlyReturn:
def test_finds_negative(self):
result = run_async(async_early_return([1, 2, -3, 4]))
assert result == -3
def test_no_negative(self):
result = run_async(async_early_return([1, 2, 3, 4]))
assert result == 0
def test_empty_list(self):
result = run_async(async_early_return([]))
assert result == 0
class TestAsyncErrorHandling:
def test_try_success(self):
result = run_async(async_try_operation(5))
assert result == 10
def test_try_failure(self):
with pytest.raises(ValueError):
run_async(async_try_operation(-1))
def test_safe_success(self):
success, result = run_async(async_safe_operation(5))
assert success is True
assert result == 10
def test_safe_failure(self):
success, result = run_async(async_safe_operation(-1))
assert success is False
assert result == 0
class TestAsyncCollections:
def test_map(self):
result = run_async(async_map([1, 2, 3], 10))
assert result == [11, 12, 13]
def test_filter_positive(self):
result = run_async(async_filter_positive([-1, 2, -3, 4]))
assert result == [2, 4]
def test_reduce(self):
result = run_async(async_reduce([1, 2, 3, 4], 0))
assert result == 10
def test_reduce_with_initial(self):
result = run_async(async_reduce([1, 2, 3], 100))
assert result == 106
class TestAsyncSearch:
def test_find_first(self):
result = run_async(async_find_first([1, 2, 3, 4, 5], 3))
assert result == 2
def test_find_first_not_found(self):
result = run_async(async_find_first([1, 2, 3], 10))
assert result == -1
def test_any_match_true(self):
result = run_async(async_any_match([1, 2, 3], 2))
assert result is True
def test_any_match_false(self):
result = run_async(async_any_match([1, 2, 3], 10))
assert result is False
class TestAsyncPredicates:
def test_all_positive_true(self):
result = run_async(async_all_positive([1, 2, 3]))
assert result is True
def test_all_positive_false(self):
result = run_async(async_all_positive([1, -2, 3]))
assert result is False
def test_count_matching(self):
result = run_async(async_count_matching([1, 5, 10, 15, 20], 10))
assert result == 2 # 15 and 20 are > 10
class TestAsyncPartition:
def test_partition(self):
less, greater = run_async(async_partition([1, 5, 3, 8, 2, 9], 5))
assert less == [1, 3, 2]
assert greater == [5, 8, 9]
class TestAsyncMath:
def test_sum_squares(self):
# 1^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14
result = run_async(async_sum_squares([1, 2, 3]))
assert result == 14
def test_fibonacci(self):
assert run_async(async_fibonacci(0)) == 0
assert run_async(async_fibonacci(1)) == 1
assert run_async(async_fibonacci(10)) == 55
def test_factorial(self):
assert run_async(async_factorial(0)) == 1
assert run_async(async_factorial(1)) == 1
assert run_async(async_factorial(5)) == 120
class TestEdgeCases:
def test_empty_collections(self):
assert run_async(async_map([], 10)) == []
assert run_async(async_filter_positive([])) == []
assert run_async(async_reduce([], 0)) == 0
assert run_async(async_find_first([], 1)) == -1
assert run_async(async_any_match([], 1)) is False
assert run_async(async_all_positive([])) is True
def test_single_element(self):
assert run_async(async_map([5], 10)) == [15]
assert run_async(async_reduce([5], 0)) == 5
assert run_async(async_find_first([5], 5)) == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_async_basic/test_async_basic_cli.py (5611 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_async_basic/test_async_basic_cli.rs (13097 bytes)
⏱️ Parse time: 51ms
📊 Throughput: 106.2 KB/s
⏱️ Total time: 51ms
| true
|
async_basic
| 202
| 5
|
[
"context_manager",
"class_definition",
"functools"
] | 0.652
| null |
example_async_context
|
async_context_cli.py
|
#!/usr/bin/env python3
"""Async Context CLI.
Async context managers and resource management patterns.
"""
import argparse
import asyncio
import sys
from typing import Any
class AsyncResource:
"""Simple async resource with enter/exit."""
def __init__(self, name: str) -> None:
self._name: str = name
self._open: bool = False
self._operations: list[str] = []
async def __aenter__(self) -> "AsyncResource":
self._open = True
self._operations.append(f"opened:{self._name}")
return self
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
self._open = False
self._operations.append(f"closed:{self._name}")
return False
def is_open(self) -> bool:
return self._open
def get_name(self) -> str:
return self._name
def get_operations(self) -> list[str]:
return self._operations.copy()
async def read(self) -> str:
if not self._open:
raise RuntimeError("Resource not open")
self._operations.append(f"read:{self._name}")
return f"data_from_{self._name}"
async def write(self, data: str) -> None:
if not self._open:
raise RuntimeError("Resource not open")
self._operations.append(f"write:{self._name}:{data}")
class AsyncLock:
"""Simple async lock implementation."""
def __init__(self) -> None:
self._locked: bool = False
self._history: list[str] = []
async def __aenter__(self) -> "AsyncLock":
await self.acquire()
return self
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
self.release()
return False
async def acquire(self) -> None:
self._locked = True
self._history.append("acquired")
def release(self) -> None:
self._locked = False
self._history.append("released")
def is_locked(self) -> bool:
return self._locked
def get_history(self) -> list[str]:
return self._history.copy()
class AsyncTransaction:
"""Async transaction with commit/rollback."""
def __init__(self) -> None:
self._operations: list[str] = []
self._committed: bool = False
self._rolled_back: bool = False
async def __aenter__(self) -> "AsyncTransaction":
self._operations.append("begin")
return self
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
if exc_type is not None:
await self.rollback()
return True # Suppress the exception
if not self._committed:
await self.commit()
return False
async def commit(self) -> None:
self._operations.append("commit")
self._committed = True
async def rollback(self) -> None:
self._operations.append("rollback")
self._rolled_back = True
def add_operation(self, op: str) -> None:
self._operations.append(op)
def get_operations(self) -> list[str]:
return self._operations.copy()
def is_committed(self) -> bool:
return self._committed
def is_rolled_back(self) -> bool:
return self._rolled_back
class AsyncPool:
"""Simple async connection pool."""
def __init__(self, max_size: int) -> None:
self._max_size: int = max_size
self._available: list[int] = list(range(max_size))
self._in_use: list[int] = []
self._history: list[str] = []
async def acquire(self) -> int:
if not self._available:
raise RuntimeError("Pool exhausted")
conn = self._available.pop(0)
self._in_use.append(conn)
self._history.append(f"acquire:{conn}")
return conn
async def release(self, conn: int) -> None:
if conn in self._in_use:
self._in_use.remove(conn)
self._available.append(conn)
self._history.append(f"release:{conn}")
def available_count(self) -> int:
return len(self._available)
def in_use_count(self) -> int:
return len(self._in_use)
def get_history(self) -> list[str]:
return self._history.copy()
class PooledConnection:
"""Context manager for pooled connection."""
def __init__(self, pool: AsyncPool) -> None:
self._pool: AsyncPool = pool
self._conn: int = -1
async def __aenter__(self) -> int:
self._conn = await self._pool.acquire()
return self._conn
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
await self._pool.release(self._conn)
return False
async def use_resource(name: str) -> list[str]:
"""Use async resource with context manager."""
async with AsyncResource(name) as res:
await res.read()
await res.write("test_data")
return res.get_operations()
async def use_lock() -> list[str]:
"""Use async lock with context manager."""
lock = AsyncLock()
async with lock:
pass # Critical section
return lock.get_history()
async def nested_resources(name1: str, name2: str) -> tuple[list[str], list[str]]:
"""Nested async resource usage."""
async with AsyncResource(name1) as res1:
async with AsyncResource(name2) as res2:
await res1.read()
await res2.write("nested_data")
return (res1.get_operations(), res2.get_operations())
async def transaction_success() -> list[str]:
"""Successful transaction."""
async with AsyncTransaction() as tx:
tx.add_operation("insert_a")
tx.add_operation("insert_b")
return tx.get_operations()
async def transaction_failure() -> list[str]:
"""Failed transaction with rollback."""
async with AsyncTransaction() as tx:
tx.add_operation("insert_a")
raise ValueError("Simulated failure") # Will trigger rollback
return tx.get_operations()
async def pool_operations(max_size: int) -> list[str]:
"""Pool acquire/release operations."""
pool = AsyncPool(max_size)
async with PooledConnection(pool) as conn1:
async with PooledConnection(pool) as conn2:
_ = conn1 # Use connections
_ = conn2
return pool.get_history()
async def sequential_resources(names: list[str]) -> list[str]:
"""Use resources sequentially."""
all_ops: list[str] = []
for name in names:
async with AsyncResource(name) as res:
data = await res.read()
all_ops.append(data)
return all_ops
async def resource_with_error(name: str, should_fail: bool) -> tuple[bool, list[str]]:
"""Resource that may encounter an error."""
try:
async with AsyncResource(name) as res:
await res.read()
if should_fail:
raise RuntimeError("Intentional failure")
await res.write("success")
return (True, res.get_operations())
except RuntimeError:
return (False, res.get_operations())
async def scoped_lock_operations(operations: list[str]) -> list[str]:
"""Perform operations within a lock scope."""
lock = AsyncLock()
results: list[str] = []
for op in operations:
async with lock:
results.append(f"locked:{op}")
return results
def run_async(coro: object) -> object:
"""Run async function synchronously."""
return asyncio.run(coro) # type: ignore
def main() -> int:
parser = argparse.ArgumentParser(description="Async context CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# resource
res_p = subparsers.add_parser("resource", help="Use async resource")
res_p.add_argument("name")
# transaction
tx_p = subparsers.add_parser("transaction", help="Run transaction")
tx_p.add_argument("--fail", action="store_true")
# pool
pool_p = subparsers.add_parser("pool", help="Test connection pool")
pool_p.add_argument("--size", type=int, default=5)
args = parser.parse_args()
if args.command == "resource":
ops = run_async(use_resource(args.name))
print(f"Operations: {ops}")
elif args.command == "transaction":
if args.fail:
ops = run_async(transaction_failure())
else:
ops = run_async(transaction_success())
print(f"Operations: {ops}")
elif args.command == "pool":
ops = run_async(pool_operations(args.size))
print(f"Operations: {ops}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
async_context
| 301
| 0
|
[
"async_await",
"context_manager",
"class_definition",
"exception_handling",
"multiprocessing"
] | 0.946
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 429..444, value: Str("AsyncResource"), kind: None })
|
|
example_async_context
|
test_async_context_cli.py
|
"""Tests for async_context_cli.py"""
import pytest
from async_context_cli import (
AsyncLock,
AsyncPool,
AsyncResource,
AsyncTransaction,
PooledConnection,
nested_resources,
pool_operations,
resource_with_error,
run_async,
scoped_lock_operations,
sequential_resources,
transaction_failure,
transaction_success,
use_lock,
use_resource,
)
class TestAsyncResource:
def test_open_close(self):
async def test():
async with AsyncResource("test") as res:
assert res.is_open()
assert res.get_name() == "test"
assert not res.is_open()
run_async(test())
def test_operations(self):
async def test():
async with AsyncResource("test") as res:
await res.read()
await res.write("data")
ops = res.get_operations()
assert "opened:test" in ops
assert "read:test" in ops
assert "write:test:data" in ops
assert "closed:test" in ops
run_async(test())
def test_read_when_closed(self):
async def test():
res = AsyncResource("test")
with pytest.raises(RuntimeError):
await res.read()
run_async(test())
class TestAsyncLock:
def test_acquire_release(self):
async def test():
lock = AsyncLock()
async with lock:
assert lock.is_locked()
assert not lock.is_locked()
run_async(test())
def test_history(self):
async def test():
lock = AsyncLock()
async with lock:
pass
history = lock.get_history()
assert history == ["acquired", "released"]
run_async(test())
class TestAsyncTransaction:
def test_commit(self):
async def test():
async with AsyncTransaction() as tx:
tx.add_operation("insert")
assert tx.is_committed()
assert not tx.is_rolled_back()
run_async(test())
def test_explicit_commit(self):
async def test():
async with AsyncTransaction() as tx:
tx.add_operation("insert")
await tx.commit()
ops = tx.get_operations()
assert ops.count("commit") == 1 # Only committed once
run_async(test())
def test_rollback_on_error(self):
async def test():
try:
async with AsyncTransaction() as tx:
tx.add_operation("insert")
raise ValueError("Test error")
except ValueError:
pass # Should be suppressed
assert tx.is_rolled_back()
assert not tx.is_committed()
run_async(test())
def test_operations(self):
async def test():
async with AsyncTransaction() as tx:
tx.add_operation("a")
tx.add_operation("b")
ops = tx.get_operations()
assert "begin" in ops
assert "a" in ops
assert "b" in ops
assert "commit" in ops
run_async(test())
class TestAsyncPool:
def test_acquire_release(self):
async def test():
pool = AsyncPool(3)
assert pool.available_count() == 3
conn = await pool.acquire()
assert pool.available_count() == 2
assert pool.in_use_count() == 1
await pool.release(conn)
assert pool.available_count() == 3
assert pool.in_use_count() == 0
run_async(test())
def test_pool_exhaustion(self):
async def test():
pool = AsyncPool(2)
await pool.acquire()
await pool.acquire()
with pytest.raises(RuntimeError):
await pool.acquire()
run_async(test())
class TestPooledConnection:
def test_context_manager(self):
async def test():
pool = AsyncPool(5)
async with PooledConnection(pool) as conn:
assert pool.in_use_count() == 1
_ = conn
assert pool.in_use_count() == 0
run_async(test())
class TestUseResource:
def test_use_resource(self):
ops = run_async(use_resource("myres"))
assert "opened:myres" in ops
assert "read:myres" in ops
assert "write:myres:test_data" in ops
assert "closed:myres" in ops
class TestUseLock:
def test_use_lock(self):
history = run_async(use_lock())
assert history == ["acquired", "released"]
class TestNestedResources:
def test_nested(self):
ops1, ops2 = run_async(nested_resources("outer", "inner"))
assert "opened:outer" in ops1
assert "read:outer" in ops1
assert "closed:outer" in ops1
assert "opened:inner" in ops2
assert "write:inner:nested_data" in ops2
assert "closed:inner" in ops2
class TestTransactions:
def test_success(self):
ops = run_async(transaction_success())
assert "begin" in ops
assert "insert_a" in ops
assert "insert_b" in ops
assert "commit" in ops
def test_failure(self):
ops = run_async(transaction_failure())
assert "begin" in ops
assert "insert_a" in ops
assert "rollback" in ops
class TestPoolOperations:
def test_operations(self):
ops = run_async(pool_operations(5))
# Should have acquire:0, acquire:1, release:1, release:0
assert "acquire:0" in ops
assert "acquire:1" in ops
assert "release:1" in ops
assert "release:0" in ops
class TestSequentialResources:
def test_sequential(self):
results = run_async(sequential_resources(["a", "b", "c"]))
assert results == ["data_from_a", "data_from_b", "data_from_c"]
class TestResourceWithError:
def test_success(self):
success, ops = run_async(resource_with_error("test", False))
assert success is True
assert "write:test:success" in ops
def test_failure(self):
success, ops = run_async(resource_with_error("test", True))
assert success is False
assert "read:test" in ops
assert "closed:test" in ops
class TestScopedLockOperations:
def test_scoped(self):
results = run_async(scoped_lock_operations(["op1", "op2", "op3"]))
assert results == ["locked:op1", "locked:op2", "locked:op3"]
class TestEdgeCases:
def test_empty_sequential(self):
results = run_async(sequential_resources([]))
assert results == []
def test_single_resource(self):
results = run_async(sequential_resources(["single"]))
assert results == ["data_from_single"]
| false
|
async_context
| 231
| 0
|
[
"async_await",
"context_manager",
"class_definition",
"exception_handling",
"multiprocessing"
] | 0.946
|
Error: Statement type not yet supported: AsyncFunctionDef
|
|
example_async_gather
|
async_gather_cli.py
|
#!/usr/bin/env python3
"""Async Gather CLI.
Concurrent async execution patterns with asyncio.gather.
"""
import argparse
import asyncio
import sys
async def async_delay_value(value: int, delay_ms: int) -> int:
"""Return value after delay."""
await asyncio.sleep(delay_ms / 1000.0)
return value
async def async_compute(x: int) -> int:
"""Simulate computation."""
await asyncio.sleep(0.001) # Minimal delay
return x * x
async def async_may_fail(value: int, should_fail: bool) -> int:
"""Operation that may fail."""
if should_fail:
raise ValueError(f"Failed for {value}")
return value * 2
async def gather_all(values: list[int]) -> list[int]:
"""Gather all results concurrently."""
tasks = [async_compute(v) for v in values]
results = await asyncio.gather(*tasks)
return list(results)
async def gather_with_exceptions(values: list[int], fail_indices: list[int]) -> list[object]:
"""Gather with return_exceptions=True."""
tasks = [async_may_fail(v, i in fail_indices) for i, v in enumerate(values)]
results = await asyncio.gather(*tasks, return_exceptions=True)
return list(results)
async def gather_first_completed(values: list[int]) -> int:
"""Get first completed result using wait."""
tasks = [asyncio.create_task(async_compute(v)) for v in values]
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
# Cancel pending tasks
for task in pending:
task.cancel()
# Return first completed result
for task in done:
return task.result()
return -1
async def gather_all_completed(values: list[int]) -> list[int]:
"""Wait for all tasks using wait."""
tasks = [asyncio.create_task(async_compute(v)) for v in values]
done, _ = await asyncio.wait(tasks)
return [task.result() for task in done]
async def gather_with_timeout(values: list[int], timeout_sec: float) -> list[int]:
"""Gather with timeout."""
tasks = [async_delay_value(v, v * 10) for v in values] # Delay proportional to value
try:
results = await asyncio.wait_for(asyncio.gather(*tasks), timeout=timeout_sec)
return list(results)
except TimeoutError:
return []
async def concurrent_map(values: list[int], transform: int) -> list[int]:
"""Map operation executed concurrently."""
async def add_transform(v: int) -> int:
await asyncio.sleep(0.001)
return v + transform
tasks = [add_transform(v) for v in values]
results = await asyncio.gather(*tasks)
return list(results)
async def concurrent_filter_compute(values: list[int], threshold: int) -> list[int]:
"""Filter values concurrently, then compute on results."""
async def check_and_compute(v: int) -> tuple[bool, int]:
await asyncio.sleep(0.001)
return (v >= threshold, v * v if v >= threshold else 0)
tasks = [check_and_compute(v) for v in values]
results = await asyncio.gather(*tasks)
return [r[1] for r in results if r[0]]
async def fan_out_fan_in(value: int) -> int:
"""Fan out to multiple operations, then combine."""
async def op1(v: int) -> int:
await asyncio.sleep(0.001)
return v + 1
async def op2(v: int) -> int:
await asyncio.sleep(0.001)
return v * 2
async def op3(v: int) -> int:
await asyncio.sleep(0.001)
return v**2
results = await asyncio.gather(op1(value), op2(value), op3(value))
return sum(results)
async def parallel_reduce(values: list[int]) -> int:
"""Parallel tree reduction."""
if len(values) == 0:
return 0
if len(values) == 1:
return values[0]
async def add(a: int, b: int) -> int:
await asyncio.sleep(0.001)
return a + b
# Pair up and reduce
current = values
while len(current) > 1:
tasks = []
for i in range(0, len(current) - 1, 2):
tasks.append(add(current[i], current[i + 1]))
if len(current) % 2 == 1:
# Capture last value in default argument to bind loop variable
last_val = current[-1]
async def identity(v: int = last_val) -> int:
return v
tasks.append(identity())
results = await asyncio.gather(*tasks)
current = list(results)
return current[0]
async def concurrent_find_any(values: list[int], target: int) -> bool:
"""Find if any value matches target concurrently."""
async def check(v: int) -> bool:
await asyncio.sleep(0.001)
return v == target
tasks = [check(v) for v in values]
results = await asyncio.gather(*tasks)
return any(results)
async def concurrent_all_positive(values: list[int]) -> bool:
"""Check if all values are positive concurrently."""
async def is_positive(v: int) -> bool:
await asyncio.sleep(0.001)
return v > 0
tasks = [is_positive(v) for v in values]
results = await asyncio.gather(*tasks)
return all(results)
async def batch_process(values: list[int], batch_size: int) -> list[int]:
"""Process values in concurrent batches."""
results: list[int] = []
for i in range(0, len(values), batch_size):
batch = values[i : i + batch_size]
batch_results = await gather_all(batch)
results.extend(batch_results)
return results
async def parallel_max(values: list[int]) -> int:
"""Find maximum value using parallel comparison."""
if len(values) == 0:
return 0
if len(values) == 1:
return values[0]
async def max_pair(a: int, b: int) -> int:
await asyncio.sleep(0.001)
return a if a > b else b
current = values
while len(current) > 1:
tasks = []
for i in range(0, len(current) - 1, 2):
tasks.append(max_pair(current[i], current[i + 1]))
if len(current) % 2 == 1:
tasks.append(asyncio.sleep(0, current[-1])) # type: ignore
results = await asyncio.gather(*tasks)
current = [r for r in results if isinstance(r, int)]
return current[0]
async def parallel_sum(values: list[int]) -> int:
"""Sum values using parallel reduction."""
if len(values) == 0:
return 0
results = await gather_all(values) # Compute squares
# Sum results
total = 0
for r in results:
total += r
return total
def run_async(coro: object) -> object:
"""Run async function synchronously."""
return asyncio.run(coro) # type: ignore
def main() -> int:
parser = argparse.ArgumentParser(description="Async gather CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# gather
gather_p = subparsers.add_parser("gather", help="Gather concurrent results")
gather_p.add_argument("values", type=int, nargs="+")
# fanout
fanout_p = subparsers.add_parser("fanout", help="Fan out computation")
fanout_p.add_argument("value", type=int)
# batch
batch_p = subparsers.add_parser("batch", help="Batch process")
batch_p.add_argument("values", type=int, nargs="+")
batch_p.add_argument("--size", type=int, default=3)
args = parser.parse_args()
if args.command == "gather":
result = run_async(gather_all(args.values))
print(f"Results: {result}")
elif args.command == "fanout":
result = run_async(fan_out_fan_in(args.value))
print(f"Combined result: {result}")
elif args.command == "batch":
result = run_async(batch_process(args.values, args.size))
print(f"Batch results: {result}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
async_gather
| 263
| 0
|
[
"async_await",
"context_manager",
"exception_handling",
"multiprocessing",
"functools"
] | 0.946
|
Error: Statement type not yet supported: AsyncFunctionDef
|
|
example_async_gather
|
test_async_gather_cli.py
|
"""Tests for async_gather_cli.py"""
import pytest
from async_gather_cli import (
async_compute,
async_delay_value,
async_may_fail,
batch_process,
concurrent_all_positive,
concurrent_filter_compute,
concurrent_find_any,
concurrent_map,
fan_out_fan_in,
gather_all,
gather_all_completed,
gather_first_completed,
gather_with_exceptions,
parallel_sum,
run_async,
)
class TestAsyncCompute:
def test_compute(self):
result = run_async(async_compute(5))
assert result == 25
class TestAsyncDelayValue:
def test_returns_value(self):
result = run_async(async_delay_value(42, 10))
assert result == 42
class TestAsyncMayFail:
def test_success(self):
result = run_async(async_may_fail(5, False))
assert result == 10
def test_failure(self):
with pytest.raises(ValueError):
run_async(async_may_fail(5, True))
class TestGatherAll:
def test_basic(self):
result = run_async(gather_all([1, 2, 3, 4, 5]))
assert result == [1, 4, 9, 16, 25]
def test_empty(self):
result = run_async(gather_all([]))
assert result == []
def test_single(self):
result = run_async(gather_all([10]))
assert result == [100]
class TestGatherWithExceptions:
def test_no_failures(self):
result = run_async(gather_with_exceptions([1, 2, 3], []))
assert result == [2, 4, 6]
def test_with_failures(self):
result = run_async(gather_with_exceptions([1, 2, 3], [1]))
assert result[0] == 2
assert isinstance(result[1], ValueError)
assert result[2] == 6
class TestGatherFirstCompleted:
def test_returns_first(self):
result = run_async(gather_first_completed([1, 2, 3]))
assert result in [1, 4, 9] # Any squared value
class TestGatherAllCompleted:
def test_returns_all(self):
result = run_async(gather_all_completed([1, 2, 3]))
assert sorted(result) == [1, 4, 9]
class TestConcurrentMap:
def test_add_transform(self):
result = run_async(concurrent_map([1, 2, 3], 10))
assert result == [11, 12, 13]
def test_empty(self):
result = run_async(concurrent_map([], 10))
assert result == []
class TestConcurrentFilterCompute:
def test_filter_and_compute(self):
result = run_async(concurrent_filter_compute([1, 5, 3, 8, 2], 4))
assert sorted(result) == [25, 64] # 5^2=25, 8^2=64
class TestFanOutFanIn:
def test_combine(self):
# op1: 5+1=6, op2: 5*2=10, op3: 5^2=25
# sum = 6+10+25 = 41
result = run_async(fan_out_fan_in(5))
assert result == 41
class TestConcurrentFindAny:
def test_found(self):
result = run_async(concurrent_find_any([1, 2, 3, 4, 5], 3))
assert result is True
def test_not_found(self):
result = run_async(concurrent_find_any([1, 2, 3, 4, 5], 10))
assert result is False
class TestConcurrentAllPositive:
def test_all_positive(self):
result = run_async(concurrent_all_positive([1, 2, 3, 4, 5]))
assert result is True
def test_has_non_positive(self):
result = run_async(concurrent_all_positive([1, -2, 3]))
assert result is False
class TestBatchProcess:
def test_batches(self):
result = run_async(batch_process([1, 2, 3, 4, 5, 6], 2))
assert result == [1, 4, 9, 16, 25, 36]
def test_single_batch(self):
result = run_async(batch_process([1, 2], 5))
assert result == [1, 4]
class TestParallelSum:
def test_sum(self):
# Squares: 1, 4, 9, 16 -> sum = 30
result = run_async(parallel_sum([1, 2, 3, 4]))
assert result == 30
def test_empty(self):
result = run_async(parallel_sum([]))
assert result == 0
class TestEdgeCases:
def test_empty_gather(self):
result = run_async(gather_all([]))
assert result == []
def test_single_gather(self):
result = run_async(gather_all([7]))
assert result == [49]
def test_large_batch(self):
values = list(range(100))
result = run_async(batch_process(values, 10))
assert len(result) == 100
assert result[0] == 0
assert result[9] == 81
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_async_gather/test_async_gather_cli.py (4298 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_async_gather/test_async_gather_cli.rs (10181 bytes)
⏱️ Parse time: 51ms
📊 Throughput: 82.2 KB/s
⏱️ Total time: 51ms
| true
|
async_gather
| 162
| 5
|
[
"context_manager",
"class_definition",
"multiprocessing"
] | 0.652
| null |
example_async_iterator
|
async_iterator_cli.py
|
#!/usr/bin/env python3
"""Async Iterator CLI.
Async iterators and async generators.
"""
import argparse
import asyncio
import sys
from collections.abc import AsyncIterator
class AsyncRange:
"""Async range iterator."""
def __init__(self, start: int, end: int, step: int = 1) -> None:
self._start: int = start
self._end: int = end
self._step: int = step
self._current: int = start
def __aiter__(self) -> "AsyncRange":
return self
async def __anext__(self) -> int:
if (self._step > 0 and self._current >= self._end) or (
self._step < 0 and self._current <= self._end
):
raise StopAsyncIteration
value = self._current
self._current += self._step
return value
class AsyncCounter:
"""Async counter with limit."""
def __init__(self, limit: int) -> None:
self._limit: int = limit
self._count: int = 0
def __aiter__(self) -> "AsyncCounter":
return self
async def __anext__(self) -> int:
if self._count >= self._limit:
raise StopAsyncIteration
value = self._count
self._count += 1
return value
class AsyncFilter:
"""Async filtering iterator."""
def __init__(self, iterable: AsyncIterator[int], min_value: int) -> None:
self._iterable: AsyncIterator[int] = iterable
self._min_value: int = min_value
def __aiter__(self) -> "AsyncFilter":
return self
async def __anext__(self) -> int:
async for item in self._iterable:
if item >= self._min_value:
return item
raise StopAsyncIteration
class AsyncMap:
"""Async mapping iterator."""
def __init__(self, iterable: AsyncIterator[int], addend: int) -> None:
self._iterable: AsyncIterator[int] = iterable
self._addend: int = addend
def __aiter__(self) -> "AsyncMap":
return self
async def __anext__(self) -> int:
async for item in self._iterable:
return item + self._addend
raise StopAsyncIteration
class AsyncTake:
"""Async iterator that takes first n items."""
def __init__(self, iterable: AsyncIterator[int], n: int) -> None:
self._iterable: AsyncIterator[int] = iterable
self._remaining: int = n
def __aiter__(self) -> "AsyncTake":
return self
async def __anext__(self) -> int:
if self._remaining <= 0:
raise StopAsyncIteration
self._remaining -= 1
return await self._iterable.__anext__()
class AsyncSkip:
"""Async iterator that skips first n items."""
def __init__(self, iterable: AsyncIterator[int], n: int) -> None:
self._iterable: AsyncIterator[int] = iterable
self._to_skip: int = n
self._skipped: bool = False
def __aiter__(self) -> "AsyncSkip":
return self
async def __anext__(self) -> int:
if not self._skipped:
for _ in range(self._to_skip):
try:
await self._iterable.__anext__()
except StopAsyncIteration:
raise
self._skipped = True
return await self._iterable.__anext__()
async def async_generator_range(start: int, end: int) -> AsyncIterator[int]:
"""Async generator for range."""
for i in range(start, end):
yield i
async def async_generator_squares(limit: int) -> AsyncIterator[int]:
"""Async generator for squares."""
for i in range(limit):
yield i * i
async def async_generator_fibonacci(limit: int) -> AsyncIterator[int]:
"""Async generator for Fibonacci sequence."""
a, b = 0, 1
for _ in range(limit):
yield a
a, b = b, a + b
async def async_generator_filter(source: AsyncIterator[int], threshold: int) -> AsyncIterator[int]:
"""Async generator that filters values."""
async for item in source:
if item >= threshold:
yield item
async def async_generator_map(source: AsyncIterator[int], addend: int) -> AsyncIterator[int]:
"""Async generator that transforms values."""
async for item in source:
yield item + addend
async def async_generator_take(source: AsyncIterator[int], n: int) -> AsyncIterator[int]:
"""Async generator that takes first n items."""
count = 0
async for item in source:
if count >= n:
break
yield item
count += 1
async def async_generator_skip(source: AsyncIterator[int], n: int) -> AsyncIterator[int]:
"""Async generator that skips first n items."""
count = 0
async for item in source:
if count >= n:
yield item
count += 1
async def async_generator_chain(
first: AsyncIterator[int], second: AsyncIterator[int]
) -> AsyncIterator[int]:
"""Chain two async iterators."""
async for item in first:
yield item
async for item in second:
yield item
async def async_generator_enumerate(source: AsyncIterator[int]) -> AsyncIterator[tuple[int, int]]:
"""Async enumerate."""
index = 0
async for item in source:
yield (index, item)
index += 1
async def async_generator_zip(
first: AsyncIterator[int], second: AsyncIterator[int]
) -> AsyncIterator[tuple[int, int]]:
"""Async zip of two iterators."""
while True:
try:
a = await first.__anext__()
b = await second.__anext__()
yield (a, b)
except StopAsyncIteration:
break
async def collect_async(iterator: AsyncIterator[int]) -> list[int]:
"""Collect async iterator into list."""
result: list[int] = []
async for item in iterator:
result.append(item)
return result
async def sum_async(iterator: AsyncIterator[int]) -> int:
"""Sum values from async iterator."""
total = 0
async for item in iterator:
total += item
return total
async def count_async(iterator: AsyncIterator[int]) -> int:
"""Count items in async iterator."""
count = 0
async for _ in iterator:
count += 1
return count
async def any_async(iterator: AsyncIterator[int], value: int) -> bool:
"""Check if any item equals value."""
async for item in iterator:
if item == value:
return True
return False
async def all_positive_async(iterator: AsyncIterator[int]) -> bool:
"""Check if all items are positive."""
async for item in iterator:
if item <= 0:
return False
return True
async def first_async(iterator: AsyncIterator[int]) -> int:
"""Get first item or -1 if empty."""
async for item in iterator:
return item
return -1
async def last_async(iterator: AsyncIterator[int]) -> int:
"""Get last item or -1 if empty."""
result = -1
async for item in iterator:
result = item
return result
def run_async(coro: object) -> object:
"""Run async function synchronously."""
return asyncio.run(coro) # type: ignore
def main() -> int:
parser = argparse.ArgumentParser(description="Async iterator CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# range
range_p = subparsers.add_parser("range", help="Async range")
range_p.add_argument("start", type=int)
range_p.add_argument("end", type=int)
# squares
squares_p = subparsers.add_parser("squares", help="Async squares")
squares_p.add_argument("limit", type=int)
# fibonacci
fib_p = subparsers.add_parser("fibonacci", help="Async fibonacci")
fib_p.add_argument("limit", type=int)
args = parser.parse_args()
if args.command == "range":
result = run_async(collect_async(async_generator_range(args.start, args.end)))
print(f"Range: {result}")
elif args.command == "squares":
result = run_async(collect_async(async_generator_squares(args.limit)))
print(f"Squares: {result}")
elif args.command == "fibonacci":
result = run_async(collect_async(async_generator_fibonacci(args.limit)))
print(f"Fibonacci: {result}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
async_iterator
| 306
| 0
|
[
"async_await",
"generator",
"context_manager",
"class_definition",
"exception_handling"
] | 0.946
|
Error: Statement type not yet supported: AsyncFor
|
|
example_async_iterator
|
test_async_iterator_cli.py
|
"""Tests for async_iterator_cli.py"""
from async_iterator_cli import (
AsyncCounter,
AsyncRange,
all_positive_async,
any_async,
async_generator_chain,
async_generator_enumerate,
async_generator_fibonacci,
async_generator_filter,
async_generator_map,
async_generator_range,
async_generator_skip,
async_generator_squares,
async_generator_take,
async_generator_zip,
collect_async,
count_async,
first_async,
last_async,
run_async,
sum_async,
)
class TestAsyncRange:
def test_basic(self):
async def test():
results = []
async for i in AsyncRange(0, 5):
results.append(i)
return results
assert run_async(test()) == [0, 1, 2, 3, 4]
def test_with_step(self):
async def test():
results = []
async for i in AsyncRange(0, 10, 2):
results.append(i)
return results
assert run_async(test()) == [0, 2, 4, 6, 8]
def test_negative_step(self):
async def test():
results = []
async for i in AsyncRange(5, 0, -1):
results.append(i)
return results
assert run_async(test()) == [5, 4, 3, 2, 1]
def test_empty(self):
async def test():
results = []
async for i in AsyncRange(5, 5):
results.append(i)
return results
assert run_async(test()) == []
class TestAsyncCounter:
def test_basic(self):
async def test():
results = []
async for i in AsyncCounter(5):
results.append(i)
return results
assert run_async(test()) == [0, 1, 2, 3, 4]
def test_zero(self):
async def test():
results = []
async for i in AsyncCounter(0):
results.append(i)
return results
assert run_async(test()) == []
class TestAsyncGeneratorRange:
def test_basic(self):
result = run_async(collect_async(async_generator_range(0, 5)))
assert result == [0, 1, 2, 3, 4]
class TestAsyncGeneratorSquares:
def test_basic(self):
result = run_async(collect_async(async_generator_squares(5)))
assert result == [0, 1, 4, 9, 16]
class TestAsyncGeneratorFibonacci:
def test_basic(self):
result = run_async(collect_async(async_generator_fibonacci(8)))
assert result == [0, 1, 1, 2, 3, 5, 8, 13]
class TestAsyncGeneratorFilter:
def test_filter(self):
async def test():
source = async_generator_range(0, 10)
filtered = async_generator_filter(source, 5)
return await collect_async(filtered)
assert run_async(test()) == [5, 6, 7, 8, 9]
class TestAsyncGeneratorMap:
def test_map(self):
async def test():
source = async_generator_range(0, 5)
mapped = async_generator_map(source, 10)
return await collect_async(mapped)
assert run_async(test()) == [10, 11, 12, 13, 14]
class TestAsyncGeneratorTake:
def test_take(self):
async def test():
source = async_generator_range(0, 100)
taken = async_generator_take(source, 5)
return await collect_async(taken)
assert run_async(test()) == [0, 1, 2, 3, 4]
def test_take_more_than_available(self):
async def test():
source = async_generator_range(0, 3)
taken = async_generator_take(source, 10)
return await collect_async(taken)
assert run_async(test()) == [0, 1, 2]
class TestAsyncGeneratorSkip:
def test_skip(self):
async def test():
source = async_generator_range(0, 10)
skipped = async_generator_skip(source, 5)
return await collect_async(skipped)
assert run_async(test()) == [5, 6, 7, 8, 9]
class TestAsyncGeneratorChain:
def test_chain(self):
async def test():
first = async_generator_range(0, 3)
second = async_generator_range(10, 13)
chained = async_generator_chain(first, second)
return await collect_async(chained)
assert run_async(test()) == [0, 1, 2, 10, 11, 12]
class TestAsyncGeneratorEnumerate:
def test_enumerate(self):
async def test():
source = async_generator_range(10, 13)
enumerated = async_generator_enumerate(source)
results = []
async for item in enumerated:
results.append(item)
return results
assert run_async(test()) == [(0, 10), (1, 11), (2, 12)]
class TestAsyncGeneratorZip:
def test_zip(self):
async def test():
first = async_generator_range(1, 4)
second = async_generator_range(10, 13)
zipped = async_generator_zip(first, second)
results = []
async for item in zipped:
results.append(item)
return results
assert run_async(test()) == [(1, 10), (2, 11), (3, 12)]
class TestCollectAsync:
def test_collect(self):
result = run_async(collect_async(async_generator_range(0, 5)))
assert result == [0, 1, 2, 3, 4]
def test_collect_empty(self):
result = run_async(collect_async(async_generator_range(0, 0)))
assert result == []
class TestSumAsync:
def test_sum(self):
result = run_async(sum_async(async_generator_range(1, 6)))
assert result == 15 # 1+2+3+4+5
def test_sum_empty(self):
result = run_async(sum_async(async_generator_range(0, 0)))
assert result == 0
class TestCountAsync:
def test_count(self):
result = run_async(count_async(async_generator_range(0, 10)))
assert result == 10
def test_count_empty(self):
result = run_async(count_async(async_generator_range(0, 0)))
assert result == 0
class TestAnyAsync:
def test_found(self):
result = run_async(any_async(async_generator_range(0, 10), 5))
assert result is True
def test_not_found(self):
result = run_async(any_async(async_generator_range(0, 10), 100))
assert result is False
class TestAllPositiveAsync:
def test_all_positive(self):
result = run_async(all_positive_async(async_generator_range(1, 10)))
assert result is True
def test_has_non_positive(self):
async def test():
async def gen():
for i in [1, 2, -3, 4]:
yield i
return await all_positive_async(gen())
assert run_async(test()) is False
class TestFirstLastAsync:
def test_first(self):
result = run_async(first_async(async_generator_range(5, 10)))
assert result == 5
def test_first_empty(self):
result = run_async(first_async(async_generator_range(0, 0)))
assert result == -1
def test_last(self):
result = run_async(last_async(async_generator_range(5, 10)))
assert result == 9
def test_last_empty(self):
result = run_async(last_async(async_generator_range(0, 0)))
assert result == -1
class TestEdgeCases:
def test_empty_generators(self):
assert run_async(collect_async(async_generator_range(0, 0))) == []
assert run_async(collect_async(async_generator_squares(0))) == []
assert run_async(collect_async(async_generator_fibonacci(0))) == []
def test_single_element(self):
assert run_async(collect_async(async_generator_range(5, 6))) == [5]
assert run_async(sum_async(async_generator_range(5, 6))) == 5
assert run_async(first_async(async_generator_range(5, 6))) == 5
| false
|
async_iterator
| 256
| 0
|
[
"async_await",
"generator",
"class_definition"
] | 0.946
|
Error: Statement type not yet supported: AsyncFunctionDef
|
|
example_async_queue
|
async_queue_cli.py
|
#!/usr/bin/env python3
"""Async Queue CLI.
Async queue patterns for producer-consumer scenarios.
"""
import argparse
import asyncio
import sys
from typing import Generic, TypeVar
T = TypeVar("T")
class AsyncQueue(Generic[T]):
"""Simple async queue implementation."""
def __init__(self, maxsize: int = 0) -> None:
self._items: list[T] = []
self._maxsize: int = maxsize
self._closed: bool = False
async def put(self, item: T) -> None:
"""Put item into queue."""
if self._closed:
raise RuntimeError("Queue is closed")
if self._maxsize > 0:
while len(self._items) >= self._maxsize:
await asyncio.sleep(0.001) # Simple backpressure
self._items.append(item)
async def get(self) -> T:
"""Get item from queue."""
while len(self._items) == 0:
if self._closed:
raise RuntimeError("Queue is closed and empty")
await asyncio.sleep(0.001)
return self._items.pop(0)
def get_nowait(self) -> T:
"""Get item without waiting."""
if len(self._items) == 0:
raise RuntimeError("Queue is empty")
return self._items.pop(0)
def put_nowait(self, item: T) -> None:
"""Put item without waiting."""
if self._closed:
raise RuntimeError("Queue is closed")
if self._maxsize > 0 and len(self._items) >= self._maxsize:
raise RuntimeError("Queue is full")
self._items.append(item)
def qsize(self) -> int:
"""Get current queue size."""
return len(self._items)
def empty(self) -> bool:
"""Check if queue is empty."""
return len(self._items) == 0
def full(self) -> bool:
"""Check if queue is full."""
return self._maxsize > 0 and len(self._items) >= self._maxsize
def close(self) -> None:
"""Close the queue."""
self._closed = True
def is_closed(self) -> bool:
"""Check if queue is closed."""
return self._closed
class AsyncChannel(Generic[T]):
"""Async channel for communication between tasks."""
def __init__(self) -> None:
self._queue: AsyncQueue[T] = AsyncQueue()
self._producers: int = 0
self._consumers: int = 0
def add_producer(self) -> None:
"""Register a producer."""
self._producers += 1
def remove_producer(self) -> None:
"""Unregister a producer."""
self._producers -= 1
if self._producers == 0:
self._queue.close()
def add_consumer(self) -> None:
"""Register a consumer."""
self._consumers += 1
def remove_consumer(self) -> None:
"""Unregister a consumer."""
self._consumers -= 1
async def send(self, item: T) -> None:
"""Send item to channel."""
await self._queue.put(item)
async def receive(self) -> T:
"""Receive item from channel."""
return await self._queue.get()
def is_closed(self) -> bool:
"""Check if channel is closed."""
return self._queue.is_closed()
async def producer(queue: AsyncQueue[int], values: list[int]) -> int:
"""Producer that puts values into queue."""
count = 0
for value in values:
await queue.put(value)
count += 1
return count
async def consumer(queue: AsyncQueue[int], count: int) -> list[int]:
"""Consumer that gets values from queue."""
results: list[int] = []
for _ in range(count):
try:
item = await queue.get()
results.append(item)
except RuntimeError:
break
return results
async def worker(queue: AsyncQueue[int], results: list[int]) -> int:
"""Worker that processes items from queue."""
processed = 0
while True:
try:
item = queue.get_nowait()
results.append(item * 2)
processed += 1
except RuntimeError:
break
return processed
async def simple_producer_consumer(values: list[int]) -> list[int]:
"""Simple producer-consumer pattern."""
queue: AsyncQueue[int] = AsyncQueue()
# Produce all items
for v in values:
await queue.put(v)
# Consume all items
results: list[int] = []
while not queue.empty():
item = await queue.get()
results.append(item)
return results
async def bounded_queue_test(values: list[int], maxsize: int) -> list[int]:
"""Test bounded queue behavior."""
queue: AsyncQueue[int] = AsyncQueue(maxsize)
# Try to fill queue
for v in values[:maxsize]:
queue.put_nowait(v)
# Drain queue
results: list[int] = []
while not queue.empty():
results.append(queue.get_nowait())
return results
async def transform_pipeline(values: list[int]) -> list[int]:
"""Transform values through queue pipeline."""
queue1: AsyncQueue[int] = AsyncQueue()
queue2: AsyncQueue[int] = AsyncQueue()
# Stage 1: Add values to first queue
for v in values:
await queue1.put(v)
# Stage 2: Transform and move to second queue
while not queue1.empty():
item = await queue1.get()
await queue2.put(item * 2)
# Stage 3: Collect results
results: list[int] = []
while not queue2.empty():
results.append(await queue2.get())
return results
async def filter_pipeline(values: list[int], threshold: int) -> list[int]:
"""Filter values through queue pipeline."""
input_queue: AsyncQueue[int] = AsyncQueue()
output_queue: AsyncQueue[int] = AsyncQueue()
# Add input values
for v in values:
await input_queue.put(v)
# Filter
while not input_queue.empty():
item = await input_queue.get()
if item >= threshold:
await output_queue.put(item)
# Collect results
results: list[int] = []
while not output_queue.empty():
results.append(await output_queue.get())
return results
async def accumulator_pattern(values: list[int]) -> int:
"""Accumulate values from queue."""
queue: AsyncQueue[int] = AsyncQueue()
# Add values
for v in values:
await queue.put(v)
# Accumulate
total = 0
while not queue.empty():
total += await queue.get()
return total
async def batch_collector(values: list[int], batch_size: int) -> list[list[int]]:
"""Collect values into batches."""
queue: AsyncQueue[int] = AsyncQueue()
# Add values
for v in values:
await queue.put(v)
# Collect batches
batches: list[list[int]] = []
current_batch: list[int] = []
while not queue.empty():
item = await queue.get()
current_batch.append(item)
if len(current_batch) >= batch_size:
batches.append(current_batch)
current_batch = []
if current_batch:
batches.append(current_batch)
return batches
async def priority_queue_simulation(items: list[tuple[int, int]]) -> list[int]:
"""Simulate priority queue using sorted insert."""
queue: AsyncQueue[tuple[int, int]] = AsyncQueue()
# Add items (priority, value)
for item in items:
await queue.put(item)
# Drain and sort by priority
all_items: list[tuple[int, int]] = []
while not queue.empty():
all_items.append(await queue.get())
# Sort by priority (lower is higher priority)
all_items.sort(key=lambda x: x[0])
return [item[1] for item in all_items]
async def round_robin_queues(values: list[int], num_queues: int) -> list[list[int]]:
"""Distribute values across multiple queues."""
queues: list[AsyncQueue[int]] = [AsyncQueue() for _ in range(num_queues)]
# Distribute values
for i, v in enumerate(values):
await queues[i % num_queues].put(v)
# Collect from each queue
results: list[list[int]] = []
for q in queues:
queue_items: list[int] = []
while not q.empty():
queue_items.append(await q.get())
results.append(queue_items)
return results
async def dedup_queue(values: list[int]) -> list[int]:
"""Remove duplicates while maintaining order."""
queue: AsyncQueue[int] = AsyncQueue()
seen: set[int] = set()
# Add values
for v in values:
await queue.put(v)
# Dedup
results: list[int] = []
while not queue.empty():
item = await queue.get()
if item not in seen:
seen.add(item)
results.append(item)
return results
def run_async(coro: object) -> object:
"""Run async function synchronously."""
return asyncio.run(coro) # type: ignore
def main() -> int:
parser = argparse.ArgumentParser(description="Async queue CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# transform
transform_p = subparsers.add_parser("transform", help="Transform pipeline")
transform_p.add_argument("values", type=int, nargs="+")
# filter
filter_p = subparsers.add_parser("filter", help="Filter pipeline")
filter_p.add_argument("values", type=int, nargs="+")
filter_p.add_argument("--threshold", type=int, default=5)
# batch
batch_p = subparsers.add_parser("batch", help="Batch collector")
batch_p.add_argument("values", type=int, nargs="+")
batch_p.add_argument("--size", type=int, default=3)
args = parser.parse_args()
if args.command == "transform":
result = run_async(transform_pipeline(args.values))
print(f"Transformed: {result}")
elif args.command == "filter":
result = run_async(filter_pipeline(args.values, args.threshold))
print(f"Filtered: {result}")
elif args.command == "batch":
result = run_async(batch_collector(args.values, args.size))
print(f"Batches: {result}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
async_queue
| 369
| 0
|
[
"async_await",
"lambda",
"class_definition",
"exception_handling"
] | 0.946
|
Type inference hints:
Hint: int for variable 'count' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'results' [High] (usage patterns suggest this type)
Type inference hints:
Hint: int for variable 'processed' [Medium] (usage patterns suggest this type)
Hint: int for variable 'item' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'results' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for
|
|
example_async_queue
|
test_async_queue_cli.py
|
"""Tests for async_queue_cli.py"""
from async_queue_cli import (
AsyncChannel,
AsyncQueue,
accumulator_pattern,
batch_collector,
bounded_queue_test,
dedup_queue,
filter_pipeline,
priority_queue_simulation,
producer,
round_robin_queues,
run_async,
simple_producer_consumer,
transform_pipeline,
worker,
)
class TestAsyncQueue:
def test_put_get(self):
async def test():
q: AsyncQueue[int] = AsyncQueue()
await q.put(1)
await q.put(2)
return [await q.get(), await q.get()]
assert run_async(test()) == [1, 2]
def test_put_get_nowait(self):
async def test():
q: AsyncQueue[int] = AsyncQueue()
q.put_nowait(1)
q.put_nowait(2)
return [q.get_nowait(), q.get_nowait()]
assert run_async(test()) == [1, 2]
def test_empty(self):
async def test():
q: AsyncQueue[int] = AsyncQueue()
empty_before = q.empty()
await q.put(1)
empty_after = q.empty()
return (empty_before, empty_after)
assert run_async(test()) == (True, False)
def test_qsize(self):
async def test():
q: AsyncQueue[int] = AsyncQueue()
sizes = [q.qsize()]
await q.put(1)
sizes.append(q.qsize())
await q.put(2)
sizes.append(q.qsize())
await q.get()
sizes.append(q.qsize())
return sizes
assert run_async(test()) == [0, 1, 2, 1]
def test_close(self):
async def test():
q: AsyncQueue[int] = AsyncQueue()
q.close()
return q.is_closed()
assert run_async(test()) is True
def test_put_after_close(self):
async def test():
q: AsyncQueue[int] = AsyncQueue()
q.close()
try:
await q.put(1)
return False
except RuntimeError:
return True
assert run_async(test()) is True
class TestBoundedQueue:
def test_full(self):
async def test():
q: AsyncQueue[int] = AsyncQueue(maxsize=2)
q.put_nowait(1)
q.put_nowait(2)
return q.full()
assert run_async(test()) is True
def test_put_nowait_full_raises(self):
async def test():
q: AsyncQueue[int] = AsyncQueue(maxsize=2)
q.put_nowait(1)
q.put_nowait(2)
try:
q.put_nowait(3)
return False
except RuntimeError:
return True
assert run_async(test()) is True
class TestAsyncChannel:
def test_send_receive(self):
async def test():
ch: AsyncChannel[int] = AsyncChannel()
await ch.send(42)
return await ch.receive()
assert run_async(test()) == 42
def test_producer_consumer_tracking(self):
async def test():
ch: AsyncChannel[int] = AsyncChannel()
ch.add_producer()
ch.add_consumer()
await ch.send(1)
await ch.send(2)
ch.remove_producer()
return ch.is_closed()
assert run_async(test()) is True
class TestProducerConsumer:
def test_producer(self):
async def test():
q: AsyncQueue[int] = AsyncQueue()
count = await producer(q, [1, 2, 3, 4, 5])
return count
assert run_async(test()) == 5
def test_simple_producer_consumer(self):
result = run_async(simple_producer_consumer([1, 2, 3, 4, 5]))
assert result == [1, 2, 3, 4, 5]
class TestWorker:
def test_worker_processes_items(self):
async def test():
q: AsyncQueue[int] = AsyncQueue()
q.put_nowait(1)
q.put_nowait(2)
q.put_nowait(3)
results: list[int] = []
processed = await worker(q, results)
return (processed, results)
count, results = run_async(test())
assert count == 3
assert results == [2, 4, 6] # Doubled values
class TestBoundedQueueTest:
def test_bounded(self):
result = run_async(bounded_queue_test([1, 2, 3, 4, 5], 3))
assert result == [1, 2, 3]
class TestTransformPipeline:
def test_transform(self):
result = run_async(transform_pipeline([1, 2, 3]))
assert result == [2, 4, 6]
class TestFilterPipeline:
def test_filter(self):
result = run_async(filter_pipeline([1, 5, 3, 8, 2], 4))
assert result == [5, 8]
class TestAccumulatorPattern:
def test_accumulate(self):
result = run_async(accumulator_pattern([1, 2, 3, 4, 5]))
assert result == 15
class TestBatchCollector:
def test_even_batches(self):
result = run_async(batch_collector([1, 2, 3, 4, 5, 6], 3))
assert result == [[1, 2, 3], [4, 5, 6]]
def test_uneven_batches(self):
result = run_async(batch_collector([1, 2, 3, 4, 5], 3))
assert result == [[1, 2, 3], [4, 5]]
def test_single_batch(self):
result = run_async(batch_collector([1, 2], 5))
assert result == [[1, 2]]
class TestPriorityQueueSimulation:
def test_priority_order(self):
items = [(3, 30), (1, 10), (2, 20)]
result = run_async(priority_queue_simulation(items))
assert result == [10, 20, 30] # Ordered by priority
class TestRoundRobinQueues:
def test_distribution(self):
result = run_async(round_robin_queues([1, 2, 3, 4, 5, 6], 3))
assert result == [[1, 4], [2, 5], [3, 6]]
class TestDedupQueue:
def test_dedup(self):
result = run_async(dedup_queue([1, 2, 2, 3, 1, 4, 3, 5]))
assert result == [1, 2, 3, 4, 5]
def test_no_duplicates(self):
result = run_async(dedup_queue([1, 2, 3]))
assert result == [1, 2, 3]
class TestEdgeCases:
def test_empty_queue(self):
result = run_async(simple_producer_consumer([]))
assert result == []
def test_single_item(self):
result = run_async(simple_producer_consumer([42]))
assert result == [42]
def test_empty_transform(self):
result = run_async(transform_pipeline([]))
assert result == []
def test_empty_batch(self):
result = run_async(batch_collector([], 3))
assert result == []
| false
|
async_queue
| 225
| 0
|
[
"async_await",
"class_definition",
"exception_handling"
] | 0.946
|
Error: Statement type not yet supported: AsyncFunctionDef
|
|
example_backup_tool
|
backup_cli.py
|
#!/usr/bin/env python3
"""Simple backup tool CLI.
Create and restore file backups with timestamps.
"""
import argparse
import hashlib
import os
import shutil
import sys
from datetime import datetime
def get_timestamp() -> str:
"""Get current timestamp for backup naming."""
return datetime.now().strftime("%Y%m%d_%H%M%S_%f")
def parse_timestamp(name: str) -> datetime | None:
"""Parse timestamp from backup name."""
# Extract timestamp pattern YYYYMMDD_HHMMSS_ffffff
parts = name.split("_")
if len(parts) < 3:
return None
try:
date_part = parts[-3]
time_part = parts[-2]
micro_part = parts[-1].split(".")[0] # Remove extension
return datetime.strptime(f"{date_part}_{time_part}_{micro_part}", "%Y%m%d_%H%M%S_%f")
except (ValueError, IndexError):
return None
def get_file_checksum(path: str) -> str:
"""Calculate SHA256 checksum of file."""
hasher = hashlib.sha256()
try:
with open(path, "rb") as f:
while chunk := f.read(65536):
hasher.update(chunk)
return hasher.hexdigest()[:16] # Short checksum
except OSError:
return ""
def create_backup_name(source: str, backup_dir: str) -> str:
"""Create backup filename with timestamp."""
basename = os.path.basename(source)
name, ext = os.path.splitext(basename)
timestamp = get_timestamp()
backup_name = f"{name}_{timestamp}{ext}"
return os.path.join(backup_dir, backup_name)
def backup_file(source: str, backup_dir: str, verify: bool = False) -> str:
"""Create a backup of a file.
Returns backup path on success, empty string on failure.
"""
if not os.path.isfile(source):
return ""
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
backup_path = create_backup_name(source, backup_dir)
try:
shutil.copy2(source, backup_path)
if verify:
src_checksum = get_file_checksum(source)
bak_checksum = get_file_checksum(backup_path)
if src_checksum != bak_checksum:
os.remove(backup_path)
return ""
return backup_path
except OSError:
return ""
def list_backups(backup_dir: str, pattern: str = "") -> list[tuple[str, datetime]]:
"""List backups in directory, optionally filtered by pattern.
Returns list of (path, timestamp) tuples sorted by date.
"""
if not os.path.isdir(backup_dir):
return []
backups = []
for entry in os.listdir(backup_dir):
if pattern and pattern not in entry:
continue
path = os.path.join(backup_dir, entry)
if not os.path.isfile(path):
continue
timestamp = parse_timestamp(entry)
if timestamp:
backups.append((path, timestamp))
return sorted(backups, key=lambda x: x[1], reverse=True)
def get_latest_backup(backup_dir: str, pattern: str = "") -> str:
"""Get the most recent backup matching pattern."""
backups = list_backups(backup_dir, pattern)
if not backups:
return ""
return backups[0][0]
def restore_backup(backup_path: str, dest: str, verify: bool = False) -> bool:
"""Restore a backup to destination."""
if not os.path.isfile(backup_path):
return False
try:
shutil.copy2(backup_path, dest)
if verify:
src_checksum = get_file_checksum(backup_path)
dst_checksum = get_file_checksum(dest)
if src_checksum != dst_checksum:
return False
return True
except OSError:
return False
def prune_backups(backup_dir: str, pattern: str, keep: int) -> int:
"""Remove old backups, keeping only the most recent N.
Returns number of backups removed.
"""
backups = list_backups(backup_dir, pattern)
if len(backups) <= keep:
return 0
removed = 0
for path, _ in backups[keep:]:
try:
os.remove(path)
removed += 1
except OSError:
pass
return removed
def main() -> int:
parser = argparse.ArgumentParser(description="Simple file backup tool")
subparsers = parser.add_subparsers(dest="command", help="Command")
# Backup command
backup_parser = subparsers.add_parser("backup", help="Create a backup")
backup_parser.add_argument("source", help="File to backup")
backup_parser.add_argument("-d", "--dest", default="./backups", help="Backup directory")
backup_parser.add_argument("--verify", action="store_true", help="Verify backup checksum")
# List command
list_parser = subparsers.add_parser("list", help="List backups")
list_parser.add_argument("-d", "--dir", default="./backups", help="Backup directory")
list_parser.add_argument("-p", "--pattern", default="", help="Filter by pattern")
# Restore command
restore_parser = subparsers.add_parser("restore", help="Restore a backup")
restore_parser.add_argument("backup", help="Backup file or 'latest'")
restore_parser.add_argument("dest", help="Destination path")
restore_parser.add_argument("-d", "--dir", default="./backups", help="Backup directory")
restore_parser.add_argument("-p", "--pattern", default="", help="Pattern for latest lookup")
restore_parser.add_argument("--verify", action="store_true", help="Verify restore checksum")
# Prune command
prune_parser = subparsers.add_parser("prune", help="Remove old backups")
prune_parser.add_argument("-d", "--dir", default="./backups", help="Backup directory")
prune_parser.add_argument("-p", "--pattern", default="", help="Filter by pattern")
prune_parser.add_argument("-k", "--keep", type=int, default=5, help="Number of backups to keep")
args = parser.parse_args()
if args.command == "backup":
result = backup_file(args.source, args.dest, args.verify)
if result:
print(f"Created backup: {result}")
return 0
print("Backup failed", file=sys.stderr)
return 1
elif args.command == "list":
backups = list_backups(args.dir, args.pattern)
if not backups:
print("No backups found")
return 0
for path, timestamp in backups:
name = os.path.basename(path)
size = os.path.getsize(path)
print(f"{timestamp.isoformat()} {size:>10} {name}")
return 0
elif args.command == "restore":
if args.backup == "latest":
backup_path = get_latest_backup(args.dir, args.pattern)
if not backup_path:
print("No backups found", file=sys.stderr)
return 1
else:
backup_path = args.backup
if restore_backup(backup_path, args.dest, args.verify):
print(f"Restored {backup_path} to {args.dest}")
return 0
print("Restore failed", file=sys.stderr)
return 1
elif args.command == "prune":
removed = prune_backups(args.dir, args.pattern, args.keep)
print(f"Removed {removed} old backups")
return 0
else:
parser.print_help()
return 1
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_backup_tool/backup_cli.py (7237 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_backup_tool/backup_cli.rs (13411 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_backup_tool/Cargo.toml (5 dependencies)
⏱️ Parse time: 54ms
📊 Throughput: 130.0 KB/s
⏱️ Total time: 54ms
| true
|
backup_tool
| 232
| 6
|
[
"lambda",
"context_manager",
"exception_handling",
"walrus_operator"
] | 0.85
| null |
example_backup_tool
|
test_backup_cli.py
|
"""Tests for backup_cli.py"""
import os
import tempfile
import time
import pytest
from backup_cli import (
backup_file,
get_file_checksum,
get_latest_backup,
get_timestamp,
list_backups,
parse_timestamp,
prune_backups,
restore_backup,
)
@pytest.fixture
def temp_env():
"""Create temporary source file and backup directory."""
with tempfile.TemporaryDirectory() as tmpdir:
source = os.path.join(tmpdir, "source.txt")
backup_dir = os.path.join(tmpdir, "backups")
with open(source, "w") as f:
f.write("test content")
yield source, backup_dir
class TestTimestamp:
def test_get_timestamp_format(self):
ts = get_timestamp()
# Should be YYYYMMDD_HHMMSS_ffffff
assert len(ts) == 22
assert ts[8] == "_"
assert ts[15] == "_"
def test_parse_timestamp(self):
result = parse_timestamp("file_20231225_143000_123456.txt")
assert result is not None
assert result.year == 2023
assert result.month == 12
assert result.day == 25
assert result.hour == 14
assert result.minute == 30
def test_parse_invalid(self):
assert parse_timestamp("invalid") is None
assert parse_timestamp("no_timestamp.txt") is None
class TestChecksum:
def test_checksum_same_content(self, temp_env):
source, backup_dir = temp_env
# Create file with same content
other = os.path.join(os.path.dirname(source), "other.txt")
with open(other, "w") as f:
f.write("test content")
assert get_file_checksum(source) == get_file_checksum(other)
def test_checksum_different_content(self, temp_env):
source, backup_dir = temp_env
other = os.path.join(os.path.dirname(source), "other.txt")
with open(other, "w") as f:
f.write("different content")
assert get_file_checksum(source) != get_file_checksum(other)
def test_checksum_nonexistent(self):
assert get_file_checksum("/nonexistent") == ""
class TestBackupFile:
def test_backup_creates_file(self, temp_env):
source, backup_dir = temp_env
result = backup_file(source, backup_dir)
assert result != ""
assert os.path.exists(result)
assert "source" in result
def test_backup_creates_directory(self, temp_env):
source, backup_dir = temp_env
# backup_dir doesn't exist yet
assert not os.path.exists(backup_dir)
backup_file(source, backup_dir)
assert os.path.exists(backup_dir)
def test_backup_with_verify(self, temp_env):
source, backup_dir = temp_env
result = backup_file(source, backup_dir, verify=True)
assert result != ""
assert get_file_checksum(source) == get_file_checksum(result)
def test_backup_nonexistent_source(self, temp_env):
_, backup_dir = temp_env
result = backup_file("/nonexistent", backup_dir)
assert result == ""
class TestListBackups:
def test_list_empty(self, temp_env):
_, backup_dir = temp_env
backups = list_backups(backup_dir)
assert len(backups) == 0
def test_list_multiple(self, temp_env):
source, backup_dir = temp_env
backup_file(source, backup_dir)
time.sleep(0.1)
backup_file(source, backup_dir)
backups = list_backups(backup_dir)
assert len(backups) == 2
# Should be sorted newest first
assert backups[0][1] >= backups[1][1]
def test_list_with_pattern(self, temp_env):
source, backup_dir = temp_env
backup_file(source, backup_dir)
# Create another source
other = os.path.join(os.path.dirname(source), "other.txt")
with open(other, "w") as f:
f.write("other")
backup_file(other, backup_dir)
backups = list_backups(backup_dir, "source")
assert len(backups) == 1
class TestGetLatestBackup:
def test_get_latest(self, temp_env):
source, backup_dir = temp_env
backup_file(source, backup_dir)
time.sleep(0.1)
second = backup_file(source, backup_dir)
latest = get_latest_backup(backup_dir)
assert latest == second
def test_get_latest_empty(self, temp_env):
_, backup_dir = temp_env
assert get_latest_backup(backup_dir) == ""
class TestRestoreBackup:
def test_restore_success(self, temp_env):
source, backup_dir = temp_env
backup_path = backup_file(source, backup_dir)
dest = os.path.join(os.path.dirname(source), "restored.txt")
assert restore_backup(backup_path, dest) is True
assert os.path.exists(dest)
with open(dest) as f:
assert f.read() == "test content"
def test_restore_with_verify(self, temp_env):
source, backup_dir = temp_env
backup_path = backup_file(source, backup_dir)
dest = os.path.join(os.path.dirname(source), "restored.txt")
assert restore_backup(backup_path, dest, verify=True) is True
def test_restore_nonexistent(self, temp_env):
source, _ = temp_env
dest = os.path.join(os.path.dirname(source), "restored.txt")
assert restore_backup("/nonexistent", dest) is False
class TestPruneBackups:
def test_prune_keeps_recent(self, temp_env):
source, backup_dir = temp_env
# Create 5 backups
for _ in range(5):
backup_file(source, backup_dir)
time.sleep(0.1)
# Prune keeping 3
removed = prune_backups(backup_dir, "", keep=3)
assert removed == 2
backups = list_backups(backup_dir)
assert len(backups) == 3
def test_prune_nothing_to_remove(self, temp_env):
source, backup_dir = temp_env
backup_file(source, backup_dir)
backup_file(source, backup_dir)
removed = prune_backups(backup_dir, "", keep=5)
assert removed == 0
| false
|
backup_tool
| 209
| 0
|
[
"generator",
"context_manager",
"class_definition",
"decorator"
] | 0.927
|
Type inference hints:
Hint: str for variable 'source' [Medium] (usage patterns suggest this type)
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions: 1
Total estimated allocations: 0
Functions analyzed: 1
Hot Paths
[1] temp_env (100.0% of execution time)
Function Metrics
🔥 temp_env 100.0% time | 1 inst | 0 alloc
Performance Predictions
• Rust's memory layout is more cache-friendly than Python (1.
|
|
example_base64
|
encode_tool.py
|
#!/usr/bin/env python3
"""Base64 Example - Encoding/decoding CLI."""
import argparse
import base64
import sys
def cmd_encode(args):
"""Base64 encode. Depyler: proven to terminate"""
data = sys.stdin.read().strip()
encoded = base64.b64encode(data.encode()).decode()
print(encoded)
def cmd_decode(args):
"""Base64 decode. Depyler: proven to terminate"""
data = sys.stdin.read().strip()
decoded = base64.b64decode(data).decode()
print(decoded)
def cmd_urlsafe_encode(args):
"""URL-safe base64 encode. Depyler: proven to terminate"""
data = sys.stdin.read().strip()
encoded = base64.urlsafe_b64encode(data.encode()).decode()
print(encoded)
def main():
parser = argparse.ArgumentParser(description="Base64 encoding tool")
subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("encode")
subparsers.add_parser("decode")
subparsers.add_parser("urlsafe-encode")
args = parser.parse_args()
if args.command == "encode":
cmd_encode(args)
elif args.command == "decode":
cmd_decode(args)
elif args.command == "urlsafe-encode":
cmd_urlsafe_encode(args)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_base64/encode_tool.py (1231 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_base64/encode_tool.rs (2467 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_base64/Cargo.toml (2 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 24.5 KB/s
⏱️ Total time: 49ms
| true
|
base64
| 48
| 6
|
[
"stdin_usage"
] | 0.566
| null |
example_base64
|
test_encode_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for base64 CLI."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "encode_tool.py"
SCRIPT = "encode_tool.py"
def run(args, input_text=None):
return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True,
input=input_text, cwd=__file__.rsplit("/", 1)[0])
class TestEncode:
def test_encode(self):
result = run(["encode"], "hello")
assert result.returncode == 0
assert "aGVsbG8=" in result.stdout
def test_encode_longer(self):
result = run(["encode"], "hello world")
assert result.returncode == 0
assert "aGVsbG8gd29ybGQ=" in result.stdout
class TestDecode:
def test_decode(self):
result = run(["decode"], "aGVsbG8=")
assert result.returncode == 0
assert "hello" in result.stdout
class TestUrlsafe:
def test_urlsafe_encode(self):
result = run(["urlsafe-encode"], "hello+world")
assert result.returncode == 0
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_base64/test_encode_tool.py (1152 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_base64/test_encode_tool.rs (2705 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_base64/Cargo.toml (2 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 22.5 KB/s
⏱️ Total time: 50ms
| true
|
base64
| 39
| 6
|
[
"class_definition"
] | 0.612
| null |
example_batch_processor
|
batch_cli.py
|
#!/usr/bin/env python3
"""Batch processor CLI.
Process items in batches with progress tracking.
"""
import argparse
import json
import sys
import time
from dataclasses import dataclass
@dataclass
class BatchResult:
"""Result of processing a batch."""
batch_index: int
items_processed: int
items_failed: int
duration: float
errors: list[str]
@dataclass
class ProcessingStats:
"""Overall processing statistics."""
total_items: int
processed_items: int
failed_items: int
total_batches: int
completed_batches: int
start_time: float
end_time: float | None
def __init__(self, total_items: int, batch_size: int):
self.total_items = total_items
self.processed_items = 0
self.failed_items = 0
self.total_batches = (total_items + batch_size - 1) // batch_size
self.completed_batches = 0
self.start_time = time.time()
self.end_time = None
def elapsed(self) -> float:
"""Get elapsed time."""
end = self.end_time or time.time()
return end - self.start_time
def progress(self) -> float:
"""Get progress percentage."""
if self.total_items == 0:
return 100.0
return (self.processed_items / self.total_items) * 100
def items_per_second(self) -> float:
"""Get processing rate."""
elapsed = self.elapsed()
if elapsed == 0:
return 0.0
return self.processed_items / elapsed
def estimated_remaining(self) -> float:
"""Get estimated time remaining."""
rate = self.items_per_second()
if rate == 0:
return 0.0
remaining_items = self.total_items - self.processed_items
return remaining_items / rate
def to_dict(self) -> dict:
return {
"total_items": self.total_items,
"processed_items": self.processed_items,
"failed_items": self.failed_items,
"total_batches": self.total_batches,
"completed_batches": self.completed_batches,
"elapsed_seconds": self.elapsed(),
"progress_percent": self.progress(),
"items_per_second": self.items_per_second(),
"estimated_remaining_seconds": self.estimated_remaining(),
}
def chunk_list(items: list, chunk_size: int) -> list[list]:
"""Split list into chunks."""
return [items[i : i + chunk_size] for i in range(0, len(items), chunk_size)]
def process_item_dummy(item: str, fail_rate: float = 0.0) -> tuple[bool, str]:
"""Dummy item processor for demonstration."""
import random
if random.random() < fail_rate:
return False, f"Failed to process: {item}"
return True, ""
def process_batch(
batch: list,
batch_index: int,
processor=None,
delay: float = 0.0,
) -> BatchResult:
"""Process a single batch of items."""
if processor is None:
processor = process_item_dummy
start = time.time()
processed = 0
failed = 0
errors = []
for item in batch:
success, error = processor(item)
if success:
processed += 1
else:
failed += 1
errors.append(error)
if delay > 0:
time.sleep(delay)
return BatchResult(
batch_index=batch_index,
items_processed=processed,
items_failed=failed,
duration=time.time() - start,
errors=errors,
)
def process_all(
items: list,
batch_size: int,
processor=None,
delay: float = 0.0,
on_batch_complete=None,
) -> tuple[ProcessingStats, list[BatchResult]]:
"""Process all items in batches."""
stats = ProcessingStats(len(items), batch_size)
batches = chunk_list(items, batch_size)
results = []
for i, batch in enumerate(batches):
result = process_batch(batch, i, processor, delay)
results.append(result)
stats.processed_items += result.items_processed
stats.failed_items += result.items_failed
stats.completed_batches += 1
if on_batch_complete:
on_batch_complete(stats, result)
stats.end_time = time.time()
return stats, results
def format_progress(stats: ProcessingStats, width: int = 30) -> str:
"""Format progress as a status line."""
progress = stats.progress()
filled = int(width * progress / 100)
bar = "█" * filled + "░" * (width - filled)
rate = stats.items_per_second()
remaining = stats.estimated_remaining()
return (
f"[{bar}] {progress:.1f}% "
f"({stats.processed_items}/{stats.total_items}) "
f"{rate:.1f}/s "
f"ETA: {remaining:.1f}s"
)
def generate_items(count: int, prefix: str = "item") -> list[str]:
"""Generate test items."""
return [f"{prefix}_{i}" for i in range(count)]
def main() -> int:
parser = argparse.ArgumentParser(description="Batch processing tool")
parser.add_argument("input", nargs="?", help="Input file with items (one per line)")
parser.add_argument(
"-n", "--count", type=int, default=100, help="Number of items to generate (if no input)"
)
parser.add_argument("-b", "--batch-size", type=int, default=10, help="Batch size")
parser.add_argument("--delay", type=float, default=0.0, help="Delay per item (seconds)")
parser.add_argument(
"--fail-rate", type=float, default=0.0, help="Simulated failure rate (0.0 to 1.0)"
)
parser.add_argument("--progress", action="store_true", help="Show progress bar")
parser.add_argument("--json", action="store_true", help="Output results as JSON")
parser.add_argument("--dry-run", action="store_true", help="Show batch plan without processing")
args = parser.parse_args()
# Get items
if args.input:
if args.input == "-":
items = [line.strip() for line in sys.stdin if line.strip()]
else:
with open(args.input) as f:
items = [line.strip() for line in f if line.strip()]
else:
items = generate_items(args.count)
if not items:
print("No items to process")
return 0
batches = chunk_list(items, args.batch_size)
if args.dry_run:
print(f"Total items: {len(items)}")
print(f"Batch size: {args.batch_size}")
print(f"Total batches: {len(batches)}")
print("\nBatch plan:")
for i, batch in enumerate(batches):
print(f" Batch {i + 1}: {len(batch)} items")
return 0
# Create processor with fail rate
def processor(item):
return process_item_dummy(item, args.fail_rate)
# Progress callback
def on_progress(stats, result):
if args.progress:
print(f"\r{format_progress(stats)}", end="", flush=True)
stats, results = process_all(
items,
args.batch_size,
processor,
args.delay,
on_progress,
)
if args.progress:
print() # Newline after progress bar
if args.json:
output = {
"stats": stats.to_dict(),
"batches": [
{
"index": r.batch_index,
"processed": r.items_processed,
"failed": r.items_failed,
"duration": r.duration,
"errors": r.errors,
}
for r in results
],
}
print(json.dumps(output, indent=2))
else:
print("\nProcessing complete:")
print(f" Total items: {stats.total_items}")
print(f" Processed: {stats.processed_items}")
print(f" Failed: {stats.failed_items}")
print(f" Total time: {stats.elapsed():.2f}s")
print(f" Rate: {stats.items_per_second():.1f} items/s")
if stats.failed_items > 0:
print(f"\nErrors ({stats.failed_items}):")
for result in results:
for error in result.errors[:5]: # Limit errors shown
print(f" - {error}")
return 0 if stats.failed_items == 0 else 1
if __name__ == "__main__":
sys.exit(main())
| false
|
batch_processor
| 279
| 0
|
[
"context_manager",
"class_definition",
"stdin_usage",
"decorator",
"multiprocessing"
] | 0.652
|
Type inference hints:
Hint: int for variable 'failed' [Medium] (usage patterns suggest this type)
Hint: int for variable 'processed' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'errors' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'items' [High] (usage patterns suggest this type)
Hint: list[Any] for variable 'results' [High] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'remaining' [M
|
|
example_batch_processor
|
test_batch_cli.py
|
"""Tests for batch_cli.py"""
import time
from batch_cli import (
ProcessingStats,
chunk_list,
format_progress,
generate_items,
process_all,
process_batch,
process_item_dummy,
)
class TestChunkList:
def test_even_split(self):
items = list(range(10))
chunks = chunk_list(items, 5)
assert len(chunks) == 2
assert chunks[0] == [0, 1, 2, 3, 4]
assert chunks[1] == [5, 6, 7, 8, 9]
def test_uneven_split(self):
items = list(range(7))
chunks = chunk_list(items, 3)
assert len(chunks) == 3
assert chunks[0] == [0, 1, 2]
assert chunks[1] == [3, 4, 5]
assert chunks[2] == [6]
def test_single_item_chunks(self):
items = [1, 2, 3]
chunks = chunk_list(items, 1)
assert len(chunks) == 3
assert all(len(c) == 1 for c in chunks)
def test_larger_chunk_than_items(self):
items = [1, 2]
chunks = chunk_list(items, 10)
assert len(chunks) == 1
assert chunks[0] == [1, 2]
def test_empty_list(self):
chunks = chunk_list([], 5)
assert chunks == []
class TestProcessItemDummy:
def test_success(self):
success, error = process_item_dummy("test", fail_rate=0.0)
assert success is True
assert error == ""
def test_always_fail(self):
success, error = process_item_dummy("test", fail_rate=1.0)
assert success is False
assert "test" in error
class TestProcessBatch:
def test_all_success(self):
items = ["a", "b", "c"]
def always_succeed(item):
return True, ""
result = process_batch(items, 0, always_succeed)
assert result.items_processed == 3
assert result.items_failed == 0
assert result.batch_index == 0
def test_all_fail(self):
items = ["a", "b", "c"]
def always_fail(item):
return False, f"Failed: {item}"
result = process_batch(items, 0, always_fail)
assert result.items_processed == 0
assert result.items_failed == 3
assert len(result.errors) == 3
def test_mixed(self):
items = ["a", "b", "c"]
counter = [0]
def alternate(item):
counter[0] += 1
if counter[0] % 2 == 0:
return False, "Failed"
return True, ""
result = process_batch(items, 0, alternate)
assert result.items_processed == 2
assert result.items_failed == 1
class TestProcessingStats:
def test_init(self):
stats = ProcessingStats(100, 10)
assert stats.total_items == 100
assert stats.total_batches == 10
assert stats.processed_items == 0
def test_init_uneven(self):
stats = ProcessingStats(95, 10)
assert stats.total_batches == 10 # ceil(95/10)
def test_progress(self):
stats = ProcessingStats(100, 10)
assert stats.progress() == 0.0
stats.processed_items = 50
assert stats.progress() == 50.0
stats.processed_items = 100
assert stats.progress() == 100.0
def test_items_per_second(self):
stats = ProcessingStats(100, 10)
stats.processed_items = 50
# Manually set start time
stats.start_time = time.time() - 5 # 5 seconds ago
rate = stats.items_per_second()
assert 9.0 <= rate <= 11.0 # About 10/s
def test_estimated_remaining(self):
stats = ProcessingStats(100, 10)
stats.processed_items = 50
stats.start_time = time.time() - 5 # 5 seconds ago
remaining = stats.estimated_remaining()
assert 4.0 <= remaining <= 6.0 # About 5 seconds
def test_to_dict(self):
stats = ProcessingStats(100, 10)
stats.processed_items = 50
d = stats.to_dict()
assert d["total_items"] == 100
assert d["processed_items"] == 50
assert "progress_percent" in d
class TestProcessAll:
def test_simple(self):
items = list(range(10))
def processor(item):
return True, ""
stats, results = process_all(items, 3, processor)
assert stats.processed_items == 10
assert stats.failed_items == 0
assert len(results) == 4 # ceil(10/3)
def test_with_failures(self):
items = list(range(10))
def half_fail(item):
if item % 2 == 0:
return False, "Even number"
return True, ""
stats, results = process_all(items, 5, half_fail)
assert stats.processed_items == 5
assert stats.failed_items == 5
def test_callback(self):
items = list(range(10))
callback_count = [0]
def processor(item):
return True, ""
def callback(stats, result):
callback_count[0] += 1
process_all(items, 3, processor, 0, callback)
assert callback_count[0] == 4 # 4 batches
class TestFormatProgress:
def test_format(self):
stats = ProcessingStats(100, 10)
stats.processed_items = 50
result = format_progress(stats)
assert "50.0%" in result
assert "50/100" in result
class TestGenerateItems:
def test_generate(self):
items = generate_items(5)
assert len(items) == 5
assert all(item.startswith("item_") for item in items)
def test_custom_prefix(self):
items = generate_items(3, "task")
assert items[0] == "task_0"
| false
|
batch_processor
| 205
| 0
|
[
"class_definition",
"multiprocessing"
] | 0.612
|
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: Eq, left: Call { func: "len", args: [Var("c")], kwargs: [] }, right: Literal(Int(1)) }, generators: [HirComprehension { target: "c", iter: Var("chunks"), conditions: [] }] }
|
|
example_bencode_codec
|
bencode_cli.py
|
#!/usr/bin/env python3
"""Bencode codec CLI.
Encode and decode BitTorrent bencode format.
"""
import argparse
import json
import sys
def encode_int(value: int) -> bytes:
"""Encode integer to bencode."""
return f"i{value}e".encode("ascii")
def encode_bytes(value: bytes) -> bytes:
"""Encode bytes to bencode."""
return f"{len(value)}:".encode("ascii") + value
def encode_string(value: str) -> bytes:
"""Encode string to bencode."""
encoded = value.encode("utf-8")
return f"{len(encoded)}:".encode("ascii") + encoded
def encode_list(value: list) -> bytes:
"""Encode list to bencode."""
result = b"l"
for item in value:
result += bencode_encode(item)
result += b"e"
return result
def encode_dict(value: dict) -> bytes:
"""Encode dict to bencode.
Keys must be strings and are sorted.
"""
result = b"d"
for key in sorted(value.keys()):
result += encode_string(str(key))
result += bencode_encode(value[key])
result += b"e"
return result
def bencode_encode(value) -> bytes:
"""Encode Python value to bencode."""
if isinstance(value, int):
return encode_int(value)
if isinstance(value, bytes):
return encode_bytes(value)
if isinstance(value, str):
return encode_string(value)
if isinstance(value, list):
return encode_list(value)
if isinstance(value, dict):
return encode_dict(value)
raise ValueError(f"Cannot encode type: {type(value)}")
class BencodeDecoder:
"""Stateful bencode decoder."""
def __init__(self, data: bytes):
self.data = data
self.pos = 0
def decode(self):
"""Decode next value."""
if self.pos >= len(self.data):
raise ValueError("Unexpected end of data")
byte = self.data[self.pos]
if byte == ord("i"):
return self.decode_int()
if byte == ord("l"):
return self.decode_list()
if byte == ord("d"):
return self.decode_dict()
if ord("0") <= byte <= ord("9"):
return self.decode_string()
raise ValueError(f"Invalid bencode at position {self.pos}")
def decode_int(self) -> int:
"""Decode bencode integer."""
self.pos += 1 # Skip 'i'
end = self.data.index(ord("e"), self.pos)
value = int(self.data[self.pos : end].decode("ascii"))
self.pos = end + 1
return value
def decode_string(self) -> str:
"""Decode bencode string."""
colon = self.data.index(ord(":"), self.pos)
length = int(self.data[self.pos : colon].decode("ascii"))
self.pos = colon + 1
value = self.data[self.pos : self.pos + length]
self.pos += length
try:
return value.decode("utf-8")
except UnicodeDecodeError:
# Return hex for binary data
return value.hex()
def decode_list(self) -> list:
"""Decode bencode list."""
self.pos += 1 # Skip 'l'
result = []
while self.data[self.pos] != ord("e"):
result.append(self.decode())
self.pos += 1 # Skip 'e'
return result
def decode_dict(self) -> dict:
"""Decode bencode dict."""
self.pos += 1 # Skip 'd'
result = {}
while self.data[self.pos] != ord("e"):
key = self.decode_string()
value = self.decode()
result[key] = value
self.pos += 1 # Skip 'e'
return result
def bencode_decode(data: bytes):
"""Decode bencode data to Python value."""
decoder = BencodeDecoder(data)
return decoder.decode()
def validate_bencode(data: bytes) -> tuple[bool, str]:
"""Validate bencode data.
Returns (is_valid, error_message).
"""
try:
bencode_decode(data)
return True, ""
except Exception as e:
return False, str(e)
def main() -> int:
parser = argparse.ArgumentParser(description="Encode and decode bencode format")
parser.add_argument("input", nargs="?", help="Input file (- for stdin)")
parser.add_argument("-e", "--encode", action="store_true", help="Encode JSON to bencode")
parser.add_argument("-d", "--decode", action="store_true", help="Decode bencode to JSON")
parser.add_argument("--validate", action="store_true", help="Validate bencode data")
parser.add_argument("-o", "--output", help="Output file")
args = parser.parse_args()
# Read input
if args.input is None or args.input == "-":
if args.encode:
data = sys.stdin.read()
else:
data = sys.stdin.buffer.read()
else:
if args.encode:
with open(args.input) as f:
data = f.read()
else:
with open(args.input, "rb") as f:
data = f.read()
# Process
if args.validate:
if isinstance(data, str):
data = data.encode("utf-8")
valid, error = validate_bencode(data)
if valid:
print("Valid bencode")
return 0
print(f"Invalid: {error}", file=sys.stderr)
return 1
if args.encode:
try:
obj = json.loads(data)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}", file=sys.stderr)
return 1
result = bencode_encode(obj)
if args.output:
with open(args.output, "wb") as f:
f.write(result)
else:
sys.stdout.buffer.write(result)
sys.stdout.buffer.write(b"\n")
elif args.decode:
try:
obj = bencode_decode(data)
except Exception as e:
print(f"Decode error: {e}", file=sys.stderr)
return 1
result = json.dumps(obj, indent=2)
if args.output:
with open(args.output, "w") as f:
f.write(result)
else:
print(result)
else:
# Default: detect and show info
if isinstance(data, str):
data = data.encode("utf-8")
valid, error = validate_bencode(data)
if valid:
obj = bencode_decode(data)
print(f"Type: {type(obj).__name__}")
if isinstance(obj, dict):
print(f"Keys: {list(obj.keys())}")
elif isinstance(obj, list):
print(f"Length: {len(obj)}")
else:
print(f"Invalid bencode: {error}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_bencode_codec/bencode_cli.py (6564 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_bencode_codec/bencode_cli.rs (13992 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_bencode_codec/Cargo.toml (3 dependencies)
⏱️ Parse time: 56ms
📊 Throughput: 113.9 KB/s
⏱️ Total time: 56ms
| true
|
bencode_codec
| 238
| 6
|
[
"context_manager",
"class_definition",
"exception_handling",
"stdin_usage",
"multiprocessing"
] | 0.652
| null |
example_bencode_codec
|
test_bencode_cli.py
|
"""Tests for bencode_cli.py"""
from bencode_cli import (
bencode_decode,
bencode_encode,
encode_bytes,
encode_dict,
encode_int,
encode_list,
encode_string,
validate_bencode,
)
class TestEncodeInt:
def test_positive(self):
assert encode_int(42) == b"i42e"
def test_zero(self):
assert encode_int(0) == b"i0e"
def test_negative(self):
assert encode_int(-10) == b"i-10e"
class TestEncodeString:
def test_simple(self):
assert encode_string("hello") == b"5:hello"
def test_empty(self):
assert encode_string("") == b"0:"
def test_unicode(self):
result = encode_string("héllo")
# 6 bytes due to UTF-8 encoding of é
assert result.startswith(b"6:")
class TestEncodeBytes:
def test_simple(self):
assert encode_bytes(b"hello") == b"5:hello"
def test_binary(self):
assert encode_bytes(b"\x00\x01\x02") == b"3:\x00\x01\x02"
class TestEncodeList:
def test_simple(self):
result = encode_list([1, 2, 3])
assert result == b"li1ei2ei3ee"
def test_empty(self):
assert encode_list([]) == b"le"
def test_mixed(self):
result = encode_list(["a", 1])
assert result == b"l1:ai1ee"
class TestEncodeDict:
def test_simple(self):
result = encode_dict({"key": "value"})
assert result == b"d3:key5:valuee"
def test_empty(self):
assert encode_dict({}) == b"de"
def test_sorted_keys(self):
result = encode_dict({"b": 2, "a": 1})
# Keys should be sorted
assert result == b"d1:ai1e1:bi2ee"
class TestBencodeEncode:
def test_roundtrip_int(self):
original = 42
encoded = bencode_encode(original)
decoded = bencode_decode(encoded)
assert decoded == original
def test_roundtrip_string(self):
original = "hello world"
encoded = bencode_encode(original)
decoded = bencode_decode(encoded)
assert decoded == original
def test_roundtrip_list(self):
original = ["a", "b", "c"]
encoded = bencode_encode(original)
decoded = bencode_decode(encoded)
assert decoded == original
def test_roundtrip_dict(self):
original = {"name": "test", "value": 123}
encoded = bencode_encode(original)
decoded = bencode_decode(encoded)
assert decoded == original
def test_complex_structure(self):
original = {
"announce": "http://tracker.example.com",
"info": {
"name": "file.txt",
"length": 1024,
"pieces": ["abc", "def"],
},
}
encoded = bencode_encode(original)
decoded = bencode_decode(encoded)
assert decoded == original
class TestBencodeDecode:
def test_int(self):
assert bencode_decode(b"i42e") == 42
def test_negative_int(self):
assert bencode_decode(b"i-10e") == -10
def test_string(self):
assert bencode_decode(b"5:hello") == "hello"
def test_list(self):
assert bencode_decode(b"li1ei2ei3ee") == [1, 2, 3]
def test_dict(self):
result = bencode_decode(b"d3:key5:valuee")
assert result == {"key": "value"}
def test_nested(self):
data = b"d4:listli1ei2ee4:namei42ee"
result = bencode_decode(data)
assert result == {"list": [1, 2], "name": 42}
class TestValidateBencode:
def test_valid(self):
valid, error = validate_bencode(b"i42e")
assert valid is True
assert error == ""
def test_invalid(self):
valid, error = validate_bencode(b"invalid")
assert valid is False
assert error != ""
def test_truncated(self):
valid, error = validate_bencode(b"i42")
assert valid is False
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_bencode_codec/test_bencode_cli.py (3848 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_bencode_codec/test_bencode_cli.rs (8640 bytes)
⏱️ Parse time: 51ms
📊 Throughput: 73.1 KB/s
⏱️ Total time: 51ms
| true
|
bencode_codec
| 149
| 5
|
[
"class_definition"
] | 0.612
| null |
example_bin
|
bin_tool.py
|
#!/usr/bin/env python3
"""Bin Example - Binary operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Binary operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
t = subs.add_parser("tobin")
t.add_argument("num", type=int)
f = subs.add_parser("frombin")
f.add_argument("binstr")
b = subs.add_parser("bits")
b.add_argument("num", type=int)
args = parser.parse_args()
if args.cmd == "tobin":
print(format(args.num, "b"))
elif args.cmd == "frombin":
print(int(args.binstr, 2))
elif args.cmd == "bits":
count = 0
n = args.num
while n > 0:
count = count + 1
n = n // 2
print(count)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_bin/bin_tool.py (801 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_bin/bin_tool.rs (2624 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_bin/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 16.3 KB/s
⏱️ Total time: 48ms
| true
|
bin
| 33
| 6
|
[] | 0
| null |
example_bin
|
test_bin_tool.py
|
"""Tests for bin_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "bin_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_tobin():
r = run("tobin 10")
assert r.returncode == 0
assert r.stdout.strip() == "1010"
def test_frombin():
r = run("frombin 1010")
assert r.returncode == 0
assert r.stdout.strip() == "10"
def test_bits():
r = run("bits 255")
assert r.returncode == 0
assert r.stdout.strip() == "8"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_bin/test_bin_tool.py (610 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_bin/test_bin_tool.rs (1820 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_bin/Cargo.toml (2 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 12.6 KB/s
⏱️ Total time: 47ms
| true
|
bin
| 32
| 6
|
[] | 0
| null |
example_binary_codec
|
binary_codec_cli.py
|
#!/usr/bin/env python3
"""Binary Codec CLI.
Binary encoding/decoding utilities (base64, hex, etc).
"""
import argparse
import base64
import sys
def encode_hex(data: bytes) -> str:
"""Encode bytes to hex string."""
return data.hex()
def decode_hex(hex_str: str) -> bytes:
"""Decode hex string to bytes."""
return bytes.fromhex(hex_str)
def encode_hex_upper(data: bytes) -> str:
"""Encode bytes to uppercase hex string."""
return data.hex().upper()
def encode_base64(data: bytes) -> str:
"""Encode bytes to base64 string."""
return base64.b64encode(data).decode("ascii")
def decode_base64(b64_str: str) -> bytes:
"""Decode base64 string to bytes."""
return base64.b64decode(b64_str)
def encode_base64_url(data: bytes) -> str:
"""Encode bytes to URL-safe base64."""
return base64.urlsafe_b64encode(data).decode("ascii")
def decode_base64_url(b64_str: str) -> bytes:
"""Decode URL-safe base64 string."""
return base64.urlsafe_b64decode(b64_str)
def encode_base32(data: bytes) -> str:
"""Encode bytes to base32 string."""
return base64.b32encode(data).decode("ascii")
def decode_base32(b32_str: str) -> bytes:
"""Decode base32 string to bytes."""
return base64.b32decode(b32_str)
def encode_base16(data: bytes) -> str:
"""Encode bytes to base16 (hex) string."""
return base64.b16encode(data).decode("ascii")
def decode_base16(b16_str: str) -> bytes:
"""Decode base16 (hex) string to bytes."""
return base64.b16decode(b16_str)
def bytes_to_binary_string(data: bytes) -> str:
"""Convert bytes to binary string representation."""
return " ".join(format(b, "08b") for b in data)
def binary_string_to_bytes(bin_str: str) -> bytes:
"""Convert binary string to bytes."""
parts = bin_str.split()
return bytes(int(p, 2) for p in parts)
def bytes_to_int_list(data: bytes) -> list[int]:
"""Convert bytes to list of integers."""
return list(data)
def int_list_to_bytes(values: list[int]) -> bytes:
"""Convert list of integers to bytes."""
return bytes(values)
def encode_ascii_hex(text: str) -> str:
"""Encode ASCII text to hex representation."""
return text.encode("ascii").hex()
def decode_ascii_hex(hex_str: str) -> str:
"""Decode hex to ASCII text."""
return bytes.fromhex(hex_str).decode("ascii")
def encode_utf8_hex(text: str) -> str:
"""Encode UTF-8 text to hex representation."""
return text.encode("utf-8").hex()
def decode_utf8_hex(hex_str: str) -> str:
"""Decode hex to UTF-8 text."""
return bytes.fromhex(hex_str).decode("utf-8")
def escape_bytes(data: bytes) -> str:
"""Escape non-printable bytes as \\xNN."""
result = []
for b in data:
if 32 <= b < 127:
result.append(chr(b))
else:
result.append(f"\\x{b:02x}")
return "".join(result)
def unescape_bytes(text: str) -> bytes:
"""Unescape \\xNN sequences to bytes."""
result = bytearray()
i = 0
while i < len(text):
if text[i : i + 2] == "\\x" and i + 4 <= len(text):
hex_chars = text[i + 2 : i + 4]
try:
result.append(int(hex_chars, 16))
i += 4
continue
except ValueError:
pass
result.append(ord(text[i]))
i += 1
return bytes(result)
def run_length_encode(data: bytes) -> bytes:
"""Simple run-length encoding."""
if len(data) == 0:
return b""
result = bytearray()
current = data[0]
count = 1
for i in range(1, len(data)):
if data[i] == current and count < 255:
count += 1
else:
result.append(count)
result.append(current)
current = data[i]
count = 1
result.append(count)
result.append(current)
return bytes(result)
def run_length_decode(data: bytes) -> bytes:
"""Simple run-length decoding."""
result = bytearray()
i = 0
while i + 1 < len(data):
count = data[i]
value = data[i + 1]
result.extend([value] * count)
i += 2
return bytes(result)
def xor_cipher(data: bytes, key: bytes) -> bytes:
"""XOR cipher with repeating key."""
result = bytearray(len(data))
key_len = len(key)
if key_len == 0:
return bytes(data)
for i in range(len(data)):
result[i] = data[i] ^ key[i % key_len]
return bytes(result)
def caesar_cipher(data: bytes, shift: int) -> bytes:
"""Caesar cipher on byte values."""
result = bytearray(len(data))
for i in range(len(data)):
result[i] = (data[i] + shift) & 0xFF
return bytes(result)
def caesar_decipher(data: bytes, shift: int) -> bytes:
"""Reverse Caesar cipher."""
return caesar_cipher(data, -shift)
def bit_reverse_bytes(data: bytes) -> bytes:
"""Reverse bits in each byte."""
result = bytearray(len(data))
for i, b in enumerate(data):
reversed_byte = 0
for j in range(8):
if b & (1 << j):
reversed_byte |= 1 << (7 - j)
result[i] = reversed_byte
return bytes(result)
def nibble_swap(data: bytes) -> bytes:
"""Swap high and low nibbles in each byte."""
result = bytearray(len(data))
for i, b in enumerate(data):
result[i] = ((b & 0x0F) << 4) | ((b >> 4) & 0x0F)
return bytes(result)
def invert_bytes(data: bytes) -> bytes:
"""Invert all bytes (NOT operation)."""
result = bytearray(len(data))
for i, b in enumerate(data):
result[i] = (~b) & 0xFF
return bytes(result)
def calculate_crc8(data: bytes, polynomial: int = 0x07) -> int:
"""Calculate CRC-8 checksum."""
crc = 0
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x80:
crc = ((crc << 1) ^ polynomial) & 0xFF
else:
crc = (crc << 1) & 0xFF
return crc
def calculate_crc16(data: bytes, polynomial: int = 0x8005) -> int:
"""Calculate CRC-16 checksum."""
crc = 0xFFFF
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 1:
crc = (crc >> 1) ^ polynomial
else:
crc >>= 1
return crc
def hamming_encode_nibble(nibble: int) -> int:
"""Encode a nibble with Hamming(7,4) code."""
d = [(nibble >> i) & 1 for i in range(4)]
p1 = d[0] ^ d[1] ^ d[3]
p2 = d[0] ^ d[2] ^ d[3]
p3 = d[1] ^ d[2] ^ d[3]
return p1 | (p2 << 1) | (d[0] << 2) | (p3 << 3) | (d[1] << 4) | (d[2] << 5) | (d[3] << 6)
def hamming_decode_byte(encoded: int) -> tuple[int, int]:
"""Decode Hamming(7,4) code, return (data, errors)."""
p1 = ((encoded >> 0) ^ (encoded >> 2) ^ (encoded >> 4) ^ (encoded >> 6)) & 1
p2 = ((encoded >> 1) ^ (encoded >> 2) ^ (encoded >> 5) ^ (encoded >> 6)) & 1
p3 = ((encoded >> 3) ^ (encoded >> 4) ^ (encoded >> 5) ^ (encoded >> 6)) & 1
error_pos = p1 | (p2 << 1) | (p3 << 2)
if error_pos:
encoded ^= 1 << (error_pos - 1)
data = (
((encoded >> 2) & 1)
| (((encoded >> 4) & 1) << 1)
| (((encoded >> 5) & 1) << 2)
| (((encoded >> 6) & 1) << 3)
)
return (data, 1 if error_pos else 0)
def main() -> int:
parser = argparse.ArgumentParser(description="Binary codec CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# hex
hex_p = subparsers.add_parser("hex", help="Hex encode/decode")
hex_p.add_argument("action", choices=["encode", "decode"])
hex_p.add_argument("data")
# base64
b64_p = subparsers.add_parser("base64", help="Base64 encode/decode")
b64_p.add_argument("action", choices=["encode", "decode"])
b64_p.add_argument("data")
b64_p.add_argument("--url-safe", action="store_true")
# rle
rle_p = subparsers.add_parser("rle", help="Run-length encode/decode")
rle_p.add_argument("action", choices=["encode", "decode"])
rle_p.add_argument("hex_data")
# xor
xor_p = subparsers.add_parser("xor", help="XOR cipher")
xor_p.add_argument("hex_data")
xor_p.add_argument("hex_key")
# crc
crc_p = subparsers.add_parser("crc", help="Calculate CRC")
crc_p.add_argument("hex_data")
crc_p.add_argument("--bits", type=int, choices=[8, 16], default=8)
args = parser.parse_args()
if args.command == "hex":
if args.action == "encode":
data = args.data.encode("utf-8")
print(encode_hex(data))
else:
data = decode_hex(args.data)
print(data.decode("utf-8", errors="replace"))
elif args.command == "base64":
if args.action == "encode":
data = args.data.encode("utf-8")
if args.url_safe:
print(encode_base64_url(data))
else:
print(encode_base64(data))
else:
if args.url_safe:
data = decode_base64_url(args.data)
else:
data = decode_base64(args.data)
print(data.decode("utf-8"))
elif args.command == "rle":
if args.action == "encode":
data = bytes.fromhex(args.hex_data)
result = run_length_encode(data)
print(result.hex())
else:
data = bytes.fromhex(args.hex_data)
result = run_length_decode(data)
print(result.hex())
elif args.command == "xor":
data = bytes.fromhex(args.hex_data)
key = bytes.fromhex(args.hex_key)
result = xor_cipher(data, key)
print(result.hex())
elif args.command == "crc":
data = bytes.fromhex(args.hex_data)
if args.bits == 8:
print(f"{calculate_crc8(data):02x}")
else:
print(f"{calculate_crc16(data):04x}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
binary_codec
| 357
| 0
|
[
"context_manager",
"exception_handling"
] | 0.652
|
Type inference hints:
Hint: str for variable 'bin_str' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'b' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'result' [High] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'hex_chars' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'text' [High] (usage patterns suggest this type)
Hint: list[Any] for variable 'result' [High] (u
|
|
example_binary_codec
|
test_binary_codec_cli.py
|
"""Tests for binary_codec_cli.py"""
from binary_codec_cli import (
binary_string_to_bytes,
bit_reverse_bytes,
bytes_to_binary_string,
bytes_to_int_list,
caesar_cipher,
caesar_decipher,
calculate_crc8,
calculate_crc16,
decode_ascii_hex,
decode_base16,
decode_base32,
decode_base64,
decode_base64_url,
decode_hex,
decode_utf8_hex,
encode_ascii_hex,
encode_base16,
encode_base32,
encode_base64,
encode_base64_url,
encode_hex,
encode_hex_upper,
encode_utf8_hex,
escape_bytes,
hamming_decode_byte,
hamming_encode_nibble,
int_list_to_bytes,
invert_bytes,
nibble_swap,
run_length_decode,
run_length_encode,
unescape_bytes,
xor_cipher,
)
class TestHexEncoding:
def test_encode(self):
assert encode_hex(b"\x00\xff\xab") == "00ffab"
def test_decode(self):
assert decode_hex("00ffab") == b"\x00\xff\xab"
def test_encode_upper(self):
assert encode_hex_upper(b"\xab\xcd") == "ABCD"
def test_roundtrip(self):
data = b"Hello, World!"
assert decode_hex(encode_hex(data)) == data
class TestBase64Encoding:
def test_encode(self):
assert encode_base64(b"Hello") == "SGVsbG8="
def test_decode(self):
assert decode_base64("SGVsbG8=") == b"Hello"
def test_url_safe_encode(self):
data = b"\xff\xfe\xfd"
result = encode_base64_url(data)
assert "+" not in result
assert "/" not in result
def test_url_safe_roundtrip(self):
data = b"\xff\xfe\xfd"
assert decode_base64_url(encode_base64_url(data)) == data
class TestBase32Encoding:
def test_encode(self):
assert encode_base32(b"Hi") == "JBUQ===="
def test_decode(self):
assert decode_base32("JBUQ====") == b"Hi"
def test_roundtrip(self):
data = b"Test data"
assert decode_base32(encode_base32(data)) == data
class TestBase16Encoding:
def test_encode(self):
assert encode_base16(b"\xab\xcd") == "ABCD"
def test_decode(self):
assert decode_base16("ABCD") == b"\xab\xcd"
class TestBinaryString:
def test_to_binary(self):
assert bytes_to_binary_string(b"\x00\xff") == "00000000 11111111"
def test_from_binary(self):
assert binary_string_to_bytes("00000000 11111111") == b"\x00\xff"
def test_roundtrip(self):
data = b"\x12\x34"
assert binary_string_to_bytes(bytes_to_binary_string(data)) == data
class TestIntList:
def test_to_list(self):
assert bytes_to_int_list(b"\x01\x02\x03") == [1, 2, 3]
def test_from_list(self):
assert int_list_to_bytes([1, 2, 3]) == b"\x01\x02\x03"
class TestAsciiUtf8Hex:
def test_ascii_encode(self):
assert encode_ascii_hex("ABC") == "414243"
def test_ascii_decode(self):
assert decode_ascii_hex("414243") == "ABC"
def test_utf8_encode(self):
result = encode_utf8_hex("世")
assert len(result) == 6 # 3 bytes * 2 hex chars
def test_utf8_decode(self):
encoded = encode_utf8_hex("世界")
assert decode_utf8_hex(encoded) == "世界"
class TestEscape:
def test_escape_printable(self):
assert escape_bytes(b"ABC") == "ABC"
def test_escape_non_printable(self):
assert escape_bytes(b"\x00\x01\x02") == "\\x00\\x01\\x02"
def test_escape_mixed(self):
assert escape_bytes(b"A\x00B") == "A\\x00B"
def test_unescape(self):
assert unescape_bytes("A\\x00B") == b"A\x00B"
def test_roundtrip(self):
data = b"Hello\x00\x01World"
assert unescape_bytes(escape_bytes(data)) == data
class TestRunLengthEncoding:
def test_encode_basic(self):
data = b"\x00\x00\x00\x01\x01"
encoded = run_length_encode(data)
assert encoded == b"\x03\x00\x02\x01"
def test_decode_basic(self):
encoded = b"\x03\x00\x02\x01"
assert run_length_decode(encoded) == b"\x00\x00\x00\x01\x01"
def test_roundtrip(self):
data = b"\xaa\xaa\xaa\xaa\xbb\xbb\xcc"
assert run_length_decode(run_length_encode(data)) == data
def test_empty(self):
assert run_length_encode(b"") == b""
assert run_length_decode(b"") == b""
class TestXorCipher:
def test_basic(self):
data = b"\x00\xff"
key = b"\xff"
result = xor_cipher(data, key)
assert result == b"\xff\x00"
def test_repeating_key(self):
data = b"\x00\x01\x02\x03"
key = b"\xff\x00"
result = xor_cipher(data, key)
assert result == b"\xff\x01\xfd\x03"
def test_roundtrip(self):
data = b"Secret message"
key = b"key"
encrypted = xor_cipher(data, key)
decrypted = xor_cipher(encrypted, key)
assert decrypted == data
def test_empty_key(self):
data = b"\x01\x02\x03"
assert xor_cipher(data, b"") == data
class TestCaesarCipher:
def test_cipher(self):
data = b"\x00\x01\x02"
assert caesar_cipher(data, 1) == b"\x01\x02\x03"
def test_decipher(self):
data = b"\x01\x02\x03"
assert caesar_decipher(data, 1) == b"\x00\x01\x02"
def test_wrap(self):
data = b"\xff"
assert caesar_cipher(data, 1) == b"\x00"
def test_roundtrip(self):
data = b"Hello"
for shift in [1, 5, 100, 255]:
assert caesar_decipher(caesar_cipher(data, shift), shift) == data
class TestBitOperations:
def test_bit_reverse(self):
assert bit_reverse_bytes(b"\x80") == b"\x01"
assert bit_reverse_bytes(b"\x0f") == b"\xf0"
def test_nibble_swap(self):
assert nibble_swap(b"\xab") == b"\xba"
assert nibble_swap(b"\x12\x34") == b"\x21\x43"
def test_invert(self):
assert invert_bytes(b"\x00") == b"\xff"
assert invert_bytes(b"\xff") == b"\x00"
assert invert_bytes(b"\xaa") == b"\x55"
class TestCRC:
def test_crc8_empty(self):
assert calculate_crc8(b"") == 0
def test_crc8_basic(self):
result = calculate_crc8(b"123456789")
assert isinstance(result, int)
assert 0 <= result <= 255
def test_crc16_basic(self):
result = calculate_crc16(b"123456789")
assert isinstance(result, int)
assert 0 <= result <= 65535
def test_crc_deterministic(self):
data = b"Test data"
assert calculate_crc8(data) == calculate_crc8(data)
assert calculate_crc16(data) == calculate_crc16(data)
class TestHammingCode:
def test_encode_nibble(self):
# Hamming(7,4) should produce 7-bit code
result = hamming_encode_nibble(0b0101)
assert 0 <= result < 128
def test_decode_no_error(self):
encoded = hamming_encode_nibble(0b1010)
data, errors = hamming_decode_byte(encoded)
assert data == 0b1010
assert errors == 0
def test_roundtrip(self):
for nibble in range(16):
encoded = hamming_encode_nibble(nibble)
decoded, _ = hamming_decode_byte(encoded)
assert decoded == nibble
class TestEdgeCases:
def test_empty_data(self):
assert encode_hex(b"") == ""
assert decode_hex("") == b""
assert encode_base64(b"") == ""
assert decode_base64("") == b""
def test_single_byte(self):
data = b"\x42"
assert decode_hex(encode_hex(data)) == data
assert decode_base64(encode_base64(data)) == data
def test_all_zeros(self):
data = b"\x00\x00\x00"
assert decode_hex(encode_hex(data)) == data
assert run_length_decode(run_length_encode(data)) == data
def test_all_ones(self):
data = b"\xff\xff\xff"
assert decode_hex(encode_hex(data)) == data
assert xor_cipher(xor_cipher(data, b"\xaa"), b"\xaa") == data
| false
|
binary_codec
| 284
| 0
|
[
"class_definition"
] | 0.612
|
thread 'main' (2445357) panicked at crates/depyler-core/src/direct_rules.rs:1763:28:
expected identifier, found keyword `_`
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
|
|
example_binary_search
|
search_cli.py
|
#!/usr/bin/env python3
"""Binary search CLI.
Binary search implementations with various comparators.
"""
import argparse
import sys
from collections.abc import Callable
def binary_search(arr: list, target, key: Callable | None = None) -> int:
"""Basic binary search. Returns index or -1 if not found."""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
val = key(arr[mid]) if key else arr[mid]
target_val = key(target) if key else target
if val == target_val:
return mid
elif val < target_val:
left = mid + 1
else:
right = mid - 1
return -1
def binary_search_left(arr: list, target, key: Callable | None = None) -> int:
"""Find leftmost position where target could be inserted."""
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
val = key(arr[mid]) if key else arr[mid]
target_val = key(target) if key else target
if val < target_val:
left = mid + 1
else:
right = mid
return left
def binary_search_right(arr: list, target, key: Callable | None = None) -> int:
"""Find rightmost position where target could be inserted."""
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
val = key(arr[mid]) if key else arr[mid]
target_val = key(target) if key else target
if val <= target_val:
left = mid + 1
else:
right = mid
return left
def count_occurrences(arr: list, target, key: Callable | None = None) -> int:
"""Count occurrences of target in sorted array."""
left_idx = binary_search_left(arr, target, key)
right_idx = binary_search_right(arr, target, key)
return right_idx - left_idx
def find_range(arr: list, target, key: Callable | None = None) -> tuple[int, int]:
"""Find the range [start, end) of target in sorted array."""
left_idx = binary_search_left(arr, target, key)
right_idx = binary_search_right(arr, target, key)
if left_idx == right_idx:
return -1, -1
return left_idx, right_idx - 1
def search_rotated(arr: list, target) -> int:
"""Search in a rotated sorted array."""
if not arr:
return -1
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
# Left half is sorted
if arr[left] <= arr[mid]:
if arr[left] <= target < arr[mid]:
right = mid - 1
else:
left = mid + 1
# Right half is sorted
else:
if arr[mid] < target <= arr[right]:
left = mid + 1
else:
right = mid - 1
return -1
def find_peak(arr: list) -> int:
"""Find a peak element index (element greater than neighbors)."""
if not arr:
return -1
if len(arr) == 1:
return 0
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] < arr[mid + 1]:
left = mid + 1
else:
right = mid
return left
def search_closest(arr: list, target) -> int:
"""Find index of element closest to target."""
if not arr:
return -1
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] < target:
left = mid + 1
else:
right = mid
# Check neighbors for closest
if left == 0:
return 0
if left == len(arr):
return len(arr) - 1
if abs(arr[left] - target) < abs(arr[left - 1] - target):
return left
return left - 1
def search_floor(arr: list, target) -> int:
"""Find largest element <= target."""
if not arr:
return -1
idx = binary_search_right(arr, target)
if idx == 0:
return -1 if arr[0] > target else 0
return idx - 1
def search_ceil(arr: list, target) -> int:
"""Find smallest element >= target."""
if not arr:
return -1
idx = binary_search_left(arr, target)
if idx == len(arr):
return -1
return idx
def main() -> int:
parser = argparse.ArgumentParser(description="Binary search operations")
parser.add_argument("target", type=int, help="Target value to search")
parser.add_argument("values", nargs="*", type=int, help="Sorted values to search in")
parser.add_argument(
"--mode",
choices=["find", "left", "right", "count", "range", "closest", "floor", "ceil"],
default="find",
help="Search mode",
)
parser.add_argument("--rotated", action="store_true", help="Search rotated array")
parser.add_argument("--peak", action="store_true", help="Find peak element")
args = parser.parse_args()
if not args.values:
values = [int(x) for x in sys.stdin.read().split()]
else:
values = args.values
if args.peak:
idx = find_peak(values)
if idx >= 0:
print(f"Peak at index {idx}: {values[idx]}")
else:
print("No peak found")
return 0
if args.rotated:
idx = search_rotated(values, args.target)
elif args.mode == "find":
idx = binary_search(values, args.target)
elif args.mode == "left":
idx = binary_search_left(values, args.target)
elif args.mode == "right":
idx = binary_search_right(values, args.target)
elif args.mode == "count":
count = count_occurrences(values, args.target)
print(f"Count: {count}")
return 0
elif args.mode == "range":
start, end = find_range(values, args.target)
if start == -1:
print("Not found")
else:
print(f"Range: [{start}, {end}]")
return 0
elif args.mode == "closest":
idx = search_closest(values, args.target)
elif args.mode == "floor":
idx = search_floor(values, args.target)
elif args.mode == "ceil":
idx = search_ceil(values, args.target)
else:
idx = -1
if idx >= 0:
print(f"Index: {idx}, Value: {values[idx]}")
else:
print("Not found")
return 0 if idx >= 0 else 1
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_binary_search/search_cli.py (6365 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_binary_search/search_cli.rs (16559 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_binary_search/Cargo.toml (3 dependencies)
⏱️ Parse time: 107ms
📊 Throughput: 57.9 KB/s
⏱️ Total time: 107ms
| true
|
binary_search
| 249
| 6
|
[
"context_manager",
"stdin_usage"
] | 0.652
| null |
example_binary_search
|
test_search_cli.py
|
"""Tests for search_cli.py"""
from search_cli import (
binary_search,
binary_search_left,
binary_search_right,
count_occurrences,
find_peak,
find_range,
search_ceil,
search_closest,
search_floor,
search_rotated,
)
class TestBinarySearch:
def test_found(self):
arr = [1, 3, 5, 7, 9]
assert binary_search(arr, 5) == 2
def test_not_found(self):
arr = [1, 3, 5, 7, 9]
assert binary_search(arr, 4) == -1
def test_first_element(self):
arr = [1, 3, 5, 7, 9]
assert binary_search(arr, 1) == 0
def test_last_element(self):
arr = [1, 3, 5, 7, 9]
assert binary_search(arr, 9) == 4
def test_empty(self):
assert binary_search([], 5) == -1
def test_single_found(self):
assert binary_search([5], 5) == 0
def test_single_not_found(self):
assert binary_search([5], 3) == -1
def test_with_key(self):
arr = ["a", "bb", "ccc", "dddd"]
assert binary_search(arr, "xx", key=len) == 1 # len("xx") == 2
class TestBinarySearchLeft:
def test_found(self):
arr = [1, 2, 2, 2, 3]
assert binary_search_left(arr, 2) == 1
def test_not_found_insert(self):
arr = [1, 3, 5, 7]
assert binary_search_left(arr, 4) == 2
def test_smaller_than_all(self):
arr = [2, 4, 6]
assert binary_search_left(arr, 1) == 0
def test_larger_than_all(self):
arr = [2, 4, 6]
assert binary_search_left(arr, 10) == 3
class TestBinarySearchRight:
def test_found(self):
arr = [1, 2, 2, 2, 3]
assert binary_search_right(arr, 2) == 4
def test_not_found_insert(self):
arr = [1, 3, 5, 7]
assert binary_search_right(arr, 4) == 2
class TestCountOccurrences:
def test_multiple(self):
arr = [1, 2, 2, 2, 3, 4]
assert count_occurrences(arr, 2) == 3
def test_single(self):
arr = [1, 2, 3, 4, 5]
assert count_occurrences(arr, 3) == 1
def test_none(self):
arr = [1, 2, 4, 5]
assert count_occurrences(arr, 3) == 0
class TestFindRange:
def test_multiple(self):
arr = [1, 2, 2, 2, 3]
start, end = find_range(arr, 2)
assert start == 1
assert end == 3
def test_single(self):
arr = [1, 2, 3, 4, 5]
start, end = find_range(arr, 3)
assert start == 2
assert end == 2
def test_not_found(self):
arr = [1, 2, 4, 5]
start, end = find_range(arr, 3)
assert start == -1
assert end == -1
class TestSearchRotated:
def test_rotated_left(self):
arr = [4, 5, 6, 7, 0, 1, 2]
assert search_rotated(arr, 0) == 4
def test_rotated_right(self):
arr = [4, 5, 6, 7, 0, 1, 2]
assert search_rotated(arr, 5) == 1
def test_not_rotated(self):
arr = [1, 2, 3, 4, 5]
assert search_rotated(arr, 3) == 2
def test_not_found(self):
arr = [4, 5, 6, 7, 0, 1, 2]
assert search_rotated(arr, 3) == -1
def test_empty(self):
assert search_rotated([], 5) == -1
class TestFindPeak:
def test_peak_in_middle(self):
arr = [1, 3, 5, 4, 2]
idx = find_peak(arr)
assert arr[idx] >= arr[idx - 1] if idx > 0 else True
assert arr[idx] >= arr[idx + 1] if idx < len(arr) - 1 else True
def test_ascending(self):
arr = [1, 2, 3, 4, 5]
assert find_peak(arr) == 4
def test_descending(self):
arr = [5, 4, 3, 2, 1]
assert find_peak(arr) == 0
def test_single(self):
assert find_peak([5]) == 0
def test_empty(self):
assert find_peak([]) == -1
class TestSearchClosest:
def test_exact(self):
arr = [1, 3, 5, 7, 9]
assert search_closest(arr, 5) == 2
def test_between(self):
arr = [1, 3, 5, 7, 9]
idx = search_closest(arr, 6)
assert arr[idx] in [5, 7]
def test_smaller(self):
arr = [5, 10, 15]
assert search_closest(arr, 1) == 0
def test_larger(self):
arr = [5, 10, 15]
assert search_closest(arr, 20) == 2
def test_empty(self):
assert search_closest([], 5) == -1
class TestSearchFloor:
def test_exact(self):
arr = [1, 3, 5, 7, 9]
assert search_floor(arr, 5) == 2
def test_between(self):
arr = [1, 3, 5, 7, 9]
assert search_floor(arr, 6) == 2 # floor is 5
def test_smaller_than_all(self):
arr = [5, 10, 15]
assert search_floor(arr, 3) == -1
def test_empty(self):
assert search_floor([], 5) == -1
class TestSearchCeil:
def test_exact(self):
arr = [1, 3, 5, 7, 9]
assert search_ceil(arr, 5) == 2
def test_between(self):
arr = [1, 3, 5, 7, 9]
assert search_ceil(arr, 6) == 3 # ceil is 7
def test_larger_than_all(self):
arr = [5, 10, 15]
assert search_ceil(arr, 20) == -1
def test_empty(self):
assert search_ceil([], 5) == -1
| false
|
binary_search
| 206
| 0
|
[
"class_definition"
] | 0.612
|
Error: Expression type not yet supported: IfExpr { test: Binary { op: Gt, left: Var("idx"), right: Literal(Int(0)) }, body: Binary { op: GtEq, left: Index { base: Var("arr"), index: Var("idx") }, right: Index { base: Var("arr"), index: Binary { op: Sub, left: Var("idx"), right: Literal(Int(1)) } } }, orelse: Literal(Bool(true)) }
|
|
example_bisect
|
bisect_tool.py
|
#!/usr/bin/env python3
"""Bisect Example - Binary search CLI."""
import argparse
import bisect
def main():
parser = argparse.ArgumentParser(description="Binary search tool")
subs = parser.add_subparsers(dest="cmd", required=True)
lp = subs.add_parser("left")
lp.add_argument("x", type=int)
r = subs.add_parser("right")
r.add_argument("x", type=int)
args = parser.parse_args()
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
if args.cmd == "left":
print(bisect.bisect_left(items, args.x))
elif args.cmd == "right":
print(bisect.bisect_right(items, args.x))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_bisect/bisect_tool.py (650 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_bisect/bisect_tool.rs (1706 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_bisect/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 12.9 KB/s
⏱️ Total time: 49ms
| true
|
bisect
| 27
| 6
|
[] | 0
| null |
example_bisect
|
test_bisect_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for bisect CLI."""
import subprocess
SCRIPT = "bisect_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestBisect:
def test_left(self): r = run(["left", "5"]); assert r.returncode == 0 and "4" in r.stdout
def test_right(self): r = run(["right", "5"]); assert r.returncode == 0 and "5" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_bisect/test_bisect_tool.py (528 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_bisect/test_bisect_tool.rs (1702 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 10.3 KB/s
⏱️ Total time: 50ms
| true
|
bisect
| 13
| 5
|
[
"class_definition"
] | 0.612
| null |
example_bitwise_ops
|
bitwise_ops_cli.py
|
#!/usr/bin/env python3
"""Bitwise Operations CLI.
Bitwise operations and bit manipulation patterns.
"""
import argparse
import sys
def bit_and(a: int, b: int) -> int:
"""Bitwise AND."""
return a & b
def bit_or(a: int, b: int) -> int:
"""Bitwise OR."""
return a | b
def bit_xor(a: int, b: int) -> int:
"""Bitwise XOR."""
return a ^ b
def bit_not(a: int) -> int:
"""Bitwise NOT (complement)."""
return ~a
def left_shift(value: int, count: int) -> int:
"""Left shift."""
return value << count
def right_shift(value: int, count: int) -> int:
"""Right shift (arithmetic)."""
return value >> count
def unsigned_right_shift(value: int, count: int, bits: int = 32) -> int:
"""Unsigned right shift (logical)."""
mask = (1 << bits) - 1
return (value & mask) >> count
def set_bit(value: int, position: int) -> int:
"""Set bit at position."""
return value | (1 << position)
def clear_bit(value: int, position: int) -> int:
"""Clear bit at position."""
return value & ~(1 << position)
def toggle_bit(value: int, position: int) -> int:
"""Toggle bit at position."""
return value ^ (1 << position)
def check_bit(value: int, position: int) -> bool:
"""Check if bit is set at position."""
return (value & (1 << position)) != 0
def count_set_bits(value: int) -> int:
"""Count number of set bits (popcount)."""
count = 0
while value:
count += value & 1
value >>= 1
return count
def count_set_bits_fast(value: int) -> int:
"""Count set bits using Brian Kernighan's algorithm."""
count = 0
while value:
value &= value - 1
count += 1
return count
def is_power_of_two(value: int) -> bool:
"""Check if value is power of two."""
return value > 0 and (value & (value - 1)) == 0
def next_power_of_two(value: int) -> int:
"""Find next power of two >= value."""
if value <= 1:
return 1
value -= 1
value |= value >> 1
value |= value >> 2
value |= value >> 4
value |= value >> 8
value |= value >> 16
return value + 1
def lowest_set_bit(value: int) -> int:
"""Get lowest set bit."""
if value == 0:
return 0
return value & (-value)
def highest_set_bit(value: int) -> int:
"""Get position of highest set bit."""
if value == 0:
return -1
position = 0
while value > 1:
value >>= 1
position += 1
return position
def swap_bits(value: int, pos1: int, pos2: int) -> int:
"""Swap bits at two positions."""
bit1 = (value >> pos1) & 1
bit2 = (value >> pos2) & 1
if bit1 != bit2:
value = toggle_bit(value, pos1)
value = toggle_bit(value, pos2)
return value
def reverse_bits(value: int, bits: int = 8) -> int:
"""Reverse bit order."""
result = 0
for _ in range(bits):
result = (result << 1) | (value & 1)
value >>= 1
return result
def rotate_left(value: int, count: int, bits: int = 32) -> int:
"""Rotate bits left."""
count %= bits
mask = (1 << bits) - 1
return ((value << count) | (value >> (bits - count))) & mask
def rotate_right(value: int, count: int, bits: int = 32) -> int:
"""Rotate bits right."""
count %= bits
mask = (1 << bits) - 1
return ((value >> count) | (value << (bits - count))) & mask
def extract_bits(value: int, start: int, length: int) -> int:
"""Extract bits from position start with given length."""
mask = (1 << length) - 1
return (value >> start) & mask
def insert_bits(value: int, bits: int, start: int, length: int) -> int:
"""Insert bits at position start with given length."""
mask = (1 << length) - 1
cleared = value & ~(mask << start)
return cleared | ((bits & mask) << start)
def parity(value: int) -> int:
"""Calculate parity (0 if even number of 1s, 1 if odd)."""
p = 0
while value:
p ^= value & 1
value >>= 1
return p
def leading_zeros(value: int, bits: int = 32) -> int:
"""Count leading zeros."""
if value == 0:
return bits
count = 0
mask = 1 << (bits - 1)
while (value & mask) == 0:
count += 1
mask >>= 1
return count
def trailing_zeros(value: int) -> int:
"""Count trailing zeros."""
if value == 0:
return 32
count = 0
while (value & 1) == 0:
count += 1
value >>= 1
return count
def sign_extend(value: int, from_bits: int, to_bits: int = 32) -> int:
"""Sign extend from smaller bit width to larger."""
sign_bit = 1 << (from_bits - 1)
if value & sign_bit:
mask = ((1 << to_bits) - 1) ^ ((1 << from_bits) - 1)
return value | mask
return value
def gray_encode(n: int) -> int:
"""Convert to Gray code."""
return n ^ (n >> 1)
def gray_decode(gray: int) -> int:
"""Convert from Gray code."""
n = gray
mask = n
while mask:
mask >>= 1
n ^= mask
return n
def interleave_bits(x: int, y: int) -> int:
"""Interleave bits of x and y (Morton code)."""
result = 0
for i in range(16):
result |= ((x >> i) & 1) << (2 * i)
result |= ((y >> i) & 1) << (2 * i + 1)
return result
def deinterleave_bits(z: int) -> tuple[int, int]:
"""Deinterleave Morton code back to x and y."""
x = 0
y = 0
for i in range(16):
x |= ((z >> (2 * i)) & 1) << i
y |= ((z >> (2 * i + 1)) & 1) << i
return (x, y)
def to_binary_string(value: int, bits: int = 8) -> str:
"""Convert to binary string with leading zeros."""
return format(value & ((1 << bits) - 1), f"0{bits}b")
def from_binary_string(s: str) -> int:
"""Convert binary string to integer."""
return int(s, 2)
def main() -> int:
parser = argparse.ArgumentParser(description="Bitwise operations CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# binary
bin_p = subparsers.add_parser("binary", help="Show binary representation")
bin_p.add_argument("value", type=int)
bin_p.add_argument("--bits", type=int, default=8)
# popcount
pop_p = subparsers.add_parser("popcount", help="Count set bits")
pop_p.add_argument("value", type=int)
# power2
pow_p = subparsers.add_parser("power2", help="Check/find power of 2")
pow_p.add_argument("value", type=int)
pow_p.add_argument("--next", action="store_true")
# shift
shift_p = subparsers.add_parser("shift", help="Shift operations")
shift_p.add_argument("value", type=int)
shift_p.add_argument("count", type=int)
shift_p.add_argument("--left", action="store_true")
shift_p.add_argument("--rotate", action="store_true")
args = parser.parse_args()
if args.command == "binary":
print(to_binary_string(args.value, args.bits))
elif args.command == "popcount":
print(f"Set bits: {count_set_bits(args.value)}")
elif args.command == "power2":
if args.next:
print(f"Next power of 2: {next_power_of_two(args.value)}")
else:
print(f"Is power of 2: {is_power_of_two(args.value)}")
elif args.command == "shift":
if args.rotate:
if args.left:
result = rotate_left(args.value, args.count)
else:
result = rotate_right(args.value, args.count)
print(f"Rotated: {result}")
else:
if args.left:
result = left_shift(args.value, args.count)
else:
result = right_shift(args.value, args.count)
print(f"Shifted: {result}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
bitwise_ops
| 312
| 0
|
[
"context_manager"
] | 0.652
|
Type inference hints:
Hint: int for variable 'count' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: int for variable 'count' [Medium] (usage patterns suggest this type)
Hint: int for variable 'value' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: int for variable 'value' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: int for variable 'value' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: int f
|
|
example_bitwise_ops
|
test_bitwise_ops_cli.py
|
"""Tests for bitwise_ops_cli.py"""
from bitwise_ops_cli import (
bit_and,
bit_not,
bit_or,
bit_xor,
check_bit,
clear_bit,
count_set_bits,
count_set_bits_fast,
deinterleave_bits,
extract_bits,
from_binary_string,
gray_decode,
gray_encode,
highest_set_bit,
insert_bits,
interleave_bits,
is_power_of_two,
leading_zeros,
left_shift,
lowest_set_bit,
next_power_of_two,
parity,
reverse_bits,
right_shift,
rotate_left,
rotate_right,
set_bit,
sign_extend,
swap_bits,
to_binary_string,
toggle_bit,
trailing_zeros,
unsigned_right_shift,
)
class TestBasicBitwise:
def test_and(self):
assert bit_and(0b1100, 0b1010) == 0b1000
def test_or(self):
assert bit_or(0b1100, 0b1010) == 0b1110
def test_xor(self):
assert bit_xor(0b1100, 0b1010) == 0b0110
def test_not(self):
assert bit_not(0) == -1
assert bit_not(-1) == 0
class TestShift:
def test_left_shift(self):
assert left_shift(1, 3) == 8
assert left_shift(0b0101, 2) == 0b010100
def test_right_shift(self):
assert right_shift(8, 2) == 2
assert right_shift(0b1100, 2) == 0b11
def test_unsigned_right_shift(self):
assert unsigned_right_shift(0xFF, 4, 8) == 0x0F
def test_right_shift_negative(self):
# Python preserves sign bit for >>
assert right_shift(-8, 2) == -2
class TestBitManipulation:
def test_set_bit(self):
assert set_bit(0b0000, 2) == 0b0100
assert set_bit(0b0100, 2) == 0b0100 # Already set
def test_clear_bit(self):
assert clear_bit(0b1111, 2) == 0b1011
assert clear_bit(0b1011, 2) == 0b1011 # Already clear
def test_toggle_bit(self):
assert toggle_bit(0b1100, 2) == 0b1000
assert toggle_bit(0b1000, 2) == 0b1100
def test_check_bit(self):
assert check_bit(0b1100, 2) is True
assert check_bit(0b1100, 0) is False
class TestCountBits:
def test_count_set_bits(self):
assert count_set_bits(0) == 0
assert count_set_bits(1) == 1
assert count_set_bits(0b1111) == 4
assert count_set_bits(0b10101010) == 4
def test_count_set_bits_fast(self):
assert count_set_bits_fast(0) == 0
assert count_set_bits_fast(0b1111) == 4
assert count_set_bits_fast(0xFF) == 8
class TestPowerOfTwo:
def test_is_power_of_two(self):
assert is_power_of_two(1) is True
assert is_power_of_two(2) is True
assert is_power_of_two(4) is True
assert is_power_of_two(0) is False
assert is_power_of_two(3) is False
assert is_power_of_two(6) is False
def test_next_power_of_two(self):
assert next_power_of_two(0) == 1
assert next_power_of_two(1) == 1
assert next_power_of_two(3) == 4
assert next_power_of_two(5) == 8
assert next_power_of_two(8) == 8
class TestFindBits:
def test_lowest_set_bit(self):
assert lowest_set_bit(0) == 0
assert lowest_set_bit(0b1100) == 0b0100
assert lowest_set_bit(0b1000) == 0b1000
def test_highest_set_bit(self):
assert highest_set_bit(0) == -1
assert highest_set_bit(1) == 0
assert highest_set_bit(8) == 3
assert highest_set_bit(0b1111) == 3
class TestSwapBits:
def test_swap_different(self):
assert swap_bits(0b1010, 0, 1) == 0b1001
def test_swap_same(self):
assert swap_bits(0b1111, 0, 1) == 0b1111
class TestReverse:
def test_reverse_byte(self):
assert reverse_bits(0b10000000, 8) == 0b00000001
assert reverse_bits(0b11110000, 8) == 0b00001111
assert reverse_bits(0b10101010, 8) == 0b01010101
class TestRotate:
def test_rotate_left(self):
assert rotate_left(0b00000001, 1, 8) == 0b00000010
assert rotate_left(0b10000000, 1, 8) == 0b00000001
def test_rotate_right(self):
assert rotate_right(0b00000010, 1, 8) == 0b00000001
assert rotate_right(0b00000001, 1, 8) == 0b10000000
class TestExtractInsert:
def test_extract_bits(self):
assert extract_bits(0b11110000, 4, 4) == 0b1111
assert extract_bits(0b10101010, 2, 4) == 0b1010
def test_insert_bits(self):
assert insert_bits(0b00000000, 0b1111, 4, 4) == 0b11110000
assert insert_bits(0b11111111, 0b0000, 4, 4) == 0b00001111
class TestParity:
def test_even_parity(self):
assert parity(0b1100) == 0
assert parity(0b1111) == 0
def test_odd_parity(self):
assert parity(0b1000) == 1
assert parity(0b0111) == 1
class TestLeadingTrailingZeros:
def test_leading_zeros(self):
assert leading_zeros(0, 8) == 8
assert leading_zeros(0b10000000, 8) == 0
assert leading_zeros(0b00000001, 8) == 7
def test_trailing_zeros(self):
assert trailing_zeros(0) == 32
assert trailing_zeros(1) == 0
assert trailing_zeros(0b1000) == 3
class TestSignExtend:
def test_positive(self):
assert sign_extend(0b0111, 4, 8) == 0b0111
def test_negative(self):
assert sign_extend(0b1000, 4, 8) == 0b11111000
class TestGrayCode:
def test_encode(self):
assert gray_encode(0) == 0
assert gray_encode(1) == 1
assert gray_encode(2) == 3
assert gray_encode(3) == 2
def test_decode(self):
assert gray_decode(0) == 0
assert gray_decode(1) == 1
assert gray_decode(3) == 2
assert gray_decode(2) == 3
def test_roundtrip(self):
for i in range(16):
assert gray_decode(gray_encode(i)) == i
class TestMortonCode:
def test_interleave(self):
assert interleave_bits(0, 0) == 0
assert interleave_bits(1, 0) == 1
assert interleave_bits(0, 1) == 2
assert interleave_bits(1, 1) == 3
def test_deinterleave(self):
assert deinterleave_bits(0) == (0, 0)
assert deinterleave_bits(1) == (1, 0)
assert deinterleave_bits(2) == (0, 1)
assert deinterleave_bits(3) == (1, 1)
def test_roundtrip(self):
for x in range(16):
for y in range(16):
z = interleave_bits(x, y)
assert deinterleave_bits(z) == (x, y)
class TestBinaryString:
def test_to_binary(self):
assert to_binary_string(0, 8) == "00000000"
assert to_binary_string(255, 8) == "11111111"
assert to_binary_string(5, 4) == "0101"
def test_from_binary(self):
assert from_binary_string("1010") == 10
assert from_binary_string("11111111") == 255
def test_roundtrip(self):
for i in range(256):
s = to_binary_string(i, 8)
assert from_binary_string(s) == i
class TestEdgeCases:
def test_all_zeros(self):
assert count_set_bits(0) == 0
assert is_power_of_two(0) is False
assert lowest_set_bit(0) == 0
def test_all_ones_byte(self):
assert count_set_bits(0xFF) == 8
assert reverse_bits(0xFF, 8) == 0xFF
def test_negative_numbers(self):
# XOR with -1 is NOT
assert bit_xor(-1, 0) == -1
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_bitwise_ops/test_bitwise_ops_cli.py (7199 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_bitwise_ops/test_bitwise_ops_cli.rs (17235 bytes)
⏱️ Parse time: 52ms
📊 Throughput: 134.4 KB/s
⏱️ Total time: 52ms
| true
|
bitwise_ops
| 264
| 5
|
[
"context_manager",
"class_definition"
] | 0.652
| null |
example_bool
|
bool_tool.py
|
#!/usr/bin/env python3
"""Bool Example - Boolean operations CLI.
Examples:
>>> bool_and(1, 1)
True
>>> bool_or(0, 1)
True
>>> bool_not(0)
True
"""
import argparse
def bool_and(x: int, y: int) -> bool:
"""Logical AND of two integers as booleans.
>>> bool_and(1, 1)
True
>>> bool_and(1, 0)
False
>>> bool_and(0, 0)
False
"""
return x != 0 and y != 0
def bool_or(x: int, y: int) -> bool:
"""Logical OR of two integers as booleans.
>>> bool_or(1, 0)
True
>>> bool_or(0, 1)
True
>>> bool_or(0, 0)
False
"""
return x != 0 or y != 0
def bool_not(x: int) -> bool:
"""Logical NOT of integer as boolean.
>>> bool_not(0)
True
>>> bool_not(1)
False
>>> bool_not(5)
False
"""
return x == 0
def main():
parser = argparse.ArgumentParser(description="Boolean operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
a = subs.add_parser("and")
a.add_argument("x", type=int)
a.add_argument("y", type=int)
o = subs.add_parser("or")
o.add_argument("x", type=int)
o.add_argument("y", type=int)
n = subs.add_parser("not")
n.add_argument("x", type=int)
args = parser.parse_args()
if args.cmd == "and":
print("true" if bool_and(args.x, args.y) else "false")
elif args.cmd == "or":
print("true" if bool_or(args.x, args.y) else "false")
elif args.cmd == "not":
print("true" if bool_not(args.x) else "false")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_bool/bool_tool.py (1566 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_bool/bool_tool.rs (2582 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_bool/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 31.1 KB/s
⏱️ Total time: 49ms
| true
|
bool
| 78
| 6
|
[] | 0
| null |
example_bool
|
test_bool_tool.py
|
"""Tests for bool_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "bool_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_and():
r = run("and 1 1")
assert r.returncode == 0
assert r.stdout.strip() == "true"
def test_or():
r = run("or 0 1")
assert r.returncode == 0
assert r.stdout.strip() == "true"
def test_not():
r = run("not 0")
assert r.returncode == 0
assert r.stdout.strip() == "true"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_bool/test_bool_tool.py (599 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_bool/test_bool_tool.rs (1808 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_bool/Cargo.toml (2 dependencies)
⏱️ Parse time: 50ms
📊 Throughput: 11.6 KB/s
⏱️ Total time: 50ms
| true
|
bool
| 32
| 6
|
[] | 0
| null |
example_byte_buffer
|
byte_buffer_cli.py
|
#!/usr/bin/env python3
"""Byte Buffer CLI.
Growable byte buffer operations with read/write cursor.
"""
import argparse
import struct
import sys
class ByteBuffer:
"""A growable byte buffer with read/write cursor."""
def __init__(self, capacity: int = 256) -> None:
self._data: bytearray = bytearray(capacity)
self._write_pos: int = 0
self._read_pos: int = 0
self._capacity: int = capacity
self._length: int = 0 # High water mark of data
@classmethod
def from_bytes(cls, data: bytes) -> "ByteBuffer":
"""Create buffer from existing bytes."""
buf = cls(len(data))
buf._data[: len(data)] = data
buf._write_pos = len(data)
buf._length = len(data)
return buf
def capacity(self) -> int:
"""Get buffer capacity."""
return self._capacity
def length(self) -> int:
"""Get number of bytes written."""
return self._length
def remaining_read(self) -> int:
"""Get number of bytes available to read."""
return self._length - self._read_pos
def remaining_write(self) -> int:
"""Get number of bytes available to write."""
return self._capacity - self._write_pos
def write_pos(self) -> int:
"""Get current write position."""
return self._write_pos
def read_pos(self) -> int:
"""Get current read position."""
return self._read_pos
def seek_read(self, pos: int) -> None:
"""Set read position."""
self._read_pos = max(0, min(pos, self._length))
def seek_write(self, pos: int) -> None:
"""Set write position."""
self._write_pos = max(0, min(pos, self._capacity))
def rewind(self) -> None:
"""Reset read position to beginning."""
self._read_pos = 0
def clear(self) -> None:
"""Clear buffer."""
self._write_pos = 0
self._read_pos = 0
self._length = 0
def _ensure_capacity(self, additional: int) -> None:
"""Ensure buffer can hold additional bytes."""
required = self._write_pos + additional
if required > self._capacity:
new_capacity = max(self._capacity * 2, required)
new_data = bytearray(new_capacity)
new_data[: self._write_pos] = self._data[: self._write_pos]
self._data = new_data
self._capacity = new_capacity
def write_byte(self, value: int) -> None:
"""Write a single byte."""
self._ensure_capacity(1)
self._data[self._write_pos] = value & 0xFF
self._write_pos += 1
if self._write_pos > self._length:
self._length = self._write_pos
def read_byte(self) -> int:
"""Read a single byte."""
if self._read_pos >= self._length:
raise BufferError("No more bytes to read")
value = self._data[self._read_pos]
self._read_pos += 1
return value
def write_bytes(self, data: bytes) -> None:
"""Write multiple bytes."""
self._ensure_capacity(len(data))
self._data[self._write_pos : self._write_pos + len(data)] = data
self._write_pos += len(data)
if self._write_pos > self._length:
self._length = self._write_pos
def read_bytes(self, count: int) -> bytes:
"""Read multiple bytes."""
available = self._length - self._read_pos
count = min(count, available)
data = bytes(self._data[self._read_pos : self._read_pos + count])
self._read_pos += count
return data
def write_short(self, value: int, big_endian: bool = False) -> None:
"""Write a 16-bit integer."""
fmt = ">h" if big_endian else "<h"
self.write_bytes(struct.pack(fmt, value))
def read_short(self, big_endian: bool = False) -> int:
"""Read a 16-bit integer."""
fmt = ">h" if big_endian else "<h"
data = self.read_bytes(2)
return struct.unpack(fmt, data)[0]
def write_int(self, value: int, big_endian: bool = False) -> None:
"""Write a 32-bit integer."""
fmt = ">i" if big_endian else "<i"
self.write_bytes(struct.pack(fmt, value))
def read_int(self, big_endian: bool = False) -> int:
"""Read a 32-bit integer."""
fmt = ">i" if big_endian else "<i"
data = self.read_bytes(4)
return struct.unpack(fmt, data)[0]
def write_long(self, value: int, big_endian: bool = False) -> None:
"""Write a 64-bit integer."""
fmt = ">q" if big_endian else "<q"
self.write_bytes(struct.pack(fmt, value))
def read_long(self, big_endian: bool = False) -> int:
"""Read a 64-bit integer."""
fmt = ">q" if big_endian else "<q"
data = self.read_bytes(8)
return struct.unpack(fmt, data)[0]
def write_float(self, value: float, big_endian: bool = False) -> None:
"""Write a 32-bit float."""
fmt = ">f" if big_endian else "<f"
self.write_bytes(struct.pack(fmt, value))
def read_float(self, big_endian: bool = False) -> float:
"""Read a 32-bit float."""
fmt = ">f" if big_endian else "<f"
data = self.read_bytes(4)
return struct.unpack(fmt, data)[0]
def write_double(self, value: float, big_endian: bool = False) -> None:
"""Write a 64-bit double."""
fmt = ">d" if big_endian else "<d"
self.write_bytes(struct.pack(fmt, value))
def read_double(self, big_endian: bool = False) -> float:
"""Read a 64-bit double."""
fmt = ">d" if big_endian else "<d"
data = self.read_bytes(8)
return struct.unpack(fmt, data)[0]
def write_string(self, value: str, encoding: str = "utf-8") -> None:
"""Write a length-prefixed string."""
encoded = value.encode(encoding)
self.write_int(len(encoded))
self.write_bytes(encoded)
def read_string(self, encoding: str = "utf-8") -> str:
"""Read a length-prefixed string."""
length = self.read_int()
data = self.read_bytes(length)
return data.decode(encoding)
def write_fixed_string(self, value: str, length: int) -> None:
"""Write a fixed-length string (null-padded)."""
encoded = value.encode("utf-8")[:length]
padded = encoded.ljust(length, b"\x00")
self.write_bytes(padded)
def read_fixed_string(self, length: int) -> str:
"""Read a fixed-length string (null-terminated)."""
data = self.read_bytes(length)
return data.rstrip(b"\x00").decode("utf-8")
def to_bytes(self) -> bytes:
"""Get buffer contents as bytes."""
return bytes(self._data[: self._length])
def peek_byte(self) -> int:
"""Peek at next byte without advancing read position."""
if self._read_pos >= self._length:
raise BufferError("No more bytes to peek")
return self._data[self._read_pos]
def skip(self, count: int) -> None:
"""Skip bytes in read stream."""
self._read_pos = min(self._read_pos + count, self._length)
def create_buffer(capacity: int) -> ByteBuffer:
"""Create a new buffer with given capacity."""
return ByteBuffer(capacity)
def buffer_from_hex(hex_str: str) -> ByteBuffer:
"""Create buffer from hex string."""
return ByteBuffer.from_bytes(bytes.fromhex(hex_str))
def write_message(buf: ByteBuffer, msg_type: int, payload: bytes) -> None:
"""Write a typed message (type + length + payload)."""
buf.write_byte(msg_type)
buf.write_int(len(payload))
buf.write_bytes(payload)
def read_message(buf: ByteBuffer) -> tuple[int, bytes]:
"""Read a typed message."""
msg_type = buf.read_byte()
length = buf.read_int()
payload = buf.read_bytes(length)
return (msg_type, payload)
def write_varints(buf: ByteBuffer, values: list[int]) -> None:
"""Write variable-length encoded integers."""
buf.write_int(len(values))
for v in values:
write_varint(buf, v)
def write_varint(buf: ByteBuffer, value: int) -> None:
"""Write a variable-length encoded integer."""
while value >= 0x80:
buf.write_byte((value & 0x7F) | 0x80)
value >>= 7
buf.write_byte(value & 0x7F)
def read_varint(buf: ByteBuffer) -> int:
"""Read a variable-length encoded integer."""
result = 0
shift = 0
while True:
b = buf.read_byte()
result |= (b & 0x7F) << shift
if (b & 0x80) == 0:
break
shift += 7
return result
def read_varints(buf: ByteBuffer) -> list[int]:
"""Read variable-length encoded integers."""
count = buf.read_int()
return [read_varint(buf) for _ in range(count)]
def main() -> int:
parser = argparse.ArgumentParser(description="Byte buffer CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# create
create_p = subparsers.add_parser("create", help="Create and populate buffer")
create_p.add_argument("values", type=int, nargs="+")
# message
msg_p = subparsers.add_parser("message", help="Create typed message")
msg_p.add_argument("type", type=int)
msg_p.add_argument("hex_payload")
# varint
var_p = subparsers.add_parser("varint", help="Encode integers as varints")
var_p.add_argument("values", type=int, nargs="+")
args = parser.parse_args()
if args.command == "create":
buf = ByteBuffer()
for v in args.values:
buf.write_byte(v)
print(f"Buffer: {buf.to_bytes().hex()}")
elif args.command == "message":
buf = ByteBuffer()
payload = bytes.fromhex(args.hex_payload)
write_message(buf, args.type, payload)
print(f"Message: {buf.to_bytes().hex()}")
elif args.command == "varint":
buf = ByteBuffer()
write_varints(buf, args.values)
print(f"Varints: {buf.to_bytes().hex()}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
byte_buffer
| 310
| 0
|
[
"context_manager",
"class_definition",
"exception_handling",
"decorator"
] | 0.652
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 548..560, value: Str("ByteBuffer"), kind: None })
|
|
example_byte_buffer
|
test_byte_buffer_cli.py
|
"""Tests for byte_buffer_cli.py"""
import pytest
from byte_buffer_cli import (
ByteBuffer,
buffer_from_hex,
create_buffer,
read_message,
read_varint,
read_varints,
write_message,
write_varint,
write_varints,
)
class TestByteBufferBasic:
def test_create(self):
buf = ByteBuffer(64)
assert buf.capacity() == 64
assert buf.length() == 0
def test_from_bytes(self):
buf = ByteBuffer.from_bytes(b"\x01\x02\x03")
assert buf.length() == 3
assert buf.read_byte() == 1
def test_write_read_byte(self):
buf = ByteBuffer()
buf.write_byte(42)
buf.rewind()
assert buf.read_byte() == 42
def test_write_read_bytes(self):
buf = ByteBuffer()
buf.write_bytes(b"\x01\x02\x03")
buf.rewind()
assert buf.read_bytes(3) == b"\x01\x02\x03"
class TestByteBufferIntegers:
def test_short_little_endian(self):
buf = ByteBuffer()
buf.write_short(0x1234)
buf.rewind()
assert buf.read_short() == 0x1234
def test_short_big_endian(self):
buf = ByteBuffer()
buf.write_short(0x1234, big_endian=True)
buf.rewind()
assert buf.read_short(big_endian=True) == 0x1234
def test_int(self):
buf = ByteBuffer()
buf.write_int(0x12345678)
buf.rewind()
assert buf.read_int() == 0x12345678
def test_long(self):
buf = ByteBuffer()
buf.write_long(0x123456789ABCDEF0)
buf.rewind()
assert buf.read_long() == 0x123456789ABCDEF0
def test_negative_int(self):
buf = ByteBuffer()
buf.write_int(-1)
buf.rewind()
assert buf.read_int() == -1
class TestByteBufferFloats:
def test_float(self):
buf = ByteBuffer()
buf.write_float(3.14)
buf.rewind()
assert abs(buf.read_float() - 3.14) < 1e-5
def test_double(self):
buf = ByteBuffer()
buf.write_double(3.141592653589793)
buf.rewind()
assert buf.read_double() == 3.141592653589793
class TestByteBufferStrings:
def test_string(self):
buf = ByteBuffer()
buf.write_string("Hello")
buf.rewind()
assert buf.read_string() == "Hello"
def test_fixed_string(self):
buf = ByteBuffer()
buf.write_fixed_string("Hi", 10)
buf.rewind()
assert buf.read_fixed_string(10) == "Hi"
def test_unicode_string(self):
buf = ByteBuffer()
buf.write_string("Hello, 世界")
buf.rewind()
assert buf.read_string() == "Hello, 世界"
class TestByteBufferPosition:
def test_seek_read(self):
buf = ByteBuffer()
buf.write_bytes(b"\x01\x02\x03\x04")
buf.seek_read(2)
assert buf.read_byte() == 3
def test_seek_write(self):
buf = ByteBuffer()
buf.write_bytes(b"\x01\x02\x03\x04")
buf.seek_write(2)
buf.write_byte(0xFF)
buf.rewind()
assert buf.read_bytes(4) == b"\x01\x02\xFF\x04"
def test_rewind(self):
buf = ByteBuffer()
buf.write_bytes(b"\x01\x02\x03")
buf.read_byte()
buf.read_byte()
buf.rewind()
assert buf.read_byte() == 1
def test_clear(self):
buf = ByteBuffer()
buf.write_bytes(b"\x01\x02\x03")
buf.clear()
assert buf.length() == 0
assert buf.read_pos() == 0
class TestByteBufferCapacity:
def test_auto_grow(self):
buf = ByteBuffer(4)
buf.write_bytes(b"\x01\x02\x03\x04\x05\x06")
assert buf.length() == 6
assert buf.capacity() >= 6
def test_remaining_read(self):
buf = ByteBuffer()
buf.write_bytes(b"\x01\x02\x03\x04")
buf.rewind()
buf.read_byte()
assert buf.remaining_read() == 3
def test_remaining_write(self):
buf = ByteBuffer(10)
buf.write_bytes(b"\x01\x02\x03")
assert buf.remaining_write() == 7
class TestByteBufferPeek:
def test_peek_byte(self):
buf = ByteBuffer()
buf.write_byte(42)
buf.rewind()
assert buf.peek_byte() == 42
assert buf.peek_byte() == 42 # Didn't advance
assert buf.read_byte() == 42 # Now advance
def test_skip(self):
buf = ByteBuffer()
buf.write_bytes(b"\x01\x02\x03\x04\x05")
buf.rewind()
buf.skip(2)
assert buf.read_byte() == 3
class TestByteBufferToBytes:
def test_to_bytes(self):
buf = ByteBuffer()
buf.write_bytes(b"\x01\x02\x03")
assert buf.to_bytes() == b"\x01\x02\x03"
class TestHelperFunctions:
def test_create_buffer(self):
buf = create_buffer(32)
assert buf.capacity() == 32
def test_buffer_from_hex(self):
buf = buffer_from_hex("010203")
assert buf.length() == 3
assert buf.read_byte() == 1
class TestMessage:
def test_write_read_message(self):
buf = ByteBuffer()
write_message(buf, 1, b"\xDE\xAD\xBE\xEF")
buf.rewind()
msg_type, payload = read_message(buf)
assert msg_type == 1
assert payload == b"\xDE\xAD\xBE\xEF"
def test_empty_message(self):
buf = ByteBuffer()
write_message(buf, 0, b"")
buf.rewind()
msg_type, payload = read_message(buf)
assert msg_type == 0
assert payload == b""
class TestVarint:
def test_write_read_small(self):
buf = ByteBuffer()
write_varint(buf, 127)
buf.rewind()
assert read_varint(buf) == 127
def test_write_read_medium(self):
buf = ByteBuffer()
write_varint(buf, 300)
buf.rewind()
assert read_varint(buf) == 300
def test_write_read_large(self):
buf = ByteBuffer()
write_varint(buf, 100000)
buf.rewind()
assert read_varint(buf) == 100000
def test_varints_list(self):
buf = ByteBuffer()
values = [1, 127, 300, 100000]
write_varints(buf, values)
buf.rewind()
result = read_varints(buf)
assert result == values
class TestEdgeCases:
def test_read_past_end(self):
buf = ByteBuffer()
buf.write_byte(1)
buf.rewind()
buf.read_byte()
with pytest.raises(BufferError):
buf.read_byte()
def test_peek_empty(self):
buf = ByteBuffer()
with pytest.raises(BufferError):
buf.peek_byte()
def test_zero_capacity(self):
buf = ByteBuffer(0)
buf.write_byte(1) # Should auto-grow
assert buf.length() == 1
def test_seek_bounds(self):
buf = ByteBuffer()
buf.write_bytes(b"\x01\x02\x03")
buf.seek_read(100) # Beyond end
assert buf.read_pos() == 3
buf.seek_read(-1) # Before start
assert buf.read_pos() == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_byte_buffer/test_byte_buffer_cli.py (6874 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_byte_buffer/test_byte_buffer_cli.rs (11594 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 136.6 KB/s
⏱️ Total time: 49ms
| true
|
byte_buffer
| 264
| 5
|
[
"context_manager",
"class_definition"
] | 0.652
| null |
example_calc_parser
|
calc_cli.py
|
#!/usr/bin/env python3
"""Calculator Parser CLI.
Recursive descent parser for arithmetic expressions.
"""
import argparse
import math
import sys
from dataclasses import dataclass
from enum import Enum, auto
class TokenType(Enum):
"""Token types for the calculator."""
NUMBER = auto()
PLUS = auto()
MINUS = auto()
MULTIPLY = auto()
DIVIDE = auto()
POWER = auto()
MODULO = auto()
LPAREN = auto()
RPAREN = auto()
COMMA = auto()
IDENTIFIER = auto()
EOF = auto()
@dataclass
class Token:
"""Lexer token."""
type: TokenType
value: str | float
position: int
class Lexer:
"""Tokenizer for arithmetic expressions."""
def __init__(self, text: str):
self.text = text
self.pos = 0
def peek(self) -> str:
"""Look at current character without consuming."""
if self.pos >= len(self.text):
return ""
return self.text[self.pos]
def advance(self) -> str:
"""Consume and return current character."""
char = self.peek()
self.pos += 1
return char
def skip_whitespace(self) -> None:
"""Skip whitespace characters."""
while self.peek().isspace():
self.advance()
def read_number(self) -> float:
"""Read a number (integer or float)."""
start = self.pos
has_dot = False
while self.peek().isdigit() or (self.peek() == "." and not has_dot):
if self.peek() == ".":
has_dot = True
self.advance()
return float(self.text[start : self.pos])
def read_identifier(self) -> str:
"""Read an identifier (function name or variable)."""
start = self.pos
while self.peek().isalnum() or self.peek() == "_":
self.advance()
return self.text[start : self.pos]
def next_token(self) -> Token:
"""Get the next token."""
self.skip_whitespace()
pos = self.pos
if self.pos >= len(self.text):
return Token(TokenType.EOF, "", pos)
char = self.peek()
if char.isdigit() or (
char == "." and self.pos + 1 < len(self.text) and self.text[self.pos + 1].isdigit()
):
return Token(TokenType.NUMBER, self.read_number(), pos)
if char.isalpha() or char == "_":
return Token(TokenType.IDENTIFIER, self.read_identifier(), pos)
self.advance()
token_map = {
"+": TokenType.PLUS,
"-": TokenType.MINUS,
"*": TokenType.MULTIPLY,
"/": TokenType.DIVIDE,
"^": TokenType.POWER,
"%": TokenType.MODULO,
"(": TokenType.LPAREN,
")": TokenType.RPAREN,
",": TokenType.COMMA,
}
if char in token_map:
return Token(token_map[char], char, pos)
raise SyntaxError(f"Unexpected character '{char}' at position {pos}")
def tokenize(self) -> list[Token]:
"""Tokenize entire input."""
tokens = []
while True:
token = self.next_token()
tokens.append(token)
if token.type == TokenType.EOF:
break
return tokens
class Parser:
"""Recursive descent parser for arithmetic expressions."""
FUNCTIONS = {
"sin": math.sin,
"cos": math.cos,
"tan": math.tan,
"sqrt": math.sqrt,
"abs": abs,
"log": math.log,
"log10": math.log10,
"exp": math.exp,
"floor": math.floor,
"ceil": math.ceil,
"round": round,
"min": min,
"max": max,
"pow": pow,
}
CONSTANTS = {
"pi": math.pi,
"e": math.e,
"tau": math.tau,
}
def __init__(self, text: str):
self.lexer = Lexer(text)
self.current_token = self.lexer.next_token()
self.variables: dict[str, float] = {}
def error(self, message: str) -> None:
"""Raise a syntax error."""
raise SyntaxError(f"{message} at position {self.current_token.position}")
def eat(self, token_type: TokenType) -> Token:
"""Consume a token of expected type."""
if self.current_token.type == token_type:
token = self.current_token
self.current_token = self.lexer.next_token()
return token
self.error(f"Expected {token_type.name}, got {self.current_token.type.name}")
return self.current_token # unreachable
def parse(self) -> float:
"""Parse and evaluate the expression."""
result = self.expression()
if self.current_token.type != TokenType.EOF:
self.error("Unexpected token after expression")
return result
def expression(self) -> float:
"""Parse addition/subtraction."""
result = self.term()
while self.current_token.type in (TokenType.PLUS, TokenType.MINUS):
if self.current_token.type == TokenType.PLUS:
self.eat(TokenType.PLUS)
result += self.term()
else:
self.eat(TokenType.MINUS)
result -= self.term()
return result
def term(self) -> float:
"""Parse multiplication/division."""
result = self.power()
while self.current_token.type in (TokenType.MULTIPLY, TokenType.DIVIDE, TokenType.MODULO):
if self.current_token.type == TokenType.MULTIPLY:
self.eat(TokenType.MULTIPLY)
result *= self.power()
elif self.current_token.type == TokenType.DIVIDE:
self.eat(TokenType.DIVIDE)
divisor = self.power()
if divisor == 0:
raise ZeroDivisionError("Division by zero")
result /= divisor
else:
self.eat(TokenType.MODULO)
result %= self.power()
return result
def power(self) -> float:
"""Parse exponentiation (right associative)."""
result = self.unary()
if self.current_token.type == TokenType.POWER:
self.eat(TokenType.POWER)
result = result ** self.power()
return result
def unary(self) -> float:
"""Parse unary operators."""
if self.current_token.type == TokenType.MINUS:
self.eat(TokenType.MINUS)
return -self.unary()
if self.current_token.type == TokenType.PLUS:
self.eat(TokenType.PLUS)
return self.unary()
return self.primary()
def primary(self) -> float:
"""Parse primary expressions."""
token = self.current_token
if token.type == TokenType.NUMBER:
self.eat(TokenType.NUMBER)
return float(token.value)
if token.type == TokenType.LPAREN:
self.eat(TokenType.LPAREN)
result = self.expression()
self.eat(TokenType.RPAREN)
return result
if token.type == TokenType.IDENTIFIER:
name = str(token.value)
self.eat(TokenType.IDENTIFIER)
# Check if it's a function call
if self.current_token.type == TokenType.LPAREN:
return self.function_call(name)
# Check if it's a constant
if name in self.CONSTANTS:
return self.CONSTANTS[name]
# Check if it's a variable
if name in self.variables:
return self.variables[name]
self.error(f"Unknown identifier '{name}'")
self.error(f"Unexpected token {token.type.name}")
return 0 # unreachable
def function_call(self, name: str) -> float:
"""Parse and evaluate function call."""
if name not in self.FUNCTIONS:
self.error(f"Unknown function '{name}'")
self.eat(TokenType.LPAREN)
args = []
if self.current_token.type != TokenType.RPAREN:
args.append(self.expression())
while self.current_token.type == TokenType.COMMA:
self.eat(TokenType.COMMA)
args.append(self.expression())
self.eat(TokenType.RPAREN)
func = self.FUNCTIONS[name]
try:
return func(*args)
except TypeError as e:
self.error(f"Function '{name}' error: {e}")
return 0 # unreachable
def evaluate(expression: str, variables: dict[str, float] | None = None) -> float:
"""Evaluate an arithmetic expression."""
parser = Parser(expression)
if variables:
parser.variables = variables
return parser.parse()
def tokenize(expression: str) -> list[Token]:
"""Tokenize an expression."""
lexer = Lexer(expression)
return lexer.tokenize()
def format_result(value: float) -> str:
"""Format result for display."""
if value == int(value):
return str(int(value))
return f"{value:.10g}"
def main() -> int:
parser = argparse.ArgumentParser(description="Calculator expression parser")
parser.add_argument("expression", nargs="?", help="Expression to evaluate")
parser.add_argument("--tokenize", action="store_true", help="Show tokens only")
parser.add_argument("--var", nargs="*", help="Variables: name=value")
args = parser.parse_args()
if not args.expression:
# Interactive mode
print("Calculator (type 'quit' to exit)")
while True:
try:
line = input("> ").strip()
if line.lower() in ("quit", "exit", "q"):
break
if not line:
continue
result = evaluate(line)
print(f"= {format_result(result)}")
except (SyntaxError, ZeroDivisionError, ValueError) as e:
print(f"Error: {e}")
except EOFError:
break
return 0
# Parse variables
variables = {}
if args.var:
for v in args.var:
name, value = v.split("=")
variables[name.strip()] = float(value.strip())
if args.tokenize:
tokens = tokenize(args.expression)
for token in tokens:
print(f"{token.type.name:12} {token.value!r:15} @ {token.position}")
return 0
try:
result = evaluate(args.expression, variables)
print(format_result(result))
except (SyntaxError, ZeroDivisionError, ValueError) as e:
print(f"Error: {e}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_calc_parser/calc_cli.py (10573 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_calc_parser/calc_cli.rs (16382 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_calc_parser/Cargo.toml (3 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 185.0 KB/s
⏱️ Total time: 56ms
| true
|
calc_parser
| 370
| 6
|
[
"class_definition",
"exception_handling",
"stdin_usage",
"decorator"
] | 0.612
| null |
example_calc_parser
|
test_calc_cli.py
|
"""Tests for calc_cli.py"""
import math
import pytest
from calc_cli import (
Lexer,
TokenType,
evaluate,
tokenize,
)
class TestLexer:
def test_number(self):
lexer = Lexer("42")
token = lexer.next_token()
assert token.type == TokenType.NUMBER
assert token.value == 42.0
def test_float(self):
lexer = Lexer("3.14")
token = lexer.next_token()
assert token.type == TokenType.NUMBER
assert token.value == pytest.approx(3.14)
def test_operators(self):
tokens = tokenize("+ - * / ^ %")
types = [t.type for t in tokens[:-1]] # Exclude EOF
assert types == [
TokenType.PLUS,
TokenType.MINUS,
TokenType.MULTIPLY,
TokenType.DIVIDE,
TokenType.POWER,
TokenType.MODULO,
]
def test_parentheses(self):
tokens = tokenize("()")
assert tokens[0].type == TokenType.LPAREN
assert tokens[1].type == TokenType.RPAREN
def test_identifier(self):
lexer = Lexer("sin")
token = lexer.next_token()
assert token.type == TokenType.IDENTIFIER
assert token.value == "sin"
def test_whitespace(self):
tokens = tokenize(" 1 + 2 ")
values = [t.value for t in tokens if t.type == TokenType.NUMBER]
assert values == [1.0, 2.0]
def test_expression(self):
tokens = tokenize("2 + 3 * 4")
types = [t.type for t in tokens[:-1]]
assert types == [
TokenType.NUMBER,
TokenType.PLUS,
TokenType.NUMBER,
TokenType.MULTIPLY,
TokenType.NUMBER,
]
class TestParser:
def test_number(self):
assert evaluate("42") == 42
def test_addition(self):
assert evaluate("2 + 3") == 5
def test_subtraction(self):
assert evaluate("5 - 3") == 2
def test_multiplication(self):
assert evaluate("2 * 3") == 6
def test_division(self):
assert evaluate("6 / 2") == 3
def test_modulo(self):
assert evaluate("7 % 3") == 1
def test_power(self):
assert evaluate("2 ^ 3") == 8
def test_precedence(self):
assert evaluate("2 + 3 * 4") == 14
assert evaluate("2 * 3 + 4") == 10
def test_parentheses(self):
assert evaluate("(2 + 3) * 4") == 20
def test_nested_parentheses(self):
assert evaluate("((2 + 3) * (4 - 1))") == 15
def test_unary_minus(self):
assert evaluate("-5") == -5
assert evaluate("2 + -3") == -1
assert evaluate("--5") == 5
def test_unary_plus(self):
assert evaluate("+5") == 5
def test_power_right_associative(self):
# 2^3^2 should be 2^9 = 512, not 8^2 = 64
assert evaluate("2 ^ 3 ^ 2") == 512
class TestFunctions:
def test_sin(self):
assert evaluate("sin(0)") == pytest.approx(0)
assert evaluate("sin(pi/2)") == pytest.approx(1)
def test_cos(self):
assert evaluate("cos(0)") == pytest.approx(1)
assert evaluate("cos(pi)") == pytest.approx(-1)
def test_sqrt(self):
assert evaluate("sqrt(4)") == 2
assert evaluate("sqrt(2)") == pytest.approx(math.sqrt(2))
def test_abs(self):
assert evaluate("abs(-5)") == 5
assert evaluate("abs(5)") == 5
def test_log(self):
assert evaluate("log(e)") == pytest.approx(1)
def test_exp(self):
assert evaluate("exp(0)") == 1
assert evaluate("exp(1)") == pytest.approx(math.e)
def test_floor_ceil(self):
assert evaluate("floor(3.7)") == 3
assert evaluate("ceil(3.2)") == 4
def test_min_max(self):
assert evaluate("min(3, 5)") == 3
assert evaluate("max(3, 5)") == 5
assert evaluate("min(1, 2, 3)") == 1
def test_pow(self):
assert evaluate("pow(2, 3)") == 8
def test_nested_functions(self):
assert evaluate("sqrt(abs(-16))") == 4
class TestConstants:
def test_pi(self):
assert evaluate("pi") == pytest.approx(math.pi)
def test_e(self):
assert evaluate("e") == pytest.approx(math.e)
def test_tau(self):
assert evaluate("tau") == pytest.approx(math.tau)
def test_in_expression(self):
assert evaluate("2 * pi") == pytest.approx(2 * math.pi)
class TestVariables:
def test_simple(self):
assert evaluate("x + 1", {"x": 5}) == 6
def test_multiple(self):
assert evaluate("x + y", {"x": 2, "y": 3}) == 5
def test_in_expression(self):
assert evaluate("2 * x + 3 * y", {"x": 4, "y": 2}) == 14
class TestErrors:
def test_division_by_zero(self):
with pytest.raises(ZeroDivisionError):
evaluate("1 / 0")
def test_unknown_identifier(self):
with pytest.raises(SyntaxError):
evaluate("unknown")
def test_unknown_function(self):
with pytest.raises(SyntaxError):
evaluate("foo(1)")
def test_unexpected_token(self):
# Parser handles unary +, so "1 + + 2" is valid (= 1 + (+2) = 3)
# Use truly invalid syntax
with pytest.raises(SyntaxError):
evaluate("1 2 +")
def test_unclosed_paren(self):
with pytest.raises(SyntaxError):
evaluate("(1 + 2")
def test_unexpected_char(self):
with pytest.raises(SyntaxError):
evaluate("1 @ 2")
class TestComplexExpressions:
def test_complex_1(self):
result = evaluate("(1 + 2) * (3 + 4) / 7")
assert result == pytest.approx(3)
def test_complex_2(self):
result = evaluate("2 ^ 3 + 4 * 5 - 6 / 2")
assert result == pytest.approx(25) # 8 + 20 - 3
def test_scientific(self):
result = evaluate("sqrt(3^2 + 4^2)")
assert result == pytest.approx(5)
def test_trig(self):
result = evaluate("sin(pi/6)")
assert result == pytest.approx(0.5)
def test_logarithm(self):
result = evaluate("log(e^2)")
assert result == pytest.approx(2)
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_calc_parser/test_calc_cli.py (6053 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_calc_parser/test_calc_cli.rs (11250 bytes)
⏱️ Parse time: 54ms
📊 Throughput: 108.2 KB/s
⏱️ Total time: 54ms
| true
|
calc_parser
| 224
| 5
|
[
"context_manager",
"class_definition",
"decorator"
] | 0.652
| null |
example_calendar
|
cal_tool.py
|
#!/usr/bin/env python3
"""Calendar Example - Calendar CLI."""
import argparse
import calendar
def cmd_month(args):
"""Show month calendar. Depyler: proven to terminate"""
print(calendar.month(args.year, args.month))
def cmd_year(args):
"""Show year calendar. Depyler: proven to terminate"""
print(calendar.calendar(args.year))
def cmd_weekday(args):
"""Get weekday name. Depyler: proven to terminate"""
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
day = calendar.weekday(args.year, args.month, args.day)
print(days[day])
def cmd_leap(args):
"""Check leap year. Depyler: proven to terminate"""
is_leap = calendar.isleap(args.year)
print(f"{args.year} is {'a leap' if is_leap else 'not a leap'} year")
def main():
parser = argparse.ArgumentParser(description="Calendar tool")
subs = parser.add_subparsers(dest="command", required=True)
m = subs.add_parser("month")
m.add_argument("year", type=int)
m.add_argument("month", type=int)
y = subs.add_parser("year")
y.add_argument("year", type=int)
w = subs.add_parser("weekday")
w.add_argument("year", type=int)
w.add_argument("month", type=int)
w.add_argument("day", type=int)
lp = subs.add_parser("leap")
lp.add_argument("year", type=int)
args = parser.parse_args()
{"month": cmd_month, "year": cmd_year, "weekday": cmd_weekday, "leap": cmd_leap}[args.command](
args
)
if __name__ == "__main__":
main()
| false
|
calendar
| 52
| 0
|
[] | 0
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 1367..1461, value: Dict(ExprDict { range: 1367..1447, keys: [Some(Constant(ExprConstant { range: 1368..1375, value: Str("month"), kind: None })), Some(Constant(ExprConstant { range: 1388..1394, value: Str("year"), kind: None })), Some(Constant(ExprConstant { range: 1406..1415, value: Str("weekday"), kind: None })), Some(Constant(ExprConstant { range: 1430..1436, value: Str("leap"), kind: None }))], values: [Name(ExprName { r
|
|
example_calendar
|
test_cal_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for calendar CLI."""
import subprocess
SCRIPT = "cal_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestMonth:
def test_month(self):
result = run(["month", "2024", "1"])
assert result.returncode == 0
assert "January" in result.stdout or "Mo" in result.stdout
class TestYear:
def test_year(self):
result = run(["year", "2024"])
assert result.returncode == 0
class TestWeekday:
def test_weekday(self):
result = run(["weekday", "2024", "1", "1"])
assert result.returncode == 0
assert "Monday" in result.stdout
class TestLeap:
def test_leap_true(self):
result = run(["leap", "2024"])
assert result.returncode == 0
assert "True" in result.stdout or "true" in result.stdout or "leap" in result.stdout.lower()
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_calendar/test_cal_tool.py (1067 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_calendar/test_cal_tool.rs (2894 bytes)
⏱️ Parse time: 50ms
📊 Throughput: 20.5 KB/s
⏱️ Total time: 51ms
| true
|
calendar
| 34
| 5
|
[
"class_definition"
] | 0.612
| null |
example_callback_pattern
|
callback_pattern_cli.py
|
#!/usr/bin/env python3
"""Callback Pattern CLI.
Callback and handler function patterns.
"""
import argparse
import sys
from collections.abc import Callable
# Event types
EventHandler = Callable[[str, dict[str, object]], None]
DataProcessor = Callable[[list[int]], list[int]]
Validator = Callable[[object], bool]
ErrorHandler = Callable[[Exception], None]
class EventEmitter:
"""Simple event emitter with callbacks."""
def __init__(self) -> None:
self._handlers: dict[str, list[EventHandler]] = {}
def on(self, event: str, handler: EventHandler) -> None:
"""Register event handler."""
if event not in self._handlers:
self._handlers[event] = []
self._handlers[event].append(handler)
def off(self, event: str, handler: EventHandler) -> None:
"""Remove event handler."""
if event in self._handlers:
self._handlers[event] = [h for h in self._handlers[event] if h != handler]
def emit(self, event: str, data: dict[str, object]) -> None:
"""Emit event to all handlers."""
if event in self._handlers:
for handler in self._handlers[event]:
handler(event, data)
def once(self, event: str, handler: EventHandler) -> None:
"""Register one-time handler."""
def wrapper(evt: str, data: dict[str, object]) -> None:
handler(evt, data)
self.off(event, wrapper)
self.on(event, wrapper)
class DataPipeline:
"""Data processing pipeline with callbacks."""
def __init__(self) -> None:
self._processors: list[DataProcessor] = []
self._error_handler: ErrorHandler | None = None
def add_processor(self, processor: DataProcessor) -> "DataPipeline":
"""Add processor to pipeline."""
self._processors.append(processor)
return self
def on_error(self, handler: ErrorHandler) -> "DataPipeline":
"""Set error handler."""
self._error_handler = handler
return self
def process(self, data: list[int]) -> list[int]:
"""Process data through pipeline."""
result = data
for processor in self._processors:
try:
result = processor(result)
except Exception as e:
if self._error_handler:
self._error_handler(e)
raise
return result
class FormValidator:
"""Form validator with validation callbacks."""
def __init__(self) -> None:
self._validators: dict[str, list[Validator]] = {}
def add_rule(self, field: str, validator: Validator) -> "FormValidator":
"""Add validation rule for field."""
if field not in self._validators:
self._validators[field] = []
self._validators[field].append(validator)
return self
def validate(self, data: dict[str, object]) -> tuple[bool, list[str]]:
"""Validate data, return (valid, errors)."""
errors: list[str] = []
for field, validators in self._validators.items():
value = data.get(field)
for validator in validators:
if not validator(value):
errors.append(f"Validation failed for {field}")
return (len(errors) == 0, errors)
def create_logger_callback(prefix: str) -> EventHandler:
"""Create logging callback."""
def handler(event: str, data: dict[str, object]) -> None:
print(f"[{prefix}] {event}: {data}")
return handler
def create_filter_callback(predicate: Callable[[int], bool]) -> DataProcessor:
"""Create filter processor callback."""
def processor(data: list[int]) -> list[int]:
return [x for x in data if predicate(x)]
return processor
def create_map_callback(transform: Callable[[int], int]) -> DataProcessor:
"""Create map processor callback."""
def processor(data: list[int]) -> list[int]:
return [transform(x) for x in data]
return processor
def create_range_validator(min_val: int, max_val: int) -> Validator:
"""Create range validator."""
def validator(value: object) -> bool:
if not isinstance(value, int):
return False
return min_val <= value <= max_val
return validator
def create_length_validator(min_len: int, max_len: int) -> Validator:
"""Create string length validator."""
def validator(value: object) -> bool:
if not isinstance(value, str):
return False
return min_len <= len(value) <= max_len
return validator
def create_pattern_validator(pattern: str) -> Validator:
"""Create pattern validator."""
import re
def validator(value: object) -> bool:
if not isinstance(value, str):
return False
return bool(re.match(pattern, value))
return validator
def with_callback(
func: Callable[..., object], callback: Callable[[object], None]
) -> Callable[..., object]:
"""Wrap function to call callback with result."""
def wrapper(*args: object, **kwargs: object) -> object:
result = func(*args, **kwargs)
callback(result)
return result
return wrapper
def with_error_callback(
func: Callable[..., object], on_error: ErrorHandler
) -> Callable[..., object]:
"""Wrap function to call error handler on exception."""
def wrapper(*args: object, **kwargs: object) -> object:
try:
return func(*args, **kwargs)
except Exception as e:
on_error(e)
raise
return wrapper
def async_like(
func: Callable[..., object], on_complete: Callable[[object], None], on_error: ErrorHandler
) -> Callable[..., None]:
"""Simulate async-style callbacks."""
def wrapper(*args: object, **kwargs: object) -> None:
try:
result = func(*args, **kwargs)
on_complete(result)
except Exception as e:
on_error(e)
return wrapper
def retry_with_callback(
func: Callable[[], object], max_retries: int, on_retry: Callable[[int, Exception], None]
) -> object:
"""Retry function with callback on each retry."""
last_error: Exception | None = None
for attempt in range(max_retries):
try:
return func()
except Exception as e:
last_error = e
if attempt < max_retries - 1:
on_retry(attempt + 1, e)
if last_error:
raise last_error
raise RuntimeError("No attempts made")
def map_with_callback(
items: list[int], transform: Callable[[int], int], on_item: Callable[[int, int, int], None]
) -> list[int]:
"""Map with callback for each item (index, old, new)."""
result: list[int] = []
for i, item in enumerate(items):
new_val = transform(item)
on_item(i, item, new_val)
result.append(new_val)
return result
def reduce_with_callback(
items: list[int],
func: Callable[[int, int], int],
initial: int,
on_step: Callable[[int, int, int], None],
) -> int:
"""Reduce with callback for each step (acc, item, new_acc)."""
acc = initial
for item in items:
new_acc = func(acc, item)
on_step(acc, item, new_acc)
acc = new_acc
return acc
def main() -> int:
parser = argparse.ArgumentParser(description="Callback pattern CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# events
subparsers.add_parser("events", help="Test event emitter")
# pipeline
pipe_p = subparsers.add_parser("pipeline", help="Test data pipeline")
pipe_p.add_argument("items", type=int, nargs="+")
pipe_p.add_argument("--filter-positive", action="store_true")
pipe_p.add_argument("--double", action="store_true")
# validate
val_p = subparsers.add_parser("validate", help="Test form validator")
val_p.add_argument("--age", type=int)
val_p.add_argument("--name")
args = parser.parse_args()
if args.command == "events":
emitter = EventEmitter()
log_handler = create_logger_callback("LOG")
emitter.on("data", log_handler)
emitter.emit("data", {"value": 42})
emitter.emit("data", {"value": 100})
elif args.command == "pipeline":
pipeline = DataPipeline()
if args.filter_positive:
pipeline.add_processor(create_filter_callback(lambda x: x > 0))
if args.double:
pipeline.add_processor(create_map_callback(lambda x: x * 2))
result = pipeline.process(args.items)
print(f"Result: {result}")
elif args.command == "validate":
validator = FormValidator()
if args.age is not None:
validator.add_rule("age", create_range_validator(0, 150))
if args.name is not None:
validator.add_rule("name", create_length_validator(1, 50))
data: dict[str, object] = {}
if args.age is not None:
data["age"] = args.age
if args.name is not None:
data["name"] = args.name
valid, errors = validator.validate(data)
if valid:
print("Valid!")
else:
print(f"Invalid: {', '.join(errors)}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
callback_pattern
| 315
| 0
|
[
"lambda",
"context_manager",
"class_definition",
"exception_handling",
"multiprocessing",
"functools"
] | 0.783
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 1739..1753, value: Str("DataPipeline"), kind: None })
|
|
example_callback_pattern
|
test_callback_pattern_cli.py
|
"""Tests for callback_pattern_cli.py"""
import pytest
from callback_pattern_cli import (
DataPipeline,
EventEmitter,
FormValidator,
async_like,
create_filter_callback,
create_length_validator,
create_logger_callback,
create_map_callback,
create_range_validator,
map_with_callback,
reduce_with_callback,
retry_with_callback,
with_callback,
with_error_callback,
)
class TestEventEmitter:
def test_on_and_emit(self):
emitter = EventEmitter()
events: list[dict[str, object]] = []
emitter.on("test", lambda e, d: events.append(d))
emitter.emit("test", {"value": 1})
emitter.emit("test", {"value": 2})
assert len(events) == 2
def test_off(self):
emitter = EventEmitter()
events: list[dict[str, object]] = []
def handler(e, d):
return events.append(d)
emitter.on("test", handler)
emitter.emit("test", {"value": 1})
emitter.off("test", handler)
emitter.emit("test", {"value": 2})
assert len(events) == 1
def test_once(self):
emitter = EventEmitter()
events: list[dict[str, object]] = []
emitter.once("test", lambda e, d: events.append(d))
emitter.emit("test", {"value": 1})
emitter.emit("test", {"value": 2})
assert len(events) == 1
def test_multiple_handlers(self):
emitter = EventEmitter()
results: list[int] = []
emitter.on("test", lambda e, d: results.append(1))
emitter.on("test", lambda e, d: results.append(2))
emitter.emit("test", {})
assert results == [1, 2]
class TestDataPipeline:
def test_single_processor(self):
pipeline = DataPipeline()
pipeline.add_processor(lambda data: [x * 2 for x in data])
result = pipeline.process([1, 2, 3])
assert result == [2, 4, 6]
def test_chained_processors(self):
pipeline = DataPipeline()
pipeline.add_processor(lambda data: [x * 2 for x in data])
pipeline.add_processor(lambda data: [x + 1 for x in data])
result = pipeline.process([1, 2, 3])
assert result == [3, 5, 7]
def test_error_handler(self):
errors: list[Exception] = []
pipeline = DataPipeline()
pipeline.add_processor(lambda data: [1 / x for x in data])
pipeline.on_error(lambda e: errors.append(e))
with pytest.raises(ZeroDivisionError):
pipeline.process([1, 0, 2])
assert len(errors) == 1
class TestFormValidator:
def test_valid(self):
validator = FormValidator()
validator.add_rule("age", lambda v: isinstance(v, int) and v >= 0)
valid, errors = validator.validate({"age": 25})
assert valid is True
assert errors == []
def test_invalid(self):
validator = FormValidator()
validator.add_rule("age", lambda v: isinstance(v, int) and v >= 0)
valid, errors = validator.validate({"age": -1})
assert valid is False
assert len(errors) == 1
def test_multiple_rules(self):
validator = FormValidator()
validator.add_rule("age", lambda v: isinstance(v, int))
validator.add_rule("age", lambda v: v >= 0)
validator.add_rule("name", lambda v: isinstance(v, str))
valid, errors = validator.validate({"age": 25, "name": "Alice"})
assert valid is True
class TestCreateLoggerCallback:
def test_creates_handler(self, capsys):
handler = create_logger_callback("TEST")
handler("event", {"key": "value"})
captured = capsys.readouterr()
assert "[TEST]" in captured.out
assert "event" in captured.out
class TestCreateFilterCallback:
def test_filter(self):
filter_positive = create_filter_callback(lambda x: x > 0)
result = filter_positive([-1, 0, 1, 2])
assert result == [1, 2]
class TestCreateMapCallback:
def test_map(self):
double = create_map_callback(lambda x: x * 2)
result = double([1, 2, 3])
assert result == [2, 4, 6]
class TestCreateRangeValidator:
def test_in_range(self):
validator = create_range_validator(0, 100)
assert validator(50) is True
def test_out_of_range(self):
validator = create_range_validator(0, 100)
assert validator(150) is False
def test_non_int(self):
validator = create_range_validator(0, 100)
assert validator("50") is False
class TestCreateLengthValidator:
def test_valid_length(self):
validator = create_length_validator(3, 10)
assert validator("hello") is True
def test_too_short(self):
validator = create_length_validator(3, 10)
assert validator("ab") is False
def test_non_string(self):
validator = create_length_validator(3, 10)
assert validator(123) is False
class TestWithCallback:
def test_calls_callback(self):
results: list[object] = []
wrapped = with_callback(lambda x: x * 2, lambda r: results.append(r))
result = wrapped(5)
assert result == 10
assert results == [10]
class TestWithErrorCallback:
def test_calls_error_handler(self):
errors: list[Exception] = []
wrapped = with_error_callback(
lambda x: 1 / x,
lambda e: errors.append(e)
)
with pytest.raises(ZeroDivisionError):
wrapped(0)
assert len(errors) == 1
class TestAsyncLike:
def test_success(self):
results: list[object] = []
errors: list[Exception] = []
wrapper = async_like(
lambda: 42,
lambda r: results.append(r),
lambda e: errors.append(e)
)
wrapper()
assert results == [42]
assert errors == []
def test_error(self):
results: list[object] = []
errors: list[Exception] = []
wrapper = async_like(
lambda: 1 / 0,
lambda r: results.append(r),
lambda e: errors.append(e)
)
wrapper()
assert results == []
assert len(errors) == 1
class TestRetryWithCallback:
def test_success_first_try(self):
retries: list[int] = []
result = retry_with_callback(
lambda: 42,
3,
lambda attempt, e: retries.append(attempt)
)
assert result == 42
assert retries == []
def test_success_after_retry(self):
attempts = [0]
retries: list[int] = []
def flaky() -> int:
attempts[0] += 1
if attempts[0] < 3:
raise ValueError("Not yet")
return 42
result = retry_with_callback(flaky, 5, lambda a, e: retries.append(a))
assert result == 42
assert retries == [1, 2]
class TestMapWithCallback:
def test_callback_called(self):
calls: list[tuple[int, int, int]] = []
result = map_with_callback(
[1, 2, 3],
lambda x: x * 2,
lambda i, old, new: calls.append((i, old, new))
)
assert result == [2, 4, 6]
assert calls == [(0, 1, 2), (1, 2, 4), (2, 3, 6)]
class TestReduceWithCallback:
def test_callback_called(self):
steps: list[tuple[int, int, int]] = []
result = reduce_with_callback(
[1, 2, 3],
lambda a, b: a + b,
0,
lambda acc, item, new: steps.append((acc, item, new))
)
assert result == 6
assert steps == [(0, 1, 1), (1, 2, 3), (3, 3, 6)]
class TestEdgeCases:
def test_empty_pipeline(self):
pipeline = DataPipeline()
result = pipeline.process([1, 2, 3])
assert result == [1, 2, 3]
def test_empty_validator(self):
validator = FormValidator()
valid, errors = validator.validate({})
assert valid is True
def test_no_handlers(self):
emitter = EventEmitter()
emitter.emit("unknown", {}) # Should not raise
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_callback_pattern/test_callback_pattern_cli.py (8039 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_callback_pattern/test_callback_pattern_cli.rs (15530 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_callback_pattern/Cargo.toml (2 dependencies)
⏱️ Parse time: 103ms
📊 Throughput: 75.6 KB/s
⏱️ Total time: 104ms
| true
|
callback_pattern
| 267
| 6
|
[
"lambda",
"context_manager",
"class_definition",
"exception_handling",
"functools"
] | 0.783
| null |
example_choices
|
choice_validator.py
|
#!/usr/bin/env python3
"""
Choices Validation Example
Demonstrates:
- choices parameter for string validation
- choices with integer types
- Default values with choices
- Help text showing valid choices
This validates depyler's ability to transpile choices
to Rust (clap value_parser with PossibleValues).
"""
import argparse
def main():
"""
Main entry point demonstrating choices validation.
Depyler: proven to terminate
"""
parser = argparse.ArgumentParser(
description="Demonstrate argument choices validation",
prog="choice_validator",
)
# String choices - log level
parser.add_argument(
"--level",
"-l",
type=str,
choices=["debug", "info", "warning", "error"],
required=True,
help="Log level (debug, info, warning, error)",
)
# Integer choices - priority
parser.add_argument(
"--priority",
"-p",
type=int,
choices=[1, 2, 3, 4, 5],
default=3,
help="Priority level 1-5 (default: 3)",
)
# String choices - output format
parser.add_argument(
"--format",
"-f",
type=str,
choices=["json", "yaml", "xml", "text"],
default="json",
help="Output format (default: json)",
)
parser.add_argument("--version", action="version", version="1.0.0")
args = parser.parse_args()
print(f"Level: {args.level}")
print(f"Priority: {args.priority}")
print(f"Format: {args.format}")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_choices/choice_validator.py (1553 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_choices/choice_validator.rs (1066 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_choices/Cargo.toml (1 dependencies)
⏱️ Parse time: 45ms
📊 Throughput: 33.1 KB/s
⏱️ Total time: 46ms
| true
|
choices
| 69
| 6
|
[
"context_manager"
] | 0.652
| null |
example_choices
|
test_choice_validator.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests written FIRST for choices validation."""
import subprocess
SCRIPT = "choice_validator.py"
def run(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(
["python3", SCRIPT] + args,
capture_output=True,
text=True,
cwd=__file__.rsplit("/", 1)[0],
)
class TestStringChoices:
"""Test string choice validation."""
def test_valid_log_level_debug(self):
result = run(["--level", "debug"])
assert result.returncode == 0
assert "Level: debug" in result.stdout
def test_valid_log_level_info(self):
result = run(["--level", "info"])
assert result.returncode == 0
assert "Level: info" in result.stdout
def test_valid_log_level_warning(self):
result = run(["--level", "warning"])
assert result.returncode == 0
def test_valid_log_level_error(self):
result = run(["--level", "error"])
assert result.returncode == 0
def test_invalid_log_level(self):
result = run(["--level", "trace"])
assert result.returncode != 0
assert "invalid choice" in result.stderr.lower()
class TestIntegerChoices:
"""Test integer choice validation."""
def test_valid_priority_1(self):
result = run(["--level", "info", "--priority", "1"])
assert result.returncode == 0
assert "Priority: 1" in result.stdout
def test_valid_priority_5(self):
result = run(["--level", "info", "--priority", "5"])
assert result.returncode == 0
assert "Priority: 5" in result.stdout
def test_invalid_priority(self):
result = run(["--level", "info", "--priority", "10"])
assert result.returncode != 0
assert "invalid choice" in result.stderr.lower()
class TestFormatChoices:
"""Test output format choices."""
def test_format_json(self):
result = run(["--level", "info", "--format", "json"])
assert result.returncode == 0
assert "Format: json" in result.stdout
def test_format_yaml(self):
result = run(["--level", "info", "--format", "yaml"])
assert result.returncode == 0
def test_format_xml(self):
result = run(["--level", "info", "--format", "xml"])
assert result.returncode == 0
def test_format_invalid(self):
result = run(["--level", "info", "--format", "csv"])
assert result.returncode != 0
class TestDefaults:
"""Test default values with choices."""
def test_default_priority(self):
result = run(["--level", "info"])
assert result.returncode == 0
assert "Priority: 3" in result.stdout # default
def test_default_format(self):
result = run(["--level", "info"])
assert result.returncode == 0
assert "Format: json" in result.stdout # default
class TestHelpOutput:
"""Test help shows choices."""
def test_help_shows_choices(self):
result = run(["--help"])
assert result.returncode == 0
assert "debug" in result.stdout
assert "info" in result.stdout
assert "json" in result.stdout
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_choices/test_choice_validator.py (3167 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_choices/test_choice_validator.rs (5820 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_choices/Cargo.toml (2 dependencies)
⏱️ Parse time: 99ms
📊 Throughput: 31.1 KB/s
⏱️ Total time: 99ms
| true
|
choices
| 107
| 6
|
[
"context_manager",
"class_definition",
"multiprocessing"
] | 0.652
| null |
example_closure_capture
|
closure_capture_cli.py
|
#!/usr/bin/env python3
"""Closure Capture CLI.
Closures capturing outer variables patterns.
"""
import argparse
import sys
from collections.abc import Callable
def make_adder(n: int) -> Callable[[int], int]:
"""Create function that adds n."""
def adder(x: int) -> int:
return x + n
return adder
def make_multiplier(n: int) -> Callable[[int], int]:
"""Create function that multiplies by n."""
def multiplier(x: int) -> int:
return x * n
return multiplier
def make_power(exp: int) -> Callable[[int], int]:
"""Create function that raises to power exp."""
def power(x: int) -> int:
return x**exp
return power
def make_range_checker(min_val: int, max_val: int) -> Callable[[int], bool]:
"""Create range checker function."""
def checker(x: int) -> bool:
return min_val <= x <= max_val
return checker
def make_prefix_formatter(prefix: str) -> Callable[[str], str]:
"""Create string formatter with prefix."""
def formatter(s: str) -> str:
return f"{prefix}{s}"
return formatter
def make_suffix_formatter(suffix: str) -> Callable[[str], str]:
"""Create string formatter with suffix."""
def formatter(s: str) -> str:
return f"{s}{suffix}"
return formatter
def make_counter() -> Callable[[], int]:
"""Create counter that increments each call."""
count = [0] # Use list to allow mutation in closure
def counter() -> int:
count[0] += 1
return count[0]
return counter
def make_accumulator(initial: int) -> tuple[Callable[[int], int], Callable[[], int]]:
"""Create accumulator with add and get functions."""
total = [initial]
def add(x: int) -> int:
total[0] += x
return total[0]
def get() -> int:
return total[0]
return (add, get)
def make_threshold_filter(threshold: int) -> Callable[[list[int]], list[int]]:
"""Create filter for values above threshold."""
def filter_fn(items: list[int]) -> list[int]:
return [x for x in items if x > threshold]
return filter_fn
def make_validator(rules: list[Callable[[str], bool]]) -> Callable[[str], bool]:
"""Create validator that checks all rules."""
def validate(value: str) -> bool:
return all(rule(value) for rule in rules)
return validate
def make_transformer_chain(fns: list[Callable[[int], int]]) -> Callable[[int], int]:
"""Create chain of transformers."""
def transform(x: int) -> int:
result = x
for fn in fns:
result = fn(result)
return result
return transform
def make_cache() -> tuple[Callable[[str, int], None], Callable[[str], int | None]]:
"""Create simple cache with set and get."""
cache: dict[str, int] = {}
def set_value(key: str, value: int) -> None:
cache[key] = value
def get_value(key: str) -> int | None:
return cache.get(key)
return (set_value, get_value)
def make_rate_limiter(max_calls: int) -> Callable[[], bool]:
"""Create rate limiter that allows max_calls."""
calls = [0]
def check() -> bool:
if calls[0] >= max_calls:
return False
calls[0] += 1
return True
return check
def make_toggler(initial: bool) -> Callable[[], bool]:
"""Create toggle function."""
state = [initial]
def toggle() -> bool:
state[0] = not state[0]
return state[0]
return toggle
def make_once() -> Callable[[Callable[[], int]], Callable[[], int]]:
"""Create function that runs inner function only once."""
def once_wrapper(fn: Callable[[], int]) -> Callable[[], int]:
called = [False]
result: list[int] = []
def wrapped() -> int:
if not called[0]:
called[0] = True
result.append(fn())
return result[0]
return wrapped
return once_wrapper
def make_comparator(key: str) -> Callable[[dict[str, int], dict[str, int]], int]:
"""Create comparator function for dict key."""
def compare(a: dict[str, int], b: dict[str, int]) -> int:
va = a.get(key, 0)
vb = b.get(key, 0)
if va < vb:
return -1
elif va > vb:
return 1
return 0
return compare
def make_default_factory(default: int) -> Callable[[dict[str, int], str], int]:
"""Create function that gets with default."""
def getter(d: dict[str, int], key: str) -> int:
return d.get(key, default)
return getter
def make_bounded_counter(
min_val: int, max_val: int
) -> tuple[Callable[[], int], Callable[[], int], Callable[[], int]]:
"""Create bounded counter with inc, dec, get."""
value = [min_val]
def inc() -> int:
if value[0] < max_val:
value[0] += 1
return value[0]
def dec() -> int:
if value[0] > min_val:
value[0] -= 1
return value[0]
def get() -> int:
return value[0]
return (inc, dec, get)
def make_string_builder() -> tuple[Callable[[str], None], Callable[[], str]]:
"""Create string builder with append and build."""
parts: list[str] = []
def append(s: str) -> None:
parts.append(s)
def build() -> str:
return "".join(parts)
return (append, build)
def compose(f: Callable[[int], int], g: Callable[[int], int]) -> Callable[[int], int]:
"""Compose two functions: (f . g)(x) = f(g(x))."""
def composed(x: int) -> int:
return f(g(x))
return composed
def apply_n_times(f: Callable[[int], int], n: int) -> Callable[[int], int]:
"""Apply function n times."""
def applied(x: int) -> int:
result = x
for _ in range(n):
result = f(result)
return result
return applied
def main() -> int:
parser = argparse.ArgumentParser(description="Closure capture CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# adder
add_p = subparsers.add_parser("adder", help="Create adder")
add_p.add_argument("n", type=int)
add_p.add_argument("x", type=int)
# multiplier
mul_p = subparsers.add_parser("multiplier", help="Create multiplier")
mul_p.add_argument("n", type=int)
mul_p.add_argument("x", type=int)
# counter
cnt_p = subparsers.add_parser("counter", help="Test counter")
cnt_p.add_argument("--calls", type=int, default=3)
# filter
filt_p = subparsers.add_parser("filter", help="Filter numbers")
filt_p.add_argument("threshold", type=int)
filt_p.add_argument("items", type=int, nargs="+")
args = parser.parse_args()
if args.command == "adder":
adder = make_adder(args.n)
print(f"{args.x} + {args.n} = {adder(args.x)}")
elif args.command == "multiplier":
multiplier = make_multiplier(args.n)
print(f"{args.x} * {args.n} = {multiplier(args.x)}")
elif args.command == "counter":
counter = make_counter()
for _ in range(args.calls):
print(f"Count: {counter()}")
elif args.command == "filter":
filter_fn = make_threshold_filter(args.threshold)
result = filter_fn(args.items)
print(f"Filtered: {result}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_closure_capture/closure_capture_cli.py (7349 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_closure_capture/closure_capture_cli.rs (10993 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_closure_capture/Cargo.toml (4 dependencies)
⏱️ Parse time: 106ms
📊 Throughput: 67.2 KB/s
⏱️ Total time: 107ms
| true
|
closure_capture
| 306
| 6
|
[
"context_manager"
] | 0.652
| null |
example_closure_capture
|
test_closure_capture_cli.py
|
"""Tests for closure_capture_cli.py"""
from closure_capture_cli import (
apply_n_times,
compose,
make_accumulator,
make_adder,
make_bounded_counter,
make_cache,
make_comparator,
make_counter,
make_default_factory,
make_multiplier,
make_once,
make_power,
make_prefix_formatter,
make_range_checker,
make_rate_limiter,
make_string_builder,
make_suffix_formatter,
make_threshold_filter,
make_toggler,
make_transformer_chain,
make_validator,
)
class TestMakeAdder:
def test_add_5(self):
add5 = make_adder(5)
assert add5(10) == 15
def test_add_zero(self):
add0 = make_adder(0)
assert add0(42) == 42
def test_add_negative(self):
add_neg = make_adder(-3)
assert add_neg(10) == 7
class TestMakeMultiplier:
def test_multiply_2(self):
mul2 = make_multiplier(2)
assert mul2(5) == 10
def test_multiply_zero(self):
mul0 = make_multiplier(0)
assert mul0(100) == 0
class TestMakePower:
def test_square(self):
square = make_power(2)
assert square(5) == 25
def test_cube(self):
cube = make_power(3)
assert cube(2) == 8
class TestMakeRangeChecker:
def test_in_range(self):
checker = make_range_checker(0, 10)
assert checker(5) is True
def test_out_of_range(self):
checker = make_range_checker(0, 10)
assert checker(15) is False
def test_boundary(self):
checker = make_range_checker(0, 10)
assert checker(0) is True
assert checker(10) is True
class TestMakePrefixFormatter:
def test_prefix(self):
fmt = make_prefix_formatter("Hello, ")
assert fmt("World") == "Hello, World"
class TestMakeSuffixFormatter:
def test_suffix(self):
fmt = make_suffix_formatter("!")
assert fmt("Hello") == "Hello!"
class TestMakeCounter:
def test_increment(self):
counter = make_counter()
assert counter() == 1
assert counter() == 2
assert counter() == 3
def test_independent(self):
c1 = make_counter()
c2 = make_counter()
assert c1() == 1
assert c2() == 1
assert c1() == 2
class TestMakeAccumulator:
def test_accumulate(self):
add, get = make_accumulator(0)
assert get() == 0
assert add(5) == 5
assert add(3) == 8
assert get() == 8
def test_initial_value(self):
add, get = make_accumulator(10)
assert get() == 10
assert add(5) == 15
class TestMakeThresholdFilter:
def test_filter(self):
filt = make_threshold_filter(5)
assert filt([1, 6, 3, 8, 4, 10]) == [6, 8, 10]
def test_none_pass(self):
filt = make_threshold_filter(100)
assert filt([1, 2, 3]) == []
class TestMakeValidator:
def test_all_pass(self):
rules = [
lambda s: len(s) >= 3,
lambda s: s.isalnum(),
]
validator = make_validator(rules)
assert validator("abc123") is True
def test_one_fails(self):
rules = [
lambda s: len(s) >= 3,
lambda s: s.isalnum(),
]
validator = make_validator(rules)
assert validator("ab") is False
class TestMakeTransformerChain:
def test_chain(self):
def add2(x):
return x + 2
def mul3(x):
return x * 3
chain = make_transformer_chain([add2, mul3])
assert chain(5) == 21 # (5 + 2) * 3
class TestMakeCache:
def test_set_get(self):
set_val, get_val = make_cache()
set_val("key", 42)
assert get_val("key") == 42
def test_missing_key(self):
_, get_val = make_cache()
assert get_val("missing") is None
class TestMakeRateLimiter:
def test_under_limit(self):
limiter = make_rate_limiter(3)
assert limiter() is True
assert limiter() is True
assert limiter() is True
def test_over_limit(self):
limiter = make_rate_limiter(2)
assert limiter() is True
assert limiter() is True
assert limiter() is False
class TestMakeToggler:
def test_toggle(self):
toggle = make_toggler(False)
assert toggle() is True
assert toggle() is False
assert toggle() is True
class TestMakeOnce:
def test_once(self):
once_factory = make_once()
call_count = [0]
def expensive() -> int:
call_count[0] += 1
return 42
wrapped = once_factory(expensive)
assert wrapped() == 42
assert wrapped() == 42
assert call_count[0] == 1
class TestMakeComparator:
def test_compare(self):
compare = make_comparator("value")
assert compare({"value": 1}, {"value": 2}) == -1
assert compare({"value": 2}, {"value": 1}) == 1
assert compare({"value": 1}, {"value": 1}) == 0
class TestMakeDefaultFactory:
def test_existing_key(self):
getter = make_default_factory(0)
assert getter({"a": 5}, "a") == 5
def test_missing_key(self):
getter = make_default_factory(-1)
assert getter({"a": 5}, "b") == -1
class TestMakeBoundedCounter:
def test_increment(self):
inc, dec, get = make_bounded_counter(0, 5)
assert get() == 0
assert inc() == 1
assert inc() == 2
def test_bounds(self):
inc, dec, get = make_bounded_counter(0, 2)
inc()
inc()
assert inc() == 2 # At max, doesn't increase
dec()
dec()
assert dec() == 0 # At min, doesn't decrease
class TestMakeStringBuilder:
def test_build(self):
append, build = make_string_builder()
append("Hello")
append(" ")
append("World")
assert build() == "Hello World"
class TestCompose:
def test_compose(self):
def add1(x):
return x + 1
def mul2(x):
return x * 2
composed = compose(mul2, add1) # mul2(add1(x))
assert composed(5) == 12 # (5 + 1) * 2
class TestApplyNTimes:
def test_apply(self):
def double(x):
return x * 2
quadruple = apply_n_times(double, 2)
assert quadruple(3) == 12
def test_apply_zero(self):
def double(x):
return x * 2
identity = apply_n_times(double, 0)
assert identity(3) == 3
class TestEdgeCases:
def test_negative_adder(self):
sub5 = make_adder(-5)
assert sub5(10) == 5
def test_power_of_one(self):
identity = make_power(1)
assert identity(7) == 7
def test_empty_validator_rules(self):
validator = make_validator([])
assert validator("anything") is True
def test_empty_transformer_chain(self):
chain = make_transformer_chain([])
assert chain(42) == 42
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_closure_capture/test_closure_capture_cli.py (6935 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_closure_capture/test_closure_capture_cli.rs (15389 bytes)
⏱️ Parse time: 56ms
📊 Throughput: 119.7 KB/s
⏱️ Total time: 56ms
| true
|
closure_capture
| 285
| 5
|
[
"lambda",
"class_definition"
] | 0.783
| null |
example_cmath
|
cmath_tool.py
|
#!/usr/bin/env python3
"""Cmath Example - Complex math CLI."""
import argparse
import math
def main():
parser = argparse.ArgumentParser(description="Complex math tool")
subs = parser.add_subparsers(dest="cmd", required=True)
a = subs.add_parser("abs")
a.add_argument("real", type=float)
a.add_argument("imag", type=float)
p = subs.add_parser("phase")
p.add_argument("real", type=float)
p.add_argument("imag", type=float)
po = subs.add_parser("polar")
po.add_argument("real", type=float)
po.add_argument("imag", type=float)
args = parser.parse_args()
if args.cmd == "abs":
print(math.sqrt(args.real * args.real + args.imag * args.imag))
elif args.cmd == "phase":
print(math.atan2(args.imag, args.real))
elif args.cmd == "polar":
r = math.sqrt(args.real * args.real + args.imag * args.imag)
theta = math.atan2(args.imag, args.real)
print(f"{r} {theta}")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_cmath/cmath_tool.py (997 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_cmath/cmath_tool.rs (1373 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_cmath/Cargo.toml (1 dependencies)
⏱️ Parse time: 50ms
📊 Throughput: 19.4 KB/s
⏱️ Total time: 50ms
| true
|
cmath
| 34
| 6
|
[] | 0
| null |
example_cmath
|
test_cmath_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for cmath CLI."""
import subprocess
SCRIPT = "cmath_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestCmath:
def test_abs(self): r = run(["abs", "3", "4"]); assert r.returncode == 0 and "5" in r.stdout
def test_phase(self): r = run(["phase", "1", "1"]); assert r.returncode == 0
def test_polar(self): r = run(["polar", "3", "4"]); assert r.returncode == 0 and "5" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_cmath/test_cmath_tool.py (614 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_cmath/test_cmath_tool.rs (1886 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 12.1 KB/s
⏱️ Total time: 49ms
| true
|
cmath
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_colorsys
|
color_tool.py
|
#!/usr/bin/env python3
"""Colorsys Example - Color conversion CLI."""
import argparse
import colorsys
def cmd_rgb2hsv(args):
"""RGB to HSV. Depyler: proven to terminate"""
r, g, b = args.r / 255, args.g / 255, args.b / 255
h, s, v = colorsys.rgb_to_hsv(r, g, b)
print(f"HSV: {h:.3f}, {s:.3f}, {v:.3f}")
def cmd_hsv2rgb(args):
"""HSV to RGB. Depyler: proven to terminate"""
r, g, b = colorsys.hsv_to_rgb(args.h, args.s, args.v)
print(f"RGB: {int(r * 255)}, {int(g * 255)}, {int(b * 255)}")
def cmd_rgb2hls(args):
"""RGB to HLS. Depyler: proven to terminate"""
r, g, b = args.r / 255, args.g / 255, args.b / 255
h, light, s = colorsys.rgb_to_hls(r, g, b)
print(f"HLS: {h:.3f}, {light:.3f}, {s:.3f}")
def cmd_hex(args):
"""RGB to Hex. Depyler: proven to terminate"""
print(f"#{args.r:02x}{args.g:02x}{args.b:02x}")
def main():
parser = argparse.ArgumentParser(description="Color conversion tool")
subs = parser.add_subparsers(dest="command", required=True)
r2h = subs.add_parser("rgb2hsv")
r2h.add_argument("r", type=int)
r2h.add_argument("g", type=int)
r2h.add_argument("b", type=int)
h2r = subs.add_parser("hsv2rgb")
h2r.add_argument("h", type=float)
h2r.add_argument("s", type=float)
h2r.add_argument("v", type=float)
r2l = subs.add_parser("rgb2hls")
r2l.add_argument("r", type=int)
r2l.add_argument("g", type=int)
r2l.add_argument("b", type=int)
hx = subs.add_parser("hex")
hx.add_argument("r", type=int)
hx.add_argument("g", type=int)
hx.add_argument("b", type=int)
args = parser.parse_args()
{"rgb2hsv": cmd_rgb2hsv, "hsv2rgb": cmd_hsv2rgb, "rgb2hls": cmd_rgb2hls, "hex": cmd_hex}[
args.command
](args)
if __name__ == "__main__":
main()
| false
|
colorsys
| 59
| 0
|
[] | 0
|
Error: Unsupported function call type: Subscript(ExprSubscript { range: 1638..1754, value: Dict(ExprDict { range: 1638..1726, keys: [Some(Constant(ExprConstant { range: 1639..1648, value: Str("rgb2hsv"), kind: None })), Some(Constant(ExprConstant { range: 1663..1672, value: Str("hsv2rgb"), kind: None })), Some(Constant(ExprConstant { range: 1687..1696, value: Str("rgb2hls"), kind: None })), Some(Constant(ExprConstant { range: 1711..1716, value: Str("hex"), kind: None }))], values: [Name(ExprName
|
|
example_colorsys
|
test_color_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for colorsys CLI."""
import subprocess
SCRIPT = "color_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestRgbToHsv:
def test_red(self):
result = run(["rgb2hsv", "255", "0", "0"])
assert result.returncode == 0
assert "0" in result.stdout # hue = 0 for red
class TestHsvToRgb:
def test_convert(self):
result = run(["hsv2rgb", "0.5", "1.0", "1.0"])
assert result.returncode == 0
class TestRgbToHls:
def test_convert(self):
result = run(["rgb2hls", "255", "128", "64"])
assert result.returncode == 0
class TestHex:
def test_to_hex(self):
result = run(["hex", "255", "128", "0"])
assert result.returncode == 0
assert "ff8000" in result.stdout.lower()
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_colorsys/test_color_tool.py (1003 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_colorsys/test_color_tool.rs (2864 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 19.6 KB/s
⏱️ Total time: 50ms
| true
|
colorsys
| 33
| 5
|
[
"class_definition"
] | 0.612
| null |
example_complex
|
complex_cli.py
|
#!/usr/bin/env python3
"""
Complex CLI example demonstrating advanced argparse features.
This example showcases:
- Mutually exclusive groups (--json, --xml, --yaml)
- Argument groups (input, output, processing)
- Custom types and validation (port, positive int, email)
- File I/O arguments
- Environment variable fallback
"""
import argparse
import os
import re
def port_number(value):
"""Custom type for port number validation (1-65535)."""
try:
port = int(value)
if port < 1 or port > 65535:
raise argparse.ArgumentTypeError(f"Port must be between 1 and 65535, got {port}")
return port
except ValueError:
raise argparse.ArgumentTypeError(f"Port must be an integer, got '{value}'") from None
def positive_int(value):
"""Custom type for positive integer validation (>= 1)."""
try:
num = int(value)
if num < 1:
raise argparse.ArgumentTypeError(f"Value must be positive (>= 1), got {num}")
return num
except ValueError:
raise argparse.ArgumentTypeError(f"Value must be an integer, got '{value}'") from None
def email_address(value):
"""Custom type for email address validation."""
# Simple email validation pattern
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
if not re.match(pattern, value):
raise argparse.ArgumentTypeError(f"Invalid email address: '{value}'")
return value
def main():
"""Main entry point for the complex CLI."""
# Create the top-level parser
parser = argparse.ArgumentParser(
description="Complex CLI example with advanced argparse features",
prog="complex_cli.py",
epilog="Example: %(prog)s --input data.txt --json --port 8080",
)
# Version
parser.add_argument(
"--version",
action="version",
version="1.0.0",
)
# ===== INPUT GROUP =====
input_group = parser.add_argument_group("input options", "Options for input file handling")
input_group.add_argument(
"--input",
"-i",
required=True,
help="Input file path (required)",
)
input_group.add_argument(
"--encoding",
default="utf-8",
help="Input file encoding (default: utf-8)",
)
# ===== OUTPUT GROUP =====
output_group = parser.add_argument_group(
"output options", "Options for output format and destination"
)
output_group.add_argument(
"--output",
"-o",
help="Output file path (default: stdout)",
)
# Mutually exclusive group for output format
format_group = output_group.add_mutually_exclusive_group()
format_group.add_argument(
"--json",
action="store_true",
help="Output in JSON format",
)
format_group.add_argument(
"--xml",
action="store_true",
help="Output in XML format",
)
format_group.add_argument(
"--yaml",
action="store_true",
help="Output in YAML format",
)
# ===== PROCESSING GROUP =====
processing_group = parser.add_argument_group(
"processing options", "Options for data processing"
)
processing_group.add_argument(
"--port",
type=port_number,
help="Port number (1-65535)",
)
processing_group.add_argument(
"--count",
type=positive_int,
help="Count (positive integer)",
)
processing_group.add_argument(
"--email",
type=email_address,
help="Email address",
)
# Parse arguments
args = parser.parse_args()
# Determine output format (with environment variable fallback)
output_format = None
if args.json:
output_format = "json"
elif args.xml:
output_format = "xml"
elif args.yaml:
output_format = "yaml"
else:
# Fallback to environment variable
env_format = os.environ.get("DEFAULT_FORMAT", "text")
output_format = env_format.lower()
# Get config file from environment if set
config_file = os.environ.get("CONFIG_FILE")
# Build output message
output_lines = []
output_lines.append(f"Input: {args.input}")
if args.output:
output_lines.append(f"Output: {args.output}")
else:
output_lines.append("Output: stdout")
output_lines.append(f"Format: {output_format}")
if args.encoding:
output_lines.append(f"Encoding: {args.encoding}")
if args.port:
output_lines.append(f"Port: {args.port}")
if args.count:
output_lines.append(f"Count: {args.count}")
if args.email:
output_lines.append(f"Email: {args.email}")
if config_file:
output_lines.append(f"Config: {config_file}")
# Print output
for line in output_lines:
print(line)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_complex/complex_cli.py (4866 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_complex/complex_cli.rs (6386 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_complex/Cargo.toml (2 dependencies)
⏱️ Parse time: 52ms
📊 Throughput: 90.7 KB/s
⏱️ Total time: 52ms
| true
|
complex
| 187
| 6
|
[
"context_manager",
"exception_handling",
"decorator"
] | 0.652
| null |
example_complex
|
test_complex_cli.py
|
#!/usr/bin/env python3
"""
Comprehensive test suite for complex_cli.py (example_complex).
This test suite follows the extreme TDD approach with 100% coverage goals.
Tests are written BEFORE implementation (RED phase).
Features Tested:
1. Mutually exclusive groups (--json, --xml, --yaml output formats)
2. Argument groups (input options, output options, processing options)
3. Custom types (port number, positive integer, valid email)
4. File I/O arguments (input file, output file with argparse.FileType)
5. Environment variable fallback (default output format, config file)
6. Default values and validation
7. Error handling
Test Categories:
1. Help and version output
2. Mutually exclusive groups
3. Argument groups
4. Custom type validation
5. File I/O
6. Environment variables
7. Combined features
8. Edge cases and error handling
"""
import os
import subprocess
from pathlib import Path
# Path to the script
SCRIPT_PATH = Path(__file__).parent / "complex_cli.py"
def run_cli(*args, env=None):
"""Helper function to run the CLI with given arguments and optional environment."""
full_env = os.environ.copy()
if env:
full_env.update(env)
result = subprocess.run(
["python3", str(SCRIPT_PATH)] + list(args),
capture_output=True,
text=True,
env=full_env,
)
return result
class TestHelpAndVersion:
"""Test help and version output."""
def test_help_flag(self):
"""Test --help flag displays comprehensive help"""
result = run_cli("--help")
assert result.returncode == 0, "Help should exit with code 0"
assert "usage:" in result.stdout.lower(), "Help should show usage"
# Check for argument groups in help
assert "input" in result.stdout.lower(), "Help should mention input options"
assert "output" in result.stdout.lower(), "Help should mention output options"
def test_version_flag(self):
"""Test --version flag displays version"""
result = run_cli("--version")
assert result.returncode == 0, "Version should exit with code 0"
assert "1.0.0" in result.stdout, "Should display version 1.0.0"
class TestMutuallyExclusiveGroups:
"""Test mutually exclusive argument groups."""
def test_json_format(self):
"""Test --json output format"""
result = run_cli("--json", "--input", "test.txt")
assert result.returncode == 0, "Should succeed with --json"
assert "json" in result.stdout.lower(), "Output should mention JSON format"
def test_xml_format(self):
"""Test --xml output format"""
result = run_cli("--xml", "--input", "test.txt")
assert result.returncode == 0, "Should succeed with --xml"
assert "xml" in result.stdout.lower(), "Output should mention XML format"
def test_yaml_format(self):
"""Test --yaml output format"""
result = run_cli("--yaml", "--input", "test.txt")
assert result.returncode == 0, "Should succeed with --yaml"
assert "yaml" in result.stdout.lower(), "Output should mention YAML format"
def test_json_and_xml_mutually_exclusive(self):
"""Test that --json and --xml cannot be used together"""
result = run_cli("--json", "--xml", "--input", "test.txt")
assert result.returncode != 0, "Should fail when both --json and --xml specified"
assert (
"not allowed" in result.stderr.lower() or "mutually exclusive" in result.stderr.lower()
)
def test_json_and_yaml_mutually_exclusive(self):
"""Test that --json and --yaml cannot be used together"""
result = run_cli("--json", "--yaml", "--input", "test.txt")
assert result.returncode != 0, "Should fail when both --json and --yaml specified"
def test_xml_and_yaml_mutually_exclusive(self):
"""Test that --xml and --yaml cannot be used together"""
result = run_cli("--xml", "--yaml", "--input", "test.txt")
assert result.returncode != 0, "Should fail when both --xml and --yaml specified"
def test_all_three_formats_mutually_exclusive(self):
"""Test that all three formats cannot be used together"""
result = run_cli("--json", "--xml", "--yaml", "--input", "test.txt")
assert result.returncode != 0, "Should fail when all three formats specified"
class TestCustomTypes:
"""Test custom type validation."""
def test_valid_port_number(self):
"""Test valid port number (1-65535)"""
result = run_cli("--port", "8080", "--input", "test.txt")
assert result.returncode == 0, "Should accept valid port number"
assert "8080" in result.stdout, "Output should show port number"
def test_port_too_low(self):
"""Test port number below valid range"""
result = run_cli("--port", "0", "--input", "test.txt")
assert result.returncode != 0, "Should reject port 0"
def test_port_too_high(self):
"""Test port number above valid range"""
result = run_cli("--port", "65536", "--input", "test.txt")
assert result.returncode != 0, "Should reject port > 65535"
def test_port_negative(self):
"""Test negative port number"""
result = run_cli("--port", "-1", "--input", "test.txt")
assert result.returncode != 0, "Should reject negative port"
def test_valid_count(self):
"""Test valid positive integer count"""
result = run_cli("--count", "10", "--input", "test.txt")
assert result.returncode == 0, "Should accept positive integer"
assert "10" in result.stdout, "Output should show count"
def test_count_zero(self):
"""Test count of zero (should fail for positive integer)"""
result = run_cli("--count", "0", "--input", "test.txt")
assert result.returncode != 0, "Should reject count of 0"
def test_count_negative(self):
"""Test negative count"""
result = run_cli("--count", "-5", "--input", "test.txt")
assert result.returncode != 0, "Should reject negative count"
def test_valid_email(self):
"""Test valid email address"""
result = run_cli("--email", "[email protected]", "--input", "test.txt")
assert result.returncode == 0, "Should accept valid email"
assert "[email protected]" in result.stdout
def test_invalid_email_no_at(self):
"""Test invalid email without @ symbol"""
result = run_cli("--email", "userexample.com", "--input", "test.txt")
assert result.returncode != 0, "Should reject email without @"
def test_invalid_email_no_domain(self):
"""Test invalid email without domain"""
result = run_cli("--email", "user@", "--input", "test.txt")
assert result.returncode != 0, "Should reject email without domain"
class TestFileIO:
"""Test file I/O arguments."""
def test_input_file_required(self):
"""Test that --input is required"""
result = run_cli()
assert result.returncode != 0, "Should fail without --input"
assert "required" in result.stderr.lower() or "expected" in result.stderr.lower()
def test_input_file_specified(self):
"""Test with input file specified"""
result = run_cli("--input", "data.txt")
assert result.returncode == 0, "Should succeed with --input"
assert "data.txt" in result.stdout, "Output should mention input file"
def test_output_file_optional(self):
"""Test output file is optional (defaults to stdout)"""
result = run_cli("--input", "data.txt")
assert result.returncode == 0, "Should succeed without --output"
def test_output_file_specified(self):
"""Test with output file specified"""
result = run_cli("--input", "data.txt", "--output", "result.txt")
assert result.returncode == 0, "Should succeed with --output"
assert "result.txt" in result.stdout, "Output should mention output file"
def test_input_file_with_path(self):
"""Test input file with path"""
result = run_cli("--input", "/path/to/data.txt")
assert result.returncode == 0, "Should handle file paths"
assert "/path/to/data.txt" in result.stdout
class TestEnvironmentVariables:
"""Test environment variable fallback."""
def test_default_format_from_env(self):
"""Test DEFAULT_FORMAT environment variable"""
result = run_cli("--input", "test.txt", env={"DEFAULT_FORMAT": "xml"})
assert result.returncode == 0, "Should succeed with env var"
# When no format flag is given, should use env var default
assert "xml" in result.stdout.lower() or "format" in result.stdout.lower()
def test_format_flag_overrides_env(self):
"""Test that explicit --json overrides DEFAULT_FORMAT env var"""
result = run_cli("--json", "--input", "test.txt", env={"DEFAULT_FORMAT": "xml"})
assert result.returncode == 0, "Should succeed"
assert "json" in result.stdout.lower(), "Explicit flag should override env var"
def test_config_file_from_env(self):
"""Test CONFIG_FILE environment variable"""
result = run_cli("--input", "test.txt", env={"CONFIG_FILE": "/etc/config.yaml"})
assert result.returncode == 0, "Should accept config file from env"
class TestArgumentGroups:
"""Test that argument groups work correctly."""
def test_input_group_arguments(self):
"""Test input group arguments work together"""
result = run_cli("--input", "data.txt", "--encoding", "utf-8")
assert result.returncode == 0, "Input group args should work"
assert "utf-8" in result.stdout, "Output should show encoding"
def test_output_group_arguments(self):
"""Test output group arguments work together"""
result = run_cli("--input", "data.txt", "--output", "result.txt", "--json")
assert result.returncode == 0, "Output group args should work"
def test_processing_group_arguments(self):
"""Test processing group arguments work together"""
result = run_cli("--input", "data.txt", "--count", "5", "--port", "8080")
assert result.returncode == 0, "Processing group args should work"
class TestCombinedFeatures:
"""Test combinations of features."""
def test_full_command_json(self):
"""Test full command with JSON output"""
result = run_cli(
"--input",
"data.txt",
"--output",
"result.txt",
"--json",
"--port",
"8080",
"--count",
"10",
"--email",
"[email protected]",
)
assert result.returncode == 0, "Full command should succeed"
assert "json" in result.stdout.lower()
assert "8080" in result.stdout
assert "10" in result.stdout
assert "[email protected]" in result.stdout
def test_full_command_xml(self):
"""Test full command with XML output"""
result = run_cli(
"--input",
"data.txt",
"--xml",
"--count",
"5",
)
assert result.returncode == 0, "Full command should succeed"
assert "xml" in result.stdout.lower()
def test_minimal_command(self):
"""Test minimal required arguments only"""
result = run_cli("--input", "data.txt")
assert result.returncode == 0, "Minimal command should succeed"
class TestEdgeCases:
"""Test edge cases and boundary conditions."""
def test_port_boundary_1(self):
"""Test port number at lower boundary (1)"""
result = run_cli("--port", "1", "--input", "test.txt")
assert result.returncode == 0, "Port 1 should be valid"
def test_port_boundary_65535(self):
"""Test port number at upper boundary (65535)"""
result = run_cli("--port", "65535", "--input", "test.txt")
assert result.returncode == 0, "Port 65535 should be valid"
def test_count_boundary_1(self):
"""Test count at lower boundary (1)"""
result = run_cli("--count", "1", "--input", "test.txt")
assert result.returncode == 0, "Count 1 should be valid"
def test_very_long_input_path(self):
"""Test with very long file path"""
long_path = "a" * 200 + ".txt"
result = run_cli("--input", long_path)
assert result.returncode == 0, "Should handle long paths"
def test_special_chars_in_filename(self):
"""Test filename with special characters"""
result = run_cli("--input", "file-name_2024.txt")
assert result.returncode == 0, "Should handle special chars in filename"
def test_stdout_ends_with_newline(self):
"""Test that output ends with newline"""
result = run_cli("--input", "test.txt")
if result.stdout:
assert result.stdout.endswith("\n"), "Output should end with newline"
def test_deterministic_output(self):
"""Test that output is deterministic across multiple runs"""
result1 = run_cli("--input", "test.txt", "--json")
result2 = run_cli("--input", "test.txt", "--json")
assert result1.stdout == result2.stdout, "Output should be deterministic"
assert result1.returncode == result2.returncode
class TestErrorMessages:
"""Test error messages are helpful."""
def test_missing_input_error_message(self):
"""Test error message when --input is missing"""
result = run_cli("--json")
assert result.returncode != 0
assert "--input" in result.stderr or "input" in result.stderr.lower()
def test_invalid_port_error_message(self):
"""Test error message for invalid port"""
result = run_cli("--port", "99999", "--input", "test.txt")
assert result.returncode != 0
assert "port" in result.stderr.lower() or "invalid" in result.stderr.lower()
def test_mutual_exclusion_error_message(self):
"""Test error message for mutually exclusive args"""
result = run_cli("--json", "--xml", "--input", "test.txt")
assert result.returncode != 0
# Error should clearly indicate the conflict
assert (
"not allowed" in result.stderr.lower()
or "mutually exclusive" in result.stderr.lower()
or "one of" in result.stderr.lower()
)
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_complex/test_complex_cli.py (14363 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_complex/test_complex_cli.rs (21681 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_complex/Cargo.toml (2 dependencies)
⏱️ Parse time: 56ms
📊 Throughput: 250.3 KB/s
⏱️ Total time: 56ms
| true
|
complex
| 356
| 6
|
[
"context_manager",
"class_definition",
"decorator",
"multiprocessing"
] | 0.652
| null |
example_config
|
config_manager.py
|
#!/usr/bin/env python3
"""
Config File Example - Configuration management
Demonstrates:
- Reading/writing JSON config files
- Merging CLI args with config file defaults
- Subcommands for config operations (get, set, list, init)
- File I/O operations
- Nested dict handling
This validates depyler's ability to transpile file operations
and JSON handling to Rust (serde_json + std::fs).
"""
import argparse
import json
import sys
from pathlib import Path
DEFAULT_CONFIG = {
"database": {"host": "localhost", "port": 5432},
"logging": {"level": "INFO", "file": "app.log"},
"features": {"debug": False, "verbose": False},
}
def load_config(path):
"""
Load config from JSON file
Returns default config if file doesn't exist.
Depyler: proven to terminate
"""
if Path(path).exists():
with open(path) as f:
return json.load(f)
return DEFAULT_CONFIG.copy()
def save_config(path, config):
"""
Save config to JSON file
Depyler: proven to terminate
"""
with open(path, "w") as f:
json.dump(config, f, indent=2)
def get_nested_value(config, key):
"""
Get value from nested dict using dot notation
Example: "database.host" -> config["database"]["host"]
Depyler: proven to terminate
"""
keys = key.split(".")
value = config
for k in keys:
if isinstance(value, dict) and k in value:
value = value[k]
else:
return None
return value
def set_nested_value(config, key, value):
"""
Set value in nested dict using dot notation
Example: "database.host", "db.example.com" -> config["database"]["host"] = "db.example.com"
Depyler: proven to terminate
"""
keys = key.split(".")
current = config
for k in keys[:-1]:
if k not in current:
current[k] = {}
current = current[k]
current[keys[-1]] = value
def main():
"""
Main entry point for config manager CLI
Supports subcommands: init, get, set, list
"""
parser = argparse.ArgumentParser(
description="Configuration file management CLI",
prog="config_manager.py",
)
parser.add_argument(
"--config", default="config.json", help="Path to config file (default: config.json)"
)
subparsers = parser.add_subparsers(dest="action", required=True, help="Action to perform")
# Init command - create default config
subparsers.add_parser("init", help="Initialize default config file")
# Get command - retrieve config value
get_parser = subparsers.add_parser("get", help="Get config value by key")
get_parser.add_argument("key", help="Config key using dot notation (e.g., database.host)")
# Set command - update config value
set_parser = subparsers.add_parser("set", help="Set config value")
set_parser.add_argument("key", help="Config key using dot notation")
set_parser.add_argument("value", help="Config value to set")
# List command - show all config
subparsers.add_parser("list", help="List all config values")
args = parser.parse_args()
# Handle init action
if args.action == "init":
save_config(args.config, DEFAULT_CONFIG)
print(f"Initialized config at {args.config}")
return
# Load config for other actions
config = load_config(args.config)
# Handle list action
if args.action == "list":
print(json.dumps(config, indent=2))
# Handle get action
elif args.action == "get":
value = get_nested_value(config, args.key)
if value is None:
print(f"Error: Key not found: {args.key}", file=sys.stderr)
sys.exit(1)
# Format output based on type
if isinstance(value, (dict, list)):
print(json.dumps(value, indent=2))
else:
print(value)
# Handle set action
elif args.action == "set":
set_nested_value(config, args.key, args.value)
save_config(args.config, config)
print(f"Set {args.key} = {args.value}")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_config/config_manager.py (4099 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_config/config_manager.rs (6713 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_config/Cargo.toml (4 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 75.2 KB/s
⏱️ Total time: 53ms
| true
|
config
| 151
| 6
|
[
"context_manager"
] | 0.652
| null |
example_config
|
test_config_manager.py
|
#!/usr/bin/env python3
"""
Tests for config_manager.py
Comprehensive test coverage for configuration file management CLI.
"""
import json
import subprocess
from pathlib import Path
import pytest
SCRIPT = Path(__file__).parent / "config_manager.py"
def run_cli(*args):
"""
Helper to run config_manager.py CLI
Returns (stdout, stderr, returncode)
"""
result = subprocess.run(
["python3", str(SCRIPT)] + list(args),
capture_output=True,
text=True,
)
return result.stdout, result.stderr, result.returncode
class TestConfigInit:
"""Test config initialization"""
def test_init_creates_default_config(self, tmp_path):
"""Test that init creates a config file with default values"""
config_file = tmp_path / "test_config.json"
stdout, stderr, code = run_cli("--config", str(config_file), "init")
assert code == 0
assert config_file.exists()
assert f"Initialized config at {config_file}" in stdout
# Verify content
with open(config_file) as f:
config = json.load(f)
assert "database" in config
assert "logging" in config
assert "features" in config
def test_init_overwrites_existing_config(self, tmp_path):
"""Test that init overwrites existing config"""
config_file = tmp_path / "test_config.json"
# Create existing config
with open(config_file, "w") as f:
json.dump({"old": "data"}, f)
stdout, stderr, code = run_cli("--config", str(config_file), "init")
assert code == 0
with open(config_file) as f:
config = json.load(f)
assert "old" not in config
assert "database" in config
class TestConfigList:
"""Test config listing"""
def test_list_shows_default_config(self, tmp_path):
"""Test that list shows all config values"""
config_file = tmp_path / "test_config.json"
run_cli("--config", str(config_file), "init")
stdout, stderr, code = run_cli("--config", str(config_file), "list")
assert code == 0
config = json.loads(stdout)
assert config["database"]["host"] == "localhost"
assert config["database"]["port"] == 5432
assert config["logging"]["level"] == "INFO"
def test_list_nonexistent_config_shows_defaults(self, tmp_path):
"""Test that list shows defaults if config doesn't exist"""
config_file = tmp_path / "nonexistent.json"
stdout, stderr, code = run_cli("--config", str(config_file), "list")
assert code == 0
config = json.loads(stdout)
assert "database" in config
class TestConfigGet:
"""Test getting config values"""
def test_get_top_level_key(self, tmp_path):
"""Test getting a top-level config key"""
config_file = tmp_path / "test_config.json"
run_cli("--config", str(config_file), "init")
stdout, stderr, code = run_cli("--config", str(config_file), "get", "database")
assert code == 0
value = json.loads(stdout)
assert value["host"] == "localhost"
assert value["port"] == 5432
def test_get_nested_key(self, tmp_path):
"""Test getting a nested config key using dot notation"""
config_file = tmp_path / "test_config.json"
run_cli("--config", str(config_file), "init")
stdout, stderr, code = run_cli("--config", str(config_file), "get", "database.host")
assert code == 0
assert stdout.strip() == "localhost"
def test_get_nested_number(self, tmp_path):
"""Test getting a numeric config value"""
config_file = tmp_path / "test_config.json"
run_cli("--config", str(config_file), "init")
stdout, stderr, code = run_cli("--config", str(config_file), "get", "database.port")
assert code == 0
assert stdout.strip() == "5432"
def test_get_nested_boolean(self, tmp_path):
"""Test getting a boolean config value"""
config_file = tmp_path / "test_config.json"
run_cli("--config", str(config_file), "init")
stdout, stderr, code = run_cli("--config", str(config_file), "get", "features.debug")
assert code == 0
assert stdout.strip() == "False"
def test_get_nonexistent_key_fails(self, tmp_path):
"""Test that getting a nonexistent key fails"""
config_file = tmp_path / "test_config.json"
run_cli("--config", str(config_file), "init")
stdout, stderr, code = run_cli("--config", str(config_file), "get", "nonexistent.key")
assert code == 1
assert "Key not found" in stderr
class TestConfigSet:
"""Test setting config values"""
def test_set_string_value(self, tmp_path):
"""Test setting a string config value"""
config_file = tmp_path / "test_config.json"
run_cli("--config", str(config_file), "init")
stdout, stderr, code = run_cli(
"--config", str(config_file), "set", "database.host", "db.example.com"
)
assert code == 0
assert "Set database.host = db.example.com" in stdout
# Verify value was saved
stdout, _, _ = run_cli("--config", str(config_file), "get", "database.host")
assert stdout.strip() == "db.example.com"
def test_set_creates_new_key(self, tmp_path):
"""Test that set creates a new key if it doesn't exist"""
config_file = tmp_path / "test_config.json"
run_cli("--config", str(config_file), "init")
stdout, stderr, code = run_cli(
"--config", str(config_file), "set", "newkey.nested", "newvalue"
)
assert code == 0
# Verify new key exists
stdout, _, _ = run_cli("--config", str(config_file), "get", "newkey.nested")
assert stdout.strip() == "newvalue"
def test_set_persists_to_file(self, tmp_path):
"""Test that set persists changes to file"""
config_file = tmp_path / "test_config.json"
run_cli("--config", str(config_file), "init")
run_cli("--config", str(config_file), "set", "logging.level", "DEBUG")
# Read file directly
with open(config_file) as f:
config = json.load(f)
assert config["logging"]["level"] == "DEBUG"
class TestConfigHelp:
"""Test help messages"""
def test_help_message(self):
"""Test that --help works"""
stdout, stderr, code = run_cli("--help")
assert code == 0
assert "Configuration file management" in stdout
assert "init" in stdout
assert "get" in stdout
assert "set" in stdout
assert "list" in stdout
def test_subcommand_help(self):
"""Test that subcommand help works"""
stdout, stderr, code = run_cli("get", "--help")
assert code == 0
assert "key" in stdout # Should show key argument
class TestConfigDefaultPath:
"""Test default config path behavior"""
def test_default_config_path(self, tmp_path, monkeypatch):
"""Test that default config path is config.json"""
# Change to temp directory
monkeypatch.chdir(tmp_path)
stdout, stderr, code = run_cli("init")
assert code == 0
assert Path("config.json").exists()
@pytest.fixture
def tmp_path(tmp_path_factory):
"""Create a temporary directory for tests"""
return tmp_path_factory.mktemp("config_test")
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_config/test_config_manager.py (7454 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_config/test_config_manager.rs (10088 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_config/Cargo.toml (2 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 135.0 KB/s
⏱️ Total time: 54ms
| true
|
config
| 235
| 6
|
[
"context_manager",
"class_definition",
"decorator"
] | 0.652
| null |
example_config_validator
|
config_cli.py
|
#!/usr/bin/env python3
"""Configuration Validator CLI.
Validate configuration dictionaries against rules.
"""
import argparse
import json
import sys
from dataclasses import dataclass, field
from enum import Enum, auto
class RuleType(Enum):
"""Validation rule types."""
REQUIRED = auto()
TYPE = auto()
MIN = auto()
MAX = auto()
MIN_LENGTH = auto()
MAX_LENGTH = auto()
PATTERN = auto()
ENUM = auto()
CUSTOM = auto()
class ValueType(Enum):
"""Configuration value types."""
STRING = auto()
INT = auto()
FLOAT = auto()
BOOL = auto()
LIST = auto()
DICT = auto()
ANY = auto()
@dataclass
class Rule:
"""Validation rule."""
rule_type: RuleType
value: any = None
@dataclass
class FieldSchema:
"""Field schema definition."""
name: str
value_type: ValueType = ValueType.ANY
rules: list[Rule] = field(default_factory=list)
nested: dict[str, "FieldSchema"] | None = None
@dataclass
class ValidationError:
"""Validation error."""
path: str
message: str
rule_type: RuleType | None = None
def get_value_type(value: any) -> ValueType:
"""Get ValueType for a Python value."""
if isinstance(value, bool):
return ValueType.BOOL
if isinstance(value, int):
return ValueType.INT
if isinstance(value, float):
return ValueType.FLOAT
if isinstance(value, str):
return ValueType.STRING
if isinstance(value, list):
return ValueType.LIST
if isinstance(value, dict):
return ValueType.DICT
return ValueType.ANY
def type_matches(value: any, expected: ValueType) -> bool:
"""Check if value matches expected type."""
if expected == ValueType.ANY:
return True
actual = get_value_type(value)
# Allow int for float
if expected == ValueType.FLOAT and actual == ValueType.INT:
return True
return actual == expected
def validate_field(value: any, schema: FieldSchema, path: str) -> list[ValidationError]:
"""Validate a field against its schema."""
errors = []
for rule in schema.rules:
if rule.rule_type == RuleType.REQUIRED:
if value is None:
errors.append(
ValidationError(path, f"Field '{path}' is required", RuleType.REQUIRED)
)
return errors
if value is None:
continue
if rule.rule_type == RuleType.TYPE:
if not type_matches(value, schema.value_type):
errors.append(
ValidationError(
path,
f"Expected {schema.value_type.name.lower()}, got {get_value_type(value).name.lower()}",
RuleType.TYPE,
)
)
elif rule.rule_type == RuleType.MIN:
if isinstance(value, (int, float)) and value < rule.value:
errors.append(
ValidationError(
path, f"Value {value} is less than minimum {rule.value}", RuleType.MIN
)
)
elif rule.rule_type == RuleType.MAX:
if isinstance(value, (int, float)) and value > rule.value:
errors.append(
ValidationError(
path, f"Value {value} is greater than maximum {rule.value}", RuleType.MAX
)
)
elif rule.rule_type == RuleType.MIN_LENGTH:
if hasattr(value, "__len__") and len(value) < rule.value:
errors.append(
ValidationError(
path,
f"Length {len(value)} is less than minimum {rule.value}",
RuleType.MIN_LENGTH,
)
)
elif rule.rule_type == RuleType.MAX_LENGTH:
if hasattr(value, "__len__") and len(value) > rule.value:
errors.append(
ValidationError(
path,
f"Length {len(value)} is greater than maximum {rule.value}",
RuleType.MAX_LENGTH,
)
)
elif rule.rule_type == RuleType.PATTERN:
import re
if isinstance(value, str) and not re.match(rule.value, value):
errors.append(
ValidationError(
path, f"Value does not match pattern '{rule.value}'", RuleType.PATTERN
)
)
elif rule.rule_type == RuleType.ENUM:
if value not in rule.value:
errors.append(
ValidationError(path, f"Value must be one of: {rule.value}", RuleType.ENUM)
)
# Validate nested fields
if schema.nested and isinstance(value, dict):
for field_name, field_schema in schema.nested.items():
field_value = value.get(field_name)
field_path = f"{path}.{field_name}" if path else field_name
errors.extend(validate_field(field_value, field_schema, field_path))
return errors
def validate(config: dict, schema: dict[str, FieldSchema]) -> list[ValidationError]:
"""Validate configuration against schema."""
errors = []
for field_name, field_schema in schema.items():
value = config.get(field_name)
errors.extend(validate_field(value, field_schema, field_name))
return errors
def create_field(
value_type: ValueType = ValueType.ANY,
required: bool = False,
min_val: float | None = None,
max_val: float | None = None,
min_length: int | None = None,
max_length: int | None = None,
pattern: str | None = None,
enum: list | None = None,
nested: dict[str, "FieldSchema"] | None = None,
) -> FieldSchema:
"""Create a field schema with rules."""
rules = []
if required:
rules.append(Rule(RuleType.REQUIRED))
rules.append(Rule(RuleType.TYPE))
if min_val is not None:
rules.append(Rule(RuleType.MIN, min_val))
if max_val is not None:
rules.append(Rule(RuleType.MAX, max_val))
if min_length is not None:
rules.append(Rule(RuleType.MIN_LENGTH, min_length))
if max_length is not None:
rules.append(Rule(RuleType.MAX_LENGTH, max_length))
if pattern is not None:
rules.append(Rule(RuleType.PATTERN, pattern))
if enum is not None:
rules.append(Rule(RuleType.ENUM, enum))
return FieldSchema("", value_type, rules, nested)
def parse_type(type_str: str) -> ValueType:
"""Parse type string to ValueType."""
type_map = {
"string": ValueType.STRING,
"str": ValueType.STRING,
"int": ValueType.INT,
"integer": ValueType.INT,
"float": ValueType.FLOAT,
"number": ValueType.FLOAT,
"bool": ValueType.BOOL,
"boolean": ValueType.BOOL,
"list": ValueType.LIST,
"array": ValueType.LIST,
"dict": ValueType.DICT,
"object": ValueType.DICT,
"any": ValueType.ANY,
}
return type_map.get(type_str.lower(), ValueType.ANY)
def parse_schema_dict(schema_dict: dict) -> dict[str, FieldSchema]:
"""Parse schema from dictionary."""
result = {}
for field_name, field_def in schema_dict.items():
if isinstance(field_def, str):
# Simple type definition
result[field_name] = create_field(parse_type(field_def))
elif isinstance(field_def, dict):
# Complex definition
value_type = parse_type(field_def.get("type", "any"))
required = field_def.get("required", False)
min_val = field_def.get("min")
max_val = field_def.get("max")
min_length = field_def.get("minLength")
max_length = field_def.get("maxLength")
pattern = field_def.get("pattern")
enum = field_def.get("enum")
nested = None
if "properties" in field_def:
nested = parse_schema_dict(field_def["properties"])
field_schema = create_field(
value_type,
required,
min_val,
max_val,
min_length,
max_length,
pattern,
enum,
nested,
)
field_schema.name = field_name
result[field_name] = field_schema
return result
def merge_configs(base: dict, override: dict) -> dict:
"""Deep merge two configurations."""
result = dict(base)
for key, value in override.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = merge_configs(result[key], value)
else:
result[key] = value
return result
def flatten_config(config: dict, prefix: str = "") -> dict[str, any]:
"""Flatten nested config to dot notation."""
result = {}
for key, value in config.items():
full_key = f"{prefix}.{key}" if prefix else key
if isinstance(value, dict):
result.update(flatten_config(value, full_key))
else:
result[full_key] = value
return result
def unflatten_config(flat: dict[str, any]) -> dict:
"""Unflatten dot notation to nested dict."""
result = {}
for key, value in flat.items():
parts = key.split(".")
current = result
for part in parts[:-1]:
if part not in current:
current[part] = {}
current = current[part]
current[parts[-1]] = value
return result
def diff_configs(config1: dict, config2: dict) -> dict:
"""Find differences between two configurations."""
flat1 = flatten_config(config1)
flat2 = flatten_config(config2)
all_keys = set(flat1.keys()) | set(flat2.keys())
diff = {"added": {}, "removed": {}, "changed": {}}
for key in all_keys:
if key not in flat1:
diff["added"][key] = flat2[key]
elif key not in flat2:
diff["removed"][key] = flat1[key]
elif flat1[key] != flat2[key]:
diff["changed"][key] = {"from": flat1[key], "to": flat2[key]}
return diff
def main() -> int:
parser = argparse.ArgumentParser(description="Configuration validator")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# validate command
validate_parser = subparsers.add_parser("validate", help="Validate config against schema")
validate_parser.add_argument("config", help="Config file (JSON)")
validate_parser.add_argument("--schema", "-s", required=True, help="Schema file (JSON)")
# merge command
merge_parser = subparsers.add_parser("merge", help="Merge configurations")
merge_parser.add_argument("base", help="Base config file")
merge_parser.add_argument("override", help="Override config file")
# flatten command
flatten_parser = subparsers.add_parser("flatten", help="Flatten config to dot notation")
flatten_parser.add_argument("config", help="Config file")
# unflatten command
unflatten_parser = subparsers.add_parser("unflatten", help="Unflatten dot notation config")
unflatten_parser.add_argument("config", help="Flat config file")
# diff command
diff_parser = subparsers.add_parser("diff", help="Diff two configurations")
diff_parser.add_argument("config1", help="First config file")
diff_parser.add_argument("config2", help="Second config file")
args = parser.parse_args()
if args.command == "validate":
with open(args.config) as f:
config = json.load(f)
with open(args.schema) as f:
schema_dict = json.load(f)
schema = parse_schema_dict(schema_dict)
errors = validate(config, schema)
if errors:
for error in errors:
print(f"Error at '{error.path}': {error.message}", file=sys.stderr)
return 1
print("Configuration is valid")
return 0
if args.command == "merge":
with open(args.base) as f:
base = json.load(f)
with open(args.override) as f:
override = json.load(f)
result = merge_configs(base, override)
print(json.dumps(result, indent=2))
return 0
if args.command == "flatten":
with open(args.config) as f:
config = json.load(f)
flat = flatten_config(config)
print(json.dumps(flat, indent=2))
return 0
if args.command == "unflatten":
with open(args.config) as f:
flat = json.load(f)
config = unflatten_config(flat)
print(json.dumps(config, indent=2))
return 0
if args.command == "diff":
with open(args.config1) as f:
config1 = json.load(f)
with open(args.config2) as f:
config2 = json.load(f)
diff = diff_configs(config1, config2)
print(json.dumps(diff, indent=2))
return 0
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
config_validator
| 444
| 0
|
[
"context_manager",
"class_definition",
"decorator"
] | 0.652
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 946..959, value: Str("FieldSchema"), kind: None })
|
|
example_config_validator
|
test_config_cli.py
|
"""Tests for config_cli.py"""
from config_cli import (
RuleType,
ValueType,
create_field,
diff_configs,
flatten_config,
get_value_type,
merge_configs,
parse_schema_dict,
parse_type,
type_matches,
unflatten_config,
validate,
validate_field,
)
class TestGetValueType:
def test_string(self):
assert get_value_type("hello") == ValueType.STRING
def test_int(self):
assert get_value_type(42) == ValueType.INT
def test_float(self):
assert get_value_type(3.14) == ValueType.FLOAT
def test_bool(self):
assert get_value_type(True) == ValueType.BOOL
assert get_value_type(False) == ValueType.BOOL
def test_list(self):
assert get_value_type([1, 2, 3]) == ValueType.LIST
def test_dict(self):
assert get_value_type({"a": 1}) == ValueType.DICT
class TestTypeMatches:
def test_exact_match(self):
assert type_matches("hello", ValueType.STRING) is True
assert type_matches(42, ValueType.INT) is True
assert type_matches(True, ValueType.BOOL) is True
def test_any_matches_all(self):
assert type_matches("hello", ValueType.ANY) is True
assert type_matches(42, ValueType.ANY) is True
assert type_matches([1, 2], ValueType.ANY) is True
def test_int_matches_float(self):
assert type_matches(42, ValueType.FLOAT) is True
def test_mismatch(self):
assert type_matches("hello", ValueType.INT) is False
assert type_matches(42, ValueType.STRING) is False
class TestValidateField:
def test_required_present(self):
schema = create_field(ValueType.STRING, required=True)
errors = validate_field("value", schema, "field")
assert len(errors) == 0
def test_required_missing(self):
schema = create_field(ValueType.STRING, required=True)
errors = validate_field(None, schema, "field")
assert len(errors) == 1
assert errors[0].rule_type == RuleType.REQUIRED
def test_type_valid(self):
schema = create_field(ValueType.STRING)
errors = validate_field("hello", schema, "field")
type_errors = [e for e in errors if e.rule_type == RuleType.TYPE]
assert len(type_errors) == 0
def test_type_invalid(self):
schema = create_field(ValueType.INT)
errors = validate_field("hello", schema, "field")
type_errors = [e for e in errors if e.rule_type == RuleType.TYPE]
assert len(type_errors) == 1
def test_min_valid(self):
schema = create_field(ValueType.INT, min_val=0)
errors = validate_field(10, schema, "field")
min_errors = [e for e in errors if e.rule_type == RuleType.MIN]
assert len(min_errors) == 0
def test_min_invalid(self):
schema = create_field(ValueType.INT, min_val=0)
errors = validate_field(-5, schema, "field")
min_errors = [e for e in errors if e.rule_type == RuleType.MIN]
assert len(min_errors) == 1
def test_max_valid(self):
schema = create_field(ValueType.INT, max_val=100)
errors = validate_field(50, schema, "field")
max_errors = [e for e in errors if e.rule_type == RuleType.MAX]
assert len(max_errors) == 0
def test_max_invalid(self):
schema = create_field(ValueType.INT, max_val=100)
errors = validate_field(150, schema, "field")
max_errors = [e for e in errors if e.rule_type == RuleType.MAX]
assert len(max_errors) == 1
def test_min_length_valid(self):
schema = create_field(ValueType.STRING, min_length=3)
errors = validate_field("hello", schema, "field")
len_errors = [e for e in errors if e.rule_type == RuleType.MIN_LENGTH]
assert len(len_errors) == 0
def test_min_length_invalid(self):
schema = create_field(ValueType.STRING, min_length=10)
errors = validate_field("hi", schema, "field")
len_errors = [e for e in errors if e.rule_type == RuleType.MIN_LENGTH]
assert len(len_errors) == 1
def test_max_length_valid(self):
schema = create_field(ValueType.STRING, max_length=10)
errors = validate_field("hello", schema, "field")
len_errors = [e for e in errors if e.rule_type == RuleType.MAX_LENGTH]
assert len(len_errors) == 0
def test_max_length_invalid(self):
schema = create_field(ValueType.STRING, max_length=3)
errors = validate_field("hello", schema, "field")
len_errors = [e for e in errors if e.rule_type == RuleType.MAX_LENGTH]
assert len(len_errors) == 1
def test_pattern_valid(self):
schema = create_field(ValueType.STRING, pattern=r"^\d{3}-\d{4}$")
errors = validate_field("123-4567", schema, "field")
pattern_errors = [e for e in errors if e.rule_type == RuleType.PATTERN]
assert len(pattern_errors) == 0
def test_pattern_invalid(self):
schema = create_field(ValueType.STRING, pattern=r"^\d{3}-\d{4}$")
errors = validate_field("invalid", schema, "field")
pattern_errors = [e for e in errors if e.rule_type == RuleType.PATTERN]
assert len(pattern_errors) == 1
def test_enum_valid(self):
schema = create_field(ValueType.STRING, enum=["a", "b", "c"])
errors = validate_field("b", schema, "field")
enum_errors = [e for e in errors if e.rule_type == RuleType.ENUM]
assert len(enum_errors) == 0
def test_enum_invalid(self):
schema = create_field(ValueType.STRING, enum=["a", "b", "c"])
errors = validate_field("d", schema, "field")
enum_errors = [e for e in errors if e.rule_type == RuleType.ENUM]
assert len(enum_errors) == 1
class TestValidate:
def test_simple_config(self):
config = {"name": "test", "port": 8080}
schema = {
"name": create_field(ValueType.STRING, required=True),
"port": create_field(ValueType.INT, required=True),
}
errors = validate(config, schema)
assert len(errors) == 0
def test_missing_required(self):
config = {"name": "test"}
schema = {
"name": create_field(ValueType.STRING, required=True),
"port": create_field(ValueType.INT, required=True),
}
errors = validate(config, schema)
assert len(errors) == 1
assert "port" in errors[0].path
def test_nested_config(self):
config = {"database": {"host": "localhost", "port": 5432}}
nested_schema = {
"host": create_field(ValueType.STRING, required=True),
"port": create_field(ValueType.INT, required=True),
}
schema = {"database": create_field(ValueType.DICT, required=True, nested=nested_schema)}
errors = validate(config, schema)
assert len(errors) == 0
class TestParseType:
def test_string_aliases(self):
assert parse_type("string") == ValueType.STRING
assert parse_type("str") == ValueType.STRING
assert parse_type("STRING") == ValueType.STRING
def test_int_aliases(self):
assert parse_type("int") == ValueType.INT
assert parse_type("integer") == ValueType.INT
def test_float_aliases(self):
assert parse_type("float") == ValueType.FLOAT
assert parse_type("number") == ValueType.FLOAT
def test_bool_aliases(self):
assert parse_type("bool") == ValueType.BOOL
assert parse_type("boolean") == ValueType.BOOL
def test_list_aliases(self):
assert parse_type("list") == ValueType.LIST
assert parse_type("array") == ValueType.LIST
def test_dict_aliases(self):
assert parse_type("dict") == ValueType.DICT
assert parse_type("object") == ValueType.DICT
def test_unknown(self):
assert parse_type("unknown") == ValueType.ANY
class TestParseSchemaDict:
def test_simple_types(self):
schema_dict = {"name": "string", "port": "int"}
schema = parse_schema_dict(schema_dict)
assert "name" in schema
assert "port" in schema
assert schema["name"].value_type == ValueType.STRING
assert schema["port"].value_type == ValueType.INT
def test_complex_definition(self):
schema_dict = {"port": {"type": "int", "required": True, "min": 1, "max": 65535}}
schema = parse_schema_dict(schema_dict)
assert schema["port"].value_type == ValueType.INT
rules = [r.rule_type for r in schema["port"].rules]
assert RuleType.REQUIRED in rules
assert RuleType.MIN in rules
assert RuleType.MAX in rules
def test_nested_properties(self):
schema_dict = {"database": {"type": "object", "properties": {"host": "string", "port": "int"}}}
schema = parse_schema_dict(schema_dict)
assert schema["database"].nested is not None
assert "host" in schema["database"].nested
assert "port" in schema["database"].nested
class TestMergeConfigs:
def test_simple_merge(self):
base = {"a": 1, "b": 2}
override = {"b": 3, "c": 4}
result = merge_configs(base, override)
assert result == {"a": 1, "b": 3, "c": 4}
def test_nested_merge(self):
base = {"db": {"host": "localhost", "port": 5432}}
override = {"db": {"port": 3306}}
result = merge_configs(base, override)
assert result == {"db": {"host": "localhost", "port": 3306}}
def test_override_dict_with_value(self):
base = {"db": {"host": "localhost"}}
override = {"db": "sqlite:///db.sqlite"}
result = merge_configs(base, override)
assert result == {"db": "sqlite:///db.sqlite"}
class TestFlattenConfig:
def test_flat_config(self):
config = {"a": 1, "b": 2}
flat = flatten_config(config)
assert flat == {"a": 1, "b": 2}
def test_nested_config(self):
config = {"db": {"host": "localhost", "port": 5432}}
flat = flatten_config(config)
assert flat == {"db.host": "localhost", "db.port": 5432}
def test_deeply_nested(self):
config = {"a": {"b": {"c": "value"}}}
flat = flatten_config(config)
assert flat == {"a.b.c": "value"}
class TestUnflattenConfig:
def test_simple(self):
flat = {"a": 1, "b": 2}
config = unflatten_config(flat)
assert config == {"a": 1, "b": 2}
def test_nested(self):
flat = {"db.host": "localhost", "db.port": 5432}
config = unflatten_config(flat)
assert config == {"db": {"host": "localhost", "port": 5432}}
def test_deeply_nested(self):
flat = {"a.b.c": "value"}
config = unflatten_config(flat)
assert config == {"a": {"b": {"c": "value"}}}
class TestDiffConfigs:
def test_added(self):
config1 = {"a": 1}
config2 = {"a": 1, "b": 2}
diff = diff_configs(config1, config2)
assert diff["added"] == {"b": 2}
def test_removed(self):
config1 = {"a": 1, "b": 2}
config2 = {"a": 1}
diff = diff_configs(config1, config2)
assert diff["removed"] == {"b": 2}
def test_changed(self):
config1 = {"a": 1}
config2 = {"a": 2}
diff = diff_configs(config1, config2)
assert diff["changed"] == {"a": {"from": 1, "to": 2}}
def test_nested_diff(self):
config1 = {"db": {"port": 5432}}
config2 = {"db": {"port": 3306}}
diff = diff_configs(config1, config2)
assert "db.port" in diff["changed"]
def test_no_changes(self):
config1 = {"a": 1, "b": 2}
config2 = {"a": 1, "b": 2}
diff = diff_configs(config1, config2)
assert diff["added"] == {}
assert diff["removed"] == {}
assert diff["changed"] == {}
class TestRoundTrip:
def test_flatten_unflatten(self):
original = {"a": {"b": {"c": 1}}, "x": {"y": 2}, "z": 3}
flat = flatten_config(original)
restored = unflatten_config(flat)
assert restored == original
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_config_validator/test_config_cli.py (12020 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_config_validator/test_config_cli.rs (31023 bytes)
⏱️ Parse time: 60ms
📊 Throughput: 193.9 KB/s
⏱️ Total time: 60ms
| true
|
config_validator
| 337
| 5
|
[
"class_definition"
] | 0.612
| null |
example_configparser
|
config_tool.py
|
#!/usr/bin/env python3
"""Config Example - Key-value parsing CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Config parsing tool")
subs = parser.add_subparsers(dest="cmd", required=True)
k = subs.add_parser("key")
k.add_argument("pair")
v = subs.add_parser("value")
v.add_argument("pair")
c = subs.add_parser("count")
c.add_argument("data")
args = parser.parse_args()
if args.cmd == "key":
parts = args.pair.split("=")
print(parts[0])
elif args.cmd == "value":
parts = args.pair.split("=")
print(parts[1])
elif args.cmd == "count":
print(len(args.data.split(",")))
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_configparser/config_tool.py (732 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_configparser/config_tool.rs (1844 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_configparser/Cargo.toml (1 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 14.9 KB/s
⏱️ Total time: 48ms
| true
|
configparser
| 30
| 6
|
[] | 0
| null |
example_configparser
|
test_config_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for config CLI."""
import subprocess
SCRIPT = "config_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestConfig:
def test_key(self): r = run(["key", "host=localhost"]); assert "host" in r.stdout
def test_value(self): r = run(["value", "host=localhost"]); assert "localhost" in r.stdout
def test_count(self): r = run(["count", "a,b,c,d"]); assert "4" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_configparser/test_config_tool.py (599 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_configparser/test_config_tool.rs (1861 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 11.8 KB/s
⏱️ Total time: 49ms
| true
|
configparser
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_context_error
|
context_error_cli.py
|
#!/usr/bin/env python3
"""Context Error CLI.
Context managers with error handling patterns.
"""
import argparse
import sys
from contextlib import contextmanager
class Resource:
"""Simulated resource with cleanup."""
def __init__(self, name: str):
self.name = name
self.is_open = False
self.data: list[str] = []
def open(self) -> None:
if self.is_open:
raise RuntimeError(f"Resource {self.name} already open")
self.is_open = True
def close(self) -> None:
self.is_open = False
def write(self, data: str) -> None:
if not self.is_open:
raise RuntimeError(f"Resource {self.name} not open")
self.data.append(data)
def read(self) -> list[str]:
if not self.is_open:
raise RuntimeError(f"Resource {self.name} not open")
return self.data.copy()
class ManagedResource:
"""Resource with context manager protocol."""
def __init__(self, name: str, fail_on_enter: bool = False, fail_on_exit: bool = False):
self.name = name
self.fail_on_enter = fail_on_enter
self.fail_on_exit = fail_on_exit
self.entered = False
self.exited = False
self.data: list[str] = []
def __enter__(self) -> "ManagedResource":
if self.fail_on_enter:
raise RuntimeError(f"Failed to enter {self.name}")
self.entered = True
return self
def __exit__(self, exc_type: type | None, exc_val: Exception | None, exc_tb: object) -> bool:
self.exited = True
if self.fail_on_exit:
raise RuntimeError(f"Failed to exit {self.name}")
# Return False to not suppress exceptions
return False
def write(self, data: str) -> None:
self.data.append(data)
class SuppressingResource:
"""Resource that suppresses specific exceptions."""
def __init__(self, name: str, suppress_types: list[type]):
self.name = name
self.suppress_types = suppress_types
self.suppressed: Exception | None = None
def __enter__(self) -> "SuppressingResource":
return self
def __exit__(self, exc_type: type | None, exc_val: Exception | None, exc_tb: object) -> bool:
if exc_type is not None and exc_type in self.suppress_types:
self.suppressed = exc_val
return True
return False
class TransactionResource:
"""Resource with rollback on error."""
def __init__(self, name: str):
self.name = name
self.operations: list[str] = []
self.committed = False
self.rolled_back = False
def __enter__(self) -> "TransactionResource":
return self
def __exit__(self, exc_type: type | None, exc_val: Exception | None, exc_tb: object) -> bool:
if exc_type is not None:
self.rollback()
else:
self.commit()
return False
def execute(self, op: str) -> None:
self.operations.append(op)
def commit(self) -> None:
self.committed = True
def rollback(self) -> None:
self.rolled_back = True
self.operations.clear()
@contextmanager
def managed_open(name: str, fail: bool = False):
"""Context manager using generator."""
resource = Resource(name)
resource.open()
try:
if fail:
raise RuntimeError("Simulated failure")
yield resource
finally:
resource.close()
@contextmanager
def error_handler(operation: str):
"""Context manager that logs errors."""
errors: list[str] = []
try:
yield errors
except Exception as e:
errors.append(f"{operation}: {type(e).__name__}: {e}")
raise
@contextmanager
def suppress_errors(*exception_types: type):
"""Context manager that suppresses specific errors."""
try:
yield
except exception_types:
pass
@contextmanager
def transaction():
"""Simple transaction context manager."""
ops: list[str] = []
committed = [False]
try:
yield ops
committed[0] = True
except Exception:
ops.clear()
raise
def use_managed_resource(name: str, data: str) -> str:
"""Use managed resource to write data."""
with ManagedResource(name) as res:
res.write(data)
return f"wrote:{data}"
def use_managed_resource_with_error(name: str) -> str:
"""Use managed resource that fails."""
try:
with ManagedResource(name, fail_on_enter=True) as res:
res.write("test")
return "success"
except RuntimeError:
return "failed_enter"
def use_suppressing_resource(name: str, raise_error: bool) -> str:
"""Use resource that suppresses ValueError."""
with SuppressingResource(name, [ValueError]) as res:
if raise_error:
raise ValueError("suppressed error")
return "no_error"
if res.suppressed:
return f"suppressed:{res.suppressed}"
return "completed"
def use_transaction(ops_to_do: list[str], fail_at: int | None) -> tuple[list[str], bool]:
"""Use transaction resource."""
tx = TransactionResource("tx")
try:
with tx:
for i, op in enumerate(ops_to_do):
if fail_at is not None and i == fail_at:
raise RuntimeError("Transaction failed")
tx.execute(op)
except RuntimeError:
pass
return (tx.operations, tx.committed)
def nested_contexts(outer_name: str, inner_name: str) -> str:
"""Nested context managers."""
with ManagedResource(outer_name) as outer:
outer.write("outer_start")
with ManagedResource(inner_name) as inner:
inner.write("inner")
outer.write("outer_end")
return f"outer:{len(outer.data)},inner:{len(inner.data)}"
def multiple_contexts(names: list[str]) -> list[str]:
"""Multiple context managers in one with statement."""
resources = [ManagedResource(n) for n in names]
results: list[str] = []
# Simulate multiple context managers
for res in resources:
res.__enter__()
try:
for res in resources:
res.write("data")
results.append(res.name)
finally:
for res in reversed(resources):
res.__exit__(None, None, None)
return results
def context_with_return(name: str) -> str:
"""Context manager with early return."""
with ManagedResource(name) as res:
res.write("before")
if name == "early":
return "early_return"
res.write("after")
return "normal_return"
def context_cleanup_on_error(name: str, should_fail: bool) -> tuple[bool, bool]:
"""Verify cleanup happens on error."""
res = ManagedResource(name)
try:
with res:
if should_fail:
raise ValueError("test error")
except ValueError:
pass
return (res.entered, res.exited)
def generator_context_test(name: str, fail: bool) -> str:
"""Test generator-based context manager."""
try:
with managed_open(name, fail=fail) as res:
res.write("test")
return f"success:{len(res.data)}"
except RuntimeError:
return "error"
def accumulate_with_transaction(values: list[str]) -> tuple[int, bool]:
"""Accumulate values in transaction."""
total = 0
with transaction() as ops:
for v in values:
num = int(v)
total += num
ops.append(f"add:{num}")
return (total, len(ops) > 0)
def safe_accumulate(values: list[str]) -> tuple[int, list[str]]:
"""Safely accumulate, collecting errors."""
total = 0
errors: list[str] = []
for v in values:
with SuppressingResource("parse", [ValueError]) as res:
total += int(v)
if res.suppressed:
errors.append(f"invalid:{v}")
return (total, errors)
def main() -> int:
parser = argparse.ArgumentParser(description="Context error CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# resource
res_p = subparsers.add_parser("resource", help="Use resource")
res_p.add_argument("name")
res_p.add_argument("data")
# transaction
tx_p = subparsers.add_parser("transaction", help="Run transaction")
tx_p.add_argument("ops", nargs="+")
tx_p.add_argument("--fail-at", type=int)
# nested
nest_p = subparsers.add_parser("nested", help="Nested contexts")
nest_p.add_argument("outer")
nest_p.add_argument("inner")
args = parser.parse_args()
if args.command == "resource":
result = use_managed_resource(args.name, args.data)
print(result)
elif args.command == "transaction":
ops, committed = use_transaction(args.ops, args.fail_at)
print(f"Operations: {ops}")
print(f"Committed: {committed}")
elif args.command == "nested":
result = nested_contexts(args.outer, args.inner)
print(result)
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
context_error
| 326
| 0
|
[
"generator",
"context_manager",
"class_definition",
"exception_handling",
"decorator"
] | 0.927
|
Error: Unsupported type annotation: Constant(ExprConstant { range: 1280..1297, value: Str("ManagedResource"), kind: None })
|
|
example_context_error
|
test_context_error_cli.py
|
"""Tests for context_error_cli.py"""
import pytest
from context_error_cli import (
ManagedResource,
Resource,
SuppressingResource,
TransactionResource,
accumulate_with_transaction,
context_cleanup_on_error,
context_with_return,
generator_context_test,
managed_open,
multiple_contexts,
nested_contexts,
safe_accumulate,
use_managed_resource,
use_managed_resource_with_error,
use_suppressing_resource,
use_transaction,
)
class TestResource:
def test_open_close(self):
r = Resource("test")
assert not r.is_open
r.open()
assert r.is_open
r.close()
assert not r.is_open
def test_double_open(self):
r = Resource("test")
r.open()
with pytest.raises(RuntimeError):
r.open()
def test_write_when_closed(self):
r = Resource("test")
with pytest.raises(RuntimeError):
r.write("data")
def test_write_when_open(self):
r = Resource("test")
r.open()
r.write("data")
assert r.data == ["data"]
class TestManagedResource:
def test_enter_exit(self):
res = ManagedResource("test")
assert not res.entered
with res:
assert res.entered
assert res.exited
def test_fail_on_enter(self):
res = ManagedResource("test", fail_on_enter=True)
with pytest.raises(RuntimeError):
with res:
pass
def test_fail_on_exit(self):
res = ManagedResource("test", fail_on_exit=True)
with pytest.raises(RuntimeError):
with res:
res.write("test")
def test_write_data(self):
with ManagedResource("test") as res:
res.write("data1")
res.write("data2")
assert res.data == ["data1", "data2"]
class TestSuppressingResource:
def test_no_exception(self):
with SuppressingResource("test", [ValueError]) as res:
pass
assert res.suppressed is None
def test_suppress_matching(self):
with SuppressingResource("test", [ValueError]) as res:
raise ValueError("test")
assert res.suppressed is not None
def test_no_suppress_non_matching(self):
with pytest.raises(RuntimeError):
with SuppressingResource("test", [ValueError]):
raise RuntimeError("not suppressed")
class TestTransactionResource:
def test_commit_on_success(self):
with TransactionResource("tx") as tx:
tx.execute("op1")
tx.execute("op2")
assert tx.committed
assert not tx.rolled_back
assert tx.operations == ["op1", "op2"]
def test_rollback_on_error(self):
tx = TransactionResource("tx")
try:
with tx:
tx.execute("op1")
raise ValueError("error")
except ValueError:
pass
assert not tx.committed
assert tx.rolled_back
assert tx.operations == []
class TestManagedOpen:
def test_success(self):
with managed_open("test") as res:
res.write("data")
assert res.is_open
assert not res.is_open
def test_failure(self):
with pytest.raises(RuntimeError):
with managed_open("test", fail=True) as res:
res.write("data")
class TestUseManagedResource:
def test_success(self):
result = use_managed_resource("test", "hello")
assert result == "wrote:hello"
class TestUseManagedResourceWithError:
def test_fail_enter(self):
result = use_managed_resource_with_error("test")
assert result == "failed_enter"
class TestUseSuppressingResource:
def test_no_error(self):
result = use_suppressing_resource("test", False)
assert result == "no_error"
class TestUseTransaction:
def test_success(self):
ops, committed = use_transaction(["op1", "op2"], None)
assert ops == ["op1", "op2"]
assert committed is True
def test_failure(self):
ops, committed = use_transaction(["op1", "op2", "op3"], 1)
assert ops == []
assert committed is False
class TestNestedContexts:
def test_nested(self):
result = nested_contexts("outer", "inner")
assert "outer:2" in result
assert "inner:1" in result
class TestMultipleContexts:
def test_multiple(self):
result = multiple_contexts(["a", "b", "c"])
assert result == ["a", "b", "c"]
class TestContextWithReturn:
def test_early_return(self):
result = context_with_return("early")
assert result == "early_return"
def test_normal_return(self):
result = context_with_return("normal")
assert result == "normal_return"
class TestContextCleanupOnError:
def test_success(self):
entered, exited = context_cleanup_on_error("test", False)
assert entered is True
assert exited is True
def test_error(self):
entered, exited = context_cleanup_on_error("test", True)
assert entered is True
assert exited is True
class TestGeneratorContextTest:
def test_success(self):
result = generator_context_test("test", False)
assert "success" in result
def test_failure(self):
result = generator_context_test("test", True)
assert result == "error"
class TestAccumulateWithTransaction:
def test_success(self):
total, has_ops = accumulate_with_transaction(["1", "2", "3"])
assert total == 6
assert has_ops is True
def test_failure(self):
with pytest.raises(ValueError):
accumulate_with_transaction(["1", "abc", "3"])
class TestSafeAccumulate:
def test_all_valid(self):
total, errors = safe_accumulate(["1", "2", "3"])
assert total == 6
assert errors == []
def test_some_invalid(self):
total, errors = safe_accumulate(["1", "abc", "3"])
assert total == 4
assert len(errors) == 1
class TestEdgeCases:
def test_empty_resource_name(self):
res = ManagedResource("")
with res:
res.write("data")
assert res.data == ["data"]
def test_empty_transaction(self):
with TransactionResource("tx") as tx:
pass
assert tx.committed is True
assert tx.operations == []
def test_exception_in_finally(self):
res = ManagedResource("test", fail_on_exit=True)
with pytest.raises(RuntimeError):
with res:
raise ValueError("inner")
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_context_error/test_context_error_cli.py (6629 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_context_error/test_context_error_cli.rs (16380 bytes)
⏱️ Parse time: 52ms
📊 Throughput: 124.1 KB/s
⏱️ Total time: 52ms
| true
|
context_error
| 245
| 5
|
[
"context_manager",
"class_definition",
"exception_handling"
] | 0.652
| null |
example_contextlib
|
resource_tool.py
|
#!/usr/bin/env python3
"""
Contextlib Example - Resource management
Demonstrates contextlib patterns for resource handling.
"""
import argparse
import tempfile
from contextlib import redirect_stdout
def cmd_tempfile(args):
"""Create temp file. Depyler: proven to terminate"""
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as f:
f.write(args.content)
print(f"Created: {f.name}")
def cmd_redirect(args):
"""Redirect stdout to file. Depyler: proven to terminate"""
with open(args.output, "w") as f:
with redirect_stdout(f):
print(args.message)
print(f"Written to: {args.output}")
def main():
parser = argparse.ArgumentParser(description="Resource management tool")
subparsers = parser.add_subparsers(dest="command", required=True)
tmp = subparsers.add_parser("tempfile")
tmp.add_argument("--content", required=True)
redir = subparsers.add_parser("redirect")
redir.add_argument("output")
redir.add_argument("--message", required=True)
args = parser.parse_args()
if args.command == "tempfile":
cmd_tempfile(args)
elif args.command == "redirect":
cmd_redirect(args)
if __name__ == "__main__":
main()
| false
|
contextlib
| 47
| 0
|
[
"context_manager"
] | 0.652
|
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions: 48
Total estimated allocations: 0
Functions analyzed: 3
Hot Paths
[1] cmd_redirect (25.0% of execution time)
[2] main (72.9% of execution time)
Function Metrics
🔥 main 72.9% time | 35 inst | 0 alloc
🔥 cmd_redirect 25.0% time | 12 inst | 0 alloc
cmd_tempfile 2.1% time | 1 inst | 0 alloc
|
|
example_contextlib
|
test_resource_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for contextlib CLI."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "resource_tool.py"
import os
import tempfile
SCRIPT = "resource_tool.py"
def run(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True,
cwd=__file__.rsplit("/", 1)[0])
class TestTempFile:
def test_tempfile_create(self):
result = run(["tempfile", "--content", "hello"])
assert result.returncode == 0
assert "Created" in result.stdout
class TestRedirect:
def test_redirect_stdout(self):
with tempfile.NamedTemporaryFile(delete=False, suffix=".txt") as f:
fname = f.name
try:
result = run(["redirect", fname, "--message", "test"])
assert result.returncode == 0
with open(fname) as f:
assert "test" in f.read()
finally:
os.unlink(fname)
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_contextlib/test_resource_tool.py (1138 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_contextlib/test_resource_tool.rs (2800 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_contextlib/Cargo.toml (3 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 22.5 KB/s
⏱️ Total time: 49ms
| true
|
contextlib
| 42
| 6
|
[
"context_manager",
"class_definition",
"exception_handling",
"multiprocessing"
] | 0.652
| null |
example_copy
|
copy_tool.py
|
#!/usr/bin/env python3
"""Copy Example - Copy operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Copy operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
s = subs.add_parser("shallow")
s.add_argument("value")
d = subs.add_parser("deep")
d.add_argument("value")
du = subs.add_parser("dup")
du.add_argument("value")
du.add_argument("times", type=int)
args = parser.parse_args()
if args.cmd == "shallow":
print(args.value)
elif args.cmd == "deep":
print(args.value)
elif args.cmd == "dup":
i = 0
while i < args.times:
print(args.value)
i = i + 1
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_copy/copy_tool.py (760 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_copy/copy_tool.rs (1064 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_copy/Cargo.toml (1 dependencies)
⏱️ Parse time: 47ms
📊 Throughput: 15.7 KB/s
⏱️ Total time: 47ms
| true
|
copy
| 32
| 6
|
[] | 0
| null |
example_copy
|
test_copy_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for copy CLI."""
import subprocess
SCRIPT = "copy_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestCopy:
def test_shallow(self): r = run(["shallow", "hello"]); assert r.returncode == 0 and "hello" in r.stdout
def test_deep(self): r = run(["deep", "world"]); assert r.returncode == 0 and "world" in r.stdout
def test_dup(self): r = run(["dup", "test", "3"]); assert r.returncode == 0 and r.stdout.count("test") == 3
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_copy/test_copy_tool.py (654 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_copy/test_copy_tool.rs (1913 bytes)
⏱️ Parse time: 48ms
📊 Throughput: 13.2 KB/s
⏱️ Total time: 48ms
| true
|
copy
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_count
|
count_tool.py
|
#!/usr/bin/env python3
"""Count Example - String count operations CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="String count tool")
subs = parser.add_subparsers(dest="cmd", required=True)
ch = subs.add_parser("char")
ch.add_argument("text")
ch.add_argument("target")
v = subs.add_parser("vowels")
v.add_argument("text")
co = subs.add_parser("consonants")
co.add_argument("text")
args = parser.parse_args()
if args.cmd == "char":
count = 0
i = 0
while i < len(args.text):
if args.text[i] == args.target:
count = count + 1
i = i + 1
print(count)
elif args.cmd == "vowels":
count = 0
i = 0
while i < len(args.text):
c = args.text[i]
if c == "a" or c == "e" or c == "i" or c == "o" or c == "u":
count = count + 1
i = i + 1
print(count)
elif args.cmd == "consonants":
count = 0
i = 0
while i < len(args.text):
c = args.text[i]
is_vowel = c == "a" or c == "e" or c == "i" or c == "o" or c == "u"
is_alpha = c >= "a" and c <= "z"
if is_alpha and not is_vowel:
count = count + 1
i = i + 1
print(count)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_count/count_tool.py (1391 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_count/count_tool.rs (3847 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_count/Cargo.toml (1 dependencies)
⏱️ Parse time: 49ms
📊 Throughput: 27.5 KB/s
⏱️ Total time: 49ms
| true
|
count
| 51
| 6
|
[] | 0
| null |
example_count
|
test_count_tool.py
|
"""Tests for count_tool - EXTREME TDD."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "count_tool.py"
def run(cmd):
return subprocess.run(
["python3", str(SCRIPT)] + cmd.split(),
capture_output=True,
text=True,
)
def test_char():
r = run("char mississippi s")
assert r.returncode == 0
assert r.stdout.strip() == "4"
def test_vowels():
r = run("vowels hello")
assert r.returncode == 0
assert r.stdout.strip() == "2"
def test_consonants():
r = run("consonants hello")
assert r.returncode == 0
assert r.stdout.strip() == "3"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_count/test_count_tool.py (632 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_count/test_count_tool.rs (1840 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_count/Cargo.toml (2 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 12.8 KB/s
⏱️ Total time: 48ms
| true
|
count
| 32
| 6
|
[] | 0
| null |
example_counter
|
test_word_counter.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for collections.Counter CLI."""
import subprocess
SCRIPT = "word_counter.py"
def run(args: list[str], input_text: str = None) -> subprocess.CompletedProcess:
return subprocess.run(
["python3", SCRIPT] + args,
capture_output=True,
text=True,
input=input_text,
cwd=__file__.rsplit("/", 1)[0],
)
class TestWordCount:
"""Test word frequency counting."""
def test_count_words(self):
result = run(["count"], "hello world hello")
assert result.returncode == 0
assert "hello" in result.stdout
assert "2" in result.stdout
def test_count_empty(self):
result = run(["count"], "")
assert result.returncode == 0
def test_count_single(self):
result = run(["count"], "word")
assert result.returncode == 0
assert "word" in result.stdout
class TestTopN:
"""Test top N most common."""
def test_top_3(self):
result = run(["top", "3"], "a a a b b c")
assert result.returncode == 0
assert "a" in result.stdout
def test_top_1(self):
result = run(["top", "1"], "x y y z z z")
assert result.returncode == 0
assert "z" in result.stdout
class TestCharCount:
"""Test character counting."""
def test_char_count(self):
result = run(["chars"], "aab")
assert result.returncode == 0
assert "a" in result.stdout
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
assert "count" in result.stdout
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_counter/test_word_counter.py (1622 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_counter/test_word_counter.rs (3178 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_counter/Cargo.toml (2 dependencies)
⏱️ Parse time: 96ms
📊 Throughput: 16.4 KB/s
⏱️ Total time: 99ms
| true
|
counter
| 65
| 6
|
[
"class_definition",
"multiprocessing"
] | 0.612
| null |
example_counter
|
word_counter.py
|
#!/usr/bin/env python3
"""
Counter Example - Word/character frequency CLI
Demonstrates:
- collections.Counter
- most_common()
- Counter arithmetic
- stdin processing
This validates depyler's ability to transpile Counter
to Rust (HashMap with frequency counting).
"""
import argparse
import sys
from collections import Counter
def cmd_count(args):
"""Count word frequencies. Depyler: proven to terminate"""
text = sys.stdin.read()
words = text.split()
counter = Counter(words)
for word, count in counter.items():
print(f"{word}: {count}")
def cmd_top(args):
"""Show top N words. Depyler: proven to terminate"""
text = sys.stdin.read()
words = text.split()
counter = Counter(words)
for word, count in counter.most_common(args.n):
print(f"{word}: {count}")
def cmd_chars(args):
"""Count character frequencies. Depyler: proven to terminate"""
text = sys.stdin.read().strip()
counter = Counter(text)
for char, count in counter.most_common():
if char.strip():
print(f"'{char}': {count}")
def main():
"""Main entry point. Depyler: proven to terminate"""
parser = argparse.ArgumentParser(description="Word/character frequency counter")
subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("count", help="Count word frequencies")
top_parser = subparsers.add_parser("top", help="Show top N words")
top_parser.add_argument("n", type=int, help="Number of top words")
subparsers.add_parser("chars", help="Count character frequencies")
args = parser.parse_args()
if args.command == "count":
cmd_count(args)
elif args.command == "top":
cmd_top(args)
elif args.command == "chars":
cmd_chars(args)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_counter/word_counter.py (1832 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_counter/word_counter.rs (3156 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_counter/Cargo.toml (1 dependencies)
⏱️ Parse time: 51ms
📊 Throughput: 34.5 KB/s
⏱️ Total time: 52ms
| true
|
counter
| 70
| 6
|
[
"context_manager",
"stdin_usage"
] | 0.652
| null |
example_crc32_tool
|
crc32_cli.py
|
#!/usr/bin/env python3
"""CRC32 checksum calculator CLI.
Calculate and verify CRC32 checksums.
"""
import argparse
import os
import sys
# CRC32 polynomial (IEEE 802.3)
CRC32_POLY = 0xEDB88320
# Pre-computed CRC32 table
CRC32_TABLE: list[int] = []
def init_crc32_table() -> None:
"""Initialize CRC32 lookup table."""
global CRC32_TABLE
if CRC32_TABLE:
return
for i in range(256):
crc = i
for _ in range(8):
if crc & 1:
crc = (crc >> 1) ^ CRC32_POLY
else:
crc >>= 1
CRC32_TABLE.append(crc)
def crc32_update(crc: int, data: bytes) -> int:
"""Update CRC32 with data."""
init_crc32_table()
for byte in data:
crc = CRC32_TABLE[(crc ^ byte) & 0xFF] ^ (crc >> 8)
return crc
def crc32(data: bytes) -> int:
"""Calculate CRC32 of data."""
return crc32_update(0xFFFFFFFF, data) ^ 0xFFFFFFFF
def crc32_file(path: str, chunk_size: int = 65536) -> int:
"""Calculate CRC32 of file."""
crc = 0xFFFFFFFF
init_crc32_table()
with open(path, "rb") as f:
while chunk := f.read(chunk_size):
crc = crc32_update(crc, chunk)
return crc ^ 0xFFFFFFFF
def format_crc32(value: int) -> str:
"""Format CRC32 value as hex string."""
return f"{value:08x}"
def parse_crc32(hex_str: str) -> int | None:
"""Parse CRC32 from hex string."""
try:
return int(hex_str, 16)
except ValueError:
return None
def verify_checksum(path: str, expected: int) -> bool:
"""Verify file checksum matches expected."""
actual = crc32_file(path)
return actual == expected
def generate_checksum_file(paths: list[str]) -> list[str]:
"""Generate checksum file content."""
lines = []
for path in paths:
if not os.path.isfile(path):
continue
checksum = crc32_file(path)
lines.append(f"{format_crc32(checksum)} {path}")
return lines
def parse_checksum_file(content: str) -> list[tuple[int, str]]:
"""Parse checksum file content.
Returns list of (checksum, path) tuples.
"""
result = []
for line in content.strip().split("\n"):
line = line.strip()
if not line or line.startswith("#"):
continue
# Format: CHECKSUM FILENAME
parts = line.split(None, 1)
if len(parts) != 2:
continue
checksum = parse_crc32(parts[0])
if checksum is None:
continue
result.append((checksum, parts[1]))
return result
def verify_checksum_file(content: str) -> list[tuple[str, bool, str]]:
"""Verify checksums from checksum file.
Returns list of (path, passed, message) tuples.
"""
results = []
entries = parse_checksum_file(content)
for expected, path in entries:
if not os.path.exists(path):
results.append((path, False, "NOT FOUND"))
continue
try:
actual = crc32_file(path)
if actual == expected:
results.append((path, True, "OK"))
else:
results.append((path, False, f"FAILED (got {format_crc32(actual)})"))
except OSError as e:
results.append((path, False, f"ERROR: {e}"))
return results
def main() -> int:
parser = argparse.ArgumentParser(description="Calculate and verify CRC32 checksums")
parser.add_argument("files", nargs="*", help="Files to checksum")
parser.add_argument("-c", "--check", metavar="FILE", help="Verify checksums from file")
parser.add_argument("-s", "--string", metavar="TEXT", help="Calculate checksum of string")
parser.add_argument("--verify", metavar="CHECKSUM", help="Verify file against checksum")
parser.add_argument("--binary", action="store_true", help="Output raw binary checksum")
parser.add_argument("-q", "--quiet", action="store_true", help="Quiet mode (exit code only)")
args = parser.parse_args()
# Verify checksums from file
if args.check:
try:
with open(args.check) as f:
content = f.read()
except OSError as e:
print(f"Error reading {args.check}: {e}", file=sys.stderr)
return 1
results = verify_checksum_file(content)
failed = 0
for path, passed, message in results:
if not args.quiet:
print(f"{path}: {message}")
if not passed:
failed += 1
if failed > 0:
if not args.quiet:
print(f"\n{failed} failed")
return 1
return 0
# Calculate checksum of string
if args.string:
checksum = crc32(args.string.encode("utf-8"))
if args.binary:
sys.stdout.buffer.write(checksum.to_bytes(4, "little"))
else:
print(format_crc32(checksum))
return 0
# Verify specific checksum
if args.verify:
if not args.files:
print("No files specified", file=sys.stderr)
return 1
expected = parse_crc32(args.verify)
if expected is None:
print(f"Invalid checksum: {args.verify}", file=sys.stderr)
return 1
all_passed = True
for path in args.files:
if not os.path.isfile(path):
if not args.quiet:
print(f"{path}: NOT FOUND")
all_passed = False
continue
passed = verify_checksum(path, expected)
if not args.quiet:
status = "OK" if passed else "FAILED"
print(f"{path}: {status}")
if not passed:
all_passed = False
return 0 if all_passed else 1
# Calculate checksums for files
if not args.files:
# Read from stdin
data = sys.stdin.buffer.read()
checksum = crc32(data)
if args.binary:
sys.stdout.buffer.write(checksum.to_bytes(4, "little"))
else:
print(format_crc32(checksum))
return 0
for path in args.files:
if not os.path.isfile(path):
print(f"{path}: NOT FOUND", file=sys.stderr)
continue
try:
checksum = crc32_file(path)
if args.binary:
sys.stdout.buffer.write(checksum.to_bytes(4, "little"))
else:
print(f"{format_crc32(checksum)} {path}")
except OSError as e:
print(f"{path}: {e}", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
crc32_tool
| 240
| 0
|
[
"context_manager",
"exception_handling",
"stdin_usage",
"walrus_operator"
] | 0.85
|
Error: Statement type not yet supported: Global
|
|
example_crc32_tool
|
test_crc32_cli.py
|
"""Tests for crc32_cli.py"""
import os
import tempfile
from crc32_cli import (
crc32,
crc32_file,
crc32_update,
format_crc32,
generate_checksum_file,
init_crc32_table,
parse_checksum_file,
parse_crc32,
verify_checksum,
verify_checksum_file,
)
class TestCrc32:
def test_empty(self):
# CRC32 of empty string is 0
assert crc32(b"") == 0
def test_simple(self):
# Known CRC32 values
assert crc32(b"hello") == 0x3610A686
def test_abc(self):
assert crc32(b"abc") == 0x352441C2
def test_incremental(self):
# CRC32 should be same whether computed incrementally or at once
data = b"hello world"
direct = crc32(data)
init_crc32_table()
crc = 0xFFFFFFFF
crc = crc32_update(crc, b"hello ")
crc = crc32_update(crc, b"world")
incremental = crc ^ 0xFFFFFFFF
assert direct == incremental
class TestCrc32File:
def test_file(self):
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(b"hello")
path = f.name
try:
result = crc32_file(path)
assert result == crc32(b"hello")
finally:
os.unlink(path)
def test_large_file(self):
# Test chunked reading
data = b"x" * 100000
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(data)
path = f.name
try:
result = crc32_file(path)
assert result == crc32(data)
finally:
os.unlink(path)
class TestFormatCrc32:
def test_format(self):
assert format_crc32(0) == "00000000"
assert format_crc32(255) == "000000ff"
assert format_crc32(0xDEADBEEF) == "deadbeef"
class TestParseCrc32:
def test_valid(self):
assert parse_crc32("00000000") == 0
assert parse_crc32("deadbeef") == 0xDEADBEEF
assert parse_crc32("DEADBEEF") == 0xDEADBEEF
def test_invalid(self):
assert parse_crc32("invalid") is None
assert parse_crc32("") is None
class TestVerifyChecksum:
def test_match(self):
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(b"hello")
path = f.name
try:
expected = crc32(b"hello")
assert verify_checksum(path, expected) is True
finally:
os.unlink(path)
def test_mismatch(self):
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(b"hello")
path = f.name
try:
assert verify_checksum(path, 0x12345678) is False
finally:
os.unlink(path)
class TestGenerateChecksumFile:
def test_generate(self):
with tempfile.TemporaryDirectory() as tmpdir:
path1 = os.path.join(tmpdir, "file1.txt")
path2 = os.path.join(tmpdir, "file2.txt")
with open(path1, "wb") as f:
f.write(b"hello")
with open(path2, "wb") as f:
f.write(b"world")
lines = generate_checksum_file([path1, path2])
assert len(lines) == 2
assert "3610a686" in lines[0]
assert path1 in lines[0]
class TestParseChecksumFile:
def test_parse(self):
content = """
3610a686 file1.txt
74ab2534 file2.txt
"""
result = parse_checksum_file(content)
assert len(result) == 2
assert result[0] == (0x3610A686, "file1.txt")
assert result[1] == (0x74AB2534, "file2.txt")
def test_skip_comments(self):
content = """
# Comment
3610a686 file1.txt
"""
result = parse_checksum_file(content)
assert len(result) == 1
def test_skip_invalid(self):
content = """
invalid line
3610a686 file1.txt
"""
result = parse_checksum_file(content)
assert len(result) == 1
class TestVerifyChecksumFile:
def test_verify_pass(self):
with tempfile.TemporaryDirectory() as tmpdir:
path = os.path.join(tmpdir, "file.txt")
with open(path, "wb") as f:
f.write(b"hello")
checksum = format_crc32(crc32(b"hello"))
content = f"{checksum} {path}"
results = verify_checksum_file(content)
assert len(results) == 1
assert results[0][1] is True
def test_verify_fail(self):
with tempfile.TemporaryDirectory() as tmpdir:
path = os.path.join(tmpdir, "file.txt")
with open(path, "wb") as f:
f.write(b"hello")
content = f"00000000 {path}"
results = verify_checksum_file(content)
assert len(results) == 1
assert results[0][1] is False
def test_missing_file(self):
content = "3610a686 /nonexistent/file.txt"
results = verify_checksum_file(content)
assert len(results) == 1
assert results[0][1] is False
assert "NOT FOUND" in results[0][2]
| false
|
crc32_tool
| 190
| 0
|
[
"context_manager",
"class_definition",
"exception_handling"
] | 0.652
|
Error: join() requires exactly one argument
|
|
example_cron_validator
|
cron_cli.py
|
#!/usr/bin/env python3
"""Cron expression validator CLI.
Validate and explain cron expressions.
"""
import argparse
import re
import sys
from datetime import datetime, timedelta
FIELD_NAMES = ["minute", "hour", "day_of_month", "month", "day_of_week"]
FIELD_RANGES = {
"minute": (0, 59),
"hour": (0, 23),
"day_of_month": (1, 31),
"month": (1, 12),
"day_of_week": (0, 6),
}
MONTH_NAMES = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
DAY_NAMES = {
"sun": 0,
"mon": 1,
"tue": 2,
"wed": 3,
"thu": 4,
"fri": 5,
"sat": 6,
}
def parse_field(field: str, field_name: str) -> list[int] | None:
"""Parse a single cron field.
Returns list of values or None if invalid.
"""
min_val, max_val = FIELD_RANGES[field_name]
field = field.lower()
# Replace month/day names
if field_name == "month":
for name, num in MONTH_NAMES.items():
field = field.replace(name, str(num))
elif field_name == "day_of_week":
for name, num in DAY_NAMES.items():
field = field.replace(name, str(num))
values = set()
# Handle wildcards
if field == "*":
return list(range(min_val, max_val + 1))
# Handle comma-separated parts
for part in field.split(","):
part = part.strip()
# Handle step values */n or range/n
step = 1
if "/" in part:
part, step_str = part.split("/", 1)
try:
step = int(step_str)
except ValueError:
return None
# Handle ranges
if "-" in part and part != "*":
range_match = re.match(r"(\d+)-(\d+)", part)
if range_match:
start = int(range_match.group(1))
end = int(range_match.group(2))
if start > end or start < min_val or end > max_val:
return None
values.update(range(start, end + 1, step))
else:
return None
elif part == "*":
values.update(range(min_val, max_val + 1, step))
else:
try:
val = int(part)
if val < min_val or val > max_val:
return None
values.add(val)
except ValueError:
return None
return sorted(values)
def parse_cron(expression: str) -> dict | None:
"""Parse cron expression into field values.
Returns dict with parsed values or None if invalid.
"""
parts = expression.strip().split()
if len(parts) != 5:
return None
result = {}
for i, field_name in enumerate(FIELD_NAMES):
values = parse_field(parts[i], field_name)
if values is None:
return None
result[field_name] = values
return result
def validate_cron(expression: str) -> tuple[bool, str]:
"""Validate cron expression.
Returns (is_valid, error_message).
"""
parsed = parse_cron(expression)
if parsed is None:
return False, "Invalid cron expression format"
return True, ""
def explain_field(values: list[int], field_name: str) -> str:
"""Generate human-readable explanation of field values."""
min_val, max_val = FIELD_RANGES[field_name]
if values == list(range(min_val, max_val + 1)):
return "every " + field_name.replace("_", " ")
if len(values) == 1:
if field_name == "day_of_week":
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
return f"on {days[values[0]]}"
if field_name == "month":
months = [
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
return f"in {months[values[0]]}"
return f"at {field_name.replace('_', ' ')} {values[0]}"
# Check for step pattern
if len(values) > 2:
diffs = [values[i + 1] - values[i] for i in range(len(values) - 1)]
if len(set(diffs)) == 1:
step = diffs[0]
return f"every {step} {field_name.replace('_', ' ')}s"
return f"{field_name.replace('_', ' ')}s {', '.join(map(str, values))}"
def explain_cron(expression: str) -> str:
"""Generate human-readable explanation of cron expression."""
parsed = parse_cron(expression)
if not parsed:
return "Invalid expression"
parts = []
# Minute
if parsed["minute"] != list(range(0, 60)):
parts.append(f"at minute {', '.join(map(str, parsed['minute']))}")
# Hour
if parsed["hour"] != list(range(0, 24)):
parts.append(f"at hour {', '.join(map(str, parsed['hour']))}")
# Day of month
if parsed["day_of_month"] != list(range(1, 32)):
parts.append(f"on day {', '.join(map(str, parsed['day_of_month']))}")
# Month
if parsed["month"] != list(range(1, 13)):
months = [
"",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
month_names = [months[m] for m in parsed["month"]]
parts.append(f"in {', '.join(month_names)}")
# Day of week
if parsed["day_of_week"] != list(range(0, 7)):
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
day_names = [days[d] for d in parsed["day_of_week"]]
parts.append(f"on {', '.join(day_names)}")
if not parts:
return "Every minute"
return ", ".join(parts)
def matches_cron(parsed: dict, dt: datetime) -> bool:
"""Check if datetime matches parsed cron expression."""
if dt.minute not in parsed["minute"]:
return False
if dt.hour not in parsed["hour"]:
return False
if dt.day not in parsed["day_of_month"]:
return False
if dt.month not in parsed["month"]:
return False
if dt.weekday() not in [(d - 1) % 7 for d in parsed["day_of_week"]]:
# Cron: 0=Sunday, Python: 0=Monday
dow = (dt.weekday() + 1) % 7
if dow not in parsed["day_of_week"]:
return False
return True
def next_run(expression: str, after: datetime | None = None) -> datetime | None:
"""Calculate next run time for cron expression."""
parsed = parse_cron(expression)
if not parsed:
return None
if after is None:
after = datetime.now()
current = after.replace(second=0, microsecond=0) + timedelta(minutes=1)
# Check up to 1 year ahead
for _ in range(365 * 24 * 60):
if matches_cron(parsed, current):
return current
current += timedelta(minutes=1)
return None
def main() -> int:
parser = argparse.ArgumentParser(description="Validate and explain cron expressions")
parser.add_argument("expression", nargs="?", help="Cron expression (5 fields)")
parser.add_argument("--validate", action="store_true", help="Only validate, don't explain")
parser.add_argument("--next", action="store_true", help="Show next run time")
parser.add_argument("--next-n", type=int, metavar="N", help="Show next N run times")
args = parser.parse_args()
if not args.expression:
print("Usage: cron_cli.py '* * * * *'")
print("\nCommon examples:")
print(" '0 * * * *' - Every hour")
print(" '0 0 * * *' - Every day at midnight")
print(" '0 0 * * 0' - Every Sunday at midnight")
print(" '*/15 * * * *' - Every 15 minutes")
return 0
valid, error = validate_cron(args.expression)
if not valid:
print(f"Invalid: {error}", file=sys.stderr)
return 1
if args.validate:
print("Valid")
return 0
if args.next:
next_time = next_run(args.expression)
if next_time:
print(f"Next run: {next_time.strftime('%Y-%m-%d %H:%M')}")
else:
print("No upcoming run found")
return 0
if args.next_n:
current = datetime.now()
print(f"Next {args.next_n} runs:")
for _ in range(args.next_n):
next_time = next_run(args.expression, current)
if next_time:
print(f" {next_time.strftime('%Y-%m-%d %H:%M')}")
current = next_time
else:
break
return 0
# Default: explain
print(f"Expression: {args.expression}")
print(f"Explanation: {explain_cron(args.expression)}")
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_cron_validator/cron_cli.py (8959 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_cron_validator/cron_cli.rs (16703 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_cron_validator/Cargo.toml (6 dependencies)
⏱️ Parse time: 55ms
📊 Throughput: 157.4 KB/s
⏱️ Total time: 55ms
| true
|
cron_validator
| 324
| 6
|
[
"context_manager",
"exception_handling"
] | 0.652
| null |
example_cron_validator
|
test_cron_cli.py
|
"""Tests for cron_cli.py"""
from datetime import datetime
from cron_cli import (
explain_cron,
matches_cron,
next_run,
parse_cron,
parse_field,
validate_cron,
)
class TestParseField:
def test_wildcard(self):
result = parse_field("*", "minute")
assert result == list(range(0, 60))
def test_single_value(self):
result = parse_field("30", "minute")
assert result == [30]
def test_range(self):
result = parse_field("1-5", "day_of_week")
assert result == [1, 2, 3, 4, 5]
def test_step(self):
result = parse_field("*/15", "minute")
assert result == [0, 15, 30, 45]
def test_range_step(self):
result = parse_field("0-30/10", "minute")
assert result == [0, 10, 20, 30]
def test_list(self):
result = parse_field("1,3,5", "day_of_week")
assert result == [1, 3, 5]
def test_month_name(self):
result = parse_field("jan", "month")
assert result == [1]
def test_day_name(self):
result = parse_field("mon", "day_of_week")
assert result == [1]
def test_invalid_range(self):
result = parse_field("50-70", "minute")
assert result is None
def test_invalid_value(self):
result = parse_field("abc", "minute")
assert result is None
class TestParseCron:
def test_all_wildcards(self):
result = parse_cron("* * * * *")
assert result is not None
assert result["minute"] == list(range(0, 60))
def test_specific_time(self):
result = parse_cron("30 14 * * *")
assert result is not None
assert result["minute"] == [30]
assert result["hour"] == [14]
def test_invalid_format(self):
result = parse_cron("* * *") # Too few fields
assert result is None
def test_invalid_values(self):
result = parse_cron("60 * * * *") # Invalid minute
assert result is None
class TestValidateCron:
def test_valid(self):
valid, error = validate_cron("0 0 * * *")
assert valid is True
assert error == ""
def test_invalid(self):
valid, error = validate_cron("invalid")
assert valid is False
assert error != ""
class TestExplainCron:
def test_every_minute(self):
result = explain_cron("* * * * *")
assert "minute" in result.lower()
def test_hourly(self):
result = explain_cron("0 * * * *")
assert "0" in result
def test_daily(self):
result = explain_cron("0 0 * * *")
assert "0" in result
def test_weekly(self):
result = explain_cron("0 0 * * 0")
assert "Sun" in result
def test_monthly(self):
result = explain_cron("0 0 1 * *")
assert "1" in result
class TestMatchesCron:
def test_matches_every_minute(self):
parsed = parse_cron("* * * * *")
dt = datetime(2023, 12, 25, 14, 30)
assert matches_cron(parsed, dt) is True
def test_matches_specific_time(self):
parsed = parse_cron("30 14 * * *")
dt = datetime(2023, 12, 25, 14, 30)
assert matches_cron(parsed, dt) is True
def test_no_match_minute(self):
parsed = parse_cron("0 * * * *")
dt = datetime(2023, 12, 25, 14, 30)
assert matches_cron(parsed, dt) is False
def test_no_match_hour(self):
parsed = parse_cron("30 12 * * *")
dt = datetime(2023, 12, 25, 14, 30)
assert matches_cron(parsed, dt) is False
class TestNextRun:
def test_next_hour(self):
after = datetime(2023, 12, 25, 14, 30)
result = next_run("0 * * * *", after)
assert result is not None
assert result.minute == 0
assert result.hour == 15
def test_next_day(self):
after = datetime(2023, 12, 25, 23, 30)
result = next_run("0 0 * * *", after)
assert result is not None
assert result.day == 26
assert result.hour == 0
def test_invalid_expression(self):
result = next_run("invalid")
assert result is None
def test_every_15_minutes(self):
after = datetime(2023, 12, 25, 14, 10)
result = next_run("*/15 * * * *", after)
assert result is not None
assert result.minute == 15
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_cron_validator/test_cron_cli.py (4302 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_cron_validator/test_cron_cli.rs (7732 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_cron_validator/Cargo.toml (1 dependencies)
⏱️ Parse time: 50ms
📊 Throughput: 83.3 KB/s
⏱️ Total time: 50ms
| true
|
cron_validator
| 157
| 6
|
[
"class_definition"
] | 0.612
| null |
example_csv
|
csv_tool.py
|
#!/usr/bin/env python3
"""CSV Example - CSV-like parsing CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="CSV operations tool")
subs = parser.add_subparsers(dest="cmd", required=True)
c = subs.add_parser("count")
c.add_argument("row")
f = subs.add_parser("field")
f.add_argument("row")
f.add_argument("index", type=int)
args = parser.parse_args()
if args.cmd == "count":
fields = args.row.split(",")
print(len(fields))
elif args.cmd == "field":
fields = args.row.split(",")
print(fields[args.index])
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_csv/csv_tool.py (650 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_csv/csv_tool.rs (1893 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_csv/Cargo.toml (1 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 13.2 KB/s
⏱️ Total time: 48ms
| true
|
csv
| 27
| 6
|
[] | 0
| null |
example_csv
|
test_csv_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for csv CLI."""
import subprocess
SCRIPT = "csv_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestCsv:
def test_count(self): r = run(["count", "a,b,c"]); assert "3" in r.stdout
def test_field(self): r = run(["field", "a,b,c", "1"]); assert "b" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_csv/test_csv_tool.py (490 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_csv/test_csv_tool.rs (1678 bytes)
⏱️ Parse time: 48ms
📊 Throughput: 9.8 KB/s
⏱️ Total time: 48ms
| true
|
csv
| 13
| 5
|
[
"class_definition"
] | 0.612
| null |
example_csv_basic
|
csv_basic_cli.py
|
#!/usr/bin/env python3
"""CSV Basic CLI.
CSV reading and writing operations.
"""
import argparse
import csv
import io
import sys
def parse_csv(content: str, delimiter: str = ",") -> list[list[str]]:
"""Parse CSV string to list of rows."""
reader = csv.reader(io.StringIO(content), delimiter=delimiter)
return list(reader)
def parse_csv_dict(content: str, delimiter: str = ",") -> list[dict[str, str]]:
"""Parse CSV to list of dicts (first row as headers)."""
reader = csv.DictReader(io.StringIO(content), delimiter=delimiter)
return list(reader)
def to_csv(rows: list[list[str]], delimiter: str = ",") -> str:
"""Convert list of rows to CSV string."""
output = io.StringIO()
writer = csv.writer(output, delimiter=delimiter)
writer.writerows(rows)
return output.getvalue()
def to_csv_dict(
data: list[dict[str, str]], headers: list[str] | None = None, delimiter: str = ","
) -> str:
"""Convert list of dicts to CSV string."""
if not data:
return ""
output = io.StringIO()
fieldnames = headers or list(data[0].keys())
writer = csv.DictWriter(output, fieldnames=fieldnames, delimiter=delimiter)
writer.writeheader()
writer.writerows(data)
return output.getvalue()
def read_csv_file(path: str, delimiter: str = ",") -> list[list[str]]:
"""Read CSV file to list of rows."""
with open(path, newline="") as f:
reader = csv.reader(f, delimiter=delimiter)
return list(reader)
def read_csv_dict_file(path: str, delimiter: str = ",") -> list[dict[str, str]]:
"""Read CSV file to list of dicts."""
with open(path, newline="") as f:
reader = csv.DictReader(f, delimiter=delimiter)
return list(reader)
def write_csv_file(path: str, rows: list[list[str]], delimiter: str = ",") -> None:
"""Write list of rows to CSV file."""
with open(path, "w", newline="") as f:
writer = csv.writer(f, delimiter=delimiter)
writer.writerows(rows)
def write_csv_dict_file(
path: str, data: list[dict[str, str]], headers: list[str] | None = None, delimiter: str = ","
) -> None:
"""Write list of dicts to CSV file."""
if not data:
return
with open(path, "w", newline="") as f:
fieldnames = headers or list(data[0].keys())
writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter=delimiter)
writer.writeheader()
writer.writerows(data)
def get_headers(content: str, delimiter: str = ",") -> list[str]:
"""Get CSV headers (first row)."""
rows = parse_csv(content, delimiter)
return rows[0] if rows else []
def get_column(rows: list[list[str]], index: int) -> list[str]:
"""Get column by index."""
return [row[index] for row in rows if index < len(row)]
def get_column_by_name(data: list[dict[str, str]], name: str) -> list[str]:
"""Get column by name from dict data."""
return [row.get(name, "") for row in data]
def row_count(rows: list[list[str]]) -> int:
"""Count rows (including header)."""
return len(rows)
def column_count(rows: list[list[str]]) -> int:
"""Count columns (based on first row)."""
return len(rows[0]) if rows else 0
def filter_rows(rows: list[list[str]], column: int, value: str) -> list[list[str]]:
"""Filter rows where column equals value."""
return [row for row in rows if len(row) > column and row[column] == value]
def filter_dict_rows(data: list[dict[str, str]], key: str, value: str) -> list[dict[str, str]]:
"""Filter dict rows where key equals value."""
return [row for row in data if row.get(key) == value]
def sort_by_column(rows: list[list[str]], column: int, reverse: bool = False) -> list[list[str]]:
"""Sort rows by column (keeps header first if present)."""
if not rows:
return rows
header = rows[0]
data = rows[1:]
sorted_data = sorted(data, key=lambda r: r[column] if column < len(r) else "", reverse=reverse)
return [header] + sorted_data
def sort_dict_by_key(
data: list[dict[str, str]], key: str, reverse: bool = False
) -> list[dict[str, str]]:
"""Sort dict rows by key."""
return sorted(data, key=lambda r: r.get(key, ""), reverse=reverse)
def select_columns(rows: list[list[str]], columns: list[int]) -> list[list[str]]:
"""Select specific columns by index."""
return [[row[i] for i in columns if i < len(row)] for row in rows]
def select_dict_columns(data: list[dict[str, str]], columns: list[str]) -> list[dict[str, str]]:
"""Select specific columns by name."""
return [{k: row.get(k, "") for k in columns} for row in data]
def add_column(rows: list[list[str]], values: list[str], header: str = "") -> list[list[str]]:
"""Add column to rows."""
result = []
for i, row in enumerate(rows):
if i == 0:
result.append(row + [header])
elif i - 1 < len(values):
result.append(row + [values[i - 1]])
else:
result.append(row + [""])
return result
def remove_column(rows: list[list[str]], column: int) -> list[list[str]]:
"""Remove column by index."""
return [[cell for j, cell in enumerate(row) if j != column] for row in rows]
def rename_header(rows: list[list[str]], old: str, new: str) -> list[list[str]]:
"""Rename header."""
if not rows:
return rows
header = [new if h == old else h for h in rows[0]]
return [header] + rows[1:]
def merge_csv(rows1: list[list[str]], rows2: list[list[str]]) -> list[list[str]]:
"""Merge two CSVs (append rows, assuming same headers)."""
if not rows1:
return rows2
if not rows2:
return rows1
return rows1 + rows2[1:]
def unique_values(rows: list[list[str]], column: int) -> list[str]:
"""Get unique values in column."""
seen: set[str] = set()
result: list[str] = []
for row in rows:
if column < len(row):
val = row[column]
if val not in seen:
seen.add(val)
result.append(val)
return result
def count_by_column(rows: list[list[str]], column: int) -> dict[str, int]:
"""Count occurrences of each value in column."""
counts: dict[str, int] = {}
for row in rows:
if column < len(row):
val = row[column]
counts[val] = counts.get(val, 0) + 1
return counts
def transpose(rows: list[list[str]]) -> list[list[str]]:
"""Transpose CSV (rows become columns)."""
if not rows:
return []
max_cols = max(len(row) for row in rows)
return [
[rows[j][i] if i < len(rows[j]) else "" for j in range(len(rows))] for i in range(max_cols)
]
def main() -> int:
parser = argparse.ArgumentParser(description="CSV basic CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# parse
parse_p = subparsers.add_parser("parse", help="Parse CSV string")
parse_p.add_argument("csv", help="CSV string")
parse_p.add_argument("-d", "--delimiter", default=",", help="Delimiter")
# read
read_p = subparsers.add_parser("read", help="Read CSV file")
read_p.add_argument("file", help="CSV file path")
read_p.add_argument("-d", "--delimiter", default=",", help="Delimiter")
# headers
headers_p = subparsers.add_parser("headers", help="Get headers")
headers_p.add_argument("file", help="CSV file path")
# count
count_p = subparsers.add_parser("count", help="Count rows")
count_p.add_argument("file", help="CSV file path")
# column
column_p = subparsers.add_parser("column", help="Get column")
column_p.add_argument("file", help="CSV file path")
column_p.add_argument("index", type=int, help="Column index")
args = parser.parse_args()
if args.command == "parse":
rows = parse_csv(args.csv, args.delimiter)
for row in rows:
print(row)
elif args.command == "read":
rows = read_csv_file(args.file, args.delimiter)
for row in rows:
print(row)
elif args.command == "headers":
rows = read_csv_file(args.file)
if rows:
print(rows[0])
elif args.command == "count":
rows = read_csv_file(args.file)
print(f"Rows: {len(rows)}")
if rows:
print(f"Columns: {len(rows[0])}")
elif args.command == "column":
rows = read_csv_file(args.file)
column = get_column(rows, args.index)
for val in column:
print(val)
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_csv_basic/csv_basic_cli.py (8580 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_csv_basic/csv_basic_cli.rs (21337 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_csv_basic/Cargo.toml (2 dependencies)
⏱️ Parse time: 58ms
📊 Throughput: 142.7 KB/s
⏱️ Total time: 58ms
| true
|
csv_basic
| 275
| 6
|
[
"lambda",
"context_manager"
] | 0.783
| null |
example_csv_basic
|
test_csv_basic_cli.py
|
"""Tests for csv_basic_cli.py"""
import os
import tempfile
from csv_basic_cli import (
add_column,
column_count,
count_by_column,
filter_dict_rows,
filter_rows,
get_column,
get_column_by_name,
get_headers,
merge_csv,
parse_csv,
parse_csv_dict,
read_csv_dict_file,
read_csv_file,
remove_column,
rename_header,
row_count,
select_columns,
select_dict_columns,
sort_by_column,
sort_dict_by_key,
to_csv,
to_csv_dict,
transpose,
unique_values,
write_csv_dict_file,
write_csv_file,
)
class TestParseCsv:
def test_parse_csv(self):
content = "a,b,c\n1,2,3\n4,5,6"
rows = parse_csv(content)
assert rows == [["a", "b", "c"], ["1", "2", "3"], ["4", "5", "6"]]
def test_parse_csv_custom_delimiter(self):
content = "a;b;c\n1;2;3"
rows = parse_csv(content, delimiter=";")
assert rows == [["a", "b", "c"], ["1", "2", "3"]]
class TestParseCsvDict:
def test_parse_csv_dict(self):
content = "name,age\nAlice,30\nBob,25"
data = parse_csv_dict(content)
assert data == [{"name": "Alice", "age": "30"}, {"name": "Bob", "age": "25"}]
class TestToCsv:
def test_to_csv(self):
rows = [["a", "b"], ["1", "2"]]
result = to_csv(rows)
assert "a,b" in result
assert "1,2" in result
def test_to_csv_dict(self):
data = [{"name": "Alice", "age": "30"}]
result = to_csv_dict(data)
assert "name,age" in result
assert "Alice,30" in result
class TestFileOperations:
def test_read_write_csv_file(self):
rows = [["a", "b"], ["1", "2"]]
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
path = f.name
try:
write_csv_file(path, rows)
result = read_csv_file(path)
assert result == rows
finally:
os.unlink(path)
def test_read_write_csv_dict_file(self):
data = [{"name": "Alice", "age": "30"}]
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
path = f.name
try:
write_csv_dict_file(path, data)
result = read_csv_dict_file(path)
assert result == data
finally:
os.unlink(path)
class TestGetHeaders:
def test_get_headers(self):
content = "name,age,city\n1,2,3"
headers = get_headers(content)
assert headers == ["name", "age", "city"]
class TestGetColumn:
def test_get_column(self):
rows = [["a", "b"], ["1", "2"], ["3", "4"]]
column = get_column(rows, 0)
assert column == ["a", "1", "3"]
def test_get_column_by_name(self):
data = [{"name": "Alice", "age": "30"}, {"name": "Bob", "age": "25"}]
column = get_column_by_name(data, "name")
assert column == ["Alice", "Bob"]
class TestRowColumnCount:
def test_row_count(self):
rows = [["a"], ["b"], ["c"]]
assert row_count(rows) == 3
def test_column_count(self):
rows = [["a", "b", "c"], ["1", "2", "3"]]
assert column_count(rows) == 3
class TestFilter:
def test_filter_rows(self):
rows = [["name", "age"], ["Alice", "30"], ["Bob", "25"], ["Alice", "35"]]
result = filter_rows(rows, 0, "Alice")
assert len(result) == 2
def test_filter_dict_rows(self):
data = [{"name": "Alice", "age": "30"}, {"name": "Bob", "age": "25"}]
result = filter_dict_rows(data, "name", "Alice")
assert result == [{"name": "Alice", "age": "30"}]
class TestSort:
def test_sort_by_column(self):
rows = [["name", "age"], ["Bob", "25"], ["Alice", "30"]]
result = sort_by_column(rows, 0)
assert result[1][0] == "Alice"
assert result[2][0] == "Bob"
def test_sort_dict_by_key(self):
data = [{"name": "Bob"}, {"name": "Alice"}]
result = sort_dict_by_key(data, "name")
assert result[0]["name"] == "Alice"
class TestSelectColumns:
def test_select_columns(self):
rows = [["a", "b", "c"], ["1", "2", "3"]]
result = select_columns(rows, [0, 2])
assert result == [["a", "c"], ["1", "3"]]
def test_select_dict_columns(self):
data = [{"a": "1", "b": "2", "c": "3"}]
result = select_dict_columns(data, ["a", "c"])
assert result == [{"a": "1", "c": "3"}]
class TestAddRemoveColumn:
def test_add_column(self):
rows = [["name"], ["Alice"], ["Bob"]]
result = add_column(rows, ["30", "25"], "age")
assert result == [["name", "age"], ["Alice", "30"], ["Bob", "25"]]
def test_remove_column(self):
rows = [["a", "b", "c"], ["1", "2", "3"]]
result = remove_column(rows, 1)
assert result == [["a", "c"], ["1", "3"]]
class TestRenameHeader:
def test_rename_header(self):
rows = [["old_name", "age"], ["Alice", "30"]]
result = rename_header(rows, "old_name", "new_name")
assert result[0] == ["new_name", "age"]
class TestMergeCsv:
def test_merge_csv(self):
rows1 = [["a", "b"], ["1", "2"]]
rows2 = [["a", "b"], ["3", "4"]]
result = merge_csv(rows1, rows2)
assert len(result) == 3
assert result[2] == ["3", "4"]
class TestUniqueValues:
def test_unique_values(self):
rows = [["a"], ["b"], ["a"], ["c"], ["b"]]
result = unique_values(rows, 0)
assert result == ["a", "b", "c"]
class TestCountByColumn:
def test_count_by_column(self):
rows = [["a"], ["b"], ["a"], ["a"]]
result = count_by_column(rows, 0)
assert result == {"a": 3, "b": 1}
class TestTranspose:
def test_transpose(self):
rows = [["a", "b"], ["1", "2"], ["3", "4"]]
result = transpose(rows)
assert result == [["a", "1", "3"], ["b", "2", "4"]]
class TestEdgeCases:
def test_empty_csv(self):
rows = parse_csv("")
assert rows == []
def test_single_row(self):
rows = parse_csv("a,b,c")
assert rows == [["a", "b", "c"]]
def test_quoted_fields(self):
content = 'name,description\nAlice,"Hello, World"'
rows = parse_csv(content)
assert rows[1] == ["Alice", "Hello, World"]
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_csv_basic/test_csv_basic_cli.py (6302 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_csv_basic/test_csv_basic_cli.rs (21844 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_csv_basic/Cargo.toml (1 dependencies)
⏱️ Parse time: 56ms
📊 Throughput: 108.6 KB/s
⏱️ Total time: 56ms
| true
|
csv_basic
| 220
| 6
|
[
"context_manager",
"class_definition",
"exception_handling"
] | 0.652
| null |
example_csv_dialect
|
csv_dialect_cli.py
|
#!/usr/bin/env python3
"""CSV parser with custom dialect support.
Supports custom delimiters, quote characters, and escape handling.
"""
import argparse
import sys
def parse_csv_line(line: str, delimiter: str, quote: str, escape: str) -> list:
"""Parse a single CSV line with custom dialect."""
fields = []
current = ""
in_quotes = False
i = 0
while i < len(line):
char = line[i]
if escape and char == escape and i + 1 < len(line):
# Escape sequence
current += line[i + 1]
i += 2
continue
if char == quote:
in_quotes = not in_quotes
i += 1
continue
if char == delimiter and not in_quotes:
fields.append(current)
current = ""
i += 1
continue
current += char
i += 1
fields.append(current)
return fields
def format_csv_line(fields: list, delimiter: str, quote: str, always_quote: bool) -> str:
"""Format fields as a CSV line."""
result = []
for field in fields:
needs_quote = always_quote or delimiter in field or quote in field or "\n" in field
if needs_quote:
escaped = field.replace(quote, quote + quote)
result.append(f"{quote}{escaped}{quote}")
else:
result.append(field)
return delimiter.join(result)
def convert_delimiter(lines: list, from_delim: str, to_delim: str, quote: str, escape: str) -> list:
"""Convert CSV from one delimiter to another."""
result = []
for line in lines:
if line.strip():
fields = parse_csv_line(line.strip(), from_delim, quote, escape)
result.append(format_csv_line(fields, to_delim, quote, False))
return result
def get_column(lines: list, col_index: int, delimiter: str, quote: str, escape: str) -> list:
"""Extract a single column from CSV."""
result = []
for line in lines:
if line.strip():
fields = parse_csv_line(line.strip(), delimiter, quote, escape)
if col_index < len(fields):
result.append(fields[col_index])
return result
def count_columns(lines: list, delimiter: str, quote: str, escape: str) -> dict:
"""Count rows by number of columns."""
counts: dict = {}
for line in lines:
if line.strip():
fields = parse_csv_line(line.strip(), delimiter, quote, escape)
n = len(fields)
counts[n] = counts.get(n, 0) + 1
return counts
def main() -> int:
parser = argparse.ArgumentParser(description="CSV parser with custom dialect support")
parser.add_argument("input", nargs="?", help="Input CSV file (- for stdin)")
parser.add_argument("-d", "--delimiter", default=",", help="Field delimiter (default: ,)")
parser.add_argument("-q", "--quote", default='"', help='Quote character (default: ")')
parser.add_argument("-e", "--escape", default="", help="Escape character (default: none)")
parser.add_argument("--to-delimiter", metavar="DELIM", help="Convert to this delimiter")
parser.add_argument("--column", type=int, metavar="N", help="Extract column N (0-indexed)")
parser.add_argument("--count-columns", action="store_true", help="Count rows by column count")
parser.add_argument("--skip-header", action="store_true", help="Skip first line")
args = parser.parse_args()
# Read input
if args.input is None or args.input == "-":
lines = sys.stdin.readlines()
else:
with open(args.input) as f:
lines = f.readlines()
# Skip header if requested
if args.skip_header and lines:
lines = lines[1:]
# Perform operation
if args.to_delimiter:
result = convert_delimiter(
lines, args.delimiter, args.to_delimiter, args.quote, args.escape
)
for line in result:
print(line)
elif args.column is not None:
values = get_column(lines, args.column, args.delimiter, args.quote, args.escape)
for value in values:
print(value)
elif args.count_columns:
counts = count_columns(lines, args.delimiter, args.quote, args.escape)
for n, count in sorted(counts.items()):
print(f"{n} columns: {count} rows")
else:
# Default: parse and re-output
for line in lines:
if line.strip():
fields = parse_csv_line(line.strip(), args.delimiter, args.quote, args.escape)
print(format_csv_line(fields, args.delimiter, args.quote, False))
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
csv_dialect
| 140
| 0
|
[
"context_manager",
"stdin_usage"
] | 0.652
|
Type inference hints:
Hint: int for variable 'char' [Medium] (usage patterns suggest this type)
Hint: int for variable 'i' [High] (usage patterns suggest this type)
Hint: int for variable 'current' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'line' [High] (usage patterns suggest this type)
Hint: list[Any] for variable 'fields' [High] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'field' [Medium] (usage patterns suggest this type)
Hi
|
|
example_csv_dialect
|
test_csv_dialect_cli.py
|
"""Tests for csv_dialect_cli.py"""
from csv_dialect_cli import (
convert_delimiter,
count_columns,
format_csv_line,
get_column,
parse_csv_line,
)
class TestParsing:
def test_simple_csv(self):
result = parse_csv_line("a,b,c", ",", '"', "")
assert result == ["a", "b", "c"]
def test_quoted_field(self):
result = parse_csv_line('"hello, world",b', ",", '"', "")
assert result == ["hello, world", "b"]
def test_tab_delimiter(self):
result = parse_csv_line("a\tb\tc", "\t", '"', "")
assert result == ["a", "b", "c"]
def test_semicolon_delimiter(self):
result = parse_csv_line("a;b;c", ";", '"', "")
assert result == ["a", "b", "c"]
def test_escaped_quote(self):
result = parse_csv_line('a,"b""c",d', ",", '"', "")
# After parsing, quotes are removed
assert len(result) == 3
def test_backslash_escape(self):
result = parse_csv_line(r'a,b\,c,d', ",", '"', "\\")
assert result == ["a", "b,c", "d"]
class TestFormatting:
def test_simple_format(self):
result = format_csv_line(["a", "b", "c"], ",", '"', False)
assert result == "a,b,c"
def test_quote_when_needed(self):
result = format_csv_line(["hello, world", "b"], ",", '"', False)
assert result == '"hello, world",b'
def test_always_quote(self):
result = format_csv_line(["a", "b"], ",", '"', True)
assert result == '"a","b"'
class TestConvert:
def test_comma_to_tab(self):
lines = ["a,b,c", "1,2,3"]
result = convert_delimiter(lines, ",", "\t", '"', "")
assert result == ["a\tb\tc", "1\t2\t3"]
def test_semicolon_to_comma(self):
lines = ["a;b;c"]
result = convert_delimiter(lines, ";", ",", '"', "")
assert result == ["a,b,c"]
class TestColumn:
def test_get_first_column(self):
lines = ["a,b,c", "1,2,3"]
result = get_column(lines, 0, ",", '"', "")
assert result == ["a", "1"]
def test_get_last_column(self):
lines = ["a,b,c", "1,2,3"]
result = get_column(lines, 2, ",", '"', "")
assert result == ["c", "3"]
class TestCount:
def test_count_columns(self):
lines = ["a,b,c", "1,2", "x,y,z"]
result = count_columns(lines, ",", '"', "")
assert result[3] == 2
assert result[2] == 1
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_csv_dialect/test_csv_dialect_cli.py (2398 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_csv_dialect/test_csv_dialect_cli.rs (6202 bytes)
⏱️ Parse time: 49ms
📊 Throughput: 47.7 KB/s
⏱️ Total time: 49ms
| true
|
csv_dialect
| 82
| 5
|
[
"class_definition"
] | 0.612
| null |
example_csv_filter
|
csv_filter.py
|
#!/usr/bin/env python3
"""
CSV Filter - Memory-efficient CSV filtering using generators
Demonstrates:
- Generator expressions for lazy evaluation
- csv.DictReader iteration
- Predicate filtering with lambda/functions
- Streaming write to stdout or file
- argparse for CLI options
This validates depyler's ability to transpile:
- Generator expressions: (row for row in reader if predicate(row))
- File iteration patterns: for line in f
- csv module usage
Depyler: stress test for generator transpilation
"""
import argparse
import csv
import sys
def filter_csv(input_file, column, value, output_file=None):
"""
Filter CSV rows where column equals value.
Uses generator to process one row at a time.
Args:
input_file: Path to input CSV
column: Column name to filter on
value: Value to match
output_file: Path to output CSV (stdout if None)
Depyler: proven to terminate
"""
with open(input_file) as f:
reader = csv.DictReader(f)
# Store fieldnames before consuming reader
fieldnames = reader.fieldnames
# Generator expression - lazy evaluation
filtered_rows = (row for row in reader if row[column] == value)
# Setup output
output = open(output_file, "w") if output_file else sys.stdout
try:
# Write header
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
# Process and write one row at a time
for row in filtered_rows:
writer.writerow(row)
finally:
if output_file:
output.close()
def filter_csv_advanced(input_file, filters, output_file=None):
"""
Filter CSV with multiple column criteria.
Args:
input_file: Path to input CSV
filters: Dict of {column: value} filters (AND logic)
output_file: Path to output CSV
Depyler: proven to terminate
"""
def matches_all_filters(row):
"""Check if row matches all filter criteria"""
return all(row.get(col) == val for col, val in filters.items())
with open(input_file) as f:
reader = csv.DictReader(f)
# Store fieldnames
fieldnames = reader.fieldnames
# Generator with complex predicate
filtered_rows = (row for row in reader if matches_all_filters(row))
output = open(output_file, "w") if output_file else sys.stdout
try:
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
count = 0
for row in filtered_rows:
writer.writerow(row)
count += 1
print(f"Filtered {count} rows", file=sys.stderr)
finally:
if output_file:
output.close()
def main():
"""CLI entry point"""
parser = argparse.ArgumentParser(
description="Filter CSV files by column values", prog="csv_filter"
)
parser.add_argument("input", help="Input CSV file")
parser.add_argument("--column", "-c", required=True, help="Column to filter")
parser.add_argument("--value", "-v", required=True, help="Value to match")
parser.add_argument("--output", "-o", help="Output CSV file (default: stdout)")
parser.add_argument("--version", action="version", version="1.0.0")
args = parser.parse_args()
filter_csv(args.input, args.column, args.value, args.output)
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_csv_filter/csv_filter.py (3503 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_csv_filter/csv_filter.rs (4236 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_csv_filter/Cargo.toml (4 dependencies)
⏱️ Parse time: 95ms
📊 Throughput: 35.7 KB/s
⏱️ Total time: 95ms
| true
|
csv_filter
| 124
| 6
|
[
"context_manager",
"exception_handling",
"multiprocessing"
] | 0.652
| null |
example_csv_filter
|
test_csv_filter.py
|
#!/usr/bin/env python3
"""
Test suite for csv_filter - Memory-efficient CSV filtering
Tests generator expressions, streaming I/O, and memory efficiency.
Following EXTREME TDD methodology with 100% coverage goal.
"""
import csv
import subprocess
import sys
from pathlib import Path
import pytest
# Test data fixtures
@pytest.fixture
def sample_csv_data():
"""Sample CSV data for testing"""
return [
{"name": "Alice", "age": "25", "city": "NYC"},
{"name": "Bob", "age": "30", "city": "LA"},
{"name": "Charlie", "age": "25", "city": "Chicago"},
{"name": "Diana", "age": "35", "city": "NYC"},
{"name": "Eve", "age": "25", "city": "Seattle"},
]
@pytest.fixture
def sample_csv_file(tmp_path, sample_csv_data):
"""Create temporary CSV file with sample data"""
csv_file = tmp_path / "test.csv"
with open(csv_file, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age", "city"])
writer.writeheader()
writer.writerows(sample_csv_data)
return csv_file
@pytest.fixture
def empty_csv_file(tmp_path):
"""Create empty CSV file"""
csv_file = tmp_path / "empty.csv"
with open(csv_file, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age", "city"])
writer.writeheader()
return csv_file
class TestBasicFiltering:
"""Test core filtering functionality"""
def test_filter_by_single_column(self, sample_csv_file, tmp_path):
"""Filter rows where age equals 25"""
from csv_filter import filter_csv
output_file = tmp_path / "output.csv"
filter_csv(str(sample_csv_file), "age", "25", str(output_file))
# Verify output
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 3
assert all(row["age"] == "25" for row in rows)
assert {row["name"] for row in rows} == {"Alice", "Charlie", "Eve"}
def test_filter_no_matches(self, sample_csv_file, tmp_path):
"""Filter with no matching rows"""
from csv_filter import filter_csv
output_file = tmp_path / "output.csv"
filter_csv(str(sample_csv_file), "age", "99", str(output_file))
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 0
def test_filter_all_match(self, tmp_path):
"""Filter where all rows match"""
from csv_filter import filter_csv
# Create file where all have same value
csv_file = tmp_path / "test.csv"
data = [{"name": f"Person{i}", "status": "active"} for i in range(5)]
with open(csv_file, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "status"])
writer.writeheader()
writer.writerows(data)
output_file = tmp_path / "output.csv"
filter_csv(str(csv_file), "status", "active", str(output_file))
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 5
def test_filter_by_string_column(self, sample_csv_file, tmp_path):
"""Filter by city name"""
from csv_filter import filter_csv
output_file = tmp_path / "output.csv"
filter_csv(str(sample_csv_file), "city", "NYC", str(output_file))
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 2
assert all(row["city"] == "NYC" for row in rows)
def test_output_to_stdout(self, sample_csv_file, capsys):
"""Filter with output to stdout"""
from csv_filter import filter_csv
filter_csv(str(sample_csv_file), "age", "25", None)
captured = capsys.readouterr()
lines = captured.out.strip().split("\n")
# Header + 3 matching rows
assert len(lines) == 4
assert "name,age,city" in lines[0]
class TestAdvancedFiltering:
"""Test advanced filtering with multiple criteria"""
def test_filter_multiple_criteria(self, sample_csv_file, tmp_path):
"""Filter with AND logic on multiple columns"""
from csv_filter import filter_csv_advanced
filters = {"age": "25", "city": "NYC"}
output_file = tmp_path / "output.csv"
filter_csv_advanced(str(sample_csv_file), filters, str(output_file))
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 1
assert rows[0]["name"] == "Alice"
def test_multiple_criteria_no_match(self, sample_csv_file, tmp_path):
"""Multiple criteria with no matching rows"""
from csv_filter import filter_csv_advanced
filters = {"age": "25", "city": "Boston"} # No one age 25 in Boston
output_file = tmp_path / "output.csv"
filter_csv_advanced(str(sample_csv_file), filters, str(output_file))
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 0
def test_empty_filters(self, sample_csv_file, tmp_path):
"""Empty filter dict should return all rows"""
from csv_filter import filter_csv_advanced
filters = {}
output_file = tmp_path / "output.csv"
filter_csv_advanced(str(sample_csv_file), filters, str(output_file))
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 5
class TestEdgeCases:
"""Test edge cases and error handling"""
def test_empty_input_file(self, empty_csv_file, tmp_path):
"""Filter empty CSV file"""
from csv_filter import filter_csv
output_file = tmp_path / "output.csv"
filter_csv(str(empty_csv_file), "age", "25", str(output_file))
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 0
def test_nonexistent_column(self, sample_csv_file, tmp_path):
"""Filter by non-existent column should raise KeyError"""
from csv_filter import filter_csv
output_file = tmp_path / "output.csv"
with pytest.raises(KeyError):
filter_csv(str(sample_csv_file), "nonexistent", "value", str(output_file))
def test_nonexistent_input_file(self, tmp_path):
"""Non-existent input file should raise FileNotFoundError"""
from csv_filter import filter_csv
output_file = tmp_path / "output.csv"
with pytest.raises(FileNotFoundError):
filter_csv("/nonexistent/file.csv", "age", "25", str(output_file))
class TestMemoryEfficiency:
"""Test memory efficiency with large datasets"""
def test_large_file_streaming(self, tmp_path):
"""Verify streaming behavior with 10K rows"""
from csv_filter import filter_csv
# Generate large CSV (10K rows)
large_file = tmp_path / "large.csv"
with open(large_file, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["id", "value", "category"])
writer.writeheader()
for i in range(10000):
writer.writerow({"id": str(i), "value": str(i % 100), "category": "A" if i % 2 == 0 else "B"})
output_file = tmp_path / "output.csv"
filter_csv(str(large_file), "category", "A", str(output_file))
# Verify 5000 rows match (half are category A)
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 5000
assert all(row["category"] == "A" for row in rows)
class TestCLIInterface:
"""Test command-line interface"""
def test_cli_help(self):
"""Test --help flag"""
result = subprocess.run(
[sys.executable, "csv_filter.py", "--help"],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
assert result.returncode == 0
assert "Filter CSV files" in result.stdout
def test_cli_version(self):
"""Test --version flag"""
result = subprocess.run(
[sys.executable, "csv_filter.py", "--version"],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
assert result.returncode == 0
assert "1.0.0" in result.stdout
def test_cli_basic_filter(self, sample_csv_file, tmp_path):
"""Test CLI basic filtering"""
output_file = tmp_path / "output.csv"
result = subprocess.run(
[
sys.executable,
"csv_filter.py",
str(sample_csv_file),
"--column",
"age",
"--value",
"25",
"--output",
str(output_file),
],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
assert result.returncode == 0
assert output_file.exists()
with open(output_file) as f:
reader = csv.DictReader(f)
rows = list(reader)
assert len(rows) == 3
def test_cli_missing_required_args(self):
"""Test CLI with missing required arguments"""
result = subprocess.run(
[sys.executable, "csv_filter.py"],
capture_output=True,
text=True,
cwd=Path(__file__).parent,
)
assert result.returncode != 0
class TestPropertyBased:
"""Property-based tests for invariants"""
def test_filtered_count_less_than_input(self, sample_csv_file, tmp_path):
"""Property: filtered rows ≤ input rows"""
from csv_filter import filter_csv
# Count input rows
with open(sample_csv_file) as f:
input_count = sum(1 for _ in csv.DictReader(f))
output_file = tmp_path / "output.csv"
filter_csv(str(sample_csv_file), "age", "25", str(output_file))
# Count output rows
with open(output_file) as f:
output_count = sum(1 for _ in csv.DictReader(f))
assert output_count <= input_count
def test_all_filtered_rows_match_predicate(self, sample_csv_file, tmp_path):
"""Property: all output rows match filter criteria"""
from csv_filter import filter_csv
output_file = tmp_path / "output.csv"
filter_csv(str(sample_csv_file), "city", "NYC", str(output_file))
with open(output_file) as f:
reader = csv.DictReader(f)
for row in reader:
assert row["city"] == "NYC"
def test_output_preserves_field_structure(self, sample_csv_file, tmp_path):
"""Property: output has same fields as input"""
from csv_filter import filter_csv
# Get input fieldnames
with open(sample_csv_file) as f:
input_fields = csv.DictReader(f).fieldnames
output_file = tmp_path / "output.csv"
filter_csv(str(sample_csv_file), "age", "25", str(output_file))
# Get output fieldnames
with open(output_file) as f:
output_fields = csv.DictReader(f).fieldnames
assert input_fields == output_fields
def test_idempotent_filtering(self, sample_csv_file, tmp_path):
"""Property: filtering twice produces same result"""
from csv_filter import filter_csv
output1 = tmp_path / "output1.csv"
output2 = tmp_path / "output2.csv"
filter_csv(str(sample_csv_file), "age", "25", str(output1))
filter_csv(str(output1), "age", "25", str(output2))
# Read both outputs
with open(output1) as f:
rows1 = list(csv.DictReader(f))
with open(output2) as f:
rows2 = list(csv.DictReader(f))
assert rows1 == rows2
| false
|
csv_filter
| 373
| 0
|
[
"context_manager",
"class_definition",
"exception_handling",
"stdin_usage",
"decorator"
] | 0.652
|
Type inference hints:
Hint: list[Any] for return type [Medium] (explicit return)
Type inference hints:
Hint: str for return type [Medium] (explicit return)
Hint: int for variable 'tmp_path' [Medium] (usage patterns suggest this type)
Hint: str for variable 'csv_file' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: str for return type [Medium] (explicit return)
Hint: int for variable 'tmp_path' [Medium] (usage patterns suggest this type)
Hint: str for variable 'csv_file'
|
|
example_custom_exception
|
custom_exception_cli.py
|
#!/usr/bin/env python3
"""Custom Exception CLI.
Custom exception classes with inheritance patterns.
"""
import argparse
import sys
class AppError(Exception):
"""Base application error."""
def __init__(self, message: str, code: int = 0):
super().__init__(message)
self.message = message
self.code = code
class ValidationError(AppError):
"""Validation error."""
def __init__(self, field: str, message: str):
super().__init__(f"{field}: {message}", code=400)
self.field = field
class NotFoundError(AppError):
"""Resource not found error."""
def __init__(self, resource: str, identifier: str):
super().__init__(f"{resource} '{identifier}' not found", code=404)
self.resource = resource
self.identifier = identifier
class AuthenticationError(AppError):
"""Authentication error."""
def __init__(self, message: str = "Authentication failed"):
super().__init__(message, code=401)
class AuthorizationError(AppError):
"""Authorization error."""
def __init__(self, action: str, resource: str):
super().__init__(f"Not authorized to {action} {resource}", code=403)
self.action = action
self.resource = resource
class RateLimitError(AppError):
"""Rate limit exceeded error."""
def __init__(self, limit: int, window: int):
super().__init__(f"Rate limit {limit} per {window}s exceeded", code=429)
self.limit = limit
self.window = window
def validate_username(username: str) -> str:
"""Validate username format."""
if len(username) < 3:
raise ValidationError("username", "must be at least 3 characters")
if len(username) > 20:
raise ValidationError("username", "must be at most 20 characters")
if not username.isalnum():
raise ValidationError("username", "must be alphanumeric")
return username
def validate_email(email: str) -> str:
"""Validate email format."""
if "@" not in email:
raise ValidationError("email", "must contain @")
parts = email.split("@")
if len(parts) != 2:
raise ValidationError("email", "invalid format")
if not parts[0] or not parts[1]:
raise ValidationError("email", "missing local or domain part")
return email
def validate_age(age: int) -> int:
"""Validate age value."""
if age < 0:
raise ValidationError("age", "cannot be negative")
if age > 150:
raise ValidationError("age", "unrealistic value")
return age
def validate_password(password: str) -> str:
"""Validate password strength."""
if len(password) < 8:
raise ValidationError("password", "must be at least 8 characters")
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
if not (has_upper and has_lower and has_digit):
raise ValidationError("password", "must have upper, lower, and digit")
return password
def find_user(users: dict[str, str], user_id: str) -> str:
"""Find user by ID."""
if user_id not in users:
raise NotFoundError("User", user_id)
return users[user_id]
def find_item(items: dict[int, str], item_id: int) -> str:
"""Find item by ID."""
if item_id not in items:
raise NotFoundError("Item", str(item_id))
return items[item_id]
def authenticate(token: str, valid_tokens: list[str]) -> bool:
"""Authenticate with token."""
if token not in valid_tokens:
raise AuthenticationError("Invalid token")
return True
def authorize_action(user_role: str, required_role: str, action: str, resource: str) -> bool:
"""Authorize user action."""
roles = ["guest", "user", "admin"]
if roles.index(user_role) < roles.index(required_role):
raise AuthorizationError(action, resource)
return True
def check_rate_limit(count: int, limit: int, window: int) -> bool:
"""Check if rate limit exceeded."""
if count > limit:
raise RateLimitError(limit, window)
return True
def safe_validate_username(username: str) -> tuple[bool, str]:
"""Safely validate username, return status and message."""
try:
validate_username(username)
return (True, "valid")
except ValidationError as e:
return (False, e.message)
def safe_find_user(users: dict[str, str], user_id: str) -> str | None:
"""Safely find user, return None if not found."""
try:
return find_user(users, user_id)
except NotFoundError:
return None
def get_error_code(error: AppError) -> int:
"""Get error code from exception."""
return error.code
def format_error(error: AppError) -> str:
"""Format error for display."""
return f"[{error.code}] {error.message}"
def handle_validation_errors(fields: dict[str, str]) -> list[str]:
"""Validate multiple fields, collect errors."""
errors: list[str] = []
if "username" in fields:
try:
validate_username(fields["username"])
except ValidationError as e:
errors.append(e.message)
if "email" in fields:
try:
validate_email(fields["email"])
except ValidationError as e:
errors.append(e.message)
return errors
def validate_registration(username: str, email: str, password: str) -> dict[str, str]:
"""Validate registration data, raise first error."""
validate_username(username)
validate_email(email)
validate_password(password)
return {"username": username, "email": email, "status": "valid"}
def try_authenticate_and_authorize(
token: str, valid_tokens: list[str], user_role: str, required_role: str
) -> str:
"""Try to authenticate and authorize."""
try:
authenticate(token, valid_tokens)
authorize_action(user_role, required_role, "access", "resource")
return "success"
except AuthenticationError:
return "auth_failed"
except AuthorizationError:
return "not_authorized"
def main() -> int:
parser = argparse.ArgumentParser(description="Custom exception CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# validate
val_p = subparsers.add_parser("validate", help="Validate input")
val_p.add_argument("--username")
val_p.add_argument("--email")
val_p.add_argument("--password")
# find
find_p = subparsers.add_parser("find", help="Find resource")
find_p.add_argument("resource")
find_p.add_argument("id")
# auth
auth_p = subparsers.add_parser("auth", help="Authenticate")
auth_p.add_argument("token")
args = parser.parse_args()
if args.command == "validate":
try:
if args.username:
validate_username(args.username)
print(f"Username '{args.username}' is valid")
if args.email:
validate_email(args.email)
print(f"Email '{args.email}' is valid")
if args.password:
validate_password(args.password)
print("Password is valid")
except ValidationError as e:
print(f"Validation error: {e.message}")
return 1
elif args.command == "find":
try:
users = {"1": "alice", "2": "bob"}
result = find_user(users, args.id)
print(f"Found: {result}")
except NotFoundError as e:
print(f"Not found: {e.message}")
return 1
elif args.command == "auth":
try:
valid = ["token123", "token456"]
authenticate(args.token, valid)
print("Authentication successful")
except AuthenticationError as e:
print(f"Auth error: {e.message}")
return 1
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_custom_exception/custom_exception_cli.py (7923 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_custom_exception/custom_exception_cli.rs (15511 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_custom_exception/Cargo.toml (1 dependencies)
⏱️ Parse time: 57ms
📊 Throughput: 133.6 KB/s
⏱️ Total time: 58ms
| true
|
custom_exception
| 268
| 6
|
[
"context_manager",
"class_definition",
"exception_handling",
"decorator"
] | 0.652
| null |
example_custom_exception
|
test_custom_exception_cli.py
|
"""Tests for custom_exception_cli.py"""
import pytest
from custom_exception_cli import (
AppError,
AuthenticationError,
AuthorizationError,
NotFoundError,
RateLimitError,
ValidationError,
authenticate,
authorize_action,
check_rate_limit,
find_item,
find_user,
format_error,
get_error_code,
handle_validation_errors,
safe_find_user,
safe_validate_username,
try_authenticate_and_authorize,
validate_age,
validate_email,
validate_password,
validate_registration,
validate_username,
)
class TestAppError:
def test_base_error(self):
error = AppError("test error", 500)
assert error.message == "test error"
assert error.code == 500
def test_default_code(self):
error = AppError("test")
assert error.code == 0
class TestValidationError:
def test_creation(self):
error = ValidationError("field", "invalid")
assert error.field == "field"
assert "field: invalid" in error.message
assert error.code == 400
class TestNotFoundError:
def test_creation(self):
error = NotFoundError("User", "123")
assert error.resource == "User"
assert error.identifier == "123"
assert error.code == 404
class TestAuthenticationError:
def test_creation(self):
error = AuthenticationError()
assert error.code == 401
def test_custom_message(self):
error = AuthenticationError("Custom message")
assert "Custom message" in error.message
class TestAuthorizationError:
def test_creation(self):
error = AuthorizationError("delete", "file")
assert error.action == "delete"
assert error.resource == "file"
assert error.code == 403
class TestRateLimitError:
def test_creation(self):
error = RateLimitError(100, 60)
assert error.limit == 100
assert error.window == 60
assert error.code == 429
class TestValidateUsername:
def test_valid_username(self):
assert validate_username("alice") == "alice"
def test_too_short(self):
with pytest.raises(ValidationError) as exc:
validate_username("ab")
assert "at least 3" in exc.value.message
def test_too_long(self):
with pytest.raises(ValidationError) as exc:
validate_username("a" * 21)
assert "at most 20" in exc.value.message
def test_not_alphanumeric(self):
with pytest.raises(ValidationError) as exc:
validate_username("alice!")
assert "alphanumeric" in exc.value.message
class TestValidateEmail:
def test_valid_email(self):
assert validate_email("[email protected]") == "[email protected]"
def test_no_at_sign(self):
with pytest.raises(ValidationError) as exc:
validate_email("testexample.com")
assert "@" in exc.value.message
def test_empty_local_part(self):
with pytest.raises(ValidationError) as exc:
validate_email("@example.com")
assert "missing" in exc.value.message
class TestValidateAge:
def test_valid_age(self):
assert validate_age(25) == 25
def test_negative_age(self):
with pytest.raises(ValidationError) as exc:
validate_age(-1)
assert "negative" in exc.value.message
def test_unrealistic_age(self):
with pytest.raises(ValidationError) as exc:
validate_age(200)
assert "unrealistic" in exc.value.message
class TestValidatePassword:
def test_valid_password(self):
assert validate_password("Password1") == "Password1"
def test_too_short(self):
with pytest.raises(ValidationError) as exc:
validate_password("Pass1")
assert "8 characters" in exc.value.message
def test_missing_requirements(self):
with pytest.raises(ValidationError) as exc:
validate_password("password")
assert "upper" in exc.value.message
class TestFindUser:
def test_found(self):
users = {"1": "alice", "2": "bob"}
assert find_user(users, "1") == "alice"
def test_not_found(self):
users = {"1": "alice"}
with pytest.raises(NotFoundError) as exc:
find_user(users, "99")
assert exc.value.identifier == "99"
class TestFindItem:
def test_found(self):
items = {1: "item1", 2: "item2"}
assert find_item(items, 1) == "item1"
def test_not_found(self):
items = {1: "item1"}
with pytest.raises(NotFoundError):
find_item(items, 99)
class TestAuthenticate:
def test_valid_token(self):
assert authenticate("valid", ["valid", "other"]) is True
def test_invalid_token(self):
with pytest.raises(AuthenticationError):
authenticate("invalid", ["valid"])
class TestAuthorizeAction:
def test_authorized(self):
assert authorize_action("admin", "user", "delete", "file") is True
def test_not_authorized(self):
with pytest.raises(AuthorizationError):
authorize_action("guest", "admin", "delete", "file")
class TestCheckRateLimit:
def test_within_limit(self):
assert check_rate_limit(50, 100, 60) is True
def test_exceeded(self):
with pytest.raises(RateLimitError):
check_rate_limit(101, 100, 60)
class TestSafeValidateUsername:
def test_valid(self):
success, msg = safe_validate_username("alice")
assert success is True
assert msg == "valid"
def test_invalid(self):
success, msg = safe_validate_username("ab")
assert success is False
assert "3 characters" in msg
class TestSafeFindUser:
def test_found(self):
users = {"1": "alice"}
assert safe_find_user(users, "1") == "alice"
def test_not_found(self):
users = {"1": "alice"}
assert safe_find_user(users, "99") is None
class TestGetErrorCode:
def test_get_code(self):
error = ValidationError("field", "message")
assert get_error_code(error) == 400
class TestFormatError:
def test_format(self):
error = NotFoundError("User", "123")
formatted = format_error(error)
assert "[404]" in formatted
assert "User" in formatted
class TestHandleValidationErrors:
def test_all_valid(self):
fields = {"username": "alice", "email": "[email protected]"}
errors = handle_validation_errors(fields)
assert errors == []
def test_some_invalid(self):
fields = {"username": "ab", "email": "invalid"}
errors = handle_validation_errors(fields)
assert len(errors) == 2
class TestValidateRegistration:
def test_valid(self):
result = validate_registration("alice", "[email protected]", "Password1")
assert result["status"] == "valid"
def test_invalid_username(self):
with pytest.raises(ValidationError):
validate_registration("ab", "[email protected]", "Password1")
class TestTryAuthenticateAndAuthorize:
def test_success(self):
result = try_authenticate_and_authorize("valid", ["valid"], "admin", "user")
assert result == "success"
def test_auth_failed(self):
result = try_authenticate_and_authorize("invalid", ["valid"], "admin", "user")
assert result == "auth_failed"
def test_not_authorized(self):
result = try_authenticate_and_authorize("valid", ["valid"], "guest", "admin")
assert result == "not_authorized"
class TestEdgeCases:
def test_empty_username(self):
with pytest.raises(ValidationError):
validate_username("")
def test_boundary_age(self):
assert validate_age(0) == 0
assert validate_age(150) == 150
def test_exact_password_length(self):
assert validate_password("Passwor1") == "Passwor1"
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_custom_exception/test_custom_exception_cli.py (7868 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_custom_exception/test_custom_exception_cli.rs (20779 bytes)
⏱️ Parse time: 55ms
📊 Throughput: 139.1 KB/s
⏱️ Total time: 55ms
| true
|
custom_exception
| 280
| 5
|
[
"context_manager",
"class_definition",
"decorator"
] | 0.652
| null |
example_custom_types
|
custom_tool.py
|
#!/usr/bin/env python3
"""Custom Types Example - Custom argument type CLI."""
import argparse
def main():
parser = argparse.ArgumentParser(description="Custom types tool")
subs = parser.add_subparsers(dest="cmd", required=True)
p = subs.add_parser("port")
p.add_argument("value", type=int)
pc = subs.add_parser("percent")
pc.add_argument("value", type=int)
b = subs.add_parser("bytes")
b.add_argument("value", type=int)
args = parser.parse_args()
if args.cmd == "port":
if args.value >= 1 and args.value <= 65535:
print(f"Valid port: {args.value}")
elif args.cmd == "percent":
print(args.value / 100.0)
elif args.cmd == "bytes":
print(f"{args.value / 1024} KB")
if __name__ == "__main__":
main()
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_custom_types/custom_tool.py (791 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_custom_types/custom_tool.rs (1675 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_custom_types/Cargo.toml (1 dependencies)
⏱️ Parse time: 50ms
📊 Throughput: 15.3 KB/s
⏱️ Total time: 50ms
| true
|
custom_types
| 29
| 6
|
[] | 0
| null |
example_custom_types
|
test_custom_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for custom types CLI."""
import subprocess
SCRIPT = "custom_tool.py"
def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0])
class TestCustomTypes:
def test_port(self): r = run(["port", "8080"]); assert r.returncode == 0 and "8080" in r.stdout
def test_percent(self): r = run(["percent", "50"]); assert r.returncode == 0 and "0.5" in r.stdout
def test_bytes(self): r = run(["bytes", "1024"]); assert r.returncode == 0 and "1" in r.stdout
class TestHelp:
def test_help(self): assert run(["--help"]).returncode == 0
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_custom_types/test_custom_tool.py (651 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_custom_types/test_custom_tool.rs (1909 bytes)
⏱️ Parse time: 47ms
📊 Throughput: 13.3 KB/s
⏱️ Total time: 48ms
| true
|
custom_types
| 14
| 5
|
[
"class_definition"
] | 0.612
| null |
example_dataclass
|
data_tool.py
|
#!/usr/bin/env python3
"""
Dataclass Example - Structured data CLI
Demonstrates:
- @dataclass decorator
- Type annotations
- Default values
- JSON serialization
This validates depyler's ability to transpile dataclasses
to Rust (struct with serde derive).
"""
import argparse
import json
from dataclasses import asdict, dataclass
@dataclass
class Person:
"""A person record. Depyler: proven to terminate"""
name: str
age: int
email: str = ""
def cmd_create(args):
"""Create a person record. Depyler: proven to terminate"""
person = Person(name=args.name, age=args.age, email=args.email or "")
if args.json:
print(json.dumps(asdict(person)))
else:
print(f"Name: {person.name}")
print(f"Age: {person.age}")
if person.email:
print(f"Email: {person.email}")
def main():
"""Main entry point. Depyler: proven to terminate"""
parser = argparse.ArgumentParser(description="Structured data tool")
subparsers = parser.add_subparsers(dest="command", required=True)
create_parser = subparsers.add_parser("create", help="Create person record")
create_parser.add_argument("--name", required=True, help="Person name")
create_parser.add_argument("--age", type=int, required=True, help="Person age")
create_parser.add_argument("--email", help="Email address")
create_parser.add_argument("--json", action="store_true", help="Output as JSON")
args = parser.parse_args()
if args.command == "create":
cmd_create(args)
if __name__ == "__main__":
main()
| false
|
dataclass
| 60
| 0
|
[
"context_manager",
"class_definition",
"decorator"
] | 0.652
|
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions: 67
Total estimated allocations: 0
Functions analyzed: 2
Hot Paths
[1] cmd_create (59.7% of execution time)
[2] main (40.3% of execution time)
Function Metrics
🔥 cmd_create 59.7% time | 40 inst | 0 alloc
🔥 main 40.3% time | 27 inst | 0 alloc
Performance Predictions
• Rust's memory layout is more cache-friendly th
|
|
example_dataclass
|
test_data_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests for dataclass CLI."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "data_tool.py"
import json
SCRIPT = "data_tool.py"
def run(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(
["python3", SCRIPT] + args,
capture_output=True,
text=True,
cwd=__file__.rsplit("/", 1)[0],
)
class TestCreatePerson:
"""Test person creation."""
def test_create_basic(self):
result = run(["create", "--name", "Alice", "--age", "30"])
assert result.returncode == 0
assert "Alice" in result.stdout
def test_create_with_email(self):
result = run(["create", "--name", "Bob", "--age", "25", "--email", "[email protected]"])
assert result.returncode == 0
assert "[email protected]" in result.stdout
class TestJsonOutput:
"""Test JSON serialization."""
def test_json_output(self):
result = run(["create", "--name", "Test", "--age", "20", "--json"])
assert result.returncode == 0
data = json.loads(result.stdout)
assert data["name"] == "Test"
assert data["age"] == 20
class TestValidation:
"""Test field validation."""
def test_missing_name(self):
result = run(["create", "--age", "30"])
assert result.returncode != 0
def test_missing_age(self):
result = run(["create", "--name", "Test"])
assert result.returncode != 0
class TestHelp:
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
assert "create" in result.stdout
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_dataclass/test_data_tool.py (1638 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_dataclass/test_data_tool.rs (3656 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_dataclass/Cargo.toml (2 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 32.7 KB/s
⏱️ Total time: 49ms
| true
|
dataclass
| 63
| 6
|
[
"class_definition",
"decorator",
"multiprocessing"
] | 0.612
| null |
example_datetime
|
test_time_tool.py
|
#!/usr/bin/env python3
"""EXTREME TDD: Tests written FIRST for datetime operations."""
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).parent / "time_tool.py"
import re
SCRIPT = "time_tool.py"
def run(args: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(
["python3", SCRIPT] + args,
capture_output=True,
text=True,
cwd=__file__.rsplit("/", 1)[0],
)
class TestCurrentTime:
"""Test current time display."""
def test_now_default(self):
result = run(["now"])
assert result.returncode == 0
assert re.search(r"\d{4}-\d{2}-\d{2}", result.stdout)
def test_now_iso_format(self):
result = run(["now", "--format", "iso"])
assert result.returncode == 0
assert "T" in result.stdout # ISO format has T separator
def test_now_date_only(self):
result = run(["now", "--format", "date"])
assert result.returncode == 0
assert re.search(r"^\d{4}-\d{2}-\d{2}\n$", result.stdout)
class TestTimestampConversion:
"""Test Unix timestamp conversion."""
def test_timestamp_to_date(self):
result = run(["timestamp", "0"])
assert result.returncode == 0
assert "1970" in result.stdout
def test_timestamp_recent(self):
result = run(["timestamp", "1700000000"])
assert result.returncode == 0
assert "2023" in result.stdout
class TestDateParsing:
"""Test date string parsing."""
def test_parse_iso(self):
result = run(["parse", "2024-01-15"])
assert result.returncode == 0
assert "2024" in result.stdout
def test_parse_with_time(self):
result = run(["parse", "2024-06-15T10:30:00"])
assert result.returncode == 0
class TestDuration:
"""Test duration calculations."""
def test_duration_days(self):
result = run(["duration", "--days", "7"])
assert result.returncode == 0
assert "168" in result.stdout # 7 days = 168 hours
def test_duration_hours(self):
result = run(["duration", "--hours", "48"])
assert result.returncode == 0
assert "2" in result.stdout # 48 hours = 2 days
class TestHelp:
"""Test help output."""
def test_help(self):
result = run(["--help"])
assert result.returncode == 0
assert "now" in result.stdout
assert "timestamp" in result.stdout
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_datetime/test_time_tool.py (2427 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_datetime/test_time_tool.rs (4282 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_datetime/Cargo.toml (2 dependencies)
⏱️ Parse time: 48ms
📊 Throughput: 48.7 KB/s
⏱️ Total time: 48ms
| true
|
datetime
| 89
| 6
|
[
"class_definition",
"multiprocessing"
] | 0.612
| null |
example_datetime
|
time_tool.py
|
#!/usr/bin/env python3
"""
Datetime Example - Time manipulation CLI
Demonstrates:
- datetime.now(), datetime.fromtimestamp()
- strftime/strptime formatting
- timedelta calculations
- ISO format handling
This validates depyler's ability to transpile datetime
to Rust (chrono crate).
"""
import argparse
from datetime import datetime, timedelta
def cmd_now(args):
"""Display current time. Depyler: proven to terminate"""
now = datetime.now()
if args.format == "iso":
print(now.isoformat())
elif args.format == "date":
print(now.strftime("%Y-%m-%d"))
else:
print(now.strftime("%Y-%m-%d %H:%M:%S"))
def cmd_timestamp(args):
"""Convert Unix timestamp. Depyler: proven to terminate"""
dt = datetime.fromtimestamp(int(args.timestamp))
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
def cmd_parse(args):
"""Parse date string. Depyler: proven to terminate"""
if "T" in args.date:
dt = datetime.fromisoformat(args.date)
else:
dt = datetime.strptime(args.date, "%Y-%m-%d")
print(f"Parsed: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
def cmd_duration(args):
"""Calculate duration. Depyler: proven to terminate"""
if args.days:
delta = timedelta(days=args.days)
print(f"{args.days} days = {int(delta.total_seconds() // 3600)} hours")
elif args.hours:
delta = timedelta(hours=args.hours)
print(f"{args.hours} hours = {int(delta.total_seconds() // 86400)} days")
def main():
"""Main entry point. Depyler: proven to terminate"""
parser = argparse.ArgumentParser(description="Time manipulation tool")
subparsers = parser.add_subparsers(dest="command", required=True)
# now subcommand
now_parser = subparsers.add_parser("now", help="Show current time")
now_parser.add_argument("--format", choices=["default", "iso", "date"], default="default")
# timestamp subcommand
ts_parser = subparsers.add_parser("timestamp", help="Convert Unix timestamp")
ts_parser.add_argument("timestamp", help="Unix timestamp")
# parse subcommand
parse_parser = subparsers.add_parser("parse", help="Parse date string")
parse_parser.add_argument("date", help="Date string (YYYY-MM-DD or ISO)")
# duration subcommand
dur_parser = subparsers.add_parser("duration", help="Calculate duration")
dur_parser.add_argument("--days", type=int, help="Number of days")
dur_parser.add_argument("--hours", type=int, help="Number of hours")
args = parser.parse_args()
if args.command == "now":
cmd_now(args)
elif args.command == "timestamp":
cmd_timestamp(args)
elif args.command == "parse":
cmd_parse(args)
elif args.command == "duration":
cmd_duration(args)
if __name__ == "__main__":
main()
| false
|
datetime
| 90
| 0
|
[] | 0
|
Profiling Report
══════════════════════════════════════════════════
Summary
Total estimated instructions: 141
Total estimated allocations: 0
Functions analyzed: 5
Hot Paths
[1] main (33.3% of execution time)
[2] cmd_duration (25.5% of execution time)
[3] cmd_parse (12.8% of execution time)
[4] cmd_now (19.1% of execution time)
Function Metrics
🔥 main 33.3% time | 47 inst | 0 alloc
🔥 cmd_duration 25.5% time | 36 inst |
|
|
example_datetime_basic
|
datetime_basic_cli.py
|
#!/usr/bin/env python3
"""Datetime Basic CLI.
Basic date and time operations.
"""
import argparse
import sys
from datetime import date, datetime, time, timezone
def today() -> date:
"""Get today's date."""
return date.today()
def now() -> datetime:
"""Get current datetime."""
return datetime.now()
def utc_now() -> datetime:
"""Get current UTC datetime."""
return datetime.now(timezone.utc)
def create_date(year: int, month: int, day: int) -> date:
"""Create date from components."""
return date(year, month, day)
def create_time(hour: int, minute: int, second: int = 0, microsecond: int = 0) -> time:
"""Create time from components."""
return time(hour, minute, second, microsecond)
def create_datetime(
year: int, month: int, day: int, hour: int = 0, minute: int = 0, second: int = 0
) -> datetime:
"""Create datetime from components."""
return datetime(year, month, day, hour, minute, second)
def get_year(d: date) -> int:
"""Get year from date."""
return d.year
def get_month(d: date) -> int:
"""Get month from date."""
return d.month
def get_day(d: date) -> int:
"""Get day from date."""
return d.day
def get_hour(t: time) -> int:
"""Get hour from time."""
return t.hour
def get_minute(t: time) -> int:
"""Get minute from time."""
return t.minute
def get_second(t: time) -> int:
"""Get second from time."""
return t.second
def get_microsecond(t: time) -> int:
"""Get microsecond from time."""
return t.microsecond
def weekday(d: date) -> int:
"""Get weekday (Monday=0, Sunday=6)."""
return d.weekday()
def isoweekday(d: date) -> int:
"""Get ISO weekday (Monday=1, Sunday=7)."""
return d.isoweekday()
def isocalendar(d: date) -> tuple[int, int, int]:
"""Get ISO calendar (year, week, weekday)."""
iso = d.isocalendar()
return (iso.year, iso.week, iso.weekday)
def isoformat_date(d: date) -> str:
"""Get ISO format string for date."""
return d.isoformat()
def isoformat_time(t: time) -> str:
"""Get ISO format string for time."""
return t.isoformat()
def isoformat_datetime(dt: datetime) -> str:
"""Get ISO format string for datetime."""
return dt.isoformat()
def from_isoformat_date(s: str) -> date:
"""Parse date from ISO format."""
return date.fromisoformat(s)
def from_isoformat_time(s: str) -> time:
"""Parse time from ISO format."""
return time.fromisoformat(s)
def from_isoformat_datetime(s: str) -> datetime:
"""Parse datetime from ISO format."""
return datetime.fromisoformat(s)
def from_timestamp(ts: float) -> datetime:
"""Create datetime from Unix timestamp."""
return datetime.fromtimestamp(ts)
def from_utc_timestamp(ts: float) -> datetime:
"""Create datetime from UTC Unix timestamp."""
return datetime.fromtimestamp(ts, timezone.utc)
def to_timestamp(dt: datetime) -> float:
"""Get Unix timestamp from datetime."""
return dt.timestamp()
def from_ordinal(n: int) -> date:
"""Create date from ordinal (days since year 1)."""
return date.fromordinal(n)
def to_ordinal(d: date) -> int:
"""Get ordinal (days since year 1) from date."""
return d.toordinal()
def replace_date(
d: date, year: int | None = None, month: int | None = None, day: int | None = None
) -> date:
"""Replace date components."""
return d.replace(
year=year if year is not None else d.year,
month=month if month is not None else d.month,
day=day if day is not None else d.day,
)
def replace_time(
t: time,
hour: int | None = None,
minute: int | None = None,
second: int | None = None,
) -> time:
"""Replace time components."""
return t.replace(
hour=hour if hour is not None else t.hour,
minute=minute if minute is not None else t.minute,
second=second if second is not None else t.second,
)
def date_to_datetime(d: date) -> datetime:
"""Convert date to datetime at midnight."""
return datetime.combine(d, time())
def datetime_date(dt: datetime) -> date:
"""Extract date from datetime."""
return dt.date()
def datetime_time(dt: datetime) -> time:
"""Extract time from datetime."""
return dt.time()
def combine(d: date, t: time) -> datetime:
"""Combine date and time into datetime."""
return datetime.combine(d, t)
def min_date() -> date:
"""Get minimum representable date."""
return date.min
def max_date() -> date:
"""Get maximum representable date."""
return date.max
def min_time() -> time:
"""Get minimum representable time."""
return time.min
def max_time() -> time:
"""Get maximum representable time."""
return time.max
def min_datetime() -> datetime:
"""Get minimum representable datetime."""
return datetime.min
def max_datetime() -> datetime:
"""Get maximum representable datetime."""
return datetime.max
def ctime(dt: datetime) -> str:
"""Get ctime format string."""
return dt.ctime()
def timetuple(dt: datetime) -> tuple:
"""Get time tuple."""
return dt.timetuple()
def is_leap_year(year: int) -> bool:
"""Check if year is a leap year."""
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
def days_in_month(year: int, month: int) -> int:
"""Get number of days in a month."""
if month == 2:
return 29 if is_leap_year(year) else 28
elif month in (4, 6, 9, 11):
return 30
else:
return 31
def days_in_year(year: int) -> int:
"""Get number of days in a year."""
return 366 if is_leap_year(year) else 365
def compare_dates(d1: date, d2: date) -> int:
"""Compare two dates (-1, 0, 1)."""
if d1 < d2:
return -1
elif d1 > d2:
return 1
return 0
def weekday_name(d: date) -> str:
"""Get weekday name."""
names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
return names[d.weekday()]
def month_name(month: int) -> str:
"""Get month name."""
names = [
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
return names[month]
def main() -> int:
parser = argparse.ArgumentParser(description="Datetime basic CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# now
subparsers.add_parser("now", help="Show current datetime")
# today
subparsers.add_parser("today", help="Show today's date")
# date
date_p = subparsers.add_parser("date", help="Create date")
date_p.add_argument("year", type=int, help="Year")
date_p.add_argument("month", type=int, help="Month")
date_p.add_argument("day", type=int, help="Day")
# parse
parse_p = subparsers.add_parser("parse", help="Parse ISO date/datetime")
parse_p.add_argument("value", help="ISO format string")
# timestamp
ts_p = subparsers.add_parser("timestamp", help="Convert timestamp")
ts_p.add_argument("value", type=float, help="Unix timestamp")
# weekday
wd_p = subparsers.add_parser("weekday", help="Get weekday")
wd_p.add_argument("date", help="Date (YYYY-MM-DD)")
# leap
leap_p = subparsers.add_parser("leap", help="Check leap year")
leap_p.add_argument("year", type=int, help="Year")
# days
days_p = subparsers.add_parser("days", help="Days in month/year")
days_p.add_argument("year", type=int, help="Year")
days_p.add_argument("month", type=int, nargs="?", help="Month")
args = parser.parse_args()
if args.command == "now":
print(f"Local: {now()}")
print(f"UTC: {utc_now()}")
print(f"Timestamp: {now().timestamp()}")
elif args.command == "today":
d = today()
print(f"Date: {d}")
print(f"Weekday: {weekday_name(d)}")
print(f"Day of year: {d.timetuple().tm_yday}")
elif args.command == "date":
d = create_date(args.year, args.month, args.day)
print(f"Date: {d}")
print(f"ISO: {d.isoformat()}")
print(f"Weekday: {weekday_name(d)}")
elif args.command == "parse":
if "T" in args.value or " " in args.value:
dt = from_isoformat_datetime(args.value)
print(f"Datetime: {dt}")
print(f"Date: {dt.date()}")
print(f"Time: {dt.time()}")
else:
d = from_isoformat_date(args.value)
print(f"Date: {d}")
print(f"Weekday: {weekday_name(d)}")
elif args.command == "timestamp":
dt = from_timestamp(args.value)
print(f"Local: {dt}")
print(f"UTC: {from_utc_timestamp(args.value)}")
elif args.command == "weekday":
d = from_isoformat_date(args.date)
print(f"Weekday: {weekday(d)} ({weekday_name(d)})")
print(f"ISO weekday: {isoweekday(d)}")
elif args.command == "leap":
if is_leap_year(args.year):
print(f"{args.year} is a leap year")
else:
print(f"{args.year} is not a leap year")
elif args.command == "days":
if args.month:
d = days_in_month(args.year, args.month)
print(f"Days in {month_name(args.month)} {args.year}: {d}")
else:
d = days_in_year(args.year)
print(f"Days in {args.year}: {d}")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
datetime_basic
| 388
| 0
|
[] | 0
|
Type inference hints:
Hint: str for variable 'd' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 't' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'names' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'names' [High] (usage patterns suggest this type)
Type inference hints:
Hint: str for variable 'd' [High] (usage patterns suggest this type)
Hint: str for var
|
|
example_datetime_basic
|
test_datetime_basic_cli.py
|
"""Tests for datetime_basic_cli.py"""
from datetime import date, datetime
from datetime_basic_cli import (
combine,
compare_dates,
create_date,
create_datetime,
create_time,
ctime,
date_to_datetime,
datetime_date,
datetime_time,
days_in_month,
days_in_year,
from_isoformat_date,
from_isoformat_datetime,
from_isoformat_time,
from_ordinal,
from_timestamp,
get_day,
get_hour,
get_microsecond,
get_minute,
get_month,
get_second,
get_year,
is_leap_year,
isocalendar,
isoformat_date,
isoformat_datetime,
isoformat_time,
isoweekday,
max_date,
max_datetime,
max_time,
min_date,
min_datetime,
min_time,
month_name,
now,
replace_date,
replace_time,
timetuple,
to_ordinal,
to_timestamp,
today,
utc_now,
weekday,
weekday_name,
)
class TestToday:
def test_today(self):
d = today()
assert isinstance(d, date)
def test_now(self):
dt = now()
assert isinstance(dt, datetime)
def test_utc_now(self):
dt = utc_now()
assert isinstance(dt, datetime)
class TestCreateDate:
def test_create_date(self):
d = create_date(2024, 6, 15)
assert d.year == 2024
assert d.month == 6
assert d.day == 15
def test_create_date_edge(self):
d = create_date(1, 1, 1)
assert d.year == 1
class TestCreateTime:
def test_create_time(self):
t = create_time(14, 30, 45)
assert t.hour == 14
assert t.minute == 30
assert t.second == 45
def test_create_time_with_micro(self):
t = create_time(12, 0, 0, 123456)
assert t.microsecond == 123456
class TestCreateDatetime:
def test_create_datetime(self):
dt = create_datetime(2024, 6, 15, 14, 30, 45)
assert dt.year == 2024
assert dt.hour == 14
class TestGetters:
def test_get_year(self):
d = create_date(2024, 6, 15)
assert get_year(d) == 2024
def test_get_month(self):
d = create_date(2024, 6, 15)
assert get_month(d) == 6
def test_get_day(self):
d = create_date(2024, 6, 15)
assert get_day(d) == 15
def test_get_hour(self):
t = create_time(14, 30, 45)
assert get_hour(t) == 14
def test_get_minute(self):
t = create_time(14, 30, 45)
assert get_minute(t) == 30
def test_get_second(self):
t = create_time(14, 30, 45)
assert get_second(t) == 45
def test_get_microsecond(self):
t = create_time(14, 30, 45, 123)
assert get_microsecond(t) == 123
class TestWeekday:
def test_weekday(self):
d = create_date(2024, 6, 17) # Monday
assert weekday(d) == 0
def test_isoweekday(self):
d = create_date(2024, 6, 17) # Monday
assert isoweekday(d) == 1
def test_weekday_sunday(self):
d = create_date(2024, 6, 16) # Sunday
assert weekday(d) == 6
assert isoweekday(d) == 7
class TestISOCalendar:
def test_isocalendar(self):
d = create_date(2024, 1, 1)
year, week, day = isocalendar(d)
assert year == 2024
assert week == 1
assert day == 1
class TestISOFormat:
def test_isoformat_date(self):
d = create_date(2024, 6, 15)
assert isoformat_date(d) == "2024-06-15"
def test_isoformat_time(self):
t = create_time(14, 30, 45)
assert isoformat_time(t) == "14:30:45"
def test_isoformat_datetime(self):
dt = create_datetime(2024, 6, 15, 14, 30, 45)
assert isoformat_datetime(dt) == "2024-06-15T14:30:45"
class TestFromISOFormat:
def test_from_isoformat_date(self):
d = from_isoformat_date("2024-06-15")
assert d == create_date(2024, 6, 15)
def test_from_isoformat_time(self):
t = from_isoformat_time("14:30:45")
assert t == create_time(14, 30, 45)
def test_from_isoformat_datetime(self):
dt = from_isoformat_datetime("2024-06-15T14:30:45")
assert dt == create_datetime(2024, 6, 15, 14, 30, 45)
class TestTimestamp:
def test_from_timestamp(self):
dt = from_timestamp(0)
# Will be epoch in local timezone
assert dt.year >= 1969 # Could be 1969 or 1970 depending on timezone
def test_to_timestamp(self):
dt = create_datetime(1970, 1, 1, 0, 0, 0)
ts = to_timestamp(dt)
assert isinstance(ts, float)
class TestOrdinal:
def test_from_ordinal(self):
d = from_ordinal(1)
assert d == create_date(1, 1, 1)
def test_to_ordinal(self):
d = create_date(1, 1, 1)
assert to_ordinal(d) == 1
class TestReplace:
def test_replace_date(self):
d = create_date(2024, 6, 15)
d2 = replace_date(d, year=2025)
assert d2 == create_date(2025, 6, 15)
def test_replace_date_month(self):
d = create_date(2024, 6, 15)
d2 = replace_date(d, month=12)
assert d2 == create_date(2024, 12, 15)
def test_replace_time(self):
t = create_time(14, 30, 45)
t2 = replace_time(t, hour=10)
assert t2 == create_time(10, 30, 45)
class TestCombine:
def test_date_to_datetime(self):
d = create_date(2024, 6, 15)
dt = date_to_datetime(d)
assert dt.year == 2024
assert dt.hour == 0
def test_datetime_date(self):
dt = create_datetime(2024, 6, 15, 14, 30)
d = datetime_date(dt)
assert d == create_date(2024, 6, 15)
def test_datetime_time(self):
dt = create_datetime(2024, 6, 15, 14, 30, 45)
t = datetime_time(dt)
assert t == create_time(14, 30, 45)
def test_combine(self):
d = create_date(2024, 6, 15)
t = create_time(14, 30, 45)
dt = combine(d, t)
assert dt == create_datetime(2024, 6, 15, 14, 30, 45)
class TestMinMax:
def test_min_max_date(self):
assert min_date() < max_date()
def test_min_max_time(self):
assert min_time() < max_time()
def test_min_max_datetime(self):
assert min_datetime() < max_datetime()
class TestCtime:
def test_ctime(self):
dt = create_datetime(2024, 6, 15, 14, 30, 45)
c = ctime(dt)
assert "2024" in c
assert "14:30:45" in c
class TestTimetuple:
def test_timetuple(self):
dt = create_datetime(2024, 6, 15, 14, 30, 45)
tt = timetuple(dt)
assert tt.tm_year == 2024
assert tt.tm_mon == 6
class TestLeapYear:
def test_leap_year_2024(self):
assert is_leap_year(2024) is True
def test_not_leap_year_2023(self):
assert is_leap_year(2023) is False
def test_not_leap_year_1900(self):
assert is_leap_year(1900) is False
def test_leap_year_2000(self):
assert is_leap_year(2000) is True
class TestDaysIn:
def test_days_in_january(self):
assert days_in_month(2024, 1) == 31
def test_days_in_february_leap(self):
assert days_in_month(2024, 2) == 29
def test_days_in_february_non_leap(self):
assert days_in_month(2023, 2) == 28
def test_days_in_april(self):
assert days_in_month(2024, 4) == 30
def test_days_in_year_leap(self):
assert days_in_year(2024) == 366
def test_days_in_year_non_leap(self):
assert days_in_year(2023) == 365
class TestCompare:
def test_compare_less(self):
d1 = create_date(2024, 1, 1)
d2 = create_date(2024, 12, 31)
assert compare_dates(d1, d2) == -1
def test_compare_greater(self):
d1 = create_date(2024, 12, 31)
d2 = create_date(2024, 1, 1)
assert compare_dates(d1, d2) == 1
def test_compare_equal(self):
d1 = create_date(2024, 6, 15)
d2 = create_date(2024, 6, 15)
assert compare_dates(d1, d2) == 0
class TestNames:
def test_weekday_name(self):
d = create_date(2024, 6, 17) # Monday
assert weekday_name(d) == "Monday"
def test_month_name(self):
assert month_name(1) == "January"
assert month_name(12) == "December"
class TestEdgeCases:
def test_midnight(self):
t = create_time(0, 0, 0)
assert t.hour == 0
assert t.minute == 0
def test_end_of_day(self):
t = create_time(23, 59, 59)
assert t.hour == 23
def test_year_1(self):
d = create_date(1, 1, 1)
assert d.year == 1
def test_far_future(self):
d = create_date(9999, 12, 31)
assert d.year == 9999
|
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_datetime_basic/test_datetime_basic_cli.py (8590 bytes)
📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_datetime_basic/test_datetime_basic_cli.rs (23193 bytes)
📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_datetime_basic/Cargo.toml (1 dependencies)
⏱️ Parse time: 53ms
📊 Throughput: 156.7 KB/s
⏱️ Total time: 53ms
| true
|
datetime_basic
| 349
| 6
|
[
"class_definition"
] | 0.612
| null |
example_datetime_calendar
|
datetime_calendar_cli.py
|
#!/usr/bin/env python3
"""Datetime Calendar CLI.
Calendar module operations.
"""
import argparse
import calendar
import sys
from datetime import date
def is_leap(year: int) -> bool:
"""Check if year is a leap year."""
return calendar.isleap(year)
def leap_days(y1: int, y2: int) -> int:
"""Count leap years between y1 and y2."""
return calendar.leapdays(y1, y2)
def weekday(year: int, month: int, day: int) -> int:
"""Get weekday for date (Monday=0)."""
return calendar.weekday(year, month, day)
def monthrange(year: int, month: int) -> tuple[int, int]:
"""Get first weekday and days in month."""
return calendar.monthrange(year, month)
def days_in_month(year: int, month: int) -> int:
"""Get number of days in month."""
_, days = calendar.monthrange(year, month)
return days
def first_weekday_of_month(year: int, month: int) -> int:
"""Get first weekday of month (Monday=0)."""
first, _ = calendar.monthrange(year, month)
return first
def month_calendar(year: int, month: int) -> list[list[int]]:
"""Get calendar grid for month."""
return calendar.monthcalendar(year, month)
def text_calendar_month(year: int, month: int, w: int = 2, lines: int = 1) -> str:
"""Get text calendar for month."""
return calendar.month(year, month, w, lines)
def text_calendar_year(year: int, w: int = 2, lines: int = 1, c: int = 6, m: int = 3) -> str:
"""Get text calendar for year."""
return calendar.calendar(year, w, lines, c, m)
def month_name(month: int) -> str:
"""Get month name (1-12)."""
return calendar.month_name[month]
def month_abbr(month: int) -> str:
"""Get abbreviated month name."""
return calendar.month_abbr[month]
def day_name(weekday: int) -> str:
"""Get day name (0=Monday)."""
return calendar.day_name[weekday]
def day_abbr(weekday: int) -> str:
"""Get abbreviated day name."""
return calendar.day_abbr[weekday]
def all_month_names() -> list[str]:
"""Get all month names."""
return list(calendar.month_name)[1:] # Skip empty first element
def all_day_names() -> list[str]:
"""Get all day names."""
return list(calendar.day_name)
def iter_month_days(year: int, month: int) -> list[tuple[int, int]]:
"""Iterate over days in month as (weekday, day) tuples."""
c = calendar.Calendar()
return [(wd, day) for day, wd in c.itermonthdays2(year, month) if day != 0]
def iter_month_dates(year: int, month: int) -> list[date]:
"""Iterate over dates in month."""
c = calendar.Calendar()
return [date(year, month, day) for day, _ in c.itermonthdays2(year, month) if day != 0]
def weeks_in_month(year: int, month: int) -> int:
"""Get number of weeks in month."""
return len(calendar.monthcalendar(year, month))
def get_week(year: int, month: int, week: int) -> list[int]:
"""Get specific week of month (0-indexed)."""
cal = calendar.monthcalendar(year, month)
if 0 <= week < len(cal):
return cal[week]
return []
def nth_weekday_of_month(year: int, month: int, weekday: int, n: int) -> date | None:
"""Get nth occurrence of weekday in month (1-indexed)."""
c = calendar.Calendar()
days = [day for day, wd in c.itermonthdays2(year, month) if day != 0 and wd == weekday]
if 1 <= n <= len(days):
return date(year, month, days[n - 1])
return None
def last_weekday_of_month(year: int, month: int, weekday: int) -> date | None:
"""Get last occurrence of weekday in month."""
c = calendar.Calendar()
days = [day for day, wd in c.itermonthdays2(year, month) if day != 0 and wd == weekday]
if days:
return date(year, month, days[-1])
return None
def timegm(t: tuple) -> int:
"""Convert time tuple to Unix timestamp (UTC)."""
return calendar.timegm(t)
def set_first_weekday(weekday: int) -> None:
"""Set first day of week (0=Monday, 6=Sunday)."""
calendar.setfirstweekday(weekday)
def get_first_weekday() -> int:
"""Get first day of week setting."""
return calendar.firstweekday()
def html_calendar_month(year: int, month: int) -> str:
"""Get HTML calendar for month."""
hc = calendar.HTMLCalendar()
return hc.formatmonth(year, month)
def html_calendar_year(year: int) -> str:
"""Get HTML calendar for year."""
hc = calendar.HTMLCalendar()
return hc.formatyear(year)
def year_calendar(year: int) -> list[list[list[list[int]]]]:
"""Get calendar data for year."""
c = calendar.Calendar()
return [c.monthdayscalendar(year, month) for month in range(1, 13)]
def weekdays_in_month(year: int, month: int, weekday: int) -> list[int]:
"""Get all occurrences of a weekday in month."""
c = calendar.Calendar()
return [day for day, wd in c.itermonthdays2(year, month) if day != 0 and wd == weekday]
def count_weekdays_in_month(year: int, month: int, weekday: int) -> int:
"""Count occurrences of weekday in month."""
return len(weekdays_in_month(year, month, weekday))
def business_days_in_month(year: int, month: int) -> int:
"""Count business days (Mon-Fri) in month."""
c = calendar.Calendar()
count = 0
for day, wd in c.itermonthdays2(year, month):
if day != 0 and wd < 5:
count += 1
return count
def weekend_days_in_month(year: int, month: int) -> int:
"""Count weekend days in month."""
c = calendar.Calendar()
count = 0
for day, wd in c.itermonthdays2(year, month):
if day != 0 and wd >= 5:
count += 1
return count
def is_last_day_of_month(d: date) -> bool:
"""Check if date is last day of month."""
return d.day == days_in_month(d.year, d.month)
def is_first_day_of_month(d: date) -> bool:
"""Check if date is first day of month."""
return d.day == 1
def next_month(year: int, month: int) -> tuple[int, int]:
"""Get next month as (year, month)."""
if month == 12:
return (year + 1, 1)
return (year, month + 1)
def prev_month(year: int, month: int) -> tuple[int, int]:
"""Get previous month as (year, month)."""
if month == 1:
return (year - 1, 12)
return (year, month - 1)
def quarter_of_month(month: int) -> int:
"""Get quarter (1-4) for month."""
return (month - 1) // 3 + 1
def months_in_quarter(quarter: int) -> list[int]:
"""Get months in quarter (1-4)."""
start = (quarter - 1) * 3 + 1
return [start, start + 1, start + 2]
def main() -> int:
parser = argparse.ArgumentParser(description="Datetime calendar CLI")
subparsers = parser.add_subparsers(dest="command", help="Commands")
# month
month_p = subparsers.add_parser("month", help="Show month calendar")
month_p.add_argument("year", type=int, help="Year")
month_p.add_argument("month", type=int, help="Month")
# year
year_p = subparsers.add_parser("year", help="Show year calendar")
year_p.add_argument("year", type=int, help="Year")
# leap
leap_p = subparsers.add_parser("leap", help="Check leap year")
leap_p.add_argument("year", type=int, help="Year")
# info
info_p = subparsers.add_parser("info", help="Month info")
info_p.add_argument("year", type=int, help="Year")
info_p.add_argument("month", type=int, help="Month")
# nth
nth_p = subparsers.add_parser("nth", help="Find nth weekday")
nth_p.add_argument("year", type=int, help="Year")
nth_p.add_argument("month", type=int, help="Month")
nth_p.add_argument("weekday", type=int, help="Weekday (0=Mon)")
nth_p.add_argument("n", type=int, help="Which occurrence")
args = parser.parse_args()
if args.command == "month":
print(text_calendar_month(args.year, args.month))
elif args.command == "year":
print(text_calendar_year(args.year))
elif args.command == "leap":
if is_leap(args.year):
print(f"{args.year} is a leap year")
else:
print(f"{args.year} is not a leap year")
elif args.command == "info":
name = month_name(args.month)
days = days_in_month(args.year, args.month)
weeks = weeks_in_month(args.year, args.month)
biz = business_days_in_month(args.year, args.month)
weekend = weekend_days_in_month(args.year, args.month)
print(f"Month: {name} {args.year}")
print(f"Days: {days}")
print(f"Weeks: {weeks}")
print(f"Business days: {biz}")
print(f"Weekend days: {weekend}")
elif args.command == "nth":
d = nth_weekday_of_month(args.year, args.month, args.weekday, args.n)
if d:
day_n = day_name(args.weekday)
print(
f"The {args.n}{'st' if args.n == 1 else 'nd' if args.n == 2 else 'rd' if args.n == 3 else 'th'} {day_n} is {d}"
)
else:
print("Not found")
else:
parser.print_help()
return 0
if __name__ == "__main__":
sys.exit(main())
| false
|
datetime_calendar
| 304
| 0
|
[] | 0
|
Type inference hints:
Hint: list[Any] for variable 'cal' [High] (usage patterns suggest this type)
Type inference hints:
Hint: int for variable 'n' [Medium] (usage patterns suggest this type)
Hint: list[Any] for variable 'days' [High] (usage patterns suggest this type)
Type inference hints:
Hint: list[Any] for variable 'days' [High] (usage patterns suggest this type)
Type inference hints:
Hint: int for variable 'count' [Medium] (usage patterns suggest this type)
Type inference hints:
Hint: i
|
|
example_datetime_calendar
|
test_datetime_calendar_cli.py
|
"""Tests for datetime_calendar_cli.py"""
from datetime import date
from datetime_calendar_cli import (
all_day_names,
all_month_names,
business_days_in_month,
count_weekdays_in_month,
day_abbr,
day_name,
days_in_month,
first_weekday_of_month,
get_first_weekday,
get_week,
html_calendar_month,
is_first_day_of_month,
is_last_day_of_month,
is_leap,
iter_month_dates,
iter_month_days,
last_weekday_of_month,
leap_days,
month_abbr,
month_calendar,
month_name,
monthrange,
months_in_quarter,
next_month,
nth_weekday_of_month,
prev_month,
quarter_of_month,
text_calendar_month,
text_calendar_year,
weekday,
weekdays_in_month,
weekend_days_in_month,
weeks_in_month,
year_calendar,
)
class TestLeapYear:
def test_is_leap_2024(self):
assert is_leap(2024) is True
def test_is_leap_2023(self):
assert is_leap(2023) is False
def test_is_leap_1900(self):
assert is_leap(1900) is False
def test_is_leap_2000(self):
assert is_leap(2000) is True
def test_leap_days(self):
count = leap_days(2000, 2024)
assert count > 0
class TestWeekday:
def test_weekday_known(self):
# June 15, 2024 is Saturday (5)
assert weekday(2024, 6, 15) == 5
def test_weekday_monday(self):
# June 17, 2024 is Monday (0)
assert weekday(2024, 6, 17) == 0
class TestMonthrange:
def test_monthrange(self):
first, days = monthrange(2024, 6)
assert days == 30
def test_days_in_month_february_leap(self):
assert days_in_month(2024, 2) == 29
def test_days_in_month_february_nonleap(self):
assert days_in_month(2023, 2) == 28
def test_first_weekday_of_month(self):
first = first_weekday_of_month(2024, 6)
assert 0 <= first <= 6
class TestMonthCalendar:
def test_month_calendar(self):
cal = month_calendar(2024, 6)
assert len(cal) >= 4
assert len(cal[0]) == 7
def test_text_calendar_month(self):
text = text_calendar_month(2024, 6)
assert "June" in text
assert "2024" in text
def test_text_calendar_year(self):
text = text_calendar_year(2024)
assert "2024" in text
assert "January" in text
class TestNames:
def test_month_name(self):
assert month_name(1) == "January"
assert month_name(12) == "December"
def test_month_abbr(self):
assert month_abbr(1) == "Jan"
assert month_abbr(12) == "Dec"
def test_day_name(self):
assert day_name(0) == "Monday"
assert day_name(6) == "Sunday"
def test_day_abbr(self):
assert day_abbr(0) == "Mon"
assert day_abbr(6) == "Sun"
def test_all_month_names(self):
names = all_month_names()
assert len(names) == 12
def test_all_day_names(self):
names = all_day_names()
assert len(names) == 7
class TestIterMonth:
def test_iter_month_days(self):
days = iter_month_days(2024, 6)
assert len(days) == 30
def test_iter_month_dates(self):
dates = iter_month_dates(2024, 6)
assert len(dates) == 30
assert all(isinstance(d, date) for d in dates)
class TestWeeksInMonth:
def test_weeks_in_month(self):
weeks = weeks_in_month(2024, 6)
assert weeks >= 4
assert weeks <= 6
def test_get_week(self):
week = get_week(2024, 6, 0)
assert len(week) == 7
class TestNthWeekday:
def test_nth_weekday_first_monday(self):
d = nth_weekday_of_month(2024, 6, 0, 1) # First Monday
assert d is not None
assert d.weekday() == 0
def test_nth_weekday_second_friday(self):
d = nth_weekday_of_month(2024, 6, 4, 2) # Second Friday
assert d is not None
assert d.weekday() == 4
def test_nth_weekday_out_of_range(self):
d = nth_weekday_of_month(2024, 6, 0, 10) # 10th Monday (doesn't exist)
assert d is None
def test_last_weekday_of_month(self):
d = last_weekday_of_month(2024, 6, 0) # Last Monday
assert d is not None
assert d.weekday() == 0
assert d.month == 6
class TestWeekdaysInMonth:
def test_weekdays_in_month(self):
mondays = weekdays_in_month(2024, 6, 0)
assert len(mondays) > 0
assert all(isinstance(day, int) for day in mondays)
def test_count_weekdays_in_month(self):
count = count_weekdays_in_month(2024, 6, 0)
assert count >= 4
class TestBusinessDays:
def test_business_days_in_month(self):
biz = business_days_in_month(2024, 6)
assert 20 <= biz <= 23
def test_weekend_days_in_month(self):
weekend = weekend_days_in_month(2024, 6)
total = days_in_month(2024, 6)
biz = business_days_in_month(2024, 6)
assert weekend == total - biz
class TestDayChecks:
def test_is_last_day_of_month(self):
assert is_last_day_of_month(date(2024, 6, 30)) is True
assert is_last_day_of_month(date(2024, 6, 29)) is False
def test_is_first_day_of_month(self):
assert is_first_day_of_month(date(2024, 6, 1)) is True
assert is_first_day_of_month(date(2024, 6, 2)) is False
class TestMonthNavigation:
def test_next_month(self):
assert next_month(2024, 6) == (2024, 7)
assert next_month(2024, 12) == (2025, 1)
def test_prev_month(self):
assert prev_month(2024, 6) == (2024, 5)
assert prev_month(2024, 1) == (2023, 12)
class TestQuarter:
def test_quarter_of_month(self):
assert quarter_of_month(1) == 1
assert quarter_of_month(3) == 1
assert quarter_of_month(4) == 2
assert quarter_of_month(7) == 3
assert quarter_of_month(10) == 4
assert quarter_of_month(12) == 4
def test_months_in_quarter(self):
assert months_in_quarter(1) == [1, 2, 3]
assert months_in_quarter(2) == [4, 5, 6]
assert months_in_quarter(3) == [7, 8, 9]
assert months_in_quarter(4) == [10, 11, 12]
class TestHTML:
def test_html_calendar_month(self):
html = html_calendar_month(2024, 6)
assert "<table" in html
assert "</table>" in html
class TestYearCalendar:
def test_year_calendar(self):
cal = year_calendar(2024)
assert len(cal) == 12
class TestFirstWeekday:
def test_get_first_weekday(self):
wd = get_first_weekday()
assert 0 <= wd <= 6
class TestEdgeCases:
def test_february_leap_year(self):
days = days_in_month(2024, 2)
assert days == 29
def test_february_non_leap(self):
days = days_in_month(2023, 2)
assert days == 28
def test_december_to_january(self):
y, m = next_month(2024, 12)
assert y == 2025
assert m == 1
| false
|
datetime_calendar
| 264
| 0
|
[
"class_definition"
] | 0.612
|
Error: Expression type not yet supported: GeneratorExp { element: Call { func: "isinstance", args: [Var("d"), Var("date")], kwargs: [] }, generators: [HirComprehension { target: "d", iter: Var("dates"), conditions: [] }] }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.