LiveSync 0.3.0__py3-none-any.whl → 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: LiveSync
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: Repeatedly synchronize local workspace with a (slow) remote machine
5
5
  Home-page: https://github.com/zauberzeug/livesync
6
6
  Author: Zauberzeug GmbH
@@ -11,7 +11,6 @@ Requires-Python: >=3.7
11
11
  Description-Content-Type: text/markdown
12
12
  License-File: LICENSE
13
13
  Requires-Dist: pathspec
14
- Requires-Dist: pyjson5
15
14
  Requires-Dist: watchfiles
16
15
 
17
16
  # LiveSync
@@ -35,6 +34,8 @@ It works best if you have some kind of reload mechanism in place on the target (
35
34
 
36
35
  ## Usage
37
36
 
37
+ ### BASH
38
+
38
39
  ```bash
39
40
  livesync <source> <username>@<host>
40
41
  ```
@@ -46,28 +47,52 @@ Press `CTRL-C` to abort the synchronization.
46
47
  Positional arguments:
47
48
 
48
49
  - `<source>`
49
- local folder or VSCode workspace file
50
- - `<username>@<host>`
51
- target user and host (e.g. username@hostname)
50
+ local folder
51
+ - `<target>`
52
+ target user, host and path (e.g. user@host:~/path; path defaults to source folder name in home directory)
53
+ - `<rsync_args>`
54
+ arbitrary rsync parameters after "--"
52
55
 
53
56
  Options:
54
57
 
55
- - `--target-root TARGET_ROOT`
56
- subfolder on target to synchronize to (default: "")
57
- - `--target-port TARGET_PORT`
58
+ - `--ssh-port SSH_PORT`
58
59
  SSH port on target (default: 22)
59
60
  - `--on-change ON_CHANGE`
60
61
  command to be executed on remote host after any file change (default: None)
61
62
  - `--mutex-interval MUTEX_INTERVAL`
62
63
  interval in which mutex is updated (default: 10 seconds)
63
64
 
65
+ ### Python
66
+
67
+ Simple example:
68
+
69
+ ```py
70
+ from livesync import Folder, sync
71
+
72
+ sync(
73
+ Folder('.', 'robot:~/navigation'),
74
+ Folder('../rosys', 'robot:~/rosys'),
75
+ )
76
+ ```
77
+
78
+ Advanced example:
79
+
80
+ ```py
81
+ from livesync import Folder, sync
82
+
83
+ sync(
84
+ Folder('.', 'robot:~/navigation', on_change='touch ~/navigation/main.py'),
85
+ Folder('../rosys', 'robot:~/rosys', ssh_port=2222).rsync_args(add='-L', remove='--checksum'),
86
+ mutex_interval=30,
87
+ )
88
+ ```
89
+
64
90
  ### Notes
65
91
 
66
92
  - We suggest you have some auto-reloading in place on the (slow) target machine, like [NiceGUI](https://nicegui.io).
67
93
  - Only one user per target host should run LiveSync at a time. Therefore LiveSync provides a mutex mechanism.
68
94
  - You can create a `.syncignore` file in any source directory to skip additional files and directories from syncing.
69
95
  - If a `.syncignore` file doesn't exist, it is automatically created containing `.git/`, `__pycache__/`, `.DS_Store`, `*.tmp`, and `.env`.
70
- - If you pass a VSCode workspace file as `source`, LiveSync will synchronize each directory listed in the `folders` section.
71
96
 
72
97
  ## Installation
73
98
 
@@ -0,0 +1,12 @@
1
+ livesync/__init__.py,sha256=tZrvnAIpVuo9cQHMCvi6l2vup66NXPxRwyR5UBNtCTs,50
2
+ livesync/folder.py,sha256=09blUNJI-VFPg7FXEgEHXMKffmFf82swNOLvSEgnS7o,4069
3
+ livesync/livesync.py,sha256=gOFq8_mxAGEt3pXt_5EtlpFqLwE5sZwfbRsHiUh-F6k,1159
4
+ livesync/mutex.py,sha256=nHaP0Tge3ZV7jyVBbYsMug5L5YkuJf8_XIbfAdVJkPc,1741
5
+ livesync/run_subprocess.py,sha256=ZZqK9dlOVlJhL0xkKN7bG-BAT558nHk-IJNGqIMeWyM,368
6
+ livesync/sync.py,sha256=r0CWptPcIvYs6uv9iV_JM7My360dSHMeFYAISntpQTA,1446
7
+ LiveSync-0.3.1.dist-info/LICENSE,sha256=QcBlwggRQYhvfTAE481AAMFQfMS_N6Bj8Svh1T6dsnI,1072
8
+ LiveSync-0.3.1.dist-info/METADATA,sha256=kDBdMh9Jd3VQyhCCein4Dij5fBABstkS0ixEfOB3PeM,4576
9
+ LiveSync-0.3.1.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
10
+ LiveSync-0.3.1.dist-info/entry_points.txt,sha256=4dn5YR27lUlJWea3yqLKLqR4MwqjcqzMR5Q4jVFnytI,52
11
+ LiveSync-0.3.1.dist-info/top_level.txt,sha256=mLwExc6wTUGqxvUkYMio5rxGS1h8bvxpNsR2ebfjSL4,9
12
+ LiveSync-0.3.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.41.2)
2
+ Generator: bdist_wheel (0.42.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
livesync/__init__.py CHANGED
@@ -1,2 +1,2 @@
1
- from .folder import Folder, Target
2
- from .mutex import Mutex
1
+ from .folder import Folder
2
+ from .sync import sync
livesync/folder.py CHANGED
@@ -1,92 +1,93 @@
1
+ from __future__ import annotations
2
+
1
3
  import asyncio
2
4
  import subprocess
3
5
  import sys
4
- from dataclasses import dataclass
5
6
  from pathlib import Path
6
- from typing import List, Optional
7
+ from typing import Callable, List, Optional, Union
7
8
 
8
9
  import pathspec
9
10
  import watchfiles
10
11
 
11
- KWONLY_SLOTS = {'kw_only': True, 'slots': True} if sys.version_info >= (3, 10) else {}
12
- DEFAULT_IGNORES = ['.git/', '__pycache__/', '.DS_Store', '*.tmp', '.env']
13
-
14
-
15
- def run_subprocess(command: str, *, quiet: bool = False) -> None:
16
- result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True)
17
- if not quiet:
18
- print(result.stdout.decode())
19
-
20
-
21
- @dataclass(**KWONLY_SLOTS)
22
- class Target:
23
- host: str
24
- port: int
25
- root: Path
26
-
27
- def make_target_root_directory(self) -> None:
28
- print(f'make target root directory {self.root}')
29
- run_subprocess(f'ssh {self.host} -p {self.port} "mkdir -p {self.root}"')
12
+ from .run_subprocess import run_subprocess
30
13
 
31
14
 
32
15
  class Folder:
33
-
34
- def __init__(self, local_dir: Path, target: Target) -> None:
35
- self.local_path = local_dir.resolve() # one should avoid `absolute` if Python < 3.11
16
+ DEFAULT_IGNORES = ['.git/', '__pycache__/', '.DS_Store', '*.tmp', '.env']
17
+ DEFAULT_RSYNC_ARGS = ['--prune-empty-dirs', '--delete', '-a', '-v', '-z', '--checksum', '--no-t']
18
+
19
+ def __init__(self,
20
+ source_path: Union[str, Path],
21
+ target: str, *,
22
+ ssh_port: int = 22,
23
+ on_change: Optional[Union[str, Callable]] = None,
24
+ ) -> None:
25
+ self.source_path = Path(source_path).resolve() # one should avoid `absolute` if Python < 3.11
26
+ if ':' not in target:
27
+ target = f'{target}:{self.source_path.name}'
36
28
  self.target = target
37
-
38
- # from https://stackoverflow.com/a/22090594/3419103
39
- match_pattern = pathspec.patterns.gitwildmatch.GitWildMatchPattern
40
- self._ignore_spec = pathspec.PathSpec.from_lines(match_pattern, self.get_ignores())
41
-
29
+ self.host, self.target_path = target.split(':')
30
+ self.ssh_port = ssh_port
31
+ self.on_change = on_change or None
32
+ self._rsync_args: List[str] = self.DEFAULT_RSYNC_ARGS[:]
42
33
  self._stop_watching = asyncio.Event()
43
34
 
44
- @property
45
- def target_path(self) -> Path:
46
- return self.target.root / self.local_path.stem
47
-
48
- @property
49
- def ssh_path(self) -> str:
50
- return f'{self.target.host}:{self.target_path}'
51
-
52
- def get_ignores(self) -> List[str]:
53
- path = self.local_path / '.syncignore'
35
+ if not self.source_path.is_dir():
36
+ print(f'Invalid path: {self.source_path}')
37
+ sys.exit(1)
38
+
39
+ match_pattern = pathspec.patterns.gitwildmatch.GitWildMatchPattern # https://stackoverflow.com/a/22090594/3419103
40
+ self._ignore_spec = pathspec.PathSpec.from_lines(match_pattern, self._get_ignores())
41
+
42
+ def rsync_args(self,
43
+ add: Optional[str] = None,
44
+ remove: Optional[str] = None,
45
+ replace: Optional[str] = None) -> Folder:
46
+ if replace is not None:
47
+ self._rsync_args.clear()
48
+ add_args = (add or '').split() + (replace or '').split()
49
+ remove_args = remove.split() if remove else []
50
+ self._rsync_args += [arg for arg in add_args if arg not in self._rsync_args]
51
+ self._rsync_args = [arg for arg in self._rsync_args if arg not in remove_args]
52
+ return self
53
+
54
+ def _get_ignores(self) -> List[str]:
55
+ path = self.source_path / '.syncignore'
54
56
  if not path.is_file():
55
- path.write_text('\n'.join(DEFAULT_IGNORES))
57
+ path.write_text('\n'.join(self.DEFAULT_IGNORES))
56
58
  return [line.strip() for line in path.read_text().splitlines() if not line.startswith('#')]
57
59
 
58
60
  def get_summary(self) -> str:
59
- summary = f'{self.local_path} --> {self.ssh_path}\n'
60
- if not (self.local_path / '.git').exists():
61
+ summary = f'{self.source_path} --> {self.target}\n'
62
+ if not (self.source_path / '.git').exists():
61
63
  return summary
62
64
  try:
63
65
  cmd = ['git', 'log', '--pretty=format:[%h]\n', '-n', '1']
64
- summary += subprocess.check_output(cmd, cwd=self.local_path).decode()
66
+ summary += subprocess.check_output(cmd, cwd=self.source_path).decode()
65
67
  cmd = ['git', 'status', '--short', '--branch']
66
- summary += subprocess.check_output(cmd, cwd=self.local_path).decode().strip() + '\n'
68
+ summary += subprocess.check_output(cmd, cwd=self.source_path).decode().strip() + '\n'
67
69
  except Exception:
68
70
  pass # maybe git is not installed
69
71
  return summary
70
72
 
71
- async def watch(self, on_change_command: Optional[str]) -> None:
73
+ async def watch(self) -> None:
72
74
  try:
73
- async for changes in watchfiles.awatch(self.local_path, stop_event=self._stop_watching,
75
+ async for changes in watchfiles.awatch(self.source_path, stop_event=self._stop_watching,
74
76
  watch_filter=lambda _, filepath: not self._ignore_spec.match_file(filepath)):
75
77
  for change, filepath in changes:
76
78
  print('?+U-'[change], filepath)
77
- self.sync(on_change_command)
79
+ self.sync()
78
80
  except RuntimeError as e:
79
81
  if 'Already borrowed' not in str(e):
80
82
  raise
81
83
 
82
- def stop_watching(self) -> None:
83
- self._stop_watching.set()
84
-
85
- def sync(self, post_sync_command: Optional[str] = None) -> None:
86
- args = '--prune-empty-dirs --delete -avz --checksum --no-t'
87
- # args += ' --mkdirs' # INFO: this option is not available in rsync < 3.2.3
88
- args += ''.join(f' --exclude="{e}"' for e in self.get_ignores())
89
- args += f' -e "ssh -p {self.target.port}"'
90
- run_subprocess(f'rsync {args} {self.local_path}/ {self.ssh_path}/', quiet=True)
91
- if post_sync_command:
92
- run_subprocess(f'ssh {self.target.host} -p {self.target.port} "cd {self.target_path}; {post_sync_command}"')
84
+ def sync(self) -> None:
85
+ args = ' '.join(self._rsync_args)
86
+ args += ''.join(f' --exclude="{e}"' for e in self._get_ignores())
87
+ args += f' -e "ssh -p {self.ssh_port}"' # NOTE: use SSH with custom port
88
+ args += f' --rsync-path="mkdir -p {self.target_path} && rsync"' # NOTE: create target folder if not exists
89
+ run_subprocess(f'rsync {args} {self.source_path}/ {self.target}/', quiet=True)
90
+ if isinstance(self.on_change, str):
91
+ run_subprocess(f'ssh {self.host} -p {self.ssh_port} "cd {self.target_path}; {self.on_change}"')
92
+ if callable(self.on_change):
93
+ self.on_change()
livesync/livesync.py CHANGED
@@ -1,74 +1,24 @@
1
1
  #!/usr/bin/env python3
2
2
  import argparse
3
- import asyncio
4
- import sys
5
- from pathlib import Path
6
- from typing import List
7
3
 
8
- import pyjson5
4
+ from livesync import Folder, sync
9
5
 
10
- from livesync import Folder, Mutex, Target
11
6
 
12
-
13
- def git_summary(folders: List[Folder]) -> str:
14
- return '\n'.join(f.get_summary() for f in folders).replace('"', '\'')
15
-
16
-
17
- async def async_main() -> None:
7
+ def main():
18
8
  parser = argparse.ArgumentParser(
19
- description='Repeatedly synchronize local directories with remote machine',
9
+ description='Repeatedly synchronize a local directory with a remote machine',
20
10
  formatter_class=argparse.ArgumentDefaultsHelpFormatter)
21
- parser.add_argument('source', type=str, help='local source folder or VSCode workspace file')
22
- parser.add_argument('--target-root', type=str, default='', help='subfolder on target to synchronize to')
23
- parser.add_argument('--target-port', type=int, default=22, help='SSH port on target')
11
+ parser.add_argument('source', type=str, default='.', help='local source folder')
12
+ parser.add_argument('target', type=str, help='target path (e.g. username@hostname:/path/to/target)')
13
+ parser.add_argument('--ssh-port', type=int, default=22, help='SSH port on target')
24
14
  parser.add_argument('--on-change', type=str, help='command to be executed on remote host after any file change')
25
15
  parser.add_argument('--mutex-interval', type=int, default=10, help='interval in which mutex is updated')
26
- parser.add_argument('host', type=str, help='the target host (e.g. username@hostname)')
16
+ parser.add_argument('rsync_args', nargs=argparse.REMAINDER, help='arbitrary rsync parameters after "--"')
27
17
  args = parser.parse_args()
28
- source = Path(args.source)
29
- target = Target(host=args.host, port=args.target_port, root=Path(args.target_root))
30
-
31
- folders: List[Folder] = []
32
- if source.is_file():
33
- workspace = pyjson5.decode(source.read_text())
34
- paths = [Path(f['path']) for f in workspace['folders']]
35
- folders = [Folder(p, target) for p in paths if p.is_dir()]
36
- else:
37
- folders = [Folder(source, target)]
38
-
39
- for folder in folders:
40
- if not folder.local_path.is_dir():
41
- print(f'Invalid path: {folder.local_path}')
42
- sys.exit(1)
43
-
44
- print('Checking mutex...')
45
- mutex = Mutex(target)
46
- if not mutex.set(git_summary(folders)):
47
- print(f'Target is in use by {mutex.occupant}')
48
- sys.exit(1)
49
18
 
50
- if args.target_root:
51
- print('Creating target root directory...')
52
- target.make_target_root_directory()
53
-
54
- print('Initial sync...')
55
- for folder in folders:
56
- print(f' {folder.local_path} --> {folder.ssh_path}')
57
- folder.sync(post_sync_command=args.on_change)
58
-
59
- print('Watching for file changes...')
60
- for folder in folders:
61
- asyncio.create_task(folder.watch(on_change_command=args.on_change))
62
-
63
- while mutex.set(git_summary(folders)):
64
- await asyncio.sleep(args.mutex_interval)
65
-
66
-
67
- def main():
68
- try:
69
- asyncio.run(async_main())
70
- except KeyboardInterrupt:
71
- print('Bye!')
19
+ folder = Folder(args.source, args.target, ssh_port=args.ssh_port, on_change=args.on_change)
20
+ folder.rsync_args(' '.join(args.rsync_args))
21
+ sync(folder, mutex_interval=args.mutex_interval)
72
22
 
73
23
 
74
24
  if __name__ == '__main__':
livesync/mutex.py CHANGED
@@ -4,22 +4,23 @@ import subprocess
4
4
  from datetime import datetime, timedelta
5
5
  from typing import Optional
6
6
 
7
- from .folder import Target
8
-
9
- MUTEX_FILEPATH = '~/.livesync_mutex'
10
-
11
7
 
12
8
  class Mutex:
9
+ DEFAULT_FILEPATH = '~/.livesync_mutex'
13
10
 
14
- def __init__(self, target: Target) -> None:
15
- self.target = target
11
+ def __init__(self, host: str, port: int) -> None:
12
+ self.host = host
13
+ self.port = port
16
14
  self.occupant: Optional[str] = None
17
15
  self.user_id = socket.gethostname()
18
16
 
19
- def is_free(self, info: str) -> bool:
17
+ def is_free(self) -> bool:
20
18
  try:
21
- output = self._run_ssh_command(f'cat {MUTEX_FILEPATH} || echo "{self.tag}\n{info}"').splitlines()[0]
22
- words = output.strip().split()
19
+ command = f'[ -f {self.DEFAULT_FILEPATH} ] && cat {self.DEFAULT_FILEPATH} || echo'
20
+ output = self._run_ssh_command(command).strip()
21
+ if not output:
22
+ return True
23
+ words = output.splitlines()[0].strip().split()
23
24
  self.occupant = words[0]
24
25
  occupant_ok = self.occupant == self.user_id
25
26
  mutex_datetime = datetime.fromisoformat(words[1])
@@ -30,10 +31,10 @@ class Mutex:
30
31
  return False
31
32
 
32
33
  def set(self, info: str) -> bool:
33
- if not self.is_free(info):
34
+ if not self.is_free():
34
35
  return False
35
36
  try:
36
- self._run_ssh_command(f'echo "{self.tag}\n{info}" > {MUTEX_FILEPATH}')
37
+ self._run_ssh_command(f'echo "{self.tag}\n{info}" > {self.DEFAULT_FILEPATH}')
37
38
  return True
38
39
  except subprocess.CalledProcessError:
39
40
  print('Could not write mutex file')
@@ -44,5 +45,5 @@ class Mutex:
44
45
  return f'{self.user_id} {datetime.now().isoformat()}'
45
46
 
46
47
  def _run_ssh_command(self, command: str) -> str:
47
- ssh_command = ['ssh', self.target.host, '-p', str(self.target.port), command]
48
+ ssh_command = ['ssh', self.host, '-p', str(self.port), command]
48
49
  return subprocess.check_output(ssh_command, stderr=subprocess.DEVNULL).decode()
@@ -0,0 +1,11 @@
1
+ import subprocess
2
+
3
+
4
+ def run_subprocess(command: str, *, quiet: bool = False) -> None:
5
+ try:
6
+ result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True)
7
+ if not quiet:
8
+ print(result.stdout.decode())
9
+ except subprocess.CalledProcessError as e:
10
+ print(e.stdout.decode())
11
+ raise
livesync/sync.py ADDED
@@ -0,0 +1,45 @@
1
+ import asyncio
2
+ import sys
3
+ from typing import Iterable
4
+
5
+ from .folder import Folder
6
+ from .mutex import Mutex
7
+
8
+
9
+ def get_summary(folders: Iterable[Folder]) -> str:
10
+ return '\n'.join(folder.get_summary() for folder in folders).replace('"', '\'')
11
+
12
+
13
+ async def run_folder_tasks(folders: Iterable[Folder], mutex_interval: float) -> None:
14
+ try:
15
+ summary = get_summary(folders)
16
+ mutexes = {folder.host: Mutex(folder.host, folder.ssh_port) for folder in folders}
17
+ for mutex in mutexes.values():
18
+ print(f'Checking mutex on {mutex.host}', flush=True)
19
+ if not mutex.set(summary):
20
+ print(f'Target is in use by {mutex.occupant}')
21
+ sys.exit(1)
22
+
23
+ for folder in folders:
24
+ print(f' {folder.source_path} --> {folder.target}', flush=True)
25
+ folder.sync()
26
+
27
+ for folder in folders:
28
+ print(f'Watch folder {folder.source_path}', flush=True)
29
+ asyncio.create_task(folder.watch())
30
+
31
+ while True:
32
+ summary = get_summary(folders)
33
+ for mutex in mutexes.values():
34
+ if not mutex.set(summary):
35
+ break
36
+ await asyncio.sleep(mutex_interval)
37
+ except Exception as e:
38
+ print(e)
39
+
40
+
41
+ def sync(*folders: Folder, mutex_interval: float = 10) -> None:
42
+ try:
43
+ asyncio.run(run_folder_tasks(folders, mutex_interval))
44
+ except KeyboardInterrupt:
45
+ print('Bye!')
@@ -1,10 +0,0 @@
1
- livesync/__init__.py,sha256=V9nt0JRzIeiiLDVNDMZ20SqLMSqFh8uPViPsp2WYK6g,60
2
- livesync/folder.py,sha256=NhorutBdi6_0bhLCPjrVi8TIPZ3TPDQxJRQ0L0-3kRU,3619
3
- livesync/livesync.py,sha256=PKaw-WD4WOZb-X2n4ihj0C8jEOff4s5dopOGiOM3xI4,2586
4
- livesync/mutex.py,sha256=C3Az3Exfgj1ohKnhWl77TDvuJlv3q2qieSgtJF__Wdc,1646
5
- LiveSync-0.3.0.dist-info/LICENSE,sha256=QcBlwggRQYhvfTAE481AAMFQfMS_N6Bj8Svh1T6dsnI,1072
6
- LiveSync-0.3.0.dist-info/METADATA,sha256=pjVKS1x7LaYr_emVuhAwMUIQyK-WKxJYzPUhnVMs9fc,4285
7
- LiveSync-0.3.0.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
8
- LiveSync-0.3.0.dist-info/entry_points.txt,sha256=4dn5YR27lUlJWea3yqLKLqR4MwqjcqzMR5Q4jVFnytI,52
9
- LiveSync-0.3.0.dist-info/top_level.txt,sha256=mLwExc6wTUGqxvUkYMio5rxGS1h8bvxpNsR2ebfjSL4,9
10
- LiveSync-0.3.0.dist-info/RECORD,,