Skip to content

Commit

Permalink
Add support to edit the knowledge contribution for native mode
Browse files Browse the repository at this point in the history
Signed-off-by: Anil Vishnoi <[email protected]>
  • Loading branch information
vishnoianil committed Jan 26, 2025
1 parent 0163834 commit 059ca1a
Show file tree
Hide file tree
Showing 12 changed files with 321 additions and 202 deletions.
55 changes: 45 additions & 10 deletions src/app/api/native/pr/knowledge/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,14 @@ export async function POST(req: NextRequest) {
const REPO_DIR = path.join(LOCAL_TAXONOMY_ROOT_DIR, '/taxonomy');
try {
// Extract the data from the request body
const { content, attribution, name, email, submissionSummary, filePath } = await req.json();
const { action, branchName, content, attribution, name, email, submissionSummary, filePath, oldFilesPath } = await req.json();

let knowledgeBranchName;
if (action == 'update' && branchName != '') {
knowledgeBranchName = branchName;
} else {
knowledgeBranchName = `knowledge-contribution-${Date.now()}`;
}

// Parse the YAML string into an object
const knowledgeData = yaml.load(content) as KnowledgeYamlData;
Expand All @@ -27,24 +34,29 @@ export async function POST(req: NextRequest) {
const yamlString = dumpYaml(knowledgeData);

// Define branch name and file paths
const branchName = `knowledge-contribution-${Date.now()}`;
const newYamlFilePath = path.join(KNOWLEDGE_DIR, filePath, 'qna.yaml');
const newAttributionFilePath = path.join(KNOWLEDGE_DIR, filePath, 'attribution.txt');
const attributionContent = `Title of work: ${attribution.title_of_work}
Link to work: ${attribution.link_to_work}
Revision: ${attribution.revision}
License of the work: ${attribution.license_of_the_work}
Creator names: ${attribution.creator_names}
`;

// Set the flag if commit needs to be amended
let amendCommit = false;

// Initialize the repository if it doesn’t exist
await git.init({ fs, dir: REPO_DIR });

// Create a new branch
await git.branch({ fs, dir: REPO_DIR, ref: branchName });
// Create a new branch if the knowledge is pushed for first time
if (action != 'update') {
await git.branch({ fs, dir: REPO_DIR, ref: knowledgeBranchName });
}

// Checkout the new branch
await git.checkout({ fs, dir: REPO_DIR, ref: branchName });
await git.checkout({ fs, dir: REPO_DIR, ref: knowledgeBranchName });

const newYamlFilePath = path.join(KNOWLEDGE_DIR, filePath, 'qna.yaml');
const newAttributionFilePath = path.join(KNOWLEDGE_DIR, filePath, 'attribution.txt');

// Write YAML file to the knowledge directory
const yamlFilePath = path.join(REPO_DIR, newYamlFilePath);
Expand All @@ -59,6 +71,28 @@ Creator names: ${attribution.creator_names}
await git.add({ fs, dir: REPO_DIR, filepath: newYamlFilePath });
await git.add({ fs, dir: REPO_DIR, filepath: newAttributionFilePath });

if (action == 'update') {
// Define file paths
const oldYamlFilePath = path.join(KNOWLEDGE_DIR, oldFilesPath, 'qna.yaml');
const oldAttributionFilePath = path.join(KNOWLEDGE_DIR, oldFilesPath, 'attribution.txt');

if (oldYamlFilePath != newYamlFilePath) {
console.log('File path for the knowledge contribution is updated, removing the old files.');
// Write the QnA YAML file
const yamlFilePath = path.join(REPO_DIR, oldYamlFilePath);
fs.unlinkSync(yamlFilePath);

// Write the attribution text file
const attributionFilePath = path.join(REPO_DIR, oldAttributionFilePath);
fs.unlinkSync(attributionFilePath);

await git.remove({ fs, dir: REPO_DIR, filepath: oldYamlFilePath });
await git.remove({ fs, dir: REPO_DIR, filepath: oldAttributionFilePath });

amendCommit = true;
}
}

// Commit the changes
await git.commit({
fs,
Expand All @@ -67,12 +101,13 @@ Creator names: ${attribution.creator_names}
author: {
name: name,
email: email
}
},
amend: amendCommit
});

// Respond with success message and branch name
console.log(`Knowledge contribution submitted successfully to local taxonomy repo. Submission Name is ${branchName}.`);
return NextResponse.json({ message: 'Knowledge contribution submitted successfully.', branch: branchName }, { status: 201 });
console.log(`Knowledge contribution submitted successfully to local taxonomy repo. Submission Name is ${knowledgeBranchName}.`);
return NextResponse.json({ message: 'Knowledge contribution submitted successfully.', branch: knowledgeBranchName }, { status: 201 });
} catch (error) {
console.error(`Failed to submit knowledge contribution to local taxonomy repo:`, error);
return NextResponse.json({ error: 'Failed to submit knowledge contribution.' }, { status: 500 });
Expand Down
27 changes: 12 additions & 15 deletions src/components/Contribute/EditKnowledge/github/EditKnowledge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { KnowledgeEditFormData, KnowledgeFormData, QuestionAndAnswerPair, Knowle
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import KnowledgeFormGithub from '../../Knowledge/Github';
import { ValidatedOptions, Modal, ModalVariant } from '@patternfly/react-core';
import { ValidatedOptions, Modal, ModalVariant, ModalBody } from '@patternfly/react-core';

interface EditKnowledgeClientComponentProps {
prNumber: number;
Expand Down Expand Up @@ -57,8 +57,7 @@ const EditKnowledge: React.FC<EditKnowledgeClientComponentProps> = ({ prNumber }
branchName: '',
knowledgeFormData: knowledgeExistingFormData,
pullRequestNumber: prNumber,
yamlFile: { filename: '' },
attributionFile: { filename: '' }
oldFilesPath: ''
};

knowledgeExistingFormData.submissionSummary = prData.title;
Expand All @@ -70,11 +69,14 @@ const EditKnowledge: React.FC<EditKnowledgeClientComponentProps> = ({ prNumber }
if (!foundYamlFile) {
throw new Error('No YAML file found in the pull request.');
}
knowledgeEditFormData.yamlFile = foundYamlFile;
const existingFilesPath = foundYamlFile.filename.split('/').slice(1, -1).join('/');

// Set the current Yaml file path as a old files path
knowledgeEditFormData.oldFilesPath = existingFilesPath + '/';

const yamlContent = await fetchFileContent(session.accessToken, foundYamlFile.filename, prData.head.sha);
const yamlData: KnowledgeYamlData = yaml.load(yamlContent) as KnowledgeYamlData;
console.log('Parsed YAML data:', yamlData);
console.log('Parsed Knowledge YAML data:', yamlData);

// Populate the form fields with YAML data
knowledgeExistingFormData.documentOutline = yamlData.document_outline;
Expand Down Expand Up @@ -118,9 +120,8 @@ const EditKnowledge: React.FC<EditKnowledgeClientComponentProps> = ({ prNumber }
if (foundAttributionFile) {
const attributionContent = await fetchFileContent(session.accessToken, foundAttributionFile.filename, prData.head.sha);
const attributionData = parseAttributionContent(attributionContent);
console.log('Parsed attribution data:', attributionData);
console.log('Parsed knowledge attribution data:', attributionData);

knowledgeEditFormData.attributionFile = foundAttributionFile;
// Populate the form fields with attribution data
knowledgeExistingFormData.titleWork = attributionData.title_of_work;
knowledgeExistingFormData.linkWork = attributionData.link_to_work ? attributionData.link_to_work : '';
Expand Down Expand Up @@ -165,19 +166,15 @@ const EditKnowledge: React.FC<EditKnowledgeClientComponentProps> = ({ prNumber }

if (isLoading) {
return (
// <AppLayout>
<Modal variant={ModalVariant.small} title="Loading Knowledge Data" isOpen={isLoading} onClose={() => handleOnClose()}>
<div>{loadingMsg}</div>
<ModalBody>
<div>{loadingMsg}</div>
</ModalBody>
</Modal>
// </AppLayout>
);
}

return (
// <AppLayout>
<KnowledgeFormGithub knowledgeEditFormData={knowledgeEditFormData} />
// </AppLayout>
);
return <KnowledgeFormGithub knowledgeEditFormData={knowledgeEditFormData} />;
};

export default EditKnowledge;
Loading

0 comments on commit 059ca1a

Please sign in to comment.