Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exception handling #207

Merged
merged 31 commits into from
Jan 2, 2019
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
5b47b3c
Exception handling for backups (#206)
Dec 26, 2018
1d279fd
Exception handling for --new_path (#206)
Dec 26, 2018
59ba373
Typo in config dict key
Dec 26, 2018
a9b1956
Fixed reinstalling packages w/ no package backups
Dec 27, 2018
ecbfbe5
coverage: trailing space
Dec 27, 2018
289cb65
Added EOF blank line
Jan 1, 2019
f436375
Updated to exit after no package backups are found
Jan 1, 2019
41c6f99
PEP8
Jan 1, 2019
5a96b6c
got rid of extra EOL blank line
Jan 1, 2019
cb2b47e
break to return
Jan 1, 2019
28f40b6
Refactored out existing file check into utils.py
Jan 1, 2019
fb5cef6
PEP8
Jan 1, 2019
5054d89
Updated backup prompt to not be literal satan
Jan 1, 2019
11434b6
Added check for existing but empty package directories
Jan 1, 2019
3783008
Fixed empty dir check and modified package error message
Jan 1, 2019
ef21b41
Updated existing file check function name
alichtman Jan 1, 2019
4fc4841
Pulled renaming suggested change
Jan 1, 2019
6947433
Modified empty directory check condition
Jan 2, 2019
89d425f
ternary up in here
Jan 2, 2019
65ae865
renamed print_pkg_mgr_error()
Jan 2, 2019
551f4a3
modified package error message
Jan 2, 2019
2b90678
removed unnecessary parameters and updated function calls
Jan 2, 2019
e16c9f0
missing comma
Jan 2, 2019
6584ba7
removed print_shell_cmd_error
Jan 2, 2019
eaf0b9d
Updated new_dir_is_valid to return bool
Jan 2, 2019
ff1233a
updated to reflect new new_dir_is_valid()
Jan 2, 2019
ee9343d
removed comment
Jan 2, 2019
6c7f9fa
Updated error message
Jan 2, 2019
92adb5b
moved empty backup dir check into function
Jan 2, 2019
e9ae1aa
updated empty_backup_dir_check() message
Jan 2, 2019
2031741
Fix error message.
alichtman Jan 2, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
existing_file_check)


# 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 existing_file_check(abs_path):
sys.exit(1)
alichtman marked this conversation as resolved.
Show resolved Hide resolved

print_path_blue("\nUpdating shallow-backup path to:", abs_path)
backup_config["backup_path"] = abs_path
write_config(backup_config)
Expand Down
38 changes: 16 additions & 22 deletions shallow_backup/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,59 +102,53 @@ def backup_packages(backup_path, skip=False):
print_pkg_mgr_backup(mgr)
command = "{} list".format(mgr)
dest = "{}/{}_list.txt".format(backup_path, mgr.replace(" ", "-"))
run_cmd_write_stdout(command, dest)
run_cmd_write_stdout(command, dest, mgr)
ibokuri marked this conversation as resolved.
Show resolved Hide resolved

# cargo
print_pkg_mgr_backup("cargo")
command = "ls {}".format(home_prefix(".cargo/bin/"))
dest = "{}/cargo_list.txt".format(backup_path)
run_cmd_write_stdout(command, dest)
run_cmd_write_stdout(command, dest, 'cargo')
ibokuri marked this conversation as resolved.
Show resolved Hide resolved

# pip
print_pkg_mgr_backup("pip")
command = "pip list --format=freeze"
dest = "{}/pip_list.txt".format(backup_path)
run_cmd_write_stdout(command, dest)
run_cmd_write_stdout(command, dest, 'pip')
ibokuri marked this conversation as resolved.
Show resolved Hide resolved

# npm
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, 'npm') == 0:
ibokuri marked this conversation as resolved.
Show resolved Hide resolved
ibokuri marked this conversation as resolved.
Show resolved Hide resolved
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")
command = "apm list --installed --bare"
dest = "{}/apm_list.txt".format(backup_path)
run_cmd_write_stdout(command, dest)
run_cmd_write_stdout(command, dest, 'Atom')
ibokuri marked this conversation as resolved.
Show resolved Hide resolved

# macports
print_pkg_mgr_backup("macports")
command = "port installed requested"
dest = "{}/macports_list.txt".format(backup_path)
run_cmd_write_stdout(command, dest)
run_cmd_write_stdout(command, dest, 'macports')
ibokuri marked this conversation as resolved.
Show resolved Hide resolved

# system installs
print_pkg_mgr_backup("System Applications")
applications_path = get_applications_dir()
command = "ls {}".format(applications_path)
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)
run_cmd_write_stdout(command, dest, 'system applications')
ibokuri marked this conversation as resolved.
Show resolved Hide resolved


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

11 changes: 10 additions & 1 deletion 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 @@ -91,6 +92,11 @@ def print_pkg_mgr_reinstall(mgr):
print("{}Reinstalling {}{}{}{}{}...{}".format(Fore.BLUE, Style.BRIGHT, Fore.YELLOW, mgr, Fore.BLUE, Style.NORMAL, Style.RESET_ALL))


def print_pkg_mgr_error(mgr):
print("{}Package {}{}{}{}{} not installed.{}".format(Fore.RED, Style.BRIGHT, Fore.YELLOW, mgr, Fore.RED,
Style.NORMAL, Style.RESET_ALL))


def prompt_yes_no(message, color):
"""
Print question and return True or False depending on user selection from list.
Expand All @@ -102,4 +108,7 @@ def prompt_yes_no(message, color):
]

answers = inquirer.prompt(questions)
return answers.get('choice').strip().lower() == 'yes'
if answers:
return answers.get('choice').strip().lower() == 'yes'
else:
sys.exit(1)
29 changes: 21 additions & 8 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 existing_file_check


def path_update_prompt(config):
Expand All @@ -15,13 +17,19 @@ 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)
while True:
print_green_bold("Enter relative or absolute path:")
abs_path = expand_to_abs_path(input())

if existing_file_check(abs_path):
ibokuri marked this conversation as resolved.
Show resolved Hide resolved
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):
print_red_bold('No package backups found.')
alichtman marked this conversation as resolved.
Show resolved Hide resolved
sys.exit(1)

print_section_header("REINSTALLING PACKAGES", Fore.BLUE)

# Figure out which install lists they have saved
Expand Down
20 changes: 16 additions & 4 deletions shallow_backup/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,36 @@ 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)
alichtman marked this conversation as resolved.
Show resolved Hide resolved
alichtman marked this conversation as resolved.
Show resolved Hide resolved
return process
else:
process = sp.run(command, stdout=sp.PIPE)
process = sp.run(command, stdout=sp.PIPE, stderr=sp.DEVNULL)
ibokuri marked this conversation as resolved.
Show resolved Hide resolved
return process
except FileNotFoundError: # If package manager is missing
return None


def run_cmd_write_stdout(command, filepath):
def run_cmd_write_stdout(command, filepath, package):
alichtman marked this conversation as resolved.
Show resolved Hide resolved
ibokuri marked this conversation as resolved.
Show resolved Hide resolved
"""
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
:param: package str name of package to print for failed commands
ibokuri marked this conversation as resolved.
Show resolved Hide resolved
"""
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
ibokuri marked this conversation as resolved.
Show resolved Hide resolved
else:
print_pkg_mgr_error(package) # skip package or say it's not installed?
return 1


def existing_file_check(abs_path):
ibokuri marked this conversation as resolved.
Show resolved Hide resolved
if os.path.isfile(abs_path):
print_path_red('New path is an existing file:', abs_path)
alichtman marked this conversation as resolved.
Show resolved Hide resolved
print_red_bold('Please enter a directory.\n')


def safe_mkdir(directory):
Expand Down