Skip to content

Commit

Permalink
Reworked, improved, etc
Browse files Browse the repository at this point in the history
  • Loading branch information
imayhaveborkedit committed Jan 10, 2016
1 parent 9fe93c2 commit eccf22c
Showing 1 changed file with 135 additions and 52 deletions.
187 changes: 135 additions & 52 deletions run.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,109 @@
import sys, os, traceback, subprocess, webbrowser

def check_for_git():
try:
return bool(subprocess.check_output('git --version'))
except:
return False

def check_for_pip():
try:
return bool(subprocess.check_output('pip -V'))
except:
return False
class GIT(object):

def check_for_module_pip(mod):
import pip
return pip.main(['-q', 'show', mod]) == 0
@classmethod
def works(cls):
try:
return bool(subprocess.check_output('git --version', shell=True))
except:
return False

def get_module_version(mod):
# if not check_for_pip() blah blah blah
try:
out = subprocess.check_output('pip show %s' % mod, )
datas = str(out).split('\\r\\n')
expectedversion = datas[3]
# TODO: Maybe I should only check for if you can import pip. It seems like more if an issue if you can't

class PIP(object):

looked_for = False
pip_command = None
use_import = False

if expectedversion.startswith('Version: '):
return expectedversion.split()[1]
@classmethod
def run(cls, command, use_import=False, quiet=False, check_output=False):
if not cls.works():
raise RuntimeError("Unable to locate pip")

check = subprocess.check_output if check_output else subprocess.check_call

if cls.use_import or use_import:
try:
import pip
return pip.main(["-q"] + command.split() if quiet else command.split())
except:
traceback.print_exc()
print("Error using pip import")
else:
return [x.split()[1] for x in datas if x.startswith("Version: ")][0]
except:
pass
try:
return check("{} {}{}".format(
cls.pip_command,
'-q ' if quiet else '',
command), shell=True)
except subprocess.CalledProcessError as e:
return e.returncode

@classmethod
def run_install(cls, cmd, use_import=False, quiet=False, check_output=False):
return cls.run("install %s" % cmd, use_import, quiet, check_output)

@classmethod
def run_show(cls, cmd, use_import=False, quiet=False, check_output=False):
return cls.run("show %s" % cmd, use_import, quiet, check_output)

@classmethod
def works(cls):
if not cls.looked_for:
cls.find_pip3()

return cls.pip_command or cls.use_import

@classmethod
def find_pip3(cls):
cls.looked_for = True

if cls._check_command_exists('pip3.5 -V'):
cls.pip_command = 'pip3.5'

elif cls._check_command_exists('pip3 -V'):
if subprocess.check_output('pip3 -V', shell=True).strip().endswith('(python 3.5)'):
cls.pip_command = 'pip3'

elif cls._check_command_exists('pip -V'):
if subprocess.check_output('pip -V', shell=True).strip().endswith('(python 3.5)'):
cls.pip_command = 'pip'
else:
try:
import pip
cls.use_import = True
except:
pass

return cls.works()

@classmethod
def get_module_version(cls, mod):
try:
out = cls.run_show(mod, check_output=True)
datas = str(out).split('\\r\\n')
expectedversion = datas[3]

if expectedversion.startswith('Version: '):
return expectedversion.split()[1]
else:
return [x.split()[1] for x in datas if x.startswith("Version: ")][0]
except:
pass

@staticmethod
def _check_command_exists(cmd):
try:
subprocess.check_output(cmd, shell=True)
return True
except subprocess.CalledProcessError:
return True
except:
traceback.print_exc()
return False

def install_module(mod, quiet=False):
# TODO: Error code checks, I got 2 for permission denied (needs admin to write)
try:
import pip
return pip.main(["-q", "install"] + mod.split() if quiet else ["install"] + mod.split())
except:
if check_for_pip():
return subprocess.check_call("pip %sinstall %s" % ('-q ' if quiet else '', mod))

def open_in_wb(text, printanyways=True, indents=4):
import webbrowser
Expand All @@ -52,27 +118,44 @@ def open_in_wb(text, printanyways=True, indents=4):
def main():
if not sys.version.startswith("3.5"):
print("Python 3.5+ is required. This version is %s" % sys.version.split()[0])
print("Attempting to locate python 3.5...")

try:
subprocess.check_output('py -3.5 -c "exit()"')
print("Python 3.5 found. Launching bot...")
os.system('start cmd /k py -3.5 run.py')
if sys.platform.startswith('win'):
print("Attempting to locate python 3.5...")

from random import sample
titlenum = ''.join(map(str, sample(range(50000), 6)))
titlestuff = str(hex(int(titlenum)))[2:]
pycom = None

os.system('title %s' % titlestuff)
os.system('taskkill /fi "WindowTitle eq %s"' % titlestuff)
try:
subprocess.check_output('py -3.5 -c "exit()"', shell=True)
pycom = 'py -3.5'
except:

except:
traceback.print_exc()
input("Press any key to continue . . .")
# check other locations or some shit
try:
subprocess.check_output('python3 -c "exit()"', shell=True)
pycom = 'python3'
except:
pass

if pycom:
print("Python 3 found. Launching bot...")
os.system('start cmd /k %s run.py' % pycom)

print("Please run the bot using python 3.5")
input("Press enter to continue . . .")

return

if '--upgrade' in sys.argv:
# MOAR CHECKS?
err = PIP.run_install('--upgrade -r requirements.txt', quiet=True)
if err == 2:
print("Upgrade failed, you may need to run it as admin")
elif err:
print("Automatic upgrade failed")

input("Press enter to continue . . .")
return


tried_requirementstxt = False
tryagain = True

Expand All @@ -88,8 +171,8 @@ def main():
traceback.print_exc()

if not tried_requirementstxt:
err = install_module('-r requirements.txt', True)
tried_requirementstxt = True
err = PIP.run_install('-r requirements.txt', quiet=True)

if err == 2:
print("\nIf that said \"Access is denied\", run it as admin.")
Expand All @@ -102,7 +185,7 @@ def unfuck(e):
try:
import pip
except:
if not check_for_pip():
if not PIP.works():
print("Additionally, pip cannot be imported. Has python been installed properly?")
print("Bot setup instructions can be found here:")
open_in_wb("https://github.com/SexualRhinoceros/MusicBot/blob/develop/README.md")
Expand All @@ -118,13 +201,13 @@ def unfuck(e):

print("Discord.py is not installed.")

if not check_for_git():
if not GIT.works():
print("Additionally, git is also not installed. Please install git.")
print("Bot setup instructions can be found here:")
open_in_wb("https://github.com/SexualRhinoceros/MusicBot/blob/develop/README.md")
return

err = install_module("git+https://github.com/Rapptz/discord.py@async")
err = PIP.run_install("git+https://github.com/Rapptz/discord.py@async")

if err:
print()
Expand All @@ -139,7 +222,7 @@ def unfuck(e):
elif e.name == 'opus':
print("Discord.py is out of date. Did you install the old version?")

err = install_module("--upgrade git+https://github.com/Rapptz/discord.py@async")
err = PIP.run_install("--upgrade git+https://github.com/Rapptz/discord.py@async")

if err:
print()
Expand All @@ -156,7 +239,7 @@ def unfuck(e):

print("Module 'win_unicode_console' is missing.")

err = install_module("win_unicode_console")
err = PIP.run_install("win_unicode_console")

if err:
print()
Expand Down

0 comments on commit eccf22c

Please sign in to comment.