feat(core): Write selected project to file instead of stdout

This commit is contained in:
Patrick Auernig 2024-11-26 17:26:32 +01:00
parent af9da826aa
commit 44dd99e543
2 changed files with 38 additions and 7 deletions

View File

@ -3,6 +3,7 @@ mod tui;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use anyhow::{ensure, Result};
@ -38,7 +39,7 @@ fn main() -> Result<()> {
let result = match &args.cmd {
Some(cmd) => handle_subcommands(projects, cmd),
None => tui::run(projects),
None => run_tui(projects),
};
if let Err(err) = result {
@ -50,6 +51,18 @@ fn main() -> Result<()> {
}
fn run_tui(projects: Projects) -> Result<()> {
clear_selected_project_file()?;
let selected_project = tui::run(projects)?;
if let Some(selected_project) = selected_project {
write_selected_project_file(selected_project)?
}
Ok(())
}
fn handle_subcommands(mut projects: Projects, cmd: &Command) -> Result<()> {
match cmd {
Command::Add { path } => {
@ -91,6 +104,27 @@ fn list_projects(projects: &Projects) -> Result<()> {
Ok(())
}
fn clear_selected_project_file() -> Result<()> {
let cache_file = dirs::cache_path().join("selected-project");
if fs::exists(&cache_file)? {
fs::remove_file(cache_file)?;
}
Ok(())
}
fn write_selected_project_file(path: PathBuf) -> Result<()> {
let cache_file = dirs::cache_path().join("selected-project");
let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(cache_file)?;
write!(file, "{}", path.display())?;
Ok(())
}
fn write_projects_file(projects: &Projects) -> Result<()> {
let projects_file = dirs::data_path().join("projects");

View File

@ -43,7 +43,7 @@ impl State {
}
pub fn run(projects: Projects) -> Result<()> {
pub fn run(projects: Projects) -> Result<Option<PathBuf>> {
let mut term = ratatui::init();
let mut state = State::new(projects);
@ -69,11 +69,7 @@ pub fn run(projects: Projects) -> Result<()> {
ratatui::restore();
if let Some(path) = state.selected_project {
println!("{}", path.display());
}
Ok(())
Ok(state.selected_project)
}
@ -105,6 +101,7 @@ fn handle_messages(state: &mut State, rx: &mut mpsc::Receiver<Message>) -> Resul
match msg {
Message::Exit => {
state.should_exit = true;
state.selected_project = None;
}
Message::MoveDown => {
state.project_table.select_next();