1use crate::Ctx;
2use std::{io::Write, path::PathBuf};
3
4pub enum StateField {
5 Endpoint,
6 PreviousEndpoint,
7 Env,
8}
9
10pub struct State {
11 pub handle: Option<String>,
12 pub previous_handle: Option<String>,
13}
14
15impl StateField {
16 pub const STATE_DIR: &'static str = "user/state";
17
18 pub fn file_path(&self, ctx: &Ctx) -> PathBuf {
19 ctx.path().join(Self::STATE_DIR).join(match self {
20 Self::Endpoint => "endpoint",
21 Self::Env => "env",
22 Self::PreviousEndpoint => "previous-endpoint",
23 })
24 }
25
26 pub fn get(&self, ctx: &Ctx) -> Result<String, Box<dyn std::error::Error>> {
27 let bytes = std::fs::read(self.file_path(ctx))?;
28
29 Ok(String::from_utf8(bytes)?)
30 }
31
32 pub fn set(&self, ctx: &Ctx, value: &str) -> Result<(), std::io::Error> {
33 let file = std::fs::OpenOptions::new()
34 .truncate(true)
35 .create(true)
36 .write(true)
37 .open(self.file_path(ctx));
38
39 file?.write_all(value.as_bytes())
40 }
41}
42
43impl State {
44 pub fn get(&self, ctx: &Ctx, field: StateField) -> Result<String, Box<dyn std::error::Error>> {
45 let overwrite = match field {
46 StateField::Endpoint => self.handle.clone(),
47 _ => None,
48 };
49
50 if let Some(overwrite) = overwrite {
51 return Ok(overwrite);
52 }
53
54 field.get(ctx)
55 }
56}