itcpr 3.0.1__tar.gz → 3.0.2__tar.gz

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.5
2
2
  Name: itcpr
3
- Version: 3.0.1
3
+ Version: 3.0.2
4
4
  Summary: ITCPR Sync: keeps your ITCPR research folder on Alpha in sync with this computer.
5
5
  Project-URL: Homepage, https://itcpr.org
6
6
  Author: ITCPR
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "itcpr"
7
- version = "3.0.1"
7
+ version = "3.0.2"
8
8
  description = "ITCPR Sync: keeps your ITCPR research folder on Alpha in sync with this computer."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,3 +1,3 @@
1
1
  """ITCPR Sync: keeps a member's research folder on Alpha in sync with their own computer."""
2
- __version__ = '3.0.1'
2
+ __version__ = '3.0.2'
3
3
  APP_NAME = 'ITCPR Sync'
@@ -39,6 +39,7 @@ def main() -> None:
39
39
  commands.add_parser('status', help='what ITCPR Sync is doing')
40
40
  commands.add_parser('open', help='open the synced folder')
41
41
  commands.add_parser('start', help='start syncing, after choosing folders (exclude) and the place (folder)')
42
+ commands.add_parser('update', help='install the newest version from PyPI')
42
43
  commands.add_parser('pause', help='pause syncing')
43
44
  commands.add_parser('resume', help='resume syncing')
44
45
  exclude = commands.add_parser('exclude', help="stop syncing a folder to this computer (it stays on Alpha)")
@@ -92,6 +93,22 @@ def main() -> None:
92
93
  settings.started = True
93
94
  settings.save()
94
95
  print(f'Syncing to {settings.root}.')
96
+ elif args.command == 'update':
97
+ from . import updates
98
+ from .service import running
99
+ how = updates.plan()
100
+ if how is None:
101
+ print('This is a development copy: update it with git.')
102
+ return
103
+ newest = updates.latest()
104
+ if not updates.newer(newest):
105
+ print(f'ITCPR Sync {__version__} is up to date.')
106
+ return
107
+ if running():
108
+ print(f'Version {newest} is available. Quit ITCPR Sync first, or use Update in its Settings.')
109
+ sys.exit(1)
110
+ print(f'Updating to {newest}...')
111
+ sys.exit(subprocess.run(how['upgrade']).returncode)
95
112
  elif args.command in ('pause', 'resume'):
96
113
  settings = Settings.load()
97
114
  settings.paused = args.command == 'pause'
@@ -19,7 +19,7 @@ from PySide6.QtWidgets import (QApplication, QCheckBox, QFileDialog, QFrame, QHB
19
19
  QSystemTrayIcon, QTabWidget, QTreeWidget, QTreeWidgetItem,
20
20
  QVBoxLayout, QWidget)
21
21
 
22
- from . import APP_NAME, __version__, auth, autostart
22
+ from . import APP_NAME, __version__, auth, autostart, updates
23
23
  from .cli import open_folder, size
24
24
  from .service import Service, SingleInstance, setup_logging
25
25
  from .settings import Settings, app_dir
@@ -158,6 +158,7 @@ class Bridge(QObject):
158
158
  signed_in = Signal(str)
159
159
  versions = Signal(object)
160
160
  restored = Signal(str, bool)
161
+ update_checked = Signal()
161
162
 
162
163
 
163
164
  class Hero(QWidget):
@@ -553,6 +554,18 @@ class Window(QWidget):
553
554
  held.addStretch()
554
555
  box.addWidget(self.held)
555
556
 
557
+ self.update_bar = card()
558
+ bar = QHBoxLayout(self.update_bar)
559
+ bar.setContentsMargins(12, 6, 6, 6)
560
+ self.update_bar_text = label()
561
+ bar.addWidget(self.update_bar_text, 1)
562
+ self.update_bar_button = button('Update', 'primary')
563
+ self.update_bar_button.clicked.connect(self.app.install_update)
564
+ bar.addWidget(self.update_bar_button)
565
+ self.update_bar.setVisible(False)
566
+ box.addSpacing(4)
567
+ box.addWidget(self.update_bar)
568
+
556
569
  self.tabs = QTabWidget()
557
570
  self.tabs.setDocumentMode(True)
558
571
  self.tabs.tabBar().setDrawBase(False)
@@ -914,17 +927,41 @@ class Window(QWidget):
914
927
  lines.addWidget(row(QLabel('Pause syncing'), None, self.pause))
915
928
  box.addWidget(syncing)
916
929
 
917
- box.addStretch()
918
- about = QHBoxLayout()
919
- about.addWidget(label(f'{APP_NAME} {__version__}', faint=True))
920
- about.addStretch()
930
+ box.addSpacing(8)
931
+ box.addWidget(section('Updates'))
932
+ about = card()
933
+ lines = QVBoxLayout(about)
934
+ lines.setContentsMargins(0, 0, 0, 0)
935
+ self.update_title = Elided(f'{APP_NAME} {__version__}', mode=Qt.ElideRight)
936
+ self.update_detail = Elided(mode=Qt.ElideRight, muted=True)
937
+ self.update_check = button('Check now')
938
+ self.update_check.clicked.connect(self.app.check_updates)
939
+ self.update_button = button('Update', 'primary')
940
+ self.update_button.clicked.connect(self.app.install_update)
921
941
  logs = button('Logs', 'ghost')
922
942
  logs.clicked.connect(lambda: open_folder(str(app_dir())))
923
- about.addWidget(logs)
924
- box.addLayout(about)
943
+ lines.addWidget(row(self.update_title, self.update_detail, logs, self.update_check, self.update_button))
944
+ box.addWidget(about)
945
+ box.addStretch()
925
946
  scroll.setWidget(page)
926
947
  return scroll
927
948
 
949
+ def refresh_updates(self, info: dict) -> None:
950
+ state, newest = info.get('state'), info.get('latest')
951
+ details = {'checking': 'Checking for updates…', 'current': 'Up to date', 'available': f'Version {newest} is available',
952
+ 'failed': info.get('error') or "Couldn't check for updates", 'dev': 'Development copy: updates come from git',
953
+ 'updating': 'Updating… ITCPR Sync restarts by itself'}
954
+ self.update_detail.setText(details.get(state, ''))
955
+ self.update_detail.setProperty('tone', 'good' if state == 'available' else None)
956
+ repolish(self.update_detail)
957
+ self.update_button.setVisible(state in ('available', 'updating'))
958
+ self.update_button.setEnabled(state == 'available')
959
+ self.update_button.setText('Updating…' if state == 'updating' else f'Update to {newest}' if newest else 'Update')
960
+ self.update_check.setVisible(state in ('current', 'failed'))
961
+ self.update_bar.setVisible(state in ('available', 'updating'))
962
+ self.update_bar_text.setText(f'ITCPR Sync {newest} is available' if state == 'available' else 'Updating… ITCPR Sync restarts by itself')
963
+ self.update_bar_button.setEnabled(state == 'available')
964
+
928
965
  def set_autostart(self, on: bool) -> None:
929
966
  settings = Settings.load()
930
967
  if settings.autostart != on:
@@ -1048,6 +1085,13 @@ class TrayApp:
1048
1085
  self.ticker = QTimer()
1049
1086
  self.ticker.timeout.connect(self.refresh)
1050
1087
  self.ticker.start(30_000)
1088
+ self.update_info = {'state': 'checking', 'latest': None}
1089
+ self.bridge.update_checked.connect(self.after_update_check)
1090
+ self.update_timer = QTimer()
1091
+ self.update_timer.timeout.connect(self.check_updates)
1092
+ self.update_timer.start(12 * 3600 * 1000)
1093
+ QTimer.singleShot(15_000, self.check_updates)
1094
+ self.window.refresh_updates(self.update_info)
1051
1095
  settings = Settings.load()
1052
1096
  if settings.autostart:
1053
1097
  autostart.apply(True)
@@ -1083,6 +1127,8 @@ class TrayApp:
1083
1127
  self.open_app_action = menu.addAction(f'Open {APP_NAME}', self.show_window)
1084
1128
  self.open_folder_action = menu.addAction('Open folder', lambda: open_folder(Settings.load().root))
1085
1129
  self.pause_action = menu.addAction('Pause', self.toggle_pause)
1130
+ self.update_action = menu.addAction('Update', self.install_update)
1131
+ self.update_action.setVisible(False)
1086
1132
  menu.addSeparator()
1087
1133
  menu.addAction('Quit', self.quit)
1088
1134
  self.menu = menu
@@ -1121,6 +1167,54 @@ class TrayApp:
1121
1167
  self.window.raise_()
1122
1168
  self.window.activateWindow()
1123
1169
 
1170
+ # Updates
1171
+
1172
+ def check_updates(self) -> None:
1173
+ if updates.plan() is None:
1174
+ self.update_info = {'state': 'dev', 'latest': None}
1175
+ self.after_update_check()
1176
+ return
1177
+ if self.update_info.get('state') == 'updating':
1178
+ return
1179
+ self.update_info = {**self.update_info, 'state': 'checking'}
1180
+ self.window.refresh_updates(self.update_info)
1181
+
1182
+ def work():
1183
+ try:
1184
+ newest = updates.latest()
1185
+ self.update_info = {'state': 'available' if updates.newer(newest) else 'current', 'latest': newest}
1186
+ except Exception:
1187
+ self.update_info = {'state': 'failed', 'latest': None, 'error': "Couldn't reach PyPI to check for updates"}
1188
+ self.bridge.update_checked.emit()
1189
+ threading.Thread(target=work, daemon=True).start()
1190
+
1191
+ def after_update_check(self) -> None:
1192
+ info = self.update_info
1193
+ if self.tray:
1194
+ self.update_action.setVisible(info.get('state') == 'available')
1195
+ self.update_action.setText(f"Update to {info.get('latest')}")
1196
+ if info.get('state') == 'available' and info.get('latest') != getattr(self, 'announced', None):
1197
+ self.announced = info.get('latest')
1198
+ self.tray.showMessage(APP_NAME, f"Version {info['latest']} is available. Open ITCPR Sync to update.", QSystemTrayIcon.Information)
1199
+ self.window.refresh_updates(info)
1200
+
1201
+ def install_update(self) -> None:
1202
+ how = updates.plan()
1203
+ if not how or self.update_info.get('state') != 'available':
1204
+ return
1205
+ self.update_info = {**self.update_info, 'state': 'updating'}
1206
+ self.window.refresh_updates(self.update_info)
1207
+ try:
1208
+ updates.start(how)
1209
+ except OSError as failure:
1210
+ self.update_info = {**self.update_info, 'state': 'available'}
1211
+ self.window.refresh_updates(self.update_info)
1212
+ box = QMessageBox(QMessageBox.Warning, APP_NAME, f"Couldn't start the update: {failure}", QMessageBox.Ok, self.window)
1213
+ box.setTextFormat(Qt.PlainText)
1214
+ box.exec()
1215
+ return
1216
+ QTimer.singleShot(400, self.quit) # the helper waits for this to close, updates, and starts the new version
1217
+
1124
1218
  def set_paused(self, on: bool) -> None:
1125
1219
  settings = Settings.load()
1126
1220
  if settings.paused != on:
@@ -0,0 +1,100 @@
1
+ """
2
+ Updates: the newest version on PyPI, and installing it.
3
+
4
+ The app can't replace its own program while it runs (Windows locks it), so updating starts a small
5
+ helper and quits. The helper waits for the app to close, upgrades it the way it was installed (uv, as
6
+ the install line does, or pip), writes what happened to update.log, and starts the app again. If the
7
+ upgrade fails, the same version starts again.
8
+ """
9
+ import base64
10
+ import os
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import httpx
18
+
19
+ from . import __version__
20
+ from .settings import app_dir
21
+
22
+ PACKAGE = 'itcpr'
23
+ VERSION = re.compile(r'^\d+(\.\d+){1,3}$')
24
+
25
+
26
+ def parse(version: str) -> tuple:
27
+ return tuple(int(n) for n in version.split('.'))
28
+
29
+
30
+ def latest() -> str:
31
+ """The newest release on PyPI. Raises when PyPI can't be asked."""
32
+ response = httpx.get(f'https://pypi.org/pypi/{PACKAGE}/json', timeout=15, headers={'User-Agent': f'itcpr-sync/{__version__}'})
33
+ response.raise_for_status()
34
+ version = str(response.json().get('info', {}).get('version', ''))
35
+ if not VERSION.match(version):
36
+ raise ValueError('PyPI gave an unexpected version.')
37
+ return version
38
+
39
+
40
+ def newer(version: str) -> bool:
41
+ return parse(version) > parse(__version__)
42
+
43
+
44
+ def _uv() -> str | None:
45
+ found = shutil.which('uv')
46
+ if found:
47
+ return found
48
+ local = Path.home() / '.local' / 'bin' / ('uv.exe' if sys.platform == 'win32' else 'uv')
49
+ return str(local) if local.exists() else None
50
+
51
+
52
+ def plan() -> dict | None:
53
+ """How this copy updates: the upgrade command and how to start it again. None for a development copy."""
54
+ here = Path(__file__).resolve()
55
+ prefix = Path(sys.prefix).resolve()
56
+ if prefix not in here.parents: # running from a source checkout (pip install -e): updates come from git
57
+ return None
58
+ python = Path(sys.executable)
59
+ if sys.platform == 'win32' and python.with_name('pythonw.exe').exists():
60
+ python = python.with_name('pythonw.exe')
61
+ tray = shutil.which('itcpr-sync-tray')
62
+ restart = [tray] if tray else [str(python), '-m', 'itcpr_sync.tray']
63
+ uv = _uv()
64
+ if uv and prefix.parent.name.lower() == 'tools' and prefix.name.lower() == PACKAGE: # installed with `uv tool install itcpr`
65
+ upgrade = [uv, 'tool', 'install', '--upgrade', PACKAGE]
66
+ else:
67
+ upgrade = [sys.executable, '-m', 'pip', 'install', '--upgrade', PACKAGE]
68
+ return {'upgrade': upgrade, 'restart': restart}
69
+
70
+
71
+ def start(how: dict) -> None:
72
+ """Starts the helper that upgrades and restarts the app once this process has exited. The caller quits next."""
73
+ log = str(app_dir() / 'update.log')
74
+ pid = str(os.getpid())
75
+ if sys.platform == 'win32':
76
+ quote = lambda value: "'" + value.replace("'", "''") + "'" # noqa: E731 (PowerShell single quotes)
77
+ command = (f"Wait-Process -Id {pid} -Timeout 120 -ErrorAction SilentlyContinue; "
78
+ f"& {' '.join(quote(a) for a in how['upgrade'])} *> {quote(log)}; "
79
+ f"Start-Process -FilePath {quote(how['restart'][0])}"
80
+ + (f" -ArgumentList {', '.join(quote(a) for a in how['restart'][1:])}" if len(how['restart']) > 1 else ''))
81
+ encoded = base64.b64encode(command.encode('utf-16-le')).decode()
82
+ flags = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW
83
+ subprocess.Popen(['powershell.exe', '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-EncodedCommand', encoded],
84
+ creationflags=flags, close_fds=True)
85
+ else:
86
+ # A tiny Python helper. Paths go in as separate arguments, never pasted into code, so spaces or quotes are safe.
87
+ runner = ('import subprocess, sys, os, time\n'
88
+ 'pid, log, n = int(sys.argv[1]), sys.argv[2], int(sys.argv[3])\n'
89
+ 'upgrade, restart = sys.argv[4:4 + n], sys.argv[4 + n:]\n'
90
+ 'while True:\n'
91
+ ' try:\n'
92
+ ' os.kill(pid, 0)\n'
93
+ ' except OSError:\n'
94
+ ' break\n'
95
+ ' time.sleep(0.5)\n'
96
+ 'with open(log, "w") as out:\n'
97
+ ' subprocess.run(upgrade, stdout=out, stderr=subprocess.STDOUT)\n'
98
+ 'subprocess.Popen(restart, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n')
99
+ subprocess.Popen([sys.executable, '-c', runner, pid, log, str(len(how['upgrade'])), *how['upgrade'], *how['restart']],
100
+ start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes