GitHub Copilot Chat Archives - The GitHub Blog https://github.blog/tag/github-copilot-chat/ Updates, ideas, and inspiration from GitHub to help developers build and design software. Wed, 02 Jul 2025 14:16:16 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://github.blog/wp-content/uploads/2019/01/cropped-github-favicon-512.png?fit=32%2C32 GitHub Copilot Chat Archives - The GitHub Blog https://github.blog/tag/github-copilot-chat/ 32 32 153214340 How to refactor code with GitHub Copilot https://github.blog/ai-and-ml/github-copilot/how-to-refactor-code-with-github-copilot/ Tue, 11 Feb 2025 17:00:05 +0000 https://github.blog/?p=82544 Discover how to use GitHub Copilot to refactor your code and see samples of it in action.

The post How to refactor code with GitHub Copilot appeared first on The GitHub Blog.

]]>

We’ve all been there—staring at a function that looks like it was written by an over-caffeinated goblin at 3 AM (maybe even your alter ego). You could pretend it doesn’t exist, or you could refactor it. Luckily, GitHub Copilot makes the second option less painful.

Let’s get to it.

What is code refactoring?

Feel free to breeze past this section if you already know what’s involved with refactoring code, but we wanted to take a moment to cover what we’ll be looking at today.

Think of refactoring as giving your project some digital spring cleaning—a glow up for your functions, classes, and modules. But instead of just tidying up, you’re making your code more efficient, maintainable, and readable, all without changing its external behavior.

Some standard ways of refactoring include:

  • Simplifying complex conditionals (because no one should need a PhD to read your if statements)
  • Extracting duplicated logic (so you’re not trying to maintain code in ten different places)
  • Improving variable and function names (because doThing() is a crime against humanity)
  • Converting monolithic functions into smaller, modular pieces (to prevent the dreaded “function that spans multiple screens” scenario)

Refactoring isn’t just about tidiness—it’s about making your codebase more resilient, scalable, and enjoyable to work with. Let’s find out how GitHub Copilot can help you do it faster and with fewer headaches.

Know what your code does before you refactor anything

It might seem obvious to say this, but before you can refactor any code you need to understand how it works. If you don’t know what your code is doing, you won’t know whether or not the “improvements” you’re making are changing the core functionality of the code.

Consider the following method:

public String getSound(String animal) {
  if (animal == null) {
      System.out.println("Oops! A null animal?");
  } else if (animal.equalsIgnoreCase("Dog")) {
      return "Bark";
  } else if ( animal.equalsIgnoreCase("Cat")) {
      return "Meow";
  } else if ( animal.equalsIgnoreCase("Bird")) {
      return "Tweet";
  }
  return "Unknown";
}

You might look at this and immediately think “they should use a switch statement,” and that would be one example of refactoring the code. But having that knee jerk reaction requires you to know how if-statements and switch-statements work. You can only make that suggestion if you understand this code will continue cycling through if-statements until it finds an appropriate match. Otherwise, it will return the value of Unknown.

As codebases get more complex and make calls between multiple files, this gets (much) more complicated. And this is one way Copilot can help you.

You can ask Copilot Chat to explain how some code works, either by asking in plain language or using the /explain slash command. To limit the scope of what Copilot looks at, select the code in your IDE before asking your query, or specify specific files for it to consider by using #file. While you’re at it, you can even ask it to add code comments to help you (or anyone else reading the code) in the future.

Here are some sample prompts:

  • Explain what this code does.
  • What is this code doing?
  • Add comments to this code to make it more understandable.

You should use Copilot Chat to analyze and explain your codebase until you fully understand the code you’re looking to refactor.

Try some blanket improvements to refactor your code

Like most things in life, it’s usually best to start small. When you’re first getting started with refactoring code, keep it simple: open up Copilot Chat in your project and ask “how would you improve this?” Just like when you are asking GitHub Copilot to explain some code, you can specify what it looks at by highlighting sections of code or identifying specific files by using #file.

Here are some sample prompts:

  • How would you improve this?
  • Improve the variable names in this function.
  • #file:pageInit.js, #file:socketConnector.js Offer suggestions to simplify this code.

Copilot will then offer suggestions to improve the code in the way that you specified. This is great for getting started, but Copilot can do much more if you give it some guidance.

When working with any generative AI-powered developer tool, it is often useful to include more context in your prompts—ones that are more likely to get you the results you’re looking for. By being specific about what you want the tool to do, it focuses the efforts toward that end.

It’s a bit like if someone tells you to code something, and you have so many ideas and questions that you’re not quite sure where to begin. But if someone tells you they specifically want you to code a class that sorts a list, you can focus on the task at hand.

The prompts above don’t offer much specificity or context, which leaves Copilot to explore all the possible ways your code could be improved. The upside? You may see options that you might not have considered. The downside is some of the proposed solutions might not address your specific concerns.

Make a plan for refactoring your codebase

What do you want to do to your code? Do you want to make it more readable? Or do you want to find redundant code and remove it? Coming up with a plan for the improvements you want to make will help you to hit your goals. This comes back to making sure you understand your code. If you know how it works, you can come up with a plan for the type of improvements that you want to make.

Maybe your code base has a bunch of different scripts that all perform the same general function. You could strip out the code into a common module to import into each of the different scripts, making the code easier to change and maintain.

To do so, you can direct Copilot to look for these common code sections and to pull them into a single module.

Here’s a sample prompt:

Inspect all my js files for GitHub API calls and create a new class that will manage all the GitHub API calls.

Now that we have provided some guidance and additional context, Copilot will provide suggestions targeting this specific improvement that we want to make to our code.

You can also provide a laundry list of tasks, or ask Copilot to keep things in mind while it is doing the refactoring.

In that vein, here’s a sample prompt to consider:

Can you refactor the GitHubController class to:
- remove nested logic structures
- make the code more concise
- while doing this, check if the code is safe and add comments if not

The takeaway here is Copilot is very good at taking directions—and the more specific your directions are, the more it will generate outputs in line with your intended end goal.

For more guidance on creating good prompts, see our documentation on prompt engineering for GitHub Copilot.

A real-world example: Using GitHub Copilot to refactor code

Sometimes the best way to understand something is to see it in use. To help with this, we wanted to share an experience where we needed to use GitHub Copilot to refactor our own code, interspersed with some general guidance and pointers.

It started with a couple of organizations independently requesting help with their individual large migration projects, which involved moving from other data centers into tens of thousands of repositories on GitHub. After building a proof of concept, we started creating individual systems, each tailored to the needs of the individual customer and their unique systems. While we were doing this, a third organization made a similar request for help, and we realized this was a common need.

At this point in time, we had two systems that were both suited for large-scale migrations, but each of them was heavily customized for the original company making the request. We quickly realized the best solution involved refactoring our code to improve its modularity so we could use it across different organizations. This would not be easy—the codebase was made up of several different scripts and workflows with a lot of moving parts. And that’s when we turned to Copilot for help.

First we came up with a plan. We created a set of high-level goals and used these to guide us during the refactoring process. We wanted to make sure the code was:

  • Modular and reusable for different organizations: The code should be organized into small, self-contained modules that could be reused and combined for new functionality.
  • Maintainable: The code should be easy to maintain and extend as needed. That meant making it well-organized, well-documented, and easy to understand.
  • Customizable for different organizations: The code should be flexible enough to meet the unique needs of each organization.
  • Following coding standards and best practices: The code should be consistent, readable, and easy to understand.

With this plan in place, it was time to ask Copilot for help.

Step 1: Creating the initial module

Our first step was creating a common module we could import into each of the different scripts. This would allow us to reuse the same code across many different scripts, making it easier to maintain and extend. We created a skeleton of a module called gh-migrations. Then we used Copilot to fill in the details.

Here was the prompt we gave Copilot:

I am creating a module, gh-migrations, which will hold common functionality to be used through out my project. I have already created an index.js for the module. Please inspect the other js files for GitHub API calls, create a new class for the module which will manage all GitHub API calls. This class should also account for rate limiting and errors. Do not make edits to the javascript files, rather identify the API calls, and add the functionality to the new GitHub API class.

And here was Copilot’s response:

I'll help create a GitHub API management class based on the API calls found in the provided files. Here's a step-by-step solution:

1. From analyzing the files, I identified these common GitHub API operations: 
  * Issues creation and updates
  * Issue search
  * Rate limit handling (403 errors)
  * Common error handling patterns

2. I'll create a class that encapsulates these operations with proper error handling and rate limiting.

.github/lib/gh-migrations/index.js
Here's the GitHub API management class implementation:

<code>

This implementation:

1. Creates a GitHubApiManager class that handles all GitHub API interactions
2. Implements automatic rate limiting retry logic in withRateLimit
3. Provides methods for common operations: 
  * createIssue: Creates a new issue
  * updateIssue: Updates an existing issue
  * searchIssues: Searches for issues using GitHub's search API
  * findIssueByTitle: Helper method to find issues by title
  * getIssue: Gets a specific issue by number

Usage example:

<code>

The class handles:
  * Automatic retry on rate limits
  * Consistent error handling
  * Repository context management
  * Common GitHub API operations used across the codebase

This centralizes all GitHub API interactions and makes the code more maintainable and consistent.

After reviewing the code (as you should always do!), we made the recommended changes. The next step was putting these changes into a separate file while ensuring the index.js file could reference it.

Here was the prompt we entered for Copilot:

Rename the class GitHubApiManager to GHApi and put it in a separate file that is referenced in the index.js file.

And here was Copilot’s response:

I'll help you split the code into two files. Here's the step by step solution:

1. Create a new file gh-api.js for the GHApi class
2. Update index.js to export the renamed class from the new file

.github/lib/gh-migrations/gh-api.js
Create a new file containing the renamed class:

<code>

.github/lib/gh-migrations/index.js
Update the index file to export the renamed class from the new file:

<code>

The changes:
1. Created a new file gh-api.js with the renamed class
2. Moved all the class implementation to the new file
3. Updated the class name from GitHubApiManager to GHApi
4. Modified index.js to require and export the class from the new file

Now consumers of this module can continue to import it the same way, but the implementation is better organized.

After making these changes, we then had to repeat the process for each of the files that contained GitHub API calls. Be aware, we didn’t want to refactor the code directly at this stage. Instead, we wanted to create a common module we could use for refactoring code later.

Here was the prompt we entered for Copilot:

The gh-api.js file is a new class that will be used to manage all GitHub API calls. Please review the other javascript files for GitHub API calls to be added to gh-api.js. Do not edit the javascript files, only add new functionality to gh-api.js.

And here was Copilot’s response:

I'll analyze the JavaScript files and add the missing API functionality to the GHApi class.

.github/lib/gh-migrations/gh-api.js
Add methods for issue operations, searching, and deletion based on the API calls found in migration.js and application.js:

<code>

This implementation adds all the GitHub API functionality found in the other files:

1. From migration.js:
  * createComment for updating issues with comments
  * getIssue and isMigrationIssue for checking migration status
2. From application.js:
  * searchIssues and searchIssuesByTitle for finding issues
  * getIssueNodeId and deleteIssue for issue deletion via GraphQL
  * findJiraIssue helper method to get Jira ticket information

The methods maintain the same rate limiting and error handling patterns while providing a cleaner interface for the API operations.

Step 2: Adding new classes

Once we had the new GHApi class to handle the GitHub API, we want to create some reusable classes for different entities in our application. Since our application is a migration tool managed via GitHub Issues, we wanted to create classes for the following entities:

  • Migration issues represent repository migrations from various sources. They contain configuration and metadata about the repository and how the migration should be performed.
  • Batch issues represent a batch of migrations. They contain more high-level metadata about groups of individual migration issues such as custom application ids and status of the batch.
  • Team issues represent the migration of a group of users, their associated repositories, and the permissions to those repositories.
  • Rewire issues represent Azure DevOps pipelines rewire operations. They allow for the reconfiguration of Azure DevOps pipelines to point to the new GitHub repositories after a migration has been completed.

Here was the prompt we entered for Copilot:

Review the create-migration-issue.js and develop a new class called MigrationIssue that contains the properties associated with a migration. This shoud be added to the gh-migrations module where index.js is located.

And here was Copilot’s response:

