Skip to content

Commit

Permalink
Add the Astro Prettier Plugin (withastro#1199)
Browse files Browse the repository at this point in the history
* Add Astro Prettier Plugin

* Format everything!

* Revert "Format everything!"

This reverts commit ef849a6.

* Update plugin version

* Format everything

* Revert "Format everything"

This reverts commit a91789d.

* Format everything

* Update branch

* Update printWidth to match main repo

* Update .github/workflows/format.yml

Co-authored-by: Chris Swithinbank <[email protected]>

Co-authored-by: Chris Swithinbank <[email protected]>
  • Loading branch information
Princesseuh and delucis authored Sep 13, 2022
1 parent 7f946f4 commit af21fba
Show file tree
Hide file tree
Showing 118 changed files with 2,182 additions and 1,364 deletions.
5 changes: 4 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ module.exports = {
parser: '@typescript-eslint/parser',
extends: ['plugin:@typescript-eslint/recommended'],
rules: {
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', destructuredArrayIgnorePattern: '^_' }],
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', destructuredArrayIgnorePattern: '^_' },
],
'@typescript-eslint/no-non-null-assertion': 'off',
},
},
Expand Down
30 changes: 30 additions & 0 deletions .github/workflows/format.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: 'Format Code'

on:
push:
branches:
- main

jobs:
format:
runs-on: ubuntu-latest
env:
NODE_OPTIONS: "--max_old_space_size=4096"
steps:
- name: Check out code using Git
uses: actions/checkout@v3
with:
ref: ${{ github.head_ref }}
# Needs access to push to main
token: ${{ secrets.FREDKBOT_GITHUB_TOKEN }}
- name: Install Tools & Dependencies
uses: ./.github/actions/install
- name: Format code
run: pnpm run format:ci
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: '[ci] format'
branch: ${{ github.head_ref }}
commit_user_name: fredkbot
commit_user_email: [email protected]
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ node_modules
.github
.changeset
*.md
src/pages/lighthouse/*.astro
pnpm-lock.yaml
8 changes: 7 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"printWidth": 180,
"printWidth": 100,
"semi": true,
"singleQuote": true,
"tabWidth": 2,
Expand All @@ -11,6 +11,12 @@
"options": {
"useTabs": false
}
},
{
"files": ["**/*.astro"],
"options": {
"parser": "astro"
}
}
]
}
6 changes: 4 additions & 2 deletions astro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,16 @@ const createSROnlyLabel = (text: string) => {
export default defineConfig({
site: 'https://docs.astro.build/',
legacy: {
astroFlavoredMarkdown: true
astroFlavoredMarkdown: true,
},
integrations: [
preact({ compat: true }),
sitemap({
i18n: {
defaultLocale: 'en',
locales: Object.fromEntries(Object.keys(languages).map((lang) => [lang, normalizeLangTag(lang)])),
locales: Object.fromEntries(
Object.keys(languages).map((lang) => [lang, normalizeLangTag(lang)])
),
},
}),
astroAsides(),
Expand Down
5 changes: 4 additions & 1 deletion integrations/astro-asides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ export function astroAsides(): AstroIntegration {
});

// Auto-import the Aside component and attach it to the global scope
injectScript('page-ssr', `import ${AsideTagname} from "~/components/Aside.astro"; global.${AsideTagname} = ${AsideTagname};`);
injectScript(
'page-ssr',
`import ${AsideTagname} from "~/components/Aside.astro"; global.${AsideTagname} = ${AsideTagname};`
);
},
},
};
Expand Down
35 changes: 22 additions & 13 deletions integrations/astro-code-snippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,13 @@ export function remarkCodeSnippets(): Plugin<[], Root> {
let title = metaTitle;

// Preprocess the code
const { preprocessedCode, extractedFileName, removedLineIndex, removedLineCount } = preprocessCode(
code.value,
code.lang || '',
// Only try to extract a file name from the code if no meta title was found above
title === undefined
);
const { preprocessedCode, extractedFileName, removedLineIndex, removedLineCount } =
preprocessCode(
code.value,
code.lang || '',
// Only try to extract a file name from the code if no meta title was found above
title === undefined
);
code.value = preprocessedCode;
if (extractedFileName) {
title = extractedFileName;
Expand All @@ -90,8 +91,10 @@ export function remarkCodeSnippets(): Plugin<[], Root> {
prev.children[0].children[0];

// Require the strong content to be either raw text or inline code and retrieve its value
const prevParaStrongTextValue = strongContent && strongContent.type === 'text' && strongContent.value;
const prevParaStrongCodeValue = strongContent && strongContent.type === 'inlineCode' && strongContent.value;
const prevParaStrongTextValue =
strongContent && strongContent.type === 'text' && strongContent.value;
const prevParaStrongCodeValue =
strongContent && strongContent.type === 'inlineCode' && strongContent.value;
const potentialFileName = prevParaStrongTextValue || prevParaStrongCodeValue;

// Check if it's a file name
Expand Down Expand Up @@ -177,10 +180,13 @@ function parseMeta(meta: string) {
// - `del=/src\/pages\/.*\.astro/` (escaping special chars with a backslash works, too)
// - `ins=/this|that/`
const inlineMarkings: string[] = [];
meta = meta.replace(/(?:\s|^)(?:([a-zA-Z]+)\s*=\s*)?([/"'])(.*?)(?<!\\)\2(?=\s|$)/g, (_, prefix, delimiter, expression) => {
inlineMarkings.push(`${prefix || 'mark'}=${delimiter}${expression}${delimiter}`);
return '';
});
meta = meta.replace(
/(?:\s|^)(?:([a-zA-Z]+)\s*=\s*)?([/"'])(.*?)(?<!\\)\2(?=\s|$)/g,
(_, prefix, delimiter, expression) => {
inlineMarkings.push(`${prefix || 'mark'}=${delimiter}${expression}${delimiter}`);
return '';
}
);

return {
title,
Expand Down Expand Up @@ -295,7 +301,10 @@ export function astroCodeSnippets(): AstroIntegration {
});

// Auto-import the Aside component and attach it to the global scope
injectScript('page-ssr', `import ${CodeSnippetTagname} from "~/components/CodeSnippet/CodeSnippet.astro"; global.${CodeSnippetTagname} = ${CodeSnippetTagname};`);
injectScript(
'page-ssr',
`import ${CodeSnippetTagname} from "~/components/CodeSnippet/CodeSnippet.astro"; global.${CodeSnippetTagname} = ${CodeSnippetTagname};`
);
},
},
};
Expand Down
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"format": "prettier -w .",
"format": "pnpm run format:code",
"format:ci": "pnpm run format:imports && pnpm run format:code",
"format:code": "prettier -w . --cache --plugin-search-dir=.",
"format:imports": "organize-imports-cli ./tsconfig.json",
"add-language": "node ./scripts/add-language.mjs",
"docgen": "node ./scripts/docgen.mjs",
"docgen:integrations": "tsm --require=./scripts/lib/filter-warnings.cjs ./scripts/generate-integration-pages.ts",
Expand Down Expand Up @@ -48,10 +51,12 @@
"htmlparser2": "^7.2.0",
"kleur": "^4.1.5",
"node-fetch": "^3.2.10",
"organize-imports-cli": "^0.10.0",
"p-retry": "^5.1.1",
"parse-numeric-range": "^1.3.0",
"preact": "^10.10.1",
"prettier": "^2.7.1",
"prettier-plugin-astro": "^0.5.4",
"prompts": "^2.4.2",
"remark": "^14.0.2",
"remark-directive": "^2.0.1",
Expand Down
25 changes: 10 additions & 15 deletions plugins/remark-fallback-lang.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,22 @@ export function remarkFallbackLang(): Plugin<[], Root> {
const pageLang = getLanguageCodeFromPathname(pageUrl.pathname);

// Ignore pages without language prefix and English pages
if (!pageLang || pageLang === 'en')
return;
if (!pageLang || pageLang === 'en') return;

visit(tree, 'link', (link) => {
const linkUrl = new URL(link.url, pageUrl);

// Ignore external links
if (pageUrl.host !== linkUrl.host)
return;
if (pageUrl.host !== linkUrl.host) return;

// Ignore link targets without language prefix
const linkLang = getLanguageCodeFromPathname(linkUrl.pathname);
if (!linkLang)
return;
if (!linkLang) return;

// Ignore link targets that have a valid source file
const linkSourceFileName = tryFindSourceFileForPathname(linkUrl.pathname, pageSourceDir);
if (linkSourceFileName)
return;

if (linkSourceFileName) return;

link.children.push({
type: 'html',
value: `&nbsp;(EN)`,
Expand All @@ -58,25 +54,24 @@ function getLanguageCodeFromPathname(pathname: string) {
const firstPathPart = pathname.split('/')[1];
// Only return parts that look like a two-letter language code
// with optional two-letter country code
if (firstPathPart.match(/^[a-z]{2}(-[a-zA-Z]{2})?$/))
return firstPathPart;
if (firstPathPart.match(/^[a-z]{2}(-[a-zA-Z]{2})?$/)) return firstPathPart;
}

/**
* Attempts to find a Markdown source file for the given `pathname`.
*
*
* Example: Given a pathname of `/en/some-page` or `/en/some-page/`,
* searches for the source file in the following locations
* and returns the first matching path:
* - `${this.pageSourceDir}/en/some-page.md`
* - `${this.pageSourceDir}/en/some-page/index.md`
*
*
* If no existing file is found, returns `undefined`.
*/
export function tryFindSourceFileForPathname (pathname: string, pageSourceDir: string) {
export function tryFindSourceFileForPathname(pathname: string, pageSourceDir: string) {
const possibleSourceFilePaths = [
path.join(pageSourceDir, pathname, '.') + '.md',
path.join(pageSourceDir, pathname, 'index.md'),
];
return possibleSourceFilePaths.find(possiblePath => fs.existsSync(possiblePath));
return possibleSourceFilePaths.find((possiblePath) => fs.existsSync(possiblePath));
}
Loading

0 comments on commit af21fba

Please sign in to comment.