File indexing completed on 2024-12-01 11:19:02

0001 """
0002 Module containing classes for creating merge requests
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 import sys
0011 
0012 from typing import TextIO, Optional
0013 
0014 from gitlab.v4.objects import Snippet
0015 
0016 from lab.repositoryconnection import RepositoryConnection
0017 from lab.utils import Utils, LogType
0018 
0019 
0020 def parser(
0021     subparsers: argparse._SubParsersAction,  # pylint: disable=protected-access
0022 ) -> argparse.ArgumentParser:
0023     """
0024     Subparser for paste command
0025     :param subparsers: subparsers object from global parser
0026     :return: merge request creation subparser
0027     """
0028     snippet_parser: argparse.ArgumentParser = subparsers.add_parser(
0029         "snippet", help="Create a snippet from stdin or file", aliases=["paste"]
0030     )
0031     snippet_parser.add_argument("--title", help="Add a custom title", default="Empty title")
0032     snippet_parser.add_argument(
0033         "filename",
0034         metavar="str",
0035         type=str,
0036         nargs="?",
0037         help="File name to uplad",
0038     )
0039     return snippet_parser
0040 
0041 
0042 def run(args: argparse.Namespace) -> None:
0043     """
0044     run snippet creation commands
0045     :param args: parsed arguments
0046     """
0047     snippets = Snippets()
0048     file: TextIO
0049     if args.filename:
0050         try:
0051             file = open(args.filename, "r")
0052         except FileNotFoundError:
0053             Utils.log(LogType.ERROR, "Failed to open file", args.filename)
0054             sys.exit(1)
0055     else:
0056         file = sys.stdin
0057 
0058     snippets.paste(file, title=args.title)
0059 
0060 
0061 class Snippets(RepositoryConnection):
0062     """
0063     Class for creating snippets
0064     """
0065 
0066     def __init__(self) -> None:
0067         RepositoryConnection.__init__(self)
0068 
0069     def paste(self, file: TextIO, title: Optional[str]) -> None:
0070         """
0071         paste the contents of a TextIO object
0072         """
0073         snippet: Snippet = self._connection.snippets.create(
0074             {"title": title, "file_name": file.name, "content": file.read(), "visibility": "public"}
0075         )
0076         Utils.log(LogType.INFO, "Created snippet at", snippet.web_url)
0077         print("You can access it raw at", snippet.raw_url)