Skip to content

⚡️ Speed up function determine_dependency_manager by 15% in PR #1195 (liniting_issues)#1196

Merged
KRRT7 merged 1 commit intoliniting_issuesfrom
codeflash/optimize-pr1195-2026-01-29T17.08.06
Jan 29, 2026
Merged

⚡️ Speed up function determine_dependency_manager by 15% in PR #1195 (liniting_issues)#1196
KRRT7 merged 1 commit intoliniting_issuesfrom
codeflash/optimize-pr1195-2026-01-29T17.08.06

Conversation

@codeflash-ai
Copy link
Contributor

@codeflash-ai codeflash-ai bot commented Jan 29, 2026

⚡️ This pull request contains optimizations for PR #1195

If you approve this dependent PR, these changes will be merged into the original PR branch liniting_issues.

This PR will be automatically closed if the original PR is merged.


📄 15% (0.15x) speedup for determine_dependency_manager in codeflash/cli_cmds/cmd_init.py

⏱️ Runtime : 2.33 milliseconds 2.03 milliseconds (best of 109 runs)

📝 Explanation and details

The optimization achieves a 14% runtime improvement by caching Path.cwd() once at the start of the function instead of calling it twice during the lock file checks.

Key optimization:

  • Single Path.cwd() call: The original code called Path.cwd() twice (lines checking poetry.lock and uv.lock), while the optimized version calls it once and reuses the result via the cwd variable.

Why this matters:
Path.cwd() is a relatively expensive operation that involves system calls to retrieve the current working directory. Line profiler results show:

  • Original: First lock check took 3.59ms (57.2% of total time), second took 2.26ms (36% of total time)
  • Optimized: The single cwd = Path.cwd() took 1.79ms (32.7%), with subsequent checks using the cached path taking 2.05ms (37.4%) and 1.22ms (22.1%)

The net effect is reducing filesystem/system call overhead from ~5.85ms to ~5.05ms across the lock file checks.

Performance characteristics:
Based on the annotated tests, this optimization provides consistent 11-19% speedups across nearly all test cases:

  • Best speedup (19.2%): Test with uv-prefixed keys like "uvApp"
  • Strong improvements (16-17%): Tests checking lock files or no tool sections
  • Consistent gains (11-15%): Tests with tool section parsing

The optimization is particularly beneficial when determine_dependency_manager is called frequently, as indicated by the function_references showing it's invoked during GitHub Actions workflow generation (both in generate_dynamic_workflow_content and customize_codeflash_yaml_content). Since these are CI/CD initialization paths that may be called multiple times during repository setup, the cumulative savings become meaningful.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 47 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
from __future__ import annotations

from enum import Enum

# imports
from codeflash.cli_cmds.cmd_init import determine_dependency_manager


# Provide a real DependencyManager enum used by the function under test.
# This mirrors what the original code expects to reference.
class DependencyManager(Enum):
    POETRY = "poetry"
    UV = "uv"
    PIP = "pip"
    UNKNOWN = "unknown"


def test_no_tool_and_no_lock_files_returns_pip(tmp_path, monkeypatch):
    # When there is no "tool" key in pyproject_data and no lock files in cwd,
    # the function should decide on PIP.
    monkeypatch.chdir(tmp_path)  # ensure we are in an isolated directory with no lock files
    codeflash_output = determine_dependency_manager({})
    result = codeflash_output  # 45.0μs -> 38.7μs (16.3% faster)


def test_poetry_lock_file_takes_precedence_over_pyproject(tmp_path, monkeypatch):
    # If poetry.lock exists in cwd, the function should immediately return POETRY,
    # regardless of pyproject contents.
    monkeypatch.chdir(tmp_path)
    # create poetry.lock file to simulate Poetry-managed project
    (tmp_path / "poetry.lock").write_text("lock content")
    # Even if pyproject_data suggests something else, lock file should win
    codeflash_output = determine_dependency_manager({"tool": {"pip": {}}})
    result = codeflash_output  # 24.2μs -> 24.4μs (0.784% slower)


def test_uv_lock_file_when_no_poetry_lock(tmp_path, monkeypatch):
    # If uv.lock exists but poetry.lock does not, function should return UV.
    monkeypatch.chdir(tmp_path)
    (tmp_path / "uv.lock").write_text("uv lock content")
    codeflash_output = determine_dependency_manager({})
    result = codeflash_output  # 43.9μs -> 37.6μs (16.9% faster)


def test_tool_section_poetry_key_detected():
    # If pyproject_data has tool section with a "poetry" key, return POETRY.
    pyproject = {"tool": {"poetry": {"name": "example"}}}
    codeflash_output = determine_dependency_manager(pyproject)
    result = codeflash_output  # 41.4μs -> 36.3μs (14.0% faster)


def test_tool_section_uv_prefix_detected():
    # Any tool key that starts with "uv" should indicate the UV manager.
    pyproject = {"tool": {"uvicorn": {"some": "value"}}}
    codeflash_output = determine_dependency_manager(pyproject)
    result = codeflash_output  # 40.1μs -> 36.0μs (11.5% faster)


def test_tool_section_pip_or_setuptools_markers():
    # If "pip" is in tool section, return PIP.
    pyproject1 = {"tool": {"pip": {"key": "value"}}}
    codeflash_output = determine_dependency_manager(pyproject1)  # 38.6μs -> 34.1μs (13.1% faster)

    # If "setuptools" is in tool section, return PIP.
    pyproject2 = {"tool": {"setuptools": {"cfg": True}}}
    codeflash_output = determine_dependency_manager(pyproject2)  # 23.8μs -> 20.8μs (14.4% faster)


def test_tool_section_unknown_marker():
    # If tool section exists but contains none of the recognized markers,
    # the function should return UNKNOWN.
    pyproject = {"tool": {"some_other_tool": {}}}
    codeflash_output = determine_dependency_manager(pyproject)  # 37.5μs -> 33.6μs (11.8% faster)


def test_both_lock_files_poetry_takes_precedence(tmp_path, monkeypatch):
    # When both poetry.lock and uv.lock are present, poetry.lock check comes first
    # so function should return POETRY.
    monkeypatch.chdir(tmp_path)
    (tmp_path / "poetry.lock").write_text("poetry")
    (tmp_path / "uv.lock").write_text("uv")
    codeflash_output = determine_dependency_manager({})  # 23.1μs -> 23.3μs (0.860% slower)


def test_tool_key_case_sensitivity_is_strict():
    # Keys are case-sensitive; "Poetry" should not match "poetry".
    pyproject = {"tool": {"Poetry": {"name": "caps"}}}
    codeflash_output = determine_dependency_manager(pyproject)  # 39.8μs -> 33.7μs (17.8% faster)


def test_tool_keys_that_start_with_uv_but_are_many_variants():
    # Ensure startswith matching works for different uv-prefixed keys (uv, uv_, uvApp)
    pyproject1 = {"tool": {"uv": {}}}
    pyproject2 = {"tool": {"uv_thing": {}}}
    pyproject3 = {"tool": {"uvApp": {}}}
    codeflash_output = determine_dependency_manager(pyproject1)  # 41.3μs -> 36.6μs (12.7% faster)
    codeflash_output = determine_dependency_manager(pyproject2)  # 23.8μs -> 21.1μs (12.5% faster)
    codeflash_output = determine_dependency_manager(pyproject3)  # 21.1μs -> 17.7μs (19.2% faster)


def test_large_tool_section_without_matches_is_unknown():
    # Build a large tool dict near the specified upper bound (under 1000 entries)
    # with none of the recognized markers present. This checks the function's
    # scalability for membership and startswith operations.
    large_tool = {f"tool_key_{i}": {"i": i} for i in range(900)}  # 900 entries < 1000
    pyproject = {"tool": large_tool}
    # No lock files in cwd, so determination relies solely on pyproject content.
    codeflash_output = determine_dependency_manager(pyproject)  # 41.0μs -> 35.7μs (14.9% faster)


def test_large_tool_section_with_one_uv_prefix_among_many():
    # Place a single uv-prefixed key among many others to ensure detection still works.
    large_tool = {f"tool_key_{i}": {} for i in range(899)}
    large_tool["uv_special"] = {"marker": True}
    pyproject = {"tool": large_tool}
    codeflash_output = determine_dependency_manager(pyproject)  # 40.2μs -> 34.9μs (15.3% faster)


# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
import tempfile
from enum import Enum
from pathlib import Path
from unittest.mock import patch

from codeflash.cli_cmds.cmd_init import determine_dependency_manager


# We need to understand the DependencyManager enum
# Based on the function, it returns DependencyManager with values:
# POETRY, UV, PIP, UNKNOWN
class DependencyManager(Enum):
    """Enum for dependency managers."""

    POETRY = "poetry"
    UV = "uv"
    PIP = "pip"
    UNKNOWN = "unknown"


class TestDetermineDependencyManagerBasic:
    """Basic test cases for determine_dependency_manager function."""

    def test_poetry_lock_file_exists(self):
        """Test that POETRY is returned when poetry.lock exists in current directory."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create poetry.lock file
            poetry_lock_path = Path(tmpdir) / "poetry.lock"
            poetry_lock_path.touch()

            # Call function with empty pyproject_data
            codeflash_output = determine_dependency_manager({})
            result = codeflash_output

    def test_uv_lock_file_exists(self):
        """Test that UV is returned when uv.lock exists in current directory."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create uv.lock file
            uv_lock_path = Path(tmpdir) / "uv.lock"
            uv_lock_path.touch()

            # Call function with empty pyproject_data
            codeflash_output = determine_dependency_manager({})
            result = codeflash_output

    def test_poetry_in_tool_section(self):
        """Test that POETRY is returned when poetry is in tool section."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with poetry in tool section
            pyproject_data = {"tool": {"poetry": {"name": "my-project", "version": "0.1.0"}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_uv_in_tool_section(self):
        """Test that UV is returned when uv key is in tool section."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with uv in tool section
            pyproject_data = {"tool": {"uv": {"sources": []}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_pip_when_no_tool_section(self):
        """Test that PIP is returned when tool section is missing."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create minimal pyproject_data without tool section
            pyproject_data = {"build-system": {"requires": ["setuptools"]}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_pip_when_pip_in_tool_section(self):
        """Test that PIP is returned when pip is in tool section."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with pip in tool section
            pyproject_data = {"tool": {"pip": {"index-url": "https://pypi.org/simple"}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_pip_when_setuptools_in_tool_section(self):
        """Test that PIP is returned when setuptools is in tool section."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with setuptools in tool section
            pyproject_data = {"tool": {"setuptools": {"packages": ["mypackage"]}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_unknown_when_tool_section_has_unknown_keys(self):
        """Test that UNKNOWN is returned when tool section has only unknown keys."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with unknown tool keys
            pyproject_data = {"tool": {"mypy": {"python_version": "3.9"}, "black": {"line-length": 88}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_empty_pyproject_data(self):
        """Test that PIP is returned when pyproject_data is empty."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Call function with empty dict
            codeflash_output = determine_dependency_manager({})
            result = codeflash_output


class TestDetermineDependencyManagerEdgeCases:
    """Edge case test cases for determine_dependency_manager function."""

    def test_poetry_lock_takes_precedence_over_tool_section(self):
        """Test that poetry.lock file takes precedence over tool section."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create poetry.lock file
            poetry_lock_path = Path(tmpdir) / "poetry.lock"
            poetry_lock_path.touch()

            # Create pyproject_data with uv in tool section
            pyproject_data = {"tool": {"uv": {}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_uv_lock_takes_precedence_over_tool_section(self):
        """Test that uv.lock file takes precedence over tool section."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create uv.lock file
            uv_lock_path = Path(tmpdir) / "uv.lock"
            uv_lock_path.touch()

            # Create pyproject_data with poetry in tool section
            pyproject_data = {"tool": {"poetry": {}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_poetry_lock_takes_precedence_over_uv_lock(self):
        """Test that poetry.lock takes precedence when both lock files exist."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create both lock files
            poetry_lock_path = Path(tmpdir) / "poetry.lock"
            poetry_lock_path.touch()
            uv_lock_path = Path(tmpdir) / "uv.lock"
            uv_lock_path.touch()

            # Call function
            codeflash_output = determine_dependency_manager({})
            result = codeflash_output

    def test_uv_with_prefix_variations(self):
        """Test that UV is detected with various key prefixes starting with 'uv'."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Test with uv-specific key variations
            test_cases = [{"tool": {"uv": {}}}, {"tool": {"uv-config": {}}}, {"tool": {"uvxyz": {}}}]

            for pyproject_data in test_cases:
                codeflash_output = determine_dependency_manager(pyproject_data)
                result = codeflash_output

    def test_poetry_in_tool_section_with_other_tools(self):
        """Test that POETRY is returned when poetry is present with other tools."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with poetry and other tools
            pyproject_data = {"tool": {"poetry": {"name": "my-project"}, "black": {"line-length": 88}, "mypy": {}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_uv_in_tool_section_with_other_tools(self):
        """Test that UV is returned when uv is present with other tools."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with uv and other tools
            pyproject_data = {"tool": {"black": {"line-length": 88}, "uv": {"sources": []}, "mypy": {}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_pip_takes_precedence_over_unknown(self):
        """Test that PIP is returned when pip is present, taking precedence over unknown tools."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with pip and unknown tools
            pyproject_data = {
                "tool": {"black": {"line-length": 88}, "pip": {"index-url": "https://pypi.org"}, "mypy": {}}
            }

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_setuptools_takes_precedence_over_unknown(self):
        """Test that PIP is returned when setuptools is present, taking precedence over unknown tools."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with setuptools and unknown tools
            pyproject_data = {
                "tool": {"black": {"line-length": 88}, "setuptools": {"packages": ["mypackage"]}, "mypy": {}}
            }

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_empty_tool_section(self):
        """Test that PIP is returned when tool section exists but is empty."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with empty tool section
            pyproject_data = {"tool": {}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_tool_section_with_nested_structures(self):
        """Test with deeply nested tool sections."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with deeply nested structures
            pyproject_data = {
                "tool": {
                    "poetry": {
                        "dependencies": {"python": "^3.9", "requests": {"version": "^2.28.0", "extras": ["security"]}},
                        "group": {"dev": {"dependencies": {"pytest": "^7.0"}}},
                    }
                }
            }

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_case_sensitivity_of_tool_keys(self):
        """Test that tool keys are case-sensitive."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with uppercase keys (should not match)
            pyproject_data = {
                "tool": {
                    "Poetry": {},  # Uppercase P
                    "UV": {},  # Uppercase UV
                }
            }

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_uv_with_case_variation(self):
        """Test that uv detection is case-sensitive with prefix check."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with uppercase UV prefix
            pyproject_data = {
                "tool": {
                    "UV": {}  # Uppercase (should NOT match uv prefix)
                }
            }

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output


class TestDetermineDependencyManagerLargeScale:
    """Large scale test cases for determine_dependency_manager function."""

    def test_tool_section_with_many_unknown_tools(self):
        """Test with tool section containing many unknown tools."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with 100 unknown tools
            tool_section = {}
            for i in range(100):
                tool_section[f"tool_{i}"] = {"config": f"value_{i}"}

            pyproject_data = {"tool": tool_section}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_tool_section_with_many_unknown_tools_and_poetry(self):
        """Test with tool section containing many unknown tools plus poetry."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with 100 unknown tools and poetry
            tool_section = {"poetry": {"name": "my-project"}}
            for i in range(100):
                tool_section[f"tool_{i}"] = {"config": f"value_{i}"}

            pyproject_data = {"tool": tool_section}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_tool_section_with_many_uv_prefix_keys(self):
        """Test with tool section containing many uv-prefixed keys."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with 100 uv-prefixed keys
            tool_section = {}
            for i in range(100):
                tool_section[f"uv-config-{i}"] = {"option": i}

            pyproject_data = {"tool": tool_section}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_performance_with_large_tool_section(self):
        """Test performance with a large tool section containing many keys."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with 500 various tools
            tool_section = {}
            for i in range(500):
                tool_section[f"tool_{i}"] = {"config": f"value_{i}", "nested": {"key1": "val1", "key2": "val2"}}

            pyproject_data = {"tool": tool_section}

            # Call function and measure performance
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_poetry_detection_with_large_dependencies(self):
        """Test poetry detection with large dependency section."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create poetry config with 200 dependencies
            dependencies = {}
            for i in range(200):
                dependencies[f"package-{i}"] = f"^{i}.0.0"

            pyproject_data = {
                "tool": {"poetry": {"name": "my-project", "version": "0.1.0", "dependencies": dependencies}}
            }

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_mixed_dependency_managers_poetry_wins(self):
        """Test when multiple dependency manager markers exist, poetry wins."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with poetry, uv, and pip markers
            pyproject_data = {"tool": {"poetry": {"name": "project"}, "uv-config": {}, "pip": {}, "setuptools": {}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_mixed_dependency_managers_uv_second(self):
        """Test when poetry is absent but uv is present with pip/setuptools."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with uv, pip, and setuptools markers
            pyproject_data = {"tool": {"uv": {"sources": []}, "pip": {}, "setuptools": {}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_mixed_dependency_managers_pip_third(self):
        """Test when only pip or setuptools markers exist."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create pyproject_data with only pip marker
            pyproject_data = {"tool": {"pip": {"index-url": "https://pypi.org"}, "setuptools": {}}}

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output

    def test_tool_section_all_known_managers_with_lock_files(self):
        """Test that lock files take precedence even with all managers defined."""
        with tempfile.TemporaryDirectory() as tmpdir, patch("pathlib.Path.cwd", return_value=Path(tmpdir)):
            # Create poetry.lock file
            poetry_lock_path = Path(tmpdir) / "poetry.lock"
            poetry_lock_path.touch()

            # Create pyproject_data with all dependency managers
            pyproject_data = {
                "tool": {"poetry": {"name": "project"}, "uv": {"sources": []}, "pip": {}, "setuptools": {}}
            }

            # Call function
            codeflash_output = determine_dependency_manager(pyproject_data)
            result = codeflash_output


# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

To edit these changes git checkout codeflash/optimize-pr1195-2026-01-29T17.08.06 and push.

Codeflash

The optimization achieves a **14% runtime improvement** by caching `Path.cwd()` once at the start of the function instead of calling it twice during the lock file checks.

**Key optimization:**
- **Single Path.cwd() call**: The original code called `Path.cwd()` twice (lines checking `poetry.lock` and `uv.lock`), while the optimized version calls it once and reuses the result via the `cwd` variable.

**Why this matters:**
`Path.cwd()` is a relatively expensive operation that involves system calls to retrieve the current working directory. Line profiler results show:
- Original: First lock check took 3.59ms (57.2% of total time), second took 2.26ms (36% of total time)
- Optimized: The single `cwd = Path.cwd()` took 1.79ms (32.7%), with subsequent checks using the cached path taking 2.05ms (37.4%) and 1.22ms (22.1%)

The net effect is reducing filesystem/system call overhead from ~5.85ms to ~5.05ms across the lock file checks.

**Performance characteristics:**
Based on the annotated tests, this optimization provides consistent **11-19% speedups** across nearly all test cases:
- Best speedup (19.2%): Test with uv-prefixed keys like "uvApp"
- Strong improvements (16-17%): Tests checking lock files or no tool sections
- Consistent gains (11-15%): Tests with tool section parsing

The optimization is particularly beneficial when `determine_dependency_manager` is called frequently, as indicated by the function_references showing it's invoked during GitHub Actions workflow generation (both in `generate_dynamic_workflow_content` and `customize_codeflash_yaml_content`). Since these are CI/CD initialization paths that may be called multiple times during repository setup, the cumulative savings become meaningful.
@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Jan 29, 2026
@KRRT7 KRRT7 merged commit 6bc06f1 into liniting_issues Jan 29, 2026
20 of 23 checks passed
@KRRT7 KRRT7 deleted the codeflash/optimize-pr1195-2026-01-29T17.08.06 branch January 29, 2026 17:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant