Skip to content

Feature: Custom code gen class name #694

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from

Conversation

mdikcinar
Copy link

@mdikcinar mdikcinar commented Jun 21, 2024

Hi, this is needed when we import localizations from multiple packages.
#449

Summary by CodeRabbit

  • New Features

    • Added a CLI option --class-name (-c) to set a custom name for the generated keys class.
    • Generated output now uses the chosen class name; defaults to LocaleKeys when not provided.
  • Bug Fixes / Validation

    • Added runtime validation for the provided class name; invalid names produce an error and abort generation.

@mdikcinar
Copy link
Author

@aissat Hi, could you please review this PR when you have a chance?
It has been open for quite a while, and we’ve been working off a fork because of it.

@aissat aissat requested a review from Copilot August 12, 2025 07:43
Copilot

This comment was marked as outdated.

Copy link

coderabbitai bot commented Aug 18, 2025

Walkthrough

Adds a new CLI option (--class-name / -c) wired into GenerateOptions.className, validates it at runtime for 'keys' format, and uses it when generating the keys file so the produced header is abstract class <className> { ... } (defaults to LocaleKeys). Also minor formatting and toString/ArgParser updates.

Changes

Cohort / File(s) Summary
CLI option, options struct, and parser
bin/generate.dart
- Add GenerateOptions.className: String? and expose it via CLI flag --class-name / -c (default LocaleKeys).
- Update ArgParser and GenerateOptions.toString() to include className.
Generation flow and writer
bin/generate.dart (same file, generator functions)
- Compute effective className (trim, fallback to LocaleKeys) and validate it when format == 'keys'; print error and abort on invalid identifier.
- Thread className into generation call paths and pass to _writeKeys.
- _writeKeys now accepts className and emits abstract class $className { ... } instead of fixed LocaleKeys.
- Minor formatting cleanup (remove extraneous blank line near output path assignment).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI as generate.dart CLI
    participant Gen as Generator
    participant Writer as _writeKeys

    User->>CLI: run (optionally --class-name MyKeys)
    CLI->>Gen: create GenerateOptions(className: "MyKeys"|null)
    Gen->>Gen: compute effective className (trim/fallback), validate if format=='keys'
    Gen->>Writer: _writeKeys(className)
    Writer-->>Gen: writes file with "abstract class <className> { ... }"
    Gen-->>User: output files generated / error on invalid name
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I twitch my ears at flags so fine,
“--class-name” marks the name in line.
No longer bound to LocaleKeys—hip hooray!
I hop, I stamp, new headers on display.
Carrots, classes, tailored and bright 🥕✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mdikcinar mdikcinar requested a review from Copilot August 18, 2025 19:53
Copilot

This comment was marked as outdated.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
bin/generate.dart (4)

84-91: Drop null-assertion in callback and clarify help text

Avoid x! — it’s unnecessary (you already have a fallback later) and brittle. Also, clarify that the option affects the keys format only.

Apply this diff:

   parser.addOption(
     'class-name',
     abbr: 'c',
     defaultsTo: 'LocaleKeys',
-    callback: (String? x) => generateOptions!.className = x!,
-    help: 'Custom class name for generated file',
+    callback: (String? x) => generateOptions!.className = x,
+    help: 'Custom class name for generated keys class (keys format)',
   );

If you’d like, I can also update the README/usage docs to mention the new flag and its scope (keys format only). Want me to open a docs PR?


102-102: Include className in GenerateOptions.toString() for easier debugging

Printing the parsed className helps when troubleshooting CLI invocations.

Outside the selected lines, update toString() like this:

   @override
   String toString() {
-    return 'format: $format sourceDir: $sourceDir sourceFile: $sourceFile outputDir: $outputDir outputFile: $outputFile skipUnnecessaryKeys: $skipUnnecessaryKeys';
+    return 'format: $format '
+        'sourceDir: $sourceDir '
+        'sourceFile: $sourceFile '
+        'outputDir: $outputDir '
+        'outputFile: $outputFile '
+        'skipUnnecessaryKeys: $skipUnnecessaryKeys '
+        'className: $className';
   }

152-158: Validate --class-name to ensure a valid Dart identifier

Guard against invalid class names (e.g., names starting with a digit or containing spaces) to avoid generating uncompilable code. Trim whitespace and validate only when format is keys.

Apply this diff:

-  final className = options.className ?? 'LocaleKeys';
+  final className = (options.className?.trim().isNotEmpty ?? false)
+      ? options.className!.trim()
+      : 'LocaleKeys';
+  if (options.format == 'keys' &&
+      !RegExp(r'^[A-Za-z_$][A-Za-z0-9_$]*$').hasMatch(className)) {
+    stderr.writeln(
+        "Invalid --class-name '$className'. It must be a valid Dart identifier (start with a letter or _; only letters, digits, _ or \$).");
+    return;
+  }

186-198: Fix double space in generated class declaration

Minor formatting nit: there’s a double space between class and $className.

Apply this diff:

-abstract class  $className {
+abstract class $className {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c818108 and 5a71dc2.

📒 Files selected for processing (1)
  • bin/generate.dart (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (1)
bin/generate.dart (1)

170-172: Threading className through to _writeKeys looks good

Passing the resolved class name into the writer is the right place to apply the option.

- Updated the class name callback to allow null values.
- Enhanced the toString method to include className in GenerateOptions.
- Added validation for className to ensure it is a valid Dart identifier.
- Trimmed whitespace from className before use.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
bin/generate.dart (3)

84-91: New --class-name flag looks good; consider trimming input and clarifying help text.

Minor UX polish: trim the provided value early and make the help text explicit about constraints and default.

   parser.addOption(
     'class-name',
     abbr: 'c',
     defaultsTo: 'LocaleKeys',
-    callback: (String? x) => generateOptions!.className = x,
-    help: 'Custom class name for generated keys class (keys format)',
+    callback: (String? x) => generateOptions!.className = x?.trim(),
+    help: 'Custom class name for the generated keys class (used only with --format keys). Must be a valid Dart identifier. Default: LocaleKeys',
   );

158-162: Prefer returning Future for async API surface (avoid async void).

async void swallows errors and can’t be awaited. Using Future<void> improves error propagation and composability. If you take this, also await the call site in handleLangFiles.

-void generateFile(
+Future<void> generateFile(
   List<FileSystemEntity> files,
   Directory outputPath,
   GenerateOptions options,
 ) async {

Outside this hunk, in handleLangFiles(...), update the call:

await generateFile(files, outputPath, options);

And consider changing handleLangFiles signature to Future<void> as well for consistency.


211-211: Dynamic class header emission works; consider a gentle style nudge.

Given this class is meant to be imported, a leading underscore would make it library-private. You might optionally warn if className.startsWith('_'), and/or recommend PascalCase in the help text (already covered above).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5a71dc2 and 882f89f.

📒 Files selected for processing (1)
  • bin/generate.dart (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (4)
bin/generate.dart (4)

102-102: Good addition to GenerateOptions.

Adding className to options is consistent with other fields and keeps it discoverable in one place.


107-114: toString update is fine.

Including className in the debugging output is helpful for tracing CLI usage.


184-186: Threading the className into _writeKeys is correct.

This keeps the generator pure and makes the output deterministic from options.


200-206: _writeKeys signature change is appropriate.

Passing className explicitly improves testability and avoids hidden globals.

Comment on lines +163 to +171
final className = (options.className?.trim().isNotEmpty ?? false)
? options.className!.trim()
: 'LocaleKeys';
if (options.format == 'keys' &&
!RegExp(r'^[A-Za-z_$][A-Za-z0-9_$]*$').hasMatch(className)) {
stderr.writeln(
"Invalid --class-name '$className'. It must be a valid Dart identifier (start with a letter or _; only letters, digits, _ or \$).");
return;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix null-aware chaining bug and tighten Dart identifier validation (disallow '$', check reserved words).

  • options.className?.trim().isNotEmpty is a static error: trim() is null-aware, yielding String?, so .isNotEmpty must also be null-aware.
  • The identifier regex currently allows $, which is not valid in Dart identifiers.
  • Optional: Guard against reserved words to prevent generating uncompilable code.
-  final className = (options.className?.trim().isNotEmpty ?? false)
-      ? options.className!.trim()
-      : 'LocaleKeys';
-  if (options.format == 'keys' &&
-      !RegExp(r'^[A-Za-z_$][A-Za-z0-9_$]*$').hasMatch(className)) {
-    stderr.writeln(
-        "Invalid --class-name '$className'. It must be a valid Dart identifier (start with a letter or _; only letters, digits, _ or \$).");
-    return;
-  }
+  final rawClassName = options.className?.trim();
+  final className =
+      (rawClassName?.isNotEmpty ?? false) ? rawClassName! : 'LocaleKeys';
+  if (options.format == 'keys') {
+    // Valid Dart identifier: letters or _ to start; then letters/digits/_ only. No '$'.
+    final isValidIdentifier =
+        RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$').hasMatch(className);
+    const reservedWords = {
+      'abstract','as','assert','async','await','break','case','catch','class','const',
+      'continue','covariant','default','deferred','do','dynamic','else','enum','export',
+      'extends','extension','external','factory','false','final','finally','for','Function',
+      'get','hide','if','implements','import','in','interface','is','late','library','mixin',
+      'new','null','on','operator','part','required','rethrow','return','set','show','static',
+      'super','switch','sync','this','throw','true','try','typedef','var','void','while','with',
+      'yield'
+    };
+    if (!isValidIdentifier || reservedWords.contains(className)) {
+      stderr.writeln(
+          "Invalid --class-name '$className'. It must be a valid Dart identifier (start with a letter or _, contain only letters, digits, or _), and not be a reserved word.");
+      return;
+    }
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
final className = (options.className?.trim().isNotEmpty ?? false)
? options.className!.trim()
: 'LocaleKeys';
if (options.format == 'keys' &&
!RegExp(r'^[A-Za-z_$][A-Za-z0-9_$]*$').hasMatch(className)) {
stderr.writeln(
"Invalid --class-name '$className'. It must be a valid Dart identifier (start with a letter or _; only letters, digits, _ or \$).");
return;
}
final rawClassName = options.className?.trim();
final className =
(rawClassName?.isNotEmpty ?? false) ? rawClassName! : 'LocaleKeys';
if (options.format == 'keys') {
// Valid Dart identifier: letters or _ to start; then letters/digits/_ only. No '$'.
final isValidIdentifier =
RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$').hasMatch(className);
const reservedWords = {
'abstract','as','assert','async','await','break','case','catch','class','const',
'continue','covariant','default','deferred','do','dynamic','else','enum','export',
'extends','extension','external','factory','false','final','finally','for','Function',
'get','hide','if','implements','import','in','interface','is','late','library','mixin',
'new','null','on','operator','part','required','rethrow','return','set','show','static',
'super','switch','sync','this','throw','true','try','typedef','var','void','while','with',
'yield'
};
if (!isValidIdentifier || reservedWords.contains(className)) {
stderr.writeln(
"Invalid --class-name '$className'. It must be a valid Dart identifier (start with a letter or _, contain only letters, digits, or _), and not be a reserved word.");
return;
}
}
🤖 Prompt for AI Agents
In bin/generate.dart around lines 163 to 171, fix the null-aware chaining and
tighten identifier validation: ensure you call trim() only when className is
non-null and propagate null-safety when checking isNotEmpty (e.g., use
options.className != null && options.className!.trim().isNotEmpty or store
trimmed value in a local non-null variable before checking), change the RegExp
to disallow '$' (use something like r'^[A-Za-z_][A-Za-z0-9_]*$' so identifiers
start with a letter or underscore and contain only letters, digits or
underscores), and add a reserved-word guard (compare the candidate className
against a set of Dart reserved words and reject or alter it) so the tool never
emits an invalid Dart identifier; update the stderr message accordingly.

@mdikcinar mdikcinar requested a review from Copilot August 18, 2025 20:08
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review any files in this pull request.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.
You can also share your feedback on Copilot code review for a chance to win a $100 gift card. Take the survey.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants