1
\$\begingroup\$

For work, we have to use Atlassian Jira, which is depressing. To make my life a bit easier, I decided to write a cli application to get ticket summaries, and I thought it would make a good first project in rust. The code below works, but I would be grateful for any tips/improvements. I'm a python programmer, so it's almost certainly not idiomatic rust...

extern crate reqwest;
extern crate tokio;
use serde_json;
use reqwest::header::{AUTHORIZATION,ACCEPT,CONTENT_TYPE,HeaderValue,HeaderMap};

const BASE_URL: &str = "https://subdomain.atlassian.net/rest/api/latest/issue";

fn parse_config() -> String {
    let config_file = std::fs::read_to_string("/home/username/.config/jiracli").expect("No config file found");
    String::from(config_file.trim())
}

async fn summarise(client: reqwest::Client, ticket_number:String) -> Result<String, Box<dyn std::error::Error>> {
    let compiled_url = format!("{}/{}", &BASE_URL, ticket_number);
    let json_response: serde_json::Value = client.get(&compiled_url).send().await?.json().await?;
    let ticket_fields = json_response["fields"].as_object().unwrap();
    let ticket_summary = ticket_fields.get("summary").unwrap().as_str().unwrap();
    let ticket_status = ticket_fields["status"].as_object().unwrap().get("name").unwrap().as_str().unwrap();
    let ticket_creator = ticket_fields["creator"].as_object().unwrap().get("displayName").unwrap().as_str().unwrap();
    let response=format!("Creator: {}\nStatus: {}\nSummary: {}", ticket_creator,ticket_status,ticket_summary);
    Ok(String::from(response))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let verb = std::env::args().nth(1).expect("No verb provided");
    let ticket_number = std::env::args().nth(2).expect("No ticket provided");
    let formatted_auth = format!("Basic {}", parse_config());
    let auth_header_value = HeaderValue::from_str(&formatted_auth).unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, auth_header_value);
    headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
    headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
    let client = reqwest::Client::builder()
        .default_headers(headers)
        .build()?;
    let result = match &verb[..] {
        "summary" => Ok(summarise(client, ticket_number).await),
        _ => Err("Not implemented")
    };
    println!("{}", result.unwrap()?);
    Ok(())
}

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.