├── 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 | ![flowchart](docs/flowchart.png) 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. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------