• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2#
3# Copyright 2018 - The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16"""Base setup subtask runner.
17
18BaseTaskRunner defines basic methods which will be called in the setup process.
19
20the flow in each child task runner will be in below manner:
21Check ShouldRun() -> PrintWelcomMessage() -> _Run()
22"""
23
24from __future__ import print_function
25import logging
26import os
27import textwrap
28
29
30logger = logging.getLogger(__name__)
31_PARAGRAPH_BREAK = "="
32
33
34class BaseTaskRunner(object):
35    """A basic task runner class for setup cmd."""
36
37    # WELCOME_MESSAGE and WELCOME_MESSAGE_TITLE should both be defined as
38    # strings.
39    WELCOME_MESSAGE = None
40    WELCOME_MESSAGE_TITLE = None
41
42    def PrintWelcomeMessage(self):
43        """Print out the welcome message in a fancy format.
44
45        This method will print out the welcome message in the following manner
46        given the following example:
47        e.g.
48        WELCOME_MESSAGE_TITLE = "title"
49        WELCOME_MESSAGE = (
50            "this is one long str "
51            "broken into multiple lines "
52            "based on the screen width"
53        )
54
55        actual output will be:
56        ===========================
57         [title]
58         this is one long str
59         broken into multiple lines
60         based on the screen width
61        ===========================
62        """
63        if not self.WELCOME_MESSAGE and not self.WELCOME_MESSAGE_TITLE:
64            logger.debug("No welcome message for %s", self.__class__.__name__)
65            return
66
67        # define the layout of message.
68        console_width = int(os.popen('stty size', 'r').read().split()[1])
69        break_width = int(console_width / 2)
70
71        # start to print welcome message.
72        print("\n" +_PARAGRAPH_BREAK * break_width)
73        print(" [%s] " % self.WELCOME_MESSAGE_TITLE)
74        print(textwrap.fill(
75            self.WELCOME_MESSAGE,
76            break_width - 2,
77            initial_indent=" ",
78            subsequent_indent=" "))
79        print(_PARAGRAPH_BREAK * break_width + "\n")
80
81    # pylint: disable=no-self-use
82    def ShouldRun(self):
83        """Check if setup should run.
84
85        Returns:
86            Boolean, True if setup should run False otherwise.
87        """
88        return True
89
90    def Run(self, force_setup=False):
91        """Main entry point to the task runner.
92
93        Args:
94            force_setup: Boolean, True to force execute Run method no matter
95                         the result of ShoudRun.
96        """
97        if self.ShouldRun() or force_setup:
98            self.PrintWelcomeMessage()
99            self._Run()
100        else:
101            logger.info("Skipping setup step: %s", self.__class__.__name__)
102
103    def _Run(self):
104        """run the setup procedure."""
105        raise NotImplementedError()
106