Example #1
0
def finish_install(program_internal_name):
    """End of Install.

    Ran after every program install.

    Args:
        program_internal_name (str): Name of program as stored in the database

    """
    config.vprint("Removing temporary install directory (if it exists)")
    try:
        rmtree("/tmp/hamstall-temp")
    except FileNotFoundError:
        pass
    config.vprint("Adding program to hamstall list of programs")
    config.db["programs"].update({program_internal_name: {"desktops": []}})
    config.write_db()
    yn = generic.get_input('Would you like to add the program to your PATH? [Y/n]', ['y', 'n'], 'y')
    if yn == 'y':
        pathify(program_internal_name)
    yn = generic.get_input('Would you like to create a binlink? [y/N]', ['y', 'n'], 'n')
    if yn == 'y':
        binlink(program_internal_name)
    yn = generic.get_input('Would you like to create a desktop file? [y/N]', ['y', 'n'], 'n')
    if yn == 'y':
        create_desktop(program_internal_name)
    print("Install complete!")
    generic.leave()
Example #2
0
def configure():
    """Change hamstall Options."""
    while True:
        print("""
Select an option:
au - Enable/disable the ability to install updates when hamstall is run. Currently {au}.
v - Enable/disable verbose mode, showing more output when hamstall commands are run. Currently {v}.
b - Swap branches in hamstall. Allows you to get updates sooner at the cost of possible bugs. Current branch: {b}.
e - Exit hamstall
        """.format(
            au=generic.endi(config.read_config("AutoInstall")), v=generic.endi(config.read_config("Verbose")),
            b=config.db["version"]["branch"]
        ))
        option = generic.get_input("[au/v/b/E] ", ['au', 'v', 'b', 'e'], 'e')
        if option == 'au':
            if not can_update:
                print("requests isn't installed, so AutoInstall cannot be enabled!")
            else:
                key = "AutoInstall"
        elif option == 'v':
            key = "Verbose"
        elif option == 'b':
            branch_wizard()
            key = None
        elif option == 'e':
            generic.leave()
        if key is not None:
            new_value = config.change_config(key, "flip")
            print("\n{key} mode {value}!".format(key=key, value=generic.endi(new_value)))
Example #3
0
def command(program):
    """Mini-Shell.

    Takes commands and passes them to the user's command interpreter while in the program directory

    Args:
        program (str): Program to run commands on

    """
    run = 'y'
    while run == 'y':
        command = input('Please enter a command: ')
        call(["cd", "~/.hamstall/bin/{}/".format(program), "&&", command])
        run = generic.get_input('Would you like to run another command? [y/N]', ['y', 'n'], 'n')
    return
Example #4
0
def manage(program):
    """Manage Installed Program.

    Args:
        program (str): Internal name of program to manage

    """
    while True:
        print("Enter an option to manage " + program + ":")
        print("b - Create binlinks for " + program)
        print("p - Add " + program + " to PATH")
        print("n - Rename " + program)
        print("u - Uninstall " + program)
        print("r - Remove all binlinks + PATHs for " + program)
        print("d - Create a .desktop file for " + program)
        print("rd - Remove a .desktop file for " + program)
        print("c - Run a command inside " + program + "'s directory")
        print("s - Launch a shell inside " + program + "'s directory")
        print("E - Exit program management")
        option = generic.get_input("[b/p/n/u/r/d/rd/c/s/E]", ['b', 'p', 'n', 'u', 'r', 'd', 'c', 'rd', 's', 'e'], 'e')
        if option == 'b':
            binlink(program)
        elif option == 'p':
            pathify(program)
        elif option == 'n':
            program = rename(program)
        elif option == 'u':
            uninstall(program)
            generic.leave()
        elif option == 'r':
            config.remove_line(program, "~/.hamstall/.bashrc", 'poundword')
        elif option == 'd':
            create_desktop(program)
        elif option == 'rd':
            remove_desktop(program)
        elif option == 'c':
            command(program)
        elif option == 's':
            print("When you exit the shell, you will be returned to here.")
            os.chdir(config.full("~/.hamstall/bin/" + program + "/"))
            call(["/bin/bash"])
        elif option == 'e':
            generic.leave()
Example #5
0
def binlink(program_internal_name):
    """Link Program.

    Creates an alias that cd's into a program directory before running a file in the program

    Args:
        program_internal_name (str): Name of program to create a binlink for

    """
    while True:
        files = os.listdir(config.full('~/.hamstall/bin/' + program_internal_name + '/'))
        print(' '.join(files))
        file_chosen = 'Cool fact. This line was originally written on line 163.'
        while file_chosen not in files:  # Get file to binlink from user
            file_chosen = input('Please enter a file listed above. If you would like to cancel, type exit: ')
            if file_chosen == "exit":
                return
        line_to_add = 'alias ' + file_chosen + "='cd " + config.full('~/.hamstall/bin/' + program_internal_name) + \
                      '/ && ./' + file_chosen + "' # " + program_internal_name + "\n"
        config.vprint("Adding alias to bashrc")
        config.add_line(line_to_add, "~/.hamstall/.bashrc")
        yn = generic.get_input('Would you like to continue adding files to be run directly? [y/N]', ['y', 'n'], 'n')
        if yn == 'n':
            return
Example #6
0
def branch_wizard():
    """Switch Branches."""
    if get_online_version("prog", "master") <= 18:
        extra_warning = """
hamstall stable release 1.2.0 hasn't happened yet!
You cannot reset to the older version of hamstall! You must stay on this version!
###############
        """
    else:
        extra_warning = ""
    print("""\n\n
####WARNING####
WARNING: You are changing branches of hamstall!
Changing from master to beta means you may receive updates that contain bugs, some extremely severe!
Changing from beta to master means you will either HAVE ALL OF YOUR HAMSTALL PROGRAMS DELETED
or you will have to STAY ON THE UPDATE YOU CURRENTLY HAVE UNTIL MASTER CATCHES UP!

Switching branches will trigger an immediate update of hamstall!
###############
{extra_warning}
Select a branch:
m - Master branch. Less bugs, more stable, wait for updates.
b - Beta branch. More bugs, less stable, updates asap.
E - Exit branch wizard and don't change branches.
    """.format(extra_warning=extra_warning))
    ans = generic.get_input("[m/b/E] ", ['m', 'b', 'e'], 'e')
    if ans == 'e':
        print("Not changing branches!")
        generic.leave()
    elif ans == 'm' and config.db["version"]["branch"] == "master":
        print("Already on the master branch, not switching!")
        generic.leave()
    elif ans == 'b' and config.db["version"]["branch"] == "beta":
        print("Already on the beta branch, not switching!")
        generic.leave()
    else:
        check = input('Type "YES" (without the quotes) to confirm the branch switch! ')
        if check != "YES":
            print("Cancelling branch switch.")
            generic.leave()
        if ans == 'm':
            branch = "master"
            if not config.check_bin("git"):
                print("Git is not installed! Your branch can be switched, but downgrading is impossible! "
                "If you would like to exit here, type \"y\"!")
                if generic.get_input("", ['y','n'], 'n') == 'y':
                    print("Branch has not been changed!")
                    generic.leave(1)
                else:
                    print("Continuing with branch switch.")
        elif ans == 'b':
            branch = "beta"
        print("Changing branches and updating hamstall!")
        config.vprint("Switching branch and writing change to file")
        config.db["version"]["branch"] = branch
        config.write_db()
        if branch == "beta":
            config.vprint("Updating hamstall...")
            update(True)
            generic.leave(0)
        elif branch == "master":
            if get_online_version("prog", "master") <= 18:
                print("Cannot downgrade; staying on this version until master catches up!")
                generic.leave(0)
            print("Would you like to downgrade? If you do, all hamstall programs will be deleted!")
            dr = generic.get_input("If you don't, hamstall will remain at its current version until master is at a newer release! [y/N]",
            ['y', 'n'], 'n')
            if dr == 'y':
                config.vprint("Deleting and re-installing hamstall.")
                os.chdir(config.full("~/.hamstall"))
                config.vprint("Removing old hamstall .pys")
                for i in os.listdir():
                    i_num = len(i) - 3
                    if i[i_num:len(i)] == '.py':
                        try:
                            os.remove(i)
                        except FileNotFoundError:
                            pass
                try:
                    rmtree("/tmp/hamstall-temp")
                except FileNotFoundError:
                    pass
                os.mkdir("/tmp/hamstall-temp")
                os.chdir("/tmp/hamstall-temp")
                config.vprint("Cloning hamstall from the master branch")
                call(["git", "clone", "https://github.com/hammy3502/hamstall.git"])
                os.chdir("/tmp/hamstall-temp/hamstall")
                config.vprint("Adding new hamstall .pys")
                for i in os.listdir():
                    i_num = len(i) - 3
                    if i[i_num:len(i)] == '.py':
                        copyfile(i, config.full('~/.hamstall/' + i))
                config.vprint("Removing old database and programs.")
                try:
                    os.remove(config.full("~/.hamstall/database"))
                except FileNotFoundError:
                    pass
                try:
                    rmtree(config.full("~/.hamstall/bin"))
                except FileNotFoundError:
                    pass
                os.mkdir(config.full("~/.hamstall/bin"))
                print("Please run hamstall again to re-create the database!")
                config.unlock()
                config.db = {"refresh": True}
                config.write_db()
                sys.exit(0)
Example #7
0
def create_desktop(program_internal_name):
    """Create Desktop.

    Walks the user through creating a .desktop file for a program

    Args:
        program_internal_name (str): Name of program as stored in the database

    """
    files = os.listdir(config.full('~/.hamstall/bin/' + program_internal_name + '/'))
    print(' '.join(files))
    program_file = '/Placeholder/'
    config.vprint("Getting user inputs")
    while program_file not in files:  # Get file to binlink from user
        program_file = input('Please enter a file listed above. If you would like to cancel, type exit: ')
        if program_file == "exit":
            return
    desktop_name = "{}-{}".format(program_file, program_internal_name)
    if config.exists("~/.local/share/applications/{}.desktop".format(desktop_name)):
        print("Desktop file already exists!")
        return
    exec_path = config.full("~/.hamstall/bin/{}/{}".format(program_internal_name, program_file))
    path = config.full("~/.hamstall/bin/{}/".format(program_internal_name))
    comment = "/"
    while not comment.replace(" ", "").isalnum() and comment != "":
        comment = input("Please input a comment for the application: ")
    if comment == "":
        comment = program_internal_name
    icon = ";"
    while not icon.replace("-", "").replace("_", "").replace("/", "").isalnum() and icon != "":
        icon = input("Enter the path to an icon, the name of the icon, or press ENTER for no icon! ")
    if icon != "":
        icon = "Icon=" + icon
    terminal = generic.get_input("Should this program launch a terminal to run it in? [y/N]", ['y', 'n'], 'n')
    if terminal.lower() == 'y':
        should_terminal = "True"
    else:
        should_terminal = "False"
    name = "/"
    while not name.replace(" ", "").isalnum() and name != "":
        name = input("Please enter a name: ")
    if name == "":
        name = program_internal_name
    ans = " "
    chosen_categories = []
    categories = ["audio", "video", "development", "education", "game", "graphics", "network", "office", "science",
                  "settings", "system", "utility", "end"]
    while ans.lower() != "end":
        print("Please enter categories, one at a time, from the list of .desktop categories below (defaults to "
              "Utility). Type \"end\" to end category selection. \n")
        print(", ".join(categories))
        ans = generic.get_input("", categories, "Utility")
        if ans.capitalize() in chosen_categories or ans == "end":
            pass
        else:
            ans = ans.capitalize()
            chosen_categories.append(ans)
            if ans in ["Audio", "Video"] and not ("AudioVideo" in chosen_categories):
                chosen_categories.append("AudioVideo")
    if not chosen_categories:
        chosen_categories = ["Utility"]
    cats = ";".join(chosen_categories) + ";"  # Get categories for the .desktop
    to_write = """
[Desktop Entry]
Name={name}
Comment={comment}
Path={path}
Exec={exec_path}
{icon}
Terminal={should_terminal}
Type=Application
Categories={categories}
""".format(name=name, comment=comment, exec_path=exec_path,
           should_terminal=should_terminal, categories=cats,
           icon=icon, path=path)
    os.chdir(config.full("~/.local/share/applications/"))
    config.create("./{}.desktop".format(desktop_name))
    with open(config.full("./{}.desktop".format(desktop_name)), 'w') as f:
        f.write(to_write)
    config.db["programs"][program_internal_name]["desktops"].append(desktop_name)
    print("\nDesktop file created!")
Example #8
0
if config.db == {"refresh": True}:  # Downgrade check
    print("Hang tight! We're finishing up your downgrade...")
    config.create("~/.hamstall/database")
    prog_manage.create_db()
    config.db = config.get_db()
    config.write_db()
    print("We're done! Continuing hamstall execution...")

if args.first:  # Check if -f or --first is supplied
    prog_manage.first_time_setup(False)

if not (config.exists('~/.hamstall/hamstall.py')
        ):  # Make sure hamstall is installed
    """Install hamstall if it doesn't exist"""
    yn = generic.get_input(
        'hamstall is not installed on your system. Would you like to install it? [Y/n]',
        ['y', 'n', 'debug'], 'y')
    if yn == 'y':
        prog_manage.first_time_setup(False)
    elif yn == 'debug':
        prog_manage.first_time_setup(True)
    else:
        print('hamstall not installed.')
        config.unlock()
        sys.exit(0)
    generic.leave()

try:  # Lingering upgrades check
    file_version = prog_manage.get_file_version('file')
except KeyError:
    file_version = 1