This commit is contained in:
João Moreno 2021-10-27 15:53:05 +02:00
Родитель 52a4fdd030
Коммит 02a955cc10
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 896B853774D1A575
9 изменённых файлов: 107 добавлений и 89 удалений

Просмотреть файл

@ -12,14 +12,14 @@ use std::io::prelude::*;
const BLOCK_MAX_SIZE: usize = 4096;
pub struct BlockRead<'a> {
reader: &'a mut Read,
reader: &'a mut dyn Read,
buffer: [u8; BLOCK_MAX_SIZE],
pos: usize,
left: usize,
}
impl<'a> BlockRead<'a> {
pub fn new(reader: &'a mut Read) -> BlockRead<'a> {
pub fn new(reader: &'a mut dyn Read) -> BlockRead<'a> {
BlockRead {
reader,
buffer: [0; BLOCK_MAX_SIZE],
@ -95,13 +95,13 @@ impl<'a> Read for BlockRead<'a> {
}
pub struct BlockWrite<'a> {
writer: &'a mut Write,
writer: &'a mut dyn Write,
buffer: [u8; BLOCK_MAX_SIZE],
pos: usize,
}
impl<'a> BlockWrite<'a> {
pub fn new(writer: &'a mut Write) -> BlockWrite<'a> {
pub fn new(writer: &'a mut dyn Write) -> BlockWrite<'a> {
BlockWrite {
writer,
buffer: [0; BLOCK_MAX_SIZE],

Просмотреть файл

@ -27,8 +27,8 @@ unsafe extern "system" fn dlgproc(hwnd: HWND, msg: UINT, _: WPARAM, l: LPARAM) -
use winapi::um::commctrl::PBM_SETMARQUEE;
use winapi::um::processthreadsapi::GetCurrentThreadId;
use winapi::um::winuser::{
GetDesktopWindow, GetWindowRect, SendDlgItemMessageW, SetWindowPos, ShowWindow,
HWND_TOPMOST, SW_HIDE, WM_DESTROY, WM_INITDIALOG,
GetDesktopWindow, GetWindowRect, SendDlgItemMessageW, SetWindowPos, ShowWindow, HWND_TOPMOST,
SW_HIDE, WM_DESTROY, WM_INITDIALOG,
};
match msg {
@ -37,7 +37,7 @@ unsafe extern "system" fn dlgproc(hwnd: HWND, msg: UINT, _: WPARAM, l: LPARAM) -
if !data.silent {
SendDlgItemMessageW(hwnd, resources::PROGRESS_SLIDER, PBM_SETMARQUEE, 1, 0);
let mut rect: RECT = mem::uninitialized();
let mut rect = mem::MaybeUninit::<RECT>::uninit().assume_init();
GetWindowRect(hwnd, &mut rect);
let width = rect.right - rect.left;
@ -58,7 +58,8 @@ unsafe extern "system" fn dlgproc(hwnd: HWND, msg: UINT, _: WPARAM, l: LPARAM) -
ShowWindow(hwnd, SW_HIDE);
}
data.tx
data
.tx
.send(ProgressWindow {
ui_thread_id: GetCurrentThreadId(),
})
@ -130,8 +131,8 @@ pub enum MessageBoxResult {
pub fn message_box(text: &str, caption: &str, mbtype: MessageBoxType) -> MessageBoxResult {
use winapi::um::winuser::{
MessageBoxW, IDABORT, IDCANCEL, IDCONTINUE, IDIGNORE, IDNO, IDOK, IDRETRY, IDTRYAGAIN,
IDYES, MB_ICONERROR, MB_RETRYCANCEL, MB_SYSTEMMODAL,
MessageBoxW, IDABORT, IDCANCEL, IDCONTINUE, IDIGNORE, IDNO, IDOK, IDRETRY, IDTRYAGAIN, IDYES,
MB_ICONERROR, MB_RETRYCANCEL, MB_SYSTEMMODAL,
};
let result: i32;

Просмотреть файл

@ -12,7 +12,7 @@ use winapi::um::winnt::HANDLE;
pub struct FileHandle(HANDLE);
impl FileHandle {
pub fn new(path: &Path) -> Result<FileHandle, Box<error::Error>> {
pub fn new(path: &Path) -> Result<FileHandle, Box<dyn error::Error>> {
use winapi::um::fileapi::CreateFileW;
use winapi::um::fileapi::OPEN_EXISTING;
use winapi::um::handleapi::INVALID_HANDLE_VALUE;
@ -37,14 +37,15 @@ impl FileHandle {
"Failed to create file handle: {}",
util::get_last_error_message()?
),
).into());
)
.into());
}
Ok(FileHandle(handle))
}
}
pub fn mark_for_deletion(&self) -> Result<(), Box<error::Error>> {
pub fn mark_for_deletion(&self) -> Result<(), Box<dyn error::Error>> {
use std::mem;
use winapi::shared::minwindef::{DWORD, FALSE, LPVOID, TRUE};
use winapi::um::fileapi::SetFileInformationByHandle;
@ -67,14 +68,15 @@ impl FileHandle {
"Failed to mark file for deletion: {}",
util::get_last_error_message()?
),
).into());
)
.into());
}
}
Ok(())
}
pub fn close(&self) -> Result<(), Box<error::Error>> {
pub fn close(&self) -> Result<(), Box<dyn error::Error>> {
use winapi::shared::minwindef::FALSE;
use winapi::um::handleapi::CloseHandle;
@ -86,7 +88,8 @@ impl FileHandle {
"Failed to close file handle: {}",
util::get_last_error_message()?
),
).into());
)
.into());
}
}

Просмотреть файл

@ -35,7 +35,7 @@ use std::{env, error, fmt, fs, io, thread};
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn read_file(path: &Path) -> Result<(Header, Vec<FileRec>), Box<error::Error>> {
fn read_file(path: &Path) -> Result<(Header, Vec<FileRec>), Box<dyn error::Error>> {
let input_file = fs::File::open(path)?;
let mut input = io::BufReader::new(input_file);
@ -50,7 +50,11 @@ fn read_file(path: &Path) -> Result<(Header, Vec<FileRec>), Box<error::Error>> {
Ok((header, recs))
}
fn write_file(path: &Path, header: &Header, recs: Vec<FileRec>) -> Result<(), Box<error::Error>> {
fn write_file(
path: &Path,
header: &Header,
recs: Vec<FileRec>,
) -> Result<(), Box<dyn error::Error>> {
let mut output_file = fs::File::create(path)?;
// skip header
@ -88,7 +92,7 @@ fn delete_existing_version(
log: &slog::Logger,
root_path: &Path,
update_folder_name: &str,
) -> Result<(), Box<error::Error>> {
) -> Result<(), Box<dyn error::Error>> {
let mut directories: LinkedList<PathBuf> = LinkedList::new();
let mut top_directories: LinkedList<PathBuf> = LinkedList::new();
let mut file_handles: LinkedList<FileHandle> = LinkedList::new();
@ -139,7 +143,7 @@ fn delete_existing_version(
let msg = format!("Opening file handle: {:?}", entry_path);
let file_handle = util::retry(
&msg,
|attempt| -> Result<FileHandle, Box<error::Error>> {
|attempt| -> Result<FileHandle, Box<dyn error::Error>> {
info!(
log,
"Get file handle: {:?} (attempt {})", entry_path, attempt
@ -160,7 +164,7 @@ fn delete_existing_version(
for file_handle in &file_handles {
util::retry(
"marking a file for deletion",
|_| -> Result<(), Box<error::Error>> { file_handle.mark_for_deletion() },
|_| -> Result<(), Box<dyn error::Error>> { file_handle.mark_for_deletion() },
None,
)?;
}
@ -170,7 +174,7 @@ fn delete_existing_version(
for file_handle in &file_handles {
util::retry(
"closing a file handle",
|_| -> Result<(), Box<error::Error>> { file_handle.close() },
|_| -> Result<(), Box<dyn error::Error>> { file_handle.close() },
None,
)?;
}
@ -181,7 +185,7 @@ fn delete_existing_version(
let msg = format!("Deleting a directory: {:?}", dir);
util::retry(
&msg,
|attempt| -> Result<(), Box<error::Error>> {
|attempt| -> Result<(), Box<dyn error::Error>> {
if !dir.exists() {
return Ok(());
}
@ -205,7 +209,7 @@ fn move_update(
log: &slog::Logger,
uninstdat_path: &Path,
update_folder_name: &str,
) -> Result<(), Box<error::Error>> {
) -> Result<(), Box<dyn error::Error>> {
info!(
log,
"move_update: {:?}, {}", uninstdat_path, update_folder_name
@ -262,7 +266,7 @@ fn patch_uninstdat(
log: &slog::Logger,
uninstdat_path: &PathBuf,
update_folder_name: &str,
) -> Result<(), Box<error::Error>> {
) -> Result<(), Box<dyn error::Error>> {
let (header, recs) = read_file(&uninstdat_path)?;
info!(log, "header: {:?}", header);
@ -296,7 +300,7 @@ fn do_update(
log: &slog::Logger,
code_path: &PathBuf,
update_folder_name: &str,
) -> Result<(), Box<error::Error>> {
) -> Result<(), Box<dyn error::Error>> {
info!(log, "do_update: {:?}, {}", code_path, update_folder_name);
let root_path = code_path.parent().ok_or(io::Error::new(
@ -324,7 +328,7 @@ fn update(
code_path: &PathBuf,
update_folder_name: &str,
silent: bool,
) -> Result<(), Box<error::Error>> {
) -> Result<(), Box<dyn error::Error>> {
process::wait_or_kill(log, code_path)?;
info!(log, "Inno Updater v{}", VERSION);
@ -360,21 +364,24 @@ impl error::Error for ArgumentError {
"ArgumentError"
}
fn cause(&self) -> Option<&error::Error> {
fn cause(&self) -> Option<&dyn error::Error> {
None
}
}
fn _main(log: &slog::Logger, args: &Vec<String>) -> Result<(), Box<error::Error>> {
fn _main(log: &slog::Logger, args: &Vec<String>) -> Result<(), Box<dyn error::Error>> {
info!(log, "Starting: {}, {}", args[1], args[2]);
let code_path = PathBuf::from(&args[1]);
if !code_path.is_absolute() {
return Err(ArgumentError(format!(
"Code path needs to be absolute. Instead got: {}",
args[1]
)).into());
return Err(
ArgumentError(format!(
"Code path needs to be absolute. Instead got: {}",
args[1]
))
.into(),
);
}
if !code_path.exists() {
@ -384,10 +391,13 @@ fn _main(log: &slog::Logger, args: &Vec<String>) -> Result<(), Box<error::Error>
let silent = args[2].clone();
if silent != "true" && silent != "false" {
return Err(ArgumentError(format!(
"Silent needs to be true or false. Instead got: {}",
silent
)).into());
return Err(
ArgumentError(format!(
"Silent needs to be true or false. Instead got: {}",
silent
))
.into(),
);
}
update(log, &code_path, "_", silent == "true")
@ -441,7 +451,7 @@ fn __main(args: &Vec<String>) -> i32 {
}
}
fn parse(path: &Path) -> Result<(), Box<error::Error>> {
fn parse(path: &Path) -> Result<(), Box<dyn error::Error>> {
let (header, recs) = read_file(path)?;
println!("{:?}", header);
@ -498,7 +508,7 @@ fn main() {
let window = rx.recv().unwrap();
let result = util::retry(
"simulating a failed retry operation",
|_| -> Result<u32, Box<error::Error>> {
|_| -> Result<u32, Box<dyn error::Error>> {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"[[Simulated error message]]",

Просмотреть файл

@ -88,7 +88,7 @@ impl<'a> error::Error for StringDecodeError<'a> {
"StringDecodeError"
}
fn cause(&self) -> Option<&error::Error> {
fn cause(&self) -> Option<&dyn error::Error> {
None
}
}
@ -98,13 +98,13 @@ fn decode_strings<'a>(data: &[u8]) -> Result<Vec<String>, StringDecodeError<'a>>
let mut slice = data.clone();
loop {
let reader: &mut Read = &mut slice.clone();
let reader: &mut dyn Read = &mut slice.clone();
let byte_result = reader
.read_u8()
.map_err(|_| StringDecodeError("Failed to parse file rec string header"))?;
match byte_result {
0x00...0xfc => panic!("What 0x{:x}", byte_result),
0x00..=0xfc => panic!("What 0x{:x}", byte_result),
0xfd => panic!("What 0x{:x}", byte_result),
0xfe => {
let size = reader
@ -132,7 +132,6 @@ fn decode_strings<'a>(data: &[u8]) -> Result<Vec<String>, StringDecodeError<'a>>
}
return Ok(result);
}
_ => return Err(StringDecodeError("Invalid file rec string header")),
}
}
}
@ -151,7 +150,7 @@ impl<'a> error::Error for StringEncodeError<'a> {
"StringEncodeError"
}
fn cause(&self) -> Option<&error::Error> {
fn cause(&self) -> Option<&dyn error::Error> {
None
}
}
@ -199,7 +198,7 @@ impl<'a> error::Error for FileRecParseError<'a> {
"FileRecParseError"
}
fn cause(&self) -> Option<&error::Error> {
fn cause(&self) -> Option<&dyn error::Error> {
None
}
}
@ -218,7 +217,7 @@ impl<'a> error::Error for FileRecWriteError<'a> {
"FileRecWriteError"
}
fn cause(&self) -> Option<&error::Error> {
fn cause(&self) -> Option<&dyn error::Error> {
None
}
}
@ -237,13 +236,13 @@ impl error::Error for RebaseError {
"RebaseError"
}
fn cause(&self) -> Option<&error::Error> {
fn cause(&self) -> Option<&dyn error::Error> {
None
}
}
impl<'a> FileRec {
pub fn from_reader<'b>(reader: &mut Read) -> Result<FileRec, FileRecParseError<'b>> {
pub fn from_reader<'b>(reader: &mut dyn Read) -> Result<FileRec, FileRecParseError<'b>> {
let typ = reader
.read_u16::<LittleEndian>()
.map_err(|_| FileRecParseError("Failed to parse file rec typ"))?;
@ -252,8 +251,7 @@ impl<'a> FileRec {
.map_err(|_| FileRecParseError("Failed to parse file rec extra data"))?;
let data_size = reader
.read_u32::<LittleEndian>()
.map_err(|_| FileRecParseError("Failed to parse file rec data size"))?
as usize;
.map_err(|_| FileRecParseError("Failed to parse file rec data size"))? as usize;
if data_size > 0x8000000 {
return Err(FileRecParseError("File rec data size too large"));
@ -273,7 +271,7 @@ impl<'a> FileRec {
})
}
pub fn to_writer<'b>(&self, writer: &mut Write) -> Result<(), FileRecWriteError<'b>> {
pub fn to_writer<'b>(&self, writer: &mut dyn Write) -> Result<(), FileRecWriteError<'b>> {
writer
.write_u16::<LittleEndian>(self.typ as u16)
.map_err(|_| FileRecWriteError("Failed to write file rec typ to buffer"))?;
@ -293,7 +291,7 @@ impl<'a> FileRec {
Ok(())
}
pub fn rebase(&self, update_path: &Path) -> Result<FileRec, Box<error::Error>> {
pub fn rebase(&self, update_path: &Path) -> Result<FileRec, Box<dyn error::Error>> {
let paths = decode_strings(&self.data)?;
let from = update_path.to_str().ok_or(RebaseError)?;

Просмотреть файл

@ -24,7 +24,7 @@ impl<'a> error::Error for HeaderParseError<'a> {
"HeaderParseError"
}
fn cause(&self) -> Option<&error::Error> {
fn cause(&self) -> Option<&dyn error::Error> {
None
}
}
@ -43,7 +43,7 @@ impl<'a> error::Error for HeaderWriteError<'a> {
"HeaderWriteError"
}
fn cause(&self) -> Option<&error::Error> {
fn cause(&self) -> Option<&dyn error::Error> {
None
}
}
@ -85,7 +85,7 @@ impl fmt::Debug for Header {
}
impl Header {
pub fn from_reader<'a>(reader: &mut Read) -> Result<Header, HeaderParseError<'a>> {
pub fn from_reader<'a>(reader: &mut dyn Read) -> Result<Header, HeaderParseError<'a>> {
let mut buf = [0; HEADER_SIZE];
reader
.read_exact(&mut buf)
@ -101,9 +101,9 @@ impl Header {
let version = read
.read_i32::<LittleEndian>()
.map_err(|_| HeaderParseError("Failed to parse header version"))?;
let num_recs =
read.read_i32::<LittleEndian>()
.map_err(|_| HeaderParseError("Failed to parse header num recs"))? as usize;
let num_recs = read
.read_i32::<LittleEndian>()
.map_err(|_| HeaderParseError("Failed to parse header num recs"))? as usize;
let end_offset = read
.read_u32::<LittleEndian>()
.map_err(|_| HeaderParseError("Failed to parse header end offset"))?;
@ -112,7 +112,8 @@ impl Header {
.map_err(|_| HeaderParseError("Failed to parse header flags"))?;
let mut reserved = [0; 108];
read.read_exact(&mut reserved)
read
.read_exact(&mut reserved)
.map_err(|_| HeaderParseError("Failed to parse header reserved"))?;
let crc = read
@ -149,7 +150,7 @@ impl Header {
})
}
pub fn to_writer<'a>(&self, writer: &mut Write) -> Result<(), HeaderWriteError<'a>> {
pub fn to_writer<'a>(&self, writer: &mut dyn Write) -> Result<(), HeaderWriteError<'a>> {
let mut buf = [0; HEADER_SIZE];
{
let mut buf_writer: &mut [u8] = &mut buf;
@ -189,7 +190,7 @@ impl Header {
buf_writer
.write_u32::<LittleEndian>(crc)
.map_err(|_| HeaderWriteError("Failed to write header crc to buffer"))?;;
.map_err(|_| HeaderWriteError("Failed to write header crc to buffer"))?;
}
writer

Просмотреть файл

@ -18,8 +18,7 @@ pub struct RunningProcess {
pub fn get_running_processes() -> Result<Vec<RunningProcess>, io::Error> {
use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
use winapi::um::tlhelp32::{
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
TH32CS_SNAPPROCESS,
CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS,
};
unsafe {
@ -81,7 +80,7 @@ fn kill_process_if(
log: &slog::Logger,
process: &RunningProcess,
path: &Path,
) -> Result<(), Box<error::Error>> {
) -> Result<(), Box<dyn error::Error>> {
use winapi::shared::minwindef::MAX_PATH;
use winapi::um::handleapi::CloseHandle;
use winapi::um::processthreadsapi::{OpenProcess, TerminateProcess};
@ -102,13 +101,16 @@ fn kill_process_if(
);
if handle.is_null() {
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"Failed to open process: {}",
util::get_last_error_message()?
),
).into());
return Err(
io::Error::new(
io::ErrorKind::Other,
format!(
"Failed to open process: {}",
util::get_last_error_message()?
),
)
.into(),
);
}
let mut raw_path = [0u16; MAX_PATH];
@ -122,13 +124,16 @@ fn kill_process_if(
if len == 0 {
CloseHandle(handle);
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"Failed to get process file name: {}",
util::get_last_error_message()?
),
).into());
return Err(
io::Error::new(
io::ErrorKind::Other,
format!(
"Failed to get process file name: {}",
util::get_last_error_message()?
),
)
.into(),
);
}
let process_path = PathBuf::from(from_utf16(&raw_path[0..len])?);
@ -157,7 +162,7 @@ fn kill_process_if(
}
}
pub fn wait_or_kill(log: &slog::Logger, path: &Path) -> Result<(), Box<error::Error>> {
pub fn wait_or_kill(log: &slog::Logger, path: &Path) -> Result<(), Box<dyn error::Error>> {
let file_name = path.file_name().ok_or(io::Error::new(
io::ErrorKind::Other,
"Could not get process file name",

Просмотреть файл

@ -15,7 +15,10 @@ pub enum ReadUtf8StringError {
UTF8Error(string::FromUtf8Error),
}
pub fn read_utf8_string(reader: &mut Read, capacity: usize) -> Result<String, ReadUtf8StringError> {
pub fn read_utf8_string(
reader: &mut dyn Read,
capacity: usize,
) -> Result<String, ReadUtf8StringError> {
let mut vec = vec![0; capacity];
reader
@ -29,7 +32,7 @@ pub fn read_utf8_string(reader: &mut Read, capacity: usize) -> Result<String, Re
}
pub fn write_utf8_string(
writer: &mut Write,
writer: &mut dyn Write,
string: &String,
capacity: usize,
) -> Result<(), io::Error> {

Просмотреть файл

@ -18,9 +18,9 @@ use strings::from_utf16;
* - 25: ~4 minutes
* - 27: ~5 minutes
*/
pub fn retry<F, R, T>(task: &str, closure: F, max_attempts: T) -> Result<R, Box<error::Error>>
pub fn retry<F, R, T>(task: &str, closure: F, max_attempts: T) -> Result<R, Box<dyn error::Error>>
where
F: Fn(u32) -> Result<R, Box<error::Error>>,
F: Fn(u32) -> Result<R, Box<dyn error::Error>>,
T: Into<Option<u32>>,
{
let mut attempt: u32 = 0;
@ -35,11 +35,8 @@ where
Err(err) => {
if attempt >= max_attempts {
let msg = format!("There was an error while {}:\n\n{}\n\nPlease verify there are no Visual Studio Code processes still executing.", task, err);
let mb_result = gui::message_box(
&msg,
"Visual Studio Code",
gui::MessageBoxType::RetryCancel,
);
let mb_result =
gui::message_box(&msg, "Visual Studio Code", gui::MessageBoxType::RetryCancel);
match mb_result {
gui::MessageBoxResult::Retry => {
@ -57,7 +54,7 @@ where
}
}
pub fn get_last_error_message() -> Result<String, Box<error::Error>> {
pub fn get_last_error_message() -> Result<String, Box<dyn error::Error>> {
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::winbase::{
FormatMessageW, FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS,