May 28, 2024 - 13 min

GitHub Copilot: Unlocking Smart Coding with Your AI Development Assistant


				Leni Duderija, Q's React Engineer
				

Leni Duderija

React Engineer

GitHub Copilot blog hero image

Exploring the potential of GitHub Copilot: Enhancing developers’ capabilities and boosting coding productivity


As AI technology continues to evolve, it shapes our lives and work in profound ways, with software development being no exception. A multitude of AI coding assistants, including GitHub Copilot, Code Llama, StableCode, ChatGPT, Tabnine, and Amazon CodeWhisperer, have emerged to assist developers in writing code faster and more efficiently.


Beyond mere coding, these AI assistants have evolved into intelligent rubber ducks, capable of explaining code, aiding in debugging, crafting meaningful commit messages, generating documentation, and assisting with commonly forgotten git commands.


This blog focuses on GitHub Copilot, one of the most popular AI assistants, providing an overview of its features, practical examples, and insights into how it enhances the development workflow.


About Github Copilot


GitHub Copilot is an AI pair programmer developed by GitHub, OpenAI, and Microsoft. It provides autocomplete-style suggestions to developers as they code, supporting all languages and frameworks found in public repositories. The quality of suggestions depends on the diversity and volume of training data.


With enhanced performance in languages like Python, JavaScript, TypeScript, Ruby, Go, C#, and C++, Copilot offers suggestions through typing code or writing natural language comments. Additionally, GitHub Copilot features a Chat feature powered by GPT-4, enabling developers to interact with Copilot for solutions, bug fixes, or code explanations.


Available across IDEs, GitHub Mobile as a chat interface, in terminal through GitHub CLI and on Github.com with Enterprise subscription, GitHub Copilot offers three subscription plans: Copilot Individual, Copilot Business, and Copilot Enterprise. The Individual plan includes a 30-day trial period, allowing users to experience its capabilities firsthand before committing to a subscription.


Copilot GitHub Plans comparison

Github Copilot plans comparison


GitHub Copilot is available as an extension in various popular Integrated Development Environments (IDEs), including Visual Studio Code, Visual Studio, Vim, Neovim, the JetBrains suite of IDEs, and Azure Data Studio. In the following sections, we’ll explore how GitHub Copilot is utilized specifically within Visual Studio Code.


Getting started with Github Copilot in VS Code


GitHub Copilot is accessible through either a personal GitHub account, with a GitHub Copilot Individual subscription, or an organization account, with a GitHub Copilot Business or Enterprise subscription. This blog focuses on getting started with Copilot using an Individual license.


Once subscribed, the initial step involves installing the Github Copilot extension from the Visual Studio Code Marketplace. This process entails several steps, including authorizing VS Code in your GitHub account and authorizing this tool in the browser. For detailed instructions, please refer to the following link.


GitHub Copilot extension in VS Code Marketplace GitHub Copilot extension in VS Code Marketplace


While installing the GitHub Copilot extension is sufficient to start receiving suggestions, to access GitHub Copilot Chat, it’s necessary to install the corresponding extension from the Marketplace as well. This will enable you to fully utilize the capabilities of GitHub Copilot, including interacting with it for solutions, bug fixes, or code explanations.




GitHub Copilot Chat extension in VS Code Marketplace


GitHub Copilot Chat in VS Code

GitHub Copilot Chat in VS Code


To utilize Copilot in the CLI, it’s essential to install the github-copilot extension using GitHub CLI. This extension enables seamless integration with the command line interface, expanding the accessibility of GitHub Copilot across different development environments.


gh extension install github/gh-copilot


Before installing the github-copilot extension, ensure that GitHub CLI is installed on your system. Instructions for installing GitHub CLI can be found on this link. Once GitHub CLI is installed, proceed with installing the github-copilot extension to enable Copilot functionality in the command line interface.


Exploring Basic Code Suggestions: Examples to Get Started with GitHub Copilot


GitHub Copilot offers code suggestions through both code writing and natural language comments. In the examples below, we explore basic scenarios such as calculating the difference between two dates or generating dummy data like text, random numbers, dates, colors, and arrays of objects for various purposes such as social media posts, payment methods, or country and language selection.


A Basic Function for Calculating the Difference in Days Between Two Dates

Example 1: A Basic Function for Calculating the Difference in Days Between Two Dates


Example 2: Creating Various Dummy Data for Common Project Scenarios

Example 2: Creating Various Dummy Data for Common Project Scenarios


To access Copilot commands within our files, simply press ⌘+i to open the communication pop-up.


GithubCopilot_Commands_in_file

GitHub Copilot Commands Available in File


Below, we can observe suggestions for field validations commonly employed in form development, along with the /fix command in action to refine the suggested code.


Example 3: Basic Field Validation Suggestions - Passwords, Emails, Credit Cards

Example 3: Basic Field Validation Suggestions – Passwords, Emails, Credit Cards


Example 4: Utilizing GitHub /fix for Email Validation Adjustment

Example 4: Utilizing GitHub /fix for Email Validation Adjustment


Example 5: Utilizing GitHub /fix for Password Validation Adjustment

Example 5: Utilizing GitHub /fix for Password Validation Adjustment


If dealing with large arrays of hardcoded data, we can prompt Copilot to remove any duplicates present.


Example 6: Removing Duplicates from an Array with Copilot

Example 6: Removing Duplicates from an Array with Copilot


When working with forms, it’s common to implement validation along with error messages and initial data. In the example below, we first defined the FormDataType interface. Based on the props within that interface, I prompted Copilot to generate a Yup validation schema and an initial form data object. Additionally, we included an example of a password generator function with specific conditions. These conditions were automatically incorporated into the Yup validation.


Example 7: Password Generator Function, Form Initialization with Yup, Initial Data, and TypeScript Interface Creation

Example 7: Password Generator Function, Form Initialization with Yup, Initial Data, and TypeScript Interface Creation


In the example below, we utilize a comment to describe the initialization of an Axios instance and the usage of its interceptors for authentication.


Example 8: Creating Axios Instance with Interceptors for Authentication Token Addition - Accepting Suggestions with 'Tab' Key

Example 8: Creating Axios Instance with Interceptors for Authentication Token Addition – Accepting Suggestions with ‘Tab’ Key


In the following example, we witness Copilot’s Intellisense-like behavior as it suggests complete code for the useLocalStorage hook.


Example 9: Creating the useLocalStorage Hook and Resolving Errors

Example 9: Creating the useLocalStorage Hook and Resolving Errors


We can also request examples of usage from Copilot. Below, we have an example of a useFetch hook that was generated, along with an example of how to use the hook. This approach allows us to seek usage examples for any hook or library we use, ensuring we understand the correct way to utilize them.


Example 10: UseFetch Hook with Cancellation Mechanism and Usage Example

Example 10: UseFetch Hook with Cancellation Mechanism and Usage Example


GitHub Copilot can save time by quickly generating boilerplate code for tasks like creating Redux code, base components, CRUD APIs, service files, and more. Below are examples of generating an Express server with basic user routes, a user.service.ts file consuming those routes, and the quick creation of TypeScript interfaces. Additionally, we demonstrate how Copilot handles GraphQL queries and mutations.


Example 11: Generating Simple CRUD Operations in Express

Example 11: Generating Simple CRUD Operations in Express


Example 12: Generating users.service.ts File Based on Previously Generated CRUD Operations

Example 12: Generating users.service.ts File Based on Previously Generated CRUD Operations


Example 13: Modifying User Model with Copilot Assistance

Example 13: Modifying User Model with Copilot Assistance


Example 14: Handling GraphQL Queries and Mutations with Copilot

Example 14: Handling GraphQL Queries and Mutations with Copilot


Code Suggestions in Existing Project Workflows


My experience using Copilot with an old codebase paralleled my testing scenarios, albeit with an added layer of complexity due to its integration with existing project packages.


When tasked with creating new type definition files, Copilot efficiently learned from existing definitions and proposed code snippets incorporating those types. Similarly, during service creation, it seamlessly integrated these new types alongside a custom Http client powered by Axios.


Notably, Copilot’s suggestions extended to UI component creation, consistently favoring styled-components. Interestingly, it even provided default base styles tailored to component names; for example, automatically setting a height of 1px and width of 100% for a Divider component.


However, I encountered a minor hiccup when updating a type name, necessitating changes throughout the file. Though Copilot eventually managed to adjust the type name, it struggled with importing from the defining file, resorting to a generic path with a comment prompting manual correction. In such instances, I found resorting to Ctrl+R and IDE auto-import to be a more straightforward solution. Nonetheless, this may simply reflect my limited experience with Copilot.


Example 15: New Service Generated with Comments

Example 15: New Service Generated with Comments


Example 16: Default Base Code for Divider and Description UI Components

Example 16: Default Base Code for Divider and Description UI Components


GitHub Copilot Chat


The main difference between using GitHub Copilot in code and in Chat lies in their functionalities. In code, Copilot seamlessly integrates with your development environment, allowing it to directly make changes to the file based on suggestions. On the other hand, using Copilot in Chat provides a collaborative space for communication within its own tab.

However, while Copilot can still provide code suggestions in Chat, it doesn’t have the capability to apply those changes directly to the file; users must manually copy and paste the code.


It’s important to note that there are differences in available commands between Copilot Chat and its integration within code. For instance, the /docs command, which allows for writing documentation, is not available in Chat, although we can still ask to write documentation for us. Instead, Chat offers commands like /new for generating a new workspace, /newNotebook for creating a Jupyter notebook, or @terminal to provide assistance with terminal commands.


Overall, understanding the distinctions between using Copilot in code versus Chat can help users effectively leverage its capabilities within their development workflows.


GitHub Copilot Chat: Available Commands

GitHub Copilot Chat: Available Commands


In GitHub Copilot Chat, users can request code changes or generate new code, similar to using it directly within a file. All examples previously mentioned can be utilized in Chat, with the key distinction being that changes made in Chat do not directly impact files, as mentioned earlier. Below, we demonstrate an example of using Copilot Chat to convert a JavaScript class constructor to a factory function.


Example 17: Replacing Class Constructor with Factory Function Using GitHub Copilot Chat

Example 17: Replacing Class Constructor with Factory Function Using GitHub Copilot Chat


In addition to requesting code changes or generating new code, we can also ask Copilot to explain existing code or provide suggestions for improvements. The examples below showcase these capabilities in action.


Example 18: Requesting Error Suggestions in a Different Manner with GitHub Copilot Chat

Example 18: Requesting Error Suggestions in a Different Manner with GitHub Copilot Chat


Example19-AskingForCodeImprovements

Example 19: Requesting Code Improvements from GitHub Copilot Chat


Example20-ExplainingInterceptors

Example 20: GitHub Copilot Chat Explaining Axios Interceptors


In addition to its code generation capabilities, GitHub Copilot can be utilized to generate entire projects using the @workspace /new command. Instead of relying on tools like CRA or Vite, users can specify project requirements such as desired technologies, packages, routes, and more, allowing Copilot to suggest and create a customized workspace. A demonstration of using this command can be found in the video below.



Efficient Test and Documentation Generation with GitHub Copilot


GitHub Copilot proves to be immensely useful and time-saving for generating tests, especially considering the frequent repetition of code in testing scenarios. With the /tests command, Copilot simplifies the test generation process, allowing users to request test cases through various methods.


Whether it’s asking Copilot Chat to generate test cases for a specific file, using the communication popup directly in the file, writing a comment in natural language, or simply starting to write code, Copilot seamlessly suggests the rest of the test cases.


Example 21: Automatically Generated Test Cases for Base Button Component

Example 21: Automatically Generated Test Cases for Base Button Component


Example 22: Correcting Usage of Test Method

Example 22: Correcting Usage of Test Method


Example 23: Generating Mock Data for Testing

Example 23: Generating Mock Data for Testing


Example 24: Test Cases Generated for a Page, with Additional Tests Added via Comments, Utilizing Generated Mock Data

Example 24: Test Cases Generated for a Page, with Additional Tests Added via Comments, Utilizing Generated Mock Data


Example 25: Generating Test Cases for Modal Component with Login Form Using GitHub Copilot Chat

Example 25: Generating Test Cases for Modal Component with Login Form Using GitHub Copilot Chat


GitHub Copilot streamlines the process of documentation integration into code by offering multiple methods. Developers can directly request documentation within the file through comments or by adding a markdown file and writing a comment, although the latter may not consistently yield optimal suggestions.


For comprehensive and detailed documentation, utilizing Copilot Chat proves most effective, providing thorough explanations and usage examples.


While the generated documentation is typically basic, it serves well in providing comments for methods and types. Notably, Copilot excels in generating detailed documentation for public libraries, offering valuable insights and instructions. Additionally, Copilot functions as an intelligent IntelliSense tool, suggesting words or sentences that may have been overlooked, enhancing the documentation process for custom code.


Example 26: Code Documented with Comments Using GitHub Copilot

Example 26: Code Documented with Comments Using GitHub Copilot


Example 27: Generating Markdown File for Requested Documentation Using GitHub Copilot

Example 27: Generating Markdown File for Requested Documentation Using GitHub Copilot


Github Copilot in CLI


GitHub Copilot in the Command Line Interface (CLI) serves as a versatile chat-like interface, offering assistance with various command line tasks. Users can request help with generic commands, git commands, or GitHub-specific gh commands, refining their queries until they obtain the precise information they need.


Copilot’s ability to suggest the appropriate command for specific tasks streamlines the CLI learning process, making it easier for users to navigate and execute commands effectively. Moreover, Copilot serves as a resource for explaining unfamiliar commands, providing clear and concise explanations to help users understand their functionalities and usage.


For further information, refer to the documentation page for comprehensive details and usage guidelines.


Example 28: Leveraging GitHub Copilot in the Command Line Interface (CLI)

Example 28: Leveraging GitHub Copilot in the Command Line Interface (CLI)


Additional Use Cases and Demonstrations


While testing GitHub Copilot, I discovered several other intriguing applications. For instance, it can generate commit messages seamlessly within Git Lens, explain error messages from the terminal, and offer suggestions for resolving them. Additionally, it proves beneficial in generating CI/CD scripts, such as those for deploying applications using GitHub Actions.


It’s worth noting that GitHub Copilot can also assist in generating pull request descriptions. However, this feature is currently exclusive to the Enterprise subscription, which I didn’t have access to for testing purposes. From examples I’ve seen, it appears to function similarly to the way it generates commits in VS Code.


Copilot in the GitHub Mobile app bears a resemblance to ChatGPT and offers multifaceted assistance. It can provide answers to queries about GitHub features, workflows, and terminology, as well as offer guidance on efficient GitHub usage, including repository management, issues, and pull requests. Additionally, it aids in finding specific information within GitHub repositories using the codesearch function, offers code suggestions or solutions based on user queries, and can even explain programming languages and coding techniques.


I’m enthusiastic about exploring further possibilities for utilization of Github Copilot.


Example 29: Generating Commit Messages for New Pages in the Application with GitHub Copilot

Example 29: Generating Commit Messages for New Pages in the Application with GitHub Copilot


Example 30: Generating Commit Messages for Refactoring Existing Code and Creating Documentation with GitHub Copilot

Example 30: Generating Commit Messages for Refactoring Existing Code and Creating Documentation with GitHub Copilot


Example 31: GitHub Copilot Explaining Error Messages from Terminal

Example 31: GitHub Copilot Explaining Error Messages from Terminal


Example 32: Generating Basic GitHub Actions Workflow Configuration

Example 32: Generating Basic GitHub Actions Workflow Configuration


Exploring Areas for Improvement


While GitHub Copilot, like other AI tools, offers significant benefits, it’s not without its imperfections. During my testing of its features, I encountered several issues.


One notable challenge is the variability in the quality of code suggestions. While Copilot aims to provide helpful recommendations, the suggestions can range from well-structured and efficient to convoluted or inefficient. This variance is understandable given that Copilot learns from public repositories containing a mix of old and suboptimal code. It’s essential to carefully review and understand these suggestions before accepting them.


Additionally, Copilot may experience performance issues or slowdowns, particularly when generating complex code suggestions or processing large datasets. This can sometimes result in suggestions being cut off, leading to incomplete or truncated recommendations. However, this issue is usually quickly resolved by repeating the question to Copilot.


Another challenge arises when using the /fix command to make changes to code in a file. In some cases, it may fail to apply changes to requested parts only, potentially due to improper usage of the command. However, using the same command in Copilot Chat often yields better results, as it provides explanations for the changes made.


Importing custom components may also pose challenges, particularly when creating a new file where Copilot has limited context about the component’s purpose. However, this issue is less prevalent when editing existing components.


Furthermore, without a clear understanding of the user’s intentions, Copilot may provide misguided or unhelpful assistance. This issue can be mitigated by learning how to formulate queries effectively to elicit the best possible response from Copilot.


Finally, while rare, there have been instances where listing all suggestions in a new tab resulted in a large chunk of code redundantly repeating a single function multiple times. While this occurrence has minimal impact on the overall Copilot experience, it highlights the occasional quirks that may arise when using AI-driven tools.


Example 33: Redundant Repetition of Single Function

Example 33: Redundant Repetition of Single Function


While some of these issues may diminish with increased familiarity and usage of Copilot, others are inherent to the nature of evolving AI technologies. As Copilot continues to improve and adapt, we can anticipate solutions to these challenges.


It’s encouraging to note that only a few of these have a more significant impact on the coding experience. By carefully reviewing suggested code and selecting the best solutions, or by mastering more efficient tool usage, we can mitigate these challenges. Most of these issues had a small or negligible impact on the overall coding experience.


Conclusion


GitHub Copilot has been a game-changer for my productivity as a developer. It’s like having an invaluable assistant that consistently provides insightful suggestions and solutions, significantly enriching my coding experience.


From swiftly generating boilerplate code to offering indispensable documentation capabilities, Copilot streamlines development workflows and unlocks new possibilities in coding. GitHub Copilot offers solutions and explanations directly within the IDE, eliminating the need to search for answers elsewhere.


While there are occasional pitfalls, such as over-reliance or the need for caution when accepting suggestions, the overall benefits far outweigh these considerations. With a 30-day trial period, I recommend every developer to explore all of its capabilities and become accustomed to its seamless integration into the coding process.


It quickly becomes an indispensable coding partner, enhancing productivity and creativity in ways that were previously unimaginable.


Give Kudos by sharing the post!

Share:

ABOUT AUTHOR
Leni Duderija, Q's React Engineer

Leni Duderija

React Engineer

React developer at Q with almost a decade of experience in frontend development. Alongside coding, he plays trumpet, he's passionate about hiking, sports and martial arts, with a particular affinity for Krav Maga, boxing, and CrossFit. Wine lover. Recently, he's been lacing up his shoes for runs with his toddler Bartul.