mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 04:46:08 +00:00
feat(xbox): install MSIXVC2 back-compat titles from their content boxes (#2851)
* feat(xbox): install MSIXVC2 packages from their encrypted content boxes * feat(xbox): run a package's custom install actions once per prefix * fix(xbox): launch the program a launcher menu names instead of the menu * fix(xbox): check free space before an MSIXVC2 install starts * fix(xbox): keep a forwarded launch path relative when the install folder is reached through a link * fix(xbox): rebuild the MSIXVC2 patch on the final legacy install * fix(xbox): keep a backup whose release fails, and test an interrupted restore * fix(xbox): verify resumed msixvc2 files, contain writes, decode install action arguments * fix(xbox): keep one completion record per msixvc2 file, never follow a linked install state * fix(xbox): drop a torn msixvc2 completion record before appending to it * fix(xbox): repair a torn msixvc2 record from its tail instead of rereading it
This commit is contained in:
1 parent
b43724e5f3
commit
6ed281f78d
8 files changed
+1464
-21
No files matched your search
@@ -102,8 +102,29 @@ internal object XboxManifest {
|
||||
file = matches.single()
|
||||
}
|
||||
require(file.canonicalPath.startsWith(folder.canonicalPath + File.separator))
|
||||
if (file.isFile) return file.relativeTo(folder).invariantSeparatorsPath
|
||||
if (file.isFile) return forwarded(folder, file) ?: file.relativeTo(folder).invariantSeparatorsPath
|
||||
}
|
||||
error("The Xbox package has no supported PC launch executable.")
|
||||
}
|
||||
|
||||
private fun forwarded(folder: File, launcher: File): String? = try {
|
||||
val arguments = File(launcher.parentFile, launcher.nameWithoutExtension + "LaunchArguments.txt")
|
||||
if (!arguments.isFile || arguments.length() > 65_536) null
|
||||
else arguments.readLines().firstNotNullOfOrNull { line ->
|
||||
line.trim().takeIf { it.startsWith("exe=", ignoreCase = true) }?.substring(4)?.trim()
|
||||
}?.takeIf { it.isNotEmpty() && !it.contains(':') }?.let { target -> located(folder.canonicalFile, launcher.parentFile.canonicalFile, target) }
|
||||
} catch (_: java.io.IOException) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun located(root: File, start: File, target: String): String? {
|
||||
var file = start
|
||||
for (part in target.split('/', '\\').filter { it.isNotEmpty() && it != "." }) {
|
||||
file = if (part == "..") file.parentFile ?: return null
|
||||
else file.listFiles().orEmpty().filter { it.name.equals(part, true) }.singleOrNull() ?: return null
|
||||
}
|
||||
val resolved = file.canonicalFile
|
||||
if (!resolved.isFile || !resolved.path.startsWith(root.path + File.separator) || !resolved.extension.equals("exe", true)) return null
|
||||
return resolved.relativeTo(root).invariantSeparatorsPath
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,46 @@ class XboxManifestTest {
|
||||
java.io.File(root, "MicrosoftGame.Config").writeText("<Game><ExecutableList><Executable Name=\"bin\\GAME.EXE\" TargetDeviceFamily=\"PC\"/></ExecutableList></Game>")
|
||||
assertEquals("Bin/Game.exe", XboxInstaller.executable(root))
|
||||
}
|
||||
@Test fun aLauncherMenuIsSkippedForTheProgramItNames() {
|
||||
val root = temporary.newFolder()
|
||||
java.io.File(root, "EmuMenu").mkdir()
|
||||
java.io.File(root, "EmuMenu/EmuMenu.exe").writeText("menu")
|
||||
java.io.File(root, "Emu.exe").writeText("emulator")
|
||||
java.io.File(root, "MicrosoftGame.config").writeText("<Game><ExecutableList><Executable Name=\"EmuMenu\\EmuMenu.exe\"/></ExecutableList></Game>")
|
||||
java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("exe=..\\Emu.exe\r\ntitlename=Game\r\n")
|
||||
assertEquals("Emu.exe", XboxInstaller.executable(root))
|
||||
java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("exe=..\\..\\outside.exe\r\n")
|
||||
assertEquals("EmuMenu/EmuMenu.exe", XboxInstaller.executable(root))
|
||||
java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("titlename=Game\r\n")
|
||||
assertEquals("EmuMenu/EmuMenu.exe", XboxInstaller.executable(root))
|
||||
java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("exe=..\\EMU.EXE\r\n")
|
||||
assertEquals("Emu.exe", XboxInstaller.executable(root))
|
||||
java.io.File(root, "emu.exe").writeText("other")
|
||||
if (root.listFiles().orEmpty().count { it.name.equals("emu.exe", true) } == 2)
|
||||
assertEquals("EmuMenu/EmuMenu.exe", XboxInstaller.executable(root))
|
||||
}
|
||||
@Test fun anUnreadableForwardingFileFallsBackToTheDeclaredProgram() {
|
||||
val root = temporary.newFolder()
|
||||
java.io.File(root, "EmuMenu").mkdir()
|
||||
java.io.File(root, "EmuMenu/EmuMenu.exe").writeText("menu")
|
||||
java.io.File(root, "Emu.exe").writeText("emulator")
|
||||
java.io.File(root, "MicrosoftGame.config").writeText("<Game><ExecutableList><Executable Name=\"EmuMenu\\EmuMenu.exe\"/></ExecutableList></Game>")
|
||||
val arguments = java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").apply { writeText("exe=..\\Emu.exe\r\n") }
|
||||
org.junit.Assume.assumeTrue(arguments.setReadable(false, false) && !arguments.canRead())
|
||||
try { assertEquals("EmuMenu/EmuMenu.exe", XboxInstaller.executable(root)) } finally { arguments.setReadable(true, false) }
|
||||
}
|
||||
@Test fun aForwardedProgramStaysRelativeWhenTheFolderIsReachedThroughALink() {
|
||||
val real = temporary.newFolder()
|
||||
java.io.File(real, "EmuMenu").mkdir()
|
||||
java.io.File(real, "EmuMenu/EmuMenu.exe").writeText("menu")
|
||||
java.io.File(real, "Emu.exe").writeText("emulator")
|
||||
java.io.File(real, "MicrosoftGame.config").writeText("<Game><ExecutableList><Executable Name=\"EmuMenu\\EmuMenu.exe\"/></ExecutableList></Game>")
|
||||
java.io.File(real, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("exe=..\\Emu.exe\r\n")
|
||||
val link = java.io.File(temporary.root, "linked")
|
||||
val linked = runCatching { java.nio.file.Files.createSymbolicLink(link.toPath(), real.toPath()) }.isSuccess
|
||||
org.junit.Assume.assumeTrue(linked)
|
||||
assertEquals("Emu.exe", XboxInstaller.executable(link))
|
||||
}
|
||||
@Test fun rejectsTraversalAndExternalEntities() {
|
||||
for (xml in listOf("<Game><Executable Name=\"../escape.exe\"/></Game>",
|
||||
"<!DOCTYPE Game [<!ENTITY external SYSTEM 'file:///etc/passwd'>]><Game>&external;</Game>",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/python3
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
@@ -11,6 +12,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import xml.etree.ElementTree as ElementTree
|
||||
|
||||
BIN = Path(__file__).resolve().parent
|
||||
RUNTIME = Path('/usr/local/lib/droiddeck-xbox')
|
||||
@@ -137,6 +139,117 @@ def register_classes(proton, prefix, env):
|
||||
print('droiddeck-xbox: Windows Runtime class registration failed; launching without it', file=sys.stderr)
|
||||
|
||||
|
||||
def game_config(exe):
|
||||
path = Path(exe)
|
||||
if not path.is_absolute():
|
||||
return None
|
||||
for folder in list(path.parents)[:4]:
|
||||
config = folder / 'MicrosoftGame.config'
|
||||
if config.is_file():
|
||||
return config
|
||||
return None
|
||||
|
||||
|
||||
def windows_arguments(text):
|
||||
arguments, current, quoted, started, at = [], [], False, False, 0
|
||||
while at < len(text):
|
||||
char = text[at]
|
||||
if char == '\\':
|
||||
run = len(text) - at - len(text[at:].lstrip('\\'))
|
||||
at += run
|
||||
if at < len(text) and text[at] == '"':
|
||||
current.append('\\' * (run // 2))
|
||||
if run % 2:
|
||||
current.append('"')
|
||||
at += 1
|
||||
else:
|
||||
current.append('\\' * run)
|
||||
started = True
|
||||
continue
|
||||
if char == '"':
|
||||
if quoted and text[at + 1:at + 2] == '"':
|
||||
current.append('"')
|
||||
at += 2
|
||||
continue
|
||||
quoted = not quoted
|
||||
started = True
|
||||
elif char in ' \t' and not quoted:
|
||||
if started:
|
||||
arguments.append(''.join(current))
|
||||
current, started = [], False
|
||||
else:
|
||||
current.append(char)
|
||||
started = True
|
||||
at += 1
|
||||
if started:
|
||||
arguments.append(''.join(current))
|
||||
return arguments
|
||||
|
||||
|
||||
def install_actions(config):
|
||||
try:
|
||||
root = ElementTree.fromstring(config.read_bytes())
|
||||
except (OSError, ElementTree.ParseError):
|
||||
return []
|
||||
actions = []
|
||||
for registration in root.iter():
|
||||
if registration.tag.rsplit('}', 1)[-1] != 'CustomInstallActions':
|
||||
continue
|
||||
folder = next((node.text or '' for node in registration if node.tag.rsplit('}', 1)[-1] == 'Folder'), '')
|
||||
for node in registration.iter():
|
||||
if node.tag.rsplit('}', 1)[-1] != 'InstallAction':
|
||||
continue
|
||||
name, file = node.get('Name', ''), node.get('File', '')
|
||||
parts = [part for part in (folder.strip() + '\\' + file).replace('/', '\\').split('\\') if part]
|
||||
if not name or not file or any(part in ('.', '..') or ':' in part for part in parts):
|
||||
continue
|
||||
target = config.parent.joinpath(*parts)
|
||||
try:
|
||||
inside = target.resolve().is_relative_to(config.parent.resolve())
|
||||
except OSError:
|
||||
inside = False
|
||||
if inside and target.is_file() and target.suffix.lower() in ('.msi', '.exe'):
|
||||
actions.append((name, target, windows_arguments(node.get('Arguments', ''))))
|
||||
return actions
|
||||
|
||||
|
||||
def run_install_actions(proton, prefix, exe, env):
|
||||
config = game_config(exe)
|
||||
if config is None:
|
||||
return
|
||||
done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions'
|
||||
for name, target, arguments in install_actions(config):
|
||||
try:
|
||||
content = hashlib.sha256()
|
||||
with target.open('rb') as source:
|
||||
for block in iter(lambda: source.read(1 << 20), b''):
|
||||
content.update(block)
|
||||
identity = hashlib.sha256(name.encode('utf-8') + b'\0' + content.digest()).hexdigest()[:24]
|
||||
marker = done / ('%s-%s' % (''.join(c for c in name if c.isalnum() or c in '-_')[:64], identity))
|
||||
if marker.exists():
|
||||
continue
|
||||
except OSError as error:
|
||||
print('droiddeck-xbox: install action %s could not be read (%s); launching without it' % (name, error), file=sys.stderr)
|
||||
continue
|
||||
windows = 'Z:' + str(target).replace('/', '\\')
|
||||
if target.suffix.lower() == '.msi':
|
||||
command = [proton, 'run', 'msiexec', '/i', windows, *arguments]
|
||||
else:
|
||||
command = [proton, 'run', windows, *arguments]
|
||||
try:
|
||||
code = subprocess.run(command, stdout=sys.stderr, env=env, timeout=600).returncode
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
code = None
|
||||
if code != 0:
|
||||
print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr)
|
||||
continue
|
||||
try:
|
||||
done.mkdir(parents=True, exist_ok=True)
|
||||
marker.touch()
|
||||
except OSError as error:
|
||||
print('droiddeck-xbox: install action %s finished but could not be recorded (%s)' % (name, error), file=sys.stderr)
|
||||
|
||||
|
||||
def view_drive(prefix, exe):
|
||||
path = Path(exe)
|
||||
view = next((parent for parent in path.parents if parent.name.startswith('droiddeck-xbox-')), None)
|
||||
@@ -184,6 +297,7 @@ def wine(argv, source_env=None):
|
||||
target.unlink()
|
||||
shutil.copyfile(RUNTIME / 'windows' / name, target)
|
||||
register_classes(command[0], prefix, env)
|
||||
run_install_actions(command[0], prefix, argv[0], env)
|
||||
overrides = ';'.join(name[:-4] + '=n' for name in DLLS if name != 'libnghttp2.dll')
|
||||
env['WINEDLLOVERRIDES'] = overrides + ';' + env.get('WINEDLLOVERRIDES', '')
|
||||
exe, drive = view_drive(prefix, argv[0])
|
||||
|
||||
@@ -178,6 +178,101 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
self.assertEqual(sorted(p.name for p in devices.iterdir()), ['v:', 'w:', 'x:'])
|
||||
self.assertEqual(xbox['view_drive'](root / 'pfx', '/games/Game.exe'), ('/games/Game.exe', None))
|
||||
|
||||
def test_package_install_actions_run_once_and_stay_inside_the_game(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
|
||||
(game / 'Installers').mkdir(parents=True)
|
||||
(game / 'Installers' / 'GameInputRedist.msi').write_bytes(b'msi')
|
||||
(game / 'Emu.exe').write_bytes(b'exe')
|
||||
(Path(root) / 'outside.msi').write_bytes(b'msi')
|
||||
(game / 'MicrosoftGame.config').write_text(
|
||||
'<Game><DesktopRegistration><CustomInstallActions><Folder>Installers</Folder><InstallActionList>'
|
||||
'<InstallAction File="GameInputRedist.msi" Name="InstallGameInput" Arguments="/quiet"/>'
|
||||
'<InstallAction File="..\\..\\outside.msi" Name="Escape"/>'
|
||||
'</InstallActionList></CustomInstallActions></DesktopRegistration></Game>')
|
||||
with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
|
||||
xbox['run_install_actions']('/selected/proton', prefix, str(game / 'Emu.exe'), {'A': '1'})
|
||||
xbox['run_install_actions']('/selected/proton', prefix, str(game / 'Emu.exe'), {'A': '1'})
|
||||
self.assertEqual(child.call_count, 1)
|
||||
command = child.call_args.args[0]
|
||||
self.assertEqual(command[:4], ['/selected/proton', 'run', 'msiexec', '/i'])
|
||||
self.assertTrue(command[4].startswith('Z:') and command[4].endswith('GameInputRedist.msi'))
|
||||
self.assertEqual(command[5:], ['/quiet'])
|
||||
|
||||
def test_a_failed_install_action_is_retried_on_the_next_launch(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
|
||||
game.mkdir()
|
||||
(game / 'setup.exe').write_bytes(b'exe')
|
||||
(game / 'MicrosoftGame.config').write_text(
|
||||
'<Game><CustomInstallActions><InstallActionList><InstallAction File="setup.exe" Name="Setup"/>'
|
||||
'</InstallActionList></CustomInstallActions></Game>')
|
||||
with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 1)) as child:
|
||||
xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {})
|
||||
xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {})
|
||||
self.assertEqual(child.call_count, 2)
|
||||
self.assertEqual(child.call_args.args[0][:2], ['/p', 'run'])
|
||||
|
||||
def test_install_action_arguments_follow_windows_command_line_rules(self):
|
||||
parse = xbox['windows_arguments']
|
||||
self.assertEqual(parse('/quiet /log "C:\\ProgramData\\Game Setup\\install.log"'),
|
||||
['/quiet', '/log', 'C:\\ProgramData\\Game Setup\\install.log'])
|
||||
self.assertEqual(parse('a\\\\b "x\\"y" "\\\\" "" c""d "e""f"'), ['a\\\\b', 'x"y', '\\', '', 'cd', 'e"f'])
|
||||
self.assertEqual(parse(' '), [])
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
|
||||
game.mkdir()
|
||||
(game / 'setup.msi').write_bytes(b'msi')
|
||||
(game / 'MicrosoftGame.config').write_text(
|
||||
'<Game><CustomInstallActions><InstallActionList><InstallAction File="setup.msi" Name="Setup" '
|
||||
'Arguments="/quiet /log "C:\\ProgramData\\Game Setup\\install.log""/>'
|
||||
'</InstallActionList></CustomInstallActions></Game>')
|
||||
with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
|
||||
xbox['run_install_actions']('/p', prefix, str(game / 'setup.msi'), {})
|
||||
self.assertEqual(child.call_args.args[0][5:], ['/quiet', '/log', 'C:\\ProgramData\\Game Setup\\install.log'])
|
||||
|
||||
def test_actions_whose_names_differ_only_in_punctuation_each_run(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
|
||||
game.mkdir()
|
||||
(game / 'setup.exe').write_bytes(b'exe')
|
||||
(game / 'MicrosoftGame.config').write_text(
|
||||
'<Game><CustomInstallActions><InstallActionList>'
|
||||
'<InstallAction File="setup.exe" Name="Setup A" Arguments="/a"/>'
|
||||
'<InstallAction File="setup.exe" Name="SetupA" Arguments="/b"/>'
|
||||
'</InstallActionList></CustomInstallActions></Game>')
|
||||
with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
|
||||
xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {})
|
||||
xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {})
|
||||
self.assertEqual([call.args[0][-1] for call in child.call_args_list], ['/a', '/b'])
|
||||
|
||||
def test_an_install_action_error_never_stops_the_launch(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
|
||||
game.mkdir()
|
||||
(game / 'first.exe').write_bytes(b'exe')
|
||||
(game / 'second.exe').write_bytes(b'exe')
|
||||
(game / 'MicrosoftGame.config').write_text(
|
||||
'<Game><CustomInstallActions><InstallActionList>'
|
||||
'<InstallAction File="first.exe" Name="First"/><InstallAction File="second.exe" Name="Second"/>'
|
||||
'</InstallActionList></CustomInstallActions></Game>')
|
||||
real_open = Path.open
|
||||
def unreadable(path, *args, **kwargs):
|
||||
if path.name == 'first.exe':
|
||||
raise PermissionError('denied')
|
||||
return real_open(path, *args, **kwargs)
|
||||
with patch.object(Path, 'open', unreadable), \
|
||||
patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
|
||||
xbox['run_install_actions']('/p', prefix, str(game / 'first.exe'), {})
|
||||
self.assertEqual(child.call_count, 1)
|
||||
self.assertTrue(child.call_args.args[0][2].endswith('second.exe'))
|
||||
with patch('subprocess.run', side_effect=OSError('no proton')):
|
||||
xbox['run_install_actions']('/p', prefix, str(game / 'first.exe'), {})
|
||||
with patch.object(Path, 'touch', side_effect=OSError('read-only')), \
|
||||
patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
|
||||
xbox['run_install_actions']('/p', prefix / 'other', str(game / 'first.exe'), {})
|
||||
self.assertEqual(child.call_count, 2)
|
||||
|
||||
def test_missing_runtime_classes_are_registered_once(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
prefix = Path(root)
|
||||
|
||||
@@ -125,6 +125,15 @@ download plus two copies of the largest container, and each container is deleted
|
||||
The download has no control channel: cancelling kills it and the next attempt starts that
|
||||
container from zero.
|
||||
|
||||
`droiddeck-msixvc2.patch` installs MSIXVC2 packages, the format Xbox 360 backward-compatible
|
||||
titles ship in. The package Windows Update serves is only an index (`XboxPackage.cbor`, chunk and
|
||||
file tables); the files are encrypted, Brotli-compressed segments inside `.box` blobs on the Xbox
|
||||
content hosts. `streaming` unpacks the index, licenses its content id, derives the package key from
|
||||
the content key (SP800-108 HMAC-SHA256, label `MSIXVC2:PackageData:AES_256_CBC`), unwraps each
|
||||
segment key with AES-256-CBC, fetches adjacent segments in one ranged request, and checks the
|
||||
SHA-384 of every stored segment, decompressed segment and finished file before it is renamed into
|
||||
place. Files already complete are skipped on a retry.
|
||||
|
||||
Cloud saves and in-game identity use the reused XGameRuntime/service interfaces;
|
||||
those are game-dependent. Entitlements distinguish purchases from Game Pass
|
||||
access, and the backend performs a fresh license check for downloads and launch.
|
||||
|
||||
@@ -2026,7 +2026,7 @@ index 0000000..7fec6e5
|
||||
+ }
|
||||
+}
|
||||
diff --git a/crates/xodus-cli/src/commands/streaming.rs b/crates/xodus-cli/src/commands/streaming.rs
|
||||
index a0136f8..8637cab 100644
|
||||
index a0136f8..8e9d0e0 100644
|
||||
--- a/crates/xodus-cli/src/commands/streaming.rs
|
||||
+++ b/crates/xodus-cli/src/commands/streaming.rs
|
||||
@@ -9,7 +9,7 @@ use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
|
||||
@@ -2054,7 +2054,7 @@ index a0136f8..8637cab 100644
|
||||
let remote_xvd = match XvdFile::parse(&mut remote_file).await {
|
||||
Ok(xvd) => xvd,
|
||||
Err(error) => { failure::report_metadata(error.as_ref()); return ExitCode::FAILURE; }
|
||||
@@ -692,3 +701,337 @@ where
|
||||
@@ -692,3 +701,369 @@ where
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -2095,11 +2095,7 @@ index a0136f8..8637cab 100644
|
||||
+ Ok::<(), String>(())
|
||||
+ })();
|
||||
+ match result {
|
||||
+ Ok(()) => {
|
||||
+ std::fs::remove_file(previous.join(PENDING)).ok();
|
||||
+ std::fs::remove_dir_all(&previous).ok();
|
||||
+ Ok(())
|
||||
+ }
|
||||
+ Ok(()) => release(&previous),
|
||||
+ Err(error) => {
|
||||
+ let stuck: Vec<String> = placed
|
||||
+ .iter()
|
||||
@@ -2125,7 +2121,22 @@ index a0136f8..8637cab 100644
|
||||
+
|
||||
+/// Moves every entry kept in `previous` back into `out`, then removes `previous`.
|
||||
+/// On any failure `previous` stays, holding what has not been put back.
|
||||
+fn release(previous: &Path) -> Result<(), String> {
|
||||
+ std::fs::remove_file(previous.join(PENDING))
|
||||
+ .map_err(|error| format!("the replacement finished but its backup could not be released: {error}"))?;
|
||||
+ std::fs::remove_dir_all(previous).ok();
|
||||
+ Ok(())
|
||||
+}
|
||||
+
|
||||
+fn restore(previous: &Path, out: &Path) -> Result<(), String> {
|
||||
+ restore_with(previous, out, &mut |from, to| std::fs::rename(from, to))
|
||||
+}
|
||||
+
|
||||
+fn restore_with(
|
||||
+ previous: &Path,
|
||||
+ out: &Path,
|
||||
+ move_entry: &mut dyn FnMut(&Path, &Path) -> std::io::Result<()>,
|
||||
+) -> Result<(), String> {
|
||||
+ let placed = std::fs::read_to_string(previous.join(PENDING)).map_err(|error| error.to_string())?;
|
||||
+ for name in placed.lines().filter(|name| !name.is_empty() && !name.contains(['/', '\\']) && *name != "." && *name != "..") {
|
||||
+ let target = out.join(name);
|
||||
@@ -2146,7 +2157,7 @@ index a0136f8..8637cab 100644
|
||||
+ if std::fs::symlink_metadata(&target).is_ok() {
|
||||
+ remove(&target).map_err(|error| format!("could not clear {}: {error}", target.display()))?;
|
||||
+ }
|
||||
+ std::fs::rename(entry.path(), &target).map_err(|error| format!("could not restore {}: {error}", target.display()))?;
|
||||
+ move_entry(&entry.path(), &target).map_err(|error| format!("could not restore {}: {error}", target.display()))?;
|
||||
+ }
|
||||
+ std::fs::remove_file(previous.join(PENDING)).map_err(|error| error.to_string())?;
|
||||
+ std::fs::remove_dir(previous).map_err(|error| error.to_string())
|
||||
@@ -2312,21 +2323,42 @@ index a0136f8..8637cab 100644
|
||||
+ #[test]
|
||||
+ fn a_restore_interrupted_after_its_removals_never_deletes_what_it_put_back() {
|
||||
+ let root = tempfile::tempdir().unwrap();
|
||||
+ let (staging, out) = (root.path().join("staging"), root.path().join("out"));
|
||||
+ let out = root.path().join("out");
|
||||
+ let previous = out.join(".xodus-plain-previous");
|
||||
+ std::fs::create_dir_all(&staging).unwrap();
|
||||
+ std::fs::create_dir_all(&previous).unwrap();
|
||||
+ std::fs::write(previous.join(".pending"), "a").unwrap();
|
||||
+ std::fs::write(previous.join("a"), b"old").unwrap();
|
||||
+ std::fs::write(out.join("a"), b"stray").unwrap();
|
||||
+ super::restore(&previous, &out).unwrap();
|
||||
+ assert_eq!(std::fs::read(out.join("a")).unwrap(), b"old");
|
||||
+ std::fs::create_dir_all(&previous).unwrap();
|
||||
+ std::fs::write(previous.join(".pending"), "").unwrap();
|
||||
+ std::fs::write(previous.join(".pending"), "a
|
||||
+b").unwrap();
|
||||
+ std::fs::write(previous.join("a"), b"old-a").unwrap();
|
||||
+ std::fs::write(previous.join("b"), b"old-b").unwrap();
|
||||
+ super::publish(&staging, &out).unwrap();
|
||||
+ assert_eq!(std::fs::read(out.join("a")).unwrap(), b"old");
|
||||
+ std::fs::write(out.join("a"), b"new-a").unwrap();
|
||||
+ std::fs::write(out.join("b"), b"new-b").unwrap();
|
||||
+ let mut moves = 0;
|
||||
+ let interrupted = super::restore_with(&previous, &out, &mut |from, to| {
|
||||
+ moves += 1;
|
||||
+ if moves == 2 { return Err(std::io::Error::other("interrupted")) }
|
||||
+ std::fs::rename(from, to)
|
||||
+ });
|
||||
+ assert!(interrupted.is_err());
|
||||
+ let restored = ["a", "b"].into_iter().find(|name| out.join(name).exists()).unwrap();
|
||||
+ super::restore(&previous, &out).unwrap();
|
||||
+ assert_eq!(std::fs::read(out.join(restored)).unwrap(), format!("old-{restored}").as_bytes());
|
||||
+ assert_eq!(std::fs::read(out.join("a")).unwrap(), b"old-a");
|
||||
+ assert_eq!(std::fs::read(out.join("b")).unwrap(), b"old-b");
|
||||
+ assert!(!previous.exists());
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_backup_whose_marker_cannot_be_removed_is_kept_and_reported() {
|
||||
+ let root = tempfile::tempdir().unwrap();
|
||||
+ let previous = root.path().join(".xodus-plain-previous");
|
||||
+ std::fs::create_dir_all(previous.join(".pending").join("held")).unwrap();
|
||||
+ std::fs::write(previous.join("kept"), b"old").unwrap();
|
||||
+ assert!(super::release(&previous).is_err());
|
||||
+ assert!(previous.join("kept").exists());
|
||||
+ std::fs::remove_dir_all(previous.join(".pending")).unwrap();
|
||||
+ std::fs::write(previous.join(".pending"), b"").unwrap();
|
||||
+ super::release(&previous).unwrap();
|
||||
+ assert!(!previous.exists());
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,7 +11,8 @@ lock = json.loads((recipe / 'backend.lock.json').read_text())
|
||||
local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch',
|
||||
'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch',
|
||||
'droiddeck-licensing-device-ticket.patch', 'droiddeck-dlc-mount.patch',
|
||||
'droiddeck-legacy-packages.patch', 'droiddeck-legacy-install.patch', 'droiddeck-legacy-run.patch']
|
||||
'droiddeck-legacy-packages.patch', 'droiddeck-legacy-install.patch', 'droiddeck-legacy-run.patch',
|
||||
'droiddeck-msixvc2.patch']
|
||||
identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest()
|
||||
source = cache / ('source-' + identity[:16])
|
||||
if not (source / '.prepared').is_file():
|
||||
|
||||
Reference in new issue
Block a user