From 999f0527218962606b040f53d3c5aade44e0f13d Mon Sep 17 00:00:00 2001 From: Alexandr Skurikhin Date: Tue, 3 Jun 2025 16:55:29 +0300 Subject: [PATCH] Add local_git_branch loader --- docs/index.md | 7 +++++ migration_lint/source_loader/local.py | 43 ++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index ca1bd2b..d79d332 100644 --- a/docs/index.md +++ b/docs/index.md @@ -46,6 +46,13 @@ migration-lint --loader=local_git --extractor= It will examine files in current repository that are added or modified and not yet commited. +If you need to check all committed changes in the current branch compared to +master/main branch (configurable with `CI_DEFAULT_BRANCH`): + +```shell linenums="0" +migration-lint --loader=local_git_branch --extractor= +``` + ### GitLab If you need to run it on the GitLab pipeline: diff --git a/migration_lint/source_loader/local.py b/migration_lint/source_loader/local.py index 7bab9b3..ff6360e 100644 --- a/migration_lint/source_loader/local.py +++ b/migration_lint/source_loader/local.py @@ -1,5 +1,5 @@ import os -from typing import Sequence +from typing import Any, Sequence from migration_lint import logger from migration_lint.source_loader.base import BaseSourceLoader @@ -34,3 +34,44 @@ def get_changed_files(self) -> Sequence[SourceDiff]: SourceDiff(old_path=diff.a_path, path=diff.b_path) for diff in filtered_diffs ] + + +class LocalGitBranchLoader(BaseSourceLoader): + """A loader to obtain files changed for local committed files since default branch.""" + + NAME = "local_git_branch" + + def __init__( + self, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.default_branch = os.environ.get("CI_DEFAULT_BRANCH", "master") + + def get_changed_files(self) -> Sequence[SourceDiff]: + """Return a list of changed files.""" + + from git import Repo + + logger.info( + f"### Getting changed files for local commited files since {self.default_branch}" + ) + + repo = Repo(os.getcwd(), search_parent_directories=True) + current_branch = repo.active_branch.name + diffs = repo.commit(self.default_branch).diff(repo.commit(current_branch)) + + filtered_diffs = [ + d + for d in diffs + if not d.deleted_file + and (not self.only_new_files or self.only_new_files and d.new_file) + ] + + logger.info("Files changed: ") + logger.info("\n".join([f"- {d.a_path}" for d in filtered_diffs])) + + return [ + SourceDiff(old_path=diff.a_path, path=diff.b_path) + for diff in filtered_diffs + ]