I'll help create a new MigrationIssue class based on the migration configuration and status shown in the code. Here's the step-by-step solution:

1. Create a new file migration-issue.js in the gh-migrations directory
2. Update the index.js file to expose the new class
3. Extract configuration and status properties from the create-migration-issues.js file into the new class

migration-issue.js
Create a new class to represent a migration issue with all necessary properties and methods.

<code>

index.js
Update the index.js to expose the new MigrationIssue class.

<code>

The new MigrationIssue class encapsulates all the properties that were previously spread across various objects in the create-migration-issues.js file. It provides a clean interface for creating and managing migration issues, with helper methods for generating issue titles and source types.

You can now use this class in create-migration-issues.js by replacing the manual object creation with the MigrationIssue class. For example, the createMigrationConfig function could be replaced with:

<code>

The process for creating new classes for the other entities was similar to the above. We created new classes for BatchIssues, TeamIssues, and RewireIssues, each with their own properties and methods.

Step 3: Encapsulation

After we built out our entity classes, we realized they should manage their own state. This is a common pattern in object-oriented programming, where the class is responsible for managing its state and behavior. Remember our goal about following good coding standards?

The class should include methods to get and set the state of the object, as well as methods to perform actions on the object. It should also be responsible for utilizing the GitHub API and manage the state of the object rather than the client code. This will help standardize and protect the state of the object, as well as give the client code a simpler interface to work with.

Here was the prompt we entered for Copilot:

The MigrationIssue class should contain a initializer that uses the gh-api.js to create the resulting GitHub Issue. The initializer should take in an optional parameter called issueNumber, if the issueNumber is omitted the initializer should create a new Migration Issue and return the issue number created, if the issueNumber is passed to the initializer, the gh-api.js should be used to return the title and body of the issue which the class will parse to create the properties of the MigrationIssue.

And here was Copilot’s response:

I'll help you modify the code to add initialization logic to the MigrationIssue class. Here's the step-by-step solution:

1. Add a static method to parse issue body into configuration
2. Add initialization methods to handle both new and existing issues
3. Modify constructor to accept GHApi instance
4. Add method to generate issue body
5. Add method to create or load issue

migration-issue.js
Update the MigrationIssue class to handle initialization from GHApi.

<code>

The main changes include:

1. Constructor now accepts a GHApi instance as first parameter
2. Added parseIssueBody static method to parse configuration from issue body
3. Added generateIssueBody method to create the issue body format
4. Added initialize async method that either creates a new issue or loads an existing one
5. The initialize method returns the issue number in both cases

To use this updated class:

<code>

Remember how we said it’s always important to review suggestions from Copilot? In this case, the initialize method wasn’t connected to the constructor, like we would expect. We asked Copilot to address this issue with an iterative prompt.

Here was the prompt we entered for Copilot:

The MigrationIssue class has an initialize function that encapsulates functionality that should be included in the constructor. Rewire the constuctor method to include the initialzie function.

And here was Copilot’s response:

Let's modify the class to move the initialization logic into the constructor. Here's the step-by-step solution:

1. Make constructors async
2. Move initialization logic into constructor
3. Remove separate initialize method
4. Keep static parseIssueBody method

migration-issue.js
Move initialization logic into constructor.

<code>

The main changes:

1. Removed initialize method from the class
2. Added static create and load factory methods
3. Added save method to handle issue creation
4. Constructor remains synchronous but now only handles property initialization

Usage example:

<code>

This approach follows better object-oriented principles by:

1. Using factory methods for different creation scenarios
2. Keeping the constructor simple and synchronous
3. Separating issue creation into a distinct operation
4. Making the API more intuitive

In this case, Copilot suggested a different approach than we were thinking of with a factory method (which is a great way to handle different scenarios when creating or loading an issue). Even if it wasn’t what we were thinking, it worked and also kept the constructor clean and focused on just initializing the object. Moreover, the save method is a good way to encapsulate the logic for creating a new issue, and it makes the code more readable.

Now we just needed to repeat this process with each of the new classes we added.

Step 4: Final refactoring

After we built a common module, we needed to refactor the client code to make it much cleaner and easier to read and maintain. After that, we’d also be able to identify and add any missing functionality in the common module.

This was an iterative process, and we needed to go back and forth between the client code and the common module to make sure everything worked properly. Because of the way this project evolved, it afforded us the opportunity to make sweeping changes to the codebase. It’s much more common to make small, incremental changes to the codebase, especially if it’s code that’s actively in use. In both of these cases, don’t forget to write tests to ensure the code works as expected.

Here was the prompt we entered for Copilot:

Using the gh-migrations module, refactor the create-migration-issues.js

And here was Copilot’s response:

I'll help you refactor the create-migration-issues.js file to use the gh-migrations module. Here's the step-by-step solution:

1. Import the gh-migrations module
2. Create GHApi instance
3. Use MigrationIssue class for creating and managing migration issues
4. Simplify the main logic using the new classes

create-migration-issues.js
Refactor to use the gh-migrations module for better code organization and reusability.

<code>

The refactoring:

1. Removes redundant code by using the MigrationIssue class
2. Simplifies issue creation and management
3. Uses GHApi for GitHub API calls with built-in rate limiting
4. Removes duplicate code for different source types
5. Improves code organization and maintainability

The main changes:
  * Removed several helper functions as they're now part of the MigrationIssue class
  * Simplified the main logic flow
  * Added better error handling
  * Used structured configuration object
  * Maintained the same functionality while reducing code complexity

Now we needed to refactor the remaining scripts in the same manner. For example, this is how we used Copilot to help with refactoring the create-team-issues.js script.

Here was the prompt we entered for Copilot:

Using the gh-migrations module refactor the create-team-issues.js

And here was Copilot’s response:

I'll help you refactor the create-team-issues.js file to use the gh-migrations module. Here's the step-by-step solution:

1. Import the gh-migrations module
2. Replace manual issue creation with TeamIssue class
3. Simplify team creation logic using the new class
4. Maintain the same JiraIssue tracking functionality

create-team-issues.js
Refactor to use the gh-migrations module for creating team issues.

<code>

The refactoring:

1. Uses the TeamIssue class to manage team issue creation
2. Simplifies the code by removing redundant config and status objects
3. Uses GHApi for GitHub operations with built-in rate limiting
4. Maintains the same JiraIssue tracking functionality
5. Reduces code duplication by using a loop for team creation

The code is now more maintainable and follows the same pattern as the migration issues implementation.

From there, it was a matter of rinsing and repeating this process with each of our scripts.

By first creating the common module, we could guide Copilot and make sure that the final, refactored codebase was something we could use with multiple organizations. It gave us a foundation we could reuse and customize based on the needs of the system we were migrating.

Things to keep in mind

Sometimes refactoring code can be really easy, like our first example with the sequential if statements. But the more you dig into it, the more it grows, and you might find yourself facing down the Herculean task of trying to refactor a codebase that stretches across multiple files from a larger team of developers.

Speaking from experience: It can be daunting to even know where to start.

Remember to take a step back and start with the basics. Your first step should always be improving your understanding of the codebase you want to refactor. The more you know about what you’re starting out with, the greater chance that you will be able to think of ways to refactor it effectively. And once you come up with some ideas, you can always ask GitHub Copilot to help turn your vision into reality. It’s got your back and is more than willing to help.

Start using GitHub Copilot for free
Our free version of GitHub Copilot is included by default in personal GitHub accounts and VS Code to help you start new projects, manage existing repositories, and more.

Start using GitHub Copilot >

The post How to refactor code with GitHub Copilot appeared first on The GitHub Blog.

]]>
82544
GitHub Copilot: The agent awakens https://github.blog/news-insights/product-news/github-copilot-the-agent-awakens/ Thu, 06 Feb 2025 17:04:30 +0000 https://github.blog/?p=82456 Introducing agent mode for GitHub Copilot in VS Code, announcing the general availability of Copilot Edits, and providing a first look at our SWE agent.

The post GitHub Copilot: The agent awakens appeared first on The GitHub Blog.

]]>

When we introduced GitHub Copilot back in 2021, we had a clear goal: to make developers’ lives easier with an AI pair programmer that helps them write better code. The name reflects our belief that artificial intelligence (AI) isn’t replacing the developer. Instead, it’s always on their side. And like any good first officer, Copilot can also fly by itself: for example, when providing pull request feedback, autofixing security vulnerabilities, or brainstorming on how to implement an issue.

Today, we are upgrading GitHub Copilot with the force of even more agentic AI – introducing agent mode and announcing the General Availability of Copilot Edits, both in VS Code. We are adding Gemini 2.0 Flash to the model picker for all Copilot users. And we unveil a first look at Copilot’s new autonomous agent, codenamed Project Padawan. From code completions, chat, and multi-file edits to workspace and agents, Copilot puts the human at the center of the creative work that is software development. AI helps with the things you don’t want to do, so you have more time for the things you do.

Agent mode available in preview 🤖

GitHub Copilot’s new agent mode is capable of iterating on its own code, recognizing errors, and fixing them automatically. It can suggest terminal commands and ask you to execute them. It also analyzes run-time errors with self-healing capabilities.

In agent mode, Copilot will iterate on not just its own output, but the result of that output. And it will iterate until it has completed all the subtasks required to complete your prompt. Instead of performing just the task you requested, Copilot now has the ability to infer additional tasks that were not specified, but are also necessary for the primary request to work. Even better, it can catch its own errors, freeing you up from having to copy/paste from the terminal back into chat.

Here’s an example where GitHub Copilot builds a web app to track marathon training:

To get started, you’ll need to download VS Code Insiders and then enable the agent mode setting for GitHub Copilot Chat:

Settings screen for Visual Studio Code showing the words 'Copilot Agent' in the settings search box, and the option for Chat Agent: Enabled activated

Then, when in the Copilot Edits panel, switch from Edit to Agent right next to the model picker:

Agent mode will change the way developers work in their editor; and as such, we will bring it to all IDEs that Copilot supports. We also know that today’s Insiders build isn’t perfect, and welcome your feedback as we improve both VS Code and the underlying agentic technology in the coming months.

Copilot Edits, now GA in VS Code 🎉

Announced at GitHub Universe in October last year, Copilot Edits combines the best of Chat and Inline Chat with a conversational flow and the ability to make inline changes across a set of files that you manage. The feedback you provided in the past was instrumental in shipping this feature as GA in VS Code today. Thank you!

In Copilot Edits you specify a set of files to be edited, and then use natural language to ask GitHub Copilot for what you need. Copilot Edits makes inline changes in your workspace, across multiple files, using a UI designed for fast iteration. You stay in the flow of your code while reviewing the suggested changes, accepting what works, and iterating with follow-up asks.

Visual Studio Code showing multiple files added to Copilot Edit

Behind the scenes, Copilot Edits leverages a dual-model architecture to enhance editing efficiency and accuracy. First, a foundation language model considers a full context of the Edits session to generate initial edit suggestions. You can choose the foundation language model that you prefer between: OpenAI’s GPT-4o, o1, o3-mini, Anthropic’s Claude 3.5 Sonnet, and now, Google’s Gemini 2.0 Flash. For the optimal experience, we developed a speculative decoding endpoint, optimized for fast application of changes in files. The proposed edits from the foundation model are sent to the speculative decoding endpoint that will then propose those changes inline in the editor.

Copilot Edits works because it puts you in control, from setting the right context to accepting changes. The experience is iterative: when the model gets it wrong, you can review changes across multiple files, accept good ones and iterate until, together with Copilot, you arrive at the right solution. After accepting changes, you can run the code to verify the changes and, when needed, undo in Copilot Edits to get back to a previous working state. Copilot Edits is in the Secondary Side Bar (default on the right) so that you can interact with views in the Primary Side Bar, such as the Explorer, Debug, or Source Control view, while you’re reviewing proposed changes. For example, you can have unit tests running in the Testing view on the left, while using the Copilot Edits view on the right, so that in every iteration you can verify if the changes Copilot Edits proposed are passing your unit tests.

Using your voice is a natural experience while using Copilot Edits. Just talking to Copilot makes the back and forth smooth and conversational. It almost feels like interacting with a colleague with area expertise, using the same kind of iterative flow that you would use in real-life pair programming.

Next on our roadmap is to improve the performance of the apply changes speculative decoding endpoint, support transitions into Copilot Edits from Copilot Chat by preserving context, suggest files to the working set, and allow you to undo suggested chunks. If you want to be among the first to get your hands on these improvements, make sure to use VS Code Insiders and the pre-release version of the GitHub Copilot Chat extension. To help improve the feature, please file issues in our repo.

Beyond the GA in VS Code, Copilot Edits is now in preview for Visual Studio 2022.

Project Padawan: SWE agents on GitHub

We’re excited to share a first look at our autonomous SWE agent and how we envision these types of agents will fit into the GitHub user experience. When the product we are building under the codename Project Padawan ships later this year, it will allow you to directly assign issues to GitHub Copilot, using any of the GitHub clients, and have it produce fully tested pull requests. Once a task is finished, Copilot will assign human reviewers to the PR, and work to resolve feedback they add. In a sense, it will be like onboarding Copilot as a contributor to every repository on GitHub. ✨

Behind the scenes, Copilot automatically spins up a secure cloud sandbox for every task it’s assigned. It then asynchronously clones the repository, sets up the environment, analyzes the codebase, edits the necessary files, and builds, tests, and lints the code. Additionally, Copilot takes into account any discussion within the issue or PR, and any custom instruction within the repository, so it understands the full intent of its task, as well as the guidelines and conventions of the project.

And just as we did with Copilot Extensions and the model picker in Copilot, we will also provide opportunities to integrate into this AI-native workflow and work closely with partners and customers in a tight feedback loop. We believe the end-state of Project Padawan will result in transforming how teams manage critical-yet-mundane tasks, such as fixing bugs or creating and maintaining automated tests. Because ultimately, it’s all about empowering developers by allowing them to focus on what matters, and letting copilots do the rest. And don’t worry. We will have patience, so the agent won’t turn to the dark side. 😉

Awaken the agent with agent mode for GitHub Copilot in VS Code today.

The post GitHub Copilot: The agent awakens appeared first on The GitHub Blog.

]]>
82456
Modernizing legacy code with GitHub Copilot: Tips and examples https://github.blog/ai-and-ml/github-copilot/modernizing-legacy-code-with-github-copilot-tips-and-examples/ Wed, 22 Jan 2025 17:00:32 +0000 https://github.blog/?p=82109 Learn how to modernize legacy code with GitHub Copilot with real-world examples.

The post Modernizing legacy code with GitHub Copilot: Tips and examples appeared first on The GitHub Blog.

]]>

Let’s talk about legacy code—you know, the code that’s old enough to drive and definitely old enough to haunt your dreams. Maybe it’s a sprawling COBOL system or an early version of C++ written back when “Y2K” was a serious concern. Now, decades later, you’re being asked to “look into it” and modernize it (while wondering if you need to send a note to that person who retired a few years ago and may know how this thing works).

This is where AI coding tools like GitHub Copilot can offer some much-needed assistance—and I’m speaking from personal experience. In my day-to-day work, I often help organizations in the public sector, finance, and retail to deploy GitHub Copilot, and one question I hear again and again is, “How can we use Copilot to modernize legacy systems?”

In this article, I’ll walk you through just that using one of the most infamous old-school languages: COBOL. This isn’t because I’m a masochist—lots of critical systems still use COBOL. But while it still does what it’s supposed to do, there are a lot of integration and compatibility challenges (it is pretty old), and the number of developers who can read and write COBOL isn’t exactly what it used to be. All of this makes COBOL programs that much harder to modernize. In our example, we’ll take an account management system written in COBOL and modernize it into Node.js.

Here’s something fun, too: Everything we share below can be done with any GitHub Copilot tier—including our free tier.

With that in mind, I’ll show you how Copilot can help you navigate and modernize legacy code, including the common pain points like wrangling technical debt, migrating to modern frameworks, and dealing with that one cryptic variable named X. (Seriously, why is it always X?)

So, grab your debugger and buckle up.

The challenges of legacy code

Let’s face it: working with legacy code can feel like stepping into a time machine, except instead of a cool DeLorean, you’re handed a dusty, 10,000-line COBOL program with zero documentation, and a warning that, if this breaks, the entire payroll system goes down.”

No pressure.

The truth is, modernizing legacy code isn’t just about updating syntax or swapping out old libraries. You’re more than likely staring at technical debt, compatibility issues, and the knowledge that the people who originally wrote this code are happily retired or have long since left your organization.

Here’s a closer look at the common pain points and challenges any developer dealing with legacy systems will likely face:

  • Technical debt: Legacy systems are often riddled with technical debt accumulated over years—or even decades. Hardcoded logic, sprawling dependencies, and “temporary” fixes that somehow became permanent all add up to a brittle, unmaintainable mess.
  • Integration challenges: Modernizing legacy systems doesn’t happen in isolation. These systems usually need to integrate with newer tech stacks, and that’s where things get messy. APIs may not line up, data formats might clash, and the whole thing starts feeling like a house of cards held together with duct tape.

  • Data migration and compatibility: Legacy systems often come with outdated data formats or storage methods that make modernizing them a logistical headache. Converting and migrating this data while ensuring compatibility with modern systems is one of the trickiest parts of any project. It’s like trying to move a fragile vase across town in a bumpy truck—one wrong move and everything’s shattered.

  • Cost and resourcing: Modernizing legacy systems isn’t cheap. It takes time, money, and skilled engineers who are often already stretched thin. Add in organizational resistance—because, “hey, if it’s not broken, why fix it?”—and you’ve got a recipe for frustration.

  • Performance and scalability limitations: Legacy systems often struggle with modern performance requirements due to hardware limitations, less efficient code, and application architectures.

  • Security vulnerabilities: Here’s the thing about legacy code: it was often written long before today’s security standards even existed. Back then, “security” might have meant locking the server room door, not safeguarding against SQL injection or ransomware. As a result, legacy systems can be riddled with vulnerabilities that modern attackers are more than happy to exploit.

  • Testing: The final boss of legacy code modernization? Testing. Every small change introduces the risk of breaking something elsewhere and you may not even know it until weeks later.

All of this means that modernizing legacy systems isn’t just a nice-to-have—but that doesn’t make it any easier. And since you’re reading this article, there’s a good chance you’ve been asked to help modernize some legacy code.

It may feel like a big ask, but for all those reasons above (and then some) it’s super important.

How GitHub Copilot helps you refactor and modernize legacy code

Modernizing legacy code can feel like an uphill battle, especially when you’re diving into unfamiliar languages like COBOL. But GitHub Copilot makes this process faster, smoother, and—dare I say—less painful.

Before Copilot, I spent a lot of time on Google and Stack Overflow searching for information about whatever legacy language or system I was about to dive into. Don’t get me wrong, it was helpful, but it took a lot of time, and took me away from the code itself. With Copilot, I can stay in my IDE and my flow state while asking my AI programmer these questions instead. Nine times out of 10 it gives me the right answer, or points me in the right direction. That speed—and not having to break out of my flow—is really what’s so impactful for me.

Here are a few best practices I follow when using Copilot to modernize legacy code:

  • Use slash commands in Copilot Chat: These are shortcut commands you can use to explain code, generate tests, fix tests that may be failing, and more. They’re incredibly helpful when it comes to performing simple or complex functions—just highlight the code you want to perform an action on, and then enter the slash command in Copilot Chat to get started. Some of the slash commands I find most helpful include:
    • /explain explains how the code in your active editor works
    • /tests generates unit tests for the selected code
    • /fixTestFailure finds and fix failing tests
    • /fix finds and fix general problems in the selected code
  • Try chat participants to scope your prompts: In Copilot Chat, you can manually use a number of chat participants—or AI domain experts—to perform specific functions in your IDE, workspace, Azure instance, or terminal. While Copilot Chat will infer chat participants from your prompts, manually accessing them can help you hone in on specific functions. I typically use the chat participant @workspace (which you’ll see in our example below) to consider my larger codebase. Other chat participants include: @vscode when you need help with VS Code commands and features, @terminal for shell-based commands and debugging, and @azure for any help with Azure you may need.
  • Use chat variables to improve prompt context: This is something you should always use (I do, as you’ll soon see). Chat variables help you include specific context in your prompts and are incredibly useful for focusing Copilot on a specific outcome you’re trying to achieve. These include:

    • #file to include a specific file for context (my personal favorite)
    • #git to get information about your current Git repository
    • #editor to get the visibly source code in the active editor
    • #selection to get the current selection in the active editor
    • #terminalLastCommand to get the active terminal’s last run command
    • #terminalSelection to get the active terminal’s selection

    You can also type # in Copilot Chat to see a full list of chat variables.

  • Using GitHub skills for Copilot: Copilot’s GitHub-specific skills expand the type of information Copilot can provide. To access these skills in Copilot Chat in VS Code, include @github in your question.
    When you add @github to a question, Copilot dynamically selects an appropriate skill, based on the content of your question. You can also explicitly ask Copilot Chat to use a particular skill. You can do this in two ways:

    • Use natural language to ask Copilot Chat to use a skill. For example, @github Search the web to find the latest GPT4 model from OpenAI.
    • To specifically invoke a web search you can include the #web variable in your question. For example, @github #web What is the latest LTS of Node.js?
    • Current available skills
  • Start small: Legacy codebases can be massive and intimidating, so don’t try to refactor everything at once. Focus on individual functions or modules before diving into the entire system. Use Copilot to streamline these smaller refactors—it’ll help you build momentum and confidence as you go.
  • Write tests first: Before changing a single line of code, ensure you have tests that validate the current behavior (a practice known as test-driven development). You can use Copilot to generate unit tests that validate the original behavior via the slash command /tests in Copilot Chat in your IDE. These tests act as a safety net, ensuring that any changes you make won’t accidentally break something critical.

  • Embrace version control: Version control is essential when refactoring legacy systems. Use GitHub’s built-in tools like branches and pull requests to test and review your changes in isolated environments. This way, you can safely iterate without disrupting the main codebase.

  • Always review Copilot’s suggestions: Copilot’s suggestions are incredibly accurate and insightful, but human oversight is key. Always review the changes Copilot makes to ensure they align with your system’s context and coding standards.

Modernizing a legacy COBOL application with GitHub Copilot: A practical example

Ok, let’s jump into our code. Like I said earlier, we’ll be looking at an account management system written in COBOL and modernizing it into Node.js.

Notably, every step I’m going to walk you through below works in all tiers of GitHub Copilot—including the Free version. And just in case you’re wondering, I use OpenAI’s GPT-4o model (in the Free tier of Copilot you can choose between that and Anthropic’s Claude 3.5 Sonnet).

You can head to my demo repository yourself and fork it if you want to follow along (I include step-by-step instructions there, too).

A GitHub repository named "modernize-legacy-cobol-app" showcasing a project for modernizing legacy COBOL code. The repository has one branch and no tags. The file structure includes folders for .devcontainer and .vscode configurations, along with COBOL source files (main.cob, data.cob, operations.cob), documentation files (README.md, TESTPLAN.md), and a .gitignore file. The most recent commit message highlights updates to the README and .gitignore for project modernization.

This repository includes three key files—data.cob, main.cob, and operations.cob—that work together to perform various operations like crediting, debiting, viewing the account balance balance, and even exiting the program.

An important note: since Copilot is powered by generative AI models, which are nondeterministic in terms of outputs, you will likely get slightly different responses even if you follow my step-by-step instructions.

Step 1: Compile and run the program

You have two options here: you can either install a COBOL compiler (I recommend the open source GnuCOBOL compiler) or open up the terminal in a GitHub Codespaces environment (this is what I do since it’s a bit simpler). Copilot will work in either.

To install GnuCOBOL, use this brew command when using MacOS:

brew install gnucobol 

If you decide to use Codespaces or an Ubuntu Linux system, you need to run the following command to install the COBOL compiler in your instance:

sudo apt-get update && \
sudo apt-get install gnucobol

From there, you need to compile the code, link the files, and create an executable with the following command:

cobc -x main.cob operations.cob data.cob -o accountsystem

Step 2: Explain the files and code

While I don’t deal with COBOL in my day-to-day work normally, my next step is simple: find out what on Earth these files are doing. That’s where Copilot enters the picture. It’s great at helping explain (and document) code, including legacy code like we’re working with now.

Here’s the first prompt I use in Copilot Chat:

