Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b6098d331 | ||
|
|
69d70e4712 | ||
|
|
32fd954952 | ||
|
|
40ea4445cd | ||
|
|
3ca5f984de | ||
|
|
6dbf6c0e3c | ||
|
|
6a05d86801 | ||
|
|
068dfce7ca | ||
|
|
28a9089443 | ||
|
|
e42776a2c8 | ||
|
|
c8bda4b76f | ||
|
|
fe10962c4b | ||
|
|
4dc8db6921 | ||
|
|
716add6d76 | ||
|
|
98af75c725 | ||
|
|
88bd3fa403 | ||
|
|
b16f7f528d | ||
|
|
e2c0f2fffc | ||
|
|
a6be413190 | ||
|
|
8034eef8c7 | ||
|
|
3b0d5295d3 |
No files matched your search
@@ -1,11 +1,64 @@
|
||||
# Contributing to Rusty Path Of Building
|
||||
|
||||
## Reporting bugs
|
||||
|
||||
- Ensure the bug was not already reported by searching through existing [issues](https://github.com/meehl/rusty-path-of-building/issues).
|
||||
- If the bug can also be reproduced with the official runtime (e.g. by running through wine), please open an issue in the [PoB1](https://github.com/PathOfBuildingCommunity/PathOfBuilding) or [PoB2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2) repo instead. If you're unsure, feel free to just open it here.
|
||||
- If possible, use the bug report template to create the issue and provide as much information as possible.
|
||||
|
||||
## Contributing code
|
||||
|
||||
- Get familiar with the code base before you start. I'll try to add more documentation providing a high-level overview of the architecture in the future. Until then, feel free to reach out through [Discussions](https://github.com/meehl/rusty-path-of-building/discussions) if you have any questions.
|
||||
- If you intend to work on the API functions, also check out the [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) code base. A great place to ask questions about it is the PoB dev discord server. [Here](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) is more info on how to join.
|
||||
- Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
|
||||
|
||||
## macOS Development Setup
|
||||
|
||||
### 1. Install Lua runtime dependencies
|
||||
|
||||
The application requires several Lua C libraries at runtime. Install them using LuaRocks with the LuaJIT backend:
|
||||
|
||||
```bash
|
||||
brew install luajit luarocks
|
||||
|
||||
luarocks --lua-version 5.1 install luasocket
|
||||
luarocks --lua-version 5.1 install luautf8
|
||||
luarocks --lua-version 5.1 install lua-curl
|
||||
```
|
||||
|
||||
Build and install `lzip` from the bundled source (requires zlib, which is pre-installed on macOS):
|
||||
|
||||
```bash
|
||||
cd lua/libs/lzip && make LUA_IMPL=luajit install
|
||||
```
|
||||
|
||||
### 2. Configure LUA_CPATH
|
||||
|
||||
Add the following to your shell profile (`~/.zshrc` or `~/.bash_profile`) so the runtime can locate the installed libraries:
|
||||
|
||||
```bash
|
||||
eval $(luarocks --lua-version 5.1 path)
|
||||
```
|
||||
|
||||
Then reload your shell or run `source ~/.bash_profile`.
|
||||
|
||||
### 3. Startup
|
||||
|
||||
```bash
|
||||
cargo run <poe1|poe2>
|
||||
```
|
||||
|
||||
Path of Building files are automatically downloaded to the following directories on first startup:
|
||||
|
||||
- poe1: `~/Library/Application Support/RustyPathOfBuilding1`
|
||||
- poe2: `~/Library/Application Support/RustyPathOfBuilding2`
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
**Build fails with `library 'luajit-5.1' not found`**
|
||||
|
||||
This usually means the build cache points to an old LuaJIT version after a Homebrew upgrade. Run:
|
||||
|
||||
```bash
|
||||
cargo clean && cargo run <poe1|poe2>
|
||||
```
|
||||
@@ -1 +1,3 @@
|
||||
/target/
|
||||
*.so
|
||||
*.so.dSYM
|
||||
+48
-1
@@ -2,6 +2,48 @@
|
||||
|
||||
## [Unreleased] - ReleaseDate
|
||||
|
||||
## [0.2.18] - 2026-05-29
|
||||
|
||||
### Changed
|
||||
|
||||
- Raise `max_texture_array_layers` GPU requirement to support new gem tooltips
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix doubleclick handling
|
||||
|
||||
## [0.2.17] - 2026-05-24
|
||||
|
||||
### Changed
|
||||
|
||||
- Improve macOS compatibility
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix broken selection and display of colored text
|
||||
- Fix black screen during installation on nixOS
|
||||
|
||||
## [0.2.16] - 2026-03-23
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix bug that causes tarball extraction to fail
|
||||
|
||||
## [0.2.15] - 2026-03-22
|
||||
|
||||
### Changed
|
||||
|
||||
- Replace `ureq` crate with `reqwest` for better IPv4/IPv6 dual stack support
|
||||
- Refactor installer
|
||||
- Bump dependencies
|
||||
|
||||
## [0.2.14] - 2026-03-14
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix deletion of character build directories
|
||||
- Prevent installer from downloading beta versions
|
||||
|
||||
## [0.2.13] - 2026-03-09
|
||||
|
||||
### Fixed
|
||||
@@ -167,8 +209,13 @@
|
||||
- First release
|
||||
|
||||
<!-- next-url -->
|
||||
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.13...HEAD
|
||||
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.18...HEAD
|
||||
|
||||
[0.2.18]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.17...v0.2.18
|
||||
[0.2.17]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.16...v0.2.17
|
||||
[0.2.16]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.15...v0.2.16
|
||||
[0.2.15]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.14...v0.2.15
|
||||
[0.2.14]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.13...v0.2.14
|
||||
[0.2.13]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.12...v0.2.13
|
||||
[0.2.12]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.11...v0.2.12
|
||||
[0.2.11]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.10...v0.2.11
|
||||
|
||||
Generated
+1335
-453
File diff suppressed because it is too large.
Load diff
+5
-5
@@ -4,7 +4,7 @@ authors = ["meehl"]
|
||||
description = "Cross-platform runtime for Path of Building"
|
||||
repository = "https://github.com/meehl/rusty-path-of-building"
|
||||
license = "MIT"
|
||||
version = "0.2.13"
|
||||
version = "0.2.18"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
@@ -18,7 +18,7 @@ dds = "0.1.0"
|
||||
directories = "6.0.0"
|
||||
env_logger = "0.10"
|
||||
euclid = { version = "0.22.11", features = ["bytemuck"] }
|
||||
fast_image_resize = { version = "5.3.0", features = ["image"] }
|
||||
fast_image_resize = { version = "6.0.0", features = ["image"] }
|
||||
flate2 = "1.1.2"
|
||||
glob = "0.3.3"
|
||||
image = { version = "0.25.8", default-features = false, features = ["rayon", "jpeg", "png", "webp"] }
|
||||
@@ -34,14 +34,14 @@ profiling = "1.0"
|
||||
puffin_http = { version = "0.16", optional = true }
|
||||
raw-window-handle = "0.6.2"
|
||||
regex = "1.11.2"
|
||||
reqwest = { version = "0.13.2", features = ["blocking"] }
|
||||
swash = "0.2.5"
|
||||
tar = "0.4.44"
|
||||
ureq = "3.1.2"
|
||||
wgpu = { version = "27.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "wgsl"] }
|
||||
wgpu = { version = "27.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] }
|
||||
winit = "0.30"
|
||||
zstd = "0.13.3"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
smithay-clipboard = "0.7.3"
|
||||
|
||||
[features]
|
||||
|
||||
+3
-1
@@ -9,7 +9,8 @@ use crate::{
|
||||
input::{get_cursor_pos, is_key_down},
|
||||
lua::{load_module, protected_call, protected_load_module},
|
||||
paths::{
|
||||
get_runtime_path, get_script_path, get_user_path, get_work_dir, make_dir, set_work_dir,
|
||||
get_runtime_path, get_script_path, get_user_path, get_work_dir, make_dir, remove_dir,
|
||||
set_work_dir,
|
||||
},
|
||||
rendering::PoBString,
|
||||
search_handle::new_search_handle,
|
||||
@@ -51,6 +52,7 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
|
||||
globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?;
|
||||
globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?;
|
||||
globals.set("MakeDir", lua.create_function(make_dir)?)?;
|
||||
globals.set("RemoveDir", lua.create_function(remove_dir)?)?;
|
||||
|
||||
// console
|
||||
globals.set("ConPrintf", lua.create_function(console_printf)?)?;
|
||||
|
||||
@@ -47,3 +47,15 @@ pub fn make_dir(l: &Lua, path: String) -> LuaResult<MultiValue> {
|
||||
Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_dir(l: &Lua, (path, recursive): (String, Option<bool>)) -> LuaResult<MultiValue> {
|
||||
let result = if recursive.unwrap_or(false) {
|
||||
fs::remove_dir_all(&path)
|
||||
} else {
|
||||
fs::remove_dir(&path)
|
||||
};
|
||||
match result {
|
||||
Ok(_) => Ok(Value::Boolean(true).into_lua_multi(l)?),
|
||||
Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?),
|
||||
}
|
||||
}
|
||||
+18
-3
@@ -445,14 +445,29 @@ fn get_index_at_cur(
|
||||
let font_type = font_type.parse::<PoBFontType>()?;
|
||||
|
||||
let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None);
|
||||
let index = ctx.fonts().get_text_index_at_cursor(
|
||||
let index_stripped = ctx.fonts().get_text_index_at_cursor(
|
||||
job,
|
||||
Point::new(cur_x, cur_y),
|
||||
ctx.window().scale_factor(),
|
||||
);
|
||||
|
||||
// convert to lua's 1-based indexing
|
||||
Ok(index + 1)
|
||||
// build_layout_job() strips all color escape strings from the original string. The
|
||||
// resulting [`LayoutJob`] is then passed to get_text_index_at_cursor() which returns an
|
||||
// index into the **stripped* string.
|
||||
// But PoB expects an index into the **original, unstripped** text. Therefore we need to add
|
||||
// the length of all color escapes up until the cursor position to return the right value.
|
||||
//
|
||||
// TODO: avoid matching and iterating over string twice
|
||||
let mut color_escapes_total_length = 0;
|
||||
for capture in ESCAPE_STR_REGEX.find_iter(&text) {
|
||||
if capture.start() - color_escapes_total_length > index_stripped {
|
||||
break;
|
||||
}
|
||||
color_escapes_total_length += capture.len();
|
||||
}
|
||||
|
||||
// add length of color escapes and convert to lua's 1-based indexing
|
||||
Ok(index_stripped + color_escapes_total_length + 1)
|
||||
}
|
||||
|
||||
pub static ESCAPE_STR_REGEX: LazyLock<Regex> =
|
||||
|
||||
+3
-10
@@ -392,24 +392,17 @@ fn pob_font_definitions() -> FontDefinitions {
|
||||
|
||||
definitions.generic_families.insert(
|
||||
parley::GenericFamily::Monospace,
|
||||
vec!["bitstream-vera-sans-mono".to_owned()],
|
||||
vec!["Bitstream Vera Sans Mono".to_owned()],
|
||||
);
|
||||
|
||||
definitions.generic_families.insert(
|
||||
parley::GenericFamily::SansSerif,
|
||||
vec![
|
||||
"liberation-sans".to_owned(),
|
||||
"liberation-sans-bold".to_owned(),
|
||||
],
|
||||
vec!["Liberation Sans".to_owned()],
|
||||
);
|
||||
|
||||
definitions.generic_families.insert(
|
||||
parley::GenericFamily::Serif,
|
||||
vec![
|
||||
"fontin-regular".to_owned(),
|
||||
"fontin-italic".to_owned(),
|
||||
"fontin-smallcaps".to_owned(),
|
||||
],
|
||||
vec!["Fontin".to_owned(), "Fontin SmallCaps".to_owned()],
|
||||
);
|
||||
|
||||
definitions
|
||||
|
||||
+5
-5
@@ -5,7 +5,7 @@ use raw_window_handle::RawDisplayHandle;
|
||||
/// `smithay_clipboard`: Used on wayland
|
||||
/// `arboard`: All other platforms (check arboard docs for platform support)
|
||||
pub struct Clipboard {
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
smithay: Option<smithay_clipboard::Clipboard>,
|
||||
arboard: Option<arboard::Clipboard>,
|
||||
// fallback if everything else fails. only supports intra-application copy/paste
|
||||
@@ -15,7 +15,7 @@ pub struct Clipboard {
|
||||
impl Clipboard {
|
||||
pub fn new(_raw_display_handle: Option<RawDisplayHandle>) -> Self {
|
||||
Self {
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
smithay: create_smithay_clipboard(_raw_display_handle),
|
||||
arboard: create_arboard_clipboard(),
|
||||
fallback: None,
|
||||
@@ -24,7 +24,7 @@ impl Clipboard {
|
||||
|
||||
/// Sets the text content of clipboard
|
||||
pub fn set_text(&mut self, text: String) {
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(clipboard) = &mut self.smithay {
|
||||
clipboard.store(text);
|
||||
return;
|
||||
@@ -40,7 +40,7 @@ impl Clipboard {
|
||||
|
||||
/// Gets the text content of clipboard
|
||||
pub fn get_text(&mut self) -> Option<String> {
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(clipboard) = &mut self.smithay {
|
||||
return clipboard.load().ok();
|
||||
}
|
||||
@@ -57,7 +57,7 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn create_smithay_clipboard(
|
||||
raw_display_handle: Option<RawDisplayHandle>,
|
||||
) -> Option<smithay_clipboard::Clipboard> {
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ impl GraphicsContext {
|
||||
|
||||
let required_features = wgpu::Features::TEXTURE_COMPRESSION_BC;
|
||||
let required_limits = wgpu::Limits {
|
||||
max_texture_array_layers: 512,
|
||||
max_texture_array_layers: 1024,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
|
||||
+32
-13
@@ -8,6 +8,15 @@ use winit::{
|
||||
keyboard::{Key, ModifiersState, NamedKey, SmolStr},
|
||||
};
|
||||
|
||||
const DOUBLE_CLICK_DURATION: Duration = Duration::from_millis(500);
|
||||
const DOUBLE_CLICK_MOVE_THRESHOLD: f32 = 5.0;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct MousePressState {
|
||||
time: Instant,
|
||||
pos: LogicalPoint<f32>,
|
||||
}
|
||||
|
||||
/// Current state of various keyboard and mouse inputs for the application.
|
||||
#[derive(Default)]
|
||||
pub struct InputState {
|
||||
@@ -18,7 +27,7 @@ pub struct InputState {
|
||||
/// HashSet of currently pressed mouse buttons.
|
||||
mouse_pressed: HashSet<MouseButton>,
|
||||
/// HashMap of mouse buttons (keys) with the last time they were pressed.
|
||||
mouse_last_pressed: HashMap<MouseButton, Instant>,
|
||||
mouse_last_pressed: HashMap<MouseButton, MousePressState>,
|
||||
/// Current cursor position relative to the top-left corner of the window.
|
||||
cursor_pos: LogicalPoint<f32>,
|
||||
}
|
||||
@@ -41,22 +50,31 @@ impl InputState {
|
||||
/// Updates [`Self::mouse_pressed`](field@Self::mouse_pressed) based on provided
|
||||
/// `button` and `is_pressed`.
|
||||
pub fn set_mouse_pressed(&mut self, button: MouseButton, is_pressed: bool) -> bool {
|
||||
if is_pressed {
|
||||
self.mouse_pressed.insert(button);
|
||||
} else {
|
||||
if !is_pressed {
|
||||
self.mouse_pressed.remove(&button);
|
||||
return false;
|
||||
}
|
||||
|
||||
self.mouse_pressed.insert(button);
|
||||
let now = Instant::now();
|
||||
let last = self.mouse_last_pressed.entry(button);
|
||||
|
||||
match last {
|
||||
std::collections::hash_map::Entry::Occupied(mut occupied_entry) => {
|
||||
let last = occupied_entry.insert(now);
|
||||
now.duration_since(last) < Duration::from_millis(400)
|
||||
let pos = self.cursor_pos;
|
||||
match self.mouse_last_pressed.entry(button) {
|
||||
std::collections::hash_map::Entry::Occupied(mut entry) => {
|
||||
let last = entry.get();
|
||||
let delta = (last.pos - pos).abs();
|
||||
let is_double = now.duration_since(last.time) < DOUBLE_CLICK_DURATION
|
||||
&& delta.x <= DOUBLE_CLICK_MOVE_THRESHOLD
|
||||
&& delta.y <= DOUBLE_CLICK_MOVE_THRESHOLD;
|
||||
if is_double {
|
||||
// Reset so that a triple-click is not treated as two consecutive
|
||||
// double-clicks; the next click starts a fresh timing window.
|
||||
entry.remove();
|
||||
} else {
|
||||
entry.insert(MousePressState { time: now, pos });
|
||||
}
|
||||
is_double
|
||||
}
|
||||
std::collections::hash_map::Entry::Vacant(vacant_entry) => {
|
||||
vacant_entry.insert(now);
|
||||
std::collections::hash_map::Entry::Vacant(entry) => {
|
||||
entry.insert(MousePressState { time: now, pos });
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -82,6 +100,7 @@ impl InputState {
|
||||
pub fn clear_pressed(&mut self) {
|
||||
self.keys_pressed.clear();
|
||||
self.mouse_pressed.clear();
|
||||
self.mouse_last_pressed.clear();
|
||||
self.key_modifiers = ModifiersState::empty();
|
||||
}
|
||||
}
|
||||
|
||||
+186
-370
@@ -4,50 +4,47 @@ use crate::{
|
||||
color::Srgba,
|
||||
dpi::{LogicalPoint, LogicalRect},
|
||||
fonts::{Alignment, FontStyle, LayoutJob},
|
||||
installer::download::{
|
||||
DownloadEvent, ExtractionRule, build_client, download_and_extract_tarball,
|
||||
download_file_to_disk, fetch_file_contents,
|
||||
},
|
||||
mode::{AppEvent, ModeFrameOutput, ModeTransition},
|
||||
renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive},
|
||||
util::replace_in_matching_lines,
|
||||
};
|
||||
use flate2::read::GzDecoder;
|
||||
use parley::{FontFamily, GenericFamily};
|
||||
use regex::Regex;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use std::{
|
||||
fs::{self},
|
||||
io::copy,
|
||||
path::{Path, PathBuf},
|
||||
sync::mpsc::{self, Receiver, TryRecvError},
|
||||
fs,
|
||||
path::Path,
|
||||
sync::{
|
||||
LazyLock,
|
||||
mpsc::{self, Receiver, TryRecvError},
|
||||
},
|
||||
thread,
|
||||
};
|
||||
use ureq::{Agent, http::Response};
|
||||
|
||||
const REPO_NAME: &str = "meehl/rusty-pob-manifest";
|
||||
mod download;
|
||||
|
||||
enum DownloadProgress {
|
||||
Percentage(f32), // percentage of total size (between 0 and 1)
|
||||
TotalBytes(u64), // amount of bytes downloaded
|
||||
}
|
||||
const COMPAT_REPO: &str = "meehl/rusty-pob-manifest";
|
||||
|
||||
static VERSION_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^(\d+)\.(\d+)\.(\d+)$").unwrap());
|
||||
|
||||
static MANIFEST_VERSION_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<Version").unwrap());
|
||||
|
||||
enum Progress {
|
||||
Status(String),
|
||||
Download(DownloadProgress),
|
||||
Complete,
|
||||
Error(anyhow::Error),
|
||||
}
|
||||
|
||||
enum CurrentProgress {
|
||||
Starting,
|
||||
Status(String),
|
||||
Download(DownloadProgress),
|
||||
}
|
||||
|
||||
/// Execution mode in which PoB's assets are downloaded if they don't exist yet.
|
||||
/// Execution mode in which initial installation of PoB is performed.
|
||||
///
|
||||
/// Immediately transitions into PoB mode if assets already exist. Otherwise,
|
||||
/// it downloads them to the user directory and displays the download progress.
|
||||
/// Immediately transitions into PoB mode if already installed.
|
||||
pub struct InstallMode {
|
||||
progress_rx: Option<Receiver<Progress>>,
|
||||
current_progress: CurrentProgress,
|
||||
status: String,
|
||||
}
|
||||
|
||||
impl InstallMode {
|
||||
@@ -57,15 +54,15 @@ impl InstallMode {
|
||||
|
||||
thread::spawn(move || {
|
||||
if let Err(err) = install(script_dir.as_path(), game, &progress_tx) {
|
||||
progress_tx.send(Progress::Error(err)).unwrap();
|
||||
let _ = progress_tx.send(Progress::Error(err));
|
||||
return;
|
||||
}
|
||||
progress_tx.send(Progress::Complete).unwrap();
|
||||
let _ = progress_tx.send(Progress::Complete);
|
||||
});
|
||||
|
||||
Self {
|
||||
progress_rx: Some(progress_rx),
|
||||
current_progress: CurrentProgress::Starting,
|
||||
status: String::from("Starting installation..."),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,20 +80,13 @@ impl InstallMode {
|
||||
if let Some(progress_rx) = &self.progress_rx {
|
||||
loop {
|
||||
match progress_rx.try_recv() {
|
||||
Ok(Progress::Download(progress)) => {
|
||||
self.current_progress = CurrentProgress::Download(progress);
|
||||
}
|
||||
Ok(Progress::Status(msg)) => {
|
||||
self.current_progress = CurrentProgress::Status(msg);
|
||||
}
|
||||
Ok(Progress::Complete) => {
|
||||
return Ok(Some(ModeTransition::PoB));
|
||||
}
|
||||
Ok(Progress::Status(msg)) => self.status = msg,
|
||||
Ok(Progress::Complete) => return Ok(Some(ModeTransition::PoB)),
|
||||
Ok(Progress::Error(err)) => {
|
||||
return Err(anyhow::anyhow!("Download failed: {}", err));
|
||||
return Err(anyhow::anyhow!("Installation failed: {err}"));
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
return Err(anyhow::anyhow!("Download thread disconnected!"));
|
||||
return Err(anyhow::anyhow!("Install thread disconnected unexpectedly"));
|
||||
}
|
||||
Err(TryRecvError::Empty) => {
|
||||
break;
|
||||
@@ -129,24 +119,10 @@ impl InstallMode {
|
||||
FontStyle::Normal,
|
||||
);
|
||||
|
||||
let progress_text = match &self.current_progress {
|
||||
CurrentProgress::Starting => String::from("Starting download..."),
|
||||
CurrentProgress::Status(msg) => msg.clone(),
|
||||
CurrentProgress::Download(progress) => match progress {
|
||||
DownloadProgress::Percentage(progress) => {
|
||||
let percent = (progress * 100.0) as u32;
|
||||
format!("Downloading assets... ({})", percent)
|
||||
}
|
||||
DownloadProgress::TotalBytes(total_bytes) => {
|
||||
format!("Downloading assets... ({})", format_bytes(*total_bytes))
|
||||
}
|
||||
},
|
||||
};
|
||||
job.append(&progress_text, Srgba::WHITE);
|
||||
job.append(&self.status, Srgba::WHITE);
|
||||
|
||||
let layout = app_state.fonts.layout(job, app_state.window.scale_factor());
|
||||
|
||||
// center text vertically and horizontally
|
||||
let screen_size = app_state.window.logical_size().cast::<f32>();
|
||||
let pos = LogicalPoint::new(screen_size.width / 2.0, screen_size.height / 2.0);
|
||||
|
||||
@@ -157,52 +133,62 @@ impl InstallMode {
|
||||
primitive: DrawPrimitive::Text(primitive),
|
||||
};
|
||||
|
||||
let primitives = vec![clipped_primitive];
|
||||
Box::new(primitives.into_iter())
|
||||
Box::new(vec![clipped_primitive].into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function for writing status to both the message channel and the log
|
||||
fn report(tx: &mpsc::Sender<Progress>, msg: impl Into<String>) {
|
||||
let msg = msg.into();
|
||||
log::info!("{msg}");
|
||||
let _ = tx.send(Progress::Status(msg));
|
||||
}
|
||||
|
||||
/// Performs full installation of PoB assets into `target_dir`.
|
||||
///
|
||||
/// Skips installation if `rpob.version` already exists.
|
||||
///
|
||||
/// Steps:
|
||||
/// 1. Fetch the compatibility table to determine which PoB version is
|
||||
/// supported by the current Rusty PoB version.
|
||||
/// 2. Download and extract the PoB release tarball into `target_dir`.
|
||||
/// 3. Replace `UpdateCheck.lua` with a patched version and update its
|
||||
/// checksum in `manifest.xml`. This is needed to support PoB native updater.
|
||||
/// 4. Set the branch and platform fields in `manifest.xml`.
|
||||
/// 5. Write `rpob.version` to mark the installation as complete.
|
||||
fn install<P: AsRef<Path>>(
|
||||
target_dir: P,
|
||||
game: Game,
|
||||
progress_tx: &mpsc::Sender<Progress>,
|
||||
) -> anyhow::Result<()> {
|
||||
// Skip installation if version file exists
|
||||
let current_version = env!("CARGO_PKG_VERSION");
|
||||
let version_file_path = target_dir.as_ref().join("rpob.version");
|
||||
if version_file_path.exists() {
|
||||
let old_version = fs::read_to_string(&version_file_path).unwrap();
|
||||
let target_dir = target_dir.as_ref();
|
||||
let client = build_client()?;
|
||||
|
||||
let version_file_path = target_dir.join("rpob.version");
|
||||
let current_version = env!("CARGO_PKG_VERSION");
|
||||
if version_file_path.exists() {
|
||||
let old_version = fs::read_to_string(&version_file_path)?;
|
||||
if old_version != current_version {
|
||||
log::info!("New version detected: {old_version} -> {current_version}");
|
||||
log::info!("Version changed: {old_version} -> {current_version}");
|
||||
fs::write(&version_file_path, current_version).unwrap();
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
progress_tx.send(Progress::Status("Fetching compatibility info...".into()))?;
|
||||
log::info!("Fetching compatibility info...");
|
||||
let compatibility_info = fetch_compatibility_info(game)?;
|
||||
|
||||
progress_tx.send(Progress::Status("Resolving PoB version...".into()))?;
|
||||
log::info!("Resolving supported PoB version...");
|
||||
let needed_pob_version = highest_supported_pob_version(&compatibility_info, current_version)
|
||||
report(progress_tx, "Fetching compatibility info...");
|
||||
let compat_info = fetch_compatibility_info(&client, game)?;
|
||||
let pob_version = highest_supported_pob_version(&compat_info, current_version)
|
||||
.ok_or_else(|| anyhow::anyhow!("Unable to determine supported PoB version"))?;
|
||||
log::info!("Using PoB version: {needed_pob_version}");
|
||||
log::info!("Using PoB version: {pob_version}");
|
||||
|
||||
progress_tx.send(Progress::Status("Downloading assets...".into()))?;
|
||||
download_path_of_building(&target_dir, game, needed_pob_version, progress_tx)?;
|
||||
report(progress_tx, "Downloading assets...");
|
||||
download_pob(&client, target_dir, game, pob_version, progress_tx)?;
|
||||
|
||||
progress_tx.send(Progress::Status("Patching UpdateCheck...".into()))?;
|
||||
log::info!("Patching UpdateCheck...");
|
||||
replace_updatecheck(&target_dir)?;
|
||||
report(progress_tx, "Finalizing installation...");
|
||||
replace_updatecheck(&client, target_dir)?;
|
||||
set_branch_and_platform(target_dir)?;
|
||||
|
||||
progress_tx.send(Progress::Status("Finalizing installation...".into()))?;
|
||||
log::info!("Finalizing installation...");
|
||||
set_branch_and_platform(&target_dir)?;
|
||||
|
||||
fs::write(&version_file_path, env!("CARGO_PKG_VERSION")).unwrap();
|
||||
fs::write(&version_file_path, current_version)?;
|
||||
log::info!("Installation complete.");
|
||||
|
||||
Ok(())
|
||||
@@ -214,28 +200,28 @@ struct VersionReq {
|
||||
min_rpob_ver: String,
|
||||
}
|
||||
|
||||
/// Fetches and evaluates compatibility table
|
||||
fn fetch_compatibility_info(game: Game) -> anyhow::Result<Vec<VersionReq>> {
|
||||
let compatibility_info_file_name = match game {
|
||||
/// Fetches compatibility info
|
||||
fn fetch_compatibility_info(
|
||||
client: &reqwest::blocking::Client,
|
||||
game: Game,
|
||||
) -> anyhow::Result<Vec<VersionReq>> {
|
||||
let file_name = match game {
|
||||
Game::Poe1 => "Compatibility_pob1.lua",
|
||||
Game::Poe2 => "Compatibility_pob2.lua",
|
||||
};
|
||||
|
||||
let compatibility_info_file_url = &format!(
|
||||
"https://raw.githubusercontent.com/{REPO_NAME}/main/{}",
|
||||
compatibility_info_file_name
|
||||
);
|
||||
|
||||
let compatibility_info_file = download_file_contents(compatibility_info_file_url)?;
|
||||
let compatibility_info_file = fetch_file_contents(client, COMPAT_REPO, file_name)?;
|
||||
|
||||
// Load and evaluate compatibility file contents as Lua code
|
||||
let lua = mlua::Lua::new();
|
||||
let compatibility_table = lua.load(compatibility_info_file).eval::<mlua::Table>()?;
|
||||
|
||||
// Compatibility table maps PoB version to minimum required Rusty PoB version
|
||||
// Compatibility table maps PoB version to minimum required Rusty PoB version.
|
||||
// Beta versions have a non-semver suffix and are filtered out by the regex.
|
||||
Ok(compatibility_table
|
||||
.pairs::<String, String>()
|
||||
.filter_map(|p| p.ok())
|
||||
.filter(|(pob_version, _)| VERSION_RE.is_match(pob_version))
|
||||
.map(|(pob_version, min_req_rpob_ver)| VersionReq {
|
||||
pob_ver: pob_version,
|
||||
min_rpob_ver: min_req_rpob_ver,
|
||||
@@ -243,206 +229,147 @@ fn fetch_compatibility_info(game: Game) -> anyhow::Result<Vec<VersionReq>> {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Determines highest PoB version supported by given Rusty PoB version
|
||||
/// Determines the highest PoB version supported by the given Rusty PoB version.
|
||||
fn highest_supported_pob_version<'a>(
|
||||
compatibility_info: &'a Vec<VersionReq>,
|
||||
compatibility_info: &'a [VersionReq],
|
||||
rpob_version: &str,
|
||||
) -> Option<&'a str> {
|
||||
let mut highest_pob_version = None;
|
||||
let mut highest: Option<&str> = None;
|
||||
for VersionReq {
|
||||
pob_ver,
|
||||
min_rpob_ver,
|
||||
} in compatibility_info
|
||||
{
|
||||
if is_higher_version(min_rpob_ver, rpob_version).unwrap_or(false) {
|
||||
// found PoB version that meets our minimum requirements
|
||||
match highest_pob_version {
|
||||
// make sure it is the highest PoB version possible
|
||||
Some(h_pob_version) => {
|
||||
if is_higher_version(h_pob_version, pob_ver).unwrap_or(false) {
|
||||
highest_pob_version = Some(pob_ver.as_str());
|
||||
}
|
||||
}
|
||||
None => highest_pob_version = Some(pob_ver.as_str()),
|
||||
match highest {
|
||||
Some(h) if !is_higher_version(h, pob_ver).unwrap_or(false) => {}
|
||||
_ => highest = Some(pob_ver.as_str()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
highest_pob_version
|
||||
highest
|
||||
}
|
||||
|
||||
/// Downloads specified version of Path of Building
|
||||
fn download_path_of_building<P: AsRef<Path>>(
|
||||
fn download_pob<P: AsRef<Path>>(
|
||||
client: &reqwest::blocking::Client,
|
||||
target_dir: P,
|
||||
game: Game,
|
||||
pob_version: &str,
|
||||
progress_tx: &mpsc::Sender<Progress>,
|
||||
) -> anyhow::Result<()> {
|
||||
log::info!("Downloading Path of Building assets...");
|
||||
let target_dir = target_dir.as_ref();
|
||||
|
||||
let repo = match game {
|
||||
let pob_repo = match game {
|
||||
Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding",
|
||||
Game::Poe2 => "PathOfBuildingCommunity/PathOfBuilding-PoE2",
|
||||
};
|
||||
let url = format!(
|
||||
"https://github.com/{}/archive/refs/tags/v{}.tar.gz",
|
||||
repo, pob_version
|
||||
);
|
||||
|
||||
let mut response = http_get_with_backoff(&url)?;
|
||||
let total_size = response
|
||||
.headers()
|
||||
.get("Content-Length")
|
||||
.and_then(|s| s.to_str().ok()?.parse::<u64>().ok());
|
||||
let rules = vec![
|
||||
ExtractionRule::File {
|
||||
tarball_path: "manifest.xml".into(),
|
||||
dest_path: target_dir.join("manifest.xml"),
|
||||
},
|
||||
ExtractionRule::File {
|
||||
tarball_path: "help.txt".into(),
|
||||
dest_path: target_dir.join("help.txt"),
|
||||
},
|
||||
ExtractionRule::File {
|
||||
tarball_path: "changelog.txt".into(),
|
||||
dest_path: target_dir.join("changelog.txt"),
|
||||
},
|
||||
ExtractionRule::File {
|
||||
tarball_path: "LICENSE.md".into(),
|
||||
dest_path: target_dir.join("LICENSE.md"),
|
||||
},
|
||||
ExtractionRule::RewritePrefix {
|
||||
prefix: "src/".into(),
|
||||
dest_dir: target_dir.to_path_buf(),
|
||||
},
|
||||
ExtractionRule::RewritePrefix {
|
||||
prefix: "runtime/lua/".into(),
|
||||
dest_dir: target_dir.join("lua"),
|
||||
},
|
||||
];
|
||||
|
||||
let body_reader = response.body_mut().as_reader();
|
||||
let mut archive = tar::Archive::new(GzDecoder::new(body_reader));
|
||||
let mut downloaded = 0u64;
|
||||
|
||||
for file in archive.entries()? {
|
||||
let mut file = file?;
|
||||
let file_path = file.path()?;
|
||||
let components: Vec<_> = file_path.components().collect();
|
||||
|
||||
let target_path = match components.len() {
|
||||
0..=1 => None,
|
||||
// put these into target_dir/
|
||||
2 => {
|
||||
let filename = components[1].as_os_str();
|
||||
if filename == "manifest.xml"
|
||||
|| filename == "help.txt"
|
||||
|| filename == "changelog.txt"
|
||||
|| filename == "LICENSE.md"
|
||||
{
|
||||
Some(target_dir.as_ref().join(filename))
|
||||
} else {
|
||||
None
|
||||
download_and_extract_tarball(
|
||||
&client,
|
||||
pob_repo,
|
||||
&format!("v{pob_version}"),
|
||||
&rules,
|
||||
5,
|
||||
&mut |event| {
|
||||
let msg = match event {
|
||||
DownloadEvent::Progress {
|
||||
downloaded,
|
||||
total: Some(total),
|
||||
} => {
|
||||
let pct = (downloaded as f32 / total as f32 * 100.0) as u32;
|
||||
format!("Downloading assets... ({pct}%)")
|
||||
}
|
||||
}
|
||||
// put lua runtime files into target_dir/lua/
|
||||
3.. => {
|
||||
if components[1].as_os_str() == "src"
|
||||
|| (components[1].as_os_str() == "runtime"
|
||||
&& components[2].as_os_str() == "lua")
|
||||
{
|
||||
Some(
|
||||
target_dir
|
||||
.as_ref()
|
||||
.join(components[2..].iter().collect::<PathBuf>()),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
DownloadEvent::Progress {
|
||||
downloaded,
|
||||
total: None,
|
||||
} => {
|
||||
format!("Downloading assets... ({})", format_bytes(downloaded))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// create needed directories and extract
|
||||
if let Some(target_path) = target_path {
|
||||
if let Some(parent) = target_path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
file.unpack(&target_path)?;
|
||||
}
|
||||
|
||||
downloaded += file.size();
|
||||
|
||||
if let Some(total) = total_size {
|
||||
let progress = downloaded as f32 / total as f32;
|
||||
progress_tx.send(Progress::Download(DownloadProgress::Percentage(progress)))?;
|
||||
} else {
|
||||
progress_tx.send(Progress::Download(DownloadProgress::TotalBytes(downloaded)))?;
|
||||
}
|
||||
}
|
||||
|
||||
DownloadEvent::Retrying { attempt } => {
|
||||
format!("Retrying... (Attempt {})", attempt)
|
||||
}
|
||||
};
|
||||
let _ = progress_tx.send(Progress::Status(msg));
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replaces UpdateCheck with rusty-path-of-building's modified version
|
||||
fn replace_updatecheck<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
|
||||
log::info!("Downloading modified UpdateCheck.lua script...");
|
||||
/// Replaces UpdateCheck.lua with rusty-path-of-building's modified version and
|
||||
/// updates its checksum in manifest.xml.
|
||||
fn replace_updatecheck<P: AsRef<Path>>(
|
||||
client: &reqwest::blocking::Client,
|
||||
target_dir: P,
|
||||
) -> anyhow::Result<()> {
|
||||
let target_dir = target_dir.as_ref();
|
||||
let file_name = "UpdateCheck.lua";
|
||||
|
||||
download_file(
|
||||
&format!(
|
||||
"https://raw.githubusercontent.com/{REPO_NAME}/main/{}",
|
||||
"UpdateCheck.lua"
|
||||
),
|
||||
target_dir.as_ref().join("UpdateCheck.lua"),
|
||||
)?;
|
||||
download_file_to_disk(client, COMPAT_REPO, file_name, target_dir.join(file_name))?;
|
||||
|
||||
// Replace original checksum with checksum of modified update script
|
||||
let new_checksum = download_file_contents(&format!(
|
||||
"https://raw.githubusercontent.com/{REPO_NAME}/main/{}",
|
||||
"UpdateCheck.lua.sha1"
|
||||
))?;
|
||||
|
||||
// file contains checksum followed by filename (separated by whitespace)
|
||||
// we only need the checksum
|
||||
let new_checksum = new_checksum
|
||||
// .sha1 file format: "<checksum> UpdateCheck.lua" - we only need the checksum.
|
||||
let sha1_contents = fetch_file_contents(client, COMPAT_REPO, "UpdateCheck.lua.sha1")?;
|
||||
let new_checksum = sha1_contents
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("Invalid checksum file"))?;
|
||||
|
||||
let filename = target_dir.as_ref().join("manifest.xml");
|
||||
let manifest = fs::read_to_string(&filename)?;
|
||||
.ok_or_else(|| anyhow::anyhow!("Invalid checksum file format"))?;
|
||||
|
||||
let manifest_path = target_dir.join("manifest.xml");
|
||||
let manifest = fs::read_to_string(&manifest_path)?;
|
||||
let new_manifest = replace_in_matching_lines(
|
||||
&manifest,
|
||||
r#"name="UpdateCheck.lua""#,
|
||||
r#"sha1="([0-9A-Za-z]+)""#,
|
||||
&format!(r#"sha1="{}""#, new_checksum),
|
||||
&format!(r#"sha1="{new_checksum}""#),
|
||||
);
|
||||
|
||||
fs::write(&filename, &new_manifest)?;
|
||||
fs::write(&manifest_path, &new_manifest)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets branch and platform in manifest.xml
|
||||
fn set_branch_and_platform<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
|
||||
let filename = target_dir.as_ref().join("manifest.xml");
|
||||
let manifest = fs::read_to_string(&filename)?;
|
||||
let path = target_dir.as_ref().join("manifest.xml");
|
||||
let manifest = fs::read_to_string(&path)?;
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let platform = std::env::consts::OS;
|
||||
#[cfg(target_os = "windows")]
|
||||
let platform = "win32";
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let platform = std::env::consts::OS;
|
||||
|
||||
let new_version = format!(r#"<Version branch="master" platform="{}""#, platform);
|
||||
|
||||
let version_regex = Regex::new(r"<Version").unwrap();
|
||||
let new_manifest = version_regex.replace(&manifest, new_version);
|
||||
|
||||
fs::write(&filename, new_manifest.as_ref())?;
|
||||
let replacement = format!(r#"<Version branch="master" platform="{platform}""#);
|
||||
let new_manifest = MANIFEST_VERSION_RE.replace(&manifest, replacement);
|
||||
fs::write(&path, new_manifest.as_ref())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Downloads file and saves it to given path
|
||||
fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()> {
|
||||
let mut response = http_get_with_backoff(url)?;
|
||||
|
||||
if response.status().is_success() {
|
||||
let body = response.body_mut();
|
||||
let mut file = fs::File::create(file_path)?;
|
||||
copy(&mut body.as_reader(), &mut file)?;
|
||||
Ok(())
|
||||
} else {
|
||||
anyhow::bail!("Unable to download: {}", url);
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads file and returns contents as string
|
||||
fn download_file_contents(url: &str) -> anyhow::Result<String> {
|
||||
let mut response = http_get_with_backoff(url)?;
|
||||
|
||||
if response.status().is_success() {
|
||||
let body = response.body_mut();
|
||||
Ok(body.read_to_string()?)
|
||||
} else {
|
||||
anyhow::bail!("Unable to download: {}", url);
|
||||
}
|
||||
}
|
||||
|
||||
fn format_bytes(size_in_bytes: u64) -> String {
|
||||
const KB: u64 = 1024;
|
||||
const MB: u64 = KB * 1024;
|
||||
@@ -455,125 +382,14 @@ fn format_bytes(size_in_bytes: u64) -> String {
|
||||
} else if size_in_bytes >= KB {
|
||||
format!("{:.2} KB", size_in_bytes as f64 / KB as f64)
|
||||
} else {
|
||||
format!("{} bytes", size_in_bytes)
|
||||
format!("{size_in_bytes} bytes")
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculates wait time based on rate limit headers or falls back to default backoff.
|
||||
fn calculate_wait_time(resp: &Response<ureq::Body>, default_backoff: u64) -> u64 {
|
||||
let headers = resp.headers();
|
||||
|
||||
// Wait for time specified in retry-after response header if present
|
||||
if let Some(retry_after) = headers
|
||||
.get("retry-after")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.parse::<u64>().ok())
|
||||
{
|
||||
return retry_after;
|
||||
}
|
||||
|
||||
// The number of requests remaining in the current rate limit window
|
||||
let remaining = headers
|
||||
.get("x-ratelimit-remaining")
|
||||
.and_then(|v| v.to_str().ok());
|
||||
|
||||
if remaining == Some("0") {
|
||||
// Calculate time until rate limit reset
|
||||
if let Some(reset_epoch) = headers
|
||||
.get("x-ratelimit-reset")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.parse::<u64>().ok())
|
||||
{
|
||||
let now_epoch = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
|
||||
if reset_epoch > now_epoch {
|
||||
return reset_epoch - now_epoch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
default_backoff
|
||||
}
|
||||
|
||||
/// Performs a GET request with exponential backoff aware of GitHub rate limit headers.
|
||||
fn http_get_with_backoff(url: &str) -> anyhow::Result<Response<ureq::Body>> {
|
||||
const MAX_ATTEMPTS: usize = 6;
|
||||
const MAX_BACKOFF_SECS: u64 = 60;
|
||||
let mut attempt = 0;
|
||||
let mut backoff_secs: u64 = 2;
|
||||
|
||||
let config = Agent::config_builder()
|
||||
.timeout_global(Some(Duration::from_secs(10)))
|
||||
.build();
|
||||
|
||||
let agent: Agent = config.into();
|
||||
|
||||
loop {
|
||||
attempt += 1;
|
||||
let resp_result = agent
|
||||
.get(url)
|
||||
.header("User-Agent", "rusty-path-of-building")
|
||||
.call();
|
||||
|
||||
let resp = match resp_result {
|
||||
Ok(r) => r,
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"Transport error: {} (attempt {}/{})",
|
||||
err,
|
||||
attempt,
|
||||
MAX_ATTEMPTS
|
||||
);
|
||||
if attempt >= MAX_ATTEMPTS {
|
||||
return Err(anyhow::Error::new(err));
|
||||
}
|
||||
thread::sleep(Duration::from_secs(backoff_secs));
|
||||
backoff_secs = (backoff_secs * 2).min(MAX_BACKOFF_SECS);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == 403 || status == 429 {
|
||||
let wait = calculate_wait_time(&resp, backoff_secs);
|
||||
|
||||
log::warn!(
|
||||
"Rate limited (status {}). Waiting {}s before retry (attempt {}/{})",
|
||||
status,
|
||||
wait,
|
||||
attempt,
|
||||
MAX_ATTEMPTS
|
||||
);
|
||||
if attempt >= MAX_ATTEMPTS {
|
||||
return Err(anyhow::anyhow!(
|
||||
"HTTP {} after {} attempts for {}",
|
||||
status,
|
||||
attempt,
|
||||
url
|
||||
));
|
||||
}
|
||||
thread::sleep(Duration::from_secs(wait));
|
||||
backoff_secs = (backoff_secs * 2).min(MAX_BACKOFF_SECS);
|
||||
continue;
|
||||
}
|
||||
|
||||
if status.is_client_error() || status.is_server_error() {
|
||||
return Err(anyhow::anyhow!("http status: {} for {}", status, url));
|
||||
}
|
||||
|
||||
return Ok(resp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares two SemVer versions and returns true if v2 is higher or equal than v1
|
||||
/// Returns true if `v2` is greater than or equal to `v1`.
|
||||
fn is_higher_version(v1: &str, v2: &str) -> anyhow::Result<bool> {
|
||||
let re = Regex::new(r"^(\d+)\.(\d+)\.(\d+)$").unwrap();
|
||||
|
||||
let parse_version = |v: &str| -> anyhow::Result<(u32, u32, u32)> {
|
||||
let caps = re
|
||||
let caps = VERSION_RE
|
||||
.captures(v)
|
||||
.ok_or_else(|| anyhow::anyhow!("Invalid semver format: {}", v))?;
|
||||
|
||||
@@ -598,25 +414,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_major_version() {
|
||||
assert_eq!(is_higher_version("1.0.0", "2.0.0").unwrap(), true);
|
||||
assert_eq!(is_higher_version("2.0.0", "1.0.0").unwrap(), false);
|
||||
assert!(is_higher_version("1.0.0", "2.0.0").unwrap());
|
||||
assert!(!is_higher_version("2.0.0", "1.0.0").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_minor_version() {
|
||||
assert_eq!(is_higher_version("1.5.0", "1.6.0").unwrap(), true);
|
||||
assert_eq!(is_higher_version("1.10.0", "1.9.0").unwrap(), false);
|
||||
assert!(is_higher_version("1.5.0", "1.6.0").unwrap());
|
||||
assert!(!is_higher_version("1.10.0", "1.9.0").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_patch_version() {
|
||||
assert_eq!(is_higher_version("1.0.3", "1.0.4").unwrap(), true);
|
||||
assert_eq!(is_higher_version("1.0.10", "1.0.9").unwrap(), false);
|
||||
assert!(is_higher_version("1.0.3", "1.0.4").unwrap());
|
||||
assert!(!is_higher_version("1.0.10", "1.0.9").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_same_version() {
|
||||
assert_eq!(is_higher_version("1.5.3", "1.5.3").unwrap(), true);
|
||||
assert!(is_higher_version("1.5.3", "1.5.3").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -631,33 +447,33 @@ mod tests {
|
||||
fn test_highest_supported_pob_ver() {
|
||||
let compat_info = vec![
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.56.0"),
|
||||
min_rpob_ver: String::from("0.1.0"),
|
||||
pob_ver: "2.56.0".into(),
|
||||
min_rpob_ver: "0.1.0".into(),
|
||||
},
|
||||
// compat info might not be sorted by pob_version
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.58.0"),
|
||||
min_rpob_ver: String::from("0.2.6"),
|
||||
pob_ver: "2.58.0".into(),
|
||||
min_rpob_ver: "0.2.6".into(),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.57.0"),
|
||||
min_rpob_ver: String::from("0.2.6"),
|
||||
pob_ver: "2.57.0".into(),
|
||||
min_rpob_ver: "0.2.6".into(),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.58.1"),
|
||||
min_rpob_ver: String::from("0.2.8"),
|
||||
pob_ver: "2.58.1".into(),
|
||||
min_rpob_ver: "0.2.8".into(),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.59.0"),
|
||||
min_rpob_ver: String::from("0.2.9"),
|
||||
pob_ver: "2.59.0".into(),
|
||||
min_rpob_ver: "0.2.9".into(),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.59.1"),
|
||||
min_rpob_ver: String::from("0.2.10"),
|
||||
pob_ver: "2.59.1".into(),
|
||||
min_rpob_ver: "0.2.10".into(),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.59.2"),
|
||||
min_rpob_ver: String::from("0.2.10"),
|
||||
pob_ver: "2.59.2".into(),
|
||||
min_rpob_ver: "0.2.10".into(),
|
||||
},
|
||||
];
|
||||
assert_eq!(highest_supported_pob_version(&compat_info, "0.0.2"), None);
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
use std::{
|
||||
fmt,
|
||||
fs::{self, File},
|
||||
io::{self, Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use flate2::read::GzDecoder;
|
||||
use reqwest::blocking::{Client, Response};
|
||||
use tar::Archive;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum DownloadEvent {
|
||||
Progress { downloaded: u64, total: Option<u64> },
|
||||
Retrying { attempt: u32 },
|
||||
}
|
||||
|
||||
/// Build a reqwest blocking client
|
||||
pub fn build_client() -> Result<Client, reqwest::Error> {
|
||||
Client::builder().timeout(Duration::from_secs(60)).build()
|
||||
}
|
||||
|
||||
// Rate-limit-aware GET.
|
||||
//
|
||||
// `raw.githubusercontent.com` doesn't seem to use `x-ratelimit-reset` and
|
||||
// `x-ratelimit-remaining` headers like the API so only the status code is checked.
|
||||
fn get_checked(client: &Client, url: &str) -> Result<Response, GithubError> {
|
||||
let response = client.get(url).send()?;
|
||||
let status = response.status();
|
||||
|
||||
if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
|
||||
let retry_after_secs = response
|
||||
.headers()
|
||||
.get("retry-after")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.parse::<u64>().ok())
|
||||
.unwrap_or(60);
|
||||
return Err(GithubError::RateLimited {
|
||||
retry_after_s: retry_after_secs,
|
||||
});
|
||||
}
|
||||
|
||||
if !status.is_success() {
|
||||
return Err(GithubError::Http {
|
||||
status: status.as_u16(),
|
||||
url: url.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Wrapper to retry `f` up to `max_retries` times
|
||||
pub fn with_retry<T, F>(max_retries: u32, base_delay: Duration, mut f: F) -> Result<T, GithubError>
|
||||
where
|
||||
F: FnMut(u32) -> Result<T, GithubError>,
|
||||
{
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
match f(attempt) {
|
||||
Err(GithubError::RateLimited {
|
||||
retry_after_s: retry_after_secs,
|
||||
}) if attempt < max_retries => {
|
||||
log::warn!("Rate limited – sleeping {retry_after_secs}s (attempt {attempt})");
|
||||
thread::sleep(Duration::from_secs(retry_after_secs));
|
||||
attempt += 1;
|
||||
}
|
||||
Err(GithubError::Network(e)) if attempt < max_retries => {
|
||||
let delay = base_delay * (attempt + 1);
|
||||
log::warn!("Network error on attempt {attempt}: {e}. Retrying in {delay:?}");
|
||||
thread::sleep(delay);
|
||||
attempt += 1;
|
||||
}
|
||||
other => return other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Download file contents from raw.githubusercontent.com into a `String`.
|
||||
pub fn fetch_file_contents(
|
||||
client: &Client,
|
||||
repo: &str,
|
||||
file_name: &str,
|
||||
) -> Result<String, GithubError> {
|
||||
let url = format!("https://raw.githubusercontent.com/{repo}/main/{file_name}");
|
||||
let response = get_checked(client, &url)?;
|
||||
Ok(response.text()?)
|
||||
}
|
||||
|
||||
/// Download a file from raw.githubusercontent.com and write it to `dest_path`.
|
||||
pub fn download_file_to_disk<P: AsRef<Path>>(
|
||||
client: &Client,
|
||||
repo: &str,
|
||||
file_name: &str,
|
||||
dest_path: P,
|
||||
) -> Result<(), GithubError> {
|
||||
let dest_path = dest_path.as_ref();
|
||||
|
||||
let url = format!("https://raw.githubusercontent.com/{repo}/main/{file_name}");
|
||||
let mut response = get_checked(client, &url)?;
|
||||
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut file = File::create(dest_path)?;
|
||||
io::copy(&mut response, &mut file)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A rule describing how to map tarball entries to destination paths.
|
||||
///
|
||||
/// The root prefix is automatically striped and doesn't need to be specified.
|
||||
pub enum ExtractionRule {
|
||||
/// Map a single file to an exact destination path.
|
||||
File {
|
||||
tarball_path: String,
|
||||
dest_path: PathBuf,
|
||||
},
|
||||
/// Strip prefix from matching entries and place the remainder under `dest_dir`.
|
||||
RewritePrefix { prefix: String, dest_dir: PathBuf },
|
||||
}
|
||||
|
||||
/// Download a GitHub release tarball and extract entries to specified destinations.
|
||||
pub fn download_and_extract_tarball(
|
||||
client: &Client,
|
||||
repo_name: &str,
|
||||
tag: &str,
|
||||
rules: &[ExtractionRule],
|
||||
max_retries: u32,
|
||||
on_progress: &mut impl FnMut(DownloadEvent),
|
||||
) -> Result<(), GithubError> {
|
||||
let url = format!("https://github.com/{repo_name}/archive/refs/tags/{tag}.tar.gz");
|
||||
|
||||
let tmp_path =
|
||||
std::env::temp_dir().join(format!("gh-{}-{}.tar.gz", repo_name.replace('/', "-"), tag));
|
||||
|
||||
// Download to temp file
|
||||
with_retry(max_retries, Duration::from_secs(5), |attempt| {
|
||||
if attempt > 0 {
|
||||
on_progress(DownloadEvent::Retrying { attempt });
|
||||
}
|
||||
|
||||
let response = get_checked(client, &url)?;
|
||||
let content_length = response.content_length();
|
||||
|
||||
let mut tmp_file = File::create(&tmp_path)?;
|
||||
const CHUNK_SIZE: usize = 512 * 1024;
|
||||
let mut chunk = vec![0u8; CHUNK_SIZE];
|
||||
let mut downloaded: u64 = 0;
|
||||
let mut body = response;
|
||||
|
||||
let mut last_progress = Instant::now();
|
||||
const PROGRESS_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
loop {
|
||||
let n = body.read(&mut chunk)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
tmp_file.write_all(&chunk[..n])?;
|
||||
downloaded += n as u64;
|
||||
|
||||
if last_progress.elapsed() >= PROGRESS_INTERVAL {
|
||||
on_progress(DownloadEvent::Progress {
|
||||
downloaded,
|
||||
total: content_length,
|
||||
});
|
||||
last_progress = Instant::now();
|
||||
}
|
||||
}
|
||||
on_progress(DownloadEvent::Progress {
|
||||
downloaded,
|
||||
total: content_length,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
// Extract tarball to destination based on extract rules
|
||||
let tmp_file = File::open(&tmp_path)?;
|
||||
let gz = GzDecoder::new(io::BufReader::new(tmp_file));
|
||||
let mut archive = Archive::new(gz);
|
||||
|
||||
for entry_result in archive.entries()? {
|
||||
let mut entry = entry_result?;
|
||||
let entry_path = entry.path()?.to_path_buf();
|
||||
let entry_str = entry_path.to_string_lossy();
|
||||
|
||||
// Skip directory entries
|
||||
if entry_str.ends_with('/') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Strip root folder before matching against rules
|
||||
let relative = match entry_str.split_once('/') {
|
||||
Some((_, rest)) => rest,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let dest: Option<PathBuf> = rules.iter().find_map(|rule| match rule {
|
||||
ExtractionRule::File {
|
||||
tarball_path,
|
||||
dest_path,
|
||||
} => (tarball_path == relative).then(|| dest_path.clone()),
|
||||
ExtractionRule::RewritePrefix { prefix, dest_dir } => relative
|
||||
.strip_prefix(prefix)
|
||||
.map(|tail| dest_dir.join(tail)),
|
||||
});
|
||||
|
||||
if let Some(dest_path) = dest {
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut dest_file = File::create(&dest_path)?;
|
||||
io::copy(&mut entry, &mut dest_file)?;
|
||||
}
|
||||
}
|
||||
|
||||
fs::remove_file(&tmp_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum GithubError {
|
||||
Http { status: u16, url: String },
|
||||
RateLimited { retry_after_s: u64 },
|
||||
Network(reqwest::Error),
|
||||
Io(io::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for GithubError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Http { status, url } => write!(f, "HTTP error {status}: {url}"),
|
||||
Self::RateLimited { retry_after_s } => {
|
||||
write!(f, "Rate limited – retry after {retry_after_s}s")
|
||||
}
|
||||
Self::Network(e) => write!(f, "Network error: {e}"),
|
||||
Self::Io(e) => write!(f, "I/O error: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for GithubError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::Network(e) => Some(e),
|
||||
Self::Io(e) => Some(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<reqwest::Error> for GithubError {
|
||||
fn from(e: reqwest::Error) -> Self {
|
||||
Self::Network(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for GithubError {
|
||||
fn from(e: io::Error) -> Self {
|
||||
Self::Io(e)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user