pkgship.py 55.5 KB
Newer Older
1 2
#!/usr/bin/python3 # pylint: disable= too-many-lines

魔箭胖胖's avatar
魔箭胖胖 已提交
3 4
"""
Description: Entry method for custom commands
5
Class: BaseCommand,PkgshipCommand,RemoveCommand,InitDatabaseCommand,
G
gongzt 已提交
6 7
       AllPackageCommand,UpdatePackageCommand,BuildDepCommand,InstallDepCommand,
       SelfBuildCommand,BeDependCommand,SingleCommand
魔箭胖胖's avatar
魔箭胖胖 已提交
8
"""
9 10
import os
import json
11 12
import threading
from json.decoder import JSONDecodeError
13

14 15 16 17 18 19 20
try:
    import argparse
    import requests
    from requests.exceptions import ConnectionError as ConnErr
    from requests.exceptions import HTTPError
    import prettytable
    from prettytable import PrettyTable
21
    from packageship import system_config
22 23 24
    from packageship.libs.log import Log
    from packageship.libs.exception import Error
    from packageship.libs.configutils.readconfig import ReadConfig
魔箭胖胖's avatar
魔箭胖胖 已提交
25

26 27 28 29 30
    LOGGER = Log(__name__)
except ImportError as import_error:
    print('Error importing related dependencies, \
            please check if related dependencies are installed')
else:
Y
Yiru Wang Mac 已提交
31 32
    from packageship.application.apps.package.function.constants import ResponseCode
    from packageship.application.apps.package.function.constants import ListNode
33
    from packageship.application.apps.lifecycle.function.download_yaml import update_pkg_info
34 35 36 37 38

DB_NAME = 0


def main():
魔箭胖胖's avatar
魔箭胖胖 已提交
39 40
    """
    Description: Command line tool entry, register related commands
41 42 43 44 45 46
    Args:

    Returns:

    Raises:
        Error: An error occurred while executing the command
魔箭胖胖's avatar
魔箭胖胖 已提交
47
    """
48 49 50 51 52 53 54 55 56
    try:
        packship_cmd = PkgshipCommand()
        packship_cmd.parser_args()
    except Error as error:
        LOGGER.logger.error(error)
        print('command error')


class BaseCommand():
魔箭胖胖's avatar
魔箭胖胖 已提交
57 58
    """
    Description: Basic attributes used for command invocation
59 60 61 62
    Attributes:
        write_host: Can write operation single host address
        read_host: Can read the host address of the operation
        headers: Send HTTP request header information
魔箭胖胖's avatar
魔箭胖胖 已提交
63
    """
64 65

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
66 67 68 69
        """
        Description: Class instance initialization

        """
70
        self._read_config = ReadConfig(system_config.SYS_CONFIG_PATH)
