Socialify

Folder ..

Viewing setup.py
209 lines (153 loc) • 5.5 KB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# This is a Python script that is used to do a lot of things. It can be thought
# of as a manager script for this project. It is used to install requirements,
# run sorter, linter, start and build the project and more. It will be a
# constantly evolving script as the project evolves.

import logging as logger
import os
import subprocess
import sys

logger.basicConfig(stream=sys.stdout, level=logger.DEBUG)


def install_pip(package_name):
    # check if package is installed
    check_command = "pip3 show " + package_name
    try:
        output = subprocess.check_output(check_command, shell=True)
    except:
        logger.info(f"Installing {package_name}...")
        subprocess.check_call(
            [sys.executable, "-m", "pip", "-q", "install", package_name]
        )


def install_packages():
    # read PKGLIST file
    packages = []
    with open("PKGLIST", "r") as f:
        packages = f.readlines()
    packages = [x.strip() for x in packages]
    for package in packages:
        install_pip(package)


# Package Importer
def import_packages(packages):
    # import packages
    for package in packages:
        try:
            globals()[package] = __import__(package)
        except ImportError:
            logger.error(f"Package {package} not found. Installing...")
            install_pip(package)
            globals()[package] = __import__(package)


packages = ["inquirer", "click"]
import_packages(packages)


class Setup:
    def shell_run(self, command):
        output = subprocess.check_output(command, shell=True)
        return output.decode("utf-8")

    def start(self):
        install_packages()
        if not os.path.exists(".venv"):
            self.shell_run("python3 -m venv .venv")
            logger.info("Virtual environment created.")
        self.git()

    def git(self):
        username = self.shell_run("git config --global user.name")
        if username == "":
            questions = [
                globals()["inquirer"].Confirm(
                    "set_username",
                    message="Do you want to set git author name?",
                    default=True,
                ),
            ]
            answers = globals()["inquirer"].prompt(questions)
            if answers["set_username"]:
                username = globals()["inquirer"].text(
                    message="Enter git author name (not username): "
                )
                self.shell_run(f'git config --global user.name "{username}"')
            else:
                logger.warn("Git author name not set.")

        email = self.shell_run("git config --global user.email")
        if email == "":
            questions = [
                globals()["inquirer"].Confirm(
                    "set_email",
                    message="Do you want to set git author email?",
                    default=True,
                ),
            ]
            answers = globals()["inquirer"].prompt(questions)
            if answers["set_email"]:
                email = globals()["inquirer"].text(message="Enter git author email: ")
                self.shell_run(f'git config --global user.email "{email}"')
            else:
                logger.warn("Git author email not set.")

        self.configure()

    def configure(self):
        configure_path = "bin/configure"
        script = """#!{}
alias commit="./commit.sh"
alias setup="python3 setup.py"
echo "Added aliases for commit and setup."
echo ""
echo "Run 'setup' to start the setup again. Run 'setup -h' for more options."
echo "Run 'commit' to commit changes. Run 'commit -h' for help."
""".format(
            os.environ["SHELL"]
        )
        with open(configure_path, "w") as f:
            f.write(script)

        configure_st = os.stat(configure_path)
        os.chmod(configure_path, configure_st.st_mode | 0o111)
        print(
            """Configuration script created.

You may want to configure aliases for commit and setup scripts.
To do so, run the configurator binary:

    source bin/configure

You may also want to activate the virtual environment, if you haven't already:

    source .venv/bin/activate
"""
        )


CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])

click = globals()["click"]


@click.group(context_settings=CONTEXT_SETTINGS)
def cli():
    pass


@click.command(help="Start the setup.")
def start():
    Setup().start()


cli.add_command(start)


@click.command(help="Install requirements.")
def install():
    logger.info("Installing requirements...")
    install_packages()
    logger.info("Requirements installed.")


cli.add_command(install)


@click.command(help="Generate alias configuration script.")
def configure():
    Setup().configure()


cli.add_command(configure)


@click.command(help="Run the project.")
@click.option("--debug", is_flag=True, help="Run in debug mode.")
def run(debug):
    if debug:
        os.system("python3 src/texty.py --debug")
    else:
        logger.info("Running the project...")
        os.system("python3 src/texty.py")


cli.add_command(run)


@click.command(help="Start Linter.")
def lint():
    logger.info("Starting Linter...")
    os.system("python3 -m black .")


cli.add_command(lint)


@click.command(help="Start Sorter.")
def sort():
    logger.info("Starting Sorter...")
    os.system("python3 -m isort .")


cli.add_command(sort)


@click.command(help="Build the project.")
def build():
    logger.info("Building the project...")
    os.system("pyinstaller --onefile --windowed --name Texty src/texty.py")


cli.add_command(build)

if __name__ == "__main__":
    cli()