/explain #file:main.cob #file:operations.cob #file:data.cob Can you please create a high level overview of the app. It will be great if you can explain each file in detail and how they are linked.

Note how I use a combination of a slash command, pointing to specific files using the #file chat variable, and a prompt. This helps Copilot focus on exactly what I want explained by pointing it at the right files.

Copilot returns around a rather lengthy explanation that I’ll excerpt here:

Sure! Here's a high-level overview of the COBOL application, along with detailed explanations of each file and how they are linked together.
High-Level Overview
This COBOL application simulates an account management system. It allows users to view the current balance, credit the account, debit the account, and exit the application. The application is divided into three main COBOL source files: main.cob, operations.cob, and data.cob.

This alone gives me a good starting point—and Copilot’s full response offers far more detail on the logic of each file, the links between them, and the different sections of code.

Step 3: Chart out the data flow between the files

But I still need a better idea of how these three files are working together in our executable. This is where Copilot, once again, proves to be incredibly helpful with the @workspace command.

A little explanation first: entering @workspace in Copilot Chat lets you ask questions about your codebase including finding code, making plans for complex edits, explaining higher-level concepts, and more (VS Code has some good documentation on using @workspace).

For this exercise, I use @workspace to prompt Copilot for a data flow diagram while asking it to output it in a Mermaid diagram so I can clearly visualize it.

@workspace can you create a sequence diagram of the app showing the data flow of the app. Please create this in mermaid format so that I can render this in a markdown file.

Copilot then outputs a full sequence diagram in Mermaid that shows me exactly how this application works, rendered as a Markdown file. This looks like the following:

A Copilot-generated data flow diagram for a COBOL application, illustrating interactions between four components: User, MainProgram, Operations, and SubProgram. The diagram maps how the user initiates the application, selects options, and how data flows between the main program, operations module, and subprogram. It details processes such as balance inquiry, credit operations, and debit operations, showing the sequence of calls and returns among the COBOL files while updating the final balance. This diagram is featured in a GitHub blog about modernizing legacy COBOL code with GitHub Copilot.

This helps me visually understand how this application is functioning and how the data is flowing through the program.

Step 4: Generate a test plan

In our demo repository, you can see that we currently have no tests. That’s not great, so the next step is to generate tests.

We’ll use the @workspace command again with the following prompt:

@workspace The current Cobol app has no tests. Can you please create a test plan of current business logic that I can use to validate with business stakeholders about the current implementation.

Later I would like to use this test plan to create unit and integration tests in a node.js app. I am in the middle of transforming the current Cobol app to a node.js app.

The test plan should include the following:

1. Test Case ID
2. Test Case Description
3. Pre-conditions
4. Test Steps
5. Expected Result
6. Actual Result
7. Status (Pass/Fail)
8. Comments

Please create the test plan in a markdown table format. The test plan should cover all the business logic in the current Cobol app.

Copilot will then generate a test plan I can use. But in my instance, I had to take one more step: ask Copilot to generate the markdown file format for my test plan to insert it as a new file.

Convert this to markdown syntax to insert as a new file

Step 5: Convert the files from COBOL to Node.js

Now, it’s time to convert our three COBOL files into a Node.js application. Here, it’s important to use good prompting practices: provide context, give clear directions, and be specific about the outcome you want to achieve.

We start by creating a Node.js project directory:

mkdir node-accounting-app
cd node-accounting-app

From there, we iteratively convert the files main.cob, operations.cob, and data.cob into Node.js files. I’ll use the code in main.cob as the example here. Here’s my prompt for reference:

Can you convert code in #file:main.cob to node.js?

Copilot then generates the following answer:

Sure! Here is the equivalent Node.js code for the 

main.cob

 file. This code will simulate the same account management system functionality.

### COBOL Code: 

main.cob


```COBOL
IDENTIFICATION DIVISION.
       PROGRAM-ID. MainProgram.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  CONTINUE-FLAG      PIC X VALUE 'Y'.
       01  USER-CHOICE        PIC 9.
       01  FINAL-BALANCE      PIC 9(6)V99 VALUE 1000.00.

       PROCEDURE DIVISION.
           PERFORM UNTIL CONTINUE-FLAG = 'N'
               DISPLAY "1. View Balance"
               DISPLAY "2. Credit Account"
               DISPLAY "3. Debit Account"
               DISPLAY "4. Exit"
               ACCEPT USER-CHOICE

               EVALUATE USER-CHOICE
                   WHEN 1
                       CALL 'Operations' USING 'TOTAL'
                   WHEN 2
                       CALL 'Operations' USING 'CREDIT'
                   WHEN 3
                       CALL 'Operations' USING 'DEBIT'
                   WHEN 4
                       MOVE 'N' TO CONTINUE-FLAG
                       DISPLAY "Exiting the program. Goodbye!"
                   WHEN OTHER
                       DISPLAY "Invalid choice. Please try again."
               END-EVALUATE
           END-PERFORM
           STOP RUN.
```

### Node.js Code: `main.js`
```javascript
const readline = require('readline');

let continueFlag = 'Y';
let finalBalance = 1000.00;

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function displayMenu() {
    console.log("1. View Balance");
    console.log("2. Credit Account");
    console.log("3. Debit Account");
    console.log("4. Exit");
}

function handleUserChoice(choice) {
    switch (choice) {
        case '1':
            viewBalance();
            break;
        case '2':
            creditAccount();
            break;
        case '3':
            debitAccount();
            break;
        case '4':
            continueFlag = 'N';
            console.log("Exiting the program. Goodbye!");
            rl.close();
            break;
        default:
            console.log("Invalid choice. Please try again.");
            promptUser();
            break;
    }
}

function viewBalance() {
    console.log(`Current balance: ${finalBalance.toFixed(2)}`);
    promptUser();
}

function creditAccount() {
    rl.question("Enter credit amount: ", (amount) =&gt; {
        amount = parseFloat(amount);
        if (!isNaN(amount) &amp;&amp; amount &gt; 0) {
            finalBalance += amount;
            console.log(`Amount credited. New balance: ${finalBalance.toFixed(2)}`);
        } else {
            console.log("Invalid amount. Please try again.");
        }
        promptUser();
    });
}

function debitAccount() {
    rl.question("Enter debit amount: ", (amount) =&gt; {
        amount = parseFloat(amount);
        if (!isNaN(amount) &amp;&amp; amount &gt; 0) {
            if (finalBalance &gt;= amount) {
                finalBalance -= amount;
                console.log(`Amount debited. New balance: ${finalBalance.toFixed(2)}`);
            } else {
                console.log("Insufficient funds for this debit.");
            }
        } else {
            console.log("Invalid amount. Please try again.");
        }
        promptUser();
    });
}

function promptUser() {
    if (continueFlag === 'Y') {
        displayMenu();
        rl.question("Select an option: ", handleUserChoice);
    }
}

promptUser();
```

This Node.js code replicates the functionality of the COBOL main.cob file, providing a simple command-line interface for viewing the balance, crediting the account, debiting the account, and exiting the application.

Simple enough, right? Of course, we need to review this code—it’s always a requirement to trust but verify when using AI coding tools. After review, I execute similar prompts for the other two files.

Once we finish translating each COBOL file into Node.js, we need to link all the new files to initialize, install, and run the Node application. I use the following prompt to do that:

link all node.js files to work together in one accounting application and with npm commands to initialize and install and to run the app.

Copilot returns the needed program logic while linking everything together, so I just need to execute the main.js file after initializing npm.

Step 6: Generate unit and integration tests

For our last step, we generate unit and integration tests to ensure all of our new Node.js code works. Here, I again use @workspace in Copilot Chat. My prompt looks like this:

@workspace I would like to create unit and integration tests cases form the test plan mentioned in #file:TESTPLAN.md file The node.js code is in node-accounting-app folder and I am looking to generate tests for #file:operations.js file. Use a popular testing framework and also provide all the dependencies required to run the tests.

Copilot generates a number of tests in Jest, a JavaScript testing framework, with a full, step-by-step guide on how to implement and run them.

In Copilot’s own words: “This test plan covers the main functionalities of the COBOL application, including viewing the balance, crediting the account, debiting the account, and exiting the application. The test cases are implemented using Jest, a popular testing framework for Node.js. Validate this test plan with the business stakeholders to ensure it meets the business requirements. Once validated, you can use this plan to create corresponding unit tests and integration tests for the Node.js application.”

Remember, you can always ask Copilot to generate tests for edge cases, or even prompt it to find these cases by asking if there are any additional tests you—or even it—may have forgotten.

Take this with you

Modernizing legacy code doesn’t have to be a headache. With GitHub Copilot, you have a powerful tool to accelerate the process, stay in your flow, and focus on what matters most: writing great code. Here’s what to keep in mind as you embark on your modernization journey:

  • Prompting best practices are key: The quality of your prompts determines the quality of Copilot’s suggestions. Provide clear context, break down complex tasks into smaller steps, provide examples, and give Copilot specific goals to work toward. This makes your workflow smoother and your results more precise.
  • Modernizing code without scrolling through Google: Copilot reduces the grind of converting, refactoring, and rewriting legacy code by bringing answers straight to your IDE. Whether it’s migrating COBOL to Node.js or optimizing outdated logic, Copilot gets you there faster—no endless Googling required.
  • There’s a free tier of GitHub Copilot: Don’t forget—GitHub Copilot has a free version available for anyone to use, including you. All you need is a free GitHub account; no subscription needed.

Refactoring legacy code might feel like a daunting challenge, but it’s also an opportunity to learn, improve, and build something better. With GitHub Copilot by your side, you’re equipped to handle even the most stubborn systems. So, dive in, experiment with prompts, and start turning that dusty code into something modern and efficient. You’ve got this—and Copilot’s got your back.

Start using GitHub Copilot for free
Our free version of GitHub Copilot is included by default in personal GitHub accounts and VS Code to help you start new projects, manage existing repositories, and more.

Start using GitHub Copilot >

The post Modernizing legacy code with GitHub Copilot: Tips and examples appeared first on The GitHub Blog.

]]>
82109
How to use GitHub Copilot: What it can do and real-world examples https://github.blog/ai-and-ml/github-copilot/what-can-github-copilot-do-examples/ Wed, 08 Jan 2025 17:00:53 +0000 https://github.blog/?p=81844 How Copilot can generate unit tests, refactor code, create documentation, perform multi-file edits, and much more.

The post How to use GitHub Copilot: What it can do and real-world examples appeared first on The GitHub Blog.

]]>

Since the free version of GitHub Copilot launched last month, you’ve asked lots of questions, like “Is it free for everyone?” (Yes!), “Can Copilot make changes to multiple files?” (Yes again!), “What’s the name of Copilot’s mascot?” (It doesn’t have a name…yet.), and most of all: “What can GitHub Copilot actually do?”

The short answer is a lot. The longer answer covers a bunch of different use cases, workflows, coding languages, and much more, so it’s a good thing we have some space to talk about it!

We’ll update this list as GitHub Copilot continues to evolve and we add new, awesome features like we’ve been doing since we first launched it a few years ago.

Ready? Let’s go.

What is GitHub Copilot?

GitHub Copilot is a generative AI tool that functions as a coding assistant to help you write code faster and so much more.

One of the main advantages of Copilot is it draws context from your coding environment, open tabs, and your GitHub projects (including your pull requests, issues, discussions, and codebase). For example, you can ask Copilot Chat to provide a summary of code in a given repository or explain how pieces of code in your app work. In either case, it will provide an answer with the contextual knowledge of your project. You can also ask Copilot to help document, debug, and refactor code—all without the need to context switch or copy over large sections of code to another application.

GitHub Copilot is available for anyone to use with GitHub Copilot Free. If you want more advanced Copilot capabilities, we offer Pro, Business, and Enterprise tiers, too. With these options, you can pick the solution that works best for you. For your reference, we’ve included a section on the different access tiers.

How are developers using GitHub Copilot?

As GitHub Copilot capabilities continue to grow, developers are using it in a number of ways including:

  • Getting code completion suggestions while they type in the IDE
  • Asking Copilot Chat to explain how a section of code works
  • Generating tests and helping to fix code that fails a given test
  • Migrating code to a different language
  • Refactoring existing code
  • Explaining code you’re working with
  • Using Copilot Extensions to work with other applications and tools in your tech stack (you can even build a custom one)
  • Generating documentation to describe a set of changes in a pull request

What GitHub Copilot can do (and how to use it)

So, how can GitHub Copilot help you in your projects? Let’s jump in.

What’s new in GitHub Copilot

This is a living document, so we’ll update this section with the latest and greatest from Copilot as it continues to evolve.

Choose the AI model that powers GitHub Copilot

With GitHub Copilot, you can choose the model you want to work with. In Copilot Free you have access to Anthropic’s Claude 3.5 Sonnet and OpenAI’s GPT-4o models. And if you use one of the Copilot paid tiers, you’ll have more models to choose from to customize your experience.

In-line code completion

When coding, GitHub Copilot can offer coding suggestions directly in your coding environment. It can both provide code to complete what you’re currently working on or respond to natural language prompts to generate code. Developers often use this for generating boilerplate code and common coding snippets—such as the getter and setter functions of variables.

But Copilot isn’t limited to simple and repetitive code completion. Using Copilot Chat, you can tell it what you want it to do by describing the task in plain language or the /new slash command, it will then provide some code suggestions to help you get started.

💡 Pro tip: Getting the most out of this feature requires you to craft good prompts.You can learn more about effective prompting with GitHub Copilot in our documentation on prompt engineering.

Generate unit tests

Writing unit tests requires knowing the limits, edge cases, and what might cause failures in your code. Since Copilot knows about your project on GitHub and what you’re working on in your IDE, it can create unit tests to help you.

To do this, select a given block of code. Then either right-click and use the context menu or the /tests slash command. Copilot will then analyze your code and try to provide suggestions for valid inputs, edge cases, and invalid inputs.

For additional guidance on using GitHub Copilot to create unit tests, check out this blog about creating unit tests and take a look at this docs page of sample prompts.

Explain and document existing code

You can tap into GitHub Copilot’s knowledge of coding patterns to ask it to help explain how a block of code works. This is particularly useful if you’re onboarding to a new project, especially if it’s in a language you don’t have a lot of experience in.

To use this feature, select some code and use either the context menu or the /explain slash command. Copilot will then explain what the code is doing—and then generate documentation on it with another prompt.

This isn’t just useful for onboarding or making sure you understand a piece of code. You can also use this as a building block for other tasks such as helping to translate code from one language to another.

For some sample prompts, check out our docs on explaining legacy code and on explaining complex logic.

Upgrading a framework you’re working with

If you’re tasked with upgrading a codebase to a new version of a framework, it’s not as easy as recompiling the project in the new version. That often results in several errors that you need to track down and resolve. GitHub Copilot can help you here.

You can just ask why your code is producing errors. From there, you can have Copilot provide suggestions on how to fix your code to make it compliant with the new version of the framework. Then ask Copilot for suggestions on how to update the code to fit in a new framework.

Explain a codebase (or a repository on GitHub)

Trying to understand a new codebase? Ask Copilot what a repository does or to summarize key components and it will provide a summary. To get started, click the Copilot icon in the top-right corner of your screen and ask a question. You can also prompt Copilot to debug your workflows with GitHub Actions. If you want to focus Copilot’s attention, you can highlight individual files or folders in a repository, too.

💡 Pro tip: Use Copilot as a chat assistant directly on github.com with a full, natural-language interface.

Translate code to a new language

Let’s say you need to migrate legacy software from COBOL to a more modern coding language. GitHub Copilot can help you with this, even if you don’t have a lot of experience with the source language.

First, ask it to explain what some code is doing, and then use that explanation to create code in the destination language that performs the same functionality. You can also ask it to provide suggestions on how to write the code in the destination language.

Our documentation on explaining legacy code includes a sample prompt and walks through the first portion of this scenario.

Generate documentation

Closely tied to the idea of explaining how code works, you can ask GitHub Copilot to generate documentation for sections of code or entire projects. This can be incredibly useful, and a huge time saver.

In Copilot Free, you can also ask it to provide a summary of given code blocks within your IDE by using the slash command /docs. In the paid versions, you can also generate documentation from issues and pull requests.

One real-world example of this involves legacy COBOL-based applications. You can ask Copilot to help provide the missing docs for a given project. (Visit documenting legacy code to get started).

Debugging code

We’ve all been there—you have a section of code that’s spitting out an error and you aren’t sure how to fix it. Sometimes you try to implement a fix, and then you get more errors (classic 🤦).

To get help from GitHub Copilot, highlight the code in question and either right-click and select “Copilot” or use the /fix slash command in Copilot Chat. You can also ask Copilot Chat why something isn’t working to start a conversation about what the problem might be.

Copilot works by analyzing your code and drawing upon its training data. It also looks at the context of your larger project to identify patterns that might be causing the problem.

To learn more, you can find a sample prompt and tutorial on how to debug invalid JSON in our docs.

Refactoring code

Want to make your code cleaner? Perform better? Same. This is a place where GitHub Copilot can help—and I’m speaking from experience. Just highlight a specific code block (or point Copilot at a specific file with the chat variable command #file) and ask Copilot for suggestions to improve your code.

Copilot will then search for specific patterns and ways to refactor your code. For example, it might recommend breaking up a long method with multiple tasks or avoiding nested logic checks to improve readability or performance. You can quickly review and accept suggestions to refactor your code—all right in your IDE.

Check out our documentation on using GitHub Copilot for refactoring your code for some guidance on how to take advantage of this functionality. For some sample prompts, see these pages on improving code readability and optimizing performance.

Multi-file editing with Copilot Edits

Copilot Edits provide the functionality for you to edit multiple files at once. This means you don’t need to manually open each file and insert the changes—which is a huge time saver. It also helps reduce the possibility of making mistakes when making manual changes.

You can access this feature through the Copilot Chat menu.

Once you select Open Copilot Edits, prompt Copilot with the changes you want to make. It will then determine which files in your working set need to be updated based on your prompt and provide a description of the changes it recommends for each file. You can then review the changes and individually accept or reject them.

💡 Pro tip: Right now, this feature is only available in VS Code.

Learn more about multi-file editing in our documentation on Copilot Edits >

Customize GitHub Copilot to meet your needs

When using GitHub Copilot, you can create a file that will provide custom instructions that will be included in all Copilot queries. This lets you reuse some of the same context without needing to manually enter it in each prompt.

When creating prompts, offering more details helps Copilot provide more relevant responses (e.g. related to the tools you use or how your team works). Including some of the same information in each prompt once you learn what works can be very helpful. By placing these persistent details in a file, you can tailor the way GitHub Copilot works to deliver higher quality responses.

For more information, see our documentation on adding custom instructions for Copilot.

💡 Pro tip: Right now, this is only available with Copilot Chat through VS Code and Visual Studio.

Breaking down the different GitHub Copilot tiers from free to enterprise

Currently, everyone has access to the GitHub Copilot Free tier. You can start using GitHub Copilot Free in VS Code by authorizing the extension or through github.com by clicking the Copilot icon in the top right-hand side of the interface.

For more information, see this video about how to set up GitHub Copilot Free.

We also offer additional tiers with more capabilities via Pro, Business, and Enterprise with more advanced capabilities, depending on your needs.

Find out which Copilot tier works best for you >

Additional resources to explore

We hope this answers your questions about Copilot’s capabilities and inspires you to give it a try in your next project. Here’s a recap of the resources we shared throughout this article:.

The post How to use GitHub Copilot: What it can do and real-world examples appeared first on The GitHub Blog.

]]>
81844
GitHub Copilot now available in github.com for Copilot Individual and Copilot Business plans https://github.blog/news-insights/product-news/github-copilot-now-available-in-github-com-for-copilot-individual-and-copilot-business-plans/ Thu, 26 Sep 2024 18:01:17 +0000 https://github.blog/?p=80035 With this public preview, we’re unlocking the context of your code and collaborators—and taking the next step in infusing AI into every developer’s workflow.

The post GitHub Copilot now available in github.com for Copilot Individual and Copilot Business plans appeared first on The GitHub Blog.

]]>

Today, GitHub Copilot Individual and Business plans now include preview access to Copilot functionality, including GitHub Copilot Chat, in github.com. The integration with GitHub allows Copilot to leverage the rich context from repositories, pull requests, issues, actions, and more, providing you with more valuable interactions, more tailored coding assistance, and an AI-native developer experience with GitHub.

Doing more with what you know

With this latest release, GitHub Copilot is now ubiquitous across the IDE, Visual Studio Code, browser, and mobile for all Copilot users and is there to assist you across the software development lifecycle. Whether you’re on the browser or mobile, you can now use Copilot not only as an AI pair programmer that makes code suggestions, but also as a coding assistant powered by entire codebases, conversations between collaborators, and workflows.

Now, you can ask Copilot to help:

Dig deeper with OpenAI o1

For questions that require more time and intensive analysis by GitHub Copilot to construct a response, switch into immersive mode, or go directly to github.com/copilot. You can even try using an OpenAI o1 model to power your conversation. We know that one model doesn’t fit each and every task, so while the base model for GitHub Copilot Chat, GPT-4o, may provide satisfactory explanations on pull request diffs and generate great boilerplate code, o1-preview or o1-mini may suit complex tasks like crafting advanced algorithms or helping to fix performance bugs much better. Join the waitlist for early access to OpenAI o1 for Copilot Chat in immersive mode.

Get started today

By integrating GitHub Copilot into GitHub, we’re taking another step of putting AI right where you need it—whether you’re coding in an editor or troubleshooting and collaborating with your team in github.com. And with a growing ecosystem of GitHub Copilot Extensions, you can even integrate your favorite third-party and critical internal developer tools with Copilot to keep you in your flow state. This update is designed to streamline your development process, empower you with your organization’s context, and allow you to focus on what you do best—creating great software.

As with all GitHub betas, these features are governed by our pre-release terms. We’re eager to see how you all leverage these new capabilities, and, as always, you can provide feedback in the GitHub Community.


Note: videos have been sped up for display purposes.

The post GitHub Copilot now available in github.com for Copilot Individual and Copilot Business plans appeared first on The GitHub Blog.

]]>
80035
What’s new with GitHub Copilot: July 2024 https://github.blog/ai-and-ml/github-copilot/whats-new-with-github-copilot-july-2024/ Wed, 31 Jul 2024 16:00:59 +0000 https://github.blog/?p=79090 To enhance your coding experience, AI tools should excel at saving you time with repetitive, administrative tasks, while providing accurate solutions to assist developers. Today, we’re spotlighting three updates designed to increase efficiency and boost developer creativity.

The post What’s new with GitHub Copilot: July 2024 appeared first on The GitHub Blog.

]]>
Research shows that developers only spend 25% of their workday actually coding, and the rest is spent on planning, tracking issues, repetitive tasks, or trying to understand code and projects. GitHub Copilot can help reduce the time it takes to develop the context you need before you take the next step in solving a problem. Available in the IDE or on GitHub.com, Copilot helps you work the way you want to work, and you can count on GitHub to keep rolling out new capabilities to take your experience to the next level.

Take a look below to see the latest updates to GitHub Copilot, now available as a part of Copilot Enterprise.

GitHub Copilot Chat—but smarter

If searching for information is preventing you from getting into the flow state, you can get up to speed faster with GitHub Copilot Chat. With the launch of GitHub Copilot Enterprise in February, GitHub Copilot in GitHub.com gained the abilities to search both organization-specific and public repositories using natural language, the web with Bing, and knowledge base articles. We’ve since added more features to make your workflow even more seamless: Copilot Chat can now answer questions about specific issues, commits, releases, pull requests, repositories, discussions, and files on any branch, so you can develop context surrounding projects and get to solutions faster.

Bring your organization’s knowledge into VS Code and Visual Studio with Copilot Chat

Nobody likes cycling through tabs to find what they’re looking for–with Copilot Enterprise you can do a whole lot more directly from VS Code and Visual Studio:

Ask questions about your knowledge bases within VS Code (coming soon to Visual Studio)

By typing @github #kb, you can now select a knowledge base from the list, and then enter any questions about the Markdown files across multiple repositories grouped as a knowledge base. Providing the context of a knowledge to Copilot means you get organization specific suggestions tailored to your codebase and standards, unlocking organization intelligence as you and your team members implement code directly in VS Code. You can also ask questions in natural language and receive answers contained in the knowledge base.

Search across any of your repositories in GitHub from VS Code and Visual Studio

If you type @github in Copilot Chat, you can ask Copilot questions about any indexed repository in GitHub. Previously, Copilot could only answer questions about the currently active repository using the @workspace command in VS Code or #solution in Visual Studio, and the only way to access other repositories was to have GitHub.com available on another screen.

Access Bing Search right from chat for VS Code and Visual Studio

With web search powered by Bing integrated into the IDE, you can ask questions about the latest frameworks, coding languages, and best practices all without switching contexts. Adding #web with @github signals to Copilot that this is a web search and Copilot takes care of the rest.

And next? We’ll give Copilot additional context about GitHub primitives including pull requests, commits, release, discussions, and more–all integrated into Copilot in the IDE.

Chat better with GitHub Copilot Chat

We’ve made some small-but-meaningful changes to how you can interact with Copilot Chat in GitHub.com so that it’s easier, more efficient, and more natural. Users can now type out messages while the system generates responses, navigate through message history, and stop chat generation altogether—sometimes the small changes are the big wins.

Learn more about GitHub Copilot

GitHub is constantly rolling out new features for Copilot to stay aligned with what developers need. Be sure to check out Copilot’s current capabilities and use cases, and subscribe to our feature updates to stay in the loop on the latest with Copilot, released monthly.

The post What’s new with GitHub Copilot: July 2024 appeared first on The GitHub Blog.

]]>
79090
GitHub Copilot Chat in GitHub Mobile is now generally available https://github.blog/news-insights/product-news/github-copilot-chat-in-github-mobile/ Tue, 07 May 2024 16:00:04 +0000 https://github.blog/?p=77910 With GitHub Copilot Chat in GitHub Mobile, developers can collaborate, ask coding questions, and gain insights into both public and private repositories anywhere, anytime–all in natural language for users on all GitHub Copilot plans.

The post GitHub Copilot Chat in GitHub Mobile is now generally available appeared first on The GitHub Blog.

]]>

Developers are constantly coming up with new ideas, exploring new skills, and collaborating with other developers on work and personal projects. At GitHub, we understand that all this collaboration doesn’t always happen from behind desks and computers. Developers increasingly use their mobile devices to learn, understand, and perform important tasks in the software development process. Today, we’re making that easier than ever, empowering developers to build in natural language wherever they may be, with the general availability of GitHub Copilot Chat for GitHub Mobile.

With GitHub Copilot Chat natively integrated with GitHub Mobile, developers can access their AI coding assistant to get answers for all their coding questions, or even repositories and knowledge bases, from anywhere they use mobile devices.

GitHub Copilot Chat in GitHub Mobile suggesting code

By enabling every developer to build and understand code on the go with GitHub Copilot Chat, we will turn the use of natural language into an effective and default part of the coding process. This means lowering barriers to entry and democratizing access to a career in software development–a win for aspiring developers everywhere and a win for a world that increasingly relies on software to push progress forward. Whether a developer needs help understanding a block of code that a colleague wrote, or wants to learn a new framework, GitHub Copilot Chat is there to help.

What can you do with GitHub Copilot Chat?

GitHub Copilot Chat, a cornerstone of the GitHub Copilot experience, has already helped engineering organizations increase productivity by guiding developers through unfamiliar codebases, breaking down complex coding concepts, and so much more–all in natural language. Built specifically for developer scenarios, GitHub Copilot Chat offers personalized assistance to help development teams and individuals get quick answers to a wide variety of coding questions. Developers can also engage in conversations with the top 100,000+ public repositories, enabling them to deepen their understanding of various coding practices and techniques.

Customized in GitHub Copilot Enterprise

At Universe 2023, we announced that with GitHub Copilot Chat, we’re enabling the rise of natural language as the new universal programming language for every developer on the planet. By bringing the AI coding assistant to mobile phones, by far one of the most commonly used computing devices in the world, we’re continuing to deliver on that promise. With GitHub Copilot Enterprise, we’re also customizing GitHub Copilot with the context of an organization’s codebase. Now, that customization extends to mobile.

For organizations using GitHub Copilot Enterprise, developers can direct GitHub Copilot to their organization’s private repositories and ask questions including: “What does this code snippet mean?” or “how often was this function used in the project?” This places organizational knowledge directly at their fingertips. Instead of spending hours searching through documentation, developers can simply ask GitHub Copilot to find the information they need and immediately start building–whether from their computer or mobile device. This empowers teams of developers to innovate faster and express their full creativity in a world of work that is not always confined to an office, or even a desk.

Making GitHub Copilot ubiquitous wherever the developer is

Making GitHub Copilot Chat generally available for GitHub Mobile is the latest example of how we’re empowering developers with AI throughout the entire development lifecycle. When we brought GitHub Copilot to the world with code completion, we immediately began optimizing it for a variety of editors, including Visual Studio, Visual Studio Code, and the JetBrains suite of IDEs. Then, we launched GitHub Copilot Chat, now deeply integrated into GitHub’s surfaces and the command line interface, and personalized to an organization’s codebase. We also brought GitHub Copilot to pull requests, and launched code scanning autofix powered by GitHub Copilot and CodeQL to help secure the world’s code in realtime. And with GitHub Copilot Workspace, we’re meeting developers at the issue and delivering a new Copilot-native environment where you can go from idea to code in natural language.

Looking ahead, we’ll continue to infuse Copilot across the GitHub platform to lower barriers and empower 1 billion developers to achieve their full potential with code–even when they’re on the go.

We want to hear from you.

We value your feedback to enhance the GitHub Copilot experience. Join the conversation by visiting our community forum and help us shape the future of GitHub Copilot Chat in GitHub Mobile.

The post GitHub Copilot Chat in GitHub Mobile is now generally available appeared first on The GitHub Blog.

]]>
77910
Research: Quantifying GitHub Copilot’s impact on code quality https://github.blog/news-insights/research/research-quantifying-github-copilots-impact-on-code-quality/ Tue, 10 Oct 2023 16:00:26 +0000 https://github.blog/?p=74630 Findings show that code quality is better across the board and developers felt more confident, too.

The post Research: Quantifying GitHub Copilot’s impact on code quality appeared first on The GitHub Blog.

]]>
Today, we’re releasing new research on GitHub Copilot Chat. By using the power of natural language, developers in our study used GitHub Copilot Chat to get real-time guidance, tips, troubleshooting, remediation, and solutions tailored to their specific coding challenges—all in real time without leaving the IDE.

Our research found that the quality of the code authored and reviewed was better across the board with GitHub Copilot Chat enabled, even though none of the developers had used the feature before.

  • 85% of developers felt more confident in their code quality when authoring code with GitHub Copilot and GitHub Copilot Chat.
  • Code reviews were more actionable and completed 15% faster with GitHub Copilot Chat.
  • 88% of developers reported maintaining flow state with GitHub Copilot Chat because they felt more focused, less frustrated, and enjoyed coding more, too.

Three pie charts detailing how using GitHub Copilot Chat correlates with better code quality

Last year, our research uncovered that developers using GitHub Copilot code 55% faster. But working fast is just one part of the picture—in many cases, there has traditionally been a tradeoff between doing something quickly and doing something right. As artificial intelligence continues to write code for an increasing number of developers, ensuring good code quality is even more important.

What does high-quality code look like?

To measure code quality, we developed a rubric of five metrics used internally at GitHub, but that also align with academic1 and industry2 standards. Participants used the metrics to differentiate between strong code and code that slows them down.

Readable

Does the code follow the language’s idioms and naming patterns? Code that is difficult to read makes it more challenging to maintain, improve, and document.

Reusable

Is the code written so that it can be reused? Code reuse is a cornerstone of developer collaboration. It saves time and energy, breaks down silos, and creates consistency as a whole.

Concise

Does the code adhere to DRY (don’t repeat yourself)? The less repetitive the code is, the easier it’ll be to read, understand, and build upon. Complex code can lead to bugs and issues that will be tough to remediate.

Maintainable

Is the code written in a way that makes the functionality clear, transparent, and relevant to the problem at hand? Well-maintained code means that developers minimize dependencies. Maintainable code also impacts developers’ ability to search and practice code-reuse.

Resilient

Does the code anticipate and handle errors? Resilient code will maintain its functionality (or at least have minimal disruption) if there are errors. This goes a long way toward ensuring that code will, simply put, work.

Using GitHub Copilot correlates with better code quality

In this study, we investigated whether GitHub Copilot and its chatbot functionalities would improve perceived quality of the code produced, reduce time required to review the code, and produce code that passes unit testing. And by every measure, developers felt their coding improved when using GitHub Copilot.

85% of developers felt more confident in their code quality when authoring code with GitHub Copilot and Copilot Chat

GitHub Copilot Chat is a chat interface that lets you interact with GitHub Copilot, to ask and receive answers to coding-related questions from directly within a supported IDE. The chat interface provides access to coding information and support without requiring you to navigate documentation or search online forums. Copilot Chat is currently supported in Visual Studio Code and Visual Studio.

Here’s how to enable GitHub Copilot Chat.

Overall, developers told us they felt more confident because coding is easier, more error-free, more readable, more reusable, more concise, more maintainable, and more resilient with GitHub Copilot and GitHub Copilot Chat than when they’re coding without it.

Chart showing participant ratings of how GitHub Copilot Chat impacted authoring and reviewing code, measuring frustration level, focus, enjoyment, confidence, time researching, and time on repetitive tasks

The code was so clean, I could just look at the code, know what was going on, and bring it over fairly easily to my codebase. So, I felt the code quality was very clean and easy to understand. When I was doing the pull request review using Copilot, I saw how good it was at generating proper error handling code.

- Senior Software Engineer at a Fortune 500 company (study participant)

Code reviews were more actionable and completed 15% faster than without GitHub Copilot Chat (that’s first-time users, too!)

This is the part where we get to talk about quality and speed—because yes it’s possible to have both.

Developers noted that using GitHub Copilot Chat for code reviews improved the quality of their code (when compared to doing code review without it). Those code reviews were 15% faster with GitHub Copilot Chat. A higher percentage of comments were accepted, too. In fact, almost 70% of participants accepted comments from reviewers using GitHub Copilot Chat.

These results show the impact GitHub Copilot Chat has on collaboration, and underscores the potential impact of scaling it across larger engineering teams in bigger organizations. Reducing time spent on pull requests and code reviews means developers can focus on higher-priority changes. And better quality code from the start ensures code doesn’t need to be rolled back later, nor does it require additional testing.

One of the more actionable comments I received was related to conceptual understanding of my code–I want other developers to be able to understand what I'm doing, so this was good feedback.

- Software Engineer (study participant)

Bar chart showing average rating for reviewing code with and without GitHub Copilot Chat, measuring if code was easy to write, error-free, readable, reusable, concise, maintainable, resilient, and actionable

88% of developers reported maintaining flow state with GitHub Copilot Chat because they felt more focused, less frustrated, and enjoyed coding more, too

Last year’s research found 60-75% of developers using GitHub Copilot reported feeling more fulfilled in their job, less frustrated when coding, and better positioned to focus on more satisfying work. In this year’s study, 88% of participants similarly felt less frustrated and more focused. One reason is that staying in the IDE means less time spent searching and more time staying in that coveted focused flow state.

Because I’ve had industry experience for over a decade, I usually prefer coding with a notepad or a simplistic platform and Copilot Chat was a really useful tool for checking basic things without me needing to go to Google or Stack Overflow. And Copilot has a pretty neat syntax edition.

- Senior Systems Validation Engineer (study participant)

How we set up the study

In the study, the goal was to simulate the process of authoring code in a controlled setting, having the code reviewed, and incorporating the changes suggested in the code review. So, each participant was asked to author code, review code, and then review the suggestions from code review and incorporate changes.

We recruited 36 participants with between five and 10 years of software development experience. In the study, the participants authored and reviewed code both with and without GitHub Copilot Chat. (Participants had some experience using GitHub Copilot and no experience using GitHub Copilot Chat.)

Participants were asked to author API endpoints for an HTTP service that creates, reads, and deletes objects. They were randomly assigned to either use GitHub Copilot Chat to then create, read and delete API endpoints. Before using GitHub Copilot Chat, developers were shown a brief video on its functionality. The participants created one pull request for their work on the create API endpoint, and another for the read and delete portion.

After authoring the code for the API endpoints, the participants compared how using GitHub Copilot Chat impacted the quality of the code they wrote. Specifically, they were asked if the task was easier to complete; if the code had fewer errors; and was more readable, reusable, concise, maintainable, and resilient.

After the session, developers were assigned the two pull requests that another participant in the study authored. The study participants were blind to which pull request was authored with or without Copilot, but were asked to review it and provide suggestions on how the code could be improved. Then they rated the process of conducting the review with and without GitHub Copilot Chat. The reviewers then rated the quality of the code using the rubric above, measuring whether the code was readable, reusable, and well-architected.

After their code was done being reviewed by another participant, the participants that originally authored the code reviewed the comments on their pull requests to decide which were helpful in improving the quality of the code and how actionable the comments were. Again, these participants were blind to which pull had been reviewed with Copilot Chat and which hadn’t.

The promise of GitHub Copilot Chat: better quality code, faster

We know there’s a difference between doing something fast and doing something well. With GitHub Copilot Chat, it turns out you can have both.

We built GitHub Copilot and GitHub Copilot Chat to improve the lives of developers by helping them focus, keeping them in the flow, and empowering them to find more joy in their work. The results have shown that these AI tools are doing that and more—we look forward to building what’s next.

Acknowledgements

We are very grateful to all the developers who participated in the this study–we always love hearing how we can make GitHub better for you! GitHub Customer Research conducted this research with help and consultation from GitHub Next.


  1. Börstler, J., Bennin, K.E., Hooshangi, S. et al. Developers talking about code quality. Empir Software Eng 28, 128 (2023). https://doi.org/10.1007/s10664-023-10381-0 
  2. Ghani, U. (2023, September 18). 5 code review best practices – Work Life by Atlassian. Work Life by Atlassian. https://www.atlassian.com/blog/add-ons/code-review-best-practices 

The post Research: Quantifying GitHub Copilot’s impact on code quality appeared first on The GitHub Blog.

]]>
74630
Prompting GitHub Copilot Chat to become your personal AI assistant for accessibility https://github.blog/developer-skills/github/prompting-github-copilot-chat-to-become-your-personal-ai-assistant-for-accessibility/ Mon, 09 Oct 2023 16:00:05 +0000 https://github.blog/?p=74604 GitHub Copilot Chat can help you learn about accessibility and improve the accessibility of your code. In this blog, we share a sample foundational prompt that instructs GitHub Copilot Chat to become your personal AI assistant for accessibility.

The post Prompting GitHub Copilot Chat to become your personal AI assistant for accessibility appeared first on The GitHub Blog.

]]>
Large Language Models (LLMs) are trained on vast quantities of data. As a result, they have the capacity to generate a wide range of results. By default, the results from LLMs may not meet your expectations. So, how do you coax an LLM to generate results that are more aligned with your goals? You must use prompt engineering, which is a rapidly evolving art and science of constructing inputs, also known as prompts, that elicit the desired outputs.

For example, GitHub Copilot includes a sophisticated built-in prompt engineering facility that works behind the scenes. It uses contextual information from your code, comments, open tabs within your editor, and other sources to improve results. But wouldn’t it be great to optimize results and ask questions about coding by talking directly to the LLM?

That’s why we created GitHub Copilot Chat. GitHub Copilot Chat complements the code completion capabilities of GitHub Copilot by providing a chat interface directly within your favorite editor. GitHub Copilot Chat has access to all the context previously mentioned and you can also provide additional context directly via prompts within the chat window. Together, the functionalities make GitHub Copilot a personal AI assistant that can help you learn faster and write code that not only meets functional requirements, but also meets non-functional requirements that are table stakes for modern enterprise software such as security, scalability, and accessibility.

In this blog, we’ll focus specifically on the non-functional requirement of accessibility. We’ll provide a sample foundational prompt that can help you learn about accessibility directly within your editor and suggest code that is optimized for better accessibility. We’ll break down the sample prompt to understand its significance. Finally, we’ll share specific examples of accessibility-related questions and results that demonstrate the power of prompting GitHub Copilot Chat to deliver results that improve accessibility. When using GitHub Copilot Chat, we recommend that you think of yourself as a lead developer who is working with a more junior developer (GitHub Copilot Chat). As the lead developer, it is your responsibility to verify information that is provided by GitHub Copilot Chat and ensure it meets all of your requirements.

Foundational accessibility prompt

You can copy this prompt and paste it directly into GitHub Copilot Chat for Visual Studio Code:

“I need to learn about accessibility and need to write code that conforms with the WCAG 2.1 level A and AA success criteria defined at https://www.w3.org/TR/WCAG21/. I want you to be my accessibility coach, a subject-matter expert that makes me think and account for all accessibility requirements and usability enhancements. When you answer questions about accessibility please use reputable sources such as w3.org, webaim.org, developer.mozilla.org, and https://www.ibm.com/able/. When possible, please provide links and references for additional learning. When you suggest code please use semantic HTML, ensure it is operable using the keyboard, follow WCAG 2.1 sufficient techniques, and follow the ARIA Authoring Practices Guide and related design patterns. Do you understand these instructions?”

What does this do?

This prompt can serve as your baseline in your codebase, whether you are just starting a project or in the thick of an extensive project.

The prompt consists of:

  1. Providing solid context and background information to help narrow down the scope of solutions.
  2. Defining GitHub Copilot’s role and setting expectations about what feedback we are looking for.
  3. Being specific in the quality of answers we are looking to reference from reputable sources.
  4. Asking for additional resources and context to learn more and ensure the answers we receive are correct. This helps provide feedback to GitHub Copilot.
  5. Dictating one final set of requirements to even further refine the scope based on the resources we have provided.

Note: At any time you can ask GitHub Copilot if it’s still referencing the foundation prompt you provided and it will inform you of its scope.

Query input: Are you still using the instructions I provided?
GitHub Copilot response: Yes, I am still adhering to the instructions you provided. I will continue to assist you in learning about accessibility and writing code that conforms with the WCAG 2.1 level A and AA success criteria. I will use reputable sources for references and additional learning, and ensure that the code suggestions I provide use semantic HTML, are operable using the keyboard, follow WCAG 2.1 sufficient techniques, and follow the ARIA Authoring Practices Guide and related design patterns.

Examples after the setting the foundation prompt

Note: These prompts were submitted in a brand new workspace that contained no source code or files to reference. Repeating these prompts in your codebase may produce different results as GitHub Copilot can use context provided from open tabs and existing files in the codebase. In addition, please keep in mind that results from LLMs are non-deterministic.

Accessibility testing

Query input: How can I test for web accessibility?
GitHub Copilot response: There are several ways to test for web accessibility:

  1. Manual Testing: This involves navigating your website using only a keyboard, checking color contrast, and resizing text to 200% to ensure readability.
  2. Automated Testing: There are several tools available for automated accessibility testing. Some popular ones include:
    1. WAVE: A free web accessibility evaluation tool provided by WebAIM.
    2. Axe: An accessibility testing toolkit built on a library of accessibility rules.
    3. Lighthouse: An open source, automated tool for improving the quality of web pages. It has audits for performance, accessibility, progressive web apps, SEO, and more.
  3. Screen Reader Testing: This involves testing your website using a screen reader tool. Some popular screen readers include NVDA, JAWS, and VoiceOver.
  4. User Testing: This involves testing your website with people with disabilities. This can provide valuable insights into how accessible your website is in practice.

Remember, no single tool or method can catch all accessibility issues, so a combination of methods is often the best approach.

For more information, you can refer to the following resources:

Tables

Query input: What are some best practices for creating accessible tables in HTML?
GitHub Copilot response: Creating accessible tables in HTML involves several best practices:

  1. Use <th> for table headers: This helps screen readers identify headers. Also, use the scope attribute to specify whether the header is for a row or a column.
    <table>
    <tr>
    <th scope="col">Header 1</th>
    <th scope="col">Header 2</th>
    </tr>
    <tr>
    <td>Data 1</td>
    <td>Data 2</td>
    </tr>
    </table>
    
  2. Provide captions: Use the <caption> element to provide a brief overview of the table. This is especially helpful for people using screen readers.
    <table>
    <caption>Overview of sales</caption>
    <!-- rest of the table -->
    </table>
    

    Use <thead>, <tbody>, and <tfoot>: These elements help to group different sections of the table and can improve accessibility.

    <table>
    <thead> <!-- header group -->
    <tbody> <!-- body group -->
    <tfoot> <!-- footer group -->
    </table>
    
  3. Avoid complex tables: If possible, avoid using tables for complex data structures. If you must, use rowspan and colspan attributes carefully and provide additional information in cell content or with the title attribute.

  4. Ensure readability without styles: The table should be readable and make sense even when styles are turned off.
  5. Use aria-labelledby for complex tables: If a table has multiple levels of headers, use the aria-labelledby attribute to associate data cells with headers.

For more information, you can refer to the WebAIM guide on creating accessible tables.

Forms

Query input: What are some best practices for creating accessible forms in HTML?
GitHub Copilot response: Creating accessible forms in HTML involves several best practices:

  1. Use <label> for form controls: Each form control should have a corresponding <label> element. This helps screen readers identify the purpose of the form control.
    <label for="name">Name:</label>
    <input id="name" name="name" type="text" />
    
  2. Group related form controls: Use the <fieldset> element to group related form controls and <legend> to provide a description for the group.
    <fieldset>
    <legend>Choose your favorite pet:</legend>
    <input type="radio" id="dog" name="pet">
    <label for="dog">Dog</label><br>
    <input type="radio" id="cat" name="pet">
    <label for="cat">Cat</label><br>
    </fieldset>
    
  3. Provide error messages and feedback: If the user makes an error, provide clear and specific feedback. Use the aria-describedby attribute to associate the form control with the error message.
    <input type="text" id="name" name="name" aria-describedby="nameError">
    <span id="nameError">Please enter your name.</span>
    
  4. Use correct input types: Use the correct input type for the form control (for example, email, number, date). This can provide the user with the appropriate keyboard on mobile devices.

  5. Make form controls keyboard accessible: Ensure that all form controls and buttons can be accessed and used with the keyboard.
  6. Use ARIA roles and properties when necessary: If a form control requires more complex interaction, use ARIA roles and properties to provide additional information to screen reader users.

For more information, you can refer to the WebAIM guide on creating accessible forms.

Keyboard support

Query input: What are some best practices for creating proper keyboard support in HTML?
GitHub Copilot response: Creating proper keyboard support in HTML involves several best practices:

  1. Logical Tab Order: Ensure that the tab order of the page follows the visual flow of the content. This can be achieved by structuring your HTML in a logical order. Avoid using positive tabindex values as they can disrupt the natural tab order.
  2. Keyboard Focus Indication: It’s important that users can visually identify which element currently has keyboard focus. This can be achieved using CSS to style the :focus state of interactive elements.
    button:focus, a:focus {
    outline: 2px solid blue;
    }
    
  3. Skip Links: Provide a mechanism to skip to main content or different sections of the page. This can be a link at the top of the page that becomes visible when it receives keyboard focus.
    <a href="proxy.php?url=#maincontent">Skip to main content</a>
    
  4. Accessible Interactive Elements: Ensure all interactive elements are accessible via keyboard. This includes links, buttons, form controls, and custom interactive widgets. Use semantic HTML elements whenever possible as they have built-in keyboard accessibility.

  5. Keyboard Support for Custom Widgets: If you’re creating custom interactive widgets (like a dropdown menu or modal dialog), you’ll need to provide additional keyboard support. This often involves handling keypress events for keys like Enter, Space, Escape, and the arrow keys. The WAI-ARIA Authoring Practices Guide provides detailed guidance on how to add keyboard support to various types of widgets.
  6. Avoid Keyboard Traps: Ensure that keyboard users can navigate to and from all parts of the page. Avoid situations where keyboard focus can be trapped in a particular page element.

For more information, you can refer to the WebAIM guide on keyboard accessibility.

Aria

Query input: What are some best practices around using proper ARIA roles in HTML?
GitHub Copilot response: ARIA (Accessible Rich Internet Applications) roles can be used to improve accessibility, especially when creating complex interactive elements. Here are some best practices:

  1. Use Semantic HTML First: Before using ARIA, consider whether you can use semantic HTML elements. These elements have built-in accessibility features that often make ARIA unnecessary. For example, use a <button> element instead of a <div> with a role="button".
  2. Don’t Change Native Semantics: Avoid using ARIA to change the semantics of native HTML elements. For example, don’t use role="button" on a link (<a>). Instead, use a <button> element.
  3. Use Appropriate Roles: When you do need to use ARIA, ensure you’re using the appropriate role for the element. The ARIA roles model provides a list of roles and their intended use.
  4. Provide Required States and Properties: Some roles require additional ARIA states or properties. For example, a checkbox requires the aria-checked state.
    <div role="checkbox" aria-checked="false">Check me</div>
    
  5. Use aria-labelledby and aria-describedby: These attributes can be used to provide additional descriptive text for an element.
    <button aria-describedby="info">More Info</button>
    <div id="info">Clicking this button will open more information.</div>
    
  6. Test with Screen Readers: After adding ARIA roles, test your page with a screen reader to ensure it’s providing the intended information.

Remember, ARIA should be used as a last resort when semantic HTML isn’t sufficient. The WAI-ARIA Authoring Practices Guide provides detailed guidance on how to use ARIA correctly.

Analysis

Reviewing the questions we asked GitHub Copilot, it suggested a lot of good information for us to learn more about best accessibility and usability practices. A few responses may be open to interpretation, while other responses lack details or specificity. Some examples include:

  • <tfoot> is an HTML element that calls attention to a set of rows summarizing the columns of the table. Including <tfoot> can help ensure the proper understanding of a table. However, not all tables require such rows–therefore, <tfoot> is not mandatory to have a usable table if the data doesn’t require it.
  • The response for the question about forms stressed the importance of the <label> element, which can help identify different labels for their various inputs. However, that response didn’t include any description about adding “for” attributes with the same value as the <input>’s ID. The response did include “for” attributes in the code suggestion, but an explanation about proper use of the “for” attribute would have been helpful.
  • The response to our question about keyboard accessibility included an explanation about interactive controls and buttons that can be accessed and used with a keyboard. However, it did not include additional details that could benefit accessibility such as ensuring a logical tab order, testing tab order, or avoiding overriding default keyboard accessibility for semantic elements.

If you are ever unsure of a recommendation or wish to know more, ask GitHub Copilot more questions on those areas, ask to provide more references/links, and follow up on the documentation provided. As a developer, it is your responsibility to verify the information you receive, no matter the source.

Conclusion

In our exploration, GitHub Copilot Chat and a well-constructed foundational prompt come together to create a personal AI assistant for accessibility that can improve your understanding of accessibility. We invite you to try the sample prompt and work with a qualified accessibility expert to customize and improve it.

Limitations and considerations

While clever prompts can improve the accessibility of the results from GitHub Copilot Chat, it is not reasonable to expect generative AI tools to deliver perfect answers to your questions or generate code that fully conforms with accessibility standards. When working with GitHub Copilot Chat, we recommend that you think of yourself as a lead developer who is working with a more junior developer. As the lead developer, it is your responsibility to verify information that is provided by GitHub Copilot Chat and ensure it meets all of your requirements. We also recommend that you work with a qualified accessibility expert to review and test suggestions from GitHub Copilot. Finally, we recommend that you ensure that all GitHub Copilot Chat code suggestions go through proper code review, code security, and code quality channels to ensure they meet the standards of your team.

Learn more

The post Prompting GitHub Copilot Chat to become your personal AI assistant for accessibility appeared first on The GitHub Blog.

]]>
74604
How I used GitHub Copilot Chat to build a ReactJS gallery prototype https://github.blog/developer-skills/github/how-i-used-github-copilot-chat-to-build-a-reactjs-gallery-prototype/ Wed, 27 Sep 2023 16:24:25 +0000 https://github.blog/?p=74315 GitHub Copilot Chat can help developers create prototypes, understand code, make UI changes, troubleshoot errors, make code more accessible, and generate unit tests.

The post How I used GitHub Copilot Chat to build a ReactJS gallery prototype appeared first on The GitHub Blog.

]]>
Ever since we announced GitHub Copilot Chat in March this year, I’ve been thinking a lot about how it’s improving developer happiness and overall satisfaction while coding. Especially for junior developers looking to upskill, or those in the learning phase of diving into a new framework, GitHub Copilot Chat can be such a valuable tool to have in your back pocket.

ICYMI, all GitHub Copilot for Individuals users now have access to GitHub Copilot Chat beta!

The capabilities of GitHub Copilot Chat

With GitHub Copilot Chat, you can now interface with Copilot as a context-aware conversational assistant right in the IDE, allowing you to execute some of the most complex tasks with simple prompts. This goes beyond GitHub Copilot’s original capabilities, which focused on autocompletion and translating natural language comments into code. Now, developers can not only get code suggestions in-line, but they can ask Copilot questions directly, get explanations, offer prompts for code, and more, all while staying in the IDE—and in the flow.

Recently, I was preparing a conference talk and demo about ReactJS, and I had to think a bit about what kind of app I wanted to make with the help of Copilot Chat. Since photography is a hobby of mine, I decided to make a photo gallery of the tulip fields and flower shows around Amsterdam. In the end, I went through a couple different versions of this photo gallery with Copilot Chat. Using a probabilistic model, which is currently based on OpenAI’s GPT-3.5-turbo, it found the best suggestion for me based on how I prompted it, including the question I asked, the code I’d started writing, and other open tabs in my IDE.

Screenshot of GitHub Copilot Chat open in a code editor, on top of a screenshot of a React app in progress. User sennap has asked GitHub Copilot Chat, "Are there any libraries I could use to make this prettier?" Chat has responded with an example of how to use styled-components to style the gallery.

It had been a long time since I had used React, so it probably would’ve taken me a few days of searching and trial and error before coming up with something decent. But with Copilot Chat, each iteration of my photo gallery only took me about 20-30 minutes to go through.

Making prototypes and generating new code

What I most enjoyed about using Copilot Chat to create something new was discovering multiple ways I could implement my component. I didn’t have to leave my IDE and search for advice or a component to use because Copilot would suggest something in real time. If it offered me a suggestion that didn’t work out well, I could give it feedback on why that suggestion didn’t work, which enabled it to offer suggestions that better suited my needs.

Despite working in an unfamiliar framework, Copilot Chat enabled me to immediately start churning out my ideas, which was incredibly satisfying. It was empowering to discover that I can get something done so much faster than what I would have anticipated without any help.

This idea of looking for external help and examples to understand code has been part of the learning process since well before we had AI pair programming tools. I remember when I was first starting in my career and discovering all these new frameworks. I would spend hours, days, weeks doing tutorials and learning about different ways of implementing things. I would learn by copying and pasting things I saw on StackOverflow and seeing how they fit in with the rest of my code (or by chatting with my buddy that I shared a cubicle with at the time).

A lot of the time, these code snippets didn’t even work, but having something to start with really helped with the learning process and that excitement propelled me forward to the next step. This is exactly the magic I felt when using Copilot Chat—while being able to get a contextual suggestion that actually worked and helped me quickly progress to the next thing. Not to mention the amount of time and energy I saved by staying within the context of VS Code instead of searching through websites and other comments online (and avoiding some stress caused by the sentiment of some Stack Overflow comments).

GitHub Copilot Chat in action

When it came time to build my photo gallery, I used Copilot Chat to get suggestions for popular React libraries I could use. There were a few of them that I checked out in separate iterations of the gallery but styled components seems to be the easiest one for me to configure.

I wanted to include a modal as well, so I asked Copilot if the styled components library supported modals. I was really surprised that it knew exactly how to utilize the modal component of the library and how to pass the props in and handle the onClick functionality from the get-go.

In the video, you may notice that it initially gives me a generic suggestion with some boilerplate examples of how to define a modal component and how to reference it from another file. I then asked it to iterate on that suggestion and give me something more specific to how I defined my gallery. This is important because the power of GitHub Copilot is really in the prompt that you provide it: the more fine-tuned the information, the more powerful its suggestions will be. For further reading, check out these prompt tips and tricks for leveraging GitHub Copilot effectively as well as this post on how we compose prompts at GitHub.

Testing out a UI change based on a natural language prompt

When I first tried rendering a modal, that close button was out of view on the top right corner of the screen. This isn’t too difficult to do if you’re regularly developing front-end. Full transparency: I would have needed to Google how to fix this since I just don’t remember how to and CSS is hard! I was shocked that just by asking Copilot Chat to center the “X” button in the modal, it gave me a better suggestion with some new CSS to add display properties to the button that adjust it to my intention. With Copilot Chat, I got the fix I needed without having to leave the IDE or break my flow.

Making accessibility improvements

I have a background in web accessibility and I knew there would be some improvements needed to make the modals interactive with proper focus handling. There are many facets to making a component accessible and it’s important to strategize early on. Best practices include working with accessibility linting tools, and also specialists that can help you balance constraints at the start of the design and development process.

Copilot Chat can be a great addition to those tools by pointing you in the right direction to fixing accessibility issues. In the case of my gallery, the images were not presenting themselves as interactive to keyboard or screen reader users (or, even visually, which goes to show that accessibility makes products better for everyone!). I asked Copilot Chat what it recommended for me to improve the interactivity of the images. The video below illustrates the suggestions it provided around using tabindex, aria attributes, and handling keydown events.

There are, of course, other accessibility considerations to be made here. At some point I decided to make each of the images button elements with a background image, since generally it’s better to use semantic HTML. I then carried on with the rest of my work to manage the focus correctly when opening and closing the modal, as well as making sure only the visible or focused content is presented to a screen reader.

Troubleshooting errors

I was also surprised by Copilot Chat’s ability to help me debug my project whenever I came across an error message. I’d just paste the error into the chat window and GitHub Copilot would offer an explanation for what went wrong and an alternative approach so I could fix the bug quickly and move on.

Writing tests

Knowing that GitHub Copilot can suggest bug fixes, I also wanted to see how it would suggest I write tests for my code. You can ask Copilot Chat for all sorts of test cases, as well as just what kind of testing framework would make the most sense for your application.

In another iteration of my gallery, I used GitHub Copilot to help me render a countdown to the next opening of Tulip season (I went with March 21, 2024, when the tulip festival starts). I decided to make use of the new Copilot Chat slash commands that make it simple to highlight a function and prompt it to help me create some test cases. It suggested using the React testing library for rendering, as well as some methods from Jest to simulate the passage of time and make sure the passing days are represented correctly. From there, I learned about the Jest framework’s Timer Mocks and best practices for testing for fake timers.

Without GitHub Copilot and this new chat feature, navigating a test framework and relying solely on their documentation would have taken even more time.

Summarizing my changes with GitHub Copilot for pull requests

Lastly, I used GitHub Copilot for pull requests to help summarize all the changes I made in a pull request. It gave me a summary of my changes, a walk through of each of the diffs relating to those changes, and even a poem about my application.

Screenshot of an open pull request, which was created by GitHub Copilot Chat, ready to be merged into the tulip gallery repository.

All of this is to show how Copilot Chat and GitHub Copilot for pull requests made the entire coding process much more enjoyable for me while working in an unfamiliar framework—from the initial idea phase to submitting a pull request.

GitHub Copilot Trial. Don't fly solo. Try for 30 days free. Learn more.

Potential limitations and considerations

While the productivity increases for GitHub Copilot are amazing, there are valid concerns around the quality of code AI paired programming tools suggest and the danger of blindly trusting them. That’s why it’s important to remember that you, the developer, is ultimately the pilot. I think of using GitHub Copilot to be similar to pair programming with another developer: it helps me work faster, but I still need to verify the suggestions it’s giving me to ensure they meet my requirements.

While GitHub Copilot has numerous filters in place to avoid suggestions with vulnerabilities, it’s still important to review and test before deploying. As with any code you did not independently originate, you should ensure code suggestions go through proper code review, code security, and code quality channels to maintain the standards of your team.

The post How I used GitHub Copilot Chat to build a ReactJS gallery prototype appeared first on The GitHub Blog.

]]>
74315