71 72 73 74 75 76 77 78 79 80
        self.write_host = None
        self.read_host = None
        self.__http = 'http://'
        self.headers = {"Content-Type": "application/json",
                        "Accept-Language": "zh-CN,zh;q=0.9"}

        self.load_read_host()
        self.load_write_host()

    def load_write_host(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
81 82 83 84 85 86 87 88
        """
        Description: Address to load write permission
        Args:

        Returns:
        Raises:

        """
89 90 91
        wirte_port = self._read_config.get_system('write_port')

        write_ip = self._read_config.get_system('write_ip_addr')
92 93 94
        if not all([write_ip, wirte_port]):
            raise Error(
                "The system does not configure the relevant port and ip correctly")
95 96 97 98
        _write_host = self.__http + write_ip + ":" + wirte_port
        setattr(self, 'write_host', _write_host)

    def load_read_host(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
99 100 101 102 103 104 105 106
        """
        Returns:Address to load read permission
        Args:

        Returns:
        Raises:

        """
107 108 109
        read_port = self._read_config.get_system('query_port')

        read_ip = self._read_config.get_system('query_ip_addr')
110 111
        if all([read_ip, read_port]):
            _read_host = self.__http + read_ip + ":" + read_port
112

113
            setattr(self, 'read_host', _read_host)
114

115 116 117 118 119 120 121 122 123 124
    def _set_read_host(self, remote=False):
        """
            Set read domain name
        """
        if remote:
            _host = self._read_config.get_system('remote_host')
            self.read_host = _host
        if self.read_host is None:
            raise Error(
                "The system does not configure the relevant port and ip correctly")
125 126 127


class PkgshipCommand(BaseCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
128 129
    """
    Description: PKG package command line
130 131 132 133 134
    Attributes:
        statistics: Summarized data table
        table: Output table
        columns: Calculate the width of the terminal dynamically
        params: Command parameters
魔箭胖胖's avatar
魔箭胖胖 已提交
135
    """
136 137 138 139 140 141
    parser = argparse.ArgumentParser(
        description='package related dependency management')
    subparsers = parser.add_subparsers(
        help='package related dependency management')

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
142 143 144
        """
        Description: Class instance initialization
        """
145 146
        super(PkgshipCommand, self).__init__()
        self.statistics = dict()
147
        self.table = PkgshipCommand.create_table()
148
        # Calculate the total width of the current terminal
149
        self.columns = 100
150 151 152 153
        self.params = []

    @staticmethod
    def register_command(command):
魔箭胖胖's avatar
魔箭胖胖 已提交
154 155 156
        """
        Description: Registration of related commands

157
        Args:
魔箭胖胖's avatar
魔箭胖胖 已提交
158
            command: Related commands
159 160 161 162

        Returns:
        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
163
        """
164 165 166
        command.register()

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
167 168
        """
        Description: Command line parameter injection
169 170 171 172 173 174
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
175
        """
176 177 178
        for command_params in self.params:
            self.parse.add_argument(  # pylint: disable=E1101
                command_params[0],
179
                # type=eval(command_params[1]),  # pylint: disable=W0123
180
                help=command_params[2],
181 182
                default=command_params[3],
                action=command_params[4])
183 184 185

    @classmethod
    def parser_args(cls):
魔箭胖胖's avatar
魔箭胖胖 已提交
186 187
        """
        Description: Register the command line and parse related commands
188 189 190 191 192 193
        Args:

        Returns:

        Raises:
            Error: An error occurred during command parsing
魔箭胖胖's avatar
魔箭胖胖 已提交
194
        """
195 196 197 198 199 200 201 202 203
        cls.register_command(RemoveCommand())
        cls.register_command(InitDatabaseCommand())
        cls.register_command(AllPackageCommand())
        cls.register_command(UpdatePackageCommand())
        cls.register_command(BuildDepCommand())
        cls.register_command(InstallDepCommand())
        cls.register_command(SelfBuildCommand())
        cls.register_command(BeDependCommand())
        cls.register_command(SingleCommand())
204 205 206
        cls.register_command(IssueCommand())
        cls.register_command(AllTablesCommand())
        cls.register_command(BatchTaskCommand())
207 208 209 210 211 212
        try:
            args = cls.parser.parse_args()
            args.func(args)
        except Error:
            print('command error')

213
    def parse_depend_package(self, response_data, params=None):
魔箭胖胖's avatar
魔箭胖胖 已提交
214 215
        """
        Description: Parsing package data with dependencies
216 217
        Args:
            response_data: http request response content
218
            params: Parameters passed in on the command line
219
        Returns:
魔箭胖胖's avatar
魔箭胖胖 已提交
220
            Summarized data table
221 222
        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
223
        """
224 225 226 227 228
        bin_package_count = 0
        src_package_count = 0
        if response_data.get('code') == ResponseCode.SUCCESS:
            package_all = response_data.get('data')
            if isinstance(package_all, dict):
229 230 231 232 233 234
                if params:
                    if package_all.get("not_found_components"):
                        print("Problem: Not Found Components")
                        for not_found_com in package_all.get("not_found_components"):
                            print("  - nothing provides {} needed by {} ".format(not_found_com, params.packagename))
                    package_all = package_all.get("build_dict")
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

                for bin_package, package_depend in package_all.items():
                    # distinguish whether the current data is the data of the root node
                    if isinstance(package_depend, list) and \
                            package_depend[ListNode.SOURCE_NAME] != 'source':

                        row_data = [bin_package,
                                    package_depend[ListNode.SOURCE_NAME],
                                    package_depend[ListNode.VERSION],
                                    package_depend[ListNode.DBNAME]]
                        # Whether the database exists
                        if package_depend[ListNode.DBNAME] not in self.statistics:
                            self.statistics[package_depend[ListNode.DBNAME]] = {
                                'binary': [],
                                'source': []
                            }
                        # Determine whether the current binary package exists
                        if bin_package not in \
                                self.statistics[package_depend[ListNode.DBNAME]]['binary']:
                            self.statistics[package_depend[ListNode.DBNAME]
                                            ]['binary'].append(bin_package)
                            bin_package_count += 1
                        # Determine whether the source package exists
                        if package_depend[ListNode.SOURCE_NAME] not in \
                                self.statistics[package_depend[ListNode.DBNAME]]['source']:
                            self.statistics[package_depend[ListNode.DBNAME]]['source'].append(
                                package_depend[ListNode.SOURCE_NAME])
                            src_package_count += 1

                        if hasattr(self, 'table') and self.table:
                            self.table.add_row(row_data)
        else:
            LOGGER.logger.error(response_data.get('msg'))
            print(response_data.get('msg'))
        statistics_table = self.statistics_table(
            bin_package_count, src_package_count)
        return statistics_table

    def print_(self, content=None, character='=', dividing_line=False):
魔箭胖胖's avatar
魔箭胖胖 已提交
274 275
        """
        Description: Output formatted characters
276 277 278 279 280 281 282 283
        Args:
           content: Output content
           character: Output separator content
           dividing_line: Whether to show the separator
        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
284
        """
285 286 287 288 289 290 291 292 293 294
        # Get the current width of the console

        if dividing_line:
            print(character * self.columns)
        if content:
            print(content)
        if dividing_line:
            print(character * self.columns)

    @staticmethod
295
    def create_table(title=None):
魔箭胖胖's avatar
魔箭胖胖 已提交
296 297
        """
        Description: Create printed forms
298
        Args:
魔箭胖胖's avatar
魔箭胖胖 已提交
299
            title: Table title
300
        Returns:
魔箭胖胖's avatar
魔箭胖胖 已提交
301
            ASCII format table
302 303
        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
304
        """
305 306 307 308 309 310 311 312 313 314
        table = PrettyTable(title)
        # table.set_style(prettytable.PLAIN_COLUMNS)
        table.align = 'l'
        table.horizontal_char = '='
        table.junction_char = '='
        table.vrules = prettytable.NONE
        table.hrules = prettytable.FRAME
        return table

    def statistics_table(self, bin_package_count, src_package_count):
魔箭胖胖's avatar
魔箭胖胖 已提交
315 316
        """
        Description: Generate data for total statistical tables
317 318 319 320 321 322 323
        Args:
            bin_package_count: Number of binary packages
            src_package_count: Number of source packages
        Returns:
            Summarized data table
        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
324
        """
325 326 327 328 329 330 331 332 333 334 335 336
        statistics_table = self.create_table(['', 'binary', 'source'])
        statistics_table.add_row(
            ['self depend sum', bin_package_count, src_package_count])

        # cyclically count the number of source packages and binary packages in each database
        for database, statistics_item in self.statistics.items():
            statistics_table.add_row([database, len(statistics_item.get(
                'binary')), len(statistics_item.get('source'))])
        return statistics_table

    @staticmethod
    def http_error(response):
魔箭胖胖's avatar
魔箭胖胖 已提交
337 338
        """
        Description: Log error messages for http
339 340 341 342 343 344
        Args:
            response: Response content of http request
        Returns:

        Raises:
            HTTPError: http request error
魔箭胖胖's avatar
魔箭胖胖 已提交
345
        """
346 347 348 349 350 351 352 353 354
        try:
            print(response.raise_for_status())
        except HTTPError as http_error:
            LOGGER.logger.error(http_error)
            print('Request failed')
            print(http_error)


class RemoveCommand(PkgshipCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
355 356
    """
    Description: Delete database command
357 358 359
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
魔箭胖胖's avatar
魔箭胖胖 已提交
360
    """
361 362

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
363 364 365
        """
        Description: Class instance initialization
        """
366 367 368
        super(RemoveCommand, self).__init__()
        self.parse = PkgshipCommand.subparsers.add_parser(
            'rm', help='delete database operation')
369 370
        self.params = [
            ('db', 'str', 'name of the database operated', '', 'store')]
371 372

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
373 374
        """
        Description: Command line parameter injection
375 376 377 378 379 380
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
381
        """
382 383 384 385
        super(RemoveCommand, self).register()
        self.parse.set_defaults(func=self.do_command)

    def do_command(self, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
386 387
        """
        Description: Action to execute command
388 389 390 391 392 393 394
        Args:
            params: Command line parameters
        Returns:

        Raises:
            ConnErr: Request connection error

魔箭胖胖's avatar
魔箭胖胖 已提交
395
        """
396 397 398 399 400 401 402 403 404 405 406 407
        if params.db is None:
            print('No database specified for deletion')
        else:
            _url = self.write_host + '/repodatas?dbName={}'.format(params.db)
            try:
                response = requests.delete(_url)
            except ConnErr as conn_err:
                LOGGER.logger.error(conn_err)
                print(str(conn_err))
            else:
                # Determine whether to delete the mysql database or sqlite database
                if response.status_code == 200:
408 409 410 411 412
                    try:
                        data = json.loads(response.text)
                    except JSONDecodeError as json_error:
                        LOGGER.logger.error(json_error)
                        print(response.text)
413
                    else:
414 415 416 417 418
                        if data.get('code') == ResponseCode.SUCCESS:
                            print('delete success')
                        else:
                            LOGGER.logger.error(data.get('msg'))
                            print(data.get('msg'))
419 420 421 422 423
                else:
                    self.http_error(response)


class InitDatabaseCommand(PkgshipCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
424 425
    """
    Description: Initialize  database command
426 427 428
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
魔箭胖胖's avatar
魔箭胖胖 已提交
429
    """
430 431

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
432 433 434
        """
        Description: Class instance initialization
        """
435 436 437 438
        super(InitDatabaseCommand, self).__init__()
        self.parse = PkgshipCommand.subparsers.add_parser(
            'init', help='initialization of the database')
        self.params = [
439
            ('-filepath', 'str', 'name of the database operated', '', 'store')]
440 441

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
442 443
        """
        Description: Command line parameter injection
444 445 446 447 448 449
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
450
        """
451 452 453 454
        super(InitDatabaseCommand, self).register()
        self.parse.set_defaults(func=self.do_command)

    def do_command(self, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
455 456
        """
        Description: Action to execute command
457 458 459 460 461 462
        Args:
            params: Command line parameters
        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
463
        """
464 465
        file_path = params.filepath
        try:
466 467
            if file_path:
                file_path = os.path.abspath(file_path)
468 469 470
            response = requests.post(self.write_host +
                                     '/initsystem', data=json.dumps({'configfile': file_path}),
                                     headers=self.headers)
471
        except ConnErr as conn_error:
472 473 474 475
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
476 477 478 479 480
                try:
                    response_data = json.loads(response.text)
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)
481
                else:
482 483 484 485 486
                    if response_data.get('code') == ResponseCode.SUCCESS:
                        print('Database initialization success ')
                    else:
                        LOGGER.logger.error(response_data.get('msg'))
                        print(response_data.get('msg'))
487 488 489 490 491
            else:
                self.http_error(response)


class AllPackageCommand(PkgshipCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
492 493
    """
    Description: get all package commands
494 495 496 497
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
        table: Output table
魔箭胖胖's avatar
魔箭胖胖 已提交
498
    """
499 500

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
501 502 503
        """
        Description: Class instance initialization
        """
504 505 506 507 508
        super(AllPackageCommand, self).__init__()

        self.parse = PkgshipCommand.subparsers.add_parser(
            'list', help='get all package data')
        self.table = self.create_table(
509 510 511
            ['packagenames', 'database', 'version', 'license', 'maintainer',
             'release date', 'used time'])
        self.params = [('tablename', 'str', 'name of the database operated', '', 'store'),
512 513
                       ('-remote', 'str', 'The address of the remote service',
                        False, 'store_true'),
J
jiangpengju 已提交
514
                       ('-packagename', 'str',
515
                        'Package name that needs fuzzy matching', '', 'store'),
J
jiangpengju 已提交
516
                       ('-maintainer', 'str', 'Maintainer\'s name', '', 'store')
517
                       ]
518 519

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
520 521
        """
        Description: Command line parameter injection
522 523 524 525 526 527
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
528
        """
529 530 531
        super(AllPackageCommand, self).register()
        self.parse.set_defaults(func=self.do_command)

532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    def __parse_package(self, response_data, table_name):
        """
        Description: Parse the corresponding data of the package
        Args:
            response_data: http request response content
        Returns:

        Raises:

        """
        if response_data.get('code') == ResponseCode.SUCCESS:
            package_all = response_data.get('data')
            if isinstance(package_all, list):
                for package_item in package_all:
                    row_data = [package_item.get('name'),
                                table_name,
                                package_item.get('version') if package_item.get(
                                    'version') else '',
                                package_item.get('rpm_license') if package_item.get(
                                    'rpm_license') else '',
                                package_item.get('maintainer') if package_item.get(
                                    'maintainer') else '',
                                package_item.get('release_time') if package_item.get(
                                    'release_time') else '',
                                package_item.get('used_time')]
                    self.table.add_row(row_data)
        else:
            print(response_data.get('msg'))

561
    def do_command(self, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
562 563
        """
        Description: Action to execute command
564
        Args:
魔箭胖胖's avatar
魔箭胖胖 已提交
565
            params: Command line parameters
566 567 568 569
        Returns:

        Raises:
            ConnectionError: Request connection error
魔箭胖胖's avatar
魔箭胖胖 已提交
570
        """
571
        self._set_read_host(params.remote)
572
        _url = self.read_host + \
573
            '/packages?table_name={table_name}&query_pkg_name={pkg_name}&\
J
jiangpengju 已提交
574
            maintainner={maintainer}&maintainlevel={maintainlevel}&\
575 576
            page_num={page}&page_size={pagesize}'.format(
                table_name=params.tablename,
J
jiangpengju 已提交
577 578 579 580 581
                pkg_name=params.packagename,
                maintainer=params.maintainer,
                maintainlevel='',
                page=1,
                pagesize=65535).replace(' ', '')
582 583
        try:
            response = requests.get(_url)
584
        except ConnErr as conn_error:
585 586 587 588
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
589 590 591 592 593 594
                try:
                    response_data = json.loads(response.text)
                    self.__parse_package(response_data, params.tablename)
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)
595

596
                if getattr(self.table, 'rowcount'):
597
                    print(self.table)
598 599
                else:
                    print('Sorry, no relevant information has been found yet')
600 601 602 603 604
            else:
                self.http_error(response)


class UpdatePackageCommand(PkgshipCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
605 606
    """
    Description: update package data
607 608 609
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
魔箭胖胖's avatar
魔箭胖胖 已提交
610
    """
611 612

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
613 614 615
        """
        Description: Class instance initialization
        """
616 617 618 619 620
        super(UpdatePackageCommand, self).__init__()

        self.parse = PkgshipCommand.subparsers.add_parser(
            'updatepkg', help='update package data')
        self.params = [
621 622 623 624 625 626
            ('-packagename', 'str', 'Source package name', '', 'store'),
            ('-maintainer', 'str', 'Maintainers name', '', 'store'),
            ('-maintainlevel', 'int', 'database priority', 1, 'store'),
            ('-filefolder', 'str', 'Path of yaml file for batch update', '', 'store'),
            ('--batch', 'str', 'The address of the remote service',
             False, 'store_true'),
627 628 629
        ]

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
630 631
        """
        Description: Command line parameter injection
632 633 634 635 636 637
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
638
        """
639 640 641 642
        super(UpdatePackageCommand, self).register()
        self.parse.set_defaults(func=self.do_command)

    def do_command(self, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
643 644
        """
        Description: Action to execute command
645
        Args:
魔箭胖胖's avatar
魔箭胖胖 已提交
646
            params: Command line parameters
647 648 649 650
        Returns:

        Raises:
            ConnectionError: Request connection error
魔箭胖胖's avatar
魔箭胖胖 已提交
651
        """
652
        _url = self.write_host + '/lifeCycle/updatePkgInfo'
653
        try:
654 655 656
            _folder = params.filefolder
            if _folder:
                _folder = os.path.abspath(_folder)
657
            response = requests.put(
658 659 660 661 662
                _url, data=json.dumps({'pkg_name': params.packagename,
                                       'maintainer': params.maintainer,
                                       'maintainlevel': params.maintainlevel,
                                       'batch': params.batch,
                                       'filepath': _folder}),
663
                headers=self.headers)
664
        except ConnErr as conn_error:
665 666 667 668
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
669 670 671 672 673
                try:
                    data = json.loads(response.text)
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)
674
                else:
675 676 677 678 679
                    if data.get('code') == ResponseCode.SUCCESS:
                        print('update completed')
                    else:
                        LOGGER.logger.error(data.get('msg'))
                        print(data.get('msg'))
680 681 682 683 684
            else:
                self.http_error(response)


class BuildDepCommand(PkgshipCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
685 686
    """
    Description: query the compilation dependencies of the specified package
687 688 689 690 691
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
        collection: Is there a collection parameter
        collection_params: Command line collection parameters
魔箭胖胖's avatar
魔箭胖胖 已提交
692
    """
693 694

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
695 696 697
        """
        Description: Class instance initialization
        """
698
        super(BuildDepCommand, self).__init__()
699 700
        self.table = PkgshipCommand.create_table(
            ['Binary name', 'Source name', 'Version', 'Database name'])
701 702 703 704
        self.parse = PkgshipCommand.subparsers.add_parser(
            'builddep', help='query the compilation dependencies of the specified package')
        self.collection = True
        self.params = [
705 706
            ('packagename', 'str', 'source package name', '', 'store'),
            ('-remote', 'str', 'The address of the remote service', False, 'store_true')
707 708 709 710 711 712
        ]
        self.collection_params = [
            ('-dbs', 'Operational database collection')
        ]

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
713 714
        """
        Description: Command line parameter injection
715 716 717 718 719 720
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
721
        """
722 723 724 725 726 727 728 729 730
        super(BuildDepCommand, self).register()
        # collection parameters

        for cmd_params in self.collection_params:
            self.parse.add_argument(
                cmd_params[0], nargs='*', default=None, help=cmd_params[1])
        self.parse.set_defaults(func=self.do_command)

    def do_command(self, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
731 732
        """
        Description: Action to execute command
733
        Args:
魔箭胖胖's avatar
魔箭胖胖 已提交
734
            params: Command line parameters
735 736 737 738
        Returns:

        Raises:
            ConnectionError: Request connection error
魔箭胖胖's avatar
魔箭胖胖 已提交
739
        """
740 741
        self._set_read_host(params.remote)

742 743 744 745 746 747
        _url = self.read_host + '/packages/findBuildDepend'
        try:
            response = requests.post(
                _url, data=json.dumps({'sourceName': params.packagename,
                                       'db_list': params.dbs}),
                headers=self.headers)
748
        except ConnErr as conn_error:
749 750 751 752
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
753 754
                try:
                    statistics_table = self.parse_depend_package(
755
                        json.loads(response.text), params)
756 757 758 759 760 761 762 763 764 765
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)
                else:
                    if getattr(self.table, 'rowcount'):
                        self.print_('query {} buildDepend  result display:'.format(
                            params.packagename))
                        print(self.table)
                        self.print_('statistics')
                        print(statistics_table)
766 767 768 769 770
            else:
                self.http_error(response)


class InstallDepCommand(PkgshipCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
771 772
    """
    Description: query the installation dependencies of the specified package
773 774 775 776 777
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
        collection: Is there a collection parameter
        collection_params: Command line collection parameters
魔箭胖胖's avatar
魔箭胖胖 已提交
778
    """
779 780

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
781 782 783
        """
        Description: Class instance initialization
        """
784 785 786 787 788 789
        super(InstallDepCommand, self).__init__()

        self.parse = PkgshipCommand.subparsers.add_parser(
            'installdep', help='query the installation dependencies of the specified package')
        self.collection = True
        self.params = [
790 791
            ('packagename', 'str', 'source package name', '', 'store'),
            ('-remote', 'str', 'The address of the remote service', False, 'store_true')
792 793 794 795 796 797
        ]
        self.collection_params = [
            ('-dbs', 'Operational database collection')
        ]

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
798 799
        """
        Description: Command line parameter injection
800 801 802 803 804 805
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
806
        """
807 808 809 810 811 812 813 814
        super(InstallDepCommand, self).register()
        # collection parameters

        for cmd_params in self.collection_params:
            self.parse.add_argument(
                cmd_params[0], nargs='*', default=None, help=cmd_params[1])
        self.parse.set_defaults(func=self.do_command)

815
    def __parse_package(self, response_data, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
816 817
        """
        Description: Parse the corresponding data of the package
818 819
        Args:
            response_data: http response data
820
            params: Parameters passed in on the command line
821 822 823 824
        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
825
        """
826 827
        self.table = PkgshipCommand.create_table(
            ['Binary name', 'Source name', 'Version', 'Database name'])
828 829 830 831 832 833 834
        if getattr(self, 'statistics'):
            setattr(self, 'statistics', dict())
        bin_package_count = 0
        src_package_count = 0
        if response_data.get('code') == ResponseCode.SUCCESS:
            package_all = response_data.get('data')
            if isinstance(package_all, dict):
835 836 837 838 839
                if package_all.get("not_found_components"):
                    print("Problem: Not Found Components")
                    for not_found_com in package_all.get("not_found_components"):
                        print("  - nothing provides {} needed by {} ".format(not_found_com, params.packagename))
                for bin_package, package_depend in package_all.get("install_dict").items():
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
                    # distinguish whether the current data is the data of the root node
                    if isinstance(package_depend, list) and package_depend[-1][0][0] != 'root':

                        row_data = [bin_package,
                                    package_depend[ListNode.SOURCE_NAME],
                                    package_depend[ListNode.VERSION],
                                    package_depend[ListNode.DBNAME]]
                        # Whether the database exists
                        if package_depend[ListNode.DBNAME] not in self.statistics:
                            self.statistics[package_depend[ListNode.DBNAME]] = {
                                'binary': [],
                                'source': []
                            }
                        # Determine whether the current binary package exists
                        if bin_package not in \
                                self.statistics[package_depend[ListNode.DBNAME]]['binary']:
                            self.statistics[package_depend[ListNode.DBNAME]
                                            ]['binary'].append(bin_package)
                            bin_package_count += 1
                        # Determine whether the source package exists
                        if package_depend[ListNode.SOURCE_NAME] not in \
                                self.statistics[package_depend[ListNode.DBNAME]]['source']:
                            self.statistics[package_depend[ListNode.DBNAME]]['source'].append(
                                package_depend[ListNode.SOURCE_NAME])
                            src_package_count += 1

                        self.table.add_row(row_data)
        else:
            LOGGER.logger.error(response_data.get('msg'))
            print(response_data.get('msg'))
        # Display of aggregated data
        statistics_table = self.statistics_table(
            bin_package_count, src_package_count)

        return statistics_table

    def do_command(self, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
877 878
        """
        Description: Action to execute command
879 880 881 882 883 884
        Args:
            params: Command line parameters
        Returns:

        Raises:
            ConnectionError: requests connection error
魔箭胖胖's avatar
魔箭胖胖 已提交
885
        """
886 887
        self._set_read_host(params.remote)

888 889 890 891 892 893 894
        _url = self.read_host + '/packages/findInstallDepend'
        try:
            response = requests.post(_url, data=json.dumps(
                {
                    'binaryName': params.packagename,
                    'db_list': params.dbs
                }, ensure_ascii=True), headers=self.headers)
895
        except ConnErr as conn_error:
896 897 898 899
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
900 901
                try:
                    statistics_table = self.__parse_package(
902
                        json.loads(response.text), params)
903 904 905 906 907
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)
                else:
                    if getattr(self.table, 'rowcount'):
908
                        self.print_('query {} InstallDepend result display:'.format(
909 910 911 912
                            params.packagename))
                        print(self.table)
                        self.print_('statistics')
                        print(statistics_table)
913 914 915 916 917
            else:
                self.http_error(response)


class SelfBuildCommand(PkgshipCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
918 919
    """
    Description: self-compiled dependency query
920 921 922 923 924
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
        collection: Is there a collection parameter
        collection_params: Command line collection parameters
魔箭胖胖's avatar
魔箭胖胖 已提交
925
    """
926 927

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
928 929 930
        """
        Description: Class instance initialization
        """
931 932 933 934 935 936 937 938 939 940
        super(SelfBuildCommand, self).__init__()

        self.parse = PkgshipCommand.subparsers.add_parser(
            'selfbuild', help='query the self-compiled dependencies of the specified package')
        self.collection = True
        self.bin_package_table = self.create_table(
            ['package name', 'src name', 'version', 'database'])
        self.src_package_table = self.create_table([
            'src name', 'version', 'database'])
        self.params = [
941 942 943 944 945
            ('packagename', 'str', 'source package name', '', 'store'),
            ('-t', 'str', 'Source of data query', 'binary', 'store'),
            ('-w', 'str', 'whether to include other subpackages of binary', 0, 'store'),
            ('-s', 'str', 'whether it is self-compiled', 0, 'store'),
            ('-remote', 'str', 'The address of the remote service', False, 'store_true')
946 947 948 949 950 951 952
        ]

        self.collection_params = [
            ('-dbs', 'Operational database collection')
        ]

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
953 954
        """
        Description: Command line parameter injection
955 956 957 958 959 960
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
961
        """
962 963 964 965 966 967 968 969 970
        super(SelfBuildCommand, self).register()
        # collection parameters

        for cmd_params in self.collection_params:
            self.parse.add_argument(
                cmd_params[0], nargs='*', default=None, help=cmd_params[1])
        self.parse.set_defaults(func=self.do_command)

    def _parse_bin_package(self, bin_packages):
魔箭胖胖's avatar
魔箭胖胖 已提交
971 972 973 974 975 976
        """
        Description: Parsing binary result data
        Args:
            bin_packages: Binary package data

        Returns:
G
gongzt 已提交
977

魔箭胖胖's avatar
魔箭胖胖 已提交
978
        Raises:
G
gongzt 已提交
979

魔箭胖胖's avatar
魔箭胖胖 已提交
980
        """
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        bin_package_count = 0
        if bin_packages:
            for bin_package, package_depend in bin_packages.items():
                # distinguish whether the current data is the data of the root node
                if isinstance(package_depend, list) and package_depend[-1][0][0] != 'root':

                    row_data = [bin_package, package_depend[ListNode.SOURCE_NAME],
                                package_depend[ListNode.VERSION], package_depend[ListNode.DBNAME]]

                    # Whether the database exists
                    if package_depend[ListNode.DBNAME] not in self.statistics:
                        self.statistics[package_depend[ListNode.DBNAME]] = {
                            'binary': [],
                            'source': []
                        }
                    # Determine whether the current binary package exists
                    if bin_package not in \
                            self.statistics[package_depend[ListNode.DBNAME]]['binary']:
                        self.statistics[package_depend[ListNode.DBNAME]
                                        ]['binary'].append(bin_package)
                        bin_package_count += 1
                    self.bin_package_table.add_row(row_data)

        return bin_package_count

魔箭胖胖's avatar
魔箭胖胖 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    def _parse_src_package(self, src_packages):
        """
        Description: Source package data analysis
        Args:
            src_packages: Source package

        Returns:
            Source package data
        Raises:

        """
1017
        src_package_count = 0
魔箭胖胖's avatar
魔箭胖胖 已提交
1018 1019
        if src_packages:
            for src_package, package_depend in src_packages.items():
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
                # distinguish whether the current data is the data of the root node
                if isinstance(package_depend, list):

                    row_data = [src_package, package_depend[ListNode.VERSION],
                                package_depend[DB_NAME]]
                    # Whether the database exists
                    if package_depend[DB_NAME] not in self.statistics:
                        self.statistics[package_depend[DB_NAME]] = {
                            'binary': [],
                            'source': []
                        }
                    # Determine whether the current binary package exists
                    if src_package not in self.statistics[package_depend[DB_NAME]]['source']:
                        self.statistics[package_depend[DB_NAME]
                                        ]['source'].append(src_package)
                        src_package_count += 1

                    self.src_package_table.add_row(row_data)

        return src_package_count

1041
    def __parse_package(self, response_data, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
1042 1043
        """
        Description: Parse the corresponding data of the package
1044 1045
        Args:
            response_data: http response data
1046
            params: Parameters passed in on the command line
1047 1048 1049 1050
        Returns:
            Summarized data table
        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
1051
        """
1052 1053 1054 1055 1056 1057 1058 1059 1060
        if getattr(self, 'statistics'):
            setattr(self, 'statistics', dict())
        bin_package_count = 0
        src_package_count = 0

        if response_data.get('code') == ResponseCode.SUCCESS:
            package_all = response_data.get('data')
            if isinstance(package_all, dict):
                # Parsing binary result data
1061 1062 1063 1064
                if package_all.get("not_found_components"):
                    print("Problem: Not Found Components")
                    for not_found_com in package_all.get("not_found_components"):
                        print("  - nothing provides {} needed by {} ".format(not_found_com, params.packagename))
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
                bin_package_count = self._parse_bin_package(
                    package_all.get('binary_dicts'))

                # Source package data analysis
                src_package_count = self._parse_src_package(
                    package_all.get('source_dicts'))
        else:
            LOGGER.logger.error(response_data.get('msg'))
            print(response_data.get('msg'))
        # Display of aggregated data
        statistics_table = self.statistics_table(
            bin_package_count, src_package_count)
        # return (bin_package_table, src_package_table, statistics_table)
        return statistics_table

    def do_command(self, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
1081 1082
        """
        Description: Action to execute command
1083 1084 1085 1086 1087 1088
        Args:
            params: commands lines params
        Returns:

        Raises:
            ConnectionError: requests connection error
魔箭胖胖's avatar
魔箭胖胖 已提交
1089
        """
1090
        self._set_read_host(params.remote)
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
        _url = self.read_host + '/packages/findSelfDepend'
        try:
            response = requests.post(_url,
                                     data=json.dumps({
                                         'packagename': params.packagename,
                                         'db_list': params.dbs,
                                         'packtype': params.t,
                                         'selfbuild': str(params.s),
                                         'withsubpack': str(params.w)}),
                                     headers=self.headers)
1101
        except ConnErr as conn_error:
1102 1103 1104 1105
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
1106 1107
                try:
                    statistics_table = self.__parse_package(
1108
                        json.loads(response.text), params)
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)
                else:
                    if getattr(self.bin_package_table, 'rowcount') \
                            and getattr(self.src_package_table, 'rowcount'):
                        self.print_('query {} selfDepend result display :'.format(
                            params.packagename))
                        print(self.bin_package_table)
                        self.print_(character='=')
                        print(self.src_package_table)
                        self.print_('statistics')
                        print(statistics_table)
1122 1123 1124 1125 1126
            else:
                self.http_error(response)


class BeDependCommand(PkgshipCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
1127 1128
    """
    Description: dependent query
1129 1130 1131
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
魔箭胖胖's avatar
魔箭胖胖 已提交
1132
    """
1133 1134

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
1135 1136 1137
        """
        Description: Class instance initialization
        """
1138
        super(BeDependCommand, self).__init__()
1139 1140
        self.table = PkgshipCommand.create_table(
            ['Binary name', 'Source name', 'Version', 'Database name'])
1141 1142 1143
        self.parse = PkgshipCommand.subparsers.add_parser(
            'bedepend', help='dependency query for the specified package')
        self.params = [
1144 1145 1146 1147
            ('packagename', 'str', 'source package name', '', 'store'),
            ('db', 'str', 'name of the database operated', '', 'store'),
            ('-w', 'str', 'whether to include other subpackages of binary', 0, 'store'),
            ('-remote', 'str', 'The address of the remote service', False, 'store_true')
1148 1149 1150
        ]

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
1151 1152
        """
        Description: Command line parameter injection
1153 1154 1155 1156 1157 1158
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
1159
        """
1160 1161 1162 1163
        super(BeDependCommand, self).register()
        self.parse.set_defaults(func=self.do_command)

    def do_command(self, params):
魔箭胖胖's avatar
魔箭胖胖 已提交
1164 1165
        """
        Description: Action to execute command
1166 1167 1168 1169 1170 1171
        Args:
            params: command lines params
        Returns:

        Raises:
            ConnectionError: requests connection error
魔箭胖胖's avatar
魔箭胖胖 已提交
1172
        """
1173
        self._set_read_host(params.remote)
1174 1175 1176 1177 1178 1179 1180 1181 1182
        _url = self.read_host + '/packages/findBeDepend'
        try:
            response = requests.post(_url, data=json.dumps(
                {
                    'packagename': params.packagename,
                    'dbname': params.db,
                    'withsubpack': str(params.w)
                }
            ), headers=self.headers)
1183
        except ConnErr as conn_error:
1184 1185 1186 1187
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
                try:
                    statistics_table = self.parse_depend_package(
                        json.loads(response.text))
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)
                else:
                    if getattr(self.table, 'rowcount'):
                        self.print_('query {} beDepend result display :'.format(
                            params.packagename))
                        print(self.table)
                        self.print_('statistics')
                        print(statistics_table)
1201 1202 1203 1204 1205
            else:
                self.http_error(response)


class SingleCommand(PkgshipCommand):
魔箭胖胖's avatar
魔箭胖胖 已提交
1206 1207
    """
    Description: query single package information
1208 1209 1210
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
魔箭胖胖's avatar
魔箭胖胖 已提交
1211
    """
1212 1213

    def __init__(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
1214 1215 1216
        """
        Description: Class instance initialization
        """
1217 1218 1219 1220 1221
        super(SingleCommand, self).__init__()

        self.parse = PkgshipCommand.subparsers.add_parser(
            'single', help='query the information of a single package')
        self.params = [
1222
            ('packagename', 'str', 'source package name', '', 'store'),
1223
            ('tablename', 'str', 'name of the database operated', '', 'store'),
1224
            ('-remote', 'str', 'The address of the remote service', False, 'store_true')
1225
        ]
1226 1227
        self.provides_table = self.create_table(['Symbol', 'Required by'])
        self.requires_table = self.create_table(['Symbol', 'Provides by'])
1228 1229

    def register(self):
魔箭胖胖's avatar
魔箭胖胖 已提交
1230 1231
        """
        Description: Command line parameter injection
1232 1233 1234 1235 1236 1237
        Args:

        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
1238
        """
1239 1240 1241
        super(SingleCommand, self).register()
        self.parse.set_defaults(func=self.do_command)

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
    def __parse_package_detail(self, response_data):
        """

        """
        _show_field_name = ('pkg_name', 'version', 'release', 'url', 'license', 'feature',
                            'maintainer', 'maintainlevel', 'gitee_url', 'issue', 'summary',
                            'description', 'buildrequired')
        _package_detail_info = response_data.get('data')
        _line_content = []
        if _package_detail_info:
            for key in _show_field_name:
                value = _package_detail_info.get(key)
                if value is None:
                    value = ''
                if isinstance(value, list):
                    value = '、'.join(value) if value else ''
                _line_content.append('%-15s:%s' % (key, value))
        for content in _line_content:
            self.print_(content=content)

    def __parse_provides(self, provides):
        """

        """
        if provides and isinstance(provides, list):
            for _provide in provides:
                _required_by = '\n'.join(
                    _provide['requiredby']) if _provide['requiredby'] else ''
                self.provides_table.add_row(
                    [_provide['name'], _required_by])
        self.print_('Provides')
        if getattr(self.provides_table, 'rowcount'):
            print(self.provides_table)
        else:
            print('No relevant dependent data')
        self.provides_table.clear_rows()

    def __parse_requires(self, requires):
        """

        """
        if requires and isinstance(requires, list):
            for _require in requires:
                _provide_by = '\n'.join(
                    _require['providedby']) if _require['providedby'] else ''
                self.requires_table.add_row(
                    [_require['name'], _provide_by])
        self.print_('Requires')
        if getattr(self.requires_table, 'rowcount'):
            print(self.requires_table)
        else:
            print('No related components')
        self.requires_table.clear_rows()

    def __parse_subpack(self, subpacks):
        """
            Data analysis of binary package
        """
        for subpack_item in subpacks:
G
gongzt 已提交
1301
            print('-' * 50)
1302 1303 1304 1305 1306 1307
            self.print_(subpack_item['name'])

            self.__parse_provides(subpack_item['provides'])
            self.__parse_requires(subpack_item['requires'])

    def __parse_package(self, response_data):
魔箭胖胖's avatar
魔箭胖胖 已提交
1308 1309
        """
        Description: Parse the corresponding data of the package
1310 1311 1312 1313 1314 1315
        Args:
            response_data: http response data
        Returns:

        Raises:

魔箭胖胖's avatar
魔箭胖胖 已提交
1316
        """
1317
        if response_data.get('code') == ResponseCode.SUCCESS:
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

            self.__parse_package_detail(response_data)
            try:
                _subpacks = response_data['data']['subpack']
                self.__parse_subpack(_subpacks)
            except KeyError as key_error:
                LOGGER.logger.error(key_error)
        else:
            print(response_data.get('msg'))

    def do_command(self, params):
        """
        Description: Action to execute command
        Args:
            params: command lines params
        Returns:

        Raises:
            ConnectionError: requests connection error
        """
        self._set_read_host(params.remote)
        _url = self.read_host + \
            '/packages/packageInfo?table_name={db_name}&pkg_name={packagename}' \
                   .format(db_name=params.tablename, packagename=params.packagename)
        try:
            response = requests.get(_url)
        except ConnErr as conn_error:
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
                try:
                    self.__parse_package(json.loads(response.text))
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)

            else:
                self.http_error(response)


class IssueCommand(PkgshipCommand):
    """
    Description: Get the issue list
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
    """

    def __init__(self):
        """
        Description: Class instance initialization
        """
        super(IssueCommand, self).__init__()

        self.parse = PkgshipCommand.subparsers.add_parser(
            'issue', help='Query the issue list of the specified package')
        self.params = [
J
jiangpengju 已提交
1376
            ('-packagename', 'str', 'Query source package name', '', 'store'),
1377 1378 1379 1380 1381 1382 1383

            ('-issue_type', 'str', 'Type of issue', '', 'store'),
            ('-issue_status', 'str', 'the status of the issue', '', 'store'),
            ('-maintainer', 'str', 'Maintainer\'s name', '', 'store'),
            ('-page', 'int',
             'Need to query the data on the first few pages', 1, 'store'),
            ('-pagesize', 'int',
J
jiangpengju 已提交
1384
             'The size of the data displayed on each page', 65535, 'store'),
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
            ('-remote', 'str', 'The address of the remote service', False, 'store_true')
        ]
        self.table = self.create_table(
            ['issue_id', 'pkg_name', 'issue_title',
             'issue_status', 'issue_type', 'maintainer'])

    def register(self):
        """
        Description: Command line parameter injection

        """
        super(IssueCommand, self).register()
        self.parse.set_defaults(func=self.do_command)

    def __parse_package(self, response_data):
        """
        Description: Parse the corresponding data of the package

        Args:
            response_data: http response data
        """
        if response_data.get('code') == ResponseCode.SUCCESS:
            issue_all = response_data.get('data')
            if isinstance(issue_all, list):
                for issue_item in issue_all:
                    _row_data = [
                        issue_item.get('issue_id'),
                        issue_item.get('pkg_name') if issue_item.get(
                            'pkg_name') else '',
                        issue_item.get('issue_title')[:50]+'...' if issue_item.get(
                            'issue_title') else '',
                        issue_item.get('issue_status') if issue_item.get(
                            'issue_status') else '',
                        issue_item.get('issue_type') if issue_item.get(
                            'issue_type') else '',
                        issue_item.get('maintainer') if issue_item.get('maintainer') else '']
                    self.table.add_row(_row_data)
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
        else:
            print(response_data.get('msg'))

    def do_command(self, params):
        """
        Description: Action to execute command
        Args:
            params: command lines params
        Returns:

        Raises:
            ConnectionError: requests connection error
        """
        self._set_read_host(params.remote)
        _url = self.read_host + \
1437 1438 1439 1440 1441
            '/lifeCycle/issuetrace?page_num={page_num}&\
            page_size={page_size}&pkg_name={pkg_name}&issue_type={issue_type}\
            &issue_status={issue_status}&maintainer={maintainer}'\
                .format(page_num=params.page,
                        page_size=params.pagesize,
J
jiangpengju 已提交
1442
                        pkg_name=params.packagename,
1443 1444 1445
                        issue_type=params.issue_type,
                        issue_status=params.issue_status,
                        maintainer=params.maintainer).replace(' ', '')
1446 1447 1448 1449 1450 1451 1452
        try:
            response = requests.get(_url)
        except ConnErr as conn_error:
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
                try:
                    response_data = json.loads(response.text)
                    self.__parse_package(response_data)
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)
                if getattr(self.table, "rowcount"):
                    print('total count : %d' % response_data['total_count'])
                    print('total page : %d' % response_data['total_page'])
                    print('current page : %s ' % params.page)
                    print(self.table)
                else:
                    print("Sorry, no relevant information has been found yet")
            else:
                self.http_error(response)


class AllTablesCommand(PkgshipCommand):
    """
    Description: Get all data tables in the current life cycle
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
    """

    def __init__(self):
        """
        Description: Class instance initialization
        """
        super(AllTablesCommand, self).__init__()

        self.parse = PkgshipCommand.subparsers.add_parser(
            'tables', help='Get all data tables in the current life cycle')
        self.params = [
            ('-remote', 'str', 'The address of the remote service', False, 'store_true')
        ]

    def register(self):
        """
        Description: Command line parameter injection

        """
        super(AllTablesCommand, self).register()
        self.parse.set_defaults(func=self.do_command)

    def do_command(self, params):
        """
        Description: Action to execute command
        Args:
            params: command lines params
        Returns:

        Raises:
            ConnectionError: requests connection error
        """
        self._set_read_host(params.remote)
        _url = self.read_host + '/lifeCycle/tables'
        try:
            response = requests.get(_url, headers=self.headers)
        except ConnErr as conn_error:
            LOGGER.logger.error(conn_error)
            print(str(conn_error))
        else:
            if response.status_code == 200:
                try:
                    _response_content = json.loads(response.text)
                    if _response_content.get('code') == ResponseCode.SUCCESS:
                        print(
                            'The version libraries that exist in the ',
                            'current life cycle are as follows:')
                        for table in _response_content.get('data', []):
                            print(table)
                    else:
                        print('Failed to get the lifecycle repository')
                except JSONDecodeError as json_error:
                    LOGGER.logger.error(json_error)
                    print(response.text)
1530 1531 1532 1533
            else:
                self.http_error(response)


1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
class BatchTaskCommand(PkgshipCommand):
    """
    Description: Issue and life cycle information involved in batch processing packages
    Attributes:
        parse: Command line parsing example
        params: Command line parameters
    """

    def __init__(self):
        """
        Description: Class instance initialization
        """
        super(BatchTaskCommand, self).__init__()

        self.parse = PkgshipCommand.subparsers.add_parser(
            'update',
            help='Issue and life cycle information involved in batch processing packages')
        self.params = [
            ('--issue', 'str', 'Batch operation on issue', False, 'store_true'),
            ('--package', 'str', 'Package life cycle information processing',
             False, 'store_true'),
        ]

    def register(self):
        """
        Description: Command line parameter injection

        """
        super(BatchTaskCommand, self).register()
        self.parse.set_defaults(func=self.do_command)

    def do_command(self, params):
        """
        Description: Action to execute command
        Args:
            params: command lines params
        Returns:

        Raises:
            ConnectionError: requests connection error
        """
        if not params.issue and not params.package:
            print('Please select the way to operate')
        if params.issue:
            issue_thread = threading.Thread(
                target=update_pkg_info, args=(False,))
            issue_thread.start()
        if params.package:
            update_pkg_thread = threading.Thread(
                target=update_pkg_info)
            update_pkg_thread.start()


1587 1588
if __name__ == '__main__':
    main()