Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Another round of refactors #52

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/appmanifest.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{env, process::exit};

use steamlocate::InstallDir;
use steamlocate::SteamDir;

fn main() {
let args: Vec<_> = env::args().collect();
Expand All @@ -10,7 +10,7 @@ fn main() {
}
let app_id: u32 = args[1].parse().expect("<STEAM_APP_ID> should be a u32");

let steam_dir = InstallDir::locate().unwrap();
let steam_dir = SteamDir::locate().unwrap();
match steam_dir.app(app_id) {
Ok(Some(app)) => println!("Found app - {:#?}", app),
Ok(None) => println!("No app found for {}", app_id),
Expand Down
4 changes: 2 additions & 2 deletions examples/overview.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use steamlocate::InstallDir;
use steamlocate::SteamDir;

fn main() {
let steamdir = InstallDir::locate().unwrap();
let steamdir = SteamDir::locate().unwrap();
println!("Steam Dir - {:?}", steamdir.path());

// TODO: use `anyhow` to make error handling here simpler
Expand Down
2 changes: 1 addition & 1 deletion examples/shortcuts.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Just prints all discovered shortcuts aka all non-Steam added games

fn main() {
let mut steamdir = steamlocate::InstallDir::locate().unwrap();
let mut steamdir = steamlocate::SteamDir::locate().unwrap();
println!("Shortcuts:");
for maybe_shortcut in steamdir.shortcuts().unwrap() {
match maybe_shortcut {
Expand Down
24 changes: 12 additions & 12 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ impl<'library> Iterator for Iter<'library> {
/// An instance of an installed Steam app.
/// # Example
/// ```ignore
/// # use steamlocate::InstallDir;
/// let mut steamdir = InstallDir::locate().unwrap();
/// # use steamlocate::SteamDir;
/// let mut steamdir = SteamDir::locate().unwrap();
/// let gmod = steamdir.app(&4000);
/// println!("{:#?}", gmod.unwrap());
/// ```
Expand Down Expand Up @@ -248,27 +248,27 @@ impl From<u64> for Universe {
pub struct StateFlags(pub u64);

impl StateFlags {
pub fn flags(self) -> FlagIter {
pub fn flags(self) -> StateFlagIter {
self.into()
}
}

#[derive(Clone, Debug, Default)]
pub struct FlagIter(Option<FlagIterInner>);
pub struct StateFlagIter(Option<StateFlagIterInner>);

impl FlagIter {
impl StateFlagIter {
fn from_valid(valid: ValidIter) -> Self {
Self(Some(FlagIterInner::Valid(valid)))
Self(Some(StateFlagIterInner::Valid(valid)))
}
}

impl From<StateFlags> for FlagIter {
impl From<StateFlags> for StateFlagIter {
fn from(state: StateFlags) -> Self {
Self(Some(state.into()))
}
}

impl Iterator for FlagIter {
impl Iterator for StateFlagIter {
type Item = StateFlag;

fn next(&mut self) -> Option<Self::Item> {
Expand All @@ -278,8 +278,8 @@ impl Iterator for FlagIter {
// - Valid will pull on the inner iterator till it's finished
let current = std::mem::take(self);
let (next, ret) = match current.0? {
FlagIterInner::Invalid => (Self::default(), StateFlag::Invalid),
FlagIterInner::Valid(mut valid) => {
StateFlagIterInner::Invalid => (Self::default(), StateFlag::Invalid),
StateFlagIterInner::Valid(mut valid) => {
let ret = valid.next()?;
(Self::from_valid(valid), ret)
}
Expand All @@ -290,13 +290,13 @@ impl Iterator for FlagIter {
}

#[derive(Clone, Debug, Default)]
enum FlagIterInner {
enum StateFlagIterInner {
#[default]
Invalid,
Valid(ValidIter),
}

impl From<StateFlags> for FlagIterInner {
impl From<StateFlags> for StateFlagIterInner {
fn from(state: StateFlags) -> Self {
if state.0 == 0 {
Self::Invalid
Expand Down
4 changes: 2 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub type Result<T> = std::result::Result<T, Error>;
#[non_exhaustive]
pub enum Error {
// TODO: people would probably appreciate more context here even if it has to be opaque
FailedLocatingInstallDir,
FailedLocatingSteamDir,
Io {
inner: std::io::Error,
path: PathBuf,
Expand All @@ -31,7 +31,7 @@ pub enum Error {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FailedLocatingInstallDir => f.write_str("Failed locating the steam dir"),
Self::FailedLocatingSteamDir => f.write_str("Failed locating the steam dir"),
Self::Io { inner: err, path } => {
write!(f, "Encountered an I/O error: {} at {}", err, path.display())
}
Expand Down
46 changes: 23 additions & 23 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
//! # Caching
//! All functions in this crate cache their results, meaning you can call them as many times as you like and they will always return the same reference.
//!
//! If you need to get uncached results, simply instantiate a new [InstallDir](https://docs.rs/steamlocate/*/steamlocate/struct.InstallDir.html).
//! If you need to get uncached results, simply instantiate a new [SteamDir](https://docs.rs/steamlocate/*/steamlocate/struct.SteamDir.html).
//!
//! # steamid-ng Support
//! This crate supports [steamid-ng](https://docs.rs/steamid-ng) and can automatically convert [App::last_user](struct.App.html#structfield.last_user) to a [SteamID](https://docs.rs/steamid-ng/*/steamid_ng/struct.SteamID.html) for you.
Expand All @@ -34,15 +34,15 @@
//! ### Locate the installed Steam directory
//! ```rust,ignore
//! extern crate steamlocate;
//! use steamlocate::InstallDir;
//! use steamlocate::SteamDir;
//!
//! match InstallDir::locate() {
//! match SteamDir::locate() {
//! Ok(steamdir) => println!("{:#?}", steamdir),
//! Err(_) => panic!("Couldn't locate Steam on this computer!")
//! }
//! ```
//! ```ignore
//! InstallDir (
//! SteamDir (
//! path: PathBuf: "C:\\Program Files (x86)\\Steam"
//! )
//! ```
Expand All @@ -51,9 +51,9 @@
//! This will locate Garry's Mod anywhere on the filesystem.
//! ```ignore
//! extern crate steamlocate;
//! use steamlocate::InstallDir;
//! use steamlocate::SteamDir;
//!
//! let mut steamdir = InstallDir::locate().unwrap();
//! let mut steamdir = SteamDir::locate().unwrap();
//! match steamdir.app(&4000) {
//! Some(app) => println!("{:#?}", app),
//! None => panic!("Couldn't locate Garry's Mod on this computer!")
Expand All @@ -72,10 +72,10 @@
//! ### Locate all Steam apps on this filesystem
//! ```ignore
//! extern crate steamlocate;
//! use steamlocate::{InstallDir, App};
//! use steamlocate::{SteamDir, App};
//! use std::collections::HashMap;
//!
//! let mut steamdir = InstallDir::locate().unwrap();
//! let mut steamdir = SteamDir::locate().unwrap();
//! let apps: &HashMap<u32, Option<App>> = steamdir.apps();
//!
//! println!("{:#?}", apps);
Expand All @@ -96,10 +96,10 @@
//! ### Locate all Steam library folders
//! ```ignore
//! extern crate steamlocate;
//! use steamlocate::{InstallDir, LibraryFolders};
//! use steamlocate::{SteamDir, LibraryFolders};
//! use std::{vec, path::PathBuf};
//!
//! let mut steamdir: InstallDir = InstallDir::locate().unwrap();
//! let mut steamdir: SteamDir = SteamDir::locate().unwrap();
//! let libraryfolders: &LibraryFolders = steamdir.libraryfolders();
//! let paths: &Vec<PathBuf> = &libraryfolders.paths;
//!
Expand Down Expand Up @@ -146,25 +146,25 @@ pub use crate::shortcut::Shortcut;
///
/// All functions of this struct will cache their results.
///
/// If you'd like to dispose of the cache or get uncached results, just instantiate a new `InstallDir`.
/// If you'd like to dispose of the cache or get uncached results, just instantiate a new `SteamDir`.
///
/// # Example
/// ```rust,ignore
/// # use steamlocate::InstallDir;
/// let steamdir = InstallDir::locate();
/// # use steamlocate::SteamDir;
/// let steamdir = SteamDir::locate();
/// println!("{:#?}", steamdir.unwrap());
/// ```
/// ```ignore
/// InstallDir (
/// SteamDir (
/// path: "C:\\Program Files (x86)\\Steam"
/// )
/// ```
#[derive(Clone, Debug)]
pub struct InstallDir {
pub struct SteamDir {
path: PathBuf,
}

impl InstallDir {
impl SteamDir {
/// The path to the Steam installation directory on this computer.
///
/// Example: `C:\Program Files (x86)\Steam`
Expand All @@ -190,8 +190,8 @@ impl InstallDir {
///
/// # Example
/// ```ignore
/// # use steamlocate::InstallDir;
/// let mut steamdir = InstallDir::locate().unwrap();
/// # use steamlocate::SteamDir;
/// let mut steamdir = SteamDir::locate().unwrap();
/// let gmod = steamdir.app(&4000);
/// println!("{:#?}", gmod.unwrap());
/// ```
Expand Down Expand Up @@ -235,9 +235,9 @@ impl InstallDir {
shortcut::Iter::new(&self.path)
}

pub fn from_steam_dir(path: &Path) -> Result<InstallDir> {
pub fn from_steam_dir(path: &Path) -> Result<SteamDir> {
if !path.is_dir() {
return Err(Error::FailedLocatingInstallDir);
return Err(Error::FailedLocatingSteamDir);
}

// TODO(cosmic): should we do some kind of extra validation here? Could also use validation
Expand All @@ -247,12 +247,12 @@ impl InstallDir {
})
}

/// Locates the Steam installation directory on the filesystem and initializes a `InstallDir` (Windows)
/// Locates the Steam installation directory on the filesystem and initializes a `SteamDir` (Windows)
///
/// Returns `None` if no Steam installation can be located.
#[cfg(feature = "locate")]
pub fn locate() -> Result<InstallDir> {
let path = locate::locate_steam_dir().ok_or(Error::FailedLocatingInstallDir)?;
pub fn locate() -> Result<SteamDir> {
let path = locate::locate_steam_dir().ok_or(Error::FailedLocatingSteamDir)?;

Ok(Self { path })
}
Expand Down
20 changes: 14 additions & 6 deletions src/shortcut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,14 +252,22 @@ mod tests {
);
}

#[cfg(feature = "shortcuts_extras")]
#[cfg_attr(
not(feature = "shortcuts_extras"),
ignore = "Needs `shortcuts_extras` feature"
)]
#[test]
fn shortcuts_extras() {
let contents = include_bytes!("../tests/sample_data/shortcuts.vdf");
let shortcuts = parse_shortcuts(contents).unwrap();
let ideal_ids = vec![0xe89614fe02000000, 0xdb01c79902000000, 0x9d55017302000000];
for (id, shortcut) in ideal_ids.into_iter().zip(shortcuts.iter()) {
assert_eq!(id, shortcut.steam_id());
#[cfg(not(feature = "shortcuts_extras"))]
unreachable!();
#[cfg(feature = "shortcuts_extras")]
{
let contents = include_bytes!("../tests/sample_data/shortcuts.vdf");
let shortcuts = parse_shortcuts(contents).unwrap();
let ideal_ids = vec![0xe89614fe02000000, 0xdb01c79902000000, 0x9d55017302000000];
for (id, shortcut) in ideal_ids.into_iter().zip(shortcuts.iter()) {
assert_eq!(id, shortcut.steam_id());
}
}
}
}
30 changes: 15 additions & 15 deletions src/tests/test_helpers.rs → src/tests/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{
path::{Path, PathBuf},
};

use crate::InstallDir;
use crate::SteamDir;

use serde::Serialize;
use tempfile::TempDir;
Expand All @@ -25,45 +25,45 @@ pub type TestError = Box<dyn std::error::Error>;
pub type TestResult = Result<(), TestError>;

// TODO(cosmic): Add in functionality for providing shortcuts too
pub struct TempInstallDir {
steam_dir: crate::InstallDir,
pub struct TempSteamDir {
steam_dir: crate::SteamDir,
_tmps: Vec<TempDir>,
}

impl TryFrom<AppFile> for TempInstallDir {
impl TryFrom<AppFile> for TempSteamDir {
type Error = TestError;

fn try_from(app: AppFile) -> Result<Self, Self::Error> {
Self::builder().app(app).finish()
}
}

impl TryFrom<SampleApp> for TempInstallDir {
impl TryFrom<SampleApp> for TempSteamDir {
type Error = TestError;

fn try_from(sample_app: SampleApp) -> Result<Self, Self::Error> {
Self::try_from(AppFile::from(sample_app))
}
}

impl TempInstallDir {
pub fn builder() -> TempInstallDirBuilder {
TempInstallDirBuilder::default()
impl TempSteamDir {
pub fn builder() -> TempSteamDirBuilder {
TempSteamDirBuilder::default()
}

pub fn steam_dir(&self) -> &InstallDir {
pub fn steam_dir(&self) -> &SteamDir {
&self.steam_dir
}
}

#[derive(Default)]
#[must_use]
pub struct TempInstallDirBuilder {
pub struct TempSteamDirBuilder {
libraries: Vec<TempLibrary>,
apps: Vec<AppFile>,
}

impl TempInstallDirBuilder {
impl TempSteamDirBuilder {
pub fn app(mut self, app: AppFile) -> Self {
self.apps.push(app);
self
Expand All @@ -75,7 +75,7 @@ impl TempInstallDirBuilder {
}

// Steam dir is also a library, but is laid out slightly differently than a regular library
pub fn finish(self) -> Result<TempInstallDir, TestError> {
pub fn finish(self) -> Result<TempSteamDir, TestError> {
let tmp = test_temp_dir()?;
let root_dir = tmp.path().join("test-steam-dir");
let steam_dir = root_dir.join("Steam");
Expand All @@ -94,8 +94,8 @@ impl TempInstallDirBuilder {
.chain(self.libraries.into_iter().map(|library| library._tmp))
.collect();

Ok(TempInstallDir {
steam_dir: InstallDir::from_steam_dir(&steam_dir)?,
Ok(TempSteamDir {
steam_dir: SteamDir::from_steam_dir(&steam_dir)?,
_tmps: tmps,
})
}
Expand Down Expand Up @@ -290,7 +290,7 @@ impl SampleApp {

#[test]
fn sanity() -> TestResult {
let tmp_steam_dir = TempInstallDir::try_from(SampleApp::GarrysMod)?;
let tmp_steam_dir = TempSteamDir::try_from(SampleApp::GarrysMod)?;
let steam_dir = tmp_steam_dir.steam_dir();
assert!(steam_dir.app(SampleApp::GarrysMod.id()).unwrap().is_some());

Expand Down
2 changes: 1 addition & 1 deletion src/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub mod test_helpers;
pub mod helpers;
#[cfg(test)]
mod tests;
Loading