Folder names (#318)

This commit is contained in:
Wyatt Verchere
2023-07-21 20:16:07 -07:00
committed by GitHub
parent 4941260805
commit 3fa33dc241
42 changed files with 1129 additions and 535 deletions

View File

@@ -112,7 +112,7 @@ pub async fn auto_install_java(java_version: u32) -> crate::Result<PathBuf> {
)
.await?;
let path = state.directories.java_versions_dir();
let path = state.directories.java_versions_dir().await;
if path.exists() {
io::remove_dir_all(&path).await?;

View File

@@ -1,6 +1,6 @@
use crate::{
util::io::{self, IOError},
State,
{state::ProfilePathId, State},
};
use serde::{Deserialize, Serialize};
@@ -11,7 +11,7 @@ pub struct Logs {
}
impl Logs {
async fn build(
profile_uuid: uuid::Uuid,
profile_subpath: &ProfilePathId,
datetime_string: String,
clear_contents: Option<bool>,
) -> crate::Result<Self> {
@@ -20,7 +20,7 @@ impl Logs {
None
} else {
Some(
get_output_by_datetime(profile_uuid, &datetime_string)
get_output_by_datetime(profile_subpath, &datetime_string)
.await?,
)
},
@@ -35,7 +35,18 @@ pub async fn get_logs(
clear_contents: Option<bool>,
) -> crate::Result<Vec<Logs>> {
let state = State::get().await?;
let logs_folder = state.directories.profile_logs_dir(profile_uuid);
let profile_path = if let Some(p) =
crate::profile::get_by_uuid(profile_uuid, None).await?
{
p.profile_id()
} else {
return Err(crate::ErrorKind::UnmanagedProfileError(
profile_uuid.to_string(),
)
.into());
};
let logs_folder = state.directories.profile_logs_dir(&profile_path).await?;
let mut logs = Vec::new();
if logs_folder.exists() {
for entry in std::fs::read_dir(&logs_folder)
@@ -48,7 +59,7 @@ pub async fn get_logs(
if let Some(datetime_string) = path.file_name() {
logs.push(
Logs::build(
profile_uuid,
&profile_path,
datetime_string.to_string_lossy().to_string(),
clear_contents,
)
@@ -69,9 +80,19 @@ pub async fn get_logs_by_datetime(
profile_uuid: uuid::Uuid,
datetime_string: String,
) -> crate::Result<Logs> {
let profile_path = if let Some(p) =
crate::profile::get_by_uuid(profile_uuid, None).await?
{
p.profile_id()
} else {
return Err(crate::ErrorKind::UnmanagedProfileError(
profile_uuid.to_string(),
)
.into());
};
Ok(Logs {
output: Some(
get_output_by_datetime(profile_uuid, &datetime_string).await?,
get_output_by_datetime(&profile_path, &datetime_string).await?,
),
datetime_string,
})
@@ -79,19 +100,31 @@ pub async fn get_logs_by_datetime(
#[tracing::instrument]
pub async fn get_output_by_datetime(
profile_uuid: uuid::Uuid,
profile_subpath: &ProfilePathId,
datetime_string: &str,
) -> crate::Result<String> {
let state = State::get().await?;
let logs_folder = state.directories.profile_logs_dir(profile_uuid);
let logs_folder =
state.directories.profile_logs_dir(profile_subpath).await?;
let path = logs_folder.join(datetime_string).join("stdout.log");
Ok(io::read_to_string(&path).await?)
}
#[tracing::instrument]
pub async fn delete_logs(profile_uuid: uuid::Uuid) -> crate::Result<()> {
let profile_path = if let Some(p) =
crate::profile::get_by_uuid(profile_uuid, None).await?
{
p.profile_id()
} else {
return Err(crate::ErrorKind::UnmanagedProfileError(
profile_uuid.to_string(),
)
.into());
};
let state = State::get().await?;
let logs_folder = state.directories.profile_logs_dir(profile_uuid);
let logs_folder = state.directories.profile_logs_dir(&profile_path).await?;
for entry in std::fs::read_dir(&logs_folder)
.map_err(|e| IOError::with_path(e, &logs_folder))?
{
@@ -109,8 +142,19 @@ pub async fn delete_logs_by_datetime(
profile_uuid: uuid::Uuid,
datetime_string: &str,
) -> crate::Result<()> {
let profile_path = if let Some(p) =
crate::profile::get_by_uuid(profile_uuid, None).await?
{
p.profile_id()
} else {
return Err(crate::ErrorKind::UnmanagedProfileError(
profile_uuid.to_string(),
)
.into());
};
let state = State::get().await?;
let logs_folder = state.directories.profile_logs_dir(profile_uuid);
let logs_folder = state.directories.profile_logs_dir(&profile_path).await?;
let path = logs_folder.join(datetime_string);
io::remove_dir_all(&path).await?;
Ok(())

View File

@@ -29,6 +29,7 @@ pub mod prelude {
profile::{self, Profile},
profile_create, settings,
state::JavaGlobals,
state::{ProfilePathId, ProjectPathId},
util::{
io::{canonicalize, IOError},
jre::JavaVersion,

View File

@@ -4,7 +4,7 @@ use crate::event::emit::{
};
use crate::event::LoadingBarType;
use crate::pack::install_from::{EnvType, PackFile, PackFileHash};
use crate::state::{LinkedData, ProfileInstallStage, SideType};
use crate::state::{LinkedData, ProfileInstallStage, ProfilePathId, SideType};
use crate::util::fetch::{fetch_mirrors, write};
use crate::State;
use async_zip::tokio::read::seek::ZipFileReader;
@@ -20,8 +20,8 @@ use super::install_from::{
#[theseus_macros::debug_pin]
pub async fn install_pack(
location: CreatePackLocation,
profile: PathBuf,
) -> crate::Result<PathBuf> {
profile_path: ProfilePathId,
) -> crate::Result<ProfilePathId> {
// Get file from description
let description: CreatePackDescription = match location {
CreatePackLocation::FromVersionId {
@@ -31,12 +31,16 @@ pub async fn install_pack(
icon_url,
} => {
generate_pack_from_version_id(
project_id, version_id, title, icon_url, profile,
project_id,
version_id,
title,
icon_url,
profile_path,
)
.await?
}
CreatePackLocation::FromFile { path } => {
generate_pack_from_file(path, profile).await?
generate_pack_from_file(path, profile_path).await?
}
};
@@ -46,7 +50,7 @@ pub async fn install_pack(
let project_id = description.project_id;
let version_id = description.version_id;
let existing_loading_bar = description.existing_loading_bar;
let profile = description.profile;
let profile_path = description.profile_path;
let state = &State::get().await?;
@@ -125,7 +129,7 @@ pub async fn install_pack(
loader_version.cloned(),
)
.await?;
crate::api::profile::edit(&profile, |prof| {
crate::api::profile::edit(&profile_path, |prof| {
prof.metadata.name =
override_title.clone().unwrap_or_else(|| pack.name.clone());
prof.install_stage = ProfileInstallStage::PackInstalling;
@@ -142,12 +146,15 @@ pub async fn install_pack(
})
.await?;
let profile = profile.clone();
let profile_path = profile_path.clone();
let result = async {
let loading_bar = init_or_edit_loading(
existing_loading_bar,
LoadingBarType::PackDownload {
profile_path: profile.clone(),
profile_path: profile_path
.get_full_path()
.await?
.clone(),
pack_name: pack.name.clone(),
icon,
pack_id: project_id,
@@ -169,7 +176,7 @@ pub async fn install_pack(
num_files,
None,
|project| {
let profile = profile.clone();
let profile_path = profile_path.clone();
async move {
//TODO: Future update: prompt user for optional files in a modpack
if let Some(env) = project.env {
@@ -203,7 +210,10 @@ pub async fn install_pack(
match path {
Component::CurDir
| Component::Normal(_) => {
let path = profile.join(project.path);
let path = profile_path
.get_full_path()
.await?
.join(project.path);
write(
&path,
&file,
@@ -265,7 +275,10 @@ pub async fn install_pack(
if new_path.file_name().is_some() {
write(
&profile.join(new_path),
&profile_path
.get_full_path()
.await?
.join(new_path),
&content,
&state.io_semaphore,
)
@@ -285,7 +298,7 @@ pub async fn install_pack(
}
if let Some(profile_val) =
crate::api::profile::get(&profile, None).await?
crate::api::profile::get(&profile_path, None).await?
{
crate::launcher::install_minecraft(
&profile_val,
@@ -296,14 +309,14 @@ pub async fn install_pack(
State::sync().await?;
}
Ok::<PathBuf, crate::Error>(profile.clone())
Ok::<ProfilePathId, crate::Error>(profile_path.clone())
}
.await;
match result {
Ok(profile) => Ok(profile),
Err(err) => {
let _ = crate::api::profile::remove(&profile).await;
let _ = crate::api::profile::remove(&profile_path).await;
Err(err)
}
@@ -319,7 +332,7 @@ pub async fn install_pack(
match result {
Ok(profile) => Ok(profile),
Err(err) => {
let _ = crate::api::profile::remove(&profile).await;
let _ = crate::api::profile::remove(&profile_path).await;
Err(err)
}

View File

@@ -2,7 +2,9 @@ use crate::config::MODRINTH_API_URL;
use crate::data::ModLoader;
use crate::event::emit::{emit_loading, init_loading};
use crate::event::{LoadingBarId, LoadingBarType};
use crate::state::{LinkedData, ModrinthProject, ModrinthVersion, SideType};
use crate::state::{
LinkedData, ModrinthProject, ModrinthVersion, ProfilePathId, SideType,
};
use crate::util::fetch::{
fetch, fetch_advanced, fetch_json, write_cached_icon,
};
@@ -71,7 +73,7 @@ pub enum PackDependency {
Minecraft,
}
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum CreatePackLocation {
FromVersionId {
@@ -98,6 +100,7 @@ pub struct CreatePackProfile {
pub skip_install_profile: Option<bool>,
}
#[derive(Debug)]
pub struct CreatePackDescription {
pub file: bytes::Bytes,
pub icon: Option<PathBuf>,
@@ -105,7 +108,7 @@ pub struct CreatePackDescription {
pub project_id: Option<String>,
pub version_id: Option<String>,
pub existing_loading_bar: Option<LoadingBarId>,
pub profile: PathBuf,
pub profile_path: ProfilePathId,
}
pub fn get_profile_from_pack(
@@ -158,13 +161,13 @@ pub async fn generate_pack_from_version_id(
version_id: String,
title: String,
icon_url: Option<String>,
profile: PathBuf,
profile_path: ProfilePathId,
) -> crate::Result<CreatePackDescription> {
let state = State::get().await?;
let loading_bar = init_loading(
LoadingBarType::PackFileDownload {
profile_path: profile.clone(),
profile_path: profile_path.get_full_path().await?,
pack_name: title,
icon: icon_url,
pack_version: version_id.clone(),
@@ -253,7 +256,7 @@ pub async fn generate_pack_from_version_id(
project_id: Some(project_id),
version_id: Some(version_id),
existing_loading_bar: Some(loading_bar),
profile,
profile_path,
})
}
@@ -261,7 +264,7 @@ pub async fn generate_pack_from_version_id(
#[theseus_macros::debug_pin]
pub async fn generate_pack_from_file(
path: PathBuf,
profile: PathBuf,
profile_path: ProfilePathId,
) -> crate::Result<CreatePackDescription> {
let file = io::read(&path).await?;
Ok(CreatePackDescription {
@@ -271,6 +274,6 @@ pub async fn generate_pack_from_file(
project_id: None,
version_id: None,
existing_loading_bar: None,
profile,
profile_path,
})
}

View File

@@ -1,15 +1,17 @@
//! Theseus process management interface
use std::path::{Path, PathBuf};
use uuid::Uuid;
use crate::{state::MinecraftChild, util::io::IOError};
pub use crate::{
state::{
Hooks, JavaSettings, MemorySettings, Profile, Settings, WindowSize,
},
State,
};
use crate::{
state::{MinecraftChild, ProfilePathId},
util::io::IOError,
};
// Gets whether a child process stored in the state by UUID has finished
#[tracing::instrument]
@@ -45,7 +47,8 @@ pub async fn get_all_running_uuids() -> crate::Result<Vec<Uuid>> {
// Gets the Profile paths of each *running* stored process in the state
#[tracing::instrument]
pub async fn get_all_running_profile_paths() -> crate::Result<Vec<PathBuf>> {
pub async fn get_all_running_profile_paths() -> crate::Result<Vec<ProfilePathId>>
{
let state = State::get().await?;
let children = state.children.read().await;
children.running_profile_paths().await
@@ -62,7 +65,7 @@ pub async fn get_all_running_profiles() -> crate::Result<Vec<Profile>> {
// Gets the UUID of each stored process in the state by profile path
#[tracing::instrument]
pub async fn get_uuids_by_profile_path(
profile_path: &Path,
profile_path: ProfilePathId,
) -> crate::Result<Vec<Uuid>> {
let state = State::get().await?;
let children = state.children.read().await;

View File

@@ -7,7 +7,7 @@ use crate::pack::install_from::{
EnvType, PackDependency, PackFile, PackFileHash, PackFormat,
};
use crate::prelude::JavaVersion;
use crate::state::ProjectMetadata;
use crate::state::{ProfilePathId, ProjectMetadata, ProjectPathId};
use crate::util::io::{self, IOError};
use crate::{
@@ -32,14 +32,14 @@ use tokio::{fs::File, process::Command, sync::RwLock};
/// Remove a profile
#[tracing::instrument]
pub async fn remove(path: &Path) -> crate::Result<()> {
pub async fn remove(path: &ProfilePathId) -> crate::Result<()> {
let state = State::get().await?;
let mut profiles = state.profiles.write().await;
if let Some(profile) = profiles.remove(path).await? {
emit_profile(
profile.uuid,
profile.path.clone(),
profile.get_profile_full_path().await?,
&profile.metadata.name,
ProfilePayloadType::Removed,
)
@@ -49,13 +49,14 @@ pub async fn remove(path: &Path) -> crate::Result<()> {
Ok(())
}
/// Get a profile by path,
/// Get a profile by relative path (or, name)
#[tracing::instrument]
pub async fn get(
path: &Path,
path: &ProfilePathId,
clear_projects: Option<bool>,
) -> crate::Result<Option<Profile>> {
let state = State::get().await?;
let profiles = state.profiles.read().await;
let mut profile = profiles.0.get(path).cloned();
@@ -68,9 +69,29 @@ pub async fn get(
Ok(profile)
}
/// Get a profile by uuid
#[tracing::instrument]
pub async fn get_by_uuid(
uuid: uuid::Uuid,
clear_projects: Option<bool>,
) -> crate::Result<Option<Profile>> {
let state = State::get().await?;
let profiles = state.profiles.read().await;
let mut profile = profiles.0.values().find(|x| x.uuid == uuid).cloned();
if clear_projects.unwrap_or(false) {
if let Some(profile) = &mut profile {
profile.projects = HashMap::new();
}
}
Ok(profile)
}
/// Edit a profile using a given asynchronous closure
pub async fn edit<Fut>(
path: &Path,
path: &ProfilePathId,
action: impl Fn(&mut Profile) -> Fut,
) -> crate::Result<()>
where
@@ -85,7 +106,7 @@ where
emit_profile(
profile.uuid,
profile.path.clone(),
profile.get_profile_full_path().await?,
&profile.metadata.name,
ProfilePayloadType::Edited,
)
@@ -93,16 +114,14 @@ where
Ok(())
}
None => Err(crate::ErrorKind::UnmanagedProfileError(
path.display().to_string(),
)
.as_error()),
None => Err(crate::ErrorKind::UnmanagedProfileError(path.to_string())
.as_error()),
}
}
/// Edits a profile's icon
pub async fn edit_icon(
path: &Path,
path: &ProfilePathId,
icon_path: Option<&Path>,
) -> crate::Result<()> {
let state = State::get().await?;
@@ -125,17 +144,17 @@ pub async fn edit_icon(
emit_profile(
profile.uuid,
profile.path.clone(),
profile.get_profile_full_path().await?,
&profile.metadata.name,
ProfilePayloadType::Edited,
)
.await?;
Ok(())
}
None => Err(crate::ErrorKind::UnmanagedProfileError(
path.display().to_string(),
)
.as_error()),
None => {
Err(crate::ErrorKind::UnmanagedProfileError(path.to_string())
.as_error())
}
}
} else {
edit(path, |profile| {
@@ -155,7 +174,7 @@ pub async fn edit_icon(
// Generally this would be used for profile_create, to get the optimal JRE key
// this can be overwritten by the user a profile-by-profile basis
pub async fn get_optimal_jre_key(
path: &Path,
path: &ProfilePathId,
) -> crate::Result<Option<JavaVersion>> {
let state = State::get().await?;
@@ -193,10 +212,8 @@ pub async fn get_optimal_jre_key(
Ok(version)
} else {
Err(
crate::ErrorKind::UnmanagedProfileError(path.display().to_string())
.as_error(),
)
Err(crate::ErrorKind::UnmanagedProfileError(path.to_string())
.as_error())
}
}
@@ -204,7 +221,7 @@ pub async fn get_optimal_jre_key(
#[tracing::instrument]
pub async fn list(
clear_projects: Option<bool>,
) -> crate::Result<HashMap<PathBuf, Profile>> {
) -> crate::Result<HashMap<ProfilePathId, Profile>> {
let state = State::get().await?;
let profiles = state.profiles.read().await;
Ok(profiles
@@ -223,14 +240,12 @@ pub async fn list(
/// Installs/Repairs a profile
#[tracing::instrument]
pub async fn install(path: &Path) -> crate::Result<()> {
pub async fn install(path: &ProfilePathId) -> crate::Result<()> {
if let Some(profile) = get(path, None).await? {
crate::launcher::install_minecraft(&profile, None).await?;
} else {
return Err(crate::ErrorKind::UnmanagedProfileError(
path.display().to_string(),
)
.as_error());
return Err(crate::ErrorKind::UnmanagedProfileError(path.to_string())
.as_error());
}
State::sync().await?;
Ok(())
@@ -239,12 +254,12 @@ pub async fn install(path: &Path) -> crate::Result<()> {
#[tracing::instrument]
#[theseus_macros::debug_pin]
pub async fn update_all(
profile_path: &Path,
) -> crate::Result<HashMap<PathBuf, PathBuf>> {
profile_path: &ProfilePathId,
) -> crate::Result<HashMap<ProjectPathId, ProjectPathId>> {
if let Some(profile) = get(profile_path, None).await? {
let loading_bar = init_loading(
LoadingBarType::ProfileUpdate {
profile_path: profile.path.clone(),
profile_path: profile.get_profile_full_path().await?,
profile_name: profile.metadata.name.clone(),
},
100.0,
@@ -252,6 +267,7 @@ pub async fn update_all(
)
.await?;
let profile_base_path = profile.get_profile_full_path().await?;
let keys = profile
.projects
.into_iter()
@@ -272,7 +288,7 @@ pub async fn update_all(
use futures::StreamExt;
loading_try_for_each_concurrent(
futures::stream::iter(keys).map(Ok::<PathBuf, crate::Error>),
futures::stream::iter(keys).map(Ok::<ProjectPathId, crate::Error>),
None,
Some(&loading_bar),
100.0,
@@ -297,7 +313,7 @@ pub async fn update_all(
emit_profile(
profile.uuid,
profile.path,
profile_base_path,
&profile.metadata.name,
ProfilePayloadType::Edited,
)
@@ -306,20 +322,22 @@ pub async fn update_all(
Ok(Arc::try_unwrap(map).unwrap().into_inner())
} else {
Err(crate::ErrorKind::UnmanagedProfileError(
profile_path.display().to_string(),
Err(
crate::ErrorKind::UnmanagedProfileError(profile_path.to_string())
.as_error(),
)
.as_error())
}
}
/// Updates a project to the latest version
/// Uses and returns the relative path to the project
#[tracing::instrument]
#[theseus_macros::debug_pin]
pub async fn update_project(
profile_path: &Path,
project_path: &Path,
profile_path: &ProfilePathId,
project_path: &ProjectPathId,
skip_send_event: Option<bool>,
) -> crate::Result<PathBuf> {
) -> crate::Result<ProjectPathId> {
if let Some(profile) = get(profile_path, None).await? {
if let Some(project) = profile.projects.get(project_path) {
if let ProjectMetadata::Modrinth {
@@ -331,13 +349,13 @@ pub async fn update_project(
.add_project_version(update_version.id.clone())
.await?;
if path != project_path {
if path != project_path.clone() {
profile.remove_project(project_path, Some(true)).await?;
}
let state = State::get().await?;
let mut profiles = state.profiles.write().await;
if let Some(profile) = profiles.0.get_mut(project_path) {
if let Some(profile) = profiles.0.get_mut(profile_path) {
let value = profile.projects.remove(project_path);
if let Some(mut project) = value {
if let ProjectMetadata::Modrinth {
@@ -354,7 +372,7 @@ pub async fn update_project(
if !skip_send_event.unwrap_or(false) {
emit_profile(
profile.uuid,
profile.path,
profile.get_profile_full_path().await?,
&profile.metadata.name,
ProfilePayloadType::Edited,
)
@@ -371,25 +389,26 @@ pub async fn update_project(
)
.as_error())
} else {
Err(crate::ErrorKind::UnmanagedProfileError(
profile_path.display().to_string(),
Err(
crate::ErrorKind::UnmanagedProfileError(profile_path.to_string())
.as_error(),
)
.as_error())
}
}
/// Add a project from a version
/// Returns the relative path to the project as a ProjectPathId
#[tracing::instrument]
pub async fn add_project_from_version(
profile_path: &Path,
profile_path: &ProfilePathId,
version_id: String,
) -> crate::Result<PathBuf> {
) -> crate::Result<ProjectPathId> {
if let Some(profile) = get(profile_path, None).await? {
let (path, _) = profile.add_project_version(version_id).await?;
emit_profile(
profile.uuid,
profile.path,
profile.get_profile_full_path().await?,
&profile.metadata.name,
ProfilePayloadType::Edited,
)
@@ -398,20 +417,21 @@ pub async fn add_project_from_version(
Ok(path)
} else {
Err(crate::ErrorKind::UnmanagedProfileError(
profile_path.display().to_string(),
Err(
crate::ErrorKind::UnmanagedProfileError(profile_path.to_string())
.as_error(),
)
.as_error())
}
}
/// Add a project from an FS path
/// Uses and returns the relative path to the project as a ProjectPathId
#[tracing::instrument]
pub async fn add_project_from_path(
profile_path: &Path,
profile_path: &ProfilePathId,
path: &Path,
project_type: Option<String>,
) -> crate::Result<PathBuf> {
) -> crate::Result<ProjectPathId> {
if let Some(profile) = get(profile_path, None).await? {
let file = io::read(path).await?;
let file_name = path
@@ -430,7 +450,7 @@ pub async fn add_project_from_path(
emit_profile(
profile.uuid,
profile.path,
profile.get_profile_full_path().await?,
&profile.metadata.name,
ProfilePayloadType::Edited,
)
@@ -439,25 +459,27 @@ pub async fn add_project_from_path(
Ok(path)
} else {
Err(crate::ErrorKind::UnmanagedProfileError(
profile_path.display().to_string(),
Err(
crate::ErrorKind::UnmanagedProfileError(profile_path.to_string())
.as_error(),
)
.as_error())
}
}
/// Toggle whether a project is disabled or not
/// Project path should be relative to the profile
/// returns the new state, relative to the profile
#[tracing::instrument]
pub async fn toggle_disable_project(
profile: &Path,
project: &Path,
) -> crate::Result<PathBuf> {
profile: &ProfilePathId,
project: &ProjectPathId,
) -> crate::Result<ProjectPathId> {
if let Some(profile) = get(profile, None).await? {
let res = profile.toggle_disable_project(project).await?;
emit_profile(
profile.uuid,
profile.path,
profile.get_profile_full_path().await?,
&profile.metadata.name,
ProfilePayloadType::Edited,
)
@@ -466,25 +488,24 @@ pub async fn toggle_disable_project(
Ok(res)
} else {
Err(crate::ErrorKind::UnmanagedProfileError(
profile.display().to_string(),
)
.as_error())
Err(crate::ErrorKind::UnmanagedProfileError(profile.to_string())
.as_error())
}
}
/// Remove a project from a profile
/// Uses and returns the relative path to the project
#[tracing::instrument]
pub async fn remove_project(
profile: &Path,
project: &Path,
profile: &ProfilePathId,
project: &ProjectPathId,
) -> crate::Result<()> {
if let Some(profile) = get(profile, None).await? {
profile.remove_project(project, None).await?;
emit_profile(
profile.uuid,
profile.path,
profile.get_profile_full_path().await?,
&profile.metadata.name,
ProfilePayloadType::Edited,
)
@@ -493,10 +514,8 @@ pub async fn remove_project(
Ok(())
} else {
Err(crate::ErrorKind::UnmanagedProfileError(
profile.display().to_string(),
)
.as_error())
Err(crate::ErrorKind::UnmanagedProfileError(profile.to_string())
.as_error())
}
}
@@ -505,7 +524,7 @@ pub async fn remove_project(
#[tracing::instrument(skip_all)]
#[theseus_macros::debug_pin]
pub async fn export_mrpack(
profile_path: &Path,
profile_path: &ProfilePathId,
export_path: PathBuf,
included_overrides: Vec<String>, // which folders to include in the overrides
version_id: Option<String>,
@@ -516,11 +535,24 @@ pub async fn export_mrpack(
let profile = get(profile_path, None).await?.ok_or_else(|| {
crate::ErrorKind::OtherError(format!(
"Tried to export a nonexistent or unloaded profile at path {}!",
profile_path.display()
profile_path
))
})?;
let profile_base_path = &profile.path;
// remove .DS_Store files from included_overrides
let included_overrides = included_overrides
.into_iter()
.filter(|x| {
if let Some(f) = PathBuf::from(x).file_name() {
if f.to_string_lossy().starts_with(".DS_Store") {
return false;
}
}
true
})
.collect::<Vec<_>>();
let profile_base_path = &profile.get_profile_full_path().await?;
let mut file = File::create(&export_path)
.await
@@ -529,7 +561,7 @@ pub async fn export_mrpack(
// Create mrpack json configuration file
let version_id = version_id.unwrap_or("1.0.0".to_string());
let packfile = create_mrpack_json(&profile, version_id)?;
let packfile = create_mrpack_json(&profile, version_id).await?;
let modrinth_path_list = get_modrinth_pack_list(&packfile);
// Build vec of all files in the folder
@@ -539,7 +571,7 @@ pub async fn export_mrpack(
// Initialize loading bar
let loading_bar = init_loading(
LoadingBarType::ZipExtract {
profile_path: profile.path.to_path_buf(),
profile_path: profile.get_profile_full_path().await?,
profile_name: profile.metadata.name.clone(),
},
path_list.len() as f64,
@@ -628,25 +660,28 @@ pub async fn export_mrpack(
// => [folder1, folder2]
#[tracing::instrument]
pub async fn get_potential_override_folders(
profile_path: PathBuf,
profile_path: ProfilePathId,
) -> crate::Result<Vec<PathBuf>> {
// First, get a dummy mrpack json for the files within
let profile: Profile =
get(&profile_path, None).await?.ok_or_else(|| {
crate::ErrorKind::OtherError(format!(
"Tried to export a nonexistent or unloaded profile at path {}!",
profile_path.display()
profile_path
))
})?;
let mrpack = create_mrpack_json(&profile, "0".to_string())?;
// dummy mrpack to get pack list
let mrpack = create_mrpack_json(&profile, "0".to_string()).await?;
let mrpack_files = get_modrinth_pack_list(&mrpack);
let mut path_list: Vec<PathBuf> = Vec::new();
let mut read_dir = io::read_dir(&profile_path).await?;
let profile_base_dir = profile.get_profile_full_path().await?;
let mut read_dir = io::read_dir(&profile_base_dir).await?;
while let Some(entry) = read_dir
.next_entry()
.await
.map_err(|e| IOError::with_path(e, &profile_path))?
.map_err(|e| IOError::with_path(e, &profile_base_dir))?
{
let path: PathBuf = entry.path();
if path.is_dir() {
@@ -655,17 +690,17 @@ pub async fn get_potential_override_folders(
while let Some(entry) = read_dir
.next_entry()
.await
.map_err(|e| IOError::with_path(e, &profile_path))?
.map_err(|e| IOError::with_path(e, &profile_base_dir))?
{
let path: PathBuf = entry.path();
let name = path.strip_prefix(&profile_path)?.to_path_buf();
let name = path.strip_prefix(&profile_base_dir)?.to_path_buf();
if !mrpack_files.contains(&name.to_string_lossy().to_string()) {
path_list.push(name);
}
}
} else {
// One layer of files/folders if its a file
let name = path.strip_prefix(&profile_path)?.to_path_buf();
let name = path.strip_prefix(&profile_base_dir)?.to_path_buf();
if !mrpack_files.contains(&name.to_string_lossy().to_string()) {
path_list.push(name);
}
@@ -677,7 +712,9 @@ pub async fn get_potential_override_folders(
/// Run Minecraft using a profile and the default credentials, logged in credentials,
/// failing with an error if no credentials are available
#[tracing::instrument]
pub async fn run(path: &Path) -> crate::Result<Arc<RwLock<MinecraftChild>>> {
pub async fn run(
path: &ProfilePathId,
) -> crate::Result<Arc<RwLock<MinecraftChild>>> {
let state = State::get().await?;
// Get default account and refresh credentials (preferred way to log in)
@@ -702,7 +739,7 @@ pub async fn run(path: &Path) -> crate::Result<Arc<RwLock<MinecraftChild>>> {
#[tracing::instrument(skip(credentials))]
#[theseus_macros::debug_pin]
pub async fn run_credentials(
path: &Path,
path: &ProfilePathId,
credentials: &auth::Credentials,
) -> crate::Result<Arc<RwLock<MinecraftChild>>> {
let state = State::get().await?;
@@ -710,7 +747,7 @@ pub async fn run_credentials(
let profile = get(path, None).await?.ok_or_else(|| {
crate::ErrorKind::OtherError(format!(
"Tried to run a nonexistent or unloaded profile at path {}!",
path.display()
path
))
})?;
@@ -720,11 +757,12 @@ pub async fn run_credentials(
// TODO: hook parameters
let mut cmd = hook.split(' ');
if let Some(command) = cmd.next() {
let full_path = path.get_full_path().await?;
let result = Command::new(command)
.args(&cmd.collect::<Vec<&str>>())
.current_dir(path)
.current_dir(&full_path)
.spawn()
.map_err(|e| IOError::with_path(e, path))?
.map_err(|e| IOError::with_path(e, &full_path))?
.wait()
.await
.map_err(IOError::from)?;
@@ -767,7 +805,9 @@ pub async fn run_credentials(
let mut cmd = hook.split(' ');
if let Some(command) = cmd.next() {
let mut command = Command::new(command);
command.args(&cmd.collect::<Vec<&str>>()).current_dir(path);
command
.args(&cmd.collect::<Vec<&str>>())
.current_dir(path.get_full_path().await?);
Some(command)
} else {
None
@@ -806,7 +846,7 @@ fn get_modrinth_pack_list(packfile: &PackFormat) -> Vec<String> {
/// Creates a json configuration for a .mrpack zipped file
// Version ID of uploaded version (ie 1.1.5), not the unique identifying ID of the version (nvrqJg44)
#[tracing::instrument(skip_all)]
pub fn create_mrpack_json(
pub async fn create_mrpack_json(
profile: &Profile,
version_id: String,
) -> crate::Result<PackFormat> {
@@ -845,17 +885,15 @@ pub fn create_mrpack_json(
.map(|(k, v)| (k, sanitize_loader_version_string(&v).to_string()))
.collect::<HashMap<_, _>>();
let base_path = &profile.path;
let profile_base_path = profile.get_profile_full_path().await?;
let files: Result<Vec<PackFile>, crate::ErrorKind> = profile
.projects
.iter()
.filter_map(|(mod_path, project)| {
let path = match mod_path.strip_prefix(base_path) {
Ok(path) => path.to_string_lossy().to_string(),
Err(e) => {
return Some(Err(e.into()));
}
};
let path: String = profile_base_path
.join(mod_path.0.clone())
.to_string_lossy()
.to_string();
// Only Modrinth projects have a modrinth metadata field for the modrinth.json
Some(Ok(match project.metadata {

View File

@@ -1,5 +1,5 @@
//! Theseus profile management interface
use crate::state::LinkedData;
use crate::state::{LinkedData, ProfilePathId};
use crate::util::io::{self, canonicalize};
use crate::{
event::{emit::emit_profile, ProfilePayloadType},
@@ -10,20 +10,18 @@ pub use crate::{
State,
};
use daedalus::modded::LoaderVersion;
use futures::prelude::*;
use std::path::PathBuf;
use tokio_stream::wrappers::ReadDirStream;
use tracing::{info, trace};
use uuid::Uuid;
// Creates a profile at the given filepath and adds it to the in-memory state
// Returns filepath at which it can be accessed in the State
// Creates a profile of a given name and adds it to the in-memory state
// Returns relative filepath as ProfilePathId which can be used to access it in the State
#[tracing::instrument]
#[theseus_macros::debug_pin]
#[allow(clippy::too_many_arguments)]
pub async fn profile_create(
name: String, // the name of the profile, and relative path
mut name: String, // the name of the profile, and relative path
game_version: String, // the game version of the profile
modloader: ModLoader, // the modloader to use
loader_version: Option<String>, // the modloader version to use, set to "latest", "stable", or the ID of your chosen loader. defaults to latest
@@ -31,32 +29,34 @@ pub async fn profile_create(
icon_url: Option<String>, // the URL icon for a profile (ONLY USED FOR TEMPORARY PROFILES)
linked_data: Option<LinkedData>, // the linked project ID (mainly for modpacks)- used for updating
skip_install_profile: Option<bool>,
) -> crate::Result<PathBuf> {
) -> crate::Result<ProfilePathId> {
trace!("Creating new profile. {}", name);
let state = State::get().await?;
let uuid = Uuid::new_v4();
let path = state.directories.profiles_dir().join(uuid.to_string());
let mut path = state.directories.profiles_dir().await.join(&name);
if path.exists() {
if !path.is_dir() {
return Err(ProfileCreationError::NotFolder.into());
}
if path.join("profile.json").exists() {
return Err(ProfileCreationError::ProfileExistsError(
path.join("profile.json"),
)
.into());
let mut new_name;
let mut new_path;
let mut which = 1;
loop {
new_name = format!("{name} ({which})");
new_path = state.directories.profiles_dir().await.join(&new_name);
if !new_path.exists() {
break;
}
which += 1;
}
if ReadDirStream::new(io::read_dir(&path).await?)
.next()
.await
.is_some()
{
return Err(ProfileCreationError::NotEmptyFolder.into());
}
} else {
io::create_dir_all(&path).await?;
tracing::debug!(
"Folder collision: {}, renaming to: {}",
path.display(),
new_path.display()
);
path = new_path;
name = new_name;
}
io::create_dir_all(&path).await?;
info!(
"Creating profile at path {}",
@@ -73,13 +73,11 @@ pub async fn profile_create(
None
};
// Fully canonicalize now that its created for storing purposes
let path = canonicalize(&path)?;
let mut profile =
Profile::new(uuid, name, game_version, path.clone()).await?;
let mut profile = Profile::new(uuid, name, game_version).await?;
let result = async {
if let Some(ref icon) = icon {
let bytes = io::read(icon).await?;
let bytes =
io::read(state.directories.caches_dir().join(icon)).await?;
profile
.set_icon(
&state.directories.caches_dir(),
@@ -100,7 +98,7 @@ pub async fn profile_create(
emit_profile(
uuid,
path.clone(),
profile.get_profile_full_path().await?,
&profile.metadata.name,
ProfilePayloadType::Created,
)
@@ -116,14 +114,14 @@ pub async fn profile_create(
}
State::sync().await?;
Ok(path)
Ok(profile.profile_id())
}
.await;
match result {
Ok(profile) => Ok(profile),
Err(err) => {
let _ = crate::api::profile::remove(&profile.path).await;
let _ = crate::api::profile::remove(&profile.profile_id()).await;
Err(err)
}

View File

@@ -1,5 +1,16 @@
//! Theseus profile management interface
use std::path::PathBuf;
use io::IOError;
use tokio::sync::RwLock;
use crate::{
event::emit::{emit_loading, init_loading},
prelude::DirectoryInfo,
state::{self, Profiles},
util::io,
};
pub use crate::{
state::{
Hooks, JavaSettings, MemorySettings, Profile, Settings, WindowSize,
@@ -19,6 +30,16 @@ pub async fn get() -> crate::Result<Settings> {
#[tracing::instrument]
pub async fn set(settings: Settings) -> crate::Result<()> {
let state = State::get().await?;
if settings.loaded_config_dir
!= state.settings.read().await.loaded_config_dir
{
return Err(crate::ErrorKind::OtherError(
"Cannot change config directory as setting".to_string(),
)
.as_error());
}
let (reset_io, reset_fetch) = async {
let read = state.settings.read().await;
(
@@ -42,3 +63,119 @@ pub async fn set(settings: Settings) -> crate::Result<()> {
State::sync().await?;
Ok(())
}
/// Sets the new config dir, the location of all Theseus data except for the settings.json and caches
/// Takes control of the entire state and blocks until completion
pub async fn set_config_dir(new_config_dir: PathBuf) -> crate::Result<()> {
if !new_config_dir.is_dir() {
return Err(crate::ErrorKind::FSError(format!(
"New config dir is not a folder: {}",
new_config_dir.display()
))
.as_error());
}
let loading_bar = init_loading(
crate::LoadingBarType::ConfigChange {
new_path: new_config_dir.clone(),
},
100.0,
"Changing configuration directory",
)
.await?;
tracing::trace!("Changing config dir, taking control of the state");
// Take control of the state
let mut state_write = State::get_write().await?;
let old_config_dir =
state_write.directories.config_dir.read().await.clone();
tracing::trace!("Setting configuration setting");
// Set load config dir setting
let settings = {
let mut settings = state_write.settings.write().await;
settings.loaded_config_dir = Some(new_config_dir.clone());
// Some java paths are hardcoded to within our config dir, so we need to update them
tracing::trace!("Updating java keys");
for key in settings.java_globals.keys() {
if let Some(java) = settings.java_globals.get_mut(&key) {
// If the path is within the old config dir path, update it to the new config dir
if let Ok(relative_path) = PathBuf::from(java.path.clone())
.strip_prefix(&old_config_dir)
{
java.path = new_config_dir
.join(relative_path)
.to_string_lossy()
.to_string();
}
}
}
tracing::trace!("Syncing settings");
settings
.sync(&state_write.directories.settings_file())
.await?;
settings.clone()
};
tracing::trace!("Reinitializing directory");
// Set new state information
state_write.directories = DirectoryInfo::init(&settings)?;
let total_entries = std::fs::read_dir(&old_config_dir)
.map_err(|e| IOError::with_path(e, &old_config_dir))?
.count() as f64;
// Move all files over from state_write.directories.config_dir to new_config_dir
tracing::trace!("Renaming folder structure");
let mut i = 0.0;
let mut entries = io::read_dir(&old_config_dir).await?;
while let Some(entry) = entries
.next_entry()
.await
.map_err(|e| IOError::with_path(e, &old_config_dir))?
{
let entry_path = entry.path();
if let Some(file_name) = entry_path.file_name() {
// Ignore settings.json
if file_name == state::SETTINGS_FILE_NAME {
continue;
}
// Ignore caches folder
if file_name == state::CACHES_FOLDER_NAME {
continue;
}
// Ignore modrinth_logs folder
if file_name == state::LAUNCHER_LOGS_FOLDER_NAME {
continue;
}
let new_path = new_config_dir.join(file_name);
io::rename(entry_path, new_path).await?;
i += 1.0;
emit_loading(&loading_bar, 90.0 * (i / total_entries), None)
.await?;
}
}
// Reset file watcher
tracing::trace!("Reset file watcher");
let mut file_watcher = state::init_watcher().await?;
// Reset profiles (for filepaths, file watcher, etc)
state_write.profiles = RwLock::new(
Profiles::init(&state_write.directories, &mut file_watcher).await?,
);
state_write.file_watcher = RwLock::new(file_watcher);
emit_loading(&loading_bar, 10.0, None).await?;
// TODO: need to be able to safely error out of this function, reverting the changes
tracing::info!(
"Successfully switched config folder to: {}",
new_config_dir.display()
);
Ok(())
}