К основному содержанию
скилл GitHub Copilot официальный · GitHub

resx-source-generator-migration — скилл для GitHub Copilot: миграция

Скилл переводит проект с файлов .Designer.cs, созданных для .resx, на source generator. Пригодится, когда нужно заменить старую генерацию типизированных ресурсов.

Установить в GitHub Copilot · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add github/awesome-copilot --skill resx-source-generator-migration
Открыть на GitHub

Что делает resx-source-generator-migration

Скилл проверяет настройки управления пакетами и NuGet-источники, затем добавляет Microsoft.CodeAnalysis.ResxSourceGenerator по принятому в репозитории правилу версионирования. Он находит связанные с .resx элементы MSBuild и проверяет файлы-кандидаты: сгенерированный аксессор ресурсов не должен оказаться WinForms-дизайнером с InitializeComponent.

Перед миграцией скилл проверяет, что ресурсы содержат строки, а код не использует несовместимые с static partial классом создание экземпляров, наследование или интерфейсы. Он удаляет подтверждённые файлы .Designer.cs, убирает старые метаданные генератора и сохраняет обработку ресурсов форм через GenerateSource=false. Если пакет нельзя получить из настроенных источников, скилл должен спросить разрешение на изменение конфигурации. Ставьте его для миграции строковых ресурсов; для файлов с изображениями и другими нестроковыми значениями оставьте прежнюю генерацию.

Какие задачи решает

  • перевести типизированные .resx ресурсы на source generator
  • найти и удалить подтверждённые файлы .Designer.cs
  • проверить использование класса ресурсов перед переходом на static partial
  • сохранить ресурсы WinForms без генерации аксессора

Примеры запросов агенту

  • Переведи проект `src/App/App.csproj` на source generator для строковых `.resx` ресурсов.
  • Проверь, какие `.Designer.cs` связаны с `.resx` и безопасны для удаления.
  • Найди несовместимые обращения к классу ресурсов перед миграцией.

Как установить resx-source-generator-migration

1Через Skills CLI (Vercel)

npx skills add github/awesome-copilot --skill resx-source-generator-migration

2GitHub CLI

gh skill install github/awesome-copilot resx-source-generator-migration

3Вручную: положить файлы

.github/skills/resx-source-generator-migration/SKILL.md

Из того же набора554

Весь набор →
git-commit официальный github Скилл разбирает изменения Git, выбирает связанные файлы и создаёт коммит в формате Conventional Commits. Пригодится, когда нужно закоммитить одну или несколько логических частей изменений. GitHub Copilot 47 165установок excalidraw-diagram-generator официальный github Скилл превращает описание на обычном языке в диаграмму Excalidraw. Подойдёт, когда нужно показать процесс, связи между объектами или устройство системы. GitHub Copilot 31 639установок multi-stage-dockerfile официальный github Скилл помогает создавать многоэтапные Dockerfile для разных языков и фреймворков. Пригодится, когда важны размер и состав runtime-образа. GitHub Copilot 29 688установок documentation-writer официальный github Скилл для создания технической документации по фреймворку Diátaxis: туториалы, гайды, справки и объяснения. Предлагает структуру перед написанием. GitHub Copilot 27 757установок prd официальный github Собирает из идеи структурированный PRD с пользовательскими историями, техническими требованиями и рисками. Подходит для планирования новых функций, в том числе с AI. GitHub Copilot 24 035установок refactor официальный github Скилл помогает менять структуру кода без изменения внешнего поведения. Подойдёт для постепенной уборки сложных функций, дублирования и кодовых запахов. GitHub Copilot 22 321установок java-springboot официальный github Задаёт практики разработки Spring Boot-приложений: от структуры проекта до тестов и безопасности. Пригодится, когда Copilot пишет или проверяет Java-код. GitHub Copilot 21 272установок create-readme официальный github Скилл изучает проект и создаёт структурированный README.md. Подойдёт, когда документацию нужно собрать по коду и файлам проекта. GitHub Copilot 19 081установок

Похожие

