Skip to content

Commit

Permalink
Merge pull request #271 from alichtman/refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
alichtman committed May 10, 2020
2 parents bc6fe3f + 65161a5 commit 38ce431
Show file tree
Hide file tree
Showing 9 changed files with 42 additions and 55 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -48,12 +48,12 @@ Usage: shallow-backup [OPTIONS]

Options:
--add_dot Add a dotfile or dotfolder to config by path.
-all Full back up.
-configs Back up app config files.
-delete_config Delete config file.
-destroy_backup Delete backup directory.
-dotfiles Back up dotfiles.
-fonts Back up installed fonts.
-full_backup Full back up.
--new_path TEXT Input a new back up directory path.
-no_splash Don't display splash screen.
-old_path Skip setting new back up directory path prompt.
Expand Down
16 changes: 8 additions & 8 deletions shallow_backup/__main__.py
Expand Up @@ -12,7 +12,7 @@
# custom help options
@click.command(context_settings=dict(help_option_names=['-h', '-help', '--help']))
@click.option('--add_dot', default=None, help="Add a dotfile or dotfolder to config by path.")
@click.option('-all', is_flag=True, default=False, help="Full back up.")
@click.option('-full_backup', is_flag=True, default=False, help="Full back up.")
@click.option('-configs', is_flag=True, default=False, help="Back up app config files.")
@click.option('-delete_config', is_flag=True, default=False, help="Delete config file.")
@click.option('-destroy_backup', is_flag=True, default=False, help='Delete backup directory.')
Expand All @@ -31,7 +31,7 @@
@click.option('-separate_dotfiles_repo', is_flag=True, default=False, help="Use if you are trying to maintain a separate dotfiles repo and running into issue #229.")
@click.option('-show', is_flag=True, default=False, help="Display config file.")
@click.option('--version', '-v', is_flag=True, default=False, help='Display version and author info.')
def cli(add_dot, all, configs, delete_config, destroy_backup, dotfiles, fonts, new_path,
def cli(add_dot, full_backup, configs, delete_config, destroy_backup, dotfiles, fonts, new_path,
no_splash, old_path, packages, reinstall_all, reinstall_configs,
reinstall_dots, reinstall_fonts, reinstall_packages, remote,
separate_dotfiles_repo, show, version):
Expand All @@ -46,10 +46,10 @@ def cli(add_dot, all, configs, delete_config, destroy_backup, dotfiles, fonts, n

# Process CLI args
admin_action = any([add_dot, delete_config, destroy_backup, show, version])
has_cli_arg = any([old_path, all, dotfiles, packages, fonts, configs,
has_cli_arg = any([old_path, full_backup, dotfiles, packages, fonts, configs,
reinstall_dots, reinstall_fonts, reinstall_all,
reinstall_configs, reinstall_packages])
skip_prompt = any([all, dotfiles, configs, packages, fonts, reinstall_packages, reinstall_configs, reinstall_dots,
skip_prompt = any([full_backup, dotfiles, configs, packages, fonts, reinstall_packages, reinstall_configs, reinstall_dots,
reinstall_fonts])

safe_create_config()
Expand Down Expand Up @@ -123,9 +123,9 @@ def cli(add_dot, all, configs, delete_config, destroy_backup, dotfiles, fonts, n
reinstall_dots_sb(dotfiles_path)
elif reinstall_all:
reinstall_all_sb(dotfiles_path, packages_path, fonts_path, configs_path)
elif all:
elif full_backup:
backup_all(dotfiles_path, packages_path, fonts_path, configs_path, skip=True)
git_add_all_commit_push(repo, "all")
git_add_all_commit_push(repo, "full_backup")
elif dotfiles:
backup_dotfiles(dotfiles_path, skip=True)
git_add_all_commit_push(repo, "dotfiles", separate_dotfiles_repo)
Expand All @@ -143,7 +143,7 @@ def cli(add_dot, all, configs, delete_config, destroy_backup, dotfiles, fonts, n
selection = main_menu_prompt().lower().strip()
selection_words = selection.split()
if selection.startswith("back up"):
if selection_words[-1] == "all":
if selection_words[-1] == "full_backup":
backup_all(dotfiles_path, packages_path, fonts_path, configs_path)
git_add_all_commit_push(repo, selection_words[-1])
elif selection_words[-1] == "dotfiles":
Expand All @@ -167,7 +167,7 @@ def cli(add_dot, all, configs, delete_config, destroy_backup, dotfiles, fonts, n
reinstall_fonts_sb(fonts_path)
elif selection_words[-1] == "dotfiles":
reinstall_dots_sb(dotfiles_path)
elif selection_words[-1] == "all":
elif selection_words[-1] == "full_backup":
reinstall_all_sb(dotfiles_path, packages_path, fonts_path, configs_path)
elif selection.endswith("config"):
if selection == "show config":
Expand Down
8 changes: 5 additions & 3 deletions shallow_backup/compatibility.py
Expand Up @@ -3,17 +3,17 @@


def get_os_name():
"""Returns name of OS"""
return platform.system().lower()


def get_home():
"""Returns path to ~"""
return os.path.expanduser('~')


def get_config_paths():
"""
Returns a dict of config paths for the correct OS.
"""
"""Returns a dict of config paths for the correct OS."""
if "darwin" == get_os_name():
sublime2_path = os.path.join(get_home(), "Library/Application Support/Sublime Text 2")
sublime3_path = os.path.join(get_home(), "Library/Application Support/Sublime Text 3")
Expand Down Expand Up @@ -51,6 +51,7 @@ def get_config_paths():


def get_fonts_dir():
"""Returns default path to fonts on the current platform"""
os_name = get_os_name()
if os_name == "darwin":
return os.path.join(get_home(), "Library/Fonts")
Expand All @@ -59,6 +60,7 @@ def get_fonts_dir():


def get_applications_dir():
"""Returns default path to applications directory"""
os_name = get_os_name()
if os_name == "darwin":
return "/Applications"
Expand Down
28 changes: 8 additions & 20 deletions shallow_backup/config.py
Expand Up @@ -24,9 +24,9 @@ def get_config():
:return: dictionary for config
"""
config_path = get_config_path()
with open(config_path) as f:
with open(config_path) as file:
try:
config = json.load(f)
config = json.load(file)
except json.decoder.JSONDecodeError:
print_red_bold(f"ERROR: Invalid syntax in {config_path}")
sys.exit(1)
Expand All @@ -37,17 +37,17 @@ def write_config(config):
"""
Write to config file
"""
with open(get_config_path(), 'w') as f:
json.dump(config, f, indent=4)
with open(get_config_path(), 'w') as file:
json.dump(config, file, indent=4)


def get_default_config():
"""
Returns a default, platform specific config.
"""
return {
"backup_path" : "~/shallow-backup",
"dotfiles" : [
"backup_path": "~/shallow-backup",
"dotfiles": [
".bashrc",
".bash_profile",
".gitconfig",
Expand All @@ -60,7 +60,7 @@ def get_default_config():
".zprofile",
".zshrc"
],
"dotfolders" : [
"dotfolders": [
".ssh",
".vim"
],
Expand All @@ -74,7 +74,7 @@ def get_default_config():
".pypirc",
".DS_Store",
],
"config_mapping" : get_config_paths()
"config_mapping": get_config_paths()
}


Expand All @@ -90,18 +90,6 @@ def safe_create_config():
backup_config = get_default_config()
safe_mkdir(os.path.split(backup_config_path)[0])
write_config(backup_config)
else:
# If it does exist, make sure it's not outdated.
# TODO: Move this to upgrade.py
with open(backup_config_path) as config:
if "[USER]" in config.readline().strip():
if prompt_yes_no("An outdated config file has been detected. Would you like to update this?",
Fore.GREEN):
delete_config_file()
safe_create_config()
else:
print_red_bold("ERROR: Outdated config file found.")
sys.exit(0)


def delete_config_file():
Expand Down
4 changes: 2 additions & 2 deletions shallow_backup/git_wrapper.py
Expand Up @@ -14,7 +14,7 @@
"fonts": "Back up fonts.",
"packages": "Back up packages.",
"configs": "Back up configs.",
"all": "Full back up.",
"full_backup": "Full back up.",
"dotfiles": "Back up dotfiles."
}

Expand Down Expand Up @@ -54,7 +54,7 @@ def create_gitignore(dir_path, key):
if key == "root-gitignore":
files_to_ignore = get_config()["default-gitignore"]
elif key == "dotfiles-gitignore":
pass
files_to_ignore = []
with open(os.path.join(dir_path, ".gitignore"), "w+") as f:
for ignore in files_to_ignore:
f.write("{}\n".format(ignore))
Expand Down
8 changes: 2 additions & 6 deletions shallow_backup/printing.py
Expand Up @@ -66,17 +66,13 @@ def print_version_info(cli=True):


def splash_screen():
"""
Display splash graphic, and then stylized version and author info.
"""
"""Display splash graphic, and then stylized version and author info."""
print(Fore.YELLOW + Style.BRIGHT + "\n" + ProjInfo.LOGO + Style.RESET_ALL)
print_version_info(False)


def print_section_header(title, color):
"""
Prints variable sized section header
"""
"""Prints variable sized section header."""
block = "#" * (len(title) + 2)
print("\n" + color + Style.BRIGHT + block)
print("#", title)
Expand Down
12 changes: 5 additions & 7 deletions shallow_backup/reinstall.py
Expand Up @@ -13,9 +13,7 @@


def reinstall_dots_sb(dots_path, home_path=os.path.expanduser("~")):
"""
Reinstall all dotfiles and folders by copying them to the home dir.
"""
"""Reinstall all dotfiles and folders by copying them to the home dir."""
empty_backup_dir_check(dots_path, 'dotfile')
print_section_header("REINSTALLING DOTFILES", Fore.BLUE)

Expand All @@ -34,10 +32,10 @@ def reinstall_dots_sb(dots_path, home_path=os.path.expanduser("~")):
destination = home_path
try:
copy(file, destination)
except PermissionError as e:
print_red_bold(f"ERROR: {e}")
except FileNotFoundError as e:
print_red_bold(f"ERROR: {e}")
except PermissionError as err:
print_red_bold(f"ERROR: {err}")
except FileNotFoundError as err:
print_red_bold(f"ERROR: {err}")
print_section_header("DOTFILE REINSTALLATION COMPLETED", Fore.BLUE)


Expand Down
3 changes: 1 addition & 2 deletions shallow_backup/upgrade.py
Expand Up @@ -8,8 +8,7 @@


def upgrade_from_pre_v3():
"""
Before v3.0, the config file was stored at ~/.shallow-backup. In v3.0,
"""Before v3.0, the config file was stored at ~/.shallow-backup. In v3.0,
the XDG Base Directory specification was adopted and the new config is
stored in either $XDG_CONFIG_HOME/shallow-backup/shallow-backup.conf or
~/.config/shallow-backup.conf. This method upgrades from
Expand Down
16 changes: 10 additions & 6 deletions shallow_backup/utils.py
Expand Up @@ -64,18 +64,21 @@ def mkdir_overwrite(path):
full_path = os.path.join(path, f)
# Allow dotfiles to be a sub-repo, and protect img folder.
if full_path.endswith(".git") or \
full_path.endswith(".gitignore") or \
full_path.endswith("README.md") or \
full_path.endswith("img"):
full_path.endswith(".gitignore") or \
full_path.endswith("README.md") or \
full_path.endswith("img"):
continue

if os.path.isdir(full_path):
dirs.append(full_path)
else:
files.append(full_path)

[os.remove(file) for file in files]
[rmtree(dir) for dir in dirs]
for file in files:
os.remove(file)

for directory in dirs:
rmtree(directory)
else:
os.makedirs(path)

Expand Down Expand Up @@ -152,7 +155,7 @@ def copy_dir_if_valid(source_dir, backup_path):
Copy dotfolder from $HOME, excluding invalid directories.
"""
invalid = {".Trash", ".npm", ".cache", ".rvm"}
if len(invalid.intersection(set(source_dir.split("/")))) != 0:
if invalid.intersection(set(source_dir.split("/"))) != set():
return
copytree(source_dir, backup_path, symlinks=False)

Expand Down Expand Up @@ -180,4 +183,5 @@ def expand_to_abs_path(path):


def create_dir_if_doesnt_exist(path):
"""Create directory at path"""
os.makedirs(path, exist_ok=True)

0 comments on commit 38ce431

Please sign in to comment.