Skip to content

Commit

Permalink
Merge e16c9f0 into 4214d47
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason Phan committed Jan 2, 2019
2 parents 4214d47 + e16c9f0 commit dda73ce
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 41 deletions.
8 changes: 7 additions & 1 deletion shallow_backup/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
from .prompts import *
from .reinstall import *
from .git_wrapper import *
from .utils import mkdir_warn_overwrite, destroy_backup_dir, expand_to_abs_path
from .utils import (
mkdir_warn_overwrite, destroy_backup_dir, expand_to_abs_path,
new_dir_is_valid)


# custom help options
Expand Down Expand Up @@ -64,6 +66,10 @@ def cli(show, all, dotfiles, configs, packages, fonts, old_path, new_path, remot
# User entered a new path, so update the config
if new_path:
abs_path = os.path.abspath(new_path)

if new_dir_is_valid(abs_path):
sys.exit(1)

print_path_blue("\nUpdating shallow-backup path to:", abs_path)
backup_config["backup_path"] = abs_path
write_config(backup_config)
Expand Down
26 changes: 10 additions & 16 deletions shallow_backup/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,16 @@ def backup_packages(backup_path, skip=False):
print_pkg_mgr_backup("npm")
command = "npm ls --global --parseable=true --depth=0"
temp_file_path = "{}/npm_temp_list.txt".format(backup_path)
run_cmd_write_stdout(command, temp_file_path)
npm_dest_file = "{0}/npm_list.txt".format(backup_path)
# Parse npm output
with open(temp_file_path, mode="r+") as temp_file:
# Skip first line of file
temp_file.seek(1)
with open(npm_dest_file, mode="w+") as dest:
for line in temp_file:
dest.write(line.split("/")[-1])

os.remove(temp_file_path)
if run_cmd_write_stdout(command, temp_file_path) == 0:
npm_dest_file = "{0}/npm_list.txt".format(backup_path)
# Parse npm output
with open(temp_file_path, mode="r+") as temp_file:
# Skip first line of file
temp_file.seek(1)
with open(npm_dest_file, mode="w+") as dest:
for line in temp_file:
dest.write(line.split("/")[-1])
os.remove(temp_file_path)

# atom package manager
print_pkg_mgr_backup("Atom")
Expand All @@ -151,11 +150,6 @@ def backup_packages(backup_path, skip=False):
dest = "{}/system_apps_list.txt".format(backup_path)
run_cmd_write_stdout(command, dest)

# Clean up empty package list files
for file in get_abs_path_subfiles(backup_path):
if os.path.getsize(file) == 0:
os.remove(file)


def backup_fonts(backup_path, skip=False):
"""
Expand Down
4 changes: 3 additions & 1 deletion shallow_backup/git_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,15 @@ def move_git_repo(source_path, dest_path):
dest_git_ignore = os.path.join(dest_path, '.gitignore')
git_exists = os.path.exists(dest_git_dir)
gitignore_exists = os.path.exists(dest_git_ignore)

if git_exists or gitignore_exists:
print_red_bold("Evidence of a git repo has been detected.")
if git_exists:
print_path_red("A git repo already exists here:", dest_git_dir)
if gitignore_exists:
print_path_red("A gitignore file already exists here:", dest_git_ignore)
print_red_bold("Exiting to prevent accidental deletion of user data.")
sys.exit()
sys.exit(1)

git_dir = os.path.join(source_path, '.git')
git_ignore_file = os.path.join(source_path, '.gitignore')
Expand All @@ -115,3 +116,4 @@ def move_git_repo(source_path, dest_path):
print_blue_bold("Moving git repo to new location.")
except FileNotFoundError:
pass

21 changes: 15 additions & 6 deletions shallow_backup/printing.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
import inquirer
from colorama import Fore, Style
from .constants import ProjInfo
Expand Down Expand Up @@ -83,23 +84,31 @@ def print_section_header(title, color):


def print_pkg_mgr_backup(mgr):
print("{}Backing up {}{}{}{}{} packages list...{}".format(Fore.BLUE, Style.BRIGHT, Fore.YELLOW, mgr, Fore.BLUE,
Style.NORMAL, Style.RESET_ALL))
print("{}Backing up {}{}{}{}{} packages list...{}".format(Fore.BLUE, Style.BRIGHT, Fore.YELLOW, mgr,
Fore.BLUE, Style.NORMAL, Style.RESET_ALL))


def print_pkg_mgr_reinstall(mgr):
print("{}Reinstalling {}{}{}{}{}...{}".format(Fore.BLUE, Style.BRIGHT, Fore.YELLOW, mgr, Fore.BLUE, Style.NORMAL, Style.RESET_ALL))
print("{}Reinstalling {}{}{}{}{}...{}".format(Fore.BLUE, Style.BRIGHT, Fore.YELLOW,
mgr, Fore.BLUE, Style.NORMAL, Style.RESET_ALL))


def prompt_yes_no(message, color):
def print_shell_cmd_error(cmd):
print("{}$ {}".format(print_path_red('An error occurred while running: '), cmd))


def prompt_yes_no(message, color, invert=False):
"""
Print question and return True or False depending on user selection from list.
"""
questions = [inquirer.List('choice',
message=color + Style.BRIGHT + message + Fore.BLUE,
choices=[' Yes', ' No'],
choices=(' No', ' Yes') if invert else (' Yes', ' No')
)
]

answers = inquirer.prompt(questions)
return answers.get('choice').strip().lower() == 'yes'
if answers:
return answers.get('choice').strip().lower() == 'yes'
else:
sys.exit(1)
31 changes: 22 additions & 9 deletions shallow_backup/prompts.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import os
import sys
import inquirer
from colorama import Fore, Style
from .utils import *
from .printing import *
from .config import *
from .git_wrapper import git_set_remote, move_git_repo
from .utils import new_dir_is_valid


def path_update_prompt(config):
Expand All @@ -14,14 +16,20 @@ def path_update_prompt(config):
"""
current_path = config["backup_path"]
print_path_blue("Current shallow-backup path:", current_path)
if prompt_yes_no("Would you like to update this?", Fore.GREEN):
print_green_bold("Enter relative or absolute path:")
abs_path = expand_to_abs_path(input())
print_path_blue("\nUpdating shallow-backup path to:", abs_path)
mkdir_warn_overwrite(abs_path)
move_git_repo(current_path, abs_path)
config["backup_path"] = abs_path
write_config(config)
if prompt_yes_no("Would you like to update this?", Fore.GREEN, invert=True):
while True:
print_green_bold("Enter relative or absolute path:")
abs_path = expand_to_abs_path(input())

if new_dir_is_valid(abs_path):
continue

print_path_blue("\nUpdating shallow-backup path to:", abs_path)
mkdir_warn_overwrite(abs_path)
move_git_repo(current_path, abs_path)
config["backup_path"] = abs_path
write_config(config)
return


def git_url_prompt(repo):
Expand Down Expand Up @@ -159,4 +167,9 @@ def main_menu_prompt():
]

answers = inquirer.prompt(questions)
return answers.get('choice').strip().lower()

if answers:
return answers.get('choice').strip().lower()
else:
# KeyboardInterrupts
sys.exit(1)
11 changes: 6 additions & 5 deletions shallow_backup/reinstall.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,10 @@ def reinstall_configs_sb(configs_path):
"""
print_section_header("REINSTALLING CONFIG FILES", Fore.BLUE)

def backup_prefix(path):
return os.path.join(configs_path, path)

config = get_config()
for dest_path, backup_loc in config["configs_mapping"].items():
for dest_path, backup_loc in config["config_mapping"].items():
dest_path = quote(dest_path)
path_to_backup = quote(backup_prefix(backup_loc))
path_to_backup = quote(os.path.join(configs_path, backup_loc))
# TODO: REFACTOR WITH GENERIC COPY FUNCTION.
if os.path.isdir(path_to_backup):
copytree(path_to_backup, dest_path)
Expand All @@ -64,6 +61,10 @@ def reinstall_packages_sb(packages_path):
"""
Reinstall all packages from the files in backup/installs.
"""
if not os.path.isdir(packages_path) or not os.listdir(packages_path):
print_red_bold('No package backups found.')
sys.exit(1)

print_section_header("REINSTALLING PACKAGES", Fore.BLUE)

# Figure out which install lists they have saved
Expand Down
17 changes: 14 additions & 3 deletions shallow_backup/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ def run_cmd(command):
"""
try:
if not isinstance(command, list):
process = sp.run(command.split(), stdout=sp.PIPE)
process = sp.run(command.split(), stdout=sp.PIPE, stderr=sp.DEVNULL)
return process
else:
process = sp.run(command, stdout=sp.PIPE)
process = sp.run(command, stdout=sp.PIPE, stderr=sp.DEVNULL)
return process
except FileNotFoundError: # If package manager is missing
return None
Expand All @@ -25,11 +25,22 @@ def run_cmd_write_stdout(command, filepath):
"""
Runs a command and then writes its stdout to a file
:param: command str representing command to run
:param: filepath str file to write command's stdout to
"""
process = run_cmd(command)
if process:
if process and process.returncode == 0:
with open(filepath, "w+") as f:
f.write(process.stdout.decode('utf-8'))
return 0
else:
print_pkg_mgr_error(command) # skip package or say it's not installed?
return 1


def new_dir_is_valid(abs_path):
if os.path.isfile(abs_path):
print_path_red('New path is an existing file:', abs_path)
print_red_bold('Please enter a directory.\n')


def safe_mkdir(directory):
Expand Down

0 comments on commit dda73ce

Please sign in to comment.