swiftpm-macos официальный OpenAI Собирает, запускает и тестирует macOS-пакеты SwiftPM. Пригодится, когда главным входом служит Package.swift, а проекта Xcode нет. CX Codex GP ChatGPT 58установок swiftui-patterns официальный OpenAI Помогает проектировать десктопные интерфейсы на SwiftUI для macOS с правильной структурой окон, меню, тулбаров и файлов. CX Codex GP ChatGPT 57установок view-refactor официальный OpenAI Скилл помогает разложить macOS SwiftUI views и scenes по устойчивой структуре. Нужен при разделении больших view и сужении AppKit-границ. CX Codex GP ChatGPT 52установок canva-translate-design официальный Canva Pty Ltd. Переводит весь текст в дизайне Canva и создаёт отдельную копию. Нужен для локализации макета без правок каждого текстового блока вручную. CX Codex GP ChatGPT 25установок migrate-to-shoehorn Matt Pocock Переводит type assertions с as в тестах на функции из @total-typescript/shoehorn. Нужен для частичных объектов и намеренно неверных данных в проверках. Claude Code 475 388установок write-swift emilkowalski Скилл помогает писать, проверять и переносить код на Swift с учётом модели языка. Подойдёт, когда нужно разобраться с конкурентностью, ошибкой или циклом удержания объектов. Claude Code CX Codex Cursor +1 117 500установок megacave JuliusBrussee Переводит ответы ассистента на классический китайский язык (вэньянь) для экономии места на экране. Активируется командами /megacave или /caveman wenyan. Claude Code CX Codex Cursor +1 24 400установок find-docs upstash Тянет актуальную документацию, справочники API и примеры кода для любой библиотеки через Context7 CLI. Пригодится, когда агент отвечает по устаревшим данным обучения. Claude Code CX Codex Cursor +1 9 400установок

Вопросы о resx-source-generator-migration

Как установить resx-source-generator-migration в GitHub Copilot?

Выполните npx skills add github/awesome-copilot --skill resx-source-generator-migration. Можно также установить командой gh skill install github/awesome-copilot resx-source-generator-migration.

Что делает resx-source-generator-migration?

Он переводит типизированные строковые .resx ресурсы с проверенных файлов .Designer.cs на Microsoft.CodeAnalysis.ResxSourceGenerator и обновляет связанные настройки MSBuild.

Какие `.resx` ресурсы нельзя мигрировать этим скиллом?

Файлы с изображениями, иконками, массивами байтов, сериализованными объектами или другими нестроковыми значениями. Для таких ресурсов нужно сохранить прежнюю генерацию; для ресурсов форм можно отключить генерацию через GenerateSource=false.

Исходный текст

SKILL.md · MIT
---
name: resx-source-generator-migration
description: 'Migrates a project that uses checked-in .designer.cs files behind .resx to using a source-generator instead'
disable-model-invocation: true
---

Your goal is to migrate the project to use a source-generator for .resx files instead of checked-in .designer.cs files.

## User Input

Amend the instructions below with the following user input.
The user input is likely to be an absolute or repo-relative path to an msbuild project file or a directory containing an msbuild project to be migrated.

```text
$ARGUMENTS
```

## Migration

Complete each of the following sub-sections.

### Opt into the source generator

Inspect the target's package-management setup and configured NuGet sources before adding the package:

1. If the repository centrally manages package versions and already has a `PackageVersion` for `Microsoft.CodeAnalysis.ResxSourceGenerator`, add this versionless reference to an `ItemGroup` in the project file:

```xml
<PackageReference Include="Microsoft.CodeAnalysis.ResxSourceGenerator" PrivateAssets="all" />
```

2. If no central version exists, select a package version compatible with the target SDK/compiler and follow the repository's established version-management pattern. Specify the version on the `PackageReference` or add the corresponding central `PackageVersion`.
3. Verify that the configured NuGet sources can resolve the selected package. If they cannot, ask the user before changing feed configuration.

### Remove traces of .resx code-behind files

Search for any msbuild items related to resx files.
They typically come in pairs, as shown below:

```xml
<ItemGroup>
  <Compile Update="Strings.Designer.cs">
    <DesignTime>True</DesignTime>
    <AutoGen>True</AutoGen>
    <DependentUpon>Strings.resx</DependentUpon>
  </Compile>
</ItemGroup>

<ItemGroup>
  <EmbeddedResource Update="Strings.resx">
    <Generator>ResXFileCodeGenerator</Generator>
    <LastGenOutput>Strings.Designer.cs</LastGenOutput>
  </EmbeddedResource>
</ItemGroup>
```

Note that you might also find `<Generator>PublicResXFileCodeGenerator</Generator>` (or `<CustomTool>` instead of `<Generator>`) as .resx item metadata.

For each strongly typed .resx file being migrated, identify its generated designer file using all of these signals:

- `LastGenOutput` metadata on the `EmbeddedResource` item;
- a `Compile` item whose `DependentUpon` metadata names the .resx file; and
- a matching `*.Designer.cs` file on disk, even when the SDK includes it implicitly and no `Compile` item exists.

Before deleting a candidate, inspect its contents and confirm it is a generated resource accessor, such as a class containing `ResourceManager`, `Culture`, and properties that retrieve resource values. A matching filename alone is not sufficient. Do not delete WinForms or control designer files that contain UI initialization such as `InitializeComponent`; these commonly sit beside a same-named .resx file, and their `DependentUpon` metadata points to the form or control source file rather than the .resx file.

Also confirm that every resource exposed by the designer is a string and that the .resx file contains no images, icons, byte arrays, serialized objects, or other non-string values. This source generator emits string accessors backed by `ResourceManager.GetString`; it is not a compatible replacement for non-string resource properties. If any non-string resource exists, do not delete the designer or migrate that resource file. Keep its existing generation approach, or set `<GenerateSource>false</GenerateSource>` if the package would otherwise process it.

Before deletion, search the solution for every use and declaration of the accessor type. `ResXFileCodeGenerator` emits a non-static class, while this source generator emits a `static partial` class. Identify object construction, instance access, inheritance, use as a generic type argument (including `IStringLocalizer<T>`), and existing partial declarations with instance members, base types, or interfaces. Refactor each incompatible use to the static generated API and make every partial declaration compatible before migrating. If that is not appropriate, retain the existing designer and set `<GenerateSource>false</GenerateSource>` for that resource file.

For each associated designer file:

1. Delete the `*.Designer.cs` file from disk.
2. Remove its explicit MSBuild item from the project when one exists.

### Update EmbeddedResource items

Classify every .resx file before removing metadata. Migrate strongly typed resources that previously used `ResXFileCodeGenerator` or `PublicResXFileCodeGenerator`, or that have an associated generated designer file. Framework and designer resources such as WinForms form resources generally must not generate an accessor; preserve them by adding this metadata to their `EmbeddedResource` item:

```xml
<GenerateSource>false</GenerateSource>
```

The source generator otherwise generates accessors for non-culture .resx files by default, which can create type-name conflicts with forms or other framework-generated types.

Process each strongly typed `EmbeddedResource` being migrated as follows:

1. Remove the `LastGenOutput` metadata.
2. If either `Generator` or `CustomTool` metadata is set to `PublicResXFileCodeGenerator`, add `<Public>true</Public>` metadata to the item.
3. Remove the `Generator` (or `CustomTool`) metadata.
4. If the `EmbeddedResource` item has no remaining metadata after these removals, remove it only after verifying that the SDK implicitly includes that .resx file and that default embedded-resource items are enabled. Otherwise retain the explicit `Include` or equivalent item so the resource remains in the built assembly.
5. If you see `CustomToolNamespace` metadata, see the special section on that topic.

## `CustomToolNamespace` metadata special handling

When an `EmbeddedResource` item has `CustomToolNamespace` metadata, special handling is required.

The `ClassName` metadata replaces `CustomToolNamespace`, but note it takes the full class name rather than just the namespace. For example, if you had:

```xml
<EmbeddedResource Update="Strings.resx">
  <Generator>ResXFileCodeGenerator</Generator>
  <LastGenOutput>Strings.Designer.cs</LastGenOutput>
  <CustomToolNamespace>My.Namespace</CustomToolNamespace>
</EmbeddedResource>
```

It would become:

```xml
<EmbeddedResource Update="Strings.resx">
  <ClassName>My.Namespace.Strings</ClassName>
</EmbeddedResource>
```

**Before starting the migration, present these options to the user:**

1. **PREFERRED:** Drop the `CustomToolNamespace` metadata and accept the default generated namespace and class name. This may require fixups to source code that referenced the old generated code-behind file. Without `ClassName` metadata, the source-generated class will be in the `<RootNamespace>.<RelativeFolderPath>` namespace and named after the resx filename. Consider adding a using alias to affected files:
   ```csharp
   using SomeResourceFile = FullNamespace.TypeName;
   ```

2. Rewrite it as `ClassName` metadata, including the full namespace and class name (for example, `MyNamespace.MyResources`). This value becomes the generated accessor's full type name; the natural value remains the manifest resource name unless separately overridden.

### Resolving namespace/type conflicts

When the compiler emits an error about a type and namespace sharing the same name (where the identifier matches a directory name containing a .resx file):
- Move the .resx file outside that folder to remove the conflicting namespace declaration, OR
- Fully qualify the type reference to resolve the build break.

## Debugging tips

- Build with `/p:EmitCompilerGeneratedFiles=true` to write source-generated files to disk for inspection.
- You may also need `/p:CompilerGeneratedFilesOutputPath=<path>` to avoid Windows path length issues.

## Validation

Build the migrated project.

After the build succeeds, validate each resource family according to how it is consumed:

1. For each migrated neutral string resource, use the repository's existing tests or an available .NET test/console host to access at least one generated property and verify it returns the expected string. Reflection from PowerShell is an optional approach when `pwsh` is available, not a requirement.
2. For culture-specific satellite resources, switch to a representative culture and verify the neutral accessor returns the expected localized string. Do not expect a separate generated accessor for each satellite file.
3. For framework, designer, non-string, or other resources marked `GenerateSource=false`, exercise their actual consumer, such as instantiating the WinForms form/control or loading an image/object through the retained resource API.
4. Confirm every .resx file is still embedded in the expected main or satellite assembly.

© github · MIT · github/awesome-copilot

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой