-
Notifications
You must be signed in to change notification settings - Fork 1
BWDO-778 sc branch rename, rm_merged and more #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
02c2eb3
BWDO-778 sc branch rename, rm_merged and more
BenjiMilan b8a6eb0
BWDO-778 copilot changes
BenjiMilan 6e93b0a
BWDO-778 changes after review
BenjiMilan 327cb25
local git only
BenjiMilan f6c65ef
BWDO-778 - Toby and copilot review
BenjiMilan 9e2db81
BWDO-778 Toby comments
BenjiMilan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| # Copyright 2025 RDK Management | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from dataclasses import dataclass | ||
| from enum import Enum, auto | ||
| import logging | ||
| from pathlib import Path | ||
|
BenjiMilan marked this conversation as resolved.
|
||
|
|
||
| import git | ||
| from git import Repo | ||
|
|
||
| from .command import Command | ||
| from sc.exceptions import ScError | ||
| from sc_manifest_parser import ScManifest | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| @dataclass | ||
| class BranchRename(Command): | ||
| old_branch: str | ||
| new_branch: str | ||
| local_only: bool | ||
| git_only: bool | ||
|
|
||
| def run_git_command(self): | ||
| self._rename_repo(self.top_dir) | ||
|
|
||
| def run_repo_command(self): | ||
| manifest = ScManifest.from_repo_root(self.top_dir / ".repo") | ||
|
|
||
| if self.git_only: | ||
| self._rename_repo(Path.cwd()) | ||
| return | ||
|
|
||
| for proj in manifest.projects: | ||
| if proj.lock_status is None: | ||
| logger.info(f"Renaming local branch in repo: {self.top_dir / proj.path}") | ||
| self._rename_repo(self.top_dir / proj.path) | ||
|
|
||
| logger.info(f"Renaming local manifest branch: {self.top_dir / '.repo' / 'manifests'}") | ||
| self._rename_repo(self.top_dir / ".repo" / "manifests") | ||
|
|
||
| def _rename_repo(self, directory: Path): | ||
| try: | ||
| repo = Repo(directory) | ||
| except git.InvalidGitRepositoryError as e: | ||
| # We should hopefully never get here. Only if the user is missing repositories | ||
| # that should be present from their manifest. | ||
| logger.warning(f"Skipping renaming for {directory}: Not a valid git repository.") | ||
| return | ||
|
BenjiMilan marked this conversation as resolved.
|
||
|
|
||
| try: | ||
| self._rename_local(repo) | ||
| except ScError as e: | ||
| logger.warning(f"Skipping renaming for {directory}: {e}") | ||
| return | ||
|
|
||
| if not self.local_only: | ||
| try: | ||
| self._rename_remote(repo) | ||
| except ScError as e: | ||
| logger.warning(f"Skipping remote renaming for {directory}: {e}") | ||
|
|
||
| def _rename_local(self, repo: Repo): | ||
| try: | ||
| repo.git.branch("-m", self.old_branch, self.new_branch) | ||
| logger.info("Renamed locally.") | ||
| except git.GitCommandError as e: | ||
| raise ScError( | ||
| f"Unable to rename branch in repo {repo.working_dir}: {e.stderr}" | ||
| ) from e | ||
|
|
||
| def _rename_remote(self, repo: Repo): | ||
| try: | ||
| remote = repo.remotes[0].name | ||
| except IndexError as e: | ||
| raise ScError(f"No remote found for repo {repo.working_dir}.") from e | ||
|
|
||
| try: | ||
| # Push/create the new branch before deleting the old branch. | ||
| repo.git.push("-u", remote, f"{self.new_branch}:refs/heads/{self.new_branch}") | ||
| except git.GitCommandError as e: | ||
| raise ScError( | ||
| f"Failed to push new branch to remote {self.new_branch}: {e.stderr}") from e | ||
|
|
||
| if self._has_remote_branch(repo, remote, self.old_branch) is not None: | ||
| try: | ||
| repo.git.push(remote, "--delete", self.old_branch) | ||
| except git.GitCommandError as e: | ||
| raise ScError( | ||
| f"Failed to delete old branch on remote {self.old_branch}: {e.stderr}") from e | ||
|
|
||
| logger.info("Renamed remotely.") | ||
|
|
||
| def _has_remote_branch(self, repo: Repo, remote_name: str, branch_name: str) -> bool: | ||
| out = repo.git.ls_remote("--heads", remote_name, f"refs/heads/{branch_name}") | ||
|
|
||
| for line in out.splitlines(): | ||
| commit, ref = line.split() | ||
| if ref == f"refs/heads/{branch_name}": | ||
| return True | ||
|
|
||
| return False | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| # Copyright 2025 RDK Management | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
|
|
||
| import git | ||
| from git import Repo | ||
| from git_flow_library import GitFlowLibrary | ||
|
|
||
| from ..branch import Branch | ||
| from .command import Command | ||
| from .delete import Delete | ||
| from sc.exceptions import ScError | ||
| from sc.prompter import Prompter | ||
| from sc.services.tickets.ticket_service import TicketService | ||
|
|
||
| @dataclass | ||
| class BranchRmMerged(Command): | ||
| not_merged: bool = False | ||
| all: bool = False | ||
| no_prompt: bool = False | ||
| git_only: bool = False | ||
| dry_run: bool = False | ||
|
BenjiMilan marked this conversation as resolved.
|
||
|
|
||
| def run_git_command(self): | ||
| self._verify_options() | ||
| self._rm_merged(self.top_dir, git_only=True) | ||
|
|
||
| def run_repo_command(self): | ||
| self._error_on_sc_uninitialised() | ||
| self._verify_options() | ||
|
|
||
| if self.git_only: | ||
| root = GitFlowLibrary.get_git_root(Path.cwd()) | ||
| if not root: | ||
| raise ScError(f"{Path.cwd()} not a valid git repository!") | ||
| self._rm_merged(root, self.git_only) | ||
| else: | ||
| self._rm_merged(self.top_dir) | ||
|
|
||
| def _verify_options(self): | ||
| if self.not_merged and self.all: | ||
| raise ScError("Cannot pass both --all and --no-merged.") | ||
|
|
||
| def _rm_merged(self, path: Path, git_only: bool = False): | ||
| filtered_branches = self._get_feature_branches(path) | ||
|
|
||
| ticket_service = TicketService() | ||
|
|
||
| for branch in filtered_branches: | ||
| ticket = ticket_service.get_ticket_from_branch(branch.name) | ||
| print(ticket.to_terminal(one_line=True)) | ||
| print(branch.name) | ||
|
BenjiMilan marked this conversation as resolved.
BenjiMilan marked this conversation as resolved.
|
||
|
|
||
| if self.dry_run: | ||
| continue | ||
|
|
||
| if self.no_prompt: | ||
| self._delete_branch(path, branch, git_only) | ||
| elif Prompter.yn("Delete branch?"): | ||
| self._delete_branch(path, branch, git_only) | ||
|
BenjiMilan marked this conversation as resolved.
|
||
|
|
||
| def _get_feature_branches(self, path: Path) -> list[Branch]: | ||
| try: | ||
| repo = Repo(path) | ||
| except git.InvalidGitRepositoryError as e: | ||
| raise ScError(f"Invalid git repo: {path}") from e | ||
|
|
||
| develop = GitFlowLibrary.get_develop_branch(path) | ||
| master = GitFlowLibrary.get_master_branch(path) | ||
| hotfix = GitFlowLibrary.get_config_value("prefix.hotfix", path) | ||
| release = GitFlowLibrary.get_config_value("prefix.release", path) | ||
| support = GitFlowLibrary.get_config_value("prefix.support", path) | ||
|
|
||
| branch_filters = [develop, master, hotfix, release, support, "m/feature"] | ||
|
|
||
| feature = GitFlowLibrary.get_config_value("prefix.feature", path) | ||
|
|
||
| merge_type = "--merged" if not self.not_merged else "--no-merged" | ||
| merge_type = "--all" if self.all else merge_type | ||
| branches = repo.git.branch("-r", merge_type, develop).splitlines() | ||
|
|
||
| feature_branches = [ | ||
| branch.strip().split("/", 1)[1] | ||
| for branch in branches | ||
| if not any(f in branch for f in branch_filters) | ||
| and feature in branch | ||
| ] | ||
|
|
||
| return [Branch(*b.split("/", 1)) for b in feature_branches] | ||
|
|
||
| def _delete_branch(self, path: Path, branch: Branch, git_only: bool): | ||
| if git_only: | ||
| Delete(path, branch, remote=True).run_git_command() | ||
| else: | ||
| Delete(path, branch, remote=True).run_repo_command() | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.