├── tests ├── __init__.py └── test_psync.py ├── demo-usage.gif ├── psync ├── __init__.py ├── watcher.py ├── psync.py └── cli.py ├── setup.cfg ├── .gitignore ├── LICENSE ├── setup.py └── README.md /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /demo-usage.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lazywei/psync/HEAD/demo-usage.gif -------------------------------------------------------------------------------- /psync/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = """Chih-Wei Chang""" 4 | __email__ = 'bert.cwchang@gmail.com' 5 | __version__ = '0.2.0' 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | # This flag says that the code is written to work on both Python 2 and Python 3 | # 3. If at all possible, it is good practice to do this. If you cannot, you 4 | # will need to generate wheels for each Python version that you support. 5 | universal=1 -------------------------------------------------------------------------------- /psync/watcher.py: -------------------------------------------------------------------------------- 1 | from watchdog.events import FileSystemEventHandler 2 | 3 | 4 | class AnyEventHandler(FileSystemEventHandler): 5 | def __init__(self, state): 6 | super(AnyEventHandler, self).__init__() 7 | # A dirty way to emit changes to the outside world. 8 | # Should try to use other pure way to do this. 9 | self.state = state 10 | 11 | def on_any_event(self, event): 12 | super(AnyEventHandler, self).on_any_event(event) 13 | self.state["dirty"] = True 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | # pyenv python configuration file 62 | .python-version -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017, Chih-Wei Chang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /psync/psync.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import yaml 3 | import os 4 | 5 | CONFIG_FILE = ".psync" 6 | 7 | 8 | def project_root(start_from): 9 | cur_path = start_from 10 | if os.path.isfile(os.path.join(cur_path, CONFIG_FILE)): 11 | return cur_path 12 | elif cur_path == "/": 13 | return None 14 | else: 15 | par_path = os.path.abspath(os.path.join(cur_path, "../")) 16 | return project_root(par_path) 17 | 18 | 19 | def load_config(root): 20 | filepath = os.path.join(root, CONFIG_FILE) 21 | 22 | with open(filepath) as f: 23 | conf = yaml.load(f.read()) 24 | 25 | return conf 26 | 27 | 28 | def generate_config(ssh_host, remote_path, ssh_user=None, ignores=[]): 29 | return { 30 | "remote": remote_path, 31 | "ssh": { 32 | "username": ssh_user, 33 | "host": ssh_host, 34 | }, 35 | "ignores": ignores, 36 | } 37 | 38 | 39 | def ssh_path(ssh_conf, remote_path): 40 | username = ssh_conf["username"] 41 | ssh_host = ssh_conf["host"] 42 | 43 | if username is None: 44 | return "{}:{}".format(ssh_host, remote_path) 45 | else: 46 | return "{}@{}:{}".format(username, ssh_host, remote_path) 47 | 48 | 49 | def exclude_sub_cmds(ignores): 50 | cmds = [] 51 | for ig in ignores: 52 | cmds += ["--exclude", ig] 53 | 54 | return cmds 55 | 56 | 57 | def rsync_cmds(local_path, conf): 58 | 59 | ssh_conf = conf["ssh"] 60 | remote_path = conf["remote"] 61 | ignores = conf["ignores"] 62 | 63 | cmds = ["rsync", "-e", "ssh", "-ruaz"] 64 | 65 | if len(ignores) > 0: 66 | cmds += exclude_sub_cmds(ignores) 67 | 68 | cmds += ["--rsync-path", "mkdir -p {} && rsync".format(remote_path)] 69 | cmds += [local_path, ssh_path(ssh_conf, remote_path)] 70 | 71 | return cmds 72 | 73 | 74 | def cmds_seq(root, conf): 75 | return [ 76 | rsync_cmds(root, conf), 77 | ] 78 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from setuptools import setup 5 | 6 | with open('README.md') as readme_file: 7 | readme = readme_file.read() 8 | 9 | requirements = [ 10 | 'Click>=6.0', 11 | 'PyYAML>=3.12', 12 | 'watchdog>=0.8.3', 13 | ] 14 | 15 | test_requirements = [ 16 | # TODO: put package test requirements here 17 | ] 18 | 19 | setup( 20 | name='project-sync', 21 | version='0.2.0', 22 | description="A simple tool for synchronizing local project (files) " 23 | "to remote server.", 24 | long_description=readme, 25 | 26 | author="Chih-Wei Chang", 27 | author_email='bert.cwchang@gmail.com', 28 | url='https://github.com/lazywei/psync', 29 | packages=[ 30 | 'psync', 31 | ], 32 | 33 | package_dir={'psync': 34 | 'psync'}, 35 | 36 | entry_points={ 37 | 'console_scripts': [ 38 | 'psync=psync.cli:cli' 39 | ] 40 | }, 41 | 42 | install_requires=requirements, 43 | license="MIT license", 44 | 45 | zip_safe=False, 46 | 47 | keywords='project sync rsync auto watch', 48 | 49 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers 50 | classifiers=[ 51 | # How mature is this project? Common values are 52 | # 3 - Alpha 53 | # 4 - Beta 54 | # 5 - Production/Stable 55 | 'Development Status :: 3 - Alpha', 56 | 57 | # Indicate who your project is intended for 58 | 'Intended Audience :: Developers', 59 | 60 | # Pick your license as you wish (should match "license" above) 61 | 'License :: OSI Approved :: MIT License', 62 | 63 | # Specify the Python versions you support here. In particular, ensure 64 | # that you indicate whether you support Python 2, Python 3 or both. 65 | 'Programming Language :: Python :: 2', 66 | # 'Programming Language :: Python :: 2.6', 67 | 'Programming Language :: Python :: 2.7', 68 | 'Programming Language :: Python :: 3', 69 | 'Programming Language :: Python :: 3.3', 70 | 'Programming Language :: Python :: 3.4', 71 | 'Programming Language :: Python :: 3.5', 72 | 'Programming Language :: Python :: 3.6', 73 | ], 74 | 75 | test_suite='tests', 76 | tests_require=test_requirements, 77 | ) 78 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Project Sync 2 | ======================= 3 | 4 | ## Introduction 5 | 6 | #### What 7 | 8 | A simple tool based on `rsync` for uploading / synchronizing local project 9 | (files) to remote server. 10 | 11 | #### Who 12 | For people who want to work on a project locally (on your laptop) and sync the files 13 | to remote server. For example, developing locally and executing remotely. 14 | 15 | #### Why 16 | `rsync` is flexible and powerful, but flags and options are way too complex for 17 | memorizing. 18 | 19 | ## Installation 20 | 21 | ``` 22 | $ pip install project-sync 23 | ``` 24 | 25 | This will install a command line tool `psync`, the usage of which is described below. 26 | 27 | ## Usage 28 | 29 | 30 | 1. Run `psync` under project root to generate initial config file (`.psync`). 31 | ``` 32 | $ cd ~/Code/demo_project 33 | $ psync 34 | ``` 35 | It will generate the config interactively: 36 | 37 | ``` 38 | You are not in a project (no .psync found)! 39 | Generate .psync to current directory (/Users/lazywei/Code/demo_project) [Y/n]? [Y]: Y 40 | Config will be generated at /Users/lazywei/Code/demo_project: 41 | --- 42 | Remote path [~/remote/path]: ~/remote/path 43 | SSH host [ssh_host]: aws_playground 44 | SSH username or enter '-' to skip [ssh_user]: - 45 | Files or folders to ignore (separated by space) [ ]: .git .psync 46 | ignores: 47 | - .git 48 | - .psync 49 | remote: ~/remote/path 50 | ssh: 51 | host: aws_playground 52 | username: null 53 | 54 | --- 55 | Project root is now: /Users/lazywei/Code/demo_project 56 | ``` 57 | 58 | 2. Run `psync` under any nested subfolders of the project root to sync the project. 59 | ``` 60 | $ psync 61 | Running: 62 | rsync -e ssh -ruaz --exclude .git --exclude .psync --rsync-path mkdir -p ~/remote/path && rsync /Users/lazywei/Code/demo_project aws_playground:~/remote/path 63 | --- Sync Finished --- 64 | 65 | $ ssh aws_playground "ls -a ~/remote/path/demo_project" 66 | . .. README 67 | ``` 68 | 69 | 3. Run `psync watch` to watch any modification under the project root and perform sync automatically. 70 | 71 | ### Usage Demo 72 | 73 | ![Usage Demo](demo-usage.gif) 74 | 75 | ### Config Options 76 | 77 | The config (`.psync`) is a YAML file. You can edit it after initial generating. 78 | 79 | - `ignores`: an array contains all the files for folders to exclude by `rsync` 80 | - `ssh`: 81 | - `host`: SSH Host 82 | - `username`: SSH username, `null` to ignore this (for example, when you set this in `~/.ssh/config` already) 83 | - `remote`: where to sync on remote server 84 | 85 | ## Contributions 86 | 87 | This project is currently in WIP stage; any discussion, bug report and PR are more than welcome. 88 | 89 | ## License 90 | 91 | psync is available under the MIT license. See the LICENSE file for more info. 92 | -------------------------------------------------------------------------------- /psync/cli.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import click 4 | import os 5 | import subprocess 6 | import sys 7 | import time 8 | import yaml 9 | 10 | from watchdog.observers import Observer 11 | from . import psync 12 | from . import watcher 13 | 14 | 15 | if sys.hexversion <= 0x03050000: 16 | run_shell = subprocess.call 17 | else: 18 | run_shell = subprocess.run 19 | 20 | 21 | def get_project_root(): 22 | cwd = os.getcwd() 23 | root = psync.project_root(start_from=cwd) 24 | 25 | if root is None: 26 | return False, None 27 | else: 28 | return True, root 29 | 30 | 31 | def ask_for_configs(): 32 | remote_path = click.prompt("Remote path", default="~/remote/path") 33 | ssh_host = click.prompt("SSH host", default="ssh_host") 34 | ssh_user = click.prompt("SSH username or enter '-' to skip", 35 | default="ssh_user") 36 | ignores = click.prompt("Files or folders to ignore " 37 | "(separated by space)", default=" ") 38 | 39 | if ssh_user == "-": 40 | ssh_user = None 41 | 42 | if ignores.strip(): 43 | ignores = ignores.split(" ") 44 | else: 45 | ignores = [] 46 | 47 | return psync.generate_config(ssh_user=ssh_user, 48 | ssh_host=ssh_host, 49 | remote_path=remote_path, 50 | ignores=ignores) 51 | 52 | 53 | @click.group(invoke_without_command=True) 54 | @click.pass_context 55 | def cli(ctx): 56 | """Console script for psync""" 57 | if ctx.invoked_subcommand is None: 58 | perform_sync() 59 | else: 60 | pass 61 | 62 | 63 | def perform_sync(): 64 | is_proj, root = get_project_root() 65 | 66 | if not is_proj: 67 | click.echo("You are not in a project (no .psync found)!") 68 | cwd = os.getcwd() 69 | gen_conf = click.prompt( 70 | "Generate .psync to current directory ({}) [Y/n]?".format(cwd), 71 | default="Y") 72 | 73 | if gen_conf.lower() == "y": 74 | click.echo("Config will be generated at {}:".format(cwd)) 75 | click.echo("---") 76 | 77 | conf = ask_for_configs() 78 | 79 | conf_str = yaml.dump(conf, default_flow_style=False) 80 | 81 | click.echo(conf_str) 82 | click.echo("---") 83 | 84 | with open(os.path.join(cwd, psync.CONFIG_FILE), "w") as f: 85 | f.write(conf_str) 86 | 87 | click.echo("Project root is now: {}".format( 88 | psync.project_root(start_from=os.getcwd()))) 89 | click.echo("Run `psync` to perform sync or " 90 | "`psync watch` to watch any changes and perform " 91 | "sync automatically.") 92 | else: 93 | click.echo("Aborted!") 94 | else: 95 | conf = psync.load_config(root=root) 96 | 97 | for cmd in psync.cmds_seq(root, conf): 98 | click.echo("Running: {}".format(cmd[0])) 99 | run_shell(cmd) 100 | 101 | click.echo("--- Sync Finished ---") 102 | 103 | 104 | @cli.command() 105 | def watch(): 106 | is_proj, root = get_project_root() 107 | 108 | state = {"dirty": False} 109 | 110 | if not is_proj: 111 | click.echo("Run psync to generate .psync config file.") 112 | else: 113 | click.echo("Start watching {} ...".format(root)) 114 | event_handler = watcher.AnyEventHandler(state) 115 | observer = Observer() 116 | observer.schedule(event_handler, root, recursive=True) 117 | observer.start() 118 | try: 119 | while True: 120 | if state["dirty"]: 121 | click.echo("Detect modification. Perform sync.") 122 | perform_sync() 123 | state["dirty"] = False 124 | time.sleep(1) 125 | except KeyboardInterrupt: 126 | observer.stop() 127 | observer.join() 128 | 129 | 130 | if __name__ == "__main__": 131 | cli() 132 | -------------------------------------------------------------------------------- /tests/test_psync.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | test_psync 6 | ---------------------------------- 7 | 8 | Tests for `psync` module. 9 | """ 10 | 11 | # from click.testing import CliRunner 12 | 13 | from psync import psync 14 | # from psync import cli 15 | 16 | 17 | def test_load_config(tmpdir): 18 | proj_root = tmpdir.mkdir("proj_root") 19 | proj_root.join(".psync").write( 20 | "remote:\n ~/psync\nssh:\n host: psync_remote_server" 21 | "\n username: username" 22 | "\nignores: []") 23 | 24 | conf = psync.load_config(root=str(proj_root)) 25 | assert isinstance(conf, dict) is True 26 | 27 | assert "local" not in conf 28 | assert "remote" in conf 29 | assert "ssh" in conf 30 | 31 | assert isinstance(conf["remote"], str) 32 | assert isinstance(conf["ssh"], dict) 33 | 34 | assert conf["remote"] == "~/psync" 35 | assert conf["ssh"]["host"] == "psync_remote_server" 36 | assert conf["ssh"]["username"] == "username" 37 | assert len(conf["ignores"]) == 0 38 | 39 | 40 | def test_rsync_cmd(): 41 | conf = psync.generate_config(ssh_user="ssh_user", 42 | ssh_host="ssh_host", 43 | remote_path="remote_path") 44 | cmds = psync.rsync_cmds("fake/local/path", conf) 45 | 46 | assert isinstance(cmds, list) 47 | 48 | assert (" ".join(cmds) == 49 | "rsync -e ssh -ruaz --rsync-path mkdir -p {} && rsync {} {}". 50 | format(conf["remote"], "fake/local/path", 51 | psync.ssh_path(conf["ssh"], conf["remote"]))) 52 | 53 | ig_conf = psync.generate_config(ssh_user="ssh_user", 54 | ssh_host="ssh_host", 55 | remote_path="remote_path", 56 | ignores=["folderA", "fileB"]) 57 | 58 | ignores_cmds = psync.rsync_cmds("fake/local/path", ig_conf) 59 | assert "--exclude" in ignores_cmds 60 | assert "folderA" in ignores_cmds 61 | assert "fileB" in ignores_cmds 62 | 63 | 64 | def test_project_root(tmpdir): 65 | expected_root = tmpdir.mkdir("proj_root") 66 | expected_root.join(".psync").write("") 67 | 68 | nested_sub = expected_root.mkdir("sub1").mkdir("subsub") 69 | sub = expected_root.mkdir("sub2") 70 | 71 | none_root = tmpdir.mkdir("no_psync") 72 | 73 | assert psync.project_root(str(expected_root)) == expected_root 74 | assert psync.project_root(str(nested_sub)) == expected_root 75 | assert psync.project_root(str(sub)) == expected_root 76 | 77 | assert psync.project_root(str(none_root)) is None 78 | 79 | 80 | def test_generate_conf(): 81 | conf = psync.generate_config(ssh_user="ssh_user", 82 | ssh_host="ssh_host", 83 | remote_path="remote_path") 84 | 85 | assert conf["ssh"]["host"] == "ssh_host" 86 | assert conf["ssh"]["username"] == "ssh_user" 87 | assert conf["remote"] == "remote_path" 88 | assert len(conf["ignores"]) == 0 89 | 90 | nouser_conf = psync.generate_config(ssh_user=None, 91 | ssh_host="ssh_host", 92 | remote_path="remote_path") 93 | 94 | assert nouser_conf["ssh"]["host"] == "ssh_host" 95 | assert nouser_conf["ssh"]["username"] is None 96 | assert nouser_conf["remote"] == "remote_path" 97 | 98 | ignores_conf = psync.generate_config(ssh_user=None, 99 | ssh_host="ssh_host", 100 | remote_path="remote_path", 101 | ignores=["folderA", "fileB"]) 102 | 103 | assert ignores_conf["ignores"] == ["folderA", "fileB"] 104 | 105 | 106 | def test_ssh_path(): 107 | conf = psync.generate_config(ssh_user="ssh_user", 108 | ssh_host="ssh_host", 109 | remote_path="remote_path") 110 | ssh_path = psync.ssh_path(conf["ssh"], conf["remote"]) 111 | 112 | assert ssh_path == "{}@{}:{}".format( 113 | conf["ssh"]["username"], conf["ssh"]["host"], 114 | conf["remote"]) 115 | 116 | conf["ssh"]["username"] = None 117 | 118 | nouser_ssh_path = psync.ssh_path(conf["ssh"], conf["remote"]) 119 | assert nouser_ssh_path == "{}:{}".format( 120 | conf["ssh"]["host"], conf["remote"]) 121 | 122 | 123 | # def test_command_line_interface(): 124 | # runner = CliRunner() 125 | # result = runner.invoke(cli.main) 126 | # assert result.exit_code == 0 127 | # assert 'psync.cli.main' in result.output 128 | # help_result = runner.invoke(cli.main, ['--help']) 129 | # assert help_result.exit_code == 0 130 | # assert '--help Show this message and exit.' in help_result.output 131 | --------------------------------------------------------------------------------