Skip to content

Commit

Permalink
Fixing on feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
TheKrol committed Dec 29, 2024
1 parent ace5a19 commit 3aa7345
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 84 deletions.
11 changes: 1 addition & 10 deletions backend/src/gh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,6 @@ impl GitHubClient {
"head": head_branch,
"base": base_branch,
"body": pr_body,
"labels": ["discord-user:krol430"]
});

debug!("Creating pull request to {}/repos/{}/pulls", GITHUB_API_URL, repo_name);
Expand Down Expand Up @@ -335,7 +334,6 @@ impl GitHubClient {
base_branch: Option<&str>,
issue_numbers: Option<Vec<u64>>,
) -> Result<String> {
info!("Made it to the start of the update PR");
let repo_name = self.get_repo_name()?;

let mut pr_body_json = serde_json::Map::new();
Expand Down Expand Up @@ -652,10 +650,7 @@ impl GitHubClient {
/// - The request to fetch issues fails due to authentication issues, invalid input, or network problems.
/// - The GitHub API response cannot be parsed as a JSON array.
pub async fn get_issues(&self, state: Option<&str>, labels: Option<&str>) -> Result<Vec<Value>> {
let repo_name = self.get_repo_name().map_err(|e| {
error!("Failed to get repository name: {:?}", e);
e
})?;
let repo_name = self.get_repo_name()?;

let state = state.unwrap_or("open"); // Default state
let mut query_params = vec![format!("state={}", state)];
Expand All @@ -677,10 +672,6 @@ impl GitHubClient {
.send()
.await?;

if let Some(rate_limit_remaining) = response.headers().get("X-RateLimit-Remaining") {
debug!("GitHub API rate limit remaining: {}", rate_limit_remaining.to_str().unwrap_or("Unknown"));
}

if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
Expand Down
1 change: 0 additions & 1 deletion backend/src/handlers_prelude/github_handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,6 @@ pub async fn update_pull_request_handler(
State(state): State<AppState>,
Json(payload): Json<UpdatePRRequest>,
) -> Result<(StatusCode, Json<ApiResponse<String>>), (StatusCode, String)> {
info!("Received request to update pull request: {:?}", payload);

// Get the GitHub access token
let token = get_github_token(&state).await.map_err(|err| {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/lib/components/editors/DocumentEditor.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@
.commit-modal-close {
position: sticky;
cursor: pointer;
/*cursor: pointer;*/
margin-top: 0.2rem;
margin-right: 0.2rem;
float: right;
Expand Down
119 changes: 50 additions & 69 deletions frontend/src/lib/components/topbar/PullRequest.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@
branchName,
currentFile,
me,
openIssues,
selectedIssues,
openPullRequests,
baseBranch
} from '$lib/main';
import type { Issue } from '$lib/types';
Expand All @@ -22,6 +19,9 @@
let showLoadingIcon: boolean;
let selectedPullRequest: number | null = null;
let prAuthor = '';
let openIssues: Issue[] = [];
let selectedIssues: Issue[] = [];
let openPullRequests: Issue[] = [];
function openModal() {
showModal = true;
Expand All @@ -30,7 +30,7 @@
}
function closeModal() {
selectedIssues.set([]);
selectedIssues = [];
prCommit = '';
showModal = false;
selectedPullRequest = null;
Expand All @@ -49,72 +49,55 @@
}
}
function toggleSelection(issue: Issue) {
selectedIssues.update((issues: Issue[]) => {
const idx = issues.findIndex((i) => i.id === issue.id);
if (idx !== -1) {
issues.splice(idx, 1);
} else {
issues.push(issue);
}
return [...issues];
});
function toggleSelection(issue: Issue): void {
const idx = selectedIssues.findIndex((i) => i.id === issue.id);
if (idx !== -1) {
selectedIssues = selectedIssues.filter((i) => i.id !== issue.id);
} else {
selectedIssues = [...selectedIssues, issue];
}
}
onMount(() => {
getOpenIssues();
});
async function getOpenIssues() {
async function getOpenIssues(): Promise<void> {
const state = 'open';
const labels = '';
const url = `${apiAddress}/api/issues/${state}${labels ? `?labels=${labels}` : ''}`;
try {
// Fetch the data from the API
const response = await fetch(url, {
method: 'GET',
credentials: 'include'
});
// Check if the response is successful (status code 2xx)
if (!response.ok) {
const errorMessage = `Failed to fetch open issues. (Code ${response.status}: "${response.statusText}")`;
addToast({
message: errorMessage,
type: ToastType.Error,
dismissible: true
});
return;
}
// Fetch the data from the API
const response = await fetch(url, {
method: 'GET',
credentials: 'include'
});
// Parse the response as JSON
const responseData = await response.json();
// Validate the response structure
if (responseData.status === 'success' && Array.isArray(responseData.data?.issues)) {
const issuesOnly = responseData.data.issues.filter((issue: Issue) => !issue.pull_request);
const pullRequestsOnly = responseData.data.issues.filter(
(issue: Issue) => issue.pull_request
);
openIssues.set(issuesOnly);
openPullRequests.set(pullRequestsOnly);
} else {
// Handle unexpected response structure
const errorMessage = `Unexpected response structure: ${JSON.stringify(responseData)}`;
addToast({
message: errorMessage,
type: ToastType.Error,
dismissible: true
});
}
} catch (error: unknown) {
// Handle fetch or network errors
let errorMessage = 'An unknown error occurred.';
if (error instanceof Error) {
errorMessage = `An error occurred while processing the response: ${error.message}`;
}
// Check if the response is successful (status code 2xx)
if (!response.ok) {
const errorMessage = `Failed to fetch open issues. (Code ${response.status}: "${response.statusText}")`;
addToast({
message: errorMessage,
type: ToastType.Error,
dismissible: true
});
return;
}
// Parse the response as JSON
const responseData = await response.json();
// Validate the response structure
if (responseData.status === 'success' && Array.isArray(responseData.data?.issues)) {
const issuesOnly = responseData.data.issues.filter((issue: Issue) => !issue.pull_request);
const pullRequestsOnly = responseData.data.issues.filter(
(issue: Issue) => issue.pull_request
);
openIssues = issuesOnly;
openPullRequests = pullRequestsOnly;
} else {
// Handle unexpected response structure
const errorMessage = `Unexpected response structure: ${JSON.stringify(responseData)}`;
addToast({
message: errorMessage,
type: ToastType.Error,
Expand All @@ -123,13 +106,12 @@
}
}
let createPullRequest = async (): Promise<void> => {
async function createPullRequest(): Promise<void> {
const title = `Pull request form: ${$me.username}`;
const pr_description = `Changes made from ${$currentFile}.\n ${prCommit}`;
const headBranch = $branchName;
// Get selected issues from the store
const selectedIssueNumbers = get(selectedIssues).map((issue: Issue) => issue.number);
const selectedIssueNumbers = selectedIssues.map((issue: Issue) => issue.number);
showLoadingIcon = true;
const response = await fetch(`${apiAddress}/api/pulls`, {
Expand Down Expand Up @@ -182,14 +164,13 @@
closeModal();
};
let updatePullRequest = async (): Promise<void> => {
async function updatePullRequest(): Promise<void> {
// Ensure the current user is the PR author
if ($me.groups?.some((group) => group.name === 'Admin') || prAuthor === $me.username) {
const title = `Updated pull request form: ${$me.username}`;
const pr_description = `Updated changes made from ${$currentFile}.\n ${prCommit}`;
// Get selected issues from the store
const selectedIssueNumbers = $selectedIssues.map((issue: Issue) => issue.number);
const selectedIssueNumbers = selectedIssues.map((issue: Issue) => issue.number);
showLoadingIcon = true;
const response = await fetch(`${apiAddress}/api/pulls/update`, {
Expand Down Expand Up @@ -252,7 +233,7 @@
closeModal();
};
let closePullRequest = async (): Promise<void> => {
async function closePullRequest(): Promise<void> {
// Check if the current user is the PR author
if ($me.groups?.some((group) => group.name === 'Admin') || prAuthor === $me.username) {
showLoadingIcon = true;
Expand Down Expand Up @@ -304,7 +285,7 @@
async function checkOpenPullRequests() {
showLoadingIcon = true;
// Loop through each open pull request
for (const pr of $openPullRequests) {
for (const pr of openPullRequests) {
if (!pr.pull_request) continue;
// Fetch the details of the pull request using the prNumber
Expand All @@ -327,7 +308,7 @@
linkedIssues.push(parseInt(match[1], 10));
}
linkedIssues.forEach((issueNumber) => {
const matchingIssue = $openIssues.find((issue) => issue.number === issueNumber);
const matchingIssue = openIssues.find((issue) => issue.number === issueNumber);
if (matchingIssue) {
toggleSelection(matchingIssue);
}
Expand Down Expand Up @@ -388,14 +369,14 @@
<div>
<!-- Checkbox Group -->
<ul>
{#each $openIssues as issue}
{#each openIssues as issue}
<li>
<div class="issues">
<!-- Checkbox -->
<input
type="checkbox"
id={`issue-${issue.id}`}
checked={$selectedIssues.includes(issue)}
checked={selectedIssues.includes(issue)}
on:change={() => toggleSelection(issue)}
/>
<!-- Label and Issue Title -->
Expand Down
3 changes: 0 additions & 3 deletions frontend/src/lib/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@ export const branchName: Writable<string> = writable('');
export const baseBranch: Writable<string> = writable('');
export const allBranches = writable<Branch[]>([]);
export const editorText = writable<string>('');
export const openIssues = writable<Issue[]>([]);
export const selectedIssues = writable<Issue[]>([]);
export const openPullRequests = writable<Issue[]>([]);

/**
* The filesystem tree for the document folder
Expand Down

0 comments on commit 3aa7345

Please sign in to comment.