Skip to content

Commit

Permalink
feat: first working version
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben Nagy committed Apr 23, 2024
1 parent 11dfed9 commit edb05aa
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 11 deletions.
33 changes: 31 additions & 2 deletions src/components/pull_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ type DateTime = chrono::DateTime<chrono::Utc>;
use graphql_client::GraphQLQuery;
use serde::{Deserialize, Serialize};

use self::pull_requests_query::{PullRequestsQuerySearchEdgesNode, PullRequestsQuerySearchEdgesNodeOnPullRequest};
use self::pull_requests_query::{
PullRequestReviewState, PullRequestState, PullRequestsQuerySearchEdgesNodeOnPullRequest,
};

#[derive(GraphQLQuery)]
#[graphql(
schema_path = "src/github/schema.graphql",
query_path = "src/github/queries/pull_requests.graphql",
variables_derives = "Clone, Debug",
variables_derives = "Clone, Debug, Eq, PartialEq",
response_derives = "Clone, Debug"
)]
pub struct PullRequestsQuery;
Expand All @@ -25,6 +28,15 @@ pub struct PullRequest {
pub changed_files: usize,
pub additions: usize,
pub deletions: usize,
pub state: PullRequestState,
pub is_draft: bool,
pub reviews: Vec<PullRequestReview>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PullRequestReview {
pub author: String,
pub state: PullRequestReviewState,
}

impl From<&PullRequestsQuerySearchEdgesNodeOnPullRequest> for PullRequest {
Expand All @@ -39,6 +51,23 @@ impl From<&PullRequestsQuerySearchEdgesNodeOnPullRequest> for PullRequest {
changed_files: value.changed_files as usize,
additions: value.additions as usize,
deletions: value.deletions as usize,
state: value.state.clone(),
is_draft: value.is_draft,
reviews: value
.latest_reviews
.as_ref()
.unwrap()
.edges
.as_ref()
.unwrap()
.iter()
.map(|v| {
PullRequestReview {
author: v.as_ref().unwrap().node.as_ref().unwrap().author.as_ref().unwrap().login.clone(),
state: v.as_ref().unwrap().node.as_ref().unwrap().state.clone(),
}
})
.collect(),
}
}
}
67 changes: 61 additions & 6 deletions src/components/repo_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ use ratatui::{
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc::UnboundedSender;

use super::pull_request;
use super::pull_request::{self, pull_requests_query::PullRequestState};
use crate::{
action::Action,
components::{
pull_request::{pull_requests_query, PullRequest, PullRequestsQuery},
pull_request::{
pull_requests_query, pull_requests_query::PullRequestReviewState, PullRequest, PullRequestsQuery,
},
Component, Frame,
},
config::{Config, KeyBindings},
Expand All @@ -30,6 +32,7 @@ pub struct PullRequestList {
config: Config,
selected_row: usize,
pull_requests: Vec<PullRequest>,
username: String,
}

impl PullRequestList {
Expand All @@ -42,10 +45,30 @@ impl PullRequestList {
tokio::spawn(async move {
let token = std::env::var("GITHUB_TOKEN").expect("GITHUB_TOKEN must be set");
let oc = Octocrab::builder().personal_token(token).build().expect("Failed to create Octocrab client");
let response: octocrab::Result<graphql_client::Response<pull_requests_query::ResponseData>> =
oc.graphql(&PullRequestsQuery::build_query(pull_requests_query::Variables {})).await;
log::info!("Fetching pull requests");
let response: serde_json::Value = oc
.graphql(&serde_json::json!({ "query": "{ viewer { login }}" }))
.await
.unwrap_or(serde_json::Value::Null);

if let serde_json::Value::Null = response {
tx.send(Action::Error("Failed to get current user".to_string())).unwrap();
return;
}

let username = response["data"]["viewer"]["login"].as_str().unwrap();

log::info!("{}", username);

let response: octocrab::Result<graphql_client::Response<pull_requests_query::ResponseData>> = oc
.graphql(&PullRequestsQuery::build_query(pull_requests_query::Variables {
first: 10,
query: format!("is:pr involves:{} state:open", username),
}))
.await;
match response {
Ok(response) => {
log::info!("{:#?}", response);
let r = response.data.unwrap().search.edges.unwrap();
let pull_requests: Vec<PullRequest> = r
.iter()
Expand Down Expand Up @@ -122,16 +145,48 @@ impl Component for PullRequestList {
Span::styled(format!("{:+}", pr.additions), Style::new().fg(Color::LightGreen)),
Span::styled(format!("{:+}", (0 - pr.deletions as isize)), Style::new().fg(Color::LightRed)),
])),
Cell::from(match pr.state {
pull_requests_query::PullRequestState::OPEN => {
if pr.is_draft {
"DRAFT"
} else {
"OPEN"
}
},
_ => "Unknown",
}),
Cell::from(Line::from(
pr.reviews
.iter()
.map(|prr| {
vec![
Span::styled(prr.author.clone(), match prr.state {
PullRequestReviewState::COMMENTED => Style::new().fg(Color::LightBlue),
PullRequestReviewState::APPROVED => Style::new().fg(Color::LightGreen),
PullRequestReviewState::CHANGES_REQUESTED => {
Style::new().fg(Color::LightYellow)
},
_ => Style::new().fg(Color::Gray),
}),
Span::raw(" "),
]
})
.flatten()
.collect::<Vec<Span>>(),
)),
])
})
.collect::<Vec<_>>();
let mut table_state = TableState::default();
table_state.select(Some(self.selected_row));
let table = Table::default()
.widths(Constraint::from_lengths([4, 30, 60, 20, 20, 6, 6]))
.widths(Constraint::from_lengths([4, 40, 80, 20, 20, 6, 6, 50]))
.rows(rows)
.column_spacing(1)
.header(Row::new(vec!["#", "Title", "Repository", "Created", "Updated"]).bottom_margin(1))
.header(
Row::new(vec!["#", "Repository", "Title", "Created", "Updated", "Changes", "State", "Reviews"])
.bottom_margin(1),
)
.block(
Block::default()
.title(Title::from("Pull Requests"))
Expand Down
7 changes: 5 additions & 2 deletions src/github/queries/pull_requests.graphql
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
query PullRequestsQuery {
search($query: String!, type: ISSUE, $first: Int!) {
query PullRequestsQuery($query: String!, $first: Int!) {
search(type: ISSUE, query: $query, first: $first) {
edges {
node {
__typename
Expand All @@ -15,9 +15,12 @@ query PullRequestsQuery {
changedFiles
additions
deletions
state
isDraft
latestReviews(last: 10) {
edges {
node {
state
author {
__typename
login
Expand Down
3 changes: 2 additions & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ lazy_static! {
}

fn project_directory() -> Option<ProjectDirs> {
ProjectDirs::from("com", "ghtui-rs", env!("CARGO_PKG_NAME"))
ProjectDirs::from("com", "nagyben", env!("CARGO_PKG_NAME"))
}

pub fn initialize_panic_handler() -> Result<()> {
Expand Down Expand Up @@ -98,6 +98,7 @@ pub fn initialize_logging() -> Result<()> {
let directory = get_data_dir();
std::fs::create_dir_all(directory.clone())?;
let log_path = directory.join(LOG_FILE.clone());
print!("{}", log_path.display());
let log_file = std::fs::File::create(log_path)?;
std::env::set_var(
"RUST_LOG",
Expand Down

0 comments on commit edb05aa

Please sign in to comment.