final version of linux since 10 years old post
This commit is contained in:
parent
5e16c97462
commit
d8f11d1cf5
21 changed files with 304 additions and 113 deletions
12
README.md
12
README.md
|
|
@ -1,6 +1,6 @@
|
||||||
# gabeefran.co
|
# gabeefran.co
|
||||||
|
|
||||||
Personal blog of Gabriel Franco (gabeefranco). Built with Astro, TypeScript, MDX, React, and Tailwind CSS. Bilingual (English / Portuguese) via Astro's built-in i18n routing.
|
Personal blog of Gabriel Franco (gabeefranco). Built with Astro, TypeScript, MDX, React, and Tailwind CSS. Bilingual (English / Portuguese): every page lives under `/en/*` or `/pt/*` (see `src/lib/i18n.ts`).
|
||||||
|
|
||||||
## Structure
|
## Structure
|
||||||
|
|
||||||
|
|
@ -10,14 +10,18 @@ Personal blog of Gabriel Franco (gabeefranco). Built with Astro, TypeScript, MDX
|
||||||
├── src/
|
├── src/
|
||||||
│ ├── components/ Astro + React components (Header, PostCard, ObservationCard, ...)
|
│ ├── components/ Astro + React components (Header, PostCard, ObservationCard, ...)
|
||||||
│ ├── content/posts/en/*.mdx English posts
|
│ ├── content/posts/en/*.mdx English posts
|
||||||
│ ├── content/posts/pt/*.mdx Portuguese posts (same filename pairs a translation)
|
│ ├── content/posts/pt/*.mdx Portuguese posts (same filename = translation of each other)
|
||||||
│ ├── layouts/ BaseLayout, PostLayout
|
│ ├── layouts/ BaseLayout, PostLayout
|
||||||
│ ├── lib/ i18n dictionary + post helpers
|
│ ├── lib/ i18n dictionary + post helpers
|
||||||
│ └── pages/ routes: "/" is English (default locale), "/pt/*" is Portuguese
|
│ └── pages/[lang]/ routes for every language ("/" redirects to "/en")
|
||||||
└── astro.config.mjs
|
└── astro.config.mjs
|
||||||
```
|
```
|
||||||
|
|
||||||
Every post exists as two files with the same slug — `src/content/posts/en/<slug>.mdx` and `src/content/posts/pt/<slug>.mdx` — so the language switcher can always land on the matching translation.
|
A post and its translation share a **filename** — `src/content/posts/en/<file>.mdx` and `src/content/posts/pt/<file>.mdx` — which is how they're paired. The URL comes from the `slug` frontmatter field, so each language has its own: `en/hello-world.mdx` with `slug: "hello-world"` is served at `/en/posts/hello-world`, and `pt/hello-world.mdx` with `slug: "ola-mundo"` at `/pt/posts/ola-mundo`. The filename never shows up in a URL.
|
||||||
|
|
||||||
|
The language switcher, `hreflang` links, RSS feeds and sitemap all follow each post's own slug. A post can exist in only one language; its switcher then goes to the other language's home page. Social cards are named after the slug, so run `npm run og` after adding or renaming one.
|
||||||
|
|
||||||
|
Changing the slug of a published post breaks its old URL, so add a redirect for it in `astro.config.mjs`.
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,4 @@
|
||||||
// @ts-check
|
// @ts-check
|
||||||
import { readdirSync, readFileSync } from 'node:fs';
|
|
||||||
import { defineConfig } from 'astro/config';
|
|
||||||
import { defineConfig, fontProviders } from 'astro/config';
|
import { defineConfig, fontProviders } from 'astro/config';
|
||||||
|
|
||||||
import react from '@astrojs/react';
|
import react from '@astrojs/react';
|
||||||
|
|
@ -8,6 +6,8 @@ import mdx from '@astrojs/mdx';
|
||||||
import sitemap from '@astrojs/sitemap'
|
import sitemap from '@astrojs/sitemap'
|
||||||
import tailwindcss from '@tailwindcss/vite';
|
import tailwindcss from '@tailwindcss/vite';
|
||||||
import vercel from '@astrojs/vercel';
|
import vercel from '@astrojs/vercel';
|
||||||
|
import { postPath } from './src/lib/i18n.ts';
|
||||||
|
import { readPostFiles } from './src/lib/post-files.ts';
|
||||||
|
|
||||||
// English used to be served without a /en prefix. Every URL published before
|
// English used to be served without a /en prefix. Every URL published before
|
||||||
// the move keeps working through a 301; new pages only ever existed under /en.
|
// the move keeps working through a 301; new pages only ever existed under /en.
|
||||||
|
|
@ -32,13 +32,9 @@ const LEGACY_EN_PATHS = [
|
||||||
|
|
||||||
// Draft posts still get a page (reachable by URL) but stay out of the sitemap.
|
// Draft posts still get a page (reachable by URL) but stay out of the sitemap.
|
||||||
// This runs before content collections exist, so read the frontmatter directly.
|
// This runs before content collections exist, so read the frontmatter directly.
|
||||||
const DRAFT_PATHS = readdirSync('./src/content/posts', { recursive: true, encoding: 'utf-8' })
|
const DRAFT_PATHS = readPostFiles()
|
||||||
.filter((file) => file.endsWith('.mdx'))
|
.filter((post) => post.draft)
|
||||||
.map((file) => readFileSync(`./src/content/posts/${file}`, 'utf-8'))
|
.map((post) => `${postPath(post.lang, post.slug)}/`);
|
||||||
.filter((raw) => /^draft:\s*true\s*$/m.test(raw))
|
|
||||||
.map((raw) => raw.match(/^slug:\s*"?(en|pt)-([^"\n]+)"?/m))
|
|
||||||
.filter((match) => match !== null)
|
|
||||||
.map(([, lang, slug]) => `/${lang}/posts/${slug.trim()}/`);
|
|
||||||
|
|
||||||
// https://astro.build/config
|
// https://astro.build/config
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
|
|
|
||||||
|
|
@ -7,28 +7,20 @@
|
||||||
//
|
//
|
||||||
// Needs CF_ACCOUNT_ID and CF_API_TOKEN (read from .env), and the
|
// Needs CF_ACCOUNT_ID and CF_API_TOKEN (read from .env), and the
|
||||||
// /social-card and /page-card routes must be deployed at BASE_URL.
|
// /social-card and /page-card routes must be deployed at BASE_URL.
|
||||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
import { LANGS, pageMeta, tagPageMeta, type Lang, type PageKey } from '../src/lib/i18n.ts';
|
import { LANGS, pageMeta, tagPageMeta, type Lang, type PageKey } from '../src/lib/i18n.ts';
|
||||||
|
import { readPostFiles, type PostFile } from '../src/lib/post-files.ts';
|
||||||
import { pageCardPath, postCardPath, tagCardPath } from '../src/lib/social-cards.ts';
|
import { pageCardPath, postCardPath, tagCardPath } from '../src/lib/social-cards.ts';
|
||||||
|
|
||||||
const BASE_URL = process.env.SOCIAL_CARD_BASE_URL ?? 'https://gabeefran.co';
|
const BASE_URL = process.env.SOCIAL_CARD_BASE_URL ?? 'https://gabeefran.co';
|
||||||
const CF_API = 'https://api.cloudflare.com/client/v4/accounts';
|
const CF_API = 'https://api.cloudflare.com/client/v4/accounts';
|
||||||
const POSTS_DIR = 'src/content/posts';
|
|
||||||
// 404.html is prerendered once, in English (see src/pages/404.astro).
|
// 404.html is prerendered once, in English (see src/pages/404.astro).
|
||||||
const LANG_PAGES: Record<Lang, PageKey[]> = {
|
const LANG_PAGES: Record<Lang, PageKey[]> = {
|
||||||
en: ['home', 'posts', 'about', '404'],
|
en: ['home', 'posts', 'about', '404'],
|
||||||
pt: ['home', 'posts', 'about'],
|
pt: ['home', 'posts', 'about'],
|
||||||
};
|
};
|
||||||
|
|
||||||
interface Post {
|
|
||||||
lang: Lang;
|
|
||||||
slug: string;
|
|
||||||
title: string;
|
|
||||||
description?: string;
|
|
||||||
tags: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Card {
|
interface Card {
|
||||||
/** Path under public/, e.g. /social-cards/en/hello-world.png */
|
/** Path under public/, e.g. /social-cards/en/hello-world.png */
|
||||||
path: string;
|
path: string;
|
||||||
|
|
@ -37,38 +29,7 @@ interface Card {
|
||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getFrontmatterField(content: string, field: string): string | null {
|
function listCards(posts: PostFile[]): Card[] {
|
||||||
const match = content.match(new RegExp(`^${field}:\\s*"?([^"\\n]+)"?`, 'm'));
|
|
||||||
return match ? match[1].trim() : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Reads an inline tag list, e.g. `tags: ["meta", "blogging"]`. */
|
|
||||||
function getFrontmatterTags(content: string): string[] {
|
|
||||||
const list = content.match(/^tags:\s*\[([^\]]*)\]/m)?.[1] ?? '';
|
|
||||||
return [...list.matchAll(/["']([^"']+)["']/g)].map((m) => m[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Posts live at src/content/posts/<lang>/<slug>.mdx (see src/content.config.ts). */
|
|
||||||
function readPosts(): Post[] {
|
|
||||||
return LANGS.flatMap((lang) => {
|
|
||||||
const dir = join(POSTS_DIR, lang);
|
|
||||||
if (!existsSync(dir)) return [];
|
|
||||||
return readdirSync(dir)
|
|
||||||
.filter((f) => f.endsWith('.mdx'))
|
|
||||||
.map((file) => {
|
|
||||||
const raw = readFileSync(join(dir, file), 'utf-8');
|
|
||||||
if (getFrontmatterField(raw, 'draft') === 'true') return null;
|
|
||||||
const slug = file.replace(/\.mdx$/, '');
|
|
||||||
const title = getFrontmatterField(raw, 'title') ?? slug;
|
|
||||||
const description = getFrontmatterField(raw, 'description') ?? undefined;
|
|
||||||
const tags = getFrontmatterTags(raw);
|
|
||||||
return { lang, slug, title, description, tags };
|
|
||||||
})
|
|
||||||
.filter((p): p is Post => p !== null);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function listCards(posts: Post[]): Card[] {
|
|
||||||
const postCards: Card[] = posts.map((post) => {
|
const postCards: Card[] = posts.map((post) => {
|
||||||
const params: Record<string, string> = { title: post.title, author: 'Gabriel Franco' };
|
const params: Record<string, string> = { title: post.title, author: 'Gabriel Franco' };
|
||||||
if (post.description) params.description = post.description;
|
if (post.description) params.description = post.description;
|
||||||
|
|
@ -118,7 +79,7 @@ async function main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
const force = process.argv.includes('--force');
|
const force = process.argv.includes('--force');
|
||||||
const cards = listCards(readPosts());
|
const cards = listCards(readPostFiles().filter((post) => !post.draft));
|
||||||
console.log(`Found ${cards.length} cards to process\n`);
|
console.log(`Found ${cards.length} cards to process\n`);
|
||||||
|
|
||||||
let generated = 0;
|
let generated = 0;
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,11 @@ import { getLocalizedPath, LANG_LABELS, useTranslations, type Lang } from '../li
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
lang: Lang;
|
lang: Lang;
|
||||||
|
/** See BaseLayout. */
|
||||||
|
alternates: Partial<Record<Lang, string>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { lang } = Astro.props;
|
const { lang, alternates } = Astro.props;
|
||||||
const t = useTranslations(lang);
|
const t = useTranslations(lang);
|
||||||
const otherLang: Lang = lang === 'en' ? 'pt' : 'en';
|
const otherLang: Lang = lang === 'en' ? 'pt' : 'en';
|
||||||
|
|
||||||
|
|
@ -14,7 +16,8 @@ const pathname = Astro.url.pathname;
|
||||||
const homeHref = getLocalizedPath('/', lang);
|
const homeHref = getLocalizedPath('/', lang);
|
||||||
const postsHref = getLocalizedPath('/posts', lang);
|
const postsHref = getLocalizedPath('/posts', lang);
|
||||||
const aboutHref = getLocalizedPath('/about', lang);
|
const aboutHref = getLocalizedPath('/about', lang);
|
||||||
const langSwitchHref = getLocalizedPath(pathname, otherLang);
|
// Not everything is translated: fall back to the other language's home page.
|
||||||
|
const langSwitchHref = alternates[otherLang] ?? getLocalizedPath('/', otherLang);
|
||||||
|
|
||||||
const navLinks = [
|
const navLinks = [
|
||||||
{ href: homeHref, label: t('nav.home'), id: 'home' },
|
{ href: homeHref, label: t('nav.home'), id: 'home' },
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
---
|
---
|
||||||
import type { PostEntry } from '../lib/posts';
|
import type { PostEntry } from '../lib/posts';
|
||||||
import { slugOf, formatDate } from '../lib/posts';
|
import { formatDate, postHref } from '../lib/posts';
|
||||||
import { getLocalizedPath, type Lang } from '../lib/i18n';
|
import { getLocalizedPath, type Lang } from '../lib/i18n';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
|
|
@ -9,7 +9,7 @@ interface Props {
|
||||||
}
|
}
|
||||||
|
|
||||||
const { post, lang } = Astro.props;
|
const { post, lang } = Astro.props;
|
||||||
const href = getLocalizedPath(`/posts/${slugOf(post)}`, lang);
|
const href = postHref(post);
|
||||||
const tagsHref = (tag: string) => getLocalizedPath(`/tags/${tag}`, lang);
|
const tagsHref = (tag: string) => getLocalizedPath(`/tags/${tag}`, lang);
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,16 @@
|
||||||
import { defineCollection, z } from 'astro:content';
|
import { defineCollection, z } from 'astro:content';
|
||||||
import { glob } from 'astro/loaders';
|
import { glob } from 'astro/loaders';
|
||||||
|
|
||||||
// Each post lives twice: src/content/posts/en/<slug>.mdx and
|
// Posts live at src/content/posts/<lang>/<file>.mdx. The entry id is always
|
||||||
// src/content/posts/pt/<slug>.mdx. The loader id is "<lang>/<slug>",
|
// that path ("<lang>/<file>"), never the frontmatter slug: the language comes
|
||||||
// which is how we pair up translations and derive routes.
|
// from the folder, and a post and its translation share the same filename.
|
||||||
|
// The URL is /<lang>/posts/<slug>, so each translation picks its own slug.
|
||||||
const posts = defineCollection({
|
const posts = defineCollection({
|
||||||
loader: glob({ pattern: '**/*.mdx', base: './src/content/posts' }),
|
loader: glob({
|
||||||
|
pattern: '**/*.mdx',
|
||||||
|
base: './src/content/posts',
|
||||||
|
generateId: ({ entry }) => entry.replace(/\.mdx$/, ''),
|
||||||
|
}),
|
||||||
schema: z.object({
|
schema: z.object({
|
||||||
title: z.string(),
|
title: z.string(),
|
||||||
description: z.string(),
|
description: z.string(),
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
---
|
---
|
||||||
title: "This blog's Hello World (or whatever you want to call this site)"
|
title: "This blog's Hello World (or whatever you want to call this site)"
|
||||||
slug: "en-hello-world"
|
slug: "hello-world"
|
||||||
description: "A short note on why this exists and what I plan to write about here."
|
description: "A short note on why this exists and what I plan to write about here."
|
||||||
pubDate: 2026-09-22
|
pubDate: 2026-09-22
|
||||||
tags: ["meta", "blogging"]
|
tags: ["meta", "life"]
|
||||||
language: "en"
|
language: "en"
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,87 @@
|
||||||
|
---
|
||||||
|
title: "I've Been Using Linux Since I Was 10: Here's What Nobody Tells You"
|
||||||
|
description: "I started using Linux at 10, dual booting my dad's PC. Here's what I learned breaking the system, plus 3 tips for anyone just getting started."
|
||||||
|
pubDate: 2026-10-06
|
||||||
|
tags: ["linux", "life"]
|
||||||
|
seoKeywords: "learn Linux, Linux for beginners, how to start using Linux, Ubuntu and Windows dual boot, Linux terminal, package manager, switch from Windows to Linux"
|
||||||
|
slug: "using-linux-since-i-was-10-what-nobody-tells-you"
|
||||||
|
language: "en"
|
||||||
|
---
|
||||||
|
|
||||||
|
I was 10 when I spent two hours thinking I'd deleted every file on my dad's PC. All because I wanted to install Ubuntu 18.04 in a *dual boot* with Windows 7. In the end, I hadn't deleted anything, and from then on I never thought the same way again.
|
||||||
|
|
||||||
|
In this post, I want to share a bit of my experience and give some tips to anyone who's just starting out or wants to start soon.
|
||||||
|
|
||||||
|
## A bit of my story
|
||||||
|
|
||||||
|
It all starts in May 2018. I was 10 years old and already knew I really loved tech, and I was super into computers and video editing. The starting point was my dad, who took me to a bookstore here in Porto Alegre to pick out a book, since he wanted me to get back into reading. He's always been the biggest [early adopter](https://en.wikipedia.org/wiki/Technology_adoption_life_cycle) of every new phase in my life, and he still is.
|
||||||
|
|
||||||
|
He wanted me to buy an actual literature book, a story with a beginning, a middle and an end. I, on the other hand, wanted a book that would teach me something new, something I was into. We agreed to get one of each. I picked ["Programming in Python 3"](https://www.informit.com/store/programming-in-python-3-a-complete-introduction-to-9780132651653), by [Mark Summerfield](https://mark-summerfield.github.io/index.html).
|
||||||
|
|
||||||
|
My dad had a PC he barely used. Actually, I was the one using it, to learn programming and practice what the book taught. It had an AMD Athlon, already outdated even back then, and ran Windows 7. I could code on it, but it was kind of slow. On top of that, I was always searching the internet, especially YouTube, for tips on the stuff I liked.
|
||||||
|
|
||||||
|
So, during one of those searches, I came across some videos saying Linux was better for programming and for learning about computers and computing. I heard it had better tools and was more practical. So I immediately looked up how to install it, and after a long time trying and wondering whether I'd wiped my dad's files, I managed to put Ubuntu right next to Windows 7 without losing anything.
|
||||||
|
|
||||||
|
## The struggles (and the real upside)
|
||||||
|
|
||||||
|
After some time in this world, I realized the biggest advantage of choosing Linux wasn't practicality or anything like that. **It was learning the hard way how an operating system works, and how to fix things when they go wrong.**
|
||||||
|
|
||||||
|
Because a lot of things went wrong.
|
||||||
|
|
||||||
|
First, while I was still trying to install the system, I thought I had formatted the Windows partition. Thank God that wasn't the problem, but it took me about two hours to figure that out. In the end, we called Enéas, who was my family's hero when it came to computers.
|
||||||
|
|
||||||
|
He was the one we called whenever we needed a repair, maintenance or an *upgrade* on my mom's and dad's computers. When he got there, he looked things over and showed me that I hadn't deleted the partition; GRUB (a *bootloader* common in many Linux distros) just wasn't detecting the Windows partition. So he taught me how to change the boot order straight from the BIOS, and in the end, everything worked out.
|
||||||
|
|
||||||
|
Thank you so much, Enéas! Besides being our hero, you were one of the only people I could talk to about what I was learning about computers, so you probably remember that I talked way more than necessary whenever you came over. For us "IT guys" who are passionate about what we do, sometimes that's all we need.
|
||||||
|
|
||||||
|
But I didn't get discouraged because I needed help. Actually, I wanted to be the guy who'd help someone someday. So I kept trying, and I learned a lot every time something broke.
|
||||||
|
|
||||||
|
Another thing that happened was that the system just wouldn't recognize my TP-Link Wi-Fi adapter. I don't know if it was because I forgot to enable the kernel module, or if some package was missing, or if there really was no driver for that adapter. After a while, we ran network cables through the house, and then I didn't need the adapter anymore. So I forgot about that problem.
|
||||||
|
|
||||||
|
All I know is that nowadays I sometimes need that adapter on my PC, and it works *plug-and-play*. I don't know if that driver now ships with the Linux kernel by default or if I just learned how to set it up properly. But anyway, problem solved, even if it took a few years.
|
||||||
|
|
||||||
|
And I think it's this kind of struggle that makes you learn. To this day, I haven't found a better way to understand, in practice, how a computer and its operating system work. It's by getting your hands dirty and making mistakes that we start to understand, and **no system gives you as much freedom to practice and make mistakes as Linux.**
|
||||||
|
|
||||||
|
## I think I know how I can help you
|
||||||
|
|
||||||
|
The learning process needs a bit of friction. There has to be trial and error. But what I can do to help you, if you're just starting out, is give you some info to cut down on the headaches. What I'm about to say is meant to prepare you for what's coming. That way, I hope you'll get used to it faster and learn more.
|
||||||
|
|
||||||
|
**The main thing is to get the "Windows way of doing things" out of your head.** It's a different operating system, so things are done differently. A lot of what you know carries over, sure. But be ready to think differently.
|
||||||
|
|
||||||
|
Here are 3 tips on the main differences between Linux and Windows.
|
||||||
|
|
||||||
|
### 1. Understand the terminal
|
||||||
|
|
||||||
|
On Windows, we're used to doing everything through the graphical interface. After all, there's a GUI (graphical user interface) for everything there. It's not like Linux doesn't have one, but the default and fastest way to get around the system is the command line. If you stick to the graphical interface, I promise you'll learn very little.
|
||||||
|
|
||||||
|
That black screen with white letters and a monospaced font can seem intimidating at first. But I swear it's not that hard to get used to. I recommend opening the terminal and learning how your shell works, the basic commands (`ls`, `cd`, `cp`, `mv`, `rm`, `cat`, etc.) and how to get around using only the command line. Test everything in a safe environment, where you're not afraid of breaking everything. Keep looking up how to do your everyday tasks. Trust me, there's a command for anything you want to do.
|
||||||
|
|
||||||
|
### 2. Understand package management
|
||||||
|
|
||||||
|
Package management is something we're not used to in Windows environments. There, it basically doesn't exist the way it does in operating systems like Linux.
|
||||||
|
|
||||||
|
When you want to download a program, get used to not hunting for an executable on the internet. Learn to search for programs in your distribution's package manager and install them through it.
|
||||||
|
|
||||||
|
Remember that `C:\Program Files` folder? On Windows, it centralizes all the files your programs need to run properly. On Linux, though, files are spread across several folders, and the system knows where to find them. Binaries in `/bin` or `/usr/bin`, shared libraries in `/usr/lib`, and so on. What the package manager does is unpack the package you want to install and put each file in its proper place, automatically.
|
||||||
|
|
||||||
|
And each distribution has a different package system. Debian uses `dpkg` and `apt`, Red Hat family distros (Fedora, RHEL, Rocky) use `rpm` and `dnf`, and Arch uses `pacman`. Each one works a little differently, so look up what your distro uses and learn it.
|
||||||
|
|
||||||
|
### 3. Understand troubleshooting
|
||||||
|
|
||||||
|
This is the most important one. **On Linux, every error has an explanation.** When something crashes or goes wrong, you can be sure there's a log somewhere explaining what happened.
|
||||||
|
|
||||||
|
Troubleshooting always comes down to checking the logs, fixing what went wrong and trying again. There's not much of a secret when you don't know what to do. Throw it into Google or an AI and you'll find a ton of forum posts where someone else explains they had the same problem and asks for help. Sometimes there's an answer, and sometimes there isn't. Just make sure you're looking at the right forums. There's no point trying to fix a problem on Ubuntu by following a step-by-step guide from the Arch Linux forum.
|
||||||
|
|
||||||
|
This forum-digging part is very real. It's a big part of how you learn. But **don't forget to look up what commands do before running them**, because that's where a security problem lies. Someone could just post a malicious command for people to run. And beyond security, if we're using Linux to learn something, it's good to know why we do what we do.
|
||||||
|
|
||||||
|
That time the Wi-Fi adapter didn't work, I spent a lot of time looking for the answer on forums. In that case, it took a while for the problem to get solved. But it was definitely worth it, because I learned a lot of new stuff along the way.
|
||||||
|
|
||||||
|
## Anyway...
|
||||||
|
|
||||||
|
Eight years have passed since that dual boot on my dad's PC, and I still use Linux every day. I've switched distros a few times, broken the system more times than I'd like and, honestly, I still break it every now and then. The difference is that now I know where to start looking for the problem.
|
||||||
|
|
||||||
|
And that's what nobody tells you. **Linux isn't going to make you more productive right off the bat.** At first, you'll waste time on stuff that would be one click on Windows. You'll spend a whole afternoon trying to get the Wi-Fi working, or thinking you deleted someone's files. But each of those struggles teaches you something no course or book teaches in quite the same way. Before you know it, you understand partitions, bootloaders, kernel modules and permissions, without ever sitting down to study them formally.
|
||||||
|
|
||||||
|
Remember how I said I wanted to be the guy who'd help someone someday? This post is a bit of that. If you're thinking about starting, *start*. Do it in an environment where you're not afraid to make mistakes, read the logs, research before running any command and, above all, don't get discouraged when you need to ask for help. I did, and that's when I learned the most.
|
||||||
|
|
||||||
|
And if something goes really wrong, well, everybody needs an Enéas every now and then. I'm here if you need me.
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
---
|
---
|
||||||
title: "Spotify's Time Capsule Change and the Enshittification of Software"
|
title: "Spotify's Time Capsule Change and the Enshittification of Software"
|
||||||
slug: "en-spotify-complaining"
|
slug: "spotify-complaining"
|
||||||
description: "Spotify just removed one of its best features. Beyond a bit of complaining, I want to open a debate about what software is turning into."
|
description: "Spotify just removed one of its best features. Beyond a bit of complaining, I want to open a debate about what software is turning into."
|
||||||
pubDate: 2026-09-2
|
pubDate: 2026-09-2
|
||||||
tags: ["software", "life"]
|
tags: ["software", "life"]
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
---
|
---
|
||||||
title: "Understanding Plugin4Shell: An Exploit That Uses a Simple Git Trick to Fool AI Coding Agents"
|
title: "Understanding Plugin4Shell: An Exploit That Uses a Simple Git Trick to Fool AI Coding Agents"
|
||||||
description: "A git branch named after a commit hash was enough to make AI coding agents run unverified plugins. I reproduced the Plugin4Shell trick on GitHub and Forgejo."
|
description: "A git branch named after a commit hash was enough to make AI coding agents run unverified plugins. I reproduced the Plugin4Shell trick on GitHub and Forgejo."
|
||||||
slug: "en-understanding-plugin4shell-git-trick-ai-coding-agents"
|
slug: "understanding-plugin4shell-git-trick-ai-coding-agents"
|
||||||
pubDate: 2026-09-28
|
pubDate: 2026-09-28
|
||||||
tags: ["cybersecurity", "git", "ai", "software"]
|
tags: ["cybersecurity", "git", "ai", "software"]
|
||||||
seoKeywords: "Plugin4Shell, git branch named after commit hash, SHA pinning bypass, AI coding agents security, Claude Code plugin vulnerability, supply chain attack, git internals, Forgejo"
|
seoKeywords: "Plugin4Shell, git branch named after commit hash, SHA pinning bypass, AI coding agents security, Claude Code plugin vulnerability, supply chain attack, git internals, Forgejo"
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@
|
||||||
title: "O Hello World desse blog (ou seja lá como você queira chamar esse site)"
|
title: "O Hello World desse blog (ou seja lá como você queira chamar esse site)"
|
||||||
description: "Uma nota curta sobre por que isso existe e sobre o que pretendo escrever aqui."
|
description: "Uma nota curta sobre por que isso existe e sobre o que pretendo escrever aqui."
|
||||||
pubDate: 2026-09-22
|
pubDate: 2026-09-22
|
||||||
slug: "pt-hello-world"
|
slug: "hello-world"
|
||||||
tags: ["meta", "blogging"]
|
tags: ["meta", "life"]
|
||||||
language: "pt"
|
language: "pt"
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,14 @@
|
||||||
---
|
---
|
||||||
title: "Eu Uso Linux Desde os Meus 10 Anos de Idade: Aqui Está o Que Ninguém te Conta"
|
title: "Eu Uso Linux Desde os Meus 10 Anos de Idade: Aqui Está o Que Ninguém te Conta"
|
||||||
description: "ainda não tem descrição"
|
description: "Comecei no Linux aos 10 anos, num dual boot no PC do meu pai. Conto o que aprendi quebrando o sistema e dou 3 dicas pra quem está começando agora."
|
||||||
slug: "pt-linux-since-10-what-nobody-tells-you"
|
pubDate: 2026-10-06
|
||||||
pubDate: 2026-09-30
|
tags: ["linux", "life"]
|
||||||
tags: ["draft"]
|
seoKeywords: "aprender Linux, Linux para iniciantes, como começar a usar Linux, dual boot Ubuntu e Windows, terminal Linux, gerenciador de pacotes, migrar do Windows para o Linux"
|
||||||
seoKeywords: ""
|
slug: "uso-linux-desde-meus-10-anos-o-que-ninguem-te-conta"
|
||||||
draft: true
|
|
||||||
language: "pt"
|
language: "pt"
|
||||||
---
|
---
|
||||||
|
|
||||||
Quando eu comecei a programar, ouvi dizer que pra aprender programação de verdade tem que usar Linux. Eu simplesmente fui lá e segui essa dica à risca. Instalei o Ubuntu 18.04 em dual boot com o Windows 7, e a partir daí nunca mais pensei da mesma forma.
|
Eu tinha 10 anos quando passei duas horas achando que tinha apagado todos os arquivos do PC do meu pai. Tudo isso porque eu queria instalar o Ubuntu 18.04 em *dual boot* com o Windows 7. No fim, não tinha apagado nada, e a partir daí nunca mais pensei da mesma forma.
|
||||||
|
|
||||||
Nesse post, quero compartilhar um pouco da minha experiência, e dar algumas dicas pra quem está começando agora ou quer começar em breve.
|
Nesse post, quero compartilhar um pouco da minha experiência, e dar algumas dicas pra quem está começando agora ou quer começar em breve.
|
||||||
|
|
||||||
|
|
@ -19,32 +18,70 @@ Tudo começa em maio de 2018. Eu tinha 10 anos de idade e já sabia que gostava
|
||||||
|
|
||||||
Ele queria que eu comprasse um livro de literatura mesmo, de histórias com início, meio e fim. Eu, por outro lado, queria comprar um livro que me ensinasse alguma coisa nova, dentro dos meus interesses. Concordamos em levar um de cada. Eu escolhi ["Programação em Python 3"](https://www.estantevirtual.com.br/livro/programacao-em-python-3-0FS-0355-000-BK), do [Mark Summerfield](https://mark-summerfield.github.io/index.html).
|
Ele queria que eu comprasse um livro de literatura mesmo, de histórias com início, meio e fim. Eu, por outro lado, queria comprar um livro que me ensinasse alguma coisa nova, dentro dos meus interesses. Concordamos em levar um de cada. Eu escolhi ["Programação em Python 3"](https://www.estantevirtual.com.br/livro/programacao-em-python-3-0FS-0355-000-BK), do [Mark Summerfield](https://mark-summerfield.github.io/index.html).
|
||||||
|
|
||||||
Meu pai tinha um PC que ele raramente usava. Na verdade, quem usava era eu, pra aprender programação e praticar o conteúdo do livro. Tinha um AMD Athlon, já ultrapassado mesmo naquela época, e rodava Windows 7. Conseguia programar, mas era meio lento. Além disso, eu era muito de pesquisar na internet, principalmente no YouTube, por dicas sobre assuntos que eu gostava. Assim, numa dessas pesquisas, vi alguns vídeos que diziam que Linux era melhor pra programar e aprender sobre informática e computação. Ouvi que tinha ferramentas melhores e era mais prático. Então já fui logo pesquisar como instalar, e depois de muito tempo tentando e me perguntando se tinha apagado os arquivos do meu pai, consegui colocar o Ubuntu ao lado do Windows 7 sem perder nada.
|
Meu pai tinha um PC que ele raramente usava. Na verdade, quem usava era eu, pra aprender programação e praticar o conteúdo do livro. Tinha um AMD Athlon, já ultrapassado mesmo naquela época, e rodava Windows 7. Conseguia programar, mas era meio lento. Além disso, eu era muito de pesquisar na internet, principalmente no YouTube, por dicas sobre assuntos que eu gostava.
|
||||||
|
|
||||||
## A real vantagem do Linux
|
Assim, numa dessas pesquisas, vi alguns vídeos que diziam que Linux era melhor pra programar e aprender sobre informática e computação. Ouvi dizer que tinha ferramentas melhores e era mais prático. Então já fui logo pesquisar como instalar, e depois de muito tempo tentando e me perguntando se tinha apagado os arquivos do meu pai, consegui colocar o Ubuntu ao lado do Windows 7 sem perder nada.
|
||||||
|
|
||||||
Depois de algum tempo nesse mundo, percebi que a maior vantagem de ter escolhido o Linux não foi a praticidade, nem nada parecido. Foi aprender na marra sobre como um sistema operacional funciona, e como consertar coisas que dão errado.
|
## Os perrengues (e a real vantagem)
|
||||||
|
|
||||||
cotinuar ....
|
Depois de algum tempo nesse mundo, percebi que a maior vantagem de ter escolhido o Linux não foi a praticidade, nem nada parecido. **Foi aprender na marra sobre como um sistema operacional funciona, e como consertar coisas que dão errado.**
|
||||||
|
|
||||||
|
Até porque muita coisa deu errado.
|
||||||
|
|
||||||
|
Primeiramente, ainda quando estava tentando instalar o sistema, pensei que tinha formatado a partição do Windows. Graças a Deus não era esse o problema, mas até eu descobrir isso se foram umas duas horas. No fim, chamamos o Enéas, que era o herói da minha família quando se tratava de informática.
|
||||||
|
|
||||||
|
Era ele quem chamávamos quando precisávamos de algum conserto, manutenção ou *upgrade* nos computadores da minha mãe e do meu pai. Chegando lá, ele avaliou a situação e me mostrou que eu não tinha apagado a partição, mas o GRUB (*bootloader* comum em várias distros Linux) não reconhecia a partição do Windows. Então, ele me ensinou a trocar a ordem de boot pela BIOS mesmo, e, no final, deu tudo certo.
|
||||||
|
|
||||||
|
Muito obrigado, Enéas! Além de ser o nosso herói, você era uma das únicas pessoas com quem eu podia falar sobre meus aprendizados computacionais, então deve se lembrar que eu falava bem mais do que o necessário quando aparecia lá em casa. Pra nós, "caras da TI" apaixonados pelo que fazem, às vezes isso é só o que precisamos.
|
||||||
|
|
||||||
|
Mas eu não me desmotivei por ter precisado de ajuda. Na verdade, eu queria ser o cara que ajudaria alguém algum dia. Por isso, continuei tentando, e aprendi muito a cada vez que dava problema.
|
||||||
|
|
||||||
|
Outra situação que ocorreu era que o sistema simplesmente não reconhecia meu adaptador de Wi-Fi da TP-Link. Não sei se era porque eu esqueci de ativar o módulo do kernel, ou se faltou algum pacote, ou se realmente não tinha driver pra esse adaptador. Depois de um tempo, passamos cabos de rede pela casa e aí eu não precisava mais do adaptador. Então, esqueci desse problema.
|
||||||
|
|
||||||
|
Só sei que, hoje em dia, às vezes preciso desse adaptador no meu PC, e ele funciona *plug-and-play*. Não sei se esse driver agora vem no kernel Linux por padrão ou se eu que aprendi a configurar direito. Mas enfim, problema resolvido, mesmo que alguns anos depois.
|
||||||
|
|
||||||
|
E eu acho que é esse tipo de perrengue que te faz aprender. Até hoje não encontrei nenhum jeito melhor de entender, na prática, como funciona um computador e seu sistema operacional. É colocando a mão na massa e errando que vamos entendendo, e **nenhum sistema te deixa tão livre pra praticar e errar quanto o Linux.**
|
||||||
|
|
||||||
## Acho que eu sei como posso te ajudar
|
## Acho que eu sei como posso te ajudar
|
||||||
|
|
||||||
Dar dicas sobre como se adaptar melhor ao linux, tirando o mindset do windows da cabeça, comparando com como as coisas são no windows. A finalidade é ajudar o eleitor a se acostumar mais rápido. Falar com o leitor em segunda pessoa nessa seção.
|
O processo de aprendizado exige um pouco de fricção. Tem que ter tentativa e erro. Mas o que eu posso fazer pra ajudar você, que está começando, é te dar algumas informações pra diminuir a dor de cabeça. O que vou falar agora é pra que você se prepare para o que está por vir. Assim, espero que consiga se acostumar mais rápido e aprender mais.
|
||||||
|
|
||||||
### Entenda o terminal
|
**O principal é tirar o "jeito Windows de resolver as coisas" da sua cabeça.** É outro sistema operacional, então as coisas são feitas de outro jeito. Muita coisa é reaproveitável, sim. Mas esteja pronto pra pensar de um jeito diferente.
|
||||||
|
|
||||||
Falar que o terminal não é a única opção, mas falar sobre a importância de saber fazer as coisas pela linha de comando.
|
Aqui vão 3 dicas sobre as principais diferenças do Linux pro Windows.
|
||||||
|
|
||||||
### Entenda o gerenciamento de pacotes
|
### 1. Entenda o terminal
|
||||||
|
|
||||||
Falar sobre o que é gerenciamento de pacotes, como ele funciona no windows, e como funciona nas distros linux.
|
No Windows, estamos acostumados a fazer tudo pela interface gráfica. Até porque lá tem uma GUI (interface gráfica de usuário) pra tudo. Não é como se no Linux não tivesse, mas o jeito padrão e mais rápido de navegar pelo sistema é pela linha de comando. Usando a interface gráfica, te garanto que vai aprender muito pouco.
|
||||||
|
|
||||||
### Entenda os drivers
|
Essa tela preta com letras brancas e fonte monoespaçada pode parecer intimidadora no começo. Mas juro que não é tão difícil se acostumar. Recomendo abrir o terminal, entender sobre como funciona o seu shell, os comandos básicos (`ls`, `cd`, `cp`, `mv`, `rm`, `cat`, etc.) e como navegar apenas pela linha de comando. Teste tudo num ambiente seguro, onde não tenha medo de estragar tudo. Vá pesquisando sobre como executar suas tarefas do dia a dia. Te garanto, tem comando pra qualquer coisa que queira fazer.
|
||||||
|
|
||||||
Falar sobre minha experiência com os drivers de wifi como exemplo
|
### 2. Entenda o gerenciamento de pacotes
|
||||||
|
|
||||||
|
Gerenciamento de pacotes é algo com o qual não estamos acostumados em ambientes Windows. Lá, ele praticamente não existe da forma que existe nos sistemas operacionais como o Linux.
|
||||||
|
|
||||||
|
Quando quiser baixar um programa, se acostume a não procurar por um executável na internet. Aprenda a pesquisar por programas no gerenciador de pacotes da sua distribuição e instalar programas por ele.
|
||||||
|
|
||||||
|
Lembra daquela pasta `C:\Arquivos de Programas`? No Windows, ela centraliza todos os arquivos necessários para que seus programas rodem corretamente. Já no Linux, os arquivos ficam separados em várias pastas, e o sistema sabe onde os encontrar. Binários em `/bin` ou `/usr/bin`, bibliotecas compartilhadas em `/usr/lib`, e por aí vai. O que o gerenciador de pacotes faz é extrair o pacote que você quer baixar e colocar cada arquivo no seu devido lugar, automaticamente.
|
||||||
|
|
||||||
|
E cada distribuição tem um sistema de pacotes diferente. Debian usa o `dpkg` e o `apt`, distros da família Red Hat (Fedora, RHEL, Rocky) usam o `rpm` e o `dnf`, e o Arch usa o `pacman`. Cada um tem um jeito de funcionar levemente diferente, então pesquisa sobre o que a sua distro usa e aprende ele.
|
||||||
|
|
||||||
|
### 3. Entenda a resolução de problemas
|
||||||
|
|
||||||
|
Isso é o mais importante. **No Linux, tudo que dá erro se explica.** Quando tem um crash ou algo dá errado, pode ter certeza que em algum lugar tem um log explicando o que aconteceu.
|
||||||
|
|
||||||
|
O processo de resolução de problemas sempre envolve olhar os logs, consertar o que deu errado e tentar de novo. Não tem muito segredo quando não se sabe o que fazer. Jogando no Google ou na IA, vai achar um monte de post de fórum, onde outra pessoa explica que teve o mesmo problema e pede ajuda. Às vezes tem resposta, e às vezes não. Só tenha certeza que está olhando nos fóruns certos. Não adianta querer resolver um problema no Ubuntu, seguindo um passo a passo obtido do fórum do Arch Linux.
|
||||||
|
|
||||||
|
Essa parte de pesquisar em fóruns é muito real. É boa parte de como se aprende. Mas **não se esqueça de pesquisar sobre o que os comandos fazem antes de executar**, porque aí mora um problema de segurança. Alguém pode simplesmente colocar um comando malicioso pra galera executar. E além da segurança, se estamos usando Linux pra aprender algo, é bom que a gente saiba por que fazemos o que fazemos.
|
||||||
|
|
||||||
|
Aquela vez que o adaptador de Wi-Fi não funcionou, passei muito tempo procurando a resposta em fóruns. Naquele caso, demorou um tempo pra que o problema fosse resolvido. Mas com certeza valeu a pena, porque aprendi muita coisa nova no processo.
|
||||||
|
|
||||||
## Enfim...
|
## Enfim...
|
||||||
|
|
||||||
Conclusão.
|
Já se passaram oito anos desde aquele dual boot no PC do meu pai, e eu continuo usando Linux todos os dias. Mudei de distro algumas vezes, quebrei o sistema mais vezes do que gostaria e, sinceramente, ainda quebro de vez em quando. A diferença é que hoje eu sei por onde começar a procurar o problema.
|
||||||
|
|
||||||
|
E é isso que ninguém te conta. **O Linux não vai te deixar mais produtivo logo de cara.** No começo, você vai perder tempo com coisa que no Windows seria um clique. Vai ficar uma tarde inteira tentando fazer o Wi-Fi funcionar, ou achando que apagou os arquivos de alguém. Mas cada um desses perrengues te ensina alguma coisa que nenhum curso ou livro ensina do mesmo jeito. Quando você vê, já entende de partições, bootloader, módulos do kernel e permissões, sem nunca ter sentado pra estudar isso formalmente.
|
||||||
|
|
||||||
|
Lembra que eu disse que queria ser o cara que ajudaria alguém algum dia? Esse post é um pouco disso. Se você está pensando em começar, *comece*. Faça num ambiente onde não tenha medo de errar, leia os logs, pesquise antes de rodar qualquer comando e, principalmente, não desanime quando precisar pedir ajuda. Eu precisei, e foi aí que eu mais aprendi.
|
||||||
|
|
||||||
|
E se algo der muito errado, bom, todo mundo precisa de um Enéas de vez em quando. Fico à disposição.
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
---
|
---
|
||||||
title: "A mudança na cápsula do tempo do Spotify e a bostificação do software"
|
title: "A mudança na cápsula do tempo do Spotify e a bostificação do software"
|
||||||
description: "Spotify simplesmente removeu uma das suas melhores funcionalidades. Além de reclamar um pouco, quero abrir um debate sobre o que os softwares estão se tornando."
|
description: "Spotify simplesmente removeu uma das suas melhores funcionalidades. Além de reclamar um pouco, quero abrir um debate sobre o que os softwares estão se tornando."
|
||||||
slug: "pt-spotify-complaining"
|
slug: "spotify-complaining"
|
||||||
pubDate: 2026-09-2
|
pubDate: 2026-09-2
|
||||||
tags: ["software", "life"]
|
tags: ["software", "life"]
|
||||||
language: "pt"
|
language: "pt"
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
---
|
---
|
||||||
title: "Entendendo o Plugin4Shell: um exploit que usa um truque simples do git para enganar agentes de IA de programação"
|
title: "Entendendo o Plugin4Shell: um exploit que usa um truque simples do git para enganar agentes de IA de programação"
|
||||||
description: "Uma branch do git com o nome de um hash de commit bastou para fazer agentes de IA de programação rodarem plugins não verificados. Reproduzi o truque do Plugin4Shell no GitHub e no Forgejo."
|
description: "Uma branch do git com o nome de um hash de commit bastou para fazer agentes de IA de programação rodarem plugins não verificados. Reproduzi o truque do Plugin4Shell no GitHub e no Forgejo."
|
||||||
slug: "pt-understanding-plugin4shell-git-trick-ai-coding-agents"
|
slug: "understanding-plugin4shell-git-trick-ai-coding-agents"
|
||||||
pubDate: 2026-09-28
|
pubDate: 2026-09-28
|
||||||
tags: ["cybersecurity", "git", "ai", "software"]
|
tags: ["cybersecurity", "git", "ai", "software"]
|
||||||
seoKeywords: "Plugin4Shell, branch do git com nome de hash de commit, bypass de SHA pinning, segurança de agentes de IA de programação, vulnerabilidade de plugin do Claude Code, ataque à cadeia de suprimentos, internals do git, Forgejo"
|
seoKeywords: "Plugin4Shell, branch do git com nome de hash de commit, bypass de SHA pinning, segurança de agentes de IA de programação, vulnerabilidade de plugin do Claude Code, ataque à cadeia de suprimentos, internals do git, Forgejo"
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { Font } from 'astro:assets';
|
||||||
import '../styles/global.css';
|
import '../styles/global.css';
|
||||||
import Header from '../components/Header.astro';
|
import Header from '../components/Header.astro';
|
||||||
import Footer from '../components/Footer.astro';
|
import Footer from '../components/Footer.astro';
|
||||||
import { getLocalizedPath, type Lang } from '../lib/i18n';
|
import { HREFLANGS, localizedAlternates, type Lang } from '../lib/i18n';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
title: string;
|
title: string;
|
||||||
|
|
@ -18,9 +18,16 @@ interface Props {
|
||||||
image?: string;
|
image?: string;
|
||||||
/** Keep the page out of search engines (used for draft posts). */
|
/** Keep the page out of search engines (used for draft posts). */
|
||||||
noindex?: boolean;
|
noindex?: boolean;
|
||||||
|
/**
|
||||||
|
* This page in each language it exists in, for hreflang links and the
|
||||||
|
* language switcher. Defaults to the same path under every language; pages
|
||||||
|
* whose URL differs per language (posts) or that may be missing in some
|
||||||
|
* language (posts, tags) pass their own.
|
||||||
|
*/
|
||||||
|
alternates?: Partial<Record<Lang, string>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { title, description, lang, noindex } = Astro.props;
|
const { title, description, lang, noindex, alternates = localizedAlternates(Astro.url.pathname) } = Astro.props;
|
||||||
const image = Astro.props.image && existsSync(`public${Astro.props.image}`) ? Astro.props.image : '/logo.png';
|
const image = Astro.props.image && existsSync(`public${Astro.props.image}`) ? Astro.props.image : '/logo.png';
|
||||||
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
|
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
|
||||||
---
|
---
|
||||||
|
|
@ -34,8 +41,9 @@ const canonicalURL = new URL(Astro.url.pathname, Astro.site);
|
||||||
<link rel="alternate icon" href="/favicon.ico" />
|
<link rel="alternate icon" href="/favicon.ico" />
|
||||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||||
<link rel="canonical" href={canonicalURL} />
|
<link rel="canonical" href={canonicalURL} />
|
||||||
<link rel="alternate" hreflang="en" href={new URL(getLocalizedPath(Astro.url.pathname, 'en'), Astro.site)} />
|
{Object.entries(alternates).map(([altLang, path]) => (
|
||||||
<link rel="alternate" hreflang="pt-BR" href={new URL(getLocalizedPath(Astro.url.pathname, 'pt'), Astro.site)} />
|
<link rel="alternate" hreflang={HREFLANGS[altLang as Lang]} href={new URL(path, Astro.site)} />
|
||||||
|
))}
|
||||||
<meta name="generator" content={Astro.generator} />
|
<meta name="generator" content={Astro.generator} />
|
||||||
<link rel="sitemap" href="/sitemap-index.xml" />
|
<link rel="sitemap" href="/sitemap-index.xml" />
|
||||||
|
|
||||||
|
|
@ -82,7 +90,7 @@ const canonicalURL = new URL(Astro.url.pathname, Astro.site);
|
||||||
</script>
|
</script>
|
||||||
</head>
|
</head>
|
||||||
<body class="flex min-h-screen flex-col bg-bg font-sans text-text antialiased selection:bg-primary selection:text-white">
|
<body class="flex min-h-screen flex-col bg-bg font-sans text-text antialiased selection:bg-primary selection:text-white">
|
||||||
<Header lang={lang} />
|
<Header lang={lang} alternates={alternates} />
|
||||||
<main class="flex-1">
|
<main class="flex-1">
|
||||||
<slot />
|
<slot />
|
||||||
</main>
|
</main>
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,12 @@ export const LANG_LABELS: Record<Lang, string> = {
|
||||||
pt: 'Português',
|
pt: 'Português',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** hreflang values for <link rel="alternate">. */
|
||||||
|
export const HREFLANGS: Record<Lang, string> = {
|
||||||
|
en: 'en',
|
||||||
|
pt: 'pt-BR',
|
||||||
|
};
|
||||||
|
|
||||||
export const ui = {
|
export const ui = {
|
||||||
en: {
|
en: {
|
||||||
'site.name': 'gabeefranco',
|
'site.name': 'gabeefranco',
|
||||||
|
|
@ -163,3 +169,13 @@ export function getLocalizedPath(pathname: string, lang: Lang): string {
|
||||||
const stripped = (isLang(first) ? pathname.slice(first.length + 1) : pathname) || '/';
|
const stripped = (isLang(first) ? pathname.slice(first.length + 1) : pathname) || '/';
|
||||||
return stripped === '/' ? `/${lang}` : `/${lang}${stripped}`;
|
return stripped === '/' ? `/${lang}` : `/${lang}${stripped}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Every language has its own slug for a post, so post URLs aren't derivable from each other. */
|
||||||
|
export function postPath(lang: Lang, slug: string): string {
|
||||||
|
return `/${lang}/posts/${slug}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Path of the same page in each language, for pages that exist in every language. */
|
||||||
|
export function localizedAlternates(pathname: string): Record<Lang, string> {
|
||||||
|
return Object.fromEntries(LANGS.map((lang) => [lang, getLocalizedPath(pathname, lang)])) as Record<Lang, string>;
|
||||||
|
}
|
||||||
|
|
|
||||||
52
src/lib/post-files.ts
Normal file
52
src/lib/post-files.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
// Reads post frontmatter straight from disk, for code that runs outside
|
||||||
|
// content collections: astro.config.mjs (before collections exist) and
|
||||||
|
// scripts/generate-social-cards.ts (plain Node). Keep this file free of Astro
|
||||||
|
// imports and use explicit .ts extensions so Node can load it directly.
|
||||||
|
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { LANGS, type Lang } from './i18n.ts';
|
||||||
|
|
||||||
|
const POSTS_DIR = 'src/content/posts';
|
||||||
|
|
||||||
|
export interface PostFile {
|
||||||
|
lang: Lang;
|
||||||
|
slug: string;
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
tags: string[];
|
||||||
|
draft: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getFrontmatterField(content: string, field: string): string | null {
|
||||||
|
const match = content.match(new RegExp(`^${field}:\\s*"?([^"\\n]+)"?`, 'm'));
|
||||||
|
return match ? match[1].trim() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads an inline tag list, e.g. `tags: ["meta", "blogging"]`. */
|
||||||
|
function getFrontmatterTags(content: string): string[] {
|
||||||
|
const list = content.match(/^tags:\s*\[([^\]]*)\]/m)?.[1] ?? '';
|
||||||
|
return [...list.matchAll(/["']([^"']+)["']/g)].map((m) => m[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Posts live at src/content/posts/<lang>/<file>.mdx (see src/content.config.ts). */
|
||||||
|
export function readPostFiles(): PostFile[] {
|
||||||
|
return LANGS.flatMap((lang) => {
|
||||||
|
const dir = join(POSTS_DIR, lang);
|
||||||
|
if (!existsSync(dir)) return [];
|
||||||
|
return readdirSync(dir)
|
||||||
|
.filter((file) => file.endsWith('.mdx'))
|
||||||
|
.map((file) => {
|
||||||
|
const raw = readFileSync(join(dir, file), 'utf-8');
|
||||||
|
const slug = getFrontmatterField(raw, 'slug');
|
||||||
|
if (!slug) throw new Error(`${join(dir, file)} is missing a \`slug\` in its frontmatter`);
|
||||||
|
return {
|
||||||
|
lang,
|
||||||
|
slug,
|
||||||
|
title: getFrontmatterField(raw, 'title') ?? slug,
|
||||||
|
description: getFrontmatterField(raw, 'description') ?? undefined,
|
||||||
|
tags: getFrontmatterTags(raw),
|
||||||
|
draft: getFrontmatterField(raw, 'draft') === 'true',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
@ -1,15 +1,20 @@
|
||||||
import { getCollection, type CollectionEntry } from 'astro:content';
|
import { getCollection, type CollectionEntry } from 'astro:content';
|
||||||
import type { Lang } from './i18n';
|
import { getLocalizedPath, LANGS, postPath, type Lang } from './i18n';
|
||||||
|
|
||||||
export type PostEntry = CollectionEntry<'posts'>;
|
export type PostEntry = CollectionEntry<'posts'>;
|
||||||
|
|
||||||
/** The id is "<lang>/<slug>" (see src/content.config.ts). */
|
/** The id is "<lang>/<file>" (see src/content.config.ts). */
|
||||||
export function langOf(entry: PostEntry): Lang {
|
export function langOf(entry: PostEntry): Lang {
|
||||||
return entry.id.split('/')[0] as Lang;
|
return entry.id.split('/')[0] as Lang;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function slugOf(entry: PostEntry): string {
|
/** Shared by a post and its translations: the filename without the language folder. */
|
||||||
return entry.id.replace('pt-', '').replace('en-', '');
|
function translationKeyOf(entry: PostEntry): string {
|
||||||
|
return entry.id.slice(entry.id.indexOf('/') + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function postHref(entry: PostEntry): string {
|
||||||
|
return postPath(langOf(entry), entry.data.slug);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -17,15 +22,21 @@ export function slugOf(entry: PostEntry): string {
|
||||||
* feed. Pass `includeDrafts` to still build their pages (reachable by URL only).
|
* feed. Pass `includeDrafts` to still build their pages (reachable by URL only).
|
||||||
*/
|
*/
|
||||||
export async function getPostsByLang(lang: Lang, { includeDrafts = false } = {}): Promise<PostEntry[]> {
|
export async function getPostsByLang(lang: Lang, { includeDrafts = false } = {}): Promise<PostEntry[]> {
|
||||||
const posts = await getCollection('posts', ({ id, data }) => {
|
const posts = await getCollection('posts', (entry) => langOf(entry) === lang && (includeDrafts || !entry.data.draft));
|
||||||
return id.startsWith(`${lang}-`) && (includeDrafts || !data.draft);
|
|
||||||
});
|
|
||||||
return posts.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());
|
return posts.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPostBySlug(lang: Lang, slug: string): Promise<PostEntry | undefined> {
|
/**
|
||||||
const posts = await getCollection('posts');
|
* URL of the post in every language it's translated to, itself included.
|
||||||
return posts.find((p) => p.id === `${lang}/${slug}`);
|
* Draft translations are only linked from other drafts.
|
||||||
|
*/
|
||||||
|
export async function getPostAlternates(entry: PostEntry): Promise<Partial<Record<Lang, string>>> {
|
||||||
|
const key = translationKeyOf(entry);
|
||||||
|
const translations = await getCollection(
|
||||||
|
'posts',
|
||||||
|
(other) => translationKeyOf(other) === key && (entry.data.draft || !other.data.draft),
|
||||||
|
);
|
||||||
|
return Object.fromEntries(translations.map((post) => [langOf(post), postHref(post)]));
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAllTags(lang: Lang): Promise<string[]> {
|
export async function getAllTags(lang: Lang): Promise<string[]> {
|
||||||
|
|
@ -37,6 +48,14 @@ export async function getAllTags(lang: Lang): Promise<string[]> {
|
||||||
return [...tags].sort((a, b) => a.localeCompare(b));
|
return [...tags].sort((a, b) => a.localeCompare(b));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** URL of the tag page in every language that has posts with that tag. */
|
||||||
|
export async function getTagAlternates(tag: string): Promise<Partial<Record<Lang, string>>> {
|
||||||
|
const tagsByLang = await Promise.all(LANGS.map(async (lang) => [lang, await getAllTags(lang)] as const));
|
||||||
|
return Object.fromEntries(
|
||||||
|
tagsByLang.filter(([, tags]) => tags.includes(tag)).map(([lang]) => [lang, getLocalizedPath(`/tags/${tag}`, lang)]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const WORDS_PER_MINUTE = 200;
|
const WORDS_PER_MINUTE = 200;
|
||||||
|
|
||||||
export function estimateReadingMinutes(body: string): number {
|
export function estimateReadingMinutes(body: string): number {
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import rss from '@astrojs/rss';
|
import rss from '@astrojs/rss';
|
||||||
import type { APIContext } from 'astro';
|
import type { APIContext } from 'astro';
|
||||||
import { getLocalizedPath, langPaths, useTranslations, type Lang } from '../../lib/i18n';
|
import { getLocalizedPath, langPaths, useTranslations, type Lang } from '../../lib/i18n';
|
||||||
import { getPostsByLang, slugOf } from '../../lib/posts';
|
import { getPostsByLang, postHref } from '../../lib/posts';
|
||||||
|
|
||||||
export const getStaticPaths = langPaths;
|
export const getStaticPaths = langPaths;
|
||||||
|
|
||||||
|
|
@ -18,7 +18,7 @@ export async function GET(context: APIContext) {
|
||||||
title: post.data.title,
|
title: post.data.title,
|
||||||
pubDate: post.data.pubDate,
|
pubDate: post.data.pubDate,
|
||||||
description: post.data.description,
|
description: post.data.description,
|
||||||
link: `${getLocalizedPath(`/posts/${slugOf(post)}`, lang)}/`,
|
link: `${postHref(post)}/`,
|
||||||
})),
|
})),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,13 +4,13 @@ import BaseLayout from '../../../layouts/BaseLayout.astro';
|
||||||
import PostLayout from '../../../layouts/PostLayout.astro';
|
import PostLayout from '../../../layouts/PostLayout.astro';
|
||||||
import ObservationCard from '../../../components/ObservationCard';
|
import ObservationCard from '../../../components/ObservationCard';
|
||||||
import { LANGS, useTranslations, type Lang } from '../../../lib/i18n';
|
import { LANGS, useTranslations, type Lang } from '../../../lib/i18n';
|
||||||
import { getPostsByLang, slugOf, estimateReadingMinutes } from '../../../lib/posts';
|
import { estimateReadingMinutes, getPostAlternates, getPostsByLang } from '../../../lib/posts';
|
||||||
import { postCardPath } from '../../../lib/social-cards';
|
import { postCardPath } from '../../../lib/social-cards';
|
||||||
|
|
||||||
export async function getStaticPaths() {
|
export async function getStaticPaths() {
|
||||||
const pathsByLang = await Promise.all(
|
const pathsByLang = await Promise.all(
|
||||||
LANGS.map(async (lang) =>
|
LANGS.map(async (lang) =>
|
||||||
(await getPostsByLang(lang, { includeDrafts: true })).map((post) => ({ params: { lang, slug: slugOf(post) }, props: { post } })),
|
(await getPostsByLang(lang, { includeDrafts: true })).map((post) => ({ params: { lang, slug: post.data.slug }, props: { post } })),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
return pathsByLang.flat();
|
return pathsByLang.flat();
|
||||||
|
|
@ -21,14 +21,16 @@ const t = useTranslations(lang);
|
||||||
const { post } = Astro.props;
|
const { post } = Astro.props;
|
||||||
const { Content } = await render(post);
|
const { Content } = await render(post);
|
||||||
const readingMinutes = estimateReadingMinutes(post.body ?? '');
|
const readingMinutes = estimateReadingMinutes(post.body ?? '');
|
||||||
|
const alternates = await getPostAlternates(post);
|
||||||
---
|
---
|
||||||
|
|
||||||
<BaseLayout
|
<BaseLayout
|
||||||
title={`${post.data.title} — ${t('site.name')}`}
|
title={`${post.data.title} — ${t('site.name')}`}
|
||||||
description={post.data.description}
|
description={post.data.description}
|
||||||
lang={lang}
|
lang={lang}
|
||||||
image={postCardPath(lang, slugOf(post))}
|
image={postCardPath(lang, post.data.slug)}
|
||||||
noindex={post.data.draft}
|
noindex={post.data.draft}
|
||||||
|
alternates={alternates}
|
||||||
>
|
>
|
||||||
<PostLayout post={post} lang={lang} readingMinutes={readingMinutes}>
|
<PostLayout post={post} lang={lang} readingMinutes={readingMinutes}>
|
||||||
<Content components={{ ObservationCard }} />
|
<Content components={{ ObservationCard }} />
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
import BaseLayout from '../../../../layouts/BaseLayout.astro';
|
import BaseLayout from '../../../../layouts/BaseLayout.astro';
|
||||||
import PostsContent from '../../../../components/PostsContent.astro';
|
import PostsContent from '../../../../components/PostsContent.astro';
|
||||||
import { LANGS, tagPageMeta, useTranslations, type Lang } from '../../../../lib/i18n';
|
import { LANGS, tagPageMeta, useTranslations, type Lang } from '../../../../lib/i18n';
|
||||||
import { getAllTags } from '../../../../lib/posts';
|
import { getAllTags, getTagAlternates } from '../../../../lib/posts';
|
||||||
import { tagCardPath } from '../../../../lib/social-cards';
|
import { tagCardPath } from '../../../../lib/social-cards';
|
||||||
|
|
||||||
export async function getStaticPaths() {
|
export async function getStaticPaths() {
|
||||||
|
|
@ -16,8 +16,9 @@ const lang = Astro.params.lang as Lang;
|
||||||
const tag = Astro.params.tag!;
|
const tag = Astro.params.tag!;
|
||||||
const t = useTranslations(lang);
|
const t = useTranslations(lang);
|
||||||
const page = tagPageMeta(lang, tag);
|
const page = tagPageMeta(lang, tag);
|
||||||
|
const alternates = await getTagAlternates(tag);
|
||||||
---
|
---
|
||||||
|
|
||||||
<BaseLayout title={`${page.title} — ${t('site.name')}`} description={page.description} lang={lang} image={tagCardPath(lang, tag)}>
|
<BaseLayout title={`${page.title} — ${t('site.name')}`} description={page.description} lang={lang} image={tagCardPath(lang, tag)} alternates={alternates}>
|
||||||
<PostsContent lang={lang} tag={tag} />
|
<PostsContent lang={lang} tag={tag} />
|
||||||
</BaseLayout>
|
</BaseLayout>
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue