├── filetailor ├── __init__.py ├── core │ ├── __init__.py │ ├── paths.py │ ├── uninstall.py │ ├── clean.py │ ├── update_yaml.py │ ├── initialize.py │ └── sync.py ├── data │ ├── __init__.py │ ├── config.ini │ ├── filetailor.yaml │ └── example_filetailor.yaml ├── helpers │ ├── __init__.py │ ├── cprint.py │ ├── get_option.py │ ├── okay_to_continue.py │ ├── diff.py │ ├── get_key_list.py │ ├── load_ini_files.py │ ├── load_yaml.py │ └── tailor_lines.py ├── config.py └── __main__.py ├── docs ├── logo.png ├── flowchart.png ├── flowchart.xcf ├── logo_no_background.png └── wiki │ ├── overview.md │ ├── file_imports.md │ └── sync.md ├── MANIFEST.in ├── pyproject.toml ├── .gitignore ├── README.md └── LICENSE /filetailor/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /filetailor/core/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /filetailor/data/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /filetailor/helpers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k4j8/filetailor/HEAD/docs/logo.png -------------------------------------------------------------------------------- /docs/flowchart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k4j8/filetailor/HEAD/docs/flowchart.png -------------------------------------------------------------------------------- /docs/flowchart.xcf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k4j8/filetailor/HEAD/docs/flowchart.xcf -------------------------------------------------------------------------------- /docs/logo_no_background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/k4j8/filetailor/HEAD/docs/logo_no_background.png -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include pyproject.toml 2 | 3 | # Include the license file 4 | include LICENSE.txt 5 | 6 | # Include the data files 7 | recursive-include filetailor/data * 8 | -------------------------------------------------------------------------------- /filetailor/data/config.ini: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | 3 | # If testing = True, additional options are provided at the CLI for debugging 4 | testing = False 5 | 6 | # Location of file to specify yaml and sync directories; run `filetailor init` to create 7 | # override_filetailor_ini_path = ~/.config/filetailor.ini 8 | -------------------------------------------------------------------------------- /filetailor/core/paths.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Shows configuration paths for filetailor""" 3 | 4 | import filetailor.config as ftconfig 5 | 6 | def main(): 7 | """Print paths""" 8 | 9 | print(f'config.ini: {ftconfig.config_ini_path}') 10 | print(f'filetailor.ini: {ftconfig.filetailor_ini_path}') 11 | print() 12 | for path in ftconfig.paths: 13 | print(f'{path}: {ftconfig.paths[path]}') 14 | -------------------------------------------------------------------------------- /filetailor/config.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from appdirs import AppDirs 4 | 5 | # https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules 6 | args = '' 7 | data = '' 8 | config_ini_path = '' 9 | override_filetailor_ini_path = '' 10 | filetailor_ini_path = '' 11 | paths = {} 12 | tools = {} 13 | yaml_default = '' 14 | yaml_devices = '' 15 | yaml_files = '' 16 | sync = '' 17 | dirs = AppDirs('filetailor', False) 18 | device_id = None 19 | -------------------------------------------------------------------------------- /docs/wiki/overview.md: -------------------------------------------------------------------------------- 1 | ```mermaid 2 | graph 3 | subgraph filetailor 4 | main.py 5 | end 6 | subgraph core 7 | clean.py 8 | initialize.py 9 | sync.py 10 | update_yaml.py 11 | end 12 | 13 | main.py --> config.py 14 | 15 | main.py --> load_config.py 16 | main.py --> load_yaml.py 17 | 18 | main.py --> initialize.py 19 | main.py --> clean.py 20 | main.py --> update_yaml.py 21 | main.py --> sync.py 22 | 23 | get_option.py --> config.py 24 | load_config.py --> config.py 25 | okay_to_continue.py --> get_option.py 26 | 27 | clean.py --> config.py 28 | clean.py --> okay_to_continue.py 29 | initialize.py --> load_config.py 30 | initialize.py --> config.py 31 | initialize.py --> okay_to_continue.py 32 | sync.py --> okay_to_continue.py 33 | sync.py --> get_option.py 34 | sync.py --> config.py 35 | sync.py --> diff.py 36 | update_yaml.py --> okay_to_continue.py 37 | update_yaml.py --> config.py 38 | ``` 39 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "filetailor" 7 | version = "0.2.1" 8 | requires-python = ">=3.6" 9 | dependencies = [ 10 | "appdirs>=1.4.4", 11 | "pyyaml>=5.4.1", 12 | "ruamel.yaml>=0.17.7", 13 | "termcolor>=1.1.0", 14 | ] 15 | authors = [ 16 | { name = "Kyle Johnston", email = "johnstonkylew@gmail.com" } 17 | ] 18 | description = "Copy and modify plain text files to a directory based on YAML to be synced between devices" 19 | readme = "README.md" 20 | license = "GPL-3.0-only" 21 | license-files = ["LICENCSE"] 22 | classifiers = [ 23 | "Natural Language :: English", 24 | "Operating System :: OS Independent", 25 | "Programming Language :: Python :: 3", 26 | "Topic :: System :: Systems Administration" 27 | ] 28 | 29 | [project.urls] 30 | Homepage = "https://github.com/k4j8/filetailor" 31 | Issues = "https://github.com/k4j8/filetailor/issues" 32 | 33 | [project.scripts] 34 | filetailor = "filetailor.__main__:main" 35 | -------------------------------------------------------------------------------- /filetailor/data/filetailor.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | # Everything is optional unless otherwise specified 3 | # If omitted, false by default 4 | # 5 | # Read https://github.com/k4j8/filetailor/blob/main/filetailor/data/example_filetailor.yaml for more options 6 | # See examples at https://github.com/k4j8/filetailor/wiki/FAQ 7 | # 8 | # default: 9 | # 10 | # # Replace VARIABLE_NAME with VARIABLE_VALUE in YAML and file contents 11 | # vars: 12 | # VARIABLE_NAME: VARIABLE_VALUE 13 | # 14 | # device DEVICE_ID: 15 | # # Overrides "default" above and can use the exact same options 16 | # 17 | # file FILE_ID: 18 | # # FILE_ID is what gets saved in the sync_dir and can be different than the 19 | # # actual file name 20 | # 21 | # # REQUIRED: PATH includes the file name unless syncing a directory 22 | # path: PATH 23 | # 24 | # # Use include_devices or exclude_devices but not both 25 | # include_devices : DEVICE_ID... 26 | # exclude_devices : DEVICE_ID... 27 | # 28 | # # If provided, only variables listed here will apply when tailoring the 29 | # # file to a device, otherwise all variables apply 30 | # vars: 31 | # - VARIABLE_NAME 32 | 33 | default: 34 | ... 35 | -------------------------------------------------------------------------------- /docs/wiki/file_imports.md: -------------------------------------------------------------------------------- 1 | ```mermaid 2 | graph 3 | 4 | linkStyle default interpolate basis 5 | 6 | subgraph __main__.py 7 | main1[Load config.ini] 8 | main2[What function are you running?] 9 | main3[No additional checks] 10 | main4[Record path] 11 | main5[ERROR] 12 | main6[Do sync/YAML/staging/filetailor.yaml exist?] 13 | main7[ERROR] 14 | main8[Load YAML] 15 | end 16 | 17 | subgraph read_filetailor_ini 18 | read1[Does filetailor.ini include expected paths?] 19 | read2[ERROR] 20 | end 21 | 22 | subgraph init.py 23 | init1[main] 24 | init2[Record path] 25 | init3[Create filetailor.ini] 26 | init4[Create paths and filetailor.yaml] 27 | end 28 | 29 | subgraph find_filetailor_ini 30 | find1[Does filetailor.ini exist?] 31 | end 32 | 33 | main1 --> main2 34 | main2 -- None --> main3 35 | main2 -- init --> init1 36 | 37 | main2 -- Other --> find1 38 | init1 --> find1 39 | find1 -- No --> main5 40 | find1 -- No --> init3 41 | find1 -- Yes, return path --> main4 42 | find1 -- Yes, return path --> init2 43 | 44 | main4 --> read1 45 | init2 --> read1 46 | read1 -- No --> read2 47 | read1 -- Yes --> main6 48 | read1 -- Yes --> init4 49 | 50 | main6 -- No --> main7 51 | main6 -- Yes --> main8 52 | ``` 53 | -------------------------------------------------------------------------------- /filetailor/helpers/cprint.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Prints colored text""" 3 | 4 | import filetailor.helpers.get_option 5 | from termcolor import cprint 6 | 7 | 8 | def is_quiet(cfile, cdevice): 9 | """Get whether quiet is true or false""" 10 | 11 | return filetailor.helpers.get_option.main('quiet', cfile, cdevice) 12 | 13 | 14 | def plain(text, cfile=None, cdevice=None): 15 | """Print uncolored text""" 16 | if not is_quiet(cfile, cdevice): 17 | print(text) 18 | 19 | 20 | def error(text, cfile=None, cdevice=None): 21 | """Color text for errors""" 22 | if not is_quiet(cfile, cdevice): 23 | cprint(text, 'red') 24 | 25 | 26 | def success(text, cfile=None, cdevice=None): 27 | """Color text for successfully modifying files""" 28 | if not is_quiet(cfile, cdevice): 29 | cprint(text, 'white', 'on_blue') 30 | 31 | 32 | def same(text, cfile=None, cdevice=None): 33 | """Color text for printing files that are the same""" 34 | if not is_quiet(cfile, cdevice): 35 | cprint(text, 'green') 36 | 37 | 38 | def differ(text, cfile=None, cdevice=None): 39 | """Color text for printing files that differ""" 40 | if not is_quiet(cfile, cdevice): 41 | cprint(text, 'red') 42 | -------------------------------------------------------------------------------- /docs/wiki/sync.md: -------------------------------------------------------------------------------- 1 | ```mermaid 2 | graph 3 | linkStyle default interpolate basis 4 | 5 | subgraph tailor_lines 6 | main 7 | update_comments 8 | end 9 | 10 | %% Specify order of certain files to avoid overlapping arrows 11 | 1((Start)) 12 | tailor_file 13 | filter_subfiles 14 | copy_file 15 | 16 | 1 --> status 17 | 1 --> backup 18 | 1 --> restore 19 | 20 | status --> backup_or_restore 21 | backup --> backup_or_restore 22 | restore --> backup_or_restore 23 | 24 | backup_or_restore --> run_script 25 | 26 | backup_or_restore --> setup 27 | 28 | backup_or_restore --> get_file_status 29 | 30 | get_file_status -- dirs --> diff_dir 31 | 32 | diff_dir --> filter_subfiles 33 | 34 | get_file_status -- files --> tailor_file 35 | diff_dir --> tailor_file 36 | 37 | backup_or_restore -- dirs --> copy_subfiles 38 | 39 | backup_or_restore -- files --> copy_files 40 | copy_subfiles --> copy_files 41 | 42 | copy_files --> copy_file 43 | copy_file --> copy_file_with_sudo 44 | 45 | copy_files --> create_dir 46 | copy_subfiles --> create_dir 47 | create_dir --> create_dir_with_sudo 48 | 49 | copy_file --> check_for_sudo 50 | create_dir --> check_for_sudo 51 | backup_or_restore --> check_for_sudo 52 | 53 | tailor_file --> main 54 | main --> update_comments 55 | ``` 56 | -------------------------------------------------------------------------------- /filetailor/helpers/get_option.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Gets active option based on CLI and YAML""" 3 | 4 | import filetailor.config as ftconfig 5 | 6 | 7 | def main(option, obj1=None, obj2=None): 8 | """Gets active option based on CLI and YAML""" 9 | 10 | yaml_default = ftconfig.yaml_default 11 | args = ftconfig.args 12 | 13 | # Use option in file, device, CLI args, then default 14 | result = None 15 | for obj in [obj1, obj2]: 16 | # Check obj1 then, if not found, obj2 17 | if obj is None: 18 | continue 19 | if (obj.type in ['file', 'subfile'] 20 | and obj.yaml_file 21 | and option in obj.yaml_file): 22 | result = obj.yaml_file[option] 23 | break 24 | if (obj.type in ['device'] 25 | and obj.yaml_device is not None 26 | and option in obj.yaml_device): 27 | result = obj.yaml_device[option] 28 | break 29 | 30 | if result is None: 31 | # If not in obj2 or obj1, check CLI args then default 32 | if option in vars(args): 33 | result = vars(args)[option] 34 | elif (yaml_default is not None) and (option in yaml_default): 35 | result = yaml_default[option] 36 | else: 37 | result = False 38 | 39 | return result 40 | -------------------------------------------------------------------------------- /filetailor/core/uninstall.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Delete filetailor directories""" 3 | 4 | import os 5 | import shutil 6 | from pathlib import Path 7 | 8 | import filetailor.helpers.okay_to_continue as okay 9 | from filetailor.helpers import cprint, load_ini_files 10 | from filetailor.helpers.get_option import main as get_option 11 | 12 | 13 | def delete(file_path): 14 | """Ask to permanently remove file or directory""" 15 | if okay.main(f'\nOkay to PERMANENTLY DELETE "{file_path}"?', 'n'): 16 | try: 17 | if not get_option('dry_run'): 18 | shutil.rmtree(file_path) 19 | cprint.success(f'Deleted "{file_path}".') 20 | delete_successful = True 21 | except NotADirectoryError: 22 | os.remove(file_path) 23 | cprint.success(f'Deleted "{file_path}".') 24 | delete_successful = True 25 | except: 26 | cprint.error(f'ERROR: Could not delete "{file_path}".') 27 | delete_successful = False 28 | else: 29 | delete_successful = False 30 | 31 | return delete_successful 32 | 33 | 34 | def main(): 35 | """Delete filetailor directories""" 36 | filetailor_ini_path = load_ini_files.find_filetailor_ini() 37 | filetailor_ini = load_ini_files.read_filetailor_ini(filetailor_ini_path) 38 | paths = filetailor_ini['PATHS'] 39 | 40 | cprint.plain('Searching for directories to remove...') 41 | uninstall_successful = True 42 | for dir_str in paths: 43 | dir_path = Path(paths[dir_str]).resolve() 44 | if dir_path.is_dir(): 45 | uninstall_successful = delete(dir_path) 46 | 47 | if uninstall_successful: 48 | if delete(filetailor_ini_path): 49 | cprint.plain('\nUninstall complete.') 50 | -------------------------------------------------------------------------------- /filetailor/helpers/okay_to_continue.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Asks user how to proceed""" 3 | 4 | import filetailor.helpers.get_option 5 | from filetailor.helpers import cprint 6 | from filetailor.helpers.diff import difftool 7 | 8 | 9 | def get_response(msg, default, obj1=None, obj2=None): 10 | """Get user response""" 11 | 12 | # Check if `--assumeyes` is applied in default, device, file, or arg 13 | # settings 14 | if filetailor.helpers.get_option.main('assumeyes', obj1, obj2): 15 | return 'a' 16 | 17 | # Determine the options 18 | valid_input = ['a', 'y', 'n'] 19 | if default == 'a': 20 | flags = '[A]ll, [y]es, [n]o' 21 | elif default == 'y': 22 | flags = '[Y/n]' 23 | elif default == 'n': 24 | flags = '[y/N]' 25 | elif default == 'd': 26 | flags = '[y]es, [n]o, show [D]ifftool' 27 | valid_input.append('d') 28 | 29 | result = None 30 | while result is None: 31 | # Get input from user 32 | user_input = input(f'{msg} {flags} ') 33 | 34 | if user_input == '': 35 | # Apply defaults 36 | result = default 37 | else: 38 | # Get first letter of input as lowercase only 39 | user_input = user_input[0].lower() 40 | 41 | # Determine result 42 | if user_input in valid_input: 43 | result = user_input 44 | else: 45 | cprint.error('Invalid input, try again.', obj1, obj2) 46 | 47 | return result 48 | 49 | 50 | def main(msg, default, obj1=None, obj2=None, src=None, dst=None): 51 | """Convert response to True/False""" 52 | 53 | result = get_response(msg, default, obj1, obj2) 54 | 55 | if result == 'd': 56 | result = 'n' 57 | difftool(src, dst) 58 | 59 | return result != 'n' 60 | -------------------------------------------------------------------------------- /filetailor/helpers/diff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Determines diff program then runs diff on two files""" 3 | 4 | import difflib 5 | import logging 6 | import subprocess 7 | 8 | import filetailor.config as ftconfig 9 | 10 | 11 | def get_git_program(cmd): 12 | """Determine diff program based on Git settings""" 13 | 14 | output = subprocess.run(['git', 'config', cmd], 15 | stdout=subprocess.PIPE, check=False) 16 | if output.stdout: 17 | diff_program = output.stdout.decode('utf-8') 18 | else: 19 | diff_program = False 20 | return diff_program 21 | 22 | 23 | def get_diff_program(src, dst, ftconfig_name, gitconfig_name): 24 | """Run diff on two files""" 25 | 26 | logging.debug('Getting diff program') 27 | 28 | # Get diff program from ftconfig 29 | diff_program = ftconfig.tools.get('diff_pager', 'none') 30 | if diff_program.lower() == 'none': 31 | # Ignore the default placeholder text of "None" generated by configparser 32 | diff_program = None 33 | 34 | # Get diff program from Git config 35 | if not diff_program: 36 | diff_program = get_git_program(gitconfig_name) 37 | if diff_program: 38 | diff_program = diff_program.strip() 39 | logging.debug('Selected %s as diff program', diff_program) 40 | 41 | try: 42 | if diff_program: 43 | # Diff using diff program defined above 44 | logging.debug('Using "%s" as diff program', diff_program) 45 | subprocess.run([diff_program, src, dst], check=False) 46 | else: 47 | # Diff using difflib if no diff program yet defined 48 | logging.debug('Using Python "difflib" as diff program') 49 | with open(src) as src_file: 50 | src_text = src_file.readlines() 51 | with open(dst) as dst_file: 52 | dst_text = dst_file.readlines() 53 | lines = list(difflib.unified_diff(src_text, dst_text, 54 | fromfile=str(src), tofile=str(dst))) 55 | if len(lines) == 0: 56 | print(f'--- {src}') 57 | print(f'+++ {dst}') 58 | print('Files have the same content.') 59 | else: 60 | for line in lines: 61 | print(line, end='') 62 | except UnicodeDecodeError: 63 | # For binary files, skip diff 64 | print(f'--- {src}') 65 | print(f'+++ {dst}') 66 | print('No diff available.') 67 | 68 | 69 | def diff(src, dst): 70 | """Run diff in terminal""" 71 | get_diff_program(src, dst, 'diff_program', 'core.pager') 72 | 73 | 74 | def difftool(src, dst): 75 | """Run diff in external tool""" 76 | get_diff_program(src, dst, 'difftool', 'diff.tool') 77 | -------------------------------------------------------------------------------- /filetailor/helpers/get_key_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Get the list of keys in both the device and file, or just the device if 3 | there are none in the key 4 | """ 5 | 6 | 7 | def get_var_phrase(var_type): 8 | """Converts variable type to corresponding phrase in the YAML""" 9 | if var_type == 'vars': 10 | var_phrase = 'vars' 11 | elif var_type == 'yaml': 12 | var_phrase = 'yaml_only' 13 | elif var_type == 'file': 14 | var_phrase = 'file_only' 15 | 16 | return var_phrase 17 | 18 | 19 | def is_valid(yaml, var_type): 20 | """Checks if `var_type` is in `yaml`""" 21 | 22 | valid = False 23 | if yaml: 24 | # `yaml` exists 25 | var_phrase = get_var_phrase(var_type) 26 | if var_phrase in yaml and yaml[var_phrase]: 27 | valid = True 28 | 29 | return valid 30 | 31 | 32 | def get_key_val_dict(yaml_default, yaml_device, yaml_file, var_type): 33 | """Checks which file keys are in device and default, then returns the 34 | pairs 35 | """ 36 | 37 | key_list = {} 38 | if yaml_file['vars']: 39 | # `vars` is not an empty list 40 | var_phrase = get_var_phrase(var_type) 41 | for key in yaml_file['vars']: 42 | if (is_valid(yaml_device, var_type) 43 | and key in yaml_device[var_phrase]): 44 | key_list.update({key: yaml_device[var_phrase][key]}) 45 | elif (is_valid(yaml_default, var_type) 46 | and key in yaml_default[var_phrase]): 47 | key_list.update({key: yaml_default[var_phrase][key]}) 48 | 49 | return key_list 50 | 51 | 52 | def main(yaml_default, yaml_device, yaml_file, var_type): 53 | """Get the list of {key: value} corresponding to the device 54 | and file (if provided) 55 | 56 | Called by `update_line` and `tailor_yaml` 57 | """ 58 | 59 | key_list = {} 60 | 61 | if yaml_file and 'vars' in yaml_file: 62 | # `vars` in both file and devices, so use common vars 63 | key_list.update(get_key_val_dict(yaml_default, yaml_device, yaml_file, 64 | 'vars')) 65 | key_list.update(get_key_val_dict(yaml_default, yaml_device, yaml_file, 66 | var_type)) 67 | else: 68 | # `vars` in device only, so use that list 69 | if is_valid(yaml_default, 'vars'): 70 | key_list.update(yaml_default['vars']) 71 | if is_valid(yaml_device, 'vars'): 72 | key_list.update(yaml_device['vars']) 73 | if is_valid(yaml_device, var_type): 74 | key_list.update(yaml_device[get_var_phrase(var_type)]) 75 | if is_valid(yaml_default, var_type): 76 | key_list.update(yaml_default[get_var_phrase(var_type)]) 77 | 78 | return key_list 79 | -------------------------------------------------------------------------------- /filetailor/helpers/load_ini_files.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Loads values from config.ini or filetailor.ini""" 3 | 4 | import configparser 5 | import logging 6 | import os 7 | import sys 8 | from pathlib import Path 9 | 10 | import filetailor.config as ftconfig 11 | from filetailor.helpers import cprint 12 | 13 | 14 | def check_paths(paths): 15 | """Checks 'sync_dir' and 'yaml' are in paths""" 16 | 17 | keys_exist = ('sync_dir' in paths 18 | and 'yaml' in paths 19 | and 'in-progress_dir' in paths) 20 | return keys_exist 21 | 22 | 23 | def read_filetailor_ini(filetailor_ini_path): 24 | """Loads values from filetailor.ini, called by __main__.py when functions 25 | are called 26 | """ 27 | 28 | # Read filetailor.ini 29 | logging.debug('"filetailor.ini" found, adding to "paths"') 30 | filetailor_ini = configparser.ConfigParser() 31 | filetailor_ini.read(filetailor_ini_path) 32 | 33 | # Check filetailor.ini for paths 34 | if ('PATHS' in filetailor_ini) and check_paths(filetailor_ini['PATHS']): 35 | for path in filetailor_ini['PATHS']: 36 | # Expand ~ to full path 37 | filetailor_ini['PATHS'][path] = os.path.expanduser(filetailor_ini['PATHS'][path]) 38 | logging.debug('path for %s = %s', path, filetailor_ini['PATHS'][path]) 39 | else: 40 | # filetailor_ini incomplete 41 | cprint.error(f'ERROR: Missing keys from "{filetailor_ini_path}".') 42 | sys.exit() 43 | 44 | return filetailor_ini 45 | 46 | 47 | def find_filetailor_ini(): 48 | """Gets location of filetailor.ini based on input and OS""" 49 | 50 | # User override path if defined, otherwise use OS default 51 | override = ftconfig.override_filetailor_ini_path 52 | if override != '': 53 | filetailor_ini_path = Path(os.path.expanduser(override)) 54 | else: 55 | filetailor_ini_path = os.path.join( 56 | ftconfig.dirs.user_config_dir, 'filetailor.ini') 57 | ftconfig.filetailor_ini_path = filetailor_ini_path 58 | 59 | return filetailor_ini_path 60 | 61 | 62 | def load_config_ini(): 63 | """Loads values from config.ini, called by __main__.py, even when no 64 | functions are called (such as `filetailor --help`) 65 | """ 66 | 67 | logging.debug('Running load_config_ini') 68 | 69 | # Read config.ini 70 | data = ftconfig.data 71 | config_ini_path = os.path.join(data, 'config.ini') 72 | ftconfig.config_ini_path = config_ini_path 73 | if not os.path.isfile(config_ini_path): 74 | cprint.error(f'"config.ini" not found at "{config_ini_path}". Please ' 75 | + 'reinstall filetailor.') 76 | sys.exit() 77 | config_ini = configparser.ConfigParser() 78 | config_ini.read(config_ini_path) 79 | logging.debug('config_ini.sections() = %s', config_ini.sections()) 80 | 81 | return config_ini 82 | -------------------------------------------------------------------------------- /filetailor/core/clean.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Remove files from sync_dir that are no longer defined in YAML""" 3 | 4 | import os 5 | import shutil 6 | 7 | import filetailor.config as ftconfig 8 | import filetailor.helpers.okay_to_continue as okay 9 | from filetailor.helpers import cprint 10 | from filetailor.helpers.get_option import main as get_option 11 | 12 | 13 | def file_in_yaml(sync_file, yaml_files): 14 | """Returns if `sync_file` is in `yaml_files` without the "unique" attribute 15 | OR `sync_file` without its unique part is in `yaml_files` and the "unique" 16 | attribute is present 17 | """ 18 | 19 | underscore_location = sync_file.rfind('_') 20 | if underscore_location != -1: 21 | # Check if this file is saved with "unique" formatting 22 | unique_id = sync_file[:underscore_location] 23 | try: 24 | if yaml_files[unique_id]['unique']: 25 | # This file matches the unique formatting and the file has 26 | # the unique attribute 27 | return True 28 | except (KeyError, TypeError): 29 | pass 30 | if sync_file in yaml_files: 31 | # Check this file is NOT saved with "unique" formatting 32 | try: 33 | if yaml_files[sync_file]['unique']: 34 | # This file matches the file ID, but it doesn't have a unique 35 | # extension and this file has the unique attribute 36 | return False 37 | except (KeyError, TypeError): 38 | pass 39 | 40 | # This file is in the YAML 41 | return True 42 | 43 | # This file was not found in the YAML 44 | return False 45 | 46 | 47 | def main(): 48 | """Remove files from sync_dir that are no longer defined in YAML""" 49 | paths = ftconfig.paths 50 | 51 | cprint.plain('Searching for files in sync directory not listed in YAML...') 52 | sync_files = os.listdir(paths['sync_dir']) 53 | yaml_files = ftconfig.yaml_files 54 | orphans_found = False 55 | for sync_file in sync_files: 56 | if not file_in_yaml(sync_file, yaml_files): 57 | orphans_found = True 58 | if okay.main(f'\nOkay to delete "{sync_file}" from sync directory ' 59 | + '(no longer tracked in YAML)?', 'y'): 60 | sync_file_path = os.path.join(paths['sync_dir'], sync_file) 61 | try: 62 | if not get_option('dry_run'): 63 | shutil.rmtree(sync_file_path) 64 | cprint.success(f'Deleted "{sync_file}" from sync directory.') 65 | except NotADirectoryError: 66 | os.remove(sync_file_path) 67 | cprint.success(f'Deleted "{sync_file}" from sync directory.') 68 | if orphans_found: 69 | cprint.plain('\nClean complete.\n') 70 | else: 71 | cprint.plain('\nNo untracked files found.\n') 72 | -------------------------------------------------------------------------------- /filetailor/data/example_filetailor.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | # Everything is optional unless otherwise specified 3 | # If omitted, false by default 4 | 5 | default: 6 | 7 | # Replace VARIABLE_NAME with VARIABLE_VALUE in YAML and file contents 8 | vars: 9 | VARIABLE_NAME: VARIABLE_VALUE 10 | 11 | # Replace VARIABLE_NAME with VARIABLE_VALUE in YAML 12 | yaml_only: 13 | VARIABLE_NAME: VARIABLE_VALUE 14 | 15 | # Replace VARIABLE_NAME with VARIABLE_VALUE in file contents 16 | file_only: 17 | VARIABLE_NAME: VARIABLE_VALUE 18 | 19 | # Default options 20 | # These only apply when backing up or restoring a file 21 | quiet: true|false 22 | no_diff: true|false 23 | no_backup: true|false 24 | assumeyes: true|false 25 | dry_run: true|false 26 | sudo: true|false 27 | 28 | # Save files to STAGING_PATH instead of normal file PATH 29 | # Each file is saved in "STAGING_PATH/FILE_ID/filename_with_extension". 30 | staging: STAGING_PATH 31 | 32 | 33 | device DEVICE_ID: 34 | # Overrides "default" above and can use the exact same options in addition 35 | # to the "hostname" option below 36 | 37 | # If DEVICE_ID is not the same as the device's hostname, the hostname can 38 | # be specified here 39 | hostname: HOSTNAME 40 | 41 | 42 | file FILE_ID: 43 | # FILE_ID is what gets saved in the sync_dir and can be different than the 44 | # actual file name 45 | 46 | # REQUIRED: PATH includes the full path and the file name 47 | path: PATH 48 | 49 | # If provided, only variables listed here will apply when tailoring the 50 | # file to a device, otherwise all variables apply 51 | vars: 52 | - VARIABLE_NAME 53 | 54 | # File-specific options (overrides default and device) 55 | quiet: true|false 56 | no_diff: true|false 57 | no_bak: true|false 58 | assumeyes: true|false 59 | dry_run: true|false 60 | sudo: true|false 61 | 62 | # Save files to STAGING_PATH instead of normal file PATH 63 | # Each file is saved in "STAGING_PATH/FILE_ID/filename_with_extension". 64 | staging: STAGING_PATH 65 | 66 | # If unique = true, device name will be appending to filename and no 67 | # tailoring between devices will take place 68 | unique: true|false 69 | 70 | # Use include_devices or exclude_devices but not both 71 | include_devices : DEVICE_ID... 72 | exclude_devices : DEVICE_ID... 73 | 74 | # For directories only 75 | # https://docs.python.org/3/library/re.html#re.Pattern.search 76 | # For example, to include only ".py" files, REXEG = "\.py" 77 | # Subdirectories are automatically excluded 78 | include_contents: REGEX 79 | exclude_contents: REGEX 80 | 81 | # Executable scripts to run before/after backup/restore 82 | # Scripts execute after variables 83 | # Backup stripts also execute when checking file status 84 | scripts: 85 | before_backup : PATH_TO_SCRIPT 86 | after_backup : PATH_TO_SCRIPT 87 | before_restore: PATH_TO_SCRIPT 88 | after_restore : PATH_TO_SCRIPT 89 | ... 90 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ---> Python 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | pip-wheel-metadata/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | .python-version 87 | 88 | # pipenv 89 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 90 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 91 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 92 | # install all needed dependencies. 93 | #Pipfile.lock 94 | 95 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 96 | __pypackages__/ 97 | 98 | # Celery stuff 99 | celerybeat-schedule 100 | celerybeat.pid 101 | 102 | # SageMath parsed files 103 | *.sage.py 104 | 105 | # Environments 106 | .env 107 | .venv 108 | env/ 109 | venv/ 110 | ENV/ 111 | env.bak/ 112 | venv.bak/ 113 | 114 | # Spyder project settings 115 | .spyderproject 116 | .spyproject 117 | 118 | # Rope project settings 119 | .ropeproject 120 | 121 | # mkdocs documentation 122 | /site 123 | 124 | # mypy 125 | .mypy_cache/ 126 | .dmypy.json 127 | dmypy.json 128 | 129 | # Pyre type checker 130 | .pyre/ 131 | 132 | # ---> Vim 133 | # Swap 134 | [._]*.s[a-v][a-z] 135 | !*.svg # comment out if you don't need vector files 136 | [._]*.sw[a-p] 137 | [._]s[a-rt-v][a-z] 138 | [._]ss[a-gi-z] 139 | [._]sw[a-p] 140 | 141 | # Session 142 | Session.vim 143 | Sessionx.vim 144 | 145 | # Temporary 146 | .netrwhist 147 | *~ 148 | # Auto-generated tag files 149 | tags 150 | # Persistent undo 151 | [._]*.un~ 152 | 153 | # ---> NotepadPP 154 | # Notepad++ backups # 155 | *.bak 156 | 157 | # ---> Custom 158 | # Zettlr 159 | .ztr-directory 160 | wily-report.html 161 | -------------------------------------------------------------------------------- /filetailor/helpers/load_yaml.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Imports YAML""" 3 | 4 | import logging 5 | import os 6 | import sys 7 | 8 | import yaml 9 | 10 | from filetailor.helpers import cprint 11 | from filetailor.helpers.load_ini_files import find_filetailor_ini 12 | 13 | DEFAULT_KEYS = ['vars', 'yaml_only', 'file_only', 'quiet', 'no_diff', 14 | 'no_backup', 'assumeyes', 'dry_run', 'sudo', 'staging'] 15 | FILE_KEYS = ['path', 'vars', 'quiet', 'no_diff', 'no_backup', 'assumeyes', 'dry_run', 16 | 'sudo', 'staging', 'unique', 'include_devices', 'exclude_devices', 17 | 'include_contents', 'exclude_contents', 'scripts'] 18 | 19 | 20 | def check_for_duplicates(paths, dictionary, key): 21 | """Checks for duplicate keys in YAML""" 22 | if key in dictionary: 23 | cprint.error(f'ERROR: Duplicate key "{key}". Please correct ' + 24 | f'"{paths["yaml_dir"]}".') 25 | sys.exit() 26 | return 0 27 | 28 | 29 | def validate_yaml(input_yaml, valid_keys, name): 30 | """Check that all keys are valid inputs""" 31 | if input_yaml is not None: 32 | for key in input_yaml: 33 | if key not in valid_keys: 34 | cprint.error(f'Key "{key}" in YAML "{name}" is not valid. ' 35 | + 'Please fix.') 36 | 37 | 38 | def main(paths): 39 | """Imports YAML""" 40 | logging.debug('Running load_yaml') 41 | 42 | # Check directories exist 43 | dirs_found = True 44 | expected_keys = ('yaml', 'sync_dir', 'in-progress_dir') 45 | for expected_key in expected_keys: 46 | if expected_key not in paths.keys(): 47 | filetailor_ini_path = find_filetailor_ini() 48 | cprint.error(f'"{expected_key}" not found in ' 49 | + f'"{filetailor_ini_path}".') 50 | dirs_found = False 51 | if not dirs_found: 52 | cprint.plain('Exiting...') 53 | sys.exit() 54 | 55 | # Get filetailor.yaml 56 | with open(paths['yaml'], 'r') as f: 57 | data = yaml.load(f, Loader=yaml.Loader) 58 | 59 | # Split YAML into 3 dictionaries 60 | yaml_default = {} 61 | yaml_devices = {} 62 | yaml_files = {} 63 | if data: 64 | for key in data.keys(): 65 | key_type, _, key_value = key.partition(' ') 66 | if key_type == 'default': 67 | # default 68 | yaml_default = data['default'] 69 | else: 70 | if key_type == 'device': 71 | # Device 72 | yaml_devices[key_value] = data[key] 73 | elif key_type == 'file': 74 | # File 75 | yaml_files[key_value] = data[key] 76 | 77 | logging.debug('') 78 | logging.debug('yaml_default = %s', yaml_default) 79 | logging.debug('yaml_devices = %s', yaml_devices) 80 | logging.debug('yaml_files = %s', yaml_files) 81 | logging.debug('') 82 | logging.debug('yaml_default:\n%s', 83 | yaml.dump(yaml_default, Dumper=yaml.Dumper)) 84 | logging.debug('yaml_devices:\n%s', 85 | yaml.dump(yaml_devices, Dumper=yaml.Dumper)) 86 | logging.debug('yaml_files:\n%s', 87 | yaml.dump(yaml_files, Dumper=yaml.Dumper)) 88 | logging.debug('') 89 | 90 | validate_yaml(yaml_default, DEFAULT_KEYS, 'default') 91 | for device in yaml_devices: 92 | validate_yaml(yaml_devices[device], 93 | DEFAULT_KEYS + ['hostname'], 94 | 'device ' + device) 95 | for file in yaml_files: 96 | validate_yaml(yaml_files[file], 97 | FILE_KEYS, 98 | 'file ' + file) 99 | 100 | return (yaml_default, yaml_devices, yaml_files) 101 | -------------------------------------------------------------------------------- /filetailor/core/update_yaml.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Add or remove devices and files from YAML""" 3 | 4 | import logging 5 | import os 6 | import sys 7 | from pathlib import Path 8 | 9 | import filetailor.config as ftconfig 10 | import filetailor.helpers.okay_to_continue as okay 11 | from filetailor.helpers import cprint 12 | from ruamel.yaml import YAML 13 | 14 | 15 | def yaml_add(args, yaml_devices, yaml_files, data): 16 | """Add files to `data` with name if provided, otherwise basename""" 17 | 18 | # Check if enough names provided 19 | if args.name is not None: 20 | if len(args.PATHS) > 1 and args.name is not None: 21 | cprint.error('ERROR: When specifying a name for the file with, only ' 22 | + 'one file at a time can be added.') 23 | sys.exit() 24 | 25 | # Add device to `data` 26 | device = ftconfig.device_id 27 | if device not in yaml_devices: 28 | if okay.main(f'Device is not in YAML. Okay to add "{device}"?', 29 | 'y'): 30 | data[f'device {device}'] = None 31 | cprint.success(f'Added "{device}" to YAML.') 32 | 33 | # Add each file to `data` 34 | for (i, fpath_str) in enumerate(args.PATHS): 35 | fpath = Path(fpath_str).resolve() 36 | if args.name is None: 37 | basename = os.path.basename(fpath) 38 | else: 39 | basename = args.name[i] 40 | if yaml_files and basename in yaml_files: 41 | print(f'"{basename}" is already in "filetailor.yaml", ' + 42 | 'skipping file.') 43 | continue 44 | data[f'file {basename}'] = {} 45 | data[f'file {basename}']['path'] = str(fpath.absolute()) 46 | cprint.success(f'File "{basename}" added to YAML.') 47 | 48 | 49 | def yaml_remove(args, yaml_files, data): 50 | """Remove files from `data`""" 51 | 52 | files_removed = False 53 | 54 | # Remove each file from `data` 55 | for fpath_str in args.FILES: 56 | fpath = Path(fpath_str).resolve() 57 | basename = os.path.basename(fpath) 58 | if basename in yaml_files: 59 | del data[f'file {basename}'] 60 | cprint.success(f'File "{basename}" removed from YAML.') 61 | files_removed = True 62 | else: 63 | cprint.error(f'"{basename}" not in "filetailor.yaml", ' 64 | + 'skipping file.') 65 | 66 | return files_removed 67 | 68 | 69 | def main(operation): 70 | """Add or remove devices and files from YAML""" 71 | 72 | # Import from config 73 | args = ftconfig.args 74 | yaml_devices = ftconfig.yaml_devices 75 | yaml_files = ftconfig.yaml_files 76 | 77 | # Load `filetailor.yaml` using ruamel 78 | filetailor_yaml_path = os.path.expanduser(ftconfig.paths['yaml']) 79 | ruamel = YAML() 80 | with open(filetailor_yaml_path, 'r') as filetailor_yaml: 81 | data = ruamel.load(filetailor_yaml) 82 | if data is None: 83 | data = {} 84 | 85 | if operation == 'add': 86 | yaml_add(args, yaml_devices, yaml_files, data) 87 | cprint.plain('Run "filetailor backup" to sync the new files.') 88 | elif operation == 'remove': 89 | files_removed = yaml_remove(args, yaml_files, data) 90 | if files_removed: 91 | cprint.plain('Run "filetailor clean" to delete the removed files.') 92 | else: 93 | cprint.plain('No files were removed from YAML.') 94 | 95 | # Show resulting YAML 96 | if args.dry_run: 97 | # Debug not working yet 98 | # https://stackoverflow.com/questions/47614862/best-way-to-use-ruamel-yaml-to-dump-to-string-not-to-stream 99 | # logging.debug(ruamel.dump(data, None, transform=print)) 100 | logging.debug('data = %s' % data) 101 | else: 102 | # Dump `data` to `filetailor.yaml` 103 | with open(filetailor_yaml_path, 'w') as filetailor_yaml: 104 | ruamel.dump(data, filetailor_yaml) 105 | -------------------------------------------------------------------------------- /filetailor/core/initialize.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Creates filetailor.ini if it doesn't exist. Creates directories if it does 3 | exist. 4 | """ 5 | 6 | import configparser 7 | import os 8 | import shutil 9 | import sys 10 | import tempfile 11 | from pathlib import Path 12 | 13 | import filetailor.config as ftconfig 14 | import filetailor.helpers.okay_to_continue as okay 15 | from filetailor.helpers import cprint, load_ini_files 16 | from filetailor.helpers.get_option import main as get_option 17 | 18 | 19 | def copy_filetailor_ini(data, os_path): 20 | """Copy "filetailor.ini" and "example_filetailor.ini""" 21 | 22 | if not get_option('dry_run'): 23 | shutil.copyfile(os.path.join(data, 'filetailor.yaml'), 24 | os_path) 25 | cprint.success(f'Created "{os_path}" and default "filetailor.yaml".') 26 | 27 | 28 | def create_filetailor_ini(filetailor_ini_path): 29 | """Create filetailor.ini if it doesn't exist""" 30 | 31 | if okay.main(f'Create "{filetailor_ini_path}"?', 'y'): 32 | parent_dir = Path(filetailor_ini_path).parent.absolute() 33 | if not os.path.isdir(parent_dir): 34 | # Create filetailor directory if it does not exist 35 | if not os.path.isfile(parent_dir) and not get_option('dry_run'): 36 | os.makedirs(parent_dir) 37 | else: 38 | cprint.plain(f'File named "{parent_dir}" already exists. ' 39 | + 'Please delete it and try again.') 40 | 41 | dirs = ftconfig.dirs 42 | 43 | # Create `filetailor.ini` 44 | config = configparser.ConfigParser() 45 | config['PATHS'] = {} 46 | config['PATHS']['sync_dir'] = os.path.join(dirs.user_data_dir, 'sync') 47 | config['PATHS']['yaml'] = os.path.join(dirs.user_data_dir, 'filetailor.yaml') 48 | if sys.platform in ['linux', 'darwin']: 49 | config['PATHS']['in-progress_dir'] = dirs.user_cache_dir 50 | else: 51 | config['PATHS']['in-progress_dir'] = os.path.join( 52 | tempfile.gettempdir(), 'filetailor') 53 | config['TOOLS'] = {} 54 | config['TOOLS']['diff_pager'] = 'None' 55 | config['TOOLS']['difftool'] = 'None' 56 | with open(filetailor_ini_path, 'w', encoding='UTF-8') as configfile: 57 | config.write(configfile) 58 | 59 | cprint.success(f'\nCreated "{filetailor_ini_path}".') 60 | cprint.plain('Update "filetailor.ini" with your desired ' 61 | + 'locations for synced files and configuration YAML, ' 62 | + 'then run "filetailor init" again ' 63 | + 'to create the directories.') 64 | else: 65 | cprint.plain('Exiting...') 66 | 67 | 68 | def main(): 69 | """Read filetailor.ini""" 70 | 71 | filetailor_ini_path = load_ini_files.find_filetailor_ini() 72 | if not os.path.isfile(filetailor_ini_path): 73 | # If filetailor.ini does not exist, create it 74 | create_filetailor_ini(filetailor_ini_path) 75 | sys.exit() 76 | 77 | # If filetailor.ini does exist, load it and proceed 78 | filetailor_ini = load_ini_files.read_filetailor_ini( 79 | filetailor_ini_path) 80 | paths = filetailor_ini['PATHS'] 81 | 82 | # Get location of data directory 83 | data = ftconfig.data 84 | 85 | cprint.plain('Reading settings from "filetailor.ini"...') 86 | 87 | # If sync_dir, yaml, and in-progress_dir do not exist, create them 88 | cprint.plain('Creating filetailor directories...') 89 | init_complete = True 90 | 91 | # Check directories exist 92 | for key in ['sync_dir', 'yaml', 'in-progress_dir']: 93 | 94 | if key not in paths: 95 | cprint.error(f'\nMissing "{key}" in "filetailor.ini"') 96 | init_complete = False 97 | continue 98 | 99 | # Convert to Path type 100 | os_path = Path(paths[key]) 101 | 102 | # Check if directory exists, otherwise create path 103 | if ( 104 | (key in ['sync_dir', 'in-progress_dir'] and os.path.isdir(os_path)) 105 | or (key == 'yaml' and os.path.isfile(os_path)) 106 | ): 107 | cprint.plain(f'\n"{os_path}" already exists ({key}).') 108 | else: 109 | if okay.main(f'\nCreate "{os_path}" for {key}?', 'y'): 110 | if not get_option('dry_run'): 111 | if key == 'yaml': 112 | # Copy the default filetailor.yaml for yaml 113 | copy_filetailor_ini(data, os_path) 114 | else: 115 | Path(os_path).mkdir(parents=True) 116 | else: 117 | cprint.success(f'Created "{os_path}".') 118 | else: 119 | init_complete = False 120 | 121 | if init_complete: 122 | cprint.plain('\nfiletailor initialization complete. Be sure to use Git, ' 123 | + 'Syncthing, etc. to sync the `sync_dir` directory and ' 124 | + '`filetailor.yaml` between your devices.') 125 | else: 126 | cprint.error('\nfiletailor initialization NOT complete, run ' + 127 | '"filetailor init" again.') 128 | -------------------------------------------------------------------------------- /filetailor/helpers/tailor_lines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Tailor a line of text by adding and removing comment for a 3 | specific device based on the YAML 4 | """ 5 | 6 | import logging 7 | import re 8 | import sys 9 | 10 | import filetailor.config as ftconfig 11 | from filetailor.helpers import cprint 12 | from filetailor.helpers.get_key_list import main as get_key_list 13 | 14 | 15 | class LineAttributes: 16 | 17 | # Example: dummy_text //{filetailor host1 host2} additional text 18 | # Regex accounts for `{begin filetailor`, `{end filetailor`, and just 19 | # `{filetailor` 20 | global P1 21 | P1 = re.compile(r'(\S*)\{(begin |end |)filetailor (.*?)\}') 22 | 23 | def __init__(self, line, number, key_list={}): 24 | self.line = line 25 | self.number = number 26 | self.indent = self.get_indent() 27 | self.comment_char = None 28 | self.action = None 29 | self.devices = None 30 | self.get_action(key_list) 31 | 32 | def get_action(self, key_list): 33 | m1 = P1.search(self.line) 34 | if m1: 35 | 36 | # From `{filetailor`, `comment_sym` is equal to all preceding 37 | # characters until the first whitespace. 38 | # `devices` is all following characters until the first `}` 39 | # From example, `comment_char` = `//` 40 | self.comment_char = m1.group(1) 41 | 42 | # From example, `action` = `''` 43 | self.action = m1.group(2) 44 | 45 | # From example, `devices` = `device1 device2` 46 | devices = m1.group(3).split() 47 | 48 | # Converted device(s) have had vars replaced with values 49 | converted_devices = [] 50 | 51 | for device in devices: 52 | converted_device = device 53 | for key in key_list: 54 | # Replace vars in `line` with keys for backup; reverse for restore 55 | var = key_list[key] 56 | converted_device = converted_device.replace(key, var) 57 | converted_devices = converted_devices + converted_device.split() 58 | self.devices = converted_devices 59 | 60 | def update(self, source_text): 61 | """Update line and indent with new `self.number`""" 62 | self.line = source_text[self.number] 63 | self.indent = self.get_indent(self.line) 64 | 65 | def get_indent(self): 66 | """Get number of whitespaces at beginning of line""" 67 | 68 | if len(self.line) == len(self.line.lstrip()): 69 | # No indentation 70 | indent = 0 71 | else: 72 | # Some indentation 73 | indent = len(self.line) - len(self.line.lstrip()) 74 | 75 | return indent 76 | 77 | 78 | def update_comments(line, comment_char, indent): 79 | """Add or remove comments to tailor the line to the device 80 | 81 | Called by `update_line` 82 | """ 83 | 84 | if ftconfig.sync in ['backup']: 85 | # If backup, comment out lines 86 | 87 | if len(line) > 1: 88 | # If line contains text, add comment_char and space in place of 89 | # empty line text 90 | line = ' '*indent + comment_char + ' ' + line[indent:] 91 | else: 92 | # If line is blank, add comment_char only 93 | # This is likely due to a multi-line tailor 94 | line = ' '*indent + comment_char + '\n' 95 | 96 | if ftconfig.sync in ['status', 'restore']: 97 | # If restore, uncomment lines 98 | # Remove space trailing the comment if it exists 99 | 100 | # Check if line is more than just a comment and whitespace 101 | if len(line.strip()) > 1: # `.strip` removes newline character 102 | # Line contains text, so replace comment and following space 103 | line = line.replace(comment_char + ' ', '', 1) 104 | else: 105 | # Blank line aside from comment, so replace comment 106 | line = line.replace(comment_char, '', 1) 107 | 108 | return line 109 | 110 | 111 | def main(xfile): 112 | """Tailor the line to fit the sync directory (backup) or device (restore) 113 | 114 | Called by `tailor_file` 115 | """ 116 | 117 | with open(xfile.source) as source_file: 118 | try: 119 | source_text = source_file.readlines() 120 | except (UnboundLocalError, UnicodeDecodeError): 121 | logging.debug('Ignoring binary file {xfile.file_id}') 122 | return False 123 | 124 | 125 | source_tailored = [] 126 | multiline = [] # List of comment symbols in active multiline 127 | 128 | # Update vars 129 | key_list = get_key_list(xfile.yaml_default, 130 | xfile.yaml_device, 131 | xfile.yaml_file, 132 | 'file') 133 | 134 | for (current_line_number, line) in enumerate(source_text): 135 | # For each line in file 136 | 137 | for key in key_list: 138 | # Replace vars in `line` with keys for backup; reverse for restore 139 | var = key_list[key] 140 | if ftconfig.sync in ['backup']: 141 | line = line.replace(var, key) 142 | if ftconfig.sync in ['status', 'restore']: 143 | line = line.replace(key, var) 144 | 145 | # Update filetailor tags 146 | cline = LineAttributes(line, current_line_number, key_list=key_list) 147 | if cline.action is not None and xfile.device_id in cline.devices: 148 | if cline.action == '': 149 | # Single-line edit 150 | line = update_comments(line, cline.comment_char, cline.indent) 151 | elif cline.action in ['begin ', 'end ']: 152 | if cline.action == 'begin ': 153 | # Check for multi-line start 154 | multiline.append(cline.comment_char) 155 | multiline_begin = LineAttributes(line, current_line_number) 156 | elif cline.action == 'end ': 157 | # Check for multi-line stop 158 | del multiline[-1] 159 | elif len(multiline) > 0: 160 | # Update multi-line edits 161 | cline.comment_char = multiline[-1] 162 | line = update_comments(line, cline.comment_char, multiline_begin.indent) 163 | 164 | source_tailored.append(line) 165 | 166 | if len(multiline) > 0: 167 | # Multi-line error 168 | cprint.error(f'ERROR: In "{xfile.file_id}", multi-line control begun ' 169 | + 'but not ended.', xfile) 170 | input('Press return to continue.') 171 | 172 | return source_tailored 173 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # filetailor 2 | 3 | **Update:** I have since discovered [Chezmoi](https://www.chezmoi.io/), which has many of the same features as filetailor and is much more mature. I recommend using Chezmoi instead. However, Chezmoi does rely on templates, unlike filetailor. 4 | 5 | filetailor is a peer-based configuration management utility for plain-text files (and directories) such as dotfiles. Files are backed up to a specified directory using filetailor, copied to another device using tools such as [Nextcloud](https://nextcloud.com/), [Syncthing](https://syncthing.net/), or [Git](https://git-scm.com/), and then copied to other devices using filetailor again. No symbolic links are used in the process. 6 | 7 | During the backup and restore process, filetailor can modify the file contents and path for the specific device according to variables and line-specific controls defined in YAML _without_ the use of templates. See [list of features](https://github.com/k4j8/filetailor/wiki/Features). 8 | 9 |  10 | 11 | 12 | 13 | **Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)* 14 | 15 | - [Example Usage](#example-usage) 16 | - [Getting Started](#getting-started) 17 | - [Installation](#installation) 18 | - [Configuration](#configuration) 19 | - [Usage](#usage) 20 | - [Line-Specific Control](#line-specific-control) 21 | - [Example: single-line control](#example-single-line-control) 22 | - [Diff Programs](#diff-programs) 23 | - [More Help](#more-help) 24 | - [Contributing](#contributing) 25 | 26 | 27 | 28 | ## Example Usage 29 | 30 | Here's how to sync a file to use `dev1home` on "device1" and `dev2home` on "device2" for the alias `MYHOME`. 31 | 32 | **.bashrc** on "device1": 33 | 34 | ```bash 35 | alias MYHOME='/home/dev1home/' #{filetailor device1} 36 | # alias MYHOME='/home/dev2home/' #{filetailor device2} 37 | ``` 38 | ```bash 39 | [user@device1 ~]$ filetailor add .bashrc 40 | [user@device1 ~]$ filetailor backup 41 | ``` 42 | 43 | During backup from "device1" to the sync directory, the first line gets commented out because the tag matches the device name. Sync the sync directory with the backed-up version of the file using your preferred method of choice to "device2" then restore with filetailor. During restore on "device2", the second line gets uncommented (again, because the tag matches the device name). 44 | ```bash 45 | [user@device2 ~]$ filetailor restore 46 | ``` 47 | 48 | **.bashrc** on "device2": 49 | 50 | ```bash 51 | # alias MYHOME='/home/dev1home/' #{filetailor device1} 52 | alias MYHOME='/home/dev2home/' #{filetailor device2} 53 | ``` 54 | 55 | ## Getting Started 56 | 57 | ### Installation 58 | 59 | filetailor requires Python 3.6+ and pip. Install by running the following commands: 60 | ```bash 61 | $ pip install filetailor 62 | 63 | $ filetailor init 64 | # Update the newly created "filetailor.ini" with your desired locations for synced files and configuration YAML 65 | 66 | $ filetailor init 67 | # Accept confirmations to create directories 68 | ``` 69 | 70 | To sync filetailor between devices, sync the `sync_dir` and `yaml_dir` directories created in the above steps using Git, Syncthing, etc. 71 | 72 | See [Alternative Installs](https://github.com/k4j8/filetailor/wiki/Alternative-Installs) for other installation methods. 73 | 74 | ### Configuration 75 | 76 | `filetailor.yaml` ("the YAML") controls which files sync to which devices. 77 | 78 | You can add/remove files to and from the YAML by running `filetailor add PATHS` and `filetailor remove PATHS` (local paths are okay). Alternatively, you can update the YAML manually by following the comments within. 79 | 80 | The YAML also defines variables, which are strings to replace when restoring to a specific device, such as a path to a file that differs between devices. See the [FAQ](https://github.com/k4j8/filetailor/wiki/FAQ) in the wiki for examples. 81 | 82 | ### Usage 83 | 84 | To backup all files defined in the YAML from the local device to the sync directory, run `filetailor backup`. Lines/blocks matching the device name will be commented out as they are copied to the sync directory. 85 | 86 | To restore all files defined in the YAML from the sync directory to the local device, run `filetailor restore`. Lines/blocks matching the device name will be uncommented as they are copied to the local device. 87 | 88 | To list all available commands, run `filetailor --help`. For command details, run `filetailor COMMAND --help`. 89 | 90 | ## Line-Specific Control 91 | 92 | You can control the contents of individual files by device with line-specific controls such as the [Example Usage](https://github.com/k4j8/filetailor#example-usage) above. There are two types of line-specific controls: single-line and multi-line. 93 | 94 | To use a single-line control, append a tag to the line you want to be commented out on other devices. During backup, any lines tagged for the current device will be commented out. During restore, lines tagged for the current device will be uncommented. Single-line control tag format: 95 |
(Code being controlled) COMMENT_SYM{filetailor DEVICES...}
96 | `COMMENT_SYM` is any symbol(s) used for comments and must be preceded by at least one space.
97 |
98 | To control a block of lines, see [Multi-line Controls](https://github.com/k4j8/filetailor/wiki/Multi-Line-Controls).
99 |
100 | #### Example: single-line control
101 |
102 | How the code should be written on "desktop":
103 | ```bash
104 | export $device_type="desktop" #{filetailor desktop}
105 | # export $device_type="laptop" #{filetailor laptop1 laptop2}
106 | ```
107 |
108 | After backing up the file through filetailor and then restoring to "laptop1" or "laptop2", the code would appear like this:
109 | ```bash
110 | # export $device_type="desktop" #{filetailor desktop}
111 | export $device_type="laptop" #{filetailor laptop1 laptop2}
112 | ```
113 |
114 | How the code would look on any other device and in the filetailor sync directory:
115 | ```bash
116 | # export $device_type="desktop" #{filetailor desktop}
117 | # export $device_type="laptop" #{filetailor laptop1 laptop2}
118 | ```
119 |
120 | ## Diff Programs
121 |
122 | Before backing up or restoring files, filetailor will show a diff of the changes. To set the diff programs for filetailor, add the following option to `filetailor.ini`.
123 | ```ini
124 | [TOOLS]
125 | diff_pager = YOUR_FAVORITE_DIFF_PROGRAM # for viewing diff in terminal
126 | difftool = YOUR_FAVORITE_DIFFTOOL # for making edits during diff in external tool
127 | ```
128 |
129 | If `diff_pager` is not set, filetailor will use `core.pager` (from Git config, [git-config docs](https://git-scm.com/docs/git-config)) if defined, otherwise uses `diff`.
130 | If `difftool` is not set, filetailor will use `diff.tool` (from Git config, [git-difftool docs](https://git-scm.com/docs/git-difftool)) if defined, otherwise uses `diff`.
131 |
132 | One popular supported diff pager is [Delta](https://github.com/dandavison/delta#installation). To install, follow the installation instructions in the link.
133 |
134 | Run the following command to set Delta as your [default pager for Git](https://www.git-scm.com/book/en/v2/Customizing-Git-Git-Configuration) (and thus filetailor):
135 | ```bash
136 | $ git config --global core.pager delta
137 | ```
138 |
139 | ## More Help
140 |
141 | See [FAQ](https://github.com/k4j8/filetailor/wiki/FAQ) in the wiki for more help and examples.
142 |
143 | Links:
144 | - [GitHub](https://github.com/k4j8/filetailor)
145 | - [PyPI](https://pypi.org/project/filetailor/)
146 | - [AlternativeTo](https://alternativeto.net/software/filetailor/about/)
147 |
148 | ## Contributing
149 |
150 | Feedback is welcome! Ways to contribute include:
151 | - Report a bug
152 | - Recommendations on new features
153 | - Suggestions to improve documentation and print statement readability
154 |
155 | Pull requests are welcome as well, but please open an issue first describing the change. When submitting PRs, please try to conform to the following style guides:
156 | - Python code style: [PEP8](https://www.python.org/dev/peps/pep-0008/)
157 | - Man page formatting: [man-pages(7)](https://man7.org/linux/man-pages/man7/man-pages.7.html)
158 | - Commit message formatting: [How to Write a Git Commit Message](https://chris.beams.io/posts/git-commit/)
159 | - Packaging: [Python Packaging User Guide](https://packaging.python.org/)
160 | - Release versioning: [Semantic Versioning](https://semver.org/)
161 |
--------------------------------------------------------------------------------
/filetailor/__main__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """Entry point for filetailor. Calls other helper functions to load configs and
3 | YAML. Calls other core functions to modify files and YAML.
4 | """
5 |
6 | import argparse
7 | import logging
8 | import os
9 | import platform
10 | import sys
11 | from pathlib import Path
12 | import pkg_resources
13 |
14 | import filetailor.config as ftconfig
15 | import filetailor.core.clean
16 | import filetailor.core.initialize
17 | import filetailor.core.paths
18 | import filetailor.core.sync
19 | import filetailor.core.uninstall
20 | import filetailor.core.update_yaml
21 | import filetailor.helpers.load_yaml
22 | from filetailor.helpers import load_ini_files
23 |
24 | __version__ = pkg_resources.require('filetailor')[0].version
25 |
26 |
27 | def get_hostname():
28 | """Returns the hostname of the machine"""
29 |
30 | return platform.node()
31 |
32 |
33 | def get_device_id(yaml_devices, device):
34 | """Given device (device_id or hostname), returns the device_id
35 |
36 | Example YAML:
37 | ```yaml
38 | device DEVICE_ID:
39 | hostname: HOSTNAME
40 | ```
41 | """
42 |
43 | device_id = device
44 | if device not in yaml_devices:
45 | # Search hostnames
46 | for key in yaml_devices.keys():
47 | if yaml_devices[key] and 'hostname' in yaml_devices[key]:
48 | if device == yaml_devices[key]['hostname']:
49 | device_id = key
50 |
51 | return device_id
52 |
53 |
54 | # PARSERS
55 |
56 | def update_parser_all(parser, config_ini):
57 | """Adds arguments to the parser"""
58 | parser.add_argument('-q', '--quiet', action='store_true',
59 | help='suppress all output not requiring user input')
60 | parser.add_argument('-y', '--assumeyes', action='store_true',
61 | help='suppress all output requiring user input by '
62 | + 'assuming yes')
63 | if config_ini['DEFAULT'].get('testing', False):
64 | parser.add_argument('--debug', action='store_true',
65 | help='display debug info')
66 | parser.add_argument('--test', action='store_true',
67 | help='use test YAML, sync, and files')
68 | return parser
69 |
70 |
71 | def update_parser_sync(parser, environment):
72 | """Adds arguments to the backup and restore parsers"""
73 | parser = update_parser_all(parser, environment)
74 | parser.add_argument('FILES', nargs='*',
75 | help='files to interact on as specified in YAML, '
76 | + 'defaults to all files for device')
77 | parser.add_argument('-d', '--device', default=get_hostname(),
78 | help='specify device name to use, defaults to '
79 | + 'current hostname')
80 | parser.add_argument('--no-diff', action='store_true',
81 | help='suppress diff output')
82 | parser.add_argument('--dry-run', action='store_true',
83 | help='do not modify any files')
84 | parser.add_argument('--sudo', action='store_true',
85 | help='use "sudo" when copying/creating files')
86 | return parser
87 |
88 |
89 | def update_parser_sync_restore(parser, environment):
90 | """Adds arguments to the restore parser"""
91 | parser = update_parser_sync(parser, environment)
92 | parser.add_argument('--staging',
93 | help='store files to staging directory instead of '
94 | + 'local files')
95 | return parser
96 |
97 |
98 | def update_parser_yaml_modify(parser):
99 | """Adds arguments to the add and remove parsers"""
100 | parser.add_argument('-d', '--device', default=get_hostname(),
101 | help='specify device name to use, defaults to current '
102 | + 'hostname')
103 | parser.add_argument('--no-diff', action='store_true')
104 | parser.add_argument('--dry-run', action='store_true',
105 | help='do not modify any files')
106 |
107 | return parser
108 |
109 |
110 | # YAML
111 |
112 | def prep_yaml():
113 | """Find filetailor.ini, read it, then load YAML"""
114 |
115 | if 'test' in ARGS and ARGS.test:
116 | # Use test locations
117 | logging.debug('Using test config')
118 | paths = {'sync_dir': './tests/sync', 'yaml_dir': './tests/yaml'}
119 | else:
120 | # Load YAML
121 | logging.debug('Using production config')
122 | filetailor_ini_path = load_ini_files.find_filetailor_ini()
123 | if not os.path.isfile(filetailor_ini_path):
124 | print('ERROR: "filetailor.ini" not found at '
125 | + f'"{filetailor_ini_path}".')
126 | print('Fix the path or run "filetailor init" to generate a new '
127 | + 'INI file.')
128 | sys.exit()
129 | filetailor_ini = load_ini_files.read_filetailor_ini(
130 | filetailor_ini_path)
131 | paths = filetailor_ini['PATHS']
132 |
133 | # Check directories exist
134 | for key in paths:
135 |
136 | if key not in ['sync_dir', 'yaml', 'in-progress_dir']:
137 | continue
138 |
139 | # Convert to Path type
140 | os_path = Path(paths[key])
141 |
142 | # Check if directory exists
143 | if not os.path.exists(os_path):
144 | print(f'ERROR: "{os_path}" does not exist ({key}). '
145 | + 'Run "filetailor init" to create.')
146 | sys.exit()
147 |
148 | # Load YAML
149 | logging.debug('Loading YAML')
150 | (yaml_default, yaml_devices,
151 | yaml_files) = filetailor.helpers.load_yaml.main(paths)
152 | ftconfig.yaml_default = yaml_default
153 | ftconfig.yaml_devices = yaml_devices
154 | ftconfig.yaml_files = yaml_files
155 |
156 | ftconfig.paths = paths
157 | ftconfig.tools = filetailor_ini['TOOLS']
158 | if 'device' in ARGS:
159 | ftconfig.device_id = get_device_id(yaml_devices, ARGS.device)
160 |
161 |
162 | # CORE FUNCTIONS
163 |
164 | def call_init():
165 | """Create filetailor.ini or create sync_dir and yaml"""
166 | filetailor.core.initialize.main()
167 |
168 |
169 | def call_sync_status():
170 | """Display status of local files in comparison to the sync directory"""
171 | logging.debug('Calling sync:status')
172 | ftconfig.sync = 'status'
173 | prep_yaml()
174 | filetailor.core.sync.status()
175 |
176 |
177 | def call_sync_backup():
178 | """Copy files from local machine to sync_dir"""
179 | logging.debug('Calling sync:backup')
180 | ftconfig.sync = 'backup'
181 | prep_yaml()
182 | filetailor.core.sync.backup()
183 |
184 |
185 | def call_sync_restore():
186 | """Copy files from sync_dir to local machine"""
187 | logging.debug('Calling sync:restore')
188 | ftconfig.sync = 'restore'
189 | prep_yaml()
190 | filetailor.core.sync.restore()
191 |
192 |
193 | def call_yaml_add():
194 | """Add file location to YAML for backup/restore"""
195 | prep_yaml()
196 | filetailor.core.update_yaml.main('add')
197 |
198 |
199 | def call_yaml_remove():
200 | """Remove file location from YAML for backup/restore"""
201 | prep_yaml()
202 | filetailor.core.update_yaml.main('remove')
203 |
204 |
205 | def call_clean():
206 | """Remove files from sync_dir that are no longer defined in YAML"""
207 | prep_yaml()
208 | filetailor.core.clean.main()
209 |
210 |
211 | def call_uninstall():
212 | """Delete filetailor directories"""
213 | filetailor.core.uninstall.main()
214 |
215 |
216 | def call_paths():
217 | """Show filetailor paths"""
218 | prep_yaml()
219 | filetailor.core.paths.main()
220 |
221 |
222 | def main():
223 | """Create argparse parsers, update variables, and call the core function as
224 | defined by the user arguments
225 | """
226 |
227 | # Get path to data directory
228 | ftconfig.data = os.path.join(os.path.dirname(__file__), 'data')
229 |
230 | # Load config.ini
231 | config_ini = load_ini_files.load_config_ini()
232 | override_filetailor_ini_path = config_ini['DEFAULT'].get(
233 | 'override_filetailor_ini_path', '')
234 | ftconfig.override_filetailor_ini_path = override_filetailor_ini_path
235 |
236 | # Generate main parser
237 | parser = argparse.ArgumentParser(
238 | description=('Peer-based configuration management utility with a high'
239 | ' level of file content control.'))
240 | parser = update_parser_all(parser, config_ini)
241 | parser.add_argument('--version', action='version',
242 | version=f'%(prog)s {__version__}')
243 | subparsers = parser.add_subparsers(
244 | help='commands executing various aspects of filetailor')
245 |
246 | # Generate subparsers
247 |
248 | # Parser: init
249 | parser_init = subparsers.add_parser(
250 | 'init',
251 | help='initialize new directories for sync')
252 | parser_init = update_parser_all(parser_init, config_ini)
253 | parser_init.set_defaults(func=call_init)
254 |
255 | # Parser: status
256 | parser_sync_status = subparsers.add_parser(
257 | 'status',
258 | help='display status of local files in comparison to the sync directory')
259 | parser_sync_status = update_parser_sync(parser_sync_status, config_ini)
260 | parser_sync_status.set_defaults(func=call_sync_status)
261 |
262 | # Parser: backup
263 | parser_sync_backup = subparsers.add_parser(
264 | 'backup',
265 | help='copy files from local device to sync directory')
266 | parser_sync_backup = update_parser_sync(parser_sync_backup, config_ini)
267 | parser_sync_backup.set_defaults(func=call_sync_backup)
268 |
269 | # Parser: restore
270 | parser_sync_restore = subparsers.add_parser(
271 | 'restore',
272 | help='copy files from sync directory to local device')
273 | parser_sync_restore.add_argument('--no-backup', action='store_true')
274 | parser_sync_restore = update_parser_sync_restore(parser_sync_restore, config_ini)
275 | parser_sync_restore.set_defaults(func=call_sync_restore)
276 |
277 | # Parser: yaml:add
278 | parser_yaml_add = subparsers.add_parser(
279 | 'add',
280 | help='add files to YAML')
281 | parser_yaml_add = update_parser_all(parser_yaml_add, config_ini)
282 | parser_yaml_add.add_argument(
283 | 'PATHS', nargs='*', type=Path,
284 | help='file path(s) on system to add to YAML')
285 | parser_yaml_add.add_argument(
286 | '-n', '--name', action='append', help='name to save within YAML')
287 | parser_yaml_add = update_parser_yaml_modify(parser_yaml_add)
288 | parser_yaml_add.set_defaults(func=call_yaml_add)
289 |
290 | # Parser: yaml:remove
291 | parser_yaml_remove = subparsers.add_parser(
292 | 'remove',
293 | help='remove files from YAML')
294 | parser_yaml_remove = update_parser_all(parser_yaml_remove, config_ini)
295 | parser_yaml_remove.add_argument(
296 | 'FILES', nargs='*', help='file(s) to remove from YAML')
297 | parser_yaml_remove = update_parser_yaml_modify(parser_yaml_remove)
298 | parser_yaml_remove.set_defaults(func=call_yaml_remove)
299 |
300 | # Parser: clean
301 | parser_clean = subparsers.add_parser(
302 | 'clean',
303 | help='permanently delete files from sync directory not in YAML')
304 | parser_clean = update_parser_all(parser_clean, config_ini)
305 | parser_clean.add_argument('--dry-run', action='store_true',
306 | help='do not modify any files')
307 | parser_clean.set_defaults(func=call_clean)
308 |
309 | # Parser: uninstall
310 | parser_uninstall = subparsers.add_parser(
311 | 'uninstall',
312 | help='delete filetailor directories')
313 | parser_uninstall = update_parser_all(parser_uninstall, config_ini)
314 | parser_uninstall.add_argument('--dry-run', action='store_true',
315 | help='do not modify any files')
316 | parser_uninstall.set_defaults(func=call_uninstall)
317 |
318 | # Parser: paths
319 | parser_paths = subparsers.add_parser(
320 | 'paths',
321 | help='show paths to configuration files')
322 | parser_paths.set_defaults(func=call_paths)
323 |
324 | # Get ARGS then call function
325 | global ARGS
326 | ARGS = parser.parse_args()
327 | ftconfig.args = ARGS
328 | if 'debug' in ARGS and ARGS.debug:
329 | logging.getLogger().setLevel(logging.DEBUG)
330 | logging.info('ARGS = %s', ARGS)
331 |
332 | if 'func' in ARGS:
333 | # Call core function
334 | ARGS.func()
335 | else:
336 | # Call help if no argument provided
337 | parser.print_help()
338 |
339 |
340 | # https://docs.python.org/3/library/__main__.html
341 | if __name__ == '__main__':
342 | main()
343 |
--------------------------------------------------------------------------------
/filetailor/core/sync.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """Copy files between local machine and sync_dir"""
3 |
4 | # pylint: disable=no-member
5 |
6 | import copy
7 | import filecmp
8 | import logging
9 | import os
10 | import re
11 | import shutil
12 | import stat
13 | import sys
14 | from pathlib import Path
15 |
16 | import filetailor.config as ftconfig
17 | import filetailor.helpers.get_key_list
18 | import filetailor.helpers.okay_to_continue as okay
19 | import filetailor.helpers.tailor_lines
20 | from filetailor.helpers import cprint
21 | from filetailor.helpers.diff import diff
22 | from filetailor.helpers.get_option import main as get_option
23 |
24 | STATUS = 'status'
25 | BACKUP = 'backup'
26 | RESTORE = 'restore'
27 | SAME = 'same'
28 | DIFFERENT = 'different'
29 | MISSING_SOURCE = 'missing source'
30 | MISSING_TARGET = 'missing target'
31 | MISSING_BOTH = 'missing both'
32 | SKIP = 'skip'
33 | UPDATE = 'Update'
34 | ADD_NEW = 'Add new'
35 | DELETE = 'Delete'
36 |
37 |
38 | class CDevice():
39 | """Current device"""
40 | type = 'device'
41 |
42 | def __init__(self, device_id, yaml_devices):
43 | self.device_id = device_id
44 | self.yaml_default = YAML_DEFAULT
45 | self.yaml_device = self.tailor_yaml(
46 | YAML_DEFAULT, yaml_devices[device_id])
47 |
48 | def replace_dict_values(self, d, find, replace):
49 | # pylint: disable=invalid-name
50 | """Replace dictionary values (not keys) recursively"""
51 | if d:
52 | for key in d.keys():
53 | if isinstance(d[key], dict):
54 | d[key] = self.replace_dict_values(d[key], find, replace)
55 | elif isinstance(d[key], str):
56 | d[key] = d[key].replace(find, replace)
57 |
58 | return d
59 |
60 | def tailor_yaml(self, yaml_device, yaml_file=None):
61 | """Replace vars in yaml"""
62 | key_list = filetailor.helpers.get_key_list.main(
63 | YAML_DEFAULT, yaml_device, yaml_file, 'yaml')
64 |
65 | # pylint: disable=consider-using-dict-items
66 | for key in key_list:
67 | var = key_list[key]
68 | if yaml_file:
69 | # Replace vars in `yaml_file` from `yaml_device` and
70 | # `YAML_DEFAULT`
71 | self.replace_dict_values(yaml_file, key, var)
72 | # else:
73 | # # Replace vars in `yaml_device` from `YAML_DEFAULT`
74 | # self.replace_dict_values(yaml_device, key, var)
75 |
76 | if yaml_file:
77 | return yaml_file
78 | return yaml_device
79 |
80 |
81 | class CFile(CDevice):
82 | """Current file"""
83 | type = 'file'
84 |
85 | def __init__(self, file_id, cdevice):
86 | # super().__init__(device_id, yaml_device)
87 | self.device = cdevice
88 | self.device_id = cdevice.device_id
89 | self.yaml_default = YAML_DEFAULT
90 | self.yaml_device = cdevice.yaml_device
91 | self.yaml_file = self.tailor_yaml(
92 | cdevice.yaml_device, yaml_files[file_id])
93 | self.file_id = self.get_file_id(file_id, cdevice)
94 | self.local = None
95 | self.sync = None
96 | self.dircmp_report = None
97 | self.source = None
98 | self.target = None
99 | self.target_parent = None
100 | self.in_progress = None
101 | self.stats = None
102 |
103 | self.new = None
104 | self.delete = None
105 | self.changed = []
106 |
107 | def get_file_id(self, file_id, cdevice):
108 | """Prefix `file_id` with device name if `unique = True`"""
109 | if self.yaml_file and 'unique' in self.yaml_file:
110 | if self.yaml_file['unique']:
111 | return f'{file_id}_{cdevice.device_id}'
112 | return file_id
113 |
114 | def set_paths(self, source, target, parent=None):
115 | """Set paths and associated attributes"""
116 | self.source = source
117 | self.target = target
118 | self.target_parent = self.target.parent.absolute()
119 |
120 | if parent:
121 | self.in_progress = Path(os.path.join(
122 | ftconfig.paths['in-progress_dir'], parent, self.file_id))
123 | else:
124 | self.in_progress = Path(os.path.join(
125 | ftconfig.paths['in-progress_dir'], self.file_id))
126 |
127 | def clean_in_progress_file(self):
128 | """Remove in_progress_file"""
129 | if not get_option('dry_run', self, self.device):
130 | if self.in_progress.is_file():
131 | os.remove(self.in_progress)
132 | elif self.in_progress.is_dir():
133 | shutil.rmtree(self.in_progress)
134 |
135 |
136 | class SubFile(CFile):
137 | """Subfile of a directory (class CFile)"""
138 | type = 'subfile'
139 | def __init__(self, file_id, cfile):
140 | self.device = cfile.device
141 | self.device_id = cfile.device_id
142 | self.yaml_default = YAML_DEFAULT
143 | self.file_id = file_id
144 | self.yaml_device = cfile.yaml_device
145 | self.yaml_file = cfile.yaml_file
146 | CFile.set_paths(self,
147 | Path(os.path.join(cfile.source, file_id)),
148 | Path(os.path.join(cfile.target, file_id)),
149 | cfile.file_id)
150 |
151 |
152 | def check_for_sudo(xfile, device):
153 | """Check if filetailor should use sudo
154 |
155 | Called by `copy_file`, `create_dir`, and `backup_or_restore`
156 | """
157 | if ftconfig.sync == RESTORE and get_option('sudo', xfile, device):
158 | use_sudo = True
159 | else:
160 | use_sudo = False
161 |
162 | return use_sudo
163 |
164 |
165 | def copy_file_with_sudo(in_progress, target, delete):
166 | """Copy file with permissions and sudo
167 |
168 | Called by `copy_file` (for files and dirs)
169 | """
170 |
171 | if delete:
172 | shutil.os.system(f'sudo rm "{target}"')
173 | else:
174 | shutil.os.system(f'sudo cp "{in_progress}" "{target}"')
175 | # subprocess.run(f'cp --preserve --recursive {source} {target}')
176 |
177 | return True
178 |
179 |
180 | def copy_file(in_progress, target, xfile, delete):
181 | """Copy file with permissions
182 |
183 | Called by `copy_files` (for files and dirs)
184 | """
185 |
186 | copied = False
187 | if check_for_sudo(xfile, xfile.device):
188 | copy_file_with_sudo(in_progress, target, delete)
189 | else:
190 | try:
191 | if delete:
192 | os.remove(target)
193 | else:
194 | shutil.copy2(in_progress, target)
195 | if ftconfig.sync == RESTORE and sys.platform.startswith('linux'):
196 | # Apply permissions
197 | os.chown(target, xfile.stats[stat.ST_UID],
198 | xfile.stats[stat.ST_GID])
199 | copied = True
200 | except PermissionError:
201 | if okay.main(f'Insufficient permissions to create "{target}". '
202 | + 'Try with "sudo"?', 'n'):
203 | copied = copy_file_with_sudo(in_progress, target, delete)
204 | else:
205 | copied = False
206 |
207 | return copied
208 |
209 |
210 | def create_dir_with_sudo(path):
211 | """Create the directory with sudo
212 |
213 | Called by `create_dir` (for files and dirs)
214 | """
215 |
216 | shutil.os.system(f'sudo mkdir --parents "{path}"')
217 | cprint.success(f'Created "{path}" with sudo.')
218 | print()
219 |
220 | return True
221 |
222 |
223 | def create_dir(path, xfile):
224 | """Create the directory if it does not exist
225 |
226 | Called by `get_file_status` (for staging directories),
227 | `copy_files` (for files and dirs) and `copy_subfiles` (for dirs)
228 | """
229 |
230 | if path.is_dir():
231 | dir_exists = True
232 | else:
233 | dir_exists = False
234 | if okay.main(f'"{path}" does not exist. Create?', 'n'):
235 | create_dir_continue = True
236 | else:
237 | create_dir_continue = False
238 | if create_dir_continue:
239 | if check_for_sudo(xfile, xfile.device):
240 | if not get_option('dry_run', xfile, xfile.device):
241 | dir_exists = create_dir_with_sudo(path)
242 | else:
243 | try:
244 | if not get_option('dry_run', xfile, xfile.device):
245 | os.makedirs(path)
246 | cprint.success(f'Created "{path}".')
247 | print()
248 | dir_exists = True
249 | except PermissionError:
250 | if okay.main('Insufficient permissions to create '
251 | + f'"{path}". Try with "sudo"?', 'n'):
252 | dir_exists = create_dir_with_sudo(path)
253 | else:
254 | dir_exists = False
255 |
256 | return dir_exists
257 |
258 |
259 | def copy_files(xfile, delete=False):
260 | """Copy file while creating parents and backups
261 |
262 | Called by `backup_or_restore` (for files) and `copy_subfiles` (for dirs)
263 | """
264 |
265 | # Create parent directory if needed
266 | if not create_dir(xfile.target_parent, xfile):
267 | return
268 |
269 | if (ftconfig.sync == RESTORE
270 | and not get_option('no_backup', xfile, xfile.device)
271 | and not get_option('dry_run', xfile, xfile.device)):
272 | # Create backup
273 | if xfile.target.is_file():
274 | copy_file(xfile.target, xfile.target.with_suffix('.filetailor_backup'),
275 | xfile, False)
276 |
277 | if not args.dry_run:
278 | if copy_file(xfile.in_progress, xfile.target, xfile, delete):
279 | if delete:
280 | cprint.success(f'Deleted "{xfile.target}".')
281 | else:
282 | cprint.success(f'Copied "{xfile.source}" to "{xfile.target}".')
283 | print()
284 |
285 |
286 | def copy_subfiles(cfile, subfiles_list, verb):
287 | """Tailor subfiles within a directory
288 |
289 | Called by `backup_or_restore` (for dirs)
290 | """
291 |
292 | if subfiles_list and len(subfiles_list):
293 | delete = (verb == DELETE)
294 | response = okay.get_response(f'\n{verb} files?', 'a')
295 | if response != 'n':
296 | if not create_dir(cfile.target, cfile):
297 | return
298 | for file_id in subfiles_list:
299 | subfile = SubFile(file_id, cfile)
300 | subfile.stats = cfile.stats
301 | if verb == UPDATE:
302 | diff(subfile.target, subfile.in_progress)
303 | if response == 'a':
304 | # Copy/delete each file without asking
305 | if not get_option('dry_run', cfile, cfile.device):
306 | copy_files(subfile, delete)
307 | elif okay.main(f'{verb} "{file_id}"?', 'd',
308 | obj1=cfile, obj2=cfile.device,
309 | src=subfile.source, dst=subfile.target):
310 | # Asked to copy/delete file, answer was yes
311 | if not get_option('dry_run', cfile, cfile.device):
312 | copy_files(subfile, delete)
313 | subfile.clean_in_progress_file()
314 |
315 |
316 | def tailor_file(xfile):
317 | """Backup or restore a single file; return True if files differ
318 |
319 | Called by `get_file_status` (for files) and `diff_dir` (for dirs)
320 | """
321 |
322 | logging.debug('xfile.source = %s', xfile.source)
323 | logging.debug('target = %s', xfile.target)
324 |
325 | # Convert all variables in source_text
326 | source_tailored = filetailor.helpers.tailor_lines.main(xfile)
327 | logging.debug('source_tailored = %s', source_tailored)
328 |
329 | # Write source_tailored to a file (in_progress_file)
330 | with open(xfile.in_progress, 'w', encoding='UTF-8') as in_progress_file:
331 | if source_tailored:
332 | in_progress_file.writelines(source_tailored)
333 | else:
334 | in_progress_file = xfile
335 |
336 | # Compare files
337 | if (xfile.target.is_file()
338 | and filecmp.cmp(xfile.in_progress, xfile.target, shallow=False)):
339 | # Files are identical
340 | logging.debug('Skipping %s, identical', xfile.source)
341 | files_differ = False
342 |
343 | else:
344 | # Files differ
345 | logging.debug('Diffing %s', xfile.source)
346 | files_differ = True
347 |
348 | return files_differ
349 |
350 |
351 | def filter_subfiles(search_criteria, subfiles, return_matching):
352 | """Return list of `subfiles` matching `p` if `return_matching` is True
353 | and return list of subfiles not matching `p` if `return_matching` is False
354 |
355 | Called by `diff_dir` (for dirs)
356 | """
357 |
358 | matching = []
359 | for subfile in subfiles:
360 | matches = search_criteria.search(subfile)
361 | if ((matches and return_matching)
362 | or (not matches and not return_matching)):
363 | # Ignore all files that match the filter
364 | # and ignore all files not matching the filter
365 | matching.append(subfile)
366 |
367 | return matching
368 |
369 |
370 | def diff_dir(cfile):
371 | """Compare local directory to sync directory and record the sync status of
372 | each subfile but do not ask the user any questions; return True if files
373 | differ
374 |
375 | Called by `get_file_status` (for dirs)
376 | """
377 |
378 | # Ignore subdirectories
379 | # os.walk returns root, dirs, files, so os.walk(cfile.source))[1] returns all dirs
380 | ignores = next(os.walk(cfile.source))[1]
381 | try:
382 | if ftconfig.sync in [STATUS, RESTORE]:
383 | ignores += next(os.walk(cfile.local))[1]
384 | except StopIteration:
385 | pass
386 |
387 | # Get subfiles from source and target
388 | if cfile.target.is_dir():
389 | subfiles = os.listdir(cfile.source) + os.listdir(cfile.target)
390 | else:
391 | subfiles = os.listdir(cfile.source)
392 |
393 | # Ignore `.filetailor_backup` files
394 | search_criteria = re.compile(r'\.filetailor_backup$')
395 | ignores += filter_subfiles(search_criteria, subfiles, True)
396 |
397 | # Update ignores based on YAML
398 | if 'include_contents' in cfile.yaml_file:
399 | search_criteria = re.compile(cfile.yaml_file['include_contents'])
400 | ignores += filter_subfiles(search_criteria, subfiles, False)
401 | if 'exclude_contents' in cfile.yaml_file:
402 | search_criteria = re.compile(cfile.yaml_file['exclude_contents'])
403 | ignores += filter_subfiles(search_criteria, subfiles, True)
404 |
405 | # Create cfile in in-progress_dir
406 | if not cfile.in_progress.is_dir():
407 | if not get_option('dry_run', cfile, cfile.device):
408 | os.mkdir(cfile.in_progress)
409 |
410 | # Compare source to target directory
411 | if cfile.target.is_dir():
412 | dircmp_report = filecmp.dircmp(cfile.source, cfile.target,
413 | ignore=ignores)
414 | # Get subfiles changed, new, and delete
415 | if dircmp_report.diff_files:
416 | for file_id in dircmp_report.diff_files:
417 | subfile = SubFile(file_id, cfile)
418 | if tailor_file(subfile):
419 | cfile.changed.append(subfile.file_id)
420 | cfile.new = dircmp_report.left_only
421 | cfile.delete = dircmp_report.right_only
422 | else:
423 | # Target directory does not exist, all files are new
424 | cfile.new = set(subfiles) - set(ignores)
425 |
426 | if cfile.new:
427 | for file_id in cfile.new:
428 | subfile = SubFile(file_id, cfile)
429 | tailor_file(subfile)
430 |
431 | # Determine if directories differ
432 | files_differ = cfile.changed or cfile.new or cfile.delete
433 |
434 | return files_differ
435 |
436 |
437 | def get_file_status(cfile, cdevice):
438 | """Tailor file and return if files differ
439 |
440 | Called by `status` and `backup_or_restore`
441 | """
442 |
443 | # Loop through each file to perform the sync operation
444 | logging.debug('Beginning %s', cfile.file_id)
445 |
446 | # Check if file is for this device
447 | if 'include_devices' in cfile.yaml_file:
448 | if cdevice.device_id not in cfile.yaml_file['include_devices']:
449 | logging.debug('Skipping %s, host not in included list',
450 | cfile.file_id)
451 | return SKIP
452 | elif 'exclude_devices' in cfile.yaml_file:
453 | if cdevice.device_id in cfile.yaml_file['exclude_devices']:
454 | logging.debug('Skipping %s, host in excluded list',
455 | cfile.file_id)
456 | return SKIP
457 |
458 | run_script(cfile, 'before', ftconfig.sync)
459 |
460 | # Define file locations `sync` and `local`
461 | cfile.sync = Path(os.path.join(ftconfig.paths['sync_dir'], cfile.file_id))
462 | staging_dir = get_option('staging', cfile, cfile.device)
463 | if staging_dir:
464 | cfile.local = Path(os.path.join(
465 | Path(staging_dir).resolve(),
466 | cfile.file_id,
467 | os.path.basename(cfile.yaml_file['path'])))
468 | else:
469 | cfile.local = Path(cfile.yaml_file['path'])
470 |
471 | # Define file location `source` and `target`
472 | if ftconfig.sync in [BACKUP]:
473 | source = cfile.local
474 | target = cfile.sync
475 |
476 | elif ftconfig.sync in [STATUS, RESTORE]:
477 | source = cfile.sync
478 | target = cfile.local
479 |
480 | # Check if `source` and `target` are files or directories,
481 | # also set `in_progress` path
482 | cfile.set_paths(source, target)
483 |
484 | # Copy owner and group from `local` (same as `target`)
485 | if ftconfig.sync in [RESTORE]:
486 |
487 | if not cfile.target.exists() and not cfile.target_parent.is_dir():
488 | # Target nor its parent exist, so offer to create parent dir
489 | cprint.plain(f'For "{cfile.file_id}", local file\'s parent directory '
490 | + f'"{cfile.target_parent}" does not exist.')
491 | if not create_dir(cfile.target_parent, cfile):
492 | return SKIP
493 |
494 | if cfile.target.exists():
495 | # Target exists
496 | cfile.stats = os.stat(cfile.local)
497 | logging.debug('stats[stat.ST_UID] = %s', cfile.stats[stat.ST_UID])
498 | logging.debug('stats[stat.ST_GID] = %s', cfile.stats[stat.ST_GID])
499 | logging.debug('stats[stat.st_mode] = %s', cfile.stats[stat.ST_MODE])
500 | else:
501 | # Parent of target exists
502 | cfile.stats = os.stat(cfile.target_parent)
503 | logging.debug('stats[stat.ST_UID] = %s', cfile.stats[stat.ST_UID])
504 | logging.debug('stats[stat.ST_GID] = %s', cfile.stats[stat.ST_GID])
505 | logging.debug('stats[stat.st_mode] = %s', cfile.stats[stat.ST_MODE])
506 |
507 | # Tailor and compare files
508 | # First check if a file/directory of opposite type will block creating
509 | # a new file.
510 | if cfile.source.is_file():
511 | # For files
512 | if cfile.target.is_dir():
513 | cprint.plain(f'Trying to copy file "{cfile.file_id}" to '
514 | + f'"{cfile.target}", but a directory (not file) of '
515 | + 'the same name already exists. Skipping.')
516 | return
517 | files_differ = tailor_file(cfile)
518 | if cfile.target.is_file():
519 | if files_differ:
520 | file_status = DIFFERENT
521 | else:
522 | file_status = SAME
523 | else:
524 | file_status = MISSING_TARGET
525 | elif cfile.source.is_dir():
526 | # For directories
527 | if cfile.target.is_file():
528 | cprint.plain(f'Trying to copy directory "{cfile.file_id}" to '
529 | + f'"{cfile.target}", but a file (not directory) of '
530 | + 'the same name already exists. Skipping.')
531 | return
532 | files_differ = diff_dir(cfile)
533 | if cfile.target.is_dir():
534 | if files_differ:
535 | file_status = DIFFERENT
536 | else:
537 | file_status = SAME
538 | else:
539 | file_status = MISSING_TARGET
540 | elif cfile.target.exists():
541 | file_status = MISSING_SOURCE
542 | else:
543 | file_status = MISSING_BOTH
544 |
545 | return file_status
546 |
547 |
548 | def setup():
549 | """Get current device with YAML and files to sync
550 |
551 | Called by `backup_or_restore`
552 | """
553 |
554 | logging.debug('Running setup')
555 | global args
556 | args = ftconfig.args
557 |
558 | # Get YAML
559 | global YAML_DEFAULT
560 | YAML_DEFAULT = copy.deepcopy(ftconfig.yaml_default)
561 | yaml_devices = copy.deepcopy(ftconfig.yaml_devices)
562 | global yaml_files
563 | yaml_files = copy.deepcopy(ftconfig.yaml_files)
564 |
565 | # Get current device
566 | device_id = ftconfig.device_id
567 |
568 | # Replace vars in device YAML
569 | if device_id not in yaml_devices:
570 | cprint.error(f'Device "{device_id}" is not in YAML. Run "filetailor '
571 | + 'add" or manually update YAML with device to use '
572 | + 'filetailor.')
573 | sys.exit()
574 | cdevice = CDevice(device_id, yaml_devices)
575 |
576 | # Get list of files to operate on
577 | if args.FILES == []:
578 | # Use all files in YAML if user didn't specify any
579 | files = yaml_files.keys()
580 | else:
581 | # If the user specified files, use those
582 | files = []
583 | for file_id in args.FILES:
584 | if file_id in yaml_files:
585 | # Check file exists in the YAML
586 | files.append(file_id)
587 | else:
588 | cprint.plain(f'{file_id} not found in YAML.')
589 |
590 | return (cdevice, files)
591 |
592 |
593 | def run_script(cfile, time, operation):
594 | """Runs script from YAML
595 |
596 | Called by `backup_or_restore`
597 | """
598 |
599 | if time == 'before':
600 | if operation in [STATUS, BACKUP]:
601 | script_name = 'before_backup'
602 | elif operation == RESTORE:
603 | script_name = 'before_restore'
604 | elif time == 'after':
605 | if operation in [STATUS, BACKUP]:
606 | script_name = 'after_backup'
607 | elif operation == RESTORE:
608 | script_name = 'after_restore'
609 |
610 | try:
611 | script_command = cfile.yaml_file['scripts'][script_name]
612 | cprint.plain(f'For file "{cfile.file_id}", running {script_name} '
613 | + f'script "{script_command}"')
614 | shutil.os.system(script_command)
615 | except (KeyError, TypeError, UnboundLocalError):
616 | pass
617 |
618 |
619 | def backup_or_restore():
620 | """Copy files from/to local machine and sync_dir
621 |
622 | Called by `status`, `backup`, and `restore`
623 | """
624 |
625 | (cdevice, files) = setup()
626 | for file_id in files:
627 |
628 | # Replace vars in file YAML
629 | cfile = CFile(file_id, cdevice)
630 |
631 | file_status = get_file_status(cfile, cdevice)
632 | if file_status == SKIP:
633 | continue
634 |
635 | # If running status, report the status
636 | if ftconfig.sync == STATUS and file_status == SAME:
637 | cprint.same(f'No change: {cfile.file_id}')
638 | elif ftconfig.sync == STATUS and file_status == DIFFERENT:
639 | cprint.differ(f'Modified: {cfile.file_id}')
640 | elif ftconfig.sync == STATUS and file_status == MISSING_TARGET:
641 | cprint.differ(f'Not in local directory: "{cfile.file_id}" does '
642 | + f'not exist at "{cfile.target}".')
643 |
644 | # Report issue if missing source
645 | elif file_status in [MISSING_SOURCE, MISSING_BOTH]:
646 | if ftconfig.sync in [BACKUP]:
647 | cprint.differ(f'Not in local directory: "{cfile.file_id}" does '
648 | + f'not exist at "{cfile.source}".')
649 | if ftconfig.sync in [STATUS, RESTORE]:
650 | cprint.differ(f'Not in sync directory: "{cfile.file_id}" does '
651 | + f'not exist at "{cfile.source}".')
652 |
653 | # If running backup/restore and not missing source, update files
654 | elif file_status in [DIFFERENT, MISSING_TARGET]:
655 |
656 | if cfile.source.is_file():
657 | # For files
658 | # Print diff or state target doesn't exist
659 | if file_status == DIFFERENT:
660 | if not get_option('no_diff', cfile, cfile.device):
661 | diff(cfile.target, cfile.in_progress)
662 | elif file_status == MISSING_TARGET:
663 | cprint.plain(f'For "{cfile.file_id}", '
664 | + f'"{cfile.target}" does not exist.')
665 | cprint.plain('')
666 |
667 | # Copy file
668 | if check_for_sudo(cfile, cfile.device):
669 | cprint.plain('Using "sudo"...')
670 | if okay.main(f'Copy file "{cfile.file_id}"?', 'd',
671 | obj1=cfile, obj2=cfile.device,
672 | src=cfile.in_progress, dst=cfile.target):
673 | copy_files(cfile)
674 |
675 | elif cfile.source.is_dir():
676 | # For directories
677 | cprint.differ(f'\nDIRECTORY: {cfile.file_id}')
678 | if cfile.changed:
679 | cprint.plain('\nFiles to update:')
680 | cprint.plain(cfile.changed)
681 | if cfile.new:
682 | cprint.plain('\nNew files to add:')
683 | cprint.plain(cfile.new)
684 | if cfile.delete:
685 | cprint.plain('\nOld files to delete:')
686 | cprint.plain(cfile.delete)
687 | copy_subfiles(cfile, cfile.changed, UPDATE)
688 | copy_subfiles(cfile, cfile.new, ADD_NEW)
689 | copy_subfiles(cfile, cfile.delete, DELETE)
690 |
691 | if file_status != SKIP:
692 | if ftconfig.sync == STATUS:
693 | cfile.clean_in_progress_file()
694 | run_script(cfile, 'after', ftconfig.sync)
695 |
696 |
697 | def status():
698 | """Show status of files"""
699 | logging.debug('Running status')
700 | backup_or_restore()
701 | cprint.plain('\nStatus check complete!\n')
702 |
703 |
704 | def backup():
705 | """Copy files from local machine to sync_dir"""
706 | logging.debug('Running backup')
707 | backup_or_restore()
708 | cprint.plain('\nBackup complete!\n')
709 |
710 |
711 | def restore():
712 | """Copy files from sync_dir to local machine"""
713 | logging.debug('Running restore')
714 | backup_or_restore()
715 | cprint.plain('\nRestore complete!\n')
716 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.