• 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
29logger = logging.getLogger(__name__)
30_PARAGRAPH_BREAK = "="
31
32
33class BaseTaskRunner(object):
34    """A basic task runner class for setup cmd."""
35
36    # WELCOME_MESSAGE and WELCOME_MESSAGE_TITLE should both be defined as
37    # strings.
38    WELCOME_MESSAGE = None
39    WELCOME_MESSAGE_TITLE = None
40
41    def PrintWelcomeMessage(self):
42        """Print out the welcome message in a fancy format.
43
44        This method will print out the welcome message in the following manner
45        given the following example:
46        e.g.
47        WELCOME_MESSAGE_TITLE = "title"
48        WELCOME_MESSAGE = (
49            "this is one long str "
50            "broken into multiple lines "
51            "based on the screen width"
52        )
53
54        actual output will be:
55        ===========================
56         [title]
57         this is one long str
58         broken into multiple lines
59         based on the screen width
60        ===========================
61        """
62        if not self.WELCOME_MESSAGE and not self.WELCOME_MESSAGE_TITLE:
63            logger.debug("No welcome message for %s", self.__class__.__name__)
64            return
65
66        # define the layout of message.
67        console_width = int(os.popen('stty size', 'r').read().split()[1])
68        break_width = console_width / 2
69
70        # start to print welcome message.
71        print("\n" +_PARAGRAPH_BREAK * break_width)
72        print(" [%s] " % self.WELCOME_MESSAGE_TITLE)
73        print(textwrap.fill(
74            self.WELCOME_MESSAGE,
75            break_width - 2,
76            initial_indent=" ",
77            subsequent_indent=" "))
78        print(_PARAGRAPH_BREAK * break_width + "\n")
79
80    # pylint: disable=no-self-use
81    def ShouldRun(self):
82        """Check if setup should run.
83
84        Returns:
85            Boolean, True if setup should run False otherwise.
86        """
87        return True
88
89    def Run(self, force_setup=False):
90        """Main entry point to the task runner.
91
92        Args:
93            force_setup: Boolean, True to force execute Run method no matter
94                         the result of ShoudRun.
95        """
96        if self.ShouldRun() or force_setup:
97            self.PrintWelcomeMessage()
98            self._Run()
99        else:
100            logger.info("Skipping setup step: %s", self.__class__.__name__)
101
102    def _Run(self):
103        """run the setup procedure."""
104        raise NotImplementedError()
105