From 8b091ca8523370930591dc0cc746eb7ae99b6983 Mon Sep 17 00:00:00 2001 From: Leonardo Pinho Date: Fri, 6 Dec 2024 10:22:32 -0300 Subject: [PATCH] fix(ci): able to publish more than one event per file --- .../workflows/publish-posts-updated-gcp.yml | 12 --- ci-scripts/publish-post-update.js | 76 +++++++++++-------- content/hello-world.mdx | 4 +- content/react-debug-magic.mdx | 2 +- content/react-state-management.mdx | 2 +- 5 files changed, 48 insertions(+), 48 deletions(-) diff --git a/.github/workflows/publish-posts-updated-gcp.yml b/.github/workflows/publish-posts-updated-gcp.yml index ddec193..9c5bedc 100644 --- a/.github/workflows/publish-posts-updated-gcp.yml +++ b/.github/workflows/publish-posts-updated-gcp.yml @@ -31,18 +31,6 @@ jobs: with: aws-region: ${{ secrets.AWS_REGION }} role-to-assume: ${{ secrets.AWS_ROLE_ARN }} - # inline-session-policy: >- - # { - # "Version": "2012-10-17", - # "Statement": [ - # { - # "Sid": "SSMReadAccess", - # "Effect": "Allow", - # "Action": "ssm:GetParameter", - # "Resource": "arn:aws:ssm:*:${{ secrets.AWS_ACCOUNT_ID }}:parameter/${{ secrets.GCP_TOPIC_PARAMETER_PATH }}" - # } - # ] - # } - name: Fetch GCP Topic Name from SSM id: fetch-topic-name diff --git a/ci-scripts/publish-post-update.js b/ci-scripts/publish-post-update.js index 0e466a0..852ec7c 100644 --- a/ci-scripts/publish-post-update.js +++ b/ci-scripts/publish-post-update.js @@ -6,8 +6,6 @@ const { execSync } = require('child_process'); // Configure Pub/Sub const topicName = process.env.GCP_TOPIC_NAME; - -// Initialize PubSub client using default credentials const pubSubClient = new PubSub(); // Extract frontmatter from an MDX file @@ -17,24 +15,33 @@ function extractFrontmatter(filePath) { return frontmatter; } -// Determine event type based on git diff -function determineEventType(filePath) { - const slug = path.basename(filePath, '.mdx'); +// Determine event types based on git diff +function determineEventTypes(filePath) { try { - const creationOutput = execSync(`git diff --diff-filter=M --name-only HEAD~1`).toString().trim().includes(filePath); - if (creationOutput) { - return 'POST_CREATED'; - } - if (!fs.existsSync(filePath)) { - return 'POST_DELETED'; + // Check if file was created + const createdFiles = execSync(`git diff --diff-filter=A --name-only HEAD~1`).toString().trim().split('\n'); + if (createdFiles.includes(filePath)) { + return ['POST_CREATED']; } - const diffOutput = execSync(`git diff HEAD~1 HEAD -- ${filePath}`).toString().trim(); - if (diffOutput.includes('title') || diffOutput.includes('tags') || diffOutput.includes('description')) { - return 'META_UPDATED'; + + // Check if file was deleted + const deletedFiles = execSync(`git diff --diff-filter=D --name-only HEAD~1`).toString().trim().split('\n'); + if (deletedFiles.includes(filePath)) { + return ['POST_DELETED']; } - return 'CONTENT_UPDATED'; + + // Check for content and metadata changes + const diffOutput = execSync(`git diff HEAD~1 HEAD -- ${filePath}`).toString(); + const hasMetadataChanges = ['title', 'tags', 'description', 'date'].some((field) => diffOutput.includes(field)); + const hasContentChanges = diffOutput.replace(/---\n[\s\S]*?---\n/, '').trim() !== ''; + + const events = []; + if (hasMetadataChanges) events.push('META_UPDATED'); + if (hasContentChanges) events.push('CONTENT_UPDATED'); + + return events.length > 0 ? events : ['UNKNOWN']; } catch (error) { - console.error(`Error determining event type for ${slug}:`, error); + console.error(`Error determining event types for ${filePath}:`, error); throw error; } } @@ -42,10 +49,10 @@ function determineEventType(filePath) { // Publish event to Pub/Sub async function publishEvent(slug, frontmatter, eventType) { const post = { - title: frontmatter.title, - tags: frontmatter.tags, - created_at: frontmatter.date, - description: frontmatter.description, + title: frontmatter.title || null, + tags: frontmatter.tags || [], + created_at: frontmatter.date || null, + description: frontmatter.description || null, slug, }; @@ -57,14 +64,13 @@ async function publishEvent(slug, frontmatter, eventType) { }, }; - // const dataBuffer = Buffer.from(JSON.stringify({ message})); - try { - await pubSubClient.topic(topicName).publishMessage({data: Buffer.from(JSON.stringify(message.data)) , attributes: message.attributes}) - console.log(`Message published for slug: ${slug}`); + await pubSubClient + .topic(topicName) + .publishMessage({ data: Buffer.from(JSON.stringify(message.data)), attributes: message.attributes }); + console.log(`Message published for slug: ${slug}, Event Type: ${eventType}`); } catch (error) { - console.log(`Failed to publish message for slug: ${slug}`, error); - console.error(`Failed to publish message for slug: ${slug}`, error); + console.error(`Failed to publish message for slug: ${slug}, Event Type: ${eventType}`, error); process.exit(1); } } @@ -72,15 +78,21 @@ async function publishEvent(slug, frontmatter, eventType) { // Main script (async () => { const changedFiles = process.env.CHANGED_FILES.split(',').filter((file) => file.endsWith('.mdx')); - console.log("changed files:",changedFiles) + console.log("Changed files:", changedFiles); + for (const file of changedFiles) { + if (!fs.existsSync(file)) { + console.log(`File does not exist: ${file}`); + continue; + } const slug = path.basename(file, '.mdx'); const frontmatter = extractFrontmatter(file); - const eventType = determineEventType(file); + const eventTypes = determineEventTypes(file); - console.log(`Detected change in ${file}: Event Type - ${eventType}`); - await publishEvent(slug, frontmatter, eventType); - console.log("published event for slug", slug) + console.log(`Detected changes in ${file}: Event Types - ${eventTypes}`); + for (const eventType of eventTypes) { + await publishEvent(slug, frontmatter, eventType); + } } - console.log("Published.") + console.log("All events published."); })(); diff --git a/content/hello-world.mdx b/content/hello-world.mdx index a4af7e6..6f56aee 100644 --- a/content/hello-world.mdx +++ b/content/hello-world.mdx @@ -2,7 +2,7 @@ title: Hello World description: This is our first blog post. Really cool date: 2024-03-06 -tags: ["code", "blog"] +tags: ["code", "blog", "test"] published: true --- @@ -10,6 +10,6 @@ published: true # Hello World -Welcome to my blog `inline code` +Welcome to my test blog `inline code` ### Header 3 diff --git a/content/react-debug-magic.mdx b/content/react-debug-magic.mdx index a15cf5b..a3113a8 100644 --- a/content/react-debug-magic.mdx +++ b/content/react-debug-magic.mdx @@ -2,7 +2,7 @@ title: "Debugging React with Wizardry and Magic: A Developer's Spellbook" description: Enter the mystical world of debugging React applications with a touch of humor. Learn spells and incantations to banish bugs and optimize your code, all while navigating the enchanting forest of React development. date: 2024-02-27 -tags: ["react"] +tags: ["react", "test"] published: true --- diff --git a/content/react-state-management.mdx b/content/react-state-management.mdx index cb50591..3174e62 100644 --- a/content/react-state-management.mdx +++ b/content/react-state-management.mdx @@ -17,7 +17,7 @@ Our story begins with a young component, fresh and eager, falling deeply in love const [love, setLove] = useState("undeniable"); ``` -## The Jealous Sibling: Prop Drilling +## The Jealous Sibling: Prop Drilling test But as in any good soap opera, there's a twist. A sibling component, envious of the love affair, desires the state for itself. This leads to the dark practice of prop drilling, passing the beloved state down through layers of components, causing confusion and chaos.