chiark / gitweb /
Make this program build on Windows!
authorSimon Tatham <anakin@pobox.com>
Sun, 31 Dec 2023 14:29:20 +0000 (14:29 +0000)
committerSimon Tatham <anakin@pobox.com>
Sun, 31 Dec 2023 14:30:54 +0000 (14:30 +0000)
I tried it out of pure curiosity. As I expected, the 'xdg' crate
didn't work (I already knew it was documented to not work on Windows),
but everything else was fine, and it compiles and runs!

Cargo.toml
src/config.rs

index c425f21135cbb41488de9a86cdff126d26fc131c..ca75ce13a0be3807088e43c6bcf8da812606e1d0 100644 (file)
@@ -16,4 +16,6 @@ reqwest = { version = "0.11.23", features = ["blocking"] }
 serde = { version = "1.0.193", features = ["derive"] }
 serde_json = "1.0.108"
 unicode-width = "0.1.5"
+
+[target.'cfg(unix)'.dependencies]
 xdg = "2.5.2"
index 70e1ab44ae7cfb85e4411d54c5ee3fd62dac511d..e6c50103c75ff5152af3ef098f27743e3029dec9 100644 (file)
@@ -1,8 +1,15 @@
 use std::path::PathBuf;
 
+#[cfg(windows)]
+use std::str::FromStr;
+
 #[derive(Debug)]
 pub enum ConfigError {
+    #[cfg(unix)]
     XDG(xdg::BaseDirectoriesError),
+
+    #[cfg(windows)]
+    Env(std::env::VarError),
 }
 
 impl std::fmt::Display for ConfigError {
@@ -10,22 +17,46 @@ impl std::fmt::Display for ConfigError {
         Result<(), std::fmt::Error>
     {
         match self {
+            #[cfg(unix)]
             ConfigError::XDG(e) => { e.fmt(f) },
+
+            #[cfg(windows)]
+            ConfigError::Env(e) => {
+                // FIXME: how _should_ we include the information
+                // about what environment variable?
+                write!(f, "%APPDATA%: {}", e)
+            },
         }
     }
 }
 
+#[cfg(unix)]
 impl From<xdg::BaseDirectoriesError> for ConfigError {
     fn from(err: xdg::BaseDirectoriesError) -> Self {
         ConfigError::XDG(err)
     }
 }
 
+#[cfg(windows)]
+impl From<std::env::VarError> for ConfigError {
+    fn from(err: std::env::VarError) -> Self {
+        ConfigError::Env(err)
+    }
+}
+
+#[cfg(windows)]
+impl From<std::convert::Infallible> for ConfigError {
+    fn from(_: std::convert::Infallible) -> Self {
+        panic!("I thought you said it was infallible?");
+    }
+}
+
 pub struct ConfigLocation {
     dir: PathBuf,
 }
 
 impl ConfigLocation {
+    #[cfg(unix)]
     pub fn default() -> Result<Self, ConfigError> {
         let base_dirs = xdg::BaseDirectories::with_prefix("mastodonochrome")?;
         Ok(ConfigLocation {
@@ -33,6 +64,17 @@ impl ConfigLocation {
         })
     }
 
+    #[cfg(windows)]
+    pub fn default() -> Result<Self, ConfigError> {
+        let appdata = std::env::var("APPDATA")?;
+        let mut dir = PathBuf::from_str(&appdata)?;
+        dir.push("mastodonochrome");
+
+        Ok(ConfigLocation {
+            dir: dir,
+        })
+    }
+
     pub fn from_pathbuf(dir: PathBuf) -> Self {
         ConfigLocation {
             dir: dir,