|
2 | 2 |
|
3 | 3 | import argparse |
4 | 4 | import os |
| 5 | +from pathlib import Path |
5 | 6 | import subprocess |
| 7 | +import yaml |
| 8 | +from typing import Dict |
| 9 | + |
6 | 10 |
|
7 | 11 | cmd_str = 'watchmedo shell-command --recursive --patterns="{local_dir}*" --command="rsync --filter=\':- .gitignore\' ' \ |
8 | 12 | '--exclude \'*.ipynb\' --exclude \'.git\' --delete-after -rz --port {port} {local_dir} ' \ |
9 | 13 | '{target}:{remote_dir}" {local_dir}' |
10 | 14 |
|
11 | 15 | epilog_str = ''' |
12 | | -Example for connecting to LeoMed: |
13 | | - code_sync --local_dir mylocaldir/ --remote_dir myremotedir/ --target medinfmk --port 2222\n |
| 16 | +EXAMPLE USAGE |
| 17 | +Register a project: |
| 18 | + code_sync --register <project> |
| 19 | +
|
| 20 | +code_sync a registered project: |
| 21 | + code_sync <project> |
| 22 | +
|
| 23 | +List all projects registered to code_sync: |
| 24 | + code_sync --list |
| 25 | +
|
| 26 | +Run code_sync with specific parameters: |
| 27 | + code_sync --local_dir <mylocaldir/> --remote_dir <myremotedir/> --target <ssh_remote> --port 2222\n |
14 | 28 |
|
15 | 29 | ''' |
16 | 30 |
|
| 31 | +CONFIG_FILE_NAME = '.code_sync' |
| 32 | + |
17 | 33 |
|
18 | 34 | def code_sync(local_dir, remote_dir, target, port=22): |
19 | 35 | # clean up slashes |
20 | 36 | local_dir = os.path.join(local_dir, '') |
21 | 37 | remote_dir = os.path.join(remote_dir, '') |
22 | 38 |
|
23 | | - # subprocess.call() |
| 39 | + print(f"Starting code_sync between {local_dir} and {target}:{remote_dir} ...") |
| 40 | + print('(^C to quit)') |
24 | 41 | cmd = cmd_str.format(local_dir=local_dir, remote_dir=remote_dir, target=target, port=port) |
25 | 42 | subprocess.call(cmd, shell=True) |
26 | 43 |
|
27 | 44 |
|
| 45 | +def get_config_file_path() -> Path: |
| 46 | + return Path(Path.home(), CONFIG_FILE_NAME) |
| 47 | + |
| 48 | + |
| 49 | +def load_config() -> Dict: |
| 50 | + """ |
| 51 | + Load the code_sync config file. Create a blank one if no file exists. |
| 52 | +
|
| 53 | + Returns: |
| 54 | + The config loaded from the file. |
| 55 | + """ |
| 56 | + |
| 57 | + create_config_if_not_exists() |
| 58 | + |
| 59 | + config_file_path = get_config_file_path() |
| 60 | + with open(config_file_path, 'r') as f: |
| 61 | + config = yaml.safe_load(f) |
| 62 | + # if config is empty, return an empty dictionary (not None) |
| 63 | + if config is None: |
| 64 | + config = {} |
| 65 | + return config |
| 66 | + |
| 67 | + |
| 68 | +def init_config() -> None: |
| 69 | + """Create an empty config file.""" |
| 70 | + config_path = get_config_file_path() |
| 71 | + open(config_path.__str__(), 'x').close() |
| 72 | + |
| 73 | + |
| 74 | +def create_config_if_not_exists() -> None: |
| 75 | + """Create the code_sync config if it does not already exist.""" |
| 76 | + config_file_path = get_config_file_path() |
| 77 | + if not config_file_path.exists(): |
| 78 | + init_config() |
| 79 | + |
| 80 | + |
| 81 | +def register_project(project: str) -> None: |
| 82 | + """ |
| 83 | + Register a project to the code_sync config. |
| 84 | +
|
| 85 | + Args: |
| 86 | + project: The name of the project to register. |
| 87 | +
|
| 88 | + Returns: |
| 89 | + None. The result is saved to the code_sync config. |
| 90 | +
|
| 91 | + Raises: |
| 92 | + ValueError if there is already a registered project with the given name. |
| 93 | +
|
| 94 | + """ |
| 95 | + config = load_config() |
| 96 | + if project in config: |
| 97 | + raise ValueError(f"Project '{project}' is already registered") |
| 98 | + |
| 99 | + print(f"Registering new project '{project}'") |
| 100 | + local_dir = input('Path to code_sync on this local machine: ') |
| 101 | + target = input('Destination machine: ') |
| 102 | + remote_dir = input('Path on the destination machine to sync: ') |
| 103 | + port = int(input('Port number to use (default 22): ') or "22") |
| 104 | + |
| 105 | + config_entry_data = { |
| 106 | + project: { |
| 107 | + 'local_dir': local_dir, |
| 108 | + 'target': target, |
| 109 | + 'remote_dir': remote_dir, |
| 110 | + 'port': port, |
| 111 | + |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + create_config_if_not_exists() |
| 116 | + config_file_path = get_config_file_path() |
| 117 | + with open(config_file_path.__str__(), 'a') as f: |
| 118 | + yaml.dump(config_entry_data, f, default_flow_style=False, indent=4) |
| 119 | + |
| 120 | + print(f"Successfully registered project '{project}'") |
| 121 | + return |
| 122 | + |
| 123 | + |
| 124 | +def list_projects() -> None: |
| 125 | + """List all projects registered to code_sync.""" |
| 126 | + create_config_if_not_exists() |
| 127 | + config = load_config() |
| 128 | + if len(config) == 0: |
| 129 | + print('No projects registered') |
| 130 | + else: |
| 131 | + formatted_keys = ', '.join(list(config.keys())) |
| 132 | + print(formatted_keys) |
| 133 | + return |
| 134 | + |
| 135 | + |
| 136 | +def identify_code_sync_parameters(args) -> Dict: |
| 137 | + """ |
| 138 | + Identify the code_sync parameters. The user may specify a project (which should be registered to the code_sync |
| 139 | + config) or specific all command line arguments. |
| 140 | + Args: |
| 141 | + args: The args object from argparse. |
| 142 | +
|
| 143 | + Returns: |
| 144 | + Dictionary of the parameters to be used for the code_sync command. |
| 145 | +
|
| 146 | + Raises: |
| 147 | + ValueError if the specified project is not registered to the code_sync config. |
| 148 | + """ |
| 149 | + if args.project is not None: |
| 150 | + config = load_config() |
| 151 | + if args.project not in config: |
| 152 | + raise ValueError(f"Project '{args.project}' is not registered") |
| 153 | + parameters = config[args.project] |
| 154 | + else: |
| 155 | + if args.local_dir is None or args.remote_dir is None or args.target is None: |
| 156 | + raise ValueError('Missing argument. If a project is not specified, then local_dir, remote_dir, and target' |
| 157 | + ' must be specified.') |
| 158 | + parameters = dict() |
| 159 | + parameters['local_dir'] = args.local_dir |
| 160 | + parameters['remote_dir'] = args.remote_dir |
| 161 | + parameters['target'] = args.target |
| 162 | + parameters['port'] = args.local_dir |
| 163 | + return parameters |
| 164 | + |
| 165 | + |
28 | 166 | def main(): |
29 | 167 | parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, epilog=epilog_str) |
30 | | - parser.add_argument('--local_dir', help='the local code directory you want to sync', required=True) |
31 | | - parser.add_argument('--remote_dir', help='the remote directory you want to sync', required=True) |
32 | | - parser.add_argument('--target', help='specify which remote machine to connect to', required=True) |
| 168 | + parser.add_argument('project', nargs='?', default=None) |
| 169 | + parser.add_argument('--register', help='Register a new project to code_sync', required=False) |
| 170 | + parser.add_argument('--list', action='store_true', help='List all registered projects', required=False) |
| 171 | + parser.add_argument('--local_dir', help='The local code directory you want to sync', required=False) |
| 172 | + parser.add_argument('--remote_dir', help='The remote directory you want to sync', required=False) |
| 173 | + parser.add_argument('--target', help='Specify which remote machine to connect to', required=False) |
33 | 174 | parser.add_argument('--port', type=int, help='ssh port for connecting to remote', default=22) |
34 | | - |
35 | 175 | args = parser.parse_args() |
36 | 176 |
|
37 | | - code_sync(local_dir=args.local_dir, remote_dir=args.remote_dir, target=args.target, port=args.port) |
| 177 | + if args.register is not None: |
| 178 | + register_project(args.register) |
| 179 | + elif args.list: |
| 180 | + list_projects() |
| 181 | + else: |
| 182 | + params = identify_code_sync_parameters(args) |
| 183 | + code_sync(local_dir=params['local_dir'], remote_dir=params['remote_dir'], target=params['target'], |
| 184 | + port=params['port']) |
38 | 185 |
|
39 | 186 |
|
40 | 187 | if __name__ == '__main__': |
|
0 commit comments