Skip to content

feat: allow emojis (gitmoji) in messages #222

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

Closed

Conversation

kohanyirobert
Copy link
Contributor

@kohanyirobert kohanyirobert commented Feb 22, 2025

To allow commit messages like refactor: ♻️ don't use a monorepo and so I use devmoji a tool to automate and ease gitmoji usage.

However the default regex doesn't allow emojis in the message. I'm not sure whether this is an oversight or that the conventional commit "spec" (if it is a spec) says that this not allowed.

If it doesn't disallow this I would wager it can be allowed, hence my PR.

Since Python re doesn't support using \p{Emoji} I added a long messy character class in __init__.py.

If it could considered to update to regex this long regex could be shortened considerable ... not sure it's worth the effort tho' and the extra dependency to manage.

Summary by CodeRabbit

  • New Features

    • Expanded commit message validation to support a broader range of characters, including emojis and various symbols.
  • Tests

    • Added tests to verify that commit messages containing emojis are properly validated.

Copy link
Contributor

coderabbitai bot commented Feb 22, 2025

Walkthrough

The changes update the commit message validation by modifying the regular expression in the default configuration to include a broader Unicode range, such as emojis and various symbols. Additionally, new tests have been added to ensure that commit messages containing emojis are correctly validated by the system. No modifications have been made to the public or exported entities.

Changes

File(s) Change Summary
commit_check/init.py Updated the regex pattern in DEFAULT_CONFIG to support extended Unicode characters (emojis and symbols) in commit messages.
tests/commit_test.py Added two tests to verify that commit messages with emojis pass validation; imported DEFAULT_CONFIG.

Sequence Diagram(s)

sequenceDiagram
    participant T as Test
    participant R as CommitMsgReader
    participant V as Validator

    T->>+R: get_default_commit_msg_file()
    R-->>-T: default commit message file
    T->>+R: read_commit_msg(file)
    R-->>-T: "fix: 🐛 sample message"
    T->>+V: check_commit_msg("fix: 🐛 sample message")
    V-->>-T: 0 (success)
Loading

Poem

Hop, hop, commit away,
I tweak the regex in a playful display!
Emojis join the dance in the code, 🎉
Each commit now wears a vibrant mode.
From rabbit hops to code so neat,
My changes make our commits complete!
🐰


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1be470a and ca0bdc6.

📒 Files selected for processing (2)
  • commit_check/__init__.py (1 hunks)
  • tests/commit_test.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/commit_test.py
  • commit_check/init.py

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@kohanyirobert
Copy link
Contributor Author

Please mind, that the check fails due to my name. See #221.

Copy link
Contributor

@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 (2)
commit_check/__init__.py (1)

19-19: LGTM! Consider using the regex library for better maintainability.

The updated regex pattern correctly supports emojis while maintaining backward compatibility. However, the complex Unicode ranges could be simplified using the regex library's \p{Emoji} syntax.

Consider transitioning to the regex library to simplify the pattern:

-            'regex': r'^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test){1}(\([\w\-\.]+\))?(!)?: ([\U0001F600-\U0001F64F\U0001F300-\U0001F5FF\U0001F680-\U0001F6FF\U0001F700-\U0001F77F\U0001F780-\U0001F7FF\U0001F800-\U0001F8FF\U0001F900-\U0001F9FF\U0001FA00-\U0001FA6F\U0001FA70-\U0001FAFF\u2600-\u26FF\u2700-\u27BF] )?([\w ])+([\s\S]*)|(Merge).*|(fixup!.*)',
+            'regex': r'^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test){1}(\([\w\-\.]+\))?(!)?: (\p{Emoji} )?([\w ])+([\s\S]*)|(Merge).*|(fixup!.*)',
tests/commit_test.py (1)

51-67: LGTM! Consider adding more test cases for comprehensive coverage.

The test correctly verifies emoji support in commit messages. However, consider expanding the test coverage:

Add more test cases to verify different emoji scenarios:

+def test_check_commit_msg_with_various_emoji_patterns(mocker):
+    mock_get_default_commit_msg_file = mocker.patch(
+        "commit_check.commit.get_default_commit_msg_file",
+        return_value=".git/COMMIT_EDITMSG"
+    )
+    
+    test_cases = [
+        "feat: ✨ new feature",           # Sparkles
+        "refactor: ♻️ cleanup code",      # Recycle with variation selector
+        "style: 💅 polish UI",            # Nail polish
+        "docs: 📚 update readme",         # Books
+        "test: multiple 🧪 ✅ emojis",    # Multiple emojis
+    ]
+    
+    checks = [next(c for c in DEFAULT_CONFIG['checks'] if c['check'] == 'message')]
+    
+    for msg in test_cases:
+        mock_read_commit_msg = mocker.patch(
+            "commit_check.commit.read_commit_msg",
+            return_value=msg
+        )
+        
+        result = check_commit_msg(checks, commit_msg_file="")
+        assert result == 0
+        mock_read_commit_msg.assert_called_once_with(".git/COMMIT_EDITMSG")
+        mock_read_commit_msg.reset_mock()
+    
+    mock_get_default_commit_msg_file.assert_called()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 41e0244 and 1be470a.

📒 Files selected for processing (2)
  • commit_check/__init__.py (1 hunks)
  • tests/commit_test.py (2 hunks)
🔇 Additional comments (1)
commit_check/__init__.py (1)

19-19:

✅ Verification successful

Verify the performance impact of the complex regex pattern.

The extensive Unicode ranges in the pattern might affect performance. Let's verify the impact:


🏁 Script executed:

#!/bin/bash
# Description: Test regex pattern performance with and without emoji ranges

# Create test file with sample commit messages
cat << 'EOF' > test_commits.txt
feat: add new feature
fix: 🐛 fix bug
refactor: ♻️ improve code
chore: 🔧 update dependencies
style: 💄 format code
test: ✅ add tests
EOF

# Test performance using Python
python3 - << 'EOF'
import re
import time
import statistics

# Original pattern (simplified for testing)
original = r'^(feat|fix|refactor|style|test){1}(\([\w\-\.]+\))?(!)?: ([\w ])+([\s\S]*)'

# New pattern with emoji support
new = r'^(feat|fix|refactor|style|test){1}(\([\w\-\.]+\))?(!)?: ([\U0001F600-\U0001F64F\U0001F300-\U0001F5FF\U0001F680-\U0001F6FF\U0001F700-\U0001F77F\U0001F780-\U0001F7FF\U0001F800-\U0001F8FF\U0001F900-\U0001F9FF\U0001FA00-\U0001FA6F\U0001FA70-\U0001FAFF\u2600-\u26FF\u2700-\u27BF] )?([\w ])+([\s\S]*)'

def test_pattern(pattern, messages, iterations=1000):
    times = []
    compiled = re.compile(pattern)
    for _ in range(iterations):
        start = time.perf_counter_ns()
        for msg in messages:
            compiled.match(msg)
        end = time.perf_counter_ns()
        times.append(end - start)
    return statistics.mean(times) / 1_000_000  # Convert to milliseconds

with open('test_commits.txt', 'r') as f:
    messages = f.readlines()

original_time = test_pattern(original, messages)
new_time = test_pattern(new, messages)

print(f'Original pattern average time: {original_time:.3f}ms')
print(f'New pattern average time: {new_time:.3f}ms')
print(f'Performance impact: {((new_time - original_time) / original_time * 100):.1f}%')
EOF

Length of output: 116


Performance Impact Acceptable – Change Approved

The added Unicode ranges for emoji support do introduce a relative performance overhead (a roughly 43.6% increase), but in absolute terms the difference is minimal (from ~0.002ms to ~0.003ms per match). This impact is negligible in the context of commit message validation. Overall, the change maintains backward compatibility while extending support for emojis. As a minor improvement for long-term maintainability, consider exploring a dedicated regex library or alternative approaches to simplify such complex patterns if further issues arise.

  • Verified performance using a test script.
  • The absolute cost per match is insignificant.
  • Suggest evaluating regex library options for clarity and potential future maintenance.

There are emojis out there that consist of a Unicode code point for the emoji and a variation selector too (another code point).

See related test.
Copy link

@shenxianpeng
Copy link
Contributor

Hi @kohanyirobert,

Thanks for your pull request! You're right—the default regex only covers the general scenario.

But you can add your own .commit-check.yml file to customize your configuration to cover more scenario https://github.com/commit-check/commit-check?tab=readme-ov-file#use-custom-configuration

@kohanyirobert
Copy link
Contributor Author

Alright, got it. I'll close this PR then.

@kohanyirobert kohanyirobert deleted the feat/gitmoji-message branch February 23, 2025 16:18
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