GitHub Copilot Tutorial
In this GitHub Copilot tutorial, we’ll show you how to configure and safely use this tool with IntelliJ for Java development projects.
Join the DZone community and get the full member experience.
Join For FreeThis article describes the GitHub Copilot tool and the main guidelines and assumptions regarding its use in software development projects. The guidelines concern both the tool’s configuration and its application in everyday work and assume the reader will use GitHub Copilot with IntelliJ IDEA (via a dedicated plugin).
GitHub Copilot: What Is It?
GitHub Copilot is an AI developer assistant that uses a generative AI model trained for all programming languages available in GitHub repositories. The full description and documentation of the tool is available here.
There are other similar tools on the market, such as OpenAI Codex, JetBrains AI Assistant, or Tabnine, but GitHub Copilot stands out due to the following features:
- The largest and most diverse collection for training an AI model – GitHub repositories
- Estimated usage share – currently approx. 40-50% (according to Abhay Mishra’s article based on undisclosed industry insights), but the market is very dynamic
- Support for popular technologies – we’ve tested it with the Java programming language, Scala, Kotlin, Groovy, SQL, Spring, Dockerfile, OpenShift, Bash
- Very good integration with the JetBrains IntelliJ IDEA IDE
- Low entry-level due to quick and easy configuration, general ease of use, clear documentation, and many usage examples on the internet
- A wide range of functionalities, including:
- Suggestions while writing code
- Generating code based on comments in natural language
- Taking existing code into account when generating a new code snippet
- Creating unit tests
- Chat – allows you to ask questions regarding code, language, and technology, as well as suggests corrections for simplifying the code
- CLI – support for working in the console and creating bash scripts
Our Goals
Our main goal for using GitHub Copilot was to improve the efficiency of writing code and its quality. In addition, we intended it to support and assist us in work in which programmers lack knowledge and experience. Here are the specific goals that we wanted our development team to achieve by using GitHub Copilot:
1. Accelerating Development
- Generating code fragments
- Generating SQL queries
- Hints for creating and modifying OpenShift and Dockerfile configuration files
- Faster search for solutions using the chat function, e.g., explanation of regular expressions, operation of libraries or framework mechanisms
2. Improving Code Quality
- Generating unit tests with edge cases – both in Java and Groovy languages
- Suggesting corrections and simplifications in our own code
3. Working With Less Frequently Used Technologies
- Explaining and generating code (including unit tests) in Scala and Kotlin
- Support while using “legacy” solutions like Activiti, etc.
- Support in creating and understanding configuration files
4. More Efficient Administrative Work in the Console Using CLI Functions
Tool Limitations Guidelines
Since GitHub Copilot is based on generative AI, you must always remember that it may generate incorrect code or responses. Therefore, when using the tool, you must be aware of potential limitations and apply the principle of limited trust and verification. The main limitations are presented in the table below.
Limitation | Description |
Limited scope of knowledge | The tool is based on code found in GitHub repositories. Some problems, or complex structures, languages or data notations, have poor representation in the training sets |
Dynamic development and features in the beta phase | The tool is developing very dynamically. Patches and updates appear every week or every several weeks, which indicates that many elements of the tool are not working properly. Some functionalities, such as GitHub Copilot CLI, are still in beta |
Inaccurate code | The tool provider informs that the generated code may not meet the user’s expectations, may not solve the actual problem, and may contain errors |
Inaccurate chat responses | When using chat, the accuracy of the answer depends largely on the question or command formulated. The documentation says that “Copilot Chat is not designed to answer non-coding questions”, so there are possible answers, especially in areas not strictly related to the code (design, etc.), that will not be appropriate or even sensible |
Dangerous code | The training set (repositories) may also contain code elements that violate security rules, both in the security and safety sense, such as API keys, network scanning, IP addresses, code that overloads resources or causes memory leaks, etc. |
To minimize the negative impact of the identified GitHub Copilot limitations, you should always:
- Check alternative suggestions (using Ctrl+[ and Ctrl+], etc.) and choose the ones that best suit a given situation
- Read and analyze the correctness of the generated code
- Test and run code in pre-production environments – primarily locally and in the development environment
- Submit the generated code to code review
Important: Never deploy the code generated by GitHub Copilot to production environments without performing the above checks.
Configuration Guidelines
In this section, we’ll present the basic information regarding the pricing plans (with advantages and disadvantages for each option, as seen from the perspective of our intended goals) and personal account configuration (for both GitHub Copilot and the IntelliJ IDEA plugin).
Pricing Plans
GitHub Copilot offers three subscription plans with different scopes of offered functionality and cost. In our case, two plans were worth considering: Copilot Individual or Copilot Business. The Copilot Enterprise plan additionally offers access to chat via the github.com website and generating summaries for pull requests, which was unimportant for our assumed goals (but it may be different in your case). Both plans’ main advantages and disadvantages are presented in the table below.
Plan | Advantages | Disadvantages |
GitHub Copilot Individual | Lower cost at $10/month/user
Offers the key functionality required to achieve the intended goals |
Lack of control over tool configuration and user access by the organization |
GitHub Copilot Business | Offers the key functionality required to achieve the intended goals
Control over tool configuration and user access by the organization |
Higher cost at $19/month/user |
In our case, Copilot Business was the better option, especially because it allows full control over the configuration and access to the tool for developers in the team. If you’re working on your own, the Copilot Individual plan might be enough.
Account Configuration
You can configure GitHub Copilot when purchasing a subscription plan, and the settings can also be changed after activating the account in the organization’s account settings on GitHub. At the account level, there were two key parameters for our use case to configure in GitHub Copilot, described in the table below.
Option name | Description | Recommended settings |
Suggestions matching public code | Available options:
Allowed and Blocked Determines whether to show or to block code suggestions that overlap around 150 lines with public code |
Blocked
This option reduces the risk of duplicating code from public repositories, thus reducing the uncertainty about the copyright ownership of the code |
Allow GitHub to use my code snippets for product improvements | Available options: Yes and No
Determines whether GitHub, its affiliates, and third parties may use user code snippets to explore and improve GitHub Copilot suggestions, related product models, and features |
No
If you plan to use GitHub Copilot for commercial purposes, GitHub and its associated entities should not use user code due to copyright considerations |
Here is a detailed description and instructions for changing configuration options in your GitHub account.
IntelliJ IDEA Plugin Configuration
To enable GitHub Copilot in the IntelliJ IDEA IDE, you must install the GitHub Copilot extension from the Visual Studio Code marketplace. Installation is done via the IDE in the plugin settings. After installation, log in to your GitHub account with your device code. You can find detailed instructions for installing and updating the plugin here.
The GitHub Copilot plugin for the IntelliJ IDEA IDE offers the ability to configure the following things:
- Automatic submission of suggestions
- The way suggestions are displayed
- Automatic plugin updates
- Supported languages
- Keyboard shortcuts
In our case, using the default plugin settings was recommended because they ensure good working comfort and are compatible with the existing tool documentation. Any changes to the configuration can be made by each user according to their own preferences.
How To Use GitHub Copilot in IntelliJ
Here are some guidelines for using key functionalities that will help you use the GitHub Copilot tool optimally.
Generating Application Code
When To Use
- Creating classes
- Creating fields, methods, constructors
- Writing code snippets inside methods
How To Use
- By writing code and using automatic suggestions – it’s always worth checking other suggestions using the Ctrl+] / Ctrl+[ keys
- By writing concise and precise comments in natural English
- Using the chat function – the chat can generate a fragment of code in response to a query (see examples in the section “Using the GitHub Copilot Chat” below) and allows you to quickly generate code using the Copy Code Block or Insert Code Block at Cursor buttons that appear in the section with code in the chat window
Writing Unit Tests
When To Use
- Creating new classes and methods that we want to cover with unit tests
- Coverage of existing classes and methods with unit tests
How To Use
- By writing a comment in the test class. For example, if you write
// Unit test in JUnit for CurrencyService
, you will get the following result:
- It is possible to generate individual test methods by entering in the comment the test case that the method is to test. Similarly, you can generate mocks in the test class.
- Using the chat – you can select the GitHub Copilot > Generate Test option from the context menu, enter the
/tests
command, or write an instruction in a natural language, e.g.,Generate unit test for class CurrencyService
. In response, you will receive a descriptive explanation of the test structure and the code of the entire test class:
Generating SQL Queries and Stored Procedures
When To Use
- When writing DDL, DML, and DQL queries that will be used in the application
- During data analysis and errors related to data in the database
- When writing scripts and stored procedures
How To Use
- IMPORTANT: you must have a database connection configured in IntelliJ IDEA or DataGrip
- By writing queries and using automatic suggestions
- By writing a comment, e.g. if you write
– – get party data for account
, you will get the following result:
Creating OpenShift Configuration or Other Configuration Files
When To Use
- Creating or modifying configuration files
- Analysis of directives, their options and values, and configuration mechanisms
How To Use
- By writing directives and using automatic suggestions
- Using the chat – you can select the directive and choose GitHub Copilot > Explain This from the context menu, enter the /explain command, or write a query in natural language about a given configuration element
Using the BASH Console
When To Use
- When trying to use obscure console commands
- For an explanation of command operation and its options
- To find the right command to perform a task
- When writing BASH scripts
How To Use
- IMPORTANT: to use the CLI tool, install GitHub CLI with the gh-copilot extension according to the instructions
- Currently, the tool offers two commands, summarized in the table below
Command | Example | Result |
gh copilot suggest | # gh copilot suggest “find IP number in text file” | grep -E -o ‘([0-9]{1,3}\.){3}[0-9]{1,3}’ <filename> |
gh copilot explain | # gh copilot explain “curl -k” | curl is used to issue web requests, e.g., download web pages
–k or –insecure allows curl to perform insecure SSL connections and transfers |
How To Use GitHub Copilot Chat
We’ve written a separate chapter for the GitHub Copilot Chat – as there are several use cases worth talking about. Let’s go through them individually and discuss specific guidelines for each case.
Creating New Functionalities
When To Use
- When you are looking for a solution to a problem, such as creating a website, a method that performs a specific task, error handling for a given block of code/method/class, etc.
How To Use
- Enter a query in natural English regarding the functionality you are looking for. It should concern topics related to programming – code, frameworks/libraries, services, architecture, etc. Below is an example for the query: How to get currency exchange data?
Using Regular Expressions
When To Use
- When you need to create and verify a regular expression
How To Use
- Enter a query in natural English regarding the pattern you are looking for. The example below shows a generated method with an incorrect pattern, a query, and a response with an explanation and corrected code
Finding Errors in the Code
When To Use
- When you create new classes or methods
- When analyzing a class or method that causes errors
How To Use
- You can select the code and choose GitHub Copilot > Fix This from the context menu, enter the
/fix
command, or write an instruction in natural English, e.g., Find possible errors in this class. You can specify a command to a method name or error type. For example, for a simple class, explanations of potential errors were obtained, and the chat generated code to handle these errors:
Explanation of Existing Code
When To Use
- When you don’t understand what exactly a module, class, method, piece of code, regular expression, etc., does
- When you don’t know the framework or library mechanism used
How To Use
- In a class or method, you can select GitHub Copilot > Explain this from the context menu, type the
/explain
command, or write a query in natural English about the problematic code element, e.g., Explain what is this class doing. The example below presents an explanation of the class and its methods. This applies to the class generated in the bug-finding example
Simplify Existing Code
When To Use
- When the code is complicated and difficult to understand or unnecessarily extensive
- When refactoring the code
How To Use
- In a class or selected method or code fragment, you can select GitHub Copilot > Simplify This from the context menu, type the
/simplify
command, or write a query in natural English. An example of a simple method of refactoring for a class is below:
The result:
Summary: A Powerful Tool, as Long as You’re Cautious
As you can see, GitHub Copilot can be a powerful tool in a software developer’s arsenal. It can speed up and simplify various processes and day-to-day tasks. However, as with all things related to generative AI, you can never fully trust this tool – therefore, the crucial rule is to always read, review, and test what it creates.
Published at DZone with permission of Karol Świder. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments