Customize Gemini Code Assist behavior in GitHub Stay organized with collections Save and categorize content based on your preferences.
AI-generated Key Takeaways
You can customize Gemini Code Assist's code review by adding a
styleguide.mdfile in the.gemini/folder of your repository.The enterprise version allows managing style guides and configurations for multiple repositories via the Google Cloud console.
Gemini Code Assist's standard code review focuses on correctness, efficiency, maintainability, security, and miscellaneous topics when a custom style guide is not provided.
A
config.yamlfile can be used to enable or disable various features and specify files to ignore using glob patterns.When both repository-specific and Google Cloud console configurations exist, the repository's
config.yamloverrides console settings, whilestyleguide.mdfiles are combined.
If you have a custom set of best practices or conventions that you wantGemini Code Assist on GitHubto check for, you can add astyleguide.md file to the.gemini/ root folderof your repository. Users of theenterprise version ofGemini Code Assist on GitHub can use the Google Cloudconsole to add style guide information for use across multiple repositories.In both cases, the style guide is treated as a regular Markdown file, andexpands the standard prompt that Gemini Code Assist onGitHub uses. For instructions on adding a style guide, seeadd configuration files.
Standard code review patterns
When custom style guides aren't specified, these are the main categories ofareas where Gemini Code Assist focuses its code review on:
Correctness: Makes sure the code functions as intended and handles edgecases, checks for logic errors, race conditions, or incorrect API usage.
Efficiency: Identifies potential performance bottlenecks or areas foroptimization, like excessive loops, memory leaks, inefficient data structures,redundant calculations, excessive logging, and inefficient string manipulation.
Maintainability: Assesses code readability, modularity, and adherence tolanguage idioms and best practices. Targets poor naming for variables,functions, and classes, lack of comments or documentation, complex code, codeduplication, inconsistent formatting, and magic numbers.
Security: Identifies potential vulnerabilities in data handling or inputvalidation, like insecure storage of sensitive data, injection attacks,insufficient access controls, Cross-Site Request Forgery (CSRF), and InsecureDirect Object References (IDOR).
Miscellaneous: Other topics are considered when reviewing the pullrequest, like testing, performance, scalability, modularity and reusability, anderror logging and monitoring.
Add configuration files
You can modify Gemini Code Assist behavior by adding supportedconfiguration files to a.gemini/ folder located in the root of yourrepository. Gemini Code Assist uses the following files, ifyou've added them to the.gemini/ folder:
config.yaml: A file that contains various configurable features that you canenable or disable, including specifying files to ignore usingglob patterns.styleguide.md: A Markdown file which instructsGemini Code Assist with some specific rules that you want itto follow when performing a code review.
config.yaml example
The following code snippet is an example of aconfig.yaml file. In thisexample, each property is set to the default value used byGemini Code Assist. You can use this snippet as a template tocreate your ownconfig.yaml file:
have_fun:falsecode_review:disable:falsecomment_severity_threshold:MEDIUMmax_review_comments:-1pull_request_opened:help:falsesummary:truecode_review:trueinclude_drafts:trueignore_patterns:[]config.yaml schema
The following code snippet is the schema for theconfig.yaml file. Itdefines all of the possible configuration options and their accepted values:
$schema:"http://json-schema.org/draft-07/schema#"title:RepoConfigdescription:Configuration for Gemini Code Assist on a repository. All fields are optional and have default values.type:objectproperties:have_fun:type:booleandescription: Enables fun features such as a poem in the initial pull request summary. Default:false.ignore_patterns:type:arrayitems:type:stringdescription: A list of glob patterns for files and directories that Gemini Code Assist should ignore. Files matching any pattern in this list will be skipped during interactions. Default:[].code_review:type:objectdescription:Configuration for code reviews. All fields are optional and have default values.properties:disable:type:booleandescription: Disables Gemini from acting on pull requests. Default:false.comment_severity_threshold:type:stringenum:-LOW-MEDIUM-HIGH-CRITICALdescription: The minimum severity of review comments to consider. Default:MEDIUM.max_review_comments:type:integerformat:int64description: The maximum number of review comments to consider. Use -1 for unlimited. Default:-1.pull_request_opened:type:objectdescription:Configuration for pull request opened events. All fields are optional and have default values.properties:help:type:booleandescription: Posts a help message on pull request open. Default:false.summary:type:booleandescription: Posts a pull request summary on the pull request open. Default:true.code_review:type:booleandescription: Posts a code review on pull request open. Default:true.include_drafts:type:booleandescription: Enables agent functionality on draft pull requests. Default:true.
styleguide.md
Thestyleguide.md file does not have a defined schema. Instead, it's anatural language description of how you want Gemini Code Assistto structure its code reviews. The following code snippet is an example of astyleguide.md file:
# Company X Python Style Guide# IntroductionThis style guide outlines the coding conventions for Python code developed at Company X.It's based on PEP 8, but with some modifications to address specific needs andpreferences within our organization.# Key Principles* **Readability:** Code should be easy to understand for all team members.* **Maintainability:** Code should be easy to modify and extend.* **Consistency:** Adhering to a consistent style across all projects improves collaboration and reduces errors.* **Performance:** While readability is paramount, code should be efficient.# Deviations from PEP 8## Line Length* **Maximum line length:** 100 characters (instead of PEP 8's 79). * Modern screens allow for wider lines, improving code readability in many cases. * Many common patterns in our codebase, like long strings or URLs, often exceed 79 characters.## Indentation* **Use 4 spaces per indentation level.** (PEP 8 recommendation)## Imports* **Group imports:** * Standard library imports * Related third party imports * Local application/library specific imports* **Absolute imports:** Always use absolute imports for clarity.* **Import order within groups:** Sort alphabetically.## Naming Conventions* **Variables:** Use lowercase with underscores (snake_case): `user_name`, `total_count`* **Constants:** Use uppercase with underscores: `MAX_VALUE`, `DATABASE_NAME`* **Functions:** Use lowercase with underscores (snake_case): `calculate_total()`, `process_data()`* **Classes:** Use CapWords (CamelCase): `UserManager`, `PaymentProcessor`* **Modules:** Use lowercase with underscores (snake_case): `user_utils`, `payment_gateway`## Docstrings* **Use triple double quotes (`"""Docstring goes here."""`) for all docstrings.*** **First line:** Concise summary of the object's purpose.* **For complex functions/classes:** Include detailed descriptions of parameters, return values, attributes, and exceptions.* **Use Google style docstrings:** This helps with automated documentation generation. ```python def my_function(param1, param2): """Single-line summary. More detailed description, if necessary. Args: param1 (int): The first parameter. param2 (str): The second parameter. Returns: bool: The return value. True for success, False otherwise. Raises: ValueError: If `param2` is invalid. """ # function body here ```## Type Hints* **Use type hints:** Type hints improve code readability and help catch errors early.* **Follow PEP 484:** Use the standard type hinting syntax.## Comments* **Write clear and concise comments:** Explain the "why" behind the code, not just the "what".* **Comment sparingly:** Well-written code should be self-documenting where possible.* **Use complete sentences:** Start comments with a capital letter and use proper punctuation.## Logging* **Use a standard logging framework:** Company X uses the built-in `logging` module.* **Log at appropriate levels:** DEBUG, INFO, WARNING, ERROR, CRITICAL* **Provide context:** Include relevant information in log messages to aid debugging.## Error Handling* **Use specific exceptions:** Avoid using broad exceptions like `Exception`.* **Handle exceptions gracefully:** Provide informative error messages and avoid crashing the program.* **Use `try...except` blocks:** Isolate code that might raise exceptions.# Tooling* **Code formatter:** [Specify formatter, e.g., Black] - Enforces consistent formatting automatically.* **Linter:** [Specify linter, e.g., Flake8, Pylint] - Identifies potential issues and style violations.# Example```python"""Module for user authentication."""import hashlibimport loggingimport osfrom companyx.db import user_databaseLOGGER = logging.getLogger(__name__)def hash_password(password: str) -> str: """Hashes a password using SHA-256. Args: password (str): The password to hash. Returns: str: The hashed password. """ salt = os.urandom(16) salted_password = salt + password.encode('utf-8') hashed_password = hashlib.sha256(salted_password).hexdigest() return f"{salt.hex()}:{hashed_password}"def authenticate_user(username: str, password: str) -> bool: """Authenticates a user against the database. Args: username (str): The user's username. password (str): The user's password. Returns: bool: True if the user is authenticated, False otherwise. """ try: user = user_database.get_user(username) if user is None: LOGGER.warning("Authentication failed: User not found - %s", username) return False stored_hash = user.password_hash salt, hashed_password = stored_hash.split(':') salted_password = bytes.fromhex(salt) + password.encode('utf-8') calculated_hash = hashlib.sha256(salted_password).hexdigest() if calculated_hash == hashed_password: LOGGER.info("User authenticated successfully - %s", username) return True else: LOGGER.warning("Authentication failed: Incorrect password - %s", username) return False except Exception as e: LOGGER.error("An error occurred during authentication: %s", e) return False```Manage configuration files across multiple repositories
Preview
This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms for Google Cloud. Pre-GA features are available "as is" and might have limited support. For more information, see theGoogle Cloud launch stage descriptions.
If you have the enterprise version of Gemini Code Assist onGitHub, you can use the Google Cloud console to apply one set ofconfigurations and one style guide to all the repositories that are linked in aDeveloper Connect connection.
Note that if a repository managed in this way also has its ownconfig.yaml orstyleguide.md, the following behavior occurs:
The repository's
config.yamlsettings override the Google Cloud consolesettings.The repository's
styleguide.mdis combined with the Google Cloud consolestyle guide.
The following steps show how to control one set of configurations and onestyle guide across multiple repositories. These steps assume you have previouslyset up the enterprise version.
In the Google Cloud console, go to the Gemini Code AssistAgents & Tools page.
In theAgents section, locate theCode Assist Source Code Management card, and clickAdvanced.
TheEdit Code Assist Source Code Management pane opens.
In theConnections table, click the name of the connection that you wantto apply a configuration or style guide to.
The details page for the connection opens.
In theSettings tab, update the settings that you want to change.
In theStyle guide tab, add the style guide you want the repositoriesassociated with this connection to use.
ClickSave.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-11-05 UTC.