Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for posting comments #6

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# Version with a security patch:
chrono = { version = ">=0.4.20", features = ["serde"] }
tracing = "0.1.41"

[dev-dependencies]
tokio = { version = ">=1.37", features = ["full"] }
71 changes: 70 additions & 1 deletion src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@ limitations under the License.
// * https://docs.atlassian.com/software/jira/docs/api/REST/latest/
// * https://docs.atlassian.com/jira-software/REST/latest/

use serde::Serialize;

use crate::errors::JiraQueryError;
use crate::issue_model::{Issue, JqlResults};
use crate::{Comment, User};

// The prefix of every subsequent REST request.
// This string comes directly after the host in the URL.
Expand Down Expand Up @@ -74,6 +77,8 @@ enum Method<'a> {
Key(&'a str),
Keys(&'a [&'a str]),
Search(&'a str),
User(&'a str),
Myself(),
}

impl<'a> Method<'a> {
Expand All @@ -82,6 +87,8 @@ impl<'a> Method<'a> {
Self::Key(id) => format!("issue/{id}"),
Self::Keys(ids) => format!("search?jql=id%20in%20({})", ids.join(",")),
Self::Search(query) => format!("search?jql={query}"),
Self::User(id) => format!("user?accountId={id}"),
Self::Myself() => format!("myself"),
}
}
}
Expand Down Expand Up @@ -137,7 +144,7 @@ impl JiraInstance {

// The `startAt` option is only valid with JQL. With a URL by key, it breaks the REST query.
let start_at = match method {
Method::Key(_) => String::new(),
Method::Key(_) | Method::User(_) | Method::Myself() => String::new(),
Method::Keys(_) | Method::Search(_) => format!("&startAt={start_at}"),
};

Expand All @@ -162,6 +169,24 @@ impl JiraInstance {
authenticated.send().await
}

async fn authenticated_post<T: Serialize + Sized>(
&self,
url: &str,
body: &T,
) -> Result<reqwest::Response, reqwest::Error> {
let request_builder = self.client.post(url);
let authenticated = match &self.auth {
Auth::Anonymous => request_builder,
Auth::ApiKey(key) => request_builder.header("Authorization", &format!("Bearer {key}")),
Auth::Basic { user, password } => request_builder.basic_auth(user, Some(password)),
};
authenticated
.header("Content-Type", "application/json")
.json(body)
.send()
.await
}

// This method uses a separate implementation from `issues` because Jira provides a way
// to request a single ticket specifically. That conveniently handles error cases
// where no tickets might match, or more than one might.
Expand Down Expand Up @@ -279,6 +304,50 @@ impl JiraInstance {
Ok(issues)
}
}

pub async fn post_comment(
&self,
issue_id: &str,
_user_id: &str,
content: &str,
) -> Result<Comment, Box<dyn std::error::Error + Send + Sync>> {
let url = self.path(&Method::Key(issue_id), 0) + "/comment";

tracing::info!("URL: {}", url);

// let user_url = self.path(&Method::User(user_id), 0);
let user_url = self.path(&Method::Myself(), 0);

tracing::info!("User URL: {}", user_url);

let user = self
.authenticated_get(&user_url)
.await?
.json::<User>()
.await?;

tracing::info!("User: {:#?}", user);

// TODO: If user_id != "", don't use myself
let comment = Comment {
// author: Some(user),
body: content.to_owned(),
..Default::default()
};

tracing::info!("Built comment: {:#?}", comment);

// let response = self.authenticated_post(&url, &comment).await?;
let response = self.authenticated_post(&url, &comment).await?;

tracing::info!("Response: {:#?}", response);

let comment = response.json::<Comment>().await?;

tracing::info!("Parsed comment: {:#?}", comment);

Ok(comment)
}
}

#[cfg(test)]
Expand Down
18 changes: 9 additions & 9 deletions src/issue_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ pub struct Fields {
pub timespent: Option<i32>,
pub aggregatetimespent: Option<i32>,
pub aggregatetimeoriginalestimate: Option<i32>,
pub progress: Progress,
pub aggregateprogress: Progress,
pub progress: Option<Progress>,
pub aggregateprogress: Option<Progress>,
pub workratio: i64,
pub summary: String,
pub creator: User,
Expand Down Expand Up @@ -272,18 +272,18 @@ pub struct Progress {
}

/// A comment below a Jira issue.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct Comment {
pub author: User,
pub author: Option<User>,
pub body: String,
pub created: DateTime<Utc>,
pub id: String,
pub created: Option<DateTime<Utc>>,
pub id: Option<String>,
#[serde(rename = "updateAuthor")]
pub update_author: User,
pub updated: DateTime<Utc>,
pub update_author: Option<User>,
pub updated: Option<DateTime<Utc>>,
pub visibility: Option<Visibility>,
#[serde(rename = "self")]
pub self_link: String,
pub self_link: Option<String>,
#[serde(flatten)]
pub extra: Value,
}
Expand Down
15 changes: 15 additions & 0 deletions tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ fn apache_jira() -> JiraInstance {
JiraInstance::at("https://issues.apache.org/jira/".to_string()).unwrap()
}

/// A common convenience function to get anonymous access
/// to the Whamcloud Jira instance.
fn whamcloud_jira() -> JiraInstance {
JiraInstance::at("https://jira.whamcloud.com".to_string()).unwrap()
}

/// Try accessing several public issues separately
/// to test the client and the deserialization.
#[tokio::test]
Expand Down Expand Up @@ -148,3 +154,12 @@ async fn access_apache_issues() {
.await
.unwrap();
}

#[tokio::test]
async fn access_whamcloud_issues() {
let instance = whamcloud_jira();
let _issues = instance
.issues(&["LU-10647", "LU-13009", "LU-8002", "LU-8874"])
.await
.unwrap();
}