Skip to content

Commit

Permalink
fix(ci): able to publish more than one event per file
Browse files Browse the repository at this point in the history
  • Loading branch information
leo-the-nardo committed Dec 6, 2024
1 parent 2bd4e54 commit 8b091ca
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 48 deletions.
12 changes: 0 additions & 12 deletions .github/workflows/publish-posts-updated-gcp.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
76 changes: 44 additions & 32 deletions ci-scripts/publish-post-update.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -17,35 +15,44 @@ 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;
}
}

// 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,
};

Expand All @@ -57,30 +64,35 @@ 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);
}
}

// 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.");
})();
4 changes: 2 additions & 2 deletions content/hello-world.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
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
---

<Callout type="warning">Hello I am a callout</Callout>

# Hello World

Welcome to my blog `inline code`
Welcome to my test blog `inline code`

### Header 3
2 changes: 1 addition & 1 deletion content/react-debug-magic.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
---

Expand Down
2 changes: 1 addition & 1 deletion content/react-state-management.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down

0 comments on commit 8b091ca

Please sign in to comment.