diff --git a/scripts/update-git-templates.mjs b/scripts/update-git-templates.mjs new file mode 100644 index 00000000..a2a41902 --- /dev/null +++ b/scripts/update-git-templates.mjs @@ -0,0 +1,75 @@ +// Downloads every template of github/gitignore and alexkaratarakis/gitattributes into JSON snapshots that the +// gitignore and gitattributes generators fall back to when offline or when GitHub can't be reached. +// Usage: pnpm script:update:git-templates (set GITHUB_TOKEN to avoid the unauthenticated API rate limit) +import fs from 'node:fs/promises'; + +const sources = [ + { + repository: 'github/gitignore', + ref: 'main', + extension: '.gitignore', + output: 'src/tools/gitignore-generator/gitignore-templates.json', + }, + { + repository: 'alexkaratarakis/gitattributes', + ref: 'master', + extension: '.gitattributes', + output: 'src/tools/gitattributes-generator/gitattributes-templates.json', + }, +]; + +const CONCURRENCY = 8; + +const apiHeaders = { + Accept: 'application/vnd.github+json', + ...(process.env.GITHUB_TOKEN ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` } : {}), +}; + +async function fetchOk(url, init) { + const response = await fetch(url, init); + if (!response.ok) { + throw new Error(`${url}: ${response.status} ${response.statusText}`); + } + return response; +} + +async function snapshot({ repository, ref, extension, output }) { + const commit = await ( + await fetchOk(`https://api.github.com/repos/${repository}/commits/${ref}`, { headers: apiHeaders }) + ).json(); + const tree = await ( + await fetchOk(`https://api.github.com/repos/${repository}/git/trees/${commit.sha}?recursive=true`, { + headers: apiHeaders, + }) + ).json(); + if (tree.truncated) { + throw new Error(`${repository}: tree listing is truncated`); + } + + // Same name derivation as the tools: the path without its extension, skipping a bare root dotfile + const names = tree.tree + .filter(({ type, path }) => type === 'blob' && path.endsWith(extension)) + .map(({ path }) => path.slice(0, -extension.length)) + .filter(Boolean) + .sort((a, b) => a.localeCompare(b)); + + const templates = {}; + for (let i = 0; i < names.length; i += CONCURRENCY) { + const batch = names.slice(i, i + CONCURRENCY); + const contents = await Promise.all( + batch.map(async (name) => + (await fetchOk(`https://raw.githubusercontent.com/${repository}/${commit.sha}/${name}${extension}`)).text(), + ), + ); + batch.forEach((name, index) => (templates[name] = contents[index])); + } + + const data = { repository, ref, commit: commit.sha, date: commit.commit.committer.date, templates }; + await fs.writeFile(output, `${JSON.stringify(data, null, 2)}\n`); + const size = (await fs.stat(output)).size; + console.log(`${output}: ${names.length} templates from ${repository}@${commit.sha.slice(0, 7)} (${size} bytes)`); +} + +for (const source of sources) { + await snapshot(source); +} diff --git a/src/tools/gitattributes-generator/gitattributes-generator.vue b/src/tools/gitattributes-generator/gitattributes-generator.vue index 7a2d15f4..2538e10c 100644 --- a/src/tools/gitattributes-generator/gitattributes-generator.vue +++ b/src/tools/gitattributes-generator/gitattributes-generator.vue @@ -2,6 +2,15 @@ import { useI18n } from 'vue-i18n'; import { onMounted } from 'vue'; import { useLocalStorage } from '@vueuse/core'; +import { + type GitTemplatesSnapshot, + type GitTemplatesSource, + liveTemplateUrl, + loadTemplate, + loadTemplateNames, + snapshotDay, +} from '../gitignore-generator/git-templates'; +import { isOfflineMode } from '@/tools-settings'; const { t } = useI18n(); @@ -13,70 +22,45 @@ const output = ref(''); const lastFetched = useLocalStorage('gitattr-gen:ts', 0); const CACHE_TTL = 1000 * 60 * 60 * 24; // 24h +// Commit date of the bundled snapshot, shown when templates come from it (offline mode or GitHub unreachable) +const snapshotDate = ref(''); + +const source: GitTemplatesSource = { + repository: 'alexkaratarakis/gitattributes', + ref: 'master', + extension: '.gitattributes', + loadSnapshot: () => import('./gitattributes-templates.json').then((m) => m.default as GitTemplatesSnapshot), +}; + async function loadOptions() { const now = Date.now(); const isStale = !options.value.length || now - lastFetched.value > CACHE_TTL; - if (!isStale) { + if (!isStale && !isOfflineMode) { // Use cached options return; } - try { - const res = await fetch( - 'https://api.github.com/repos/alexkaratarakis/gitattributes/git/trees/master?recursive=true', - ); - const files = await res.json(); - options.value = files.tree - .filter((f: any) => f.path.endsWith('.gitattributes')) - .map((f: any) => f.path.replace('.gitattributes', '')) - .filter(Boolean) - .map((name: string) => ({ - label: name, - value: name, - })); + const { names, snapshot } = await loadTemplateNames(source, { offline: isOfflineMode }); + options.value = names.map((name: string) => ({ + label: name, + value: name, + })); + if (snapshot) { + snapshotDate.value = snapshotDay(snapshot); + } else { lastFetched.value = now; - } catch { - if (!options.value?.length) { - options.value = [ - 'ActionScript', - 'Ada', - 'Ballerina', - 'C++', - 'CSharp', - 'Common', - 'Delphi', - 'Drupal', - 'Fortran', - 'Fountain', - 'Go', - 'Java', - 'Lua', - 'Matlab', - 'ObjectiveC', - 'Pascal', - 'Perl', - 'Python', - 'R', - 'Rails', - 'Servoy', - 'VisualStudio', - 'Web', - ].map((name) => ({ - label: name, - value: name, - })); - } } } async function generateOutput() { let gitattributes = ''; for (const lang of selected.value) { - const url = `https://raw.githubusercontent.com/alexkaratarakis/gitattributes/master/${lang}.gitattributes`; - const res = await fetch(url); - const text = await res.text(); - gitattributes += `${gitattributes ? '\n\n' : ''}# === .gitattributes for ${lang} (${url}) ===\n\n${text}`; + const { content, url, snapshot } = await loadTemplate(source, lang, { offline: isOfflineMode }); + if (snapshot) { + snapshotDate.value = snapshotDay(snapshot); + } + gitattributes += `${gitattributes ? '\n\n' : ''}# === .gitattributes for ${lang} (${url}) ===\n\n${content}`; } output.value = gitattributes; } @@ -86,9 +70,7 @@ const commands = computed(() => { if (!selected.value.length) { return { curl: '', wget: '', powershell: '', cmd: '' }; } - const urls = selected.value - .map((lang) => `https://raw.githubusercontent.com/alexkaratarakis/gitattributes/master/${lang}.gitattributes`) - .join(' '); + const urls = selected.value.map((lang) => liveTemplateUrl(source, lang)).join(' '); return { curl: `curl ${urls} > .gitattributes`, wget: `wget ${urls} -O .gitattributes`, @@ -111,6 +93,9 @@ onMounted(loadOptions); :options="options" /> + + {{ t('tools.gitattributes-generator.texts.snapshot-used', [snapshotDate]) }} + {{ t('tools.gitattributes-generator.texts.tag-fetch-generate') }} @@ -120,7 +105,8 @@ onMounted(loadOptions); - + + diff --git a/src/tools/gitattributes-generator/gitattributes-templates.json b/src/tools/gitattributes-generator/gitattributes-templates.json new file mode 100644 index 00000000..44361628 --- /dev/null +++ b/src/tools/gitattributes-generator/gitattributes-templates.json @@ -0,0 +1,49 @@ +{ + "repository": "alexkaratarakis/gitattributes", + "ref": "master", + "commit": "2c20a14833a5ab196c7fc3effcc72ef4e895f4d4", + "date": "2026-07-22T18:17:24Z", + "templates": { + "ActionScript": "# Adobe Flash authoring file\n*.fla text\n\n# ActionScript file\n*.as text\n\n# Flash XML file\n*.xml text\n\n# Treat .swf and .swc as binary\n# https://stackoverflow.com/q/1529178\n\n# Compiled Flash file\n*.swf binary -crlf -diff -merge\n\n# Compiled Flash Library/Script\n*.swc binary -crlf -diff -merge\n\n# ActionScript Communication file\n*.asc text\n\n# Flash JavaScript file\n*.jsfl text\n", + "Ada": "# Handle line endings automatically for files detected as text\n# and leave all files detected as binary untouched.\n* text=auto\n\n# Ada files\n*.ada text diff=ada\n*.adb text diff=ada\n*.ads text diff=ada\n\n# GNAT Project files (syntax similar to Ada)\n*.gpr linguist-language=Ada\n", + "C++": "# Sources\n*.c text diff=cpp\n*.cc text diff=cpp\n*.cxx text diff=cpp\n*.cpp text diff=cpp\n*.cpi text diff=cpp\n*.c++ text diff=cpp\n*.hpp text diff=cpp\n*.h text diff=cpp\n*.h++ text diff=cpp\n*.hh text diff=cpp\n\n# Compiled Object files\n*.slo binary\n*.lo binary\n*.o binary\n*.obj binary\n\n# Precompiled Headers\n*.gch binary\n*.pch binary\n\n# Compiled Dynamic libraries\n*.so binary\n*.dylib binary\n*.dll binary\n\n# Compiled Static libraries\n*.lai binary\n*.la binary\n*.a binary\n*.lib binary\n\n# Executables\n*.exe binary\n*.out binary\n*.app binary\n", + "Common": "# Common settings that generally should always be used with your language specific settings\n\n# Auto detect text files and perform LF normalization\n* text=auto\n\n#\n# The above will handle all files NOT found below\n#\n\n# Documents\n*.bibtex text diff=bibtex\n*.doc diff=astextplain\n*.DOC diff=astextplain\n*.docx diff=astextplain\n*.DOCX diff=astextplain\n*.dot diff=astextplain\n*.DOT diff=astextplain\n*.pdf diff=astextplain\n*.PDF diff=astextplain\n*.rtf diff=astextplain\n*.RTF diff=astextplain\n*.md text diff=markdown\n*.mdx text diff=markdown\n*.tex text diff=tex\n*.adoc text\n*.textile text\n*.mustache text\n*.csv text eol=crlf\n*.tab text\n*.tsv text\n*.txt text\n*.sql text\n*.epub diff=astextplain\n\n# Graphics\n*.png binary\n*.jpg binary\n*.jpeg binary\n*.gif binary\n*.tif binary\n*.tiff binary\n*.ico binary\n# SVG treated as text by default.\n*.svg text\n# If you want to treat it as binary,\n# use the following line instead.\n# *.svg binary\n*.eps binary\n\n# Scripts\n*.bash text eol=lf\n*.fish text eol=lf\n*.ksh text eol=lf\n*.sh text eol=lf\n*.zsh text eol=lf\n# These are explicitly windows files and should use crlf\n*.bat text eol=crlf\n*.cmd text eol=crlf\n*.ps1 text eol=crlf\n\n# Serialisation\n*.json text\n*.toml text\n*.xml text\n*.yaml text\n*.yml text\n\n# Archives\n*.7z binary\n*.bz binary\n*.bz2 binary\n*.bzip2 binary\n*.gz binary\n*.lz binary\n*.lzma binary\n*.rar binary\n*.tar binary\n*.taz binary\n*.tbz binary\n*.tbz2 binary\n*.tgz binary\n*.tlz binary\n*.txz binary\n*.xz binary\n*.Z binary\n*.zip binary\n*.zst binary\n\n# Text files where line endings should be preserved\n*.patch -text\n\n#\n# Exclude files from exporting\n#\n\n.gitattributes export-ignore\n.gitignore export-ignore\n.gitkeep export-ignore\n", + "community/Ballerina": "# Handle line endings automatically for files detected as text\n# and leave all files detected as binary untouched.\n* text=auto\n\n#\n# The above will handle all files NOT found below\n#\n# These files are text and should be normalized (Convert crlf => lf)\n*.bal text\n*.bash text eol=lf\n*.css text diff=css\n*.df text\n*.htm text diff=html\n*.html text diff=html\n*.js text\n*.mjs text\n*.cjs text\n*.json text\n*.properties text\n*.sh text eol=lf\n*.tld text\n*.txt text\n*.tag text\n*.tagx text\n*.xml text\n*.yml text\n\n# These files are binary and should be left untouched\n# (binary is a macro for -text -diff)\n*.balx binary\n*.dll binary\n*.ear binary\n*.gif binary\n*.ico binary\n*.jpg binary\n*.jpeg binary\n*.png binary\n*.so binary\n", + "community/Flutter": "# Auto detect text files and perform LF normalization\n* text=auto\n\n# Always perform LF normalization\n*.dart text\n*.gradle text\n*.html text\n*.java text\n*.json text\n*.md text\n*.py text\n*.sh text\n*.txt text\n*.xml text\n*.yaml text\n\n# Make sure that these Windows files always have CRLF line endings at checkout\n*.bat text eol=crlf\n*.ps1 text eol=crlf\n*.rc text eol=crlf\n*.sln text eol=crlf\n*.props text eol=crlf\n*.vcxproj text eol=crlf\n*.vcxproj.filters text eol=crlf\n# Including templates\n*.sln.tmpl text eol=crlf\n*.props.tmpl text eol=crlf\n*.vcxproj.tmpl text eol=crlf\n\n# Never perform LF normalization\n*.ico binary\n*.jar binary\n*.png binary\n*.zip binary\n*.ttf binary\n*.otf binary\n", + "community/Fountain": "# Handle line endings automatically for files detected as text\n# and leave all files detected as binary untouched.\n* text=auto\n\n# Fountain files\n*.fountain text diff=fountain\n*.pdf binary\n*.fdx text\n", + "community/FSharp": "# Auto detect text files and perform LF normalization\n* text=auto\n\n*.fs text diff=fsharp\n*.fsx text diff=fsharp\n*.sln text eol=crlf\n*.fsproj text eol=crlf\n", + "community/Hashicorp": "# HachiCorp Configuration Language\n*.hcl eol=lf\n\n# Terraform\n*.tf text eol=lf\n*.tf.json text eol=lf\n*.tfvars text eol=lf\n\n# Vagrant\nVagrantfile text eol=lf\n", + "community/sql": "# Basic .gitattributes for sql files\n\n*.sql linguist-detectable=true\n*.sql linguist-language=sql\n", + "CSharp": "# Auto detect text files and perform LF normalization\n* text=auto\n\n*.cs text diff=csharp\n*.cshtml text diff=html\n*.csx text diff=csharp\n*.sln text eol=crlf\n*.slnx text eol=crlf\n*.csproj text eol=crlf\n", + "Delphi": "#\n# Project files\n#\n\n# Delphi form module\n*.dfm text\n\n# Delphi project options file\n*.dof text\n\n# Desktop configuration\n*.dsk binary\n\n#\n# General\n#\n\n# Text file\n*.txt text\n\n# Gettext Portable Object\n*.po binary\n\n# Backup\n*.bak binary\n\n# Config file\n*.cfg text\n\n# Compiled Help File - contains html. See also package chm\n*.chm binary\n\n# Comma Separated Values text file format\n*.csv text eol=crlf\n\n# Directly executable program\n*.exe binary\n\n# Help file\n*.hlp binary\n\n# Initialization file\n*.ini text\n\n# OpenDocument text document\n*.odt text\n\n# Portable Document Format\n*.pdf binary\n\n# PostScript\n*.ps text\n\n# Rich Text Format text file\n*.rtf text\n\n#\n# Image\n#\n\n# Portable network graphic\n*.png binary\n\n# Bitmap\n*.bmp binary\n\n# Icon\n*.ico binary\n\n# Pixmap\n*.xpm binary\n\n# Portable pixmap\n*.ppm binary\n\n# Portable graymap\n*.pgm binary\n\n# Portable bitmap\n*.pbm binary\n\n# Lossy graphics file\n*.jpg binary\n\n#\n# XML\n#\n\n*.xml text\n*.dtd text\n*.xsd text\n*.xsl text\n\n#\n# Web\n#\n\n# Hypertext Markup Language\n*.html text diff=html\n\n# Cascading style sheet\n*.css text diff=css\n\n#\n# Archive\n#\n\n# tape archive\n*.tar binary\n\n# archive file\n*.zip binary\n\n#\n# Database\n#\n\n# Database file\n*.dbf binary\n\n# Multiple index file\n*.mdx binary\n\n#\n# Spreadsheet\n#\n\n# OpenOffice.org Calc spreadsheet File Format\n*.ods binary\n\n# Microsoft Excel File Format\n*.xls binary\n\n# Microsoft Office Open XML Excel File Format\n*.xlsx binary\n", + "Drupal": "# Drupal git normalization\n# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html\n# @see https://www.drupal.org/node/1542048\n\n# Normally these settings would be done with macro attributes for improved\n# readability and easier maintenance. However macros can only be defined at the\n# repository root directory. Drupal avoids making any assumptions about where it\n# is installed.\n\n# Define text file attributes.\n# - Treat them as text.\n# - Ensure no CRLF line-endings, neither on checkout nor on checkin.\n# - Detect whitespace errors.\n# - Exposed by default in `git diff --color` on the CLI.\n# - Validate with `git diff --check`.\n# - Deny applying with `git apply --whitespace=error-all`.\n# - Fix automatically with `git apply --whitespace=fix`.\n\n*.bash text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php\n*.config text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.css text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.dist text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.engine text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php\n*.html text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html\n*.inc text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php\n*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php\n*.js text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.mjs text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.cjs text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.json text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.lock text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.map text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.md text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.module text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php\n*.php text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php\n*.po text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php\n*.script text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.sh text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php\n*.sql text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.svg text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.theme text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php\n*.twig text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.txt text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.xml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n*.yml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2\n\n# Define binary file attributes.\n# - Do not treat them as text.\n# - Include binary diff in patches instead of \"binary files differ.\"\n*.eot -text diff\n*.exe -text diff\n*.gif -text diff\n*.gz -text diff\n*.ico -text diff\n*.jpeg -text diff\n*.jpg -text diff\n*.otf -text diff\n*.phar -text diff\n*.png -text diff\n*.svgz -text diff\n*.ttf -text diff\n*.woff -text diff\n*.woff2 -text diff\n", + "DyalogAPL": "# Basic .gitattributes for a Dyalog APL repo.\n# This template includes MiServer\n\n# Source files\n# ============\n*.apl? linguist-language=APL\n*.dyalog linguist-language=APL\n*.dyapp linguist-language=APL\n*.mipage linguist-language=APL\n\n# Config and log files\n# ====================\n.dcfg linguist-language=JSON5\n.dlf linguist-language=JSON5\n", + "Elixir": "# Handle line endings automatically for files detected as text\n# and leave all files detected as binary untouched.\n* text=auto\n\n# Elixir files\n*.ex diff=elixir\n*.exs diff=elixir\n", + "Fortran": "# Handle line endings automatically for files detected as text\n# and leave all files detected as binary untouched.\n* text=auto\n\n# Fortran files\n*.f text diff=fortran\n*.for text diff=fortran\n*.f90 text diff=fortran\n*.f95 text diff=fortran\n*.f03 text diff=fortran\n", + "Global/DevContainer": "# Fix syntax highlighting on GitHub to allow comments\n.devcontainer.json linguist-language=JSON-with-Comments\ndevcontainer.json linguist-language=JSON-with-Comments\n", + "Global/VisualStudio": "###############################################################################\n# Set default behavior to automatically normalize line endings.\n###############################################################################\n* text=auto\n\n###############################################################################\n# Set the merge driver for project and solution files\n#\n# Merging from the command prompt will add diff markers to the files if there\n# are conflicts (Merging from VS is not affected by the settings below, in VS\n# the diff markers are never inserted). Diff markers may cause the following\n# file extensions to fail to load in VS. An alternative would be to treat\n# these files as binary and thus will always conflict and require user\n# intervention with every merge. To do so, just comment the entries below and\n# uncomment the group further below\n###############################################################################\n\n*.sln text eol=crlf\n*.csproj text eol=crlf\n*.vbproj text eol=crlf\n*.vcxproj text eol=crlf\n*.vcproj text eol=crlf\n*.dbproj text eol=crlf\n*.fsproj text eol=crlf\n*.lsproj text eol=crlf\n*.wixproj text eol=crlf\n*.modelproj text eol=crlf\n*.sqlproj text eol=crlf\n*.wwaproj text eol=crlf\n\n*.xproj text eol=crlf\n*.props text eol=crlf\n*.filters text eol=crlf\n*.vcxitems text eol=crlf\n\n\n#*.sln merge=binary\n#*.csproj merge=binary\n#*.vbproj merge=binary\n#*.vcxproj merge=binary\n#*.vcproj merge=binary\n#*.dbproj merge=binary\n#*.fsproj merge=binary\n#*.lsproj merge=binary\n#*.wixproj merge=binary\n#*.modelproj merge=binary\n#*.sqlproj merge=binary\n#*.wwaproj merge=binary\n\n#*.xproj merge=binary\n#*.props merge=binary\n#*.filters merge=binary\n#*.vcxitems merge=binary\n", + "Global/VisualStudioCode": "# Fix syntax highlighting on GitHub to allow comments\n.vscode/*.json linguist-language=JSON-with-Comments\n", + "Go": "# Treat all Go files in this repo as binary, with no git magic updating\n# line endings. Windows users contributing to Go will need to use a\n# modern version of git and editors capable of LF line endings.\n\n*.go -text diff=golang\n", + "Java": "# Java sources\n*.java text diff=java\n*.kt text diff=kotlin\n*.groovy text diff=java\n*.scala text diff=java\n*.gradle text diff=java\n*.gradle.kts text diff=kotlin\n\n# These files are text and should be normalized (Convert crlf => lf)\n*.css text diff=css\n*.scss text diff=css\n*.sass text\n*.df text\n*.htm text diff=html\n*.html text diff=html\n*.js text\n*.mjs text\n*.cjs text\n*.jsp text\n*.jspf text\n*.jspx text\n*.properties text\n*.tld text\n*.tag text\n*.tagx text\n*.xml text\n\n# These files are binary and should be left untouched\n# (binary is a macro for -text -diff)\n*.class binary\n*.dll binary\n*.ear binary\n*.jar binary\n*.so binary\n*.war binary\n*.jks binary\n\n# Common build-tool wrapper scripts ('.cmd' versions are handled by 'Common.gitattributes')\nmvnw text eol=lf\ngradlew text eol=lf\n\n# These are explicitly windows files and should use crlf\n*.bat text eol=crlf\n", + "Lua": "# Basic .gitattributes for a Lua repo.\n\n# Source files\n# ============\n*.lua text\n\n# Luadoc output\n# =============\n*.html text diff=html\n*.css text diff=css\n", + "Markdown": "# Apply override to all files in the directory\n*.md linguist-detectable\n", + "Mathematica": "# Basic .gitattributes for a Mathematica repo.\n\n# Source files\n# Caution: *.m also matches Matlab files.\n# ============\n*.nb text diff=mathematica\n*.wls text diff=mathematica\n*.wl text diff=mathematica\n*.m text diff=mathematica\n\n# Test files\n# ==========\n*.wlt text diff=mathematica\n*.mt text diff=mathematica\n\n# Binary files\n# ============\n*.mx binary\n", + "Matlab": "# Basic .gitattributes for a MATLAB repo.\n# This template includes Simulink and MuPAD extensions, in addition\n# to the MATLAB extensions.\n\n# Source files\n# ============\n*.m text diff=matlab\n*.mu text diff=matlab\n\n# Caution: *.m also matches Mathematica packages.\n\n# Binary files\n# ============\n*.p binary\n*.mex* binary\n*.fig binary\n*.mat binary\n*.mdl binary\n*.slx binary\n*.mdlp binary\n*.slxp binary\n*.sldd binary\n*.mltbx binary\n*.mlappinstall binary\n*.mlpkginstall binary\n*.mn binary\n", + "MicrosoftShell": "\n# Basic .gitattributes for a Microsoft Shell repo.\n\n# Source files\n# ============\n*.msh text eol=crlf\n*.msh1 text eol=crlf\n*.msh2 text eol=crlf\n*.mshxml text eol=crlf\n*.msh1xml text eol=crlf\n*.msh2xml text eol=crlf\n*.mcf text eol=crlf\n", + "ObjectiveC": "# compare .pbxproj files as binary and always merge as union\n*.pbxproj binary -merge=union\n*.m text diff=objc\n", + "Pascal": "# Lazarus Project Information file (stored in XML; contains project-specific settings)\n*.lpi text\n\n# Lazarus Program file; contains Pascal source of main program\n*.lpr text\n\n# Lazarus Form file; contains configuration information for all objects on a form\n# (stored in a Lazarus-specific format; the actions are described by Pascal source code in a corresponding *.pas file)\n*.lfm text\n\n# Unit with Pascal code (typically for a form stored in a corresponding *.lfm file)\n*.pas text diff=pascal\n\n# Pascal code\n*.p text diff=pascal\n*.pp text diff=pascal\n\n# Lazarus Resource file (this is a generated file; not to be confused with a Windows resource file).\n*.lrs text\n\n# Compiled unit, symbols part.\n*.ppu binary\n\n# (1) Compiled unit, code part.\n# (2) Compiled code from other compilers (e.g. gcc)\n*.o binary\n\n# Object resource, automatically generated from {$R} directive.\n*.or text\n\n# (1) Compiled unit, code part for smartlinking (on some platforms)\n# (2) Compiled code from other compilers (e.g. gcc) linked into a static library\n*.a binary\n\n# Lazarus package information file. (stored in XML; contains package-specific settings)\n*.lpk text\n\n# Include file\n*.inc text\n\n# Lazarus Project Session file. See Project Options -> Save session information in\n*.lps text\n\n# Lazarus Resourcestring table created when saving a lfm file and i18n is enabled. It contains the TTranslateString properties of the lfm.\n*.lrt text\n\n# Resourcestring table created by the compiler for every unit with a resourcestring section.\n*.rst text\n\n# Resourcestring table in JSON format created by FPC 2.7.1 for units with resourcestring section.\n*.rsj text\n\n# Compilation session for a project\n*.compiled text\n\n# Resource file\n*.res text\n\n# Lazarus resource form file\n*.rc text\n\n# Icon file\n*.ico binary\n", + "Perl": "# Basic .gitattributes for a perl repo.\n\n# Source files\n# ============\n*.pl text diff=perl\n*.pm text diff=perl\n", + "PHP": "# Auto detect text files and perform LF normalization\n* text=auto\n\n# PHP files\n*.php text eol=lf diff=php\n*.phpt text eol=lf diff=php\n*.phtml text eol=lf diff=html\n*.twig text eol=lf\n*.phar binary\n\n# Configuration\nphpcs.xml text eol=lf\nphpunit.xml text eol=lf\nphpstan.neon text eol=lf\npsalm.xml text eol=lf\n", + "PowerShell": "# Basic .gitattributes for a PowerShell repo.\n\n# Source files\n# ============\n*.ps1 text eol=crlf\n*.ps1x text eol=crlf\n*.psm1 text eol=crlf\n*.psd1 text eol=crlf\n*.ps1xml text eol=crlf\n*.pssc text eol=crlf\n*.psrc text eol=crlf\n*.cdxml text eol=crlf\n", + "Python": "# Basic .gitattributes for a python repo.\n\n# Source files\n# ============\n*.pxd text diff=python\n*.py text diff=python\n*.py3 text diff=python\n*.pyw text diff=python\n*.pyx text diff=python\n*.pyz text diff=python\n*.pyi text diff=python\n\n# Binary files\n# ============\n*.db binary\n*.p binary\n*.pkl binary\n*.pickle binary\n*.pyc binary export-ignore\n*.pyo binary export-ignore\n*.pyd binary\n\n# Jupyter notebook\n*.ipynb text eol=lf\n\n# Note: .db, .p, and .pkl files are associated\n# with the python modules ``pickle``, ``dbm.*``,\n# ``shelve``, ``marshal``, ``anydbm``, & ``bsddb``\n# (among others).\n", + "R": "# Basic .gitattributes for a R repo.\n\n# Source files\n# ============\n*.Rdata binary\n*.RData binary\n*.rda binary\n*.rdb binary\n*.rds binary\n*.Rd text\n*.Rdx binary\n*.Rmd\t text\n*.R \t text\n*.Rproj text\n*.[Rr]md linguist-detectable\n", + "Rails": "# These settings are for Ruby On Rails project\n#\n#\n# Define a dummy ours merge strategy with:\n#\n# $ git config --global merge.ours.driver true\nschema.rb merge=ours diff=ruby\n", + "Rust": "# Auto detect text files and perform normalization\n* text=auto\n\n*.rs text diff=rust\n*.toml text diff=toml\nCargo.lock text\n", + "Servoy": "# Auto detect text files and perform LF normalization\n* text=auto\n\n*.frm -text\n*.val -text\n*.tbl -text\n*.rel -text\n*.obj -text\n*.dbi -text\n*.sec -text\n*.css text diff=css\n*.js eol=lf\n*.mjs eol=lf\n*.cjs eol=lf\n", + "Swift": "# Swift gitattributes\n*.pbxproj merge=union\n*.swift text diff=swift\n", + "TinaCMS": "# https://tina.io/\n.tina/__generated__/ linguist-generated\n", + "Unity": "# Define macros (only works in top-level gitattributes files)\n[attr]lfs filter=lfs diff=lfs merge=lfs -text\n[attr]unity-json eol=lf linguist-language=json\n[attr]unity-yaml merge=unityyamlmerge eol=lf linguist-language=yaml\n\n# Optionally collapse Unity YAML files on GitHub diffs\n# [attr]unity-yaml merge=unityyamlmerge text linguist-language=yaml linguist-generated\n\n# Unity source files\n*.cginc text\n*.compute text linguist-language=hlsl\n*.cs text diff=csharp\n*.hlsl text linguist-language=hlsl\n*.raytrace text linguist-language=hlsl\n*.shader text\n\n# Unity JSON files\n*.asmdef unity-json\n*.asmref unity-json\n*.index unity-json\n*.inputactions unity-json\n*.shadergraph unity-json\n*.shadersubgraph unity-json\n\n# Unity UI Toolkit files\n*.tss text diff=css linguist-language=css\n*.uss text diff=css linguist-language=css\n*.uxml text linguist-language=xml linguist-detectable\n\n# Unity YAML files\n*.anim unity-yaml\n*.asset unity-yaml\n*.brush unity-yaml\n*.controller unity-yaml\n*.flare unity-yaml\n*.fontsettings unity-yaml\n*.giparams unity-yaml\n*.guiskin unity-yaml\n*.lighting unity-yaml\n*.mask unity-yaml\n*.mat unity-yaml\n*.meta unity-yaml\n*.mixer unity-yaml\n*.overrideController unity-yaml\n*.playable unity-yaml\n*.prefab unity-yaml\n*.preset unity-yaml\n*.renderTexture unity-yaml\n*.scenetemplate unity-yaml\n*.shadervariants unity-yaml\n*.signal unity-yaml\n*.spriteatlas unity-yaml\n*.spriteatlasv2 unity-yaml\n*.terrainlayer unity-yaml\n*.unity unity-yaml\n\n# \"physic\" for 3D but \"physics\" for 2D\n*.physicMaterial unity-yaml\n*.physicsMaterial2D unity-yaml\n\n# Exclude from GitHub stats and diffs: third-party plugins, packages lock file\nAssets/Plugins/** linguist-generated\nPackages/packages-lock.json linguist-generated\n\n# Unity LFS\n*.cubemap lfs\n*.unitypackage lfs\n\n# 3D models\n*.3dm lfs\n*.3ds lfs\n*.blend lfs\n*.blend1 lfs\n*.c4d lfs\n*.collada lfs\n*.dae lfs\n*.dxf lfs\n*.FBX lfs\n*.fbx lfs\n*.jas lfs\n*.lws lfs\n*.lxo lfs\n*.ma lfs\n*.max lfs\n*.mb lfs\n*.obj lfs\n*.ply lfs\n*.skp lfs\n*.stl lfs\n*.ztl lfs\n\n# Audio\n*.aif lfs\n*.aiff lfs\n*.it lfs\n*.mod lfs\n*.mp3 lfs\n*.ogg lfs\n*.s3m lfs\n*.wav lfs\n*.xm lfs\n\n# Video\n*.asf lfs\n*.avi lfs\n*.flv lfs\n*.mov lfs\n*.mp4 lfs\n*.mpeg lfs\n*.mpg lfs\n*.ogv lfs\n*.wmv lfs\n\n# Images\n*.bmp lfs\n*.exr lfs\n*.gif lfs\n*.hdr lfs\n*.iff lfs\n*.jpeg lfs\n*.jpg lfs\n*.pict lfs\n*.png lfs\n*.psd lfs\n*.tga lfs\n*.tif lfs\n*.tiff lfs\n*.webp lfs\n\n# Compressed Archive\n*.7z lfs\n*.bz2 lfs\n*.gz lfs\n*.rar lfs\n*.tar lfs\n*.zip lfs\n\n# Compiled Dynamic Library\n*.dll lfs\n*.pdb lfs\n*.so lfs\n\n# Fonts\n*.otf lfs\n*.ttf lfs\n\n# Executable/Installer\n*.apk lfs\n*.exe lfs\n\n# Documents\n*.pdf lfs\n\n# ETC\n*.a lfs\n*.reason lfs\n*.rns lfs\n\n# Spine export file for Unity\n*.skel.bytes lfs\n\n# Exceptions for .asset files such as lightning pre-baking\nLightingData.asset binary\n", + "Vim": "# Basic .gitattributes for a Vim repo.\n# Vim on Linux works with LF only, Vim on Windows works with both LF and CRLF\n\n# Source files\n# ============\n*.vim text eol=lf\n.vimrc text eol=lf\n.gvimrc text eol=lf\n", + "Web": "## GITATTRIBUTES FOR WEB PROJECTS\n#\n# These settings are for any web project.\n#\n# Details per file setting:\n# text These files should be normalized (i.e. convert CRLF to LF).\n# binary These files are binary and should be left untouched.\n#\n# Note that binary is a macro for -text -diff.\n######################################################################\n\n# Auto detect\n## Handle line endings automatically for files detected as\n## text and leave all files detected as binary untouched.\n## This will handle all files NOT defined below.\n* text=auto\n\n# Source code\n*.bash text eol=lf\n*.bat text eol=crlf\n*.cmd text eol=crlf\n*.coffee text\n*.css text diff=css\n*.htm text diff=html\n*.html text diff=html\n*.inc text\n*.ini text\n*.js text\n*.mjs text\n*.cjs text\n*.json text\n*.jsx text\n*.less text\n*.ls text\n*.map text -diff\n*.od text\n*.onlydata text\n*.php text diff=php\n*.pl text\n*.ps1 text eol=crlf\n*.py text diff=python\n*.rb text diff=ruby\n*.sass text\n*.scm text\n*.scss text diff=css\n*.sh text eol=lf\n.husky/* text eol=lf\n*.sql text\n*.styl text\n*.tag text\n*.ts text\n*.tsx text\n*.xml text\n*.xhtml text diff=html\n\n# Docker\nDockerfile text\n\n# Documentation\n*.ipynb text eol=lf\n*.markdown text diff=markdown\n*.md text diff=markdown\n*.mdwn text diff=markdown\n*.mdown text diff=markdown\n*.mkd text diff=markdown\n*.mkdn text diff=markdown\n*.mdtxt text\n*.mdtext text\n*.txt text\nAUTHORS text\nCHANGELOG text\nCHANGES text\nCONTRIBUTING text\nCOPYING text\ncopyright text\n*COPYRIGHT* text\nINSTALL text\nlicense text\nLICENSE text\nNEWS text\nreadme text\n*README* text\nTODO text\n\n# Templates\n*.dot text\n*.ejs text\n*.erb text\n*.haml text\n*.handlebars text\n*.hbs text\n*.hbt text\n*.jade text\n*.latte text\n*.mustache text\n*.njk text\n*.phtml text\n*.svelte text\n*.tmpl text\n*.tpl text\n*.twig text\n*.vue text\n\n# Configs\n*.cnf text\n*.conf text\n*.config text\n.editorconfig text\n*.env text\n.gitattributes text\n.gitconfig text\n.htaccess text\n*.lock text -diff\npackage.json text eol=lf\npackage-lock.json text eol=lf -diff\npnpm-lock.yaml text eol=lf -diff\n.prettierrc text\nyarn.lock text -diff\n*.toml text\n*.yaml text\n*.yml text\nbrowserslist text\nMakefile text\nmakefile text\n# Fixes syntax highlighting on GitHub to allow comments\ntsconfig.json linguist-language=JSON-with-Comments\n\n# Heroku\nProcfile text\n\n# Graphics\n*.ai binary\n*.bmp binary\n*.eps binary\n*.gif binary\n*.gifv binary\n*.ico binary\n*.jng binary\n*.jp2 binary\n*.jpg binary\n*.jpeg binary\n*.jpx binary\n*.jxr binary\n*.pdf binary\n*.png binary\n*.psb binary\n*.psd binary\n# SVG treated as an asset (binary) by default.\n*.svg text\n# If you want to treat it as binary,\n# use the following line instead.\n# *.svg binary\n*.svgz binary\n*.tif binary\n*.tiff binary\n*.wbmp binary\n*.webp binary\n\n# Audio\n*.kar binary\n*.m4a binary\n*.mid binary\n*.midi binary\n*.mp3 binary\n*.ogg binary\n*.ra binary\n\n# Video\n*.3gpp binary\n*.3gp binary\n*.as binary\n*.asf binary\n*.asx binary\n*.avi binary\n*.fla binary\n*.flv binary\n*.m4v binary\n*.mng binary\n*.mov binary\n*.mp4 binary\n*.mpeg binary\n*.mpg binary\n*.ogv binary\n*.swc binary\n*.swf binary\n*.webm binary\n\n# Archives\n*.7z binary\n*.gz binary\n*.jar binary\n*.rar binary\n*.tar binary\n*.zip binary\n\n# Fonts\n*.ttf binary\n*.eot binary\n*.otf binary\n*.woff binary\n*.woff2 binary\n\n# Executables\n*.exe binary\n*.pyc binary\n# Prevents massive diffs caused by vendored, minified files\n**/.yarn/releases/** binary\n**/.yarn/plugins/** binary\n\n# RC files (like .babelrc or .eslintrc)\n*.*rc text\n\n# Ignore files (like .npmignore or .gitignore)\n*.*ignore text\n\n# Prevents massive diffs from built files\ndist/** binary\n" + } +} diff --git a/src/tools/gitignore-generator/git-templates.test.ts b/src/tools/gitignore-generator/git-templates.test.ts new file mode 100644 index 00000000..ed23b203 --- /dev/null +++ b/src/tools/gitignore-generator/git-templates.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, it, vi } from 'vitest'; +import { type GitTemplatesSnapshot, type GitTemplatesSource, loadTemplate, loadTemplateNames } from './git-templates'; + +const snapshot: GitTemplatesSnapshot = { + repository: 'github/gitignore', + ref: 'main', + commit: 'abc123', + date: '2026-10-02T20:59:38Z', + templates: { Node: 'node_modules/\n', 'Global/macOS': '.DS_Store\n' }, +}; + +function makeSource() { + const loadSnapshot = vi.fn<() => Promise>(async () => snapshot); + const source: GitTemplatesSource = { + repository: 'github/gitignore', + ref: 'main', + extension: '.gitignore', + loadSnapshot, + }; + return { source, loadSnapshot }; +} + +type Fetch = (url: string) => Promise; + +const okJson = (body: unknown) => async () => new Response(JSON.stringify(body)); +const failing = async (): Promise => { + throw new TypeError('Failed to fetch'); +}; + +describe('git-templates', () => { + describe('loadTemplateNames', () => { + it('lists live templates without loading the snapshot when online', async () => { + const { source, loadSnapshot } = makeSource(); + const fetchFn = vi.fn( + okJson({ tree: [{ path: 'Node.gitignore' }, { path: 'README.md' }, { path: 'Global/Vim.gitignore' }] }), + ); + + expect(await loadTemplateNames(source, { offline: false, fetchFn })).to.deep.equal({ + names: ['Node', 'Global/Vim'], + }); + expect(fetchFn).toHaveBeenCalledWith( + 'https://api.github.com/repos/github/gitignore/git/trees/main?recursive=true', + ); + expect(loadSnapshot).not.toHaveBeenCalled(); + }); + + it('uses the snapshot, without any request, when offline', async () => { + const { source } = makeSource(); + const fetchFn = vi.fn(failing); + + expect(await loadTemplateNames(source, { offline: true, fetchFn })).to.deep.equal({ + names: ['Node', 'Global/macOS'], + snapshot, + }); + expect(fetchFn).not.toHaveBeenCalled(); + }); + + it('falls back to the snapshot when the request fails or is rejected', async () => { + const { source } = makeSource(); + + expect((await loadTemplateNames(source, { offline: false, fetchFn: failing })).snapshot).to.equal(snapshot); + const rateLimited = async () => new Response('{"message":"API rate limit exceeded"}', { status: 403 }); + expect((await loadTemplateNames(source, { offline: false, fetchFn: rateLimited })).snapshot).to.equal(snapshot); + }); + }); + + describe('loadTemplate', () => { + it('fetches the live template when online', async () => { + const { source } = makeSource(); + const fetchFn = vi.fn(async () => new Response('live\n')); + + expect(await loadTemplate(source, 'Node', { offline: false, fetchFn })).to.deep.equal({ + content: 'live\n', + url: 'https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore', + }); + }); + + it('reads the snapshot, pinned to its commit, when offline or when the fetch fails', async () => { + const { source } = makeSource(); + const expected = { + content: '.DS_Store\n', + url: 'https://raw.githubusercontent.com/github/gitignore/abc123/Global/macOS.gitignore', + snapshot, + }; + const fetchFn = vi.fn(failing); + + expect(await loadTemplate(source, 'Global/macOS', { offline: true, fetchFn })).to.deep.equal(expected); + expect(fetchFn).not.toHaveBeenCalled(); + expect(await loadTemplate(source, 'Global/macOS', { offline: false, fetchFn })).to.deep.equal(expected); + const notFound = async () => new Response('404: Not Found', { status: 404 }); + expect(await loadTemplate(source, 'Global/macOS', { offline: false, fetchFn: notFound })).to.deep.equal(expected); + }); + + it('rethrows the live error when the snapshot does not have the template either', async () => { + const { source } = makeSource(); + + await expect(loadTemplate(source, 'Unknown', { offline: false, fetchFn: failing })).rejects.toThrow( + 'Failed to fetch', + ); + await expect(loadTemplate(source, 'Unknown', { offline: true })).rejects.toThrow('Unknown template: Unknown'); + }); + }); +}); diff --git a/src/tools/gitignore-generator/git-templates.ts b/src/tools/gitignore-generator/git-templates.ts new file mode 100644 index 00000000..d105c837 --- /dev/null +++ b/src/tools/gitignore-generator/git-templates.ts @@ -0,0 +1,102 @@ +// Template loading shared by the gitignore and gitattributes generators: live from GitHub, with a bundled snapshot +// (generated by scripts/update-git-templates.mjs) used in offline mode or whenever GitHub can't be reached. + +export interface GitTemplatesSnapshot { + repository: string; + ref: string; + commit: string; + date: string; + templates: Record; +} + +export interface GitTemplatesSource { + /** GitHub `owner/repo` */ + repository: string; + /** Branch the live templates are read from */ + ref: string; + /** Template file extension, e.g. `.gitignore` */ + extension: string; + /** Lazily loads the bundled snapshot, so it stays out of the bundle until needed */ + loadSnapshot: () => Promise; +} + +type Fetch = (url: string) => Promise; + +export function liveTemplateUrl({ repository, ref, extension }: GitTemplatesSource, name: string) { + return `https://raw.githubusercontent.com/${repository}/${ref}/${name}${extension}`; +} + +async function fetchOk(fetchFn: Fetch, url: string) { + const response = await fetchFn(url); + if (!response.ok) { + throw new Error(`${url}: ${response.status} ${response.statusText}`); + } + return response; +} + +/** Template names (paths without extension) from a GitHub recursive tree listing */ +export function templateNamesFromTree(tree: { path: string }[], extension: string) { + return tree + .filter(({ path }) => path.endsWith(extension)) + .map(({ path }) => path.slice(0, -extension.length)) + .filter(Boolean); +} + +/** Snapshot commit date as YYYY-MM-DD, for display */ +export function snapshotDay(snapshot: GitTemplatesSnapshot) { + return snapshot.date.slice(0, 10); +} + +/** + * Lists the available templates: live from the GitHub API, or from the snapshot when `offline` or when the live + * listing fails. `snapshot` is set when the snapshot was used. + */ +export async function loadTemplateNames( + source: GitTemplatesSource, + { offline, fetchFn = fetch }: { offline: boolean; fetchFn?: Fetch }, +): Promise<{ names: string[]; snapshot?: GitTemplatesSnapshot }> { + if (!offline) { + try { + const response = await fetchOk( + fetchFn, + `https://api.github.com/repos/${source.repository}/git/trees/${source.ref}?recursive=true`, + ); + const { tree } = await response.json(); + const names = templateNamesFromTree(tree, source.extension); + if (names.length) { + return { names }; + } + } catch {} + } + const snapshot = await source.loadSnapshot(); + return { names: Object.keys(snapshot.templates), snapshot }; +} + +/** + * Fetches one template live, or reads it from the snapshot when `offline` or when the live fetch fails. + * `url` is where the content comes from (pinned to the snapshot commit when the snapshot was used). + */ +export async function loadTemplate( + source: GitTemplatesSource, + name: string, + { offline, fetchFn = fetch }: { offline: boolean; fetchFn?: Fetch }, +): Promise<{ content: string; url: string; snapshot?: GitTemplatesSnapshot }> { + let liveError: unknown; + if (!offline) { + const url = liveTemplateUrl(source, name); + try { + return { content: await (await fetchOk(fetchFn, url)).text(), url }; + } catch (e) { + liveError = e; + } + } + const snapshot = await source.loadSnapshot(); + if (!Object.hasOwn(snapshot.templates, name)) { + throw liveError ?? new Error(`Unknown template: ${name}`); + } + return { + content: snapshot.templates[name], + url: `https://raw.githubusercontent.com/${source.repository}/${snapshot.commit}/${name}${source.extension}`, + snapshot, + }; +} diff --git a/src/tools/gitignore-generator/gitignore-generator.vue b/src/tools/gitignore-generator/gitignore-generator.vue index 966ab79d..d8765e7d 100644 --- a/src/tools/gitignore-generator/gitignore-generator.vue +++ b/src/tools/gitignore-generator/gitignore-generator.vue @@ -1,5 +1,13 @@