Skip to content

[GitLab] Submodule expansion functionality added - #2014

Merged
mrT23 merged 7 commits into
The-PR-Agent:mainfrom
alex107ivanov:gitlab-submodule-expansion-2
Sep 2, 2025
Merged

mrT23 merged 7 commits into
The-PR-Agent:mainfrom
alex107ivanov:gitlab-submodule-expansion-2

Conversation

@alex107ivanov

@alex107ivanov alex107ivanov commented Aug 26, 2025 •

Copy link
Copy Markdown
Contributor

User description

In our project, we have a bunch of submodules as the subparts of the if, and often the changes in the PR spread over the submodules. To analyse, describe, etc, the PR correctly, the reviewer also needs to take a look at the submodule changes, so as the PR-Agent.

This change adds the ability to replace the "sumbodule changed from SHA_x to SHA_y" to the full diff.


PR Type

Enhancement


Description

  • GitLab submodule diff expansion functionality added

  • Submodule changes now show full file diffs instead of SHA updates

  • Configurable via GITLAB.EXPAND_SUBMODULE_DIFFS setting

  • Comprehensive test coverage and documentation updates


Diagram Walkthrough

flowchart LR
  A["GitLab MR Changes"] --> B["Detect Submodule Updates"]
  B --> C["Parse .gitmodules"]
  C --> D["Fetch Submodule Diffs"]
  D --> E["Expand to Full File Changes"]
  E --> F["Enhanced PR Analysis"]
Loading

File Walkthrough

Relevant files
Enhancement
gitlab_provider.py
GitLab submodule diff expansion implementation                     

pr_agent/git_providers/gitlab_provider.py

  • Added submodule expansion functionality with caching
  • Implemented .gitmodules parsing and project resolution
  • Added methods to fetch and expand submodule diffs
  • Modified get_diff_files() and get_files() to use expanded changes
+233/-16
Tests
test_gitlab_provider.py
Comprehensive submodule expansion test coverage                   

tests/unittest/test_gitlab_provider.py

  • Added comprehensive tests for submodule functionality
  • Tests for .gitmodules parsing and project path resolution
  • Tests for submodule comparison caching mechanism
  • Improved test structure and formatting
+75/-28 
Documentation
index.md
Recent updates documentation entry                                             

docs/docs/recent_updates/index.md

  • Added entry for GitLab submodule diff expansion feature
  • Referenced configuration documentation
+1/-0     
additional_configurations.md
GitLab submodule configuration documentation                         

docs/docs/usage-guide/additional_configurations.md

  • Added section explaining GitLab submodule diff expansion
  • Documented expand_submodule_diffs configuration option
  • Minor formatting improvements
+14/-3   

Functionality to include the submodule changes to the Model input added
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
✅ No TODO sections
🔒 Security concerns

Project resolution fallback:
The search-based fallback in _project_by_path may select an unintended project (first match) which could expose diff metadata from another repository the token can access. Consider enforcing exact path_with_namespace matches only, or validating origin against .gitmodules host and namespace before proceeding.

⚡ Recommended focus areas for review

Robustness

_get_gitmodules_map parsing is minimal and may mis-handle quoted paths, multiple submodules, or inline comments; consider using a proper .gitmodules parser or more resilient regex to avoid wrong path->URL mapping.

content = (
    _read_text(getattr(self.mr, "target_branch", None))
    or _read_text(getattr(self.mr, "source_branch", None))
)
if not content:
    return {}

out: dict[str, str] = {}
cur_path: str | None = None
for line in content.splitlines():
    s = line.strip()  # ensure 's' is str
    if s.startswith("[submodule"):
        cur_path = None
    elif s.startswith("path ="):
        cur_path = s.split("=", 1)[1].strip()
    elif s.startswith("url =") and cur_path:
        out[cur_path] = s.split("=", 1)[1].strip()
return out
Performance

_expand_submodule_changes may call _compare_submodule for each submodule change; add caching per (proj_path, old_sha, new_sha) to avoid repeated API calls when methods (get_diff_files/get_files/get_relevant_diff) are invoked multiple times.

    get_logger().info(f"[submodule] {sub_path} url={repo_url} -> proj_path={proj_path}")
    sub_diffs = self._compare_submodule(proj_path, old_sha, new_sha)
    for sd in sub_diffs:
        sd_diff = sd.get("diff") or ""
        sd_old = sd.get("old_path") or sd.get("a_path") or ""
        sd_new = sd.get("new_path") or sd.get("b_path") or sd_old
        out.append({
            "old_path": f"{sub_path}/{sd_old}" if sd_old else sub_path,
            "new_path": f"{sub_path}/{sd_new}" if sd_new else sub_path,
            "diff": sd_diff,
            "new_file": sd.get("new_file", False),
            "deleted_file": sd.get("deleted_file", False),
            "renamed_file": sd.get("renamed_file", False),
        })
return out
Error handling

_project_by_path search fallback can pick a wrong project by name if no exact match; log a warning and skip instead of defaulting to the first match, or require exact path_with_namespace to prevent cross-repo leakage.

    # as a last resort, first match of that name
    if matches:
        return self.gl.projects.get(matches[0].id)
except Exception:

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 26, 2025 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 9f9d085

CategorySuggestion                                                                                                                                    Impact
Incremental [*]
Validate project resolution results

Avoid returning immediately from self.gl.projects.get(enc)/get(proj_path)
because these calls will succeed for numeric project IDs on instances where a
group name coincides with an ID, potentially resolving the wrong project;
instead, after each get, verify the returned project's path_with_namespace
matches proj_path (case-insensitive), and only then return, otherwise continue
to the next strategy.

pr_agent/git_providers/gitlab_provider.py [167-206]

 def _project_by_path(self, proj_path: str):
     """
     Resolve a project by path with multiple strategies:
-    1) URL-encoded path_with_namespace
-    2) Raw path_with_namespace
+    1) URL-encoded path_with_namespace (validated)
+    2) Raw path_with_namespace (validated)
     3) Search fallback + exact match on path_with_namespace (case-insensitive)
     Returns a project object or None.
     """
     if not proj_path:
         return None
 
+    def _validated(proj_obj):
+        try:
+            pwn = getattr(proj_obj, "path_with_namespace", "")
+            if pwn and pwn.lower() == proj_path.lower():
+                return proj_obj
+        except Exception:
+            pass
+        return None
+
     # 1) Encoded
     try:
         enc = urllib.parse.quote_plus(proj_path)
-        return self.gl.projects.get(enc)
+        p = self.gl.projects.get(enc)
+        vp = _validated(p)
+        if vp:
+            return vp
     except Exception:
         pass
 
     # 2) Raw
     try:
-        return self.gl.projects.get(proj_path)
+        p = self.gl.projects.get(proj_path)
+        vp = _validated(p)
+        if vp:
+            return vp
     except Exception:
         pass
 
     # 3) Search fallback
     try:
         name = proj_path.split("/")[-1]
-        # membership=True so we don't leak other people's repos
         matches = self.gl.projects.list(search=name, simple=True, membership=True, per_page=100)
-        # prefer exact path_with_namespace match (case-insensitive)
         for p in matches:
             pwn = getattr(p, "path_with_namespace", "")
             if pwn.lower() == proj_path.lower():
                 return self.gl.projects.get(p.id)
         if matches:
             get_logger().warning(f"[submodule] no exact match for {proj_path} (skip)")
     except Exception:
         pass
 
     return None
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a subtle edge case where self.gl.projects.get() could resolve an incorrect project if a project path resembles a numeric ID, and proposes a robust validation check to prevent this potential bug.

Medium
General
Harden .gitmodules parsing

The .gitmodules format uses [submodule "name"] section headers, not typical INI
names, and ConfigParser may transform them. To avoid missed entries, normalize
by iterating parser.items(section) and lowercasing keys, ensuring robust
extraction of both 'path' and 'url'.

pr_agent/git_providers/gitlab_provider.py [80-150]

 def _get_gitmodules_map(self) -> dict[str, str]:
     """
     Return {submodule_path -> repo_url} from '.gitmodules' (best effort).
     Tries target branch first, then source branch. Always returns text.
     """
     try:
         proj = self.gl.projects.get(self.id_project)
     except Exception:
         return {}
 
     import base64
 
     def _read_text(ref: str | None) -> str | None:
         if not ref:
             return None
         try:
             f = proj.files.get(file_path=".gitmodules", ref=ref)
         except Exception:
             return None
 
-        # 1) python-gitlab File.decode() – usually returns BYTES
         try:
             raw = f.decode()
             if isinstance(raw, (bytes, bytearray)):
                 return raw.decode("utf-8", "ignore")
             if isinstance(raw, str):
                 return raw
         except Exception:
             pass
 
-        # 2) fallback: base64 decode f.content
         try:
             c = getattr(f, "content", None)
             if c:
                 return base64.b64decode(c).decode("utf-8", "ignore")
         except Exception:
             pass
 
         return None
 
     content = (
         _read_text(getattr(self.mr, "target_branch", None))
         or _read_text(getattr(self.mr, "source_branch", None))
     )
     if not content:
         return {}
 
     import configparser
 
     parser = configparser.ConfigParser(
         delimiters=("=",),
         interpolation=None,
         inline_comment_prefixes=("#", ";"),
         strict=False,
     )
     try:
         parser.read_string(content)
     except Exception:
         return {}
 
     out: dict[str, str] = {}
     for section in parser.sections():
-        if not section.lower().startswith("submodule"):
+        if "submodule" not in section.lower():
             continue
-        path = parser.get(section, "path", fallback=None)
-        url = parser.get(section, "url", fallback=None)
+        # collect keys in a case-insensitive way
+        items = {k.lower(): v for k, v in parser.items(section)}
+        path = items.get("path")
+        url = items.get("url")
         if path and url:
             path = path.strip().strip('"').strip("'")
             url = url.strip().strip('"').strip("'")
             out[path] = url
     return out
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: This suggestion correctly identifies a potential issue with parsing .gitmodules and proposes a more robust, case-insensitive method for extracting path and url, preventing potential failures with non-standard key casing.

Medium
Mark and filter expanded diffs

Preserve original submodule change entry and clearly separate expanded diffs to
avoid duplicate or misleading records. Add a marker field (e.g.,
'expanded_from_submodule') and skip appending when compare returns empty to
reduce noise.

pr_agent/git_providers/gitlab_provider.py [233-286]

 def _expand_submodule_changes(self, changes: list[dict]) -> list[dict]:
     """
     If enabled, expand 'Subproject commit' bumps into real file diffs from the submodule.
     Soft-fail on any issue.
     """
     try:
         if not bool(get_settings().get("GITLAB.EXPAND_SUBMODULE_DIFFS", False)):
             return changes
     except Exception:
         return changes
 
     gitmodules = self._get_gitmodules_map()
     if not gitmodules:
         return changes
 
     out = list(changes)
     for ch in changes:
         patch = ch.get("diff") or ""
         if "Subproject commit" not in patch:
             continue
 
-        # Extract old/new SHAs from the hunk
         old_m = re.search(r"^-Subproject commit ([0-9a-f]{7,40})", patch, re.M)
         new_m = re.search(r"^\+Subproject commit ([0-9a-f]{7,40})", patch, re.M)
         if not (old_m and new_m):
             continue
         old_sha, new_sha = old_m.group(1), new_m.group(1)
 
         sub_path = ch.get("new_path") or ch.get("old_path") or ""
         repo_url = gitmodules.get(sub_path)
         if not repo_url:
             get_logger().warning(f"[submodule] no url for '{sub_path}' in .gitmodules (skip)")
             continue
 
         proj_path = self._url_to_project_path(repo_url)
         if not proj_path:
             get_logger().warning(f"[submodule] cannot parse project path from url '{repo_url}' (skip)")
             continue
 
         get_logger().info(f"[submodule] {sub_path} url={repo_url} -> proj_path={proj_path}")
         sub_diffs = self._compare_submodule(proj_path, old_sha, new_sha)
+        if not sub_diffs:
+            # No expansion available; keep original entry only
+            continue
+
         for sd in sub_diffs:
             sd_diff = sd.get("diff") or ""
             sd_old = sd.get("old_path") or sd.get("a_path") or ""
             sd_new = sd.get("new_path") or sd.get("b_path") or sd_old
             out.append({
                 "old_path": f"{sub_path}/{sd_old}" if sd_old else sub_path,
                 "new_path": f"{sub_path}/{sd_new}" if sd_new else sub_path,
                 "diff": sd_diff,
                 "new_file": sd.get("new_file", False),
                 "deleted_file": sd.get("deleted_file", False),
                 "renamed_file": sd.get("renamed_file", False),
+                "expanded_from_submodule": sub_path,
             })
     return out
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: This is a good suggestion that improves the robustness of the new feature by adding a marker field to distinguish expanded submodule diffs, making the data structure clearer for downstream processing.

Low
Learned
best practice
Normalize boolean config values

Normalize the config value to a proper boolean (accepting strings like
"true"/"false") and guard against missing settings to avoid unexpected behavior.

pr_agent/git_providers/gitlab_provider.py [239-240]

-if not bool(get_settings().get("GITLAB.EXPAND_SUBMODULE_DIFFS", False)):
+try:
+    raw = get_settings().get("GITLAB.EXPAND_SUBMODULE_DIFFS", False)
+    val = str(raw).strip().lower() if raw is not None else "false"
+    expand = val in {"1", "true", "yes", "on"}
+except Exception:
+    expand = False
+if not expand:
     return changes
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Validate and normalize user-provided configuration values with safe defaults; guard nested access and handle booleans consistently.

Low
  • Update
  • Author self-review: I have reviewed the PR code suggestions, and addressed the relevant ones.

Previous suggestions

✅ Suggestions up to commit e5e4d2a
CategorySuggestion                                                                                                                                    Impact
High-level
Validate and resolve submodule URLs

The submodule expansion can fetch diffs from the wrong project because URLs are
not host-validated or resolved when they are relative, and a broad
search-by-name fallback may pick an unrelated repo. Restrict expansion to
submodules whose URL host matches the current GitLab instance and properly
resolve relative URLs against the superproject’s namespace; if an exact
path_with_namespace cannot be determined, skip expansion rather than searching
by name. This guards against incorrect diffs and data leakage while keeping
results accurate.

Examples:

pr_agent/git_providers/gitlab_provider.py [137-151]
    def _url_to_project_path(self, url: str) -> str | None:
        """
        Convert ssh/https GitLab URL to 'group/subgroup/repo' project path.
        """
        try:
            if url.startswith("git@") and ":" in url:
                path = url.split(":", 1)[1]
            else:
                path = urllib.parse.urlparse(url).path.lstrip("/")
            if path.endswith(".git"):

 ... (clipped 5 lines)
pr_agent/git_providers/gitlab_provider.py [152-192]
    def _project_by_path(self, proj_path: str):
        """
        Resolve a project by path with multiple strategies:
        1) URL-encoded path_with_namespace
        2) Raw path_with_namespace
        3) Search fallback + exact match on path_with_namespace (case-insensitive)
        Returns a project object or None.
        """
        if not proj_path:
            return None

 ... (clipped 31 lines)

Solution Walkthrough:

Before:

def _url_to_project_path(self, url: str) -> str | None:
    # Discards host, doesn't handle relative URLs
    if url.startswith("git@"):
        path = url.split(":", 1)[1]
    else:
        path = urlparse(url).path.lstrip("/")
    if path.endswith(".git"):
        path = path[:-4]
    return path

def _project_by_path(self, proj_path: str):
    # Tries direct get
    try:
        return self.gl.projects.get(proj_path)
    except Exception:
        pass
    # Falls back to broad search by name
    name = proj_path.split("/")[-1]
    matches = self.gl.projects.list(search=name, membership=True)
    if matches:
        return self.gl.projects.get(matches[0].id) # <-- Picks first match if no exact path match
    return None

After:

def _url_to_project_path(self, url: str) -> str | None:
    current_host = urlparse(self.gl.url).hostname
    
    # Handle relative URLs
    if url.startswith("../"):
        # Resolve relative to main project path
        ...
    
    # Validate host
    parsed_url = urlparse(url)
    if parsed_url.hostname and parsed_url.hostname != current_host:
        return None # External host, skip.
    
    path = parsed_url.path.lstrip("/")
    if path.endswith(".git"):
        path = path[:-4]
    return path

def _project_by_path(self, proj_path: str):
    # Try direct get by encoded and raw path
    try:
        return self.gl.projects.get(proj_path)
    except Exception:
        pass
    # Do NOT fall back to a broad search. If direct get fails, we can't be sure.
    return None
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies critical design flaws in the submodule resolution logic, including lack of host validation, improper handling of relative URLs, and a risky search fallback, which could lead to incorrect diffs.

High
Possible issue
✅ Avoid resolving to incorrect repository
Suggestion Impact:The commit removed the fallback that returned the first match and replaced it with a warning without returning a project, effectively avoiding incorrect repository resolution.

code diff:

@@ -183,9 +198,8 @@
                 pwn = getattr(p, "path_with_namespace", "")
                 if pwn.lower() == proj_path.lower():
                     return self.gl.projects.get(p.id)
-            # as a last resort, first match of that name
             if matches:
-                return self.gl.projects.get(matches[0].id)
+                get_logger().warning(f"[submodule] no exact match for {proj_path} (skip)")
         except Exception:
             pass

The fallback logic to return the first search result is risky. The GitLab API
search for a project name can return multiple repositories with the same name
from different groups. Returning the first match without verifying the full path
could lead to analyzing an incorrect repository, which is a critical bug. It's
safer to return None if no exact path match is found.

pr_agent/git_providers/gitlab_provider.py [186-188]

-# as a last resort, first match of that name
-if matches:
-    return self.gl.projects.get(matches[0].id)
+# if no exact match is found, we don't want to guess

[Suggestion processed]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical flaw in the project resolution logic where falling back to the first search match for a submodule could lead to analyzing the wrong repository.

High
General
Simplify submodule expansion logic

The current implementation iterates through the original changes list, copies
it, and then appends submodule diffs. This logic is slightly complex and can be
simplified. A clearer approach is to build a new list, adding either the
original change or the expanded submodule diffs in a single pass. This improves
readability and maintainability.

pr_agent/git_providers/gitlab_provider.py [226-263]

-out = list(changes)
+out = []
 for ch in changes:
     patch = ch.get("diff") or ""
     if "Subproject commit" not in patch:
+        out.append(ch)
         continue
 
     # Extract old/new SHAs from the hunk
     old_m = re.search(r"^-Subproject commit ([0-9a-f]{7,40})", patch, re.M)
     new_m = re.search(r"^\+Subproject commit ([0-9a-f]{7,40})", patch, re.M)
     if not (old_m and new_m):
+        out.append(ch)
         continue
     old_sha, new_sha = old_m.group(1), new_m.group(1)
 
     sub_path = ch.get("new_path") or ch.get("old_path") or ""
     repo_url = gitmodules.get(sub_path)
     if not repo_url:
         get_logger().warning(f"[submodule] no url for '{sub_path}' in .gitmodules (skip)")
+        out.append(ch)
         continue
 
     proj_path = self._url_to_project_path(repo_url)
     if not proj_path:
         get_logger().warning(f"[submodule] cannot parse project path from url '{repo_url}' (skip)")
+        out.append(ch)
         continue
 
     get_logger().info(f"[submodule] {sub_path} url={repo_url} -> proj_path={proj_path}")
     sub_diffs = self._compare_submodule(proj_path, old_sha, new_sha)
+    if not sub_diffs:
+        out.append(ch)
+        continue
+
     for sd in sub_diffs:
         sd_diff = sd.get("diff") or ""
         sd_old = sd.get("old_path") or sd.get("a_path") or ""
         sd_new = sd.get("new_path") or sd.get("b_path") or sd_old
         out.append({
             "old_path": f"{sub_path}/{sd_old}" if sd_old else sub_path,
             "new_path": f"{sub_path}/{sd_new}" if sd_new else sub_path,
             "diff": sd_diff,
             "new_file": sd.get("new_file", False),
             "deleted_file": sd.get("deleted_file", False),
             "renamed_file": sd.get("renamed_file", False),
         })
Suggestion importance[1-10]: 8

__

Why: The suggestion fixes a bug where the original submodule commit change was kept alongside the expanded file diffs, and it improves the logic by correctly replacing the original change.

Medium
Remove redundant file decoding logic

The _read_text helper function contains redundant decoding logic. The
python-gitlab library's f.decode() method already handles the base64 decoding of
the file content and returns bytes. The subsequent fallback logic to manually
decode f.content is therefore unnecessary. Simplifying this to a single decoding
attempt makes the code cleaner and more efficient.

pr_agent/git_providers/gitlab_provider.py [90-116]

 def _read_text(ref: str | None) -> str | None:
     if not ref:
         return None
     try:
         f = proj.files.get(file_path=".gitmodules", ref=ref)
+        decoded_content = f.decode()
+        if isinstance(decoded_content, (bytes, bytearray)):
+            return decoded_content.decode("utf-8", "ignore")
+        # The decode() method might return a string directly in some cases
+        if isinstance(decoded_content, str):
+            return decoded_content
     except Exception:
         return None
-
-    # 1) python-gitlab File.decode() – usually returns BYTES
-    try:
-        raw = f.decode()
-        if isinstance(raw, (bytes, bytearray)):
-            return raw.decode("utf-8", "ignore")
-        if isinstance(raw, str):
-            return raw
-    except Exception:
-        pass
-
-    # 2) fallback: base64 decode f.content
-    try:
-        c = getattr(f, "content", None)
-        if c:
-            return base64.b64decode(c).decode("utf-8", "ignore")
-    except Exception:
-        pass
-
     return None
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly points out that the fallback base64 decoding logic is redundant, as f.decode() from python-gitlab already handles it, thus simplifying the code.

Low
Learned
best practice
Add null-safety guards

Guard against None or unexpected payloads from the API before indexing or
mutating the response. Add defensive checks and early returns to avoid
TypeError/KeyError if the response is None or not a dict, and log a clear error.

pr_agent/git_providers/gitlab_provider.py [616-618]

-_changes = self.mr.changes()  # dict
-_changes['changes'] = self._expand_submodule_changes(_changes.get('changes', []))
+try:
+    _changes = self.mr.changes() or {}
+except Exception as e:
+    get_logger().error(f"Failed to fetch MR changes: {e}")
+    return None
+if not isinstance(_changes, dict):
+    get_logger().error('Unexpected changes payload for the merge request.')
+    return None
+_changes['changes'] = self._expand_submodule_changes(_changes.get('changes', []) or [])
 changes = _changes
Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Add null-safety checks before accessing nested dict keys or mutating them to prevent runtime exceptions.

Low
Add error handling for API calls

Protect the API call with a try/except to handle request failures gracefully.
Log the exception and fall back to an empty list to keep the flow resilient.

pr_agent/git_providers/gitlab_provider.py [386-388]

-raw_changes = self.mr.changes().get('changes', [])
-raw_changes = self._expand_submodule_changes(raw_changes)
+try:
+    mr_changes = self.mr.changes() or {}
+except Exception as e:
+    get_logger().error(f"Failed to fetch MR changes: {e}")
+    mr_changes = {}
+raw_changes = self._expand_submodule_changes(mr_changes.get('changes', []) or [])
 diffs_original = raw_changes
Suggestion importance[1-10]: 5

__

Why:
Relevant best practice - Wrap API calls in try/except with meaningful logging to prevent crashes and aid troubleshooting.

Low

@alex107ivanov
alex107ivanov marked this pull request as draft August 28, 2025 16:07
@alex107ivanov
alex107ivanov marked this pull request as ready for review August 28, 2025 16:08
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
✅ No TODO sections
🔒 No security concerns identified
⚡ Recommended focus areas for review

Robustness

Submodule expansion appends new diff entries to the original list without removing the original "Subproject commit" entry, potentially double-counting paths and confusing downstream consumers; verify intended behavior and adjust to replace instead of append if needed.

out = list(changes)
for ch in changes:
    patch = ch.get("diff") or ""
    if "Subproject commit" not in patch:
        continue

    # Extract old/new SHAs from the hunk
    old_m = re.search(r"^-Subproject commit ([0-9a-f]{7,40})", patch, re.M)
    new_m = re.search(r"^\+Subproject commit ([0-9a-f]{7,40})", patch, re.M)
    if not (old_m and new_m):
        continue
    old_sha, new_sha = old_m.group(1), new_m.group(1)

    sub_path = ch.get("new_path") or ch.get("old_path") or ""
    repo_url = gitmodules.get(sub_path)
    if not repo_url:
        get_logger().warning(f"[submodule] no url for '{sub_path}' in .gitmodules (skip)")
        continue

    proj_path = self._url_to_project_path(repo_url)
    if not proj_path:
        get_logger().warning(f"[submodule] cannot parse project path from url '{repo_url}' (skip)")
        continue

    get_logger().info(f"[submodule] {sub_path} url={repo_url} -> proj_path={proj_path}")
    sub_diffs = self._compare_submodule(proj_path, old_sha, new_sha)
    for sd in sub_diffs:
        sd_diff = sd.get("diff") or ""
        sd_old = sd.get("old_path") or sd.get("a_path") or ""
        sd_new = sd.get("new_path") or sd.get("b_path") or sd_old
        out.append({
            "old_path": f"{sub_path}/{sd_old}" if sd_old else sub_path,
            "new_path": f"{sub_path}/{sd_new}" if sd_new else sub_path,
            "diff": sd_diff,
            "new_file": sd.get("new_file", False),
            "deleted_file": sd.get("deleted_file", False),
            "renamed_file": sd.get("renamed_file", False),
        })
return out
Matching Logic

_project_by_path search fallback only exact-matches path_with_namespace; consider also matching on full path normalization and handling URL-encoding/decoding edge cases to reduce false negatives.

# 3) Search fallback
try:
    name = proj_path.split("/")[-1]
    # membership=True so we don't leak other people's repos
    matches = self.gl.projects.list(search=name, simple=True, membership=True, per_page=100)
    # prefer exact path_with_namespace match (case-insensitive)
    for p in matches:
        pwn = getattr(p, "path_with_namespace", "")
        if pwn.lower() == proj_path.lower():
            return self.gl.projects.get(p.id)
    if matches:
        get_logger().warning(f"[submodule] no exact match for {proj_path} (skip)")
except Exception:
    pass

return None
Performance

Expanding submodules can significantly increase API calls; ensure pagination and rate limiting/backoff are handled and that expansion respects large MR limits to avoid timeouts.

try:
    if not bool(get_settings().get("GITLAB.EXPAND_SUBMODULE_DIFFS", False)):
        return changes
except Exception:
    return changes

gitmodules = self._get_gitmodules_map()
if not gitmodules:
    return changes

out = list(changes)
for ch in changes:
    patch = ch.get("diff") or ""
    if "Subproject commit" not in patch:
        continue

    # Extract old/new SHAs from the hunk
    old_m = re.search(r"^-Subproject commit ([0-9a-f]{7,40})", patch, re.M)
    new_m = re.search(r"^\+Subproject commit ([0-9a-f]{7,40})", patch, re.M)
    if not (old_m and new_m):
        continue
    old_sha, new_sha = old_m.group(1), new_m.group(1)

    sub_path = ch.get("new_path") or ch.get("old_path") or ""
    repo_url = gitmodules.get(sub_path)
    if not repo_url:
        get_logger().warning(f"[submodule] no url for '{sub_path}' in .gitmodules (skip)")
        continue

    proj_path = self._url_to_project_path(repo_url)
    if not proj_path:
        get_logger().warning(f"[submodule] cannot parse project path from url '{repo_url}' (skip)")
        continue

    get_logger().info(f"[submodule] {sub_path} url={repo_url} -> proj_path={proj_path}")
    sub_diffs = self._compare_submodule(proj_path, old_sha, new_sha)
    for sd in sub_diffs:
        sd_diff = sd.get("diff") or ""
        sd_old = sd.get("old_path") or sd.get("a_path") or ""
        sd_new = sd.get("new_path") or sd.get("b_path") or sd_old
        out.append({
            "old_path": f"{sub_path}/{sd_old}" if sd_old else sub_path,
            "new_path": f"{sub_path}/{sd_new}" if sd_new else sub_path,
            "diff": sd_diff,
            "new_file": sd.get("new_file", False),
            "deleted_file": sd.get("deleted_file", False),
            "renamed_file": sd.get("renamed_file", False),
        })
return out

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Separate analysis-only submodule expansion

You’re mixing expanded submodule diffs into the MR’s change set
(get_diff_files/get_files/get_relevant_diff), which makes the provider treat
files from other repositories as if they belong to the MR. This risks failed or
mis-targeted inline comments and brittle diff parsing, since the submodule diff
headers’ paths won’t match the prefixed new_path you produce. Keep original MR
changes for all MR operations (positions/comments, file lists) and expose
expanded submodule diffs via a separate analysis-only channel or mark them as
non-commentable, normalizing paths only if you must merge them.

Examples:

pr_agent/git_providers/gitlab_provider.py [408-410]
        raw_changes = self.mr.changes().get('changes', [])
        raw_changes = self._expand_submodule_changes(raw_changes)
        diffs_original = raw_changes
pr_agent/git_providers/gitlab_provider.py [278-285]
                out.append({
                    "old_path": f"{sub_path}/{sd_old}" if sd_old else sub_path,
                    "new_path": f"{sub_path}/{sd_new}" if sd_new else sub_path,
                    "diff": sd_diff,
                    "new_file": sd.get("new_file", False),
                    "deleted_file": sd.get("deleted_file", False),
                    "renamed_file": sd.get("renamed_file", False),
                })

Solution Walkthrough:

Before:

class GitLabProvider:
    def get_diff_files(self) -> list[FilePatchInfo]:
        raw_changes = self.mr.changes().get('changes', [])
        # Submodule changes are mixed in, with no distinction
        raw_changes = self._expand_submodule_changes(raw_changes)
        
        diff_files = []
        for change in raw_changes:
            # All changes are processed identically.
            # Paths in patch content (--- a/file) don't match
            # the prefixed path in the change object ('sub/file').
            diff_files.append(FilePatchInfo(
                full_path=change['new_path'],
                patch=change['diff']
            ))
        return diff_files

After:

class GitLabProvider:
    def get_diff_files(self) -> list[FilePatchInfo]:
        raw_changes = self.mr.changes().get('changes', [])
        # Expansion logic now marks submodule changes
        expanded_changes = self._expand_submodule_changes(raw_changes)

        diff_files = []
        for change in expanded_changes:
            is_submodule = change.get("is_from_submodule", False)
            patch_content = change['diff']

            if is_submodule:
                # Normalize paths inside the patch itself
                # e.g., '--- a/file.py' -> '--- a/sub/file.py'
                patch_content = normalize_patch_paths(patch_content, ...)

            file_info = FilePatchInfo(
                full_path=change['new_path'],
                patch=patch_content,
                is_commentable=not is_submodule, # Mark as non-commentable
            )
            diff_files.append(file_info)
        return diff_files
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a critical design flaw where mixing submodule diffs into the main MR change set will break core functionality like inline commenting, as the file paths are not valid in the MR's context.

High
General
Reuse cached data to avoid re-fetching

The get_files method fetches and processes changes from self.mr.changes() every
time it's called and self.git_files is not yet populated. This can lead to
redundant API calls and processing if other methods like get_diff_files have
already fetched the same data.

To optimize performance, you should reuse the self.diff_files list if it has
already been computed by get_diff_files(). This avoids refetching and
reprocessing submodule changes.

pr_agent/git_providers/gitlab_provider.py [478-483]

 def get_files(self) -> list:
-    if not self.git_files:
-        raw_changes = self.mr.changes().get('changes', [])
-        raw_changes = self._expand_submodule_changes(raw_changes)
-        self.git_files = [c.get('new_path') for c in raw_changes if c.get('new_path')]
+    if self.git_files:
+        return self.git_files
+    if self.diff_files:
+        self.git_files = [f.filename for f in self.diff_files]
+        return self.git_files
+
+    raw_changes = self.mr.changes().get('changes', [])
+    raw_changes = self._expand_submodule_changes(raw_changes)
+    self.git_files = [c.get('new_path') for c in raw_changes if c.get('new_path')]
     return self.git_files
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion proposes a valid optimization to reuse self.diff_files if available, preventing redundant API calls and processing, which improves performance.

Medium
Avoid duplicating failure caching logic

The _compare_submodule function caches an empty list [] on failure, but it does
so in two separate places with identical code. This duplication can lead to
maintenance issues if the caching logic needs to be updated in the future.

To improve maintainability and adhere to the DRY (Don't Repeat Yourself)
principle, you should consolidate the failure caching logic into a single
location within the except block.

pr_agent/git_providers/gitlab_provider.py [208-231]

 def _compare_submodule(self, proj_path: str, old_sha: str, new_sha: str) -> list[dict]:
     """
     Call repository_compare on submodule project; return list of diffs.
     """
     key = (proj_path, old_sha, new_sha)
     if key in self._submodule_cache:
         return self._submodule_cache[key]
     try:
         proj = self._project_by_path(proj_path)
         if proj is None:
-            get_logger().warning(f"[submodule] resolve failed for {proj_path}")
-            self._submodule_cache[key] = []
-            return []
+            raise ValueError(f"resolve failed for {proj_path}")
+
         cmp = proj.repository_compare(old_sha, new_sha)
         if isinstance(cmp, dict):
             diffs = cmp.get("diffs", []) or []
         else:
             diffs = []
         self._submodule_cache[key] = diffs
         return diffs
     except Exception as e:
         get_logger().warning(f"[submodule] compare failed for {proj_path} {old_sha}..{new_sha}: {e}")
         self._submodule_cache[key] = []
         return []
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies duplicated code for failure handling and proposes a valid refactoring to improve maintainability by adhering to the DRY principle.

Low
Learned
best practice
Deduplicate change expansion logic

Factor repeated changes fetch-and-expand logic into a private helper (e.g.,
_get_expanded_changes()) and reuse it in get_diff_files, get_files, and
get_relevant_diff.

pr_agent/git_providers/gitlab_provider.py [480-482]

-raw_changes = self.mr.changes().get('changes', [])
-raw_changes = self._expand_submodule_changes(raw_changes)
-self.git_files = [c.get('new_path') for c in raw_changes if c.get('new_path')]
+changes = self._get_expanded_changes()
+self.git_files = [c.get('new_path') for c in changes if c.get('new_path')]
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Extract duplicated logic into a helper to follow the DRY principle and keep behavior consistent.

Low
Handle MR changes API errors

Wrap the self.mr.changes() GitLab API call in a try-except block and log
failures to avoid crashing on network or permission errors.

pr_agent/git_providers/gitlab_provider.py [408-410]

-raw_changes = self.mr.changes().get('changes', [])
+try:
+    raw_changes = self.mr.changes().get('changes', [])
+except Exception as e:
+    get_logger().error(f"Failed to fetch MR changes: {e}")
+    raw_changes = []
 raw_changes = self._expand_submodule_changes(raw_changes)
 diffs_original = raw_changes
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why:
Relevant best practice - Add proper error handling with try-except around API calls to prevent crashes and provide meaningful logs.

Low
  • More
  • Author self-review: I have reviewed the PR code suggestions, and addressed the relevant ones.

@mrT23

mrT23 commented Sep 1, 2025

Copy link
Copy Markdown
Contributor

thanks @alex107ivanov
quite complicated, but the logic looks right.

for better documentation, please add

[gitlab]
expand_submodule_diffs=false

to the configuration file, and we can merge

@alex107ivanov

alex107ivanov commented Sep 1, 2025 •

Copy link
Copy Markdown
Contributor Author

thanks @alex107ivanov quite complicated, but the logic looks right.
for better documentation, please add
to the configuration file, and we can merge

Done. Thank you!
I also have an idea of adding task trackers to the PR Agent, so it can check if the PR covers the related task. Not sure if I can handle it - architecture and realization are not a big problem, but the prompts are really not my strength. Anyway, if I'll have enough free time I'll try it.

@mrT23

mrT23 commented Sep 2, 2025

Copy link
Copy Markdown
Contributor

thanks @alex107ivanov quite complicated, but the logic looks right.
for better documentation, please add
to the configuration file, and we can merge

Done. Thank you! I also have an idea of adding task trackers to the PR Agent, so it can check if the PR covers the related task. Not sure if I can handle it - architecture and realization are not a big problem, but the prompts are really not my strength. Anyway, if I'll have enough free time I'll try it.

Is it different than this:
https://qodo-merge-docs.qodo.ai/core-abilities/fetching_ticket_context/#review-tool
?

@mrT23
mrT23 merged commit 411f933 into The-PR-Agent:main Sep 2, 2025
@alex107ivanov

alex107ivanov commented Sep 2, 2025 •

Copy link
Copy Markdown
Contributor Author

Is it different than this: https://qodo-merge-docs.qodo.ai/core-abilities/fetching_ticket_context/#review-tool ?

Exactly what I was looking for. Thank you!

@alex107ivanov

alex107ivanov commented Sep 2, 2025 •

Copy link
Copy Markdown
Contributor Author

Is it different than this: https://qodo-merge-docs.qodo.ai/core-abilities/fetching_ticket_context/#review-tool ?

Sorry for the stupid question - does it work with Jira? First, I tried to add the configuration options, then I tried to find any related code, and found only GitHub and Azure implementations for the issue extraction code.

@mrT23

mrT23 commented Sep 2, 2025

Copy link
Copy Markdown
Contributor

JIRA is implemented in Qodo Merge (the paid version)

@alex107ivanov

Copy link
Copy Markdown
Contributor Author

JIRA is implemented in Qodo Merge (the paid version)

Ah, I see. Meanwhile, I implemented the Jira (self-hosted version) functionality, but it seems you don't need the PR, right?

@mrT23

mrT23 commented Sep 3, 2025

Copy link
Copy Markdown
Contributor

correct. its suitable for your local deployment

@heYeCheng

Copy link
Copy Markdown

Preparing review...

1 similar comment
@heYeCheng

Copy link
Copy Markdown

Preparing review...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants