File indexing completed on 2024-04-28 17:00:01

0001 """
0002 This module contains code for the feature command
0003 """
0004 
0005 # SPDX-FileCopyrightText: 2020 Jonah BrĂ¼chert <jbb@kaidan.im>
0006 #
0007 # SPDX-License-Identifier: GPL-2.0-or-later
0008 
0009 import argparse
0010 
0011 from typing import Any
0012 
0013 from git import Repo
0014 from git.exc import GitCommandError
0015 
0016 from lab.utils import Utils, LogType
0017 
0018 
0019 def parser(
0020     subparsers: argparse._SubParsersAction,  # pylint: disable=protected-access
0021 ) -> argparse.ArgumentParser:
0022     """
0023     Subparser for feature command
0024     :param subparsers: subparsers object from global parser
0025     :return: feature request subparser
0026     """
0027     feature_parser: argparse.ArgumentParser = subparsers.add_parser(
0028         "feature", help="Create branches and list branches"
0029     )
0030     feature_parser.add_argument("name", nargs="?", help="name for the new branch")
0031     feature_parser.add_argument(
0032         "start",
0033         nargs="?",
0034         help="starting point for the new branch",
0035         default="origin/" + Utils.get_default_branch(Utils.get_cwd_repo()),
0036     )
0037     return feature_parser
0038 
0039 
0040 def run(args: argparse.Namespace) -> None:
0041     """
0042     run feature command
0043     :param args: parsed arguments
0044     """
0045     feature = Feature()
0046     if args.name:
0047         feature.checkout(args.start, args.name)
0048     else:
0049         feature.list()
0050 
0051 
0052 class Feature:
0053     """
0054     represents the feature command
0055     """
0056 
0057     # private
0058     __repo: Repo
0059     __git: Any
0060 
0061     def __init__(self) -> None:
0062         self.__repo = Utils.get_cwd_repo()
0063         self.__git = self.__repo.git
0064 
0065     def checkout(self, start: str, name: str) -> None:
0066         """
0067         Checkouts a branch if it exists or creates a new one
0068         """
0069         try:
0070             if name in self.__repo.refs:
0071                 self.__git.checkout(name)
0072                 Utils.log(LogType.INFO, "Switched to branch '{}'".format(name))
0073             else:
0074                 self.__git.checkout(start, b=name)  # create a new branch
0075                 Utils.log(LogType.INFO, "Switched to a new branch '{}'".format(name))
0076 
0077         except GitCommandError as git_error:
0078             Utils.log(LogType.ERROR, git_error.stderr.strip())
0079 
0080     def list(self) -> None:
0081         """
0082         lists branches
0083         """
0084         print(self.__git.branch())