Skip to content

Commit

Permalink
Run Rust formatter (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaishavGandhi authored Apr 4, 2020
1 parent c4ebcfd commit ac45fbc
Show file tree
Hide file tree
Showing 7 changed files with 280 additions and 196 deletions.
72 changes: 43 additions & 29 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
use reqwest::blocking::RequestBuilder;
use std::{io, fs};
use serde::{Deserialize};
use crate::structs::{FabConfig, WhoAmIResponse};
use std::fs::{read_to_string, File};
use crate::WHO_AM_I;
use reqwest::blocking::RequestBuilder;
use serde::Deserialize;
use std::fs::{read_to_string, File};
use std::{fs, io};

pub fn init() -> Result<FabConfig, String> {
let existing_config = read_config();

match existing_config {
Ok(config) => Result::Ok(config),
Err(_) => {
println!(" _ _ _ _ ______ _
println!(
" _ _ _ _ ______ _
| | | | | | | | | ___| | |
| | | | ___| | ___ ___ _ __ ___ ___ | |_ ___ | |_ __ _| |__
| |/\\| |/ _ \\ |/ __/ _ \\| '_ ` _ \\ / _ \\ | __/ _ \\ | _/ _` | '_ \\
\\ /\\ / __/ | (_| (_) | | | | | | __/ | || (_) | | || (_| | |_) |
\\/ \\/ \\___|_|\\___\\___/|_| |_| |_|\\___| \\__\\___/ \\_| \\__,_|_.__/");
\\/ \\/ \\___|_|\\___\\___/|_| |_| |_|\\___| \\__\\___/ \\_| \\__,_|_.__/"
);

println!("Let's get you started!");
println!("Enter the URL where your Phabricator instance is hosted. Example: https://phab.mycompany.com/");
Expand All @@ -38,13 +40,13 @@ pub fn init() -> Result<FabConfig, String> {
// Get user's details
let phid = match get_phid(&hosted_instance, &token) {
Ok(phid) => phid,
Err(message) => panic!(message)
Err(message) => panic!(message),
};

let config = FabConfig {
hosted_instance,
api_token: token,
phid
phid,
};

write_config(&config);
Expand All @@ -56,7 +58,10 @@ pub fn init() -> Result<FabConfig, String> {

/// Function that will execute the network request provided by RequestBuilder and
/// prompt for an API token if session is invalidated.
pub fn send<T: serde::de::DeserializeOwned>(config: &FabConfig, request: RequestBuilder) -> Result<T, String> {
pub fn send<T: serde::de::DeserializeOwned>(
config: &FabConfig,
request: RequestBuilder,
) -> Result<T, String> {
let request = request.try_clone().unwrap();
let response = request
.send()
Expand All @@ -78,25 +83,27 @@ pub fn send<T: serde::de::DeserializeOwned>(config: &FabConfig, request: Request
let new_config = FabConfig {
api_token: token,
hosted_instance: current_config.hosted_instance,
phid: current_config.phid
phid: current_config.phid,
};

write_config(&new_config)
},
}
Err(_err) => {}
}
}
}
Result::Err(String::from("Token regenerated. Please try the command again"))
Result::Err(String::from(
"Token regenerated. Please try the command again",
))
}

/// Prompts for a token and writes the token to the configuration file.
fn prompt_token(hosted_instance: &str) -> Result<String, String> {

println!("Enter an API token that Fab can use. You can create one at {}settings/user/YOUR_USERNAME/page/apitokens", &hosted_instance);
let mut api_token = String::new();

io::stdin().read_line(&mut api_token)
io::stdin()
.read_line(&mut api_token)
.expect("Failed to read token");

// Trim newlines
Expand All @@ -112,7 +119,8 @@ fn prompt_token(hosted_instance: &str) -> Result<String, String> {
fn prompt_hosted_instance() -> Result<String, String> {
let mut hosted_instance = String::new();

io::stdin().read_line(&mut hosted_instance)
io::stdin()
.read_line(&mut hosted_instance)
.expect("Failed to read URL");

// Trim newlines
Expand All @@ -132,41 +140,47 @@ fn prompt_hosted_instance() -> Result<String, String> {
}

fn write_config(config: &FabConfig) {
let path_buf = dirs::home_dir()
.expect("Couldn't find home directory");
let path_buf = dirs::home_dir().expect("Couldn't find home directory");

let home_dir = path_buf.to_str().expect("Couldn't convert home directory to string.");
let home_dir = path_buf
.to_str()
.expect("Couldn't convert home directory to string.");
let fab_dir = format!("{}/.fab", home_dir);
let config_file = format!("{}/.fab/config.json", home_dir);

fs::create_dir_all(&fab_dir).unwrap_or_else(|_| panic!("Couldn't create directory {}", &fab_dir));
serde_json::to_writer(&File::create(config_file).expect("Couldn't load file"), &config).expect("Couldn't write config to file");
fs::create_dir_all(&fab_dir)
.unwrap_or_else(|_| panic!("Couldn't create directory {}", &fab_dir));
serde_json::to_writer(
&File::create(config_file).expect("Couldn't load file"),
&config,
)
.expect("Couldn't write config to file");
}

/// Tries to read the config file
fn read_config() -> Result<FabConfig, String> {
let path_buf = dirs::home_dir()
.expect("Couldn't find home directory");
let path_buf = dirs::home_dir().expect("Couldn't find home directory");

let home_dir = path_buf.to_str().expect("Couldn't convert home directory to string.");
let home_dir = path_buf
.to_str()
.expect("Couldn't convert home directory to string.");
let config_file = format!("{}/.fab/config.json", home_dir);

let contents = read_to_string(&config_file);

match contents {
Err(_message) => Result::Err(String::from("Failed to read file")),
Ok(content) => {
let config: FabConfig = ::serde_json::from_str(&content).expect("Couldn't deserialize to FabConfig");
let config: FabConfig =
::serde_json::from_str(&content).expect("Couldn't deserialize to FabConfig");
Result::Ok(config)
}
}
}

fn get_phid(hosted_instance: &str, api_token: &str) -> Result<String, String> {
let url = format!("{}{}", hosted_instance, WHO_AM_I);
let json_body = json!({
"api.token": api_token
});
let json_body = json!({ "api.token": api_token });

let response = reqwest::blocking::Client::new()
.post(&url)
Expand All @@ -176,12 +190,12 @@ fn get_phid(hosted_instance: &str, api_token: &str) -> Result<String, String> {

match response.json::<WhoAmIResponse>() {
Ok(res) => Result::Ok(res.result.phid),
Err(_message) => Result::Err(String::from("Error getting user's phabricator ID"))
Err(_message) => Result::Err(String::from("Error getting user's phabricator ID")),
}
}

#[derive(Deserialize, Debug)]
struct NetworkResponse<T> {
pub error_code: Option<String>,
pub result: Option<T>
pub result: Option<T>,
}
62 changes: 33 additions & 29 deletions src/diffs.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::structs::{Revision, FabConfig, RevisionData};
use clap::ArgMatches;
use comfy_table::{Table, Cell, ContentArrangement, Attribute, CellAlignment};
use crate::NO_BORDER_PRESET;
use crate::auth;
use crate::structs::{FabConfig, Revision, RevisionData};
use crate::NO_BORDER_PRESET;
use clap::ArgMatches;
use comfy_table::{Attribute, Cell, CellAlignment, ContentArrangement, Table};

const DIFFERENTIAL_SEARCH_URL: &str = "api/differential.revision.search";

Expand All @@ -20,54 +20,59 @@ pub fn process_diff_command(_matches: &ArgMatches, config: &FabConfig) {
/// Get diffs that are authored by the user.
pub fn get_authored_diffs(config: &FabConfig) -> Result<Vec<Revision>, String> {
let json_body = json!({
"queryKey": "authored",
"api.token": config.api_token,
});
"queryKey": "authored",
"api.token": config.api_token,
});

let url = format!("{}{}", &config.hosted_instance, DIFFERENTIAL_SEARCH_URL.to_string());
let url = format!(
"{}{}",
&config.hosted_instance,
DIFFERENTIAL_SEARCH_URL.to_string()
);

let result = auth::send::<RevisionData>(config, reqwest::blocking::Client::new()
.post(&url)
.form(&json_body));
let result = auth::send::<RevisionData>(
config,
reqwest::blocking::Client::new().post(&url).form(&json_body),
);

match result {
Ok(result) => {
let revisions = result.data
let revisions = result
.data
.into_iter()
.filter(|rev| !rev.fields.status.closed)
.collect();
Result::Ok(revisions)
},
Err(_err) => {
Result::Err(String::from("Couldn't fetch authored diffs"))
}
Err(_err) => Result::Err(String::from("Couldn't fetch authored diffs")),
}
}

/// Get the diffs that needs review from the user.
pub fn get_needs_review_diffs(config: &FabConfig) -> Result<Vec<Revision>, String> {
let json_body = json!({
"api.token": config.api_token,
"constraints[reviewerPHIDs][0]": config.phid
});
"api.token": config.api_token,
"constraints[reviewerPHIDs][0]": config.phid
});

let url = format!("{}{}", config.hosted_instance, DIFFERENTIAL_SEARCH_URL);

let result = auth::send::<RevisionData>(config, reqwest::blocking::Client::new()
.post(&url)
.form(&json_body));

let result = auth::send::<RevisionData>(
config,
reqwest::blocking::Client::new().post(&url).form(&json_body),
);

match result {
Ok(response) => {
let revisions = response.data
let revisions = response
.data
.into_iter()
.filter(|rev| !rev.fields.status.closed)
.collect();

Result::Ok(revisions)
},
Err(_err) => Result::Err(String::from("Failed to fetch needs-review diffs"))
}
Err(_err) => Result::Err(String::from("Failed to fetch needs-review diffs")),
}
}

Expand All @@ -86,16 +91,15 @@ pub fn render_diffs(config: &FabConfig, revisions: &[Revision]) {
.set_alignment(CellAlignment::Center)
.add_attribute(Attribute::Bold),
Cell::new(&revision.fields.title),
Cell::new(&revision.url(config))
.add_attribute(Attribute::Bold)
Cell::new(&revision.url(config)).add_attribute(Attribute::Bold),
]);
}
println!("{}", table);
}


fn process_diffs_needs_review(config: &FabConfig) {
let revisions = get_needs_review_diffs(config).expect("Failed to fetch response for needs-review diffs");
let revisions =
get_needs_review_diffs(config).expect("Failed to fetch response for needs-review diffs");

// let revisions = response.data.iter().filter(|rev| !rev.fields.status.closed).collect();
render_diffs(config, &revisions)
Expand Down
Loading

0 comments on commit ac45fbc

Please sign in to comment.