Skip to content

Commit

Permalink
▱ Fetch entities in parallel for real
Browse files Browse the repository at this point in the history
- Futures are cold, JS brain gaslight me

Co-authored-by: William Barbosa <[email protected]>
  • Loading branch information
shantanuraj and heytherewill committed Dec 12, 2023
1 parent 373a0e2 commit e1b748f
Show file tree
Hide file tree
Showing 14 changed files with 85 additions and 46 deletions.
61 changes: 45 additions & 16 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ serde = { version = "1.0.159", features = ["derive"] }
serde_json = "1.0.95"
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1.27.0", features = ["full"] }
futures = "0.3.29"
base64 = "0.21.0"
async-trait = "0.1.68"

Expand Down
25 changes: 14 additions & 11 deletions src/api/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,18 @@ impl V9ApiClient {
let header_content =
"Basic ".to_string() + general_purpose::STANDARD.encode(auth_string).as_str();
let mut headers = header::HeaderMap::new();
let auth_header = header::HeaderValue::from_str(header_content.as_str())?;
let auth_header = header::HeaderValue::from_str(header_content.as_str()).expect("Invalid header value");
headers.insert(header::AUTHORIZATION, auth_header);

let base_client = Client::builder().default_headers(headers);
let http_client = {
if let Some(proxy) = proxy {
base_client.proxy(reqwest::Proxy::all(proxy)?)
base_client.proxy(reqwest::Proxy::all(proxy).expect("Invalid proxy"))
} else {
base_client
}
}
.build()?;
.build().expect("Couldn't build a http client");
let api_client = Self {
http_client,
base_url: "https://track.toggl.com/api/v9".to_string(),
Expand Down Expand Up @@ -140,13 +140,16 @@ impl ApiClient for V9ApiClient {
}

async fn get_entities(&self) -> ResultWithDefaultError<Entities> {
let network_time_entries = self.get_time_entries();
let network_projects = self.get_projects();
let network_tasks = self.get_tasks();
let network_clients = self.get_clients();
let (network_time_entries, network_projects, network_tasks, network_clients) =
futures::future::join4(
self.get_time_entries(),
self.get_projects(),
self.get_tasks(),
self.get_clients(),
).await;

let clients: HashMap<i64, crate::models::Client> = network_clients
.await?
.unwrap_or_default()
.iter()
.map(|c| {
(
Expand All @@ -161,7 +164,7 @@ impl ApiClient for V9ApiClient {
.collect();

let projects: HashMap<i64, Project> = network_projects
.await?
.unwrap_or_default()
.iter()
.map(|p| {
(
Expand All @@ -183,7 +186,7 @@ impl ApiClient for V9ApiClient {
.collect();

let tasks: HashMap<i64, Task> = network_tasks
.await?
.unwrap_or_default()
.iter()
.map(|t| {
(
Expand All @@ -199,7 +202,7 @@ impl ApiClient for V9ApiClient {
.collect();

let time_entries = network_time_entries
.await?
.unwrap_or_default()
.iter()
.map(|te| TimeEntry {
id: te.id,
Expand Down
2 changes: 1 addition & 1 deletion src/commands/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl AuthenticationCommand {
"{} {}",
AUTH_SUCCEEDED_MESSAGE.green(),
user.email.green().bold(),
)?;
).expect("failed to write to stdout");

Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions src/commands/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ impl StartCommand {
let workspace_id = (api_client.get_user().await?).default_workspace_id;
let entities = api_client.get_entities().await?;

let config_path = config::locate::locate_config_path()?;
let track_config = config::parser::get_config_from_file(config_path)?;
let config_path = config::locate::locate_config_path().expect("failed to locate config");
let track_config = config::parser::get_config_from_file(config_path).expect("failed to parse config");
let default_time_entry = track_config.get_default_entry(entities.clone())?;

let project = project_name
Expand Down
4 changes: 2 additions & 2 deletions src/config/active.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ pub struct ConfigActiveCommand;

impl ConfigActiveCommand {
pub async fn execute() -> ResultWithDefaultError<()> {
let config_path = super::locate::locate_config_path()?;
let track_config = super::parser::get_config_from_file(config_path)?;
let config_path = super::locate::locate_config_path().expect("failed to locate config");
let track_config = super::parser::get_config_from_file(config_path).expect("failed to parse config");
println!("{}", track_config.get_active_config()?);
Ok(())
}
Expand Down
8 changes: 4 additions & 4 deletions src/config/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ impl ConfigInitCommand {
match config_path {
Ok(path) => {
if edit {
utilities::open_path_in_editor(path)?
utilities::open_path_in_editor(path).expect("failed to open config in editor");
} else {
let display_path = utilities::simplify_config_path_for_display(path.as_path());
println!(
Expand All @@ -22,16 +22,16 @@ impl ConfigInitCommand {
}
Err(_) => {
let default_config = include_bytes!("./fixtures/default.toml");
let config_path = super::locate::get_config_path_for_current_dir()?;
let config_path = super::locate::get_config_path_for_current_dir().expect("failed to get config path for current directory");
let config_dir = config_path.parent().unwrap();
let display_config_path = utilities::simplify_config_path_for_display(config_dir);
let msg = format!(
"{} {}",
"Created config at".green().bold(),
display_config_path
);
std::fs::create_dir_all(config_dir)?;
std::fs::write(config_path, default_config)?;
std::fs::create_dir_all(config_dir).expect("failed to create config directory");
std::fs::write(config_path, default_config).expect("failed to write config");
println!("{}", msg);
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/config/manage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ pub struct ConfigManageCommand;

impl ConfigManageCommand {
pub async fn execute(delete: bool, edit: bool, show_path: bool) -> ResultWithDefaultError<()> {
let path = super::locate::locate_config_path()?;
let path = super::locate::locate_config_path().expect("failed to locate config");
let display_path = utilities::simplify_config_path_for_display(path.as_path());

if delete {
return fs::remove_file(path).map_err(|e| e.into()).map(|_| {
return Ok(fs::remove_file(path).map(|_| {
println!(
"{} {}",
"Config file deleted from".red().bold(),
display_path
);
});
}).expect("failed to delete config"));
}
if edit {
return utilities::open_path_in_editor(path);
Expand Down
2 changes: 1 addition & 1 deletion src/config/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ impl TrackConfig {
self.get_branch_config(branch.as_deref())
}
pub fn get_active_config(&self) -> ResultWithDefaultError<&BranchConfig> {
let current_dir = std::env::current_dir()?;
let current_dir = std::env::current_dir().expect("Failed to get current directory");
return Ok(self.get_branch_config_for_dir(&current_dir));
}
pub fn get_default_entry(&self, entities: Entities) -> ResultWithDefaultError<TimeEntry> {
Expand Down
5 changes: 4 additions & 1 deletion src/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ impl KeyringStorage {

impl CredentialsStorage for KeyringStorage {
fn read(&self) -> ResultWithDefaultError<Credentials> {
let api_token = self.keyring.get_password()?;
let api_token = self
.keyring
.get_password()
.expect("failed to read from keyring");
Ok(Credentials { api_token })
}

Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ async fn execute_subcommand(args: CommandLineArguments) -> ResultWithDefaultErro
if !directory.is_dir() {
return Err(Box::new(error::ArgumentError::NotADirectory(directory)));
}
std::env::set_current_dir(directory)?;
std::env::set_current_dir(directory).expect("Couldn't set current directory");
}
match command {
None => RunningTimeEntryCommand::execute(get_default_api_client()?).await?,
Expand Down
2 changes: 1 addition & 1 deletion src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use colors_transform::{Color, Rgb};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};

pub type ResultWithDefaultError<T> = Result<T, Box<dyn std::error::Error>>;
pub type ResultWithDefaultError<T> = Result<T, Box<dyn std::error::Error + Send>>;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Entities {
Expand Down
7 changes: 5 additions & 2 deletions src/picker/fzf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,16 @@ impl ItemPicker for FzfPicker {
let fzf_input = format_as_fzf_input(&items);
let possible_elements = create_element_hash_map(&items);

writeln!(child.stdin.as_mut().unwrap(), "{}", fzf_input)?;
writeln!(child.stdin.as_mut().unwrap(), "{}", fzf_input)
.expect("Failed to write to fzf stdin");

match child.wait_with_output() {
Err(_) => Err(Box::new(PickerError::Generic)),
Ok(output) => match output.status.code() {
Some(0) => {
let user_selected_string = String::from_utf8(output.stdout)?;
let user_selected_string = String::from_utf8(output.stdout).expect(
"Failed to convert fzf output to string. This should never happen.",
);
let selected_item_index =
utilities::remove_trailing_newline(user_selected_string);
let selected_item =
Expand Down
2 changes: 1 addition & 1 deletion src/utilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub fn read_from_stdin_with_constraints(text: &str, valid_values: &[String]) ->
}
}

pub fn open_path_in_editor<P>(path: P) -> Result<(), Box<dyn std::error::Error>>
pub fn open_path_in_editor<P>(path: P) -> Result<(), Box<dyn std::error::Error + Send>>
where
P: AsRef<Path> + std::convert::AsRef<std::ffi::OsStr>,
{
Expand Down

0 comments on commit e1b748f

Please sign in to comment.