LiveSync 0.2.1__py3-none-any.whl → 0.3.0__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.
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.1
2
+ Name: LiveSync
3
+ Version: 0.3.0
4
+ Summary: Repeatedly synchronize local workspace with a (slow) remote machine
5
+ Home-page: https://github.com/zauberzeug/livesync
6
+ Author: Zauberzeug GmbH
7
+ Author-email: info@zauberzeug.com
8
+ License: MIT
9
+ Keywords: sync remote watch filesystem development deploy live hot reload
10
+ Requires-Python: >=3.7
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: pathspec
14
+ Requires-Dist: pyjson5
15
+ Requires-Dist: watchfiles
16
+
17
+ # LiveSync
18
+
19
+ Repeatedly synchronize local workspace with a (slow) remote machine.
20
+ It is available as [PyPI package](https://pypi.org/project/livesync/) and hosted on [GitHub](https://github.com/zauberzeug/livesync).
21
+
22
+ [![PyPI version](https://badge.fury.io/py/livesync.svg)](https://pypi.org/project/livesync/)
23
+ [![PyPI - Downloads](https://img.shields.io/pypi/dm/livesync)](https://pypi.org/project/livesync/)
24
+ [![GitHub commit activity](https://img.shields.io/github/commit-activity/m/zauberzeug/livesync)](https://github.com/zauberzeug/livesync/graphs/commit-activity)
25
+ [![GitHub issues](https://img.shields.io/github/issues/zauberzeug/livesync)](https://github.com/zauberzeug/livesync/issues)
26
+ [![GitHub license](https://img.shields.io/github/license/zauberzeug/livesync)](https://github.com/zauberzeug/livesync/blob/main/LICENSE)
27
+
28
+ ## Use Case
29
+
30
+ [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview) and similar tools are great as long as your remote machine is powerful enough.
31
+ But if your target is a Raspberry Pi, Jetson Nano/Xavier/Orin, Beagle Board or similar, it feels like coding in jelly.
32
+ Especially if you run powerful extensions like Pylance.
33
+ LiveSync solves this by watching your code for changes and just copying the modifications to the slow remote machine.
34
+ It works best if you have some kind of reload mechanism in place on the target ([NiceGUI](https://nicegui.io), [FastAPI](https://fastapi.tiangolo.com/) or [Flask](https://flask.palletsprojects.com/) for example).
35
+
36
+ ## Usage
37
+
38
+ ```bash
39
+ livesync <source> <username>@<host>
40
+ ```
41
+
42
+ LiveSync uses rsync (SSH) to copy the files, so the `<username>@<host>` must be accessible via SSH (ideally by key, not password or passphrase, because it will be called over and over).
43
+
44
+ Press `CTRL-C` to abort the synchronization.
45
+
46
+ Positional arguments:
47
+
48
+ - `<source>`
49
+ local folder or VSCode workspace file
50
+ - `<username>@<host>`
51
+ target user and host (e.g. username@hostname)
52
+
53
+ Options:
54
+
55
+ - `--target-root TARGET_ROOT`
56
+ subfolder on target to synchronize to (default: "")
57
+ - `--target-port TARGET_PORT`
58
+ SSH port on target (default: 22)
59
+ - `--on-change ON_CHANGE`
60
+ command to be executed on remote host after any file change (default: None)
61
+ - `--mutex-interval MUTEX_INTERVAL`
62
+ interval in which mutex is updated (default: 10 seconds)
63
+
64
+ ### Notes
65
+
66
+ - We suggest you have some auto-reloading in place on the (slow) target machine, like [NiceGUI](https://nicegui.io).
67
+ - Only one user per target host should run LiveSync at a time. Therefore LiveSync provides a mutex mechanism.
68
+ - You can create a `.syncignore` file in any source directory to skip additional files and directories from syncing.
69
+ - 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
+
72
+ ## Installation
73
+
74
+ ```bash
75
+ python3 -m pip install livesync
76
+ ```
77
+
78
+ ## Development
79
+
80
+ For development we suggest to use the following instructions instead of the normal pip installation:
81
+
82
+ ```bash
83
+ git clone git@github.com:zauberzeug/livesync.git
84
+ cd livesync
85
+ python3 -m pip uninstall livesync # remove previous installed version
86
+ python3 -m pip install -e .
87
+ ```
88
+
89
+ Now you can change the code and call the `livesync` command from your `$PATH` variable with the modified code.
90
+
91
+ ## Testing
92
+
93
+ We have build a small testing infrastructure with two docker containers.
94
+ See [tests/README.md](https://github.com/zauberzeug/livesync/blob/main/tests/README.md) for details.
95
+
96
+ ## Releases
97
+
98
+ Just create and push a new tag with the new version name (v0.2.1 for example).
99
+ After a successful build a new release will be created.
100
+ This should be edited to describe the changes in the release notes.
@@ -0,0 +1,10 @@
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,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.37.1)
2
+ Generator: bdist_wheel (0.41.2)
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
1
+ from .folder import Folder, Target
2
2
  from .mutex import Mutex
livesync/folder.py CHANGED
@@ -1,63 +1,76 @@
1
1
  import asyncio
2
- import os
3
2
  import subprocess
3
+ import sys
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
4
6
  from typing import List, Optional
5
7
 
6
8
  import pathspec
7
9
  import watchfiles
8
10
 
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}"')
30
+
9
31
 
10
32
  class Folder:
11
33
 
12
- def __init__(self, local_dir: str, target_host: str) -> None:
13
- self.local_dir = os.path.abspath(local_dir)
14
- self.target_host = target_host
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
36
+ self.target = target
15
37
 
16
- # https://stackoverflow.com/a/22090594/3419103
17
- self._ignore_spec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, self.get_excludes())
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())
18
41
 
19
42
  self._stop_watching = asyncio.Event()
20
43
 
21
44
  @property
22
- def target_path(self) -> str:
23
- return os.path.basename(os.path.realpath(self.local_dir))
24
-
25
- @property
26
- def ssh_target(self) -> str:
27
- return f'{self.target_host}:{self.target_path}'
45
+ def target_path(self) -> Path:
46
+ return self.target.root / self.local_path.stem
28
47
 
29
48
  @property
30
- def is_valid(self) -> bool:
31
- return os.path.isdir(self.local_dir)
32
-
33
- def get_excludes(self) -> List[str]:
34
- return ['.git/', '__pycache__/', '.DS_Store'] + \
35
- self._parse_ignore_file(f'{self.local_dir}/.syncignore') + \
36
- self._parse_ignore_file(f'{self.local_dir}/.gitignore')
49
+ def ssh_path(self) -> str:
50
+ return f'{self.target.host}:{self.target_path}'
37
51
 
38
- @staticmethod
39
- def _parse_ignore_file(path: str) -> List[str]:
40
- if not os.path.isfile(path):
41
- return []
42
- with open(path) as f:
43
- return [line.strip() for line in f.readlines() if not line.startswith('#')]
52
+ def get_ignores(self) -> List[str]:
53
+ path = self.local_path / '.syncignore'
54
+ if not path.is_file():
55
+ path.write_text('\n'.join(DEFAULT_IGNORES))
56
+ return [line.strip() for line in path.read_text().splitlines() if not line.startswith('#')]
44
57
 
45
58
  def get_summary(self) -> str:
46
- summary = f'{self.local_dir} --> {self.ssh_target}\n'
47
- if not os.path.exists(os.path.join(self.local_dir, '.git')):
59
+ summary = f'{self.local_path} --> {self.ssh_path}\n'
60
+ if not (self.local_path / '.git').exists():
48
61
  return summary
49
62
  try:
50
63
  cmd = ['git', 'log', '--pretty=format:[%h]\n', '-n', '1']
51
- summary += subprocess.check_output(cmd, cwd=self.local_dir).decode()
64
+ summary += subprocess.check_output(cmd, cwd=self.local_path).decode()
52
65
  cmd = ['git', 'status', '--short', '--branch']
53
- summary += subprocess.check_output(cmd, cwd=self.local_dir).decode().strip()
54
- except:
66
+ summary += subprocess.check_output(cmd, cwd=self.local_path).decode().strip() + '\n'
67
+ except Exception:
55
68
  pass # maybe git is not installed
56
69
  return summary
57
70
 
58
71
  async def watch(self, on_change_command: Optional[str]) -> None:
59
72
  try:
60
- async for changes in watchfiles.awatch(self.local_dir, stop_event=self._stop_watching,
73
+ async for changes in watchfiles.awatch(self.local_path, stop_event=self._stop_watching,
61
74
  watch_filter=lambda _, filepath: not self._ignore_spec.match_file(filepath)):
62
75
  for change, filepath in changes:
63
76
  print('?+U-'[change], filepath)
@@ -71,8 +84,9 @@ class Folder:
71
84
 
72
85
  def sync(self, post_sync_command: Optional[str] = None) -> None:
73
86
  args = '--prune-empty-dirs --delete -avz --checksum --no-t'
74
- args += ''.join(f' --exclude="{e}"' for e in self.get_excludes())
75
- command = f'rsync {args} {self.local_dir}/ {self.ssh_target}'
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)
76
91
  if post_sync_command:
77
- command += f'; ssh {self.target_host} "cd {self.target_path}; {post_sync_command}"'
78
- subprocess.run(command, shell=True, stdout=subprocess.DEVNULL)
92
+ run_subprocess(f'ssh {self.target.host} -p {self.target.port} "cd {self.target_path}; {post_sync_command}"')
livesync/livesync.py CHANGED
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env python3
2
2
  import argparse
3
3
  import asyncio
4
- import json
5
4
  import sys
6
- from glob import glob
5
+ from pathlib import Path
7
6
  from typing import List
8
7
 
9
- from livesync import Folder, Mutex
8
+ import pyjson5
9
+
10
+ from livesync import Folder, Mutex, Target
10
11
 
11
12
 
12
13
  def git_summary(folders: List[Folder]) -> str:
@@ -14,36 +15,45 @@ def git_summary(folders: List[Folder]) -> str:
14
15
 
15
16
 
16
17
  async def async_main() -> None:
17
- parser = argparse.ArgumentParser(description='Repeatedly synchronize local workspace with remote machine')
18
+ parser = argparse.ArgumentParser(
19
+ description='Repeatedly synchronize local directories with remote machine',
20
+ 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')
18
24
  parser.add_argument('--on-change', type=str, help='command to be executed on remote host after any file change')
19
- parser.add_argument('--source', type=str, help='source folder on local host instead of vscode workspace file')
20
- parser.add_argument('--mutex-interval', type=int, nargs='?', default=10, help='interval in which mutex is updated')
25
+ parser.add_argument('--mutex-interval', type=int, default=10, help='interval in which mutex is updated')
21
26
  parser.add_argument('host', type=str, help='the target host (e.g. username@hostname)')
22
27
  args = parser.parse_args()
28
+ source = Path(args.source)
29
+ target = Target(host=args.host, port=args.target_port, root=Path(args.target_root))
23
30
 
24
31
  folders: List[Folder] = []
25
- workspaces = glob('*.code-workspace')
26
- if args.source is None and workspaces:
27
- print(f'Reading vscode workspace file {workspaces[0]} ...')
28
- try:
29
- with open(workspaces[0]) as f:
30
- workspace = json.load(f)
31
- folders = [Folder(folder['path'], args.host) for folder in workspace['folders']]
32
- except IndexError:
33
- print('No vscode workspace file found; provide --source parameter or start in dir with *.code-workspace file')
34
- sys.exit(1)
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()]
35
36
  else:
36
- folders = [Folder(args.source or '.', args.host)]
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)
37
43
 
38
44
  print('Checking mutex...')
39
- mutex = Mutex(args.host)
45
+ mutex = Mutex(target)
40
46
  if not mutex.set(git_summary(folders)):
41
47
  print(f'Target is in use by {mutex.occupant}')
42
48
  sys.exit(1)
43
49
 
50
+ if args.target_root:
51
+ print('Creating target root directory...')
52
+ target.make_target_root_directory()
53
+
44
54
  print('Initial sync...')
45
55
  for folder in folders:
46
- print(f' {folder.local_dir} --> {folder.ssh_target}')
56
+ print(f' {folder.local_path} --> {folder.ssh_path}')
47
57
  folder.sync(post_sync_command=args.on_change)
48
58
 
49
59
  print('Watching for file changes...')
livesync/mutex.py CHANGED
@@ -2,28 +2,30 @@ import logging
2
2
  import socket
3
3
  import subprocess
4
4
  from datetime import datetime, timedelta
5
+ from typing import Optional
6
+
7
+ from .folder import Target
5
8
 
6
9
  MUTEX_FILEPATH = '~/.livesync_mutex'
7
10
 
8
11
 
9
12
  class Mutex:
10
13
 
11
- def __init__(self, host: str) -> None:
12
- self.host = host
13
- self.occupant: str = None
14
+ def __init__(self, target: Target) -> None:
15
+ self.target = target
16
+ self.occupant: Optional[str] = None
14
17
  self.user_id = socket.gethostname()
15
18
 
16
19
  def is_free(self, info: str) -> bool:
17
20
  try:
18
- command = ['ssh', self.host, f'cat {MUTEX_FILEPATH} || echo "{self.tag}\n{info}"']
19
- output = subprocess.check_output(command, stderr=subprocess.DEVNULL).decode().splitlines()[0]
21
+ output = self._run_ssh_command(f'cat {MUTEX_FILEPATH} || echo "{self.tag}\n{info}"').splitlines()[0]
20
22
  words = output.strip().split()
21
23
  self.occupant = words[0]
22
24
  occupant_ok = self.occupant == self.user_id
23
25
  mutex_datetime = datetime.fromisoformat(words[1])
24
26
  mutex_expired = datetime.now() - mutex_datetime > timedelta(seconds=15)
25
27
  return occupant_ok or mutex_expired
26
- except:
28
+ except Exception:
27
29
  logging.exception('Could not access target system')
28
30
  return False
29
31
 
@@ -31,8 +33,7 @@ class Mutex:
31
33
  if not self.is_free(info):
32
34
  return False
33
35
  try:
34
- command = ['ssh', self.host, f'echo "{self.tag}\n{info}" > {MUTEX_FILEPATH}']
35
- subprocess.check_output(command, stderr=subprocess.DEVNULL)
36
+ self._run_ssh_command(f'echo "{self.tag}\n{info}" > {MUTEX_FILEPATH}')
36
37
  return True
37
38
  except subprocess.CalledProcessError:
38
39
  print('Could not write mutex file')
@@ -41,3 +42,7 @@ class Mutex:
41
42
  @property
42
43
  def tag(self) -> str:
43
44
  return f'{self.user_id} {datetime.now().isoformat()}'
45
+
46
+ def _run_ssh_command(self, command: str) -> str:
47
+ ssh_command = ['ssh', self.target.host, '-p', str(self.target.port), command]
48
+ return subprocess.check_output(ssh_command, stderr=subprocess.DEVNULL).decode()
@@ -1,67 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: LiveSync
3
- Version: 0.2.1
4
- Summary: Repeatedly synchronize local workspace with a (slow) remote machine
5
- Home-page: https://github.com/zauberzeug/livesync
6
- Author: Zauberzeug GmbH
7
- Author-email: info@zauberzeug.com
8
- License: MIT
9
- Keywords: sync remote watch filesystem development deploy live hot reload
10
- Requires-Python: >=3.7
11
- Description-Content-Type: text/markdown
12
- License-File: LICENSE
13
- Requires-Dist: watchfiles
14
- Requires-Dist: pathspec
15
-
16
- # LiveSync
17
-
18
- Repeatedly synchronize local workspace with a (slow) remote machine.
19
-
20
- ## Use Case
21
-
22
- [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview) and similar tools are great as long as your remote machine is powerful enough.
23
- But if your target is a Raspberry Pi, Jetson Nano/Xavier/Orin, Beagle Board or similar, it feels like coding in yelly.
24
- Especially if you run powerful extensions like Pylance.
25
- LiveSync solves this by watching your code and just copying the changed files to the slow remote machine.
26
- It works best if you have some kind of reloading mechanism in place on the target.
27
- We obviously recommend [NiceGUI](https://nicegui.io).
28
-
29
- ## Install
30
-
31
- ```bash
32
- python3 -m pip install livesync
33
- ```
34
-
35
- ## Usage
36
-
37
- ```bash
38
- cd <my_folder_with_vscode_workspace>
39
- livesync <username>@<host>
40
- ```
41
-
42
- LiveSync uses rsync (SSH) to copy the files, so the `<username>@<host>` must be accessible via SSH (ideally by key, not password or passphrase, because it will be called over and over).
43
-
44
- Press `CTRL-C` to abort the synchronization.
45
-
46
- ### Notes
47
-
48
- - We suggest you have some auto-reloading in place on the (slow) target machine, like [NiceGUI](https://nicegui.io).
49
- - Only one user per target host can run LiveSync at a time.
50
- - By default `.git/` folders are not synchronized.
51
- - All files and directories from the `.gitignore` of any source directory are also excluded from synchronization.
52
- - You can create a `.syncignore` file in any source directory to skip additional files and directories from syncing.
53
-
54
- ## Development
55
-
56
- ```bash
57
- git clone git@github.com:zauberzeug/livesync.git
58
- cd livesync
59
- python3 -m pip uninstall livesync # remove previous installed version
60
- python3 -m pip install -e .
61
- ```
62
-
63
- Now you can change the code and still use the `livesync` command from your `$PATH` variable.
64
-
65
- ## Releases
66
-
67
- Just create and push a new tag with the new version name.
@@ -1,10 +0,0 @@
1
- livesync/__init__.py,sha256=8EPS0Mjy54QwW5ak8L8uv13ZCub0-WCYa1KB0UqilGI,52
2
- livesync/folder.py,sha256=qJv3oEOfZUANle1GAFpiYWOZAIBPIp_DgV0C9kflI7Y,3010
3
- livesync/livesync.py,sha256=SNUuijoFRFBJfmUyAK3nQxExFTbL87JbLwJlhQT9eU0,2264
4
- livesync/mutex.py,sha256=venXO1Nnj8msN185e2QqhCpc_saNY-lQFNeSlZNMiPE,1500
5
- LiveSync-0.2.1.dist-info/LICENSE,sha256=QcBlwggRQYhvfTAE481AAMFQfMS_N6Bj8Svh1T6dsnI,1072
6
- LiveSync-0.2.1.dist-info/METADATA,sha256=8RyxXLrHYssPDWd_jF-IgOOX-0akFPPYmEhWiya7dTo,2342
7
- LiveSync-0.2.1.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
8
- LiveSync-0.2.1.dist-info/entry_points.txt,sha256=4dn5YR27lUlJWea3yqLKLqR4MwqjcqzMR5Q4jVFnytI,52
9
- LiveSync-0.2.1.dist-info/top_level.txt,sha256=mLwExc6wTUGqxvUkYMio5rxGS1h8bvxpNsR2ebfjSL4,9
10
- LiveSync-0.2.1.dist-info/RECORD,,